]> git.wh0rd.org Git - tt-rss.git/blob - update.php
another take on inclusion of errorhandler in CLI scripts
[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 "functions.php";
11         require_once "rssfuncs.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         // Create a database connection.
21         $link = db_connect(DB_HOST, DB_USER, DB_PASS, DB_NAME);
22
23         init_connection($link);
24
25         $longopts = array("feeds",
26                         "feedbrowser",
27                         "daemon",
28                         "daemon-loop",
29                         "task:",
30                         "cleanup-tags",
31                         "quiet",
32                         "log:",
33                         "indexes",
34                         "update-schema",
35                         "convert-filters",
36                         "force-update",
37                         "list-plugins",
38                         "help");
39
40         foreach ($pluginhost->get_commands() as $command => $data) {
41                 array_push($longopts, $command . $data["suffix"]);
42         }
43
44         $options = getopt("", $longopts);
45
46         if (count($options) == 0 && !defined('STDIN')) {
47                 ?> <html>
48                 <head>
49                 <title>Tiny Tiny RSS data update script.</title>
50                 <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
51                 <link rel="stylesheet" type="text/css" href="utility.css">
52                 </head>
53
54                 <body>
55                 <div class="floatingLogo"><img src="images/logo_small.png"></div>
56                 <h1><?php echo __("Tiny Tiny RSS data update script.") ?></h1>
57
58                 <?php print_error("Please run this script from the command line. Use option \"-help\" to display command help if this error is displayed erroneously."); ?>
59
60                 </body></html>
61         <?php
62                 exit;
63         }
64
65         if (count($options) == 0 || isset($options["help"]) ) {
66                 print "Tiny Tiny RSS data update script.\n\n";
67                 print "Options:\n";
68                 print "  --feeds              - update feeds\n";
69                 print "  --feedbrowser        - update feedbrowser\n";
70                 print "  --daemon             - start single-process update daemon\n";
71                 print "  --task N             - create lockfile using this task id\n";
72                 print "  --cleanup-tags       - perform tags table maintenance\n";
73                 print "  --quiet              - don't output messages to stdout\n";
74                 print "  --log FILE           - log messages to FILE\n";
75                 print "  --indexes            - recreate missing schema indexes\n";
76                 print "  --update-schema      - update database schema\n";
77                 print "  --convert-filters    - convert type1 filters to type2\n";
78                 print "  --force-update       - force update of all feeds\n";
79                 print "  --list-plugins       - list all available plugins\n";
80                 print "  --help               - show this help\n";
81                 print "Plugin options:\n";
82
83                 foreach ($pluginhost->get_commands() as $command => $data) {
84                         $args = $data['arghelp'];
85                         printf(" --%-19s - %s\n", "$command $args", $data["description"]);
86                 }
87
88                 return;
89         }
90
91         if (!isset($options['daemon'])) {
92                 require_once "errorhandler.php";
93         }
94
95         if (!isset($options['update-schema'])) {
96                 $schema_version = get_schema_version($link);
97
98                 if ($schema_version != SCHEMA_VERSION) {
99                         die("Schema version is wrong, please upgrade the database.\n");
100                 }
101         }
102
103         define('QUIET', isset($options['quiet']));
104
105         if (isset($options["log"])) {
106                 _debug("Logging to " . $options["log"]);
107                 define('LOGFILE', $options["log"]);
108         }
109
110         if (!isset($options["daemon"])) {
111                 $lock_filename = "update.lock";
112         } else {
113                 $lock_filename = "update_daemon.lock";
114         }
115
116         if (isset($options["task"])) {
117                 _debug("Using task id " . $options["task"]);
118                 $lock_filename = $lock_filename . "-task_" . $options["task"];
119         }
120
121         $lock_handle = make_lockfile($lock_filename);
122         $must_exit = false;
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
130         if (isset($options["force-update"])) {
131                 _debug("marking all feeds as needing update...");
132
133                 db_query($link, "UPDATE ttrss_feeds SET last_update_started = '1970-01-01',
134                                 last_updated = '1970-01-01'");
135         }
136
137         if (isset($options["feeds"])) {
138                 // Update all feeds needing a update.
139                 update_daemon_common($link);
140
141                 // Update feedbrowser
142                 $count = update_feedbrowser_cache($link);
143                 _debug("Feedbrowser updated, $count feeds processed.");
144
145                 // Purge orphans and cleanup tags
146                 purge_orphans($link, true);
147
148                 $rc = cleanup_tags($link, 14, 50000);
149                 _debug("Cleaned $rc cached tags.");
150
151                 global $pluginhost;
152                 $pluginhost->run_hooks($pluginhost::HOOK_UPDATE_TASK, "hook_update_task", $op);
153         }
154
155         if (isset($options["feedbrowser"])) {
156                 $count = update_feedbrowser_cache($link);
157                 print "Finished, $count feeds processed.\n";
158         }
159
160         if (isset($options["daemon"])) {
161                 while (true) {
162                         $quiet = (isset($options["quiet"])) ? "--quiet" : "";
163
164                         passthru(PHP_EXECUTABLE . " " . $argv[0] ." --daemon-loop $quiet");
165                         _debug("Sleeping for " . DAEMON_SLEEP_INTERVAL . " seconds...");
166                         sleep(DAEMON_SLEEP_INTERVAL);
167                 }
168         }
169
170         if (isset($options["daemon-loop"])) {
171                 if (!make_stampfile('update_daemon.stamp')) {
172                         _debug("warning: unable to create stampfile\n");
173                 }
174
175                 // Call to the feed batch update function
176                 // or regenerate feedbrowser cache
177
178                 if (rand(0,100) > 30) {
179                         update_daemon_common($link);
180                 } else {
181                         $count = update_feedbrowser_cache($link);
182                         _debug("Feedbrowser updated, $count feeds processed.");
183
184                         purge_orphans($link, true);
185
186                         $rc = cleanup_tags($link, 14, 50000);
187
188                         _debug("Cleaned $rc cached tags.");
189
190                         global $pluginhost;
191                         $pluginhost->run_hooks($pluginhost::HOOK_UPDATE_TASK, "hook_update_task", $op);
192                 }
193
194         }
195
196         if (isset($options["cleanup-tags"])) {
197                 $rc = cleanup_tags($link, 14, 50000);
198                 _debug("$rc tags deleted.\n");
199         }
200
201         if (isset($options["indexes"])) {
202                 _debug("PLEASE BACKUP YOUR DATABASE BEFORE PROCEEDING!");
203                 _debug("Type 'yes' to continue.");
204
205                 if (read_stdin() != 'yes')
206                         exit;
207
208                 _debug("clearing existing indexes...");
209
210                 if (DB_TYPE == "pgsql") {
211                         $result = db_query($link, "SELECT relname FROM
212                                 pg_catalog.pg_class WHERE relname LIKE 'ttrss_%'
213                                         AND relname NOT LIKE '%_pkey'
214                                 AND relkind = 'i'");
215                 } else {
216                         $result = db_query($link, "SELECT index_name,table_name FROM
217                                 information_schema.statistics WHERE index_name LIKE 'ttrss_%'");
218                 }
219
220                 while ($line = db_fetch_assoc($result)) {
221                         if (DB_TYPE == "pgsql") {
222                                 $statement = "DROP INDEX " . $line["relname"];
223                                 _debug($statement);
224                         } else {
225                                 $statement = "ALTER TABLE ".
226                                         $line['table_name']." DROP INDEX ".$line['index_name'];
227                                 _debug($statement);
228                         }
229                         db_query($link, $statement, false);
230                 }
231
232                 _debug("reading indexes from schema for: " . DB_TYPE);
233
234                 $fp = fopen("schema/ttrss_schema_" . DB_TYPE . ".sql", "r");
235                 if ($fp) {
236                         while ($line = fgets($fp)) {
237                                 $matches = array();
238
239                                 if (preg_match("/^create index ([^ ]+) on ([^ ]+)$/i", $line, $matches)) {
240                                         $index = $matches[1];
241                                         $table = $matches[2];
242
243                                         $statement = "CREATE INDEX $index ON $table";
244
245                                         _debug($statement);
246                                         db_query($link, $statement);
247                                 }
248                         }
249                         fclose($fp);
250                 } else {
251                         _debug("unable to open schema file.");
252                 }
253                 _debug("all done.");
254         }
255
256         if (isset($options["convert-filters"])) {
257                 _debug("WARNING: this will remove all existing type2 filters.");
258                 _debug("Type 'yes' to continue.");
259
260                 if (read_stdin() != 'yes')
261                         exit;
262
263                 _debug("converting filters...");
264
265                 db_query($link, "DELETE FROM ttrss_filters2");
266
267                 $result = db_query($link, "SELECT * FROM ttrss_filters ORDER BY id");
268
269                 while ($line = db_fetch_assoc($result)) {
270                         $owner_uid = $line["owner_uid"];
271
272                         // date filters are removed
273                         if ($line["filter_type"] != 5) {
274                                 $filter = array();
275
276                                 if (sql_bool_to_bool($line["cat_filter"])) {
277                                         $feed_id = "CAT:" . (int)$line["cat_id"];
278                                 } else {
279                                         $feed_id = (int)$line["feed_id"];
280                                 }
281
282                                 $filter["enabled"] = $line["enabled"] ? "on" : "off";
283                                 $filter["rule"] = array(
284                                         json_encode(array(
285                                                 "reg_exp" => $line["reg_exp"],
286                                                 "feed_id" => $feed_id,
287                                                 "filter_type" => $line["filter_type"])));
288
289                                 $filter["action"] = array(
290                                         json_encode(array(
291                                                 "action_id" => $line["action_id"],
292                                                 "action_param_label" => $line["action_param"],
293                                                 "action_param" => $line["action_param"])));
294
295                                 // Oh god it's full of hacks
296
297                                 $_REQUEST = $filter;
298                                 $_SESSION["uid"] = $owner_uid;
299
300                                 $filters = new Pref_Filters($link, $_REQUEST);
301                                 $filters->add();
302                         }
303                 }
304
305         }
306
307         if (isset($options["update-schema"])) {
308                 _debug("checking for updates (" . DB_TYPE . ")...");
309
310                 $updater = new DbUpdater($link, DB_TYPE, SCHEMA_VERSION);
311
312                 if ($updater->isUpdateRequired()) {
313                         _debug("schema update required, version " . $updater->getSchemaVersion() . " to " . SCHEMA_VERSION);
314                         _debug("WARNING: please backup your database before continuing.");
315                         _debug("Type 'yes' to continue.");
316
317                         if (read_stdin() != 'yes')
318                                 exit;
319
320                         for ($i = $updater->getSchemaVersion() + 1; $i <= SCHEMA_VERSION; $i++) {
321                                 _debug("performing update up to version $i...");
322
323                                 $result = $updater->performUpdateTo($i);
324
325                                 _debug($result ? "OK!" : "FAILED!");
326
327                                 if (!$result) return;
328
329                         }
330                 } else {
331                         _debug("update not required.");
332                 }
333
334         }
335
336         if (isset($options["list-plugins"])) {
337                 $tmppluginhost = new PluginHost($link);
338                 $tmppluginhost->load_all($tmppluginhost::KIND_ALL);
339                 $enabled = array_map("trim", explode(",", PLUGINS));
340
341                 echo "List of all available plugins:\n";
342
343                 foreach ($tmppluginhost->get_plugins() as $name => $plugin) {
344                         $about = $plugin->about();
345
346                         $status = $about[3] ? "system" : "user";
347
348                         if (in_array($name, $enabled)) $name .= "*";
349
350                         printf("%-50s %-10s v%.2f (by %s)\n%s\n\n",
351                                 $name, $status, $about[0], $about[2], $about[1]);
352                 }
353
354                 echo "Plugins marked by * are currently enabled for all users.\n";
355
356         }
357
358         $pluginhost->run_commands($options);
359
360         db_close($link);
361
362         if ($lock_handle != false) {
363                 fclose($lock_handle);
364         }
365
366         if (file_exists(LOCK_DIRECTORY . "/$lock_filename"))
367                 unlink(LOCK_DIRECTORY . "/$lock_filename");
368 ?>