ExportService.php 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * Provide useful methods to generate files to export.
  5. */
  6. class FreshRSS_Export_Service {
  7. private readonly FreshRSS_CategoryDAO $category_dao;
  8. private readonly FreshRSS_FeedDAO $feed_dao;
  9. private readonly FreshRSS_EntryDAO $entry_dao;
  10. private readonly FreshRSS_TagDAO $tag_dao;
  11. final public const FRSS_NAMESPACE = 'https://freshrss.org/opml';
  12. final public const TYPE_HTML_XPATH = 'HTML+XPath';
  13. final public const TYPE_XML_XPATH = 'XML+XPath';
  14. final public const TYPE_RSS_ATOM = 'rss';
  15. final public const TYPE_JSON_DOTPATH = 'JSON+DotPath'; // Legacy 1.24.0-dev
  16. final public const TYPE_JSON_DOTNOTATION = 'JSON+DotNotation';
  17. final public const TYPE_JSONFEED = 'JSONFeed';
  18. final public const TYPE_HTML_XPATH_JSON_DOTNOTATION = 'HTML+XPath+JSON+DotNotation';
  19. final public const PRIORITY_IMPORTANT = 'important';
  20. final public const PRIORITY_MAIN_STREAM = 'main';
  21. final public const PRIORITY_CATEGORY = 'category';
  22. final public const PRIORITY_FEED = 'feed';
  23. final public const PRIORITY_HIDDEN = 'hidden';
  24. /**
  25. * Initialize the service for the given user.
  26. */
  27. public function __construct(private readonly string $username) {
  28. $this->category_dao = FreshRSS_Factory::createCategoryDao($this->username);
  29. $this->feed_dao = FreshRSS_Factory::createFeedDao($this->username);
  30. $this->entry_dao = FreshRSS_Factory::createEntryDao($this->username);
  31. $this->tag_dao = FreshRSS_Factory::createTagDao();
  32. }
  33. /**
  34. * Generate OPML file.
  35. * @return array{0:string,1:string} First item is the filename, second item is the path of a temporary file with the content
  36. * @throws Minz_PermissionDeniedException
  37. */
  38. public function generateOpml(): array {
  39. $view = new FreshRSS_View();
  40. $day = date('Y-m-d');
  41. $view->categories = $this->category_dao->listSortedCategories(prePopulateFeeds: true, details: true);
  42. $view->excludeMutedFeeds = false;
  43. $view->includeSensitiveCurlParams = true;
  44. return [
  45. "feeds_{$day}.opml.xml",
  46. self::helperToTempFile($view, 'export/opml'),
  47. ];
  48. }
  49. /**
  50. * Generate the starred and labelled entries file.
  51. *
  52. * Both starred and labelled entries are put into a "starred" file, that’s
  53. * why there is only one method for both.
  54. *
  55. * @phpstan-param 'S'|'T'|'ST' $type
  56. * @param string $type must be one of:
  57. * 'S' (starred/favourite),
  58. * 'T' (taggued/labelled),
  59. * 'ST' (starred or labelled)
  60. * @return array{0:string,1:string} First item is the filename, second item is the path of a temporary file with the content
  61. * @throws Minz_PermissionDeniedException
  62. */
  63. public function generateStarredEntries(string $type): array {
  64. $view = new FreshRSS_View();
  65. $view->categories = $this->category_dao->listCategories(prePopulateFeeds: true);
  66. $day = date('Y-m-d');
  67. $view->list_title = _t('sub.import_export.starred_list');
  68. $view->type = 'starred';
  69. $entriesId = $this->entry_dao->listIdsWhere($type, 0, FreshRSS_Entry::STATE_ALL, order: 'ASC', limit: -1) ?? [];
  70. $view->entryIdsTagNames = $this->tag_dao->getEntryIdsTagNames($entriesId);
  71. // The following is a streamable query, i.e. must be last
  72. $view->entries = $this->entry_dao->listWhere(
  73. $type, 0, FreshRSS_Entry::STATE_ALL, order: 'ASC', limit: -1
  74. );
  75. return [
  76. "starred_{$day}.json",
  77. self::helperToTempFile($view, 'export/articles'),
  78. ];
  79. }
  80. /**
  81. * Generate the entries file for the given feed.
  82. * @return array{0:string,1:string}|null First item is the filename, second item is the path of a temporary file with the content.
  83. * It also can return null if the feed doesn’t exist.
  84. * @throws Minz_PermissionDeniedException
  85. */
  86. public function generateFeedEntries(int $feed_id, int $max_number_entries): ?array {
  87. $view = new FreshRSS_View();
  88. $view->categories = $this->category_dao->listCategories(prePopulateFeeds: true);
  89. $feed = FreshRSS_Category::findFeed($view->categories, $feed_id);
  90. if ($feed === null) {
  91. return null;
  92. }
  93. $view->feed = $feed;
  94. $day = date('Y-m-d');
  95. $filename = "feed_{$day}_" . $feed->categoryId() . '_' . $feed->id() . '.json';
  96. $view->list_title = _t('sub.import_export.feed_list', $feed->name());
  97. $view->type = 'feed/' . $feed->id();
  98. $entriesId = $this->entry_dao->listIdsWhere(
  99. 'f', $feed->id(), FreshRSS_Entry::STATE_ALL, order: 'ASC', limit: $max_number_entries
  100. ) ?? [];
  101. $view->entryIdsTagNames = $this->tag_dao->getEntryIdsTagNames($entriesId);
  102. // The following is a streamable query, i.e. must be last
  103. $view->entries = $this->entry_dao->listWhere(
  104. 'f', $feed->id(), FreshRSS_Entry::STATE_ALL, order: 'ASC', limit: $max_number_entries
  105. );
  106. return [
  107. $filename,
  108. self::helperToTempFile($view, 'export/articles'),
  109. ];
  110. }
  111. /**
  112. * Generate the entries files for all the feeds.
  113. * @return array<string,string> Keys are filenames and values are paths of temporary files with the contents.
  114. * @throws Minz_PermissionDeniedException
  115. */
  116. public function generateAllFeedEntries(int $max_number_entries): array {
  117. $feed_ids = $this->feed_dao->listFeedsIds();
  118. $exported_files = [];
  119. foreach ($feed_ids as $feed_id) {
  120. $result = $this->generateFeedEntries($feed_id, $max_number_entries);
  121. if ($result === null) {
  122. continue;
  123. }
  124. [$filename, $path] = $result;
  125. $exported_files[$filename] = $path;
  126. }
  127. return $exported_files;
  128. }
  129. /**
  130. * Compress several files in a Zip file.
  131. * @param array<string,string> $files where the key is the filename, the value is the path of the file
  132. * @return array{0:string,1:string|false} First item is the zip filename, second item is the path of a temporary zip file, or false in case of error
  133. * @throws Minz_PermissionDeniedException
  134. */
  135. public function zip(array $files): array {
  136. $day = date('Y-m-d');
  137. $zip_filename = 'freshrss_' . $this->username . '_' . $day . '_export.zip';
  138. $zip_file = self::tempFile();
  139. $zip_archive = new ZipArchive();
  140. $zip_archive->open($zip_file, ZipArchive::OVERWRITE);
  141. foreach ($files as $filename => $path) {
  142. $zip_archive->addFile($path, $filename);
  143. }
  144. return [
  145. $zip_filename,
  146. $zip_archive->close() ? $zip_file : false,
  147. ];
  148. }
  149. /**
  150. * Create a temporary file, which is deleted at the end of the script.
  151. * @throws Minz_PermissionDeniedException
  152. */
  153. private static function tempFile(): string {
  154. $filename = tempnam(TMP_PATH, 'export');
  155. if ($filename === false) {
  156. throw new Minz_PermissionDeniedException(TMP_PATH);
  157. }
  158. register_shutdown_function(static fn() => @unlink($filename));
  159. return $filename;
  160. }
  161. /**
  162. * Render a view helper into a temporary file, instead of keeping the whole content in memory.
  163. * @return string The path of the temporary file
  164. * @throws Minz_PermissionDeniedException
  165. */
  166. private static function helperToTempFile(FreshRSS_View $view, string $helper): string {
  167. $filename = self::tempFile();
  168. $view->helperToFile($helper, $filename);
  169. return $filename;
  170. }
  171. }