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