]> git.wh0rd.org - tt-rss.git/blame - include/rssfuncs.php
fix update stopped by get_article_labels()
[tt-rss.git] / include / rssfuncs.php
CommitLineData
2c08214a 1<?php
09e8bdfd
AD
2 define('DAEMON_UPDATE_LOGIN_LIMIT', 30);
3 define('DAEMON_FEED_LIMIT', 100);
0f556e3e 4 define('DAEMON_SLEEP_INTERVAL', 60);
09e8bdfd 5
79178062
AD
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($line["subscribers"]);
22 $feed_url = db_escape_string($line["feed_url"]);
23 $title = db_escape_string($line["title"]);
24 $site_url = db_escape_string($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
2c08214a
AD
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
61c1812f
AD
63 define('PREFS_NO_CACHE', true);
64
2c08214a 65 // Test if the user has loggued in recently. If not, it does not update its feeds.
09e8bdfd 66 if (!SINGLE_USER_MODE && DAEMON_UPDATE_LOGIN_LIMIT > 0) {
2c08214a
AD
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_feeds.last_updated < NOW() - CAST((ttrss_user_prefs.value || ' minutes') AS INTERVAL)
81 ) OR (
82 ttrss_feeds.update_interval > 0
83 AND ttrss_feeds.last_updated < NOW() - CAST((ttrss_feeds.update_interval || ' minutes') AS INTERVAL)
941e48a4
AD
84 ) OR ttrss_feeds.last_updated IS NULL
85 OR last_updated = '1970-01-01 00:00:00')";
2c08214a
AD
86 } else {
87 $update_limit_qpart = "AND ((
88 ttrss_feeds.update_interval = 0
89 AND ttrss_feeds.last_updated < DATE_SUB(NOW(), INTERVAL CONVERT(ttrss_user_prefs.value, SIGNED INTEGER) MINUTE)
90 ) OR (
91 ttrss_feeds.update_interval > 0
92 AND ttrss_feeds.last_updated < DATE_SUB(NOW(), INTERVAL ttrss_feeds.update_interval MINUTE)
941e48a4
AD
93 ) OR ttrss_feeds.last_updated IS NULL
94 OR last_updated = '1970-01-01 00:00:00')";
2c08214a
AD
95 }
96
97 // Test if feed is currently being updated by another process.
98 if (DB_TYPE == "pgsql") {
99 $updstart_thresh_qpart = "AND (ttrss_feeds.last_update_started IS NULL OR ttrss_feeds.last_update_started < NOW() - INTERVAL '5 minutes')";
100 } else {
101 $updstart_thresh_qpart = "AND (ttrss_feeds.last_update_started IS NULL OR ttrss_feeds.last_update_started < DATE_SUB(NOW(), INTERVAL 5 MINUTE))";
102 }
103
104 // Test if there is a limit to number of updated feeds
105 $query_limit = "";
106 if($limit) $query_limit = sprintf("LIMIT %d", $limit);
107
108 $random_qpart = sql_random_function();
109
110 // We search for feed needing update.
111 $result = db_query($link, "SELECT ttrss_feeds.feed_url,ttrss_feeds.id, ttrss_feeds.owner_uid,
112 ".SUBSTRING_FOR_DATE."(ttrss_feeds.last_updated,1,19) AS last_updated,
113 ttrss_feeds.update_interval
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...\n", 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 $feeds_to_update[$line['id']] = $line;
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 $feed_ids = array_keys($feeds_to_update);
138 if($feed_ids) {
139 db_query($link, sprintf("UPDATE ttrss_feeds SET last_update_started = NOW()
140 WHERE id IN (%s)", implode(',', $feed_ids)));
141 }
142
3c696512
AD
143 expire_cached_files($debug);
144
2c08214a
AD
145 // For each feed, we call the feed update function.
146 while ($line = array_pop($feeds_to_update)) {
147
148 if($debug) _debug("Feed: " . $line["feed_url"] . ", " . $line["last_updated"]);
149
150 update_rss_feed($link, $line["id"], true);
151
152 sleep(1); // prevent flood (FIXME make this an option?)
153 }
154
155 // Send feed digests by email if needed.
8437c066 156 send_headlines_digests($link, $debug);
2c08214a
AD
157
158 } // function update_daemon_common
159
0e4a7d7a 160 function update_rss_feed($link, $feed, $ignore_daemon = false, $no_cache = false,
2c08214a
AD
161 $override_url = false) {
162
163 require_once "lib/simplepie/simplepie.inc";
164 require_once "lib/magpierss/rss_fetch.inc";
165 require_once 'lib/magpierss/rss_utils.inc';
166
2c08214a
AD
167 $debug_enabled = defined('DAEMON_EXTENDED_DEBUG') || $_REQUEST['xdebug'];
168
169 if (!$_REQUEST["daemon"] && !$ignore_daemon) {
170 return false;
171 }
172
173 if ($debug_enabled) {
174 _debug("update_rss_feed: start");
175 }
176
177 if (!$ignore_daemon) {
178
179 if (DB_TYPE == "pgsql") {
180 $updstart_thresh_qpart = "(ttrss_feeds.last_update_started IS NULL OR ttrss_feeds.last_update_started < NOW() - INTERVAL '120 seconds')";
181 } else {
182 $updstart_thresh_qpart = "(ttrss_feeds.last_update_started IS NULL OR ttrss_feeds.last_update_started < DATE_SUB(NOW(), INTERVAL 120 SECOND))";
183 }
184
185 $result = db_query($link, "SELECT id,update_interval,auth_login,
6cb2269c 186 auth_pass,cache_images,update_method,last_updated
2c08214a
AD
187 FROM ttrss_feeds WHERE id = '$feed' AND $updstart_thresh_qpart");
188
189 } else {
190
191 $result = db_query($link, "SELECT id,update_interval,auth_login,
192 feed_url,auth_pass,cache_images,update_method,last_updated,
193 mark_unread_on_update, owner_uid, update_on_checksum_change,
194 pubsub_state
195 FROM ttrss_feeds WHERE id = '$feed'");
196
197 }
198
199 if (db_num_rows($result) == 0) {
200 if ($debug_enabled) {
201 _debug("update_rss_feed: feed $feed NOT FOUND/SKIPPED");
202 }
203 return false;
204 }
205
206 $update_method = db_fetch_result($result, 0, "update_method");
207 $last_updated = db_fetch_result($result, 0, "last_updated");
208 $owner_uid = db_fetch_result($result, 0, "owner_uid");
209 $mark_unread_on_update = sql_bool_to_bool(db_fetch_result($result,
210 0, "mark_unread_on_update"));
211 $update_on_checksum_change = sql_bool_to_bool(db_fetch_result($result,
212 0, "update_on_checksum_change"));
213 $pubsub_state = db_fetch_result($result, 0, "pubsub_state");
214
215 db_query($link, "UPDATE ttrss_feeds SET last_update_started = NOW()
216 WHERE id = '$feed'");
217
218 $auth_login = db_fetch_result($result, 0, "auth_login");
219 $auth_pass = db_fetch_result($result, 0, "auth_pass");
220
221 if ($update_method == 0)
222 $update_method = DEFAULT_UPDATE_METHOD + 1;
223
224 // 1 - Magpie
225 // 2 - SimplePie
226 // 3 - Twitter OAuth
227
228 if ($update_method == 2)
229 $use_simplepie = true;
230 else
231 $use_simplepie = false;
232
233 if ($debug_enabled) {
234 _debug("update method: $update_method (feed setting: $update_method) (use simplepie: $use_simplepie)\n");
235 }
236
237 if ($update_method == 1) {
238 $auth_login = urlencode($auth_login);
239 $auth_pass = urlencode($auth_pass);
240 }
241
2c08214a
AD
242 $cache_images = sql_bool_to_bool(db_fetch_result($result, 0, "cache_images"));
243 $fetch_url = db_fetch_result($result, 0, "feed_url");
244
2c08214a
AD
245 $feed = db_escape_string($feed);
246
247 if ($auth_login && $auth_pass ){
248 $url_parts = array();
249 preg_match("/(^[^:]*):\/\/(.*)/", $fetch_url, $url_parts);
250
251 if ($url_parts[1] && $url_parts[2]) {
252 $fetch_url = $url_parts[1] . "://$auth_login:$auth_pass@" . $url_parts[2];
253 }
254
255 }
256
257 if ($override_url)
258 $fetch_url = $override_url;
259
260 if ($debug_enabled) {
261 _debug("update_rss_feed: fetching [$fetch_url]...");
262 }
263
0e4a7d7a
AD
264 // Ignore cache if new feed or manual update.
265 $cache_age = (is_null($last_updated) || $last_updated == '1970-01-01 00:00:00') ?
266 -1 : get_feed_update_interval($link, $feed) * 60;
2c08214a 267
304aadb9 268 if ($update_method == 1) {
2c08214a 269
0e4a7d7a
AD
270 define('MAGPIE_CACHE_AGE', $cache_age);
271 define('MAGPIE_CACHE_ON', !$no_cache);
c0c2abba 272 define('MAGPIE_FETCH_TIME_OUT', $no_cache ? 15 : 60);
0e4a7d7a 273 define('MAGPIE_CACHE_DIR', CACHE_DIR . "/magpie");
2c08214a 274
0e4a7d7a 275 $rss = @fetch_rss($fetch_url);
2c08214a 276 } else {
0e4a7d7a 277 $simplepie_cache_dir = CACHE_DIR . "/simplepie";
2c08214a 278
0e4a7d7a
AD
279 if (!is_dir($simplepie_cache_dir)) {
280 mkdir($simplepie_cache_dir);
281 }
2c08214a 282
0e4a7d7a
AD
283 $rss = new SimplePie();
284 $rss->set_useragent(SELF_USER_AGENT);
c0c2abba 285 $rss->set_timeout($no_cache ? 15 : 60);
0e4a7d7a
AD
286 $rss->set_feed_url($fetch_url);
287 $rss->set_output_encoding('UTF-8');
288 //$rss->force_feed(true);
2c08214a 289
0e4a7d7a
AD
290 if ($debug_enabled) {
291 _debug("feed update interval (sec): " .
292 get_feed_update_interval($link, $feed)*60);
293 }
2c08214a 294
0e4a7d7a 295 $rss->enable_cache(!$no_cache);
2c08214a 296
0e4a7d7a
AD
297 if (!$no_cache) {
298 $rss->set_cache_location($simplepie_cache_dir);
299 $rss->set_cache_duration($cache_age);
2c08214a
AD
300 }
301
0e4a7d7a 302 $rss->init();
2c08214a
AD
303 }
304
305// print_r($rss);
306
307 if ($debug_enabled) {
308 _debug("update_rss_feed: fetch done, parsing...");
309 }
310
311 $feed = db_escape_string($feed);
312
313 if ($update_method == 2) {
314 $fetch_ok = !$rss->error();
315 } else {
316 $fetch_ok = !!$rss;
317 }
318
319 if ($fetch_ok) {
320
321 if ($debug_enabled) {
322 _debug("update_rss_feed: processing feed data...");
323 }
324
325// db_query($link, "BEGIN");
326
382268c6
AD
327 if (DB_TYPE == "pgsql") {
328 $favicon_interval_qpart = "favicon_last_checked < NOW() - INTERVAL '12 hour'";
329 } else {
330 $favicon_interval_qpart = "favicon_last_checked < DATE_SUB(NOW(), INTERVAL 12 HOUR)";
331 }
332
333 $result = db_query($link, "SELECT title,icon_url,site_url,owner_uid,
334 (favicon_last_checked IS NULL OR $favicon_interval_qpart) AS
335 favicon_needs_check
2c08214a
AD
336 FROM ttrss_feeds WHERE id = '$feed'");
337
338 $registered_title = db_fetch_result($result, 0, "title");
339 $orig_icon_url = db_fetch_result($result, 0, "icon_url");
340 $orig_site_url = db_fetch_result($result, 0, "site_url");
382268c6
AD
341 $favicon_needs_check = sql_bool_to_bool(db_fetch_result($result, 0,
342 "favicon_needs_check"));
2c08214a
AD
343
344 $owner_uid = db_fetch_result($result, 0, "owner_uid");
345
346 if ($use_simplepie) {
0cf81637 347 $site_url = db_escape_string(trim($rss->get_link()));
2c08214a 348 } else {
0cf81637
AD
349 $site_url = db_escape_string(trim($rss->channel["link"]));
350 }
351
352 // weird, weird Magpie
353 if (!$use_simplepie) {
354 if (!$site_url) $site_url = db_escape_string($rss->channel["link_"]);
2c08214a
AD
355 }
356
357 $site_url = rewrite_relative_url($fetch_url, $site_url);
0cf81637 358 $site_url = substr($site_url, 0, 250);
2c08214a
AD
359
360 if ($debug_enabled) {
361 _debug("update_rss_feed: checking favicon...");
362 }
363
f2798eb6
AD
364 if ($favicon_needs_check) {
365 check_feed_favicon($site_url, $feed, $link);
366
367 db_query($link, "UPDATE ttrss_feeds SET favicon_last_checked = NOW()
368 WHERE id = '$feed'");
369 }
2c08214a
AD
370
371 if (!$registered_title || $registered_title == "[Unknown]") {
372
373 if ($use_simplepie) {
374 $feed_title = db_escape_string($rss->get_title());
375 } else {
376 $feed_title = db_escape_string($rss->channel["title"]);
377 }
378
379 if ($debug_enabled) {
380 _debug("update_rss_feed: registering title: $feed_title");
381 }
382
383 db_query($link, "UPDATE ttrss_feeds SET
384 title = '$feed_title' WHERE id = '$feed'");
385 }
386
0cf81637 387 if ($site_url && $orig_site_url != $site_url) {
2c08214a
AD
388 db_query($link, "UPDATE ttrss_feeds SET
389 site_url = '$site_url' WHERE id = '$feed'");
390 }
391
392// print "I: " . $rss->channel["image"]["url"];
393
394 if (!$use_simplepie) {
0cf81637 395 $icon_url = db_escape_string(trim($rss->image["url"]));
2c08214a 396 } else {
0cf81637 397 $icon_url = db_escape_string(trim($rss->get_image_url()));
2c08214a
AD
398 }
399
0cf81637 400 $icon_url = rewrite_relative_url($fetch_url, $icon_url);
2c08214a
AD
401 $icon_url = substr($icon_url, 0, 250);
402
403 if ($icon_url && $orig_icon_url != $icon_url) {
404 db_query($link, "UPDATE ttrss_feeds SET icon_url = '$icon_url' WHERE id = '$feed'");
405 }
406
407 if ($debug_enabled) {
b24504b1 408 _debug("update_rss_feed: loading filters & labels...");
2c08214a
AD
409 }
410
411 $filters = load_filters($link, $feed, $owner_uid);
b24504b1 412 $labels = get_all_labels($link, $owner_uid);
2c08214a 413
67bd0b1f
AD
414 if ($debug_enabled) {
415 //print_r($filters);
416 _debug("update_rss_feed: " . count($filters) . " filters loaded.");
417 }
2c08214a
AD
418
419 if ($use_simplepie) {
420 $iterator = $rss->get_items();
421 } else {
422 $iterator = $rss->items;
423 if (!$iterator || !is_array($iterator)) $iterator = $rss->entries;
424 if (!$iterator || !is_array($iterator)) $iterator = $rss;
425 }
426
427 if (!is_array($iterator)) {
428 /* db_query($link, "UPDATE ttrss_feeds
429 SET last_error = 'Parse error: can\'t find any articles.'
430 WHERE id = '$feed'"); */
431
432 // clear any errors and mark feed as updated if fetched okay
433 // even if it's blank
434
435 if ($debug_enabled) {
436 _debug("update_rss_feed: entry iterator is not an array, no articles?");
437 }
438
439 db_query($link, "UPDATE ttrss_feeds
440 SET last_updated = NOW(), last_error = '' WHERE id = '$feed'");
441
442 return; // no articles
443 }
444
445 if ($pubsub_state != 2 && PUBSUBHUBBUB_ENABLED) {
446
447 if ($debug_enabled) _debug("update_rss_feed: checking for PUSH hub...");
448
449 $feed_hub_url = false;
450 if ($use_simplepie) {
451 $links = $rss->get_links('hub');
452
453 if ($links && is_array($links)) {
454 foreach ($links as $l) {
455 $feed_hub_url = $l;
456 break;
457 }
458 }
459
460 } else {
461 $atom = $rss->channel['atom'];
462
463 if ($atom) {
464 if ($atom['link@rel'] == 'hub') {
465 $feed_hub_url = $atom['link@href'];
466 }
467
468 if (!$feed_hub_url && $atom['link#'] > 1) {
469 for ($i = 2; $i <= $atom['link#']; $i++) {
470 if ($atom["link#$i@rel"] == 'hub') {
471 $feed_hub_url = $atom["link#$i@href"];
472 break;
473 }
474 }
475 }
476 } else {
477 $feed_hub_url = $rss->channel['link_hub'];
478 }
479 }
480
481 if ($debug_enabled) _debug("update_rss_feed: feed hub url: $feed_hub_url");
482
483 if ($feed_hub_url && function_exists('curl_init') &&
484 !ini_get("open_basedir")) {
485
486 require_once 'lib/pubsubhubbub/subscriber.php';
487
488 $callback_url = get_self_url_prefix() .
489 "/public.php?op=pubsub&id=$feed";
490
491 $s = new Subscriber($feed_hub_url, $callback_url);
492
493 $rc = $s->subscribe($fetch_url);
494
495 if ($debug_enabled)
496 _debug("update_rss_feed: feed hub url found, subscribe request sent.");
497
498 db_query($link, "UPDATE ttrss_feeds SET pubsub_state = 1
499 WHERE id = '$feed'");
500 }
501 }
502
503 if ($debug_enabled) {
504 _debug("update_rss_feed: processing articles...");
505 }
506
507 foreach ($iterator as $item) {
2c08214a
AD
508 if ($_REQUEST['xdebug'] == 2) {
509 print_r($item);
510 }
511
512 if ($use_simplepie) {
513 $entry_guid = $item->get_id();
514 if (!$entry_guid) $entry_guid = $item->get_link();
515 if (!$entry_guid) $entry_guid = make_guid_from_title($item->get_title());
516
517 } else {
518
519 $entry_guid = $item["id"];
520
521 if (!$entry_guid) $entry_guid = $item["guid"];
522 if (!$entry_guid) $entry_guid = $item["about"];
523 if (!$entry_guid) $entry_guid = $item["link"];
524 if (!$entry_guid) $entry_guid = make_guid_from_title($item["title"]);
525 }
526
527 if ($debug_enabled) {
528 _debug("update_rss_feed: guid $entry_guid");
529 }
530
531 if (!$entry_guid) continue;
532
533 $entry_timestamp = "";
534
535 if ($use_simplepie) {
536 $entry_timestamp = strtotime($item->get_date());
537 } else {
538 $rss_2_date = $item['pubdate'];
539 $rss_1_date = $item['dc']['date'];
540 $atom_date = $item['issued'];
541 if (!$atom_date) $atom_date = $item['updated'];
542
543 if ($atom_date != "") $entry_timestamp = parse_w3cdtf($atom_date);
544 if ($rss_1_date != "") $entry_timestamp = parse_w3cdtf($rss_1_date);
545 if ($rss_2_date != "") $entry_timestamp = strtotime($rss_2_date);
546
547 }
548
549 if ($entry_timestamp == "" || $entry_timestamp == -1 || !$entry_timestamp) {
550 $entry_timestamp = time();
551 $no_orig_date = 'true';
552 } else {
553 $no_orig_date = 'false';
554 }
555
556 $entry_timestamp_fmt = strftime("%Y/%m/%d %H:%M:%S", $entry_timestamp);
557
558 if ($debug_enabled) {
559 _debug("update_rss_feed: date $entry_timestamp [$entry_timestamp_fmt]");
560 }
561
562 if ($use_simplepie) {
563 $entry_title = $item->get_title();
564 } else {
565 $entry_title = trim(strip_tags($item["title"]));
566 }
567
568 if ($use_simplepie) {
569 $entry_link = $item->get_link();
570 } else {
571 // strange Magpie workaround
572 $entry_link = $item["link_"];
573 if (!$entry_link) $entry_link = $item["link"];
574 }
575
576 $entry_link = rewrite_relative_url($site_url, $entry_link);
577
578 if ($debug_enabled) {
579 _debug("update_rss_feed: title $entry_title");
580 _debug("update_rss_feed: link $entry_link");
581 }
582
583 if (!$entry_title) $entry_title = date("Y-m-d H:i:s", $entry_timestamp);;
584
585 $entry_link = strip_tags($entry_link);
586
587 if ($use_simplepie) {
588 $entry_content = $item->get_content();
589 if (!$entry_content) $entry_content = $item->get_description();
590 } else {
591 $entry_content = $item["content:escaped"];
592
593 if (!$entry_content) $entry_content = $item["content:encoded"];
eb38af4e 594 if (!$entry_content && is_array($entry_content)) $entry_content = $item["content"]["encoded"];
2c08214a
AD
595 if (!$entry_content) $entry_content = $item["content"];
596
597 if (is_array($entry_content)) $entry_content = $entry_content[0];
598
599 // Magpie bugs are getting ridiculous
600 if (trim($entry_content) == "Array") $entry_content = false;
601
602 if (!$entry_content) $entry_content = $item["atom_content"];
603 if (!$entry_content) $entry_content = $item["summary"];
604
605 if (!$entry_content ||
606 strlen($entry_content) < strlen($item["description"])) {
607 $entry_content = $item["description"];
608 };
609
610 // WTF
611 if (is_array($entry_content)) {
612 $entry_content = $entry_content["encoded"];
613 if (!$entry_content) $entry_content = $entry_content["escaped"];
614 }
615 }
616
c5867798 617 if ($cache_images && is_writable(CACHE_DIR . '/images'))
3c696512
AD
618 $entry_content = cache_images($entry_content, $site_url, $debug_enabled);
619
2c08214a
AD
620 if ($_REQUEST["xdebug"] == 2) {
621 print "update_rss_feed: content: ";
487f0750 622 print $entry_content;
3c696512 623 print "\n";
2c08214a
AD
624 }
625
626 $entry_content_unescaped = $entry_content;
627
628 if ($use_simplepie) {
629 $entry_comments = strip_tags($item->data["comments"]);
630 if ($item->get_author()) {
631 $entry_author_item = $item->get_author();
632 $entry_author = $entry_author_item->get_name();
633 if (!$entry_author) $entry_author = $entry_author_item->get_email();
634
635 $entry_author = db_escape_string($entry_author);
636 }
637 } else {
638 $entry_comments = strip_tags($item["comments"]);
639
640 $entry_author = db_escape_string(strip_tags($item['dc']['creator']));
641
642 if ($item['author']) {
643
644 if (is_array($item['author'])) {
645
646 if (!$entry_author) {
647 $entry_author = db_escape_string(strip_tags($item['author']['name']));
648 }
649
650 if (!$entry_author) {
651 $entry_author = db_escape_string(strip_tags($item['author']['email']));
652 }
653 }
654
655 if (!$entry_author) {
656 $entry_author = db_escape_string(strip_tags($item['author']));
657 }
658 }
659 }
660
661 if (preg_match('/^[\t\n\r ]*$/', $entry_author)) $entry_author = '';
662
663 $entry_guid = db_escape_string(strip_tags($entry_guid));
664 $entry_guid = mb_substr($entry_guid, 0, 250);
665
666 $result = db_query($link, "SELECT id FROM ttrss_entries
667 WHERE guid = '$entry_guid'");
668
669 $entry_content = db_escape_string($entry_content, false);
670
487f0750 671 $content_hash = "SHA1:" . sha1(strip_tags($entry_content));
2c08214a
AD
672
673 $entry_title = db_escape_string($entry_title);
674 $entry_link = db_escape_string($entry_link);
675 $entry_comments = mb_substr(db_escape_string($entry_comments), 0, 250);
676 $entry_author = mb_substr($entry_author, 0, 250);
677
678 if ($use_simplepie) {
679 $num_comments = 0; #FIXME#
680 } else {
681 $num_comments = db_escape_string($item["slash"]["comments"]);
682 }
683
684 if (!$num_comments) $num_comments = 0;
685
686 if ($debug_enabled) {
687 _debug("update_rss_feed: looking for tags [1]...");
688 }
689
690 // parse <category> entries into tags
691
692 $additional_tags = array();
693
694 if ($use_simplepie) {
695
696 $additional_tags_src = $item->get_categories();
697
698 if (is_array($additional_tags_src)) {
699 foreach ($additional_tags_src as $tobj) {
700 array_push($additional_tags, $tobj->get_term());
701 }
702 }
703
704 if ($debug_enabled) {
705 _debug("update_rss_feed: category tags:");
706 print_r($additional_tags);
707 }
708
709 } else {
710
711 $t_ctr = $item['category#'];
712
713 if ($t_ctr == 0) {
714 $additional_tags = array();
715 } else if ($t_ctr > 0) {
716 $additional_tags = array($item['category']);
717
718 if ($item['category@term']) {
719 array_push($additional_tags, $item['category@term']);
720 }
721
722 for ($i = 0; $i <= $t_ctr; $i++ ) {
723 if ($item["category#$i"]) {
724 array_push($additional_tags, $item["category#$i"]);
725 }
726
727 if ($item["category#$i@term"]) {
728 array_push($additional_tags, $item["category#$i@term"]);
729 }
730 }
731 }
732
733 // parse <dc:subject> elements
734
735 $t_ctr = $item['dc']['subject#'];
736
737 if ($t_ctr > 0) {
738 array_push($additional_tags, $item['dc']['subject']);
739
740 for ($i = 0; $i <= $t_ctr; $i++ ) {
741 if ($item['dc']["subject#$i"]) {
742 array_push($additional_tags, $item['dc']["subject#$i"]);
743 }
744 }
745 }
746 }
747
748 if ($debug_enabled) {
749 _debug("update_rss_feed: looking for tags [2]...");
750 }
751
752 /* taaaags */
753 // <a href="..." rel="tag">Xorg</a>, //
754
755 $entry_tags = null;
756
757 preg_match_all("/<a.*?rel=['\"]tag['\"].*?\>([^<]+)<\/a>/i",
758 $entry_content_unescaped, $entry_tags);
759
760 $entry_tags = $entry_tags[1];
761
762 $entry_tags = array_merge($entry_tags, $additional_tags);
763 $entry_tags = array_unique($entry_tags);
764
765 for ($i = 0; $i < count($entry_tags); $i++)
766 $entry_tags[$i] = mb_strtolower($entry_tags[$i], 'utf-8');
767
768 if ($debug_enabled) {
6aff7845
AD
769 //_debug("update_rss_feed: unfiltered tags found:");
770 //print_r($entry_tags);
2c08214a
AD
771 }
772
2c08214a
AD
773 if ($debug_enabled) {
774 _debug("update_rss_feed: done collecting data [TITLE:$entry_title]");
775 }
776
777 db_query($link, "BEGIN");
778
779 if (db_num_rows($result) == 0) {
780
781 if ($debug_enabled) {
782 _debug("update_rss_feed: base guid not found");
783 }
784
785 // base post entry does not exist, create it
786
787 $result = db_query($link,
788 "INSERT INTO ttrss_entries
789 (title,
790 guid,
791 link,
792 updated,
793 content,
794 content_hash,
795 no_orig_date,
796 date_updated,
797 date_entered,
798 comments,
799 num_comments,
800 author)
801 VALUES
802 ('$entry_title',
803 '$entry_guid',
804 '$entry_link',
805 '$entry_timestamp_fmt',
806 '$entry_content',
807 '$content_hash',
808 $no_orig_date,
809 NOW(),
810 NOW(),
811 '$entry_comments',
812 '$num_comments',
813 '$entry_author')");
814 } else {
815 // we keep encountering the entry in feeds, so we need to
816 // update date_updated column so that we don't get horrible
817 // dupes when the entry gets purged and reinserted again e.g.
818 // in the case of SLOW SLOW OMG SLOW updating feeds
819
820 $base_entry_id = db_fetch_result($result, 0, "id");
821
822 db_query($link, "UPDATE ttrss_entries SET date_updated = NOW()
823 WHERE id = '$base_entry_id'");
824 }
825
826 // now it should exist, if not - bad luck then
827
828 $result = db_query($link, "SELECT
829 id,content_hash,no_orig_date,title,
830 ".SUBSTRING_FOR_DATE."(date_updated,1,19) as date_updated,
831 ".SUBSTRING_FOR_DATE."(updated,1,19) as updated,
832 num_comments
833 FROM
834 ttrss_entries
835 WHERE guid = '$entry_guid'");
836
837 $entry_ref_id = 0;
838 $entry_int_id = 0;
839
840 if (db_num_rows($result) == 1) {
841
842 if ($debug_enabled) {
843 _debug("update_rss_feed: base guid found, checking for user record");
844 }
845
846 // this will be used below in update handler
847 $orig_content_hash = db_fetch_result($result, 0, "content_hash");
848 $orig_title = db_fetch_result($result, 0, "title");
849 $orig_num_comments = db_fetch_result($result, 0, "num_comments");
850 $orig_date_updated = strtotime(db_fetch_result($result,
851 0, "date_updated"));
852
853 $ref_id = db_fetch_result($result, 0, "id");
854 $entry_ref_id = $ref_id;
855
856 // check for user post link to main table
857
858 // do we allow duplicate posts with same GUID in different feeds?
859 if (get_pref($link, "ALLOW_DUPLICATE_POSTS", $owner_uid, false)) {
860 $dupcheck_qpart = "AND (feed_id = '$feed' OR feed_id IS NULL)";
861 } else {
862 $dupcheck_qpart = "";
863 }
864
865 /* Collect article tags here so we could filter by them: */
866
867 $article_filters = get_article_filters($filters, $entry_title,
3fc6e71a 868 strip_tags($entry_content), $entry_link, $entry_timestamp, $entry_author,
2c08214a
AD
869 $entry_tags);
870
871 if ($debug_enabled) {
872 _debug("update_rss_feed: article filters: ");
873 if (count($article_filters) != 0) {
874 print_r($article_filters);
875 }
876 }
877
bb894b29 878 $article_labels = get_article_labels($link, $entry_ref_id, $owner_uid);
b24504b1 879
2c08214a
AD
880 if (find_article_filter($article_filters, "filter")) {
881 db_query($link, "COMMIT"); // close transaction in progress
882 continue;
883 }
884
885 $score = calculate_article_score($article_filters);
886
887 if ($debug_enabled) {
888 _debug("update_rss_feed: initial score: $score");
889 }
890
891 $query = "SELECT ref_id, int_id FROM ttrss_user_entries WHERE
892 ref_id = '$ref_id' AND owner_uid = '$owner_uid'
893 $dupcheck_qpart";
894
895// if ($_REQUEST["xdebug"]) print "$query\n";
896
897 $result = db_query($link, $query);
898
899 // okay it doesn't exist - create user entry
900 if (db_num_rows($result) == 0) {
901
902 if ($debug_enabled) {
903 _debug("update_rss_feed: user record not found, creating...");
904 }
905
906 if ($score >= -500 && !find_article_filter($article_filters, 'catchup')) {
907 $unread = 'true';
908 $last_read_qpart = 'NULL';
909 } else {
910 $unread = 'false';
911 $last_read_qpart = 'NOW()';
912 }
913
914 if (find_article_filter($article_filters, 'mark') || $score > 1000) {
915 $marked = 'true';
916 } else {
917 $marked = 'false';
918 }
919
920 if (find_article_filter($article_filters, 'publish')) {
921 $published = 'true';
922 } else {
923 $published = 'false';
924 }
925
2ea9bbfd
AD
926 // N-grams
927
928 if (DB_TYPE == "pgsql" and defined('_NGRAM_TITLE_DUPLICATE_THRESHOLD')) {
929
930 $result = db_query($link, "SELECT COUNT(*) AS similar FROM
931 ttrss_entries,ttrss_user_entries
932 WHERE ref_id = id AND updated >= NOW() - INTERVAL '7 day'
933 AND similarity(title, '$entry_title') >= "._NGRAM_TITLE_DUPLICATE_THRESHOLD."
934 AND owner_uid = $owner_uid");
935
936 $ngram_similar = db_fetch_result($result, 0, "similar");
937
938 if ($debug_enabled) {
939 _debug("update_rss_feed: N-gram similar results: $ngram_similar");
940 }
941
942 if ($ngram_similar > 0) {
943 $unread = 'false';
944 }
945 }
946
2c08214a
AD
947 $result = db_query($link,
948 "INSERT INTO ttrss_user_entries
949 (ref_id, owner_uid, feed_id, unread, last_read, marked,
950 published, score, tag_cache, label_cache, uuid)
951 VALUES ('$ref_id', '$owner_uid', '$feed', $unread,
952 $last_read_qpart, $marked, $published, '$score', '', '', '')");
953
954 if (PUBSUBHUBBUB_HUB && $published == 'true') {
955 $rss_link = get_self_url_prefix() .
956 "/public.php?op=rss&id=-2&key=" .
957 get_feed_access_key($link, -2, false, $owner_uid);
958
959 $p = new Publisher(PUBSUBHUBBUB_HUB);
960
961 $pubsub_result = $p->publish_update($rss_link);
962 }
963
964 $result = db_query($link,
965 "SELECT int_id FROM ttrss_user_entries WHERE
966 ref_id = '$ref_id' AND owner_uid = '$owner_uid' AND
967 feed_id = '$feed' LIMIT 1");
968
969 if (db_num_rows($result) == 1) {
970 $entry_int_id = db_fetch_result($result, 0, "int_id");
971 }
972 } else {
973 if ($debug_enabled) {
974 _debug("update_rss_feed: user record FOUND");
975 }
976
977 $entry_ref_id = db_fetch_result($result, 0, "ref_id");
978 $entry_int_id = db_fetch_result($result, 0, "int_id");
979 }
980
981 if ($debug_enabled) {
982 _debug("update_rss_feed: RID: $entry_ref_id, IID: $entry_int_id");
983 }
984
985 $post_needs_update = false;
986 $update_insignificant = false;
987
988 if ($orig_num_comments != $num_comments) {
989 $post_needs_update = true;
990 $update_insignificant = true;
991 }
992
993 if ($content_hash != $orig_content_hash) {
994 $post_needs_update = true;
995 $update_insignificant = false;
996 }
997
998 if (db_escape_string($orig_title) != $entry_title) {
999 $post_needs_update = true;
1000 $update_insignificant = false;
1001 }
1002
1003 // if post needs update, update it and mark all user entries
1004 // linking to this post as updated
1005 if ($post_needs_update) {
1006
1007 if (defined('DAEMON_EXTENDED_DEBUG')) {
1008 _debug("update_rss_feed: post $entry_guid needs update...");
1009 }
1010
1011// print "<!-- post $orig_title needs update : $post_needs_update -->";
1012
1013 db_query($link, "UPDATE ttrss_entries
1014 SET title = '$entry_title', content = '$entry_content',
1015 content_hash = '$content_hash',
1016 updated = '$entry_timestamp_fmt',
1017 num_comments = '$num_comments'
1018 WHERE id = '$ref_id'");
1019
1020 if (!$update_insignificant) {
1021 if ($mark_unread_on_update) {
1022 db_query($link, "UPDATE ttrss_user_entries
1023 SET last_read = null, unread = true WHERE ref_id = '$ref_id'");
1024 } else if ($update_on_checksum_change) {
1025 db_query($link, "UPDATE ttrss_user_entries
1026 SET last_read = null WHERE ref_id = '$ref_id'
1027 AND unread = false");
1028 }
1029 }
1030 }
1031 }
1032
1033 db_query($link, "COMMIT");
1034
1035 if ($debug_enabled) {
1036 _debug("update_rss_feed: assigning labels...");
1037 }
1038
92c14e9d 1039 assign_article_to_label_filters($link, $entry_ref_id, $article_filters,
b24504b1 1040 $owner_uid, $article_labels);
2c08214a
AD
1041
1042 if ($debug_enabled) {
1043 _debug("update_rss_feed: looking for enclosures...");
1044 }
1045
1046 // enclosures
1047
1048 $enclosures = array();
1049
1050 if ($use_simplepie) {
1051 $encs = $item->get_enclosures();
1052
1053 if (is_array($encs)) {
1054 foreach ($encs as $e) {
1055 $e_item = array(
1056 $e->link, $e->type, $e->length);
1057
1058 array_push($enclosures, $e_item);
1059 }
1060 }
1061
1062 } else {
1063 // <enclosure>
1064
1065 $e_ctr = $item['enclosure#'];
1066
1067 if ($e_ctr > 0) {
1068 $e_item = array($item['enclosure@url'],
1069 $item['enclosure@type'],
1070 $item['enclosure@length']);
1071
1072 array_push($enclosures, $e_item);
1073
1074 for ($i = 0; $i <= $e_ctr; $i++ ) {
1075
1076 if ($item["enclosure#$i@url"]) {
1077 $e_item = array($item["enclosure#$i@url"],
1078 $item["enclosure#$i@type"],
1079 $item["enclosure#$i@length"]);
1080 array_push($enclosures, $e_item);
1081 }
1082 }
1083 }
1084
1085 // <media:content>
1086 // can there be many of those? yes -fox
1087
1088 $m_ctr = $item['media']['content#'];
1089
1090 if ($m_ctr > 0) {
1091 $e_item = array($item['media']['content@url'],
1092 $item['media']['content@medium'],
1093 $item['media']['content@length']);
1094
1095 array_push($enclosures, $e_item);
1096
1097 for ($i = 0; $i <= $m_ctr; $i++ ) {
1098
1099 if ($item["media"]["content#$i@url"]) {
1100 $e_item = array($item["media"]["content#$i@url"],
1101 $item["media"]["content#$i@medium"],
1102 $item["media"]["content#$i@length"]);
1103 array_push($enclosures, $e_item);
1104 }
1105 }
1106
1107 }
1108 }
1109
1110
1111 if ($debug_enabled) {
1112 _debug("update_rss_feed: article enclosures:");
1113 print_r($enclosures);
1114 }
1115
1116 db_query($link, "BEGIN");
1117
1118 foreach ($enclosures as $enc) {
1119 $enc_url = db_escape_string($enc[0]);
1120 $enc_type = db_escape_string($enc[1]);
1121 $enc_dur = db_escape_string($enc[2]);
1122
1123 $result = db_query($link, "SELECT id FROM ttrss_enclosures
1124 WHERE content_url = '$enc_url' AND post_id = '$entry_ref_id'");
1125
1126 if (db_num_rows($result) == 0) {
1127 db_query($link, "INSERT INTO ttrss_enclosures
1128 (content_url, content_type, title, duration, post_id) VALUES
1129 ('$enc_url', '$enc_type', '', '$enc_dur', '$entry_ref_id')");
1130 }
1131 }
1132
1133 db_query($link, "COMMIT");
1134
1135 // check for manual tags (we have to do it here since they're loaded from filters)
1136
1137 foreach ($article_filters as $f) {
6aff7845 1138 if ($f["type"] == "tag") {
2c08214a 1139
6aff7845 1140 $manual_tags = trim_array(explode(",", $f["param"]));
2c08214a
AD
1141
1142 foreach ($manual_tags as $tag) {
1143 if (tag_is_valid($tag)) {
1144 array_push($entry_tags, $tag);
1145 }
1146 }
1147 }
1148 }
1149
1150 // Skip boring tags
1151
1152 $boring_tags = trim_array(explode(",", mb_strtolower(get_pref($link,
1153 'BLACKLISTED_TAGS', $owner_uid, ''), 'utf-8')));
1154
1155 $filtered_tags = array();
1156 $tags_to_cache = array();
1157
1158 if ($entry_tags && is_array($entry_tags)) {
1159 foreach ($entry_tags as $tag) {
1160 if (array_search($tag, $boring_tags) === false) {
1161 array_push($filtered_tags, $tag);
1162 }
1163 }
1164 }
1165
1166 $filtered_tags = array_unique($filtered_tags);
1167
1168 if ($debug_enabled) {
1169 _debug("update_rss_feed: filtered article tags:");
1170 print_r($filtered_tags);
1171 }
1172
1173 // Save article tags in the database
1174
1175 if (count($filtered_tags) > 0) {
1176
1177 db_query($link, "BEGIN");
1178
1179 foreach ($filtered_tags as $tag) {
1180
1181 $tag = sanitize_tag($tag);
1182 $tag = db_escape_string($tag);
1183
1184 if (!tag_is_valid($tag)) continue;
1185
1186 $result = db_query($link, "SELECT id FROM ttrss_tags
1187 WHERE tag_name = '$tag' AND post_int_id = '$entry_int_id' AND
1188 owner_uid = '$owner_uid' LIMIT 1");
1189
1190 if ($result && db_num_rows($result) == 0) {
1191
1192 db_query($link, "INSERT INTO ttrss_tags
1193 (owner_uid,tag_name,post_int_id)
1194 VALUES ('$owner_uid','$tag', '$entry_int_id')");
1195 }
1196
1197 array_push($tags_to_cache, $tag);
1198 }
1199
1200 /* update the cache */
1201
1202 $tags_to_cache = array_unique($tags_to_cache);
1203
1204 $tags_str = db_escape_string(join(",", $tags_to_cache));
1205
1206 db_query($link, "UPDATE ttrss_user_entries
1207 SET tag_cache = '$tags_str' WHERE ref_id = '$entry_ref_id'
1208 AND owner_uid = $owner_uid");
1209
1210 db_query($link, "COMMIT");
1211 }
1212
b24504b1
AD
1213 if (get_pref($link, "AUTO_ASSIGN_LABELS", $owner_uid, false)) {
1214 if ($debug_enabled) {
1215 _debug("update_rss_feed: auto-assigning labels...");
1216 }
1217
1218 foreach ($labels as $label) {
1219 $caption = $label["caption"];
1220
3fc6e71a 1221 if (preg_match("/\b$caption\b/i", "$tags_str " . strip_tags($entry_content) . " $entry_title")) {
b24504b1
AD
1222 if (!labels_contains_caption($article_labels, $caption)) {
1223 label_add_article($link, $entry_ref_id, $caption, $owner_uid);
1224 }
1225 }
1226 }
1227 }
1228
2c08214a
AD
1229 if ($debug_enabled) {
1230 _debug("update_rss_feed: article processed");
1231 }
1232 }
1233
1234 if (!$last_updated) {
1235 if ($debug_enabled) {
1236 _debug("update_rss_feed: new feed, catching it up...");
1237 }
1238 catchup_feed($link, $feed, false, $owner_uid);
1239 }
1240
1241 if ($debug_enabled) {
1242 _debug("purging feed...");
1243 }
1244
1245 purge_feed($link, $feed, 0, $debug_enabled);
1246
1247 db_query($link, "UPDATE ttrss_feeds
f2798eb6 1248 SET last_updated = NOW(), last_error = '' WHERE id = '$feed'");
2c08214a
AD
1249
1250// db_query($link, "COMMIT");
1251
1252 } else {
1253
1254 if ($use_simplepie) {
1255 $error_msg = mb_substr($rss->error(), 0, 250);
1256 } else {
1257 $error_msg = mb_substr(magpie_error(), 0, 250);
1258 }
1259
1260 if ($debug_enabled) {
1261 _debug("update_rss_feed: error fetching feed: $error_msg");
1262 }
1263
1264 $error_msg = db_escape_string($error_msg);
1265
1266 db_query($link,
1267 "UPDATE ttrss_feeds SET last_error = '$error_msg',
1268 last_updated = NOW() WHERE id = '$feed'");
1269 }
1270
1271 if ($use_simplepie) {
1272 unset($rss);
1273 }
1274
1275 if ($debug_enabled) {
1276 _debug("update_rss_feed: done");
1277 }
1278
1279 }
1280
3c696512
AD
1281 function cache_images($html, $site_url, $debug) {
1282 $cache_dir = CACHE_DIR . "/images";
1283
1284 libxml_use_internal_errors(true);
1285
1286 $charset_hack = '<head>
1287 <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
1288 </head>';
1289
1290 $doc = new DOMDocument();
1291 $doc->loadHTML($charset_hack . $html);
1292 $xpath = new DOMXPath($doc);
1293
1294 $entries = $xpath->query('(//img[@src])');
1295
1296 foreach ($entries as $entry) {
1297 if ($entry->hasAttribute('src')) {
1298 $src = rewrite_relative_url($site_url, $entry->getAttribute('src'));
1299
1300 $local_filename = CACHE_DIR . "/images/" . sha1($src) . ".png";
1301
1302 if ($debug) _debug("cache_images: downloading: $src to $local_filename");
1303
1304 if (!file_exists($local_filename)) {
1305 $file_content = fetch_file_contents($src);
1306
b8379e69 1307 if ($file_content && strlen($file_content) > 1024) {
3c696512
AD
1308 file_put_contents($local_filename, $file_content);
1309 }
1310 }
1311
1312 if (file_exists($local_filename)) {
1313 $entry->setAttribute('src', SELF_URL_PATH . '/image.php?url=' .
487f0750 1314 base64_encode($src));
3c696512
AD
1315 }
1316 }
1317 }
1318
1319 $node = $doc->getElementsByTagName('body')->item(0);
1320
7b8ff151 1321 return $doc->saveXML($node, LIBXML_NOEMPTYTAG);
3c696512
AD
1322 }
1323
1324 function expire_cached_files($debug) {
d3158e22 1325 foreach (array("magpie", "simplepie", "images", "export") as $dir) {
3c696512 1326 $cache_dir = CACHE_DIR . "/$dir";
2c08214a 1327
3c696512 1328 if ($debug) _debug("Expiring $cache_dir");
2c08214a 1329
3c696512
AD
1330 $num_deleted = 0;
1331
1332 if (is_writable($cache_dir)) {
1333 $files = glob("$cache_dir/*");
1334
2ab20c31
AD
1335 if ($files)
1336 foreach ($files as $file) {
1337 if (time() - filemtime($file) > 86400*7) {
1338 unlink($file);
3c696512 1339
2ab20c31
AD
1340 ++$num_deleted;
1341 }
3c696512
AD
1342 }
1343 }
3c696512
AD
1344
1345 if ($debug) _debug("Removed $num_deleted files.");
1346 }
1347 }
2c08214a 1348
a3e0bdcf
AD
1349 /**
1350 * Source: http://www.php.net/manual/en/function.parse-url.php#104527
1351 * Returns the url query as associative array
1352 *
1353 * @param string query
1354 * @return array params
1355 */
1356 function convertUrlQuery($query) {
1357 $queryParts = explode('&', $query);
1358
1359 $params = array();
1360
1361 foreach ($queryParts as $param) {
1362 $item = explode('=', $param);
1363 $params[$item[0]] = $item[1];
1364 }
1365
1366 return $params;
1367 }
92c14e9d
AD
1368
1369 function get_article_filters($filters, $title, $content, $link, $timestamp, $author, $tags) {
1370 $matches = array();
1371
1372 foreach ($filters as $filter) {
1373 $match_any_rule = $filter["match_any_rule"];
1374 $filter_match = false;
1375
1376 foreach ($filter["rules"] as $rule) {
1377 $match = false;
1378 $reg_exp = $rule["reg_exp"];
1379
1380 if (!$reg_exp)
1381 continue;
1382
1383 switch ($rule["type"]) {
1384 case "title":
1385 $match = @preg_match("/$reg_exp/i", $title);
1386 break;
1387 case "content":
1388 $match = @preg_match("/$reg_exp/i", $content);
1389 break;
1390 case "both":
1391 $match = (@preg_match("/$reg_exp/i", $title) || @preg_match("/$reg_exp/i", $title));
1392 break;
1393 case "link":
1394 $match = @preg_match("/$reg_exp/i", $link);
1395 break;
1396 case "author":
1397 $match = @preg_match("/$reg_exp/i", $author);
1398 break;
1399 case "tag":
1400 $tag_string = join(",", $tags);
1401 $match = @preg_match("/$reg_exp/i", $tag_string);
1402 break;
1403 }
1404
1405 if ($match_any_rule) {
1406 if ($match) {
1407 $filter_match = true;
1408 break;
1409 }
1410 } else {
1411 $filter_match = $match;
1412 if (!$match) {
1413 break;
1414 }
1415 }
1416 }
1417
1418 if ($filter_match) {
1419 foreach ($filter["actions"] AS $action) {
1420 array_push($matches, $action);
1421 }
1422 }
1423 }
1424
1425 return $matches;
1426 }
1427
1428 function find_article_filter($filters, $filter_name) {
1429 foreach ($filters as $f) {
1430 if ($f["type"] == $filter_name) {
1431 return $f;
1432 };
1433 }
1434 return false;
1435 }
1436
1437 function find_article_filters($filters, $filter_name) {
1438 $results = array();
1439
1440 foreach ($filters as $f) {
1441 if ($f["type"] == $filter_name) {
1442 array_push($results, $f);
1443 };
1444 }
1445 return $results;
1446 }
1447
1448 function calculate_article_score($filters) {
1449 $score = 0;
1450
1451 foreach ($filters as $f) {
1452 if ($f["type"] == "score") {
1453 $score += $f["param"];
1454 };
1455 }
1456 return $score;
1457 }
1458
b24504b1
AD
1459 function labels_contains_caption($labels, $caption) {
1460 foreach ($labels as $label) {
1461 if ($label[1] == $caption) {
1462 return true;
1463 }
1464 }
1465
1466 return false;
1467 }
1468
1469 function assign_article_to_label_filters($link, $id, $filters, $owner_uid, $article_labels) {
92c14e9d
AD
1470 foreach ($filters as $f) {
1471 if ($f["type"] == "label") {
b24504b1
AD
1472 if (!labels_contains_caption($article_labels, $f["param"])) {
1473 label_add_article($link, $id, $f["param"], $owner_uid);
1474 }
1475 }
92c14e9d
AD
1476 }
1477 }
2c08214a 1478?>