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