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