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