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