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