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