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