]> git.wh0rd.org - tt-rss.git/blame - classes/rssutils.php
dbupdater: use PDO
[tt-rss.git] / classes / rssutils.php
CommitLineData
2c08214a 1<?php
e6c886bf
AD
2class RSSUtils {
3 static function calculate_article_hash($article, $pluginhost) {
af244f92
AD
4 $tmp = "";
5
6 foreach ($article as $k => $v) {
7 if ($k != "feed" && isset($v)) {
24e6ff5d
AD
8 $x = strip_tags(is_array($v) ? implode(",", $v) : $v);
9
10 //_debug("$k:" . sha1($x) . ":" . htmlspecialchars($x), true);
11
12 $tmp .= sha1("$k:" . sha1($x));
af244f92
AD
13 }
14 }
15
eb16bd9f 16 return sha1(implode(",", $pluginhost->get_plugin_names()) . $tmp);
b1840673
AD
17 }
18
e6c886bf 19 static function update_feedbrowser_cache() {
79178062 20
a42c55f0 21 $result = db_query("SELECT feed_url, site_url, title, COUNT(id) AS subscribers
45378752
LD
22 FROM ttrss_feeds WHERE feed_url NOT IN (SELECT feed_url FROM ttrss_feeds
23 WHERE private IS true OR auth_login != '' OR auth_pass != '' OR feed_url LIKE '%:%@%/%')
79178062
AD
24 GROUP BY feed_url, site_url, title ORDER BY subscribers DESC LIMIT 1000");
25
a42c55f0 26 db_query("BEGIN");
79178062 27
a42c55f0 28 db_query("DELETE FROM ttrss_feedbrowser_cache");
79178062
AD
29
30 $count = 0;
31
32 while ($line = db_fetch_assoc($result)) {
a42c55f0
AD
33 $subscribers = db_escape_string($line["subscribers"]);
34 $feed_url = db_escape_string($line["feed_url"]);
35 $title = db_escape_string($line["title"]);
36 $site_url = db_escape_string($line["site_url"]);
79178062 37
a42c55f0 38 $tmp_result = db_query("SELECT subscribers FROM
79178062
AD
39 ttrss_feedbrowser_cache WHERE feed_url = '$feed_url'");
40
41 if (db_num_rows($tmp_result) == 0) {
42
a42c55f0 43 db_query("INSERT INTO ttrss_feedbrowser_cache
79178062
AD
44 (feed_url, site_url, title, subscribers) VALUES ('$feed_url',
45 '$site_url', '$title', '$subscribers')");
46
47 ++$count;
48
49 }
50
51 }
52
a42c55f0 53 db_query("COMMIT");
79178062
AD
54
55 return $count;
56
57 }
58
e6c886bf 59 static function update_daemon_common($limit = DAEMON_FEED_LIMIT, $debug = true) {
6322ac79 60 $schema_version = get_schema_version();
857efe49
AD
61
62 if ($schema_version != SCHEMA_VERSION) {
63 die("Schema version is wrong, please upgrade the database.\n");
64 }
65
09e8bdfd 66 if (!SINGLE_USER_MODE && DAEMON_UPDATE_LOGIN_LIMIT > 0) {
2c08214a
AD
67 if (DB_TYPE == "pgsql") {
68 $login_thresh_qpart = "AND ttrss_users.last_login >= NOW() - INTERVAL '".DAEMON_UPDATE_LOGIN_LIMIT." days'";
69 } else {
70 $login_thresh_qpart = "AND ttrss_users.last_login >= DATE_SUB(NOW(), INTERVAL ".DAEMON_UPDATE_LOGIN_LIMIT." DAY)";
71 }
72 } else {
73 $login_thresh_qpart = "";
74 }
75
2c08214a
AD
76 if (DB_TYPE == "pgsql") {
77 $update_limit_qpart = "AND ((
78 ttrss_feeds.update_interval = 0
ee0542ce 79 AND ttrss_user_prefs.value != '-1'
2c08214a
AD
80 AND ttrss_feeds.last_updated < NOW() - CAST((ttrss_user_prefs.value || ' minutes') AS INTERVAL)
81 ) OR (
82 ttrss_feeds.update_interval > 0
83 AND ttrss_feeds.last_updated < NOW() - CAST((ttrss_feeds.update_interval || ' minutes') AS INTERVAL)
f08426e3
AD
84 ) OR (ttrss_feeds.last_updated IS NULL
85 AND ttrss_user_prefs.value != '-1')
86 OR (last_updated = '1970-01-01 00:00:00'
87 AND ttrss_user_prefs.value != '-1'))";
2c08214a
AD
88 } else {
89 $update_limit_qpart = "AND ((
90 ttrss_feeds.update_interval = 0
ee0542ce 91 AND ttrss_user_prefs.value != '-1'
2c08214a
AD
92 AND ttrss_feeds.last_updated < DATE_SUB(NOW(), INTERVAL CONVERT(ttrss_user_prefs.value, SIGNED INTEGER) MINUTE)
93 ) OR (
94 ttrss_feeds.update_interval > 0
95 AND ttrss_feeds.last_updated < DATE_SUB(NOW(), INTERVAL ttrss_feeds.update_interval MINUTE)
f08426e3
AD
96 ) OR (ttrss_feeds.last_updated IS NULL
97 AND ttrss_user_prefs.value != '-1')
98 OR (last_updated = '1970-01-01 00:00:00'
99 AND ttrss_user_prefs.value != '-1'))";
2c08214a
AD
100 }
101
102 // Test if feed is currently being updated by another process.
103 if (DB_TYPE == "pgsql") {
566417c4 104 $updstart_thresh_qpart = "AND (ttrss_feeds.last_update_started IS NULL OR ttrss_feeds.last_update_started < NOW() - INTERVAL '10 minutes')";
2c08214a 105 } else {
566417c4 106 $updstart_thresh_qpart = "AND (ttrss_feeds.last_update_started IS NULL OR ttrss_feeds.last_update_started < DATE_SUB(NOW(), INTERVAL 10 MINUTE))";
2c08214a
AD
107 }
108
93af11cb 109 $query_limit = $limit ? sprintf("LIMIT %d", $limit) : "";
2c08214a 110
98070db0
TK
111 // Update the least recently updated feeds first
112 $query_order = "ORDER BY last_updated";
113 if (DB_TYPE == "pgsql") $query_order .= " NULLS FIRST";
114
fce451a4 115 $query = "SELECT DISTINCT ttrss_feeds.feed_url, ttrss_feeds.last_updated
2c08214a
AD
116 FROM
117 ttrss_feeds, ttrss_users, ttrss_user_prefs
f4ae0f05 118 WHERE
2c08214a 119 ttrss_feeds.owner_uid = ttrss_users.id
f08426e3 120 AND ttrss_user_prefs.profile IS NULL
2c08214a
AD
121 AND ttrss_users.id = ttrss_user_prefs.owner_uid
122 AND ttrss_user_prefs.pref_name = 'DEFAULT_UPDATE_INTERVAL'
123 $login_thresh_qpart $update_limit_qpart
1c4421fc 124 $updstart_thresh_qpart
98070db0 125 $query_order $query_limit";
fce451a4 126
fce451a4 127 $result = db_query($query);
2c08214a 128
93af11cb 129 if ($debug) _debug(sprintf("Scheduled %d feeds to update...", db_num_rows($result)));
2c08214a 130
2c08214a
AD
131 $feeds_to_update = array();
132 while ($line = db_fetch_assoc($result)) {
93af11cb 133 array_push($feeds_to_update, $line['feed_url']);
2c08214a
AD
134 }
135
93af11cb
AD
136 // Update last_update_started before actually starting the batch
137 // in order to minimize collision risk for parallel daemon tasks
138 if (count($feeds_to_update) > 0) {
139 $feeds_quoted = array_map(function ($s) { return "'" . db_escape_string($s) . "'"; }, $feeds_to_update);
1c4421fc 140
a42c55f0 141 db_query(sprintf("UPDATE ttrss_feeds SET last_update_started = NOW()
1c4421fc 142 WHERE feed_url IN (%s)", implode(',', $feeds_quoted)));
2c08214a
AD
143 }
144
8292d05b 145 $nf = 0;
2d9c5684 146 $bstarted = microtime(true);
8292d05b 147
5cbd1fe8
AD
148 $batch_owners = array();
149
1c4421fc
AD
150 foreach ($feeds_to_update as $feed) {
151 if($debug) _debug("Base feed: $feed");
2c08214a 152
a42c55f0 153 //update_rss_feed($line["id"], true);
2c08214a 154
1c4421fc 155 // since we have the data cached, we can deal with other feeds with the same url
15c762be 156 $tmp_result = db_query("SELECT DISTINCT ttrss_feeds.id,last_updated,ttrss_feeds.owner_uid
ee0542ce
AD
157 FROM ttrss_feeds, ttrss_users, ttrss_user_prefs WHERE
158 ttrss_user_prefs.owner_uid = ttrss_feeds.owner_uid AND
159 ttrss_users.id = ttrss_user_prefs.owner_uid AND
160 ttrss_user_prefs.pref_name = 'DEFAULT_UPDATE_INTERVAL' AND
f08426e3 161 ttrss_user_prefs.profile IS NULL AND
9e84bab4
AD
162 feed_url = '".db_escape_string($feed)."'
163 $update_limit_qpart
1c4421fc 164 $login_thresh_qpart
5929a0c1 165 ORDER BY ttrss_feeds.id $query_limit");
1c4421fc
AD
166
167 if (db_num_rows($tmp_result) > 0) {
168 while ($tline = db_fetch_assoc($tmp_result)) {
93af11cb 169 if ($debug) _debug(" => " . $tline["last_updated"] . ", " . $tline["id"] . " " . $tline["owner_uid"]);
f08426e3 170
5cbd1fe8
AD
171 if (array_search($tline["owner_uid"], $batch_owners) === FALSE)
172 array_push($batch_owners, $tline["owner_uid"]);
173
2d9c5684 174 $fstarted = microtime(true);
e6c886bf 175 RSSUtils::update_rss_feed($tline["id"], true, false);
4f71d743 176 _debug_suppress(false);
2d9c5684
AD
177
178 _debug(sprintf(" %.4f (sec)", microtime(true) - $fstarted));
179
8292d05b 180 ++$nf;
1c4421fc
AD
181 }
182 }
2c08214a
AD
183 }
184
2d9c5684
AD
185 if ($nf > 0) {
186 _debug(sprintf("Processed %d feeds in %.4f (sec), %.4f (sec/feed avg)", $nf,
187 microtime(true) - $bstarted, (microtime(true) - $bstarted) / $nf));
188 }
189
5cbd1fe8
AD
190 foreach ($batch_owners as $owner_uid) {
191 _debug("Running housekeeping tasks for user $owner_uid...");
192
e6c886bf 193 RSSUtils::housekeeping_user($owner_uid);
5cbd1fe8
AD
194 }
195
2c08214a 196 // Send feed digests by email if needed.
c2f0f24e 197 Digest::send_headlines_digests($debug);
2c08214a 198
8292d05b
AD
199 return $nf;
200
7b55001e 201 }
2c08214a 202
6022776d 203 // this is used when subscribing
e6c886bf 204 static function set_basic_feed_info($feed) {
6022776d
AD
205
206 $feed = db_escape_string($feed);
207
bec5ba93 208 $result = db_query("SELECT owner_uid,feed_url,auth_pass,auth_login,auth_pass_encrypted
6022776d
AD
209 FROM ttrss_feeds WHERE id = '$feed'");
210
bec5ba93 211 $owner_uid = db_fetch_result($result, 0, "owner_uid");
212
6022776d
AD
213 $auth_pass_encrypted = sql_bool_to_bool(db_fetch_result($result,
214 0, "auth_pass_encrypted"));
215
216 $auth_login = db_fetch_result($result, 0, "auth_login");
217 $auth_pass = db_fetch_result($result, 0, "auth_pass");
218
17a8e61d 219 if ($auth_pass_encrypted && function_exists("mcrypt_decrypt")) {
6022776d
AD
220 require_once "crypt.php";
221 $auth_pass = decrypt_string($auth_pass);
222 }
223
224 $fetch_url = db_fetch_result($result, 0, "feed_url");
225
bec5ba93 226 $pluginhost = new PluginHost();
227 $user_plugins = get_pref("_ENABLED_PLUGINS", $owner_uid);
6022776d 228
bec5ba93 229 $pluginhost->load(PLUGINS, PluginHost::KIND_ALL);
230 $pluginhost->load($user_plugins, PluginHost::KIND_USER, $owner_uid);
231 $pluginhost->load_data();
6022776d 232
3476690c 233 $basic_info = array();
bec5ba93 234 foreach ($pluginhost->get_hooks(PluginHost::HOOK_FEED_BASIC_INFO) as $plugin) {
3476690c 235 $basic_info = $plugin->hook_feed_basic_info($basic_info, $fetch_url, $owner_uid, $feed, $auth_login, $auth_pass);
236 }
6022776d 237
3476690c 238 if (!$basic_info) {
bec5ba93 239 $feed_data = fetch_file_contents($fetch_url, false,
240 $auth_login, $auth_pass, false,
241 FEED_FETCH_TIMEOUT,
242 0);
243
244 global $fetch_curl_used;
245
246 if (!$fetch_curl_used) {
247 $tmp = @gzdecode($feed_data);
248
249 if ($tmp) $feed_data = $tmp;
250 }
6022776d 251
3476690c 252 $feed_data = trim($feed_data);
6022776d 253
3476690c 254 $rss = new FeedParser($feed_data);
255 $rss->init();
6022776d 256
3476690c 257 if (!$rss->error()) {
258 $basic_info = array(
259 'title' => db_escape_string(mb_substr($rss->get_title(), 0, 199)),
260 'site_url' => db_escape_string(mb_substr(rewrite_relative_url($fetch_url, $rss->get_link()), 0, 245))
261 );
262 }
263 }
6022776d 264
3476690c 265 if ($basic_info && is_array($basic_info)) {
6022776d
AD
266 $result = db_query("SELECT title, site_url FROM ttrss_feeds WHERE id = '$feed'");
267
268 $registered_title = db_fetch_result($result, 0, "title");
269 $orig_site_url = db_fetch_result($result, 0, "site_url");
270
3476690c 271 if ($basic_info['title'] && (!$registered_title || $registered_title == "[Unknown]")) {
6022776d 272 db_query("UPDATE ttrss_feeds SET
3476690c 273 title = '${basic_info['title']}' WHERE id = '$feed'");
6022776d
AD
274 }
275
3476690c 276 if ($basic_info['site_url'] && $orig_site_url != $basic_info['site_url']) {
6022776d 277 db_query("UPDATE ttrss_feeds SET
3476690c 278 site_url = '${basic_info['site_url']}' WHERE id = '$feed'");
6022776d
AD
279 }
280 }
281 }
282
7b55001e 283 /**
e6c886bf
AD
284 * @SuppressWarnings(PHPMD.UnusedFormalParameter)
285 */
286 static function update_rss_feed($feed, $no_cache = false) {
2c08214a 287
2c08214a
AD
288 $debug_enabled = defined('DAEMON_EXTENDED_DEBUG') || $_REQUEST['xdebug'];
289
4f71d743 290 _debug_suppress(!$debug_enabled);
68cccafc 291 _debug("start", $debug_enabled);
2c08214a 292
6bb96beb
AD
293 $result = db_query("SELECT title FROM ttrss_feeds
294 WHERE id = '$feed'");
bfe1eb4e
AD
295
296 if (db_num_rows($result) == 0) {
297 _debug("feed $feed NOT FOUND/SKIPPED", $debug_enabled);
298 user_error("Attempt to update unknown/invalid feed $feed", E_USER_WARNING);
299 return false;
300 }
301
6bb96beb
AD
302 $title = db_fetch_result($result, 0, "title");
303
304 // feed was batch-subscribed or something, we need to get basic info
305 // this is not optimal currently as it fetches stuff separately TODO: optimize
306 if ($title == "[Unknown]") {
307 _debug("setting basic feed info for $feed...");
e6c886bf 308 RSSUtils::set_basic_feed_info($feed);
6bb96beb
AD
309 }
310
a42c55f0 311 $result = db_query("SELECT id,update_interval,auth_login,
5ba1ddd4 312 feed_url,auth_pass,cache_images,
5321e775 313 mark_unread_on_update, owner_uid,
153cb6d3 314 auth_pass_encrypted, feed_language,
e50c8eaa
AD
315 last_modified,
316 ".SUBSTRING_FOR_DATE."(last_unconditional, 1, 19) AS last_unconditional
87764a50 317 FROM ttrss_feeds WHERE id = '$feed'");
2c08214a 318
2c08214a
AD
319 $owner_uid = db_fetch_result($result, 0, "owner_uid");
320 $mark_unread_on_update = sql_bool_to_bool(db_fetch_result($result,
321 0, "mark_unread_on_update"));
044cff2d
AD
322 $auth_pass_encrypted = sql_bool_to_bool(db_fetch_result($result,
323 0, "auth_pass_encrypted"));
2c08214a 324
a42c55f0 325 db_query("UPDATE ttrss_feeds SET last_update_started = NOW()
2c08214a
AD
326 WHERE id = '$feed'");
327
328 $auth_login = db_fetch_result($result, 0, "auth_login");
329 $auth_pass = db_fetch_result($result, 0, "auth_pass");
330
17a8e61d 331 if ($auth_pass_encrypted && function_exists("mcrypt_decrypt")) {
044cff2d
AD
332 require_once "crypt.php";
333 $auth_pass = decrypt_string($auth_pass);
334 }
335
153cb6d3 336 $stored_last_modified = db_fetch_result($result, 0, "last_modified");
e50c8eaa 337 $last_unconditional = db_fetch_result($result, 0, "last_unconditional");
2c08214a
AD
338 $cache_images = sql_bool_to_bool(db_fetch_result($result, 0, "cache_images"));
339 $fetch_url = db_fetch_result($result, 0, "feed_url");
df659891
AD
340 $feed_language = db_escape_string(mb_strtolower(db_fetch_result($result, 0, "feed_language")));
341 if (!$feed_language) $feed_language = 'english';
2c08214a 342
a42c55f0 343 $feed = db_escape_string($feed);
2c08214a 344
f074ffe9 345 $date_feed_processed = date('Y-m-d H:i');
2c08214a 346
865a3ed6 347 $cache_filename = CACHE_DIR . "/simplepie/" . sha1($fetch_url) . ".xml";
f074ffe9 348
ee65bef4
AD
349 $pluginhost = new PluginHost();
350 $pluginhost->set_debug($debug_enabled);
351 $user_plugins = get_pref("_ENABLED_PLUGINS", $owner_uid);
352
353 $pluginhost->load(PLUGINS, PluginHost::KIND_ALL);
354 $pluginhost->load($user_plugins, PluginHost::KIND_USER, $owner_uid);
355 $pluginhost->load_data();
356
7b55001e 357 $rss_hash = false;
4f9cbdff 358
7b55001e
AD
359 $force_refetch = isset($_REQUEST["force_refetch"]);
360 $feed_data = "";
687a4f59 361
7b55001e
AD
362 foreach ($pluginhost->get_hooks(PluginHost::HOOK_FETCH_FEED) as $plugin) {
363 $feed_data = $plugin->hook_fetch_feed($feed_data, $fetch_url, $owner_uid, $feed, 0, $auth_login, $auth_pass);
364 }
2c08214a 365
7b55001e
AD
366 // try cache
367 if (!$feed_data &&
368 file_exists($cache_filename) &&
369 is_readable($cache_filename) &&
370 !$auth_login && !$auth_pass &&
371 filemtime($cache_filename) > time() - 30) {
be574731 372
7b55001e 373 _debug("using local cache [$cache_filename].", $debug_enabled);
52637d3b 374
7b55001e 375 @$feed_data = file_get_contents($cache_filename);
f074ffe9 376
7b55001e
AD
377 if ($feed_data) {
378 $rss_hash = sha1($feed_data);
88edaa93 379 }
ee65bef4 380
7b55001e
AD
381 } else {
382 _debug("local cache will not be used for this feed", $debug_enabled);
383 }
312742db 384
153cb6d3
AD
385 global $fetch_last_modified;
386
7b55001e
AD
387 // fetch feed from source
388 if (!$feed_data) {
e50c8eaa 389 _debug("last unconditional update request: $last_unconditional");
312742db 390
7b55001e
AD
391 if (ini_get("open_basedir") && function_exists("curl_init")) {
392 _debug("not using CURL due to open_basedir restrictions");
393 }
3f6f0857 394
e50c8eaa
AD
395 if (time() - strtotime($last_unconditional) > MAX_CONDITIONAL_INTERVAL) {
396 _debug("maximum allowed interval for conditional requests exceeded, forcing refetch");
397
398 $force_refetch = true;
399 } else {
400 _debug("stored last modified for conditional request: $stored_last_modified", $debug_enabled);
401 }
153cb6d3 402
e50c8eaa 403 _debug("fetching [$fetch_url] (force_refetch: $force_refetch)...", $debug_enabled);
153cb6d3
AD
404
405 $feed_data = fetch_file_contents([
406 "url" => $fetch_url,
407 "login" => $auth_login,
408 "pass" => $auth_pass,
409 "timeout" => $no_cache ? FEED_FETCH_NO_CACHE_TIMEOUT : FEED_FETCH_TIMEOUT,
410 "last_modified" => $force_refetch ? "" : $stored_last_modified
411 ]);
3f6f0857 412
7b55001e 413 global $fetch_curl_used;
3f6f0857 414
7b55001e
AD
415 if (!$fetch_curl_used) {
416 $tmp = @gzdecode($feed_data);
1367bc3f 417
7b55001e
AD
418 if ($tmp) $feed_data = $tmp;
419 }
017401dd 420
7b55001e 421 $feed_data = trim($feed_data);
fd687300 422
7b55001e 423 _debug("fetch done.", $debug_enabled);
9d930af9 424 _debug("source last modified: " . $fetch_last_modified, $debug_enabled);
153cb6d3
AD
425
426 if ($feed_data && $fetch_last_modified != $stored_last_modified) {
427 $last_modified_escaped = db_escape_string(substr($fetch_last_modified, 0, 245));
428
429 db_query("UPDATE ttrss_feeds SET last_modified = '$last_modified_escaped' WHERE id = '$feed'");
430
431 }
95beaa14 432
7b55001e
AD
433 // cache vanilla feed data for re-use
434 if ($feed_data && !$auth_pass && !$auth_login && is_writable(CACHE_DIR . "/simplepie")) {
435 $new_rss_hash = sha1($feed_data);
436
437 if ($new_rss_hash != $rss_hash) {
438 _debug("saving $cache_filename", $debug_enabled);
439 @file_put_contents($cache_filename, $feed_data);
95beaa14 440 }
4f9cbdff 441 }
7b55001e 442 }
017401dd 443
7b55001e
AD
444 if (!$feed_data) {
445 global $fetch_last_error;
446 global $fetch_last_error_code;
f074ffe9 447
7b55001e 448 _debug("unable to fetch: $fetch_last_error [$fetch_last_error_code]", $debug_enabled);
f074ffe9 449
7b55001e 450 $error_escaped = '';
7a01dc77 451
7b55001e
AD
452 // If-Modified-Since
453 if ($fetch_last_error_code != 304) {
454 $error_escaped = db_escape_string($fetch_last_error);
455 } else {
456 _debug("source claims data not modified, nothing to do.", $debug_enabled);
457 }
4f9cbdff 458
7b55001e
AD
459 db_query(
460 "UPDATE ttrss_feeds SET last_error = '$error_escaped',
461 last_updated = NOW() WHERE id = '$feed'");
4f9cbdff 462
7b55001e 463 return;
f074ffe9
AD
464 }
465
1ffe3391 466 foreach ($pluginhost->get_hooks(PluginHost::HOOK_FEED_FETCHED) as $plugin) {
6791af0c 467 $feed_data = $plugin->hook_feed_fetched($feed_data, $fetch_url, $owner_uid, $feed);
017401dd
AD
468 }
469
07d3431e
AD
470 $rss = new FeedParser($feed_data);
471 $rss->init();
2c08214a 472
a42c55f0 473 $feed = db_escape_string($feed);
2c08214a 474
19b3992b 475 if (!$rss->error()) {
2c08214a 476
d2a421e3 477 // We use local pluginhost here because we need to load different per-user feed plugins
1ffe3391 478 $pluginhost->run_hooks(PluginHost::HOOK_FEED_PARSED, "hook_feed_parsed", $rss);
4412b877 479
df659891 480 _debug("language: $feed_language", $debug_enabled);
68cccafc 481 _debug("processing feed data...", $debug_enabled);
2c08214a 482
a42c55f0 483// db_query("BEGIN");
2c08214a 484
382268c6
AD
485 if (DB_TYPE == "pgsql") {
486 $favicon_interval_qpart = "favicon_last_checked < NOW() - INTERVAL '12 hour'";
487 } else {
488 $favicon_interval_qpart = "favicon_last_checked < DATE_SUB(NOW(), INTERVAL 12 HOUR)";
489 }
490
fe4535e6 491 $result = db_query("SELECT owner_uid,favicon_avg_color,
382268c6
AD
492 (favicon_last_checked IS NULL OR $favicon_interval_qpart) AS
493 favicon_needs_check
2c08214a
AD
494 FROM ttrss_feeds WHERE id = '$feed'");
495
382268c6
AD
496 $favicon_needs_check = sql_bool_to_bool(db_fetch_result($result, 0,
497 "favicon_needs_check"));
36490f11 498 $favicon_avg_color = db_fetch_result($result, 0, "favicon_avg_color");
2c08214a
AD
499
500 $owner_uid = db_fetch_result($result, 0, "owner_uid");
501
a42c55f0 502 $site_url = db_escape_string(mb_substr(rewrite_relative_url($fetch_url, $rss->get_link()), 0, 245));
2c08214a 503
cd07592c
AD
504 _debug("site_url: $site_url", $debug_enabled);
505 _debug("feed_title: " . $rss->get_title(), $debug_enabled);
506
687a4f59 507 if ($favicon_needs_check || $force_refetch) {
36490f11
AD
508
509 /* terrible hack: if we crash on floicon shit here, we won't check
560cbd8c 510 * the icon avgcolor again (unless the icon got updated) */
36490f11 511
560cbd8c
AD
512 $favicon_file = ICONS_DIR . "/$feed.ico";
513 $favicon_modified = @filemtime($favicon_file);
514
68cccafc 515 _debug("checking favicon...", $debug_enabled);
687a4f59 516
e6c886bf 517 RSSUtils::check_feed_favicon($site_url, $feed);
560cbd8c
AD
518 $favicon_modified_new = @filemtime($favicon_file);
519
520 if ($favicon_modified_new > $favicon_modified)
521 $favicon_avg_color = '';
687a4f59 522
6ee0d4b0 523 if (file_exists($favicon_file) && function_exists("imagecreatefromstring") && $favicon_avg_color == '') {
e6c886bf 524 require_once "colors.php";
687a4f59 525
e6c886bf 526 db_query("UPDATE ttrss_feeds SET favicon_avg_color = 'fail' WHERE
aafd55ba
AD
527 id = '$feed'");
528
e6c886bf
AD
529 $favicon_color = db_escape_string(
530 calculate_avg_color($favicon_file));
63c323f7 531
e6c886bf 532 $favicon_colorstring = ",favicon_avg_color = '".$favicon_color."'";
36490f11 533 } else if ($favicon_avg_color == 'fail') {
84ceb6bd 534 _debug("floicon failed on this file, not trying to recalculate avg color", $debug_enabled);
6ac722d5 535 }
687a4f59 536
a42c55f0 537 db_query("UPDATE ttrss_feeds SET favicon_last_checked = NOW()
bc7a144d 538 $favicon_colorstring
f2798eb6
AD
539 WHERE id = '$feed'");
540 }
2c08214a 541
68cccafc 542 _debug("loading filters & labels...", $debug_enabled);
2c08214a 543
a42c55f0 544 $filters = load_filters($feed, $owner_uid);
2c08214a 545
02f3992a
AD
546 if ($debug_enabled) {
547 print_r($filters);
548 }
549
68cccafc 550 _debug("" . count($filters) . " filters loaded.", $debug_enabled);
2c08214a 551
19b3992b 552 $items = $rss->get_items();
2c08214a 553
19b3992b 554 if (!is_array($items)) {
68cccafc 555 _debug("no articles found.", $debug_enabled);
2c08214a 556
a42c55f0 557 db_query("UPDATE ttrss_feeds
e50c8eaa 558 SET last_updated = NOW(), last_unconditional = NOW(), last_error = '' WHERE id = '$feed'");
2c08214a
AD
559
560 return; // no articles
561 }
562
68cccafc 563 _debug("processing articles...", $debug_enabled);
2c08214a 564
6c9f3d4a
AD
565 $tstart = time();
566
19b3992b 567 foreach ($items as $item) {
5d56d100 568 if ($_REQUEST['xdebug'] == 3) {
2c08214a
AD
569 print_r($item);
570 }
571
6c9f3d4a
AD
572 if (ini_get("max_execution_time") > 0 && time() - $tstart >= ini_get("max_execution_time") * 0.7) {
573 _debug("looks like there's too many articles to process at once, breaking out", $debug_enabled);
574 break;
575 }
576
19b3992b
AD
577 $entry_guid = $item->get_id();
578 if (!$entry_guid) $entry_guid = $item->get_link();
e6c886bf 579 if (!$entry_guid) $entry_guid = RSSUtils::make_guid_from_title($item->get_title());
2c08214a
AD
580 if (!$entry_guid) continue;
581
3a4c8973
AD
582 $entry_guid = "$owner_uid,$entry_guid";
583
a42c55f0 584 $entry_guid_hashed = db_escape_string('SHA1:' . sha1($entry_guid));
5e3d5480 585
68cccafc 586 _debug("guid $entry_guid / $entry_guid_hashed", $debug_enabled);
5e3d5480 587
2c08214a
AD
588 $entry_timestamp = "";
589
04d2f9c8
AD
590 $entry_timestamp = $item->get_date();
591
592 _debug("orig date: " . $item->get_date(), $debug_enabled);
2c08214a 593
30123fe6 594 if ($entry_timestamp == -1 || !$entry_timestamp || $entry_timestamp > time()) {
2c08214a 595 $entry_timestamp = time();
2c08214a
AD
596 }
597
598 $entry_timestamp_fmt = strftime("%Y/%m/%d %H:%M:%S", $entry_timestamp);
599
68cccafc 600 _debug("date $entry_timestamp [$entry_timestamp_fmt]", $debug_enabled);
2c08214a 601
99429e57
AD
602// $entry_title = html_entity_decode($item->get_title(), ENT_COMPAT, 'UTF-8');
603// $entry_title = decode_numeric_entities($entry_title);
604 $entry_title = $item->get_title();
1b35d30c 605
5d56d100 606 $entry_link = rewrite_relative_url($site_url, $item->get_link());
2c08214a 607
68cccafc
AD
608 _debug("title $entry_title", $debug_enabled);
609 _debug("link $entry_link", $debug_enabled);
2c08214a
AD
610
611 if (!$entry_title) $entry_title = date("Y-m-d H:i:s", $entry_timestamp);;
612
19b3992b
AD
613 $entry_content = $item->get_content();
614 if (!$entry_content) $entry_content = $item->get_description();
2c08214a
AD
615
616 if ($_REQUEST["xdebug"] == 2) {
9ec10352 617 print "content: ";
0bc503ff 618 print htmlspecialchars($entry_content);
3c696512 619 print "\n";
2c08214a
AD
620 }
621
12ff230b
AD
622 $entry_comments = db_escape_string(mb_substr($item->get_comments_url(), 0, 245));
623 $num_comments = (int) $item->get_comments_count();
2c08214a 624
12ff230b 625 $entry_author = $item->get_author(); // escaped later
a42c55f0 626 $entry_guid = db_escape_string(mb_substr($entry_guid, 0, 245));
2c08214a 627
68cccafc
AD
628 _debug("author $entry_author", $debug_enabled);
629 _debug("num_comments: $num_comments", $debug_enabled);
ee78f81c 630 _debug("looking for tags...", $debug_enabled);
2c08214a
AD
631
632 // parse <category> entries into tags
633
634 $additional_tags = array();
635
19b3992b 636 $additional_tags_src = $item->get_categories();
2c08214a 637
19b3992b
AD
638 if (is_array($additional_tags_src)) {
639 foreach ($additional_tags_src as $tobj) {
cd07592c 640 array_push($additional_tags, $tobj);
2c08214a 641 }
19b3992b 642 }
2c08214a 643
fa6fbd36 644 $entry_tags = array_unique($additional_tags);
2c08214a
AD
645
646 for ($i = 0; $i < count($entry_tags); $i++)
647 $entry_tags[$i] = mb_strtolower($entry_tags[$i], 'utf-8');
648
ee78f81c
AD
649 _debug("tags found: " . join(",", $entry_tags), $debug_enabled);
650
68cccafc 651 _debug("done collecting data.", $debug_enabled);
2c08214a 652
3318d324 653 $result = db_query("SELECT id, content_hash, lang FROM ttrss_entries
b1840673 654 WHERE guid = '".db_escape_string($entry_guid)."' OR guid = '$entry_guid_hashed'");
b30abdad
AD
655
656 if (db_num_rows($result) != 0) {
b1840673
AD
657 $base_entry_id = db_fetch_result($result, 0, "id");
658 $entry_stored_hash = db_fetch_result($result, 0, "content_hash");
4a0da0e5 659 $article_labels = Article::get_article_labels($base_entry_id, $owner_uid);
3318d324 660 $entry_language = db_fetch_result($result, 0, "lang");
a8ac7661 661
2ed0d6c4 662 $existing_tags = Article::get_article_tags($base_entry_id, $owner_uid);
a8ac7661
AD
663 $entry_tags = array_unique(array_merge($entry_tags, $existing_tags));
664
b30abdad 665 } else {
b1840673
AD
666 $base_entry_id = false;
667 $entry_stored_hash = "";
a29fe121 668 $article_labels = array();
3318d324 669 $entry_language = "";
b30abdad
AD
670 }
671
455b1401 672 $article = array("owner_uid" => $owner_uid, // read only
b30abdad 673 "guid" => $entry_guid, // read only
59e83455 674 "guid_hashed" => $entry_guid_hashed, // read only
19b3992b
AD
675 "title" => $entry_title,
676 "content" => $entry_content,
677 "link" => $entry_link,
a29fe121 678 "labels" => $article_labels, // current limitation: can add labels to article, can't remove them
19b3992b 679 "tags" => $entry_tags,
e02555c1 680 "author" => $entry_author,
c9299c28 681 "force_catchup" => false, // ugly hack for the time being
6de3a1be 682 "score_modifier" => 0, // no previous value, plugin should recalculate score modifier based on content if needed
3318d324 683 "language" => $entry_language,
20d2195f 684 "num_comments" => $num_comments, // read only
f73e03e0
AD
685 "feed" => array("id" => $feed,
686 "fetch_url" => $fetch_url,
babfadbf
J
687 "site_url" => $site_url,
688 "cache_images" => $cache_images)
e6c886bf 689 );
cc85704f 690
b1840673 691 $entry_plugin_data = "";
e6c886bf 692 $entry_current_hash = RSSUtils::calculate_article_hash($article, $pluginhost);
b1840673
AD
693
694 _debug("article hash: $entry_current_hash [stored=$entry_stored_hash]", $debug_enabled);
695
522e8b35 696 if ($entry_current_hash == $entry_stored_hash && !isset($_REQUEST["force_rehash"])) {
b1840673
AD
697 _debug("stored article seems up to date [IID: $base_entry_id], updating timestamp only", $debug_enabled);
698
699 // we keep encountering the entry in feeds, so we need to
700 // update date_updated column so that we don't get horrible
701 // dupes when the entry gets purged and reinserted again e.g.
702 // in the case of SLOW SLOW OMG SLOW updating feeds
703
704 $base_entry_id = db_fetch_result($result, 0, "id");
705
706 db_query("UPDATE ttrss_entries SET date_updated = NOW()
707 WHERE id = '$base_entry_id'");
708
5bdcb8fd 709 continue;
b1840673
AD
710 }
711
712 _debug("hash differs, applying plugin filters:", $debug_enabled);
713
1ffe3391 714 foreach ($pluginhost->get_hooks(PluginHost::HOOK_ARTICLE_FILTER) as $plugin) {
b1840673
AD
715 _debug("... " . get_class($plugin), $debug_enabled);
716
717 $start = microtime(true);
19b3992b 718 $article = $plugin->hook_article_filter($article);
0084f0d1 719
b1840673
AD
720 _debug("=== " . sprintf("%.4f (sec)", microtime(true) - $start), $debug_enabled);
721
722 $entry_plugin_data .= mb_strtolower(get_class($plugin)) . ",";
cc85704f
AD
723 }
724
0bc503ff
AD
725 if ($_REQUEST["xdebug"] == 2) {
726 print "processed content: ";
727 print htmlspecialchars($article["content"]);
728 print "\n";
729 }
730
b1840673
AD
731 $entry_plugin_data = db_escape_string($entry_plugin_data);
732
733 _debug("plugin data: $entry_plugin_data", $debug_enabled);
734
35c12dc4
AD
735 // Workaround: 4-byte unicode requires utf8mb4 in MySQL. See https://tt-rss.org/forum/viewtopic.php?f=1&t=3377&p=20077#p20077
736 if (DB_TYPE == "mysql") {
737 foreach ($article as $k => $v) {
35c37354
AD
738
739 // i guess we'll have to take the risk of 4byte unicode labels & tags here
dae16f72 740 if (is_string($article[$k])) {
35c37354
AD
741 $article[$k] = preg_replace('/[\x{10000}-\x{10FFFF}]/u', "\xEF\xBF\xBD", $v);
742 }
35c12dc4
AD
743 }
744 }
745
b8774453
AD
746 /* Collect article tags here so we could filter by them: */
747
557d86fe
AD
748 $matched_rules = array();
749
e6c886bf 750 $article_filters = RSSUtils::get_article_filters($filters, $article["title"],
7b55001e 751 $article["content"], $article["link"], $article["author"],
557d86fe 752 $article["tags"], $matched_rules);
b8774453
AD
753
754 if ($debug_enabled) {
557d86fe
AD
755 _debug("matched filter rules: ", $debug_enabled);
756
757 if (count($matched_rules) != 0) {
758 print_r($matched_rules);
759 }
760
761 _debug("filter actions: ", $debug_enabled);
762
b8774453
AD
763 if (count($article_filters) != 0) {
764 print_r($article_filters);
765 }
766 }
767
e6c886bf 768 $plugin_filter_names = RSSUtils::find_article_filters($article_filters, "plugin");
b8774453
AD
769 $plugin_filter_actions = $pluginhost->get_filter_actions();
770
771 if (count($plugin_filter_names) > 0) {
772 _debug("applying plugin filter actions...", $debug_enabled);
773
774 foreach ($plugin_filter_names as $pfn) {
775 list($pfclass,$pfaction) = explode(":", $pfn["param"]);
776
777 if (isset($plugin_filter_actions[$pfclass])) {
778 $plugin = $pluginhost->get_plugin($pfclass);
779
780 _debug("... $pfclass: $pfaction", $debug_enabled);
781
782 if ($plugin) {
783 $start = microtime(true);
784 $article = $plugin->hook_article_filter_action($article, $pfaction);
785
786 _debug("=== " . sprintf("%.4f (sec)", microtime(true) - $start), $debug_enabled);
787 } else {
788 _debug("??? $pfclass: plugin object not found.");
789 }
790 } else {
791 _debug("??? $pfclass: filter plugin not registered.");
792 }
793 }
794 }
795
19b3992b 796 $entry_tags = $article["tags"];
a42c55f0
AD
797 $entry_guid = db_escape_string($entry_guid);
798 $entry_title = db_escape_string($article["title"]);
12ff230b 799 $entry_author = db_escape_string(mb_substr($article["author"], 0, 245));
a42c55f0 800 $entry_link = db_escape_string($article["link"]);
f935d98e 801 $entry_content = $article["content"]; // escaped below
c9299c28 802 $entry_force_catchup = $article["force_catchup"];
a29fe121 803 $article_labels = $article["labels"];
6de3a1be 804 $entry_score_modifier = (int) $article["score_modifier"];
3318d324 805 $entry_language = db_escape_string($article["language"]);
a29fe121
AD
806
807 if ($debug_enabled) {
808 _debug("article labels:", $debug_enabled);
557d86fe
AD
809
810 if (count($article_labels) != 0) {
811 print_r($article_labels);
812 }
a29fe121 813 }
c9299c28
AD
814
815 _debug("force catchup: $entry_force_catchup");
f935d98e 816
0a3fd79b 817 if ($cache_images && is_writable(CACHE_DIR . '/images'))
e6c886bf 818 RSSUtils::cache_media($entry_content, $site_url, $debug_enabled);
0a3fd79b 819
a42c55f0 820 $entry_content = db_escape_string($entry_content, false);
1f45c857 821
07877caf 822 //db_query("BEGIN");
2c08214a 823
a42c55f0 824 $result = db_query("SELECT id FROM ttrss_entries
5e3d5480 825 WHERE (guid = '$entry_guid' OR guid = '$entry_guid_hashed')");
9e222305 826
2c08214a
AD
827 if (db_num_rows($result) == 0) {
828
07d3431e 829 _debug("base guid [$entry_guid or $entry_guid_hashed] not found, creating...", $debug_enabled);
2c08214a
AD
830
831 // base post entry does not exist, create it
832
07d3431e 833 db_query(
2c08214a
AD
834 "INSERT INTO ttrss_entries
835 (title,
836 guid,
837 link,
838 updated,
839 content,
840 content_hash,
841 no_orig_date,
842 date_updated,
843 date_entered,
844 comments,
845 num_comments,
b30abdad 846 plugin_data,
6b461797 847 lang,
2c08214a
AD
848 author)
849 VALUES
850 ('$entry_title',
5e3d5480 851 '$entry_guid_hashed',
2c08214a
AD
852 '$entry_link',
853 '$entry_timestamp_fmt',
854 '$entry_content',
b1840673 855 '$entry_current_hash',
5ba1ddd4 856 false,
2c08214a 857 NOW(),
be574731 858 '$date_feed_processed',
2c08214a
AD
859 '$entry_comments',
860 '$num_comments',
b30abdad 861 '$entry_plugin_data',
6b461797 862 '$entry_language',
2c08214a 863 '$entry_author')");
e8291805 864
2c08214a
AD
865 }
866
867 // now it should exist, if not - bad luck then
868
b1840673 869 $result = db_query("SELECT id FROM ttrss_entries
5e3d5480 870 WHERE guid = '$entry_guid' OR guid = '$entry_guid_hashed'");
2c08214a
AD
871
872 $entry_ref_id = 0;
873 $entry_int_id = 0;
874
875 if (db_num_rows($result) == 1) {
876
68cccafc 877 _debug("base guid found, checking for user record", $debug_enabled);
2c08214a 878
2c08214a
AD
879 $ref_id = db_fetch_result($result, 0, "id");
880 $entry_ref_id = $ref_id;
881
5e3d5480
AD
882 /* $stored_guid = db_fetch_result($result, 0, "guid");
883 if ($stored_guid != $entry_guid_hashed) {
68cccafc 884 if ($debug_enabled) _debug("upgrading compat guid to hashed one", $debug_enabled);
5e3d5480 885
a42c55f0 886 db_query("UPDATE ttrss_entries SET guid = '$entry_guid_hashed' WHERE
5e3d5480
AD
887 id = '$ref_id'");
888 } */
889
e6c886bf 890 if (RSSUtils::find_article_filter($article_filters, "filter")) {
07877caf 891 //db_query("COMMIT"); // close transaction in progress
2c08214a
AD
892 continue;
893 }
894
e6c886bf 895 $score = RSSUtils::calculate_article_score($article_filters) + $entry_score_modifier;
2c08214a 896
6de3a1be 897 _debug("initial score: $score [including plugin modifier: $entry_score_modifier]", $debug_enabled);
2c08214a 898
4f186b1f
AD
899 // check for user post link to main table
900
2c08214a 901 $query = "SELECT ref_id, int_id FROM ttrss_user_entries WHERE
5bdcb8fd 902 ref_id = '$ref_id' AND owner_uid = '$owner_uid'";
2c08214a
AD
903
904// if ($_REQUEST["xdebug"]) print "$query\n";
905
a42c55f0 906 $result = db_query($query);
2c08214a
AD
907
908 // okay it doesn't exist - create user entry
909 if (db_num_rows($result) == 0) {
910
68cccafc 911 _debug("user record not found, creating...", $debug_enabled);
2c08214a 912
e6c886bf 913 if ($score >= -500 && !RSSUtils::find_article_filter($article_filters, 'catchup') && !$entry_force_catchup) {
2c08214a
AD
914 $unread = 'true';
915 $last_read_qpart = 'NULL';
916 } else {
917 $unread = 'false';
918 $last_read_qpart = 'NOW()';
919 }
920
e6c886bf 921 if (RSSUtils::find_article_filter($article_filters, 'mark') || $score > 1000) {
2c08214a
AD
922 $marked = 'true';
923 } else {
924 $marked = 'false';
925 }
926
e6c886bf 927 if (RSSUtils::find_article_filter($article_filters, 'publish')) {
2c08214a
AD
928 $published = 'true';
929 } else {
930 $published = 'false';
931 }
932
7873d588
AD
933 $last_marked = ($marked == 'true') ? 'NOW()' : 'NULL';
934 $last_published = ($published == 'true') ? 'NOW()' : 'NULL';
935
6322ac79 936 $result = db_query(
2c08214a
AD
937 "INSERT INTO ttrss_user_entries
938 (ref_id, owner_uid, feed_id, unread, last_read, marked,
7873d588
AD
939 published, score, tag_cache, label_cache, uuid,
940 last_marked, last_published)
2c08214a 941 VALUES ('$ref_id', '$owner_uid', '$feed', $unread,
7873d588
AD
942 $last_read_qpart, $marked, $published, '$score', '', '',
943 '', $last_marked, $last_published)");
2c08214a 944
6322ac79 945 $result = db_query(
2c08214a
AD
946 "SELECT int_id FROM ttrss_user_entries WHERE
947 ref_id = '$ref_id' AND owner_uid = '$owner_uid' AND
948 feed_id = '$feed' LIMIT 1");
949
950 if (db_num_rows($result) == 1) {
951 $entry_int_id = db_fetch_result($result, 0, "int_id");
952 }
953 } else {
68cccafc 954 _debug("user record FOUND", $debug_enabled);
2c08214a
AD
955
956 $entry_ref_id = db_fetch_result($result, 0, "ref_id");
957 $entry_int_id = db_fetch_result($result, 0, "int_id");
958 }
959
68cccafc 960 _debug("RID: $entry_ref_id, IID: $entry_int_id", $debug_enabled);
2c08214a 961
e854442e 962 if (DB_TYPE == "pgsql") {
e6c886bf 963 $tsvector_combined = db_escape_string(mb_substr($entry_title . ' ' . strip_tags(str_replace('<', ' <', $entry_content)),
e854442e
AD
964 0, 1000000));
965
df659891 966 $tsvector_qpart = "tsvector_combined = to_tsvector('$feed_language', '$tsvector_combined'),";
e854442e
AD
967
968 } else {
969 $tsvector_qpart = "";
970 }
971
b1840673
AD
972 db_query("UPDATE ttrss_entries
973 SET title = '$entry_title',
974 content = '$entry_content',
975 content_hash = '$entry_current_hash',
976 updated = '$entry_timestamp_fmt',
e854442e 977 $tsvector_qpart
b1840673
AD
978 num_comments = '$num_comments',
979 plugin_data = '$entry_plugin_data',
980 author = '$entry_author',
981 lang = '$entry_language'
982 WHERE id = '$ref_id'");
983
59e83455
AD
984 // update aux data
985 db_query("UPDATE ttrss_user_entries
986 SET score = '$score' WHERE ref_id = '$ref_id'");
987
b1840673 988 if ($mark_unread_on_update) {
24e6ff5d
AD
989 _debug("article updated, marking unread as requested.", $debug_enabled);
990
b1840673
AD
991 db_query("UPDATE ttrss_user_entries
992 SET last_read = null, unread = true WHERE ref_id = '$ref_id'");
2c08214a
AD
993 }
994 }
995
07877caf 996 //db_query("COMMIT");
2c08214a 997
a29fe121
AD
998 _debug("assigning labels [other]...", $debug_enabled);
999
1000 foreach ($article_labels as $label) {
7c9b5a3f 1001 Labels::add_article($entry_ref_id, $label[1], $owner_uid);
a29fe121
AD
1002 }
1003
1004 _debug("assigning labels [filters]...", $debug_enabled);
2c08214a 1005
e6c886bf 1006 RSSUtils::assign_article_to_label_filters($entry_ref_id, $article_filters,
b24504b1 1007 $owner_uid, $article_labels);
2c08214a 1008
68cccafc 1009 _debug("looking for enclosures...", $debug_enabled);
2c08214a
AD
1010
1011 // enclosures
1012
1013 $enclosures = array();
1014
19b3992b 1015 $encs = $item->get_enclosures();
2c08214a 1016
19b3992b
AD
1017 if (is_array($encs)) {
1018 foreach ($encs as $e) {
1019 $e_item = array(
86e53429
AD
1020 rewrite_relative_url($site_url, $e->link),
1021 $e->type, $e->length, $e->title, $e->width, $e->height);
2c08214a 1022 array_push($enclosures, $e_item);
2c08214a
AD
1023 }
1024 }
1025
388d4dfa 1026 if ($cache_images && is_writable(CACHE_DIR . '/images'))
e6c886bf 1027 RSSUtils::cache_enclosures($enclosures, $site_url, $debug_enabled);
388d4dfa 1028
2c08214a 1029 if ($debug_enabled) {
68cccafc 1030 _debug("article enclosures:", $debug_enabled);
2c08214a
AD
1031 print_r($enclosures);
1032 }
1033
dab229cd 1034 //db_query("BEGIN");
2c08214a 1035
5c54e683
AD
1036// debugging
1037// db_query("DELETE FROM ttrss_enclosures WHERE post_id = '$entry_ref_id'");
1038
2c08214a 1039 foreach ($enclosures as $enc) {
a42c55f0
AD
1040 $enc_url = db_escape_string($enc[0]);
1041 $enc_type = db_escape_string($enc[1]);
1042 $enc_dur = db_escape_string($enc[2]);
5c54e683 1043 $enc_title = db_escape_string($enc[3]);
523bd90b
FE
1044 $enc_width = intval($enc[4]);
1045 $enc_height = intval($enc[5]);
2c08214a 1046
a42c55f0 1047 $result = db_query("SELECT id FROM ttrss_enclosures
2c08214a
AD
1048 WHERE content_url = '$enc_url' AND post_id = '$entry_ref_id'");
1049
1050 if (db_num_rows($result) == 0) {
a42c55f0 1051 db_query("INSERT INTO ttrss_enclosures
523bd90b
FE
1052 (content_url, content_type, title, duration, post_id, width, height) VALUES
1053 ('$enc_url', '$enc_type', '$enc_title', '$enc_dur', '$entry_ref_id', $enc_width, $enc_height)");
2c08214a
AD
1054 }
1055 }
1056
dab229cd 1057 //db_query("COMMIT");
2c08214a
AD
1058
1059 // check for manual tags (we have to do it here since they're loaded from filters)
1060
1061 foreach ($article_filters as $f) {
6aff7845 1062 if ($f["type"] == "tag") {
2c08214a 1063
6aff7845 1064 $manual_tags = trim_array(explode(",", $f["param"]));
2c08214a
AD
1065
1066 foreach ($manual_tags as $tag) {
1067 if (tag_is_valid($tag)) {
1068 array_push($entry_tags, $tag);
1069 }
1070 }
1071 }
1072 }
1073
1074 // Skip boring tags
1075
6322ac79 1076 $boring_tags = trim_array(explode(",", mb_strtolower(get_pref(
2c08214a
AD
1077 'BLACKLISTED_TAGS', $owner_uid, ''), 'utf-8')));
1078
1079 $filtered_tags = array();
1080 $tags_to_cache = array();
1081
1082 if ($entry_tags && is_array($entry_tags)) {
1083 foreach ($entry_tags as $tag) {
1084 if (array_search($tag, $boring_tags) === false) {
1085 array_push($filtered_tags, $tag);
1086 }
1087 }
1088 }
1089
1090 $filtered_tags = array_unique($filtered_tags);
1091
1092 if ($debug_enabled) {
68cccafc 1093 _debug("filtered article tags:", $debug_enabled);
2c08214a
AD
1094 print_r($filtered_tags);
1095 }
1096
1097 // Save article tags in the database
1098
1099 if (count($filtered_tags) > 0) {
1100
dab229cd 1101 //db_query("BEGIN");
2c08214a
AD
1102
1103 foreach ($filtered_tags as $tag) {
1104
1105 $tag = sanitize_tag($tag);
a42c55f0 1106 $tag = db_escape_string($tag);
2c08214a
AD
1107
1108 if (!tag_is_valid($tag)) continue;
1109
a42c55f0 1110 $result = db_query("SELECT id FROM ttrss_tags
2c08214a
AD
1111 WHERE tag_name = '$tag' AND post_int_id = '$entry_int_id' AND
1112 owner_uid = '$owner_uid' LIMIT 1");
1113
e6c886bf 1114 if ($result && db_num_rows($result) == 0) {
2c08214a 1115
e6c886bf 1116 db_query("INSERT INTO ttrss_tags
2c08214a
AD
1117 (owner_uid,tag_name,post_int_id)
1118 VALUES ('$owner_uid','$tag', '$entry_int_id')");
e6c886bf 1119 }
2c08214a
AD
1120
1121 array_push($tags_to_cache, $tag);
1122 }
1123
1124 /* update the cache */
1125
1126 $tags_to_cache = array_unique($tags_to_cache);
1127
a42c55f0 1128 $tags_str = db_escape_string(join(",", $tags_to_cache));
2c08214a 1129
a42c55f0 1130 db_query("UPDATE ttrss_user_entries
2c08214a
AD
1131 SET tag_cache = '$tags_str' WHERE ref_id = '$entry_ref_id'
1132 AND owner_uid = $owner_uid");
1133
dab229cd 1134 //db_query("COMMIT");
2c08214a
AD
1135 }
1136
68cccafc 1137 _debug("article processed", $debug_enabled);
2c08214a
AD
1138 }
1139
68cccafc 1140 _debug("purging feed...", $debug_enabled);
2c08214a 1141
a42c55f0 1142 purge_feed($feed, 0, $debug_enabled);
2c08214a 1143
a42c55f0 1144 db_query("UPDATE ttrss_feeds
e50c8eaa 1145 SET last_updated = NOW(), last_unconditional = NOW(), last_error = '' WHERE id = '$feed'");
2c08214a 1146
a42c55f0 1147// db_query("COMMIT");
2c08214a
AD
1148
1149 } else {
1150
a42c55f0 1151 $error_msg = db_escape_string(mb_substr($rss->error(), 0, 245));
2c08214a 1152
4ad04ee2
AD
1153 _debug("fetch error: $error_msg", $debug_enabled);
1154
1155 if (count($rss->errors()) > 1) {
1156 foreach ($rss->errors() as $error) {
1157 _debug("+ $error");
1158 }
1159 }
2c08214a 1160
6322ac79 1161 db_query(
2c08214a 1162 "UPDATE ttrss_feeds SET last_error = '$error_msg',
e50c8eaa 1163 last_updated = NOW(), last_unconditional = NOW() WHERE id = '$feed'");
2c08214a 1164
88edaa93 1165 unset($rss);
7b55001e 1166 return;
88edaa93 1167 }
2c08214a 1168
68cccafc 1169 _debug("done", $debug_enabled);
88edaa93 1170
7b55001e 1171 return true;
2c08214a
AD
1172 }
1173
e6c886bf 1174 static function cache_enclosures($enclosures, $site_url, $debug) {
388d4dfa
AD
1175 foreach ($enclosures as $enc) {
1176
1177 if (preg_match("/(image|audio|video)/", $enc[1])) {
1178
1179 $src = rewrite_relative_url($site_url, $enc[0]);
1180
1181 $local_filename = CACHE_DIR . "/images/" . sha1($src);
1182
1183 if ($debug) _debug("cache_enclosures: downloading: $src to $local_filename");
1184
1185 if (!file_exists($local_filename)) {
1186 $file_content = fetch_file_contents($src);
1187
6fd03996 1188 if ($file_content && strlen($file_content) > MIN_CACHE_FILE_SIZE) {
388d4dfa
AD
1189 file_put_contents($local_filename, $file_content);
1190 }
1191 } else {
1192 touch($local_filename);
1193 }
1194 }
1195 }
1196 }
1197
e6c886bf 1198 static function cache_media($html, $site_url, $debug) {
3c696512
AD
1199 libxml_use_internal_errors(true);
1200
1201 $charset_hack = '<head>
1202 <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
1203 </head>';
1204
1205 $doc = new DOMDocument();
1206 $doc->loadHTML($charset_hack . $html);
1207 $xpath = new DOMXPath($doc);
1208
388d4dfa 1209 $entries = $xpath->query('(//img[@src])|(//video/source[@src])|(//audio/source[@src])');
3c696512
AD
1210
1211 foreach ($entries as $entry) {
5edd605a 1212 if ($entry->hasAttribute('src') && strpos($entry->getAttribute('src'), "data:") !== 0) {
3c696512
AD
1213 $src = rewrite_relative_url($site_url, $entry->getAttribute('src'));
1214
41bead9b 1215 $local_filename = CACHE_DIR . "/images/" . sha1($src);
3c696512 1216
41bead9b 1217 if ($debug) _debug("cache_media: downloading: $src to $local_filename");
3c696512
AD
1218
1219 if (!file_exists($local_filename)) {
1220 $file_content = fetch_file_contents($src);
1221
6fd03996 1222 if ($file_content && strlen($file_content) > MIN_CACHE_FILE_SIZE) {
3c696512
AD
1223 file_put_contents($local_filename, $file_content);
1224 }
4a27966e
J
1225 } else {
1226 touch($local_filename);
3c696512 1227 }
3c696512
AD
1228 }
1229 }
3c696512
AD
1230 }
1231
e6c886bf 1232 static function expire_error_log($debug) {
e2261e17
AD
1233 if ($debug) _debug("Removing old error log entries...");
1234
1235 if (DB_TYPE == "pgsql") {
a42c55f0 1236 db_query("DELETE FROM ttrss_error_log
e2261e17
AD
1237 WHERE created_at < NOW() - INTERVAL '7 days'");
1238 } else {
a42c55f0 1239 db_query("DELETE FROM ttrss_error_log
e2261e17
AD
1240 WHERE created_at < DATE_SUB(NOW(), INTERVAL 7 DAY)");
1241 }
1242
1243 }
1244
e6c886bf 1245 static function expire_lock_files($debug) {
65465085 1246 //if ($debug) _debug("Removing old lock files...");
2a91b6ff
AD
1247
1248 $num_deleted = 0;
1249
1250 if (is_writable(LOCK_DIRECTORY)) {
1251 $files = glob(LOCK_DIRECTORY . "/*.lock");
1252
1253 if ($files) {
1254 foreach ($files as $file) {
11344971 1255 if (!file_is_locked(basename($file)) && time() - filemtime($file) > 86400*2) {
2a91b6ff
AD
1256 unlink($file);
1257 ++$num_deleted;
1258 }
1259 }
1260 }
1261 }
1262
65465085 1263 if ($debug) _debug("Removed $num_deleted old lock files.");
2a91b6ff
AD
1264 }
1265
e6c886bf 1266 static function expire_cached_files($debug) {
3306daec 1267 foreach (array("simplepie", "images", "export", "upload") as $dir) {
3c696512 1268 $cache_dir = CACHE_DIR . "/$dir";
2c08214a 1269
65465085 1270// if ($debug) _debug("Expiring $cache_dir");
2c08214a 1271
3c696512
AD
1272 $num_deleted = 0;
1273
1274 if (is_writable($cache_dir)) {
1275 $files = glob("$cache_dir/*");
1276
2a91b6ff 1277 if ($files) {
2ab20c31 1278 foreach ($files as $file) {
6fd03996 1279 if (time() - filemtime($file) > 86400*CACHE_MAX_DAYS) {
2ab20c31 1280 unlink($file);
3c696512 1281
2ab20c31
AD
1282 ++$num_deleted;
1283 }
3c696512
AD
1284 }
1285 }
2a91b6ff 1286 }
3c696512 1287
65465085 1288 if ($debug) _debug("$cache_dir: removed $num_deleted files.");
3c696512
AD
1289 }
1290 }
2c08214a 1291
a3e0bdcf 1292 /**
e6c886bf
AD
1293 * Source: http://www.php.net/manual/en/function.parse-url.php#104527
1294 * Returns the url query as associative array
1295 *
1296 * @param string query
1297 * @return array params
1298 */
1299 static function convertUrlQuery($query) {
a3e0bdcf
AD
1300 $queryParts = explode('&', $query);
1301
1302 $params = array();
1303
1304 foreach ($queryParts as $param) {
1305 $item = explode('=', $param);
1306 $params[$item[0]] = $item[1];
1307 }
1308
1309 return $params;
1310 }
92c14e9d 1311
e6c886bf 1312 static function get_article_filters($filters, $title, $content, $link, $author, $tags, &$matched_rules = false) {
92c14e9d
AD
1313 $matches = array();
1314
1315 foreach ($filters as $filter) {
1316 $match_any_rule = $filter["match_any_rule"];
a3a896a1 1317 $inverse = $filter["inverse"];
92c14e9d
AD
1318 $filter_match = false;
1319
1320 foreach ($filter["rules"] as $rule) {
1321 $match = false;
ffa1bd7b 1322 $reg_exp = str_replace('/', '\/', $rule["reg_exp"]);
a3a896a1 1323 $rule_inverse = $rule["inverse"];
92c14e9d
AD
1324
1325 if (!$reg_exp)
1326 continue;
1327
1328 switch ($rule["type"]) {
e6c886bf
AD
1329 case "title":
1330 $match = @preg_match("/$reg_exp/iu", $title);
1331 break;
1332 case "content":
1333 // we don't need to deal with multiline regexps
1334 $content = preg_replace("/[\r\n\t]/", "", $content);
d03ae73e 1335
e6c886bf
AD
1336 $match = @preg_match("/$reg_exp/iu", $content);
1337 break;
1338 case "both":
1339 // we don't need to deal with multiline regexps
1340 $content = preg_replace("/[\r\n\t]/", "", $content);
d03ae73e 1341
e6c886bf
AD
1342 $match = (@preg_match("/$reg_exp/iu", $title) || @preg_match("/$reg_exp/iu", $content));
1343 break;
1344 case "link":
1345 $match = @preg_match("/$reg_exp/iu", $link);
1346 break;
1347 case "author":
1348 $match = @preg_match("/$reg_exp/iu", $author);
1349 break;
1350 case "tag":
1351 foreach ($tags as $tag) {
1352 if (@preg_match("/$reg_exp/iu", $tag)) {
1353 $match = true;
1354 break;
1355 }
7b80b5e1 1356 }
e6c886bf 1357 break;
92c14e9d
AD
1358 }
1359
a3a896a1
AD
1360 if ($rule_inverse) $match = !$match;
1361
92c14e9d
AD
1362 if ($match_any_rule) {
1363 if ($match) {
1364 $filter_match = true;
1365 break;
1366 }
1367 } else {
1368 $filter_match = $match;
1369 if (!$match) {
1370 break;
1371 }
1372 }
1373 }
1374
a3a896a1
AD
1375 if ($inverse) $filter_match = !$filter_match;
1376
92c14e9d 1377 if ($filter_match) {
557d86fe
AD
1378 if (is_array($matched_rules)) array_push($matched_rules, $rule);
1379
92c14e9d
AD
1380 foreach ($filter["actions"] AS $action) {
1381 array_push($matches, $action);
5e736e45
AD
1382
1383 // if Stop action encountered, perform no further processing
fd3e5e8d 1384 if (isset($action["type"]) && $action["type"] == "stop") return $matches;
92c14e9d
AD
1385 }
1386 }
1387 }
1388
1389 return $matches;
1390 }
1391
e6c886bf 1392 static function find_article_filter($filters, $filter_name) {
92c14e9d
AD
1393 foreach ($filters as $f) {
1394 if ($f["type"] == $filter_name) {
1395 return $f;
1396 };
1397 }
1398 return false;
1399 }
1400
e6c886bf 1401 static function find_article_filters($filters, $filter_name) {
92c14e9d
AD
1402 $results = array();
1403
1404 foreach ($filters as $f) {
1405 if ($f["type"] == $filter_name) {
1406 array_push($results, $f);
1407 };
1408 }
1409 return $results;
1410 }
1411
e6c886bf 1412 static function calculate_article_score($filters) {
92c14e9d
AD
1413 $score = 0;
1414
1415 foreach ($filters as $f) {
1416 if ($f["type"] == "score") {
1417 $score += $f["param"];
1418 };
1419 }
1420 return $score;
1421 }
1422
e6c886bf 1423 static function labels_contains_caption($labels, $caption) {
b24504b1
AD
1424 foreach ($labels as $label) {
1425 if ($label[1] == $caption) {
1426 return true;
1427 }
1428 }
1429
1430 return false;
1431 }
1432
e6c886bf 1433 static function assign_article_to_label_filters($id, $filters, $owner_uid, $article_labels) {
92c14e9d
AD
1434 foreach ($filters as $f) {
1435 if ($f["type"] == "label") {
e6c886bf 1436 if (!RSSUtils::labels_contains_caption($article_labels, $f["param"])) {
7c9b5a3f 1437 Labels::add_article($id, $f["param"], $owner_uid);
b24504b1
AD
1438 }
1439 }
92c14e9d
AD
1440 }
1441 }
87764a50 1442
e6c886bf 1443 static function make_guid_from_title($title) {
87d7e850
AD
1444 return preg_replace("/[ \"\',.:;]/", "-",
1445 mb_strtolower(strip_tags($title), 'utf-8'));
1446 }
1447
e6c886bf 1448 static function cleanup_counters_cache($debug) {
168cf351
AD
1449 $result = db_query("DELETE FROM ttrss_counters_cache
1450 WHERE feed_id > 0 AND
1451 (SELECT COUNT(id) FROM ttrss_feeds WHERE
1452 id = feed_id AND
1453 ttrss_counters_cache.owner_uid = ttrss_feeds.owner_uid) = 0");
1454 $frows = db_affected_rows($result);
1455
1456 $result = db_query("DELETE FROM ttrss_cat_counters_cache
1457 WHERE feed_id > 0 AND
1458 (SELECT COUNT(id) FROM ttrss_feed_categories WHERE
1459 id = feed_id AND
1460 ttrss_cat_counters_cache.owner_uid = ttrss_feed_categories.owner_uid) = 0");
1461 $crows = db_affected_rows($result);
1462
7b55001e 1463 if ($debug) _debug("Removed $frows (feeds) $crows (cats) orphaned counter cache entries.");
168cf351
AD
1464 }
1465
e6c886bf 1466 static function housekeeping_user($owner_uid) {
5cbd1fe8
AD
1467 $tmph = new PluginHost();
1468
1469 load_user_plugins($owner_uid, $tmph);
1470
1471 $tmph->run_hooks(PluginHost::HOOK_HOUSE_KEEPING, "hook_house_keeping", "");
1472 }
1473
e6c886bf
AD
1474 static function housekeeping_common($debug) {
1475 RSSUtils::expire_cached_files($debug);
1476 RSSUtils::expire_lock_files($debug);
1477 RSSUtils::expire_error_log($debug);
e2cf81e2 1478
e6c886bf 1479 $count = RSSUtils::update_feedbrowser_cache();
e2cf81e2
AD
1480 _debug("Feedbrowser updated, $count feeds processed.");
1481
a230bf88 1482 Article::purge_orphans( true);
e6c886bf 1483 RSSUtils::cleanup_counters_cache($debug);
e2cf81e2 1484
9b736a20
AD
1485 //$rc = cleanup_tags( 14, 50000);
1486 //_debug("Cleaned $rc cached tags.");
8e470220 1487
00f22824 1488 PluginHost::getInstance()->run_hooks(PluginHost::HOOK_HOUSE_KEEPING, "hook_house_keeping", "");
e2cf81e2 1489 }
ea79a0e0 1490
e6c886bf
AD
1491 static function check_feed_favicon($site_url, $feed) {
1492 # print "FAVICON [$site_url]: $favicon_url\n";
a230bf88
AD
1493
1494 $icon_file = ICONS_DIR . "/$feed.ico";
1495
1496 if (!file_exists($icon_file)) {
1497 $favicon_url = get_favicon_url($site_url);
1498
1499 if ($favicon_url) {
1500 // Limiting to "image" type misses those served with text/plain
1501 $contents = fetch_file_contents($favicon_url); // , "image");
1502
1503 if ($contents) {
1504 // Crude image type matching.
1505 // Patterns gleaned from the file(1) source code.
1506 if (preg_match('/^\x00\x00\x01\x00/', $contents)) {
1507 // 0 string \000\000\001\000 MS Windows icon resource
1508 //error_log("check_feed_favicon: favicon_url=$favicon_url isa MS Windows icon resource");
1509 }
1510 elseif (preg_match('/^GIF8/', $contents)) {
1511 // 0 string GIF8 GIF image data
1512 //error_log("check_feed_favicon: favicon_url=$favicon_url isa GIF image");
1513 }
1514 elseif (preg_match('/^\x89PNG\x0d\x0a\x1a\x0a/', $contents)) {
1515 // 0 string \x89PNG\x0d\x0a\x1a\x0a PNG image data
1516 //error_log("check_feed_favicon: favicon_url=$favicon_url isa PNG image");
1517 }
1518 elseif (preg_match('/^\xff\xd8/', $contents)) {
1519 // 0 beshort 0xffd8 JPEG image data
1520 //error_log("check_feed_favicon: favicon_url=$favicon_url isa JPG image");
1521 }
f9ad33c2
GG
1522 elseif (preg_match('/^BM/', $contents)) {
1523 // 0 string BM PC bitmap (OS2, Windows BMP files)
1524 //error_log("check_feed_favicon, favicon_url=$favicon_url isa BMP image");
1525 }
a230bf88
AD
1526 else {
1527 //error_log("check_feed_favicon: favicon_url=$favicon_url isa UNKNOWN type");
1528 $contents = "";
1529 }
1530 }
1531
1532 if ($contents) {
1533 $fp = @fopen($icon_file, "w");
1534
1535 if ($fp) {
1536 fwrite($fp, $contents);
1537 fclose($fp);
1538 chmod($icon_file, 0644);
1539 }
1540 }
1541 }
1542 return $icon_file;
1543 }
1544 }
e6c886bf
AD
1545
1546
1547
bec5ba93 1548}