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