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