_cli.php 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212
  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 = '/^--/';
  8. const REGEX_PARAM_OPTIONS = '/:*$/';
  9. require(__DIR__ . '/../constants.php');
  10. require(LIB_PATH . '/lib_rss.php'); //Includes class autoloader
  11. require(LIB_PATH . '/lib_install.php');
  12. Minz_Session::init('FreshRSS', true);
  13. FreshRSS_Context::initSystem();
  14. Minz_ExtensionManager::init();
  15. Minz_Translate::init('en');
  16. FreshRSS_Context::$isCli = true;
  17. /** @return never */
  18. function fail(string $message, int $exitCode = 1) {
  19. fwrite(STDERR, $message . "\n");
  20. die($exitCode);
  21. }
  22. function cliInitUser(string $username): string {
  23. if (!FreshRSS_user_Controller::checkUsername($username)) {
  24. fail('FreshRSS error: invalid username: ' . $username . "\n");
  25. }
  26. if (!FreshRSS_user_Controller::userExists($username)) {
  27. fail('FreshRSS error: user not found: ' . $username . "\n");
  28. }
  29. FreshRSS_Context::initUser($username);
  30. if (!FreshRSS_Context::hasUserConf()) {
  31. fail('FreshRSS error: invalid configuration for user: ' . $username . "\n");
  32. }
  33. $ext_list = FreshRSS_Context::userConf()->extensions_enabled;
  34. Minz_ExtensionManager::enableByList($ext_list, 'user');
  35. return $username;
  36. }
  37. function accessRights(): void {
  38. echo 'ℹ️ Remember to re-apply the appropriate access rights, such as:',
  39. "\t", 'sudo cli/access-permissions.sh', "\n";
  40. }
  41. /** @return never */
  42. function done(bool $ok = true) {
  43. if (!$ok) {
  44. fwrite(STDERR, (empty($_SERVER['argv'][0]) ? 'Process' : basename($_SERVER['argv'][0])) . ' failed!' . "\n");
  45. }
  46. exit($ok ? 0 : 1);
  47. }
  48. function performRequirementCheck(string $databaseType): void {
  49. $requirements = checkRequirements($databaseType);
  50. if ($requirements['all'] !== 'ok') {
  51. $message = 'FreshRSS failed requirements:' . "\n";
  52. foreach ($requirements as $requirement => $check) {
  53. if ($check !== 'ok' && !in_array($requirement, ['all', 'pdo', 'message'], true)) {
  54. $message .= '• ' . $requirement . "\n";
  55. }
  56. }
  57. if (!empty($requirements['message']) && $requirements['message'] !== 'ok') {
  58. $message .= '• ' . $requirements['message'] . "\n";
  59. }
  60. fail($message);
  61. }
  62. }
  63. /**
  64. * Parses parameters used with FreshRSS' CLI commands.
  65. * @param array{'valid':array<string,string>,'deprecated':array<string,string>} $parameters An array of 'valid': An
  66. * array of parameters as keys and their respective getopt() notations as values. 'deprecated' An array with
  67. * replacement parameters as keys and their respective deprecated parameters as values.
  68. * @return array{'valid':array<string,string|bool>,'invalid':array<string>} An array of 'valid': an array of all
  69. * known parameters used and their respective options and 'invalid': an array of all unknown parameters used.
  70. */
  71. function parseCliParams(array $parameters): array {
  72. global $argv;
  73. $cliParams = [];
  74. foreach ($parameters['valid'] as $param => $getopt_val) {
  75. $cliParams[] = $param . $getopt_val;
  76. }
  77. foreach ($parameters['deprecated'] as $param => $deprecatedParam) {
  78. $cliParams[] = $deprecatedParam . $parameters['valid'][$param];
  79. }
  80. $opts = getopt('', $cliParams);
  81. /** @var array<string,string|bool> $valid */
  82. $valid = is_array($opts) ? $opts : [];
  83. array_walk($valid, static fn(&$option) => $option = $option === false ? true : $option);
  84. if (checkforDeprecatedParameterUse(array_keys($valid), $parameters['deprecated'])) {
  85. $valid = updateDeprecatedParameters($valid, $parameters['deprecated']);
  86. }
  87. $invalid = findInvalidOptions(
  88. $argv,
  89. array_merge(array_keys($parameters['valid']), array_values($parameters['deprecated']))
  90. );
  91. return [
  92. 'valid' => $valid,
  93. 'invalid' => $invalid
  94. ];
  95. }
  96. /**
  97. * @param array<string> $options
  98. * @return array<string>
  99. */
  100. function getLongOptions(array $options, string $regex): array {
  101. $longOptions = array_filter($options, static function (string $a) use ($regex) {
  102. return preg_match($regex, $a) === 1;
  103. });
  104. return array_map(static function (string $a) use ($regex) {
  105. return preg_replace($regex, '', $a) ?? '';
  106. }, $longOptions);
  107. }
  108. /**
  109. * @param array<string> $input
  110. * @param array<string> $params
  111. */
  112. function validateOptions(array $input, array $params): bool {
  113. $sanitizeInput = getLongOptions($input, REGEX_INPUT_OPTIONS);
  114. $sanitizeParams = getLongOptions($params, REGEX_PARAM_OPTIONS);
  115. $unknownOptions = array_diff($sanitizeInput, $sanitizeParams);
  116. if (0 === count($unknownOptions)) {
  117. return true;
  118. }
  119. fwrite(STDERR, sprintf("FreshRSS error: unknown options: %s\n", implode (', ', $unknownOptions)));
  120. return false;
  121. }
  122. /**
  123. * Checks for use of unknown parameters with FreshRSS' CLI commands.
  124. * @param array<string> $input An array of parameters to check for validity.
  125. * @param array<string> $params An array of valid parameters to check against.
  126. * @return array<string> Returns an array of all unknown parameters found.
  127. */
  128. function findInvalidOptions(array $input, array $params): array {
  129. $sanitizeInput = getLongOptions($input, REGEX_INPUT_OPTIONS);
  130. $unknownOptions = array_diff($sanitizeInput, $params);
  131. if (0 === count($unknownOptions)) {
  132. return [];
  133. }
  134. fwrite(STDERR, sprintf("FreshRSS error: unknown options: %s\n", implode (', ', $unknownOptions)));
  135. return $unknownOptions;
  136. }
  137. /**
  138. * Checks for use of deprecated parameters with FreshRSS' CLI commands.
  139. * @param array<string> $options User inputs to check for deprecated parameter use.
  140. * @param array<string,string> $params An array with replacement parameters as keys and their respective deprecated
  141. * parameters as values.
  142. * @return bool Returns TRUE and generates a deprecation warning if deprecated parameters
  143. * have been used, FALSE otherwise.
  144. */
  145. function checkforDeprecatedParameterUse(array $options, array $params): bool {
  146. $deprecatedOptions = array_intersect($options, $params);
  147. $replacements = array_map(static fn($option) => array_search($option, $params, true), $deprecatedOptions);
  148. if (0 === count($deprecatedOptions)) {
  149. return false;
  150. }
  151. fwrite(STDERR, "FreshRSS deprecation warning: the CLI option(s): " . implode(', ', $deprecatedOptions) .
  152. " are deprecated and will be removed in a future release. Use: "
  153. . implode(', ', $replacements) . " instead\n");
  154. return true;
  155. }
  156. /**
  157. * Switches all used deprecated parameters to their replacements if they have one.
  158. *
  159. * @template T
  160. *
  161. * @param array<string,T> $options User inputs.
  162. * @param array<string,string> $params An array with replacement parameters as keys and their respective deprecated
  163. * parameters as values.
  164. * @return array<string,T> Returns $options with deprications replaced.
  165. */
  166. function updateDeprecatedParameters(array $options, array $params): array {
  167. $updatedOptions = [];
  168. foreach ($options as $param => $option) {
  169. $replacement = array_search($param, $params, true);
  170. if (is_string($replacement)) {
  171. $updatedOptions[$replacement] = $option;
  172. } else {
  173. $updatedOptions[$param] = $option;
  174. }
  175. }
  176. return $updatedOptions;
  177. }