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