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