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