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