update.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435
  1. #!/usr/bin/env php
  2. <?php
  3. set_include_path(dirname(__FILE__) ."/include" . PATH_SEPARATOR .
  4. get_include_path());
  5. define('DISABLE_SESSIONS', true);
  6. chdir(dirname(__FILE__));
  7. require_once "autoload.php";
  8. require_once "functions.php";
  9. require_once "config.php";
  10. require_once "sanity_check.php";
  11. require_once "db.php";
  12. require_once "db-prefs.php";
  13. if (!defined('PHP_EXECUTABLE'))
  14. define('PHP_EXECUTABLE', '/usr/bin/php');
  15. $pdo = Db::pdo();
  16. init_plugins();
  17. $longopts = array("feeds",
  18. "feedbrowser",
  19. "daemon",
  20. "daemon-loop",
  21. "task:",
  22. "cleanup-tags",
  23. "quiet",
  24. "log:",
  25. "log-level:",
  26. "indexes",
  27. "pidlock:",
  28. "update-schema",
  29. "convert-filters",
  30. "force-update",
  31. "gen-search-idx",
  32. "list-plugins",
  33. "debug-feed:",
  34. "force-refetch",
  35. "force-rehash",
  36. "help");
  37. foreach (PluginHost::getInstance()->get_commands() as $command => $data) {
  38. array_push($longopts, $command . $data["suffix"]);
  39. }
  40. $options = getopt("", $longopts);
  41. if (!is_array($options)) {
  42. die("error: getopt() failed. ".
  43. "Most probably you are using PHP CGI to run this script ".
  44. "instead of required PHP CLI. Check tt-rss wiki page on updating feeds for ".
  45. "additional information.\n");
  46. }
  47. if (count($options) == 0 && !defined('STDIN')) {
  48. ?> <html>
  49. <head>
  50. <title>Tiny Tiny RSS data update script.</title>
  51. <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
  52. </head>
  53. <body>
  54. <h1><?php echo __("Tiny Tiny RSS data update script.") ?></h1>
  55. <?php print_error("Please run this script from the command line. Use option \"--help\" to display command help if this error is displayed erroneously."); ?>
  56. </body></html>
  57. <?php
  58. exit;
  59. }
  60. if (count($options) == 0 || isset($options["help"]) ) {
  61. print "Tiny Tiny RSS data update script.\n\n";
  62. print "Options:\n";
  63. print " --feeds - update feeds\n";
  64. print " --feedbrowser - update feedbrowser\n";
  65. print " --daemon - start single-process update daemon\n";
  66. print " --task N - create lockfile using this task id\n";
  67. print " --cleanup-tags - perform tags table maintenance\n";
  68. print " --quiet - don't output messages to stdout\n";
  69. print " --log FILE - log messages to FILE\n";
  70. print " --log-level N - log verbosity level\n";
  71. print " --indexes - recreate missing schema indexes\n";
  72. print " --update-schema - update database schema\n";
  73. print " --gen-search-idx - generate basic PostgreSQL fulltext search index\n";
  74. print " --convert-filters - convert type1 filters to type2\n";
  75. print " --force-update - force update of all feeds\n";
  76. print " --list-plugins - list all available plugins\n";
  77. print " --debug-feed N - perform debug update of feed N\n";
  78. print " --force-refetch - debug update: force refetch feed data\n";
  79. print " --force-rehash - debug update: force rehash articles\n";
  80. print " --help - show this help\n";
  81. print "Plugin options:\n";
  82. foreach (PluginHost::getInstance()->get_commands() as $command => $data) {
  83. $args = $data['arghelp'];
  84. printf(" --%-19s - %s\n", "$command $args", $data["description"]);
  85. }
  86. return;
  87. }
  88. if (!isset($options['daemon'])) {
  89. require_once "errorhandler.php";
  90. }
  91. if (!isset($options['update-schema'])) {
  92. $schema_version = get_schema_version();
  93. if ($schema_version != SCHEMA_VERSION) {
  94. die("Schema version is wrong, please upgrade the database.\n");
  95. }
  96. }
  97. Debug::set_enabled(true);
  98. if (isset($options["log-level"])) {
  99. Debug::set_loglevel((int)$options["log-level"]);
  100. }
  101. if (isset($options["log"])) {
  102. Debug::set_quiet(isset($options['quiet']));
  103. Debug::set_logfile($options["log"]);
  104. Debug::log("Logging to " . $options["log"]);
  105. } else {
  106. if (isset($options['quiet'])) {
  107. Debug::set_loglevel(Debug::$LOG_DISABLED);
  108. }
  109. }
  110. if (!isset($options["daemon"])) {
  111. $lock_filename = "update.lock";
  112. } else {
  113. $lock_filename = "update_daemon.lock";
  114. }
  115. if (isset($options["task"])) {
  116. Debug::log("Using task id " . $options["task"]);
  117. $lock_filename = $lock_filename . "-task_" . $options["task"];
  118. }
  119. if (isset($options["pidlock"])) {
  120. $my_pid = $options["pidlock"];
  121. $lock_filename = "update_daemon-$my_pid.lock";
  122. }
  123. Debug::log("Lock: $lock_filename");
  124. $lock_handle = make_lockfile($lock_filename);
  125. $must_exit = false;
  126. if (isset($options["task"]) && isset($options["pidlock"])) {
  127. $waits = $options["task"] * 5;
  128. Debug::log("Waiting before update ($waits)");
  129. sleep($waits);
  130. }
  131. // Try to lock a file in order to avoid concurrent update.
  132. if (!$lock_handle) {
  133. die("error: Can't create lockfile ($lock_filename). ".
  134. "Maybe another update process is already running.\n");
  135. }
  136. if (isset($options["force-update"])) {
  137. Debug::log("marking all feeds as needing update...");
  138. $pdo->query( "UPDATE ttrss_feeds SET
  139. last_update_started = '1970-01-01', last_updated = '1970-01-01'");
  140. }
  141. if (isset($options["feeds"])) {
  142. RSSUtils::update_daemon_common();
  143. RSSUtils::housekeeping_common(true);
  144. PluginHost::getInstance()->run_hooks(PluginHost::HOOK_UPDATE_TASK, "hook_update_task", $op);
  145. }
  146. if (isset($options["feedbrowser"])) {
  147. $count = RSSUtils::update_feedbrowser_cache();
  148. print "Finished, $count feeds processed.\n";
  149. }
  150. if (isset($options["daemon"])) {
  151. while (true) {
  152. $quiet = (isset($options["quiet"])) ? "--quiet" : "";
  153. $log = isset($options['log']) ? '--log '.$options['log'] : '';
  154. $log_level = isset($options['log-level']) ? '--log-level '.$options['log-level'] : '';
  155. passthru(PHP_EXECUTABLE . " " . $argv[0] ." --daemon-loop $quiet $log $log_level");
  156. // let's enforce a minimum spawn interval as to not forkbomb the host
  157. $spawn_interval = max(60, DAEMON_SLEEP_INTERVAL);
  158. Debug::log("Sleeping for $spawn_interval seconds...");
  159. sleep($spawn_interval);
  160. }
  161. }
  162. if (isset($options["daemon-loop"])) {
  163. if (!make_stampfile('update_daemon.stamp')) {
  164. Debug::log("warning: unable to create stampfile\n");
  165. }
  166. RSSUtils::update_daemon_common(isset($options["pidlock"]) ? 50 : DAEMON_FEED_LIMIT);
  167. if (!isset($options["pidlock"]) || $options["task"] == 0)
  168. RSSUtils::housekeeping_common(true);
  169. PluginHost::getInstance()->run_hooks(PluginHost::HOOK_UPDATE_TASK, "hook_update_task", $op);
  170. }
  171. if (isset($options["cleanup-tags"])) {
  172. $rc = cleanup_tags( 14, 50000);
  173. Debug::log("$rc tags deleted.\n");
  174. }
  175. if (isset($options["indexes"])) {
  176. Debug::log("PLEASE BACKUP YOUR DATABASE BEFORE PROCEEDING!");
  177. Debug::log("Type 'yes' to continue.");
  178. if (read_stdin() != 'yes')
  179. exit;
  180. Debug::log("clearing existing indexes...");
  181. if (DB_TYPE == "pgsql") {
  182. $sth = $pdo->query( "SELECT relname FROM
  183. pg_catalog.pg_class WHERE relname LIKE 'ttrss_%'
  184. AND relname NOT LIKE '%_pkey'
  185. AND relkind = 'i'");
  186. } else {
  187. $sth = $pdo->query( "SELECT index_name,table_name FROM
  188. information_schema.statistics WHERE index_name LIKE 'ttrss_%'");
  189. }
  190. while ($line = $sth->fetch()) {
  191. if (DB_TYPE == "pgsql") {
  192. $statement = "DROP INDEX " . $line["relname"];
  193. Debug::log($statement);
  194. } else {
  195. $statement = "ALTER TABLE ".
  196. $line['table_name']." DROP INDEX ".$line['index_name'];
  197. Debug::log($statement);
  198. }
  199. $pdo->query($statement);
  200. }
  201. Debug::log("reading indexes from schema for: " . DB_TYPE);
  202. $fp = fopen("schema/ttrss_schema_" . DB_TYPE . ".sql", "r");
  203. if ($fp) {
  204. while ($line = fgets($fp)) {
  205. $matches = array();
  206. if (preg_match("/^create index ([^ ]+) on ([^ ]+)$/i", $line, $matches)) {
  207. $index = $matches[1];
  208. $table = $matches[2];
  209. $statement = "CREATE INDEX $index ON $table";
  210. Debug::log($statement);
  211. $pdo->query($statement);
  212. }
  213. }
  214. fclose($fp);
  215. } else {
  216. Debug::log("unable to open schema file.");
  217. }
  218. Debug::log("all done.");
  219. }
  220. if (isset($options["convert-filters"])) {
  221. Debug::log("WARNING: this will remove all existing type2 filters.");
  222. Debug::log("Type 'yes' to continue.");
  223. if (read_stdin() != 'yes')
  224. exit;
  225. Debug::log("converting filters...");
  226. $pdo->query("DELETE FROM ttrss_filters2");
  227. $res = $pdo->query("SELECT * FROM ttrss_filters ORDER BY id");
  228. while ($line = $res->fetch()) {
  229. $owner_uid = $line["owner_uid"];
  230. // date filters are removed
  231. if ($line["filter_type"] != 5) {
  232. $filter = array();
  233. if (sql_bool_to_bool($line["cat_filter"])) {
  234. $feed_id = "CAT:" . (int)$line["cat_id"];
  235. } else {
  236. $feed_id = (int)$line["feed_id"];
  237. }
  238. $filter["enabled"] = $line["enabled"] ? "on" : "off";
  239. $filter["rule"] = array(
  240. json_encode(array(
  241. "reg_exp" => $line["reg_exp"],
  242. "feed_id" => $feed_id,
  243. "filter_type" => $line["filter_type"])));
  244. $filter["action"] = array(
  245. json_encode(array(
  246. "action_id" => $line["action_id"],
  247. "action_param_label" => $line["action_param"],
  248. "action_param" => $line["action_param"])));
  249. // Oh god it's full of hacks
  250. $_REQUEST = $filter;
  251. $_SESSION["uid"] = $owner_uid;
  252. $filters = new Pref_Filters($_REQUEST);
  253. $filters->add();
  254. }
  255. }
  256. }
  257. if (isset($options["update-schema"])) {
  258. Debug::log("checking for updates (" . DB_TYPE . ")...");
  259. $updater = new DbUpdater(Db::pdo(), DB_TYPE, SCHEMA_VERSION);
  260. if ($updater->isUpdateRequired()) {
  261. Debug::log("schema update required, version " . $updater->getSchemaVersion() . " to " . SCHEMA_VERSION);
  262. Debug::log("WARNING: please backup your database before continuing.");
  263. Debug::log("Type 'yes' to continue.");
  264. if (read_stdin() != 'yes')
  265. exit;
  266. for ($i = $updater->getSchemaVersion() + 1; $i <= SCHEMA_VERSION; $i++) {
  267. Debug::log("performing update up to version $i...");
  268. $result = $updater->performUpdateTo($i, false);
  269. Debug::log($result ? "OK!" : "FAILED!");
  270. if (!$result) return;
  271. }
  272. } else {
  273. Debug::log("update not required.");
  274. }
  275. }
  276. if (isset($options["gen-search-idx"])) {
  277. echo "Generating search index (stemming set to English)...\n";
  278. $res = $pdo->query("SELECT COUNT(id) AS count FROM ttrss_entries WHERE tsvector_combined IS NULL");
  279. $row = $res->fetch();
  280. $count = $row['count'];
  281. print "Articles to process: $count.\n";
  282. $limit = 500;
  283. $processed = 0;
  284. $sth = $pdo->prepare("SELECT id, title, content FROM ttrss_entries WHERE
  285. tsvector_combined IS NULL ORDER BY id LIMIT ?");
  286. $sth->execute([$limit]);
  287. $usth = $pdo->prepare("UPDATE ttrss_entries
  288. SET tsvector_combined = to_tsvector('english', ?) WHERE id = ?");
  289. while (true) {
  290. while ($line = $sth->fetch()) {
  291. $tsvector_combined = mb_substr(strip_tags($line["title"] . " " . $line["content"]), 0, 1000000);
  292. $usth->execute([$tsvector_combined, $line['id']]);
  293. $processed++;
  294. }
  295. print "Processed $processed articles...\n";
  296. if ($processed < $limit) {
  297. echo "All done.\n";
  298. break;
  299. }
  300. }
  301. }
  302. if (isset($options["list-plugins"])) {
  303. $tmppluginhost = new PluginHost();
  304. $tmppluginhost->load_all($tmppluginhost::KIND_ALL, false);
  305. $enabled = array_map("trim", explode(",", PLUGINS));
  306. echo "List of all available plugins:\n";
  307. foreach ($tmppluginhost->get_plugins() as $name => $plugin) {
  308. $about = $plugin->about();
  309. $status = $about[3] ? "system" : "user";
  310. if (in_array($name, $enabled)) $name .= "*";
  311. printf("%-50s %-10s v%.2f (by %s)\n%s\n\n",
  312. $name, $status, $about[0], $about[2], $about[1]);
  313. }
  314. echo "Plugins marked by * are currently enabled for all users.\n";
  315. }
  316. if (isset($options["debug-feed"])) {
  317. $feed = $options["debug-feed"];
  318. if (isset($options["force-refetch"])) $_REQUEST["force_refetch"] = true;
  319. if (isset($options["force-rehash"])) $_REQUEST["force_rehash"] = true;
  320. Debug::set_loglevel(Debug::$LOG_EXTENDED);
  321. $rc = RSSUtils::update_rss_feed($feed) != false ? 0 : 1;
  322. exit($rc);
  323. }
  324. PluginHost::getInstance()->run_commands($options);
  325. if (file_exists(LOCK_DIRECTORY . "/$lock_filename"))
  326. if (strtoupper(substr(PHP_OS, 0, 3)) == 'WIN')
  327. fclose($lock_handle);
  328. unlink(LOCK_DIRECTORY . "/$lock_filename");
  329. ?>