]> git.wh0rd.org Git - tt-rss.git/blob - include/rssfuncs.php
a28cb2063077d744d5d62d558790dcde9ef17591
[tt-rss.git] / include / rssfuncs.php
1 <?php
2         define('DAEMON_UPDATE_LOGIN_LIMIT', 30);
3         define('DAEMON_FEED_LIMIT', 100);
4         define('DAEMON_SLEEP_INTERVAL', 60);
5
6         function update_feedbrowser_cache($link) {
7
8                 $result = db_query($link, "SELECT feed_url, site_url, title, COUNT(id) AS subscribers
9                         FROM ttrss_feeds WHERE (SELECT COUNT(id) = 0 FROM ttrss_feeds AS tf
10                                 WHERE tf.feed_url = ttrss_feeds.feed_url
11                                 AND (private IS true OR auth_login != '' OR auth_pass != '' OR feed_url LIKE '%:%@%/%'))
12                                 GROUP BY feed_url, site_url, title ORDER BY subscribers DESC LIMIT 1000");
13
14                 db_query($link, "BEGIN");
15
16                 db_query($link, "DELETE FROM ttrss_feedbrowser_cache");
17
18                 $count = 0;
19
20                 while ($line = db_fetch_assoc($result)) {
21                         $subscribers = db_escape_string($line["subscribers"]);
22                         $feed_url = db_escape_string($line["feed_url"]);
23                         $title = db_escape_string($line["title"]);
24                         $site_url = db_escape_string($line["site_url"]);
25
26                         $tmp_result = db_query($link, "SELECT subscribers FROM
27                                 ttrss_feedbrowser_cache WHERE feed_url = '$feed_url'");
28
29                         if (db_num_rows($tmp_result) == 0) {
30
31                                 db_query($link, "INSERT INTO ttrss_feedbrowser_cache
32                                         (feed_url, site_url, title, subscribers) VALUES ('$feed_url',
33                                                 '$site_url', '$title', '$subscribers')");
34
35                                 ++$count;
36
37                         }
38
39                 }
40
41                 db_query($link, "COMMIT");
42
43                 return $count;
44
45         }
46
47
48         /**
49          * Update a feed batch.
50          * Used by daemons to update n feeds by run.
51          * Only update feed needing a update, and not being processed
52          * by another process.
53          *
54          * @param mixed $link Database link
55          * @param integer $limit Maximum number of feeds in update batch. Default to DAEMON_FEED_LIMIT.
56          * @param boolean $from_http Set to true if you call this function from http to disable cli specific code.
57          * @param boolean $debug Set to false to disable debug output. Default to true.
58          * @return void
59          */
60         function update_daemon_common($link, $limit = DAEMON_FEED_LIMIT, $from_http = false, $debug = true) {
61                 // Process all other feeds using last_updated and interval parameters
62
63                 define('PREFS_NO_CACHE', true);
64
65                 // Test if the user has loggued in recently. If not, it does not update its feeds.
66                 if (!SINGLE_USER_MODE && DAEMON_UPDATE_LOGIN_LIMIT > 0) {
67                         if (DB_TYPE == "pgsql") {
68                                 $login_thresh_qpart = "AND ttrss_users.last_login >= NOW() - INTERVAL '".DAEMON_UPDATE_LOGIN_LIMIT." days'";
69                         } else {
70                                 $login_thresh_qpart = "AND ttrss_users.last_login >= DATE_SUB(NOW(), INTERVAL ".DAEMON_UPDATE_LOGIN_LIMIT." DAY)";
71                         }
72                 } else {
73                         $login_thresh_qpart = "";
74                 }
75
76                 // Test if the feed need a update (update interval exceded).
77                 if (DB_TYPE == "pgsql") {
78                         $update_limit_qpart = "AND ((
79                                         ttrss_feeds.update_interval = 0
80                                         AND ttrss_feeds.last_updated < NOW() - CAST((ttrss_user_prefs.value || ' minutes') AS INTERVAL)
81                                 ) OR (
82                                         ttrss_feeds.update_interval > 0
83                                         AND ttrss_feeds.last_updated < NOW() - CAST((ttrss_feeds.update_interval || ' minutes') AS INTERVAL)
84                                 ) OR ttrss_feeds.last_updated IS NULL
85                                 OR last_updated = '1970-01-01 00:00:00')";
86                 } else {
87                         $update_limit_qpart = "AND ((
88                                         ttrss_feeds.update_interval = 0
89                                         AND ttrss_feeds.last_updated < DATE_SUB(NOW(), INTERVAL CONVERT(ttrss_user_prefs.value, SIGNED INTEGER) MINUTE)
90                                 ) OR (
91                                         ttrss_feeds.update_interval > 0
92                                         AND ttrss_feeds.last_updated < DATE_SUB(NOW(), INTERVAL ttrss_feeds.update_interval MINUTE)
93                                 ) OR ttrss_feeds.last_updated IS NULL
94                                 OR last_updated = '1970-01-01 00:00:00')";
95                 }
96
97                 // Test if feed is currently being updated by another process.
98                 if (DB_TYPE == "pgsql") {
99                         $updstart_thresh_qpart = "AND (ttrss_feeds.last_update_started IS NULL OR ttrss_feeds.last_update_started < NOW() - INTERVAL '5 minutes')";
100                 } else {
101                         $updstart_thresh_qpart = "AND (ttrss_feeds.last_update_started IS NULL OR ttrss_feeds.last_update_started < DATE_SUB(NOW(), INTERVAL 5 MINUTE))";
102                 }
103
104                 // Test if there is a limit to number of updated feeds
105                 $query_limit = "";
106                 if($limit) $query_limit = sprintf("LIMIT %d", $limit);
107
108                 $random_qpart = sql_random_function();
109
110                 // We search for feed needing update.
111                 $result = db_query($link, "SELECT ttrss_feeds.feed_url,ttrss_feeds.id, ttrss_feeds.owner_uid,
112                                 ".SUBSTRING_FOR_DATE."(ttrss_feeds.last_updated,1,19) AS last_updated,
113                                 ttrss_feeds.update_interval
114                         FROM
115                                 ttrss_feeds, ttrss_users, ttrss_user_prefs
116                         WHERE
117                                 ttrss_feeds.owner_uid = ttrss_users.id
118                                 AND ttrss_users.id = ttrss_user_prefs.owner_uid
119                                 AND ttrss_user_prefs.pref_name = 'DEFAULT_UPDATE_INTERVAL'
120                                 $login_thresh_qpart $update_limit_qpart
121                          $updstart_thresh_qpart
122                         ORDER BY $random_qpart $query_limit");
123
124                 $user_prefs_cache = array();
125
126                 if($debug) _debug(sprintf("Scheduled %d feeds to update...\n", db_num_rows($result)));
127
128                 // Here is a little cache magic in order to minimize risk of double feed updates.
129                 $feeds_to_update = array();
130                 while ($line = db_fetch_assoc($result)) {
131                         $feeds_to_update[$line['id']] = $line;
132                 }
133
134                 // We update the feed last update started date before anything else.
135                 // There is no lag due to feed contents downloads
136                 // It prevent an other process to update the same feed.
137                 $feed_ids = array_keys($feeds_to_update);
138                 if($feed_ids) {
139                         db_query($link, sprintf("UPDATE ttrss_feeds SET last_update_started = NOW()
140                                 WHERE id IN (%s)", implode(',', $feed_ids)));
141                 }
142
143                 expire_cached_files($debug);
144                 expire_lock_files($debug);
145
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.
157                 send_headlines_digests($link, $debug);
158
159         } // function update_daemon_common
160
161         // ignore_daemon is not used
162         function update_rss_feed($link, $feed, $ignore_daemon = false, $no_cache = false,
163                 $override_url = false) {
164
165                 require_once "lib/simplepie/simplepie.inc";
166
167                 $debug_enabled = defined('DAEMON_EXTENDED_DEBUG') || $_REQUEST['xdebug'];
168
169                 if ($debug_enabled) {
170                         _debug("update_rss_feed: start");
171                 }
172
173                 $result = db_query($link, "SELECT id,update_interval,auth_login,
174                         feed_url,auth_pass,cache_images,last_updated,cache_content,
175                         mark_unread_on_update, owner_uid, update_on_checksum_change,
176                         pubsub_state
177                         FROM ttrss_feeds WHERE id = '$feed'");
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
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
200                 $cache_images = sql_bool_to_bool(db_fetch_result($result, 0, "cache_images"));
201                 $cache_content = sql_bool_to_bool(db_fetch_result($result, 0, "cache_content"));
202                 $fetch_url = db_fetch_result($result, 0, "feed_url");
203
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
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;
226
227                 $simplepie_cache_dir = CACHE_DIR . "/simplepie";
228
229                 if (!is_dir($simplepie_cache_dir)) {
230                         mkdir($simplepie_cache_dir);
231                 }
232
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);
239
240                 if ($debug_enabled) {
241                         _debug("feed update interval (sec): " .
242                                 get_feed_update_interval($link, $feed)*60);
243                 }
244
245                 $rss->enable_cache(!$no_cache);
246
247                 if (!$no_cache) {
248                         $rss->set_cache_location($simplepie_cache_dir);
249                         $rss->set_cache_duration($cache_age);
250                 }
251
252                 $rss->init();
253
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
262                 if (!$rss->error()) {
263
264                         if ($debug_enabled) {
265                                 _debug("update_rss_feed: processing feed data...");
266                         }
267
268 //                      db_query($link, "BEGIN");
269
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
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");
284                         $favicon_needs_check = sql_bool_to_bool(db_fetch_result($result, 0,
285                                 "favicon_needs_check"));
286
287                         $owner_uid = db_fetch_result($result, 0, "owner_uid");
288
289                         $site_url = db_escape_string(mb_substr(rewrite_relative_url($fetch_url, $rss->get_link()), 0, 250));
290
291                         if ($debug_enabled) {
292                                 _debug("update_rss_feed: checking favicon...");
293                         }
294
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                         }
301
302                         if (!$registered_title || $registered_title == "[Unknown]") {
303
304                                 $feed_title = db_escape_string($rss->get_title());
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
314                         if ($site_url && $orig_site_url != $site_url) {
315                                 db_query($link, "UPDATE ttrss_feeds SET
316                                         site_url = '$site_url' WHERE id = '$feed'");
317                         }
318
319                         $icon_url = db_escape_string(mb_substr(
320                                 rewrite_relative_url($fetch_url, $rss->get_image_url()), 0, 250));
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) {
327                                 _debug("update_rss_feed: loading filters & labels...");
328                         }
329
330                         $filters = load_filters($link, $feed, $owner_uid);
331                         $labels = get_all_labels($link, $owner_uid);
332
333                         if ($debug_enabled) {
334                                 //print_r($filters);
335                                 _debug("update_rss_feed: " . count($filters) . " filters loaded.");
336                         }
337
338                         $items = $rss->get_items();
339
340                         if (!is_array($items)) {
341                                 if ($debug_enabled) {
342                                         _debug("update_rss_feed: no articles found.");
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;
356
357                                 $links = $rss->get_links('hub');
358
359                                 if ($links && is_array($links)) {
360                                         foreach ($links as $l) {
361                                                 $feed_hub_url = $l;
362                                                 break;
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
392                         foreach ($items as $item) {
393                                 if ($_REQUEST['xdebug'] == 2) {
394                                         print_r($item);
395                                 }
396
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());
400
401                                 if ($cache_content) {
402                                         $entry_guid = "ccache:$entry_guid";
403                                 }
404
405                                 if ($auth_login || $auth_pass) {
406                                         $entry_guid = "auth,$owner_uid:$entry_guid";
407                                 }
408
409                                 if ($debug_enabled) {
410                                         _debug("update_rss_feed: guid $entry_guid");
411                                 }
412
413                                 if (!$entry_guid) continue;
414
415                                 $entry_timestamp = "";
416
417                                 $entry_timestamp = strtotime($item->get_date());
418
419                                 if ($entry_timestamp == -1 || !$entry_timestamp) {
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
432                                 $entry_title = $item->get_title();
433
434                                 $entry_link = rewrite_relative_url($site_url, htmlspecialchars_decode($item->get_link()));
435
436                                 if ($debug_enabled) {
437                                         _debug("update_rss_feed: title $entry_title");
438                                         _debug("update_rss_feed: link $entry_link");
439                                 }
440
441                                 if (!$entry_title) $entry_title = date("Y-m-d H:i:s", $entry_timestamp);;
442
443                                 $entry_content = $item->get_content();
444                                 if (!$entry_content) $entry_content = $item->get_description();
445
446                                 if ($cache_images && is_writable(CACHE_DIR . '/images'))
447                                         $entry_content = cache_images($entry_content, $site_url, $debug_enabled);
448
449                                 if ($_REQUEST["xdebug"] == 2) {
450                                         print "update_rss_feed: content: ";
451                                         print $entry_content;
452                                         print "\n";
453                                 }
454
455                                 $entry_cached_content = "";
456
457                                 $entry_comments = $item->data["comments"];
458
459                                 if ($item->get_author()) {
460                                         $entry_author_item = $item->get_author();
461                                         $entry_author = $entry_author_item->get_name();
462                                         if (!$entry_author) $entry_author = $entry_author_item->get_email();
463
464                                         $entry_author = db_escape_string($entry_author);
465                                 }
466
467                                 $entry_guid = db_escape_string(mb_substr($entry_guid, 0, 250));
468
469                                 $result = db_query($link, "SELECT id FROM       ttrss_entries
470                                         WHERE guid = '$entry_guid'");
471
472                                 $entry_comments = db_escape_string(mb_substr($entry_comments, 0, 250));
473                                 $entry_author = db_escape_string(mb_substr($entry_author, 0, 250));
474
475                                 $num_comments = $item->get_item_tags('http://purl.org/rss/1.0/modules/slash/', 'comments');
476
477                                 if (is_array($num_comments) && is_array($num_comments[0])) {
478                                         $num_comments = (int) $num_comments[0]["data"];
479                                 } else {
480                                         $num_comments = 0;
481                                 }
482
483                                 if ($debug_enabled) {
484                                         _debug("update_rss_feed: num_comments: $num_comments");
485                                         _debug("update_rss_feed: looking for tags [1]...");
486                                 }
487
488                                 // parse <category> entries into tags
489
490                                 $additional_tags = array();
491
492                                 $additional_tags_src = $item->get_categories();
493
494                                 if (is_array($additional_tags_src)) {
495                                         foreach ($additional_tags_src as $tobj) {
496                                                 array_push($additional_tags, $tobj->get_term());
497                                         }
498                                 }
499
500                                 if ($debug_enabled) {
501                                         _debug("update_rss_feed: category tags:");
502                                         print_r($additional_tags);
503                                 }
504
505                                 if ($debug_enabled) {
506                                         _debug("update_rss_feed: looking for tags [2]...");
507                                 }
508
509                                 $entry_tags = array_unique($additional_tags);
510
511                                 for ($i = 0; $i < count($entry_tags); $i++)
512                                         $entry_tags[$i] = mb_strtolower($entry_tags[$i], 'utf-8');
513
514                                 if ($debug_enabled) {
515                                         //_debug("update_rss_feed: unfiltered tags found:");
516                                         //print_r($entry_tags);
517                                 }
518
519                                 if ($debug_enabled) {
520                                         _debug("update_rss_feed: done collecting data [TITLE:$entry_title]");
521                                 }
522
523                                 // TODO: less memory-hungry implementation
524                                 global $pluginhost;
525
526                                 if ($debug_enabled) {
527                                         _debug("update_rss_feed: applying plugin filters..");
528                                 }
529
530                                 $article = array("owner_uid" => $owner_uid,
531                                         "title" => $entry_title,
532                                         "content" => $entry_content,
533                                         "link" => $entry_link,
534                                         "tags" => $entry_tags,
535                                         "author" => $entry_author);
536
537                                 foreach ($pluginhost->get_hooks($pluginhost::HOOK_ARTICLE_FILTER) as $plugin) {
538                                         $article = $plugin->hook_article_filter($article);
539                                 }
540
541                                 $entry_tags = $article["tags"];
542                                 $entry_content = db_escape_string($article["content"], false);
543                                 $entry_title = db_escape_string($article["title"]);
544                                 $entry_author = db_escape_string($article["author"]);
545                                 $entry_link = db_escape_string($article["link"]);
546
547                                 $content_hash = "SHA1:" . sha1(strip_tags($entry_content));
548
549                                 db_query($link, "BEGIN");
550
551                                 if (db_num_rows($result) == 0) {
552
553                                         if ($debug_enabled) {
554                                                 _debug("update_rss_feed: base guid not found");
555                                         }
556
557                                         if ($cache_content) {
558                                                 if ($debug_enabled) {
559                                                         _debug("update_rss_feed: caching content (initial)...");
560                                                 }
561
562                                                 $entry_cached_content = cache_content($link, $entry_link, $auth_login, $auth_pass);
563
564                                                 if ($cache_images && is_writable(CACHE_DIR . '/images'))
565                                                         $entry_cached_content = cache_images($entry_cached_content, $site_url, $debug_enabled);
566
567                                                 $entry_cached_content = db_escape_string($entry_cached_content, false);
568                                         }
569
570                                         // base post entry does not exist, create it
571
572                                         $result = db_query($link,
573                                                 "INSERT INTO ttrss_entries
574                                                         (title,
575                                                         guid,
576                                                         link,
577                                                         updated,
578                                                         content,
579                                                         content_hash,
580                                                         cached_content,
581                                                         no_orig_date,
582                                                         date_updated,
583                                                         date_entered,
584                                                         comments,
585                                                         num_comments,
586                                                         author)
587                                                 VALUES
588                                                         ('$entry_title',
589                                                         '$entry_guid',
590                                                         '$entry_link',
591                                                         '$entry_timestamp_fmt',
592                                                         '$entry_content',
593                                                         '$content_hash',
594                                                         '$entry_cached_content',
595                                                         $no_orig_date,
596                                                         NOW(),
597                                                         NOW(),
598                                                         '$entry_comments',
599                                                         '$num_comments',
600                                                         '$entry_author')");
601
602                                         $article_labels = array();
603
604                                 } else {
605                                         // we keep encountering the entry in feeds, so we need to
606                                         // update date_updated column so that we don't get horrible
607                                         // dupes when the entry gets purged and reinserted again e.g.
608                                         // in the case of SLOW SLOW OMG SLOW updating feeds
609
610                                         $base_entry_id = db_fetch_result($result, 0, "id");
611
612                                         db_query($link, "UPDATE ttrss_entries SET date_updated = NOW()
613                                                 WHERE id = '$base_entry_id'");
614
615                                         $article_labels = get_article_labels($link, $base_entry_id, $owner_uid);
616                                 }
617
618                                 // now it should exist, if not - bad luck then
619
620                                 $result = db_query($link, "SELECT
621                                                 id,content_hash,no_orig_date,title,
622                                                 ".SUBSTRING_FOR_DATE."(date_updated,1,19) as date_updated,
623                                                 ".SUBSTRING_FOR_DATE."(updated,1,19) as updated,
624                                                 num_comments, cached_content
625                                         FROM
626                                                 ttrss_entries
627                                         WHERE guid = '$entry_guid'");
628
629                                 $entry_ref_id = 0;
630                                 $entry_int_id = 0;
631
632                                 if (db_num_rows($result) == 1) {
633
634                                         if ($debug_enabled) {
635                                                 _debug("update_rss_feed: base guid found, checking for user record");
636                                         }
637
638                                         // this will be used below in update handler
639                                         $orig_content_hash = db_fetch_result($result, 0, "content_hash");
640                                         $orig_title = db_fetch_result($result, 0, "title");
641                                         $orig_num_comments = db_fetch_result($result, 0, "num_comments");
642                                         $orig_cached_content = trim(db_fetch_result($result, 0, "cached_content"));
643                                         $orig_date_updated = strtotime(db_fetch_result($result,
644                                                 0, "date_updated"));
645
646                                         $ref_id = db_fetch_result($result, 0, "id");
647                                         $entry_ref_id = $ref_id;
648
649                                         // check for user post link to main table
650
651                                         // do we allow duplicate posts with same GUID in different feeds?
652                                         if (get_pref($link, "ALLOW_DUPLICATE_POSTS", $owner_uid, false)) {
653                                                 $dupcheck_qpart = "AND (feed_id = '$feed' OR feed_id IS NULL)";
654                                         } else {
655                                                 $dupcheck_qpart = "";
656                                         }
657
658                                         /* Collect article tags here so we could filter by them: */
659
660                                         $article_filters = get_article_filters($filters, $entry_title,
661                                                 $entry_content, $entry_link, $entry_timestamp, $entry_author,
662                                                 $entry_tags);
663
664                                         if ($debug_enabled) {
665                                                 _debug("update_rss_feed: article filters: ");
666                                                 if (count($article_filters) != 0) {
667                                                         print_r($article_filters);
668                                                 }
669                                         }
670
671                                         if (find_article_filter($article_filters, "filter")) {
672                                                 db_query($link, "COMMIT"); // close transaction in progress
673                                                 continue;
674                                         }
675
676                                         $score = calculate_article_score($article_filters);
677
678                                         if ($debug_enabled) {
679                                                 _debug("update_rss_feed: initial score: $score");
680                                         }
681
682                                         $query = "SELECT ref_id, int_id FROM ttrss_user_entries WHERE
683                                                         ref_id = '$ref_id' AND owner_uid = '$owner_uid'
684                                                         $dupcheck_qpart";
685
686 //                                      if ($_REQUEST["xdebug"]) print "$query\n";
687
688                                         $result = db_query($link, $query);
689
690                                         // okay it doesn't exist - create user entry
691                                         if (db_num_rows($result) == 0) {
692
693                                                 if ($debug_enabled) {
694                                                         _debug("update_rss_feed: user record not found, creating...");
695                                                 }
696
697                                                 if ($score >= -500 && !find_article_filter($article_filters, 'catchup')) {
698                                                         $unread = 'true';
699                                                         $last_read_qpart = 'NULL';
700                                                 } else {
701                                                         $unread = 'false';
702                                                         $last_read_qpart = 'NOW()';
703                                                 }
704
705                                                 if (find_article_filter($article_filters, 'mark') || $score > 1000) {
706                                                         $marked = 'true';
707                                                 } else {
708                                                         $marked = 'false';
709                                                 }
710
711                                                 if (find_article_filter($article_filters, 'publish')) {
712                                                         $published = 'true';
713                                                 } else {
714                                                         $published = 'false';
715                                                 }
716
717                                                 // N-grams
718
719                                                 if (DB_TYPE == "pgsql" and defined('_NGRAM_TITLE_DUPLICATE_THRESHOLD')) {
720
721                                                         $result = db_query($link, "SELECT COUNT(*) AS similar FROM
722                                                                         ttrss_entries,ttrss_user_entries
723                                                                 WHERE ref_id = id AND updated >= NOW() - INTERVAL '7 day'
724                                                                         AND similarity(title, '$entry_title') >= "._NGRAM_TITLE_DUPLICATE_THRESHOLD."
725                                                                         AND owner_uid = $owner_uid");
726
727                                                         $ngram_similar = db_fetch_result($result, 0, "similar");
728
729                                                         if ($debug_enabled) {
730                                                                 _debug("update_rss_feed: N-gram similar results: $ngram_similar");
731                                                         }
732
733                                                         if ($ngram_similar > 0) {
734                                                                 $unread = 'false';
735                                                         }
736                                                 }
737
738                                                 $result = db_query($link,
739                                                         "INSERT INTO ttrss_user_entries
740                                                                 (ref_id, owner_uid, feed_id, unread, last_read, marked,
741                                                                         published, score, tag_cache, label_cache, uuid)
742                                                         VALUES ('$ref_id', '$owner_uid', '$feed', $unread,
743                                                                 $last_read_qpart, $marked, $published, '$score', '', '', '')");
744
745                                                 if (PUBSUBHUBBUB_HUB && $published == 'true') {
746                                                         $rss_link = get_self_url_prefix() .
747                                                                 "/public.php?op=rss&id=-2&key=" .
748                                                                 get_feed_access_key($link, -2, false, $owner_uid);
749
750                                                         $p = new Publisher(PUBSUBHUBBUB_HUB);
751
752                                                         $pubsub_result = $p->publish_update($rss_link);
753                                                 }
754
755                                                 $result = db_query($link,
756                                                         "SELECT int_id FROM ttrss_user_entries WHERE
757                                                                 ref_id = '$ref_id' AND owner_uid = '$owner_uid' AND
758                                                                 feed_id = '$feed' LIMIT 1");
759
760                                                 if (db_num_rows($result) == 1) {
761                                                         $entry_int_id = db_fetch_result($result, 0, "int_id");
762                                                 }
763                                         } else {
764                                                 if ($debug_enabled) {
765                                                         _debug("update_rss_feed: user record FOUND");
766                                                 }
767
768                                                 $entry_ref_id = db_fetch_result($result, 0, "ref_id");
769                                                 $entry_int_id = db_fetch_result($result, 0, "int_id");
770                                         }
771
772                                         if ($debug_enabled) {
773                                                 _debug("update_rss_feed: RID: $entry_ref_id, IID: $entry_int_id");
774                                         }
775
776                                         $post_needs_update = false;
777                                         $update_insignificant = false;
778                                         $cached_content_needs_update = false;
779
780                                         if ($orig_num_comments != $num_comments) {
781                                                 $post_needs_update = true;
782                                                 $update_insignificant = true;
783                                         }
784
785                                         if ($content_hash != $orig_content_hash) {
786                                                 $post_needs_update = true;
787                                                 $update_insignificant = false;
788                                                 $cached_content_needs_update = true;
789                                         }
790
791                                         if ($cache_content) {
792                                                 if ($debug_enabled) {
793                                                         _debug("update_rss_feed: caching content because original checksum changed...");
794                                                 }
795
796                                                 $entry_cached_content = cache_content($link, $entry_link, $auth_login, $auth_pass);
797
798                                                 if ($entry_cached_content) {
799                                                         if ($cache_images && is_writable(CACHE_DIR . '/images'))
800                                                                 $entry_cached_content = cache_images($entry_cached_content, $site_url, $debug_enabled);
801
802                                                         $entry_cached_content = db_escape_string($entry_cached_content, false);
803                                                         $post_needs_update = true;
804                                                 } else {
805                                                         $entry_cached_content = db_escape_string($orig_cached_content);
806                                                 }
807                                         } else {
808                                                 $entry_cached_content = db_escape_string($orig_cached_content);
809                                         }
810
811                                         if (db_escape_string($orig_title) != $entry_title) {
812                                                 $post_needs_update = true;
813                                                 $update_insignificant = false;
814                                         }
815
816                                         // if post needs update, update it and mark all user entries
817                                         // linking to this post as updated
818                                         if ($post_needs_update) {
819
820                                                 if (defined('DAEMON_EXTENDED_DEBUG')) {
821                                                         _debug("update_rss_feed: post $entry_guid needs update...");
822                                                 }
823
824 //                                              print "<!-- post $orig_title needs update : $post_needs_update -->";
825
826                                                 db_query($link, "UPDATE ttrss_entries
827                                                         SET title = '$entry_title', content = '$entry_content',
828                                                                 content_hash = '$content_hash',
829                                                                 cached_content = '$entry_cached_content',
830                                                                 updated = '$entry_timestamp_fmt',
831                                                                 num_comments = '$num_comments'
832                                                         WHERE id = '$ref_id'");
833
834                                                 if (!$update_insignificant) {
835                                                         if ($mark_unread_on_update) {
836                                                                 db_query($link, "UPDATE ttrss_user_entries
837                                                                         SET last_read = null, unread = true WHERE ref_id = '$ref_id'");
838                                                         } else if ($update_on_checksum_change) {
839                                                                 db_query($link, "UPDATE ttrss_user_entries
840                                                                         SET last_read = null WHERE ref_id = '$ref_id'
841                                                                                 AND unread = false");
842                                                         }
843                                                 }
844                                         }
845                                 }
846
847                                 db_query($link, "COMMIT");
848
849                                 if ($debug_enabled) {
850                                         _debug("update_rss_feed: assigning labels...");
851                                 }
852
853                                 assign_article_to_label_filters($link, $entry_ref_id, $article_filters,
854                                         $owner_uid, $article_labels);
855
856                                 if ($debug_enabled) {
857                                         _debug("update_rss_feed: looking for enclosures...");
858                                 }
859
860                                 // enclosures
861
862                                 $enclosures = array();
863
864                                 $encs = $item->get_enclosures();
865
866                                 if (is_array($encs)) {
867                                         foreach ($encs as $e) {
868                                                 $e_item = array(
869                                                         $e->link, $e->type, $e->length);
870                                                 array_push($enclosures, $e_item);
871                                         }
872                                 }
873
874                                 if ($debug_enabled) {
875                                         _debug("update_rss_feed: article enclosures:");
876                                         print_r($enclosures);
877                                 }
878
879                                 db_query($link, "BEGIN");
880
881                                 foreach ($enclosures as $enc) {
882                                         $enc_url = db_escape_string($enc[0]);
883                                         $enc_type = db_escape_string($enc[1]);
884                                         $enc_dur = db_escape_string($enc[2]);
885
886                                         $result = db_query($link, "SELECT id FROM ttrss_enclosures
887                                                 WHERE content_url = '$enc_url' AND post_id = '$entry_ref_id'");
888
889                                         if (db_num_rows($result) == 0) {
890                                                 db_query($link, "INSERT INTO ttrss_enclosures
891                                                         (content_url, content_type, title, duration, post_id) VALUES
892                                                         ('$enc_url', '$enc_type', '', '$enc_dur', '$entry_ref_id')");
893                                         }
894                                 }
895
896                                 db_query($link, "COMMIT");
897
898                                 // check for manual tags (we have to do it here since they're loaded from filters)
899
900                                 foreach ($article_filters as $f) {
901                                         if ($f["type"] == "tag") {
902
903                                                 $manual_tags = trim_array(explode(",", $f["param"]));
904
905                                                 foreach ($manual_tags as $tag) {
906                                                         if (tag_is_valid($tag)) {
907                                                                 array_push($entry_tags, $tag);
908                                                         }
909                                                 }
910                                         }
911                                 }
912
913                                 // Skip boring tags
914
915                                 $boring_tags = trim_array(explode(",", mb_strtolower(get_pref($link,
916                                         'BLACKLISTED_TAGS', $owner_uid, ''), 'utf-8')));
917
918                                 $filtered_tags = array();
919                                 $tags_to_cache = array();
920
921                                 if ($entry_tags && is_array($entry_tags)) {
922                                         foreach ($entry_tags as $tag) {
923                                                 if (array_search($tag, $boring_tags) === false) {
924                                                         array_push($filtered_tags, $tag);
925                                                 }
926                                         }
927                                 }
928
929                                 $filtered_tags = array_unique($filtered_tags);
930
931                                 if ($debug_enabled) {
932                                         _debug("update_rss_feed: filtered article tags:");
933                                         print_r($filtered_tags);
934                                 }
935
936                                 // Save article tags in the database
937
938                                 if (count($filtered_tags) > 0) {
939
940                                         db_query($link, "BEGIN");
941
942                                         foreach ($filtered_tags as $tag) {
943
944                                                 $tag = sanitize_tag($tag);
945                                                 $tag = db_escape_string($tag);
946
947                                                 if (!tag_is_valid($tag)) continue;
948
949                                                 $result = db_query($link, "SELECT id FROM ttrss_tags
950                                                         WHERE tag_name = '$tag' AND post_int_id = '$entry_int_id' AND
951                                                         owner_uid = '$owner_uid' LIMIT 1");
952
953                                                         if ($result && db_num_rows($result) == 0) {
954
955                                                                 db_query($link, "INSERT INTO ttrss_tags
956                                                                         (owner_uid,tag_name,post_int_id)
957                                                                         VALUES ('$owner_uid','$tag', '$entry_int_id')");
958                                                         }
959
960                                                 array_push($tags_to_cache, $tag);
961                                         }
962
963                                         /* update the cache */
964
965                                         $tags_to_cache = array_unique($tags_to_cache);
966
967                                         $tags_str = db_escape_string(join(",", $tags_to_cache));
968
969                                         db_query($link, "UPDATE ttrss_user_entries
970                                                 SET tag_cache = '$tags_str' WHERE ref_id = '$entry_ref_id'
971                                                 AND owner_uid = $owner_uid");
972
973                                         db_query($link, "COMMIT");
974                                 }
975
976                                 if (get_pref($link, "AUTO_ASSIGN_LABELS", $owner_uid, false)) {
977                                         if ($debug_enabled) {
978                                                 _debug("update_rss_feed: auto-assigning labels...");
979                                         }
980
981                                         foreach ($labels as $label) {
982                                                 $caption = $label["caption"];
983
984                                                 if (preg_match("/\b$caption\b/i", "$tags_str " . strip_tags($entry_content) . " $entry_title")) {
985                                                         if (!labels_contains_caption($article_labels, $caption)) {
986                                                                 label_add_article($link, $entry_ref_id, $caption, $owner_uid);
987                                                         }
988                                                 }
989                                         }
990                                 }
991
992                                 if ($debug_enabled) {
993                                         _debug("update_rss_feed: article processed");
994                                 }
995                         }
996
997                         if (!$last_updated) {
998                                 if ($debug_enabled) {
999                                         _debug("update_rss_feed: new feed, catching it up...");
1000                                 }
1001                                 catchup_feed($link, $feed, false, $owner_uid);
1002                         }
1003
1004                         if ($debug_enabled) {
1005                                 _debug("purging feed...");
1006                         }
1007
1008                         purge_feed($link, $feed, 0, $debug_enabled);
1009
1010                         db_query($link, "UPDATE ttrss_feeds
1011                                 SET last_updated = NOW(), last_error = '' WHERE id = '$feed'");
1012
1013 //                      db_query($link, "COMMIT");
1014
1015                 } else {
1016
1017                         $error_msg = mb_substr($rss->error(), 0, 250);
1018
1019                         if ($debug_enabled) {
1020                                 _debug("update_rss_feed: error fetching feed: $error_msg");
1021                         }
1022
1023                         $error_msg = db_escape_string($error_msg);
1024
1025                         db_query($link,
1026                                 "UPDATE ttrss_feeds SET last_error = '$error_msg',
1027                                         last_updated = NOW() WHERE id = '$feed'");
1028                 }
1029
1030                 unset($rss);
1031
1032                 if ($debug_enabled) {
1033                         _debug("update_rss_feed: done");
1034                 }
1035
1036         }
1037
1038         function cache_images($html, $site_url, $debug) {
1039                 $cache_dir = CACHE_DIR . "/images";
1040
1041                 libxml_use_internal_errors(true);
1042
1043                 $charset_hack = '<head>
1044                         <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
1045                 </head>';
1046
1047                 $doc = new DOMDocument();
1048                 $doc->loadHTML($charset_hack . $html);
1049                 $xpath = new DOMXPath($doc);
1050
1051                 $entries = $xpath->query('(//img[@src])');
1052
1053                 foreach ($entries as $entry) {
1054                         if ($entry->hasAttribute('src')) {
1055                                 $src = rewrite_relative_url($site_url, $entry->getAttribute('src'));
1056
1057                                 $local_filename = CACHE_DIR . "/images/" . sha1($src) . ".png";
1058
1059                                 if ($debug) _debug("cache_images: downloading: $src to $local_filename");
1060
1061                                 if (!file_exists($local_filename)) {
1062                                         $file_content = fetch_file_contents($src);
1063
1064                                         if ($file_content && strlen($file_content) > 1024) {
1065                                                 file_put_contents($local_filename, $file_content);
1066                                         }
1067                                 }
1068
1069                                 if (file_exists($local_filename)) {
1070                                         $entry->setAttribute('src', SELF_URL_PATH . '/image.php?url=' .
1071                                                 base64_encode($src));
1072                                 }
1073                         }
1074                 }
1075
1076                 $node = $doc->getElementsByTagName('body')->item(0);
1077
1078                 return $doc->saveXML($node, LIBXML_NOEMPTYTAG);
1079         }
1080
1081         function expire_lock_files($debug) {
1082                 if ($debug) _debug("Removing old lock files...");
1083
1084                 $num_deleted = 0;
1085
1086                 if (is_writable(LOCK_DIRECTORY)) {
1087                         $files = glob(LOCK_DIRECTORY . "/*.lock");
1088
1089                         if ($files) {
1090                                 foreach ($files as $file) {
1091                                         if (!file_is_locked($file) && time() - filemtime($file) > 86400*2) {
1092                                                 unlink($file);
1093                                                 ++$num_deleted;
1094                                         }
1095                                 }
1096                         }
1097                 }
1098
1099                 if ($debug) _debug("Removed $num_deleted files.");
1100         }
1101
1102         function expire_cached_files($debug) {
1103                 foreach (array("simplepie", "images", "export") as $dir) {
1104                         $cache_dir = CACHE_DIR . "/$dir";
1105
1106                         if ($debug) _debug("Expiring $cache_dir");
1107
1108                         $num_deleted = 0;
1109
1110                         if (is_writable($cache_dir)) {
1111                                 $files = glob("$cache_dir/*");
1112
1113                                 if ($files) {
1114                                         foreach ($files as $file) {
1115                                                 if (time() - filemtime($file) > 86400*7) {
1116                                                         unlink($file);
1117
1118                                                         ++$num_deleted;
1119                                                 }
1120                                         }
1121                                 }
1122                         }
1123
1124                         if ($debug) _debug("Removed $num_deleted files.");
1125                 }
1126         }
1127
1128         /**
1129         * Source: http://www.php.net/manual/en/function.parse-url.php#104527
1130         * Returns the url query as associative array
1131         *
1132         * @param    string    query
1133         * @return    array    params
1134         */
1135         function convertUrlQuery($query) {
1136                 $queryParts = explode('&', $query);
1137
1138                 $params = array();
1139
1140                 foreach ($queryParts as $param) {
1141                         $item = explode('=', $param);
1142                         $params[$item[0]] = $item[1];
1143                 }
1144
1145                 return $params;
1146         }
1147
1148         function get_article_filters($filters, $title, $content, $link, $timestamp, $author, $tags) {
1149                 $matches = array();
1150
1151                 foreach ($filters as $filter) {
1152                         $match_any_rule = $filter["match_any_rule"];
1153                         $filter_match = false;
1154
1155                         foreach ($filter["rules"] as $rule) {
1156                                 $match = false;
1157                                 $reg_exp = $rule["reg_exp"];
1158
1159                                 if (!$reg_exp)
1160                                         continue;
1161
1162                                 switch ($rule["type"]) {
1163                                 case "title":
1164                                         $match = @preg_match("/$reg_exp/i", $title);
1165                                         break;
1166                                 case "content":
1167                                         // we don't need to deal with multiline regexps
1168                                         $content = preg_replace("/[\r\n\t]/", "", $content);
1169
1170                                         $match = @preg_match("/$reg_exp/i", $content);
1171                                         break;
1172                                 case "both":
1173                                         // we don't need to deal with multiline regexps
1174                                         $content = preg_replace("/[\r\n\t]/", "", $content);
1175
1176                                         $match = (@preg_match("/$reg_exp/i", $title) || @preg_match("/$reg_exp/i", $content));
1177                                         break;
1178                                 case "link":
1179                                         $match = @preg_match("/$reg_exp/i", $link);
1180                                         break;
1181                                 case "author":
1182                                         $match = @preg_match("/$reg_exp/i", $author);
1183                                         break;
1184                                 case "tag":
1185                                         $tag_string = join(",", $tags);
1186                                         $match = @preg_match("/$reg_exp/i", $tag_string);
1187                                         break;
1188                                 }
1189
1190                                 if ($match_any_rule) {
1191                                         if ($match) {
1192                                                 $filter_match = true;
1193                                                 break;
1194                                         }
1195                                 } else {
1196                                         $filter_match = $match;
1197                                         if (!$match) {
1198                                                 break;
1199                                         }
1200                                 }
1201                         }
1202
1203                         if ($filter_match) {
1204                                 foreach ($filter["actions"] AS $action) {
1205                                         array_push($matches, $action);
1206                                 }
1207                         }
1208                 }
1209
1210                 return $matches;
1211         }
1212
1213         function find_article_filter($filters, $filter_name) {
1214                 foreach ($filters as $f) {
1215                         if ($f["type"] == $filter_name) {
1216                                 return $f;
1217                         };
1218                 }
1219                 return false;
1220         }
1221
1222         function find_article_filters($filters, $filter_name) {
1223                 $results = array();
1224
1225                 foreach ($filters as $f) {
1226                         if ($f["type"] == $filter_name) {
1227                                 array_push($results, $f);
1228                         };
1229                 }
1230                 return $results;
1231         }
1232
1233         function calculate_article_score($filters) {
1234                 $score = 0;
1235
1236                 foreach ($filters as $f) {
1237                         if ($f["type"] == "score") {
1238                                 $score += $f["param"];
1239                         };
1240                 }
1241                 return $score;
1242         }
1243
1244         function labels_contains_caption($labels, $caption) {
1245                 foreach ($labels as $label) {
1246                         if ($label[1] == $caption) {
1247                                 return true;
1248                         }
1249                 }
1250
1251                 return false;
1252         }
1253
1254         function assign_article_to_label_filters($link, $id, $filters, $owner_uid, $article_labels) {
1255                 foreach ($filters as $f) {
1256                         if ($f["type"] == "label") {
1257                                 if (!labels_contains_caption($article_labels, $f["param"])) {
1258                                         label_add_article($link, $id, $f["param"], $owner_uid);
1259                                 }
1260                         }
1261                 }
1262         }
1263
1264         function cache_content($link, $url, $login, $pass) {
1265
1266                 $content = fetch_file_contents($url, $login, $pass);
1267
1268                 if ($content) {
1269                         $doc = new DOMDocument();
1270                         @$doc->loadHTML($content);
1271                         $xpath = new DOMXPath($doc);
1272
1273                         $node = $doc->getElementsByTagName('body')->item(0);
1274
1275                         if ($node) {
1276                                 $content = $doc->saveXML($node, LIBXML_NOEMPTYTAG);
1277
1278                                 return $content;
1279                         }
1280                 }
1281
1282                 return "";
1283         }
1284 ?>