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