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