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