]> git.wh0rd.org Git - tt-rss.git/blob - include/rssfuncs.php
fix previous, owner_uid not passed in daemon context
[tt-rss.git] / include / rssfuncs.php
1 <?php
2         define_default('DAEMON_UPDATE_LOGIN_LIMIT', 30);
3         define_default('DAEMON_FEED_LIMIT', 500);
4         define_default('DAEMON_SLEEP_INTERVAL', 120);
5         define_default('_MIN_CACHE_IMAGE_SIZE', 1024);
6
7         function calculate_article_hash($article, $pluginhost) {
8                 $tmp = "";
9
10                 foreach ($article as $k => $v) {
11                         if ($k != "feed" && isset($v)) {
12                                 $x = strip_tags(is_array($v) ? implode(",", $v) : $v);
13
14                                 //_debug("$k:" . sha1($x) . ":" . htmlspecialchars($x), true);
15
16                                 $tmp .= sha1("$k:" . sha1($x));
17                         }
18                 }
19
20                 return sha1(implode(",", $pluginhost->get_plugin_names()) . $tmp);
21         }
22
23         function update_feedbrowser_cache() {
24
25                 $result = db_query("SELECT feed_url, site_url, title, COUNT(id) AS subscribers
26                         FROM ttrss_feeds WHERE (SELECT COUNT(id) = 0 FROM ttrss_feeds AS tf
27                                 WHERE tf.feed_url = ttrss_feeds.feed_url
28                                 AND (private IS true OR auth_login != '' OR auth_pass != '' OR feed_url LIKE '%:%@%/%'))
29                                 GROUP BY feed_url, site_url, title ORDER BY subscribers DESC LIMIT 1000");
30
31                 db_query("BEGIN");
32
33                 db_query("DELETE FROM ttrss_feedbrowser_cache");
34
35                 $count = 0;
36
37                 while ($line = db_fetch_assoc($result)) {
38                         $subscribers = db_escape_string($line["subscribers"]);
39                         $feed_url = db_escape_string($line["feed_url"]);
40                         $title = db_escape_string($line["title"]);
41                         $site_url = db_escape_string($line["site_url"]);
42
43                         $tmp_result = db_query("SELECT subscribers FROM
44                                 ttrss_feedbrowser_cache WHERE feed_url = '$feed_url'");
45
46                         if (db_num_rows($tmp_result) == 0) {
47
48                                 db_query("INSERT INTO ttrss_feedbrowser_cache
49                                         (feed_url, site_url, title, subscribers) VALUES ('$feed_url',
50                                                 '$site_url', '$title', '$subscribers')");
51
52                                 ++$count;
53
54                         }
55
56                 }
57
58                 db_query("COMMIT");
59
60                 return $count;
61
62         }
63
64
65         /**
66          * Update a feed batch.
67          * Used by daemons to update n feeds by run.
68          * Only update feed needing a update, and not being processed
69          * by another process.
70          *
71          * @param mixed $link Database link
72          * @param integer $limit Maximum number of feeds in update batch. Default to DAEMON_FEED_LIMIT.
73          * @param boolean $from_http Set to true if you call this function from http to disable cli specific code.
74          * @param boolean $debug Set to false to disable debug output. Default to true.
75          * @return void
76          */
77         function update_daemon_common($limit = DAEMON_FEED_LIMIT, $from_http = false, $debug = true) {
78                 // Process all other feeds using last_updated and interval parameters
79
80                 $schema_version = get_schema_version();
81
82                 if ($schema_version != SCHEMA_VERSION) {
83                         die("Schema version is wrong, please upgrade the database.\n");
84                 }
85
86                 define('PREFS_NO_CACHE', true);
87
88                 // Test if the user has loggued in recently. If not, it does not update its feeds.
89                 if (!SINGLE_USER_MODE && DAEMON_UPDATE_LOGIN_LIMIT > 0) {
90                         if (DB_TYPE == "pgsql") {
91                                 $login_thresh_qpart = "AND ttrss_users.last_login >= NOW() - INTERVAL '".DAEMON_UPDATE_LOGIN_LIMIT." days'";
92                         } else {
93                                 $login_thresh_qpart = "AND ttrss_users.last_login >= DATE_SUB(NOW(), INTERVAL ".DAEMON_UPDATE_LOGIN_LIMIT." DAY)";
94                         }
95                 } else {
96                         $login_thresh_qpart = "";
97                 }
98
99                 // Test if the feed need a update (update interval exceeded).
100                 if (DB_TYPE == "pgsql") {
101                         $update_limit_qpart = "AND ((
102                                         ttrss_feeds.update_interval = 0
103                                         AND ttrss_user_prefs.value != '-1'
104                                         AND ttrss_feeds.last_updated < NOW() - CAST((ttrss_user_prefs.value || ' minutes') AS INTERVAL)
105                                 ) OR (
106                                         ttrss_feeds.update_interval > 0
107                                         AND ttrss_feeds.last_updated < NOW() - CAST((ttrss_feeds.update_interval || ' minutes') AS INTERVAL)
108                                 ) OR (ttrss_feeds.last_updated IS NULL
109                                         AND ttrss_user_prefs.value != '-1')
110                                 OR (last_updated = '1970-01-01 00:00:00'
111                                         AND ttrss_user_prefs.value != '-1'))";
112                 } else {
113                         $update_limit_qpart = "AND ((
114                                         ttrss_feeds.update_interval = 0
115                                         AND ttrss_user_prefs.value != '-1'
116                                         AND ttrss_feeds.last_updated < DATE_SUB(NOW(), INTERVAL CONVERT(ttrss_user_prefs.value, SIGNED INTEGER) MINUTE)
117                                 ) OR (
118                                         ttrss_feeds.update_interval > 0
119                                         AND ttrss_feeds.last_updated < DATE_SUB(NOW(), INTERVAL ttrss_feeds.update_interval MINUTE)
120                                 ) OR (ttrss_feeds.last_updated IS NULL
121                                         AND ttrss_user_prefs.value != '-1')
122                                 OR (last_updated = '1970-01-01 00:00:00'
123                                         AND ttrss_user_prefs.value != '-1'))";
124                 }
125
126                 // Test if feed is currently being updated by another process.
127                 if (DB_TYPE == "pgsql") {
128                         $updstart_thresh_qpart = "AND (ttrss_feeds.last_update_started IS NULL OR ttrss_feeds.last_update_started < NOW() - INTERVAL '10 minutes')";
129                 } else {
130                         $updstart_thresh_qpart = "AND (ttrss_feeds.last_update_started IS NULL OR ttrss_feeds.last_update_started < DATE_SUB(NOW(), INTERVAL 10 MINUTE))";
131                 }
132
133                 // Test if there is a limit to number of updated feeds
134                 $query_limit = "";
135                 if($limit) $query_limit = sprintf("LIMIT %d", $limit);
136
137                 $query = "SELECT DISTINCT ttrss_feeds.feed_url, ttrss_feeds.last_updated
138                         FROM
139                                 ttrss_feeds, ttrss_users, ttrss_user_prefs
140                         WHERE
141                                 ttrss_feeds.owner_uid = ttrss_users.id
142                                 AND ttrss_user_prefs.profile IS NULL
143                                 AND ttrss_users.id = ttrss_user_prefs.owner_uid
144                                 AND ttrss_user_prefs.pref_name = 'DEFAULT_UPDATE_INTERVAL'
145                                 $login_thresh_qpart $update_limit_qpart
146                                 $updstart_thresh_qpart
147                                 ORDER BY last_updated $query_limit";
148
149                 // We search for feed needing update.
150                 $result = db_query($query);
151
152                 if($debug) _debug(sprintf("Scheduled %d feeds to update...", db_num_rows($result)));
153
154                 // Here is a little cache magic in order to minimize risk of double feed updates.
155                 $feeds_to_update = array();
156                 while ($line = db_fetch_assoc($result)) {
157                         array_push($feeds_to_update, db_escape_string($line['feed_url']));
158                 }
159
160                 // We update the feed last update started date before anything else.
161                 // There is no lag due to feed contents downloads
162                 // It prevent an other process to update the same feed.
163
164                 if(count($feeds_to_update) > 0) {
165                         $feeds_quoted = array();
166
167                         foreach ($feeds_to_update as $feed) {
168                                 array_push($feeds_quoted, "'" . db_escape_string($feed) . "'");
169                         }
170
171                         db_query(sprintf("UPDATE ttrss_feeds SET last_update_started = NOW()
172                                 WHERE feed_url IN (%s)", implode(',', $feeds_quoted)));
173                 }
174
175                 $nf = 0;
176                 $bstarted = microtime(true);
177
178                 // For each feed, we call the feed update function.
179                 foreach ($feeds_to_update as $feed) {
180                         if($debug) _debug("Base feed: $feed");
181
182                         //update_rss_feed($line["id"], true);
183
184                         // since we have the data cached, we can deal with other feeds with the same url
185
186                         $tmp_result = db_query("SELECT DISTINCT ttrss_feeds.id,last_updated,ttrss_feeds.owner_uid
187                         FROM ttrss_feeds, ttrss_users, ttrss_user_prefs WHERE
188                                 ttrss_user_prefs.owner_uid = ttrss_feeds.owner_uid AND
189                                 ttrss_users.id = ttrss_user_prefs.owner_uid AND
190                                 ttrss_user_prefs.pref_name = 'DEFAULT_UPDATE_INTERVAL' AND
191                                 ttrss_user_prefs.profile IS NULL AND
192                                 feed_url = '".db_escape_string($feed)."' AND
193                                 (ttrss_feeds.update_interval > 0 OR
194                                         ttrss_user_prefs.value != '-1')
195                                 $login_thresh_qpart
196                         ORDER BY ttrss_feeds.id $query_limit");
197
198                         if (db_num_rows($tmp_result) > 0) {
199                                 $rss = false;
200
201                                 while ($tline = db_fetch_assoc($tmp_result)) {
202                                         if($debug) _debug(" => " . $tline["last_updated"] . ", " . $tline["id"] . " " . $tline["owner_uid"]);
203
204                                         $fstarted = microtime(true);
205                                         $rss = update_rss_feed($tline["id"], true, false);
206                                         _debug_suppress(false);
207
208                                         _debug(sprintf("    %.4f (sec)", microtime(true) - $fstarted));
209
210                                         ++$nf;
211                                 }
212                         }
213                 }
214
215                 if ($nf > 0) {
216                         _debug(sprintf("Processed %d feeds in %.4f (sec), %.4f (sec/feed avg)", $nf,
217                                 microtime(true) - $bstarted, (microtime(true) - $bstarted) / $nf));
218                 }
219
220                 require_once "digest.php";
221
222                 // Send feed digests by email if needed.
223                 send_headlines_digests($debug);
224
225                 return $nf;
226
227         } // function update_daemon_common
228
229         // this is used when subscribing
230         function set_basic_feed_info($feed) {
231
232                 $feed = db_escape_string($feed);
233
234                 $result = db_query("SELECT feed_url,auth_pass,auth_login,auth_pass_encrypted
235                                         FROM ttrss_feeds WHERE id = '$feed'");
236
237                 $auth_pass_encrypted = sql_bool_to_bool(db_fetch_result($result,
238                         0, "auth_pass_encrypted"));
239
240                 $auth_login = db_fetch_result($result, 0, "auth_login");
241                 $auth_pass = db_fetch_result($result, 0, "auth_pass");
242
243                 if ($auth_pass_encrypted) {
244                         require_once "crypt.php";
245                         $auth_pass = decrypt_string($auth_pass);
246                 }
247
248                 $fetch_url = db_fetch_result($result, 0, "feed_url");
249
250                 $feed_data = fetch_file_contents($fetch_url, false,
251                         $auth_login, $auth_pass, false,
252                         FEED_FETCH_TIMEOUT_TIMEOUT,
253                         0);
254
255                 global $fetch_curl_used;
256
257                 if (!$fetch_curl_used) {
258                         $tmp = @gzdecode($feed_data);
259
260                         if ($tmp) $feed_data = $tmp;
261                 }
262
263                 $feed_data = trim($feed_data);
264
265                 $rss = new FeedParser($feed_data);
266                 $rss->init();
267
268                 if (!$rss->error()) {
269
270                         $result = db_query("SELECT title, site_url FROM ttrss_feeds WHERE id = '$feed'");
271
272                         $registered_title = db_fetch_result($result, 0, "title");
273                         $orig_site_url = db_fetch_result($result, 0, "site_url");
274
275                         $site_url = db_escape_string(mb_substr(rewrite_relative_url($fetch_url, $rss->get_link()), 0, 245));
276                         $feed_title = db_escape_string(mb_substr($rss->get_title(), 0, 199));
277
278                         if ($feed_title && (!$registered_title || $registered_title == "[Unknown]")) {
279                                 db_query("UPDATE ttrss_feeds SET
280                                         title = '$feed_title' WHERE id = '$feed'");
281                         }
282
283                         if ($site_url && $orig_site_url != $site_url) {
284                                 db_query("UPDATE ttrss_feeds SET
285                                                         site_url = '$site_url' WHERE id = '$feed'");
286                         }
287                 }
288         }
289
290         // ignore_daemon is not used
291         function update_rss_feed($feed, $ignore_daemon = false, $no_cache = false, $rss = false) {
292
293                 $debug_enabled = defined('DAEMON_EXTENDED_DEBUG') || $_REQUEST['xdebug'];
294
295                 _debug_suppress(!$debug_enabled);
296                 _debug("start", $debug_enabled);
297
298                 $result = db_query("SELECT title FROM ttrss_feeds
299                         WHERE id = '$feed'");
300                 $title = db_fetch_result($result, 0, "title");
301
302                 // feed was batch-subscribed or something, we need to get basic info
303                 // this is not optimal currently as it fetches stuff separately TODO: optimize
304                 if ($title == "[Unknown]") {
305                         _debug("setting basic feed info for $feed...");
306                         set_basic_feed_info($feed);
307                 }
308
309                 $result = db_query("SELECT id,update_interval,auth_login,
310                         feed_url,auth_pass,cache_images,
311                         mark_unread_on_update, owner_uid,
312                         pubsub_state, auth_pass_encrypted,
313                         feed_language,
314                         (SELECT max(date_entered) FROM
315                                 ttrss_entries, ttrss_user_entries where ref_id = id AND feed_id = '$feed') AS last_article_timestamp
316                         FROM ttrss_feeds WHERE id = '$feed'");
317
318                 if (db_num_rows($result) == 0) {
319                         _debug("feed $feed NOT FOUND/SKIPPED", $debug_enabled);
320                         return false;
321                 }
322
323                 $last_article_timestamp = @strtotime(db_fetch_result($result, 0, "last_article_timestamp"));
324
325                 if (defined('_DISABLE_HTTP_304'))
326                         $last_article_timestamp = 0;
327
328                 $owner_uid = db_fetch_result($result, 0, "owner_uid");
329                 $mark_unread_on_update = sql_bool_to_bool(db_fetch_result($result,
330                         0, "mark_unread_on_update"));
331                 $pubsub_state = db_fetch_result($result, 0, "pubsub_state");
332                 $auth_pass_encrypted = sql_bool_to_bool(db_fetch_result($result,
333                         0, "auth_pass_encrypted"));
334
335                 db_query("UPDATE ttrss_feeds SET last_update_started = NOW()
336                         WHERE id = '$feed'");
337
338                 $auth_login = db_fetch_result($result, 0, "auth_login");
339                 $auth_pass = db_fetch_result($result, 0, "auth_pass");
340
341                 if ($auth_pass_encrypted) {
342                         require_once "crypt.php";
343                         $auth_pass = decrypt_string($auth_pass);
344                 }
345
346                 $cache_images = sql_bool_to_bool(db_fetch_result($result, 0, "cache_images"));
347                 $fetch_url = db_fetch_result($result, 0, "feed_url");
348                 $feed_language = db_escape_string(mb_strtolower(db_fetch_result($result, 0, "feed_language")));
349                 if (!$feed_language) $feed_language = 'english';
350
351                 $feed = db_escape_string($feed);
352
353                 $date_feed_processed = date('Y-m-d H:i');
354
355                 $cache_filename = CACHE_DIR . "/simplepie/" . sha1($fetch_url) . ".xml";
356
357                 $pluginhost = new PluginHost();
358                 $pluginhost->set_debug($debug_enabled);
359                 $user_plugins = get_pref("_ENABLED_PLUGINS", $owner_uid);
360
361                 $pluginhost->load(PLUGINS, PluginHost::KIND_ALL);
362                 $pluginhost->load($user_plugins, PluginHost::KIND_USER, $owner_uid);
363                 $pluginhost->load_data();
364
365                 if ($rss && is_object($rss) && get_class($rss) == "FeedParser") {
366                         _debug("using previously initialized parser object");
367                 } else {
368                         $rss_hash = false;
369
370                         $force_refetch = isset($_REQUEST["force_refetch"]);
371
372                         foreach ($pluginhost->get_hooks(PluginHost::HOOK_FETCH_FEED) as $plugin) {
373                                 $feed_data = $plugin->hook_fetch_feed($feed_data, $fetch_url, $owner_uid, $feed, $last_article_timestamp, $auth_login, $auth_pass);
374                         }
375
376                         // try cache
377                         if (!$feed_data &&
378                                 file_exists($cache_filename) &&
379                                 is_readable($cache_filename) &&
380                                 !$auth_login && !$auth_pass &&
381                                 filemtime($cache_filename) > time() - 30) {
382
383                                 _debug("using local cache [$cache_filename].", $debug_enabled);
384
385                                 @$feed_data = file_get_contents($cache_filename);
386
387                                 if ($feed_data) {
388                                         $rss_hash = sha1($feed_data);
389                                 }
390
391                         } else {
392                                 _debug("local cache will not be used for this feed", $debug_enabled);
393                         }
394
395                         // fetch feed from source
396                         if (!$feed_data) {
397                                 _debug("fetching [$fetch_url]...", $debug_enabled);
398                                 _debug("If-Modified-Since: ".gmdate('D, d M Y H:i:s \G\M\T', $last_article_timestamp), $debug_enabled);
399
400                                 $feed_data = fetch_file_contents($fetch_url, false,
401                                         $auth_login, $auth_pass, false,
402                                         $no_cache ? FEED_FETCH_NO_CACHE_TIMEOUT : FEED_FETCH_TIMEOUT,
403                                         $force_refetch ? 0 : $last_article_timestamp);
404
405                                 global $fetch_curl_used;
406
407                                 if (!$fetch_curl_used) {
408                                         $tmp = @gzdecode($feed_data);
409
410                                         if ($tmp) $feed_data = $tmp;
411                                 }
412
413                                 $feed_data = trim($feed_data);
414
415                                 _debug("fetch done.", $debug_enabled);
416
417                                 // cache vanilla feed data for re-use
418                                 if ($feed_data && !$auth_pass && !$auth_login && is_writable(CACHE_DIR . "/simplepie")) {
419                                         $new_rss_hash = sha1($feed_data);
420
421                                         if ($new_rss_hash != $rss_hash) {
422                                                 _debug("saving $cache_filename", $debug_enabled);
423                                                 @file_put_contents($cache_filename, $feed_data);
424                                         }
425                                 }
426                         }
427
428                         if (!$feed_data) {
429                                 global $fetch_last_error;
430                                 global $fetch_last_error_code;
431
432                                 _debug("unable to fetch: $fetch_last_error [$fetch_last_error_code]", $debug_enabled);
433
434                                 $error_escaped = '';
435
436                                 // If-Modified-Since
437                                 if ($fetch_last_error_code != 304) {
438                                         $error_escaped = db_escape_string($fetch_last_error);
439                                 } else {
440                                         _debug("source claims data not modified, nothing to do.", $debug_enabled);
441                                 }
442
443                                 db_query(
444                                         "UPDATE ttrss_feeds SET last_error = '$error_escaped',
445                                                 last_updated = NOW() WHERE id = '$feed'");
446
447                                 return;
448                         }
449                 }
450
451                 foreach ($pluginhost->get_hooks(PluginHost::HOOK_FEED_FETCHED) as $plugin) {
452                         $feed_data = $plugin->hook_feed_fetched($feed_data, $fetch_url, $owner_uid, $feed);
453                 }
454
455                 // set last update to now so if anything *simplepie* crashes later we won't be
456                 // continuously failing on the same feed
457                 //db_query("UPDATE ttrss_feeds SET last_updated = NOW() WHERE id = '$feed'");
458
459                 if (!$rss) {
460                         $rss = new FeedParser($feed_data);
461                         $rss->init();
462                 }
463
464 //              print_r($rss);
465
466                 $feed = db_escape_string($feed);
467
468                 if (!$rss->error()) {
469
470                         // We use local pluginhost here because we need to load different per-user feed plugins
471                         $pluginhost->run_hooks(PluginHost::HOOK_FEED_PARSED, "hook_feed_parsed", $rss);
472
473                         _debug("language: $feed_language", $debug_enabled);
474                         _debug("processing feed data...", $debug_enabled);
475
476 //                      db_query("BEGIN");
477
478                         if (DB_TYPE == "pgsql") {
479                                 $favicon_interval_qpart = "favicon_last_checked < NOW() - INTERVAL '12 hour'";
480                         } else {
481                                 $favicon_interval_qpart = "favicon_last_checked < DATE_SUB(NOW(), INTERVAL 12 HOUR)";
482                         }
483
484                         $result = db_query("SELECT owner_uid,favicon_avg_color,
485                                 (favicon_last_checked IS NULL OR $favicon_interval_qpart) AS
486                                                 favicon_needs_check
487                                 FROM ttrss_feeds WHERE id = '$feed'");
488
489                         $favicon_needs_check = sql_bool_to_bool(db_fetch_result($result, 0,
490                                 "favicon_needs_check"));
491                         $favicon_avg_color = db_fetch_result($result, 0, "favicon_avg_color");
492
493                         $owner_uid = db_fetch_result($result, 0, "owner_uid");
494
495                         $site_url = db_escape_string(mb_substr(rewrite_relative_url($fetch_url, $rss->get_link()), 0, 245));
496
497                         _debug("site_url: $site_url", $debug_enabled);
498                         _debug("feed_title: " . $rss->get_title(), $debug_enabled);
499
500                         if ($favicon_needs_check || $force_refetch) {
501
502                                 /* terrible hack: if we crash on floicon shit here, we won't check
503                                  * the icon avgcolor again (unless the icon got updated) */
504
505                                 $favicon_file = ICONS_DIR . "/$feed.ico";
506                                 $favicon_modified = @filemtime($favicon_file);
507
508                                 _debug("checking favicon...", $debug_enabled);
509
510                                 check_feed_favicon($site_url, $feed);
511                                 $favicon_modified_new = @filemtime($favicon_file);
512
513                                 if ($favicon_modified_new > $favicon_modified)
514                                         $favicon_avg_color = '';
515
516                                 if (file_exists($favicon_file) && function_exists("imagecreatefromstring") && $favicon_avg_color == '') {
517                                                 require_once "colors.php";
518
519                                                 db_query("UPDATE ttrss_feeds SET favicon_avg_color = 'fail' WHERE
520                                                         id = '$feed'");
521
522                                                 $favicon_color = db_escape_string(
523                                                         calculate_avg_color($favicon_file));
524
525                                                 $favicon_colorstring = ",favicon_avg_color = '".$favicon_color."'";
526                                 } else if ($favicon_avg_color == 'fail') {
527                                         _debug("floicon failed on this file, not trying to recalculate avg color", $debug_enabled);
528                                 }
529
530                                 db_query("UPDATE ttrss_feeds SET favicon_last_checked = NOW()
531                                         $favicon_colorstring
532                                         WHERE id = '$feed'");
533                         }
534
535                         _debug("loading filters & labels...", $debug_enabled);
536
537                         $filters = load_filters($feed, $owner_uid);
538
539                         _debug("" . count($filters) . " filters loaded.", $debug_enabled);
540
541                         $items = $rss->get_items();
542
543                         if (!is_array($items)) {
544                                 _debug("no articles found.", $debug_enabled);
545
546                                 db_query("UPDATE ttrss_feeds
547                                         SET last_updated = NOW(), last_error = '' WHERE id = '$feed'");
548
549                                 return; // no articles
550                         }
551
552                         if ($pubsub_state != 2 && PUBSUBHUBBUB_ENABLED) {
553
554                                 _debug("checking for PUSH hub...", $debug_enabled);
555
556                                 $feed_hub_url = false;
557
558                                 $links = $rss->get_links('hub');
559
560                                 if ($links && is_array($links)) {
561                                         foreach ($links as $l) {
562                                                 $feed_hub_url = $l;
563                                                 break;
564                                         }
565                                 }
566
567                                 _debug("feed hub url: $feed_hub_url", $debug_enabled);
568
569                                 $feed_self_url = $fetch_url;
570
571                                 $links = $rss->get_links('self');
572
573                                 if ($links && is_array($links)) {
574                                         foreach ($links as $l) {
575                                                 $feed_self_url = $l;
576                                                 break;
577                                         }
578                                 }
579
580                                 _debug("feed self url = $feed_self_url");
581
582                                 if ($feed_hub_url && $feed_self_url && function_exists('curl_init') &&
583                                         !ini_get("open_basedir")) {
584
585                                         require_once 'lib/pubsubhubbub/subscriber.php';
586
587                                         $callback_url = get_self_url_prefix() .
588                                                 "/public.php?op=pubsub&id=$feed";
589
590                                         $s = new Subscriber($feed_hub_url, $callback_url);
591
592                                         $rc = $s->subscribe($feed_self_url);
593
594                                         _debug("feed hub url found, subscribe request sent. [rc=$rc]", $debug_enabled);
595
596                                         db_query("UPDATE ttrss_feeds SET pubsub_state = 1
597                                                 WHERE id = '$feed'");
598                                 }
599                         }
600
601                         _debug("processing articles...", $debug_enabled);
602
603                         $tstart = time();
604
605                         foreach ($items as $item) {
606                                 if ($_REQUEST['xdebug'] == 3) {
607                                         print_r($item);
608                                 }
609
610                                 if (ini_get("max_execution_time") > 0 && time() - $tstart >= ini_get("max_execution_time") * 0.7) {
611                                         _debug("looks like there's too many articles to process at once, breaking out", $debug_enabled);
612                                         break;
613                                 }
614
615                                 $entry_guid = $item->get_id();
616                                 if (!$entry_guid) $entry_guid = $item->get_link();
617                                 if (!$entry_guid) $entry_guid = make_guid_from_title($item->get_title());
618                                 if (!$entry_guid) continue;
619
620                                 $entry_guid = "$owner_uid,$entry_guid";
621
622                                 $entry_guid_hashed = db_escape_string('SHA1:' . sha1($entry_guid));
623
624                                 _debug("guid $entry_guid / $entry_guid_hashed", $debug_enabled);
625
626                                 $entry_timestamp = "";
627
628                                 $entry_timestamp = $item->get_date();
629
630                                 _debug("orig date: " . $item->get_date(), $debug_enabled);
631
632                                 if ($entry_timestamp == -1 || !$entry_timestamp || $entry_timestamp > time()) {
633                                         $entry_timestamp = time();
634                                 }
635
636                                 $entry_timestamp_fmt = strftime("%Y/%m/%d %H:%M:%S", $entry_timestamp);
637
638                                 _debug("date $entry_timestamp [$entry_timestamp_fmt]", $debug_enabled);
639
640 //                              $entry_title = html_entity_decode($item->get_title(), ENT_COMPAT, 'UTF-8');
641 //                              $entry_title = decode_numeric_entities($entry_title);
642                                 $entry_title = $item->get_title();
643
644                                 $entry_link = rewrite_relative_url($site_url, $item->get_link());
645
646                                 _debug("title $entry_title", $debug_enabled);
647                                 _debug("link $entry_link", $debug_enabled);
648
649                                 if (!$entry_title) $entry_title = date("Y-m-d H:i:s", $entry_timestamp);;
650
651                                 $entry_content = $item->get_content();
652                                 if (!$entry_content) $entry_content = $item->get_description();
653
654                                 if ($_REQUEST["xdebug"] == 2) {
655                                         print "content: ";
656                                         print $entry_content;
657                                         print "\n";
658                                 }
659
660                                 $entry_comments = $item->get_comments_url();
661                                 $entry_author = $item->get_author();
662
663                                 $entry_guid = db_escape_string(mb_substr($entry_guid, 0, 245));
664
665                                 $entry_comments = db_escape_string(mb_substr(trim($entry_comments), 0, 245));
666                                 $entry_author = db_escape_string(mb_substr(trim($entry_author), 0, 245));
667
668                                 $num_comments = (int) $item->get_comments_count();
669
670                                 _debug("author $entry_author", $debug_enabled);
671                                 _debug("num_comments: $num_comments", $debug_enabled);
672                                 _debug("looking for tags...", $debug_enabled);
673
674                                 // parse <category> entries into tags
675
676                                 $additional_tags = array();
677
678                                 $additional_tags_src = $item->get_categories();
679
680                                 if (is_array($additional_tags_src)) {
681                                         foreach ($additional_tags_src as $tobj) {
682                                                 array_push($additional_tags, $tobj);
683                                         }
684                                 }
685
686                                 $entry_tags = array_unique($additional_tags);
687
688                                 for ($i = 0; $i < count($entry_tags); $i++)
689                                         $entry_tags[$i] = mb_strtolower($entry_tags[$i], 'utf-8');
690
691                                 _debug("tags found: " . join(",", $entry_tags), $debug_enabled);
692
693                                 _debug("done collecting data.", $debug_enabled);
694
695                                 $result = db_query("SELECT id, content_hash, lang FROM ttrss_entries
696                                         WHERE guid = '".db_escape_string($entry_guid)."' OR guid = '$entry_guid_hashed'");
697
698                                 if (db_num_rows($result) != 0) {
699                                         $base_entry_id = db_fetch_result($result, 0, "id");
700                                         $entry_stored_hash = db_fetch_result($result, 0, "content_hash");
701                                         $article_labels = get_article_labels($base_entry_id, $owner_uid);
702                                         $entry_language = db_fetch_result($result, 0, "lang");
703
704                                         $existing_tags = get_article_tags($base_entry_id, $owner_uid);
705                                         $entry_tags = array_unique(array_merge($entry_tags, $existing_tags));
706
707                                 } else {
708                                         $base_entry_id = false;
709                                         $entry_stored_hash = "";
710                                         $article_labels = array();
711                                         $entry_language = "";
712                                 }
713
714                                 $article = array("owner_uid" => $owner_uid, // read only
715                                         "guid" => $entry_guid, // read only
716                                         "guid_hashed" => $entry_guid_hashed, // read only
717                                         "title" => $entry_title,
718                                         "content" => $entry_content,
719                                         "link" => $entry_link,
720                                         "labels" => $article_labels, // current limitation: can add labels to article, can't remove them
721                                         "tags" => $entry_tags,
722                                         "author" => $entry_author,
723                                         "force_catchup" => false, // ugly hack for the time being
724                                         "score_modifier" => 0, // no previous value, plugin should recalculate score modifier based on content if needed
725                                         "language" => $entry_language,
726                                         "feed" => array("id" => $feed,
727                                                 "fetch_url" => $fetch_url,
728                                                 "site_url" => $site_url)
729                                         );
730
731                                 $entry_plugin_data = "";
732                                 $entry_current_hash = calculate_article_hash($article, $pluginhost);
733
734                                 _debug("article hash: $entry_current_hash [stored=$entry_stored_hash]", $debug_enabled);
735
736                                 if ($entry_current_hash == $entry_stored_hash && !isset($_REQUEST["force_rehash"])) {
737                                         _debug("stored article seems up to date [IID: $base_entry_id], updating timestamp only", $debug_enabled);
738
739                                         // we keep encountering the entry in feeds, so we need to
740                                         // update date_updated column so that we don't get horrible
741                                         // dupes when the entry gets purged and reinserted again e.g.
742                                         // in the case of SLOW SLOW OMG SLOW updating feeds
743
744                                         $base_entry_id = db_fetch_result($result, 0, "id");
745
746                                         db_query("UPDATE ttrss_entries SET date_updated = NOW()
747                                                 WHERE id = '$base_entry_id'");
748
749                     // if we allow duplicate posts, we have to continue to
750                     // create the user entries for this feed
751                     if (!get_pref("ALLOW_DUPLICATE_POSTS", $owner_uid, false)) {
752                         continue;
753                     }
754                                 }
755
756                                 _debug("hash differs, applying plugin filters:", $debug_enabled);
757
758                                 foreach ($pluginhost->get_hooks(PluginHost::HOOK_ARTICLE_FILTER) as $plugin) {
759                                         _debug("... " . get_class($plugin), $debug_enabled);
760
761                                         $start = microtime(true);
762                                         $article = $plugin->hook_article_filter($article);
763
764                                         _debug("=== " . sprintf("%.4f (sec)", microtime(true) - $start), $debug_enabled);
765
766                                         $entry_plugin_data .= mb_strtolower(get_class($plugin)) . ",";
767                                 }
768
769                                 $entry_plugin_data = db_escape_string($entry_plugin_data);
770
771                                 _debug("plugin data: $entry_plugin_data", $debug_enabled);
772
773                                 // Workaround: 4-byte unicode requires utf8mb4 in MySQL. See https://tt-rss.org/forum/viewtopic.php?f=1&t=3377&p=20077#p20077
774                                 if (DB_TYPE == "mysql") {
775                                         foreach ($article as $k => $v) {
776
777                                                 // i guess we'll have to take the risk of 4byte unicode labels & tags here
778                                                 if (!is_array($article[$k])) {
779                                                         $article[$k] = preg_replace('/[\x{10000}-\x{10FFFF}]/u', "\xEF\xBF\xBD", $v);
780                                                 }
781                                         }
782                                 }
783
784                                 /* Collect article tags here so we could filter by them: */
785
786                                 $article_filters = get_article_filters($filters, $article["title"],
787                                         $article["content"], $article["link"], 0, $article["author"],
788                                         $article["tags"]);
789
790                                 if ($debug_enabled) {
791                                         _debug("article filters: ", $debug_enabled);
792                                         if (count($article_filters) != 0) {
793                                                 print_r($article_filters);
794                                         }
795                                 }
796
797                                 $plugin_filter_names = find_article_filters($article_filters, "plugin");
798                                 $plugin_filter_actions = $pluginhost->get_filter_actions();
799
800                                 if (count($plugin_filter_names) > 0) {
801                                         _debug("applying plugin filter actions...", $debug_enabled);
802
803                                         foreach ($plugin_filter_names as $pfn) {
804                                                 list($pfclass,$pfaction) = explode(":", $pfn["param"]);
805
806                                                 if (isset($plugin_filter_actions[$pfclass])) {
807                                                         $plugin = $pluginhost->get_plugin($pfclass);
808
809                                                         _debug("... $pfclass: $pfaction", $debug_enabled);
810
811                                                         if ($plugin) {
812                                                                 $start = microtime(true);
813                                                                 $article = $plugin->hook_article_filter_action($article, $pfaction);
814
815                                                                 _debug("=== " . sprintf("%.4f (sec)", microtime(true) - $start), $debug_enabled);
816                                                         } else {
817                                                                 _debug("??? $pfclass: plugin object not found.");
818                                                         }
819                                                 } else {
820                                                         _debug("??? $pfclass: filter plugin not registered.");
821                                                 }
822                                         }
823                                 }
824
825                                 $entry_tags = $article["tags"];
826                                 $entry_guid = db_escape_string($entry_guid);
827                                 $entry_title = db_escape_string($article["title"]);
828                                 $entry_author = db_escape_string($article["author"]);
829                                 $entry_link = db_escape_string($article["link"]);
830                                 $entry_content = $article["content"]; // escaped below
831                                 $entry_force_catchup = $article["force_catchup"];
832                                 $article_labels = $article["labels"];
833                                 $entry_score_modifier = (int) $article["score_modifier"];
834                                 $entry_language = db_escape_string($article["language"]);
835
836                                 if ($debug_enabled) {
837                                         _debug("article labels:", $debug_enabled);
838                                         print_r($article_labels);
839                                 }
840
841                                 _debug("force catchup: $entry_force_catchup");
842
843                                 if ($cache_images && is_writable(CACHE_DIR . '/images'))
844                                         cache_images($entry_content, $site_url, $debug_enabled);
845
846                                 $entry_content = db_escape_string($entry_content, false);
847
848                                 //db_query("BEGIN");
849
850                                 $result = db_query("SELECT id FROM      ttrss_entries
851                                         WHERE (guid = '$entry_guid' OR guid = '$entry_guid_hashed')");
852
853                                 if (db_num_rows($result) == 0) {
854
855                                         _debug("base guid [$entry_guid] not found", $debug_enabled);
856
857                                         // base post entry does not exist, create it
858
859                                         $result = db_query(
860                                                 "INSERT INTO ttrss_entries
861                                                         (title,
862                                                         guid,
863                                                         link,
864                                                         updated,
865                                                         content,
866                                                         content_hash,
867                                                         no_orig_date,
868                                                         date_updated,
869                                                         date_entered,
870                                                         comments,
871                                                         num_comments,
872                                                         plugin_data,
873                                                         lang,
874                                                         author)
875                                                 VALUES
876                                                         ('$entry_title',
877                                                         '$entry_guid_hashed',
878                                                         '$entry_link',
879                                                         '$entry_timestamp_fmt',
880                                                         '$entry_content',
881                                                         '$entry_current_hash',
882                                                         false,
883                                                         NOW(),
884                                                         '$date_feed_processed',
885                                                         '$entry_comments',
886                                                         '$num_comments',
887                                                         '$entry_plugin_data',
888                                                         '$entry_language',
889                                                         '$entry_author')");
890
891                                 } else {
892                                         $base_entry_id = db_fetch_result($result, 0, "id");
893                                 }
894
895                                 // now it should exist, if not - bad luck then
896
897                                 $result = db_query("SELECT id FROM ttrss_entries
898                                         WHERE guid = '$entry_guid' OR guid = '$entry_guid_hashed'");
899
900                                 $entry_ref_id = 0;
901                                 $entry_int_id = 0;
902
903                                 if (db_num_rows($result) == 1) {
904
905                                         _debug("base guid found, checking for user record", $debug_enabled);
906
907                                         $ref_id = db_fetch_result($result, 0, "id");
908                                         $entry_ref_id = $ref_id;
909
910                                         /* $stored_guid = db_fetch_result($result, 0, "guid");
911                                         if ($stored_guid != $entry_guid_hashed) {
912                                                 if ($debug_enabled) _debug("upgrading compat guid to hashed one", $debug_enabled);
913
914                                                 db_query("UPDATE ttrss_entries SET guid = '$entry_guid_hashed' WHERE
915                                                         id = '$ref_id'");
916                                         } */
917
918                                         // check for user post link to main table
919
920                                         // do we allow duplicate posts with same GUID in different feeds?
921                                         if (get_pref("ALLOW_DUPLICATE_POSTS", $owner_uid, false)) {
922                                                 $dupcheck_qpart = "AND (feed_id = '$feed' OR feed_id IS NULL)";
923                                         } else {
924                                                 $dupcheck_qpart = "";
925                                         }
926
927                                         if (find_article_filter($article_filters, "filter")) {
928                                                 //db_query("COMMIT"); // close transaction in progress
929                                                 continue;
930                                         }
931
932                                         $score = calculate_article_score($article_filters) + $entry_score_modifier;
933
934                                         _debug("initial score: $score [including plugin modifier: $entry_score_modifier]", $debug_enabled);
935
936                                         $query = "SELECT ref_id, int_id FROM ttrss_user_entries WHERE
937                                                         ref_id = '$ref_id' AND owner_uid = '$owner_uid'
938                                                         $dupcheck_qpart";
939
940 //                                      if ($_REQUEST["xdebug"]) print "$query\n";
941
942                                         $result = db_query($query);
943
944                                         // okay it doesn't exist - create user entry
945                                         if (db_num_rows($result) == 0) {
946
947                                                 _debug("user record not found, creating...", $debug_enabled);
948
949                                                 if ($score >= -500 && !find_article_filter($article_filters, 'catchup') && !$entry_force_catchup) {
950                                                         $unread = 'true';
951                                                         $last_read_qpart = 'NULL';
952                                                 } else {
953                                                         $unread = 'false';
954                                                         $last_read_qpart = 'NOW()';
955                                                 }
956
957                                                 if (find_article_filter($article_filters, 'mark') || $score > 1000) {
958                                                         $marked = 'true';
959                                                 } else {
960                                                         $marked = 'false';
961                                                 }
962
963                                                 if (find_article_filter($article_filters, 'publish')) {
964                                                         $published = 'true';
965                                                 } else {
966                                                         $published = 'false';
967                                                 }
968
969                                                 // N-grams
970
971                                                 /* if (DB_TYPE == "pgsql" and defined('_NGRAM_TITLE_DUPLICATE_THRESHOLD')) {
972
973                                                         $result = db_query("SELECT COUNT(*) AS similar FROM
974                                                                         ttrss_entries,ttrss_user_entries
975                                                                 WHERE ref_id = id AND updated >= NOW() - INTERVAL '7 day'
976                                                                         AND similarity(title, '$entry_title') >= "._NGRAM_TITLE_DUPLICATE_THRESHOLD."
977                                                                         AND owner_uid = $owner_uid");
978
979                                                         $ngram_similar = db_fetch_result($result, 0, "similar");
980
981                                                         _debug("N-gram similar results: $ngram_similar", $debug_enabled);
982
983                                                         if ($ngram_similar > 0) {
984                                                                 $unread = 'false';
985                                                         }
986                                                 } */
987
988                                                 $last_marked = ($marked == 'true') ? 'NOW()' : 'NULL';
989                                                 $last_published = ($published == 'true') ? 'NOW()' : 'NULL';
990
991                                                 $result = db_query(
992                                                         "INSERT INTO ttrss_user_entries
993                                                                 (ref_id, owner_uid, feed_id, unread, last_read, marked,
994                                                                 published, score, tag_cache, label_cache, uuid,
995                                                                 last_marked, last_published)
996                                                         VALUES ('$ref_id', '$owner_uid', '$feed', $unread,
997                                                                 $last_read_qpart, $marked, $published, '$score', '', '',
998                                                                 '', $last_marked, $last_published)");
999
1000                                                 if (PUBSUBHUBBUB_HUB && $published == 'true') {
1001                                                         $rss_link = get_self_url_prefix() .
1002                                                                 "/public.php?op=rss&id=-2&key=" .
1003                                                                 get_feed_access_key(-2, false, $owner_uid);
1004
1005                                                         $p = new Publisher(PUBSUBHUBBUB_HUB);
1006
1007                                                         /* $pubsub_result = */ $p->publish_update($rss_link);
1008                                                 }
1009
1010                                                 $result = db_query(
1011                                                         "SELECT int_id FROM ttrss_user_entries WHERE
1012                                                                 ref_id = '$ref_id' AND owner_uid = '$owner_uid' AND
1013                                                                 feed_id = '$feed' LIMIT 1");
1014
1015                                                 if (db_num_rows($result) == 1) {
1016                                                         $entry_int_id = db_fetch_result($result, 0, "int_id");
1017                                                 }
1018                                         } else {
1019                                                 _debug("user record FOUND", $debug_enabled);
1020
1021                                                 $entry_ref_id = db_fetch_result($result, 0, "ref_id");
1022                                                 $entry_int_id = db_fetch_result($result, 0, "int_id");
1023                                         }
1024
1025                                         _debug("RID: $entry_ref_id, IID: $entry_int_id", $debug_enabled);
1026
1027                                         if (DB_TYPE == "pgsql") {
1028                                            $tsvector_combined = db_escape_string(mb_substr($entry_title . ' ' . strip_tags(str_replace('<', ' <', $entry_content)),
1029                                                         0, 1000000));
1030
1031                                                 $tsvector_qpart = "tsvector_combined = to_tsvector('$feed_language', '$tsvector_combined'),";
1032
1033                                         } else {
1034                                                 $tsvector_qpart = "";
1035                                         }
1036
1037                                         db_query("UPDATE ttrss_entries
1038                                                 SET title = '$entry_title',
1039                                                         content = '$entry_content',
1040                                                         content_hash = '$entry_current_hash',
1041                                                         updated = '$entry_timestamp_fmt',
1042                                                         $tsvector_qpart
1043                                                         num_comments = '$num_comments',
1044                                                         plugin_data = '$entry_plugin_data',
1045                                                         author = '$entry_author',
1046                                                         lang = '$entry_language'
1047                                                 WHERE id = '$ref_id'");
1048
1049                                         // update aux data
1050                                         db_query("UPDATE ttrss_user_entries
1051                                                         SET score = '$score' WHERE ref_id = '$ref_id'");
1052
1053                                         if ($mark_unread_on_update) {
1054                                                 _debug("article updated, marking unread as requested.", $debug_enabled);
1055
1056                                                 db_query("UPDATE ttrss_user_entries
1057                                                         SET last_read = null, unread = true WHERE ref_id = '$ref_id'");
1058                                         }
1059                                 }
1060
1061                                 //db_query("COMMIT");
1062
1063                                 _debug("assigning labels [other]...", $debug_enabled);
1064
1065                                 foreach ($article_labels as $label) {
1066                                         label_add_article($entry_ref_id, $label[1], $owner_uid);
1067                                 }
1068
1069                                 _debug("assigning labels [filters]...", $debug_enabled);
1070
1071                                 assign_article_to_label_filters($entry_ref_id, $article_filters,
1072                                         $owner_uid, $article_labels);
1073
1074                                 _debug("looking for enclosures...", $debug_enabled);
1075
1076                                 // enclosures
1077
1078                                 $enclosures = array();
1079
1080                                 $encs = $item->get_enclosures();
1081
1082                                 if (is_array($encs)) {
1083                                         foreach ($encs as $e) {
1084                                                 $e_item = array(
1085                                                         $e->link, $e->type, $e->length, $e->title, $e->width, $e->height);
1086                                                 array_push($enclosures, $e_item);
1087                                         }
1088                                 }
1089
1090                                 if ($debug_enabled) {
1091                                         _debug("article enclosures:", $debug_enabled);
1092                                         print_r($enclosures);
1093                                 }
1094
1095                                 //db_query("BEGIN");
1096
1097 //                              debugging
1098 //                              db_query("DELETE FROM ttrss_enclosures WHERE post_id = '$entry_ref_id'");
1099
1100                                 foreach ($enclosures as $enc) {
1101                                         $enc_url = db_escape_string($enc[0]);
1102                                         $enc_type = db_escape_string($enc[1]);
1103                                         $enc_dur = db_escape_string($enc[2]);
1104                                         $enc_title = db_escape_string($enc[3]);
1105                                         $enc_width = intval($enc[4]);
1106                                         $enc_height = intval($enc[5]);
1107
1108                                         $result = db_query("SELECT id FROM ttrss_enclosures
1109                                                 WHERE content_url = '$enc_url' AND post_id = '$entry_ref_id'");
1110
1111                                         if (db_num_rows($result) == 0) {
1112                                                 db_query("INSERT INTO ttrss_enclosures
1113                                                         (content_url, content_type, title, duration, post_id, width, height) VALUES
1114                                                         ('$enc_url', '$enc_type', '$enc_title', '$enc_dur', '$entry_ref_id', $enc_width, $enc_height)");
1115                                         }
1116                                 }
1117
1118                                 //db_query("COMMIT");
1119
1120                                 // check for manual tags (we have to do it here since they're loaded from filters)
1121
1122                                 foreach ($article_filters as $f) {
1123                                         if ($f["type"] == "tag") {
1124
1125                                                 $manual_tags = trim_array(explode(",", $f["param"]));
1126
1127                                                 foreach ($manual_tags as $tag) {
1128                                                         if (tag_is_valid($tag)) {
1129                                                                 array_push($entry_tags, $tag);
1130                                                         }
1131                                                 }
1132                                         }
1133                                 }
1134
1135                                 // Skip boring tags
1136
1137                                 $boring_tags = trim_array(explode(",", mb_strtolower(get_pref(
1138                                         'BLACKLISTED_TAGS', $owner_uid, ''), 'utf-8')));
1139
1140                                 $filtered_tags = array();
1141                                 $tags_to_cache = array();
1142
1143                                 if ($entry_tags && is_array($entry_tags)) {
1144                                         foreach ($entry_tags as $tag) {
1145                                                 if (array_search($tag, $boring_tags) === false) {
1146                                                         array_push($filtered_tags, $tag);
1147                                                 }
1148                                         }
1149                                 }
1150
1151                                 $filtered_tags = array_unique($filtered_tags);
1152
1153                                 if ($debug_enabled) {
1154                                         _debug("filtered article tags:", $debug_enabled);
1155                                         print_r($filtered_tags);
1156                                 }
1157
1158                                 // Save article tags in the database
1159
1160                                 if (count($filtered_tags) > 0) {
1161
1162                                         //db_query("BEGIN");
1163
1164                                         foreach ($filtered_tags as $tag) {
1165
1166                                                 $tag = sanitize_tag($tag);
1167                                                 $tag = db_escape_string($tag);
1168
1169                                                 if (!tag_is_valid($tag)) continue;
1170
1171                                                 $result = db_query("SELECT id FROM ttrss_tags
1172                                                         WHERE tag_name = '$tag' AND post_int_id = '$entry_int_id' AND
1173                                                         owner_uid = '$owner_uid' LIMIT 1");
1174
1175                                                         if ($result && db_num_rows($result) == 0) {
1176
1177                                                                 db_query("INSERT INTO ttrss_tags
1178                                                                         (owner_uid,tag_name,post_int_id)
1179                                                                         VALUES ('$owner_uid','$tag', '$entry_int_id')");
1180                                                         }
1181
1182                                                 array_push($tags_to_cache, $tag);
1183                                         }
1184
1185                                         /* update the cache */
1186
1187                                         $tags_to_cache = array_unique($tags_to_cache);
1188
1189                                         $tags_str = db_escape_string(join(",", $tags_to_cache));
1190
1191                                         db_query("UPDATE ttrss_user_entries
1192                                                 SET tag_cache = '$tags_str' WHERE ref_id = '$entry_ref_id'
1193                                                 AND owner_uid = $owner_uid");
1194
1195                                         //db_query("COMMIT");
1196                                 }
1197
1198                                 _debug("article processed", $debug_enabled);
1199                         }
1200
1201                         _debug("purging feed...", $debug_enabled);
1202
1203                         purge_feed($feed, 0, $debug_enabled);
1204
1205                         db_query("UPDATE ttrss_feeds
1206                                 SET last_updated = NOW(), last_error = '' WHERE id = '$feed'");
1207
1208 //                      db_query("COMMIT");
1209
1210                 } else {
1211
1212                         $error_msg = db_escape_string(mb_substr($rss->error(), 0, 245));
1213
1214                         _debug("fetch error: $error_msg", $debug_enabled);
1215
1216                         if (count($rss->errors()) > 1) {
1217                                 foreach ($rss->errors() as $error) {
1218                                         _debug("+ $error");
1219                                 }
1220                         }
1221
1222                         db_query(
1223                                 "UPDATE ttrss_feeds SET last_error = '$error_msg',
1224                                 last_updated = NOW() WHERE id = '$feed'");
1225
1226                         unset($rss);
1227                 }
1228
1229                 _debug("done", $debug_enabled);
1230
1231                 return $rss;
1232         }
1233
1234         function cache_images($html, $site_url, $debug) {
1235                 libxml_use_internal_errors(true);
1236
1237                 $charset_hack = '<head>
1238                         <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
1239                 </head>';
1240
1241                 $doc = new DOMDocument();
1242                 $doc->loadHTML($charset_hack . $html);
1243                 $xpath = new DOMXPath($doc);
1244
1245                 $entries = $xpath->query('(//img[@src])');
1246
1247                 foreach ($entries as $entry) {
1248                         if ($entry->hasAttribute('src')) {
1249                                 $src = rewrite_relative_url($site_url, $entry->getAttribute('src'));
1250
1251                                 $local_filename = CACHE_DIR . "/images/" . sha1($src) . ".png";
1252
1253                                 if ($debug) _debug("cache_images: downloading: $src to $local_filename");
1254
1255                                 if (!file_exists($local_filename)) {
1256                                         $file_content = fetch_file_contents($src);
1257
1258                                         if ($file_content && strlen($file_content) > _MIN_CACHE_IMAGE_SIZE) {
1259                                                 file_put_contents($local_filename, $file_content);
1260                                         }
1261                                 } else {
1262                                         touch($local_filename);
1263                                 }
1264                         }
1265                 }
1266         }
1267
1268         function expire_error_log($debug) {
1269                 if ($debug) _debug("Removing old error log entries...");
1270
1271                 if (DB_TYPE == "pgsql") {
1272                         db_query("DELETE FROM ttrss_error_log
1273                                 WHERE created_at < NOW() - INTERVAL '7 days'");
1274                 } else {
1275                         db_query("DELETE FROM ttrss_error_log
1276                                 WHERE created_at < DATE_SUB(NOW(), INTERVAL 7 DAY)");
1277                 }
1278
1279         }
1280
1281         function expire_lock_files($debug) {
1282                 //if ($debug) _debug("Removing old lock files...");
1283
1284                 $num_deleted = 0;
1285
1286                 if (is_writable(LOCK_DIRECTORY)) {
1287                         $files = glob(LOCK_DIRECTORY . "/*.lock");
1288
1289                         if ($files) {
1290                                 foreach ($files as $file) {
1291                                         if (!file_is_locked(basename($file)) && time() - filemtime($file) > 86400*2) {
1292                                                 unlink($file);
1293                                                 ++$num_deleted;
1294                                         }
1295                                 }
1296                         }
1297                 }
1298
1299                 if ($debug) _debug("Removed $num_deleted old lock files.");
1300         }
1301
1302         function expire_cached_files($debug) {
1303                 foreach (array("simplepie", "images", "export", "upload") as $dir) {
1304                         $cache_dir = CACHE_DIR . "/$dir";
1305
1306 //                      if ($debug) _debug("Expiring $cache_dir");
1307
1308                         $num_deleted = 0;
1309
1310                         if (is_writable($cache_dir)) {
1311                                 $files = glob("$cache_dir/*");
1312
1313                                 if ($files) {
1314                                         foreach ($files as $file) {
1315                                                 if (time() - filemtime($file) > 86400*7) {
1316                                                         unlink($file);
1317
1318                                                         ++$num_deleted;
1319                                                 }
1320                                         }
1321                                 }
1322                         }
1323
1324                         if ($debug) _debug("$cache_dir: removed $num_deleted files.");
1325                 }
1326         }
1327
1328         /**
1329         * Source: http://www.php.net/manual/en/function.parse-url.php#104527
1330         * Returns the url query as associative array
1331         *
1332         * @param    string    query
1333         * @return    array    params
1334         */
1335         function convertUrlQuery($query) {
1336                 $queryParts = explode('&', $query);
1337
1338                 $params = array();
1339
1340                 foreach ($queryParts as $param) {
1341                         $item = explode('=', $param);
1342                         $params[$item[0]] = $item[1];
1343                 }
1344
1345                 return $params;
1346         }
1347
1348         function get_article_filters($filters, $title, $content, $link, $timestamp, $author, $tags) {
1349                 $matches = array();
1350
1351                 foreach ($filters as $filter) {
1352                         $match_any_rule = $filter["match_any_rule"];
1353                         $inverse = $filter["inverse"];
1354                         $filter_match = false;
1355
1356                         foreach ($filter["rules"] as $rule) {
1357                                 $match = false;
1358                                 $reg_exp = str_replace('/', '\/', $rule["reg_exp"]);
1359                                 $rule_inverse = $rule["inverse"];
1360
1361                                 if (!$reg_exp)
1362                                         continue;
1363
1364                                 switch ($rule["type"]) {
1365                                 case "title":
1366                                         $match = @preg_match("/$reg_exp/i", $title);
1367                                         break;
1368                                 case "content":
1369                                         // we don't need to deal with multiline regexps
1370                                         $content = preg_replace("/[\r\n\t]/", "", $content);
1371
1372                                         $match = @preg_match("/$reg_exp/i", $content);
1373                                         break;
1374                                 case "both":
1375                                         // we don't need to deal with multiline regexps
1376                                         $content = preg_replace("/[\r\n\t]/", "", $content);
1377
1378                                         $match = (@preg_match("/$reg_exp/i", $title) || @preg_match("/$reg_exp/i", $content));
1379                                         break;
1380                                 case "link":
1381                                         $match = @preg_match("/$reg_exp/i", $link);
1382                                         break;
1383                                 case "author":
1384                                         $match = @preg_match("/$reg_exp/i", $author);
1385                                         break;
1386                                 case "tag":
1387                                         foreach ($tags as $tag) {
1388                                                 if (@preg_match("/$reg_exp/i", $tag)) {
1389                                                         $match = true;
1390                                                         break;
1391                                                 }
1392                                         }
1393                                         break;
1394                                 }
1395
1396                                 if ($rule_inverse) $match = !$match;
1397
1398                                 if ($match_any_rule) {
1399                                         if ($match) {
1400                                                 $filter_match = true;
1401                                                 break;
1402                                         }
1403                                 } else {
1404                                         $filter_match = $match;
1405                                         if (!$match) {
1406                                                 break;
1407                                         }
1408                                 }
1409                         }
1410
1411                         if ($inverse) $filter_match = !$filter_match;
1412
1413                         if ($filter_match) {
1414                                 foreach ($filter["actions"] AS $action) {
1415                                         array_push($matches, $action);
1416
1417                                         // if Stop action encountered, perform no further processing
1418                                         if (isset($action["type"]) && $action["type"] == "stop") return $matches;
1419                                 }
1420                         }
1421                 }
1422
1423                 return $matches;
1424         }
1425
1426         function find_article_filter($filters, $filter_name) {
1427                 foreach ($filters as $f) {
1428                         if ($f["type"] == $filter_name) {
1429                                 return $f;
1430                         };
1431                 }
1432                 return false;
1433         }
1434
1435         function find_article_filters($filters, $filter_name) {
1436                 $results = array();
1437
1438                 foreach ($filters as $f) {
1439                         if ($f["type"] == $filter_name) {
1440                                 array_push($results, $f);
1441                         };
1442                 }
1443                 return $results;
1444         }
1445
1446         function calculate_article_score($filters) {
1447                 $score = 0;
1448
1449                 foreach ($filters as $f) {
1450                         if ($f["type"] == "score") {
1451                                 $score += $f["param"];
1452                         };
1453                 }
1454                 return $score;
1455         }
1456
1457         function labels_contains_caption($labels, $caption) {
1458                 foreach ($labels as $label) {
1459                         if ($label[1] == $caption) {
1460                                 return true;
1461                         }
1462                 }
1463
1464                 return false;
1465         }
1466
1467         function assign_article_to_label_filters($id, $filters, $owner_uid, $article_labels) {
1468                 foreach ($filters as $f) {
1469                         if ($f["type"] == "label") {
1470                                 if (!labels_contains_caption($article_labels, $f["param"])) {
1471                                         label_add_article($id, $f["param"], $owner_uid);
1472                                 }
1473                         }
1474                 }
1475         }
1476
1477         function make_guid_from_title($title) {
1478                 return preg_replace("/[ \"\',.:;]/", "-",
1479                         mb_strtolower(strip_tags($title), 'utf-8'));
1480         }
1481
1482         /* function verify_feed_xml($feed_data) {
1483                 libxml_use_internal_errors(true);
1484                 $doc = new DOMDocument();
1485                 $doc->loadXML($feed_data);
1486                 $error = libxml_get_last_error();
1487                 libxml_clear_errors();
1488                 return $error;
1489         } */
1490
1491         function cleanup_counters_cache($debug) {
1492                 $result = db_query("DELETE FROM ttrss_counters_cache
1493                         WHERE feed_id > 0 AND
1494                         (SELECT COUNT(id) FROM ttrss_feeds WHERE
1495                                 id = feed_id AND
1496                                 ttrss_counters_cache.owner_uid = ttrss_feeds.owner_uid) = 0");
1497                 $frows = db_affected_rows($result);
1498
1499                 $result = db_query("DELETE FROM ttrss_cat_counters_cache
1500                         WHERE feed_id > 0 AND
1501                         (SELECT COUNT(id) FROM ttrss_feed_categories WHERE
1502                                 id = feed_id AND
1503                                 ttrss_cat_counters_cache.owner_uid = ttrss_feed_categories.owner_uid) = 0");
1504                 $crows = db_affected_rows($result);
1505
1506                 _debug("Removed $frows (feeds) $crows (cats) orphaned counter cache entries.");
1507         }
1508
1509         function housekeeping_common($debug) {
1510                 expire_cached_files($debug);
1511                 expire_lock_files($debug);
1512                 expire_error_log($debug);
1513
1514                 $count = update_feedbrowser_cache();
1515                 _debug("Feedbrowser updated, $count feeds processed.");
1516
1517                 purge_orphans( true);
1518                 cleanup_counters_cache($debug);
1519                 $rc = cleanup_tags( 14, 50000);
1520
1521                 _debug("Cleaned $rc cached tags.");
1522
1523                 PluginHost::getInstance()->run_hooks(PluginHost::HOOK_HOUSE_KEEPING, "hook_house_keeping", "");
1524
1525         }
1526 ?>