update.php 12 KB

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