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