update.php 13 KB

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