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