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