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