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