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