updateController.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405
  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 writeable! ' .
  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 (!(Minz_Request::actionName() === 'apply' && Minz_Request::paramBoolean('post_conf')) &&
  121. FreshRSS_Auth::requestReauth()) {
  122. return;
  123. }
  124. include_once LIB_PATH . '/lib_install.php';
  125. invalidateHttpCache();
  126. $this->view->is_release_channel_stable = $this->is_release_channel_stable(FRESHRSS_VERSION);
  127. $this->view->update_to_apply = false;
  128. $this->view->last_update_time = 'unknown';
  129. $timestamp = @filemtime(join_path(DATA_PATH, self::LASTUPDATEFILE));
  130. if ($timestamp !== false) {
  131. $this->view->last_update_time = timestamptodate($timestamp);
  132. }
  133. }
  134. public function indexAction(): void {
  135. FreshRSS_View::prependTitle(_t('admin.update.title') . ' · ');
  136. if (file_exists(UPDATE_FILENAME)) {
  137. // There is an update file to apply!
  138. $version = @file_get_contents(join_path(DATA_PATH, self::LASTUPDATEFILE));
  139. if ($version == '') {
  140. $version = 'unknown';
  141. }
  142. if (@touch(FRESHRSS_PATH . '/index.html')) {
  143. $this->view->update_to_apply = true;
  144. $this->view->message = [
  145. 'status' => 'good',
  146. 'title' => _t('gen.short.ok'),
  147. 'body' => _t('feedback.update.can_apply', $version),
  148. ];
  149. } else {
  150. $this->view->message = [
  151. 'status' => 'bad',
  152. 'title' => _t('gen.short.damn'),
  153. 'body' => _t('feedback.update.file_is_nok', $version, FRESHRSS_PATH),
  154. ];
  155. }
  156. }
  157. }
  158. private function is_release_channel_stable(string $currentVersion): bool {
  159. return !str_contains($currentVersion, 'dev') && !str_contains($currentVersion, 'edge');
  160. }
  161. /* Check installation if there is a newer version.
  162. via Git, if available.
  163. Else via system configuration auto_update_url
  164. */
  165. public function checkAction(): void {
  166. FreshRSS_View::prependTitle(_t('admin.update.title') . ' · ');
  167. $this->view->_path('update/index.phtml');
  168. if (file_exists(UPDATE_FILENAME)) {
  169. // There is already an update file to apply: we don’t need to check
  170. // the webserver!
  171. // Or if already check during the last hour, do nothing.
  172. Minz_Request::forward(['c' => 'update'], true);
  173. return;
  174. }
  175. $script = '';
  176. if (self::isGit()) {
  177. if (self::hasGitUpdate()) {
  178. $version = self::getCurrentGitBranch();
  179. } else {
  180. $this->view->message = [
  181. 'status' => 'latest',
  182. 'body' => _t('feedback.update.none'),
  183. ];
  184. @touch(join_path(DATA_PATH, self::LASTUPDATEFILE));
  185. return;
  186. }
  187. } else {
  188. $auto_update_url = FreshRSS_Context::systemConf()->auto_update_url . '/?v=' . FRESHRSS_VERSION;
  189. Minz_Log::debug('HTTP GET ' . $auto_update_url);
  190. $curlResource = curl_init($auto_update_url);
  191. if ($curlResource === false) {
  192. Minz_Log::warning('curl_init() failed');
  193. $this->view->message = [
  194. 'status' => 'bad',
  195. 'title' => _t('gen.short.damn'),
  196. 'body' => _t('feedback.update.server_not_found', $auto_update_url)
  197. ];
  198. return;
  199. }
  200. curl_setopt($curlResource, CURLOPT_RETURNTRANSFER, true);
  201. curl_setopt($curlResource, CURLOPT_SSL_VERIFYPEER, true);
  202. curl_setopt($curlResource, CURLOPT_SSL_VERIFYHOST, 2);
  203. $result = curl_exec($curlResource);
  204. $curlGetinfo = curl_getinfo($curlResource, CURLINFO_HTTP_CODE);
  205. $curlError = curl_error($curlResource);
  206. if ($curlGetinfo !== 200) {
  207. Minz_Log::warning(
  208. 'Error during update (HTTP code ' . $curlGetinfo . '): ' . $curlError
  209. );
  210. $this->view->message = [
  211. 'status' => 'bad',
  212. 'body' => _t('feedback.update.server_not_found', $auto_update_url),
  213. ];
  214. return;
  215. }
  216. $res_array = explode("\n", (string)$result, 2);
  217. $status = $res_array[0];
  218. if (!str_starts_with($status, 'UPDATE')) {
  219. $this->view->message = [
  220. 'status' => 'latest',
  221. 'body' => _t('feedback.update.none'),
  222. ];
  223. @touch(join_path(DATA_PATH, self::LASTUPDATEFILE));
  224. return;
  225. }
  226. $script = $res_array[1];
  227. $version = explode(' ', $status, 2);
  228. $version = $version[1];
  229. Minz_Log::notice(_t('admin.update.copiedFromURL', $auto_update_url));
  230. }
  231. if (file_put_contents(UPDATE_FILENAME, $script) !== false) {
  232. @file_put_contents(join_path(DATA_PATH, self::LASTUPDATEFILE), $version);
  233. Minz_Request::forward(['c' => 'update'], true);
  234. } else {
  235. $this->view->message = [
  236. 'status' => 'bad',
  237. 'body' => _t('feedback.update.error', 'Cannot save the update script'),
  238. ];
  239. }
  240. }
  241. public function applyAction(): void {
  242. if (FreshRSS_Context::systemConf()->disable_update || !file_exists(UPDATE_FILENAME) || !touch(FRESHRSS_PATH . '/index.html')) {
  243. Minz_Request::forward(['c' => 'update'], true);
  244. }
  245. if (Minz_Request::paramBoolean('post_conf')) {
  246. if (self::isGit()) {
  247. $res = !self::hasGitUpdate();
  248. } else {
  249. require UPDATE_FILENAME;
  250. // @phpstan-ignore function.notFound
  251. $res = do_post_update();
  252. }
  253. Minz_ExtensionManager::callHookVoid(Minz_HookType::PostUpdate);
  254. if ($res === true) {
  255. @unlink(UPDATE_FILENAME);
  256. @file_put_contents(join_path(DATA_PATH, self::LASTUPDATEFILE), '');
  257. Minz_Log::notice(_t('feedback.update.finished'));
  258. Minz_Request::good(
  259. _t('feedback.update.finished'),
  260. showNotification: FreshRSS_Context::userConf()->good_notification_timeout > 0
  261. );
  262. } else {
  263. Minz_Log::error(_t('feedback.update.error', is_string($res) ? $res : 'unknown'));
  264. Minz_Request::bad(_t('feedback.update.error', is_string($res) ? $res : 'unknown'), [ 'c' => 'update', 'a' => 'index' ]);
  265. }
  266. } else {
  267. $res = false;
  268. if (self::isGit()) {
  269. $res = self::gitPull();
  270. } else {
  271. require UPDATE_FILENAME;
  272. if (Minz_Request::isPost()) {
  273. // @phpstan-ignore function.notFound
  274. save_info_update();
  275. }
  276. // @phpstan-ignore function.notFound
  277. if (!need_info_update()) {
  278. // @phpstan-ignore function.notFound
  279. $res = apply_update();
  280. } else {
  281. return;
  282. }
  283. }
  284. if (function_exists('opcache_reset')) {
  285. opcache_reset();
  286. }
  287. if ($res === true) {
  288. Minz_Request::forward([
  289. 'c' => 'update',
  290. 'a' => 'apply',
  291. 'params' => ['post_conf' => '1'],
  292. ], true);
  293. } else {
  294. Minz_Log::error(_t('feedback.update.error', is_string($res) ? $res : 'unknown'));
  295. Minz_Request::bad(_t('feedback.update.error', is_string($res) ? $res : 'unknown'), [ 'c' => 'update', 'a' => 'index' ]);
  296. }
  297. }
  298. }
  299. /**
  300. * Check PHP and its extensions are well-installed.
  301. *
  302. * @return array<string,'ok'|'ko'|'warn'> of tested values.
  303. */
  304. private static function check_install_php(): array {
  305. require_once LIB_PATH . '/lib_install.php';
  306. return checkRequirements(FreshRSS_Context::systemConf()->db['type'] ?? '', checkPhp: true, checkFiles: false);
  307. }
  308. /**
  309. * Check different data files and directories exist.
  310. * @return array<string,'ok'|'ko'|'warn'> of tested values.
  311. */
  312. private static function check_install_files(): array {
  313. require_once LIB_PATH . '/lib_install.php';
  314. return checkRequirements(FreshRSS_Context::systemConf()->db['type'] ?? '', checkPhp: false, checkFiles: true);
  315. }
  316. /**
  317. * Check database is well-installed.
  318. *
  319. * @return array<string,bool> of tested values.
  320. */
  321. private static function check_install_database(): array {
  322. $status = [
  323. 'connection' => true,
  324. 'tables' => false,
  325. 'categories' => false,
  326. 'feeds' => false,
  327. 'entries' => false,
  328. 'entrytmp' => false,
  329. 'tag' => false,
  330. 'entrytag' => false,
  331. ];
  332. try {
  333. $dbDAO = FreshRSS_Factory::createDatabaseDAO();
  334. $status['tables'] = $dbDAO->tablesAreCorrect();
  335. $status['categories'] = $dbDAO->categoryIsCorrect();
  336. $status['feeds'] = $dbDAO->feedIsCorrect();
  337. $status['entries'] = $dbDAO->entryIsCorrect();
  338. $status['entrytmp'] = $dbDAO->entrytmpIsCorrect();
  339. $status['tag'] = $dbDAO->tagIsCorrect();
  340. $status['entrytag'] = $dbDAO->entrytagIsCorrect();
  341. } catch (Minz_PDOConnectionException $e) {
  342. $status['connection'] = false;
  343. }
  344. return $status;
  345. }
  346. /**
  347. * This action displays information about installation.
  348. */
  349. public function checkInstallAction(): void {
  350. FreshRSS_View::prependTitle(_t('install.check._') . ' · ');
  351. $this->view->status_php = self::check_install_php();
  352. $this->view->status_files = self::check_install_files();
  353. $this->view->status_database = self::check_install_database();
  354. }
  355. }