_cli.php 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191
  1. <?php
  2. declare(strict_types=1);
  3. if (php_sapi_name() !== 'cli') {
  4. die('FreshRSS error: This PHP script may only be invoked from command line!');
  5. }
  6. const EXIT_CODE_ALREADY_EXISTS = 3;
  7. const REGEX_INPUT_OPTIONS = '/^-{2}|^-{1}/';
  8. require(__DIR__ . '/../constants.php');
  9. require(LIB_PATH . '/lib_rss.php'); //Includes class autoloader
  10. require(LIB_PATH . '/lib_install.php');
  11. Minz_Session::init('FreshRSS', true);
  12. FreshRSS_Context::initSystem();
  13. Minz_ExtensionManager::init();
  14. Minz_Translate::init('en');
  15. FreshRSS_Context::$isCli = true;
  16. /** @return never */
  17. function fail(string $message, int $exitCode = 1) {
  18. fwrite(STDERR, $message . "\n");
  19. die($exitCode);
  20. }
  21. function cliInitUser(string $username): string {
  22. if (!FreshRSS_user_Controller::checkUsername($username)) {
  23. fail('FreshRSS error: invalid username: ' . $username . "\n");
  24. }
  25. if (!FreshRSS_user_Controller::userExists($username)) {
  26. fail('FreshRSS error: user not found: ' . $username . "\n");
  27. }
  28. FreshRSS_Context::initUser($username);
  29. if (!FreshRSS_Context::hasUserConf()) {
  30. fail('FreshRSS error: invalid configuration for user: ' . $username . "\n");
  31. }
  32. $ext_list = FreshRSS_Context::userConf()->extensions_enabled;
  33. Minz_ExtensionManager::enableByList($ext_list, 'user');
  34. return $username;
  35. }
  36. function accessRights(): void {
  37. echo 'ℹ️ Remember to re-apply the appropriate access rights, such as:',
  38. "\t", 'sudo cli/access-permissions.sh', "\n";
  39. }
  40. /** @return never */
  41. function done(bool $ok = true) {
  42. if (!$ok) {
  43. fwrite(STDERR, (empty($_SERVER['argv'][0]) ? 'Process' : basename($_SERVER['argv'][0])) . ' failed!' . "\n");
  44. }
  45. exit($ok ? 0 : 1);
  46. }
  47. function performRequirementCheck(string $databaseType): void {
  48. $requirements = checkRequirements($databaseType);
  49. if ($requirements['all'] !== 'ok') {
  50. $message = 'FreshRSS failed requirements:' . "\n";
  51. foreach ($requirements as $requirement => $check) {
  52. if ($check !== 'ok' && !in_array($requirement, ['all', 'pdo', 'message'], true)) {
  53. $message .= '• ' . $requirement . "\n";
  54. }
  55. }
  56. if (!empty($requirements['message']) && $requirements['message'] !== 'ok') {
  57. $message .= '• ' . $requirements['message'] . "\n";
  58. }
  59. fail($message);
  60. }
  61. }
  62. /**
  63. * Parses parameters used with FreshRSS' CLI commands.
  64. * @param array{'long':array<string,string>,'short':array<string,string>,'deprecated':array<string,string>} $parameters
  65. * Matrix of 'long': map of long option names as keys and their respective getopt() notations as values,
  66. * 'short': map of short option names as values and their equivalent long options as keys, 'deprecated': map of
  67. * replacement option names as keys and their respective deprecated option names as values.
  68. * @return array{'valid':array<string,string>,'invalid':array<string>} Matrix of 'valid': map of of all known
  69. * option names used and their respective values and 'invalid': list of all unknown options used.
  70. */
  71. function parseCliParams(array $parameters): array {
  72. global $argv;
  73. $longOptions = [];
  74. $shortOptions = '';
  75. foreach ($parameters['long'] as $name => $getopt_note) {
  76. $longOptions[] = $name . $getopt_note;
  77. }
  78. foreach ($parameters['deprecated'] as $name => $deprecatedName) {
  79. $longOptions[] = $deprecatedName . $parameters['long'][$name];
  80. }
  81. foreach ($parameters['short'] as $name => $shortName) {
  82. $shortOptions .= $shortName . $parameters['long'][$name];
  83. }
  84. $options = getopt($shortOptions, $longOptions);
  85. $valid = is_array($options) ? $options : [];
  86. array_walk($valid, static fn(&$option) => $option = $option === false ? '' : $option);
  87. /** @var array<string,string> $valid */
  88. checkForDeprecatedOptions(array_keys($valid), $parameters['deprecated']);
  89. $valid = replaceOptions($valid, $parameters['short']);
  90. $valid = replaceOptions($valid, $parameters['deprecated']);
  91. $invalid = findInvalidOptions(
  92. $argv,
  93. array_merge(array_keys($parameters['long']), array_values($parameters['short']), array_values($parameters['deprecated']))
  94. );
  95. return [
  96. 'valid' => $valid,
  97. 'invalid' => $invalid
  98. ];
  99. }
  100. /**
  101. * @param array<string> $options
  102. * @return array<string>
  103. */
  104. function getOptions(array $options, string $regex): array {
  105. $longOptions = array_filter($options, static function (string $a) use ($regex) {
  106. return preg_match($regex, $a) === 1;
  107. });
  108. return array_map(static function (string $a) use ($regex) {
  109. return preg_replace($regex, '', $a) ?? '';
  110. }, $longOptions);
  111. }
  112. /**
  113. * Checks for presence of unknown options.
  114. * @param array<string> $input List of command line arguments to check for validity.
  115. * @param array<string> $params List of valid options to check against.
  116. * @return array<string> Returns a list all unknown options found.
  117. */
  118. function findInvalidOptions(array $input, array $params): array {
  119. $sanitizeInput = getOptions($input, REGEX_INPUT_OPTIONS);
  120. $unknownOptions = array_diff($sanitizeInput, $params);
  121. if (0 === count($unknownOptions)) {
  122. return [];
  123. }
  124. fwrite(STDERR, sprintf("FreshRSS error: unknown options: %s\n", implode (', ', $unknownOptions)));
  125. return $unknownOptions;
  126. }
  127. /**
  128. * Checks for presence of deprecated options.
  129. * @param array<string> $optionNames Command line option names to check for deprecation.
  130. * @param array<string,string> $params Map of replacement options as keys and their respective deprecated
  131. * options as values.
  132. * @return bool Returns TRUE and generates a deprecation warning if deprecated options are present, FALSE otherwise.
  133. */
  134. function checkForDeprecatedOptions(array $optionNames, array $params): bool {
  135. $deprecatedOptions = array_intersect($optionNames, $params);
  136. $replacements = array_map(static fn($option) => array_search($option, $params, true), $deprecatedOptions);
  137. if (0 === count($deprecatedOptions)) {
  138. return false;
  139. }
  140. fwrite(STDERR, "FreshRSS deprecation warning: the CLI option(s): " . implode(', ', $deprecatedOptions) .
  141. " are deprecated and will be removed in a future release. Use: "
  142. . implode(', ', $replacements) . " instead\n");
  143. return true;
  144. }
  145. /**
  146. * Switches items in a list to their provided replacements.
  147. * @param array<string,string> $options Map with items to check for replacement as keys.
  148. * @param array<string,string> $replacements Map of replacement items as keys and the item they replace as their values.
  149. * @return array<string,string> Returns $options with replacements.
  150. */
  151. function replaceOptions(array $options, array $replacements): array {
  152. $updatedOptions = [];
  153. foreach ($options as $name => $value) {
  154. $replacement = array_search($name, $replacements, true);
  155. $updatedOptions[$replacement ? $replacement : $name] = $value;
  156. }
  157. return $updatedOptions;
  158. }