]> git.wh0rd.org - tt-rss.git/blob - include/rssfuncs.php
when purging inactive feeds, set last_updated to NOW()
[tt-rss.git] / include / rssfuncs.php
1 <?php
2 define('DAEMON_UPDATE_LOGIN_LIMIT', 30);
3 define('DAEMON_FEED_LIMIT', 100);
4 define('DAEMON_SLEEP_INTERVAL', 60);
5
6 function update_feedbrowser_cache($link) {
7
8 $result = db_query($link, "SELECT feed_url, site_url, title, COUNT(id) AS subscribers
9 FROM ttrss_feeds WHERE (SELECT COUNT(id) = 0 FROM ttrss_feeds AS tf
10 WHERE tf.feed_url = ttrss_feeds.feed_url
11 AND (private IS true OR auth_login != '' OR auth_pass != '' OR feed_url LIKE '%:%@%/%'))
12 GROUP BY feed_url, site_url, title ORDER BY subscribers DESC LIMIT 1000");
13
14 db_query($link, "BEGIN");
15
16 db_query($link, "DELETE FROM ttrss_feedbrowser_cache");
17
18 $count = 0;
19
20 while ($line = db_fetch_assoc($result)) {
21 $subscribers = db_escape_string($line["subscribers"]);
22 $feed_url = db_escape_string($line["feed_url"]);
23 $title = db_escape_string($line["title"]);
24 $site_url = db_escape_string($line["site_url"]);
25
26 $tmp_result = db_query($link, "SELECT subscribers FROM
27 ttrss_feedbrowser_cache WHERE feed_url = '$feed_url'");
28
29 if (db_num_rows($tmp_result) == 0) {
30
31 db_query($link, "INSERT INTO ttrss_feedbrowser_cache
32 (feed_url, site_url, title, subscribers) VALUES ('$feed_url',
33 '$site_url', '$title', '$subscribers')");
34
35 ++$count;
36
37 }
38
39 }
40
41 db_query($link, "COMMIT");
42
43 return $count;
44
45 }
46
47
48 /**
49 * Update a feed batch.
50 * Used by daemons to update n feeds by run.
51 * Only update feed needing a update, and not being processed
52 * by another process.
53 *
54 * @param mixed $link Database link
55 * @param integer $limit Maximum number of feeds in update batch. Default to DAEMON_FEED_LIMIT.
56 * @param boolean $from_http Set to true if you call this function from http to disable cli specific code.
57 * @param boolean $debug Set to false to disable debug output. Default to true.
58 * @return void
59 */
60 function update_daemon_common($link, $limit = DAEMON_FEED_LIMIT, $from_http = false, $debug = true) {
61 // Process all other feeds using last_updated and interval parameters
62
63 define('PREFS_NO_CACHE', true);
64
65 // Test if the user has loggued in recently. If not, it does not update its feeds.
66 if (!SINGLE_USER_MODE && DAEMON_UPDATE_LOGIN_LIMIT > 0) {
67 if (DB_TYPE == "pgsql") {
68 $login_thresh_qpart = "AND ttrss_users.last_login >= NOW() - INTERVAL '".DAEMON_UPDATE_LOGIN_LIMIT." days'";
69 } else {
70 $login_thresh_qpart = "AND ttrss_users.last_login >= DATE_SUB(NOW(), INTERVAL ".DAEMON_UPDATE_LOGIN_LIMIT." DAY)";
71 }
72 } else {
73 $login_thresh_qpart = "";
74 }
75
76 // Test if the feed need a update (update interval exceded).
77 if (DB_TYPE == "pgsql") {
78 $update_limit_qpart = "AND ((
79 ttrss_feeds.update_interval = 0
80 AND ttrss_feeds.last_updated < NOW() - CAST((ttrss_user_prefs.value || ' minutes') AS INTERVAL)
81 ) OR (
82 ttrss_feeds.update_interval > 0
83 AND ttrss_feeds.last_updated < NOW() - CAST((ttrss_feeds.update_interval || ' minutes') AS INTERVAL)
84 ) OR ttrss_feeds.last_updated IS NULL
85 OR last_updated = '1970-01-01 00:00:00')";
86 } else {
87 $update_limit_qpart = "AND ((
88 ttrss_feeds.update_interval = 0
89 AND ttrss_feeds.last_updated < DATE_SUB(NOW(), INTERVAL CONVERT(ttrss_user_prefs.value, SIGNED INTEGER) MINUTE)
90 ) OR (
91 ttrss_feeds.update_interval > 0
92 AND ttrss_feeds.last_updated < DATE_SUB(NOW(), INTERVAL ttrss_feeds.update_interval MINUTE)
93 ) OR ttrss_feeds.last_updated IS NULL
94 OR last_updated = '1970-01-01 00:00:00')";
95 }
96
97 // Test if feed is currently being updated by another process.
98 if (DB_TYPE == "pgsql") {
99 $updstart_thresh_qpart = "AND (ttrss_feeds.last_update_started IS NULL OR ttrss_feeds.last_update_started < NOW() - INTERVAL '5 minutes')";
100 } else {
101 $updstart_thresh_qpart = "AND (ttrss_feeds.last_update_started IS NULL OR ttrss_feeds.last_update_started < DATE_SUB(NOW(), INTERVAL 5 MINUTE))";
102 }
103
104 // Test if there is a limit to number of updated feeds
105 $query_limit = "";
106 if($limit) $query_limit = sprintf("LIMIT %d", $limit);
107
108 $random_qpart = sql_random_function();
109
110 // We search for feed needing update.
111 $result = db_query($link, "SELECT ttrss_feeds.feed_url,ttrss_feeds.id, ttrss_feeds.owner_uid,
112 ".SUBSTRING_FOR_DATE."(ttrss_feeds.last_updated,1,19) AS last_updated,
113 ttrss_feeds.update_interval
114 FROM
115 ttrss_feeds, ttrss_users, ttrss_user_prefs
116 WHERE
117 ttrss_feeds.owner_uid = ttrss_users.id
118 AND ttrss_users.id = ttrss_user_prefs.owner_uid
119 AND ttrss_user_prefs.pref_name = 'DEFAULT_UPDATE_INTERVAL'
120 $login_thresh_qpart $update_limit_qpart
121 $updstart_thresh_qpart
122 ORDER BY $random_qpart $query_limit");
123
124 $user_prefs_cache = array();
125
126 if($debug) _debug(sprintf("Scheduled %d feeds to update...\n", db_num_rows($result)));
127
128 // Here is a little cache magic in order to minimize risk of double feed updates.
129 $feeds_to_update = array();
130 while ($line = db_fetch_assoc($result)) {
131 $feeds_to_update[$line['id']] = $line;
132 }
133
134 // We update the feed last update started date before anything else.
135 // There is no lag due to feed contents downloads
136 // It prevent an other process to update the same feed.
137 $feed_ids = array_keys($feeds_to_update);
138 if($feed_ids) {
139 db_query($link, sprintf("UPDATE ttrss_feeds SET last_update_started = NOW()
140 WHERE id IN (%s)", implode(',', $feed_ids)));
141 }
142
143 expire_cached_files($debug);
144 expire_lock_files($debug);
145
146 // For each feed, we call the feed update function.
147 while ($line = array_pop($feeds_to_update)) {
148
149 if($debug) _debug("Feed: " . $line["feed_url"] . ", " . $line["last_updated"]);
150
151 update_rss_feed($link, $line["id"], true);
152
153 sleep(1); // prevent flood (FIXME make this an option?)
154 }
155
156 require_once "digest.php";
157
158 // Send feed digests by email if needed.
159 send_headlines_digests($link, $debug);
160
161 // Purge feeds with stale data OR not being updated for a while to keep DB size down
162
163 if ($debug) _debug("Purging inactive feeds...");
164
165 if (DB_TYPE == "pgsql") {
166 $interval_qpart = "NOW() - INTERVAL '1 month'";
167 } else {
168 $interval_qpart = "DATE_SUB(NOW(), INTERVAL 1 MONTH)";
169 }
170
171 $result = db_query($link, "SELECT id, feed_url FROM ttrss_feeds WHERE
172 (SELECT MAX(updated) FROM ttrss_entries, ttrss_user_entries WHERE
173 ttrss_entries.id = ref_id AND
174 ttrss_user_entries.feed_id = ttrss_feeds.id) < $interval_qpart OR
175 last_updated < $interval_qpart");
176
177 $feeds_purged = 0;
178 $articles_removed = 0;
179
180 while ($line = db_fetch_assoc($result)) {
181 $articles_removed += purge_feed($link, $line["id"], 0, false);
182
183 db_query($link, "UPDATE ttrss_feeds SET last_updated = NOW() WHERE
184 id = " . $line["id"]);
185
186 ++$feeds_purged;
187 }
188
189 if ($debug && $articles_removed > 0)
190 _debug(sprintf("Purged %d feeds (%d articles).", $feeds_purged,
191 $articles_removed));
192
193 } // function update_daemon_common
194
195 // ignore_daemon is not used
196 function update_rss_feed($link, $feed, $ignore_daemon = false, $no_cache = false,
197 $override_url = false) {
198
199 require_once "lib/simplepie/simplepie.inc";
200
201 $debug_enabled = defined('DAEMON_EXTENDED_DEBUG') || $_REQUEST['xdebug'];
202
203 if ($debug_enabled) {
204 _debug("update_rss_feed: start");
205 }
206
207 $result = db_query($link, "SELECT id,update_interval,auth_login,
208 feed_url,auth_pass,cache_images,last_updated,
209 mark_unread_on_update, owner_uid,
210 pubsub_state
211 FROM ttrss_feeds WHERE id = '$feed'");
212
213 if (db_num_rows($result) == 0) {
214 if ($debug_enabled) {
215 _debug("update_rss_feed: feed $feed NOT FOUND/SKIPPED");
216 }
217 return false;
218 }
219
220 $last_updated = db_fetch_result($result, 0, "last_updated");
221 $owner_uid = db_fetch_result($result, 0, "owner_uid");
222 $mark_unread_on_update = sql_bool_to_bool(db_fetch_result($result,
223 0, "mark_unread_on_update"));
224 $pubsub_state = db_fetch_result($result, 0, "pubsub_state");
225
226 db_query($link, "UPDATE ttrss_feeds SET last_update_started = NOW()
227 WHERE id = '$feed'");
228
229 $auth_login = db_fetch_result($result, 0, "auth_login");
230 $auth_pass = db_fetch_result($result, 0, "auth_pass");
231
232 $cache_images = sql_bool_to_bool(db_fetch_result($result, 0, "cache_images"));
233 $fetch_url = db_fetch_result($result, 0, "feed_url");
234
235 $feed = db_escape_string($feed);
236
237 /* if ($auth_login && $auth_pass ){
238 $url_parts = array();
239 preg_match("/(^[^:]*):\/\/(.*)/", $fetch_url, $url_parts);
240
241 if ($url_parts[1] && $url_parts[2]) {
242 $fetch_url = $url_parts[1] . "://$auth_login:$auth_pass@" . $url_parts[2];
243 }
244 } */
245
246 if ($override_url)
247 $fetch_url = $override_url;
248
249 if ($debug_enabled) {
250 _debug("update_rss_feed: fetching [$fetch_url]...");
251 }
252
253 // Ignore cache if new feed or manual update.
254 $cache_age = (is_null($last_updated) || $last_updated == '1970-01-01 00:00:00') ?
255 -1 : get_feed_update_interval($link, $feed) * 60;
256
257 $simplepie_cache_dir = CACHE_DIR . "/simplepie";
258
259 if (!is_dir($simplepie_cache_dir)) {
260 mkdir($simplepie_cache_dir);
261 }
262
263 $feed_data = fetch_file_contents($fetch_url, false,
264 $auth_login, $auth_pass, false, $no_cache ? 15 : 45);
265
266 if (!$feed_data) {
267 global $fetch_last_error;
268
269 if ($debug_enabled) {
270 _debug("update_rss_feed: unable to fetch: $fetch_last_error");
271 }
272
273 db_query($link,
274 "UPDATE ttrss_feeds SET last_error = '$fetch_last_error',
275 last_updated = NOW() WHERE id = '$feed'");
276
277 return;
278 }
279
280 $pluginhost = new PluginHost($link);
281 $pluginhost->set_debug($debug_enabled);
282 $user_plugins = get_pref($link, "_ENABLED_PLUGINS", $owner_uid);
283
284 $pluginhost->load(PLUGINS, $pluginhost::KIND_ALL);
285 $pluginhost->load($user_plugins, $pluginhost::KIND_USER, $owner_uid);
286 $pluginhost->load_data();
287
288 foreach ($pluginhost->get_hooks($pluginhost::HOOK_FEED_FETCHED) as $plugin) {
289 $feed_data = $plugin->hook_feed_fetched($feed_data);
290 }
291
292 if ($debug_enabled) {
293 _debug("update_rss_feed: fetch done, parsing...");
294 }
295
296 $rss = new SimplePie();
297 $rss->set_sanitize_class("SanitizeDummy");
298 // simplepie ignores the above and creates default sanitizer anyway,
299 // so let's override it...
300 $rss->sanitize = new SanitizeDummy();
301 $rss->set_output_encoding('UTF-8');
302 $rss->set_raw_data($feed_data);
303
304 if ($debug_enabled) {
305 _debug("feed update interval (sec): " .
306 get_feed_update_interval($link, $feed)*60);
307 }
308
309 $rss->enable_cache(!$no_cache);
310
311 if (!$no_cache) {
312 $rss->set_cache_location($simplepie_cache_dir);
313 $rss->set_cache_duration($cache_age);
314 }
315
316 @$rss->init();
317
318 // print_r($rss);
319
320 $feed = db_escape_string($feed);
321
322 if (!$rss->error()) {
323
324 // We use local pluginhost here because we need to load different per-user feed plugins
325 $pluginhost->run_hooks($pluginhost::HOOK_FEED_PARSED, "hook_feed_parsed", $rss);
326
327 if ($debug_enabled) {
328 _debug("update_rss_feed: processing feed data...");
329 }
330
331 // db_query($link, "BEGIN");
332
333 if (DB_TYPE == "pgsql") {
334 $favicon_interval_qpart = "favicon_last_checked < NOW() - INTERVAL '12 hour'";
335 } else {
336 $favicon_interval_qpart = "favicon_last_checked < DATE_SUB(NOW(), INTERVAL 12 HOUR)";
337 }
338
339 $result = db_query($link, "SELECT title,site_url,owner_uid,
340 (favicon_last_checked IS NULL OR $favicon_interval_qpart) AS
341 favicon_needs_check
342 FROM ttrss_feeds WHERE id = '$feed'");
343
344 $registered_title = db_fetch_result($result, 0, "title");
345 $orig_site_url = db_fetch_result($result, 0, "site_url");
346 $favicon_needs_check = sql_bool_to_bool(db_fetch_result($result, 0,
347 "favicon_needs_check"));
348
349 $owner_uid = db_fetch_result($result, 0, "owner_uid");
350
351 $site_url = db_escape_string(mb_substr(rewrite_relative_url($fetch_url, $rss->get_link()), 0, 245));
352
353 if ($debug_enabled) {
354 _debug("update_rss_feed: checking favicon...");
355 }
356
357 if ($favicon_needs_check) {
358 check_feed_favicon($site_url, $feed, $link);
359
360 db_query($link, "UPDATE ttrss_feeds SET favicon_last_checked = NOW()
361 WHERE id = '$feed'");
362 }
363
364 if (!$registered_title || $registered_title == "[Unknown]") {
365
366 $feed_title = db_escape_string($rss->get_title());
367
368 if ($debug_enabled) {
369 _debug("update_rss_feed: registering title: $feed_title");
370 }
371
372 db_query($link, "UPDATE ttrss_feeds SET
373 title = '$feed_title' WHERE id = '$feed'");
374 }
375
376 if ($site_url && $orig_site_url != $site_url) {
377 db_query($link, "UPDATE ttrss_feeds SET
378 site_url = '$site_url' WHERE id = '$feed'");
379 }
380
381 if ($debug_enabled) {
382 _debug("update_rss_feed: loading filters & labels...");
383 }
384
385 $filters = load_filters($link, $feed, $owner_uid);
386 $labels = get_all_labels($link, $owner_uid);
387
388 if ($debug_enabled) {
389 //print_r($filters);
390 _debug("update_rss_feed: " . count($filters) . " filters loaded.");
391 }
392
393 $items = $rss->get_items();
394
395 if (!is_array($items)) {
396 if ($debug_enabled) {
397 _debug("update_rss_feed: no articles found.");
398 }
399
400 db_query($link, "UPDATE ttrss_feeds
401 SET last_updated = NOW(), last_error = '' WHERE id = '$feed'");
402
403 return; // no articles
404 }
405
406 if ($pubsub_state != 2 && PUBSUBHUBBUB_ENABLED) {
407
408 if ($debug_enabled) _debug("update_rss_feed: checking for PUSH hub...");
409
410 $feed_hub_url = false;
411
412 $links = $rss->get_links('hub');
413
414 if ($links && is_array($links)) {
415 foreach ($links as $l) {
416 $feed_hub_url = $l;
417 break;
418 }
419 }
420
421 if ($debug_enabled) _debug("update_rss_feed: feed hub url: $feed_hub_url");
422
423 if ($feed_hub_url && function_exists('curl_init') &&
424 !ini_get("open_basedir")) {
425
426 require_once 'lib/pubsubhubbub/subscriber.php';
427
428 $callback_url = get_self_url_prefix() .
429 "/public.php?op=pubsub&id=$feed";
430
431 $s = new Subscriber($feed_hub_url, $callback_url);
432
433 $rc = $s->subscribe($fetch_url);
434
435 if ($debug_enabled)
436 _debug("update_rss_feed: feed hub url found, subscribe request sent.");
437
438 db_query($link, "UPDATE ttrss_feeds SET pubsub_state = 1
439 WHERE id = '$feed'");
440 }
441 }
442
443 if ($debug_enabled) {
444 _debug("update_rss_feed: processing articles...");
445 }
446
447 foreach ($items as $item) {
448 if ($_REQUEST['xdebug'] == 3) {
449 print_r($item);
450 }
451
452 $entry_guid = $item->get_id();
453 if (!$entry_guid) $entry_guid = $item->get_link();
454 if (!$entry_guid) $entry_guid = make_guid_from_title($item->get_title());
455
456 if ($debug_enabled) {
457 _debug("update_rss_feed: guid $entry_guid");
458 }
459
460 if (!$entry_guid) continue;
461
462 $entry_guid = "$owner_uid,$entry_guid";
463
464 $entry_timestamp = "";
465
466 $entry_timestamp = strtotime($item->get_date());
467
468 if ($entry_timestamp == -1 || !$entry_timestamp) {
469 $entry_timestamp = time();
470 $no_orig_date = 'true';
471 } else {
472 $no_orig_date = 'false';
473 }
474
475 $entry_timestamp_fmt = strftime("%Y/%m/%d %H:%M:%S", $entry_timestamp);
476
477 if ($debug_enabled) {
478 _debug("update_rss_feed: date $entry_timestamp [$entry_timestamp_fmt]");
479 }
480
481 $entry_title = $item->get_title();
482
483 $entry_link = rewrite_relative_url($site_url, $item->get_link());
484
485 if ($debug_enabled) {
486 _debug("update_rss_feed: title $entry_title");
487 _debug("update_rss_feed: link $entry_link");
488 }
489
490 if (!$entry_title) $entry_title = date("Y-m-d H:i:s", $entry_timestamp);;
491
492 $entry_content = $item->get_content();
493 if (!$entry_content) $entry_content = $item->get_description();
494
495 if ($_REQUEST["xdebug"] == 2) {
496 print "update_rss_feed: content: ";
497 print $entry_content;
498 print "\n";
499 }
500
501 $entry_comments = $item->data["comments"];
502
503 if ($item->get_author()) {
504 $entry_author_item = $item->get_author();
505 $entry_author = $entry_author_item->get_name();
506 if (!$entry_author) $entry_author = $entry_author_item->get_email();
507
508 $entry_author = db_escape_string($entry_author);
509 }
510
511 $entry_guid = db_escape_string(mb_substr($entry_guid, 0, 245));
512
513 $entry_comments = db_escape_string(mb_substr($entry_comments, 0, 245));
514 $entry_author = db_escape_string(mb_substr($entry_author, 0, 245));
515
516 $num_comments = $item->get_item_tags('http://purl.org/rss/1.0/modules/slash/', 'comments');
517
518 if (is_array($num_comments) && is_array($num_comments[0])) {
519 $num_comments = (int) $num_comments[0]["data"];
520 } else {
521 $num_comments = 0;
522 }
523
524 if ($debug_enabled) {
525 _debug("update_rss_feed: num_comments: $num_comments");
526 _debug("update_rss_feed: looking for tags [1]...");
527 }
528
529 // parse <category> entries into tags
530
531 $additional_tags = array();
532
533 $additional_tags_src = $item->get_categories();
534
535 if (is_array($additional_tags_src)) {
536 foreach ($additional_tags_src as $tobj) {
537 array_push($additional_tags, $tobj->get_term());
538 }
539 }
540
541 if ($debug_enabled) {
542 _debug("update_rss_feed: category tags:");
543 print_r($additional_tags);
544 }
545
546 if ($debug_enabled) {
547 _debug("update_rss_feed: looking for tags [2]...");
548 }
549
550 $entry_tags = array_unique($additional_tags);
551
552 for ($i = 0; $i < count($entry_tags); $i++)
553 $entry_tags[$i] = mb_strtolower($entry_tags[$i], 'utf-8');
554
555 if ($debug_enabled) {
556 //_debug("update_rss_feed: unfiltered tags found:");
557 //print_r($entry_tags);
558 }
559
560 if ($debug_enabled) {
561 _debug("update_rss_feed: done collecting data.");
562 }
563
564 // TODO: less memory-hungry implementation
565
566 if ($debug_enabled) {
567 _debug("update_rss_feed: applying plugin filters..");
568 }
569
570 // FIXME not sure if owner_uid is a good idea here, we may have a base entry without user entry (?)
571 $result = db_query($link, "SELECT plugin_data,title,content,link,tag_cache,author FROM ttrss_entries, ttrss_user_entries
572 WHERE ref_id = id AND guid = '".db_escape_string($entry_guid)."' AND owner_uid = $owner_uid");
573
574 if (db_num_rows($result) != 0) {
575 $entry_plugin_data = db_fetch_result($result, 0, "plugin_data");
576 $stored_article = array("title" => db_fetch_result($result, 0, "title"),
577 "content" => db_fetch_result($result, 0, "content"),
578 "link" => db_fetch_result($result, 0, "link"),
579 "tags" => explode(",", db_fetch_result($result, 0, "tag_cache")),
580 "author" => db_fetch_result($result, 0, "author"));
581 } else {
582 $entry_plugin_data = "";
583 $stored_article = array();
584 }
585
586 $article = array("owner_uid" => $owner_uid, // read only
587 "guid" => $entry_guid, // read only
588 "title" => $entry_title,
589 "content" => $entry_content,
590 "link" => $entry_link,
591 "tags" => $entry_tags,
592 "plugin_data" => $entry_plugin_data,
593 "author" => $entry_author,
594 "stored" => $stored_article);
595
596 foreach ($pluginhost->get_hooks($pluginhost::HOOK_ARTICLE_FILTER) as $plugin) {
597 $article = $plugin->hook_article_filter($article);
598 }
599
600 $entry_tags = $article["tags"];
601 $entry_guid = db_escape_string($entry_guid);
602 $entry_content = db_escape_string($article["content"], false);
603 $entry_title = db_escape_string($article["title"]);
604 $entry_author = db_escape_string($article["author"]);
605 $entry_link = db_escape_string($article["link"]);
606 $entry_plugin_data = db_escape_string($article["plugin_data"]);
607
608 if ($debug_enabled) {
609 _debug("update_rss_feed: plugin data: $entry_plugin_data");
610 }
611
612 if ($cache_images && is_writable(CACHE_DIR . '/images'))
613 $entry_content = cache_images($entry_content, $site_url, $debug_enabled);
614
615 $content_hash = "SHA1:" . sha1($entry_content);
616
617 db_query($link, "BEGIN");
618
619 $result = db_query($link, "SELECT id FROM ttrss_entries
620 WHERE guid = '$entry_guid'");
621
622 if (db_num_rows($result) == 0) {
623
624 if ($debug_enabled) {
625 _debug("update_rss_feed: base guid [$entry_guid] not found");
626 }
627
628 // base post entry does not exist, create it
629
630 $result = db_query($link,
631 "INSERT INTO ttrss_entries
632 (title,
633 guid,
634 link,
635 updated,
636 content,
637 content_hash,
638 cached_content,
639 no_orig_date,
640 date_updated,
641 date_entered,
642 comments,
643 num_comments,
644 plugin_data,
645 author)
646 VALUES
647 ('$entry_title',
648 '$entry_guid',
649 '$entry_link',
650 '$entry_timestamp_fmt',
651 '$entry_content',
652 '$content_hash',
653 '',
654 $no_orig_date,
655 NOW(),
656 NOW(),
657 '$entry_comments',
658 '$num_comments',
659 '$entry_plugin_data',
660 '$entry_author')");
661
662 $article_labels = array();
663
664 } else {
665 // we keep encountering the entry in feeds, so we need to
666 // update date_updated column so that we don't get horrible
667 // dupes when the entry gets purged and reinserted again e.g.
668 // in the case of SLOW SLOW OMG SLOW updating feeds
669
670 $base_entry_id = db_fetch_result($result, 0, "id");
671
672 db_query($link, "UPDATE ttrss_entries SET date_updated = NOW()
673 WHERE id = '$base_entry_id'");
674
675 $article_labels = get_article_labels($link, $base_entry_id, $owner_uid);
676 }
677
678 // now it should exist, if not - bad luck then
679
680 $result = db_query($link, "SELECT
681 id,content_hash,no_orig_date,title,plugin_data,
682 ".SUBSTRING_FOR_DATE."(date_updated,1,19) as date_updated,
683 ".SUBSTRING_FOR_DATE."(updated,1,19) as updated,
684 num_comments
685 FROM
686 ttrss_entries
687 WHERE guid = '$entry_guid'");
688
689 $entry_ref_id = 0;
690 $entry_int_id = 0;
691
692 if (db_num_rows($result) == 1) {
693
694 if ($debug_enabled) {
695 _debug("update_rss_feed: base guid [$entry_guid] found, checking for user record");
696 }
697
698 // this will be used below in update handler
699 $orig_content_hash = db_fetch_result($result, 0, "content_hash");
700 $orig_title = db_fetch_result($result, 0, "title");
701 $orig_num_comments = db_fetch_result($result, 0, "num_comments");
702 $orig_date_updated = strtotime(db_fetch_result($result,
703 0, "date_updated"));
704 $orig_plugin_data = db_fetch_result($result, 0, "plugin_data");
705
706 $ref_id = db_fetch_result($result, 0, "id");
707 $entry_ref_id = $ref_id;
708
709 // check for user post link to main table
710
711 // do we allow duplicate posts with same GUID in different feeds?
712 if (get_pref($link, "ALLOW_DUPLICATE_POSTS", $owner_uid, false)) {
713 $dupcheck_qpart = "AND (feed_id = '$feed' OR feed_id IS NULL)";
714 } else {
715 $dupcheck_qpart = "";
716 }
717
718 /* Collect article tags here so we could filter by them: */
719
720 $article_filters = get_article_filters($filters, $entry_title,
721 $entry_content, $entry_link, $entry_timestamp, $entry_author,
722 $entry_tags);
723
724 if ($debug_enabled) {
725 _debug("update_rss_feed: article filters: ");
726 if (count($article_filters) != 0) {
727 print_r($article_filters);
728 }
729 }
730
731 if (find_article_filter($article_filters, "filter")) {
732 db_query($link, "COMMIT"); // close transaction in progress
733 continue;
734 }
735
736 $score = calculate_article_score($article_filters);
737
738 if ($debug_enabled) {
739 _debug("update_rss_feed: initial score: $score");
740 }
741
742 $query = "SELECT ref_id, int_id FROM ttrss_user_entries WHERE
743 ref_id = '$ref_id' AND owner_uid = '$owner_uid'
744 $dupcheck_qpart";
745
746 // if ($_REQUEST["xdebug"]) print "$query\n";
747
748 $result = db_query($link, $query);
749
750 // okay it doesn't exist - create user entry
751 if (db_num_rows($result) == 0) {
752
753 if ($debug_enabled) {
754 _debug("update_rss_feed: user record not found, creating...");
755 }
756
757 if ($score >= -500 && !find_article_filter($article_filters, 'catchup')) {
758 $unread = 'true';
759 $last_read_qpart = 'NULL';
760 } else {
761 $unread = 'false';
762 $last_read_qpart = 'NOW()';
763 }
764
765 if (find_article_filter($article_filters, 'mark') || $score > 1000) {
766 $marked = 'true';
767 } else {
768 $marked = 'false';
769 }
770
771 if (find_article_filter($article_filters, 'publish')) {
772 $published = 'true';
773 } else {
774 $published = 'false';
775 }
776
777 // N-grams
778
779 if (DB_TYPE == "pgsql" and defined('_NGRAM_TITLE_DUPLICATE_THRESHOLD')) {
780
781 $result = db_query($link, "SELECT COUNT(*) AS similar FROM
782 ttrss_entries,ttrss_user_entries
783 WHERE ref_id = id AND updated >= NOW() - INTERVAL '7 day'
784 AND similarity(title, '$entry_title') >= "._NGRAM_TITLE_DUPLICATE_THRESHOLD."
785 AND owner_uid = $owner_uid");
786
787 $ngram_similar = db_fetch_result($result, 0, "similar");
788
789 if ($debug_enabled) {
790 _debug("update_rss_feed: N-gram similar results: $ngram_similar");
791 }
792
793 if ($ngram_similar > 0) {
794 $unread = 'false';
795 }
796 }
797
798 $result = db_query($link,
799 "INSERT INTO ttrss_user_entries
800 (ref_id, owner_uid, feed_id, unread, last_read, marked,
801 published, score, tag_cache, label_cache, uuid)
802 VALUES ('$ref_id', '$owner_uid', '$feed', $unread,
803 $last_read_qpart, $marked, $published, '$score', '', '', '')");
804
805 if (PUBSUBHUBBUB_HUB && $published == 'true') {
806 $rss_link = get_self_url_prefix() .
807 "/public.php?op=rss&id=-2&key=" .
808 get_feed_access_key($link, -2, false, $owner_uid);
809
810 $p = new Publisher(PUBSUBHUBBUB_HUB);
811
812 $pubsub_result = $p->publish_update($rss_link);
813 }
814
815 $result = db_query($link,
816 "SELECT int_id FROM ttrss_user_entries WHERE
817 ref_id = '$ref_id' AND owner_uid = '$owner_uid' AND
818 feed_id = '$feed' LIMIT 1");
819
820 if (db_num_rows($result) == 1) {
821 $entry_int_id = db_fetch_result($result, 0, "int_id");
822 }
823 } else {
824 if ($debug_enabled) {
825 _debug("update_rss_feed: user record FOUND");
826 }
827
828 $entry_ref_id = db_fetch_result($result, 0, "ref_id");
829 $entry_int_id = db_fetch_result($result, 0, "int_id");
830 }
831
832 if ($debug_enabled) {
833 _debug("update_rss_feed: RID: $entry_ref_id, IID: $entry_int_id");
834 }
835
836 $post_needs_update = false;
837 $update_insignificant = false;
838
839 if ($orig_num_comments != $num_comments) {
840 $post_needs_update = true;
841 $update_insignificant = true;
842 }
843
844 if ($entry_plugin_data != $orig_plugin_data) {
845 $post_needs_update = true;
846 $update_insignificant = true;
847 }
848
849 if ($content_hash != $orig_content_hash) {
850 $post_needs_update = true;
851 $update_insignificant = false;
852 }
853
854 if (db_escape_string($orig_title) != $entry_title) {
855 $post_needs_update = true;
856 $update_insignificant = false;
857 }
858
859 // if post needs update, update it and mark all user entries
860 // linking to this post as updated
861 if ($post_needs_update) {
862
863 if (defined('DAEMON_EXTENDED_DEBUG')) {
864 _debug("update_rss_feed: post $entry_guid needs update...");
865 }
866
867 // print "<!-- post $orig_title needs update : $post_needs_update -->";
868
869 db_query($link, "UPDATE ttrss_entries
870 SET title = '$entry_title', content = '$entry_content',
871 content_hash = '$content_hash',
872 updated = '$entry_timestamp_fmt',
873 num_comments = '$num_comments',
874 plugin_data = '$entry_plugin_data'
875 WHERE id = '$ref_id'");
876
877 if (!$update_insignificant) {
878 if ($mark_unread_on_update) {
879 db_query($link, "UPDATE ttrss_user_entries
880 SET last_read = null, unread = true WHERE ref_id = '$ref_id'");
881 }
882 }
883 }
884 }
885
886 db_query($link, "COMMIT");
887
888 if ($debug_enabled) {
889 _debug("update_rss_feed: assigning labels...");
890 }
891
892 assign_article_to_label_filters($link, $entry_ref_id, $article_filters,
893 $owner_uid, $article_labels);
894
895 if ($debug_enabled) {
896 _debug("update_rss_feed: looking for enclosures...");
897 }
898
899 // enclosures
900
901 $enclosures = array();
902
903 $encs = $item->get_enclosures();
904
905 if (is_array($encs)) {
906 foreach ($encs as $e) {
907 $e_item = array(
908 $e->link, $e->type, $e->length);
909 array_push($enclosures, $e_item);
910 }
911 }
912
913 if ($debug_enabled) {
914 _debug("update_rss_feed: article enclosures:");
915 print_r($enclosures);
916 }
917
918 db_query($link, "BEGIN");
919
920 foreach ($enclosures as $enc) {
921 $enc_url = db_escape_string($enc[0]);
922 $enc_type = db_escape_string($enc[1]);
923 $enc_dur = db_escape_string($enc[2]);
924
925 $result = db_query($link, "SELECT id FROM ttrss_enclosures
926 WHERE content_url = '$enc_url' AND post_id = '$entry_ref_id'");
927
928 if (db_num_rows($result) == 0) {
929 db_query($link, "INSERT INTO ttrss_enclosures
930 (content_url, content_type, title, duration, post_id) VALUES
931 ('$enc_url', '$enc_type', '', '$enc_dur', '$entry_ref_id')");
932 }
933 }
934
935 db_query($link, "COMMIT");
936
937 // check for manual tags (we have to do it here since they're loaded from filters)
938
939 foreach ($article_filters as $f) {
940 if ($f["type"] == "tag") {
941
942 $manual_tags = trim_array(explode(",", $f["param"]));
943
944 foreach ($manual_tags as $tag) {
945 if (tag_is_valid($tag)) {
946 array_push($entry_tags, $tag);
947 }
948 }
949 }
950 }
951
952 // Skip boring tags
953
954 $boring_tags = trim_array(explode(",", mb_strtolower(get_pref($link,
955 'BLACKLISTED_TAGS', $owner_uid, ''), 'utf-8')));
956
957 $filtered_tags = array();
958 $tags_to_cache = array();
959
960 if ($entry_tags && is_array($entry_tags)) {
961 foreach ($entry_tags as $tag) {
962 if (array_search($tag, $boring_tags) === false) {
963 array_push($filtered_tags, $tag);
964 }
965 }
966 }
967
968 $filtered_tags = array_unique($filtered_tags);
969
970 if ($debug_enabled) {
971 _debug("update_rss_feed: filtered article tags:");
972 print_r($filtered_tags);
973 }
974
975 // Save article tags in the database
976
977 if (count($filtered_tags) > 0) {
978
979 db_query($link, "BEGIN");
980
981 foreach ($filtered_tags as $tag) {
982
983 $tag = sanitize_tag($tag);
984 $tag = db_escape_string($tag);
985
986 if (!tag_is_valid($tag)) continue;
987
988 $result = db_query($link, "SELECT id FROM ttrss_tags
989 WHERE tag_name = '$tag' AND post_int_id = '$entry_int_id' AND
990 owner_uid = '$owner_uid' LIMIT 1");
991
992 if ($result && db_num_rows($result) == 0) {
993
994 db_query($link, "INSERT INTO ttrss_tags
995 (owner_uid,tag_name,post_int_id)
996 VALUES ('$owner_uid','$tag', '$entry_int_id')");
997 }
998
999 array_push($tags_to_cache, $tag);
1000 }
1001
1002 /* update the cache */
1003
1004 $tags_to_cache = array_unique($tags_to_cache);
1005
1006 $tags_str = db_escape_string(join(",", $tags_to_cache));
1007
1008 db_query($link, "UPDATE ttrss_user_entries
1009 SET tag_cache = '$tags_str' WHERE ref_id = '$entry_ref_id'
1010 AND owner_uid = $owner_uid");
1011
1012 db_query($link, "COMMIT");
1013 }
1014
1015 if (get_pref($link, "AUTO_ASSIGN_LABELS", $owner_uid, false)) {
1016 if ($debug_enabled) {
1017 _debug("update_rss_feed: auto-assigning labels...");
1018 }
1019
1020 foreach ($labels as $label) {
1021 $caption = $label["caption"];
1022
1023 if (preg_match("/\b$caption\b/i", "$tags_str " . strip_tags($entry_content) . " $entry_title")) {
1024 if (!labels_contains_caption($article_labels, $caption)) {
1025 label_add_article($link, $entry_ref_id, $caption, $owner_uid);
1026 }
1027 }
1028 }
1029 }
1030
1031 if ($debug_enabled) {
1032 _debug("update_rss_feed: article processed");
1033 }
1034 }
1035
1036 if (!$last_updated) {
1037 if ($debug_enabled) {
1038 _debug("update_rss_feed: new feed, catching it up...");
1039 }
1040 catchup_feed($link, $feed, false, $owner_uid);
1041 }
1042
1043 if ($debug_enabled) {
1044 _debug("purging feed...");
1045 }
1046
1047 purge_feed($link, $feed, 0, $debug_enabled);
1048
1049 db_query($link, "UPDATE ttrss_feeds
1050 SET last_updated = NOW(), last_error = '' WHERE id = '$feed'");
1051
1052 // db_query($link, "COMMIT");
1053
1054 } else {
1055
1056 $error_msg = db_escape_string(mb_substr($rss->error(), 0, 245));
1057
1058 if ($debug_enabled) {
1059 _debug("update_rss_feed: error fetching feed: $error_msg");
1060 }
1061
1062 db_query($link,
1063 "UPDATE ttrss_feeds SET last_error = '$error_msg',
1064 last_updated = NOW() WHERE id = '$feed'");
1065 }
1066
1067 unset($rss);
1068
1069 if ($debug_enabled) {
1070 _debug("update_rss_feed: done");
1071 }
1072
1073 }
1074
1075 function cache_images($html, $site_url, $debug) {
1076 $cache_dir = CACHE_DIR . "/images";
1077
1078 libxml_use_internal_errors(true);
1079
1080 $charset_hack = '<head>
1081 <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
1082 </head>';
1083
1084 $doc = new DOMDocument();
1085 $doc->loadHTML($charset_hack . $html);
1086 $xpath = new DOMXPath($doc);
1087
1088 $entries = $xpath->query('(//img[@src])');
1089
1090 foreach ($entries as $entry) {
1091 if ($entry->hasAttribute('src')) {
1092 $src = rewrite_relative_url($site_url, $entry->getAttribute('src'));
1093
1094 $local_filename = CACHE_DIR . "/images/" . sha1($src) . ".png";
1095
1096 if ($debug) _debug("cache_images: downloading: $src to $local_filename");
1097
1098 if (!file_exists($local_filename)) {
1099 $file_content = fetch_file_contents($src);
1100
1101 if ($file_content && strlen($file_content) > 1024) {
1102 file_put_contents($local_filename, $file_content);
1103 }
1104 }
1105
1106 if (file_exists($local_filename)) {
1107 $entry->setAttribute('src', SELF_URL_PATH . '/image.php?url=' .
1108 base64_encode($src));
1109 }
1110 }
1111 }
1112
1113 $node = $doc->getElementsByTagName('body')->item(0);
1114
1115 return $doc->saveXML($node, LIBXML_NOEMPTYTAG);
1116 }
1117
1118 function expire_lock_files($debug) {
1119 if ($debug) _debug("Removing old lock files...");
1120
1121 $num_deleted = 0;
1122
1123 if (is_writable(LOCK_DIRECTORY)) {
1124 $files = glob(LOCK_DIRECTORY . "/*.lock");
1125
1126 if ($files) {
1127 foreach ($files as $file) {
1128 if (!file_is_locked($file) && time() - filemtime($file) > 86400*2) {
1129 unlink($file);
1130 ++$num_deleted;
1131 }
1132 }
1133 }
1134 }
1135
1136 if ($debug) _debug("Removed $num_deleted files.");
1137 }
1138
1139 function expire_cached_files($debug) {
1140 foreach (array("simplepie", "images", "export") as $dir) {
1141 $cache_dir = CACHE_DIR . "/$dir";
1142
1143 if ($debug) _debug("Expiring $cache_dir");
1144
1145 $num_deleted = 0;
1146
1147 if (is_writable($cache_dir)) {
1148 $files = glob("$cache_dir/*");
1149
1150 if ($files) {
1151 foreach ($files as $file) {
1152 if (time() - filemtime($file) > 86400*7) {
1153 unlink($file);
1154
1155 ++$num_deleted;
1156 }
1157 }
1158 }
1159 }
1160
1161 if ($debug) _debug("Removed $num_deleted files.");
1162 }
1163 }
1164
1165 /**
1166 * Source: http://www.php.net/manual/en/function.parse-url.php#104527
1167 * Returns the url query as associative array
1168 *
1169 * @param string query
1170 * @return array params
1171 */
1172 function convertUrlQuery($query) {
1173 $queryParts = explode('&', $query);
1174
1175 $params = array();
1176
1177 foreach ($queryParts as $param) {
1178 $item = explode('=', $param);
1179 $params[$item[0]] = $item[1];
1180 }
1181
1182 return $params;
1183 }
1184
1185 function get_article_filters($filters, $title, $content, $link, $timestamp, $author, $tags) {
1186 $matches = array();
1187
1188 foreach ($filters as $filter) {
1189 $match_any_rule = $filter["match_any_rule"];
1190 $filter_match = false;
1191
1192 foreach ($filter["rules"] as $rule) {
1193 $match = false;
1194 $reg_exp = $rule["reg_exp"];
1195
1196 if (!$reg_exp)
1197 continue;
1198
1199 switch ($rule["type"]) {
1200 case "title":
1201 $match = @preg_match("/$reg_exp/i", $title);
1202 break;
1203 case "content":
1204 // we don't need to deal with multiline regexps
1205 $content = preg_replace("/[\r\n\t]/", "", $content);
1206
1207 $match = @preg_match("/$reg_exp/i", $content);
1208 break;
1209 case "both":
1210 // we don't need to deal with multiline regexps
1211 $content = preg_replace("/[\r\n\t]/", "", $content);
1212
1213 $match = (@preg_match("/$reg_exp/i", $title) || @preg_match("/$reg_exp/i", $content));
1214 break;
1215 case "link":
1216 $match = @preg_match("/$reg_exp/i", $link);
1217 break;
1218 case "author":
1219 $match = @preg_match("/$reg_exp/i", $author);
1220 break;
1221 case "tag":
1222 $tag_string = join(",", $tags);
1223 $match = @preg_match("/$reg_exp/i", $tag_string);
1224 break;
1225 }
1226
1227 if ($match_any_rule) {
1228 if ($match) {
1229 $filter_match = true;
1230 break;
1231 }
1232 } else {
1233 $filter_match = $match;
1234 if (!$match) {
1235 break;
1236 }
1237 }
1238 }
1239
1240 if ($filter_match) {
1241 foreach ($filter["actions"] AS $action) {
1242 array_push($matches, $action);
1243 }
1244 }
1245 }
1246
1247 return $matches;
1248 }
1249
1250 function find_article_filter($filters, $filter_name) {
1251 foreach ($filters as $f) {
1252 if ($f["type"] == $filter_name) {
1253 return $f;
1254 };
1255 }
1256 return false;
1257 }
1258
1259 function find_article_filters($filters, $filter_name) {
1260 $results = array();
1261
1262 foreach ($filters as $f) {
1263 if ($f["type"] == $filter_name) {
1264 array_push($results, $f);
1265 };
1266 }
1267 return $results;
1268 }
1269
1270 function calculate_article_score($filters) {
1271 $score = 0;
1272
1273 foreach ($filters as $f) {
1274 if ($f["type"] == "score") {
1275 $score += $f["param"];
1276 };
1277 }
1278 return $score;
1279 }
1280
1281 function labels_contains_caption($labels, $caption) {
1282 foreach ($labels as $label) {
1283 if ($label[1] == $caption) {
1284 return true;
1285 }
1286 }
1287
1288 return false;
1289 }
1290
1291 function assign_article_to_label_filters($link, $id, $filters, $owner_uid, $article_labels) {
1292 foreach ($filters as $f) {
1293 if ($f["type"] == "label") {
1294 if (!labels_contains_caption($article_labels, $f["param"])) {
1295 label_add_article($link, $id, $f["param"], $owner_uid);
1296 }
1297 }
1298 }
1299 }
1300
1301 function cache_content($link, $url, $login, $pass) {
1302
1303 $content = fetch_file_contents($url, $login, $pass);
1304
1305 if ($content) {
1306 $doc = new DOMDocument();
1307 @$doc->loadHTML($content);
1308 $xpath = new DOMXPath($doc);
1309
1310 $node = $doc->getElementsByTagName('body')->item(0);
1311
1312 if ($node) {
1313 $content = $doc->saveXML($node, LIBXML_NOEMPTYTAG);
1314
1315 return $content;
1316 }
1317 }
1318
1319 return "";
1320 }
1321
1322 function make_guid_from_title($title) {
1323 return preg_replace("/[ \"\',.:;]/", "-",
1324 mb_strtolower(strip_tags($title), 'utf-8'));
1325 }
1326
1327
1328 ?>