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