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