update.php 13.3 KB
Newer Older
1
#!/usr/bin/env php
2
<?php
3 4
	set_include_path(dirname(__FILE__) ."/include" . PATH_SEPARATOR .
		get_include_path());
Andrew Dolgov's avatar
Andrew Dolgov committed
5

6 7
	define('DISABLE_SESSIONS', true);

8 9
	chdir(dirname(__FILE__));

10
	require_once "autoload.php";
11
	require_once "functions.php";
Andrew Dolgov's avatar
Andrew Dolgov committed
12
	require_once "config.php";
Pavel Sterin's avatar
Pavel Sterin committed
13
	require_once "sanity_check.php";
Andrew Dolgov's avatar
Andrew Dolgov committed
14
	require_once "db.php";
15 16
	require_once "db-prefs.php";

17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61
	function cleanup_tags($days = 14, $limit = 1000) {

		$days = (int) $days;

		if (DB_TYPE == "pgsql") {
			$interval_query = "date_updated < NOW() - INTERVAL '$days days'";
		} else if (DB_TYPE == "mysql") {
			$interval_query = "date_updated < DATE_SUB(NOW(), INTERVAL $days DAY)";
		}

		$tags_deleted = 0;

		$pdo = Db::pdo();

		while ($limit > 0) {
			$limit_part = 500;

			$sth = $pdo->prepare("SELECT ttrss_tags.id AS id
						FROM ttrss_tags, ttrss_user_entries, ttrss_entries
						WHERE post_int_id = int_id AND $interval_query AND
						ref_id = ttrss_entries.id AND tag_cache != '' LIMIT ?");
			$sth->bindValue(1, $limit_part, PDO::PARAM_INT);
			$sth->execute();

			$ids = array();

			while ($line = $sth->fetch()) {
				array_push($ids, $line['id']);
			}

			if (count($ids) > 0) {
				$ids = join(",", $ids);

				$usth = $pdo->query("DELETE FROM ttrss_tags WHERE id IN ($ids)");
				$tags_deleted = $usth->rowCount();
			} else {
				break;
			}

			$limit -= $limit_part;
		}

		return $tags_deleted;
	}

62 63 64
	if (!defined('PHP_EXECUTABLE'))
		define('PHP_EXECUTABLE', '/usr/bin/php');

Andrew Dolgov's avatar
Andrew Dolgov committed
65 66
	$pdo = Db::pdo();

Andrew Dolgov's avatar
Andrew Dolgov committed
67
	init_plugins();
68

69 70 71
	$longopts = array("feeds",
			"daemon",
			"daemon-loop",
72
			"send-digests",
73 74 75
			"task:",
			"cleanup-tags",
			"quiet",
76
			"log:",
Andrew Dolgov's avatar
Andrew Dolgov committed
77
			"log-level:",
78
			"indexes",
79
			"pidlock:",
80
			"update-schema",
81 82
			"convert-filters",
			"force-update",
83
			"gen-search-idx",
84
			"list-plugins",
85 86 87
			"debug-feed:",
			"force-refetch",
			"force-rehash",
88 89
			"help");

Andrew Dolgov's avatar
Andrew Dolgov committed
90
	foreach (PluginHost::getInstance()->get_commands() as $command => $data) {
91
		array_push($longopts, $command . $data["suffix"]);
92 93 94
	}

	$options = getopt("", $longopts);
95

96 97 98 99 100 101 102
	if (!is_array($options)) {
		die("error: getopt() failed. ".
			"Most probably you are using PHP CGI to run this script ".
			"instead of required PHP CLI. Check tt-rss wiki page on updating feeds for ".
			"additional information.\n");
	}

103
	if (count($options) == 0 && !defined('STDIN')) {
104 105 106
		?>
		<!DOCTYPE html>
		<html>
107
		<head>
108
		<title>Tiny Tiny RSS data update script.</title>
109 110 111 112
		<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
		</head>

		<body>
113
		<h1><?php echo __("Tiny Tiny RSS data update script.") ?></h1>
114

115
		<?php print_error("Please run this script from the command line. Use option \"--help\" to display command help if this error is displayed erroneously."); ?>
116 117 118 119 120 121

		</body></html>
	<?php
		exit;
	}

122
	if (count($options) == 0 || isset($options["help"]) ) {
123 124
		print "Tiny Tiny RSS data update script.\n\n";
		print "Options:\n";
125 126 127 128
		print "  --feeds              - update feeds\n";
		print "  --daemon             - start single-process update daemon\n";
		print "  --task N             - create lockfile using this task id\n";
		print "  --cleanup-tags       - perform tags table maintenance\n";
129
		print "  --quiet              - don't output messages to stdout\n";
130
		print "  --log FILE           - log messages to FILE\n";
Andrew Dolgov's avatar
Andrew Dolgov committed
131
		print "  --log-level N        - log verbosity level\n";
132
		print "  --indexes            - recreate missing schema indexes\n";
133
		print "  --update-schema      - update database schema\n";
134
		print "  --gen-search-idx     - generate basic PostgreSQL fulltext search index\n";
135
		print "  --convert-filters    - convert type1 filters to type2\n";
136
		print "  --send-digests       - send pending email digests\n";
137 138
		print "  --force-update       - force update of all feeds\n";
		print "  --list-plugins       - list all available plugins\n";
139 140 141
		print "  --debug-feed N       - perform debug update of feed N\n";
		print "  --force-refetch      - debug update: force refetch feed data\n";
		print "  --force-rehash       - debug update: force rehash articles\n";
142
		print "  --help               - show this help\n";
143 144
		print "Plugin options:\n";

Andrew Dolgov's avatar
Andrew Dolgov committed
145
		foreach (PluginHost::getInstance()->get_commands() as $command => $data) {
146 147
			$args = $data['arghelp'];
			printf(" --%-19s - %s\n", "$command $args", $data["description"]);
148 149
		}

150
		return;
Andrew Dolgov's avatar
Andrew Dolgov committed
151
	}
152

153 154 155 156
	if (!isset($options['daemon'])) {
		require_once "errorhandler.php";
	}

157
	if (!isset($options['update-schema'])) {
Andrew Dolgov's avatar
Andrew Dolgov committed
158
		$schema_version = get_schema_version();
159 160

		if ($schema_version != SCHEMA_VERSION) {
161
			die("Schema version is wrong, please upgrade the database (--update-schema).\n");
162 163 164
		}
	}

Andrew Dolgov's avatar
Andrew Dolgov committed
165 166 167 168 169
	Debug::set_enabled(true);

	if (isset($options["log-level"])) {
	    Debug::set_loglevel((int)$options["log-level"]);
    }
170

171
	if (isset($options["log"])) {
172
		Debug::set_quiet(isset($options['quiet']));
Andrew Dolgov's avatar
Andrew Dolgov committed
173 174
		Debug::set_logfile($options["log"]);
        Debug::log("Logging to " . $options["log"]);
175 176 177 178
    } else {
	    if (isset($options['quiet'])) {
			Debug::set_loglevel(Debug::$LOG_DISABLED);
        }
Andrew Dolgov's avatar
Andrew Dolgov committed
179
    }
180

181
	if (!isset($options["daemon"])) {
182 183 184 185
		$lock_filename = "update.lock";
	} else {
		$lock_filename = "update_daemon.lock";
	}
186

187
	if (isset($options["task"])) {
Andrew Dolgov's avatar
Andrew Dolgov committed
188
		Debug::log("Using task id " . $options["task"]);
189 190 191
		$lock_filename = $lock_filename . "-task_" . $options["task"];
	}

192 193 194 195 196 197
	if (isset($options["pidlock"])) {
		$my_pid = $options["pidlock"];
		$lock_filename = "update_daemon-$my_pid.lock";

	}

Andrew Dolgov's avatar
Andrew Dolgov committed
198
	Debug::log("Lock: $lock_filename");
199

200 201
	$lock_handle = make_lockfile($lock_filename);
	$must_exit = false;
202

203
	if (isset($options["task"]) && isset($options["pidlock"])) {
204
		$waits = $options["task"] * 5;
Andrew Dolgov's avatar
Andrew Dolgov committed
205
		Debug::log("Waiting before update ($waits)");
206 207 208
		sleep($waits);
	}

209 210 211 212 213
	// Try to lock a file in order to avoid concurrent update.
	if (!$lock_handle) {
		die("error: Can't create lockfile ($lock_filename). ".
			"Maybe another update process is already running.\n");
	}
214

215
	if (isset($options["force-update"])) {
Andrew Dolgov's avatar
Andrew Dolgov committed
216
		Debug::log("marking all feeds as needing update...");
217

218
		$pdo->query( "UPDATE ttrss_feeds SET
Andrew Dolgov's avatar
Andrew Dolgov committed
219
          last_update_started = '1970-01-01', last_updated = '1970-01-01'");
220 221 222
	}

	if (isset($options["feeds"])) {
223 224
		RSSUtils::update_daemon_common();
		RSSUtils::housekeeping_common(true);
225

Andrew Dolgov's avatar
Andrew Dolgov committed
226
		PluginHost::getInstance()->run_hooks(PluginHost::HOOK_UPDATE_TASK, "hook_update_task", $op);
227
	}
228

229
	if (isset($options["daemon"])) {
230
		while (true) {
231
			$quiet = (isset($options["quiet"])) ? "--quiet" : "";
Andrew Dolgov's avatar
Andrew Dolgov committed
232 233
            $log = isset($options['log']) ? '--log '.$options['log'] : '';
            $log_level = isset($options['log-level']) ? '--log-level '.$options['log-level'] : '';
234

Andrew Dolgov's avatar
Andrew Dolgov committed
235
			passthru(PHP_EXECUTABLE . " " . $argv[0] ." --daemon-loop $quiet $log $log_level");
236 237 238 239

			// let's enforce a minimum spawn interval as to not forkbomb the host
			$spawn_interval = max(60, DAEMON_SLEEP_INTERVAL);

Andrew Dolgov's avatar
Andrew Dolgov committed
240
			Debug::log("Sleeping for $spawn_interval seconds...");
241
			sleep($spawn_interval);
242
		}
Andrew Dolgov's avatar
Andrew Dolgov committed
243
	}
244

245
	if (isset($options["daemon-loop"])) {
246
		if (!make_stampfile('update_daemon.stamp')) {
Andrew Dolgov's avatar
Andrew Dolgov committed
247
			Debug::log("warning: unable to create stampfile\n");
248
		}
249

250
		RSSUtils::update_daemon_common(isset($options["pidlock"]) ? 50 : DAEMON_FEED_LIMIT);
251 252

		if (!isset($options["pidlock"]) || $options["task"] == 0)
253
			RSSUtils::housekeeping_common(true);
254

Andrew Dolgov's avatar
Andrew Dolgov committed
255
		PluginHost::getInstance()->run_hooks(PluginHost::HOOK_UPDATE_TASK, "hook_update_task", $op);
256 257
	}

258
	if (isset($options["cleanup-tags"])) {
Andrew Dolgov's avatar
Andrew Dolgov committed
259
		$rc = cleanup_tags( 14, 50000);
Andrew Dolgov's avatar
Andrew Dolgov committed
260
		Debug::log("$rc tags deleted.\n");
261 262
	}

263
	if (isset($options["indexes"])) {
Andrew Dolgov's avatar
Andrew Dolgov committed
264 265
		Debug::log("PLEASE BACKUP YOUR DATABASE BEFORE PROCEEDING!");
		Debug::log("Type 'yes' to continue.");
266 267 268 269

		if (read_stdin() != 'yes')
			exit;

Andrew Dolgov's avatar
Andrew Dolgov committed
270
		Debug::log("clearing existing indexes...");
271 272

		if (DB_TYPE == "pgsql") {
Andrew Dolgov's avatar
Andrew Dolgov committed
273
			$sth = $pdo->query( "SELECT relname FROM
274 275 276 277
				pg_catalog.pg_class WHERE relname LIKE 'ttrss_%'
					AND relname NOT LIKE '%_pkey'
				AND relkind = 'i'");
		} else {
Andrew Dolgov's avatar
Andrew Dolgov committed
278
			$sth = $pdo->query( "SELECT index_name,table_name FROM
279 280 281
				information_schema.statistics WHERE index_name LIKE 'ttrss_%'");
		}

Andrew Dolgov's avatar
Andrew Dolgov committed
282
		while ($line = $sth->fetch()) {
283 284
			if (DB_TYPE == "pgsql") {
				$statement = "DROP INDEX " . $line["relname"];
Andrew Dolgov's avatar
Andrew Dolgov committed
285
				Debug::log($statement);
286 287 288
			} else {
				$statement = "ALTER TABLE ".
					$line['table_name']." DROP INDEX ".$line['index_name'];
Andrew Dolgov's avatar
Andrew Dolgov committed
289
				Debug::log($statement);
290
			}
Andrew Dolgov's avatar
Andrew Dolgov committed
291
			$pdo->query($statement);
292 293
		}

Andrew Dolgov's avatar
Andrew Dolgov committed
294
		Debug::log("reading indexes from schema for: " . DB_TYPE);
295 296 297 298 299 300 301 302 303 304 305 306

		$fp = fopen("schema/ttrss_schema_" . DB_TYPE . ".sql", "r");
		if ($fp) {
			while ($line = fgets($fp)) {
				$matches = array();

				if (preg_match("/^create index ([^ ]+) on ([^ ]+)$/i", $line, $matches)) {
					$index = $matches[1];
					$table = $matches[2];

					$statement = "CREATE INDEX $index ON $table";

Andrew Dolgov's avatar
Andrew Dolgov committed
307
					Debug::log($statement);
Andrew Dolgov's avatar
Andrew Dolgov committed
308
					$pdo->query($statement);
309 310 311 312
				}
			}
			fclose($fp);
		} else {
Andrew Dolgov's avatar
Andrew Dolgov committed
313
			Debug::log("unable to open schema file.");
314
		}
Andrew Dolgov's avatar
Andrew Dolgov committed
315
		Debug::log("all done.");
316 317
	}

318
	if (isset($options["convert-filters"])) {
Andrew Dolgov's avatar
Andrew Dolgov committed
319 320
		Debug::log("WARNING: this will remove all existing type2 filters.");
		Debug::log("Type 'yes' to continue.");
321 322 323 324

		if (read_stdin() != 'yes')
			exit;

Andrew Dolgov's avatar
Andrew Dolgov committed
325
		Debug::log("converting filters...");
326

Andrew Dolgov's avatar
Andrew Dolgov committed
327
		$pdo->query("DELETE FROM ttrss_filters2");
328

Andrew Dolgov's avatar
Andrew Dolgov committed
329
		$res = $pdo->query("SELECT * FROM ttrss_filters ORDER BY id");
330

Andrew Dolgov's avatar
Andrew Dolgov committed
331
		while ($line = $res->fetch()) {
332 333
			$owner_uid = $line["owner_uid"];

Andrew Dolgov's avatar
Andrew Dolgov committed
334 335 336 337 338 339 340 341 342
			// date filters are removed
			if ($line["filter_type"] != 5) {
				$filter = array();

				if (sql_bool_to_bool($line["cat_filter"])) {
					$feed_id = "CAT:" . (int)$line["cat_id"];
				} else {
					$feed_id = (int)$line["feed_id"];
				}
343

Andrew Dolgov's avatar
Andrew Dolgov committed
344 345 346 347 348 349
				$filter["enabled"] = $line["enabled"] ? "on" : "off";
				$filter["rule"] = array(
					json_encode(array(
						"reg_exp" => $line["reg_exp"],
						"feed_id" => $feed_id,
						"filter_type" => $line["filter_type"])));
350

Andrew Dolgov's avatar
Andrew Dolgov committed
351 352 353 354 355
				$filter["action"] = array(
					json_encode(array(
						"action_id" => $line["action_id"],
						"action_param_label" => $line["action_param"],
						"action_param" => $line["action_param"])));
356

Andrew Dolgov's avatar
Andrew Dolgov committed
357
				// Oh god it's full of hacks
358

Andrew Dolgov's avatar
Andrew Dolgov committed
359 360
				$_REQUEST = $filter;
				$_SESSION["uid"] = $owner_uid;
361

362
				$filters = new Pref_Filters($_REQUEST);
Andrew Dolgov's avatar
Andrew Dolgov committed
363 364
				$filters->add();
			}
365 366 367 368
		}

	}

369
	if (isset($options["update-schema"])) {
370
		Debug::log("Checking for updates (" . DB_TYPE . ")...");
371

Andrew Dolgov's avatar
Andrew Dolgov committed
372
		$updater = new DbUpdater(Db::pdo(), DB_TYPE, SCHEMA_VERSION);
373 374

		if ($updater->isUpdateRequired()) {
375
			Debug::log("Schema update required, version " . $updater->getSchemaVersion() . " to " . SCHEMA_VERSION);
376 377 378 379

			if (DB_TYPE == "mysql")
				Debug::Log("READ THIS: Due to MySQL limitations, your database is not completely protected while updating.\n".
					"Errors may put it in an inconsistent state requiring manual rollback.\nBACKUP YOUR DATABASE BEFORE CONTINUING.");
380 381
			else
				Debug::log("WARNING: please backup your database before continuing.");
382

Andrew Dolgov's avatar
Andrew Dolgov committed
383
			Debug::log("Type 'yes' to continue.");
384 385 386 387

			if (read_stdin() != 'yes')
				exit;

388
			Debug::log("Performing updates to version " . SCHEMA_VERSION);
389

390
			for ($i = $updater->getSchemaVersion() + 1; $i <= SCHEMA_VERSION; $i++) {
391
				Debug::log("* Updating to version $i...");
392

393
				$result = $updater->performUpdateTo($i, false);
394

395
				if ($result) {
396
					Debug::log("* Completed.");
397
				} else {
398
					Debug::log("One of the updates failed. Either retry the process or perform updates manually.");
399 400
					return;
				}
401 402 403

			}
		} else {
404
			Debug::log("Update not required.");
405 406 407 408
		}

	}

409 410
	if (isset($options["gen-search-idx"])) {
		echo "Generating search index (stemming set to English)...\n";
411

Andrew Dolgov's avatar
Andrew Dolgov committed
412 413 414
		$res = $pdo->query("SELECT COUNT(id) AS count FROM ttrss_entries WHERE tsvector_combined IS NULL");
		$row = $res->fetch();
		$count = $row['count'];
415

416
		print "Articles to process: $count.\n";
417

418 419
		$limit = 500;
		$processed = 0;
420

421
		$sth = $pdo->prepare("SELECT id, title, content FROM ttrss_entries WHERE
Andrew Dolgov's avatar
Andrew Dolgov committed
422 423 424
          tsvector_combined IS NULL ORDER BY id LIMIT ?");
		$sth->execute([$limit]);

425
		$usth = $pdo->prepare("UPDATE ttrss_entries
Andrew Dolgov's avatar
Andrew Dolgov committed
426 427
          SET tsvector_combined = to_tsvector('english', ?) WHERE id = ?");

428 429
		while (true) {

Andrew Dolgov's avatar
Andrew Dolgov committed
430
			while ($line = $sth->fetch()) {
431
				$tsvector_combined = mb_substr(strip_tags($line["title"] . " " . $line["content"]), 0, 1000000);
432

433
				$usth->execute([$tsvector_combined, $line['id']]);
Andrew Dolgov's avatar
Andrew Dolgov committed
434

435
				$processed++;
436
			}
437

438
			print "Processed $processed articles...\n";
439

Andrew Dolgov's avatar
Andrew Dolgov committed
440
			if ($processed < $limit) {
441 442 443 444 445 446
				echo "All done.\n";
				break;
			}
		}
	}

447
	if (isset($options["list-plugins"])) {
448
		$tmppluginhost = new PluginHost();
449
		$tmppluginhost->load_all($tmppluginhost::KIND_ALL, false);
450 451 452 453
		$enabled = array_map("trim", explode(",", PLUGINS));

		echo "List of all available plugins:\n";

454
		foreach ($tmppluginhost->get_plugins() as $name => $plugin) {
455
			$about = $plugin->about();
456

457 458 459 460 461 462
			$status = $about[3] ? "system" : "user";

			if (in_array($name, $enabled)) $name .= "*";

			printf("%-50s %-10s v%.2f (by %s)\n%s\n\n",
				$name, $status, $about[0], $about[2], $about[1]);
463
		}
464 465 466

		echo "Plugins marked by * are currently enabled for all users.\n";

467 468
	}

469 470 471 472 473 474
	if (isset($options["debug-feed"])) {
		$feed = $options["debug-feed"];

		if (isset($options["force-refetch"])) $_REQUEST["force_refetch"] = true;
		if (isset($options["force-rehash"])) $_REQUEST["force_rehash"] = true;

Andrew Dolgov's avatar
Andrew Dolgov committed
475
		Debug::set_loglevel(Debug::$LOG_EXTENDED);
476

477
		$rc = RSSUtils::update_rss_feed($feed) != false ? 0 : 1;
478 479

		exit($rc);
480 481
	}

482 483 484 485
	if (isset($options["send-digests"])) {
		Digest::send_headlines_digests();
	}

Andrew Dolgov's avatar
Andrew Dolgov committed
486
	PluginHost::getInstance()->run_commands($options);
487

488 489 490
	if (file_exists(LOCK_DIRECTORY . "/$lock_filename"))
		if (strtoupper(substr(PHP_OS, 0, 3)) == 'WIN')
			fclose($lock_handle);
491
		unlink(LOCK_DIRECTORY . "/$lock_filename");
492
?>