updateController.php 12 KB

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