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