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