update.php 11 KB

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