]> git.wh0rd.org - tt-rss.git/blame - include/rssfuncs.php
cache_starred_images: set filename when sending cached image
[tt-rss.git] / include / rssfuncs.php
CommitLineData
2c08214a 1<?php
fce451a4
AD
2 define_default('DAEMON_UPDATE_LOGIN_LIMIT', 30);
3 define_default('DAEMON_FEED_LIMIT', 500);
e2cf81e2 4 define_default('DAEMON_SLEEP_INTERVAL', 120);
a3d50184 5 define_default('_MIN_CACHE_IMAGE_SIZE', 1024);
09e8bdfd 6
eb16bd9f 7 function calculate_article_hash($article, $pluginhost) {
af244f92
AD
8 $tmp = "";
9
10 foreach ($article as $k => $v) {
11 if ($k != "feed" && isset($v)) {
24e6ff5d
AD
12 $x = strip_tags(is_array($v) ? implode(",", $v) : $v);
13
14 //_debug("$k:" . sha1($x) . ":" . htmlspecialchars($x), true);
15
16 $tmp .= sha1("$k:" . sha1($x));
af244f92
AD
17 }
18 }
19
eb16bd9f 20 return sha1(implode(",", $pluginhost->get_plugin_names()) . $tmp);
b1840673
AD
21 }
22
6322ac79 23 function update_feedbrowser_cache() {
79178062 24
a42c55f0 25 $result = db_query("SELECT feed_url, site_url, title, COUNT(id) AS subscribers
79178062
AD
26 FROM ttrss_feeds WHERE (SELECT COUNT(id) = 0 FROM ttrss_feeds AS tf
27 WHERE tf.feed_url = ttrss_feeds.feed_url
28 AND (private IS true OR auth_login != '' OR auth_pass != '' OR feed_url LIKE '%:%@%/%'))
29 GROUP BY feed_url, site_url, title ORDER BY subscribers DESC LIMIT 1000");
30
a42c55f0 31 db_query("BEGIN");
79178062 32
a42c55f0 33 db_query("DELETE FROM ttrss_feedbrowser_cache");
79178062
AD
34
35 $count = 0;
36
37 while ($line = db_fetch_assoc($result)) {
a42c55f0
AD
38 $subscribers = db_escape_string($line["subscribers"]);
39 $feed_url = db_escape_string($line["feed_url"]);
40 $title = db_escape_string($line["title"]);
41 $site_url = db_escape_string($line["site_url"]);
79178062 42
a42c55f0 43 $tmp_result = db_query("SELECT subscribers FROM
79178062
AD
44 ttrss_feedbrowser_cache WHERE feed_url = '$feed_url'");
45
46 if (db_num_rows($tmp_result) == 0) {
47
a42c55f0 48 db_query("INSERT INTO ttrss_feedbrowser_cache
79178062
AD
49 (feed_url, site_url, title, subscribers) VALUES ('$feed_url',
50 '$site_url', '$title', '$subscribers')");
51
52 ++$count;
53
54 }
55
56 }
57
a42c55f0 58 db_query("COMMIT");
79178062
AD
59
60 return $count;
61
62 }
63
64
2c08214a
AD
65 /**
66 * Update a feed batch.
67 * Used by daemons to update n feeds by run.
68 * Only update feed needing a update, and not being processed
69 * by another process.
70 *
71 * @param mixed $link Database link
72 * @param integer $limit Maximum number of feeds in update batch. Default to DAEMON_FEED_LIMIT.
73 * @param boolean $from_http Set to true if you call this function from http to disable cli specific code.
74 * @param boolean $debug Set to false to disable debug output. Default to true.
75 * @return void
76 */
a42c55f0 77 function update_daemon_common($limit = DAEMON_FEED_LIMIT, $from_http = false, $debug = true) {
2c08214a
AD
78 // Process all other feeds using last_updated and interval parameters
79
6322ac79 80 $schema_version = get_schema_version();
857efe49
AD
81
82 if ($schema_version != SCHEMA_VERSION) {
83 die("Schema version is wrong, please upgrade the database.\n");
84 }
85
61c1812f
AD
86 define('PREFS_NO_CACHE', true);
87
2c08214a 88 // Test if the user has loggued in recently. If not, it does not update its feeds.
09e8bdfd 89 if (!SINGLE_USER_MODE && DAEMON_UPDATE_LOGIN_LIMIT > 0) {
2c08214a
AD
90 if (DB_TYPE == "pgsql") {
91 $login_thresh_qpart = "AND ttrss_users.last_login >= NOW() - INTERVAL '".DAEMON_UPDATE_LOGIN_LIMIT." days'";
92 } else {
93 $login_thresh_qpart = "AND ttrss_users.last_login >= DATE_SUB(NOW(), INTERVAL ".DAEMON_UPDATE_LOGIN_LIMIT." DAY)";
94 }
95 } else {
96 $login_thresh_qpart = "";
97 }
98
537eca40 99 // Test if the feed need a update (update interval exceeded).
2c08214a
AD
100 if (DB_TYPE == "pgsql") {
101 $update_limit_qpart = "AND ((
102 ttrss_feeds.update_interval = 0
ee0542ce 103 AND ttrss_user_prefs.value != '-1'
2c08214a
AD
104 AND ttrss_feeds.last_updated < NOW() - CAST((ttrss_user_prefs.value || ' minutes') AS INTERVAL)
105 ) OR (
106 ttrss_feeds.update_interval > 0
107 AND ttrss_feeds.last_updated < NOW() - CAST((ttrss_feeds.update_interval || ' minutes') AS INTERVAL)
f08426e3
AD
108 ) OR (ttrss_feeds.last_updated IS NULL
109 AND ttrss_user_prefs.value != '-1')
110 OR (last_updated = '1970-01-01 00:00:00'
111 AND ttrss_user_prefs.value != '-1'))";
2c08214a
AD
112 } else {
113 $update_limit_qpart = "AND ((
114 ttrss_feeds.update_interval = 0
ee0542ce 115 AND ttrss_user_prefs.value != '-1'
2c08214a
AD
116 AND ttrss_feeds.last_updated < DATE_SUB(NOW(), INTERVAL CONVERT(ttrss_user_prefs.value, SIGNED INTEGER) MINUTE)
117 ) OR (
118 ttrss_feeds.update_interval > 0
119 AND ttrss_feeds.last_updated < DATE_SUB(NOW(), INTERVAL ttrss_feeds.update_interval MINUTE)
f08426e3
AD
120 ) OR (ttrss_feeds.last_updated IS NULL
121 AND ttrss_user_prefs.value != '-1')
122 OR (last_updated = '1970-01-01 00:00:00'
123 AND ttrss_user_prefs.value != '-1'))";
2c08214a
AD
124 }
125
126 // Test if feed is currently being updated by another process.
127 if (DB_TYPE == "pgsql") {
566417c4 128 $updstart_thresh_qpart = "AND (ttrss_feeds.last_update_started IS NULL OR ttrss_feeds.last_update_started < NOW() - INTERVAL '10 minutes')";
2c08214a 129 } else {
566417c4 130 $updstart_thresh_qpart = "AND (ttrss_feeds.last_update_started IS NULL OR ttrss_feeds.last_update_started < DATE_SUB(NOW(), INTERVAL 10 MINUTE))";
2c08214a
AD
131 }
132
133 // Test if there is a limit to number of updated feeds
134 $query_limit = "";
135 if($limit) $query_limit = sprintf("LIMIT %d", $limit);
136
98070db0
TK
137 // Update the least recently updated feeds first
138 $query_order = "ORDER BY last_updated";
139 if (DB_TYPE == "pgsql") $query_order .= " NULLS FIRST";
140
fce451a4 141 $query = "SELECT DISTINCT ttrss_feeds.feed_url, ttrss_feeds.last_updated
2c08214a
AD
142 FROM
143 ttrss_feeds, ttrss_users, ttrss_user_prefs
f4ae0f05 144 WHERE
2c08214a 145 ttrss_feeds.owner_uid = ttrss_users.id
f08426e3 146 AND ttrss_user_prefs.profile IS NULL
2c08214a
AD
147 AND ttrss_users.id = ttrss_user_prefs.owner_uid
148 AND ttrss_user_prefs.pref_name = 'DEFAULT_UPDATE_INTERVAL'
149 $login_thresh_qpart $update_limit_qpart
1c4421fc 150 $updstart_thresh_qpart
98070db0 151 $query_order $query_limit";
fce451a4
AD
152
153 // We search for feed needing update.
154 $result = db_query($query);
2c08214a 155
ca5ff2d9 156 if($debug) _debug(sprintf("Scheduled %d feeds to update...", db_num_rows($result)));
2c08214a
AD
157
158 // Here is a little cache magic in order to minimize risk of double feed updates.
159 $feeds_to_update = array();
160 while ($line = db_fetch_assoc($result)) {
a42c55f0 161 array_push($feeds_to_update, db_escape_string($line['feed_url']));
2c08214a
AD
162 }
163
164 // We update the feed last update started date before anything else.
165 // There is no lag due to feed contents downloads
166 // It prevent an other process to update the same feed.
1c4421fc
AD
167
168 if(count($feeds_to_update) > 0) {
169 $feeds_quoted = array();
170
171 foreach ($feeds_to_update as $feed) {
a42c55f0 172 array_push($feeds_quoted, "'" . db_escape_string($feed) . "'");
1c4421fc
AD
173 }
174
a42c55f0 175 db_query(sprintf("UPDATE ttrss_feeds SET last_update_started = NOW()
1c4421fc 176 WHERE feed_url IN (%s)", implode(',', $feeds_quoted)));
2c08214a
AD
177 }
178
8292d05b 179 $nf = 0;
2d9c5684 180 $bstarted = microtime(true);
8292d05b 181
2c08214a 182 // For each feed, we call the feed update function.
1c4421fc
AD
183 foreach ($feeds_to_update as $feed) {
184 if($debug) _debug("Base feed: $feed");
2c08214a 185
a42c55f0 186 //update_rss_feed($line["id"], true);
2c08214a 187
1c4421fc
AD
188 // since we have the data cached, we can deal with other feeds with the same url
189
15c762be 190 $tmp_result = db_query("SELECT DISTINCT ttrss_feeds.id,last_updated,ttrss_feeds.owner_uid
ee0542ce
AD
191 FROM ttrss_feeds, ttrss_users, ttrss_user_prefs WHERE
192 ttrss_user_prefs.owner_uid = ttrss_feeds.owner_uid AND
193 ttrss_users.id = ttrss_user_prefs.owner_uid AND
194 ttrss_user_prefs.pref_name = 'DEFAULT_UPDATE_INTERVAL' AND
f08426e3 195 ttrss_user_prefs.profile IS NULL AND
a42c55f0 196 feed_url = '".db_escape_string($feed)."' AND
ee0542ce
AD
197 (ttrss_feeds.update_interval > 0 OR
198 ttrss_user_prefs.value != '-1')
1c4421fc 199 $login_thresh_qpart
5929a0c1 200 ORDER BY ttrss_feeds.id $query_limit");
1c4421fc
AD
201
202 if (db_num_rows($tmp_result) > 0) {
88edaa93
AD
203 $rss = false;
204
1c4421fc 205 while ($tline = db_fetch_assoc($tmp_result)) {
15c762be 206 if($debug) _debug(" => " . $tline["last_updated"] . ", " . $tline["id"] . " " . $tline["owner_uid"]);
f08426e3 207
2d9c5684 208 $fstarted = microtime(true);
f77c7203 209 $rss = update_rss_feed($tline["id"], true, false);
4f71d743 210 _debug_suppress(false);
2d9c5684
AD
211
212 _debug(sprintf(" %.4f (sec)", microtime(true) - $fstarted));
213
8292d05b 214 ++$nf;
1c4421fc
AD
215 }
216 }
2c08214a
AD
217 }
218
2d9c5684
AD
219 if ($nf > 0) {
220 _debug(sprintf("Processed %d feeds in %.4f (sec), %.4f (sec/feed avg)", $nf,
221 microtime(true) - $bstarted, (microtime(true) - $bstarted) / $nf));
222 }
223
f1611683
AD
224 require_once "digest.php";
225
2c08214a 226 // Send feed digests by email if needed.
a42c55f0 227 send_headlines_digests($debug);
2c08214a 228
8292d05b
AD
229 return $nf;
230
2c08214a
AD
231 } // function update_daemon_common
232
6022776d
AD
233 // this is used when subscribing
234 function set_basic_feed_info($feed) {
235
236 $feed = db_escape_string($feed);
237
9bd422c2 238 $result = db_query("SELECT feed_url,auth_pass,auth_login,auth_pass_encrypted
6022776d
AD
239 FROM ttrss_feeds WHERE id = '$feed'");
240
241 $auth_pass_encrypted = sql_bool_to_bool(db_fetch_result($result,
242 0, "auth_pass_encrypted"));
243
244 $auth_login = db_fetch_result($result, 0, "auth_login");
245 $auth_pass = db_fetch_result($result, 0, "auth_pass");
246
247 if ($auth_pass_encrypted) {
248 require_once "crypt.php";
249 $auth_pass = decrypt_string($auth_pass);
250 }
251
252 $fetch_url = db_fetch_result($result, 0, "feed_url");
253
254 $feed_data = fetch_file_contents($fetch_url, false,
255 $auth_login, $auth_pass, false,
256 FEED_FETCH_TIMEOUT_TIMEOUT,
257 0);
258
259 global $fetch_curl_used;
260
261 if (!$fetch_curl_used) {
262 $tmp = @gzdecode($feed_data);
263
264 if ($tmp) $feed_data = $tmp;
265 }
266
267 $feed_data = trim($feed_data);
268
269 $rss = new FeedParser($feed_data);
270 $rss->init();
271
272 if (!$rss->error()) {
273
274 $result = db_query("SELECT title, site_url FROM ttrss_feeds WHERE id = '$feed'");
275
276 $registered_title = db_fetch_result($result, 0, "title");
277 $orig_site_url = db_fetch_result($result, 0, "site_url");
278
279 $site_url = db_escape_string(mb_substr(rewrite_relative_url($fetch_url, $rss->get_link()), 0, 245));
280 $feed_title = db_escape_string(mb_substr($rss->get_title(), 0, 199));
281
282 if ($feed_title && (!$registered_title || $registered_title == "[Unknown]")) {
283 db_query("UPDATE ttrss_feeds SET
284 title = '$feed_title' WHERE id = '$feed'");
285 }
286
287 if ($site_url && $orig_site_url != $site_url) {
288 db_query("UPDATE ttrss_feeds SET
289 site_url = '$site_url' WHERE id = '$feed'");
290 }
291 }
292 }
293
87764a50 294 // ignore_daemon is not used
88edaa93 295 function update_rss_feed($feed, $ignore_daemon = false, $no_cache = false, $rss = false) {
2c08214a 296
2c08214a
AD
297 $debug_enabled = defined('DAEMON_EXTENDED_DEBUG') || $_REQUEST['xdebug'];
298
4f71d743 299 _debug_suppress(!$debug_enabled);
68cccafc 300 _debug("start", $debug_enabled);
2c08214a 301
6bb96beb
AD
302 $result = db_query("SELECT title FROM ttrss_feeds
303 WHERE id = '$feed'");
304 $title = db_fetch_result($result, 0, "title");
305
306 // feed was batch-subscribed or something, we need to get basic info
307 // this is not optimal currently as it fetches stuff separately TODO: optimize
308 if ($title == "[Unknown]") {
309 _debug("setting basic feed info for $feed...");
310 set_basic_feed_info($feed);
311 }
312
a42c55f0 313 $result = db_query("SELECT id,update_interval,auth_login,
5ba1ddd4 314 feed_url,auth_pass,cache_images,
5321e775 315 mark_unread_on_update, owner_uid,
90e5f4f1 316 pubsub_state, auth_pass_encrypted,
df659891 317 feed_language,
90e5f4f1
AD
318 (SELECT max(date_entered) FROM
319 ttrss_entries, ttrss_user_entries where ref_id = id AND feed_id = '$feed') AS last_article_timestamp
87764a50 320 FROM ttrss_feeds WHERE id = '$feed'");
2c08214a
AD
321
322 if (db_num_rows($result) == 0) {
68cccafc 323 _debug("feed $feed NOT FOUND/SKIPPED", $debug_enabled);
2c08214a
AD
324 return false;
325 }
326
90e5f4f1 327 $last_article_timestamp = @strtotime(db_fetch_result($result, 0, "last_article_timestamp"));
5d0d3887
AD
328
329 if (defined('_DISABLE_HTTP_304'))
330 $last_article_timestamp = 0;
331
2c08214a
AD
332 $owner_uid = db_fetch_result($result, 0, "owner_uid");
333 $mark_unread_on_update = sql_bool_to_bool(db_fetch_result($result,
334 0, "mark_unread_on_update"));
2c08214a 335 $pubsub_state = db_fetch_result($result, 0, "pubsub_state");
044cff2d
AD
336 $auth_pass_encrypted = sql_bool_to_bool(db_fetch_result($result,
337 0, "auth_pass_encrypted"));
2c08214a 338
a42c55f0 339 db_query("UPDATE ttrss_feeds SET last_update_started = NOW()
2c08214a
AD
340 WHERE id = '$feed'");
341
342 $auth_login = db_fetch_result($result, 0, "auth_login");
343 $auth_pass = db_fetch_result($result, 0, "auth_pass");
344
044cff2d
AD
345 if ($auth_pass_encrypted) {
346 require_once "crypt.php";
347 $auth_pass = decrypt_string($auth_pass);
348 }
349
2c08214a
AD
350 $cache_images = sql_bool_to_bool(db_fetch_result($result, 0, "cache_images"));
351 $fetch_url = db_fetch_result($result, 0, "feed_url");
df659891
AD
352 $feed_language = db_escape_string(mb_strtolower(db_fetch_result($result, 0, "feed_language")));
353 if (!$feed_language) $feed_language = 'english';
2c08214a 354
a42c55f0 355 $feed = db_escape_string($feed);
2c08214a 356
f074ffe9 357 $date_feed_processed = date('Y-m-d H:i');
2c08214a 358
865a3ed6 359 $cache_filename = CACHE_DIR . "/simplepie/" . sha1($fetch_url) . ".xml";
f074ffe9 360
ee65bef4
AD
361 $pluginhost = new PluginHost();
362 $pluginhost->set_debug($debug_enabled);
363 $user_plugins = get_pref("_ENABLED_PLUGINS", $owner_uid);
364
365 $pluginhost->load(PLUGINS, PluginHost::KIND_ALL);
366 $pluginhost->load($user_plugins, PluginHost::KIND_USER, $owner_uid);
367 $pluginhost->load_data();
368
88edaa93
AD
369 if ($rss && is_object($rss) && get_class($rss) == "FeedParser") {
370 _debug("using previously initialized parser object");
371 } else {
372 $rss_hash = false;
4f9cbdff 373
88edaa93 374 $force_refetch = isset($_REQUEST["force_refetch"]);
687a4f59 375
95beaa14 376 foreach ($pluginhost->get_hooks(PluginHost::HOOK_FETCH_FEED) as $plugin) {
01465325 377 $feed_data = $plugin->hook_fetch_feed($feed_data, $fetch_url, $owner_uid, $feed, $last_article_timestamp, $auth_login, $auth_pass);
95beaa14
RA
378 }
379
380 // try cache
381 if (!$feed_data &&
382 file_exists($cache_filename) &&
88edaa93
AD
383 is_readable($cache_filename) &&
384 !$auth_login && !$auth_pass &&
385 filemtime($cache_filename) > time() - 30) {
2c08214a 386
15d0528a 387 _debug("using local cache [$cache_filename].", $debug_enabled);
be574731 388
88edaa93 389 @$feed_data = file_get_contents($cache_filename);
52637d3b 390
88edaa93
AD
391 if ($feed_data) {
392 $rss_hash = sha1($feed_data);
393 }
f074ffe9 394
88edaa93
AD
395 } else {
396 _debug("local cache will not be used for this feed", $debug_enabled);
397 }
ee65bef4 398
95beaa14 399 // fetch feed from source
fd687300
AD
400 if (!$feed_data) {
401 _debug("fetching [$fetch_url]...", $debug_enabled);
402 _debug("If-Modified-Since: ".gmdate('D, d M Y H:i:s \G\M\T', $last_article_timestamp), $debug_enabled);
96f98cb0 403
fd687300
AD
404 $feed_data = fetch_file_contents($fetch_url, false,
405 $auth_login, $auth_pass, false,
406 $no_cache ? FEED_FETCH_NO_CACHE_TIMEOUT : FEED_FETCH_TIMEOUT,
407 $force_refetch ? 0 : $last_article_timestamp);
3f6f0857 408
fd687300 409 global $fetch_curl_used;
3f6f0857 410
fd687300
AD
411 if (!$fetch_curl_used) {
412 $tmp = @gzdecode($feed_data);
3f6f0857 413
fd687300
AD
414 if ($tmp) $feed_data = $tmp;
415 }
1367bc3f 416
fd687300 417 $feed_data = trim($feed_data);
017401dd 418
fd687300
AD
419 _debug("fetch done.", $debug_enabled);
420
95beaa14
RA
421 // cache vanilla feed data for re-use
422 if ($feed_data && !$auth_pass && !$auth_login && is_writable(CACHE_DIR . "/simplepie")) {
423 $new_rss_hash = sha1($feed_data);
424
425 if ($new_rss_hash != $rss_hash) {
426 _debug("saving $cache_filename", $debug_enabled);
427 @file_put_contents($cache_filename, $feed_data);
428 }
429 }
4f9cbdff 430 }
017401dd 431
fd687300
AD
432 if (!$feed_data) {
433 global $fetch_last_error;
434 global $fetch_last_error_code;
f074ffe9 435
fd687300 436 _debug("unable to fetch: $fetch_last_error [$fetch_last_error_code]", $debug_enabled);
f074ffe9 437
fd687300 438 $error_escaped = '';
7a01dc77 439
fd687300
AD
440 // If-Modified-Since
441 if ($fetch_last_error_code != 304) {
442 $error_escaped = db_escape_string($fetch_last_error);
443 } else {
444 _debug("source claims data not modified, nothing to do.", $debug_enabled);
445 }
4f9cbdff 446
fd687300
AD
447 db_query(
448 "UPDATE ttrss_feeds SET last_error = '$error_escaped',
449 last_updated = NOW() WHERE id = '$feed'");
4f9cbdff 450
fd687300
AD
451 return;
452 }
f074ffe9
AD
453 }
454
1ffe3391 455 foreach ($pluginhost->get_hooks(PluginHost::HOOK_FEED_FETCHED) as $plugin) {
6791af0c 456 $feed_data = $plugin->hook_feed_fetched($feed_data, $fetch_url, $owner_uid, $feed);
017401dd
AD
457 }
458
5ef84097
AD
459 // set last update to now so if anything *simplepie* crashes later we won't be
460 // continuously failing on the same feed
5de40104 461 //db_query("UPDATE ttrss_feeds SET last_updated = NOW() WHERE id = '$feed'");
5ef84097 462
4f9cbdff 463 if (!$rss) {
cd07592c
AD
464 $rss = new FeedParser($feed_data);
465 $rss->init();
5de51df7
AD
466 }
467
2c08214a
AD
468// print_r($rss);
469
a42c55f0 470 $feed = db_escape_string($feed);
2c08214a 471
19b3992b 472 if (!$rss->error()) {
2c08214a 473
d2a421e3 474 // We use local pluginhost here because we need to load different per-user feed plugins
1ffe3391 475 $pluginhost->run_hooks(PluginHost::HOOK_FEED_PARSED, "hook_feed_parsed", $rss);
4412b877 476
df659891 477 _debug("language: $feed_language", $debug_enabled);
68cccafc 478 _debug("processing feed data...", $debug_enabled);
2c08214a 479
a42c55f0 480// db_query("BEGIN");
2c08214a 481
382268c6
AD
482 if (DB_TYPE == "pgsql") {
483 $favicon_interval_qpart = "favicon_last_checked < NOW() - INTERVAL '12 hour'";
484 } else {
485 $favicon_interval_qpart = "favicon_last_checked < DATE_SUB(NOW(), INTERVAL 12 HOUR)";
486 }
487
fe4535e6 488 $result = db_query("SELECT owner_uid,favicon_avg_color,
382268c6
AD
489 (favicon_last_checked IS NULL OR $favicon_interval_qpart) AS
490 favicon_needs_check
2c08214a
AD
491 FROM ttrss_feeds WHERE id = '$feed'");
492
382268c6
AD
493 $favicon_needs_check = sql_bool_to_bool(db_fetch_result($result, 0,
494 "favicon_needs_check"));
36490f11 495 $favicon_avg_color = db_fetch_result($result, 0, "favicon_avg_color");
2c08214a
AD
496
497 $owner_uid = db_fetch_result($result, 0, "owner_uid");
498
a42c55f0 499 $site_url = db_escape_string(mb_substr(rewrite_relative_url($fetch_url, $rss->get_link()), 0, 245));
2c08214a 500
cd07592c
AD
501 _debug("site_url: $site_url", $debug_enabled);
502 _debug("feed_title: " . $rss->get_title(), $debug_enabled);
503
687a4f59 504 if ($favicon_needs_check || $force_refetch) {
36490f11
AD
505
506 /* terrible hack: if we crash on floicon shit here, we won't check
560cbd8c 507 * the icon avgcolor again (unless the icon got updated) */
36490f11 508
560cbd8c
AD
509 $favicon_file = ICONS_DIR . "/$feed.ico";
510 $favicon_modified = @filemtime($favicon_file);
511
68cccafc 512 _debug("checking favicon...", $debug_enabled);
687a4f59 513
6f7798b6 514 check_feed_favicon($site_url, $feed);
560cbd8c
AD
515 $favicon_modified_new = @filemtime($favicon_file);
516
517 if ($favicon_modified_new > $favicon_modified)
518 $favicon_avg_color = '';
687a4f59 519
6ee0d4b0 520 if (file_exists($favicon_file) && function_exists("imagecreatefromstring") && $favicon_avg_color == '') {
bc7a144d 521 require_once "colors.php";
687a4f59 522
aafd55ba
AD
523 db_query("UPDATE ttrss_feeds SET favicon_avg_color = 'fail' WHERE
524 id = '$feed'");
525
6322ac79 526 $favicon_color = db_escape_string(
bc7a144d 527 calculate_avg_color($favicon_file));
63c323f7 528
bc7a144d 529 $favicon_colorstring = ",favicon_avg_color = '".$favicon_color."'";
36490f11 530 } else if ($favicon_avg_color == 'fail') {
84ceb6bd 531 _debug("floicon failed on this file, not trying to recalculate avg color", $debug_enabled);
6ac722d5 532 }
687a4f59 533
a42c55f0 534 db_query("UPDATE ttrss_feeds SET favicon_last_checked = NOW()
bc7a144d 535 $favicon_colorstring
f2798eb6
AD
536 WHERE id = '$feed'");
537 }
2c08214a 538
68cccafc 539 _debug("loading filters & labels...", $debug_enabled);
2c08214a 540
a42c55f0 541 $filters = load_filters($feed, $owner_uid);
2c08214a 542
68cccafc 543 _debug("" . count($filters) . " filters loaded.", $debug_enabled);
2c08214a 544
19b3992b 545 $items = $rss->get_items();
2c08214a 546
19b3992b 547 if (!is_array($items)) {
68cccafc 548 _debug("no articles found.", $debug_enabled);
2c08214a 549
a42c55f0 550 db_query("UPDATE ttrss_feeds
2c08214a
AD
551 SET last_updated = NOW(), last_error = '' WHERE id = '$feed'");
552
553 return; // no articles
554 }
555
556 if ($pubsub_state != 2 && PUBSUBHUBBUB_ENABLED) {
557
68cccafc 558 _debug("checking for PUSH hub...", $debug_enabled);
2c08214a
AD
559
560 $feed_hub_url = false;
2c08214a 561
19b3992b 562 $links = $rss->get_links('hub');
2c08214a 563
19b3992b
AD
564 if ($links && is_array($links)) {
565 foreach ($links as $l) {
566 $feed_hub_url = $l;
567 break;
2c08214a
AD
568 }
569 }
570
68cccafc 571 _debug("feed hub url: $feed_hub_url", $debug_enabled);
2c08214a 572
d8179cb9
AD
573 $feed_self_url = $fetch_url;
574
575 $links = $rss->get_links('self');
576
577 if ($links && is_array($links)) {
578 foreach ($links as $l) {
579 $feed_self_url = $l;
580 break;
581 }
582 }
583
584 _debug("feed self url = $feed_self_url");
585
586 if ($feed_hub_url && $feed_self_url && function_exists('curl_init') &&
2c08214a
AD
587 !ini_get("open_basedir")) {
588
589 require_once 'lib/pubsubhubbub/subscriber.php';
590
591 $callback_url = get_self_url_prefix() .
592 "/public.php?op=pubsub&id=$feed";
593
594 $s = new Subscriber($feed_hub_url, $callback_url);
595
d8179cb9 596 $rc = $s->subscribe($feed_self_url);
2c08214a 597
5ba1ddd4 598 _debug("feed hub url found, subscribe request sent. [rc=$rc]", $debug_enabled);
2c08214a 599
a42c55f0 600 db_query("UPDATE ttrss_feeds SET pubsub_state = 1
2c08214a
AD
601 WHERE id = '$feed'");
602 }
603 }
604
68cccafc 605 _debug("processing articles...", $debug_enabled);
2c08214a 606
6c9f3d4a
AD
607 $tstart = time();
608
19b3992b 609 foreach ($items as $item) {
5d56d100 610 if ($_REQUEST['xdebug'] == 3) {
2c08214a
AD
611 print_r($item);
612 }
613
6c9f3d4a
AD
614 if (ini_get("max_execution_time") > 0 && time() - $tstart >= ini_get("max_execution_time") * 0.7) {
615 _debug("looks like there's too many articles to process at once, breaking out", $debug_enabled);
616 break;
617 }
618
19b3992b
AD
619 $entry_guid = $item->get_id();
620 if (!$entry_guid) $entry_guid = $item->get_link();
621 if (!$entry_guid) $entry_guid = make_guid_from_title($item->get_title());
2c08214a
AD
622 if (!$entry_guid) continue;
623
3a4c8973
AD
624 $entry_guid = "$owner_uid,$entry_guid";
625
a42c55f0 626 $entry_guid_hashed = db_escape_string('SHA1:' . sha1($entry_guid));
5e3d5480 627
68cccafc 628 _debug("guid $entry_guid / $entry_guid_hashed", $debug_enabled);
5e3d5480 629
2c08214a
AD
630 $entry_timestamp = "";
631
04d2f9c8
AD
632 $entry_timestamp = $item->get_date();
633
634 _debug("orig date: " . $item->get_date(), $debug_enabled);
2c08214a 635
30123fe6 636 if ($entry_timestamp == -1 || !$entry_timestamp || $entry_timestamp > time()) {
2c08214a 637 $entry_timestamp = time();
2c08214a
AD
638 }
639
640 $entry_timestamp_fmt = strftime("%Y/%m/%d %H:%M:%S", $entry_timestamp);
641
68cccafc 642 _debug("date $entry_timestamp [$entry_timestamp_fmt]", $debug_enabled);
2c08214a 643
99429e57
AD
644// $entry_title = html_entity_decode($item->get_title(), ENT_COMPAT, 'UTF-8');
645// $entry_title = decode_numeric_entities($entry_title);
646 $entry_title = $item->get_title();
1b35d30c 647
5d56d100 648 $entry_link = rewrite_relative_url($site_url, $item->get_link());
2c08214a 649
68cccafc
AD
650 _debug("title $entry_title", $debug_enabled);
651 _debug("link $entry_link", $debug_enabled);
2c08214a
AD
652
653 if (!$entry_title) $entry_title = date("Y-m-d H:i:s", $entry_timestamp);;
654
19b3992b
AD
655 $entry_content = $item->get_content();
656 if (!$entry_content) $entry_content = $item->get_description();
2c08214a
AD
657
658 if ($_REQUEST["xdebug"] == 2) {
9ec10352 659 print "content: ";
487f0750 660 print $entry_content;
3c696512 661 print "\n";
2c08214a
AD
662 }
663
cd07592c
AD
664 $entry_comments = $item->get_comments_url();
665 $entry_author = $item->get_author();
2c08214a 666
a42c55f0 667 $entry_guid = db_escape_string(mb_substr($entry_guid, 0, 245));
2c08214a 668
ce2b219c
AD
669 $entry_comments = db_escape_string(mb_substr(trim($entry_comments), 0, 245));
670 $entry_author = db_escape_string(mb_substr(trim($entry_author), 0, 245));
2c08214a 671
d4992d6b 672 $num_comments = (int) $item->get_comments_count();
2c08214a 673
68cccafc
AD
674 _debug("author $entry_author", $debug_enabled);
675 _debug("num_comments: $num_comments", $debug_enabled);
ee78f81c 676 _debug("looking for tags...", $debug_enabled);
2c08214a
AD
677
678 // parse <category> entries into tags
679
680 $additional_tags = array();
681
19b3992b 682 $additional_tags_src = $item->get_categories();
2c08214a 683
19b3992b
AD
684 if (is_array($additional_tags_src)) {
685 foreach ($additional_tags_src as $tobj) {
cd07592c 686 array_push($additional_tags, $tobj);
2c08214a 687 }
19b3992b 688 }
2c08214a 689
fa6fbd36 690 $entry_tags = array_unique($additional_tags);
2c08214a
AD
691
692 for ($i = 0; $i < count($entry_tags); $i++)
693 $entry_tags[$i] = mb_strtolower($entry_tags[$i], 'utf-8');
694
ee78f81c
AD
695 _debug("tags found: " . join(",", $entry_tags), $debug_enabled);
696
68cccafc 697 _debug("done collecting data.", $debug_enabled);
2c08214a 698
3318d324 699 $result = db_query("SELECT id, content_hash, lang FROM ttrss_entries
b1840673 700 WHERE guid = '".db_escape_string($entry_guid)."' OR guid = '$entry_guid_hashed'");
b30abdad
AD
701
702 if (db_num_rows($result) != 0) {
b1840673
AD
703 $base_entry_id = db_fetch_result($result, 0, "id");
704 $entry_stored_hash = db_fetch_result($result, 0, "content_hash");
a29fe121 705 $article_labels = get_article_labels($base_entry_id, $owner_uid);
3318d324 706 $entry_language = db_fetch_result($result, 0, "lang");
a8ac7661 707
040aa540 708 $existing_tags = get_article_tags($base_entry_id, $owner_uid);
a8ac7661
AD
709 $entry_tags = array_unique(array_merge($entry_tags, $existing_tags));
710
b30abdad 711 } else {
b1840673
AD
712 $base_entry_id = false;
713 $entry_stored_hash = "";
a29fe121 714 $article_labels = array();
3318d324 715 $entry_language = "";
b30abdad
AD
716 }
717
455b1401 718 $article = array("owner_uid" => $owner_uid, // read only
b30abdad 719 "guid" => $entry_guid, // read only
59e83455 720 "guid_hashed" => $entry_guid_hashed, // read only
19b3992b
AD
721 "title" => $entry_title,
722 "content" => $entry_content,
723 "link" => $entry_link,
a29fe121 724 "labels" => $article_labels, // current limitation: can add labels to article, can't remove them
19b3992b 725 "tags" => $entry_tags,
e02555c1 726 "author" => $entry_author,
c9299c28 727 "force_catchup" => false, // ugly hack for the time being
6de3a1be 728 "score_modifier" => 0, // no previous value, plugin should recalculate score modifier based on content if needed
3318d324 729 "language" => $entry_language,
f73e03e0
AD
730 "feed" => array("id" => $feed,
731 "fetch_url" => $fetch_url,
732 "site_url" => $site_url)
733 );
cc85704f 734
b1840673 735 $entry_plugin_data = "";
eb16bd9f 736 $entry_current_hash = calculate_article_hash($article, $pluginhost);
b1840673
AD
737
738 _debug("article hash: $entry_current_hash [stored=$entry_stored_hash]", $debug_enabled);
739
522e8b35 740 if ($entry_current_hash == $entry_stored_hash && !isset($_REQUEST["force_rehash"])) {
b1840673
AD
741 _debug("stored article seems up to date [IID: $base_entry_id], updating timestamp only", $debug_enabled);
742
743 // we keep encountering the entry in feeds, so we need to
744 // update date_updated column so that we don't get horrible
745 // dupes when the entry gets purged and reinserted again e.g.
746 // in the case of SLOW SLOW OMG SLOW updating feeds
747
748 $base_entry_id = db_fetch_result($result, 0, "id");
749
750 db_query("UPDATE ttrss_entries SET date_updated = NOW()
751 WHERE id = '$base_entry_id'");
752
e44280a0 753 // if we allow duplicate posts, we have to continue to
da7e3e91
GP
754 // create the user entries for this feed
755 if (!get_pref("ALLOW_DUPLICATE_POSTS", $owner_uid, false)) {
756 continue;
757 }
b1840673
AD
758 }
759
760 _debug("hash differs, applying plugin filters:", $debug_enabled);
761
1ffe3391 762 foreach ($pluginhost->get_hooks(PluginHost::HOOK_ARTICLE_FILTER) as $plugin) {
b1840673
AD
763 _debug("... " . get_class($plugin), $debug_enabled);
764
765 $start = microtime(true);
19b3992b 766 $article = $plugin->hook_article_filter($article);
0084f0d1 767
b1840673
AD
768 _debug("=== " . sprintf("%.4f (sec)", microtime(true) - $start), $debug_enabled);
769
770 $entry_plugin_data .= mb_strtolower(get_class($plugin)) . ",";
cc85704f
AD
771 }
772
b1840673
AD
773 $entry_plugin_data = db_escape_string($entry_plugin_data);
774
775 _debug("plugin data: $entry_plugin_data", $debug_enabled);
776
35c12dc4
AD
777 // Workaround: 4-byte unicode requires utf8mb4 in MySQL. See https://tt-rss.org/forum/viewtopic.php?f=1&t=3377&p=20077#p20077
778 if (DB_TYPE == "mysql") {
779 foreach ($article as $k => $v) {
35c37354
AD
780
781 // i guess we'll have to take the risk of 4byte unicode labels & tags here
782 if (!is_array($article[$k])) {
783 $article[$k] = preg_replace('/[\x{10000}-\x{10FFFF}]/u', "\xEF\xBF\xBD", $v);
784 }
35c12dc4
AD
785 }
786 }
787
b8774453
AD
788 /* Collect article tags here so we could filter by them: */
789
790 $article_filters = get_article_filters($filters, $article["title"],
791 $article["content"], $article["link"], 0, $article["author"],
792 $article["tags"]);
793
794 if ($debug_enabled) {
795 _debug("article filters: ", $debug_enabled);
796 if (count($article_filters) != 0) {
797 print_r($article_filters);
798 }
799 }
800
801 $plugin_filter_names = find_article_filters($article_filters, "plugin");
802 $plugin_filter_actions = $pluginhost->get_filter_actions();
803
804 if (count($plugin_filter_names) > 0) {
805 _debug("applying plugin filter actions...", $debug_enabled);
806
807 foreach ($plugin_filter_names as $pfn) {
808 list($pfclass,$pfaction) = explode(":", $pfn["param"]);
809
810 if (isset($plugin_filter_actions[$pfclass])) {
811 $plugin = $pluginhost->get_plugin($pfclass);
812
813 _debug("... $pfclass: $pfaction", $debug_enabled);
814
815 if ($plugin) {
816 $start = microtime(true);
817 $article = $plugin->hook_article_filter_action($article, $pfaction);
818
819 _debug("=== " . sprintf("%.4f (sec)", microtime(true) - $start), $debug_enabled);
820 } else {
821 _debug("??? $pfclass: plugin object not found.");
822 }
823 } else {
824 _debug("??? $pfclass: filter plugin not registered.");
825 }
826 }
827 }
828
19b3992b 829 $entry_tags = $article["tags"];
a42c55f0
AD
830 $entry_guid = db_escape_string($entry_guid);
831 $entry_title = db_escape_string($article["title"]);
832 $entry_author = db_escape_string($article["author"]);
833 $entry_link = db_escape_string($article["link"]);
f935d98e 834 $entry_content = $article["content"]; // escaped below
c9299c28 835 $entry_force_catchup = $article["force_catchup"];
a29fe121 836 $article_labels = $article["labels"];
6de3a1be 837 $entry_score_modifier = (int) $article["score_modifier"];
3318d324 838 $entry_language = db_escape_string($article["language"]);
a29fe121
AD
839
840 if ($debug_enabled) {
841 _debug("article labels:", $debug_enabled);
842 print_r($article_labels);
843 }
c9299c28
AD
844
845 _debug("force catchup: $entry_force_catchup");
f935d98e 846
0a3fd79b 847 if ($cache_images && is_writable(CACHE_DIR . '/images'))
f0bd8e65 848 cache_images($entry_content, $site_url, $debug_enabled);
0a3fd79b 849
a42c55f0 850 $entry_content = db_escape_string($entry_content, false);
1f45c857 851
07877caf 852 //db_query("BEGIN");
2c08214a 853
a42c55f0 854 $result = db_query("SELECT id FROM ttrss_entries
5e3d5480 855 WHERE (guid = '$entry_guid' OR guid = '$entry_guid_hashed')");
9e222305 856
2c08214a
AD
857 if (db_num_rows($result) == 0) {
858
68cccafc 859 _debug("base guid [$entry_guid] not found", $debug_enabled);
2c08214a
AD
860
861 // base post entry does not exist, create it
862
6322ac79 863 $result = db_query(
2c08214a
AD
864 "INSERT INTO ttrss_entries
865 (title,
866 guid,
867 link,
868 updated,
869 content,
870 content_hash,
871 no_orig_date,
872 date_updated,
873 date_entered,
874 comments,
875 num_comments,
b30abdad 876 plugin_data,
6b461797 877 lang,
2c08214a
AD
878 author)
879 VALUES
880 ('$entry_title',
5e3d5480 881 '$entry_guid_hashed',
2c08214a
AD
882 '$entry_link',
883 '$entry_timestamp_fmt',
884 '$entry_content',
b1840673 885 '$entry_current_hash',
5ba1ddd4 886 false,
2c08214a 887 NOW(),
be574731 888 '$date_feed_processed',
2c08214a
AD
889 '$entry_comments',
890 '$num_comments',
b30abdad 891 '$entry_plugin_data',
6b461797 892 '$entry_language',
2c08214a 893 '$entry_author')");
e8291805 894
2c08214a 895 } else {
2c08214a 896 $base_entry_id = db_fetch_result($result, 0, "id");
2c08214a
AD
897 }
898
899 // now it should exist, if not - bad luck then
900
b1840673 901 $result = db_query("SELECT id FROM ttrss_entries
5e3d5480 902 WHERE guid = '$entry_guid' OR guid = '$entry_guid_hashed'");
2c08214a
AD
903
904 $entry_ref_id = 0;
905 $entry_int_id = 0;
906
907 if (db_num_rows($result) == 1) {
908
68cccafc 909 _debug("base guid found, checking for user record", $debug_enabled);
2c08214a 910
2c08214a
AD
911 $ref_id = db_fetch_result($result, 0, "id");
912 $entry_ref_id = $ref_id;
913
5e3d5480
AD
914 /* $stored_guid = db_fetch_result($result, 0, "guid");
915 if ($stored_guid != $entry_guid_hashed) {
68cccafc 916 if ($debug_enabled) _debug("upgrading compat guid to hashed one", $debug_enabled);
5e3d5480 917
a42c55f0 918 db_query("UPDATE ttrss_entries SET guid = '$entry_guid_hashed' WHERE
5e3d5480
AD
919 id = '$ref_id'");
920 } */
921
2c08214a
AD
922 // check for user post link to main table
923
924 // do we allow duplicate posts with same GUID in different feeds?
a42c55f0 925 if (get_pref("ALLOW_DUPLICATE_POSTS", $owner_uid, false)) {
2c08214a
AD
926 $dupcheck_qpart = "AND (feed_id = '$feed' OR feed_id IS NULL)";
927 } else {
928 $dupcheck_qpart = "";
929 }
930
2c08214a 931 if (find_article_filter($article_filters, "filter")) {
07877caf 932 //db_query("COMMIT"); // close transaction in progress
2c08214a
AD
933 continue;
934 }
935
6de3a1be 936 $score = calculate_article_score($article_filters) + $entry_score_modifier;
2c08214a 937
6de3a1be 938 _debug("initial score: $score [including plugin modifier: $entry_score_modifier]", $debug_enabled);
2c08214a
AD
939
940 $query = "SELECT ref_id, int_id FROM ttrss_user_entries WHERE
941 ref_id = '$ref_id' AND owner_uid = '$owner_uid'
942 $dupcheck_qpart";
943
944// if ($_REQUEST["xdebug"]) print "$query\n";
945
a42c55f0 946 $result = db_query($query);
2c08214a
AD
947
948 // okay it doesn't exist - create user entry
949 if (db_num_rows($result) == 0) {
950
68cccafc 951 _debug("user record not found, creating...", $debug_enabled);
2c08214a 952
c9299c28 953 if ($score >= -500 && !find_article_filter($article_filters, 'catchup') && !$entry_force_catchup) {
2c08214a
AD
954 $unread = 'true';
955 $last_read_qpart = 'NULL';
956 } else {
957 $unread = 'false';
958 $last_read_qpart = 'NOW()';
959 }
960
961 if (find_article_filter($article_filters, 'mark') || $score > 1000) {
962 $marked = 'true';
963 } else {
964 $marked = 'false';
965 }
966
967 if (find_article_filter($article_filters, 'publish')) {
968 $published = 'true';
969 } else {
970 $published = 'false';
971 }
972
2ea9bbfd
AD
973 // N-grams
974
c9299c28 975 /* if (DB_TYPE == "pgsql" and defined('_NGRAM_TITLE_DUPLICATE_THRESHOLD')) {
2ea9bbfd 976
a42c55f0 977 $result = db_query("SELECT COUNT(*) AS similar FROM
2ea9bbfd
AD
978 ttrss_entries,ttrss_user_entries
979 WHERE ref_id = id AND updated >= NOW() - INTERVAL '7 day'
980 AND similarity(title, '$entry_title') >= "._NGRAM_TITLE_DUPLICATE_THRESHOLD."
981 AND owner_uid = $owner_uid");
982
983 $ngram_similar = db_fetch_result($result, 0, "similar");
984
68cccafc 985 _debug("N-gram similar results: $ngram_similar", $debug_enabled);
2ea9bbfd
AD
986
987 if ($ngram_similar > 0) {
988 $unread = 'false';
989 }
c9299c28 990 } */
2ea9bbfd 991
7873d588
AD
992 $last_marked = ($marked == 'true') ? 'NOW()' : 'NULL';
993 $last_published = ($published == 'true') ? 'NOW()' : 'NULL';
994
6322ac79 995 $result = db_query(
2c08214a
AD
996 "INSERT INTO ttrss_user_entries
997 (ref_id, owner_uid, feed_id, unread, last_read, marked,
7873d588
AD
998 published, score, tag_cache, label_cache, uuid,
999 last_marked, last_published)
2c08214a 1000 VALUES ('$ref_id', '$owner_uid', '$feed', $unread,
7873d588
AD
1001 $last_read_qpart, $marked, $published, '$score', '', '',
1002 '', $last_marked, $last_published)");
2c08214a
AD
1003
1004 if (PUBSUBHUBBUB_HUB && $published == 'true') {
1005 $rss_link = get_self_url_prefix() .
1006 "/public.php?op=rss&id=-2&key=" .
a42c55f0 1007 get_feed_access_key(-2, false, $owner_uid);
2c08214a
AD
1008
1009 $p = new Publisher(PUBSUBHUBBUB_HUB);
1010
5ba1ddd4 1011 /* $pubsub_result = */ $p->publish_update($rss_link);
2c08214a
AD
1012 }
1013
6322ac79 1014 $result = db_query(
2c08214a
AD
1015 "SELECT int_id FROM ttrss_user_entries WHERE
1016 ref_id = '$ref_id' AND owner_uid = '$owner_uid' AND
1017 feed_id = '$feed' LIMIT 1");
1018
1019 if (db_num_rows($result) == 1) {
1020 $entry_int_id = db_fetch_result($result, 0, "int_id");
1021 }
1022 } else {
68cccafc 1023 _debug("user record FOUND", $debug_enabled);
2c08214a
AD
1024
1025 $entry_ref_id = db_fetch_result($result, 0, "ref_id");
1026 $entry_int_id = db_fetch_result($result, 0, "int_id");
1027 }
1028
68cccafc 1029 _debug("RID: $entry_ref_id, IID: $entry_int_id", $debug_enabled);
2c08214a 1030
e854442e 1031 if (DB_TYPE == "pgsql") {
978989bb 1032 $tsvector_combined = db_escape_string(mb_substr($entry_title . ' ' . strip_tags(str_replace('<', ' <', $entry_content)),
e854442e
AD
1033 0, 1000000));
1034
df659891 1035 $tsvector_qpart = "tsvector_combined = to_tsvector('$feed_language', '$tsvector_combined'),";
e854442e
AD
1036
1037 } else {
1038 $tsvector_qpart = "";
1039 }
1040
b1840673
AD
1041 db_query("UPDATE ttrss_entries
1042 SET title = '$entry_title',
1043 content = '$entry_content',
1044 content_hash = '$entry_current_hash',
1045 updated = '$entry_timestamp_fmt',
e854442e 1046 $tsvector_qpart
b1840673
AD
1047 num_comments = '$num_comments',
1048 plugin_data = '$entry_plugin_data',
1049 author = '$entry_author',
1050 lang = '$entry_language'
1051 WHERE id = '$ref_id'");
1052
59e83455
AD
1053 // update aux data
1054 db_query("UPDATE ttrss_user_entries
1055 SET score = '$score' WHERE ref_id = '$ref_id'");
1056
b1840673 1057 if ($mark_unread_on_update) {
24e6ff5d
AD
1058 _debug("article updated, marking unread as requested.", $debug_enabled);
1059
b1840673
AD
1060 db_query("UPDATE ttrss_user_entries
1061 SET last_read = null, unread = true WHERE ref_id = '$ref_id'");
2c08214a
AD
1062 }
1063 }
1064
07877caf 1065 //db_query("COMMIT");
2c08214a 1066
a29fe121
AD
1067 _debug("assigning labels [other]...", $debug_enabled);
1068
1069 foreach ($article_labels as $label) {
1070 label_add_article($entry_ref_id, $label[1], $owner_uid);
1071 }
1072
1073 _debug("assigning labels [filters]...", $debug_enabled);
2c08214a 1074
a42c55f0 1075 assign_article_to_label_filters($entry_ref_id, $article_filters,
b24504b1 1076 $owner_uid, $article_labels);
2c08214a 1077
68cccafc 1078 _debug("looking for enclosures...", $debug_enabled);
2c08214a
AD
1079
1080 // enclosures
1081
1082 $enclosures = array();
1083
19b3992b 1084 $encs = $item->get_enclosures();
2c08214a 1085
19b3992b
AD
1086 if (is_array($encs)) {
1087 foreach ($encs as $e) {
1088 $e_item = array(
523bd90b 1089 $e->link, $e->type, $e->length, $e->title, $e->width, $e->height);
2c08214a 1090 array_push($enclosures, $e_item);
2c08214a
AD
1091 }
1092 }
1093
2c08214a 1094 if ($debug_enabled) {
68cccafc 1095 _debug("article enclosures:", $debug_enabled);
2c08214a
AD
1096 print_r($enclosures);
1097 }
1098
dab229cd 1099 //db_query("BEGIN");
2c08214a 1100
5c54e683
AD
1101// debugging
1102// db_query("DELETE FROM ttrss_enclosures WHERE post_id = '$entry_ref_id'");
1103
2c08214a 1104 foreach ($enclosures as $enc) {
a42c55f0
AD
1105 $enc_url = db_escape_string($enc[0]);
1106 $enc_type = db_escape_string($enc[1]);
1107 $enc_dur = db_escape_string($enc[2]);
5c54e683 1108 $enc_title = db_escape_string($enc[3]);
523bd90b
FE
1109 $enc_width = intval($enc[4]);
1110 $enc_height = intval($enc[5]);
2c08214a 1111
a42c55f0 1112 $result = db_query("SELECT id FROM ttrss_enclosures
2c08214a
AD
1113 WHERE content_url = '$enc_url' AND post_id = '$entry_ref_id'");
1114
1115 if (db_num_rows($result) == 0) {
a42c55f0 1116 db_query("INSERT INTO ttrss_enclosures
523bd90b
FE
1117 (content_url, content_type, title, duration, post_id, width, height) VALUES
1118 ('$enc_url', '$enc_type', '$enc_title', '$enc_dur', '$entry_ref_id', $enc_width, $enc_height)");
2c08214a
AD
1119 }
1120 }
1121
dab229cd 1122 //db_query("COMMIT");
2c08214a
AD
1123
1124 // check for manual tags (we have to do it here since they're loaded from filters)
1125
1126 foreach ($article_filters as $f) {
6aff7845 1127 if ($f["type"] == "tag") {
2c08214a 1128
6aff7845 1129 $manual_tags = trim_array(explode(",", $f["param"]));
2c08214a
AD
1130
1131 foreach ($manual_tags as $tag) {
1132 if (tag_is_valid($tag)) {
1133 array_push($entry_tags, $tag);
1134 }
1135 }
1136 }
1137 }
1138
1139 // Skip boring tags
1140
6322ac79 1141 $boring_tags = trim_array(explode(",", mb_strtolower(get_pref(
2c08214a
AD
1142 'BLACKLISTED_TAGS', $owner_uid, ''), 'utf-8')));
1143
1144 $filtered_tags = array();
1145 $tags_to_cache = array();
1146
1147 if ($entry_tags && is_array($entry_tags)) {
1148 foreach ($entry_tags as $tag) {
1149 if (array_search($tag, $boring_tags) === false) {
1150 array_push($filtered_tags, $tag);
1151 }
1152 }
1153 }
1154
1155 $filtered_tags = array_unique($filtered_tags);
1156
1157 if ($debug_enabled) {
68cccafc 1158 _debug("filtered article tags:", $debug_enabled);
2c08214a
AD
1159 print_r($filtered_tags);
1160 }
1161
1162 // Save article tags in the database
1163
1164 if (count($filtered_tags) > 0) {
1165
dab229cd 1166 //db_query("BEGIN");
2c08214a
AD
1167
1168 foreach ($filtered_tags as $tag) {
1169
1170 $tag = sanitize_tag($tag);
a42c55f0 1171 $tag = db_escape_string($tag);
2c08214a
AD
1172
1173 if (!tag_is_valid($tag)) continue;
1174
a42c55f0 1175 $result = db_query("SELECT id FROM ttrss_tags
2c08214a
AD
1176 WHERE tag_name = '$tag' AND post_int_id = '$entry_int_id' AND
1177 owner_uid = '$owner_uid' LIMIT 1");
1178
1179 if ($result && db_num_rows($result) == 0) {
1180
a42c55f0 1181 db_query("INSERT INTO ttrss_tags
2c08214a
AD
1182 (owner_uid,tag_name,post_int_id)
1183 VALUES ('$owner_uid','$tag', '$entry_int_id')");
1184 }
1185
1186 array_push($tags_to_cache, $tag);
1187 }
1188
1189 /* update the cache */
1190
1191 $tags_to_cache = array_unique($tags_to_cache);
1192
a42c55f0 1193 $tags_str = db_escape_string(join(",", $tags_to_cache));
2c08214a 1194
a42c55f0 1195 db_query("UPDATE ttrss_user_entries
2c08214a
AD
1196 SET tag_cache = '$tags_str' WHERE ref_id = '$entry_ref_id'
1197 AND owner_uid = $owner_uid");
1198
dab229cd 1199 //db_query("COMMIT");
2c08214a
AD
1200 }
1201
68cccafc 1202 _debug("article processed", $debug_enabled);
2c08214a
AD
1203 }
1204
68cccafc 1205 _debug("purging feed...", $debug_enabled);
2c08214a 1206
a42c55f0 1207 purge_feed($feed, 0, $debug_enabled);
2c08214a 1208
a42c55f0 1209 db_query("UPDATE ttrss_feeds
f2798eb6 1210 SET last_updated = NOW(), last_error = '' WHERE id = '$feed'");
2c08214a 1211
a42c55f0 1212// db_query("COMMIT");
2c08214a
AD
1213
1214 } else {
1215
a42c55f0 1216 $error_msg = db_escape_string(mb_substr($rss->error(), 0, 245));
2c08214a 1217
4ad04ee2
AD
1218 _debug("fetch error: $error_msg", $debug_enabled);
1219
1220 if (count($rss->errors()) > 1) {
1221 foreach ($rss->errors() as $error) {
1222 _debug("+ $error");
1223 }
1224 }
2c08214a 1225
6322ac79 1226 db_query(
2c08214a 1227 "UPDATE ttrss_feeds SET last_error = '$error_msg',
88edaa93 1228 last_updated = NOW() WHERE id = '$feed'");
2c08214a 1229
88edaa93
AD
1230 unset($rss);
1231 }
2c08214a 1232
68cccafc 1233 _debug("done", $debug_enabled);
88edaa93
AD
1234
1235 return $rss;
2c08214a
AD
1236 }
1237
3c696512 1238 function cache_images($html, $site_url, $debug) {
3c696512
AD
1239 libxml_use_internal_errors(true);
1240
1241 $charset_hack = '<head>
1242 <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
1243 </head>';
1244
1245 $doc = new DOMDocument();
1246 $doc->loadHTML($charset_hack . $html);
1247 $xpath = new DOMXPath($doc);
1248
1249 $entries = $xpath->query('(//img[@src])');
1250
1251 foreach ($entries as $entry) {
1252 if ($entry->hasAttribute('src')) {
1253 $src = rewrite_relative_url($site_url, $entry->getAttribute('src'));
1254
1255 $local_filename = CACHE_DIR . "/images/" . sha1($src) . ".png";
1256
1257 if ($debug) _debug("cache_images: downloading: $src to $local_filename");
1258
1259 if (!file_exists($local_filename)) {
1260 $file_content = fetch_file_contents($src);
1261
a3d50184 1262 if ($file_content && strlen($file_content) > _MIN_CACHE_IMAGE_SIZE) {
3c696512
AD
1263 file_put_contents($local_filename, $file_content);
1264 }
4a27966e
J
1265 } else {
1266 touch($local_filename);
3c696512 1267 }
3c696512
AD
1268 }
1269 }
3c696512
AD
1270 }
1271
a42c55f0 1272 function expire_error_log($debug) {
e2261e17
AD
1273 if ($debug) _debug("Removing old error log entries...");
1274
1275 if (DB_TYPE == "pgsql") {
a42c55f0 1276 db_query("DELETE FROM ttrss_error_log
e2261e17
AD
1277 WHERE created_at < NOW() - INTERVAL '7 days'");
1278 } else {
a42c55f0 1279 db_query("DELETE FROM ttrss_error_log
e2261e17
AD
1280 WHERE created_at < DATE_SUB(NOW(), INTERVAL 7 DAY)");
1281 }
1282
1283 }
1284
2a91b6ff 1285 function expire_lock_files($debug) {
65465085 1286 //if ($debug) _debug("Removing old lock files...");
2a91b6ff
AD
1287
1288 $num_deleted = 0;
1289
1290 if (is_writable(LOCK_DIRECTORY)) {
1291 $files = glob(LOCK_DIRECTORY . "/*.lock");
1292
1293 if ($files) {
1294 foreach ($files as $file) {
11344971 1295 if (!file_is_locked(basename($file)) && time() - filemtime($file) > 86400*2) {
2a91b6ff
AD
1296 unlink($file);
1297 ++$num_deleted;
1298 }
1299 }
1300 }
1301 }
1302
65465085 1303 if ($debug) _debug("Removed $num_deleted old lock files.");
2a91b6ff
AD
1304 }
1305
3c696512 1306 function expire_cached_files($debug) {
3306daec 1307 foreach (array("simplepie", "images", "export", "upload") as $dir) {
3c696512 1308 $cache_dir = CACHE_DIR . "/$dir";
2c08214a 1309
65465085 1310// if ($debug) _debug("Expiring $cache_dir");
2c08214a 1311
3c696512
AD
1312 $num_deleted = 0;
1313
1314 if (is_writable($cache_dir)) {
1315 $files = glob("$cache_dir/*");
1316
2a91b6ff 1317 if ($files) {
2ab20c31
AD
1318 foreach ($files as $file) {
1319 if (time() - filemtime($file) > 86400*7) {
1320 unlink($file);
3c696512 1321
2ab20c31
AD
1322 ++$num_deleted;
1323 }
3c696512
AD
1324 }
1325 }
2a91b6ff 1326 }
3c696512 1327
65465085 1328 if ($debug) _debug("$cache_dir: removed $num_deleted files.");
3c696512
AD
1329 }
1330 }
2c08214a 1331
a3e0bdcf
AD
1332 /**
1333 * Source: http://www.php.net/manual/en/function.parse-url.php#104527
1334 * Returns the url query as associative array
1335 *
1336 * @param string query
1337 * @return array params
1338 */
1339 function convertUrlQuery($query) {
1340 $queryParts = explode('&', $query);
1341
1342 $params = array();
1343
1344 foreach ($queryParts as $param) {
1345 $item = explode('=', $param);
1346 $params[$item[0]] = $item[1];
1347 }
1348
1349 return $params;
1350 }
92c14e9d 1351
48cb2536 1352 function get_article_filters($filters, $title, $content, $link, $timestamp, $author, $tags) {
92c14e9d
AD
1353 $matches = array();
1354
1355 foreach ($filters as $filter) {
1356 $match_any_rule = $filter["match_any_rule"];
a3a896a1 1357 $inverse = $filter["inverse"];
92c14e9d
AD
1358 $filter_match = false;
1359
1360 foreach ($filter["rules"] as $rule) {
1361 $match = false;
ffa1bd7b 1362 $reg_exp = str_replace('/', '\/', $rule["reg_exp"]);
a3a896a1 1363 $rule_inverse = $rule["inverse"];
92c14e9d
AD
1364
1365 if (!$reg_exp)
1366 continue;
1367
1368 switch ($rule["type"]) {
1369 case "title":
1370 $match = @preg_match("/$reg_exp/i", $title);
1371 break;
1372 case "content":
d03ae73e
AD
1373 // we don't need to deal with multiline regexps
1374 $content = preg_replace("/[\r\n\t]/", "", $content);
1375
92c14e9d
AD
1376 $match = @preg_match("/$reg_exp/i", $content);
1377 break;
1378 case "both":
d03ae73e
AD
1379 // we don't need to deal with multiline regexps
1380 $content = preg_replace("/[\r\n\t]/", "", $content);
1381
72d1d067 1382 $match = (@preg_match("/$reg_exp/i", $title) || @preg_match("/$reg_exp/i", $content));
92c14e9d
AD
1383 break;
1384 case "link":
1385 $match = @preg_match("/$reg_exp/i", $link);
1386 break;
1387 case "author":
1388 $match = @preg_match("/$reg_exp/i", $author);
1389 break;
1390 case "tag":
7b80b5e1
DK
1391 foreach ($tags as $tag) {
1392 if (@preg_match("/$reg_exp/i", $tag)) {
1393 $match = true;
1394 break;
1395 }
1396 }
92c14e9d
AD
1397 break;
1398 }
1399
a3a896a1
AD
1400 if ($rule_inverse) $match = !$match;
1401
92c14e9d
AD
1402 if ($match_any_rule) {
1403 if ($match) {
1404 $filter_match = true;
1405 break;
1406 }
1407 } else {
1408 $filter_match = $match;
1409 if (!$match) {
1410 break;
1411 }
1412 }
1413 }
1414
a3a896a1
AD
1415 if ($inverse) $filter_match = !$filter_match;
1416
92c14e9d
AD
1417 if ($filter_match) {
1418 foreach ($filter["actions"] AS $action) {
1419 array_push($matches, $action);
5e736e45
AD
1420
1421 // if Stop action encountered, perform no further processing
fd3e5e8d 1422 if (isset($action["type"]) && $action["type"] == "stop") return $matches;
92c14e9d
AD
1423 }
1424 }
1425 }
1426
1427 return $matches;
1428 }
1429
1430 function find_article_filter($filters, $filter_name) {
1431 foreach ($filters as $f) {
1432 if ($f["type"] == $filter_name) {
1433 return $f;
1434 };
1435 }
1436 return false;
1437 }
1438
1439 function find_article_filters($filters, $filter_name) {
1440 $results = array();
1441
1442 foreach ($filters as $f) {
1443 if ($f["type"] == $filter_name) {
1444 array_push($results, $f);
1445 };
1446 }
1447 return $results;
1448 }
1449
1450 function calculate_article_score($filters) {
1451 $score = 0;
1452
1453 foreach ($filters as $f) {
1454 if ($f["type"] == "score") {
1455 $score += $f["param"];
1456 };
1457 }
1458 return $score;
1459 }
1460
b24504b1
AD
1461 function labels_contains_caption($labels, $caption) {
1462 foreach ($labels as $label) {
1463 if ($label[1] == $caption) {
1464 return true;
1465 }
1466 }
1467
1468 return false;
1469 }
1470
a42c55f0 1471 function assign_article_to_label_filters($id, $filters, $owner_uid, $article_labels) {
92c14e9d
AD
1472 foreach ($filters as $f) {
1473 if ($f["type"] == "label") {
b24504b1 1474 if (!labels_contains_caption($article_labels, $f["param"])) {
a42c55f0 1475 label_add_article($id, $f["param"], $owner_uid);
b24504b1
AD
1476 }
1477 }
92c14e9d
AD
1478 }
1479 }
87764a50 1480
87d7e850
AD
1481 function make_guid_from_title($title) {
1482 return preg_replace("/[ \"\',.:;]/", "-",
1483 mb_strtolower(strip_tags($title), 'utf-8'));
1484 }
1485
d1f3fa97 1486 /* function verify_feed_xml($feed_data) {
ebec81a6
AD
1487 libxml_use_internal_errors(true);
1488 $doc = new DOMDocument();
1489 $doc->loadXML($feed_data);
1490 $error = libxml_get_last_error();
1491 libxml_clear_errors();
1492 return $error;
d1f3fa97 1493 } */
87d7e850 1494
168cf351
AD
1495 function cleanup_counters_cache($debug) {
1496 $result = db_query("DELETE FROM ttrss_counters_cache
1497 WHERE feed_id > 0 AND
1498 (SELECT COUNT(id) FROM ttrss_feeds WHERE
1499 id = feed_id AND
1500 ttrss_counters_cache.owner_uid = ttrss_feeds.owner_uid) = 0");
1501 $frows = db_affected_rows($result);
1502
1503 $result = db_query("DELETE FROM ttrss_cat_counters_cache
1504 WHERE feed_id > 0 AND
1505 (SELECT COUNT(id) FROM ttrss_feed_categories WHERE
1506 id = feed_id AND
1507 ttrss_cat_counters_cache.owner_uid = ttrss_feed_categories.owner_uid) = 0");
1508 $crows = db_affected_rows($result);
1509
1510 _debug("Removed $frows (feeds) $crows (cats) orphaned counter cache entries.");
1511 }
1512
e2cf81e2
AD
1513 function housekeeping_common($debug) {
1514 expire_cached_files($debug);
1515 expire_lock_files($debug);
1516 expire_error_log($debug);
1517
1518 $count = update_feedbrowser_cache();
1519 _debug("Feedbrowser updated, $count feeds processed.");
1520
1521 purge_orphans( true);
168cf351 1522 cleanup_counters_cache($debug);
e2cf81e2 1523
9b736a20
AD
1524 //$rc = cleanup_tags( 14, 50000);
1525 //_debug("Cleaned $rc cached tags.");
8e470220 1526
00f22824 1527 PluginHost::getInstance()->run_hooks(PluginHost::HOOK_HOUSE_KEEPING, "hook_house_keeping", "");
8e470220 1528
e2cf81e2 1529 }
2c08214a 1530?>