4
0

export-sqlite-auto.php 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. #!/usr/bin/env php
  2. <?php
  3. declare(strict_types=1);
  4. require __DIR__ . '/_cli.php';
  5. performRequirementCheck(FreshRSS_Context::systemConf()->db['type'] ?? '');
  6. $cliOptions = new class extends CliOptionsParser {
  7. public bool $quiet;
  8. public function __construct() {
  9. $this->addOption('quiet', (new CliOption('quiet', 'q'))->withValueNone());
  10. parent::__construct();
  11. }
  12. };
  13. if (!empty($cliOptions->errors)) {
  14. fail('FreshRSS error: ' . array_shift($cliOptions->errors) . "\n" . $cliOptions->usage);
  15. }
  16. $config = FreshRSS_Context::systemConf()->auto_sqlite_export;
  17. $enabled = !empty($config['enabled']);
  18. $retention = max(1, (int)($config['retention'] ?? 7));
  19. $verbose = !$cliOptions->quiet;
  20. if (!$enabled) {
  21. if ($verbose) {
  22. echo "FreshRSS automatic SQLite export is disabled (see `auto_sqlite_export.enabled` in `data/config.php`).\n";
  23. }
  24. exit(0);
  25. }
  26. $ok = true;
  27. $timestamp = gmdate('Ymd\THis\Z');
  28. foreach (FreshRSS_user_Controller::listUsers() as $username) {
  29. $username = cliInitUser($username);
  30. $exportDir = DATA_PATH . '/users/' . $username . '/sqlite-backups';
  31. if (!is_dir($exportDir) && !@mkdir($exportDir, 0755, true)) {
  32. fwrite(STDERR, "FreshRSS error: unable to create export directory: {$exportDir}\n");
  33. $ok = false;
  34. continue;
  35. }
  36. $filename = $exportDir . '/' . $timestamp . '.sqlite';
  37. if ($verbose) {
  38. echo 'FreshRSS automatic SQLite export for user “', $username, '” -> ', $filename, "\n";
  39. }
  40. $databaseDAO = FreshRSS_Factory::createDatabaseDAO($username);
  41. $exported = $databaseDAO->dbCopy($filename, FreshRSS_DatabaseDAO::SQLITE_EXPORT, false, $verbose);
  42. $ok = $ok && $exported;
  43. if (!$exported) {
  44. continue;
  45. }
  46. $existing = glob($exportDir . '/*.sqlite') ?: [];
  47. if (count($existing) > $retention) {
  48. sort($existing);
  49. $toDelete = array_slice($existing, 0, count($existing) - $retention);
  50. foreach ($toDelete as $old) {
  51. if (@unlink($old)) {
  52. if ($verbose) {
  53. echo "Pruned old export: {$old}\n";
  54. }
  55. } else {
  56. fwrite(STDERR, "FreshRSS warning: failed to prune old export: {$old}\n");
  57. }
  58. }
  59. }
  60. }
  61. done($ok);