]> git.wh0rd.org - tt-rss.git/blame - include/rssfuncs.php
remove magpie, fix article filter plugins
[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);
0f556e3e 4 define('DAEMON_SLEEP_INTERVAL', 60);
09e8bdfd 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)
941e48a4
AD
84 ) OR ttrss_feeds.last_updated IS NULL
85 OR last_updated = '1970-01-01 00:00:00')";
2c08214a
AD
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)
941e48a4
AD
93 ) OR ttrss_feeds.last_updated IS NULL
94 OR last_updated = '1970-01-01 00:00:00')";
2c08214a
AD
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
3c696512 143 expire_cached_files($debug);
2a91b6ff 144 expire_lock_files($debug);
3c696512 145
2c08214a
AD
146 // For each feed, we call the feed update function.
147 while ($line = array_pop($feeds_to_update)) {
148
149 if($debug) _debug("Feed: " . $line["feed_url"] . ", " . $line["last_updated"]);
150
151 update_rss_feed($link, $line["id"], true);
152
153 sleep(1); // prevent flood (FIXME make this an option?)
154 }
155
156 // Send feed digests by email if needed.
8437c066 157 send_headlines_digests($link, $debug);
2c08214a
AD
158
159 } // function update_daemon_common
160
87764a50 161 // ignore_daemon is not used
0e4a7d7a 162 function update_rss_feed($link, $feed, $ignore_daemon = false, $no_cache = false,
2c08214a
AD
163 $override_url = false) {
164
165 require_once "lib/simplepie/simplepie.inc";
2c08214a 166
2c08214a
AD
167 $debug_enabled = defined('DAEMON_EXTENDED_DEBUG') || $_REQUEST['xdebug'];
168
2c08214a
AD
169 if ($debug_enabled) {
170 _debug("update_rss_feed: start");
171 }
172
87764a50 173 $result = db_query($link, "SELECT id,update_interval,auth_login,
19b3992b 174 feed_url,auth_pass,cache_images,last_updated,cache_content,
87764a50
AD
175 mark_unread_on_update, owner_uid, update_on_checksum_change,
176 pubsub_state
177 FROM ttrss_feeds WHERE id = '$feed'");
2c08214a
AD
178
179 if (db_num_rows($result) == 0) {
180 if ($debug_enabled) {
181 _debug("update_rss_feed: feed $feed NOT FOUND/SKIPPED");
182 }
183 return false;
184 }
185
2c08214a
AD
186 $last_updated = db_fetch_result($result, 0, "last_updated");
187 $owner_uid = db_fetch_result($result, 0, "owner_uid");
188 $mark_unread_on_update = sql_bool_to_bool(db_fetch_result($result,
189 0, "mark_unread_on_update"));
190 $update_on_checksum_change = sql_bool_to_bool(db_fetch_result($result,
191 0, "update_on_checksum_change"));
192 $pubsub_state = db_fetch_result($result, 0, "pubsub_state");
193
194 db_query($link, "UPDATE ttrss_feeds SET last_update_started = NOW()
195 WHERE id = '$feed'");
196
197 $auth_login = db_fetch_result($result, 0, "auth_login");
198 $auth_pass = db_fetch_result($result, 0, "auth_pass");
199
2c08214a 200 $cache_images = sql_bool_to_bool(db_fetch_result($result, 0, "cache_images"));
87764a50 201 $cache_content = sql_bool_to_bool(db_fetch_result($result, 0, "cache_content"));
2c08214a
AD
202 $fetch_url = db_fetch_result($result, 0, "feed_url");
203
2c08214a
AD
204 $feed = db_escape_string($feed);
205
206 if ($auth_login && $auth_pass ){
207 $url_parts = array();
208 preg_match("/(^[^:]*):\/\/(.*)/", $fetch_url, $url_parts);
209
210 if ($url_parts[1] && $url_parts[2]) {
211 $fetch_url = $url_parts[1] . "://$auth_login:$auth_pass@" . $url_parts[2];
212 }
213
214 }
215
216 if ($override_url)
217 $fetch_url = $override_url;
218
219 if ($debug_enabled) {
220 _debug("update_rss_feed: fetching [$fetch_url]...");
221 }
222
0e4a7d7a
AD
223 // Ignore cache if new feed or manual update.
224 $cache_age = (is_null($last_updated) || $last_updated == '1970-01-01 00:00:00') ?
225 -1 : get_feed_update_interval($link, $feed) * 60;
2c08214a 226
19b3992b 227 $simplepie_cache_dir = CACHE_DIR . "/simplepie";
2c08214a 228
19b3992b
AD
229 if (!is_dir($simplepie_cache_dir)) {
230 mkdir($simplepie_cache_dir);
231 }
2c08214a 232
19b3992b
AD
233 $rss = new SimplePie();
234 $rss->set_useragent(SELF_USER_AGENT);
235 $rss->set_timeout($no_cache ? 15 : 60);
236 $rss->set_feed_url($fetch_url);
237 $rss->set_output_encoding('UTF-8');
238 //$rss->force_feed(true);
2c08214a 239
19b3992b
AD
240 if ($debug_enabled) {
241 _debug("feed update interval (sec): " .
242 get_feed_update_interval($link, $feed)*60);
243 }
2c08214a 244
19b3992b 245 $rss->enable_cache(!$no_cache);
2c08214a 246
19b3992b
AD
247 if (!$no_cache) {
248 $rss->set_cache_location($simplepie_cache_dir);
249 $rss->set_cache_duration($cache_age);
2c08214a
AD
250 }
251
19b3992b
AD
252 $rss->init();
253
2c08214a
AD
254// print_r($rss);
255
256 if ($debug_enabled) {
257 _debug("update_rss_feed: fetch done, parsing...");
258 }
259
260 $feed = db_escape_string($feed);
261
19b3992b 262 if (!$rss->error()) {
2c08214a
AD
263
264 if ($debug_enabled) {
265 _debug("update_rss_feed: processing feed data...");
266 }
267
268// db_query($link, "BEGIN");
269
382268c6
AD
270 if (DB_TYPE == "pgsql") {
271 $favicon_interval_qpart = "favicon_last_checked < NOW() - INTERVAL '12 hour'";
272 } else {
273 $favicon_interval_qpart = "favicon_last_checked < DATE_SUB(NOW(), INTERVAL 12 HOUR)";
274 }
275
276 $result = db_query($link, "SELECT title,icon_url,site_url,owner_uid,
277 (favicon_last_checked IS NULL OR $favicon_interval_qpart) AS
278 favicon_needs_check
2c08214a
AD
279 FROM ttrss_feeds WHERE id = '$feed'");
280
281 $registered_title = db_fetch_result($result, 0, "title");
282 $orig_icon_url = db_fetch_result($result, 0, "icon_url");
283 $orig_site_url = db_fetch_result($result, 0, "site_url");
382268c6
AD
284 $favicon_needs_check = sql_bool_to_bool(db_fetch_result($result, 0,
285 "favicon_needs_check"));
2c08214a
AD
286
287 $owner_uid = db_fetch_result($result, 0, "owner_uid");
288
19b3992b 289 $site_url = db_escape_string(mb_substr(rewrite_relative_url($fetch_url, $rss->get_link()), 0, 250));
2c08214a
AD
290
291 if ($debug_enabled) {
292 _debug("update_rss_feed: checking favicon...");
293 }
294
f2798eb6
AD
295 if ($favicon_needs_check) {
296 check_feed_favicon($site_url, $feed, $link);
297
298 db_query($link, "UPDATE ttrss_feeds SET favicon_last_checked = NOW()
299 WHERE id = '$feed'");
300 }
2c08214a
AD
301
302 if (!$registered_title || $registered_title == "[Unknown]") {
303
19b3992b 304 $feed_title = db_escape_string($rss->get_title());
2c08214a
AD
305
306 if ($debug_enabled) {
307 _debug("update_rss_feed: registering title: $feed_title");
308 }
309
310 db_query($link, "UPDATE ttrss_feeds SET
311 title = '$feed_title' WHERE id = '$feed'");
312 }
313
0cf81637 314 if ($site_url && $orig_site_url != $site_url) {
2c08214a
AD
315 db_query($link, "UPDATE ttrss_feeds SET
316 site_url = '$site_url' WHERE id = '$feed'");
317 }
318
19b3992b
AD
319 $icon_url = db_escape_string(mb_substr(
320 rewrite_relative_url($fetch_url, $rss->get_image_url()), 0, 250));
2c08214a
AD
321
322 if ($icon_url && $orig_icon_url != $icon_url) {
323 db_query($link, "UPDATE ttrss_feeds SET icon_url = '$icon_url' WHERE id = '$feed'");
324 }
325
326 if ($debug_enabled) {
b24504b1 327 _debug("update_rss_feed: loading filters & labels...");
2c08214a
AD
328 }
329
330 $filters = load_filters($link, $feed, $owner_uid);
b24504b1 331 $labels = get_all_labels($link, $owner_uid);
2c08214a 332
67bd0b1f
AD
333 if ($debug_enabled) {
334 //print_r($filters);
335 _debug("update_rss_feed: " . count($filters) . " filters loaded.");
336 }
2c08214a 337
19b3992b 338 $items = $rss->get_items();
2c08214a 339
19b3992b 340 if (!is_array($items)) {
2c08214a 341 if ($debug_enabled) {
19b3992b 342 _debug("update_rss_feed: no articles found.");
2c08214a
AD
343 }
344
345 db_query($link, "UPDATE ttrss_feeds
346 SET last_updated = NOW(), last_error = '' WHERE id = '$feed'");
347
348 return; // no articles
349 }
350
351 if ($pubsub_state != 2 && PUBSUBHUBBUB_ENABLED) {
352
353 if ($debug_enabled) _debug("update_rss_feed: checking for PUSH hub...");
354
355 $feed_hub_url = false;
2c08214a 356
19b3992b 357 $links = $rss->get_links('hub');
2c08214a 358
19b3992b
AD
359 if ($links && is_array($links)) {
360 foreach ($links as $l) {
361 $feed_hub_url = $l;
362 break;
2c08214a
AD
363 }
364 }
365
366 if ($debug_enabled) _debug("update_rss_feed: feed hub url: $feed_hub_url");
367
368 if ($feed_hub_url && function_exists('curl_init') &&
369 !ini_get("open_basedir")) {
370
371 require_once 'lib/pubsubhubbub/subscriber.php';
372
373 $callback_url = get_self_url_prefix() .
374 "/public.php?op=pubsub&id=$feed";
375
376 $s = new Subscriber($feed_hub_url, $callback_url);
377
378 $rc = $s->subscribe($fetch_url);
379
380 if ($debug_enabled)
381 _debug("update_rss_feed: feed hub url found, subscribe request sent.");
382
383 db_query($link, "UPDATE ttrss_feeds SET pubsub_state = 1
384 WHERE id = '$feed'");
385 }
386 }
387
388 if ($debug_enabled) {
389 _debug("update_rss_feed: processing articles...");
390 }
391
19b3992b 392 foreach ($items as $item) {
2c08214a
AD
393 if ($_REQUEST['xdebug'] == 2) {
394 print_r($item);
395 }
396
19b3992b
AD
397 $entry_guid = $item->get_id();
398 if (!$entry_guid) $entry_guid = $item->get_link();
399 if (!$entry_guid) $entry_guid = make_guid_from_title($item->get_title());
2c08214a 400
765509c5 401 if ($cache_content) {
d5e9cf28 402 $entry_guid = "ccache:$entry_guid";
765509c5
AD
403 }
404
405 if ($auth_login || $auth_pass) {
406 $entry_guid = "auth,$owner_uid:$entry_guid";
407 }
408
2c08214a
AD
409 if ($debug_enabled) {
410 _debug("update_rss_feed: guid $entry_guid");
411 }
412
413 if (!$entry_guid) continue;
414
415 $entry_timestamp = "";
416
19b3992b 417 $entry_timestamp = strtotime($item->get_date());
2c08214a 418
19b3992b 419 if ($entry_timestamp == -1 || !$entry_timestamp) {
2c08214a
AD
420 $entry_timestamp = time();
421 $no_orig_date = 'true';
422 } else {
423 $no_orig_date = 'false';
424 }
425
426 $entry_timestamp_fmt = strftime("%Y/%m/%d %H:%M:%S", $entry_timestamp);
427
428 if ($debug_enabled) {
429 _debug("update_rss_feed: date $entry_timestamp [$entry_timestamp_fmt]");
430 }
431
19b3992b
AD
432 $entry_title = $item->get_title();
433 $entry_link = rewrite_relative_url($site_url, $item->get_link());
2c08214a
AD
434
435 if ($debug_enabled) {
436 _debug("update_rss_feed: title $entry_title");
437 _debug("update_rss_feed: link $entry_link");
438 }
439
440 if (!$entry_title) $entry_title = date("Y-m-d H:i:s", $entry_timestamp);;
441
19b3992b
AD
442 $entry_content = $item->get_content();
443 if (!$entry_content) $entry_content = $item->get_description();
2c08214a 444
c5867798 445 if ($cache_images && is_writable(CACHE_DIR . '/images'))
3c696512
AD
446 $entry_content = cache_images($entry_content, $site_url, $debug_enabled);
447
2c08214a
AD
448 if ($_REQUEST["xdebug"] == 2) {
449 print "update_rss_feed: content: ";
487f0750 450 print $entry_content;
3c696512 451 print "\n";
2c08214a
AD
452 }
453
87764a50 454 $entry_cached_content = "";
2c08214a 455
19b3992b 456 $entry_comments = $item->data["comments"];
2c08214a 457
19b3992b
AD
458 if ($item->get_author()) {
459 $entry_author_item = $item->get_author();
460 $entry_author = $entry_author_item->get_name();
461 if (!$entry_author) $entry_author = $entry_author_item->get_email();
2c08214a 462
19b3992b 463 $entry_author = db_escape_string($entry_author);
2c08214a
AD
464 }
465
19b3992b 466 $entry_guid = db_escape_string(mb_substr($entry_guid, 0, 250));
2c08214a
AD
467
468 $result = db_query($link, "SELECT id FROM ttrss_entries
469 WHERE guid = '$entry_guid'");
470
19b3992b
AD
471 $entry_comments = db_escape_string(mb_substr($entry_comments, 0, 250));
472 $entry_author = db_escape_string(mb_substr($entry_author, 0, 250));
2c08214a 473
19b3992b 474 $num_comments = $item->get_item_tags('http://purl.org/rss/1.0/modules/slash/', 'comments');
83e6e313 475
19b3992b
AD
476 if (is_array($num_comments) && is_array($num_comments[0])) {
477 $num_comments = (int) $num_comments[0]["data"];
2c08214a 478 } else {
19b3992b 479 $num_comments = 0;
2c08214a
AD
480 }
481
2c08214a 482 if ($debug_enabled) {
83e6e313 483 _debug("update_rss_feed: num_comments: $num_comments");
2c08214a
AD
484 _debug("update_rss_feed: looking for tags [1]...");
485 }
486
487 // parse <category> entries into tags
488
489 $additional_tags = array();
490
19b3992b 491 $additional_tags_src = $item->get_categories();
2c08214a 492
19b3992b
AD
493 if (is_array($additional_tags_src)) {
494 foreach ($additional_tags_src as $tobj) {
495 array_push($additional_tags, $tobj->get_term());
2c08214a 496 }
19b3992b 497 }
2c08214a 498
19b3992b
AD
499 if ($debug_enabled) {
500 _debug("update_rss_feed: category tags:");
501 print_r($additional_tags);
2c08214a
AD
502 }
503
504 if ($debug_enabled) {
505 _debug("update_rss_feed: looking for tags [2]...");
506 }
507
508 /* taaaags */
509 // <a href="..." rel="tag">Xorg</a>, //
510
511 $entry_tags = null;
512
513 preg_match_all("/<a.*?rel=['\"]tag['\"].*?\>([^<]+)<\/a>/i",
2bbd6994 514 $entry_content, $entry_tags);
2c08214a
AD
515
516 $entry_tags = $entry_tags[1];
517
518 $entry_tags = array_merge($entry_tags, $additional_tags);
519 $entry_tags = array_unique($entry_tags);
520
521 for ($i = 0; $i < count($entry_tags); $i++)
522 $entry_tags[$i] = mb_strtolower($entry_tags[$i], 'utf-8');
523
524 if ($debug_enabled) {
6aff7845
AD
525 //_debug("update_rss_feed: unfiltered tags found:");
526 //print_r($entry_tags);
2c08214a
AD
527 }
528
2c08214a
AD
529 if ($debug_enabled) {
530 _debug("update_rss_feed: done collecting data [TITLE:$entry_title]");
531 }
532
cc85704f 533 // TODO: less memory-hungry implementation
19c73507
AD
534 global $pluginhost;
535
19b3992b
AD
536 if ($debug_enabled) {
537 _debug("update_rss_feed: applying plugin filters..");
538 }
cc85704f 539
19b3992b
AD
540 $article = array("owner_uid" => $owner_uid,
541 "title" => $entry_title,
542 "content" => $entry_content,
543 "link" => $entry_link,
544 "tags" => $entry_tags,
545 "author" => $entry_author);
cc85704f 546
19b3992b
AD
547 foreach ($pluginhost->get_hooks($pluginhost::HOOK_ARTICLE_FILTER) as $plugin) {
548 $article = $plugin->hook_article_filter($article);
cc85704f
AD
549 }
550
19b3992b
AD
551 $entry_title = $article["title"];
552 $entry_content = $article["content"];
553 $entry_tags = $article["tags"];
554 $entry_author = $article["author"];
555
2bbd6994
AD
556 $entry_content = db_escape_string($entry_content, false);
557 $entry_title = db_escape_string($entry_title);
558 $entry_author = db_escape_string($entry_author);
559 $entry_link = db_escape_string($entry_link);
560
cc85704f
AD
561 $content_hash = "SHA1:" . sha1(strip_tags($entry_content));
562
2c08214a
AD
563 db_query($link, "BEGIN");
564
565 if (db_num_rows($result) == 0) {
566
567 if ($debug_enabled) {
568 _debug("update_rss_feed: base guid not found");
569 }
570
87764a50
AD
571 if ($cache_content) {
572 if ($debug_enabled) {
8054439f 573 _debug("update_rss_feed: caching content (initial)...");
87764a50
AD
574 }
575
576 $entry_cached_content = cache_content($link, $entry_link, $auth_login, $auth_pass);
577
578 if ($cache_images && is_writable(CACHE_DIR . '/images'))
579 $entry_cached_content = cache_images($entry_cached_content, $site_url, $debug_enabled);
580
581 $entry_cached_content = db_escape_string($entry_cached_content, false);
87764a50
AD
582 }
583
2c08214a
AD
584 // base post entry does not exist, create it
585
586 $result = db_query($link,
587 "INSERT INTO ttrss_entries
588 (title,
589 guid,
590 link,
591 updated,
592 content,
593 content_hash,
87764a50 594 cached_content,
2c08214a
AD
595 no_orig_date,
596 date_updated,
597 date_entered,
598 comments,
599 num_comments,
600 author)
601 VALUES
602 ('$entry_title',
603 '$entry_guid',
604 '$entry_link',
605 '$entry_timestamp_fmt',
606 '$entry_content',
607 '$content_hash',
cb93a5de 608 '$entry_cached_content',
2c08214a
AD
609 $no_orig_date,
610 NOW(),
611 NOW(),
612 '$entry_comments',
613 '$num_comments',
614 '$entry_author')");
e8291805
AD
615
616 $article_labels = array();
617
2c08214a
AD
618 } else {
619 // we keep encountering the entry in feeds, so we need to
620 // update date_updated column so that we don't get horrible
621 // dupes when the entry gets purged and reinserted again e.g.
622 // in the case of SLOW SLOW OMG SLOW updating feeds
623
624 $base_entry_id = db_fetch_result($result, 0, "id");
625
626 db_query($link, "UPDATE ttrss_entries SET date_updated = NOW()
627 WHERE id = '$base_entry_id'");
e8291805
AD
628
629 $article_labels = get_article_labels($link, $base_entry_id, $owner_uid);
2c08214a
AD
630 }
631
632 // now it should exist, if not - bad luck then
633
634 $result = db_query($link, "SELECT
635 id,content_hash,no_orig_date,title,
636 ".SUBSTRING_FOR_DATE."(date_updated,1,19) as date_updated,
637 ".SUBSTRING_FOR_DATE."(updated,1,19) as updated,
130b0781 638 num_comments, cached_content
2c08214a
AD
639 FROM
640 ttrss_entries
641 WHERE guid = '$entry_guid'");
642
643 $entry_ref_id = 0;
644 $entry_int_id = 0;
645
646 if (db_num_rows($result) == 1) {
647
648 if ($debug_enabled) {
649 _debug("update_rss_feed: base guid found, checking for user record");
650 }
651
652 // this will be used below in update handler
653 $orig_content_hash = db_fetch_result($result, 0, "content_hash");
654 $orig_title = db_fetch_result($result, 0, "title");
655 $orig_num_comments = db_fetch_result($result, 0, "num_comments");
130b0781 656 $orig_cached_content = trim(db_fetch_result($result, 0, "cached_content"));
2c08214a
AD
657 $orig_date_updated = strtotime(db_fetch_result($result,
658 0, "date_updated"));
659
660 $ref_id = db_fetch_result($result, 0, "id");
661 $entry_ref_id = $ref_id;
662
663 // check for user post link to main table
664
665 // do we allow duplicate posts with same GUID in different feeds?
666 if (get_pref($link, "ALLOW_DUPLICATE_POSTS", $owner_uid, false)) {
667 $dupcheck_qpart = "AND (feed_id = '$feed' OR feed_id IS NULL)";
668 } else {
669 $dupcheck_qpart = "";
670 }
671
672 /* Collect article tags here so we could filter by them: */
673
674 $article_filters = get_article_filters($filters, $entry_title,
4021d61a 675 $entry_content, $entry_link, $entry_timestamp, $entry_author,
2c08214a
AD
676 $entry_tags);
677
678 if ($debug_enabled) {
679 _debug("update_rss_feed: article filters: ");
680 if (count($article_filters) != 0) {
681 print_r($article_filters);
682 }
683 }
684
685 if (find_article_filter($article_filters, "filter")) {
686 db_query($link, "COMMIT"); // close transaction in progress
687 continue;
688 }
689
690 $score = calculate_article_score($article_filters);
691
692 if ($debug_enabled) {
693 _debug("update_rss_feed: initial score: $score");
694 }
695
696 $query = "SELECT ref_id, int_id FROM ttrss_user_entries WHERE
697 ref_id = '$ref_id' AND owner_uid = '$owner_uid'
698 $dupcheck_qpart";
699
700// if ($_REQUEST["xdebug"]) print "$query\n";
701
702 $result = db_query($link, $query);
703
704 // okay it doesn't exist - create user entry
705 if (db_num_rows($result) == 0) {
706
707 if ($debug_enabled) {
708 _debug("update_rss_feed: user record not found, creating...");
709 }
710
711 if ($score >= -500 && !find_article_filter($article_filters, 'catchup')) {
712 $unread = 'true';
713 $last_read_qpart = 'NULL';
714 } else {
715 $unread = 'false';
716 $last_read_qpart = 'NOW()';
717 }
718
719 if (find_article_filter($article_filters, 'mark') || $score > 1000) {
720 $marked = 'true';
721 } else {
722 $marked = 'false';
723 }
724
725 if (find_article_filter($article_filters, 'publish')) {
726 $published = 'true';
727 } else {
728 $published = 'false';
729 }
730
2ea9bbfd
AD
731 // N-grams
732
733 if (DB_TYPE == "pgsql" and defined('_NGRAM_TITLE_DUPLICATE_THRESHOLD')) {
734
735 $result = db_query($link, "SELECT COUNT(*) AS similar FROM
736 ttrss_entries,ttrss_user_entries
737 WHERE ref_id = id AND updated >= NOW() - INTERVAL '7 day'
738 AND similarity(title, '$entry_title') >= "._NGRAM_TITLE_DUPLICATE_THRESHOLD."
739 AND owner_uid = $owner_uid");
740
741 $ngram_similar = db_fetch_result($result, 0, "similar");
742
743 if ($debug_enabled) {
744 _debug("update_rss_feed: N-gram similar results: $ngram_similar");
745 }
746
747 if ($ngram_similar > 0) {
748 $unread = 'false';
749 }
750 }
751
2c08214a
AD
752 $result = db_query($link,
753 "INSERT INTO ttrss_user_entries
754 (ref_id, owner_uid, feed_id, unread, last_read, marked,
755 published, score, tag_cache, label_cache, uuid)
756 VALUES ('$ref_id', '$owner_uid', '$feed', $unread,
757 $last_read_qpart, $marked, $published, '$score', '', '', '')");
758
759 if (PUBSUBHUBBUB_HUB && $published == 'true') {
760 $rss_link = get_self_url_prefix() .
761 "/public.php?op=rss&id=-2&key=" .
762 get_feed_access_key($link, -2, false, $owner_uid);
763
764 $p = new Publisher(PUBSUBHUBBUB_HUB);
765
766 $pubsub_result = $p->publish_update($rss_link);
767 }
768
769 $result = db_query($link,
770 "SELECT int_id FROM ttrss_user_entries WHERE
771 ref_id = '$ref_id' AND owner_uid = '$owner_uid' AND
772 feed_id = '$feed' LIMIT 1");
773
774 if (db_num_rows($result) == 1) {
775 $entry_int_id = db_fetch_result($result, 0, "int_id");
776 }
777 } else {
778 if ($debug_enabled) {
779 _debug("update_rss_feed: user record FOUND");
780 }
781
782 $entry_ref_id = db_fetch_result($result, 0, "ref_id");
783 $entry_int_id = db_fetch_result($result, 0, "int_id");
784 }
785
786 if ($debug_enabled) {
787 _debug("update_rss_feed: RID: $entry_ref_id, IID: $entry_int_id");
788 }
789
790 $post_needs_update = false;
791 $update_insignificant = false;
130b0781 792 $cached_content_needs_update = false;
2c08214a
AD
793
794 if ($orig_num_comments != $num_comments) {
795 $post_needs_update = true;
796 $update_insignificant = true;
797 }
798
799 if ($content_hash != $orig_content_hash) {
800 $post_needs_update = true;
801 $update_insignificant = false;
130b0781
AD
802 $cached_content_needs_update = true;
803 }
87764a50 804
130b0781
AD
805 if ($cache_content) {
806 if ($debug_enabled) {
807 _debug("update_rss_feed: caching content because original checksum changed...");
808 }
87764a50 809
130b0781 810 $entry_cached_content = cache_content($link, $entry_link, $auth_login, $auth_pass);
87764a50 811
130b0781 812 if ($entry_cached_content) {
87764a50
AD
813 if ($cache_images && is_writable(CACHE_DIR . '/images'))
814 $entry_cached_content = cache_images($entry_cached_content, $site_url, $debug_enabled);
815
816 $entry_cached_content = db_escape_string($entry_cached_content, false);
130b0781
AD
817 $post_needs_update = true;
818 } else {
819 $entry_cached_content = db_escape_string($orig_cached_content);
87764a50 820 }
130b0781
AD
821 } else {
822 $entry_cached_content = db_escape_string($orig_cached_content);
2c08214a
AD
823 }
824
825 if (db_escape_string($orig_title) != $entry_title) {
826 $post_needs_update = true;
827 $update_insignificant = false;
828 }
829
830 // if post needs update, update it and mark all user entries
831 // linking to this post as updated
832 if ($post_needs_update) {
833
834 if (defined('DAEMON_EXTENDED_DEBUG')) {
835 _debug("update_rss_feed: post $entry_guid needs update...");
836 }
837
838// print "<!-- post $orig_title needs update : $post_needs_update -->";
839
840 db_query($link, "UPDATE ttrss_entries
841 SET title = '$entry_title', content = '$entry_content',
842 content_hash = '$content_hash',
87764a50 843 cached_content = '$entry_cached_content',
2c08214a
AD
844 updated = '$entry_timestamp_fmt',
845 num_comments = '$num_comments'
846 WHERE id = '$ref_id'");
847
848 if (!$update_insignificant) {
849 if ($mark_unread_on_update) {
850 db_query($link, "UPDATE ttrss_user_entries
851 SET last_read = null, unread = true WHERE ref_id = '$ref_id'");
852 } else if ($update_on_checksum_change) {
853 db_query($link, "UPDATE ttrss_user_entries
854 SET last_read = null WHERE ref_id = '$ref_id'
855 AND unread = false");
856 }
857 }
858 }
859 }
860
861 db_query($link, "COMMIT");
862
863 if ($debug_enabled) {
864 _debug("update_rss_feed: assigning labels...");
865 }
866
92c14e9d 867 assign_article_to_label_filters($link, $entry_ref_id, $article_filters,
b24504b1 868 $owner_uid, $article_labels);
2c08214a
AD
869
870 if ($debug_enabled) {
871 _debug("update_rss_feed: looking for enclosures...");
872 }
873
874 // enclosures
875
876 $enclosures = array();
877
19b3992b 878 $encs = $item->get_enclosures();
2c08214a 879
19b3992b
AD
880 if (is_array($encs)) {
881 foreach ($encs as $e) {
882 $e_item = array(
883 $e->link, $e->type, $e->length);
2c08214a 884 array_push($enclosures, $e_item);
2c08214a
AD
885 }
886 }
887
2c08214a
AD
888 if ($debug_enabled) {
889 _debug("update_rss_feed: article enclosures:");
890 print_r($enclosures);
891 }
892
893 db_query($link, "BEGIN");
894
895 foreach ($enclosures as $enc) {
896 $enc_url = db_escape_string($enc[0]);
897 $enc_type = db_escape_string($enc[1]);
898 $enc_dur = db_escape_string($enc[2]);
899
900 $result = db_query($link, "SELECT id FROM ttrss_enclosures
901 WHERE content_url = '$enc_url' AND post_id = '$entry_ref_id'");
902
903 if (db_num_rows($result) == 0) {
904 db_query($link, "INSERT INTO ttrss_enclosures
905 (content_url, content_type, title, duration, post_id) VALUES
906 ('$enc_url', '$enc_type', '', '$enc_dur', '$entry_ref_id')");
907 }
908 }
909
910 db_query($link, "COMMIT");
911
912 // check for manual tags (we have to do it here since they're loaded from filters)
913
914 foreach ($article_filters as $f) {
6aff7845 915 if ($f["type"] == "tag") {
2c08214a 916
6aff7845 917 $manual_tags = trim_array(explode(",", $f["param"]));
2c08214a
AD
918
919 foreach ($manual_tags as $tag) {
920 if (tag_is_valid($tag)) {
921 array_push($entry_tags, $tag);
922 }
923 }
924 }
925 }
926
927 // Skip boring tags
928
929 $boring_tags = trim_array(explode(",", mb_strtolower(get_pref($link,
930 'BLACKLISTED_TAGS', $owner_uid, ''), 'utf-8')));
931
932 $filtered_tags = array();
933 $tags_to_cache = array();
934
935 if ($entry_tags && is_array($entry_tags)) {
936 foreach ($entry_tags as $tag) {
937 if (array_search($tag, $boring_tags) === false) {
938 array_push($filtered_tags, $tag);
939 }
940 }
941 }
942
943 $filtered_tags = array_unique($filtered_tags);
944
945 if ($debug_enabled) {
946 _debug("update_rss_feed: filtered article tags:");
947 print_r($filtered_tags);
948 }
949
950 // Save article tags in the database
951
952 if (count($filtered_tags) > 0) {
953
954 db_query($link, "BEGIN");
955
956 foreach ($filtered_tags as $tag) {
957
958 $tag = sanitize_tag($tag);
959 $tag = db_escape_string($tag);
960
961 if (!tag_is_valid($tag)) continue;
962
963 $result = db_query($link, "SELECT id FROM ttrss_tags
964 WHERE tag_name = '$tag' AND post_int_id = '$entry_int_id' AND
965 owner_uid = '$owner_uid' LIMIT 1");
966
967 if ($result && db_num_rows($result) == 0) {
968
969 db_query($link, "INSERT INTO ttrss_tags
970 (owner_uid,tag_name,post_int_id)
971 VALUES ('$owner_uid','$tag', '$entry_int_id')");
972 }
973
974 array_push($tags_to_cache, $tag);
975 }
976
977 /* update the cache */
978
979 $tags_to_cache = array_unique($tags_to_cache);
980
981 $tags_str = db_escape_string(join(",", $tags_to_cache));
982
983 db_query($link, "UPDATE ttrss_user_entries
984 SET tag_cache = '$tags_str' WHERE ref_id = '$entry_ref_id'
985 AND owner_uid = $owner_uid");
986
987 db_query($link, "COMMIT");
988 }
989
b24504b1
AD
990 if (get_pref($link, "AUTO_ASSIGN_LABELS", $owner_uid, false)) {
991 if ($debug_enabled) {
992 _debug("update_rss_feed: auto-assigning labels...");
993 }
994
995 foreach ($labels as $label) {
996 $caption = $label["caption"];
997
3fc6e71a 998 if (preg_match("/\b$caption\b/i", "$tags_str " . strip_tags($entry_content) . " $entry_title")) {
b24504b1
AD
999 if (!labels_contains_caption($article_labels, $caption)) {
1000 label_add_article($link, $entry_ref_id, $caption, $owner_uid);
1001 }
1002 }
1003 }
1004 }
1005
2c08214a
AD
1006 if ($debug_enabled) {
1007 _debug("update_rss_feed: article processed");
1008 }
1009 }
1010
1011 if (!$last_updated) {
1012 if ($debug_enabled) {
1013 _debug("update_rss_feed: new feed, catching it up...");
1014 }
1015 catchup_feed($link, $feed, false, $owner_uid);
1016 }
1017
1018 if ($debug_enabled) {
1019 _debug("purging feed...");
1020 }
1021
1022 purge_feed($link, $feed, 0, $debug_enabled);
1023
1024 db_query($link, "UPDATE ttrss_feeds
f2798eb6 1025 SET last_updated = NOW(), last_error = '' WHERE id = '$feed'");
2c08214a
AD
1026
1027// db_query($link, "COMMIT");
1028
1029 } else {
1030
19b3992b 1031 $error_msg = mb_substr($rss->error(), 0, 250);
2c08214a
AD
1032
1033 if ($debug_enabled) {
1034 _debug("update_rss_feed: error fetching feed: $error_msg");
1035 }
1036
1037 $error_msg = db_escape_string($error_msg);
1038
1039 db_query($link,
1040 "UPDATE ttrss_feeds SET last_error = '$error_msg',
1041 last_updated = NOW() WHERE id = '$feed'");
1042 }
1043
19b3992b 1044 unset($rss);
2c08214a
AD
1045
1046 if ($debug_enabled) {
1047 _debug("update_rss_feed: done");
1048 }
1049
1050 }
1051
3c696512
AD
1052 function cache_images($html, $site_url, $debug) {
1053 $cache_dir = CACHE_DIR . "/images";
1054
1055 libxml_use_internal_errors(true);
1056
1057 $charset_hack = '<head>
1058 <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
1059 </head>';
1060
1061 $doc = new DOMDocument();
1062 $doc->loadHTML($charset_hack . $html);
1063 $xpath = new DOMXPath($doc);
1064
1065 $entries = $xpath->query('(//img[@src])');
1066
1067 foreach ($entries as $entry) {
1068 if ($entry->hasAttribute('src')) {
1069 $src = rewrite_relative_url($site_url, $entry->getAttribute('src'));
1070
1071 $local_filename = CACHE_DIR . "/images/" . sha1($src) . ".png";
1072
1073 if ($debug) _debug("cache_images: downloading: $src to $local_filename");
1074
1075 if (!file_exists($local_filename)) {
1076 $file_content = fetch_file_contents($src);
1077
b8379e69 1078 if ($file_content && strlen($file_content) > 1024) {
3c696512
AD
1079 file_put_contents($local_filename, $file_content);
1080 }
1081 }
1082
1083 if (file_exists($local_filename)) {
1084 $entry->setAttribute('src', SELF_URL_PATH . '/image.php?url=' .
487f0750 1085 base64_encode($src));
3c696512
AD
1086 }
1087 }
1088 }
1089
1090 $node = $doc->getElementsByTagName('body')->item(0);
1091
7b8ff151 1092 return $doc->saveXML($node, LIBXML_NOEMPTYTAG);
3c696512
AD
1093 }
1094
2a91b6ff
AD
1095 function expire_lock_files($debug) {
1096 if ($debug) _debug("Removing old lock files...");
1097
1098 $num_deleted = 0;
1099
1100 if (is_writable(LOCK_DIRECTORY)) {
1101 $files = glob(LOCK_DIRECTORY . "/*.lock");
1102
1103 if ($files) {
1104 foreach ($files as $file) {
1105 if (!file_is_locked($file) && time() - filemtime($file) > 86400*2) {
1106 unlink($file);
1107 ++$num_deleted;
1108 }
1109 }
1110 }
1111 }
1112
1113 if ($debug) _debug("Removed $num_deleted files.");
1114 }
1115
3c696512 1116 function expire_cached_files($debug) {
19b3992b 1117 foreach (array("simplepie", "images", "export") as $dir) {
3c696512 1118 $cache_dir = CACHE_DIR . "/$dir";
2c08214a 1119
3c696512 1120 if ($debug) _debug("Expiring $cache_dir");
2c08214a 1121
3c696512
AD
1122 $num_deleted = 0;
1123
1124 if (is_writable($cache_dir)) {
1125 $files = glob("$cache_dir/*");
1126
2a91b6ff 1127 if ($files) {
2ab20c31
AD
1128 foreach ($files as $file) {
1129 if (time() - filemtime($file) > 86400*7) {
1130 unlink($file);
3c696512 1131
2ab20c31
AD
1132 ++$num_deleted;
1133 }
3c696512
AD
1134 }
1135 }
2a91b6ff 1136 }
3c696512
AD
1137
1138 if ($debug) _debug("Removed $num_deleted files.");
1139 }
1140 }
2c08214a 1141
a3e0bdcf
AD
1142 /**
1143 * Source: http://www.php.net/manual/en/function.parse-url.php#104527
1144 * Returns the url query as associative array
1145 *
1146 * @param string query
1147 * @return array params
1148 */
1149 function convertUrlQuery($query) {
1150 $queryParts = explode('&', $query);
1151
1152 $params = array();
1153
1154 foreach ($queryParts as $param) {
1155 $item = explode('=', $param);
1156 $params[$item[0]] = $item[1];
1157 }
1158
1159 return $params;
1160 }
92c14e9d
AD
1161
1162 function get_article_filters($filters, $title, $content, $link, $timestamp, $author, $tags) {
1163 $matches = array();
1164
1165 foreach ($filters as $filter) {
1166 $match_any_rule = $filter["match_any_rule"];
1167 $filter_match = false;
1168
1169 foreach ($filter["rules"] as $rule) {
1170 $match = false;
1171 $reg_exp = $rule["reg_exp"];
1172
1173 if (!$reg_exp)
1174 continue;
1175
1176 switch ($rule["type"]) {
1177 case "title":
1178 $match = @preg_match("/$reg_exp/i", $title);
1179 break;
1180 case "content":
d03ae73e
AD
1181 // we don't need to deal with multiline regexps
1182 $content = preg_replace("/[\r\n\t]/", "", $content);
1183
92c14e9d
AD
1184 $match = @preg_match("/$reg_exp/i", $content);
1185 break;
1186 case "both":
d03ae73e
AD
1187 // we don't need to deal with multiline regexps
1188 $content = preg_replace("/[\r\n\t]/", "", $content);
1189
72d1d067 1190 $match = (@preg_match("/$reg_exp/i", $title) || @preg_match("/$reg_exp/i", $content));
92c14e9d
AD
1191 break;
1192 case "link":
1193 $match = @preg_match("/$reg_exp/i", $link);
1194 break;
1195 case "author":
1196 $match = @preg_match("/$reg_exp/i", $author);
1197 break;
1198 case "tag":
1199 $tag_string = join(",", $tags);
1200 $match = @preg_match("/$reg_exp/i", $tag_string);
1201 break;
1202 }
1203
1204 if ($match_any_rule) {
1205 if ($match) {
1206 $filter_match = true;
1207 break;
1208 }
1209 } else {
1210 $filter_match = $match;
1211 if (!$match) {
1212 break;
1213 }
1214 }
1215 }
1216
1217 if ($filter_match) {
1218 foreach ($filter["actions"] AS $action) {
1219 array_push($matches, $action);
1220 }
1221 }
1222 }
1223
1224 return $matches;
1225 }
1226
1227 function find_article_filter($filters, $filter_name) {
1228 foreach ($filters as $f) {
1229 if ($f["type"] == $filter_name) {
1230 return $f;
1231 };
1232 }
1233 return false;
1234 }
1235
1236 function find_article_filters($filters, $filter_name) {
1237 $results = array();
1238
1239 foreach ($filters as $f) {
1240 if ($f["type"] == $filter_name) {
1241 array_push($results, $f);
1242 };
1243 }
1244 return $results;
1245 }
1246
1247 function calculate_article_score($filters) {
1248 $score = 0;
1249
1250 foreach ($filters as $f) {
1251 if ($f["type"] == "score") {
1252 $score += $f["param"];
1253 };
1254 }
1255 return $score;
1256 }
1257
b24504b1
AD
1258 function labels_contains_caption($labels, $caption) {
1259 foreach ($labels as $label) {
1260 if ($label[1] == $caption) {
1261 return true;
1262 }
1263 }
1264
1265 return false;
1266 }
1267
1268 function assign_article_to_label_filters($link, $id, $filters, $owner_uid, $article_labels) {
92c14e9d
AD
1269 foreach ($filters as $f) {
1270 if ($f["type"] == "label") {
b24504b1
AD
1271 if (!labels_contains_caption($article_labels, $f["param"])) {
1272 label_add_article($link, $id, $f["param"], $owner_uid);
1273 }
1274 }
92c14e9d
AD
1275 }
1276 }
87764a50
AD
1277
1278 function cache_content($link, $url, $login, $pass) {
1279
1280 $content = fetch_file_contents($url, $login, $pass);
1281
1282 if ($content) {
1283 $doc = new DOMDocument();
1284 @$doc->loadHTML($content);
1285 $xpath = new DOMXPath($doc);
1286
1287 $node = $doc->getElementsByTagName('body')->item(0);
1288
1289 if ($node) {
1290 $content = $doc->saveXML($node, LIBXML_NOEMPTYTAG);
1291
1292 return $content;
1293 }
1294 }
1295
1296 return "";
1297 }
2c08214a 1298?>