updateController.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440
  1. <?php
  2. declare(strict_types=1);
  3. class FreshRSS_update_Controller extends FreshRSS_ActionController {
  4. private const LASTUPDATEFILE = 'last_update.txt';
  5. public static function isGit(): bool {
  6. return is_dir(FRESHRSS_PATH . '/.git/');
  7. }
  8. /**
  9. * Automatic change to the new name of edge branch since FreshRSS 1.18.0,
  10. * and perform checks for several git errors.
  11. * @throws Minz_Exception
  12. */
  13. public static function migrateToGitEdge(): bool {
  14. if (!is_writable(FRESHRSS_PATH . '/.git/config')) {
  15. throw new Minz_Exception('Error during git checkout: .git directory does not seem writable! ' .
  16. 'Please git pull manually!');
  17. }
  18. if (!function_exists('exec')) {
  19. throw new Minz_Exception('Error during git checkout: exec() function is disabled! ' .
  20. 'Please git pull manually!');
  21. }
  22. exec('git --version', $output, $return);
  23. if ($return != 0) {
  24. throw new Minz_Exception("Error {$return} git not found: Please update manually!");
  25. }
  26. //Note `git branch --show-current` requires git 2.22+
  27. exec('git symbolic-ref --short HEAD 2>&1', $output, $return);
  28. if ($return != 0) {
  29. throw new Minz_Exception("Error {$return} during git symbolic-ref: " .
  30. 'Reapply `chown www-data:www-data -R ' . FRESHRSS_PATH . '` ' .
  31. 'or git pull manually! ' .
  32. json_encode($output, JSON_UNESCAPED_SLASHES));
  33. }
  34. $line = implode('', $output);
  35. if ($line !== 'master' && $line !== 'dev') {
  36. return true; // not on master or dev, nothing to do
  37. }
  38. Minz_Log::warning('Automatic migration to git edge branch');
  39. unset($output);
  40. exec('git checkout edge --guess -f', $output, $return);
  41. if ($return != 0) {
  42. throw new Minz_Exception("Error {$return} during git checkout to edge branch! ' .
  43. 'Please change branch manually!");
  44. }
  45. unset($output);
  46. exec('git reset --hard FETCH_HEAD', $output, $return);
  47. if ($return != 0) {
  48. throw new Minz_Exception("Error {$return} during git reset! Please git pull manually!");
  49. }
  50. return true;
  51. }
  52. public static function getCurrentGitBranch(): string {
  53. $output = [];
  54. exec('git branch --show-current', $output, $return);
  55. if ($return === 0) {
  56. return 'git branch: ' . $output[0];
  57. } else {
  58. return 'git';
  59. }
  60. }
  61. public static function hasGitUpdate(): bool {
  62. $cwd = getcwd();
  63. if ($cwd === false) {
  64. Minz_Log::warning('getcwd() failed');
  65. return false;
  66. }
  67. chdir(FRESHRSS_PATH);
  68. $output = [];
  69. try {
  70. /** @throws ValueError */
  71. exec('git fetch --prune', $output, $return);
  72. if ($return == 0) {
  73. $output = [];
  74. exec('git status -sb --porcelain remote', $output, $return);
  75. } else {
  76. $line = implode('; ', $output);
  77. Minz_Log::warning('git fetch warning: ' . $line);
  78. }
  79. } catch (Throwable $e) {
  80. Minz_Log::warning('git fetch error: ' . $e->getMessage());
  81. }
  82. chdir($cwd);
  83. $line = implode('; ', $output);
  84. return $line == '' ||
  85. str_contains($line, '[behind') || str_contains($line, '[ahead') || str_contains($line, '[gone');
  86. }
  87. /** @return string|true */
  88. public static function gitPull(): string|bool {
  89. Minz_Log::notice(_t('admin.update.viaGit'));
  90. $cwd = getcwd();
  91. if ($cwd === false) {
  92. Minz_Log::warning('getcwd() failed');
  93. return 'getcwd() failed';
  94. }
  95. chdir(FRESHRSS_PATH);
  96. $output = [];
  97. $return = 1;
  98. try {
  99. exec('git fetch --prune', $output, $return);
  100. if ($return == 0) {
  101. $output = [];
  102. exec('git reset --hard FETCH_HEAD', $output, $return);
  103. }
  104. $output = [];
  105. self::migrateToGitEdge();
  106. } catch (Throwable $e) {
  107. Minz_Log::warning('Git error: ' . $e->getMessage());
  108. $output = $e->getMessage();
  109. $return = 1;
  110. }
  111. chdir($cwd);
  112. $line = is_array($output) ? implode('; ', $output) : $output;
  113. return $return == 0 ? true : 'Git error: ' . $line;
  114. }
  115. #[\Override]
  116. public function firstAction(): void {
  117. if (!FreshRSS_Auth::hasAccess('admin')) {
  118. Minz_Error::error(403);
  119. }
  120. if (FreshRSS_Auth::requestReauth()) {
  121. return;
  122. }
  123. include_once LIB_PATH . '/lib_install.php';
  124. invalidateHttpCache();
  125. $this->view->is_release_channel_stable = $this->is_release_channel_stable(FRESHRSS_VERSION);
  126. $this->view->update_to_apply = false;
  127. $this->view->last_update_time = 'unknown';
  128. $timestamp = @filemtime(join_path(DATA_PATH, self::LASTUPDATEFILE));
  129. if ($timestamp !== false) {
  130. $this->view->last_update_time = timestamptodate($timestamp);
  131. }
  132. }
  133. public function indexAction(): void {
  134. FreshRSS_View::prependTitle(_t('admin.update.title') . ' · ');
  135. if (file_exists(UPDATE_FILENAME)) {
  136. // There is an update file to apply!
  137. $version = @file_get_contents(join_path(DATA_PATH, self::LASTUPDATEFILE));
  138. if ($version == '') {
  139. $version = 'unknown';
  140. }
  141. if (@touch(FRESHRSS_PATH . '/index.html')) {
  142. $this->view->update_to_apply = true;
  143. $this->view->message = [
  144. 'status' => 'good',
  145. 'title' => _t('gen.short.ok'),
  146. 'body' => _t('feedback.update.can_apply', $version),
  147. ];
  148. } else {
  149. $this->view->message = [
  150. 'status' => 'bad',
  151. 'title' => _t('gen.short.damn'),
  152. 'body' => _t('feedback.update.file_is_nok', $version, FRESHRSS_PATH),
  153. ];
  154. }
  155. }
  156. }
  157. private function is_release_channel_stable(string $currentVersion): bool {
  158. return !str_contains($currentVersion, 'dev') && !str_contains($currentVersion, 'edge');
  159. }
  160. /* Check installation if there is a newer version.
  161. via Git, if available.
  162. Else via system configuration auto_update_url
  163. */
  164. public function checkAction(): void {
  165. if (!Minz_Request::isPost()) {
  166. Minz_Request::forward(['c' => 'update', 'a' => 'index'], true);
  167. return;
  168. }
  169. FreshRSS_View::prependTitle(_t('admin.update.title') . ' · ');
  170. $this->view->_path('update/index.phtml');
  171. if (file_exists(UPDATE_FILENAME)) {
  172. // There is already an update file to apply: we don’t need to check
  173. // the webserver!
  174. // Or if already check during the last hour, do nothing.
  175. Minz_Request::forward(['c' => 'update'], true);
  176. return;
  177. }
  178. $script = '';
  179. if (self::isGit()) {
  180. if (self::hasGitUpdate()) {
  181. $version = self::getCurrentGitBranch();
  182. } else {
  183. $this->view->message = [
  184. 'status' => 'latest',
  185. 'body' => _t('feedback.update.none'),
  186. ];
  187. @touch(join_path(DATA_PATH, self::LASTUPDATEFILE));
  188. return;
  189. }
  190. } else {
  191. $auto_update_url = FreshRSS_Context::systemConf()->auto_update_url . '/?v=' . FRESHRSS_VERSION;
  192. Minz_Log::debug('HTTP GET ' . $auto_update_url);
  193. $curlResource = curl_init($auto_update_url);
  194. if ($curlResource === false) {
  195. Minz_Log::warning('curl_init() failed');
  196. $this->view->message = [
  197. 'status' => 'bad',
  198. 'title' => _t('gen.short.damn'),
  199. 'body' => _t('feedback.update.server_not_found', $auto_update_url)
  200. ];
  201. return;
  202. }
  203. curl_setopt($curlResource, CURLOPT_RETURNTRANSFER, true);
  204. curl_setopt($curlResource, CURLOPT_SSL_VERIFYPEER, true);
  205. curl_setopt($curlResource, CURLOPT_SSL_VERIFYHOST, 2);
  206. $curl_options = [];
  207. if (defined('CURLOPT_PROTOCOLS_STR') && is_int(CURLOPT_PROTOCOLS_STR)) {
  208. $curl_options[CURLOPT_PROTOCOLS_STR] = 'http,https';
  209. if (defined('CURLOPT_REDIR_PROTOCOLS_STR') && is_int(CURLOPT_REDIR_PROTOCOLS_STR)) {
  210. $curl_options[CURLOPT_REDIR_PROTOCOLS_STR] = 'http,https';
  211. }
  212. } elseif (defined('CURLPROTO_HTTP') && defined('CURLPROTO_HTTPS')) {
  213. // Legacy PHP 8.2-
  214. if (defined('CURLOPT_PROTOCOLS')) {
  215. $curl_options[CURLOPT_PROTOCOLS] = CURLPROTO_HTTP | CURLPROTO_HTTPS;
  216. }
  217. if (defined('CURLOPT_REDIR_PROTOCOLS')) {
  218. $curl_options[CURLOPT_REDIR_PROTOCOLS] = CURLPROTO_HTTP | CURLPROTO_HTTPS;
  219. }
  220. }
  221. curl_setopt_array($curlResource, $curl_options);
  222. $result = curl_exec($curlResource);
  223. $curlGetinfo = curl_getinfo($curlResource, CURLINFO_HTTP_CODE);
  224. $curlError = curl_error($curlResource);
  225. if ($curlGetinfo !== 200) {
  226. Minz_Log::warning(
  227. 'Error during update (HTTP code ' . $curlGetinfo . '): ' . $curlError
  228. );
  229. $this->view->message = [
  230. 'status' => 'bad',
  231. 'body' => _t('feedback.update.server_not_found', $auto_update_url),
  232. ];
  233. return;
  234. }
  235. $res_array = explode("\n", (string)$result, 2);
  236. $status = $res_array[0];
  237. if (!str_starts_with($status, 'UPDATE')) {
  238. $this->view->message = [
  239. 'status' => 'latest',
  240. 'body' => _t('feedback.update.none'),
  241. ];
  242. @touch(join_path(DATA_PATH, self::LASTUPDATEFILE));
  243. return;
  244. }
  245. $script = $res_array[1];
  246. $version = explode(' ', $status, 2);
  247. $version = $version[1];
  248. Minz_Log::notice(_t('admin.update.copiedFromURL', $auto_update_url));
  249. }
  250. if (file_put_contents(UPDATE_FILENAME, $script) !== false) {
  251. @file_put_contents(join_path(DATA_PATH, self::LASTUPDATEFILE), $version);
  252. Minz_Request::forward(['c' => 'update'], true);
  253. } else {
  254. $this->view->message = [
  255. 'status' => 'bad',
  256. 'body' => _t('feedback.update.error', 'Cannot save the update script'),
  257. ];
  258. }
  259. }
  260. public function applyAction(): void {
  261. if (FreshRSS_Context::systemConf()->disable_update || !file_exists(UPDATE_FILENAME) || !touch(FRESHRSS_PATH . '/index.html')) {
  262. Minz_Request::forward(['c' => 'update'], true);
  263. }
  264. if (Minz_Request::paramBoolean('post_conf')) {
  265. if (!Minz_Session::paramBoolean('update_post_conf_ok')) {
  266. Minz_Request::forward(['c' => 'update', 'a' => 'index'], true);
  267. return;
  268. }
  269. Minz_Session::_param('update_post_conf_ok', false);
  270. if (self::isGit()) {
  271. $res = !self::hasGitUpdate();
  272. } else {
  273. require UPDATE_FILENAME;
  274. // @phpstan-ignore function.notFound
  275. $res = do_post_update();
  276. }
  277. Minz_ExtensionManager::callHookVoid(Minz_HookType::PostUpdate);
  278. if ($res === true) {
  279. @unlink(UPDATE_FILENAME);
  280. @file_put_contents(join_path(DATA_PATH, self::LASTUPDATEFILE), '');
  281. Minz_Log::notice(_t('feedback.update.finished'));
  282. Minz_Request::good(
  283. _t('feedback.update.finished'),
  284. showNotification: FreshRSS_Context::userConf()->good_notification_timeout > 0
  285. );
  286. } else {
  287. Minz_Log::error(_t('feedback.update.error', is_string($res) ? $res : 'unknown'));
  288. Minz_Request::bad(_t('feedback.update.error', is_string($res) ? $res : 'unknown'), [ 'c' => 'update', 'a' => 'index' ]);
  289. }
  290. } else {
  291. if (!Minz_Request::isPost()) {
  292. Minz_Request::forward(['c' => 'update', 'a' => 'index'], true);
  293. return;
  294. }
  295. $res = false;
  296. if (self::isGit()) {
  297. $res = self::gitPull();
  298. } else {
  299. require UPDATE_FILENAME;
  300. // @phpstan-ignore function.notFound
  301. save_info_update();
  302. // @phpstan-ignore function.notFound
  303. if (!need_info_update()) {
  304. // @phpstan-ignore function.notFound
  305. $res = apply_update();
  306. } else {
  307. return;
  308. }
  309. }
  310. if (function_exists('opcache_reset')) {
  311. opcache_reset();
  312. }
  313. if ($res === true) {
  314. // Authorise the single internal post-configuration redirect that follows.
  315. Minz_Session::_param('update_post_conf_ok', true);
  316. Minz_Request::forward([
  317. 'c' => 'update',
  318. 'a' => 'apply',
  319. 'params' => ['post_conf' => '1'],
  320. ], true);
  321. } else {
  322. Minz_Log::error(_t('feedback.update.error', is_string($res) ? $res : 'unknown'));
  323. Minz_Request::bad(_t('feedback.update.error', is_string($res) ? $res : 'unknown'), [ 'c' => 'update', 'a' => 'index' ]);
  324. }
  325. }
  326. }
  327. /**
  328. * Check PHP and its extensions are well-installed.
  329. *
  330. * @return array<string,'ok'|'ko'|'warn'> of tested values.
  331. */
  332. private static function check_install_php(): array {
  333. require_once LIB_PATH . '/lib_install.php';
  334. return checkRequirements(FreshRSS_Context::systemConf()->db['type'] ?? '', checkPhp: true, checkFiles: false);
  335. }
  336. /**
  337. * Check different data files and directories exist.
  338. * @return array<string,'ok'|'ko'|'warn'> of tested values.
  339. */
  340. private static function check_install_files(): array {
  341. require_once LIB_PATH . '/lib_install.php';
  342. return checkRequirements(FreshRSS_Context::systemConf()->db['type'] ?? '', checkPhp: false, checkFiles: true);
  343. }
  344. /**
  345. * Check database is well-installed.
  346. *
  347. * @return array<string,array<string,bool>|bool> of tested values.
  348. */
  349. private static function check_install_database(): array {
  350. $status = [
  351. 'connection' => true,
  352. 'tables' => false,
  353. 'table' => [
  354. 'categories' => false,
  355. 'feeds' => false,
  356. 'entries' => false,
  357. 'entrytmp' => false,
  358. 'tag' => false,
  359. 'entrytag' => false,
  360. ],
  361. ];
  362. try {
  363. $dbDAO = FreshRSS_Factory::createDatabaseDAO();
  364. $status['tables'] = $dbDAO->tablesAreCorrect();
  365. $status['table']['categories'] = $dbDAO->categoryIsCorrect();
  366. $status['table']['feeds'] = $dbDAO->feedIsCorrect();
  367. $status['table']['entries'] = $dbDAO->entryIsCorrect();
  368. $status['table']['entrytmp'] = $dbDAO->entrytmpIsCorrect();
  369. $status['table']['tag'] = $dbDAO->tagIsCorrect();
  370. $status['table']['entrytag'] = $dbDAO->entrytagIsCorrect();
  371. } catch (Minz_PDOConnectionException $e) {
  372. $status['connection'] = false;
  373. }
  374. return $status;
  375. }
  376. /**
  377. * This action displays information about installation.
  378. */
  379. public function checkInstallAction(): void {
  380. FreshRSS_View::prependTitle(_t('install.check._') . ' · ');
  381. $this->view->status_php = self::check_install_php();
  382. $this->view->status_files = self::check_install_files();
  383. $this->view->status_database = self::check_install_database();
  384. }
  385. }