]> git.wh0rd.org - tt-rss.git/blame - include/functions.php
add Public_Handler
[tt-rss.git] / include / functions.php
CommitLineData
1d3a17c7 1<?php
324944f3 2 date_default_timezone_set('UTC');
8a7f5767
CW
3 if (defined('E_DEPRECATED')) {
4 error_reporting(E_ALL & ~E_NOTICE & ~E_DEPRECATED);
5 } else {
6 error_reporting(E_ALL & ~E_NOTICE);
7 }
cce28758 8
40d13c28 9 require_once 'config.php';
cc17c205 10
fc2b26a6
AD
11 if (DB_TYPE == "pgsql") {
12 define('SUBSTRING_FOR_DATE', 'SUBSTRING_FOR_DATE');
13 } else {
14 define('SUBSTRING_FOR_DATE', 'SUBSTRING');
15 }
16
0c425dc7
AD
17 define('THEME_VERSION_REQUIRED', 1.1);
18
9632f884
AD
19 /**
20 * Return available translations names.
8d505d78 21 *
9632f884
AD
22 * @access public
23 * @return array A array of available translations.
24 */
f8c612d4 25 function get_translations() {
6a214f92 26 $tr = array(
8d505d78 27 "auto" => "Detect automatically",
a3162add 28 "ca_CA" => "Català",
6a214f92 29 "en_US" => "English",
36d0510c 30 "es_ES" => "Español",
a927fe7b 31 "de_DE" => "Deutsch",
6a214f92 32 "fr_FR" => "Français",
e78fd196 33 "hu_HU" => "Magyar (Hungarian)",
bb5d3960 34 "it_IT" => "Italiano",
1d004f12 35 "ja_JP" => "日本語 (Japanese)",
592535d7 36 "nb_NO" => "Norwegian bokmål",
6a214f92 37 "ru_RU" => "Русский",
9a063469 38 "pt_BR" => "Portuguese/Brazil",
6a214f92 39 "zh_CN" => "Simplified Chinese");
f8c612d4
AD
40
41 return $tr;
42 }
43
7b26a148
AD
44 require_once "lib/accept-to-gettext.php";
45 require_once "lib/gettext/gettext.inc";
aba609e0 46
7b26a148 47 function startup_gettext() {
8d505d78 48
7b26a148
AD
49 # Get locale from Accept-Language header
50 $lang = al2gt(array_keys(get_translations()), "text/html");
89cb787e 51
7b26a148
AD
52 if (defined('_TRANSLATION_OVERRIDE_DEFAULT')) {
53 $lang = _TRANSLATION_OVERRIDE_DEFAULT;
54 }
89cb787e 55
7b26a148
AD
56 if ($_COOKIE["ttrss_lang"] && $_COOKIE["ttrss_lang"] != "auto") {
57 $lang = $_COOKIE["ttrss_lang"];
58 }
68659d98 59
7b26a148
AD
60 /* In login action of mobile version */
61 if ($_POST["language"] && defined('MOBILE_VERSION')) {
62 $lang = $_POST["language"];
63 $_COOKIE["ttrss_lang"] = $lang;
64 }
7c33dbd4 65
7b26a148
AD
66 if ($lang) {
67 if (defined('LC_MESSAGES')) {
68 _setlocale(LC_MESSAGES, $lang);
69 } else if (defined('LC_ALL')) {
70 _setlocale(LC_ALL, $lang);
8d039718 71 }
aba609e0 72
7b26a148
AD
73 if (defined('MOBILE_VERSION')) {
74 _bindtextdomain("messages", "../locale");
75 } else {
76 _bindtextdomain("messages", "locale");
77 }
865220a4 78
7b26a148
AD
79 _textdomain("messages");
80 _bind_textdomain_codeset("messages", "UTF-8");
865220a4 81 }
7b26a148
AD
82 }
83
84 startup_gettext();
cc17c205 85
be35798b
AD
86 if (defined('MEMCACHE_SERVER')) {
87 $memcache = new Memcache;
88 $memcache->connect(MEMCACHE_SERVER, 11211);
89 }
90
b619ff15 91 require_once 'db-prefs.php';
8911ac8b 92 require_once 'version.php';
40d13c28 93
a3ee2a38
AD
94 define('MAGPIE_OUTPUT_ENCODING', 'UTF-8');
95
a18a4f38
AD
96 define('SELF_USER_AGENT', 'Tiny Tiny RSS/' . VERSION . ' (http://tt-rss.org/)');
97 define('MAGPIE_USER_AGENT', SELF_USER_AGENT);
98
500943a4
AD
99 ini_set('user_agent', SELF_USER_AGENT);
100
b0f379df 101 require_once 'lib/pubsubhubbub/publisher.php';
f4f0f80d 102
31303c6b 103 $purifier = false;
35ffb5b9 104
7d96bfcd
AD
105 $tz_offset = -1;
106 $utc_tz = new DateTimeZone('UTC');
107 $schema_version = false;
108
45004d43
AD
109 /**
110 * Print a timestamped debug message.
8d505d78 111 *
45004d43
AD
112 * @param string $msg The debug message.
113 * @return void
114 */
6f9e33e4
AD
115 function _debug($msg) {
116 $ts = strftime("%H:%M:%S", time());
2a6a9395
AD
117 if (function_exists('posix_getpid')) {
118 $ts = "$ts/" . posix_getpid();
119 }
6f9e33e4 120 print "[$ts] $msg\n";
45004d43 121 } // function _debug
6f9e33e4 122
9632f884
AD
123 /**
124 * Purge a feed old posts.
8d505d78 125 *
9632f884
AD
126 * @param mixed $link A database connection.
127 * @param mixed $feed_id The id of the purged feed.
128 * @param mixed $purge_interval Olderness of purged posts.
129 * @param boolean $debug Set to True to enable the debug. False by default.
130 * @access public
131 * @return void
132 */
ad507f85
AD
133 function purge_feed($link, $feed_id, $purge_interval, $debug = false) {
134
07d0efe9 135 if (!$purge_interval) $purge_interval = feed_purge_interval($link, $feed_id);
8d505d78 136
ad507f85 137 $rows = -1;
4c193675 138
8d505d78 139 $result = db_query($link,
07d0efe9
AD
140 "SELECT owner_uid FROM ttrss_feeds WHERE id = '$feed_id'");
141
142 $owner_uid = false;
143
144 if (db_num_rows($result) == 1) {
145 $owner_uid = db_fetch_result($result, 0, "owner_uid");
146 }
147
ab954dff
AD
148 if ($purge_interval == -1 || !$purge_interval) {
149 if ($owner_uid) {
150 ccache_update($link, $feed_id, $owner_uid);
151 }
152 return;
153 }
154
07d0efe9
AD
155 if (!$owner_uid) return;
156
3907ef71
AD
157 if (FORCE_ARTICLE_PURGE == 0) {
158 $purge_unread = get_pref($link, "PURGE_UNREAD_ARTICLES",
159 $owner_uid, false);
160 } else {
161 $purge_unread = true;
162 $purge_interval = FORCE_ARTICLE_PURGE;
163 }
07d0efe9
AD
164
165 if (!$purge_unread) $query_limit = " unread = false AND ";
166
fefa6ca3 167 if (DB_TYPE == "pgsql") {
6e7f8d26
AD
168 $pg_version = get_pgsql_version($link);
169
170 if (preg_match("/^7\./", $pg_version) || preg_match("/^8\.0/", $pg_version)) {
1e59ae35 171
8d505d78
AD
172 $result = db_query($link, "DELETE FROM ttrss_user_entries WHERE
173 ttrss_entries.id = ref_id AND
174 marked = false AND
175 feed_id = '$feed_id' AND
07d0efe9 176 $query_limit
25ea2805 177 ttrss_entries.date_updated < NOW() - INTERVAL '$purge_interval days'");
1e59ae35
AD
178
179 } else {
180
8d505d78
AD
181 $result = db_query($link, "DELETE FROM ttrss_user_entries
182 USING ttrss_entries
183 WHERE ttrss_entries.id = ref_id AND
184 marked = false AND
185 feed_id = '$feed_id' AND
07d0efe9 186 $query_limit
25ea2805 187 ttrss_entries.date_updated < NOW() - INTERVAL '$purge_interval days'");
1e59ae35 188 }
ad507f85
AD
189
190 $rows = pg_affected_rows($result);
8d505d78 191
fefa6ca3 192 } else {
8d505d78 193
30f1746f 194/* $result = db_query($link, "DELETE FROM ttrss_user_entries WHERE
fefa6ca3 195 marked = false AND feed_id = '$feed_id' AND
8d505d78 196 (SELECT date_updated FROM ttrss_entries WHERE
30f1746f
AD
197 id = ref_id) < DATE_SUB(NOW(), INTERVAL $purge_interval DAY)"); */
198
8d505d78
AD
199 $result = db_query($link, "DELETE FROM ttrss_user_entries
200 USING ttrss_user_entries, ttrss_entries
201 WHERE ttrss_entries.id = ref_id AND
202 marked = false AND
203 feed_id = '$feed_id' AND
07d0efe9 204 $query_limit
25ea2805 205 ttrss_entries.date_updated < DATE_SUB(NOW(), INTERVAL $purge_interval DAY)");
8d505d78 206
ad507f85
AD
207 $rows = mysql_affected_rows($link);
208
209 }
210
ced46404
AD
211 ccache_update($link, $feed_id, $owner_uid);
212
ad507f85 213 if ($debug) {
6f9e33e4 214 _debug("Purged feed $feed_id ($purge_interval): deleted $rows articles");
fefa6ca3 215 }
9632f884 216 } // function purge_feed
fefa6ca3 217
07d0efe9
AD
218 function feed_purge_interval($link, $feed_id) {
219
8d505d78 220 $result = db_query($link, "SELECT purge_interval, owner_uid FROM ttrss_feeds
07d0efe9
AD
221 WHERE id = '$feed_id'");
222
223 if (db_num_rows($result) == 1) {
224 $purge_interval = db_fetch_result($result, 0, "purge_interval");
225 $owner_uid = db_fetch_result($result, 0, "owner_uid");
226
8d505d78 227 if ($purge_interval == 0) $purge_interval = get_pref($link,
863be6ca 228 'PURGE_OLD_DAYS', $owner_uid);
07d0efe9
AD
229
230 return $purge_interval;
231
232 } else {
233 return -1;
234 }
235 }
236
a2d79981
AD
237 function purge_orphans($link, $do_output = false) {
238
71604ca4 239 // purge orphaned posts in main content table
8d505d78 240 $result = db_query($link, "DELETE FROM ttrss_entries WHERE
71604ca4 241 (SELECT COUNT(int_id) FROM ttrss_user_entries WHERE ref_id = id) = 0");
a2d79981
AD
242
243 if ($do_output) {
244 $rows = db_affected_rows($link, $result);
245 _debug("Purged $rows orphaned posts.");
246 }
c3a8d71a
AD
247 }
248
c7d57b66
AD
249 function get_feed_update_interval($link, $feed_id) {
250 $result = db_query($link, "SELECT owner_uid, update_interval FROM
251 ttrss_feeds WHERE id = '$feed_id'");
252
253 if (db_num_rows($result) == 1) {
254 $update_interval = db_fetch_result($result, 0, "update_interval");
255 $owner_uid = db_fetch_result($result, 0, "owner_uid");
256
257 if ($update_interval != 0) {
258 return $update_interval;
259 } else {
260 return get_pref($link, 'DEFAULT_UPDATE_INTERVAL', $owner_uid, false);
261 }
262
263 } else {
264 return -1;
265 }
266 }
267
ae5f7bb1 268 function fetch_file_contents($url, $type = false, $login = false, $pass = false, $post_query = false) {
8d505d78
AD
269 $login = urlencode($login);
270 $pass = urlencode($pass);
271
3610b48b 272 if (function_exists('curl_init') && !ini_get("open_basedir")) {
4065b60b 273 $ch = curl_init($url);
a1af1574
AD
274
275 curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 15);
276 curl_setopt($ch, CURLOPT_TIMEOUT, 45);
277 curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
278 curl_setopt($ch, CURLOPT_MAXREDIRS, 20);
279 curl_setopt($ch, CURLOPT_BINARYTRANSFER, true);
280 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
8d505d78 281 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
5f6804bc 282 curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
19929bbe 283 curl_setopt($ch, CURLOPT_USERAGENT, SELF_USER_AGENT);
268a06dc 284 curl_setopt($ch, CURLOPT_ENCODING , "gzip");
8d505d78 285
ae5f7bb1
AD
286 if ($post_query) {
287 curl_setopt($ch, CURLOPT_POST, true);
288 curl_setopt($ch, CURLOPT_POSTFIELDS, $post_query);
289 }
290
8d505d78
AD
291 if ($login && $pass)
292 curl_setopt($ch, CURLOPT_USERPWD, "$login:$pass");
a1af1574 293
fb074239 294 $contents = @curl_exec($ch);
268a06dc 295
a1af1574
AD
296 if ($contents === false) {
297 curl_close($ch);
298 return false;
4065b60b
AD
299 }
300
8d505d78 301 $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
a1af1574
AD
302 $content_type = curl_getinfo($ch, CURLINFO_CONTENT_TYPE);
303 curl_close($ch);
4065b60b 304
8d505d78 305 if ($http_code != 200 || $type && strpos($content_type, "$type") === false) {
a1af1574
AD
306 return false;
307 }
4065b60b 308
a1af1574 309 return $contents;
4065b60b 310 } else {
9949bd15 311 if ($login && $pass ){
8d505d78
AD
312 $url_parts = array();
313
314 preg_match("/(^[^:]*):\/\/(.*)/", $url, $url_parts);
315
316 if ($url_parts[1] && $url_parts[2]) {
317 $url = $url_parts[1] . "://$login:$pass@" . $url_parts[2];
318 }
319 }
320
fb074239 321 return @file_get_contents($url);
4065b60b
AD
322 }
323
324 }
78800912 325
9632f884
AD
326 /**
327 * Try to determine the favicon URL for a feed.
328 * adapted from wordpress favicon plugin by Jeff Minard (http://thecodepro.com/)
329 * http://dev.wp-plugins.org/file/favatars/trunk/favatars.php
8d505d78 330 *
9632f884
AD
331 * @param string $url A feed or page URL
332 * @access public
333 * @return mixed The favicon URL, or false if none was found.
334 */
4065b60b 335 function get_favicon_url($url) {
99331724 336
ed214298
AD
337 $favicon_url = false;
338
4065b60b 339 if ($html = @fetch_file_contents($url)) {
78800912 340
ed214298 341 libxml_use_internal_errors(true);
c798704b 342
ed214298
AD
343 $doc = new DOMDocument();
344 $doc->loadHTML($html);
345 $xpath = new DOMXPath($doc);
717f5e64 346
a712429e
AD
347 $base = $xpath->query('/html/head/base');
348 foreach ($base as $b) {
349 $url = $b->getAttribute("href");
350 break;
351 }
352
353 $entries = $xpath->query('/html/head/link[@rel="shortcut icon" or @rel="icon"]');
ed214298
AD
354 if (count($entries) > 0) {
355 foreach ($entries as $entry) {
356 $favicon_url = rewrite_relative_url($url, $entry->getAttribute("href"));
357 break;
358 }
8d505d78 359 }
4065b60b 360 }
c798704b 361
ed214298
AD
362 if (!$favicon_url)
363 $favicon_url = rewrite_relative_url($url, "/favicon.ico");
364
014d3ad8 365 return $favicon_url;
9632f884 366 } // function get_favicon_url
4065b60b 367
4065b60b 368 function check_feed_favicon($site_url, $feed, $link) {
4065b60b
AD
369# print "FAVICON [$site_url]: $favicon_url\n";
370
4065b60b
AD
371 $icon_file = ICONS_DIR . "/$feed.ico";
372
c83a5aec
AD
373 if (!file_exists($icon_file)) {
374 $favicon_url = get_favicon_url($site_url);
375
376 if ($favicon_url) {
377 $contents = fetch_file_contents($favicon_url, "image");
378
379 if ($contents) {
e894e97f 380 $fp = @fopen($icon_file, "w");
78800912 381
c83a5aec
AD
382 if ($fp) {
383 fwrite($fp, $contents);
384 fclose($fp);
385 chmod($icon_file, 0644);
386 }
a1af1574 387 }
4065b60b 388 }
78800912
AD
389 }
390 }
391
5ab9791f 392 function update_rss_feed($link, $feed, $ignore_daemon = false, $no_cache = false) {
c633e370
AD
393
394 global $memcache;
395
396 /* Update all feeds with the same URL to utilize memcache */
397
398 if ($memcache) {
8d505d78
AD
399 $result = db_query($link, "SELECT f1.id
400 FROM ttrss_feeds AS f1, ttrss_feeds AS f2
c633e370
AD
401 WHERE f2.feed_url = f1.feed_url AND f2.id = '$feed'");
402
403 while ($line = db_fetch_assoc($result)) {
5ab9791f 404 update_rss_feed_real($link, $line["id"], $ignore_daemon, $no_cache);
c633e370
AD
405 }
406 } else {
5ab9791f 407 update_rss_feed_real($link, $feed, $ignore_daemon, $no_cache);
c633e370
AD
408 }
409 }
410
55ad314e
AD
411 function update_rss_feed_real($link, $feed, $ignore_daemon = false, $no_cache = false,
412 $override_url = false) {
40d13c28 413
31303c6b
AD
414 require_once "lib/simplepie/simplepie.inc";
415 require_once "lib/magpierss/rss_fetch.inc";
416 require_once 'lib/magpierss/rss_utils.inc';
417
602690e5
AD
418 global $memcache;
419
412d258d
AD
420 $debug_enabled = defined('DAEMON_EXTENDED_DEBUG') || $_REQUEST['xdebug'];
421
b4e75b2a 422 if (!$_REQUEST["daemon"] && !$ignore_daemon) {
45004d43 423 return false;
21cfcdf2
AD
424 }
425
412d258d 426 if ($debug_enabled) {
34e420fb 427 _debug("update_rss_feed: start");
219bd8fc
AD
428 }
429
39a52499
AD
430 if (!$ignore_daemon) {
431
432 if (DB_TYPE == "pgsql") {
433 $updstart_thresh_qpart = "(ttrss_feeds.last_update_started IS NULL OR ttrss_feeds.last_update_started < NOW() - INTERVAL '120 seconds')";
434 } else {
435 $updstart_thresh_qpart = "(ttrss_feeds.last_update_started IS NULL OR ttrss_feeds.last_update_started < DATE_SUB(NOW(), INTERVAL 120 SECOND))";
8d505d78
AD
436 }
437
39a52499 438 $result = db_query($link, "SELECT id,update_interval,auth_login,
16211ddb 439 auth_pass,cache_images,update_method
39a52499 440 FROM ttrss_feeds WHERE id = '$feed' AND $updstart_thresh_qpart");
02008cb1 441
39a52499
AD
442 } else {
443
444 $result = db_query($link, "SELECT id,update_interval,auth_login,
57e24c82 445 feed_url,auth_pass,cache_images,update_method,last_updated,
5ab9791f
AD
446 mark_unread_on_update, owner_uid, update_on_checksum_change,
447 pubsub_state
39a52499
AD
448 FROM ttrss_feeds WHERE id = '$feed'");
449
450 }
a88c1f36 451
5370d37f 452 if (db_num_rows($result) == 0) {
412d258d 453 if ($debug_enabled) {
c633e370 454 _debug("update_rss_feed: feed $feed NOT FOUND/SKIPPED");
8d505d78 455 }
45004d43 456 return false;
5370d37f
AD
457 }
458
16211ddb 459 $update_method = db_fetch_result($result, 0, "update_method");
50b2db96 460 $last_updated = db_fetch_result($result, 0, "last_updated");
57e24c82 461 $owner_uid = db_fetch_result($result, 0, "owner_uid");
30a2fe5a
AD
462 $mark_unread_on_update = sql_bool_to_bool(db_fetch_result($result,
463 0, "mark_unread_on_update"));
464 $update_on_checksum_change = sql_bool_to_bool(db_fetch_result($result,
465 0, "update_on_checksum_change"));
5ab9791f 466 $pubsub_state = db_fetch_result($result, 0, "pubsub_state");
16211ddb 467
3c50da83
AD
468 db_query($link, "UPDATE ttrss_feeds SET last_update_started = NOW()
469 WHERE id = '$feed'");
470
464bd61e
AD
471 $auth_login = db_fetch_result($result, 0, "auth_login");
472 $auth_pass = db_fetch_result($result, 0, "auth_pass");
473
b3009bcd
AD
474 if ($update_method == 0)
475 $update_method = DEFAULT_UPDATE_METHOD + 1;
476
477 // 1 - Magpie
478 // 2 - SimplePie
479 // 3 - Twitter OAuth
480
481 if ($update_method == 2)
482 $use_simplepie = true;
483 else
484 $use_simplepie = false;
16211ddb 485
412d258d 486 if ($debug_enabled) {
b3009bcd 487 _debug("update method: $update_method (feed setting: $update_method) (use simplepie: $use_simplepie)\n");
16211ddb
AD
488 }
489
b3009bcd 490 if ($update_method == 1) {
464bd61e
AD
491 $auth_login = urlencode($auth_login);
492 $auth_pass = urlencode($auth_pass);
493 }
47c6c988 494
a88c1f36 495 $update_interval = db_fetch_result($result, 0, "update_interval");
bc0f0785 496 $cache_images = sql_bool_to_bool(db_fetch_result($result, 0, "cache_images"));
c633e370 497 $fetch_url = db_fetch_result($result, 0, "feed_url");
a88c1f36 498
9949bd15 499 if ($update_interval < 0) { return false; }
a88c1f36 500
ab3d0b99
AD
501 $feed = db_escape_string($feed);
502
9949bd15 503 if ($auth_login && $auth_pass ){
47c6c988
AD
504 $url_parts = array();
505 preg_match("/(^[^:]*):\/\/(.*)/", $fetch_url, $url_parts);
506
507 if ($url_parts[1] && $url_parts[2]) {
508 $fetch_url = $url_parts[1] . "://$auth_login:$auth_pass@" . $url_parts[2];
509 }
510
511 }
ab3d0b99 512
55ad314e
AD
513 if ($override_url)
514 $fetch_url = $override_url;
515
412d258d 516 if ($debug_enabled) {
ca872b9d 517 _debug("update_rss_feed: fetching [$fetch_url]...");
219bd8fc
AD
518 }
519
e656b9f7 520 $obj_id = md5("FDATA:$use_simplepie:$fetch_url");
6e4f0519 521
c633e370 522 if ($memcache && $obj = $memcache->get($obj_id)) {
6e4f0519 523
412d258d 524 if ($debug_enabled) {
c633e370 525 _debug("update_rss_feed: data found in memcache.");
6e4f0519
AD
526 }
527
c633e370
AD
528 $rss = $obj;
529
530 } else {
531
b3009bcd 532 if ($update_method == 3) {
57e24c82 533 $rss = fetch_twitter_rss($link, $fetch_url, $owner_uid);
5ab9791f
AD
534 } else if ($update_method == 1) {
535
536 define('MAGPIE_CACHE_AGE', get_feed_update_interval($link, $feed) * 60);
537 define('MAGPIE_CACHE_ON', !$no_cache);
61e420e9
AD
538 define('MAGPIE_FETCH_TIME_OUT', 60);
539 define('MAGPIE_CACHE_DIR', CACHE_DIR . "/magpie");
5ab9791f 540
fb074239 541 $rss = @fetch_rss($fetch_url);
c633e370 542 } else {
61e420e9
AD
543 $simplepie_cache_dir = CACHE_DIR . "/simplepie";
544
545 if (!is_dir($simplepie_cache_dir)) {
546 mkdir($simplepie_cache_dir);
c633e370 547 }
8d505d78 548
c633e370 549 $rss = new SimplePie();
a18a4f38 550 $rss->set_useragent(SELF_USER_AGENT);
c633e370
AD
551 # $rss->set_timeout(10);
552 $rss->set_feed_url($fetch_url);
553 $rss->set_output_encoding('UTF-8');
a19d7722 554 $rss->force_feed(true);
8d505d78 555
c633e370 556 if (SIMPLEPIE_CACHE_IMAGES && $cache_images) {
9fcbc76f 557
412d258d 558 if ($debug_enabled) {
b8998470 559 _debug("enabling image cache");
c633e370 560 }
9fcbc76f 561
b8998470 562 $rss->set_image_handler("image.php", 'i');
c633e370 563 }
8d505d78 564
412d258d 565 if ($debug_enabled) {
c633e370
AD
566 _debug("feed update interval (sec): " .
567 get_feed_update_interval($link, $feed)*60);
568 }
8d505d78 569
5ab9791f
AD
570 $rss->enable_cache(!$no_cache);
571
572 if (!$no_cache) {
61e420e9 573 $rss->set_cache_location($simplepie_cache_dir);
c633e370
AD
574 $rss->set_cache_duration(get_feed_update_interval($link, $feed) * 60);
575 }
8d505d78 576
c633e370 577 $rss->init();
6e4f0519
AD
578 }
579
c633e370 580 if ($memcache && $rss) $memcache->add($obj_id, $rss, 0, 300);
9fdf7824
AD
581 }
582
583// print_r($rss);
219bd8fc 584
412d258d 585 if ($debug_enabled) {
34e420fb 586 _debug("update_rss_feed: fetch done, parsing...");
219bd8fc
AD
587 }
588
b6eefba5 589 $feed = db_escape_string($feed);
dcee8f61 590
b3009bcd 591 if ($update_method == 2) {
ca872b9d
AD
592 $fetch_ok = !$rss->error();
593 } else {
594 $fetch_ok = !!$rss;
595 }
596
597 if ($fetch_ok) {
50b62214 598
412d258d 599 if ($debug_enabled) {
50b62214
AD
600 _debug("update_rss_feed: processing feed data...");
601 }
602
44e241cb 603// db_query($link, "BEGIN");
dd8c76a9 604
a88c1f36 605 $result = db_query($link, "SELECT title,icon_url,site_url,owner_uid
f324892e 606 FROM ttrss_feeds WHERE id = '$feed'");
331900c6 607
b6eefba5
AD
608 $registered_title = db_fetch_result($result, 0, "title");
609 $orig_icon_url = db_fetch_result($result, 0, "icon_url");
f324892e 610 $orig_site_url = db_fetch_result($result, 0, "site_url");
331900c6 611
7fed1940
AD
612 $owner_uid = db_fetch_result($result, 0, "owner_uid");
613
16211ddb 614 if ($use_simplepie) {
9fdf7824
AD
615 $site_url = $rss->get_link();
616 } else {
617 $site_url = $rss->channel["link"];
618 }
619
68a57364
AD
620 $site_url = rewrite_relative_url($fetch_url, $site_url);
621
412d258d 622 if ($debug_enabled) {
85a92289 623 _debug("update_rss_feed: checking favicon...");
a2770077
AD
624 }
625
85a92289
AD
626 check_feed_favicon($site_url, $feed, $link);
627
746b249f 628 if (!$registered_title || $registered_title == "[Unknown]") {
4bc64807 629
16211ddb 630 if ($use_simplepie) {
c2f8aac4 631 $feed_title = db_escape_string($rss->get_title());
fb486a33
AD
632 } else {
633 $feed_title = db_escape_string($rss->channel["title"]);
634 }
4bc64807 635
412d258d 636 if ($debug_enabled) {
4bc64807
AD
637 _debug("update_rss_feed: registering title: $feed_title");
638 }
8d505d78
AD
639
640 db_query($link, "UPDATE ttrss_feeds SET
f324892e
AD
641 title = '$feed_title' WHERE id = '$feed'");
642 }
643
49f9c923 644 // weird, weird Magpie
16211ddb 645 if (!$use_simplepie) {
9fdf7824
AD
646 if (!$site_url) $site_url = db_escape_string($rss->channel["link_"]);
647 }
147f7691
AD
648
649 if ($site_url && $orig_site_url != db_escape_string($site_url)) {
8d505d78 650 db_query($link, "UPDATE ttrss_feeds SET
f324892e 651 site_url = '$site_url' WHERE id = '$feed'");
331900c6 652 }
40d13c28 653
b7f4bda2
AD
654// print "I: " . $rss->channel["image"]["url"];
655
16211ddb 656 if (!$use_simplepie) {
98833033 657 $icon_url = db_escape_string($rss->image["url"]);
9fdf7824 658 } else {
98833033 659 $icon_url = db_escape_string($rss->get_image_url());
9fdf7824 660 }
b7f4bda2 661
0526ffdd
AD
662 $icon_url = substr($icon_url, 0, 250);
663
8d505d78 664 if ($icon_url && $orig_icon_url != $icon_url) {
014d3ad8 665 db_query($link, "UPDATE ttrss_feeds SET icon_url = '$icon_url' WHERE id = '$feed'");
b7f4bda2
AD
666 }
667
412d258d 668 if ($debug_enabled) {
50b62214
AD
669 _debug("update_rss_feed: loading filters...");
670 }
e6155a06 671
5daa24f2 672 $filters = load_filters($link, $feed, $owner_uid);
e6155a06 673
412d258d
AD
674// if ($debug_enabled) {
675// print_r($filters);
676// }
0569a712 677
16211ddb 678 if ($use_simplepie) {
9fdf7824
AD
679 $iterator = $rss->get_items();
680 } else {
681 $iterator = $rss->items;
682 if (!$iterator || !is_array($iterator)) $iterator = $rss->entries;
683 if (!$iterator || !is_array($iterator)) $iterator = $rss;
684 }
c22789da
AD
685
686 if (!is_array($iterator)) {
8d505d78 687 /* db_query($link, "UPDATE ttrss_feeds
75bd0669 688 SET last_error = 'Parse error: can\'t find any articles.'
77f0a2a7
AD
689 WHERE id = '$feed'"); */
690
691 // clear any errors and mark feed as updated if fetched okay
692 // even if it's blank
693
412d258d 694 if ($debug_enabled) {
844012bc
AD
695 _debug("update_rss_feed: entry iterator is not an array, no articles?");
696 }
697
8d505d78 698 db_query($link, "UPDATE ttrss_feeds
77f0a2a7
AD
699 SET last_updated = NOW(), last_error = '' WHERE id = '$feed'");
700
701 return; // no articles
c22789da 702 }
ddb68b81 703
65eebd13 704 if ($pubsub_state != 2 && PUBSUBHUBBUB_ENABLED) {
5ab9791f 705
dd50b552 706 if ($debug_enabled) _debug("update_rss_feed: checking for PUSH hub...");
c57983b1 707
5ab9791f
AD
708 $feed_hub_url = false;
709 if ($use_simplepie) {
710 $links = $rss->get_links('hub');
711
a9ac55ea
AD
712 if ($links && is_array($links)) {
713 foreach ($links as $l) {
714 $feed_hub_url = $l;
715 break;
716 }
5ab9791f
AD
717 }
718
719 } else {
720 $atom = $rss->channel['atom'];
721
722 if ($atom) {
723 if ($atom['link@rel'] == 'hub') {
724 $feed_hub_url = $atom['link@href'];
725 }
726
727 if (!$feed_hub_url && $atom['link#'] > 1) {
728 for ($i = 2; $i <= $atom['link#']; $i++) {
729 if ($atom["link#$i@rel"] == 'hub') {
730 $feed_hub_url = $atom["link#$i@href"];
a9ac55ea 731 break;
5ab9791f
AD
732 }
733 }
734 }
735 } else {
736 $feed_hub_url = $rss->channel['link_hub'];
737 }
738 }
739
dd50b552 740 if ($debug_enabled) _debug("update_rss_feed: feed hub url: $feed_hub_url");
c57983b1 741
3610b48b
AD
742 if ($feed_hub_url && function_exists('curl_init') &&
743 !ini_get("open_basedir")) {
c57983b1 744
31303c6b
AD
745 require_once 'lib/pubsubhubbub/subscriber.php';
746
5ab9791f 747 $callback_url = get_self_url_prefix() .
e0d91d84 748 "/public.php?op=pubsub&id=$feed";
5ab9791f
AD
749
750 $s = new Subscriber($feed_hub_url, $callback_url);
751
c57983b1
AD
752 $rc = $s->subscribe($fetch_url);
753
dd50b552
AD
754 if ($debug_enabled)
755 _debug("update_rss_feed: feed hub url found, subscribe request sent.");
5ab9791f
AD
756
757 db_query($link, "UPDATE ttrss_feeds SET pubsub_state = 1
758 WHERE id = '$feed'");
759 }
760 }
761
412d258d 762 if ($debug_enabled) {
50b62214
AD
763 _debug("update_rss_feed: processing articles...");
764 }
765
ddb68b81 766 foreach ($iterator as $item) {
7c5a308d 767
b4e75b2a 768 if ($_REQUEST['xdebug'] == 2) {
40ce98f4
AD
769 print_r($item);
770 }
71bd29f6 771
16211ddb 772 if ($use_simplepie) {
9fdf7824
AD
773 $entry_guid = $item->get_id();
774 if (!$entry_guid) $entry_guid = $item->get_link();
775 if (!$entry_guid) $entry_guid = make_guid_from_title($item->get_title());
776
777 } else {
778
779 $entry_guid = $item["id"];
34e420fb 780
9fdf7824 781 if (!$entry_guid) $entry_guid = $item["guid"];
530f5cda 782 if (!$entry_guid) $entry_guid = $item["about"];
9fdf7824
AD
783 if (!$entry_guid) $entry_guid = $item["link"];
784 if (!$entry_guid) $entry_guid = make_guid_from_title($item["title"]);
785 }
be832a1a 786
412d258d 787 if ($debug_enabled) {
34e420fb
AD
788 _debug("update_rss_feed: guid $entry_guid");
789 }
790
be832a1a
AD
791 if (!$entry_guid) continue;
792
793 $entry_timestamp = "";
794
16211ddb 795 if ($use_simplepie) {
9fdf7824
AD
796 $entry_timestamp = strtotime($item->get_date());
797 } else {
798 $rss_2_date = $item['pubdate'];
799 $rss_1_date = $item['dc']['date'];
800 $atom_date = $item['issued'];
801 if (!$atom_date) $atom_date = $item['updated'];
e9558345 802
9fdf7824
AD
803 if ($atom_date != "") $entry_timestamp = parse_w3cdtf($atom_date);
804 if ($rss_1_date != "") $entry_timestamp = parse_w3cdtf($rss_1_date);
805 if ($rss_2_date != "") $entry_timestamp = strtotime($rss_2_date);
e9558345 806
9fdf7824 807 }
9bb36aa0 808
2e930846 809 if ($entry_timestamp == "" || $entry_timestamp == -1 || !$entry_timestamp) {
be832a1a
AD
810 $entry_timestamp = time();
811 $no_orig_date = 'true';
812 } else {
813 $no_orig_date = 'false';
814 }
815
816 $entry_timestamp_fmt = strftime("%Y/%m/%d %H:%M:%S", $entry_timestamp);
817
412d258d 818 if ($debug_enabled) {
44d0e774
AD
819 _debug("update_rss_feed: date $entry_timestamp [$entry_timestamp_fmt]");
820 }
821
16211ddb 822 if ($use_simplepie) {
9fdf7824
AD
823 $entry_title = $item->get_title();
824 } else {
825 $entry_title = trim(strip_tags($item["title"]));
826 }
be832a1a 827
16211ddb 828 if ($use_simplepie) {
9fdf7824
AD
829 $entry_link = $item->get_link();
830 } else {
831 // strange Magpie workaround
832 $entry_link = $item["link_"];
833 if (!$entry_link) $entry_link = $item["link"];
834 }
be832a1a 835
68a57364
AD
836 $entry_link = rewrite_relative_url($site_url, $entry_link);
837
412d258d 838 if ($debug_enabled) {
9bb36aa0 839 _debug("update_rss_feed: title $entry_title");
68a57364 840 _debug("update_rss_feed: link $entry_link");
9bb36aa0
AD
841 }
842
843 if (!$entry_title) $entry_title = date("Y-m-d H:i:s", $entry_timestamp);;
7d3ab0dd 844
be832a1a 845 $entry_link = strip_tags($entry_link);
7d3ab0dd 846
16211ddb 847 if ($use_simplepie) {
4af7a36a
AD
848 $entry_content = $item->get_content();
849 if (!$entry_content) $entry_content = $item->get_description();
9fdf7824
AD
850 } else {
851 $entry_content = $item["content:escaped"];
852
853 if (!$entry_content) $entry_content = $item["content:encoded"];
e91ab107 854 if (!$entry_content) $entry_content = $item["content"]["encoded"];
9fdf7824 855 if (!$entry_content) $entry_content = $item["content"];
ea322415 856
31303c6b
AD
857 if (is_array($entry_content)) $entry_content = $entry_content[0];
858
ea322415
AD
859 // Magpie bugs are getting ridiculous
860 if (trim($entry_content) == "Array") $entry_content = false;
861
9fdf7824
AD
862 if (!$entry_content) $entry_content = $item["atom_content"];
863 if (!$entry_content) $entry_content = $item["summary"];
e91ab107 864
8d505d78 865 if (!$entry_content ||
e91ab107
AD
866 strlen($entry_content) < strlen($item["description"])) {
867 $entry_content = $item["description"];
868 };
9fdf7824
AD
869
870 // WTF
871 if (is_array($entry_content)) {
872 $entry_content = $entry_content["encoded"];
873 if (!$entry_content) $entry_content = $entry_content["escaped"];
8d505d78 874 }
be832a1a
AD
875 }
876
b4e75b2a 877 if ($_REQUEST["xdebug"] == 2) {
ea322415
AD
878 print "update_rss_feed: content: ";
879 print_r(htmlspecialchars($entry_content));
880 }
be832a1a
AD
881
882 $entry_content_unescaped = $entry_content;
be832a1a 883
16211ddb 884 if ($use_simplepie) {
9fdf7824 885 $entry_comments = strip_tags($item->data["comments"]);
30cf38dd 886 if ($item->get_author()) {
e1d600f0 887 $entry_author_item = $item->get_author();
a0c6eafb
AD
888 $entry_author = $entry_author_item->get_name();
889 if (!$entry_author) $entry_author = $entry_author_item->get_email();
d1ee9106
AD
890
891 $entry_author = db_escape_string($entry_author);
30cf38dd 892 }
9fdf7824
AD
893 } else {
894 $entry_comments = strip_tags($item["comments"]);
8d505d78 895
9fdf7824 896 $entry_author = db_escape_string(strip_tags($item['dc']['creator']));
4d6e9157 897
9fdf7824 898 if ($item['author']) {
8d505d78 899
9fdf7824 900 if (is_array($item['author'])) {
8d505d78 901
9fdf7824
AD
902 if (!$entry_author) {
903 $entry_author = db_escape_string(strip_tags($item['author']['name']));
904 }
8d505d78 905
9fdf7824
AD
906 if (!$entry_author) {
907 $entry_author = db_escape_string(strip_tags($item['author']['email']));
908 }
4d6e9157 909 }
8d505d78 910
4d6e9157 911 if (!$entry_author) {
9fdf7824 912 $entry_author = db_escape_string(strip_tags($item['author']));
4d6e9157 913 }
83f114c8 914 }
be832a1a
AD
915 }
916
83f114c8
AD
917 if (preg_match('/^[\t\n\r ]*$/', $entry_author)) $entry_author = '';
918
be832a1a 919 $entry_guid = db_escape_string(strip_tags($entry_guid));
2ad9ee56 920 $entry_guid = mb_substr($entry_guid, 0, 250);
be832a1a 921
8d505d78 922 $result = db_query($link, "SELECT id FROM ttrss_entries
be832a1a
AD
923 WHERE guid = '$entry_guid'");
924
d564f283 925 $entry_content = db_escape_string($entry_content, false);
7e43ad58
AD
926
927 $content_hash = "SHA1:" . sha1(strip_tags($entry_content));
928
be832a1a
AD
929 $entry_title = db_escape_string($entry_title);
930 $entry_link = db_escape_string($entry_link);
2544f36b
AD
931 $entry_comments = mb_substr(db_escape_string($entry_comments), 0, 250);
932 $entry_author = mb_substr($entry_author, 0, 250);
be832a1a 933
16211ddb 934 if ($use_simplepie) {
9fdf7824
AD
935 $num_comments = 0; #FIXME#
936 } else {
937 $num_comments = db_escape_string($item["slash"]["comments"]);
938 }
be832a1a
AD
939
940 if (!$num_comments) $num_comments = 0;
941
412d258d 942 if ($debug_enabled) {
c3fc5e47
AD
943 _debug("update_rss_feed: looking for tags [1]...");
944 }
945
fefef828 946 // parse <category> entries into tags
be832a1a 947
e75df19d
AD
948 $additional_tags = array();
949
16211ddb 950 if ($use_simplepie) {
be832a1a 951
9fdf7824 952 $additional_tags_src = $item->get_categories();
8d505d78 953
a702e931
AD
954 if (is_array($additional_tags_src)) {
955 foreach ($additional_tags_src as $tobj) {
956 array_push($additional_tags, $tobj->get_term());
957 }
fefef828 958 }
fefef828 959
412d258d 960 if ($debug_enabled) {
6af621c7
AD
961 _debug("update_rss_feed: category tags:");
962 print_r($additional_tags);
963 }
964
9fdf7824 965 } else {
fefef828 966
9fdf7824 967 $t_ctr = $item['category#'];
fefef828 968
9fdf7824 969 if ($t_ctr == 0) {
e75df19d 970 $additional_tags = array();
71bd29f6 971 } else if ($t_ctr > 0) {
9fdf7824 972 $additional_tags = array($item['category']);
71bd29f6
AD
973
974 if ($item['category@term']) {
975 array_push($additional_tags, $item['category@term']);
976 }
977
9fdf7824
AD
978 for ($i = 0; $i <= $t_ctr; $i++ ) {
979 if ($item["category#$i"]) {
980 array_push($additional_tags, $item["category#$i"]);
981 }
71bd29f6
AD
982
983 if ($item["category#$i@term"]) {
984 array_push($additional_tags, $item["category#$i@term"]);
985 }
9fdf7824
AD
986 }
987 }
8d505d78 988
9fdf7824 989 // parse <dc:subject> elements
8d505d78 990
9fdf7824 991 $t_ctr = $item['dc']['subject#'];
8d505d78 992
71bd29f6 993 if ($t_ctr > 0) {
e75df19d 994 array_push($additional_tags, $item['dc']['subject']);
71bd29f6 995
9fdf7824
AD
996 for ($i = 0; $i <= $t_ctr; $i++ ) {
997 if ($item['dc']["subject#$i"]) {
998 array_push($additional_tags, $item['dc']["subject#$i"]);
999 }
fefef828
AD
1000 }
1001 }
1002 }
8add756a 1003
412d258d 1004 if ($debug_enabled) {
c3fc5e47
AD
1005 _debug("update_rss_feed: looking for tags [2]...");
1006 }
e91ab107 1007
c3fc5e47
AD
1008 /* taaaags */
1009 // <a href="..." rel="tag">Xorg</a>, //
e91ab107 1010
c3fc5e47 1011 $entry_tags = null;
e91ab107 1012
c3fc5e47
AD
1013 preg_match_all("/<a.*?rel=['\"]tag['\"].*?\>([^<]+)<\/a>/i",
1014 $entry_content_unescaped, $entry_tags);
e91ab107 1015
c3fc5e47 1016 $entry_tags = $entry_tags[1];
b652fdae 1017
c3fc5e47 1018 $entry_tags = array_merge($entry_tags, $additional_tags);
1e87951d
AD
1019 $entry_tags = array_unique($entry_tags);
1020
1021 for ($i = 0; $i < count($entry_tags); $i++)
1022 $entry_tags[$i] = mb_strtolower($entry_tags[$i], 'utf-8');
b652fdae 1023
412d258d 1024 if ($debug_enabled) {
c3fc5e47
AD
1025 _debug("update_rss_feed: unfiltered tags found:");
1026 print_r($entry_tags);
ce53e200
AD
1027 }
1028
d48d160c 1029 # sanitize content
8d505d78 1030
621ffb00
AD
1031 $entry_content = sanitize_article_content($entry_content);
1032 $entry_title = sanitize_article_content($entry_title);
d48d160c 1033
412d258d 1034 if ($debug_enabled) {
34e420fb
AD
1035 _debug("update_rss_feed: done collecting data [TITLE:$entry_title]");
1036 }
1037
44e241cb
AD
1038 db_query($link, "BEGIN");
1039
4c193675
AD
1040 if (db_num_rows($result) == 0) {
1041
412d258d 1042 if ($debug_enabled) {
34e420fb
AD
1043 _debug("update_rss_feed: base guid not found");
1044 }
1045
4c193675
AD
1046 // base post entry does not exist, create it
1047
4c193675 1048 $result = db_query($link,
8d505d78 1049 "INSERT INTO ttrss_entries
4c193675
AD
1050 (title,
1051 guid,
1052 link,
1053 updated,
1054 content,
1055 content_hash,
1056 no_orig_date,
25ea2805 1057 date_updated,
4c193675 1058 date_entered,
11b0dce2 1059 comments,
b6104dee
AD
1060 num_comments,
1061 author)
4c193675 1062 VALUES
8d505d78
AD
1063 ('$entry_title',
1064 '$entry_guid',
4c193675 1065 '$entry_link',
8d505d78
AD
1066 '$entry_timestamp_fmt',
1067 '$entry_content',
4c193675 1068 '$content_hash',
8d505d78 1069 $no_orig_date,
25ea2805
AD
1070 NOW(),
1071 NOW(),
11b0dce2 1072 '$entry_comments',
b6104dee
AD
1073 '$num_comments',
1074 '$entry_author')");
8926aab8
AD
1075 } else {
1076 // we keep encountering the entry in feeds, so we need to
25ea2805 1077 // update date_updated column so that we don't get horrible
8926aab8
AD
1078 // dupes when the entry gets purged and reinserted again e.g.
1079 // in the case of SLOW SLOW OMG SLOW updating feeds
1080
1081 $base_entry_id = db_fetch_result($result, 0, "id");
1082
25ea2805 1083 db_query($link, "UPDATE ttrss_entries SET date_updated = NOW()
8926aab8 1084 WHERE id = '$base_entry_id'");
4c193675
AD
1085 }
1086
1087 // now it should exist, if not - bad luck then
1088
8d505d78 1089 $result = db_query($link, "SELECT
6385315d 1090 id,content_hash,no_orig_date,title,
25ea2805 1091 ".SUBSTRING_FOR_DATE."(date_updated,1,19) as date_updated,
2ac6b765 1092 ".SUBSTRING_FOR_DATE."(updated,1,19) as updated,
11b0dce2 1093 num_comments
8d505d78
AD
1094 FROM
1095 ttrss_entries
6385315d 1096 WHERE guid = '$entry_guid'");
4c193675 1097
ce53e200
AD
1098 $entry_ref_id = 0;
1099 $entry_int_id = 0;
1100
4c193675
AD
1101 if (db_num_rows($result) == 1) {
1102
412d258d 1103 if ($debug_enabled) {
7ca91eb3 1104 _debug("update_rss_feed: base guid found, checking for user record");
34e420fb
AD
1105 }
1106
11b0dce2
AD
1107 // this will be used below in update handler
1108 $orig_content_hash = db_fetch_result($result, 0, "content_hash");
1109 $orig_title = db_fetch_result($result, 0, "title");
1110 $orig_num_comments = db_fetch_result($result, 0, "num_comments");
8d505d78 1111 $orig_date_updated = strtotime(db_fetch_result($result,
25ea2805 1112 0, "date_updated"));
6385315d 1113
11b0dce2 1114 $ref_id = db_fetch_result($result, 0, "id");
ce53e200 1115 $entry_ref_id = $ref_id;
4c193675 1116
11b0dce2 1117 // check for user post link to main table
4c193675 1118
11b0dce2 1119 // do we allow duplicate posts with same GUID in different feeds?
8d0ec6fd 1120 if (get_pref($link, "ALLOW_DUPLICATE_POSTS", $owner_uid, false)) {
e04c18a2 1121 $dupcheck_qpart = "AND (feed_id = '$feed' OR feed_id IS NULL)";
8d505d78 1122 } else {
11b0dce2
AD
1123 $dupcheck_qpart = "";
1124 }
71604ca4 1125
c3fc5e47
AD
1126 /* Collect article tags here so we could filter by them: */
1127
8d505d78
AD
1128 $article_filters = get_article_filters($filters, $entry_title,
1129 $entry_content, $entry_link, $entry_timestamp, $entry_author,
1e87951d 1130 $entry_tags);
19c9cb11 1131
412d258d 1132 if ($debug_enabled) {
7ca91eb3
AD
1133 _debug("update_rss_feed: article filters: ");
1134 if (count($article_filters) != 0) {
1135 print_r($article_filters);
1136 }
1137 }
1138
f8382011 1139 if (find_article_filter($article_filters, "filter")) {
ee4a9812 1140 db_query($link, "COMMIT"); // close transaction in progress
11b0dce2
AD
1141 continue;
1142 }
19c9cb11 1143
ff6e357a
AD
1144 $score = calculate_article_score($article_filters);
1145
412d258d 1146 if ($debug_enabled) {
ff6e357a
AD
1147 _debug("update_rss_feed: initial score: $score");
1148 }
1149
ef83538d 1150 $query = "SELECT ref_id, int_id FROM ttrss_user_entries WHERE
11b0dce2 1151 ref_id = '$ref_id' AND owner_uid = '$owner_uid'
ef83538d
AD
1152 $dupcheck_qpart";
1153
b4e75b2a 1154// if ($_REQUEST["xdebug"]) print "$query\n";
ef83538d
AD
1155
1156 $result = db_query($link, $query);
7ca91eb3 1157
11b0dce2
AD
1158 // okay it doesn't exist - create user entry
1159 if (db_num_rows($result) == 0) {
1160
412d258d 1161 if ($debug_enabled) {
7ca91eb3
AD
1162 _debug("update_rss_feed: user record not found, creating...");
1163 }
1164
24605713 1165 if ($score >= -500 && !find_article_filter($article_filters, 'catchup')) {
11b0dce2
AD
1166 $unread = 'true';
1167 $last_read_qpart = 'NULL';
1168 } else {
1169 $unread = 'false';
1170 $last_read_qpart = 'NOW()';
8d505d78 1171 }
dd7d3187 1172
32d59314 1173 if (find_article_filter($article_filters, 'mark') || $score > 1000) {
dd7d3187
AD
1174 $marked = 'true';
1175 } else {
1176 $marked = 'false';
1177 }
a36c0dfe
AD
1178
1179 if (find_article_filter($article_filters, 'publish')) {
1180 $published = 'true';
1181 } else {
1182 $published = 'false';
1183 }
1184
11b0dce2 1185 $result = db_query($link,
8d505d78
AD
1186 "INSERT INTO ttrss_user_entries
1187 (ref_id, owner_uid, feed_id, unread, last_read, marked,
83cd33fc 1188 published, score, tag_cache, label_cache, uuid)
11b0dce2 1189 VALUES ('$ref_id', '$owner_uid', '$feed', $unread,
83cd33fc 1190 $last_read_qpart, $marked, $published, '$score', '', '', '')");
ce53e200 1191
2fcec4c4
AD
1192 if (PUBSUBHUBBUB_HUB && $published == 'true') {
1193 $rss_link = get_self_url_prefix() .
e0d91d84 1194 "/public.php?op=rss&id=-2&key=" .
50332a32 1195 get_feed_access_key($link, -2, false, $owner_uid);
2fcec4c4
AD
1196
1197 $p = new Publisher(PUBSUBHUBBUB_HUB);
1198
1199 $pubsub_result = $p->publish_update($rss_link);
1200 }
1201
8d505d78 1202 $result = db_query($link,
ce53e200
AD
1203 "SELECT int_id FROM ttrss_user_entries WHERE
1204 ref_id = '$ref_id' AND owner_uid = '$owner_uid' AND
1205 feed_id = '$feed' LIMIT 1");
1206
1207 if (db_num_rows($result) == 1) {
1208 $entry_int_id = db_fetch_result($result, 0, "int_id");
1209 }
1210 } else {
412d258d 1211 if ($debug_enabled) {
e04c18a2
AD
1212 _debug("update_rss_feed: user record FOUND");
1213 }
1214
ce53e200
AD
1215 $entry_ref_id = db_fetch_result($result, 0, "ref_id");
1216 $entry_int_id = db_fetch_result($result, 0, "int_id");
11b0dce2 1217 }
ce53e200 1218
412d258d 1219 if ($debug_enabled) {
ce53e200
AD
1220 _debug("update_rss_feed: RID: $entry_ref_id, IID: $entry_int_id");
1221 }
1222
6385315d 1223 $post_needs_update = false;
cdaa1443 1224 $update_insignificant = false;
6385315d 1225
73f168fa 1226 if ($orig_num_comments != $num_comments) {
6385315d 1227 $post_needs_update = true;
73f168fa 1228 $update_insignificant = true;
6385315d
AD
1229 }
1230
73f168fa 1231 if ($content_hash != $orig_content_hash) {
6385315d 1232 $post_needs_update = true;
73f168fa 1233 $update_insignificant = false;
6385315d
AD
1234 }
1235
73f168fa 1236 if (db_escape_string($orig_title) != $entry_title) {
11b0dce2 1237 $post_needs_update = true;
73f168fa 1238 $update_insignificant = false;
11b0dce2
AD
1239 }
1240
8d505d78
AD
1241 // if post needs update, update it and mark all user entries
1242 // linking to this post as updated
6385315d
AD
1243 if ($post_needs_update) {
1244
7ca91eb3
AD
1245 if (defined('DAEMON_EXTENDED_DEBUG')) {
1246 _debug("update_rss_feed: post $entry_guid needs update...");
1247 }
1248
6385315d
AD
1249// print "<!-- post $orig_title needs update : $post_needs_update -->";
1250
8d505d78 1251 db_query($link, "UPDATE ttrss_entries
11b0dce2 1252 SET title = '$entry_title', content = '$entry_content',
7e43ad58 1253 content_hash = '$content_hash',
ad92c6ac 1254 updated = '$entry_timestamp_fmt',
11b0dce2 1255 num_comments = '$num_comments'
6385315d
AD
1256 WHERE id = '$ref_id'");
1257
cdaa1443
AD
1258 if (!$update_insignificant) {
1259 if ($mark_unread_on_update) {
1260 db_query($link, "UPDATE ttrss_user_entries
1261 SET last_read = null, unread = true WHERE ref_id = '$ref_id'");
1262 } else if ($update_on_checksum_change) {
1263 db_query($link, "UPDATE ttrss_user_entries
1264 SET last_read = null WHERE ref_id = '$ref_id'
1265 AND unread = false");
1266 }
4919fb42 1267 }
6385315d 1268 }
4c193675
AD
1269 }
1270
44e241cb
AD
1271 db_query($link, "COMMIT");
1272
412d258d 1273 if ($debug_enabled) {
ceb30ba4
AD
1274 _debug("update_rss_feed: assigning labels...");
1275 }
1276
1277 assign_article_to_labels($link, $entry_ref_id, $article_filters,
1278 $owner_uid);
1279
412d258d 1280 if ($debug_enabled) {
ce53e200
AD
1281 _debug("update_rss_feed: looking for enclosures...");
1282 }
1283
c3fc5e47
AD
1284 // enclosures
1285
1286 $enclosures = array();
1287
1288 if ($use_simplepie) {
1289 $encs = $item->get_enclosures();
1290
1291 if (is_array($encs)) {
1292 foreach ($encs as $e) {
1293 $e_item = array(
1294 $e->link, $e->type, $e->length);
8d505d78 1295
c3fc5e47
AD
1296 array_push($enclosures, $e_item);
1297 }
1298 }
1299
1300 } else {
1301 // <enclosure>
1302
1303 $e_ctr = $item['enclosure#'];
1304
1305 if ($e_ctr > 0) {
1306 $e_item = array($item['enclosure@url'],
1307 $item['enclosure@type'],
1308 $item['enclosure@length']);
1309
1310 array_push($enclosures, $e_item);
1311
1312 for ($i = 0; $i <= $e_ctr; $i++ ) {
1313
1314 if ($item["enclosure#$i@url"]) {
1315 $e_item = array($item["enclosure#$i@url"],
1316 $item["enclosure#$i@type"],
1317 $item["enclosure#$i@length"]);
1318 array_push($enclosures, $e_item);
1319 }
1320 }
1321 }
1322
1323 // <media:content>
1324 // can there be many of those? yes -fox
1325
1326 $m_ctr = $item['media']['content#'];
1327
1328 if ($m_ctr > 0) {
1329 $e_item = array($item['media']['content@url'],
1330 $item['media']['content@medium'],
1331 $item['media']['content@length']);
1332
1333 array_push($enclosures, $e_item);
1334
1335 for ($i = 0; $i <= $m_ctr; $i++ ) {
1336
1337 if ($item["media"]["content#$i@url"]) {
1338 $e_item = array($item["media"]["content#$i@url"],
1339 $item["media"]["content#$i@medium"],
1340 $item["media"]["content#$i@length"]);
1341 array_push($enclosures, $e_item);
1342 }
1343 }
1344
1345 }
1346 }
1347
1348
412d258d 1349 if ($debug_enabled) {
c3fc5e47 1350 _debug("update_rss_feed: article enclosures:");
ce53e200
AD
1351 print_r($enclosures);
1352 }
1353
1354 db_query($link, "BEGIN");
1355
1356 foreach ($enclosures as $enc) {
1357 $enc_url = db_escape_string($enc[0]);
1358 $enc_type = db_escape_string($enc[1]);
1359 $enc_dur = db_escape_string($enc[2]);
1360
1361 $result = db_query($link, "SELECT id FROM ttrss_enclosures
1362 WHERE content_url = '$enc_url' AND post_id = '$entry_ref_id'");
1363
1364 if (db_num_rows($result) == 0) {
1365 db_query($link, "INSERT INTO ttrss_enclosures
1366 (content_url, content_type, title, duration, post_id) VALUES
1367 ('$enc_url', '$enc_type', '', '$enc_dur', '$entry_ref_id')");
1368 }
1369 }
1370
1371 db_query($link, "COMMIT");
1372
c3fc5e47 1373 // check for manual tags (we have to do it here since they're loaded from filters)
073ca0e6 1374
4d50f419
AD
1375 foreach ($article_filters as $f) {
1376 if ($f[0] == "tag") {
f8382011 1377
9949bd15 1378 $manual_tags = trim_array(explode(",", $f[1]));
073ca0e6 1379
4d50f419
AD
1380 foreach ($manual_tags as $tag) {
1381 if (tag_is_valid($tag)) {
1382 array_push($entry_tags, $tag);
1383 }
be832a1a
AD
1384 }
1385 }
1386 }
1387
c3fc5e47
AD
1388 // Skip boring tags
1389
9949bd15 1390 $boring_tags = trim_array(explode(",", mb_strtolower(get_pref($link,
11c9ea1f 1391 'BLACKLISTED_TAGS', $owner_uid, ''), 'utf-8')));
8fc70781 1392
c3fc5e47 1393 $filtered_tags = array();
779560b7 1394 $tags_to_cache = array();
c3fc5e47
AD
1395
1396 if ($entry_tags && is_array($entry_tags)) {
1397 foreach ($entry_tags as $tag) {
1398 if (array_search($tag, $boring_tags) === false) {
1399 array_push($filtered_tags, $tag);
073ca0e6
AD
1400 }
1401 }
8d505d78 1402 }
fefef828 1403
779560b7
AD
1404 $filtered_tags = array_unique($filtered_tags);
1405
412d258d 1406 if ($debug_enabled) {
c3fc5e47
AD
1407 _debug("update_rss_feed: filtered article tags:");
1408 print_r($filtered_tags);
9fdf7824
AD
1409 }
1410
c3fc5e47
AD
1411 // Save article tags in the database
1412
1413 if (count($filtered_tags) > 0) {
8d505d78 1414
44e241cb 1415 db_query($link, "BEGIN");
8d505d78 1416
779560b7 1417 foreach ($filtered_tags as $tag) {
fefef828 1418
779560b7
AD
1419 $tag = sanitize_tag($tag);
1420 $tag = db_escape_string($tag);
1421
1422 if (!tag_is_valid($tag)) continue;
8d505d78
AD
1423
1424 $result = db_query($link, "SELECT id FROM ttrss_tags
1425 WHERE tag_name = '$tag' AND post_int_id = '$entry_int_id' AND
779560b7 1426 owner_uid = '$owner_uid' LIMIT 1");
31483fc1 1427
fe99ab12 1428 if ($result && db_num_rows($result) == 0) {
8d505d78
AD
1429
1430 db_query($link, "INSERT INTO ttrss_tags
fe99ab12
AD
1431 (owner_uid,tag_name,post_int_id)
1432 VALUES ('$owner_uid','$tag', '$entry_int_id')");
779560b7 1433 }
490c366d 1434
779560b7
AD
1435 array_push($tags_to_cache, $tag);
1436 }
490c366d 1437
779560b7 1438 /* update the cache */
8d505d78 1439
779560b7 1440 $tags_to_cache = array_unique($tags_to_cache);
8d505d78 1441
779560b7 1442 $tags_str = db_escape_string(join(",", $tags_to_cache));
490c366d 1443
8d505d78 1444 db_query($link, "UPDATE ttrss_user_entries
779560b7
AD
1445 SET tag_cache = '$tags_str' WHERE ref_id = '$entry_ref_id'
1446 AND owner_uid = $owner_uid");
ce53e200 1447
44e241cb 1448 db_query($link, "COMMIT");
8d505d78 1449 }
9fdf7824 1450
412d258d 1451 if ($debug_enabled) {
9fdf7824
AD
1452 _debug("update_rss_feed: article processed");
1453 }
8d505d78 1454 }
40d13c28 1455
50b2db96 1456 if (!$last_updated) {
412d258d 1457 if ($debug_enabled) {
50b2db96
AD
1458 _debug("update_rss_feed: new feed, catching it up...");
1459 }
c7e51de1 1460 catchup_feed($link, $feed, false, $owner_uid);
50b2db96
AD
1461 }
1462
71344201
AD
1463 if ($debug_enabled) {
1464 _debug("purging feed...");
1465 }
1466
1467 purge_feed($link, $feed, 0, $debug_enabled);
3907ef71 1468
8d505d78 1469 db_query($link, "UPDATE ttrss_feeds
ab3d0b99 1470 SET last_updated = NOW(), last_error = '' WHERE id = '$feed'");
eb36b4eb 1471
44e241cb 1472// db_query($link, "COMMIT");
dd8c76a9 1473
ab3d0b99 1474 } else {
ca872b9d 1475
16211ddb 1476 if ($use_simplepie) {
ca872b9d 1477 $error_msg = mb_substr($rss->error(), 0, 250);
9fdf7824 1478 } else {
ca872b9d 1479 $error_msg = mb_substr(magpie_error(), 0, 250);
9fdf7824 1480 }
ca872b9d 1481
412d258d 1482 if ($debug_enabled) {
ca872b9d
AD
1483 _debug("update_rss_feed: error fetching feed: $error_msg");
1484 }
1485
1486 $error_msg = db_escape_string($error_msg);
1487
8d505d78
AD
1488 db_query($link,
1489 "UPDATE ttrss_feeds SET last_error = '$error_msg',
aa5f9f5f 1490 last_updated = NOW() WHERE id = '$feed'");
40d13c28
AD
1491 }
1492
16211ddb 1493 if ($use_simplepie) {
ac6ebdb3
AD
1494 unset($rss);
1495 }
1496
412d258d 1497 if ($debug_enabled) {
34e420fb 1498 _debug("update_rss_feed: done");
219bd8fc
AD
1499 }
1500
40d13c28
AD
1501 }
1502
f175937c 1503 function print_select($id, $default, $values, $attributes = "") {
79f3553b 1504 print "<select name=\"$id\" id=\"$id\" $attributes>";
a0d53889
AD
1505 foreach ($values as $v) {
1506 if ($v == $default)
60807300 1507 $sel = "selected=\"1\"";
a0d53889
AD
1508 else
1509 $sel = "";
8d505d78 1510
60807300 1511 print "<option value=\"$v\" $sel>$v</option>";
a0d53889
AD
1512 }
1513 print "</select>";
1514 }
40d13c28 1515
79f3553b
AD
1516 function print_select_hash($id, $default, $values, $attributes = "") {
1517 print "<select name=\"$id\" id='$id' $attributes>";
673d54ca
AD
1518 foreach (array_keys($values) as $v) {
1519 if ($v == $default)
74d5c8fa 1520 $sel = 'selected="selected"';
673d54ca
AD
1521 else
1522 $sel = "";
8d505d78 1523
673d54ca
AD
1524 print "<option $sel value=\"$v\">".$values[$v]."</option>";
1525 }
1526
1527 print "</select>";
1528 }
1529
c3fc5e47 1530 function get_article_filters($filters, $title, $content, $link, $timestamp, $author, $tags) {
240054f1 1531 $matches = array();
c2d9322b 1532
240054f1
AD
1533 if ($filters["title"]) {
1534 foreach ($filters["title"] as $filter) {
8d505d78
AD
1535 $reg_exp = $filter["reg_exp"];
1536 $inverse = $filter["inverse"];
1537 if ((!$inverse && @preg_match("/$reg_exp/i", $title)) ||
a9d63d29 1538 ($inverse && !@preg_match("/$reg_exp/i", $title))) {
c2d9322b 1539
240054f1
AD
1540 array_push($matches, array($filter["action"], $filter["action_param"]));
1541 }
1542 }
1543 }
1544
1545 if ($filters["content"]) {
1546 foreach ($filters["content"] as $filter) {
c2d9322b
AD
1547 $reg_exp = $filter["reg_exp"];
1548 $inverse = $filter["inverse"];
1549
8d505d78 1550 if ((!$inverse && @preg_match("/$reg_exp/i", $content)) ||
a9d63d29 1551 ($inverse && !@preg_match("/$reg_exp/i", $content))) {
c2d9322b 1552
240054f1 1553 array_push($matches, array($filter["action"], $filter["action_param"]));
8d505d78 1554 }
240054f1
AD
1555 }
1556 }
1557
1558 if ($filters["both"]) {
8d505d78
AD
1559 foreach ($filters["both"] as $filter) {
1560 $reg_exp = $filter["reg_exp"];
c2d9322b
AD
1561 $inverse = $filter["inverse"];
1562
1563 if ($inverse) {
a9d63d29 1564 if (!@preg_match("/$reg_exp/i", $title) && !preg_match("/$reg_exp/i", $content)) {
c2d9322b
AD
1565 array_push($matches, array($filter["action"], $filter["action_param"]));
1566 }
1567 } else {
a9d63d29 1568 if (@preg_match("/$reg_exp/i", $title) || preg_match("/$reg_exp/i", $content)) {
c2d9322b
AD
1569 array_push($matches, array($filter["action"], $filter["action_param"]));
1570 }
240054f1
AD
1571 }
1572 }
1573 }
1574
1575 if ($filters["link"]) {
1576 $reg_exp = $filter["reg_exp"];
1577 foreach ($filters["link"] as $filter) {
1578 $reg_exp = $filter["reg_exp"];
c2d9322b
AD
1579 $inverse = $filter["inverse"];
1580
8d505d78 1581 if ((!$inverse && @preg_match("/$reg_exp/i", $link)) ||
a9d63d29 1582 ($inverse && !@preg_match("/$reg_exp/i", $link))) {
8d505d78 1583
240054f1
AD
1584 array_push($matches, array($filter["action"], $filter["action_param"]));
1585 }
1586 }
1587 }
1588
44d0e774
AD
1589 if ($filters["date"]) {
1590 $reg_exp = $filter["reg_exp"];
1591 foreach ($filters["date"] as $filter) {
1592 $date_modifier = $filter["filter_param"];
1593 $inverse = $filter["inverse"];
1594 $check_timestamp = strtotime($filter["reg_exp"]);
1595
1596 # no-op when timestamp doesn't parse to prevent misfires
1597
1598 if ($check_timestamp) {
1599 $match_ok = false;
1600
1601 if ($date_modifier == "before" && $timestamp < $check_timestamp ||
1602 $date_modifier == "after" && $timestamp > $check_timestamp) {
1603 $match_ok = true;
1604 }
1605
1606 if ($inverse) $match_ok = !$match_ok;
1607
1608 if ($match_ok) {
1609 array_push($matches, array($filter["action"], $filter["action_param"]));
1610 }
1611 }
1612 }
8d505d78 1613 }
44d0e774 1614
fa3317be
AD
1615 if ($filters["author"]) {
1616 foreach ($filters["author"] as $filter) {
8d505d78
AD
1617 $reg_exp = $filter["reg_exp"];
1618 $inverse = $filter["inverse"];
1619 if ((!$inverse && @preg_match("/$reg_exp/i", $author)) ||
a9d63d29 1620 ($inverse && !@preg_match("/$reg_exp/i", $author))) {
fa3317be
AD
1621
1622 array_push($matches, array($filter["action"], $filter["action_param"]));
1623 }
1624 }
1625 }
1626
c3fc5e47
AD
1627 if ($filters["tag"]) {
1628
1629 $tag_string = join(",", $tags);
1630
1631 foreach ($filters["tag"] as $filter) {
1632 $reg_exp = $filter["reg_exp"];
1633 $inverse = $filter["inverse"];
1634
8d505d78 1635 if ((!$inverse && @preg_match("/$reg_exp/i", $tag_string)) ||
a9d63d29 1636 ($inverse && !@preg_match("/$reg_exp/i", $tag_string))) {
c3fc5e47
AD
1637
1638 array_push($matches, array($filter["action"], $filter["action_param"]));
8d505d78 1639 }
c3fc5e47
AD
1640 }
1641 }
1642
1643
240054f1
AD
1644 return $matches;
1645 }
1646
f8382011
AD
1647 function find_article_filter($filters, $filter_name) {
1648 foreach ($filters as $f) {
1649 if ($f[0] == $filter_name) {
1650 return $f;
1651 };
1652 }
1653 return false;
1654 }
1655
ff6e357a
AD
1656 function calculate_article_score($filters) {
1657 $score = 0;
1658
1659 foreach ($filters as $f) {
1660 if ($f[0] == "score") {
1661 $score += $f[1];
1662 };
1663 }
1664 return $score;
1665 }
1666
ceb30ba4
AD
1667 function assign_article_to_labels($link, $id, $filters, $owner_uid) {
1668 foreach ($filters as $f) {
1669 if ($f[0] == "label") {
1670 label_add_article($link, $id, $f[1], $owner_uid);
1671 };
1672 }
1673 }
ff6e357a 1674
406d9489
AD
1675 function getmicrotime() {
1676 list($usec, $sec) = explode(" ",microtime());
1677 return ((float)$usec + (float)$sec);
1678 }
1679
f541eb78 1680 function print_radio($id, $default, $true_is, $values, $attributes = "") {
77e96719 1681 foreach ($values as $v) {
8d505d78 1682
77e96719 1683 if ($v == $default)
5da169d9 1684 $sel = "checked";
77e96719 1685 else
5da169d9
AD
1686 $sel = "";
1687
f541eb78 1688 if ($v == $true_is) {
5da169d9
AD
1689 $sel .= " value=\"1\"";
1690 } else {
1691 $sel .= " value=\"0\"";
1692 }
8d505d78
AD
1693
1694 print "<input class=\"noborder\" dojoType=\"dijit.form.RadioButton\"
69654950 1695 type=\"radio\" $sel $attributes name=\"$id\">&nbsp;$v&nbsp;";
77e96719
AD
1696
1697 }
1698 }
1699
d9084cf2 1700 function initialize_user_prefs($link, $uid, $profile = false) {
ff485f1d
AD
1701
1702 $uid = db_escape_string($uid);
1703
d9084cf2
AD
1704 if (!$profile) {
1705 $profile = "NULL";
f9aa6a89 1706 $profile_qpart = "AND profile IS NULL";
d9084cf2 1707 } else {
f9aa6a89 1708 $profile_qpart = "AND profile = '$profile'";
d9084cf2
AD
1709 }
1710
f9aa6a89
AD
1711 if (get_schema_version($link) < 63) $profile_qpart = "";
1712
ff485f1d
AD
1713 db_query($link, "BEGIN");
1714
1715 $result = db_query($link, "SELECT pref_name,def_value FROM ttrss_prefs");
8d505d78
AD
1716
1717 $u_result = db_query($link, "SELECT pref_name
f9aa6a89 1718 FROM ttrss_user_prefs WHERE owner_uid = '$uid' $profile_qpart");
ff485f1d
AD
1719
1720 $active_prefs = array();
1721
1722 while ($line = db_fetch_assoc($u_result)) {
8d505d78 1723 array_push($active_prefs, $line["pref_name"]);
ff485f1d
AD
1724 }
1725
1726 while ($line = db_fetch_assoc($result)) {
1727 if (array_search($line["pref_name"], $active_prefs) === FALSE) {
1728// print "adding " . $line["pref_name"] . "<br>";
1729
f9aa6a89
AD
1730 if (get_schema_version($link) < 63) {
1731 db_query($link, "INSERT INTO ttrss_user_prefs
8d505d78 1732 (owner_uid,pref_name,value) VALUES
f9aa6a89
AD
1733 ('$uid', '".$line["pref_name"]."','".$line["def_value"]."')");
1734
1735 } else {
1736 db_query($link, "INSERT INTO ttrss_user_prefs
8d505d78 1737 (owner_uid,pref_name,value, profile) VALUES
f9aa6a89
AD
1738 ('$uid', '".$line["pref_name"]."','".$line["def_value"]."', $profile)");
1739 }
ff485f1d
AD
1740
1741 }
1742 }
1743
1744 db_query($link, "COMMIT");
1745
1746 }
956c7629 1747
8de8bfb8
AD
1748 function get_ssl_certificate_id() {
1749 if ($_SERVER["REDIRECT_SSL_CLIENT_M_SERIAL"]) {
1750 return sha1($_SERVER["REDIRECT_SSL_CLIENT_M_SERIAL"] .
1751 $_SERVER["REDIRECT_SSL_CLIENT_V_START"] .
1752 $_SERVER["REDIRECT_SSL_CLIENT_V_END"] .
1753 $_SERVER["REDIRECT_SSL_CLIENT_S_DN"]);
1754 }
1755 return "";
1756 }
1757
3d72afa1
AD
1758 function get_login_by_ssl_certificate($link) {
1759
8de8bfb8 1760 $cert_serial = db_escape_string(get_ssl_certificate_id());
3d72afa1
AD
1761
1762 if ($cert_serial) {
1763 $result = db_query($link, "SELECT login FROM ttrss_user_prefs, ttrss_users
1764 WHERE pref_name = 'SSL_CERT_SERIAL' AND value = '$cert_serial' AND
1765 owner_uid = ttrss_users.id");
1766
1767 if (db_num_rows($result) != 0) {
1768 return db_escape_string(db_fetch_result($result, 0, "login"));
1769 }
1770 }
1771
1772 return "";
1773 }
1774
bf9fc060 1775 function get_remote_user($link) {
f98252f2 1776
3d72afa1 1777 if (defined('ALLOW_REMOTE_USER_AUTH') && ALLOW_REMOTE_USER_AUTH) {
bf9fc060 1778 return db_escape_string($_SERVER["REMOTE_USER"]);
3d72afa1 1779 }
f98252f2 1780
bf9fc060 1781 return db_escape_string(get_login_by_ssl_certificate($link));
f98252f2
AD
1782 }
1783
bf9fc060
AD
1784 function get_remote_fakepass($link) {
1785 if (get_remote_user($link))
f98252f2
AD
1786 return "******";
1787 else
1788 return "";
1789 }
1790
461766f3 1791 function authenticate_user($link, $login, $password, $force_auth = false) {
c8437f35 1792
131b01b3 1793 if (!SINGLE_USER_MODE) {
c8437f35 1794
1a9f4d3c
AD
1795 $pwd_hash1 = encrypt_password($password);
1796 $pwd_hash2 = encrypt_password($password, $login);
2d969845 1797 $login = db_escape_string($login);
461766f3 1798
bf9fc060 1799 $remote_user = get_remote_user($link);
66917e70 1800
c9b63492 1801 if ($remote_user && $remote_user == $login && $login != "admin") {
3d72afa1
AD
1802
1803 $login = $remote_user;
66917e70 1804
73f5f114 1805 $query = "SELECT id,login,access_level,pwd_hash
461766f3 1806 FROM ttrss_users WHERE
66917e70
AD
1807 login = '$login'";
1808
42315f8d
AD
1809 if (defined('AUTO_CREATE_USER') && AUTO_CREATE_USER
1810 && $_SERVER["REMOTE_USER"]) {
1811 $result = db_query($link, $query);
1812
1813 // First login ?
1814 if (db_num_rows($result) == 0) {
6ad2bbbc 1815 $query2 = "INSERT INTO ttrss_users
42315f8d
AD
1816 (login,access_level,last_login,created)
1817 VALUES ('$login', 0, null, NOW())";
6ad2bbbc 1818 db_query($link, $query2);
42315f8d
AD
1819 }
1820 }
1821
461766f3 1822 } else {
1a9f4d3c 1823 $query = "SELECT id,login,access_level,pwd_hash
461766f3 1824 FROM ttrss_users WHERE
1a9f4d3c
AD
1825 login = '$login' AND (pwd_hash = '$pwd_hash1' OR
1826 pwd_hash = '$pwd_hash2')";
461766f3
AD
1827 }
1828
1829 $result = db_query($link, $query);
8d505d78 1830
131b01b3
AD
1831 if (db_num_rows($result) == 1) {
1832 $_SESSION["uid"] = db_fetch_result($result, 0, "id");
1833 $_SESSION["name"] = db_fetch_result($result, 0, "login");
1834 $_SESSION["access_level"] = db_fetch_result($result, 0, "access_level");
8d505d78
AD
1835
1836 db_query($link, "UPDATE ttrss_users SET last_login = NOW() WHERE id = " .
131b01b3 1837 $_SESSION["uid"]);
8d505d78 1838
42315f8d
AD
1839
1840 // LemonLDAP can send user informations via HTTP HEADER
1841 if (defined('AUTO_CREATE_USER') && AUTO_CREATE_USER){
1842 // update user name
8efb5f62
AD
1843 $fullname = $_SERVER['HTTP_USER_NAME'] ? $_SERVER['HTTP_USER_NAME'] : $_SERVER['AUTHENTICATE_CN'];
1844 if ($fullname){
1845 $fullname = db_escape_string($fullname);
42315f8d
AD
1846 db_query($link, "UPDATE ttrss_users SET full_name = '$fullname' WHERE id = " .
1847 $_SESSION["uid"]);
1848 }
1849 // update user mail
8efb5f62
AD
1850 $email = $_SERVER['HTTP_USER_MAIL'] ? $_SERVER['HTTP_USER_MAIL'] : $_SERVER['AUTHENTICATE_MAIL'];
1851 if ($email){
1852 $email = db_escape_string($email);
42315f8d
AD
1853 db_query($link, "UPDATE ttrss_users SET email = '$email' WHERE id = " .
1854 $_SESSION["uid"]);
1855 }
1856 }
1857
131b01b3 1858 $_SESSION["ip_address"] = $_SERVER["REMOTE_ADDR"];
1a9f4d3c 1859 $_SESSION["pwd_hash"] = db_fetch_result($result, 0, "pwd_hash");
91c5f229
AD
1860
1861 $_SESSION["last_version_check"] = time();
8d505d78 1862
131b01b3 1863 initialize_user_prefs($link, $_SESSION["uid"]);
8d505d78 1864
131b01b3
AD
1865 return true;
1866 }
8d505d78 1867
131b01b3 1868 return false;
503eb349 1869
131b01b3 1870 } else {
503eb349 1871
131b01b3
AD
1872 $_SESSION["uid"] = 1;
1873 $_SESSION["name"] = "admin";
f557cd78 1874
0bbba72d 1875 $_SESSION["ip_address"] = $_SERVER["REMOTE_ADDR"];
8d505d78 1876
0bbba72d 1877 initialize_user_prefs($link, $_SESSION["uid"]);
8d505d78 1878
c8437f35
AD
1879 return true;
1880 }
c8437f35
AD
1881 }
1882
e6cb77a0
AD
1883 function make_password($length = 8) {
1884
1885 $password = "";
8d505d78
AD
1886 $possible = "0123456789abcdfghjkmnpqrstvwxyzABCDFGHJKMNPQRSTVWXYZ";
1887
1888 $i = 0;
1889
1890 while ($i < $length) {
e6cb77a0 1891 $char = substr($possible, mt_rand(0, strlen($possible)-1), 1);
8d505d78
AD
1892
1893 if (!strstr($password, $char)) {
e6cb77a0
AD
1894 $password .= $char;
1895 $i++;
1896 }
1897 }
1898 return $password;
1899 }
1900
1901 // this is called after user is created to initialize default feeds, labels
1902 // or whatever else
8d505d78 1903
e6cb77a0
AD
1904 // user preferences are checked on every login, not here
1905
1906 function initialize_user($link, $uid) {
1907
e6cb77a0 1908 db_query($link, "insert into ttrss_feeds (owner_uid,title,feed_url)
74bff337 1909 values ('$uid', 'Tiny Tiny RSS: New Releases',
b6d486a3 1910 'http://tt-rss.org/releases.rss')");
3b0feb9b 1911
cd2cd415
AD
1912 db_query($link, "insert into ttrss_feeds (owner_uid,title,feed_url)
1913 values ('$uid', 'Tiny Tiny RSS: Forum',
f0855b88 1914 'http://tt-rss.org/forum/rss.php')");
3b0feb9b 1915 }
e6cb77a0 1916
b8aa49bc 1917 function logout_user() {
5ccc1cf5
AD
1918 session_destroy();
1919 if (isset($_COOKIE[session_name()])) {
1920 setcookie(session_name(), '', time()-42000, '/');
1921 }
b8aa49bc
AD
1922 }
1923
916f788a 1924 function validate_session($link) {
0f41fce8
AD
1925 if (SINGLE_USER_MODE) return true;
1926
1927 $check_ip = $_SESSION['ip_address'];
1928
1929 switch (SESSION_CHECK_ADDRESS) {
1930 case 0:
1931 $check_ip = '';
1932 break;
1933 case 1:
1934 $check_ip = substr($check_ip, 0, strrpos($check_ip, '.')+1);
1935 break;
1936 case 2:
1937 $check_ip = substr($check_ip, 0, strrpos($check_ip, '.'));
1938 $check_ip = substr($check_ip, 0, strrpos($check_ip, '.')+1);
1939 break;
1940 };
1941
d769a0f7 1942 if ($check_ip && strpos($_SERVER['REMOTE_ADDR'], $check_ip) !== 0) {
8d505d78 1943 $_SESSION["login_error_msg"] =
d769a0f7
AD
1944 __("Session failed to validate (incorrect IP)");
1945 return false;
1946 }
0f41fce8
AD
1947
1948 if ($_SESSION["ref_schema_version"] != get_schema_version($link, true))
05044a59 1949 return false;
05044a59 1950
e6684130
AD
1951 if ($_SESSION["uid"]) {
1952
8d505d78 1953 $result = db_query($link,
e6684130
AD
1954 "SELECT pwd_hash FROM ttrss_users WHERE id = '".$_SESSION["uid"]."'");
1955
1956 $pwd_hash = db_fetch_result($result, 0, "pwd_hash");
1957
1958 if ($pwd_hash != $_SESSION["pwd_hash"]) {
1959 return false;
1960 }
1961 }
1962
a885f0ec 1963/* if ($_SESSION["cookie_lifetime"] && $_SESSION["uid"]) {
d620cfe7 1964
8e849206 1965 //print_r($_SESSION);
d620cfe7
AD
1966
1967 if (time() > $_SESSION["cookie_lifetime"]) {
1968 return false;
1969 }
a885f0ec
AD
1970 } */
1971
916f788a
AD
1972 return true;
1973 }
1974
793185a9 1975 function login_sequence($link, $mobile = false) {
c648997b
AD
1976 $_SESSION["prefs_cache"] = array();
1977
b8aa49bc 1978 if (!SINGLE_USER_MODE) {
75836f33 1979
7f0acba7 1980 $login_action = $_POST["login_action"];
a885f0ec 1981
8d505d78 1982 # try to authenticate user if called from login form
7f0acba7 1983 if ($login_action == "do_login") {
92decf4f 1984 $login = db_escape_string($_POST["login"]);
4044a5fa 1985 $password = $_POST["password"];
d620cfe7 1986 $remember_me = $_POST["remember_me"];
f557cd78 1987
01a87dff
AD
1988 if (authenticate_user($link, $login, $password)) {
1989 $_POST["password"] = "";
d620cfe7 1990
f8c612d4 1991 $_SESSION["language"] = $_POST["language"];
05044a59 1992 $_SESSION["ref_schema_version"] = get_schema_version($link, true);
a598370d 1993 $_SESSION["bw_limit"] = !!$_POST["bw_limit"];
f8c612d4 1994
d9084cf2
AD
1995 if ($_POST["profile"]) {
1996
1997 $profile = db_escape_string($_POST["profile"]);
1998
1999 $result = db_query($link, "SELECT id FROM ttrss_settings_profiles
2000 WHERE id = '$profile' AND owner_uid = " . $_SESSION["uid"]);
2001
2002 if (db_num_rows($result) != 0) {
2003 $_SESSION["profile"] = $profile;
2004 $_SESSION["prefs_cache"] = array();
2005 }
2006 }
2007
6615cc36
AD
2008 if ($_REQUEST['return']) {
2009 header("Location: " . $_REQUEST['return']);
2010 } else {
2011 header("Location: " . $_SERVER["REQUEST_URI"]);
2012 }
2013
d620cfe7
AD
2014 exit;
2015
01a87dff 2016 return;
7f0acba7 2017 } else {
af163b85 2018 $_SESSION["login_error_msg"] = __("Incorrect username or password");
01a87dff
AD
2019 }
2020 }
2021
7f0acba7 2022 if (!$_SESSION["uid"] || !validate_session($link)) {
3d72afa1 2023
bf9fc060
AD
2024 if (get_remote_user($link) && AUTO_LOGIN) {
2025 authenticate_user($link, get_remote_user($link), null);
12df6592
AD
2026 $_SESSION["ref_schema_version"] = get_schema_version($link, true);
2027 } else {
2028 render_login_form($link, $mobile);
2029 //header("Location: login.php");
2030 exit;
2031 }
d3687e7a
AD
2032 } else {
2033 /* bump login timestamp */
8d505d78 2034 db_query($link, "UPDATE ttrss_users SET last_login = NOW() WHERE id = " .
d3687e7a 2035 $_SESSION["uid"]);
019bd5a9 2036
d54780bc 2037 if ($_SESSION["language"] && SESSION_COOKIE_LIFETIME > 0) {
8d505d78 2038 setcookie("ttrss_lang", $_SESSION["language"],
019bd5a9
AD
2039 time() + SESSION_COOKIE_LIFETIME);
2040 }
3261ca58
AD
2041
2042 // try to remove possible duplicates from feed counter cache
147f5632 2043// ccache_cleanup($link, $_SESSION["uid"]);
b8aa49bc 2044 }
d620cfe7 2045
b8aa49bc 2046 } else {
0bbba72d 2047 return authenticate_user($link, "admin", null);
b8aa49bc
AD
2048 }
2049 }
3547842a 2050
411fe209 2051 function truncate_string($str, $max_len, $suffix = '&hellip;') {
12db369c 2052 if (mb_strlen($str, "utf-8") > $max_len - 3) {
411fe209 2053 return mb_substr($str, 0, $max_len, "utf-8") . $suffix;
3547842a
AD
2054 } else {
2055 return $str;
2056 }
2057 }
54a60e1a 2058
e9823609 2059 function theme_image($link, $filename) {
883fee8d
AD
2060 if ($link) {
2061 $theme_path = get_user_theme_path($link);
e9823609 2062
883fee8d
AD
2063 if ($theme_path && is_file($theme_path.$filename)) {
2064 return $theme_path.$filename;
2065 } else {
2066 return $filename;
2067 }
e9823609
AD
2068 } else {
2069 return $filename;
2070 }
2071 }
2072
dce46cad 2073 function get_user_theme($link) {
e4c51a6c 2074
b92fbcd8 2075 if (get_schema_version($link) >= 63 && $_SESSION["uid"]) {
b97e6e02
AD
2076 $theme_name = get_pref($link, "_THEME_ID");
2077 if (is_dir("themes/$theme_name")) {
2078 return $theme_name;
2079 } else {
2080 return '';
2081 }
e4c51a6c 2082 } else {
b97e6e02 2083 return '';
e4c51a6c 2084 }
d9084cf2 2085
dce46cad
AD
2086 }
2087
2088 function get_user_theme_path($link) {
c3fddd05 2089 $theme_path = '';
dce46cad 2090
b92fbcd8 2091 if (get_schema_version($link) >= 63 && $_SESSION["uid"]) {
dce46cad
AD
2092 $theme_name = get_pref($link, "_THEME_ID");
2093
b97e6e02 2094 if ($theme_name && is_dir("themes/$theme_name")) {
dce46cad 2095 $theme_path = "themes/$theme_name/";
6ba50622 2096 } else {
dce46cad 2097 $theme_name = '';
6ba50622 2098 }
54a60e1a 2099 } else {
dce46cad
AD
2100 $theme_path = '';
2101 }
2102
0c425dc7 2103 if ($theme_path) {
8d3cb8c0
AD
2104 if (is_file("$theme_path/theme.ini")) {
2105 $ini = parse_ini_file("$theme_path/theme.ini", true);
2106 if ($ini['theme']['version'] >= THEME_VERSION_REQUIRED) {
0c425dc7
AD
2107 return $theme_path;
2108 }
2109 }
2110 }
2111 return '';
dce46cad
AD
2112 }
2113
e71f2610
AD
2114 function get_user_theme_options($link) {
2115 $t = get_user_theme_path($link);
2116
2117 if ($t) {
2118 if (is_file("$t/theme.ini")) {
2119 $ini = parse_ini_file("$t/theme.ini", true);
2120 if ($ini['theme']['version']) {
2121 return $ini['theme']['options'];
2122 }
2123 }
2124 }
f1f3a642 2125 return '';
e71f2610
AD
2126 }
2127
8d3cb8c0
AD
2128 function print_theme_includes($link) {
2129
2130 $t = get_user_theme_path($link);
2131 $time = time();
2132
2133 if ($t) {
8d505d78 2134 print "<link rel=\"stylesheet\" type=\"text/css\"
8d3cb8c0
AD
2135 href=\"$t/theme.css?$time \">";
2136 if (file_exists("$t/theme.js")) {
2137 print "<script type=\"text/javascript\" src=\"$t/theme.js?$time\">
2138 </script>";
2139 }
2140 }
2141 }
e71f2610 2142
dce46cad
AD
2143 function get_all_themes() {
2144 $themes = glob("themes/*");
2145
b97e6e02
AD
2146 asort($themes);
2147
dce46cad
AD
2148 $rv = array();
2149
2150 foreach ($themes as $t) {
2151 if (is_file("$t/theme.ini")) {
2152 $ini = parse_ini_file("$t/theme.ini", true);
8d505d78 2153 if ($ini['theme']['version'] >= THEME_VERSION_REQUIRED &&
0c425dc7 2154 !$ini['theme']['disabled']) {
dce46cad
AD
2155 $entry = array();
2156 $entry["path"] = $t;
2157 $entry["base"] = basename($t);
2158 $entry["name"] = $ini['theme']['name'];
2159 $entry["version"] = $ini['theme']['version'];
2160 $entry["author"] = $ini['theme']['author'];
e71f2610 2161 $entry["options"] = $ini['theme']['options'];
dce46cad
AD
2162 array_push($rv, $entry);
2163 }
2164 }
54a60e1a 2165 }
dce46cad
AD
2166
2167 return $rv;
54a60e1a 2168 }
be773442 2169
ab4b768f
AD
2170 function convert_timestamp($timestamp, $source_tz, $dest_tz) {
2171
2172 try {
2173 $source_tz = new DateTimeZone($source_tz);
2174 } catch (Exception $e) {
2175 $source_tz = new DateTimeZone('UTC');
2176 }
2177
2178 try {
2179 $dest_tz = new DateTimeZone($dest_tz);
2180 } catch (Exception $e) {
2181 $dest_tz = new DateTimeZone('UTC');
2182 }
2183
2184 $dt = new DateTime(date('Y-m-d H:i:s', $timestamp), $source_tz);
2185 return $dt->format('U') + $dest_tz->getOffset($dt);
2186 }
2187
324944f3
AD
2188 function make_local_datetime($link, $timestamp, $long, $owner_uid = false,
2189 $no_smart_dt = false) {
2190
2191 if (!$owner_uid) $owner_uid = $_SESSION['uid'];
2192 if (!$timestamp) $timestamp = '1970-01-01 0:00';
2193
7d96bfcd
AD
2194 global $utc_tz;
2195 global $tz_offset;
324944f3 2196
7d96bfcd
AD
2197 # We store date in UTC internally
2198 $dt = new DateTime($timestamp, $utc_tz);
2199
2200 if ($tz_offset == -1) {
2201
2202 $user_tz_string = get_pref($link, 'USER_TIMEZONE', $owner_uid);
2203
2204 try {
2205 $user_tz = new DateTimeZone($user_tz_string);
2206 } catch (Exception $e) {
2207 $user_tz = $utc_tz;
2208 }
2209
2210 $tz_offset = $user_tz->getOffset($dt);
324944f3
AD
2211 }
2212
7d96bfcd 2213 $user_timestamp = $dt->format('U') + $tz_offset;
324944f3 2214
1dc52ae7 2215 if (!$no_smart_dt) {
8d505d78 2216 return smart_date_time($link, $user_timestamp,
7d96bfcd 2217 $tz_offset, $owner_uid);
324944f3
AD
2218 } else {
2219 if ($long)
2220 $format = get_pref($link, 'LONG_DATE_FORMAT', $owner_uid);
2221 else
2222 $format = get_pref($link, 'SHORT_DATE_FORMAT', $owner_uid);
2223
2224 return date($format, $user_timestamp);
2225 }
2226 }
2227
2a5c136e
AD
2228 function smart_date_time($link, $timestamp, $tz_offset = 0, $owner_uid = false) {
2229 if (!$owner_uid) $owner_uid = $_SESSION['uid'];
2230
2231 if (date("Y.m.d", $timestamp) == date("Y.m.d", time() + $tz_offset)) {
be773442 2232 return date("G:i", $timestamp);
2a5c136e
AD
2233 } else if (date("Y", $timestamp) == date("Y", time() + $tz_offset)) {
2234 $format = get_pref($link, 'SHORT_DATE_FORMAT', $owner_uid);
2235 return date($format, $timestamp);
be773442 2236 } else {
2a5c136e
AD
2237 $format = get_pref($link, 'LONG_DATE_FORMAT', $owner_uid);
2238 return date($format, $timestamp);
be773442
AD
2239 }
2240 }
2241
e3c99f3b 2242 function sql_bool_to_bool($s) {
36184020 2243 if ($s == "t" || $s == "1" || $s == "true") {
e3c99f3b
AD
2244 return true;
2245 } else {
2246 return false;
2247 }
2248 }
8d505d78 2249
badac687
AD
2250 function bool_to_sql_bool($s) {
2251 if ($s) {
2252 return "true";
2253 } else {
2254 return "false";
2255 }
2256 }
e3c99f3b 2257
fcfa9ef1
AD
2258 // Session caching removed due to causing wrong redirects to upgrade
2259 // script when get_schema_version() is called on an obsolete session
2260 // created on a previous schema version.
199db684 2261 function get_schema_version($link, $nocache = false) {
7d96bfcd
AD
2262 global $schema_version;
2263
2264 if (!$schema_version) {
199db684
AD
2265 $result = db_query($link, "SELECT schema_version FROM ttrss_version");
2266 $version = db_fetch_result($result, 0, "schema_version");
7d96bfcd 2267 $schema_version = $version;
199db684 2268 return $version;
7d96bfcd
AD
2269 } else {
2270 return $schema_version;
2271 }
e4c51a6c
AD
2272 }
2273
6043fb7e 2274 function sanity_check($link) {
31303c6b 2275 require_once 'errors.php';
ebb948c2 2276
6043fb7e 2277 $error_code = 0;
7d96bfcd 2278 $schema_version = get_schema_version($link, true);
6043fb7e
AD
2279
2280 if ($schema_version != SCHEMA_VERSION) {
2281 $error_code = 5;
2282 }
2283
aec3ce39
AD
2284 if (DB_TYPE == "mysql") {
2285 $result = db_query($link, "SELECT true", false);
2286 if (db_num_rows($result) != 1) {
2287 $error_code = 10;
2288 }
2289 }
2290
f29ba148
AD
2291 if (db_escape_string("testTEST") != "testTEST") {
2292 $error_code = 12;
2293 }
2294
ebb948c2 2295 return array("code" => $error_code, "message" => $ERRORS[$error_code]);
6043fb7e
AD
2296 }
2297
27981ca3 2298 function file_is_locked($filename) {
31a6d42d 2299 if (function_exists('flock')) {
fb074239 2300 $fp = @fopen(LOCK_DIRECTORY . "/$filename", "r");
31a6d42d
AD
2301 if ($fp) {
2302 if (flock($fp, LOCK_EX | LOCK_NB)) {
2303 flock($fp, LOCK_UN);
2304 fclose($fp);
2305 return false;
2306 }
27981ca3 2307 fclose($fp);
31a6d42d 2308 return true;
e89aed7b
AD
2309 } else {
2310 return false;
27981ca3 2311 }
27981ca3 2312 }
c1fb4a5e 2313 return true; // consider the file always locked and skip the test
27981ca3
AD
2314 }
2315
fcb4c0c9 2316 function make_lockfile($filename) {
cfa43e02 2317 $fp = fopen(LOCK_DIRECTORY . "/$filename", "w");
fcb4c0c9 2318
82acc36d 2319 if (flock($fp, LOCK_EX | LOCK_NB)) {
4c59adb1
AD
2320 if (function_exists('posix_getpid')) {
2321 fwrite($fp, posix_getpid() . "\n");
2322 }
fcb4c0c9
AD
2323 return $fp;
2324 } else {
2325 return false;
2326 }
2327 }
2328
bf7fcde8 2329 function make_stampfile($filename) {
cfa43e02 2330 $fp = fopen(LOCK_DIRECTORY . "/$filename", "w");
bf7fcde8 2331
8e00ae9b 2332 if (flock($fp, LOCK_EX | LOCK_NB)) {
bf7fcde8 2333 fwrite($fp, time() . "\n");
8e00ae9b 2334 flock($fp, LOCK_UN);
bf7fcde8
AD
2335 fclose($fp);
2336 return true;
2337 } else {
2338 return false;
2339 }
2340 }
2341
894ebcf5
AD
2342 function sql_random_function() {
2343 if (DB_TYPE == "mysql") {
2344 return "RAND()";
2345 } else {
2346 return "RANDOM()";
2347 }
2348 }
2349
d36f5607 2350 function catchup_feed($link, $feed, $cat_view, $owner_uid = false) {
c7e51de1
AD
2351
2352 if (!$owner_uid) $owner_uid = $_SESSION['uid'];
88040f57 2353
37c03d3a 2354 //if (preg_match("/^-?[0-9][0-9]*$/", $feed) != false) {
22fdebff 2355
37c03d3a 2356 if (is_numeric($feed)) {
23aa0d16
AD
2357 if ($cat_view) {
2358
72a2f4f5 2359 if ($feed >= 0) {
f9fca8cb
AD
2360
2361 if ($feed > 0) {
2362 $cat_qpart = "cat_id = '$feed'";
2363 } else {
2364 $cat_qpart = "cat_id IS NULL";
2365 }
8d505d78
AD
2366
2367 $tmp_result = db_query($link, "SELECT id
c7e51de1 2368 FROM ttrss_feeds WHERE $cat_qpart AND owner_uid = $owner_uid");
f9fca8cb
AD
2369
2370 while ($tmp_line = db_fetch_assoc($tmp_result)) {
23aa0d16 2371
f9fca8cb 2372 $tmp_feed = $tmp_line["id"];
23aa0d16 2373
8d505d78
AD
2374 db_query($link, "UPDATE ttrss_user_entries
2375 SET unread = false,last_read = NOW()
c7e51de1 2376 WHERE feed_id = '$tmp_feed' AND owner_uid = $owner_uid");
f9fca8cb
AD
2377 }
2378 } else if ($feed == -2) {
23aa0d16 2379
8d505d78
AD
2380 db_query($link, "UPDATE ttrss_user_entries
2381 SET unread = false,last_read = NOW() WHERE (SELECT COUNT(*)
2382 FROM ttrss_user_labels2 WHERE article_id = ref_id) > 0
c7e51de1 2383 AND unread = true AND owner_uid = $owner_uid");
23aa0d16
AD
2384 }
2385
2386 } else if ($feed > 0) {
2387
8d505d78
AD
2388 db_query($link, "UPDATE ttrss_user_entries
2389 SET unread = false,last_read = NOW()
c7e51de1 2390 WHERE feed_id = '$feed' AND owner_uid = $owner_uid");
8d505d78 2391
23aa0d16
AD
2392 } else if ($feed < 0 && $feed > -10) { // special, like starred
2393
2394 if ($feed == -1) {
8d505d78 2395 db_query($link, "UPDATE ttrss_user_entries
23aa0d16 2396 SET unread = false,last_read = NOW()
c7e51de1 2397 WHERE marked = true AND owner_uid = $owner_uid");
23aa0d16 2398 }
e4f4b46f
AD
2399
2400 if ($feed == -2) {
8d505d78 2401 db_query($link, "UPDATE ttrss_user_entries
e4f4b46f 2402 SET unread = false,last_read = NOW()
c7e51de1 2403 WHERE published = true AND owner_uid = $owner_uid");
e4f4b46f
AD
2404 }
2405
2d24f032
AD
2406 if ($feed == -3) {
2407
c1d7e6c3
AD
2408 $intl = get_pref($link, "FRESH_ARTICLE_MAX_AGE");
2409
2d24f032 2410 if (DB_TYPE == "pgsql") {
8d505d78 2411 $match_part = "updated > NOW() - INTERVAL '$intl hour' ";
2d24f032 2412 } else {
8d505d78 2413 $match_part = "updated > DATE_SUB(NOW(),
c1d7e6c3 2414 INTERVAL $intl HOUR) ";
2d24f032
AD
2415 }
2416
8d505d78 2417 $result = db_query($link, "SELECT id FROM ttrss_entries,
1f3335dc
AD
2418 ttrss_user_entries WHERE $match_part AND
2419 unread = true AND
8d505d78 2420 ttrss_user_entries.ref_id = ttrss_entries.id AND
c7e51de1 2421 owner_uid = $owner_uid");
1f3335dc
AD
2422
2423 $affected_ids = array();
2424
2425 while ($line = db_fetch_assoc($result)) {
2426 array_push($affected_ids, $line["id"]);
2427 }
2428
2429 catchupArticlesById($link, $affected_ids, 0);
2d24f032
AD
2430 }
2431
3584cb11 2432 if ($feed == -4) {
8d505d78 2433 db_query($link, "UPDATE ttrss_user_entries
3584cb11 2434 SET unread = false,last_read = NOW()
c7e51de1 2435 WHERE owner_uid = $owner_uid");
3584cb11
AD
2436 }
2437
23aa0d16
AD
2438 } else if ($feed < -10) { // label
2439
23aa0d16
AD
2440 $label_id = -$feed - 11;
2441
8d505d78
AD
2442 db_query($link, "UPDATE ttrss_user_entries, ttrss_user_labels2
2443 SET unread = false, last_read = NOW()
338c238d 2444 WHERE label_id = '$label_id' AND unread = true
c7e51de1 2445 AND owner_uid = '$owner_uid' AND ref_id = article_id");
23aa0d16 2446
23aa0d16 2447 }
ad0056a8 2448
c7e51de1 2449 ccache_update($link, $feed, $owner_uid, $cat_view);
ad0056a8 2450
23aa0d16
AD
2451 } else { // tag
2452 db_query($link, "BEGIN");
2453
2454 $tag_name = db_escape_string($feed);
2455
2456 $result = db_query($link, "SELECT post_int_id FROM ttrss_tags
c7e51de1 2457 WHERE tag_name = '$tag_name' AND owner_uid = $owner_uid");
23aa0d16
AD
2458
2459 while ($line = db_fetch_assoc($result)) {
2460 db_query($link, "UPDATE ttrss_user_entries SET
8d505d78 2461 unread = false, last_read = NOW()
23aa0d16
AD
2462 WHERE int_id = " . $line["post_int_id"]);
2463 }
2464 db_query($link, "COMMIT");
2465 }
2466 }
2467
4ffa126e 2468 function getAllCounters($link, $omode = "flc", $active_feed = false) {
cf4d339c 2469
e33fe293 2470 if (!$omode) $omode = "flc";
0a6e5382 2471
6a7817c1 2472 $data = getGlobalCounters($link);
8d505d78 2473
6a7817c1
AD
2474 $data = array_merge($data, getVirtCounters($link));
2475
2476 if (strchr($omode, "l")) $data = array_merge($data, getLabelCounters($link));
2477 if (strchr($omode, "f")) $data = array_merge($data, getFeedCounters($link, $active_feed));
2478 if (strchr($omode, "t")) $data = array_merge($data, getTagCounters($link));
798f5a64 2479 if (strchr($omode, "c")) $data = array_merge($data, getCategoryCounters($link));
6a7817c1
AD
2480
2481 return $data;
8d505d78 2482 }
a9cb1f83
AD
2483
2484 function getCategoryCounters($link) {
6a7817c1 2485 $ret_arr = array();
bba7c4bf 2486
6a7817c1 2487 /* Labels category */
bba7c4bf 2488
8acc449c 2489 $cv = array("id" => -2, "kind" => "cat",
6a7817c1 2490 "counter" => getCategoryUnread($link, -2));
bba7c4bf 2491
6a7817c1 2492 array_push($ret_arr, $cv);
bba7c4bf 2493
14073c0a
AD
2494 $age_qpart = getMaxAgeSubquery();
2495
8d505d78
AD
2496 $result = db_query($link, "SELECT id AS cat_id, value AS unread
2497 FROM ttrss_feed_categories, ttrss_cat_counters_cache
2498 WHERE ttrss_cat_counters_cache.feed_id = id AND
31375163 2499 ttrss_feed_categories.owner_uid = " . $_SESSION["uid"]);
a9cb1f83
AD
2500
2501 while ($line = db_fetch_assoc($result)) {
22fdebff 2502 $line["cat_id"] = (int) $line["cat_id"];
8a4c759e 2503
8acc449c 2504 $cv = array("id" => $line["cat_id"], "kind" => "cat",
6a7817c1
AD
2505 "counter" => $line["unread"]);
2506
2507 array_push($ret_arr, $cv);
a9cb1f83 2508 }
d232a40f
AD
2509
2510 /* Special case: NULL category doesn't actually exist in the DB */
2511
9798b2b4 2512 $cv = array("id" => 0, "kind" => "cat",
6a7817c1 2513 "counter" => ccache_find($link, 0, $_SESSION["uid"], true));
d232a40f 2514
6a7817c1
AD
2515 array_push($ret_arr, $cv);
2516
2517 return $ret_arr;
a9cb1f83
AD
2518 }
2519
b6d486a3
AD
2520 function getCategoryUnread($link, $cat, $owner_uid = false) {
2521
2522 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
f295c368 2523
bba7c4bf 2524 if ($cat >= 0) {
18664970 2525
bba7c4bf
AD
2526 if ($cat != 0) {
2527 $cat_query = "cat_id = '$cat'";
2528 } else {
2529 $cat_query = "cat_id IS NULL";
2530 }
14073c0a
AD
2531
2532 $age_qpart = getMaxAgeSubquery();
2533
8d505d78 2534 $result = db_query($link, "SELECT id FROM ttrss_feeds WHERE $cat_query
b6d486a3 2535 AND owner_uid = " . $owner_uid);
8d505d78 2536
bba7c4bf
AD
2537 $cat_feeds = array();
2538 while ($line = db_fetch_assoc($result)) {
2539 array_push($cat_feeds, "feed_id = " . $line["id"]);
2540 }
8d505d78 2541
bba7c4bf 2542 if (count($cat_feeds) == 0) return 0;
8d505d78 2543
bba7c4bf 2544 $match_part = implode(" OR ", $cat_feeds);
8d505d78
AD
2545
2546 $result = db_query($link, "SELECT COUNT(int_id) AS unread
2547 FROM ttrss_user_entries,ttrss_entries
2548 WHERE unread = true AND ($match_part) AND id = ref_id
b6d486a3 2549 AND $age_qpart AND owner_uid = " . $owner_uid);
8d505d78 2550
bba7c4bf 2551 $unread = 0;
8d505d78 2552
bba7c4bf
AD
2553 # this needs to be rewritten
2554 while ($line = db_fetch_assoc($result)) {
2555 $unread += $line["unread"];
2556 }
8d505d78 2557
bba7c4bf
AD
2558 return $unread;
2559 } else if ($cat == -1) {
59e15af4 2560 return getFeedUnread($link, -1) + getFeedUnread($link, -2) + getFeedUnread($link, -3) + getFeedUnread($link, 0);
bba7c4bf 2561 } else if ($cat == -2) {
f295c368 2562
b2531a28 2563 $result = db_query($link, "
8d505d78
AD
2564 SELECT COUNT(unread) AS unread FROM
2565 ttrss_user_entries, ttrss_labels2, ttrss_user_labels2, ttrss_feeds
2566 WHERE label_id = ttrss_labels2.id AND article_id = ref_id AND
b2531a28 2567 ttrss_labels2.owner_uid = '$owner_uid'
117335bf 2568 AND unread = true AND feed_id = ttrss_feeds.id
b2531a28 2569 AND ttrss_user_entries.owner_uid = '$owner_uid'");
ceb30ba4 2570
b2531a28 2571 $unread = db_fetch_result($result, 0, "unread");
f295c368 2572
b2531a28 2573 return $unread;
f295c368 2574
8d505d78 2575 }
f295c368
AD
2576 }
2577
14073c0a
AD
2578 function getMaxAgeSubquery($days = COUNTERS_MAX_AGE) {
2579 if (DB_TYPE == "pgsql") {
8d505d78 2580 return "ttrss_entries.date_updated >
14073c0a
AD
2581 NOW() - INTERVAL '$days days'";
2582 } else {
8d505d78 2583 return "ttrss_entries.date_updated >
14073c0a
AD
2584 DATE_SUB(NOW(), INTERVAL $days DAY)";
2585 }
2586 }
2587
f295c368 2588 function getFeedUnread($link, $feed, $is_cat = false) {
2627f2d0 2589 return getFeedArticles($link, $feed, $is_cat, true, $_SESSION["uid"]);
bdb7369b
AD
2590 }
2591
ceb30ba4
AD
2592 function getLabelUnread($link, $label_id, $owner_uid = false) {
2593 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
2594
2595 $result = db_query($link, "
8d505d78
AD
2596 SELECT COUNT(unread) AS unread FROM
2597 ttrss_user_entries, ttrss_labels2, ttrss_user_labels2, ttrss_feeds
2598 WHERE label_id = ttrss_labels2.id AND article_id = ref_id AND
b0f24af1 2599 ttrss_labels2.owner_uid = '$owner_uid' AND ttrss_labels2.id = '$label_id'
117335bf 2600 AND unread = true AND feed_id = ttrss_feeds.id
933ba4ee 2601 AND ttrss_user_entries.owner_uid = '$owner_uid'");
ceb30ba4
AD
2602
2603 if (db_num_rows($result) != 0) {
2604 return db_fetch_result($result, 0, "unread");
2605 } else {
2606 return 0;
2607 }
2608 }
2609
2627f2d0
AD
2610 function getFeedArticles($link, $feed, $is_cat = false, $unread_only = false,
2611 $owner_uid = false) {
2612
22fdebff 2613 $n_feed = (int) $feed;
f295c368 2614
2627f2d0
AD
2615 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
2616
bdb7369b
AD
2617 if ($unread_only) {
2618 $unread_qpart = "unread = true";
2619 } else {
2620 $unread_qpart = "true";
2621 }
2622
14073c0a
AD
2623 $age_qpart = getMaxAgeSubquery();
2624
f295c368 2625 if ($is_cat) {
8d505d78 2626 return getCategoryUnread($link, $n_feed, $owner_uid);
326469fc
AD
2627 } if ($feed != "0" && $n_feed == 0) {
2628
c5701e70
AD
2629 $feed = db_escape_string($feed);
2630
326469fc 2631 $result = db_query($link, "SELECT SUM((SELECT COUNT(int_id)
8d505d78 2632 FROM ttrss_user_entries,ttrss_entries WHERE int_id = post_int_id
326469fc 2633 AND ref_id = id AND $age_qpart
8d505d78 2634 AND $unread_qpart)) AS count FROM ttrss_tags
326469fc
AD
2635 WHERE owner_uid = $owner_uid AND tag_name = '$feed'");
2636 return db_fetch_result($result, 0, "count");
2637
f295c368 2638 } else if ($n_feed == -1) {
a9cb1f83 2639 $match_part = "marked = true";
e4f4b46f
AD
2640 } else if ($n_feed == -2) {
2641 $match_part = "published = true";
2d24f032 2642 } else if ($n_feed == -3) {
cd2cc43d 2643 $match_part = "unread = true AND score >= 0";
2d24f032 2644
b71e188e 2645 $intl = get_pref($link, "FRESH_ARTICLE_MAX_AGE", $owner_uid);
c1d7e6c3 2646
2d24f032 2647 if (DB_TYPE == "pgsql") {
8d505d78 2648 $match_part .= " AND updated > NOW() - INTERVAL '$intl hour' ";
2d24f032 2649 } else {
7608b38a 2650 $match_part .= " AND updated > DATE_SUB(NOW(), INTERVAL $intl HOUR) ";
2d24f032 2651 }
b2531a28
AD
2652 } else if ($n_feed == -4) {
2653 $match_part = "true";
e04c18a2 2654 } else if ($n_feed >= 0) {
831ff047 2655
6e63a7c3
AD
2656 if ($n_feed != 0) {
2657 $match_part = "feed_id = '$n_feed'";
831ff047 2658 } else {
6e63a7c3 2659 $match_part = "feed_id IS NULL";
831ff047 2660 }
6e63a7c3 2661
a9cb1f83 2662 } else if ($feed < -10) {
318260cc 2663
a9cb1f83
AD
2664 $label_id = -$feed - 11;
2665
ceb30ba4 2666 return getLabelUnread($link, $label_id, $owner_uid);
a9cb1f83 2667
a9cb1f83
AD
2668 }
2669
2670 if ($match_part) {
e04c18a2
AD
2671
2672 if ($n_feed != 0) {
2673 $from_qpart = "ttrss_user_entries,ttrss_feeds,ttrss_entries";
117335bf 2674 $feeds_qpart = "ttrss_user_entries.feed_id = ttrss_feeds.id AND";
e04c18a2
AD
2675 } else {
2676 $from_qpart = "ttrss_user_entries,ttrss_entries";
c3fddd05 2677 $feeds_qpart = '';
e04c18a2
AD
2678 }
2679
8d505d78 2680 $query = "SELECT count(int_id) AS unread
e04c18a2 2681 FROM $from_qpart WHERE
8d505d78 2682 ttrss_user_entries.ref_id = ttrss_entries.id AND
14073c0a 2683 $age_qpart AND
dbfc4365
AD
2684 $feeds_qpart
2685 $unread_qpart AND ($match_part) AND ttrss_user_entries.owner_uid = $owner_uid";
2686
2687 $result = db_query($link, $query);
8d505d78 2688
a9cb1f83 2689 } else {
8d505d78 2690
a9cb1f83 2691 $result = db_query($link, "SELECT COUNT(post_int_id) AS unread
8d505d78
AD
2692 FROM ttrss_tags,ttrss_user_entries,ttrss_entries
2693 WHERE tag_name = '$feed' AND post_int_id = int_id AND ref_id = ttrss_entries.id
bdb7369b 2694 AND $unread_qpart AND $age_qpart AND
2627f2d0 2695 ttrss_tags.owner_uid = " . $owner_uid);
a9cb1f83 2696 }
8d505d78 2697
a9cb1f83 2698 $unread = db_fetch_result($result, 0, "unread");
cfb02131 2699
a9cb1f83
AD
2700 return $unread;
2701 }
2702
f3acc32e
AD
2703 function getGlobalUnread($link, $user_id = false) {
2704
2705 if (!$user_id) {
2706 $user_id = $_SESSION["uid"];
2707 }
2708
8a4c759e
AD
2709 $result = db_query($link, "SELECT SUM(value) AS c_id FROM ttrss_counters_cache
2710 WHERE owner_uid = '$user_id' AND feed_id > 0");
2711
8d505d78 2712 $c_id = db_fetch_result($result, 0, "c_id");
8a4c759e 2713
a9cb1f83
AD
2714 return $c_id;
2715 }
2716
2717 function getGlobalCounters($link, $global_unread = -1) {
6a7817c1
AD
2718 $ret_arr = array();
2719
8d505d78 2720 if ($global_unread == -1) {
a9cb1f83
AD
2721 $global_unread = getGlobalUnread($link);
2722 }
6a7817c1 2723
8d505d78 2724 $cv = array("id" => "global-unread",
6a7817c1
AD
2725 "counter" => $global_unread);
2726
2727 array_push($ret_arr, $cv);
7bf7e4d3 2728
8d505d78 2729 $result = db_query($link, "SELECT COUNT(id) AS fn FROM
7bf7e4d3
AD
2730 ttrss_feeds WHERE owner_uid = " . $_SESSION["uid"]);
2731
2732 $subscribed_feeds = db_fetch_result($result, 0, "fn");
2733
8d505d78 2734 $cv = array("id" => "subscribed-feeds",
6a7817c1 2735 "counter" => $subscribed_feeds);
7bf7e4d3 2736
6a7817c1
AD
2737 array_push($ret_arr, $cv);
2738
2739 return $ret_arr;
a9cb1f83
AD
2740 }
2741
3809b278 2742 function getTagCounters($link) {
8d505d78 2743
6a7817c1 2744 $ret_arr = array();
a9cb1f83 2745
14073c0a
AD
2746 $age_qpart = getMaxAgeSubquery();
2747
8d505d78
AD
2748 $result = db_query($link, "SELECT tag_name,SUM((SELECT COUNT(int_id)
2749 FROM ttrss_user_entries,ttrss_entries WHERE int_id = post_int_id
14073c0a 2750 AND ref_id = id AND $age_qpart
8d505d78
AD
2751 AND unread = true)) AS count FROM ttrss_tags
2752 WHERE owner_uid = ".$_SESSION['uid']." GROUP BY tag_name
ef1ac7c7 2753 ORDER BY count DESC LIMIT 55");
8d505d78 2754
a9cb1f83
AD
2755 $tags = array();
2756
2757 while ($line = db_fetch_assoc($result)) {
2758 $tags[$line["tag_name"]] += $line["count"];
2759 }
2760
2761 foreach (array_keys($tags) as $tag) {
8d505d78 2762 $unread = $tags[$tag];
a9cb1f83 2763 $tag = htmlspecialchars($tag);
6a7817c1
AD
2764
2765 $cv = array("id" => $tag,
8acc449c 2766 "kind" => "tag",
6a7817c1
AD
2767 "counter" => $unread);
2768
2769 array_push($ret_arr, $cv);
2770 }
2771
8d505d78 2772 return $ret_arr;
a9cb1f83
AD
2773 }
2774
6a7817c1 2775 function getVirtCounters($link) {
a9cb1f83 2776
ef393de7 2777 $ret_arr = array();
bdb7369b 2778
e04c18a2 2779 for ($i = 0; $i >= -4; $i--) {
bdb7369b 2780
ceb30ba4 2781 $count = getFeedUnread($link, $i);
6a7817c1
AD
2782
2783 $cv = array("id" => $i,
2abc7af0 2784 "counter" => $count);
8d505d78 2785
296c8134
AD
2786// if (get_pref($link, 'EXTENDED_FEEDLIST'))
2787// $cv["xmsg"] = getFeedArticles($link, $i)." ".__("total");
bdb7369b 2788
6a7817c1 2789 array_push($ret_arr, $cv);
8d505d78 2790 }
0a6e5382
AD
2791
2792 return $ret_arr;
2793 }
2794
11232703 2795 function getLabelCounters($link, $descriptions = false) {
6a7817c1
AD
2796
2797 $ret_arr = array();
0a6e5382
AD
2798
2799 $age_qpart = getMaxAgeSubquery();
2800
3809b278 2801 $owner_uid = $_SESSION["uid"];
bdb7369b 2802
3809b278
AD
2803 $result = db_query($link, "SELECT id, caption FROM ttrss_labels2
2804 WHERE owner_uid = '$owner_uid'");
8d505d78 2805
3809b278 2806 while ($line = db_fetch_assoc($result)) {
2d24f032 2807
3809b278 2808 $id = -$line["id"] - 11;
e4f4b46f 2809
3809b278
AD
2810 $label_name = $line["caption"];
2811 $count = getFeedUnread($link, $id);
3809b278 2812
6a7817c1 2813 $cv = array("id" => $id,
11232703
AD
2814 "counter" => $count);
2815
2816 if ($descriptions)
2817 $cv["description"] = $label_name;
a9cb1f83 2818
296c8134
AD
2819// if (get_pref($link, 'EXTENDED_FEEDLIST'))
2820// $cv["xmsg"] = getFeedArticles($link, $id)." ".__("total");
ef393de7 2821
6a7817c1 2822 array_push($ret_arr, $cv);
3809b278 2823 }
8d505d78 2824
ef393de7 2825 return $ret_arr;
a9cb1f83
AD
2826 }
2827
3809b278 2828 function getFeedCounters($link, $active_feed = false) {
a9cb1f83 2829
6a7817c1
AD
2830 $ret_arr = array();
2831
14073c0a
AD
2832 $age_qpart = getMaxAgeSubquery();
2833
8a4c759e
AD
2834 $query = "SELECT ttrss_feeds.id,
2835 ttrss_feeds.title,
8d505d78 2836 ".SUBSTRING_FOR_DATE."(ttrss_feeds.last_updated,1,19) AS last_updated,
de0a2122
AD
2837 last_error, value AS count
2838 FROM ttrss_feeds, ttrss_counters_cache
8d505d78 2839 WHERE ttrss_feeds.owner_uid = ".$_SESSION["uid"]."
55e01d7e 2840 AND ttrss_counters_cache.feed_id = id";
a9cb1f83 2841
14073c0a 2842 $result = db_query($link, $query);
a9cb1f83
AD
2843 $fctrs_modified = false;
2844
2845 while ($line = db_fetch_assoc($result)) {
8d505d78 2846
a9cb1f83 2847 $id = $line["id"];
de0a2122 2848 $count = $line["count"];
a9cb1f83 2849 $last_error = htmlspecialchars($line["last_error"]);
fb1fb4ab 2850
324944f3 2851 $last_updated = make_local_datetime($link, $line['last_updated'], false);
fb1fb4ab 2852
7defa089 2853 $has_img = feed_has_icon($id);
a9cb1f83 2854
428b704d
AD
2855 if (date('Y') - date('Y', strtotime($line['last_updated'])) > 2)
2856 $last_updated = '';
2857
6a7817c1 2858 $cv = array("id" => $id,
21884958 2859 "updated" => $last_updated,
6a7817c1
AD
2860 "counter" => $count,
2861 "has_img" => (int) $has_img);
a9cb1f83 2862
6a7817c1
AD
2863 if ($last_error)
2864 $cv["error"] = $last_error;
4ffa126e 2865
296c8134
AD
2866// if (get_pref($link, 'EXTENDED_FEEDLIST'))
2867// $cv["xmsg"] = getFeedArticles($link, $id)." ".__("total");
bdb7369b 2868
6a7817c1 2869 if ($active_feed && $id == $active_feed)
fbc95c5b 2870 $cv["title"] = truncate_string($line["title"], 30);
6a7817c1
AD
2871
2872 array_push($ret_arr, $cv);
a9cb1f83 2873
a9cb1f83 2874 }
6a7817c1
AD
2875
2876 return $ret_arr;
a9cb1f83
AD
2877 }
2878
6e7f8d26
AD
2879 function get_pgsql_version($link) {
2880 $result = db_query($link, "SELECT version() AS version");
9949bd15 2881 $version = explode(" ", db_fetch_result($result, 0, "version"));
6e7f8d26
AD
2882 return $version[1];
2883 }
2884
2b8290cd
CW
2885 /**
2886 * Subscribes the user to the given feed
2887 *
2888 * @param resource $link Database connection
2889 * @param string $url Feed URL to subscribe to
2890 * @param integer $cat_id Category ID the feed shall be added to
2891 * @param string $auth_login (optional) Feed username
2892 * @param string $auth_pass (optional) Feed password
2893 *
2894 * @return integer Status code:
2895 * 0 - OK, Feed already exists
2896 * 1 - OK, Feed added
2897 * 2 - Invalid URL
9a8ce956
CW
2898 * 3 - URL content is HTML, no feeds available
2899 * 4 - URL content is HTML which contains multiple feeds.
2900 * Here you should call extractfeedurls in rpc-backend
2901 * to get all possible feeds.
5414ad4c 2902 * 5 - Couldn't download the URL content.
2b8290cd 2903 */
8d505d78 2904 function subscribe_to_feed($link, $url, $cat_id = 0,
f27de515 2905 $auth_login = '', $auth_pass = '') {
bb0f29a4 2906
f0266f51 2907 $url = fix_url($url);
ec39a02c
AD
2908
2909 if (!$url || !validate_feed_url($url)) return 2;
a5819bb3 2910
b3009bcd
AD
2911 $update_method = 0;
2912
8d505d78 2913 $result = db_query($link, "SELECT twitter_oauth FROM ttrss_users
aeaa6991
AD
2914 WHERE id = ".$_SESSION['uid']);
2915
2916 $has_oauth = db_fetch_result($result, 0, 'twitter_oauth');
2917
54a3dd8d 2918 if (!$has_oauth || strpos($url, '://api.twitter.com') === false) {
8d505d78 2919 if (!fetch_file_contents($url, false, $auth_login, $auth_pass)) return 5;
57e24c82 2920
8d505d78
AD
2921 if (url_is_html($url, $auth_login, $auth_pass)) {
2922 $feedUrls = get_feeds_from_html($url, $auth_login, $auth_pass);
57e24c82
AD
2923 if (count($feedUrls) == 0) {
2924 return 3;
2925 } else if (count($feedUrls) > 1) {
2926 return 4;
2927 }
2928 //use feed url as new URL
2929 $url = key($feedUrls);
f6d8345b 2930 }
f6d8345b 2931
57e24c82 2932 } else {
8d505d78 2933 if (!fetch_twitter_rss($link, $url, $_SESSION['uid']))
57e24c82 2934 return 5;
b3009bcd
AD
2935
2936 $update_method = 3;
57e24c82 2937 }
956c7629
AD
2938 if ($cat_id == "0" || !$cat_id) {
2939 $cat_qpart = "NULL";
2940 } else {
2941 $cat_qpart = "'$cat_id'";
2942 }
8d505d78 2943
956c7629 2944 $result = db_query($link,
8d505d78 2945 "SELECT id FROM ttrss_feeds
a5819bb3 2946 WHERE feed_url = '$url' AND owner_uid = ".$_SESSION["uid"]);
8d505d78 2947
956c7629 2948 if (db_num_rows($result) == 0) {
956c7629 2949 $result = db_query($link,
8d505d78
AD
2950 "INSERT INTO ttrss_feeds
2951 (owner_uid,feed_url,title,cat_id, auth_login,auth_pass,update_method)
2952 VALUES ('".$_SESSION["uid"]."', '$url',
b3009bcd 2953 '[Unknown]', $cat_qpart, '$auth_login', '$auth_pass', '$update_method')");
8d505d78 2954
956c7629 2955 $result = db_query($link,
8d505d78 2956 "SELECT id FROM ttrss_feeds WHERE feed_url = '$url'
f27de515 2957 AND owner_uid = " . $_SESSION["uid"]);
8d505d78 2958
956c7629 2959 $feed_id = db_fetch_result($result, 0, "id");
8d505d78 2960
956c7629 2961 if ($feed_id) {
c633e370 2962 update_rss_feed($link, $feed_id, true);
956c7629
AD
2963 }
2964
a5819bb3 2965 return 1;
956c7629 2966 } else {
a5819bb3 2967 return 0;
956c7629
AD
2968 }
2969 }
2970
8d505d78 2971 function print_feed_select($link, $id, $default_id = "",
673d54ca
AD
2972 $attributes = "", $include_all_feeds = true) {
2973
79f3553b 2974 print "<select id=\"$id\" name=\"$id\" $attributes>";
8d505d78 2975 if ($include_all_feeds) {
89cb787e 2976 print "<option value=\"0\">".__('All feeds')."</option>";
673d54ca 2977 }
8d505d78 2978
673d54ca
AD
2979 $result = db_query($link, "SELECT id,title FROM ttrss_feeds
2980 WHERE owner_uid = ".$_SESSION["uid"]." ORDER BY title");
2981
2982 if (db_num_rows($result) > 0 && $include_all_feeds) {
2983 print "<option disabled>--------</option>";
2984 }
2985
2986 while ($line = db_fetch_assoc($result)) {
2987 if ($line["id"] == $default_id) {
10249c41 2988 $is_selected = "selected=\"1\"";
673d54ca
AD
2989 } else {
2990 $is_selected = "";
2991 }
b1710666
AD
2992
2993 $title = truncate_string(htmlspecialchars($line["title"]), 40);
2994
8d505d78 2995 printf("<option $is_selected value='%d'>%s</option>",
b1710666 2996 $line["id"], $title);
673d54ca 2997 }
8d505d78 2998
673d54ca
AD
2999 print "</select>";
3000 }
3001
8d505d78 3002 function print_feed_cat_select($link, $id, $default_id = "",
673d54ca 3003 $attributes = "", $include_all_cats = true) {
8d505d78 3004
5c7c7da9 3005 print "<select id=\"$id\" name=\"$id\" default=\"$default_id\" onchange=\"catSelectOnChange(this)\" $attributes>";
673d54ca
AD
3006
3007 if ($include_all_cats) {
d1db26aa 3008 print "<option value=\"0\">".__('Uncategorized')."</option>";
673d54ca
AD
3009 }
3010
3011 $result = db_query($link, "SELECT id,title FROM ttrss_feed_categories
3012 WHERE owner_uid = ".$_SESSION["uid"]." ORDER BY title");
3013
3014 if (db_num_rows($result) > 0 && $include_all_cats) {
c00907f2 3015 print "<option disabled=\"1\">--------</option>";
673d54ca
AD
3016 }
3017
3018 while ($line = db_fetch_assoc($result)) {
3019 if ($line["id"] == $default_id) {
10249c41 3020 $is_selected = "selected=\"1\"";
673d54ca 3021 } else {
8d505d78 3022 $is_selected = "";
673d54ca 3023 }
c00907f2
AD
3024
3025 if ($line["title"])
8d505d78 3026 printf("<option $is_selected value='%d'>%s</option>",
c00907f2 3027 $line["id"], htmlspecialchars($line["title"]));
673d54ca
AD
3028 }
3029
f9c388f5 3030# print "<option value=\"ADD_CAT\">" .__("Add category...") . "</option>";
5c7c7da9 3031
673d54ca
AD
3032 print "</select>";
3033 }
8d505d78 3034
14f69488
AD
3035 function checkbox_to_sql_bool($val) {
3036 return ($val == "on") ? "true" : "false";
3037 }
86b682ce
AD
3038
3039 function getFeedCatTitle($link, $id) {
3040 if ($id == -1) {
d1db26aa 3041 return __("Special");
86b682ce 3042 } else if ($id < -10) {
d1db26aa 3043 return __("Labels");
86b682ce 3044 } else if ($id > 0) {
8d505d78 3045 $result = db_query($link, "SELECT ttrss_feed_categories.title
86b682ce
AD
3046 FROM ttrss_feeds, ttrss_feed_categories WHERE ttrss_feeds.id = '$id' AND
3047 cat_id = ttrss_feed_categories.id");
3048 if (db_num_rows($result) == 1) {
3049 return db_fetch_result($result, 0, "title");
3050 } else {
d1db26aa 3051 return __("Uncategorized");
86b682ce
AD
3052 }
3053 } else {
3054 return "getFeedCatTitle($id) failed";
3055 }
3056
3057 }
3058
af88c48a
AD
3059 function getFeedIcon($id) {
3060 switch ($id) {
4bee8b5f
AD
3061 case 0:
3062 return "images/archive.png";
3063 break;
af88c48a 3064 case -1:
f65ffc2d 3065 return "images/mark_set.png";
af88c48a
AD
3066 break;
3067 case -2:
b97e6e02 3068 return "images/pub_set.png";
af88c48a
AD
3069 break;
3070 case -3:
3071 return "images/fresh.png";
3072 break;
3073 case -4:
3074 return "images/tag.png";
3075 break;
3076 default:
4bee8b5f
AD
3077 if ($id < -10) {
3078 return "images/label.png";
3079 } else {
8d505d78 3080 if (file_exists(ICONS_DIR . "/$id.ico"))
e2eda979 3081 return ICONS_URL . "/$id.ico";
4bee8b5f 3082 }
af88c48a
AD
3083 break;
3084 }
3085 }
3086
86b682ce
AD
3087 function getFeedTitle($link, $id) {
3088 if ($id == -1) {
d1db26aa 3089 return __("Starred articles");
945c243e
AD
3090 } else if ($id == -2) {
3091 return __("Published articles");
2d24f032
AD
3092 } else if ($id == -3) {
3093 return __("Fresh articles");
b2531a28
AD
3094 } else if ($id == -4) {
3095 return __("All articles");
80db1113 3096 } else if ($id === 0 || $id === "0") {
e04c18a2 3097 return __("Archived articles");
86b682ce 3098 } else if ($id < -10) {
76626c72 3099 $label_id = -$id - 11;
ceb30ba4 3100 $result = db_query($link, "SELECT caption FROM ttrss_labels2 WHERE id = '$label_id'");
86b682ce 3101 if (db_num_rows($result) == 1) {
ceb30ba4 3102 return db_fetch_result($result, 0, "caption");
86b682ce
AD
3103 } else {
3104 return "Unknown label ($label_id)";
3105 }
3106
147f5632 3107 } else if (is_numeric($id) && $id > 0) {
86b682ce
AD
3108 $result = db_query($link, "SELECT title FROM ttrss_feeds WHERE id = '$id'");
3109 if (db_num_rows($result) == 1) {
3110 return db_fetch_result($result, 0, "title");
3111 } else {
3112 return "Unknown feed ($id)";
3113 }
3114 } else {
22fdebff 3115 return $id;
86b682ce 3116 }
86b682ce 3117 }
3dd46f19 3118
d8221301 3119 function make_init_params($link) {
f1f3a642 3120 $params = array();
c9268ed5 3121
c4f7ba80
AD
3122 $params["theme"] = get_user_theme($link);
3123 $params["theme_options"] = get_user_theme_options($link);
f6d6e22f 3124
c4f7ba80
AD
3125 $params["sign_progress"] = theme_image($link, "images/indicator_white.gif");
3126 $params["sign_progress_tiny"] = theme_image($link, "images/indicator_tiny.gif");
3127 $params["sign_excl"] = theme_image($link, "images/sign_excl.png");
3128 $params["sign_info"] = theme_image($link, "images/sign_info.png");
be0801a1 3129
f1f3a642
AD
3130 foreach (array("ON_CATCHUP_SHOW_NEXT_FEED", "HIDE_READ_FEEDS",
3131 "ENABLE_FEED_CATS", "FEEDS_SORT_BY_UNREAD", "CONFIRM_FEED_CATCHUP",
7d12b6c8 3132 "CDM_AUTO_CATCHUP", "FRESH_ARTICLE_MAX_AGE", "DEFAULT_ARTICLE_LIMIT",
30b6ee8c 3133 "HIDE_READ_SHOWS_SPECIAL", "COMBINED_DISPLAY_MODE") as $param) {
40496720 3134
c4f7ba80 3135 $params[strtolower($param)] = (int) get_pref($link, $param);
f1f3a642 3136 }
40496720 3137
c4f7ba80
AD
3138 $params["icons_url"] = ICONS_URL;
3139 $params["cookie_lifetime"] = SESSION_COOKIE_LIFETIME;
3140 $params["default_view_mode"] = get_pref($link, "_DEFAULT_VIEW_MODE");
3141 $params["default_view_limit"] = (int) get_pref($link, "_DEFAULT_VIEW_LIMIT");
3142 $params["default_view_order_by"] = get_pref($link, "_DEFAULT_VIEW_ORDER_BY");
c4f7ba80 3143 $params["bw_limit"] = (int) $_SESSION["bw_limit"];
59b223d7 3144
8cd576a1 3145 $result = db_query($link, "SELECT MAX(id) AS mid, COUNT(*) AS nf FROM
9b7ecc0a
AD
3146 ttrss_feeds WHERE owner_uid = " . $_SESSION["uid"]);
3147
8cd576a1
AD
3148 $max_feed_id = db_fetch_result($result, 0, "mid");
3149 $num_feeds = db_fetch_result($result, 0, "nf");
9b7ecc0a 3150
8cd576a1 3151 $params["max_feed_id"] = (int) $max_feed_id;
c4f7ba80 3152 $params["num_feeds"] = (int) $num_feeds;
8cd576a1 3153
c4f7ba80 3154 $params["collapsed_feedlist"] = (int) get_pref($link, "_COLLAPSED_FEEDLIST");
9b7ecc0a 3155
d8221301 3156 return $params;
3ac2b520 3157 }
f54f515f 3158
c4f7ba80 3159 function make_runtime_info($link) {
8cd576a1
AD
3160 $data = array();
3161
3162 $result = db_query($link, "SELECT MAX(id) AS mid, COUNT(*) AS nf FROM
9b7ecc0a
AD
3163 ttrss_feeds WHERE owner_uid = " . $_SESSION["uid"]);
3164
8cd576a1
AD
3165 $max_feed_id = db_fetch_result($result, 0, "mid");
3166 $num_feeds = db_fetch_result($result, 0, "nf");
9b7ecc0a 3167
8cd576a1
AD
3168 $data["max_feed_id"] = (int) $max_feed_id;
3169 $data["num_feeds"] = (int) $num_feeds;
c4f7ba80 3170
f8fb4498 3171 $data['last_article_id'] = getLastArticleId($link);
5ae8f858 3172 $data['cdm_expanded'] = get_pref($link, 'CDM_EXPANDED');
f8fb4498 3173
dbaa4e4a 3174 if (file_exists(LOCK_DIRECTORY . "/update_daemon.lock")) {
c4f7ba80
AD
3175
3176 $data['daemon_is_running'] = (int) file_is_locked("update_daemon.lock");
8e00ae9b 3177
9041f58b 3178 if (time() - $_SESSION["daemon_stamp_check"] > 30) {
8e00ae9b 3179
fb074239 3180 $stamp = (int) @file_get_contents(LOCK_DIRECTORY . "/update_daemon.stamp");
fbae93d8 3181
8e00ae9b 3182 if ($stamp) {
9041f58b
AD
3183 $stamp_delta = time() - $stamp;
3184
3185 if ($stamp_delta > 1800) {
f6854e44 3186 $stamp_check = 0;
8e00ae9b 3187 } else {
f6854e44
AD
3188 $stamp_check = 1;
3189 $_SESSION["daemon_stamp_check"] = time();
8e00ae9b
AD
3190 }
3191
c4f7ba80 3192 $data['daemon_stamp_ok'] = $stamp_check;
f6854e44 3193
8e00ae9b
AD
3194 $stamp_fmt = date("Y.m.d, G:i", $stamp);
3195
c4f7ba80 3196 $data['daemon_stamp'] = $stamp_fmt;
8e00ae9b 3197 }
8e00ae9b 3198 }
71ad883b 3199 }
8e00ae9b 3200
63855db1 3201 if ($_SESSION["last_version_check"] + 86400 + rand(-1000, 1000) < time()) {
fb074239 3202 $new_version_details = @check_for_update($link);
d9fa39f1 3203
63855db1 3204 $data['new_version_available'] = (int) ($new_version_details != false);
d9fa39f1
AD
3205
3206 $_SESSION["last_version_check"] = time();
d9fa39f1
AD
3207 }
3208
c4f7ba80 3209 return $data;
f54f515f 3210 }
ef393de7 3211
b7d1a163 3212 function search_to_sql($link, $search, $match_on) {
ef393de7 3213
88040f57 3214 $search_query_part = "";
e20c9d88 3215
9949bd15 3216 $keywords = explode(" ", $search);
88040f57 3217 $query_keywords = array();
e20c9d88 3218
ab4b768f
AD
3219 foreach ($keywords as $k) {
3220 if (strpos($k, "-") === 0) {
3221 $k = substr($k, 1);
3222 $not = "NOT";
3223 } else {
3224 $not = "";
88040f57 3225 }
e20c9d88 3226
9949bd15 3227 $commandpair = explode(":", mb_strtolower($k), 2);
53003548
AD
3228
3229 if ($commandpair[0] == "note" && $commandpair[1]) {
3230
3231 if ($commandpair[1] == "true")
3232 array_push($query_keywords, "($not (note IS NOT NULL AND note != ''))");
3233 else
3234 array_push($query_keywords, "($not (note IS NULL OR note = ''))");
3235
3236 } else if ($commandpair[0] == "star" && $commandpair[1]) {
3237
3238 if ($commandpair[1] == "true")
3239 array_push($query_keywords, "($not (marked = true))");
3240 else
3241 array_push($query_keywords, "($not (marked = false))");
3242
3243 } else if ($commandpair[0] == "pub" && $commandpair[1]) {
3244
3245 if ($commandpair[1] == "true")
3246 array_push($query_keywords, "($not (published = true))");
3247 else
3248 array_push($query_keywords, "($not (published = false))");
3249
3250 } else if (strpos($k, "@") === 0) {
e20c9d88 3251
ab4b768f
AD
3252 $user_tz_string = get_pref($link, 'USER_TIMEZONE', $_SESSION['uid']);
3253 $orig_ts = strtotime(substr($k, 1));
ab4b768f 3254 $k = date("Y-m-d", convert_timestamp($orig_ts, $user_tz_string, 'UTC'));
8d505d78 3255
53003548
AD
3256 //$k = date("Y-m-d", strtotime(substr($k, 1)));
3257
ab4b768f
AD
3258 array_push($query_keywords, "(".SUBSTRING_FOR_DATE."(updated,1,LENGTH('$k')) $not = '$k')");
3259 } else if ($match_on == "both") {
3260 array_push($query_keywords, "(UPPER(ttrss_entries.title) $not LIKE UPPER('%$k%')
3261 OR UPPER(ttrss_entries.content) $not LIKE UPPER('%$k%'))");
3262 } else if ($match_on == "title") {
eb6c7f42 3263 array_push($query_keywords, "(UPPER(ttrss_entries.title) $not LIKE UPPER('%$k%'))");
ab4b768f 3264 } else if ($match_on == "content") {
eb6c7f42 3265 array_push($query_keywords, "(UPPER(ttrss_entries.content) $not LIKE UPPER('%$k%'))");
88040f57
AD
3266 }
3267 }
3268
3269 $search_query_part = implode("AND", $query_keywords);
3270
3271 return $search_query_part;
3272 }
3273
147f5632 3274
97e5dbb2 3275 function queryFeedHeadlines($link, $feed, $limit, $view_mode, $cat_view, $search, $search_mode, $match_on, $override_order = false, $offset = 0, $owner_uid = 0, $filter = false, $since_id = 0) {
c36bf4d5
AD
3276
3277 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
c1a0b534 3278
c3fddd05
AD
3279 $ext_tables_part = "";
3280
88040f57 3281 if ($search) {
e4f7f8df
AD
3282
3283 if (SPHINX_ENABLED) {
3284 $ids = join(",", @sphinx_search($search, 0, 500));
3285
8d505d78 3286 if ($ids)
e4f7f8df
AD
3287 $search_query_part = "ref_id IN ($ids) AND ";
3288 else
3289 $search_query_part = "ref_id = -1 AND ";
3290
3291 } else {
b7d1a163 3292 $search_query_part = search_to_sql($link, $search, $match_on);
e4f7f8df 3293 $search_query_part .= " AND ";
8d505d78 3294 }
e20c9d88 3295
ef393de7
AD
3296 } else {
3297 $search_query_part = "";
3298 }
3299
36184020
AD
3300 if ($filter) {
3301 $filter_query_part = filter_to_sql($filter);
3302 } else {
3303 $filter_query_part = "";
3304 }
3305
97e5dbb2
AD
3306 if ($since_id) {
3307 $since_id_part = "ttrss_entries.id > $since_id AND ";
3308 } else {
3309 $since_id_part = "";
3310 }
3311
ef393de7 3312 $view_query_part = "";
8d505d78 3313
7b4d02a8 3314 if ($view_mode == "adaptive" || $view_query_part == "noscores") {
ef393de7
AD
3315 if ($search) {
3316 $view_query_part = " ";
3317 } else if ($feed != -1) {
f295c368 3318 $unread = getFeedUnread($link, $feed, $cat_view);
ef393de7 3319 if ($unread > 0) {
ff863e00 3320 $view_query_part = " unread = true AND ";
ef393de7
AD
3321 }
3322 }
3323 }
8d505d78 3324
ef393de7
AD
3325 if ($view_mode == "marked") {
3326 $view_query_part = " marked = true AND ";
3327 }
23d72f39
AD
3328
3329 if ($view_mode == "published") {
3330 $view_query_part = " published = true AND ";
3331 }
3332
ef393de7
AD
3333 if ($view_mode == "unread") {
3334 $view_query_part = " unread = true AND ";
3335 }
8b09eac8
AD
3336
3337 if ($view_mode == "updated") {
3338 $view_query_part = " (last_read is null and unread = false) AND ";
3339 }
3340
ef393de7
AD
3341 if ($limit > 0) {
3342 $limit_query_part = "LIMIT " . $limit;
8d505d78 3343 }
ef393de7
AD
3344
3345 $vfeed_query_part = "";
8d505d78 3346
ef393de7
AD
3347 // override query strategy and enable feed display when searching globally
3348 if ($search && $search_mode == "all_feeds") {
3349 $query_strategy_part = "ttrss_entries.id > 0";
8d505d78 3350 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
22fdebff 3351 /* tags */
ef393de7
AD
3352 } else if (preg_match("/^-?[0-9][0-9]*$/", $feed) == false) {
3353 $query_strategy_part = "ttrss_entries.id > 0";
3354 $vfeed_query_part = "(SELECT title FROM ttrss_feeds WHERE
3355 id = feed_id) as feed_title,";
e04c18a2 3356 } else if ($feed > 0 && $search && $search_mode == "this_cat") {
8d505d78
AD
3357
3358 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
0a6c4846
AD
3359
3360 $tmp_result = false;
3361
3362 if ($cat_view) {
8d505d78 3363 $tmp_result = db_query($link, "SELECT id
0a6c4846
AD
3364 FROM ttrss_feeds WHERE cat_id = '$feed'");
3365 } else {
3366 $tmp_result = db_query($link, "SELECT id
8d505d78 3367 FROM ttrss_feeds WHERE cat_id = (SELECT cat_id FROM ttrss_feeds
0a6c4846
AD
3368 WHERE id = '$feed') AND id != '$feed'");
3369 }
8d505d78 3370
ef393de7 3371 $cat_siblings = array();
8d505d78 3372
ef393de7
AD
3373 if (db_num_rows($tmp_result) > 0) {
3374 while ($p = db_fetch_assoc($tmp_result)) {
3375 array_push($cat_siblings, "feed_id = " . $p["id"]);
3376 }
8d505d78
AD
3377
3378 $query_strategy_part = sprintf("(feed_id = %d OR %s)",
ef393de7 3379 $feed, implode(" OR ", $cat_siblings));
8d505d78 3380
ef393de7
AD
3381 } else {
3382 $query_strategy_part = "ttrss_entries.id > 0";
3383 }
8d505d78 3384
e04c18a2 3385 } else if ($feed > 0) {
8d505d78 3386
ef393de7 3387 if ($cat_view) {
5c365f60 3388
ef393de7
AD
3389 if ($feed > 0) {
3390 $query_strategy_part = "cat_id = '$feed'";
3391 } else {
3392 $query_strategy_part = "cat_id IS NULL";
3393 }
8d505d78 3394
ef393de7 3395 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
5c365f60 3396
8d505d78 3397 } else {
6e63a7c3 3398 $query_strategy_part = "feed_id = '$feed'";
ef393de7 3399 }
bfe5ddfc 3400 } else if ($feed == 0 && !$cat_view) { // archive virtual feed
e04c18a2 3401 $query_strategy_part = "feed_id IS NULL";
bfe5ddfc
AD
3402 } else if ($feed == 0 && $cat_view) { // uncategorized
3403 $query_strategy_part = "cat_id IS NULL";
3404 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
ef393de7
AD
3405 } else if ($feed == -1) { // starred virtual feed
3406 $query_strategy_part = "marked = true";
3407 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
e6a38cde
AD
3408 } else if ($feed == -2) { // published virtual feed OR labels category
3409
3410 if (!$cat_view) {
3411 $query_strategy_part = "published = true";
3412 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
3413 } else {
3414 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
3415
3416 $ext_tables_part = ",ttrss_labels2,ttrss_user_labels2";
8d505d78 3417
e6a38cde
AD
3418 $query_strategy_part = "ttrss_labels2.id = ttrss_user_labels2.label_id AND
3419 ttrss_user_labels2.article_id = ref_id";
3420
3421 }
3422
2d24f032 3423 } else if ($feed == -3) { // fresh virtual feed
cd2cc43d 3424 $query_strategy_part = "unread = true AND score >= 0";
2d24f032 3425
7a22dc2a 3426 $intl = get_pref($link, "FRESH_ARTICLE_MAX_AGE", $owner_uid);
c1d7e6c3 3427
2d24f032 3428 if (DB_TYPE == "pgsql") {
8d505d78 3429 $query_strategy_part .= " AND updated > NOW() - INTERVAL '$intl hour' ";
2d24f032 3430 } else {
7608b38a 3431 $query_strategy_part .= " AND updated > DATE_SUB(NOW(), INTERVAL $intl HOUR) ";
2d24f032
AD
3432 }
3433
b2531a28
AD
3434 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
3435 } else if ($feed == -4) { // all articles virtual feed
3436 $query_strategy_part = "true";
e4f4b46f 3437 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
ef393de7
AD
3438 } else if ($feed <= -10) { // labels
3439 $label_id = -$feed - 11;
3de0261a 3440
ceb30ba4
AD
3441 $query_strategy_part = "label_id = '$label_id' AND
3442 ttrss_labels2.id = ttrss_user_labels2.label_id AND
3443 ttrss_user_labels2.article_id = ref_id";
3de0261a 3444
ef393de7 3445 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
ceb30ba4 3446 $ext_tables_part = ",ttrss_labels2,ttrss_user_labels2";
8d505d78 3447
ef393de7
AD
3448 } else {
3449 $query_strategy_part = "id > 0"; // dumb
3450 }
d6e5706d 3451
b3990c92
AD
3452 if (get_pref($link, "SORT_HEADLINES_BY_FEED_DATE", $owner_uid)) {
3453 $date_sort_field = "updated";
3454 } else {
3455 $date_sort_field = "date_entered";
3456 }
3457
7a22dc2a 3458 if (get_pref($link, 'REVERSE_HEADLINES', $owner_uid)) {
b3990c92 3459 $order_by = "$date_sort_field";
8d505d78 3460 } else {
b3990c92 3461 $order_by = "$date_sort_field DESC";
d6e5706d 3462 }
e939722a 3463
7b4d02a8
AD
3464 if ($view_mode != "noscores") {
3465 $order_by = "score DESC, $order_by";
3466 }
48b0c4ec 3467
e939722a
AD
3468 if ($override_order) {
3469 $order_by = $override_order;
3470 }
8d505d78 3471
ef393de7
AD
3472 $feed_title = "";
3473
22fdebff
AD
3474 if ($search) {
3475 $feed_title = "Search results";
3476 } else {
ef393de7 3477 if ($cat_view) {
22fdebff 3478 $feed_title = getCategoryTitle($link, $feed);
ef393de7 3479 } else {
147f5632 3480 if (is_numeric($feed) && $feed > 0) {
8d505d78 3481 $result = db_query($link, "SELECT title,site_url,last_error
22fdebff 3482 FROM ttrss_feeds WHERE id = '$feed' AND owner_uid = $owner_uid");
8d505d78 3483
22fdebff
AD
3484 $feed_title = db_fetch_result($result, 0, "title");
3485 $feed_site_url = db_fetch_result($result, 0, "site_url");
3486 $last_error = db_fetch_result($result, 0, "last_error");
3487 } else {
3488 $feed_title = getFeedTitle($link, $feed);
8d505d78 3489 }
88040f57 3490 }
ef393de7
AD
3491 }
3492
62129e67
AD
3493 $content_query_part = "content as content_preview,";
3494
ef393de7 3495 if (preg_match("/^-?[0-9][0-9]*$/", $feed) != false) {
8d505d78 3496
ef393de7
AD
3497 if ($feed >= 0) {
3498 $feed_kind = "Feeds";
3499 } else {
3500 $feed_kind = "Labels";
3501 }
8d505d78 3502
95a82c08
AD
3503 if ($limit_query_part) {
3504 $offset_query_part = "OFFSET $offset";
3505 }
3506
d00f22ac 3507 if ($vfeed_query_part && get_pref($link, 'VFEED_GROUP_BY_FEED', $owner_uid)) {
6cfea5c7 3508 if (!$override_order) {
8d505d78 3509 $order_by = "ttrss_feeds.title, $order_by";
43fc671f 3510 }
6cfea5c7
AD
3511 }
3512
e04c18a2
AD
3513 if ($feed != "0") {
3514 $from_qpart = "ttrss_entries,ttrss_user_entries,ttrss_feeds$ext_tables_part";
117335bf 3515 $feed_check_qpart = "ttrss_user_entries.feed_id = ttrss_feeds.id AND";
e04c18a2
AD
3516
3517 } else {
3518 $from_qpart = "ttrss_entries,ttrss_user_entries$ext_tables_part
3519 LEFT JOIN ttrss_feeds ON (feed_id = ttrss_feeds.id)";
3520 }
3521
8d505d78 3522 $query = "SELECT DISTINCT
f9b2d27c 3523 date_entered,
1f64b1be 3524 guid,
ef393de7 3525 ttrss_entries.id,ttrss_entries.title,
46921916 3526 updated,
9c506873
AD
3527 label_cache,
3528 tag_cache,
c0644ee4 3529 always_display_enclosures,
d1fc2f92 3530 site_url,
c7e51de1 3531 note,
13992673
AD
3532 num_comments,
3533 comments,
db16ae50 3534 int_id,
494a64ea 3535 unread,feed_id,marked,published,link,last_read,orig_feed_id,
fc2b26a6 3536 ".SUBSTRING_FOR_DATE."(last_read,1,19) as last_read_noms,
ef393de7
AD
3537 $vfeed_query_part
3538 $content_query_part
fc2b26a6 3539 ".SUBSTRING_FOR_DATE."(updated,1,19) as updated_noms,
ff6e357a 3540 author,score
ef393de7 3541 FROM
e04c18a2 3542 $from_qpart
ef393de7 3543 WHERE
e04c18a2 3544 $feed_check_qpart
ef393de7 3545 ttrss_user_entries.ref_id = ttrss_entries.id AND
c36bf4d5 3546 ttrss_user_entries.owner_uid = '$owner_uid' AND
ef393de7 3547 $search_query_part
36184020 3548 $filter_query_part
ef393de7 3549 $view_query_part
97e5dbb2 3550 $since_id_part
ef393de7 3551 $query_strategy_part ORDER BY $order_by
95a82c08 3552 $limit_query_part $offset_query_part";
4bc311fc 3553
b4e75b2a 3554 if ($_REQUEST["debug"]) print $query;
4bc311fc
AD
3555
3556 $result = db_query($link, $query);
8d505d78 3557
ef393de7
AD
3558 } else {
3559 // browsing by tag
8d505d78 3560
147f5632
CM
3561 $select_qpart = "SELECT DISTINCT " .
3562 "date_entered," .
3563 "guid," .
3564 "note," .
3565 "ttrss_entries.id as id," .
3566 "title," .
3567 "updated," .
3568 "unread," .
3569 "feed_id," .
3570 "orig_feed_id," .
d1fc2f92
AD
3571 "site_url," .
3572 "always_display_enclosures, ".
147f5632 3573 "marked," .
d1fc2f92
AD
3574 "num_comments, " .
3575 "comments, " .
c0644ee4
AD
3576 "tag_cache," .
3577 "label_cache," .
147f5632
CM
3578 "link," .
3579 "last_read," .
3580 SUBSTRING_FOR_DATE . "(last_read,1,19) as last_read_noms," .
97e5dbb2 3581 $since_id_part .
147f5632
CM
3582 $vfeed_query_part .
3583 $content_query_part .
3584 SUBSTRING_FOR_DATE . "(updated,1,19) as updated_noms," .
3585 "score ";
3586
ef393de7 3587 $feed_kind = "Tags";
147f5632
CM
3588 $all_tags = explode(",", $feed);
3589 if ($search_mode == 'any') {
3590 $tag_sql = "tag_name in (" . implode(", ", array_map("db_quote", $all_tags)) . ")";
3591 $from_qpart = " FROM ttrss_entries,ttrss_user_entries,ttrss_tags ";
3592 $where_qpart = " WHERE " .
3593 "ref_id = ttrss_entries.id AND " .
3594 "ttrss_user_entries.owner_uid = $owner_uid AND " .
3595 "post_int_id = int_id AND $tag_sql AND " .
3596 $view_query_part .
3597 $search_query_part .
3598 $query_strategy_part . " ORDER BY $order_by " .
3599 $limit_query_part;
8d505d78 3600
147f5632
CM
3601 } else {
3602 $i = 1;
3603 $sub_selects = array();
3604 $sub_ands = array();
3605 foreach ($all_tags as $term) {
3606 array_push($sub_selects, "(SELECT post_int_id from ttrss_tags WHERE tag_name = " . db_quote($term) . " AND owner_uid = $owner_uid) as A$i");
3607 $i++;
3608 }
3609 if ($i > 2) {
3610 $x = 1;
3611 $y = 2;
3612 do {
3613 array_push($sub_ands, "A$x.post_int_id = A$y.post_int_id");
3614 $x++;
3615 $y++;
3616 } while ($y < $i);
3617 }
3618 array_push($sub_ands, "A1.post_int_id = ttrss_user_entries.int_id and ttrss_user_entries.owner_uid = $owner_uid");
3619 array_push($sub_ands, "ttrss_user_entries.ref_id = ttrss_entries.id");
3620 $from_qpart = " FROM " . implode(", ", $sub_selects) . ", ttrss_user_entries, ttrss_entries";
3621 $where_qpart = " WHERE " . implode(" AND ", $sub_ands);
3622 }
3623 // error_log("TAG SQL: " . $tag_sql);
3624 // $tag_sql = "tag_name = '$feed'"; DEFAULT way
3625
3626 // error_log("[". $select_qpart . "][" . $from_qpart . "][" .$where_qpart . "]");
3627 $result = db_query($link, $select_qpart . $from_qpart . $where_qpart);
ef393de7
AD
3628 }
3629
c7188969 3630 return array($result, $feed_title, $feed_site_url, $last_error);
8d505d78 3631
ef393de7
AD
3632 }
3633
c36bf4d5 3634 function generate_syndicated_feed($link, $owner_uid, $feed, $is_cat,
23d72f39 3635 $limit, $search, $search_mode, $match_on, $view_mode = false) {
ead2715d 3636
20e43935
AD
3637 require_once "lib/MiniTemplator.class.php";
3638
fcfa9ef1
AD
3639 $note_style = "background-color : #fff7d5;
3640 border-width : 1px; ".
c7e51de1 3641 "padding : 5px; border-style : dashed; border-color : #e7d796;".
db54143e 3642 "margin-bottom : 1em; color : #9a8c59;";
c7e51de1 3643
ead2715d 3644 if (!$limit) $limit = 30;
18664970 3645
b3990c92
AD
3646 if (get_pref($link, "SORT_HEADLINES_BY_FEED_DATE", $owner_uid)) {
3647 $date_sort_field = "updated";
3648 } else {
3649 $date_sort_field = "date_entered";
3650 }
3651
8d505d78
AD
3652 $qfh_ret = queryFeedHeadlines($link, $feed,
3653 $limit, $view_mode, $is_cat, $search, $search_mode,
b3990c92 3654 $match_on, "$date_sort_field DESC", 0, $owner_uid);
18664970
AD
3655
3656 $result = $qfh_ret[0];
59e2aab4 3657 $feed_title = htmlspecialchars($qfh_ret[1]);
18664970
AD
3658 $feed_site_url = $qfh_ret[2];
3659 $last_error = $qfh_ret[3];
3660
20e43935 3661 $feed_self_url = get_self_url_prefix() .
e0d91d84 3662 "/public.php?op=rss&id=-2&key=" .
20e43935
AD
3663 get_feed_access_key($link, -2, false);
3664
b0f379df 3665 if (!$feed_site_url) $feed_site_url = get_self_url_prefix();
4bc64807 3666
20e43935
AD
3667 $tpl = new MiniTemplator;
3668
3669 $tpl->readTemplateFromFile("templates/generated_feed.txt");
b0f379df 3670
20e43935
AD
3671 $tpl->setVariable('FEED_TITLE', $feed_title);
3672 $tpl->setVariable('VERSION', VERSION);
3673 $tpl->setVariable('FEED_URL', htmlspecialchars($feed_self_url));
3674
364e3c85 3675 if (PUBSUBHUBBUB_HUB && $feed == -2) {
20e43935
AD
3676 $tpl->setVariable('HUB_URL', htmlspecialchars(PUBSUBHUBBUB_HUB));
3677 $tpl->addBlock('feed_hub');
b0f379df
AD
3678 }
3679
20e43935 3680 $tpl->setVariable('SELF_URL', htmlspecialchars(get_self_url_prefix()));
8d505d78 3681
3baeeeca 3682 while ($line = db_fetch_assoc($result)) {
20e43935
AD
3683 $tpl->setVariable('ARTICLE_ID', htmlspecialchars($line['link']));
3684 $tpl->setVariable('ARTICLE_LINK', htmlspecialchars($line['link']));
3685 $tpl->setVariable('ARTICLE_TITLE', htmlspecialchars($line['title']));
3686 $tpl->setVariable('ARTICLE_EXCERPT',
3687 truncate_string(strip_tags($line["content_preview"]), 100, '...'));
9b1a7081
AD
3688
3689 $content = sanitize_rss($link, $line["content_preview"], false, $owner_uid);
3690
3691 if ($line['note']) {
fcfa9ef1 3692 $content = "<div style=\"$note_style\">Article note: " . $line['note'] . "</div>" .
9b1a7081
AD
3693 $content;
3694 }
3695
3696 $tpl->setVariable('ARTICLE_CONTENT', $content);
20e43935
AD
3697
3698 $tpl->setVariable('ARTICLE_UPDATED', date('c', strtotime($line["updated"])));
3699 $tpl->setVariable('ARTICLE_AUTHOR', htmlspecialchars($line['author']));
0c3d1c68 3700
bc976a8c 3701 $tags = get_article_tags($link, $line["id"], $owner_uid);
0c3d1c68
AD
3702
3703 foreach ($tags as $tag) {
20e43935
AD
3704 $tpl->setVariable('ARTICLE_CATEGORY', htmlspecialchars($tag));
3705 $tpl->addBlock('category');
2f0903a6 3706 }
8d505d78 3707
c7845467
AD
3708 $enclosures = get_article_enclosures($link, $line["id"]);
3709
3710 foreach ($enclosures as $e) {
3711 $type = htmlspecialchars($e['content_type']);
3712 $url = htmlspecialchars($e['content_url']);
3713 $length = $e['duration'];
20e43935
AD
3714
3715 $tpl->setVariable('ARTICLE_ENCLOSURE_URL', $url);
3716 $tpl->setVariable('ARTICLE_ENCLOSURE_TYPE', $type);
3717 $tpl->setVariable('ARTICLE_ENCLOSURE_LENGTH', $length);
3718
3719 $tpl->addBlock('enclosure');
c7845467
AD
3720 }
3721
20e43935
AD
3722 $tpl->addBlock('entry');
3723 }
3724
3725 $tmp = "";
8d505d78 3726
20e43935
AD
3727 $tpl->addBlock('feed');
3728 $tpl->generateOutputToString($tmp);
18664970 3729
20e43935 3730 print $tmp;
18664970
AD
3731 }
3732
0a6c4846
AD
3733 function getCategoryTitle($link, $cat_id) {
3734
bba7c4bf
AD
3735 if ($cat_id == -1) {
3736 return __("Special");
3737 } else if ($cat_id == -2) {
3738 return __("Labels");
0a6c4846 3739 } else {
bba7c4bf
AD
3740
3741 $result = db_query($link, "SELECT title FROM ttrss_feed_categories WHERE
3742 id = '$cat_id'");
3743
3744 if (db_num_rows($result) == 1) {
3745 return db_fetch_result($result, 0, "title");
3746 } else {
3747 return "Uncategorized";
3748 }
0a6c4846
AD
3749 }
3750 }
3751
8cc3c778 3752 function sanitize_rss($link, $str, $force_strip_tags = false, $owner = false, $site_url = false) {
35ffb5b9 3753 global $purifier;
8cc3c778 3754
ceb0cab5
AD
3755 if (!$owner) $owner = $_SESSION["uid"];
3756
96811a55
AD
3757 $res = trim($str); if (!$res) return '';
3758
31303c6b
AD
3759 // create global Purifier object if needed
3760 if (!$purifier) {
3761 require_once 'lib/htmlpurifier/library/HTMLPurifier.auto.php';
3762
3763 $config = HTMLPurifier_Config::createDefault();
3764
3765 $allowed = "p,a[href],i,em,b,strong,code,pre,blockquote,br,img[src|alt|title],ul,ol,li,h1,h2,h3,h4,s,object[classid|type|id|name|width|height|codebase],param[name|value],table,tr,td";
3766
3767 $config->set('HTML.SafeObject', true);
3768 @$config->set('HTML', 'Allowed', $allowed);
3769 $config->set('Output.FlashCompat', true);
3770 $config->set('Attr.EnableID', true);
3771 if (!defined('MOBILE_VERSION')) {
3772 @$config->set('Cache', 'SerializerPath', CACHE_DIR . "/htmlpurifier");
3773 } else {
3774 @$config->set('Cache', 'SerializerPath', "../" . CACHE_DIR . "/htmlpurifier");
3775 }
3776
3777 $purifier = new HTMLPurifier($config);
3778 }
3779
388c645a 3780 $res = $purifier->purify($res);
f826eee1 3781
ceb0cab5 3782 if (get_pref($link, "STRIP_IMAGES", $owner)) {
8dccabed 3783 $res = preg_replace('/<img[^>]+>/is', '', $res);
7514749d 3784 }
8dccabed 3785
46137483
AD
3786 if (strpos($res, "href=") === false)
3787 $res = rewrite_urls($res);
533c0ea6 3788
8cc3c778
AD
3789 $charset_hack = '<head>
3790 <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
3791 </head>';
3792
96811a55
AD
3793 $res = trim($res); if (!$res) return '';
3794
8cc3c778
AD
3795 libxml_use_internal_errors(true);
3796
3797 $doc = new DOMDocument();
3798 $doc->loadHTML($charset_hack . $res);
3799 $xpath = new DOMXPath($doc);
8d505d78 3800
8cc3c778 3801 $entries = $xpath->query('(//a[@href]|//img[@src])');
3f770c87 3802 $br_inserted = 0;
8cc3c778
AD
3803
3804 foreach ($entries as $entry) {
3805
3806 if ($site_url) {
3807
3808 if ($entry->hasAttribute('href'))
3809 $entry->setAttribute('href',
3810 rewrite_relative_url($site_url, $entry->getAttribute('href')));
8d505d78 3811
8cc3c778 3812 if ($entry->hasAttribute('src'))
8d505d78 3813 if (preg_match('/^image.php\?i=[a-z0-9]+$/', $entry->getAttribute('src')) == 0)
b8998470
AD
3814 $entry->setAttribute('src',
3815 rewrite_relative_url($site_url, $entry->getAttribute('src')));
8cc3c778
AD
3816 }
3817
fa403733 3818 if (strtolower($entry->nodeName) == "a") {
c401d5c9 3819 $entry->setAttribute("target", "_blank");
fa403733
AD
3820 }
3821
3f770c87 3822 if (strtolower($entry->nodeName) == "img" && !$br_inserted) {
fa403733
AD
3823 $br = $doc->createElement("br");
3824
3f770c87 3825 if ($entry->parentNode->nextSibling) {
fa403733 3826 $entry->parentNode->insertBefore($br, $entry->nextSibling);
3f770c87
AD
3827 $br_inserted = 1;
3828 }
fa403733 3829
8cc3c778 3830 }
8dccabed 3831 }
8d505d78 3832
1f6131f5 3833 $node = $doc->getElementsByTagName('body')->item(0);
8dccabed 3834
8d505d78 3835 return $doc->saveXML($node);
183ad07b 3836 }
b72c3ef8 3837
45004d43
AD
3838 /**
3839 * Send by mail a digest of last articles.
8d505d78 3840 *
45004d43
AD
3841 * @param mixed $link The database connection.
3842 * @param integer $limit The maximum number of articles by digest.
3843 * @return boolean Return false if digests are not enabled.
3844 */
9cd7c995
AD
3845 function send_headlines_digests($link, $limit = 100) {
3846
31303c6b
AD
3847 require_once 'lib/phpmailer/class.phpmailer.php';
3848
1ddba275
AD
3849 if (!DIGEST_ENABLE) return false;
3850
9cd7c995 3851 $user_limit = DIGEST_EMAIL_LIMIT;
5430c959 3852 $days = 1;
9cd7c995
AD
3853
3854 print "Sending digests, batch of max $user_limit users, days = $days, headline limit = $limit\n\n";
3855
3856 if (DB_TYPE == "pgsql") {
3857 $interval_query = "last_digest_sent < NOW() - INTERVAL '$days days'";
3858 } else if (DB_TYPE == "mysql") {
3859 $interval_query = "last_digest_sent < DATE_SUB(NOW(), INTERVAL $days DAY)";
3860 }
3861
8d505d78 3862 $result = db_query($link, "SELECT id,email FROM ttrss_users
9cd7c995
AD
3863 WHERE email != '' AND (last_digest_sent IS NULL OR $interval_query)");
3864
3865 while ($line = db_fetch_assoc($result)) {
dc85be2b 3866
9cd7c995
AD
3867 if (get_pref($link, 'DIGEST_ENABLE', $line['id'], false)) {
3868 print "Sending digest for UID:" . $line['id'] . " - " . $line["email"] . " ... ";
3869
dc85be2b
AD
3870 $do_catchup = get_pref($link, 'DIGEST_CATCHUP', $line['id'], false);
3871
9cd7c995
AD
3872 $tuple = prepare_headlines_digest($link, $line["id"], $days, $limit);
3873 $digest = $tuple[0];
3874 $headlines_count = $tuple[1];
dc85be2b 3875 $affected_ids = $tuple[2];
c62a2c21 3876 $digest_text = $tuple[3];
9cd7c995
AD
3877
3878 if ($headlines_count > 0) {
a8931123 3879
c62a2c21 3880 $mail = new PHPMailer();
a8931123 3881
d134e3a3
AD
3882 $mail->PluginDir = "lib/phpmailer/";
3883 $mail->SetLanguage("en", "lib/phpmailer/language/");
a8931123 3884
c62a2c21 3885 $mail->CharSet = "UTF-8";
a8931123 3886
c62a2c21
AD
3887 $mail->From = DIGEST_FROM_ADDRESS;
3888 $mail->FromName = DIGEST_FROM_NAME;
3889 $mail->AddAddress($line["email"], $line["login"]);
c7ddac5c 3890
c62a2c21 3891 if (DIGEST_SMTP_HOST) {
a8931123
AD
3892 $mail->Host = DIGEST_SMTP_HOST;
3893 $mail->Mailer = "smtp";
19a1da0d 3894 $mail->SMTPAuth = DIGEST_SMTP_LOGIN != '';
a8931123
AD
3895 $mail->Username = DIGEST_SMTP_LOGIN;
3896 $mail->Password = DIGEST_SMTP_PASSWORD;
c62a2c21 3897 }
a8931123 3898
c62a2c21 3899 $mail->IsHTML(true);
163a295e 3900 $mail->Subject = DIGEST_SUBJECT;
c62a2c21
AD
3901 $mail->Body = $digest;
3902 $mail->AltBody = $digest_text;
a8931123 3903
c62a2c21 3904 $rc = $mail->Send();
a8931123 3905
c62a2c21 3906 if (!$rc) print "ERROR: " . $mail->ErrorInfo;
a8931123 3907
9cd7c995 3908 print "RC=$rc\n";
a8931123 3909
c62a2c21 3910 if ($rc && $do_catchup) {
dc85be2b 3911 print "Marking affected articles as read...\n";
9968d46f 3912 catchupArticlesById($link, $affected_ids, 0, $line["id"]);
dc85be2b 3913 }
9cd7c995
AD
3914 } else {
3915 print "No headlines\n";
3916 }
019dd98d 3917
8d505d78 3918 db_query($link, "UPDATE ttrss_users SET last_digest_sent = NOW()
019dd98d 3919 WHERE id = " . $line["id"]);
9cd7c995
AD
3920 }
3921 }
3922
cedd3e89
AD
3923 print "All done.\n";
3924
9cd7c995
AD
3925 }
3926
7e3634d9 3927 function prepare_headlines_digest($link, $user_id, $days = 1, $limit = 100) {
c62a2c21 3928
fe7537b5 3929 require_once "lib/MiniTemplator.class.php";
c62a2c21
AD
3930
3931 $tpl = new MiniTemplator;
3932 $tpl_t = new MiniTemplator;
3933
3934 $tpl->readTemplateFromFile("templates/digest_template_html.txt");
3935 $tpl_t->readTemplateFromFile("templates/digest_template.txt");
3936
3937 $tpl->setVariable('CUR_DATE', date('Y/m/d'));
3938 $tpl->setVariable('CUR_TIME', date('G:i'));
3939
3940 $tpl_t->setVariable('CUR_DATE', date('Y/m/d'));
3941 $tpl_t->setVariable('CUR_TIME', date('G:i'));
7e3634d9 3942
dc85be2b
AD
3943 $affected_ids = array();
3944
7e3634d9 3945 if (DB_TYPE == "pgsql") {
25ea2805 3946 $interval_query = "ttrss_entries.date_updated > NOW() - INTERVAL '$days days'";
7e3634d9 3947 } else if (DB_TYPE == "mysql") {
25ea2805 3948 $interval_query = "ttrss_entries.date_updated > DATE_SUB(NOW(), INTERVAL $days DAY)";
7e3634d9
AD
3949 }
3950
3951 $result = db_query($link, "SELECT ttrss_entries.title,
3952 ttrss_feeds.title AS feed_title,
25ea2805 3953 date_updated,
dc85be2b 3954 ttrss_user_entries.ref_id,
7e3634d9 3955 link,
c62a2c21 3956 SUBSTRING(content, 1, 120) AS excerpt,
fc2b26a6 3957 ".SUBSTRING_FOR_DATE."(last_updated,1,19) AS last_updated
8d505d78
AD
3958 FROM
3959 ttrss_user_entries,ttrss_entries,ttrss_feeds
3960 WHERE
3961 ref_id = ttrss_entries.id AND feed_id = ttrss_feeds.id
3dd9183c 3962 AND include_in_digest = true
7e3634d9 3963 AND $interval_query
448b0abd 3964 AND ttrss_user_entries.owner_uid = $user_id
8d505d78 3965 AND unread = true
25ea2805 3966 ORDER BY ttrss_feeds.title, date_updated DESC
7e3634d9
AD
3967 LIMIT $limit");
3968
3969 $cur_feed_title = "";
3970
9cd7c995
AD
3971 $headlines_count = db_num_rows($result);
3972
c62a2c21
AD
3973 $headlines = array();
3974
7e3634d9 3975 while ($line = db_fetch_assoc($result)) {
c62a2c21
AD
3976 array_push($headlines, $line);
3977 }
3978
8d505d78 3979 for ($i = 0; $i < sizeof($headlines); $i++) {
c62a2c21
AD
3980
3981 $line = $headlines[$i];
dc85be2b
AD
3982
3983 array_push($affected_ids, $line["ref_id"]);
3984
324944f3
AD
3985 $updated = make_local_datetime($link, $line['last_updated'], false,
3986 $user_id);
7e3634d9 3987
c62a2c21
AD
3988 $tpl->setVariable('FEED_TITLE', $line["feed_title"]);
3989 $tpl->setVariable('ARTICLE_TITLE', $line["title"]);
3990 $tpl->setVariable('ARTICLE_LINK', $line["link"]);
3991 $tpl->setVariable('ARTICLE_UPDATED', $updated);
8d505d78 3992 $tpl->setVariable('ARTICLE_EXCERPT',
163a295e 3993 truncate_string(strip_tags($line["excerpt"]), 100));
7e3634d9 3994
c62a2c21
AD
3995 $tpl->addBlock('article');
3996
3997 $tpl_t->setVariable('FEED_TITLE', $line["feed_title"]);
3998 $tpl_t->setVariable('ARTICLE_TITLE', $line["title"]);
3999 $tpl_t->setVariable('ARTICLE_LINK', $line["link"]);
4000 $tpl_t->setVariable('ARTICLE_UPDATED', $updated);
8d505d78 4001// $tpl_t->setVariable('ARTICLE_EXCERPT',
c62a2c21
AD
4002// truncate_string(strip_tags($line["excerpt"]), 100));
4003
4004 $tpl_t->addBlock('article');
4005
4006 if ($headlines[$i]['feed_title'] != $headlines[$i+1]['feed_title']) {
4007 $tpl->addBlock('feed');
4008 $tpl_t->addBlock('feed');
7e3634d9
AD
4009 }
4010
7e3634d9
AD
4011 }
4012
c62a2c21
AD
4013 $tpl->addBlock('digest');
4014 $tpl->generateOutputToString($tmp);
4015
4016 $tpl_t->addBlock('digest');
4017 $tpl_t->generateOutputToString($tmp_t);
7e3634d9 4018
c62a2c21 4019 return array($tmp, $headlines_count, $affected_ids, $tmp_t);
7e3634d9
AD
4020 }
4021
73495fd1 4022 function check_for_update($link) {
63855db1
AD
4023 if (CHECK_FOR_NEW_VERSION && $_SESSION['access_level'] >= 10) {
4024 $version_url = "http://tt-rss.org/version.php?ver=" . VERSION;
b72c3ef8 4025
63855db1 4026 $version_data = @fetch_file_contents($version_url);
b72c3ef8 4027
63855db1
AD
4028 if ($version_data) {
4029 $version_data = json_decode($version_data, true);
8d505d78 4030 if ($version_data && $version_data['version']) {
f67d9754 4031
63855db1 4032 if (version_compare(VERSION, $version_data['version']) == -1) {
e91ad1e9 4033 return $version_data;
63855db1
AD
4034 }
4035 }
f67d9754 4036 }
b72c3ef8 4037 }
63855db1 4038 return false;
b72c3ef8 4039 }
472782e8 4040
18eddb2c
AD
4041 function markArticlesById($link, $ids, $cmode) {
4042
4043 $tmp_ids = array();
4044
4045 foreach ($ids as $id) {
4046 array_push($tmp_ids, "ref_id = '$id'");
4047 }
4048
4049 $ids_qpart = join(" OR ", $tmp_ids);
4050
4051 if ($cmode == 0) {
8d505d78 4052 db_query($link, "UPDATE ttrss_user_entries SET
18eddb2c
AD
4053 marked = false,last_read = NOW()
4054 WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
4055 } else if ($cmode == 1) {
8d505d78 4056 db_query($link, "UPDATE ttrss_user_entries SET
18eddb2c
AD
4057 marked = true
4058 WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
4059 } else {
8d505d78 4060 db_query($link, "UPDATE ttrss_user_entries SET
18eddb2c
AD
4061 marked = NOT marked,last_read = NOW()
4062 WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
4063 }
4064 }
4065
e4f4b46f
AD
4066 function publishArticlesById($link, $ids, $cmode) {
4067
4068 $tmp_ids = array();
4069
4070 foreach ($ids as $id) {
4071 array_push($tmp_ids, "ref_id = '$id'");
4072 }
4073
4074 $ids_qpart = join(" OR ", $tmp_ids);
4075
4076 if ($cmode == 0) {
8d505d78 4077 db_query($link, "UPDATE ttrss_user_entries SET
e4f4b46f
AD
4078 published = false,last_read = NOW()
4079 WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
4080 } else if ($cmode == 1) {
8d505d78 4081 db_query($link, "UPDATE ttrss_user_entries SET
e4f4b46f
AD
4082 published = true
4083 WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
4084 } else {
8d505d78 4085 db_query($link, "UPDATE ttrss_user_entries SET
e4f4b46f
AD
4086 published = NOT published,last_read = NOW()
4087 WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
4088 }
2fcec4c4
AD
4089
4090 if (PUBSUBHUBBUB_HUB) {
4091 $rss_link = get_self_url_prefix() .
e0d91d84 4092 "/public.php?op=rss&id=-2&key=" .
2fcec4c4
AD
4093 get_feed_access_key($link, -2, false);
4094
4095 $p = new Publisher(PUBSUBHUBBUB_HUB);
4096
4097 $pubsub_result = $p->publish_update($rss_link);
4098 }
e4f4b46f
AD
4099 }
4100
9968d46f
AD
4101 function catchupArticlesById($link, $ids, $cmode, $owner_uid = false) {
4102
4103 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
ed41f171 4104 if (count($ids) == 0) return;
472782e8
AD
4105
4106 $tmp_ids = array();
4107
4108 foreach ($ids as $id) {
4109 array_push($tmp_ids, "ref_id = '$id'");
4110 }
4111
4112 $ids_qpart = join(" OR ", $tmp_ids);
4113
4114 if ($cmode == 0) {
8d505d78 4115 db_query($link, "UPDATE ttrss_user_entries SET
472782e8 4116 unread = false,last_read = NOW()
9968d46f 4117 WHERE ($ids_qpart) AND owner_uid = $owner_uid");
472782e8 4118 } else if ($cmode == 1) {
8d505d78 4119 db_query($link, "UPDATE ttrss_user_entries SET
472782e8 4120 unread = true
9968d46f 4121 WHERE ($ids_qpart) AND owner_uid = $owner_uid");
472782e8 4122 } else {
8d505d78 4123 db_query($link, "UPDATE ttrss_user_entries SET
472782e8 4124 unread = NOT unread,last_read = NOW()
9968d46f 4125 WHERE ($ids_qpart) AND owner_uid = $owner_uid");
472782e8 4126 }
0737b95a
AD
4127
4128 /* update ccache */
4129
4130 $result = db_query($link, "SELECT DISTINCT feed_id FROM ttrss_user_entries
4131 WHERE ($ids_qpart) AND owner_uid = $owner_uid");
4132
4133 while ($line = db_fetch_assoc($result)) {
4134 ccache_update($link, $line["feed_id"], $owner_uid);
4135 }
472782e8
AD
4136 }
4137
e097e8be
AD
4138 function catchupArticleById($link, $id, $cmode) {
4139
4140 if ($cmode == 0) {
8d505d78 4141 db_query($link, "UPDATE ttrss_user_entries SET
e097e8be
AD
4142 unread = false,last_read = NOW()
4143 WHERE ref_id = '$id' AND owner_uid = " . $_SESSION["uid"]);
4144 } else if ($cmode == 1) {
8d505d78 4145 db_query($link, "UPDATE ttrss_user_entries SET
e097e8be
AD
4146 unread = true
4147 WHERE ref_id = '$id' AND owner_uid = " . $_SESSION["uid"]);
4148 } else {
8d505d78 4149 db_query($link, "UPDATE ttrss_user_entries SET
e097e8be
AD
4150 unread = NOT unread,last_read = NOW()
4151 WHERE ref_id = '$id' AND owner_uid = " . $_SESSION["uid"]);
4152 }
ab197ae1
AD
4153
4154 $feed_id = getArticleFeed($link, $id);
4155 ccache_update($link, $feed_id, $_SESSION["uid"]);
e097e8be
AD
4156 }
4157
1f64b1be 4158 function make_guid_from_title($title) {
8d505d78 4159 return preg_replace("/[ \"\',.:;]/", "-",
fefef828 4160 mb_strtolower(strip_tags($title), 'utf-8'));
1f64b1be
AD
4161 }
4162
bd202c3f 4163 function format_headline_subtoolbar($link, $feed_site_url, $feed_title,
0ef68e6f 4164 $feed_id, $is_cat, $search, $match_on,
26a1e185 4165 $search_mode, $view_mode, $error) {
e6c115b2 4166
bd202c3f
AD
4167 $page_prev_link = "viewFeedGoPage(-1)";
4168 $page_next_link = "viewFeedGoPage(1)";
4169 $page_first_link = "viewFeedGoPage(0)";
203de776 4170
bd202c3f
AD
4171 $catchup_page_link = "catchupPage()";
4172 $catchup_feed_link = "catchupCurrentFeed()";
4173 $catchup_sel_link = "catchupSelection()";
c6008b62 4174
bd202c3f
AD
4175 $archive_sel_link = "archiveSelection()";
4176 $delete_sel_link = "deleteSelection()";
e04c18a2 4177
bd202c3f
AD
4178 $sel_all_link = "selectArticles('all')";
4179 $sel_unread_link = "selectArticles('unread')";
4180 $sel_none_link = "selectArticles('none')";
4181 $sel_inv_link = "selectArticles('invert')";
11befbb2 4182
bd202c3f
AD
4183 $tog_unread_link = "selectionToggleUnread()";
4184 $tog_marked_link = "selectionToggleMarked()";
4185 $tog_published_link = "selectionTogglePublished()";
fcf70c51 4186
bd202c3f 4187 $reply = "<div id=\"subtoolbar_main\">";
fcf70c51 4188
bd202c3f
AD
4189 $reply .= __('Select:')."
4190 <a href=\"#\" onclick=\"$sel_all_link\">".__('All')."</a>,
4191 <a href=\"#\" onclick=\"$sel_unread_link\">".__('Unread')."</a>,
4192 <a href=\"#\" onclick=\"$sel_inv_link\">".__('Invert')."</a>,
4193 <a href=\"#\" onclick=\"$sel_none_link\">".__('None')."</a></li>";
fcf70c51 4194
bd202c3f 4195 $reply .= " ";
fcf70c51 4196
bd202c3f
AD
4197 $reply .= "<select dojoType=\"dijit.form.Select\"
4198 onchange=\"headlineActionsChange(this)\">";
4199 $reply .= "<option value=\"false\">".__('Actions...')."</option>";
fcf70c51 4200
bd202c3f 4201 $reply .= "<option value=\"0\" disabled=\"1\">".__('Selection toggle:')."</option>";
fcf70c51 4202
bd202c3f
AD
4203 $reply .= "<option value=\"$tog_unread_link\">".__('Unread')."</option>
4204 <option value=\"$tog_marked_link\">".__('Starred')."</option>
4205 <option value=\"$tog_published_link\">".__('Published')."</option>";
fcf70c51 4206
bd202c3f 4207 $reply .= "<option value=\"0\" disabled=\"1\">".__('Selection:')."</option>";
fcf70c51 4208
bd202c3f 4209 $reply .= "<option value=\"$catchup_sel_link\">".__('Mark as read')."</option>";
fcf70c51 4210
bd202c3f
AD
4211 if ($feed_id != "0") {
4212 $reply .= "<option value=\"$archive_sel_link\">".__('Archive')."</option>";
4213 } else {
4214 $reply .= "<option value=\"$archive_sel_link\">".__('Move back')."</option>";
4215 $reply .= "<option value=\"$delete_sel_link\">".__('Delete')."</option>";
fcf70c51 4216
bd202c3f 4217 }
fcf70c51 4218
bd202c3f
AD
4219 $reply .= "<option value=\"emailArticle(false)\">".__('Forward by email').
4220 "</option>";
fcf70c51 4221
b0f379df
AD
4222 if ($is_cat) $cat_q = "&is_cat=$is_cat";
4223
9d9faf6d
AD
4224 if ($search) {
4225 $search_q = "&q=$search&m=$match_on&smode=$search_mode";
4226 } else {
4227 $search_q = "";
4228 }
4229
bd202c3f 4230 $rss_link = htmlspecialchars(get_self_url_prefix() .
e0d91d84 4231 "/public.php?op=rss&id=$feed_id$cat_q$search_q");
0f9b4a60 4232
bd202c3f 4233 $reply .= "<option value=\"0\" disabled=\"1\">".__('Feed:')."</option>";
176b8ba6 4234
bd202c3f 4235 $reply .= "<option value=\"catchupPage()\">".__('Mark as read')."</option>";
fcf70c51 4236
bd202c3f 4237 $reply .= "<option value=\"displayDlg('generatedFeed', '$feed_id:$is_cat:$rss_link')\">".__('View as RSS')."</option>";
fcf70c51 4238
bd202c3f 4239 $reply .= "</select>";
c6008b62 4240
bd202c3f 4241 $reply .= "</div>";
0ef68e6f 4242
bd202c3f 4243 $reply .= "<div id=\"subtoolbar_ftitle\">";
26a1e185 4244
bd202c3f
AD
4245 if ($feed_site_url) {
4246 $target = "target=\"_blank\"";
4247 $reply .= "<a title=\"".__("Visit the website")."\" $target href=\"$feed_site_url\">".
4248 truncate_string($feed_title,30)."</a>";
26a1e185 4249
bd202c3f
AD
4250 if ($error) {
4251 $reply .= " (<span class=\"error\" title=\"$error\">Error</span>)";
4252 }
5163fc70 4253
bd202c3f
AD
4254 } else {
4255 if ($feed_id < -10) {
4256 $label_id = -11-$feed_id;
5163fc70 4257
bd202c3f
AD
4258 $result = db_query($link, "SELECT fg_color, bg_color
4259 FROM ttrss_labels2 WHERE id = '$label_id' AND owner_uid = " .
4260 $_SESSION["uid"]);
5163fc70 4261
bd202c3f
AD
4262 if (db_num_rows($result) != 0) {
4263 $fg_color = db_fetch_result($result, 0, "fg_color");
4264 $bg_color = db_fetch_result($result, 0, "bg_color");
5163fc70 4265
9949bd15 4266 $reply .= "<span style=\"background : $bg_color; color : $fg_color\" >";
bd202c3f
AD
4267 $reply .= $feed_title;
4268 $reply .= "</span>";
5163fc70 4269 } else {
bd202c3f 4270 $reply .= $feed_title;
5163fc70 4271 }
0ef68e6f 4272
c3fddd05 4273 } else {
bd202c3f 4274 $reply .= $feed_title;
0ef68e6f 4275 }
bd202c3f 4276 }
0ef68e6f 4277
bd202c3f
AD
4278 $reply .= "
4279 <a href=\"#\"
4280 title=\"".__("View as RSS feed")."\"
4281 onclick=\"displayDlg('generatedFeed', '$feed_id:$is_cat:$rss_link')\">
4282 <img class=\"noborder\" style=\"vertical-align : middle\" src=\"images/feed-icon-12x12.png\"></a>";
ceb30ba4 4283
bd202c3f
AD
4284 $reply .= "</div>";
4285
4286 return $reply;
4287 }
8d505d78 4288
1985a5e0 4289 function outputFeedList($link, $special = true) {
f407c086 4290
13e785e0
AD
4291 $feedlist = array();
4292
4293 $enable_cats = get_pref($link, 'ENABLE_FEED_CATS');
4294
4295 $feedlist['identifier'] = 'id';
4296 $feedlist['label'] = 'name';
4297 $feedlist['items'] = array();
f407c086
AD
4298
4299 $owner_uid = $_SESSION["uid"];
4300
cf4d339c 4301 /* virtual feeds */
f407c086 4302
1985a5e0 4303 if ($special) {
e4f4b46f 4304
1985a5e0
AD
4305 if ($enable_cats) {
4306 $cat_hidden = get_pref($link, "_COLLAPSED_SPECIAL");
4307 $cat = feedlist_init_cat($link, -1, $cat_hidden);
4308 } else {
4309 $cat['items'] = array();
4310 }
8d505d78 4311
1985a5e0
AD
4312 foreach (array(-4, -3, -1, -2, 0) as $i) {
4313 array_push($cat['items'], feedlist_init_feed($link, $i));
4314 }
8d505d78 4315
1985a5e0
AD
4316 if ($enable_cats) {
4317 array_push($feedlist['items'], $cat);
4318 } else {
4319 $feedlist['items'] = array_merge($feedlist['items'], $cat['items']);
4320 }
8d505d78 4321
1985a5e0
AD
4322 $result = db_query($link, "SELECT * FROM
4323 ttrss_labels2 WHERE owner_uid = '$owner_uid' ORDER by caption");
9fe80bcd 4324
d4f46bc1 4325 if (db_num_rows($result) > 0) {
9fe80bcd 4326
d4f46bc1
AD
4327 if (get_pref($link, 'ENABLE_FEED_CATS')) {
4328 $cat_hidden = get_pref($link, "_COLLAPSED_LABELS");
4329 $cat = feedlist_init_cat($link, -2, $cat_hidden);
4330 } else {
4331 $cat['items'] = array();
4332 }
9fe80bcd 4333
d4f46bc1 4334 while ($line = db_fetch_assoc($result)) {
8d505d78 4335
d4f46bc1
AD
4336 $label_id = -$line['id'] - 11;
4337 $count = getFeedUnread($link, $label_id);
8d505d78 4338
d4f46bc1 4339 $feed = feedlist_init_feed($link, $label_id, false, $count);
8d505d78 4340
d4f46bc1
AD
4341 $feed['fg_color'] = $line['fg_color'];
4342 $feed['bg_color'] = $line['bg_color'];
8d505d78 4343
d4f46bc1
AD
4344 array_push($cat['items'], $feed);
4345 }
8d505d78 4346
d4f46bc1
AD
4347 if ($enable_cats) {
4348 array_push($feedlist['items'], $cat);
4349 } else {
4350 $feedlist['items'] = array_merge($feedlist['items'], $cat['items']);
4351 }
1985a5e0 4352 }
9c99281f 4353 }
8d505d78 4354
76657c46 4355/* if (get_pref($link, 'ENABLE_FEED_CATS')) {
9c99281f
AD
4356 if (get_pref($link, "FEEDS_SORT_BY_UNREAD")) {
4357 $order_by_qpart = "order_id,category,unread DESC,title";
13e785e0 4358 } else {
9c99281f 4359 $order_by_qpart = "order_id,category,title";
f407c086 4360 }
9c99281f
AD
4361 } else {
4362 if (get_pref($link, "FEEDS_SORT_BY_UNREAD")) {
4363 $order_by_qpart = "unread DESC,title";
8d505d78 4364 } else {
9c99281f 4365 $order_by_qpart = "title";
f407c086 4366 }
76657c46
AD
4367 } */
4368
4d65b7df
AD
4369 /* real feeds */
4370
76657c46 4371 if ($enable_cats)
7b8a143f
AD
4372 $order_by_qpart = "ttrss_feed_categories.order_id,category,
4373 ttrss_feeds.order_id,title";
76657c46
AD
4374 else
4375 $order_by_qpart = "title";
f407c086 4376
9c99281f 4377 $age_qpart = getMaxAgeSubquery();
f407c086 4378
9c99281f
AD
4379 $query = "SELECT ttrss_feeds.id, ttrss_feeds.title,
4380 ".SUBSTRING_FOR_DATE."(last_updated,1,19) AS last_updated_noms,
4381 cat_id,last_error,
4382 ttrss_feed_categories.title AS category,
4383 ttrss_feed_categories.collapsed,
8d505d78 4384 value AS unread
9c99281f 4385 FROM ttrss_feeds LEFT JOIN ttrss_feed_categories
8d505d78
AD
4386 ON (ttrss_feed_categories.id = cat_id)
4387 LEFT JOIN ttrss_counters_cache
9c99281f
AD
4388 ON
4389 (ttrss_feeds.id = feed_id)
8d505d78 4390 WHERE
9c99281f 4391 ttrss_feeds.owner_uid = '$owner_uid'
8d505d78 4392 ORDER BY $order_by_qpart";
13e785e0 4393
9c99281f 4394 $result = db_query($link, $query);
13e785e0 4395
9c99281f 4396 $actid = $_REQUEST["actid"];
0f39ae20 4397
4d65b7df 4398 if (db_num_rows($result) > 0) {
f407c086 4399
4d65b7df 4400 $category = "";
8d505d78
AD
4401
4402 if (!$enable_cats)
4d65b7df
AD
4403 $cat['items'] = array();
4404 else
4405 $cat = false;
8d505d78 4406
4d65b7df 4407 while ($line = db_fetch_assoc($result)) {
8d505d78 4408
4d65b7df 4409 $feed = htmlspecialchars(trim($line["title"]));
8d505d78 4410
4d65b7df 4411 if (!$feed) $feed = "[Untitled]";
8d505d78
AD
4412
4413 $feed_id = $line["id"];
4d65b7df 4414 $unread = $line["unread"];
8d505d78 4415
4d65b7df
AD
4416 $cat_id = $line["cat_id"];
4417 $tmp_category = $line["category"];
4418 if (!$tmp_category) $tmp_category = __("Uncategorized");
8d505d78 4419
4d65b7df 4420 if ($category != $tmp_category && $enable_cats) {
8d505d78 4421
4d65b7df 4422 $category = $tmp_category;
8d505d78 4423
4d65b7df 4424 $collapsed = sql_bool_to_bool($line["collapsed"]);
8d505d78 4425
4d65b7df
AD
4426 // workaround for NULL category
4427 if ($category == __("Uncategorized")) {
4428 $collapsed = get_pref($link, "_COLLAPSED_UNCAT");
4429 }
8d505d78 4430
4d65b7df 4431 if ($cat) array_push($feedlist['items'], $cat);
8d505d78 4432
4d65b7df 4433 $cat = feedlist_init_cat($link, $cat_id, $collapsed);
f0855b88 4434 }
8d505d78
AD
4435
4436 $updated = make_local_datetime($link, $line["updated_noms"], false);
4437
4438 array_push($cat['items'], feedlist_init_feed($link, $feed_id,
4d65b7df
AD
4439 $feed, $unread, $line['last_error'], $updated));
4440 }
8d505d78 4441
4d65b7df
AD
4442 if ($enable_cats) {
4443 array_push($feedlist['items'], $cat);
8d505d78 4444 } else {
4d65b7df 4445 $feedlist['items'] = array_merge($feedlist['items'], $cat['items']);
f407c086
AD
4446 }
4447
9c99281f 4448 }
13e785e0
AD
4449
4450 return $feedlist;
f407c086
AD
4451 }
4452
ca5133cb 4453 function get_article_tags($link, $id, $owner_uid = 0, $tag_cache = false) {
0b126ac2 4454
bd3f2ade
AD
4455 global $memcache;
4456
0b126ac2
AD
4457 $a_id = db_escape_string($id);
4458
bc976a8c
AD
4459 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
4460
8d505d78 4461 $query = "SELECT DISTINCT tag_name,
0c3d1c68 4462 owner_uid as owner FROM
0b126ac2 4463 ttrss_tags WHERE post_int_id = (SELECT int_id FROM ttrss_user_entries WHERE
bd3f2ade 4464 ref_id = '$a_id' AND owner_uid = '$owner_uid' LIMIT 1) ORDER BY tag_name";
0b126ac2 4465
bd3f2ade 4466 $obj_id = md5("TAGS:$owner_uid:$id");
8d505d78 4467 $tags = array();
bd3f2ade
AD
4468
4469 if ($memcache && $obj = $memcache->get($obj_id)) {
4470 $tags = $obj;
4471 } else {
490c366d
AD
4472 /* check cache first */
4473
ca5133cb
AD
4474 if ($tag_cache === false) {
4475 $result = db_query($link, "SELECT tag_cache FROM ttrss_user_entries
4476 WHERE ref_id = '$id' AND owner_uid = " . $_SESSION["uid"]);
490c366d 4477
ca5133cb
AD
4478 $tag_cache = db_fetch_result($result, 0, "tag_cache");
4479 }
490c366d
AD
4480
4481 if ($tag_cache) {
4482 $tags = explode(",", $tag_cache);
4483 } else {
bd3f2ade 4484
490c366d
AD
4485 /* do it the hard way */
4486
4487 $tmp_result = db_query($link, $query);
4488
4489 while ($tmp_line = db_fetch_assoc($tmp_result)) {
8d505d78 4490 array_push($tags, $tmp_line["tag_name"]);
490c366d
AD
4491 }
4492
4493 /* update the cache */
4494
4495 $tags_str = db_escape_string(join(",", $tags));
4496
8d505d78 4497 db_query($link, "UPDATE ttrss_user_entries
490c366d
AD
4498 SET tag_cache = '$tags_str' WHERE ref_id = '$id'
4499 AND owner_uid = " . $_SESSION["uid"]);
bd3f2ade
AD
4500 }
4501
4502 if ($memcache) $memcache->add($obj_id, $tags, 0, 3600);
0b126ac2
AD
4503 }
4504
4505 return $tags;
4506 }
4507
d62a3b63
AD
4508 function trim_array($array) {
4509 $tmp = $array;
3415b075 4510 array_walk($tmp, 'trim');
d62a3b63
AD
4511 return $tmp;
4512 }
4513
be832a1a 4514 function tag_is_valid($tag) {
ef063748
AD
4515 if ($tag == '') return false;
4516 if (preg_match("/^[0-9]*$/", $tag)) return false;
41f7498a 4517 if (mb_strlen($tag) > 250) return false;
ef063748 4518
31365729
AD
4519 if (function_exists('iconv')) {
4520 $tag = iconv("utf-8", "utf-8", $tag);
4521 }
4522
ef063748
AD
4523 if (!$tag) return false;
4524
4525 return true;
be832a1a
AD
4526 }
4527
afb12ed0
AD
4528 function render_login_form($link, $mobile = 0) {
4529 switch ($mobile) {
4530 case 0:
793185a9 4531 require_once "login_form.php";
afb12ed0
AD
4532 break;
4533 case 1:
793185a9 4534 require_once "mobile/login_form.php";
afb12ed0
AD
4535 break;
4536 case 2:
4537 require_once "mobile/classic/login_form.php";
793185a9 4538 }
01a87dff
AD
4539 }
4540
dc56b3b7
AD
4541 // from http://developer.apple.com/internet/safari/faq.html
4542 function no_cache_incantation() {
4543 header("Expires: Mon, 22 Dec 1980 00:00:00 GMT"); // Happy birthday to me :)
4544 header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT"); // always modified
4545 header("Cache-Control: no-store, no-cache, must-revalidate, max-age=0"); // HTTP/1.1
4546 header("Cache-Control: post-check=0, pre-check=0", false);
4547 header("Pragma: no-cache"); // HTTP/1.0
4548 }
4549
42395d28 4550 function format_warning($msg, $id = "") {
883fee8d 4551 global $link;
8d505d78 4552 return "<div class=\"warning\" id=\"$id\">
883fee8d 4553 <img src=\"".theme_image($link, "images/sign_excl.png")."\">$msg</div>";
0d32b41e
AD
4554 }
4555
08ac193a 4556 function format_notice($msg, $id = "") {
883fee8d 4557 global $link;
8d505d78 4558 return "<div class=\"notice\" id=\"$id\">
883fee8d 4559 <img src=\"".theme_image($link, "images/sign_info.png")."\">$msg</div>";
0d32b41e
AD
4560 }
4561
08ac193a 4562 function format_error($msg, $id = "") {
883fee8d 4563 global $link;
8d505d78 4564 return "<div class=\"error\" id=\"$id\">
883fee8d 4565 <img src=\"".theme_image($link, "images/sign_excl.png")."\">$msg</div>";
68d2f95e
AD
4566 }
4567
4dccf1ed
AD
4568 function print_notice($msg) {
4569 return print format_notice($msg);
4570 }
4571
4572 function print_warning($msg) {
4573 return print format_warning($msg);
4574 }
4575
68d2f95e
AD
4576 function print_error($msg) {
4577 return print format_error($msg);
4578 }
4579
4580
4dccf1ed
AD
4581 function T_sprintf() {
4582 $args = func_get_args();
4583 return vsprintf(__(array_shift($args)), $args);
4584 }
4585
51682b23
AD
4586 function format_inline_player($link, $url, $ctype) {
4587
4588 $entry = "";
4589
8d505d78 4590 if (strpos($ctype, "audio/") === 0) {
c3edc667
AD
4591
4592 if ($_SESSION["hasAudio"] && (strpos($ctype, "ogg") !== false ||
8d505d78 4593 strpos($_SERVER['HTTP_USER_AGENT'], "Chrome") !== false ||
c3edc667
AD
4594 strpos($_SERVER['HTTP_USER_AGENT'], "Safari") !== false )) {
4595
4596 $id = 'AUDIO-' . uniqid();
4597
4598 $entry .= "<audio id=\"$id\"\">
4599 <source src=\"$url\"></source>
8d505d78 4600 </audio>";
c3edc667 4601
8d505d78 4602 $entry .= "<span onclick=\"player(this)\"
c3edc667
AD
4603 title=\"".__("Click to play")."\" status=\"0\"
4604 class=\"player\" audio-id=\"$id\">".__("Play")."</span>";
4605
4606 } else {
8d505d78
AD
4607
4608 $entry .= "<object type=\"application/x-shockwave-flash\"
ad95edc2 4609 data=\"lib/button/musicplayer.swf?song_url=$url\"
8d505d78
AD
4610 width=\"17\" height=\"17\" style='float : left; margin-right : 5px;'>
4611 <param name=\"movie\"
ad95edc2 4612 value=\"lib/button/musicplayer.swf?song_url=$url\" />
8d505d78 4613 </object>";
c3edc667 4614 }
51682b23
AD
4615 }
4616
c3edc667
AD
4617 $filename = substr($url, strrpos($url, "/")+1);
4618
4619 $entry .= " <a target=\"_blank\" href=\"" . htmlspecialchars($url) . "\">" .
4620 $filename . " (" . $ctype . ")" . "</a>";
4621
51682b23
AD
4622 return $entry;
4623 }
4624
9949bd15 4625 function format_article($link, $id, $mark_as_read = true, $zoom_mode = false) {
3de0261a 4626
009646d2
AD
4627 $rv = array();
4628
4629 $rv['id'] = $id;
4630
10eb9da8 4631 /* we can figure out feed_id from article id anyway, why do we
e04c18a2 4632 * pass feed_id here? let's ignore the argument :( */
10eb9da8
AD
4633
4634 $result = db_query($link, "SELECT feed_id FROM ttrss_user_entries
4635 WHERE ref_id = '$id'");
4636
e04c18a2 4637 $feed_id = (int) db_fetch_result($result, 0, "feed_id");
10eb9da8 4638
009646d2
AD
4639 $rv['feed_id'] = $feed_id;
4640
4641 //if (!$zoom_mode) { print "<article id='$id'><![CDATA["; };
3de0261a 4642
54e61a68 4643 $result = db_query($link, "SELECT rtl_content, always_display_enclosures FROM ttrss_feeds
3de0261a
AD
4644 WHERE id = '$feed_id' AND owner_uid = " . $_SESSION["uid"]);
4645
4646 if (db_num_rows($result) == 1) {
4647 $rtl_content = sql_bool_to_bool(db_fetch_result($result, 0, "rtl_content"));
54e61a68 4648 $always_display_enclosures = sql_bool_to_bool(db_fetch_result($result, 0, "always_display_enclosures"));
3de0261a
AD
4649 } else {
4650 $rtl_content = false;
54e61a68 4651 $always_display_enclosures = false;
3de0261a
AD
4652 }
4653
4654 if ($rtl_content) {
4655 $rtl_tag = "dir=\"RTL\"";
4656 $rtl_class = "RTL";
4657 } else {
4658 $rtl_tag = "";
4659 $rtl_class = "";
4660 }
4661
4662 if ($mark_as_read) {
8d505d78
AD
4663 $result = db_query($link, "UPDATE ttrss_user_entries
4664 SET unread = false,last_read = NOW()
3de0261a 4665 WHERE ref_id = '$id' AND owner_uid = " . $_SESSION["uid"]);
8a4c759e
AD
4666
4667 ccache_update($link, $feed_id, $_SESSION["uid"]);
3de0261a
AD
4668 }
4669
4670 $result = db_query($link, "SELECT title,link,content,feed_id,comments,int_id,
fc2b26a6 4671 ".SUBSTRING_FOR_DATE."(updated,1,16) as updated,
3de0261a 4672 (SELECT icon_url FROM ttrss_feeds WHERE id = feed_id) as icon_url,
8cc3c778 4673 (SELECT site_url FROM ttrss_feeds WHERE id = feed_id) as site_url,
3de0261a 4674 num_comments,
9c506873 4675 tag_cache,
c7e51de1 4676 author,
ef83538d 4677 orig_feed_id,
c7e51de1 4678 note
3de0261a
AD
4679 FROM ttrss_entries,ttrss_user_entries
4680 WHERE id = '$id' AND ref_id = id AND owner_uid = " . $_SESSION["uid"]);
4681
4682 if ($result) {
4683
3de0261a
AD
4684 $line = db_fetch_assoc($result);
4685
4686 if ($line["icon_url"]) {
8e289ca1 4687 $feed_icon = "<img src=\"" . $line["icon_url"] . "\">";
3de0261a
AD
4688 } else {
4689 $feed_icon = "&nbsp;";
4690 }
4691
8cc3c778
AD
4692 $feed_site_url = $line['site_url'];
4693
3de0261a
AD
4694 $num_comments = $line["num_comments"];
4695 $entry_comments = "";
4696
4697 if ($num_comments > 0) {
4698 if ($line["comments"]) {
4699 $comments_url = $line["comments"];
4700 } else {
4701 $comments_url = $line["link"];
4702 }
7514749d 4703 $entry_comments = "<a target='_blank' href=\"$comments_url\">$num_comments comments</a>";
3de0261a
AD
4704 } else {
4705 if ($line["comments"] && $line["link"] != $line["comments"]) {
7514749d 4706 $entry_comments = "<a target='_blank' href=\"".$line["comments"]."\">comments</a>";
8d505d78 4707 }
3de0261a
AD
4708 }
4709
eedfb635
AD
4710 if ($zoom_mode) {
4711 header("Content-Type: text/html");
009646d2 4712 $rv['content'] .= "<html><head>
5bb0cc8e 4713 <meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\"/>
eedfb635
AD
4714 <title>Tiny Tiny RSS - ".$line["title"]."</title>
4715 <link rel=\"stylesheet\" type=\"text/css\" href=\"tt-rss.css\">
4716 </head><body>";
4717 }
4718
009646d2 4719 $rv['content'] .= "<div id=\"PTITLE-$id\" style=\"display : none\">" .
6f3976c9 4720 truncate_string(strip_tags($line['title']), 15) . "</div>";
eedfb635 4721
009646d2 4722 $rv['content'] .= "<div class=\"postReply\" id=\"POST-$id\">";
bc372fe3 4723
009646d2 4724 $rv['content'] .= "<div onclick=\"return postClicked(event, $id)\"
bc372fe3 4725 class=\"postHeader\" id=\"POSTHDR-$id\">";
3de0261a
AD
4726
4727 $entry_author = $line["author"];
4728
4729 if ($entry_author) {
60164936 4730 $entry_author = __(" - ") . $entry_author;
3de0261a
AD
4731 }
4732
8d505d78 4733 $parsed_updated = make_local_datetime($link, $line["updated"], true,
324944f3
AD
4734 false, true);
4735
009646d2 4736 $rv['content'] .= "<div class=\"postDate$rtl_class\">$parsed_updated</div>";
3de0261a
AD
4737
4738 if ($line["link"]) {
009646d2 4739 $rv['content'] .= "<div clear='both'><a target='_blank'
a64029e5 4740 title=\"".htmlspecialchars($line['title'])."\"
8d505d78
AD
4741 href=\"" .
4742 $line["link"] . "\">" .
4743 truncate_string($line["title"], 100) .
a64029e5 4744 "<span class='author'>$entry_author</span></a></div>";
3de0261a 4745 } else {
009646d2 4746 $rv['content'] .= "<div clear='both'>" . $line["title"] . "$entry_author</div>";
3de0261a
AD
4747 }
4748
9c506873
AD
4749 $tag_cache = $line["tag_cache"];
4750
4751 if (!$tag_cache)
4752 $tags = get_article_tags($link, $id);
4753 else
4754 $tags = explode(",", $tag_cache);
4755
0780f4f4
AD
4756 $tags_str = format_tags_string($tags, $id);
4757 $tags_str_full = join(", ", $tags);
4758
4759 if (!$tags_str_full) $tags_str_full = __("no tags");
e7544143 4760
3de0261a
AD
4761 if (!$entry_comments) $entry_comments = "&nbsp;"; # placeholder
4762
009646d2 4763 $rv['content'] .= "<div style='float : right'>
8d505d78 4764 <img src='".theme_image($link, 'images/tag.png')."'
e9823609 4765 class='tagsPic' alt='Tags' title='Tags'>&nbsp;";
eedfb635
AD
4766
4767 if (!$zoom_mode) {
009646d2 4768 $rv['content'] .= "<span id=\"ATSTR-$id\">$tags_str</span>
8d505d78 4769 <a title=\"".__('Edit tags for this article')."\"
31a53903 4770 href=\"#\" onclick=\"editArticleTags($id, $feed_id)\">(+)</a>";
4710e3dc 4771
0780f4f4
AD
4772 $rv['content'] .= "<div dojoType=\"dijit.Tooltip\"
4773 id=\"ATSTRTIP-$id\" connectId=\"ATSTR-$id\"
4774 position=\"below\">$tags_str_full</div>";
4775
009646d2 4776 $rv['content'] .= "<img src=\"".theme_image($link, 'images/art-zoom.png')."\"
9ed0b90f 4777 class='tagsPic' style=\"cursor : pointer\"
ca07f49e 4778 onclick=\"postOpenInNewTab(event, $id)\"
6f3976c9 4779 alt='Zoom' title='".__('Open article in new tab')."'>";
c7e51de1 4780
741b6090 4781 //$note_escaped = htmlspecialchars($line['note'], ENT_QUOTES);
c7e51de1 4782
009646d2 4783 $rv['content'] .= "<img src=\"".theme_image($link, 'images/art-pub-note.png')."\"
9ed0b90f 4784 class='tagsPic' style=\"cursor : pointer\"
741b6090
AD
4785 onclick=\"editArticleNote($id)\"
4786 alt='PubNote' title='".__('Edit article note')."'>";
c7e51de1 4787
31a53903 4788 if (DIGEST_ENABLE) {
009646d2 4789 $rv['content'] .= "<img src=\"".theme_image($link, 'images/art-email.png')."\"
9ed0b90f 4790 class='tagsPic' style=\"cursor : pointer\"
31a53903
AD
4791 onclick=\"emailArticle($id)\"
4792 alt='Zoom' title='".__('Forward by email')."'>";
4793 }
4794
411fe209 4795 if (ENABLE_TWEET_BUTTON) {
009646d2 4796 $rv['content'] .= "<img src=\"".theme_image($link, 'images/art-tweet.png')."\"
411fe209
AD
4797 class='tagsPic' style=\"cursor : pointer\"
4798 onclick=\"tweetArticle($id)\"
4799 alt='Zoom' title='".__('Share on Twitter')."'>";
4800 }
4801
83cd33fc
AD
4802 $rv['content'] .= "<img src=\"".theme_image($link, 'images/art-share.png')."\"
4803 class='tagsPic' style=\"cursor : pointer\"
4804 onclick=\"shareArticle(".$line['int_id'].")\"
4805 alt='Zoom' title='".__('Share by URL')."'>";
4806
009646d2 4807 $rv['content'] .= "<img src=\"".theme_image($link, 'images/digest_checkbox.png')."\"
6f3976c9 4808 class='tagsPic' style=\"cursor : pointer\"
e3387e2d 4809 onclick=\"closeArticlePanel($id)\"
6f3976c9
AD
4810 alt='Zoom' title='".__('Close this panel')."'>";
4811
24ecbcae
AD
4812 } else {
4813 $tags_str = strip_tags($tags_str);
009646d2 4814 $rv['content'] .= "<span id=\"ATSTR-$id\">$tags_str</span>";
eedfb635 4815 }
009646d2
AD
4816 $rv['content'] .= "</div>";
4817 $rv['content'] .= "<div clear='both'>$entry_comments</div>";
3de0261a 4818
ef83538d
AD
4819 if ($line["orig_feed_id"]) {
4820
4821 $tmp_result = db_query($link, "SELECT * FROM ttrss_archived_feeds
4822 WHERE id = ".$line["orig_feed_id"]);
4823
4824 if (db_num_rows($tmp_result) != 0) {
4825
009646d2
AD
4826 $rv['content'] .= "<div clear='both'>";
4827 $rv['content'] .= __("Originally from:");
ef83538d 4828
009646d2 4829 $rv['content'] .= "&nbsp;";
ef83538d
AD
4830
4831 $tmp_line = db_fetch_assoc($tmp_result);
4832
009646d2 4833 $rv['content'] .= "<a target='_blank'
ef83538d
AD
4834 href=' " . htmlspecialchars($tmp_line['site_url']) . "'>" .
4835 $tmp_line['title'] . "</a>";
4836
009646d2 4837 $rv['content'] .= "&nbsp;";
ef83538d 4838
009646d2
AD
4839 $rv['content'] .= "<a target='_blank' href='" . htmlspecialchars($tmp_line['feed_url']) . "'>";
4840 $rv['content'] .= "<img title='".__('Feed URL')."'class='tinyFeedIcon' src='images/pub_set.gif'></a>";
ef83538d 4841
009646d2 4842 $rv['content'] .= "</div>";
ef83538d
AD
4843 }
4844 }
4845
009646d2 4846 $rv['content'] .= "</div>";
3de0261a 4847
009646d2 4848 $rv['content'] .= "<div id=\"POSTNOTE-$id\">";
c7e51de1 4849 if ($line['note']) {
009646d2 4850 $rv['content'] .= format_article_note($id, $line['note']);
c7e51de1 4851 }
009646d2 4852 $rv['content'] .= "</div>";
c7e51de1 4853
fcfa9ef1
AD
4854 $rv['content'] .= "<div class=\"postIcon\">" .
4855 "<a target=\"_blank\" title=\"".__("Visit the website")."\"$
4856 href=\"".htmlspecialchars($feed_site_url)."\">".
4857 $feed_icon . "</a></div>";
4858
009646d2 4859 $rv['content'] .= "<div class=\"postContent\">";
741b6090
AD
4860
4861 $article_content = sanitize_rss($link, $line["content"], false, false,
4862 $feed_site_url);
4863
009646d2 4864 $rv['content'] .= $article_content;
db54143e 4865
009646d2
AD
4866 $rv['content'] .= format_article_enclosures($link, $id,
4867 $always_display_enclosures, $article_content);
ce53e200 4868
009646d2 4869 $rv['content'] .= "</div>";
dad14b51 4870
009646d2 4871 $rv['content'] .= "</div>";
3de0261a
AD
4872
4873 }
4874
009646d2
AD
4875 if ($zoom_mode) {
4876 $rv['content'] .= "
eedfb635 4877 <div style=\"text-align : center\">
2ae69126
AD
4878 <button onclick=\"return window.close()\">".
4879 __("Close this window")."</button></div>";
009646d2 4880 $rv['content'] .= "</body></html>";
eedfb635 4881 }
3de0261a 4882
009646d2
AD
4883 return $rv;
4884
3de0261a
AD
4885 }
4886
f30ef1fa 4887 function format_headlines_list($link, $feed, $method, $view_mode, $limit, $cat_view,
8d505d78 4888 $next_unread_feed, $offset, $vgr_last_feed = false,
7b4d02a8 4889 $override_order = false) {
3de0261a 4890
52d7e7da
AD
4891 $disable_cache = false;
4892
bd202c3f
AD
4893 $reply = array();
4894
46921916
AD
4895 $timing_info = getmicrotime();
4896
961f4c73
AD
4897 $topmost_article_ids = array();
4898
71317973 4899 if (!$offset) $offset = 0;
f30ef1fa 4900 if ($method == "undefined") $method = "";
3de0261a 4901
f30ef1fa 4902 $method_split = explode(":", $method);
a9bcfb8f 4903
f30ef1fa 4904/* if ($method == "CatchupSelected") {
9949bd15 4905 $ids = explode(",", db_escape_string($_REQUEST["ids"]));
b4e75b2a 4906 $cmode = sprintf("%d", $_REQUEST["cmode"]);
3de0261a
AD
4907
4908 catchupArticlesById($link, $ids, $cmode);
b9d54789 4909 } */
3de0261a 4910
f30ef1fa 4911 if ($method == "ForceUpdate" && $feed && is_numeric($feed) > 0) {
0569a712
AD
4912 update_rss_feed($link, $feed, true);
4913 }
4914
f30ef1fa 4915 if ($method == "MarkAllRead") {
3de0261a
AD
4916 catchup_feed($link, $feed, $cat_view);
4917
4918 if (get_pref($link, 'ON_CATCHUP_SHOW_NEXT_FEED')) {
4919 if ($next_unread_feed) {
4920 $feed = $next_unread_feed;
4921 }
4922 }
4923 }
4924
f30ef1fa
AD
4925 if ($method_split[0] == "MarkAllReadGR") {
4926 catchup_feed($link, $method_split[1], false);
a9bcfb8f
AD
4927 }
4928
c3fddd05 4929 // FIXME: might break tag display?
a9bcfb8f 4930
147f5632 4931 if (is_numeric($feed) && $feed > 0 && !$cat_view) {
3de0261a
AD
4932 $result = db_query($link,
4933 "SELECT id FROM ttrss_feeds WHERE id = '$feed' LIMIT 1");
8d505d78 4934
3de0261a 4935 if (db_num_rows($result) == 0) {
bd202c3f 4936 $reply['content'] = "<div align='center'>".__('Feed not found.')."</div>";
3de0261a
AD
4937 }
4938 }
4939
4940 if (preg_match("/^-?[0-9][0-9]*$/", $feed) != false) {
10eb9da8 4941
3de0261a
AD
4942 $result = db_query($link, "SELECT rtl_content FROM ttrss_feeds
4943 WHERE id = '$feed' AND owner_uid = " . $_SESSION["uid"]);
4944
4945 if (db_num_rows($result) == 1) {
4946 $rtl_content = sql_bool_to_bool(db_fetch_result($result, 0, "rtl_content"));
4947 } else {
4948 $rtl_content = false;
4949 }
8d505d78 4950
3de0261a
AD
4951 if ($rtl_content) {
4952 $rtl_tag = "dir=\"RTL\"";
4953 } else {
4954 $rtl_tag = "";
4955 }
4956 } else {
4957 $rtl_tag = "";
4958 $rtl_content = false;
4959 }
4960
c3fddd05 4961 @$search = db_escape_string($_REQUEST["query"]);
52d7e7da 4962
8d505d78 4963 if ($search) {
52d7e7da
AD
4964 $disable_cache = true;
4965 }
4966
c3fddd05
AD
4967 @$search_mode = db_escape_string($_REQUEST["search_mode"]);
4968 @$match_on = db_escape_string($_REQUEST["match_on"]);
3de0261a
AD
4969
4970 if (!$match_on) {
4971 $match_on = "both";
4972 }
4973
b4e75b2a 4974 if ($_REQUEST["debug"]) $timing_info = print_checkpoint("H0", $timing_info);
46921916 4975
f30ef1fa
AD
4976// error_log("format_headlines_list: [" . $feed . "] method [" . $method . "]");
4977 if( $search_mode == '' && $method != '' ){
4978 $search_mode = $method;
147f5632
CM
4979 }
4980// error_log("search_mode: " . $search_mode);
8d505d78 4981 $qfh_ret = queryFeedHeadlines($link, $feed, $limit, $view_mode, $cat_view,
71317973 4982 $search, $search_mode, $match_on, $override_order, $offset);
3de0261a 4983
b4e75b2a 4984 if ($_REQUEST["debug"]) $timing_info = print_checkpoint("H1", $timing_info);
46921916 4985
3de0261a
AD
4986 $result = $qfh_ret[0];
4987 $feed_title = $qfh_ret[1];
4988 $feed_site_url = $qfh_ret[2];
4989 $last_error = $qfh_ret[3];
f56e3080 4990
081e527d
AD
4991 $vgroup_last_feed = $vgr_last_feed;
4992
78b2c6ce 4993// if (!$offset) {
3de0261a 4994
6b32516b 4995 if (db_num_rows($result) > 0) {
b9d54789
AD
4996 $reply['toolbar'] = format_headline_subtoolbar($link, $feed_site_url,
4997 $feed_title,
8d505d78 4998 $feed, $cat_view, $search, $match_on, $search_mode, $view_mode,
26a1e185 4999 $last_error);
6b32516b 5000 }
78b2c6ce 5001// }
3de0261a 5002
29dfb258
AD
5003 $headlines_count = db_num_rows($result);
5004
3de0261a
AD
5005 if (db_num_rows($result) > 0) {
5006
e56beb95 5007 $lnum = $offset;
4ab4d364 5008
3de0261a 5009 $num_unread = 0;
6cfea5c7
AD
5010 $cur_feed_title = '';
5011
784ac51f
AD
5012 $fresh_intl = get_pref($link, "FRESH_ARTICLE_MAX_AGE") * 60 * 60;
5013
7d96bfcd
AD
5014 if ($_REQUEST["debug"]) $timing_info = print_checkpoint("PS", $timing_info);
5015
3de0261a
AD
5016 while ($line = db_fetch_assoc($result)) {
5017
5018 $class = ($lnum % 2) ? "even" : "odd";
8d505d78 5019
3de0261a
AD
5020 $id = $line["id"];
5021 $feed_id = $line["feed_id"];
9c506873
AD
5022 $label_cache = $line["label_cache"];
5023 $labels = false;
5024
5025 if ($label_cache) {
5026 $label_cache = json_decode($label_cache, true);
961f4c73 5027
9c506873
AD
5028 if ($label_cache) {
5029 if ($label_cache["no-labels"] == 1)
5030 $labels = array();
5031 else
5032 $labels = $label_cache;
5033 }
5034 }
5035
5036 if (!is_array($labels)) $labels = get_article_labels($link, $id);
e2549229 5037
2eb9c95c
AD
5038 $labels_str = "<span id=\"HLLCTR-$id\">";
5039 $labels_str .= format_article_labels($labels, $id);
f9247195 5040 $labels_str .= "</span>";
8d505d78 5041
905ff52a 5042 if (count($topmost_article_ids) < 3) {
961f4c73
AD
5043 array_push($topmost_article_ids, $id);
5044 }
5045
784ac51f 5046 if ($line["last_read"] == "" && !sql_bool_to_bool($line["unread"])) {
8d505d78 5047
883fee8d 5048 $update_pic = "<img id='FUPDPIC-$id' src=\"".
8d505d78 5049 theme_image($link, 'images/updated.png')."\"
3de0261a
AD
5050 alt=\"Updated\">";
5051 } else {
8d505d78 5052 $update_pic = "<img id='FUPDPIC-$id' src=\"images/blank_icon.gif\"
3de0261a
AD
5053 alt=\"Updated\">";
5054 }
784ac51f 5055
8d505d78 5056 if (sql_bool_to_bool($line["unread"]) &&
784ac51f
AD
5057 time() - strtotime($line["updated_noms"]) < $fresh_intl) {
5058
e9823609
AD
5059 $update_pic = "<img id='FUPDPIC-$id' src=\"".
5060 theme_image($link, 'images/fresh_sign.png')."\" alt=\"Fresh\">";
784ac51f 5061 }
8d505d78 5062
3de0261a 5063 if ($line["unread"] == "t" || $line["unread"] == "1") {
ca8e3d75 5064 $class .= " Unread";
3de0261a
AD
5065 ++$num_unread;
5066 $is_unread = true;
5067 } else {
5068 $is_unread = false;
5069 }
abd8a516 5070
3de0261a 5071 if ($line["marked"] == "t" || $line["marked"] == "1") {
8d505d78
AD
5072 $marked_pic = "<img id=\"FMPIC-$id\"
5073 src=\"".theme_image($link, 'images/mark_set.png')."\"
5074 class=\"markedPic\" alt=\"Unstar article\"
b167df5e 5075 onclick='javascript:toggleMark($id)'>";
3de0261a 5076 } else {
8d505d78
AD
5077 $marked_pic = "<img id=\"FMPIC-$id\"
5078 src=\"".theme_image($link, 'images/mark_unset.png')."\"
5079 class=\"markedPic\" alt=\"Star article\"
b167df5e 5080 onclick='javascript:toggleMark($id)'>";
3de0261a
AD
5081 }
5082
e4f4b46f 5083 if ($line["published"] == "t" || $line["published"] == "1") {
8d505d78
AD
5084 $published_pic = "<img id=\"FPPIC-$id\" src=\"".theme_image($link,
5085 'images/pub_set.png')."\"
e4f4b46f 5086 class=\"markedPic\"
b167df5e 5087 alt=\"Unpublish article\" onclick='javascript:togglePub($id)'>";
e4f4b46f 5088 } else {
e9823609 5089 $published_pic = "<img id=\"FPPIC-$id\" src=\"".theme_image($link,
8d505d78 5090 'images/pub_unset.png')."\"
e4f4b46f 5091 class=\"markedPic\"
b167df5e 5092 alt=\"Publish article\" onclick='javascript:togglePub($id)'>";
e4f4b46f
AD
5093 }
5094
e944346c 5095# $content_link = "<a target=\"_blank\" href=\"".$line["link"]."\">" .
3de0261a
AD
5096# $line["title"] . "</a>";
5097
8d505d78 5098# $content_link = "<a
f0971fc1
AD
5099# href=\"" . htmlspecialchars($line["link"]) . "\"
5100# onclick=\"view($id,$feed_id);\">" .
5101# $line["title"] . "</a>";
3de0261a
AD
5102
5103# $content_link = "<a href=\"javascript:viewContentUrl('".$line["link"]."');\">" .
5104# $line["title"] . "</a>";
5105
8d505d78 5106 $updated_fmt = make_local_datetime($link, $line["updated_noms"], false);
3de0261a
AD
5107
5108 if (get_pref($link, 'SHOW_CONTENT_PREVIEW')) {
8d505d78 5109 $content_preview = truncate_string(strip_tags($line["content_preview"]),
3de0261a
AD
5110 100);
5111 }
5112
ff6e357a
AD
5113 $score = $line["score"];
5114
8d505d78 5115 $score_pic = theme_image($link,
883fee8d 5116 "images/" . get_score_pic($score));
546499a9 5117
9bf3f101 5118/* $score_title = __("(Click to change)");
8d505d78 5119 $score_pic = "<img class='hlScorePic' src=\"images/$score_pic\"
9bf3f101 5120 onclick=\"adjustArticleScore($id, $score)\" title=\"$score $score_title\">"; */
546499a9 5121
8d505d78 5122 $score_pic = "<img class='hlScorePic' src=\"$score_pic\"
9bf3f101 5123 title=\"$score\">";
ff6e357a 5124
5daa24f2
AD
5125 if ($score > 500) {
5126 $hlc_suffix = "H";
5127 } else if ($score < -100) {
5128 $hlc_suffix = "L";
5129 } else {
5130 $hlc_suffix = "";
5131 }
5132
3de0261a
AD
5133 $entry_author = $line["author"];
5134
5135 if ($entry_author) {
60164936 5136 $entry_author = " - $entry_author";
3de0261a
AD
5137 }
5138
7defa089 5139 $has_feed_icon = feed_has_icon($feed_id);
bd51294a
AD
5140
5141 if ($has_feed_icon) {
5142 $feed_icon_img = "<img class=\"tinyFeedIcon\" src=\"".ICONS_URL."/$feed_id.ico\" alt=\"\">";
5143 } else {
da4fb53f 5144 $feed_icon_img = "<img class=\"tinyFeedIcon\" src=\"images/feed-icon-12x12.png\" alt=\"\">";
bd51294a
AD
5145 }
5146
3de0261a 5147 if (!get_pref($link, 'COMBINED_DISPLAY_MODE')) {
6cfea5c7 5148
d00f22ac 5149 if (get_pref($link, 'VFEED_GROUP_BY_FEED')) {
bb031f91 5150 if ($feed_id != $vgroup_last_feed && $line["feed_title"]) {
a9bcfb8f
AD
5151
5152 $cur_feed_title = $line["feed_title"];
081e527d 5153 $vgroup_last_feed = $feed_id;
a9bcfb8f 5154
962d8ba4 5155 $cur_feed_title = htmlspecialchars($cur_feed_title);
43fc671f 5156
af163b85 5157 $vf_catchup_link = "(<a onclick='javascript:catchupFeedInGroup($feed_id);' href='#'>".__('mark as read')."</a>)";
a9bcfb8f 5158
bd202c3f 5159 $reply['content'] .= "<div class='cdmFeedTitle'>".
dc803347 5160 "<div style=\"float : right\">$feed_icon_img</div>".
4169bb67 5161 "<a href=\"#\" onclick=\"viewfeed($feed_id)\">".
8cc5e965
AD
5162 $line["feed_title"]."</a> $vf_catchup_link</div>";
5163
6cfea5c7
AD
5164 }
5165 }
314fcd2b 5166
8d505d78 5167 $mouseover_attrs = "onmouseover='postMouseIn($id)'
314fcd2b
AD
5168 onmouseout='postMouseOut($id)'";
5169
bd202c3f 5170 $reply['content'] .= "<div class='$class' id='RROW-$id' $mouseover_attrs>";
8cc5e965 5171
bd202c3f 5172 $reply['content'] .= "<div class='hlUpdPic'>$update_pic</div>";
8cc5e965 5173
bd202c3f 5174 $reply['content'] .= "<div class='hlLeft'>";
8cc5e965 5175
bd202c3f 5176 $reply['content'] .= "<input type=\"checkbox\" onclick=\"tSR(this)\"
8cc5e965 5177 id=\"RCHK-$id\">";
8d505d78 5178
bd202c3f
AD
5179 $reply['content'] .= "$marked_pic";
5180 $reply['content'] .= "$published_pic";
3de0261a 5181
bd202c3f 5182 $reply['content'] .= "</div>";
df456bb0 5183
bd202c3f 5184 $reply['content'] .= "<div onclick='return hlClicked(event, $id)'
8cc5e965 5185 class=\"hlTitle\"><span class='hlContent$hlc_suffix'>";
bd202c3f 5186 $reply['content'] .= "<a id=\"RTITLE-$id\"
f0971fc1 5187 href=\"" . htmlspecialchars($line["link"]) . "\"
ccdddcc2 5188 onclick=\"\">" .
d6571825 5189 truncate_string($line["title"], 200);
df456bb0
AD
5190
5191 if (get_pref($link, 'SHOW_CONTENT_PREVIEW')) {
5192 if ($content_preview) {
bd202c3f 5193 $reply['content'] .= "<span class=\"contentPreview\"> - $content_preview</span>";
3de0261a 5194 }
3de0261a 5195 }
df456bb0 5196
bd202c3f 5197 $reply['content'] .= "</a></span>";
df456bb0 5198
bd202c3f 5199 $reply['content'] .= $labels_str;
e2549229 5200
52c8007d
AD
5201 if (!get_pref($link, 'VFEED_GROUP_BY_FEED') &&
5202 defined('_SHOW_FEED_TITLE_IN_VFEEDS')) {
8d505d78 5203 if (@$line["feed_title"]) {
52c8007d 5204 $reply['content'] .= "<span class=\"hlFeed\">
4169bb67 5205 (<a href=\"#\" onclick=\"viewfeed($feed_id)\">".
6cfea5c7
AD
5206 $line["feed_title"]."</a>)
5207 </span>";
5208 }
52c8007d 5209 }
6e35a862 5210
bd202c3f 5211 $reply['content'] .= "</div>";
7b5e74c7 5212
bd202c3f 5213 $reply['content'] .= "<span class=\"hlUpdated\">$updated_fmt</span>";
6edeede3
AD
5214 $reply['content'] .= "<div class=\"hlRight\">";
5215
bd202c3f 5216 $reply['content'] .= $score_pic;
546499a9 5217
8cc5e965 5218 if ($line["feed_title"] && !get_pref($link, 'VFEED_GROUP_BY_FEED')) {
bd51294a 5219
bd202c3f 5220 $reply['content'] .= "<span onclick=\"viewfeed($feed_id)\"
4a06f46d 5221 style=\"cursor : pointer\"
8cc5e965
AD
5222 title=\"".htmlspecialchars($line['feed_title'])."\">
5223 $feed_icon_img<span>";
bd51294a
AD
5224 }
5225
bd202c3f
AD
5226 $reply['content'] .= "</div>";
5227 $reply['content'] .= "</div>";
3de0261a
AD
5228
5229 } else {
6cfea5c7 5230
bb031f91 5231 if (get_pref($link, 'VFEED_GROUP_BY_FEED') && $line["feed_title"]) {
081e527d
AD
5232 if ($feed_id != $vgroup_last_feed) {
5233
5234 $cur_feed_title = $line["feed_title"];
5235 $vgroup_last_feed = $feed_id;
5236
962d8ba4
AD
5237 $cur_feed_title = htmlspecialchars($cur_feed_title);
5238
af163b85 5239 $vf_catchup_link = "(<a onclick='javascript:catchupFeedInGroup($feed_id);' href='#'>".__('mark as read')."</a>)";
081e527d 5240
7defa089 5241 $has_feed_icon = feed_has_icon($feed_id);
dc803347
AD
5242
5243 if ($has_feed_icon) {
5244 $feed_icon_img = "<img class=\"tinyFeedIcon\" src=\"".ICONS_URL."/$feed_id.ico\" alt=\"\">";
5245 } else {
5246 //$feed_icon_img = "<img class=\"tinyFeedIcon\" src=\"images/blank_icon.gif\" alt=\"\">";
5247 }
5248
bd202c3f 5249 $reply['content'] .= "<div class='cdmFeedTitle'>".
dc803347 5250 "<div style=\"float : right\">$feed_icon_img</div>".
4169bb67 5251 "<a href=\"#\" onclick=\"viewfeed($feed_id)\">".
081e527d 5252 $line["feed_title"]."</a> $vf_catchup_link</div>";
6cfea5c7
AD
5253 }
5254 }
5255
0cacc891 5256 $expand_cdm = get_pref($link, 'CDM_EXPANDED');
0cacc891 5257
8d505d78 5258 $mouseover_attrs = "onmouseover='postMouseIn($id)'
314fcd2b
AD
5259 onmouseout='postMouseOut($id)'";
5260
bd202c3f 5261 $reply['content'] .= "<div class=\"$class\"
dd4c8697 5262 id=\"RROW-$id\" $mouseover_attrs'>";
3de0261a 5263
bd202c3f 5264 $reply['content'] .= "<div class=\"cdmHeader\">";
3de0261a 5265
915b61ef 5266 $reply['content'] .= "<div>";
8d505d78 5267
bd202c3f 5268 $reply['content'] .= "<input type=\"checkbox\" onclick=\"toggleSelectRowById(this,
ca8e3d75 5269 'RROW-$id')\" id=\"RCHK-$id\"/>";
5daa24f2 5270
bd202c3f
AD
5271 $reply['content'] .= "$marked_pic";
5272 $reply['content'] .= "$published_pic";
a7f003e0 5273
915b61ef
AD
5274 $reply['content'] .= "</div>";
5275
bd202c3f 5276 $reply['content'] .= "<span id=\"RTITLE-$id\"
dd4c8697 5277 onclick=\"return cdmClicked(event, $id);\"
dad14b51
AD
5278 class=\"titleWrap$hlc_suffix\">
5279 <a class=\"title\"
a64029e5 5280 title=\"".htmlspecialchars($line['title'])."\"
96d44601 5281 target=\"_blank\" href=\"".
a64029e5 5282 htmlspecialchars($line["link"])."\">".
8d505d78 5283 truncate_string($line["title"], 100) .
2547c9ec 5284 " $entry_author</a>";
0cacc891 5285
bd202c3f 5286 $reply['content'] .= $labels_str;
0cacc891 5287
52c8007d
AD
5288 if (!get_pref($link, 'VFEED_GROUP_BY_FEED') &&
5289 defined('_SHOW_FEED_TITLE_IN_VFEEDS')) {
5290 if (@$line["feed_title"]) {
5291 $reply['content'] .= "<span class=\"hlFeed\">
5292 (<a href=\"#\" onclick=\"viewfeed($feed_id)\">".
5293 $line["feed_title"]."</a>)
5294 </span>";
5295 }
5296 }
5297
02ef7e02 5298 if (!$expand_cdm)
dad14b51
AD
5299 $content_hidden = "style=\"display : none\"";
5300 else
5301 $excerpt_hidden = "style=\"display : none\"";
3de0261a 5302
bd202c3f 5303 $reply['content'] .= "<span $excerpt_hidden
dad14b51 5304 id=\"CEXC-$id\" class=\"cdmExcerpt\"> - $content_preview</span>";
3de0261a 5305
bd202c3f 5306 $reply['content'] .= "</span>";
dd4c8697 5307
915b61ef
AD
5308 $reply['content'] .= "<div>";
5309 $reply['content'] .= "<span class='updated'>$updated_fmt</span>";
5310 $reply['content'] .= "$score_pic";
5311
5312 if (!get_pref($link, "VFEED_GROUP_BY_FEED") && $line["feed_title"]) {
5313 $reply['content'] .= "<span style=\"cursor : pointer\"
5314 title=\"".htmlspecialchars($line["feed_title"])."\"
5315 onclick=\"viewfeed($feed_id)\">$feed_icon_img</span>";
5316 }
5317 $reply['content'] .= "<div class=\"updPic\">$update_pic</div>";
5318 $reply['content'] .= "</div>";
5319
bd202c3f 5320 $reply['content'] .= "</div>";
c9efd838 5321
bd202c3f 5322 $reply['content'] .= "<div class=\"cdmContent\" $content_hidden
dd4c8697 5323 onclick=\"return cdmClicked(event, $id);\"
dad14b51 5324 id=\"CICD-$id\">";
c9efd838 5325
bd202c3f 5326 $reply['content'] .= "<div class=\"cdmContentInner\">";
a04c8e8d 5327
dad14b51 5328 if ($line["orig_feed_id"]) {
494a64ea 5329
dad14b51
AD
5330 $tmp_result = db_query($link, "SELECT * FROM ttrss_archived_feeds
5331 WHERE id = ".$line["orig_feed_id"]);
494a64ea
AD
5332
5333 if (db_num_rows($tmp_result) != 0) {
8d505d78 5334
bd202c3f
AD
5335 $reply['content'] .= "<div clear='both'>";
5336 $reply['content'] .= __("Originally from:");
8d505d78 5337
bd202c3f 5338 $reply['content'] .= "&nbsp;";
8d505d78 5339
dad14b51 5340 $tmp_line = db_fetch_assoc($tmp_result);
8d505d78 5341
bd202c3f 5342 $reply['content'] .= "<a target='_blank'
dad14b51
AD
5343 href=' " . htmlspecialchars($tmp_line['site_url']) . "'>" .
5344 $tmp_line['title'] . "</a>";
8d505d78 5345
bd202c3f 5346 $reply['content'] .= "&nbsp;";
8d505d78 5347
bd202c3f
AD
5348 $reply['content'] .= "<a target='_blank' href='" . htmlspecialchars($tmp_line['feed_url']) . "'>";
5349 $reply['content'] .= "<img title='".__('Feed URL')."'class='tinyFeedIcon' src='images/pub_set.gif'></a>";
8d505d78 5350
bd202c3f 5351 $reply['content'] .= "</div>";
dad14b51 5352 }
494a64ea 5353 }
494a64ea 5354
d1fc2f92 5355 $feed_site_url = $line["site_url"];
9d3c031d 5356
b67897bf 5357 $article_content = sanitize_rss($link, $line["content_preview"],
62b800b4 5358 false, false, $feed_site_url);
621ffb00 5359
bd202c3f 5360 $reply['content'] .= "<div id=\"POSTNOTE-$id\">";
c7e51de1 5361 if ($line['note']) {
bd202c3f 5362 $reply['content'] .= format_article_note($id, $line['note']);
c7e51de1 5363 }
bd202c3f 5364 $reply['content'] .= "</div>";
c7e51de1 5365
b67897bf
AD
5366 $reply['content'] .= "<span id=\"CWRAP-$id\">";
5367 $reply['content'] .= $expand_cdm ? $article_content : '';
5368 $reply['content'] .= "</span>";
a3eeb471 5369
c0644ee4 5370/* $tmp_result = db_query($link, "SELECT always_display_enclosures FROM
dad14b51 5371 ttrss_feeds WHERE id = ".
8d505d78 5372 (($line['feed_id'] == null) ? $line['orig_feed_id'] :
c0644ee4 5373 $line['feed_id'])." AND owner_uid = ".$_SESSION["uid"]);
54e61a68 5374
8d505d78 5375 $always_display_enclosures = sql_bool_to_bool(db_fetch_result($tmp_result,
c0644ee4
AD
5376 0, "always_display_enclosures")); */
5377
5378 $always_display_enclosures = sql_bool_to_bool($line["always_display_enclosures"]);
a04c8e8d 5379
bd202c3f 5380 $reply['content'] .= format_article_enclosures($link, $id, $always_display_enclosures,
dad14b51 5381 $article_content);
a04c8e8d 5382
bd202c3f 5383 $reply['content'] .= "</div>";
3de0261a 5384
bd202c3f 5385 $reply['content'] .= "<div class=\"cdmFooter\">";
3de0261a 5386
9c506873
AD
5387 $tag_cache = $line["tag_cache"];
5388
ca5133cb
AD
5389 $tags_str = format_tags_string(
5390 get_article_tags($link, $id, $_SESSION["uid"], $tag_cache),
5391 $id);
dad14b51 5392
bd202c3f 5393 $reply['content'] .= "<img src='".theme_image($link,
dad14b51
AD
5394 'images/tag.png')."' alt='Tags' title='Tags'>
5395 <span id=\"ATSTR-$id\">$tags_str</span>
8d505d78 5396 <a title=\"".__('Edit tags for this article')."\"
4169bb67 5397 href=\"#\" onclick=\"editArticleTags($id, $feed_id, true)\">(+)</a>";
3de0261a 5398
13992673
AD
5399 $num_comments = $line["num_comments"];
5400 $entry_comments = "";
5401
5402 if ($num_comments > 0) {
5403 if ($line["comments"]) {
5404 $comments_url = $line["comments"];
5405 } else {
5406 $comments_url = $line["link"];
5407 }
5408 $entry_comments = "<a target='_blank' href=\"$comments_url\">$num_comments comments</a>";
5409 } else {
5410 if ($line["comments"] && $line["link"] != $line["comments"]) {
5411 $entry_comments = "<a target='_blank' href=\"".$line["comments"]."\">comments</a>";
5412 }
5413 }
5414
5415 if ($entry_comments) $reply['content'] .= "&nbsp;($entry_comments)";
5416
bd202c3f 5417 $reply['content'] .= "<div style=\"float : right\">";
3de0261a 5418
bd202c3f 5419 $reply['content'] .= "<img src=\"images/art-zoom.png\"
8a6702ad 5420 onclick=\"zoomToArticle(event, $id)\"
eedfb635 5421 style=\"cursor : pointer\"
8d505d78 5422 alt='Zoom'
6f3976c9 5423 title='".__('Open article in new tab')."'>";
dad14b51 5424
741b6090 5425 //$note_escaped = htmlspecialchars($line['note'], ENT_QUOTES);
411fe209 5426
bd202c3f 5427 $reply['content'] .= "<img src=\"images/art-pub-note.png\"
411fe209 5428 style=\"cursor : pointer\" style=\"cursor : pointer\"
741b6090
AD
5429 onclick=\"editArticleNote($id)\"
5430 alt='PubNote' title='".__('Edit article note')."'>";
411fe209 5431
dad14b51 5432 if (DIGEST_ENABLE) {
bd202c3f 5433 $reply['content'] .= "<img src=\"".theme_image($link, 'images/art-email.png')."\"
dad14b51
AD
5434 style=\"cursor : pointer\"
5435 onclick=\"emailArticle($id)\"
5436 alt='Zoom' title='".__('Forward by email')."'>";
5437 }
c7e51de1 5438
411fe209 5439 if (ENABLE_TWEET_BUTTON) {
bd202c3f 5440 $reply['content'] .= "<img src=\"".theme_image($link, 'images/art-tweet.png')."\"
411fe209
AD
5441 class='tagsPic' style=\"cursor : pointer\"
5442 onclick=\"tweetArticle($id)\"
5443 alt='Zoom' title='".__('Share on Twitter')."'>";
5444 }
c7e51de1 5445
db16ae50
AD
5446 $reply['content'] .= "<img src=\"".theme_image($link, 'images/art-share.png')."\"
5447 class='tagsPic' style=\"cursor : pointer\"
5448 onclick=\"shareArticle(".$line['int_id'].")\"
5449 alt='Zoom' title='".__('Share by URL')."'>";
5450
bd202c3f 5451 $reply['content'] .= "<img src=\"images/digest_checkbox.png\"
dad14b51 5452 style=\"cursor : pointer\" style=\"cursor : pointer\"
1ede5814 5453 onclick=\"dismissArticle($id)\"
dad14b51 5454 alt='Dismiss' title='".__('Dismiss article')."'>";
3de0261a 5455
bd202c3f
AD
5456 $reply['content'] .= "</div>";
5457 $reply['content'] .= "</div>";
3de0261a 5458
bd202c3f 5459 $reply['content'] .= "</div>";
3de0261a 5460
bd202c3f 5461 $reply['content'] .= "</div>";
3de0261a 5462
8d505d78
AD
5463 }
5464
3de0261a 5465 ++$lnum;
8d505d78 5466 }
3de0261a 5467
7d96bfcd
AD
5468 if ($_REQUEST["debug"]) $timing_info = print_checkpoint("PE", $timing_info);
5469
3de0261a 5470 } else {
93c841c4
AD
5471 $message = "";
5472
5473 switch ($view_mode) {
5474 case "unread":
5475 $message = __("No unread articles found to display.");
5476 break;
8b09eac8
AD
5477 case "updated":
5478 $message = __("No updated articles found to display.");
5479 break;
93c841c4
AD
5480 case "marked":
5481 $message = __("No starred articles found to display.");
5482 break;
5483 default:
215af892
AD
5484 if ($feed < -10) {
5485 $message = __("No articles found to display. You can assign articles to labels manually (see the Actions menu above) or use a filter.");
5486 } else {
5487 $message = __("No articles found to display.");
5488 }
93c841c4
AD
5489 }
5490
8f7c631e 5491 if (!$offset && $message) {
bd202c3f 5492 $reply['content'] .= "<div class='whiteBox'>$message";
8f7c631e 5493
bd202c3f 5494 $reply['content'] .= "<p class=\"small\"><span class=\"insensitive\">";
8f7c631e
AD
5495
5496 $result = db_query($link, "SELECT ".SUBSTRING_FOR_DATE."(MAX(last_updated), 1, 19) AS last_updated FROM ttrss_feeds
5497 WHERE owner_uid = " . $_SESSION['uid']);
8d505d78 5498
8f7c631e
AD
5499 $last_updated = db_fetch_result($result, 0, "last_updated");
5500 $last_updated = make_local_datetime($link, $last_updated, false);
8d505d78 5501
bd202c3f 5502 $reply['content'] .= sprintf(__("Feeds last updated at %s"), $last_updated);
8d505d78 5503
8f7c631e
AD
5504 $result = db_query($link, "SELECT COUNT(id) AS num_errors
5505 FROM ttrss_feeds WHERE last_error != '' AND owner_uid = ".$_SESSION["uid"]);
8d505d78 5506
8f7c631e 5507 $num_errors = db_fetch_result($result, 0, "num_errors");
8d505d78 5508
8f7c631e 5509 if ($num_errors > 0) {
bd202c3f
AD
5510 $reply['content'] .= "<br/>";
5511 $reply['content'] .= "<a class=\"insensitive\" href=\"#\" onclick=\"showFeedsWithErrors()\">".
8f7c631e
AD
5512 __('Some feeds have update errors (click for details)')."</a>";
5513 }
bd202c3f 5514 $reply['content'] .= "</span></p></div>";
8f7c631e 5515 }
3de0261a
AD
5516 }
5517
7d96bfcd
AD
5518 if ($_REQUEST["debug"]) $timing_info = print_checkpoint("H2", $timing_info);
5519
bd202c3f 5520 return array($topmost_article_ids, $headlines_count, $feed, $disable_cache,
7d96bfcd 5521 $vgroup_last_feed, $reply);
3de0261a 5522 }
0979b696
AD
5523
5524// from here: http://www.roscripts.com/Create_tag_cloud-71.html
5525
5526 function printTagCloud($link) {
35a03bdd 5527
8d505d78
AD
5528 $query = "SELECT tag_name, COUNT(post_int_id) AS count
5529 FROM ttrss_tags WHERE owner_uid = ".$_SESSION["uid"]."
b31af972 5530 GROUP BY tag_name ORDER BY count DESC LIMIT 50";
0979b696
AD
5531
5532 $result = db_query($link, $query);
5533
5534 $tags = array();
5535
5536 while ($line = db_fetch_assoc($result)) {
5537 $tags[$line["tag_name"]] = $line["count"];
5538 }
5539
9949bd15
CM
5540 if( count($tags) == 0 ){ return; }
5541
0979b696
AD
5542 ksort($tags);
5543
5544 $max_size = 32; // max font size in pixels
4548a580 5545 $min_size = 11; // min font size in pixels
8d505d78 5546
0979b696
AD
5547 // largest and smallest array values
5548 $max_qty = max(array_values($tags));
5549 $min_qty = min(array_values($tags));
8d505d78 5550
0979b696
AD
5551 // find the range of values
5552 $spread = $max_qty - $min_qty;
5553 if ($spread == 0) { // we don't want to divide by zero
5554 $spread = 1;
5555 }
8d505d78 5556
0979b696
AD
5557 // set the font-size increment
5558 $step = ($max_size - $min_size) / ($spread);
8d505d78 5559
0979b696
AD
5560 // loop through the tag array
5561 foreach ($tags as $key => $value) {
5562 // calculate font-size
5563 // find the $value in excess of $min_qty
5564 // multiply by the font-size increment ($size)
5565 // and add the $min_size set above
5566 $size = round($min_size + (($value - $min_qty) * $step));
546ffab4
AD
5567
5568 $key_escaped = str_replace("'", "\\'", $key);
5569
8d505d78
AD
5570 echo "<a href=\"javascript:viewfeed('$key_escaped') \" style=\"font-size: " .
5571 $size . "px\" title=\"$value articles tagged with " .
0979b696
AD
5572 $key . '">' . $key . '</a> ';
5573 }
5574 }
46921916
AD
5575
5576 function print_checkpoint($n, $s) {
8d505d78 5577 $ts = getmicrotime();
46921916
AD
5578 echo sprintf("<!-- CP[$n] %.4f seconds -->", $ts - $s);
5579 return $ts;
5580 }
14b6c54b
AD
5581
5582 function sanitize_tag($tag) {
5583 $tag = trim($tag);
5584
5585 $tag = mb_strtolower($tag, 'utf-8');
5586
78ccac0b 5587 $tag = preg_replace('/[\'\"\+\>\<]/', "", $tag);
0c3d1c68 5588
8d505d78
AD
5589// $tag = str_replace('"', "", $tag);
5590// $tag = str_replace("+", " ", $tag);
14b6c54b
AD
5591 $tag = str_replace("technorati tag: ", "", $tag);
5592
5593 return $tag;
5594 }
e4f4b46f 5595
8801fb01 5596 function get_self_url_prefix() {
ed102aa0 5597 return SELF_URL_PATH;
8801fb01 5598 }
b9d54789 5599
8801fb01 5600 function opml_publish_url($link){
e0dc56d4 5601
8801fb01 5602 $url_path = get_self_url_prefix();
8d505d78 5603 $url_path .= "/opml.php?op=publish&key=" .
2e7f046f 5604 get_feed_access_key($link, 'OPML:Publish', false, $_SESSION["uid"]);
e0dc56d4
MK
5605
5606 return $url_path;
5607 }
f56e3080 5608
45004d43
AD
5609 /**
5610 * Purge a feed contents, marked articles excepted.
8d505d78 5611 *
45004d43
AD
5612 * @param mixed $link The database connection.
5613 * @param integer $id The id of the feed to purge.
5614 * @return void
5615 */
d1f0c584 5616 function clear_feed_articles($link, $id) {
e04c18a2
AD
5617
5618 if ($id != 0) {
5619 $result = db_query($link, "DELETE FROM ttrss_user_entries
a8ae1b9a 5620 WHERE feed_id = '$id' AND marked = false AND owner_uid = " . $_SESSION["uid"]);
e04c18a2
AD
5621 } else {
5622 $result = db_query($link, "DELETE FROM ttrss_user_entries
5623 WHERE feed_id IS NULL AND marked = false AND owner_uid = " . $_SESSION["uid"]);
5624 }
d1f0c584 5625
8d505d78 5626 $result = db_query($link, "DELETE FROM ttrss_entries WHERE
d1f0c584 5627 (SELECT COUNT(int_id) FROM ttrss_user_entries WHERE ref_id = id) = 0");
ced46404
AD
5628
5629 ccache_update($link, $id, $_SESSION['uid']);
45004d43
AD
5630 } // function clear_feed_articles
5631
5632 /**
5633 * Compute the Mozilla Firefox feed adding URL from server HOST and REQUEST_URI.
5634 *
5635 * @return string The Mozilla Firefox feed adding URL.
5636 */
5637 function add_feed_url() {
ed102aa0
AD
5638 //$url_path = ($_SERVER['HTTPS'] != "on" ? 'http://' : 'https://') . $_SERVER["HTTP_HOST"] . parse_url($_SERVER["REQUEST_URI"], PHP_URL_PATH);
5639
5640 $url_path = get_self_url_prefix() .
f30ef1fa 5641 "/backend.php?op=pref-feeds&quiet=1&method=add&feed_url=%s";
755a43ee 5642 return $url_path;
45004d43
AD
5643 } // function add_feed_url
5644
5645 /**
5646 * Encrypt a password in SHA1.
8d505d78 5647 *
45004d43
AD
5648 * @param string $pass The password to encrypt.
5649 * @param string $login A optionnal login.
5650 * @return string The encrypted password.
5651 */
1a9f4d3c
AD
5652 function encrypt_password($pass, $login = '') {
5653 if ($login) {
5654 return "SHA1X:" . sha1("$login:$pass");
5655 } else {
5656 return "SHA1:" . sha1($pass);
5657 }
45004d43
AD
5658 } // function encrypt_password
5659
5660 /**
5661 * Update a feed batch.
5662 * Used by daemons to update n feeds by run.
5663 * Only update feed needing a update, and not being processed
5664 * by another process.
8d505d78 5665 *
45004d43
AD
5666 * @param mixed $link Database link
5667 * @param integer $limit Maximum number of feeds in update batch. Default to DAEMON_FEED_LIMIT.
5668 * @param boolean $from_http Set to true if you call this function from http to disable cli specific code.
5669 * @param boolean $debug Set to false to disable debug output. Default to true.
5670 * @return void
5671 */
5672 function update_daemon_common($link, $limit = DAEMON_FEED_LIMIT, $from_http = false, $debug = true) {
5673 // Process all other feeds using last_updated and interval parameters
5674
5675 // Test if the user has loggued in recently. If not, it does not update its feeds.
5676 if (DAEMON_UPDATE_LOGIN_LIMIT > 0) {
5677 if (DB_TYPE == "pgsql") {
5678 $login_thresh_qpart = "AND ttrss_users.last_login >= NOW() - INTERVAL '".DAEMON_UPDATE_LOGIN_LIMIT." days'";
5679 } else {
5680 $login_thresh_qpart = "AND ttrss_users.last_login >= DATE_SUB(NOW(), INTERVAL ".DAEMON_UPDATE_LOGIN_LIMIT." DAY)";
8d505d78 5681 }
45004d43
AD
5682 } else {
5683 $login_thresh_qpart = "";
5684 }
5685
5686 // Test if the feed need a update (update interval exceded).
5687 if (DB_TYPE == "pgsql") {
5688 $update_limit_qpart = "AND ((
5689 ttrss_feeds.update_interval = 0
5690 AND ttrss_feeds.last_updated < NOW() - CAST((ttrss_user_prefs.value || ' minutes') AS INTERVAL)
5691 ) OR (
5692 ttrss_feeds.update_interval > 0
5693 AND ttrss_feeds.last_updated < NOW() - CAST((ttrss_feeds.update_interval || ' minutes') AS INTERVAL)
da4caf5d 5694 ) OR ttrss_feeds.last_updated IS NULL)";
45004d43
AD
5695 } else {
5696 $update_limit_qpart = "AND ((
5697 ttrss_feeds.update_interval = 0
5698 AND ttrss_feeds.last_updated < DATE_SUB(NOW(), INTERVAL CONVERT(ttrss_user_prefs.value, SIGNED INTEGER) MINUTE)
5699 ) OR (
5700 ttrss_feeds.update_interval > 0
5701 AND ttrss_feeds.last_updated < DATE_SUB(NOW(), INTERVAL ttrss_feeds.update_interval MINUTE)
da4caf5d 5702 ) OR ttrss_feeds.last_updated IS NULL)";
45004d43
AD
5703 }
5704
5705 // Test if feed is currently being updated by another process.
5706 if (DB_TYPE == "pgsql") {
359fc686 5707 $updstart_thresh_qpart = "AND (ttrss_feeds.last_update_started IS NULL OR ttrss_feeds.last_update_started < NOW() - INTERVAL '5 minutes')";
45004d43 5708 } else {
359fc686 5709 $updstart_thresh_qpart = "AND (ttrss_feeds.last_update_started IS NULL OR ttrss_feeds.last_update_started < DATE_SUB(NOW(), INTERVAL 5 MINUTE))";
45004d43
AD
5710 }
5711
5712 // Test if there is a limit to number of updated feeds
5713 $query_limit = "";
5714 if($limit) $query_limit = sprintf("LIMIT %d", $limit);
5715
51b8c957
AD
5716 $random_qpart = sql_random_function();
5717
45004d43
AD
5718 // We search for feed needing update.
5719 $result = db_query($link, "SELECT ttrss_feeds.feed_url,ttrss_feeds.id, ttrss_feeds.owner_uid,
fc2b26a6 5720 ".SUBSTRING_FOR_DATE."(ttrss_feeds.last_updated,1,19) AS last_updated,
8d505d78
AD
5721 ttrss_feeds.update_interval
5722 FROM
45004d43
AD
5723 ttrss_feeds, ttrss_users, ttrss_user_prefs
5724 WHERE
5725 ttrss_feeds.owner_uid = ttrss_users.id
5726 AND ttrss_users.id = ttrss_user_prefs.owner_uid
5727 AND ttrss_user_prefs.pref_name = 'DEFAULT_UPDATE_INTERVAL'
5728 $login_thresh_qpart $update_limit_qpart
51b8c957
AD
5729 $updstart_thresh_qpart
5730 ORDER BY $random_qpart $query_limit");
45004d43
AD
5731
5732 $user_prefs_cache = array();
5733
5734 if($debug) _debug(sprintf("Scheduled %d feeds to update...\n", db_num_rows($result)));
5735
5736 // Here is a little cache magic in order to minimize risk of double feed updates.
5737 $feeds_to_update = array();
5738 while ($line = db_fetch_assoc($result)) {
5739 $feeds_to_update[$line['id']] = $line;
5740 }
5741
5742 // We update the feed last update started date before anything else.
5743 // There is no lag due to feed contents downloads
5744 // It prevent an other process to update the same feed.
5745 $feed_ids = array_keys($feeds_to_update);
5746 if($feed_ids) {
5747 db_query($link, sprintf("UPDATE ttrss_feeds SET last_update_started = NOW()
5748 WHERE id IN (%s)", implode(',', $feed_ids)));
5749 }
5750
5751 // For each feed, we call the feed update function.
5752 while ($line = array_pop($feeds_to_update)) {
5753
5754 if($debug) _debug("Feed: " . $line["feed_url"] . ", " . $line["last_updated"]);
5755
cce9822a
AD
5756 update_rss_feed($link, $line["id"], true);
5757
45004d43
AD
5758 sleep(1); // prevent flood (FIXME make this an option?)
5759 }
5760
0e0dd486
AD
5761 // Send feed digests by email if needed.
5762 if (DAEMON_SENDS_DIGESTS) send_headlines_digests($link);
5763
45004d43 5764 } // function update_daemon_common
1a9f4d3c 5765
621ffb00
AD
5766 function sanitize_article_content($text) {
5767 # we don't support CDATA sections in articles, they break our own escaping
5768 $text = preg_replace("/\[\[CDATA/", "", $text);
5769 $text = preg_replace("/\]\]\>/", "", $text);
5770 return $text;
5771 }
fee840fb
AD
5772
5773 function load_filters($link, $feed, $owner_uid, $action_id = false) {
5774 $filters = array();
5775
b8ffa322 5776 global $memcache;
fee840fb 5777
1f011328
AD
5778 $obj_id = md5("FILTER:$feed:$owner_uid:$action_id");
5779
b8ffa322
AD
5780 if ($memcache && $obj = $memcache->get($obj_id)) {
5781
b8ffa322
AD
5782 return $obj;
5783
5784 } else {
fee840fb 5785
b8ffa322 5786 if ($action_id) $ftype_query_part = "action_id = '$action_id' AND";
8d505d78 5787
b8ffa322
AD
5788 $result = db_query($link, "SELECT reg_exp,
5789 ttrss_filter_types.name AS name,
5790 ttrss_filter_actions.name AS action,
5791 inverse,
5792 action_param,
5793 filter_param
8d505d78 5794 FROM ttrss_filters,ttrss_filter_types,ttrss_filter_actions WHERE
b8ffa322
AD
5795 enabled = true AND
5796 $ftype_query_part
5797 owner_uid = $owner_uid AND
5798 ttrss_filter_types.id = filter_type AND
5799 ttrss_filter_actions.id = action_id AND
5800 (feed_id IS NULL OR feed_id = '$feed') ORDER BY reg_exp");
8d505d78 5801
b8ffa322
AD
5802 while ($line = db_fetch_assoc($result)) {
5803 if (!$filters[$line["name"]]) $filters[$line["name"]] = array();
5804 $filter["reg_exp"] = $line["reg_exp"];
5805 $filter["action"] = $line["action"];
5806 $filter["action_param"] = $line["action_param"];
5807 $filter["filter_param"] = $line["filter_param"];
5808 $filter["inverse"] = sql_bool_to_bool($line["inverse"]);
8d505d78 5809
b8ffa322
AD
5810 array_push($filters[$line["name"]], $filter);
5811 }
5812
5813 if ($memcache) $memcache->add($obj_id, $filters, 0, 3600*8);
5814
5815 return $filters;
5816 }
fee840fb 5817 }
1e36af0c
AD
5818
5819 function get_score_pic($score) {
8d505d78
AD
5820 if ($score > 100) {
5821 return "score_high.png";
5822 } else if ($score > 0) {
883fee8d 5823 return "score_half_high.png";
1cce3aca 5824 } else if ($score < -100) {
883fee8d 5825 return "score_low.png";
1cce3aca 5826 } else if ($score < 0) {
883fee8d 5827 return "score_half_low.png";
8d505d78 5828 } else {
883fee8d 5829 return "score_neutral.png";
1e36af0c
AD
5830 }
5831 }
ec92c9d1 5832
7defa089
AD
5833 function feed_has_icon($id) {
5834 return is_file(ICONS_DIR . "/$id.ico") && filesize(ICONS_DIR . "/$id.ico") > 0;
5835 }
f29ba148
AD
5836
5837 function init_connection($link) {
5f0a3741 5838 if ($link) {
324944f3 5839
5f0a3741
AD
5840 if (DB_TYPE == "pgsql") {
5841 pg_query($link, "set client_encoding = 'UTF-8'");
5842 pg_set_client_encoding("UNICODE");
5843 pg_query($link, "set datestyle = 'ISO, european'");
5844 pg_query($link, "set TIME ZONE 0");
5845 } else {
5846 db_query($link, "SET time_zone = '+0:0'");
5847
5848 if (defined('MYSQL_CHARSET') && MYSQL_CHARSET) {
5849 db_query($link, "SET NAMES " . MYSQL_CHARSET);
5850 }
f29ba148 5851 }
5f0a3741
AD
5852 return true;
5853 } else {
5854 print "Unable to connect to database:" . db_last_error();
5855 return false;
f29ba148
AD
5856 }
5857 }
5e96ca9d
AD
5858
5859 function update_feedbrowser_cache($link) {
5860
109662e1 5861 $result = db_query($link, "SELECT feed_url, site_url, title, COUNT(id) AS subscribers
8d505d78
AD
5862 FROM ttrss_feeds WHERE (SELECT COUNT(id) = 0 FROM ttrss_feeds AS tf
5863 WHERE tf.feed_url = ttrss_feeds.feed_url
d206ae1d 5864 AND (private IS true OR auth_login != '' OR auth_pass != '' OR feed_url LIKE '%:%@%/%'))
109662e1 5865 GROUP BY feed_url, site_url, title ORDER BY subscribers DESC LIMIT 1000");
8d505d78 5866
5e96ca9d 5867 db_query($link, "BEGIN");
8d505d78 5868
5e96ca9d 5869 db_query($link, "DELETE FROM ttrss_feedbrowser_cache");
8d505d78 5870
5e96ca9d 5871 $count = 0;
8d505d78 5872
5e96ca9d
AD
5873 while ($line = db_fetch_assoc($result)) {
5874 $subscribers = db_escape_string($line["subscribers"]);
5875 $feed_url = db_escape_string($line["feed_url"]);
931dcbc1 5876 $title = db_escape_string($line["title"]);
109662e1 5877 $site_url = db_escape_string($line["site_url"]);
931dcbc1
AD
5878
5879 $tmp_result = db_query($link, "SELECT subscribers FROM
5880 ttrss_feedbrowser_cache WHERE feed_url = '$feed_url'");
5881
5882 if (db_num_rows($tmp_result) == 0) {
5883
8d505d78 5884 db_query($link, "INSERT INTO ttrss_feedbrowser_cache
109662e1
AD
5885 (feed_url, site_url, title, subscribers) VALUES ('$feed_url',
5886 '$site_url', '$title', '$subscribers')");
931dcbc1
AD
5887
5888 ++$count;
5889
5890 }
8d505d78 5891
5e96ca9d 5892 }
8d505d78 5893
5e96ca9d
AD
5894 db_query($link, "COMMIT");
5895
5896 return $count;
5897
5898 }
2627f2d0 5899
0bfbf1c2 5900 /* function ccache_zero($link, $feed_id, $owner_uid) {
2627f2d0
AD
5901 db_query($link, "UPDATE ttrss_counters_cache SET
5902 value = 0, updated = NOW() WHERE
5903 feed_id = '$feed_id' AND owner_uid = '$owner_uid'");
0bfbf1c2 5904 } */
2627f2d0 5905
ad0056a8
AD
5906 function ccache_zero_all($link, $owner_uid) {
5907 db_query($link, "UPDATE ttrss_counters_cache SET
5908 value = 0 WHERE owner_uid = '$owner_uid'");
5909
5910 db_query($link, "UPDATE ttrss_cat_counters_cache SET
5911 value = 0 WHERE owner_uid = '$owner_uid'");
5912 }
5913
c7e51de1
AD
5914 function ccache_remove($link, $feed_id, $owner_uid, $is_cat = false) {
5915
5916 if (!$is_cat) {
5917 $table = "ttrss_counters_cache";
5918 } else {
5919 $table = "ttrss_cat_counters_cache";
5920 }
5921
5922 db_query($link, "DELETE FROM $table WHERE
5923 feed_id = '$feed_id' AND owner_uid = '$owner_uid'");
5924
5925 }
5926
5f4f7adf
AD
5927 function ccache_update_all($link, $owner_uid) {
5928
5929 if (get_pref($link, 'ENABLE_FEED_CATS', $owner_uid)) {
5930
5931 $result = db_query($link, "SELECT feed_id FROM ttrss_cat_counters_cache
5932 WHERE feed_id > 0 AND owner_uid = '$owner_uid'");
5933
5934 while ($line = db_fetch_assoc($result)) {
5935 ccache_update($link, $line["feed_id"], $owner_uid, true);
5936 }
5937
c5ffeb61
AD
5938 /* We have to manually include category 0 */
5939
5940 ccache_update($link, 0, $owner_uid, true);
5941
8a4c759e 5942 } else {
5f4f7adf
AD
5943 $result = db_query($link, "SELECT feed_id FROM ttrss_counters_cache
5944 WHERE feed_id > 0 AND owner_uid = '$owner_uid'");
8a4c759e 5945
5f4f7adf
AD
5946 while ($line = db_fetch_assoc($result)) {
5947 print ccache_update($link, $line["feed_id"], $owner_uid);
5948
5949 }
5950
5951 }
5952 }
2627f2d0 5953
8d505d78 5954 function ccache_find($link, $feed_id, $owner_uid, $is_cat = false,
6b49a3dd 5955 $no_update = false) {
8a4c759e 5956
5c432ba4
AD
5957 if (!is_numeric($feed_id)) return;
5958
8a4c759e
AD
5959 if (!$is_cat) {
5960 $table = "ttrss_counters_cache";
32d2181b 5961 if ($feed_id > 0) {
8d505d78 5962 $tmp_result = db_query($link, "SELECT owner_uid FROM ttrss_feeds
32d2181b
AD
5963 WHERE id = '$feed_id'");
5964 $owner_uid = db_fetch_result($tmp_result, 0, "owner_uid");
5965 }
8a4c759e
AD
5966 } else {
5967 $table = "ttrss_cat_counters_cache";
5968 }
5969
5970 if (DB_TYPE == "pgsql") {
5971 $date_qpart = "updated > NOW() - INTERVAL '15 minutes'";
5972 } else if (DB_TYPE == "mysql") {
5973 $date_qpart = "updated > DATE_SUB(NOW(), INTERVAL 15 MINUTE)";
5974 }
5975
5976 $result = db_query($link, "SELECT value FROM $table
8d505d78 5977 WHERE owner_uid = '$owner_uid' AND feed_id = '$feed_id'
37fb651d 5978 LIMIT 1");
2627f2d0
AD
5979
5980 if (db_num_rows($result) == 1) {
5981 return db_fetch_result($result, 0, "value");
5982 } else {
6b49a3dd
AD
5983 if ($no_update) {
5984 return -1;
5985 } else {
5986 return ccache_update($link, $feed_id, $owner_uid, $is_cat);
5987 }
2627f2d0
AD
5988 }
5989
5990 }
5991
8d505d78 5992 function ccache_update($link, $feed_id, $owner_uid, $is_cat = false,
6b49a3dd
AD
5993 $update_pcat = true) {
5994
5c432ba4
AD
5995 if (!is_numeric($feed_id)) return;
5996
32d2181b 5997 if (!$is_cat && $feed_id > 0) {
8d505d78 5998 $tmp_result = db_query($link, "SELECT owner_uid FROM ttrss_feeds
2e93b64c
AD
5999 WHERE id = '$feed_id'");
6000 $owner_uid = db_fetch_result($tmp_result, 0, "owner_uid");
6001 }
6002
43ead405
AD
6003 $prev_unread = ccache_find($link, $feed_id, $owner_uid, $is_cat, true);
6004
6005 /* When updating a label, all we need to do is recalculate feed counters
6006 * because labels are not cached */
c98e43db
AD
6007
6008 if ($feed_id < 0) {
43ead405
AD
6009 ccache_update_all($link, $owner_uid);
6010 return;
c98e43db
AD
6011 }
6012
8a4c759e
AD
6013 if (!$is_cat) {
6014 $table = "ttrss_counters_cache";
6015 } else {
6016 $table = "ttrss_cat_counters_cache";
6017 }
6018
b6d486a3 6019 if ($is_cat && $feed_id >= 0) {
37fb651d
AD
6020 if ($feed_id != 0) {
6021 $cat_qpart = "cat_id = '$feed_id'";
6022 } else {
6023 $cat_qpart = "cat_id IS NULL";
6024 }
6025
6b49a3dd
AD
6026 /* Recalculate counters for child feeds */
6027
6028 $result = db_query($link, "SELECT id FROM ttrss_feeds
6029 WHERE owner_uid = '$owner_uid' AND $cat_qpart");
6030
6031 while ($line = db_fetch_assoc($result)) {
6032 ccache_update($link, $line["id"], $owner_uid, false, false);
6033 }
6034
8d505d78
AD
6035 $result = db_query($link, "SELECT SUM(value) AS sv
6036 FROM ttrss_counters_cache, ttrss_feeds
6037 WHERE id = feed_id AND $cat_qpart AND
37fb651d
AD
6038 ttrss_feeds.owner_uid = '$owner_uid'");
6039
51e196de 6040 $unread = (int) db_fetch_result($result, 0, "sv");
37fb651d 6041
f55b0b12
AD
6042 } else {
6043 $unread = (int) getFeedArticles($link, $feed_id, $is_cat, true, $owner_uid);
37fb651d 6044 }
2627f2d0 6045
c7e51de1
AD
6046 db_query($link, "BEGIN");
6047
8a4c759e 6048 $result = db_query($link, "SELECT feed_id FROM $table
2627f2d0
AD
6049 WHERE owner_uid = '$owner_uid' AND feed_id = '$feed_id' LIMIT 1");
6050
6051 if (db_num_rows($result) == 1) {
8a4c759e 6052 db_query($link, "UPDATE $table SET
2627f2d0
AD
6053 value = '$unread', updated = NOW() WHERE
6054 feed_id = '$feed_id' AND owner_uid = '$owner_uid'");
6055
6056 } else {
8a4c759e 6057 db_query($link, "INSERT INTO $table
8d505d78
AD
6058 (feed_id, value, owner_uid, updated)
6059 VALUES
2627f2d0 6060 ($feed_id, $unread, $owner_uid, NOW())");
2627f2d0
AD
6061 }
6062
c7e51de1
AD
6063 db_query($link, "COMMIT");
6064
6b49a3dd 6065 if ($feed_id > 0 && $prev_unread != $unread) {
8a4c759e 6066
37fb651d 6067 if (!$is_cat) {
8a4c759e 6068
6b49a3dd 6069 /* Update parent category */
8a4c759e 6070
6b49a3dd 6071 if ($update_pcat) {
37fb651d 6072
6b49a3dd
AD
6073 $result = db_query($link, "SELECT cat_id FROM ttrss_feeds
6074 WHERE owner_uid = '$owner_uid' AND id = '$feed_id'");
8a4c759e 6075
6b49a3dd 6076 $cat_id = (int) db_fetch_result($result, 0, "cat_id");
37fb651d 6077
6b49a3dd 6078 ccache_update($link, $cat_id, $owner_uid, true);
6c2a9b9e 6079
6c2a9b9e 6080 }
8a4c759e 6081 }
5f4f7adf
AD
6082 } else if ($feed_id < 0) {
6083 ccache_update_all($link, $owner_uid);
8a4c759e
AD
6084 }
6085
6086 return $unread;
2627f2d0 6087 }
ceb30ba4 6088
0bfbf1c2 6089 /* function ccache_cleanup($link, $owner_uid) {
3261ca58 6090
cd9da663
AD
6091 if (DB_TYPE == "pgsql") {
6092 db_query($link, "DELETE FROM ttrss_counters_cache AS c1 WHERE
6093 (SELECT count(*) FROM ttrss_counters_cache AS c2
6094 WHERE c1.feed_id = c2.feed_id AND c2.owner_uid = c1.owner_uid) > 1
6095 AND owner_uid = '$owner_uid'");
6096
6097 db_query($link, "DELETE FROM ttrss_cat_counters_cache AS c1 WHERE
6098 (SELECT count(*) FROM ttrss_cat_counters_cache AS c2
6099 WHERE c1.feed_id = c2.feed_id AND c2.owner_uid = c1.owner_uid) > 1
3261ca58 6100 AND owner_uid = '$owner_uid'");
cd9da663
AD
6101 } else {
6102 db_query($link, "DELETE c1 FROM
6103 ttrss_counters_cache AS c1,
6104 ttrss_counters_cache AS c2
6105 WHERE
6106 c1.owner_uid = '$owner_uid' AND
6107 c1.owner_uid = c2.owner_uid AND
6108 c1.feed_id = c2.feed_id");
6109
6110 db_query($link, "DELETE c1 FROM
6111 ttrss_cat_counters_cache AS c1,
6112 ttrss_cat_counters_cache AS c2
6113 WHERE
6114 c1.owner_uid = '$owner_uid' AND
6115 c1.owner_uid = c2.owner_uid AND
6116 c1.feed_id = c2.feed_id");
6117
6118 }
0bfbf1c2 6119 } */
3261ca58 6120
ceb30ba4 6121 function label_find_id($link, $label, $owner_uid) {
8d505d78
AD
6122 $result = db_query($link,
6123 "SELECT id FROM ttrss_labels2 WHERE caption = '$label'
ceb30ba4
AD
6124 AND owner_uid = '$owner_uid' LIMIT 1");
6125
6126 if (db_num_rows($result) == 1) {
6127 return db_fetch_result($result, 0, "id");
6128 } else {
6129 return 0;
6130 }
6131 }
6132
814bff66 6133 function get_article_labels($link, $id) {
d721a547
AD
6134 global $memcache;
6135
d721a547
AD
6136 $obj_id = md5("LABELS:$id:" . $_SESSION["uid"]);
6137
814bff66
AD
6138 $rv = array();
6139
d721a547
AD
6140 if ($memcache && $obj = $memcache->get($obj_id)) {
6141 return $obj;
6142 } else {
905ff52a
AD
6143
6144 $result = db_query($link, "SELECT label_cache FROM
6145 ttrss_user_entries WHERE ref_id = '$id' AND owner_uid = " .
6146 $_SESSION["uid"]);
6147
6148 $label_cache = db_fetch_result($result, 0, "label_cache");
6149
6150 if ($label_cache) {
6151
6152 $label_cache = json_decode($label_cache, true);
6153
6154 if ($label_cache["no-labels"] == 1)
6155 return $rv;
6156 else
6157 return $label_cache;
6158 }
6159
8d505d78
AD
6160 $result = db_query($link,
6161 "SELECT DISTINCT label_id,caption,fg_color,bg_color
6162 FROM ttrss_labels2, ttrss_user_labels2
6163 WHERE id = label_id
6164 AND article_id = '$id'
905ff52a
AD
6165 AND owner_uid = ".$_SESSION["uid"] . "
6166 ORDER BY caption");
6167
d721a547
AD
6168 while ($line = db_fetch_assoc($result)) {
6169 $rk = array($line["label_id"], $line["caption"], $line["fg_color"],
6170 $line["bg_color"]);
6171 array_push($rv, $rk);
6172 }
6173 if ($memcache) $memcache->add($obj_id, $rv, 0, 3600);
905ff52a 6174
8d505d78 6175 if (count($rv) > 0)
905ff52a
AD
6176 label_update_cache($link, $id, $rv);
6177 else
6178 label_update_cache($link, $id, array("no-labels" => 1));
814bff66
AD
6179 }
6180
6181 return $rv;
6182 }
6183
6184
b8a637f3 6185 function label_find_caption($link, $label, $owner_uid) {
8d505d78
AD
6186 $result = db_query($link,
6187 "SELECT caption FROM ttrss_labels2 WHERE id = '$label'
b8a637f3
AD
6188 AND owner_uid = '$owner_uid' LIMIT 1");
6189
6190 if (db_num_rows($result) == 1) {
6191 return db_fetch_result($result, 0, "caption");
6192 } else {
6193 return "";
6194 }
6195 }
6196
905ff52a
AD
6197 function label_update_cache($link, $id, $labels = false, $force = false) {
6198
6199 if ($force)
6200 label_clear_cache($link, $id);
6201
8d505d78 6202 if (!$labels)
905ff52a
AD
6203 $labels = get_article_labels($link, $id);
6204
6205 $labels = db_escape_string(json_encode($labels));
6206
6207 db_query($link, "UPDATE ttrss_user_entries SET
6208 label_cache = '$labels' WHERE ref_id = '$id'");
6209
6210 }
6211
6212 function label_clear_cache($link, $id) {
6213
6214 db_query($link, "UPDATE ttrss_user_entries SET
6215 label_cache = '' WHERE ref_id = '$id'");
6216
6217 }
6218
933ba4ee
AD
6219 function label_remove_article($link, $id, $label, $owner_uid) {
6220
6221 $label_id = label_find_id($link, $label, $owner_uid);
6222
6223 if (!$label_id) return;
6224
8d505d78 6225 $result = db_query($link,
933ba4ee 6226 "DELETE FROM ttrss_user_labels2
8d505d78 6227 WHERE
933ba4ee
AD
6228 label_id = '$label_id' AND
6229 article_id = '$id'");
905ff52a
AD
6230
6231 label_clear_cache($link, $id);
933ba4ee
AD
6232 }
6233
ceb30ba4
AD
6234 function label_add_article($link, $id, $label, $owner_uid) {
6235
d721a547
AD
6236 global $memcache;
6237
6238 if ($memcache) {
6239 $obj_id = md5("LABELS:$id:$owner_uid");
6240 $memcache->delete($obj_id);
6241 }
6242
ceb30ba4
AD
6243 $label_id = label_find_id($link, $label, $owner_uid);
6244
6245 if (!$label_id) return;
6246
8d505d78
AD
6247 $result = db_query($link,
6248 "SELECT
ceb30ba4 6249 article_id FROM ttrss_labels2, ttrss_user_labels2
8d505d78
AD
6250 WHERE
6251 label_id = id AND
ceb30ba4
AD
6252 label_id = '$label_id' AND
6253 article_id = '$id' AND owner_uid = '$owner_uid'
6254 LIMIT 1");
6255
6256 if (db_num_rows($result) == 0) {
8d505d78 6257 db_query($link, "INSERT INTO ttrss_user_labels2
ceb30ba4
AD
6258 (label_id, article_id) VALUES ('$label_id', '$id')");
6259 }
905ff52a 6260
8d505d78 6261 label_clear_cache($link, $id);
905ff52a 6262
ceb30ba4 6263 }
1380f8ee
AD
6264
6265 function label_remove($link, $id, $owner_uid) {
d721a547
AD
6266 global $memcache;
6267
905ff52a
AD
6268 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
6269
d721a547
AD
6270 if ($memcache) {
6271 $obj_id = md5("LABELS:$id:$owner_uid");
6272 $memcache->delete($obj_id);
6273 }
1380f8ee
AD
6274
6275 db_query($link, "BEGIN");
6276
6277 $result = db_query($link, "SELECT caption FROM ttrss_labels2
6278 WHERE id = '$id'");
6279
6280 $caption = db_fetch_result($result, 0, "caption");
6281
6282 $result = db_query($link, "DELETE FROM ttrss_labels2 WHERE id = '$id'
905ff52a 6283 AND owner_uid = " . $owner_uid);
1380f8ee
AD
6284
6285 if (db_affected_rows($link, $result) != 0 && $caption) {
6286
8801fb01
AD
6287 /* Remove access key for the label */
6288
6289 $ext_id = -11 - $id;
6290
6291 db_query($link, "DELETE FROM ttrss_access_keys WHERE
6292 feed_id = '$ext_id' AND owner_uid = $owner_uid");
6293
1380f8ee 6294 /* Disable filters that reference label being removed */
8d505d78 6295
1380f8ee
AD
6296 db_query($link, "UPDATE ttrss_filters SET
6297 enabled = false WHERE action_param = '$caption'
6298 AND action_id = 7
905ff52a
AD
6299 AND owner_uid = " . $owner_uid);
6300
6301 /* Remove cached data */
6302
6303 db_query($link, "UPDATE ttrss_user_entries SET label_cache = ''
6304 WHERE label_cache LIKE '%$caption%' AND owner_uid = " . $owner_uid);
6305
6306 }
1380f8ee
AD
6307
6308 db_query($link, "COMMIT");
6309 }
79c88e11 6310
6b2ee18d
AD
6311 function label_create($link, $caption) {
6312
6313 db_query($link, "BEGIN");
6314
6315 $result = false;
6316
6317 $result = db_query($link, "SELECT id FROM ttrss_labels2
6318 WHERE caption = '$caption' AND owner_uid = ". $_SESSION["uid"]);
6319
6320 if (db_num_rows($result) == 0) {
6321 $result = db_query($link,
8d505d78 6322 "INSERT INTO ttrss_labels2 (caption,owner_uid)
6b2ee18d
AD
6323 VALUES ('$caption', '".$_SESSION["uid"]."')");
6324
6325 $result = db_affected_rows($link, $result) != 0;
6326 }
6327
6328 db_query($link, "COMMIT");
6329
6330 return $result;
6331 }
6332
307d187c
AD
6333 function format_tags_string($tags, $id) {
6334
6335 $tags_str = "";
6336 $tags_nolinks_str = "";
6337
6338 $num_tags = 0;
6339
d9084cf2 6340 $tag_limit = 6;
307d187c
AD
6341
6342 $formatted_tags = array();
6343
6344 foreach ($tags as $tag) {
6345 $num_tags++;
6346 $tag_escaped = str_replace("'", "\\'", $tag);
6347
275a0af2
AD
6348 if (mb_strlen($tag) > 30) {
6349 $tag = truncate_string($tag, 30);
6350 }
6351
307d187c
AD
6352 $tag_str = "<a href=\"javascript:viewfeed('$tag_escaped')\">$tag</a>";
6353
6354 array_push($formatted_tags, $tag_str);
275a0af2
AD
6355
6356 $tmp_tags_str = implode(", ", $formatted_tags);
8d505d78 6357
275a0af2 6358 if ($num_tags == $tag_limit || mb_strlen($tmp_tags_str) > 150) {
307d187c
AD
6359 break;
6360 }
6361 }
6362
6363 $tags_str = implode(", ", $formatted_tags);
6364
6365 if ($num_tags < count($tags)) {
6366 $tags_str .= ", &hellip;";
6367 }
6368
6369 if ($num_tags == 0) {
6370 $tags_str = __("no tags");
6371 }
6372
6373 return $tags_str;
6374
6375 }
2eb9c95c
AD
6376
6377 function format_article_labels($labels, $id) {
6378
6379 $labels_str = "";
6380
6381 foreach ($labels as $l) {
8d505d78 6382 $labels_str .= sprintf("<span class='hlLabelRef'
2eb9c95c
AD
6383 style='color : %s; background-color : %s'>%s</span>",
6384 $l[2], $l[3], $l[1]);
6385 }
6386
6387 return $labels_str;
6388
6389 }
c7e51de1
AD
6390
6391 function format_article_note($id, $note) {
6392
fcfa9ef1
AD
6393 $str = "<div class='articleNote' onclick=\"editArticleNote($id)\">
6394 <div class='noteEdit' onclick=\"editArticleNote($id)\">".
6395 __('(edit note)')."</div>$note</div>";
c7e51de1
AD
6396
6397 return $str;
6398 }
7f969260 6399
fcf70c51 6400 function toggle_collapse_cat($link, $cat_id, $mode) {
7f969260 6401 if ($cat_id > 0) {
fcf70c51
AD
6402 $mode = bool_to_sql_bool($mode);
6403
7f969260 6404 db_query($link, "UPDATE ttrss_feed_categories SET
8d505d78 6405 collapsed = $mode WHERE id = '$cat_id' AND owner_uid = " .
7f969260
AD
6406 $_SESSION["uid"]);
6407 } else {
6408 $pref_name = '';
6409
6410 switch ($cat_id) {
6411 case -1:
6412 $pref_name = '_COLLAPSED_SPECIAL';
6413 break;
6414 case -2:
6415 $pref_name = '_COLLAPSED_LABELS';
6416 break;
6417 case 0:
6418 $pref_name = '_COLLAPSED_UNCAT';
6419 break;
6420 }
6421
6422 if ($pref_name) {
fcf70c51 6423 if ($mode) {
7f969260 6424 set_pref($link, $pref_name, 'true');
fcf70c51
AD
6425 } else {
6426 set_pref($link, $pref_name, 'false');
7f969260
AD
6427 }
6428 }
6429 }
6430 }
7e329f13
AD
6431
6432 function remove_feed($link, $id, $owner_uid) {
6433
6434 if ($id > 0) {
e04c18a2
AD
6435
6436 /* save starred articles in Archived feed */
6437
6438 db_query($link, "BEGIN");
6439
8056ec50
AD
6440 /* prepare feed if necessary */
6441
6442 $result = db_query($link, "SELECT id FROM ttrss_archived_feeds
6443 WHERE id = '$id'");
6444
6445 if (db_num_rows($result) == 0) {
8d505d78 6446 db_query($link, "INSERT INTO ttrss_archived_feeds
8056ec50
AD
6447 (id, owner_uid, title, feed_url, site_url)
6448 SELECT id, owner_uid, title, feed_url, site_url from ttrss_feeds
6449 WHERE id = '$id'");
6450 }
6451
74d22f0c 6452 db_query($link, "UPDATE ttrss_user_entries SET feed_id = NULL,
8d505d78 6453 orig_feed_id = '$id' WHERE feed_id = '$id' AND
e04c18a2
AD
6454 marked = true AND owner_uid = $owner_uid");
6455
8801fb01
AD
6456 /* Remove access key for the feed */
6457
6458 db_query($link, "DELETE FROM ttrss_access_keys WHERE
6459 feed_id = '$id' AND owner_uid = $owner_uid");
6460
e04c18a2
AD
6461 /* remove the feed */
6462
8d505d78 6463 db_query($link, "DELETE FROM ttrss_feeds
7e329f13
AD
6464 WHERE id = '$id' AND owner_uid = $owner_uid");
6465
e04c18a2
AD
6466 db_query($link, "COMMIT");
6467
6d634e00 6468 if (file_exists(ICONS_DIR . "/$id.ico")) {
7e329f13 6469 unlink(ICONS_DIR . "/$id.ico");
6d634e00 6470 }
7e329f13
AD
6471
6472 ccache_remove($link, $id, $owner_uid);
6473
6474 } else {
6475 label_remove($link, -11-$id, $owner_uid);
6476 ccache_remove($link, -11-$id, $owner_uid);
6477 }
6478 }
6479
5c7c7da9 6480 function add_feed_category($link, $feed_cat) {
c00907f2
AD
6481
6482 if (!$feed_cat) return false;
6483
5c7c7da9
AD
6484 db_query($link, "BEGIN");
6485
6486 $result = db_query($link,
6487 "SELECT id FROM ttrss_feed_categories
6488 WHERE title = '$feed_cat' AND owner_uid = ".$_SESSION["uid"]);
6489
6490 if (db_num_rows($result) == 0) {
8d505d78 6491
5c7c7da9 6492 $result = db_query($link,
8d505d78 6493 "INSERT INTO ttrss_feed_categories (owner_uid,title)
5c7c7da9
AD
6494 VALUES ('".$_SESSION["uid"]."', '$feed_cat')");
6495
6496 db_query($link, "COMMIT");
6497
6498 return true;
6499 }
6500
6501 return false;
8d505d78 6502 }
5c7c7da9 6503
7e329f13
AD
6504 function remove_feed_category($link, $id, $owner_uid) {
6505
6506 db_query($link, "DELETE FROM ttrss_feed_categories
6507 WHERE id = '$id' AND owner_uid = $owner_uid");
6508
6509 ccache_remove($link, $id, $owner_uid, true);
6510 }
6511
16fdac16
AD
6512 function archive_article($link, $id, $owner_uid) {
6513 db_query($link, "BEGIN");
6514
6515 $result = db_query($link, "SELECT feed_id FROM ttrss_user_entries
6516 WHERE ref_id = '$id' AND owner_uid = $owner_uid");
6517
6518 if (db_num_rows($result) != 0) {
6519
6520 /* prepare the archived table */
6521
6522 $feed_id = (int) db_fetch_result($result, 0, "feed_id");
6523
6524 if ($feed_id) {
6525 $result = db_query($link, "SELECT id FROM ttrss_archived_feeds
6526 WHERE id = '$feed_id'");
6527
6528 if (db_num_rows($result) == 0) {
8d505d78 6529 db_query($link, "INSERT INTO ttrss_archived_feeds
16fdac16
AD
6530 (id, owner_uid, title, feed_url, site_url)
6531 SELECT id, owner_uid, title, feed_url, site_url from ttrss_feeds
6532 WHERE id = '$feed_id'");
6533 }
6534
8d505d78 6535 db_query($link, "UPDATE ttrss_user_entries
16fdac16
AD
6536 SET orig_feed_id = feed_id, feed_id = NULL
6537 WHERE ref_id = '$id' AND owner_uid = " . $_SESSION["uid"]);
6538 }
6539 }
6540
6541 db_query($link, "COMMIT");
6542 }
ab197ae1
AD
6543
6544 function getArticleFeed($link, $id) {
8d505d78 6545 $result = db_query($link, "SELECT feed_id FROM ttrss_user_entries
a545dc31 6546 WHERE ref_id = '$id' AND owner_uid = " . $_SESSION["uid"]);
ab197ae1
AD
6547
6548 if (db_num_rows($result) != 0) {
6549 return db_fetch_result($result, 0, "feed_id");
6550 } else {
6551 return 0;
6552 }
6553 }
a5819bb3 6554
f2c6c008
CW
6555 /**
6556 * Fixes incomplete URLs by prepending "http://".
f0266f51
CW
6557 * Also replaces feed:// with http://, and
6558 * prepends a trailing slash if the url is a domain name only.
f2c6c008
CW
6559 *
6560 * @param string $url Possibly incomplete URL
6561 *
6562 * @return string Fixed URL.
6563 */
6564 function fix_url($url) {
6565 if (strpos($url, '://') === false) {
6566 $url = 'http://' . $url;
f0266f51
CW
6567 } else if (substr($url, 0, 5) == 'feed:') {
6568 $url = 'http:' . substr($url, 5);
6569 }
6570
6571 //prepend slash if the URL has no slash in it
6572 // "http://www.example" -> "http://www.example/"
44453773 6573 if (strpos($url, '/', strpos($url, ':') + 3) === false) {
f0266f51 6574 $url .= '/';
f2c6c008 6575 }
ec39a02c
AD
6576
6577 if ($url != "http:///")
6578 return $url;
6579 else
6580 return '';
f2c6c008
CW
6581 }
6582
a5819bb3
AD
6583 function validate_feed_url($url) {
6584 $parts = parse_url($url);
6585
6586 return ($parts['scheme'] == 'http' || $parts['scheme'] == 'feed' || $parts['scheme'] == 'https');
6587
6588 }
d9084cf2 6589
be35798b
AD
6590 function get_article_enclosures($link, $id) {
6591
6592 global $memcache;
6593
8d505d78 6594 $query = "SELECT * FROM ttrss_enclosures
be35798b
AD
6595 WHERE post_id = '$id' AND content_url != ''";
6596
bd3f2ade 6597 $obj_id = md5("ENCLOSURES:$id");
be35798b
AD
6598
6599 $rv = array();
6600
bd3f2ade 6601 if ($memcache && $obj = $memcache->get($obj_id)) {
be35798b
AD
6602 $rv = $obj;
6603 } else {
6604 $result = db_query($link, $query);
6605
6606 if (db_num_rows($result) > 0) {
6607 while ($line = db_fetch_assoc($result)) {
6608 array_push($rv, $line);
6609 }
bd3f2ade 6610 if ($memcache) $memcache->add($obj_id, $rv, 0, 3600);
be35798b
AD
6611 }
6612 }
6613
6614 return $rv;
6615 }
6616
911d4c08 6617 function api_get_feeds($link, $cat_id, $unread_only, $limit, $offset) {
911d4c08
AD
6618
6619 $feeds = array();
6620
911d4c08
AD
6621 /* Labels */
6622
fb8d17f3 6623 if ($cat_id == -4 || $cat_id == -2) {
911d4c08
AD
6624 $counters = getLabelCounters($link, true);
6625
11232703 6626 foreach (array_values($counters) as $cv) {
911d4c08 6627
11232703 6628 $unread = $cv["counter"];
8d505d78 6629
911d4c08 6630 if ($unread || !$unread_only) {
8d505d78 6631
911d4c08 6632 $row = array(
11232703
AD
6633 "id" => $cv["id"],
6634 "title" => $cv["description"],
6635 "unread" => $cv["counter"],
911d4c08
AD
6636 "cat_id" => -2,
6637 );
8d505d78 6638
911d4c08
AD
6639 array_push($feeds, $row);
6640 }
6641 }
6642 }
6643
6644 /* Virtual feeds */
6645
fb8d17f3 6646 if ($cat_id == -4 || $cat_id == -1) {
911d4c08
AD
6647 foreach (array(-1, -2, -3, -4, 0) as $i) {
6648 $unread = getFeedUnread($link, $i);
6649
6650 if ($unread || !$unread_only) {
6651 $title = getFeedTitle($link, $i);
6652
6653 $row = array(
6654 "id" => $i,
6655 "title" => $title,
6656 "unread" => $unread,
6657 "cat_id" => -1,
6658 );
6659 array_push($feeds, $row);
6660 }
6661
8d505d78 6662 }
911d4c08 6663 }
b41c2549
AD
6664
6665 /* Real feeds */
6666
6667 if ($limit) {
6668 $limit_qpart = "LIMIT $limit OFFSET $offset";
6669 } else {
6670 $limit_qpart = "";
6671 }
6672
fb8d17f3 6673 if ($cat_id == -4 || $cat_id == -3) {
8d505d78 6674 $result = db_query($link, "SELECT
b41c2549
AD
6675 id, feed_url, cat_id, title, ".
6676 SUBSTRING_FOR_DATE."(last_updated,1,19) AS last_updated
8d505d78 6677 FROM ttrss_feeds WHERE owner_uid = " . $_SESSION["uid"] .
b41c2549
AD
6678 " ORDER BY cat_id, title " . $limit_qpart);
6679 } else {
fb8d17f3
AD
6680
6681 if ($cat_id)
6682 $cat_qpart = "cat_id = '$cat_id'";
6683 else
6684 $cat_qpart = "cat_id IS NULL";
6685
8d505d78 6686 $result = db_query($link, "SELECT
b41c2549
AD
6687 id, feed_url, cat_id, title, ".
6688 SUBSTRING_FOR_DATE."(last_updated,1,19) AS last_updated
8d505d78
AD
6689 FROM ttrss_feeds WHERE
6690 $cat_qpart AND owner_uid = " . $_SESSION["uid"] .
b41c2549
AD
6691 " ORDER BY cat_id, title " . $limit_qpart);
6692 }
6693
6694 while ($line = db_fetch_assoc($result)) {
6695
6696 $unread = getFeedUnread($link, $line["id"]);
6697
6698 $has_icon = feed_has_icon($line['id']);
6699
6700 if ($unread || !$unread_only) {
6701
6702 $row = array(
6703 "feed_url" => $line["feed_url"],
6704 "title" => $line["title"],
6705 "id" => (int)$line["id"],
6706 "unread" => (int)$unread,
6707 "has_icon" => $has_icon,
6708 "cat_id" => (int)$line["cat_id"],
6709 "last_updated" => strtotime($line["last_updated"])
6710 );
8d505d78 6711
b41c2549
AD
6712 array_push($feeds, $row);
6713 }
6714 }
6715
911d4c08
AD
6716 return $feeds;
6717 }
6718
6719 function api_get_headlines($link, $feed_id, $limit, $offset,
a0e580b0 6720 $filter, $is_cat, $show_excerpt, $show_content, $view_mode, $order,
97e5dbb2 6721 $include_attachments, $since_id) {
911d4c08
AD
6722
6723 /* do not rely on params below */
6724
6725 $search = db_escape_string($_REQUEST["search"]);
6726 $search_mode = db_escape_string($_REQUEST["search_mode"]);
6727 $match_on = db_escape_string($_REQUEST["match_on"]);
8d505d78
AD
6728
6729 $qfh_ret = queryFeedHeadlines($link, $feed_id, $limit,
911d4c08 6730 $view_mode, $is_cat, $search, $search_mode, $match_on,
97e5dbb2 6731 $order, $offset, 0, false, $since_id);
911d4c08
AD
6732
6733 $result = $qfh_ret[0];
6734 $feed_title = $qfh_ret[1];
6735
6736 $headlines = array();
6737
6738 while ($line = db_fetch_assoc($result)) {
8d505d78 6739 $is_updated = ($line["last_read"] == "" &&
911d4c08
AD
6740 ($line["unread"] != "t" && $line["unread"] != "1"));
6741
97a3b9f0
AD
6742 $tags = explode(",", $line["tag_cache"]);
6743 $labels = json_decode($line["label_cache"], true);
6744
6745 //if (!$tags) $tags = get_article_tags($link, $line["id"]);
6746 //if (!$labels) $labels = get_article_labels($link, $line["id"]);
6747
911d4c08
AD
6748 $headline_row = array(
6749 "id" => (int)$line["id"],
6750 "unread" => sql_bool_to_bool($line["unread"]),
6751 "marked" => sql_bool_to_bool($line["marked"]),
9ed133e7 6752 "published" => sql_bool_to_bool($line["published"]),
911d4c08
AD
6753 "updated" => strtotime($line["updated"]),
6754 "is_updated" => $is_updated,
6755 "title" => $line["title"],
6756 "link" => $line["link"],
6757 "feed_id" => $line["feed_id"],
97a3b9f0 6758 "tags" => $tags,
911d4c08
AD
6759 );
6760
a0e580b0
AD
6761 if ($include_attachments)
6762 $headline_row['attachments'] = get_article_enclosures($link,
6763 $line['id']);
6764
911d4c08
AD
6765 if ($show_excerpt) {
6766 $excerpt = truncate_string(strip_tags($line["content_preview"]), 100);
6767 $headline_row["excerpt"] = $excerpt;
6768 }
6769
6770 if ($show_content) {
6771 $headline_row["content"] = $line["content_preview"];
6772 }
6773
97a3b9f0
AD
6774 // unify label output to ease parsing
6775 if ($labels["no-labels"] == 1) $labels = array();
6776
6777 $headline_row["labels"] = $labels;
6778
911d4c08
AD
6779 array_push($headlines, $headline_row);
6780 }
6781
6782 return $headlines;
6783 }
6784
bd202c3f
AD
6785 function generate_error_feed($link, $error) {
6786 $reply = array();
6787
6788 $reply['headlines']['id'] = -6;
6789 $reply['headlines']['is_cat'] = false;
6790
6791 $reply['headlines']['toolbar'] = '';
6792 $reply['headlines']['content'] = "<div class='whiteBox'>". $error . "</div>";
6793
6794 $reply['headlines-info'] = array("count" => 0,
6795 "vgroup_last_feed" => '',
6796 "unread" => 0,
6797 "disable_cache" => true);
6798
6799 return $reply;
6800 }
fe1087fb 6801
13e785e0 6802
bd202c3f
AD
6803 function generate_dashboard_feed($link) {
6804 $reply = array();
6805
6806 $reply['headlines']['id'] = -5;
6807 $reply['headlines']['is_cat'] = false;
fe1087fb 6808
bd202c3f
AD
6809 $reply['headlines']['toolbar'] = '';
6810 $reply['headlines']['content'] = "<div class='whiteBox'>".__('No feed selected.');
fe1087fb 6811
bd202c3f 6812 $reply['headlines']['content'] .= "<p class=\"small\"><span class=\"insensitive\">";
5d128c95
AD
6813
6814 $result = db_query($link, "SELECT ".SUBSTRING_FOR_DATE."(MAX(last_updated), 1, 19) AS last_updated FROM ttrss_feeds
6815 WHERE owner_uid = " . $_SESSION['uid']);
6816
6817 $last_updated = db_fetch_result($result, 0, "last_updated");
324944f3 6818 $last_updated = make_local_datetime($link, $last_updated, false);
5d128c95 6819
bd202c3f 6820 $reply['headlines']['content'] .= sprintf(__("Feeds last updated at %s"), $last_updated);
5d128c95 6821
fe1087fb
AD
6822 $result = db_query($link, "SELECT COUNT(id) AS num_errors
6823 FROM ttrss_feeds WHERE last_error != '' AND owner_uid = ".$_SESSION["uid"]);
6824
6825 $num_errors = db_fetch_result($result, 0, "num_errors");
6826
6827 if ($num_errors > 0) {
bd202c3f
AD
6828 $reply['headlines']['content'] .= "<br/>";
6829 $reply['headlines']['content'] .= "<a class=\"insensitive\" href=\"#\" onclick=\"showFeedsWithErrors()\">".
fe1087fb
AD
6830 __('Some feeds have update errors (click for details)')."</a>";
6831 }
bd202c3f 6832 $reply['headlines']['content'] .= "</span></p>";
fe1087fb 6833
bd202c3f 6834 $reply['headlines-info'] = array("count" => 0,
ffbe082d
AD
6835 "vgroup_last_feed" => '',
6836 "unread" => 0,
6837 "disable_cache" => true);
6838
bd202c3f 6839 return $reply;
fe1087fb 6840 }
31a53903
AD
6841
6842 function save_email_address($link, $email) {
6843 // FIXME: implement persistent storage of emails
6844
8d505d78 6845 if (!$_SESSION['stored_emails'])
31a53903
AD
6846 $_SESSION['stored_emails'] = array();
6847
6848 if (!in_array($email, $_SESSION['stored_emails']))
6849 array_push($_SESSION['stored_emails'], $email);
6850 }
8801fb01
AD
6851
6852 function update_feed_access_key($link, $feed_id, $is_cat, $owner_uid = false) {
6853 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
6854
6855 $sql_is_cat = bool_to_sql_bool($is_cat);
6856
8d505d78
AD
6857 $result = db_query($link, "SELECT access_key FROM ttrss_access_keys
6858 WHERE feed_id = '$feed_id' AND is_cat = $sql_is_cat
8801fb01
AD
6859 AND owner_uid = " . $owner_uid);
6860
6861 if (db_num_rows($result) == 1) {
6862 $key = db_escape_string(sha1(uniqid(rand(), true)));
6863
6864 db_query($link, "UPDATE ttrss_access_keys SET access_key = '$key'
8d505d78 6865 WHERE feed_id = '$feed_id' AND is_cat = $sql_is_cat
8801fb01
AD
6866 AND owner_uid = " . $owner_uid);
6867
6868 return $key;
6869
6870 } else {
6871 return get_feed_access_key($link, $feed_id, $is_cat, $owner_uid);
6872 }
6873 }
6874
6875 function get_feed_access_key($link, $feed_id, $is_cat, $owner_uid = false) {
6876
6877 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
6878
6879 $sql_is_cat = bool_to_sql_bool($is_cat);
6880
8d505d78
AD
6881 $result = db_query($link, "SELECT access_key FROM ttrss_access_keys
6882 WHERE feed_id = '$feed_id' AND is_cat = $sql_is_cat
8801fb01
AD
6883 AND owner_uid = " . $owner_uid);
6884
6885 if (db_num_rows($result) == 1) {
6886 return db_fetch_result($result, 0, "access_key");
6887 } else {
6888 $key = db_escape_string(sha1(uniqid(rand(), true)));
6889
8d505d78 6890 $result = db_query($link, "INSERT INTO ttrss_access_keys
8801fb01
AD
6891 (access_key, feed_id, is_cat, owner_uid)
6892 VALUES ('$key', '$feed_id', $sql_is_cat, '$owner_uid')");
6893
6894 return $key;
6895 }
6896 return false;
6897 }
f0266f51
CW
6898
6899 /**
6900 * Extracts RSS/Atom feed URLs from the given HTML URL.
6901 *
6902 * @param string $url HTML page URL
6903 *
6904 * @return array Array of feeds. Key is the full URL, value the title
6905 */
8d505d78 6906 function get_feeds_from_html($url, $login = false, $pass = false)
f0266f51
CW
6907 {
6908 $url = fix_url($url);
6909 $baseUrl = substr($url, 0, strrpos($url, '/') + 1);
6910
fb074239
AD
6911 libxml_use_internal_errors(true);
6912
8d505d78
AD
6913 $content = @fetch_file_contents($url, false, $login, $pass);
6914
f0266f51 6915 $doc = new DOMDocument();
8d505d78 6916 $doc->loadHTML($content);
f0266f51
CW
6917 $xpath = new DOMXPath($doc);
6918 $entries = $xpath->query('/html/head/link[@rel="alternate"]');
6919 $feedUrls = array();
6920 foreach ($entries as $entry) {
6921 if ($entry->hasAttribute('href')) {
6922 $title = $entry->getAttribute('title');
6923 if ($title == '') {
6924 $title = $entry->getAttribute('type');
6925 }
923818fc
CW
6926 $feedUrl = rewrite_relative_url(
6927 $baseUrl, $entry->getAttribute('href')
6928 );
f0266f51
CW
6929 $feedUrls[$feedUrl] = $title;
6930 }
6931 }
6932 return $feedUrls;
6933 }
6934
f33479da
CW
6935 /**
6936 * Checks if the content behind the given URL is a HTML file
6937 *
6938 * @param string $url URL to check
6939 *
6940 * @return boolean True if the URL contains HTML content
6941 */
8d505d78
AD
6942 function url_is_html($url, $login = false, $pass = false) {
6943 $content = substr(fetch_file_contents($url, false, $login, $pass), 0, 1000);
6944
24eb4c78
CW
6945 if (stripos($content, '<html>') === false
6946 && stripos($content, '<html ') === false
f33479da
CW
6947 ) {
6948 return false;
6949 }
6950
6951 return true;
6952 }
24e2bb3a 6953
d90868d7 6954 function print_label_select($link, $name, $value, $attributes = "") {
24e2bb3a
AD
6955
6956 $result = db_query($link, "SELECT caption FROM ttrss_labels2
6957 WHERE owner_uid = '".$_SESSION["uid"]."' ORDER BY caption");
6958
8d505d78 6959 print "<select default=\"$value\" name=\"" . htmlspecialchars($name) .
d90868d7 6960 "\" $attributes onchange=\"labelSelectOnChange(this)\" >";
24e2bb3a
AD
6961
6962 while ($line = db_fetch_assoc($result)) {
6963
6964 $issel = ($line["caption"] == $value) ? "selected=\"1\"" : "";
6965
d90868d7
AD
6966 print "<option value=\"".htmlspecialchars($line["caption"])."\"
6967 $issel>" . htmlspecialchars($line["caption"]) . "</option>";
24e2bb3a
AD
6968
6969 }
6970
d90868d7 6971# print "<option value=\"ADD_LABEL\">" .__("Add label...") . "</option>";
24e2bb3a
AD
6972
6973 print "</select>";
6974
6975
6976 }
6977
009646d2 6978 function format_article_enclosures($link, $id, $always_display_enclosures,
dad14b51
AD
6979 $article_content) {
6980
6981 $result = get_article_enclosures($link, $id);
009646d2 6982 $rv = '';
8d505d78 6983
dad14b51 6984 if (count($result) > 0) {
8d505d78 6985
dad14b51
AD
6986 $entries_html = array();
6987 $entries = array();
8d505d78 6988
dad14b51 6989 foreach ($result as $line) {
8d505d78 6990
dad14b51
AD
6991 $url = $line["content_url"];
6992 $ctype = $line["content_type"];
8d505d78 6993
dad14b51 6994 if (!$ctype) $ctype = __("unknown type");
8d505d78 6995
c3edc667 6996# $filename = substr($url, strrpos($url, "/")+1);
8d505d78 6997
dad14b51 6998 $entry = format_inline_player($link, $url, $ctype);
8d505d78 6999
c3edc667
AD
7000# $entry .= " <a target=\"_blank\" href=\"" . htmlspecialchars($url) . "\">" .
7001# $filename . " (" . $ctype . ")" . "</a>";
8d505d78 7002
dad14b51 7003 array_push($entries_html, $entry);
8d505d78 7004
dad14b51 7005 $entry = array();
8d505d78 7006
dad14b51
AD
7007 $entry["type"] = $ctype;
7008 $entry["filename"] = $filename;
7009 $entry["url"] = $url;
8d505d78 7010
dad14b51
AD
7011 array_push($entries, $entry);
7012 }
8d505d78 7013
009646d2 7014 $rv .= "<div class=\"postEnclosures\">";
8d505d78 7015
dad14b51
AD
7016 if (!get_pref($link, "STRIP_IMAGES")) {
7017 if ($always_display_enclosures ||
7018 !preg_match("/<img/i", $article_content)) {
8d505d78 7019
dad14b51 7020 foreach ($entries as $entry) {
8d505d78 7021
dad14b51
AD
7022 if (preg_match("/image/", $entry["type"]) ||
7023 preg_match("/\.(jpg|png|gif|bmp)/i", $entry["filename"])) {
8d505d78 7024
009646d2 7025 $rv .= "<p><img
dad14b51
AD
7026 alt=\"".htmlspecialchars($entry["filename"])."\"
7027 src=\"" .htmlspecialchars($entry["url"]) . "\"/></p>";
7028 }
7029 }
7030 }
7031 }
8d505d78 7032
905ff52a 7033 if (count($entries) == 1) {
009646d2 7034 $rv .= __("Attachment:") . " ";
dad14b51 7035 } else {
009646d2 7036 $rv .= __("Attachments:") . " ";
dad14b51 7037 }
8d505d78 7038
009646d2 7039 $rv .= join(", ", $entries_html);
8d505d78 7040
009646d2 7041 $rv .= "</div>";
dad14b51 7042 }
009646d2
AD
7043
7044 return $rv;
dad14b51
AD
7045 }
7046
f8fb4498
AD
7047 function getLastArticleId($link) {
7048 $result = db_query($link, "SELECT MAX(ref_id) AS id FROM ttrss_user_entries
7049 WHERE owner_uid = " . $_SESSION["uid"]);
7050
7051 if (db_num_rows($result) == 1) {
7052 return db_fetch_result($result, 0, "id");
7053 } else {
7054 return -1;
7055 }
7056 }
8cc3c778
AD
7057
7058 function build_url($parts) {
7059 return $parts['scheme'] . "://" . $parts['host'] . $parts['path'];
7060 }
7061
f679105c
CW
7062 /**
7063 * Converts a (possibly) relative URL to a absolute one.
7064 *
7065 * @param string $url Base URL (i.e. from where the document is)
7066 * @param string $rel_url Possibly relative URL in the document
7067 *
7068 * @return string Absolute URL
7069 */
8cc3c778
AD
7070 function rewrite_relative_url($url, $rel_url) {
7071 if (strpos($rel_url, "://") !== false) {
7072 return $rel_url;
8d505d78 7073 } else if (strpos($rel_url, "/") === 0)
8cc3c778
AD
7074 {
7075 $parts = parse_url($url);
7076 $parts['path'] = $rel_url;
7077
7078 return build_url($parts);
7079
7080 } else {
7081 $parts = parse_url($url);
f679105c
CW
7082 if (!isset($parts['path'])) {
7083 $parts['path'] = '/';
7084 }
7085 $dir = $parts['path'];
7086 if (substr($dir, -1) !== '/') {
7087 $dir = dirname($parts['path']);
7088 $dir !== '/' && $dir .= '/';
7089 }
7090 $parts['path'] = $dir . $rel_url;
8cc3c778
AD
7091
7092 return build_url($parts);
7093 }
7094 }
7095
e4f7f8df 7096 function sphinx_search($query, $offset = 0, $limit = 30) {
31303c6b
AD
7097 require_once 'lib/sphinxapi.php';
7098
e4f7f8df
AD
7099 $sphinxClient = new SphinxClient();
7100
7101 $sphinxClient->SetServer('localhost', 9312);
7102 $sphinxClient->SetConnectTimeout(1);
7103
8d505d78 7104 $sphinxClient->SetFieldWeights(array('title' => 70, 'content' => 30,
e4f7f8df
AD
7105 'feed_title' => 20));
7106
7107 $sphinxClient->SetMatchMode(SPH_MATCH_EXTENDED2);
7108 $sphinxClient->SetRankingMode(SPH_RANK_PROXIMITY_BM25);
7109 $sphinxClient->SetLimits($offset, $limit, 1000);
7110 $sphinxClient->SetArrayResult(false);
7111 $sphinxClient->SetFilter('owner_uid', array($_SESSION['uid']));
8d505d78 7112
e4f7f8df
AD
7113 $result = $sphinxClient->Query($query, SPHINX_INDEX);
7114
7115 $ids = array();
7116
7117 if (is_array($result['matches'])) {
7118 foreach (array_keys($result['matches']) as $int_id) {
7119 $ref_id = $result['matches'][$int_id]['attrs']['ref_id'];
7120 array_push($ids, $ref_id);
7121 }
7122 }
7123
7124 return $ids;
7125 }
7126
868650e4
AD
7127 function cleanup_tags($link, $days = 14, $limit = 1000) {
7128
7129 if (DB_TYPE == "pgsql") {
7130 $interval_query = "date_updated < NOW() - INTERVAL '$days days'";
7131 } else if (DB_TYPE == "mysql") {
7132 $interval_query = "date_updated < DATE_SUB(NOW(), INTERVAL $days DAY)";
7133 }
7134
b5ec13fa 7135 $tags_deleted = 0;
868650e4 7136
b5ec13fa
AD
7137 while ($limit > 0) {
7138 $limit_part = 500;
7139
8d505d78
AD
7140 $query = "SELECT ttrss_tags.id AS id
7141 FROM ttrss_tags, ttrss_user_entries, ttrss_entries
b5ec13fa
AD
7142 WHERE post_int_id = int_id AND $interval_query AND
7143 ref_id = ttrss_entries.id AND tag_cache != '' LIMIT $limit_part";
8d505d78 7144
b5ec13fa
AD
7145 $result = db_query($link, $query);
7146
7147 $ids = array();
7148
7149 while ($line = db_fetch_assoc($result)) {
7150 array_push($ids, $line['id']);
7151 }
7152
7153 if (count($ids) > 0) {
7154 $ids = join(",", $ids);
7155 print ".";
7156
7157 $tmp_result = db_query($link, "DELETE FROM ttrss_tags WHERE id IN ($ids)");
7158 $tags_deleted += db_affected_rows($link, $tmp_result);
7159 } else {
7160 break;
7161 }
7162
7163 $limit -= $limit_part;
7164 }
7165
7166 print "\n";
868650e4 7167
b5ec13fa 7168 return $tags_deleted;
868650e4
AD
7169 }
7170
13e785e0
AD
7171 function feedlist_init_cat($link, $cat_id, $hidden = false) {
7172 $obj = array();
db34e084 7173 $cat_id = (int) $cat_id;
13e785e0
AD
7174
7175 if ($cat_id > 0) {
7176 $cat_unread = ccache_find($link, $cat_id, $_SESSION["uid"], true);
7177 } else if ($cat_id == 0 || $cat_id == -2) {
7178 $cat_unread = getCategoryUnread($link, $cat_id);
7179 }
7180
1985a5e0 7181 $obj['id'] = 'CAT:' . $cat_id;
13e785e0
AD
7182 $obj['items'] = array();
7183 $obj['name'] = getCategoryTitle($link, $cat_id);
7184 $obj['type'] = 'feed';
7185 $obj['unread'] = (int) $cat_unread;
7186 $obj['hidden'] = $hidden;
1985a5e0 7187 $obj['bare_id'] = $cat_id;
13e785e0
AD
7188
7189 return $obj;
7190 }
7191
fcf70c51 7192 function feedlist_init_feed($link, $feed_id, $title = false, $unread = false, $error = '', $updated = '') {
13e785e0 7193 $obj = array();
1985a5e0 7194 $feed_id = (int) $feed_id;
13e785e0 7195
8d505d78 7196 if (!$title)
13e785e0
AD
7197 $title = getFeedTitle($link, $feed_id, false);
7198
cd1bb36d 7199 if ($unread === false)
13e785e0
AD
7200 $unread = getFeedUnread($link, $feed_id, false);
7201
7202 $obj['id'] = 'FEED:' . $feed_id;
7203 $obj['name'] = $title;
7204 $obj['unread'] = (int) $unread;
7205 $obj['type'] = 'feed';
fcf70c51
AD
7206 $obj['error'] = $error;
7207 $obj['updated'] = $updated;
2ef5c21f 7208 $obj['icon'] = getFeedIcon($feed_id);
1985a5e0 7209 $obj['bare_id'] = $feed_id;
13e785e0
AD
7210
7211 return $obj;
7212 }
7213
54a3dd8d 7214
57e24c82 7215 function fetch_twitter_rss($link, $url, $owner_uid) {
31303c6b
AD
7216
7217 require_once 'lib/tmhoauth/tmhOAuth.php';
7218
8d505d78 7219 $result = db_query($link, "SELECT twitter_oauth FROM ttrss_users
57e24c82
AD
7220 WHERE id = $owner_uid");
7221
7222 $access_token = json_decode(db_fetch_result($result, 0, 'twitter_oauth'), true);
54a3dd8d 7223 $url_escaped = db_escape_string($url);
57e24c82
AD
7224
7225 if ($access_token) {
57e24c82 7226
54a3dd8d
AD
7227 $tmhOAuth = new tmhOAuth(array(
7228 'consumer_key' => CONSUMER_KEY,
7229 'consumer_secret' => CONSUMER_SECRET,
7230 'user_token' => $access_token['oauth_token'],
7231 'user_secret' => $access_token['oauth_token_secret'],
7232 ));
7233
7234 $code = $tmhOAuth->request('GET', $url);
7235
7236 if ($code == 200) {
7237
7238 $content = $tmhOAuth->response['response'];
7239
5ab9791f
AD
7240 define('MAGPIE_CACHE_ON', false);
7241
8d505d78 7242 $rss = new MagpieRSS($content, MAGPIE_OUTPUT_ENCODING,
54a3dd8d
AD
7243 MAGPIE_INPUT_ENCODING, MAGPIE_DETECT_ENCODING );
7244
7245 return $rss;
7246
7247 } else {
7248
8d505d78 7249 db_query($link, "UPDATE ttrss_feeds
54a3dd8d
AD
7250 SET last_error = 'OAuth authorization failed ($code).'
7251 WHERE feed_url = '$url_escaped' AND owner_uid = $owner_uid");
7252 }
57e24c82 7253
57e24c82 7254 } else {
54a3dd8d 7255
8d505d78 7256 db_query($link, "UPDATE ttrss_feeds
54a3dd8d 7257 SET last_error = 'OAuth information not found.'
dc891b12 7258 WHERE feed_url = '$url_escaped' AND owner_uid = $owner_uid");
54a3dd8d 7259
57e24c82
AD
7260 return false;
7261 }
7262 }
7263
88e4e597
AD
7264 function print_user_stylesheet($link) {
7265 $value = get_pref($link, 'USER_STYLESHEET');
7266
7267 if ($value) {
7268 print "<style type=\"text/css\">";
5823f9fb 7269 print str_replace("<br/>", "\n", $value);
88e4e597
AD
7270 print "</style>";
7271 }
7272
7273 }
7274
533c0ea6
AD
7275 function rewrite_urls($line) {
7276 global $url_regex;
7277
7278 $urls = null;
7279
8d505d78 7280 $result = preg_replace("/((?<!=.)((http|https|ftp)+):\/\/[^ ,!]+)/i",
533c0ea6
AD
7281 "<a target=\"_blank\" href=\"\\1\">\\1</a>", $line);
7282
7283 return $result;
7284 }
7285
36184020
AD
7286 function filter_to_sql($filter) {
7287 $query = "";
7288
7289 if (DB_TYPE == "pgsql")
7290 $reg_qpart = "~";
7291 else
7292 $reg_qpart = "REGEXP";
7293
7294 switch ($filter["type"]) {
7295 case "title":
7296 $query = "LOWER(ttrss_entries.title) $reg_qpart LOWER('".
7297 $filter['reg_exp'] . "')";
7298 break;
7299 case "content":
7300 $query = "LOWER(ttrss_entries.content) $reg_qpart LOWER('".
7301 $filter['reg_exp'] . "')";
7302 break;
7303 case "both":
7304 $query = "LOWER(ttrss_entries.title) $reg_qpart LOWER('".
7305 $filter['reg_exp'] . "') OR LOWER(" .
7306 "ttrss_entries.content) $reg_qpart LOWER('" . $filter['reg_exp'] . "')";
7307 break;
7308 case "tag":
7309 $query = "LOWER(ttrss_user_entries.tag_cache) $reg_qpart LOWER('".
7310 $filter['reg_exp'] . "')";
7311 break;
7312 case "link":
7313 $query = "LOWER(ttrss_entries.link) $reg_qpart LOWER('".
7314 $filter['reg_exp'] . "')";
7315 break;
7316 case "date":
7317
7318 if ($filter["filter_param"] == "before")
7319 $cmp_qpart = "<";
7320 else
7321 $cmp_qpart = ">=";
7322
7323 $timestamp = date("Y-m-d H:N:s", strtotime($filter["reg_exp"]));
7324 $query = "ttrss_entries.date_entered $cmp_qpart '$timestamp'";
7325 break;
7326 case "author":
7327 $query = "LOWER(ttrss_entries.author) $reg_qpart LOWER('".
7328 $filter['reg_exp'] . "')";
7329 break;
7330 }
7331
7332 if ($filter["inverse"])
7333 $query = "NOT ($query)";
7334
6338b16f
AD
7335 if ($query) {
7336 if (DB_TYPE == "pgsql") {
6b8b3af8 7337 $query = " ($query) AND ttrss_entries.date_entered > NOW() - INTERVAL '14 days'";
6338b16f 7338 } else {
decf742e 7339 $query = " ($query) AND ttrss_entries.date_entered > DATE_SUB(NOW(), INTERVAL 14 DAY)";
6338b16f 7340 }
36184020 7341 $query .= " AND ";
6338b16f 7342 }
36184020 7343
6b8b3af8 7344
36184020
AD
7345 return $query;
7346 }
ae5f7bb1
AD
7347
7348 // Status codes:
7349 // -1 - never connected
7350 // 0 - no data received
7351 // 1 - data received successfully
7352 // 2 - did not receive valid data
7353 // >10 - server error, code + 10 (e.g. 16 means server error 6)
7354
7355 function get_linked_feeds($link, $instance_id = false) {
7356 if ($instance_id)
7357 $instance_qpart = "id = '$instance_id' AND ";
7358 else
7359 $instance_qpart = "";
7360
7361 if (DB_TYPE == "pgsql") {
414d0d1f 7362 $date_qpart = "last_connected < NOW() - INTERVAL '6 hours'";
ae5f7bb1 7363 } else {
81731791 7364 $date_qpart = "last_connected < DATE_SUB(NOW(), INTERVAL 6 HOUR)";
ae5f7bb1
AD
7365 }
7366
7367 $result = db_query($link, "SELECT id, access_key, access_url FROM ttrss_linked_instances
7368 WHERE $instance_qpart $date_qpart ORDER BY last_connected");
7369
7370 while ($line = db_fetch_assoc($result)) {
7371 $id = $line['id'];
7372
7373 _debug("Updating: " . $line['access_url'] . " ($id)");
7374
e0d91d84 7375 $fetch_url = $line['access_url'] . '/public.php?op=fbexport';
ae5f7bb1
AD
7376 $post_query = 'key=' . $line['access_key'];
7377
7378 $feeds = fetch_file_contents($fetch_url, false, false, false, $post_query);
7379
e0d91d84
AD
7380 // try doing it the old way
7381 if (!$feeds) {
7382 $fetch_url = $line['access_url'] . '/backend.php?op=fbexport';
7383 $feeds = fetch_file_contents($fetch_url, false, false, false, $post_query);
7384 }
7385
ae5f7bb1
AD
7386 if ($feeds) {
7387 $feeds = json_decode($feeds, true);
7388
7389 if ($feeds) {
7390 if ($feeds['error']) {
7391 $status = $feeds['error']['code'] + 10;
7392 } else {
7393 $status = 1;
7394
7395 if (count($feeds['feeds']) > 0) {
7396
7397 db_query($link, "DELETE FROM ttrss_linked_feeds
7398 WHERE instance_id = '$id'");
7399
7400 foreach ($feeds['feeds'] as $feed) {
7401 $feed_url = db_escape_string($feed['feed_url']);
7402 $title = db_escape_string($feed['title']);
7403 $subscribers = db_escape_string($feed['subscribers']);
2b9c4bae 7404 $site_url = db_escape_string($feed['site_url']);
ae5f7bb1
AD
7405
7406 db_query($link, "INSERT INTO ttrss_linked_feeds
d61063c7 7407 (feed_url, site_url, title, subscribers, instance_id, created, updated)
ae5f7bb1 7408 VALUES
d61063c7 7409 ('$feed_url', '$site_url', '$title', '$subscribers', '$id', NOW(), NOW())");
ae5f7bb1
AD
7410 }
7411 } else {
7412 // received 0 feeds, this might indicate that
7413 // the instance on the other hand is rebuilding feedbrowser cache
7414 // we will try again later
7415
7416 // TODO: maybe perform expiration based on updated here?
7417 }
7418
7419 _debug("Processed " . count($feeds['feeds']) . " feeds.");
7420 }
7421 } else {
7422 $status = 2;
7423 }
7424
7425 } else {
7426 $status = 0;
7427 }
7428
7429 _debug("Status: $status");
7430
7431 db_query($link, "UPDATE ttrss_linked_instances SET
7432 last_status_out = '$status', last_connected = NOW() WHERE id = '$id'");
7433
7434 }
e0d91d84
AD
7435 }
7436
afcfe6ca 7437 function make_feed_browser($link, $search, $limit, $mode = 1) {
5f0a3741 7438
afcfe6ca
AD
7439 $owner_uid = $_SESSION["uid"];
7440 $rv = '';
5f0a3741 7441
afcfe6ca
AD
7442 if ($search) {
7443 $search_qpart = "AND (UPPER(feed_url) LIKE UPPER('%$search%') OR
7444 UPPER(title) LIKE UPPER('%$search%'))";
7445 } else {
7446 $search_qpart = "";
7447 }
5f0a3741 7448
afcfe6ca
AD
7449 if ($mode == 1) {
7450 /* $result = db_query($link, "SELECT feed_url, subscribers FROM
7451 ttrss_feedbrowser_cache WHERE (SELECT COUNT(id) = 0 FROM ttrss_feeds AS tf
7452 WHERE tf.feed_url = ttrss_feedbrowser_cache.feed_url
7453 AND owner_uid = '$owner_uid') $search_qpart
7454 ORDER BY subscribers DESC LIMIT $limit"); */
5f0a3741 7455
afcfe6ca
AD
7456 $result = db_query($link, "SELECT feed_url, site_url, title, SUM(subscribers) AS subscribers FROM
7457 (SELECT feed_url, site_url, title, subscribers FROM ttrss_feedbrowser_cache UNION ALL
7458 SELECT feed_url, site_url, title, subscribers FROM ttrss_linked_feeds) AS qqq
7459 WHERE
7460 (SELECT COUNT(id) = 0 FROM ttrss_feeds AS tf
7461 WHERE tf.feed_url = qqq.feed_url
7462 AND owner_uid = '$owner_uid') $search_qpart
7463 GROUP BY feed_url, site_url, title ORDER BY subscribers DESC LIMIT $limit");
5f0a3741 7464
afcfe6ca
AD
7465 } else if ($mode == 2) {
7466 $result = db_query($link, "SELECT *,
7467 (SELECT COUNT(*) FROM ttrss_user_entries WHERE
7468 orig_feed_id = ttrss_archived_feeds.id) AS articles_archived
7469 FROM
7470 ttrss_archived_feeds
7471 WHERE
7472 (SELECT COUNT(*) FROM ttrss_feeds
7473 WHERE ttrss_feeds.feed_url = ttrss_archived_feeds.feed_url AND
7474 owner_uid = '$owner_uid') = 0 AND
7475 owner_uid = '$owner_uid' $search_qpart
7476 ORDER BY id DESC LIMIT $limit");
7477 }
5f0a3741 7478
afcfe6ca 7479 $feedctr = 0;
5f0a3741 7480
afcfe6ca 7481 while ($line = db_fetch_assoc($result)) {
5f0a3741 7482
afcfe6ca 7483 if ($mode == 1) {
5f0a3741 7484
afcfe6ca
AD
7485 $feed_url = htmlspecialchars($line["feed_url"]);
7486 $site_url = htmlspecialchars($line["site_url"]);
7487 $subscribers = $line["subscribers"];
5f0a3741 7488
afcfe6ca
AD
7489 $check_box = "<input onclick='toggleSelectListRow2(this)'
7490 dojoType=\"dijit.form.CheckBox\"
7491 type=\"checkbox\" \">";
5f0a3741 7492
afcfe6ca 7493 $class = ($feedctr % 2) ? "even" : "odd";
5f0a3741 7494
afcfe6ca
AD
7495 $site_url = "<a target=\"_blank\"
7496 href=\"$site_url\">
7497 <span class=\"fb_feedTitle\">".
7498 htmlspecialchars($line["title"])."</span></a>";
5f0a3741 7499
afcfe6ca
AD
7500 $feed_url = "<a target=\"_blank\" class=\"fb_feedUrl\"
7501 href=\"$feed_url\"><img src='images/feed-icon-12x12.png'
7502 style='vertical-align : middle'></a>";
5f0a3741 7503
afcfe6ca
AD
7504 $rv .= "<li>$check_box $feed_url $site_url".
7505 "&nbsp;<span class='subscribers'>($subscribers)</span></li>";
5f0a3741 7506
afcfe6ca
AD
7507 } else if ($mode == 2) {
7508 $feed_url = htmlspecialchars($line["feed_url"]);
7509 $site_url = htmlspecialchars($line["site_url"]);
7510 $title = htmlspecialchars($line["title"]);
5f0a3741 7511
afcfe6ca
AD
7512 $check_box = "<input onclick='toggleSelectListRow2(this)' dojoType=\"dijit.form.CheckBox\"
7513 type=\"checkbox\">";
5f0a3741 7514
afcfe6ca 7515 $class = ($feedctr % 2) ? "even" : "odd";
5f0a3741 7516
afcfe6ca
AD
7517 if ($line['articles_archived'] > 0) {
7518 $archived = sprintf(__("%d archived articles"), $line['articles_archived']);
7519 $archived = "&nbsp;<span class='subscribers'>($archived)</span>";
7520 } else {
7521 $archived = '';
7522 }
5f0a3741 7523
afcfe6ca
AD
7524 $site_url = "<a target=\"_blank\"
7525 href=\"$site_url\">
7526 <span class=\"fb_feedTitle\">".
7527 htmlspecialchars($line["title"])."</span></a>";
5f0a3741 7528
afcfe6ca
AD
7529 $feed_url = "<a target=\"_blank\" class=\"fb_feedUrl\"
7530 href=\"$feed_url\"><img src='images/feed-icon-12x12.png'
7531 style='vertical-align : middle'></a>";
5f0a3741
AD
7532
7533
afcfe6ca
AD
7534 $rv .= "<li id=\"FBROW-".$line["id"]."\">".
7535 "$check_box $feed_url $site_url $archived</li>";
7536 }
5f0a3741 7537
afcfe6ca
AD
7538 ++$feedctr;
7539 }
5f0a3741 7540
afcfe6ca
AD
7541 if ($feedctr == 0) {
7542 $rv .= "<li style=\"text-align : center\"><p>".__('No feeds found.')."</p></li>";
7543 }
5f0a3741 7544
afcfe6ca 7545 return $rv;
afcfe6ca 7546 }
5f0a3741 7547
40d13c28 7548?>