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