]> git.wh0rd.org Git - tt-rss.git/blob - update.php
Make sure we are running on Windows before fclose() to avoid race condition possible...
[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 "rssfuncs.php";
13         require_once "config.php";
14         require_once "sanity_check.php";
15         require_once "db.php";
16         require_once "db-prefs.php";
17
18         if (!defined('PHP_EXECUTABLE'))
19                 define('PHP_EXECUTABLE', '/usr/bin/php');
20
21         init_plugins();
22
23         $longopts = array("feeds",
24                         "feedbrowser",
25                         "daemon",
26                         "daemon-loop",
27                         "task:",
28                         "cleanup-tags",
29                         "quiet",
30                         "log:",
31                         "indexes",
32                         "pidlock:",
33                         "update-schema",
34                         "convert-filters",
35                         "force-update",
36                         "gen-search-idx",
37                         "list-plugins",
38                         "debug-feed:",
39                         "force-refetch",
40                         "force-rehash",
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 "  --help               - show this help\n";
95                 print "Plugin options:\n";
96
97                 foreach (PluginHost::getInstance()->get_commands() as $command => $data) {
98                         $args = $data['arghelp'];
99                         printf(" --%-19s - %s\n", "$command $args", $data["description"]);
100                 }
101
102                 return;
103         }
104
105         if (!isset($options['daemon'])) {
106                 require_once "errorhandler.php";
107         }
108
109         if (!isset($options['update-schema'])) {
110                 $schema_version = get_schema_version();
111
112                 if ($schema_version != SCHEMA_VERSION) {
113                         die("Schema version is wrong, please upgrade the database.\n");
114                 }
115         }
116
117         define('QUIET', isset($options['quiet']));
118
119         if (isset($options["log"])) {
120                 _debug("Logging to " . $options["log"]);
121                 define('LOGFILE', $options["log"]);
122         }
123
124         if (!isset($options["daemon"])) {
125                 $lock_filename = "update.lock";
126         } else {
127                 $lock_filename = "update_daemon.lock";
128         }
129
130         if (isset($options["task"])) {
131                 _debug("Using task id " . $options["task"]);
132                 $lock_filename = $lock_filename . "-task_" . $options["task"];
133         }
134
135         if (isset($options["pidlock"])) {
136                 $my_pid = $options["pidlock"];
137                 $lock_filename = "update_daemon-$my_pid.lock";
138
139         }
140
141         _debug("Lock: $lock_filename");
142
143         $lock_handle = make_lockfile($lock_filename);
144         $must_exit = false;
145
146         if (isset($options["task"]) && isset($options["pidlock"])) {
147                 $waits = $options["task"] * 5;
148                 _debug("Waiting before update ($waits)");
149                 sleep($waits);
150         }
151
152         // Try to lock a file in order to avoid concurrent update.
153         if (!$lock_handle) {
154                 die("error: Can't create lockfile ($lock_filename). ".
155                         "Maybe another update process is already running.\n");
156         }
157
158         if (isset($options["force-update"])) {
159                 _debug("marking all feeds as needing update...");
160
161                 db_query( "UPDATE ttrss_feeds SET last_update_started = '1970-01-01',
162                                 last_updated = '1970-01-01'");
163         }
164
165         if (isset($options["feeds"])) {
166                 update_daemon_common();
167                 housekeeping_common(true);
168
169                 PluginHost::getInstance()->run_hooks(PluginHost::HOOK_UPDATE_TASK, "hook_update_task", $op);
170         }
171
172         if (isset($options["feedbrowser"])) {
173                 $count = update_feedbrowser_cache();
174                 print "Finished, $count feeds processed.\n";
175         }
176
177         if (isset($options["daemon"])) {
178                 while (true) {
179                         $quiet = (isset($options["quiet"])) ? "--quiet" : "";
180          $log = isset($options['log']) ? '--log '.$options['log'] : '';
181
182                         passthru(PHP_EXECUTABLE . " " . $argv[0] ." --daemon-loop $quiet $log");
183                         _debug("Sleeping for " . DAEMON_SLEEP_INTERVAL . " seconds...");
184                         sleep(DAEMON_SLEEP_INTERVAL);
185                 }
186         }
187
188         if (isset($options["daemon-loop"])) {
189                 if (!make_stampfile('update_daemon.stamp')) {
190                         _debug("warning: unable to create stampfile\n");
191                 }
192
193                 update_daemon_common(isset($options["pidlock"]) ? 50 : DAEMON_FEED_LIMIT);
194
195                 if (!isset($options["pidlock"]) || $options["task"] == 0)
196                         housekeeping_common(true);
197
198                 PluginHost::getInstance()->run_hooks(PluginHost::HOOK_UPDATE_TASK, "hook_update_task", $op);
199         }
200
201         if (isset($options["cleanup-tags"])) {
202                 $rc = cleanup_tags( 14, 50000);
203                 _debug("$rc tags deleted.\n");
204         }
205
206         if (isset($options["indexes"])) {
207                 _debug("PLEASE BACKUP YOUR DATABASE BEFORE PROCEEDING!");
208                 _debug("Type 'yes' to continue.");
209
210                 if (read_stdin() != 'yes')
211                         exit;
212
213                 _debug("clearing existing indexes...");
214
215                 if (DB_TYPE == "pgsql") {
216                         $result = db_query( "SELECT relname FROM
217                                 pg_catalog.pg_class WHERE relname LIKE 'ttrss_%'
218                                         AND relname NOT LIKE '%_pkey'
219                                 AND relkind = 'i'");
220                 } else {
221                         $result = db_query( "SELECT index_name,table_name FROM
222                                 information_schema.statistics WHERE index_name LIKE 'ttrss_%'");
223                 }
224
225                 while ($line = db_fetch_assoc($result)) {
226                         if (DB_TYPE == "pgsql") {
227                                 $statement = "DROP INDEX " . $line["relname"];
228                                 _debug($statement);
229                         } else {
230                                 $statement = "ALTER TABLE ".
231                                         $line['table_name']." DROP INDEX ".$line['index_name'];
232                                 _debug($statement);
233                         }
234                         db_query( $statement, false);
235                 }
236
237                 _debug("reading indexes from schema for: " . DB_TYPE);
238
239                 $fp = fopen("schema/ttrss_schema_" . DB_TYPE . ".sql", "r");
240                 if ($fp) {
241                         while ($line = fgets($fp)) {
242                                 $matches = array();
243
244                                 if (preg_match("/^create index ([^ ]+) on ([^ ]+)$/i", $line, $matches)) {
245                                         $index = $matches[1];
246                                         $table = $matches[2];
247
248                                         $statement = "CREATE INDEX $index ON $table";
249
250                                         _debug($statement);
251                                         db_query( $statement);
252                                 }
253                         }
254                         fclose($fp);
255                 } else {
256                         _debug("unable to open schema file.");
257                 }
258                 _debug("all done.");
259         }
260
261         if (isset($options["convert-filters"])) {
262                 _debug("WARNING: this will remove all existing type2 filters.");
263                 _debug("Type 'yes' to continue.");
264
265                 if (read_stdin() != 'yes')
266                         exit;
267
268                 _debug("converting filters...");
269
270                 db_query( "DELETE FROM ttrss_filters2");
271
272                 $result = db_query( "SELECT * FROM ttrss_filters ORDER BY id");
273
274                 while ($line = db_fetch_assoc($result)) {
275                         $owner_uid = $line["owner_uid"];
276
277                         // date filters are removed
278                         if ($line["filter_type"] != 5) {
279                                 $filter = array();
280
281                                 if (sql_bool_to_bool($line["cat_filter"])) {
282                                         $feed_id = "CAT:" . (int)$line["cat_id"];
283                                 } else {
284                                         $feed_id = (int)$line["feed_id"];
285                                 }
286
287                                 $filter["enabled"] = $line["enabled"] ? "on" : "off";
288                                 $filter["rule"] = array(
289                                         json_encode(array(
290                                                 "reg_exp" => $line["reg_exp"],
291                                                 "feed_id" => $feed_id,
292                                                 "filter_type" => $line["filter_type"])));
293
294                                 $filter["action"] = array(
295                                         json_encode(array(
296                                                 "action_id" => $line["action_id"],
297                                                 "action_param_label" => $line["action_param"],
298                                                 "action_param" => $line["action_param"])));
299
300                                 // Oh god it's full of hacks
301
302                                 $_REQUEST = $filter;
303                                 $_SESSION["uid"] = $owner_uid;
304
305                                 $filters = new Pref_Filters($_REQUEST);
306                                 $filters->add();
307                         }
308                 }
309
310         }
311
312         if (isset($options["update-schema"])) {
313                 _debug("checking for updates (" . DB_TYPE . ")...");
314
315                 $updater = new DbUpdater(Db::get(), DB_TYPE, SCHEMA_VERSION);
316
317                 if ($updater->isUpdateRequired()) {
318                         _debug("schema update required, version " . $updater->getSchemaVersion() . " to " . SCHEMA_VERSION);
319                         _debug("WARNING: please backup your database before continuing.");
320                         _debug("Type 'yes' to continue.");
321
322                         if (read_stdin() != 'yes')
323                                 exit;
324
325                         for ($i = $updater->getSchemaVersion() + 1; $i <= SCHEMA_VERSION; $i++) {
326                                 _debug("performing update up to version $i...");
327
328                                 $result = $updater->performUpdateTo($i, false);
329
330                                 _debug($result ? "OK!" : "FAILED!");
331
332                                 if (!$result) return;
333
334                         }
335                 } else {
336                         _debug("update not required.");
337                 }
338
339         }
340
341         if (isset($options["gen-search-idx"])) {
342                 echo "Generating search index (stemming set to English)...\n";
343
344                 $result = db_query("SELECT COUNT(id) AS count FROM ttrss_entries WHERE tsvector_combined IS NULL");
345                 $count = db_fetch_result($result, 0, "count");
346
347                 print "Articles to process: $count.\n";
348
349                 $limit = 500;
350                 $processed = 0;
351
352                 while (true) {
353                         $result = db_query("SELECT id, title, content FROM ttrss_entries WHERE tsvector_combined IS NULL ORDER BY id LIMIT $limit");
354
355                         while ($line = db_fetch_assoc($result)) {
356                            $tsvector_combined = db_escape_string(mb_substr($line['title'] . ' ' . strip_tags(str_replace('<', ' <', $line['content'])),
357                                         0, 1000000));
358
359                                 db_query("UPDATE ttrss_entries SET tsvector_combined = to_tsvector('english', '$tsvector_combined') WHERE id = " . $line["id"]);
360                         }
361
362                         $processed += db_num_rows($result);
363                         print "Processed $processed articles...\n";
364
365                         if (db_num_rows($result) != $limit) {
366                                 echo "All done.\n";
367                                 break;
368                         }
369                 }
370         }
371
372         if (isset($options["list-plugins"])) {
373                 $tmppluginhost = new PluginHost();
374                 $tmppluginhost->load_all($tmppluginhost::KIND_ALL, false);
375                 $enabled = array_map("trim", explode(",", PLUGINS));
376
377                 echo "List of all available plugins:\n";
378
379                 foreach ($tmppluginhost->get_plugins() as $name => $plugin) {
380                         $about = $plugin->about();
381
382                         $status = $about[3] ? "system" : "user";
383
384                         if (in_array($name, $enabled)) $name .= "*";
385
386                         printf("%-50s %-10s v%.2f (by %s)\n%s\n\n",
387                                 $name, $status, $about[0], $about[2], $about[1]);
388                 }
389
390                 echo "Plugins marked by * are currently enabled for all users.\n";
391
392         }
393
394         if (isset($options["debug-feed"])) {
395                 $feed = $options["debug-feed"];
396
397                 if (isset($options["force-refetch"])) $_REQUEST["force_refetch"] = true;
398                 if (isset($options["force-rehash"])) $_REQUEST["force_rehash"] = true;
399
400                 $_REQUEST['xdebug'] = 1;
401
402                 update_rss_feed($feed);
403         }
404
405         PluginHost::getInstance()->run_commands($options);
406
407         if (file_exists(LOCK_DIRECTORY . "/$lock_filename"))
408                 if (strtoupper(substr(PHP_OS, 0, 3)) == 'WIN')
409                         fclose($lock_handle);
410                 unlink(LOCK_DIRECTORY . "/$lock_filename");
411 ?>