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