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