]> git.wh0rd.org - tt-rss.git/blame - include/functions.php
Add Traditional Chinese Option
[tt-rss.git] / include / functions.php
CommitLineData
1d3a17c7 1<?php
6e658547 2 define('EXPECTED_CONFIG_VERSION', 26);
e596b5a9 3 define('SCHEMA_VERSION', 123);
545ca067 4
f822a8e5 5 define('LABEL_BASE_INDEX', -1024);
a413f53e 6 define('PLUGIN_FEED_BASE_INDEX', -128);
f822a8e5 7
e57a1507
AD
8 define('COOKIE_LIFETIME_LONG', 86400*365);
9
23d2471c 10 $fetch_last_error = false;
7a01dc77 11 $fetch_last_error_code = false;
ef39be2b 12 $fetch_last_content_type = false;
3f6f0857 13 $fetch_curl_used = false;
4f71d743 14 $suppress_debugging = false;
23d2471c 15
d68629dc 16 mb_internal_encoding("UTF-8");
324944f3 17 date_default_timezone_set('UTC');
8a7f5767
CW
18 if (defined('E_DEPRECATED')) {
19 error_reporting(E_ALL & ~E_NOTICE & ~E_DEPRECATED);
20 } else {
21 error_reporting(E_ALL & ~E_NOTICE);
22 }
cce28758 23
40d13c28 24 require_once 'config.php';
cc17c205 25
046ec657
BK
26 /**
27 * Define a constant if not already defined
28 *
29 * @param string $name The constant name.
30 * @param mixed $value The constant value.
31 * @access public
32 * @return boolean True if defined successfully or not.
33 */
34 function define_default($name, $value) {
046ec657
BK
35 defined($name) or define($name, $value);
36 }
37
9ef8798b
BK
38 ///// Some defaults that you can override in config.php //////
39
40 define_default('FEED_FETCH_TIMEOUT', 45);
41 // How may seconds to wait for response when requesting feed from a site
42 define_default('FEED_FETCH_NO_CACHE_TIMEOUT', 15);
43 // How may seconds to wait for response when requesting feed from a
44 // site when that feed wasn't cached before
45 define_default('FILE_FETCH_TIMEOUT', 45);
46 // Default timeout when fetching files from remote sites
47 define_default('FILE_FETCH_CONNECT_TIMEOUT', 15);
48 // How many seconds to wait for initial response from website when
49 // fetching files from remote sites
046ec657 50
fc2b26a6
AD
51 if (DB_TYPE == "pgsql") {
52 define('SUBSTRING_FOR_DATE', 'SUBSTRING_FOR_DATE');
53 } else {
54 define('SUBSTRING_FOR_DATE', 'SUBSTRING');
55 }
56
9632f884
AD
57 /**
58 * Return available translations names.
8d505d78 59 *
9632f884
AD
60 * @access public
61 * @return array A array of available translations.
62 */
f8c612d4 63 function get_translations() {
6a214f92 64 $tr = array(
8d505d78 65 "auto" => "Detect automatically",
a3162add 66 "ca_CA" => "Català",
a06b79c4 67 "cs_CZ" => "Česky",
6a214f92 68 "en_US" => "English",
36d0510c 69 "es_ES" => "Español",
a927fe7b 70 "de_DE" => "Deutsch",
6a214f92 71 "fr_FR" => "Français",
e78fd196 72 "hu_HU" => "Magyar (Hungarian)",
bb5d3960 73 "it_IT" => "Italiano",
1d004f12 74 "ja_JP" => "日本語 (Japanese)",
7b6c1ca7 75 "lv_LV" => "Latviešu",
592535d7 76 "nb_NO" => "Norwegian bokmål",
9e7f1f12 77 "nl_NL" => "Dutch",
ea45791a 78 "pl_PL" => "Polski",
d3b923c9 79 "ru_RU" => "Русский",
9a063469 80 "pt_BR" => "Portuguese/Brazil",
5d608138 81 "zh_CN" => "Simplified Chinese",
8dc5e7f0 82 "zh_TW" => "Traditional Chinese",
2324f153 83 "sv_SE" => "Svenska",
76d78eb2 84 "fi_FI" => "Suomi",
42a5abdc 85 "tr_TR" => "Türkçe");
f8c612d4
AD
86
87 return $tr;
88 }
89
7b26a148
AD
90 require_once "lib/accept-to-gettext.php";
91 require_once "lib/gettext/gettext.inc";
aba609e0 92
6b461797 93 require_once "lib/languagedetect/LanguageDetect.php";
87d7e850 94
7b26a148 95 function startup_gettext() {
8d505d78 96
7b26a148
AD
97 # Get locale from Accept-Language header
98 $lang = al2gt(array_keys(get_translations()), "text/html");
89cb787e 99
7b26a148
AD
100 if (defined('_TRANSLATION_OVERRIDE_DEFAULT')) {
101 $lang = _TRANSLATION_OVERRIDE_DEFAULT;
102 }
89cb787e 103
b18d109f
AD
104 if ($_SESSION["uid"] && get_schema_version() >= 120) {
105 $pref_lang = get_pref("USER_LANGUAGE", $_SESSION["uid"]);
1ee4900a 106
c4db796f 107 if ($pref_lang && $pref_lang != 'auto') {
7b149552
AD
108 $lang = $pref_lang;
109 }
7b26a148 110 }
7c33dbd4 111
7b26a148
AD
112 if ($lang) {
113 if (defined('LC_MESSAGES')) {
114 _setlocale(LC_MESSAGES, $lang);
115 } else if (defined('LC_ALL')) {
116 _setlocale(LC_ALL, $lang);
8d039718 117 }
aba609e0 118
d98e76d9 119 _bindtextdomain("messages", "locale");
865220a4 120
7b26a148
AD
121 _textdomain("messages");
122 _bind_textdomain_codeset("messages", "UTF-8");
865220a4 123 }
7b26a148
AD
124 }
125
b619ff15 126 require_once 'db-prefs.php';
8911ac8b 127 require_once 'version.php';
87d7e850
AD
128 require_once 'ccache.php';
129 require_once 'labels.php';
40d13c28 130
fb850eec 131 define('SELF_USER_AGENT', 'Tiny Tiny RSS/' . VERSION . ' (http://tt-rss.org/)');
500943a4
AD
132 ini_set('user_agent', SELF_USER_AGENT);
133
b0f379df 134 require_once 'lib/pubsubhubbub/publisher.php';
010efc9b 135
7d96bfcd
AD
136 $schema_version = false;
137
4f71d743
AD
138 function _debug_suppress($suppress) {
139 global $suppress_debugging;
140
141 $suppress_debugging = $suppress;
142 }
143
45004d43
AD
144 /**
145 * Print a timestamped debug message.
8d505d78 146 *
45004d43
AD
147 * @param string $msg The debug message.
148 * @return void
149 */
68cccafc 150 function _debug($msg, $show = true) {
4f71d743
AD
151 global $suppress_debugging;
152
153 //echo "[$suppress_debugging] $msg $show\n";
154
155 if ($suppress_debugging) return false;
9ec10352 156
6f9e33e4 157 $ts = strftime("%H:%M:%S", time());
2a6a9395
AD
158 if (function_exists('posix_getpid')) {
159 $ts = "$ts/" . posix_getpid();
160 }
2191eb7a 161
68cccafc 162 if ($show && !(defined('QUIET') && QUIET)) {
2191eb7a
AD
163 print "[$ts] $msg\n";
164 }
165
166 if (defined('LOGFILE')) {
167 $fp = fopen(LOGFILE, 'a+');
168
169 if ($fp) {
a33558a6
AD
170 $locked = false;
171
172 if (function_exists("flock")) {
173 $tries = 0;
174
175 // try to lock logfile for writing
176 while ($tries < 5 && !$locked = flock($fp, LOCK_EX | LOCK_NB)) {
177 sleep(1);
178 ++$tries;
179 }
180
181 if (!$locked) {
182 fclose($fp);
183 return;
184 }
185 }
186
2191eb7a 187 fputs($fp, "[$ts] $msg\n");
a33558a6
AD
188
189 if (function_exists("flock")) {
190 flock($fp, LOCK_UN);
191 }
192
2191eb7a
AD
193 fclose($fp);
194 }
195 }
196
45004d43 197 } // function _debug
6f9e33e4 198
9632f884
AD
199 /**
200 * Purge a feed old posts.
8d505d78 201 *
9632f884
AD
202 * @param mixed $link A database connection.
203 * @param mixed $feed_id The id of the purged feed.
204 * @param mixed $purge_interval Olderness of purged posts.
205 * @param boolean $debug Set to True to enable the debug. False by default.
206 * @access public
207 * @return void
208 */
a42c55f0 209 function purge_feed($feed_id, $purge_interval, $debug = false) {
ad507f85 210
a42c55f0 211 if (!$purge_interval) $purge_interval = feed_purge_interval($feed_id);
8d505d78 212
ad507f85 213 $rows = -1;
4c193675 214
6322ac79 215 $result = db_query(
07d0efe9
AD
216 "SELECT owner_uid FROM ttrss_feeds WHERE id = '$feed_id'");
217
218 $owner_uid = false;
219
220 if (db_num_rows($result) == 1) {
221 $owner_uid = db_fetch_result($result, 0, "owner_uid");
222 }
223
ab954dff
AD
224 if ($purge_interval == -1 || !$purge_interval) {
225 if ($owner_uid) {
a42c55f0 226 ccache_update($feed_id, $owner_uid);
ab954dff
AD
227 }
228 return;
229 }
230
07d0efe9
AD
231 if (!$owner_uid) return;
232
3907ef71 233 if (FORCE_ARTICLE_PURGE == 0) {
a42c55f0 234 $purge_unread = get_pref("PURGE_UNREAD_ARTICLES",
3907ef71
AD
235 $owner_uid, false);
236 } else {
237 $purge_unread = true;
238 $purge_interval = FORCE_ARTICLE_PURGE;
239 }
07d0efe9
AD
240
241 if (!$purge_unread) $query_limit = " unread = false AND ";
242
fefa6ca3 243 if (DB_TYPE == "pgsql") {
6322ac79 244 $pg_version = get_pgsql_version();
6e7f8d26
AD
245
246 if (preg_match("/^7\./", $pg_version) || preg_match("/^8\.0/", $pg_version)) {
1e59ae35 247
a42c55f0 248 $result = db_query("DELETE FROM ttrss_user_entries WHERE
8d505d78
AD
249 ttrss_entries.id = ref_id AND
250 marked = false AND
251 feed_id = '$feed_id' AND
07d0efe9 252 $query_limit
25ea2805 253 ttrss_entries.date_updated < NOW() - INTERVAL '$purge_interval days'");
1e59ae35
AD
254
255 } else {
256
a42c55f0 257 $result = db_query("DELETE FROM ttrss_user_entries
8d505d78
AD
258 USING ttrss_entries
259 WHERE ttrss_entries.id = ref_id AND
260 marked = false AND
261 feed_id = '$feed_id' AND
07d0efe9 262 $query_limit
25ea2805 263 ttrss_entries.date_updated < NOW() - INTERVAL '$purge_interval days'");
1e59ae35 264 }
ad507f85 265
fefa6ca3 266 } else {
8d505d78 267
a42c55f0 268/* $result = db_query("DELETE FROM ttrss_user_entries WHERE
fefa6ca3 269 marked = false AND feed_id = '$feed_id' AND
8d505d78 270 (SELECT date_updated FROM ttrss_entries WHERE
30f1746f
AD
271 id = ref_id) < DATE_SUB(NOW(), INTERVAL $purge_interval DAY)"); */
272
a42c55f0 273 $result = db_query("DELETE FROM ttrss_user_entries
8d505d78
AD
274 USING ttrss_user_entries, ttrss_entries
275 WHERE ttrss_entries.id = ref_id AND
276 marked = false AND
277 feed_id = '$feed_id' AND
07d0efe9 278 $query_limit
25ea2805 279 ttrss_entries.date_updated < DATE_SUB(NOW(), INTERVAL $purge_interval DAY)");
ad507f85
AD
280 }
281
a08f94bd 282 $rows = db_affected_rows($result);
3f6f0857 283
a42c55f0 284 ccache_update($feed_id, $owner_uid);
ced46404 285
ad507f85 286 if ($debug) {
6f9e33e4 287 _debug("Purged feed $feed_id ($purge_interval): deleted $rows articles");
fefa6ca3 288 }
2ea09bde
AD
289
290 return $rows;
9632f884 291 } // function purge_feed
fefa6ca3 292
a42c55f0 293 function feed_purge_interval($feed_id) {
07d0efe9 294
a42c55f0 295 $result = db_query("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
6322ac79 302 if ($purge_interval == 0) $purge_interval = get_pref(
863be6ca 303 'PURGE_OLD_DAYS', $owner_uid);
07d0efe9
AD
304
305 return $purge_interval;
306
307 } else {
308 return -1;
309 }
310 }
311
a42c55f0 312 function purge_orphans($do_output = false) {
a2d79981 313
71604ca4 314 // purge orphaned posts in main content table
a42c55f0 315 $result = db_query("DELETE FROM ttrss_entries WHERE
71604ca4 316 (SELECT COUNT(int_id) FROM ttrss_user_entries WHERE ref_id = id) = 0");
a2d79981
AD
317
318 if ($do_output) {
a42c55f0 319 $rows = db_affected_rows($result);
a2d79981
AD
320 _debug("Purged $rows orphaned posts.");
321 }
c3a8d71a
AD
322 }
323
a42c55f0
AD
324 function get_feed_update_interval($feed_id) {
325 $result = db_query("SELECT owner_uid, update_interval FROM
c7d57b66
AD
326 ttrss_feeds WHERE id = '$feed_id'");
327
328 if (db_num_rows($result) == 1) {
329 $update_interval = db_fetch_result($result, 0, "update_interval");
330 $owner_uid = db_fetch_result($result, 0, "owner_uid");
331
332 if ($update_interval != 0) {
333 return $update_interval;
334 } else {
a42c55f0 335 return get_pref('DEFAULT_UPDATE_INTERVAL', $owner_uid, false);
c7d57b66
AD
336 }
337
338 } else {
339 return -1;
340 }
341 }
342
f826070c 343 function fetch_file_contents($url, $type = false, $login = false, $pass = false, $post_query = false, $timeout = false, $timestamp = 0, $useragent = false) {
8d505d78 344
23d2471c 345 global $fetch_last_error;
7a01dc77 346 global $fetch_last_error_code;
ef39be2b 347 global $fetch_last_content_type;
3f6f0857 348 global $fetch_curl_used;
33373eca 349
2375b6b6 350 $url = str_replace(' ', '%20', $url);
23d2471c 351
3f6f0857
AD
352 if (!defined('NO_CURL') && function_exists('curl_init')) {
353
354 $fetch_curl_used = true;
b799dc8b 355
438a3ecb 356 if (ini_get("safe_mode") || ini_get("open_basedir")) {
e2b4c0b7
RH
357 $new_url = geturl($url);
358 if (!$new_url) {
359 // geturl has already populated $fetch_last_error
360 return false;
361 }
362 $ch = curl_init($new_url);
b799dc8b
AD
363 } else {
364 $ch = curl_init($url);
365 }
a1af1574 366
81c20663 367 if ($timestamp && !$post_query) {
7a01dc77
AD
368 curl_setopt($ch, CURLOPT_HTTPHEADER,
369 array("If-Modified-Since: ".gmdate('D, d M Y H:i:s \G\M\T', $timestamp)));
370 }
371
8401101d
BK
372 curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout ? $timeout : FILE_FETCH_CONNECT_TIMEOUT);
373 curl_setopt($ch, CURLOPT_TIMEOUT, $timeout ? $timeout : FILE_FETCH_TIMEOUT);
438a3ecb 374 curl_setopt($ch, CURLOPT_FOLLOWLOCATION, !ini_get("safe_mode") && !ini_get("open_basedir"));
a1af1574
AD
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);
f826070c
AD
380 curl_setopt($ch, CURLOPT_USERAGENT, $useragent ? $useragent :
381 SELF_USER_AGENT);
3f6f0857 382 curl_setopt($ch, CURLOPT_ENCODING, "");
48b657fc 383 curl_setopt($ch, CURLOPT_REFERER, $url);
0f6b9263
AD
384
385 if (!ini_get("safe_mode") && !ini_get("open_basedir")) {
386 curl_setopt($ch, CURLOPT_COOKIEJAR, "/dev/null");
387 }
8d505d78 388
05f14a7d
AD
389 if (defined('_CURL_HTTP_PROXY')) {
390 curl_setopt($ch, CURLOPT_PROXY, _CURL_HTTP_PROXY);
391 }
392
ae5f7bb1
AD
393 if ($post_query) {
394 curl_setopt($ch, CURLOPT_POST, true);
395 curl_setopt($ch, CURLOPT_POSTFIELDS, $post_query);
396 }
397
d86945c7 398 if ((OPENSSL_VERSION_NUMBER >= 0x0090808f) && (OPENSSL_VERSION_NUMBER < 0x10000000)) {
893960b0 399 curl_setopt($ch, CURLOPT_SSLVERSION, 3);
d86945c7
AD
400 }
401
8d505d78
AD
402 if ($login && $pass)
403 curl_setopt($ch, CURLOPT_USERPWD, "$login:$pass");
a1af1574 404
fb074239 405 $contents = @curl_exec($ch);
268a06dc 406
48b657fc
AD
407 if (curl_errno($ch) === 23 || curl_errno($ch) === 61) {
408 curl_setopt($ch, CURLOPT_ENCODING, 'none');
409 $contents = @curl_exec($ch);
fb850eec
AD
410 }
411
a1af1574 412 if ($contents === false) {
fb850eec 413 $fetch_last_error = curl_errno($ch) . " " . curl_error($ch);
a1af1574
AD
414 curl_close($ch);
415 return false;
4065b60b
AD
416 }
417
8d505d78 418 $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
ef39be2b 419 $fetch_last_content_type = curl_getinfo($ch, CURLINFO_CONTENT_TYPE);
4065b60b 420
7a01dc77
AD
421 $fetch_last_error_code = $http_code;
422
ef39be2b 423 if ($http_code != 200 || $type && strpos($fetch_last_content_type, "$type") === false) {
fb850eec
AD
424 if (curl_errno($ch) != 0) {
425 $fetch_last_error = curl_errno($ch) . " " . curl_error($ch);
426 } else {
427 $fetch_last_error = "HTTP Code: $http_code";
428 }
429 curl_close($ch);
a1af1574
AD
430 return false;
431 }
4065b60b 432
fb850eec
AD
433 curl_close($ch);
434
a1af1574 435 return $contents;
4065b60b 436 } else {
3f6f0857
AD
437
438 $fetch_curl_used = false;
439
d3911f80 440 if ($login && $pass){
8d505d78
AD
441 $url_parts = array();
442
443 preg_match("/(^[^:]*):\/\/(.*)/", $url, $url_parts);
444
d3911f80
AD
445 $pass = urlencode($pass);
446
8d505d78
AD
447 if ($url_parts[1] && $url_parts[2]) {
448 $url = $url_parts[1] . "://$login:$pass@" . $url_parts[2];
449 }
450 }
451
01311d86
AD
452 if (!$post_query && $timestamp) {
453 $context = stream_context_create(array(
454 'http' => array(
455 'method' => 'GET',
456 'header' => "If-Modified-Since: ".gmdate("D, d M Y H:i:s \\G\\M\\T\r\n", $timestamp)
457 )));
458 } else {
459 $context = NULL;
460 }
461
6122c449
AD
462 $old_error = error_get_last();
463
01311d86 464 $data = @file_get_contents($url, false, $context);
23d2471c 465
ef39be2b 466 $fetch_last_content_type = false; // reset if no type was sent from server
37ddf5b7 467 if (isset($http_response_header) && is_array($http_response_header)) {
df25e4d2
AD
468 foreach ($http_response_header as $h) {
469 if (substr(strtolower($h), 0, 13) == 'content-type:') {
470 $fetch_last_content_type = substr($h, 14);
471 // don't abort here b/c there might be more than one
472 // e.g. if we were being redirected -- last one is the right one
473 }
01311d86
AD
474
475 if (substr(strtolower($h), 0, 7) == 'http/1.') {
476 $fetch_last_error_code = (int) substr($h, 9, 3);
477 }
ef39be2b
MB
478 }
479 }
480
6122c449 481 if (!$data) {
23d2471c 482 $error = error_get_last();
6122c449
AD
483
484 if ($error['message'] != $old_error['message']) {
485 $fetch_last_error = $error["message"];
486 } else {
487 $fetch_last_error = "HTTP Code: $fetch_last_error_code";
488 }
23d2471c
AD
489 }
490 return $data;
4065b60b
AD
491 }
492
493 }
78800912 494
9632f884
AD
495 /**
496 * Try to determine the favicon URL for a feed.
497 * adapted from wordpress favicon plugin by Jeff Minard (http://thecodepro.com/)
498 * http://dev.wp-plugins.org/file/favatars/trunk/favatars.php
8d505d78 499 *
9632f884
AD
500 * @param string $url A feed or page URL
501 * @access public
502 * @return mixed The favicon URL, or false if none was found.
503 */
1bd11fdf 504 function get_favicon_url($url) {
99331724 505
1bd11fdf 506 $favicon_url = false;
ed214298 507
4065b60b 508 if ($html = @fetch_file_contents($url)) {
78800912 509
ed214298 510 libxml_use_internal_errors(true);
c798704b 511
ed214298
AD
512 $doc = new DOMDocument();
513 $doc->loadHTML($html);
514 $xpath = new DOMXPath($doc);
717f5e64 515
a712429e
AD
516 $base = $xpath->query('/html/head/base');
517 foreach ($base as $b) {
518 $url = $b->getAttribute("href");
519 break;
520 }
521
1bd11fdf 522 $entries = $xpath->query('/html/head/link[@rel="shortcut icon" or @rel="icon"]');
ed214298
AD
523 if (count($entries) > 0) {
524 foreach ($entries as $entry) {
1bd11fdf
AD
525 $favicon_url = rewrite_relative_url($url, $entry->getAttribute("href"));
526 break;
ed214298 527 }
8d505d78 528 }
4065b60b 529 }
c798704b 530
1bd11fdf
AD
531 if (!$favicon_url)
532 $favicon_url = rewrite_relative_url($url, "/favicon.ico");
533
534 return $favicon_url;
535 } // function get_favicon_url
536
6322ac79 537 function check_feed_favicon($site_url, $feed) {
882311d9 538# print "FAVICON [$site_url]: $favicon_url\n";
4065b60b 539
1bd11fdf
AD
540 $icon_file = ICONS_DIR . "/$feed.ico";
541
542 if (!file_exists($icon_file)) {
543 $favicon_url = get_favicon_url($site_url);
544
545 if ($favicon_url) {
546 // Limiting to "image" type misses those served with text/plain
547 $contents = fetch_file_contents($favicon_url); // , "image");
548
549 if ($contents) {
550 // Crude image type matching.
551 // Patterns gleaned from the file(1) source code.
552 if (preg_match('/^\x00\x00\x01\x00/', $contents)) {
553 // 0 string \000\000\001\000 MS Windows icon resource
554 //error_log("check_feed_favicon: favicon_url=$favicon_url isa MS Windows icon resource");
555 }
556 elseif (preg_match('/^GIF8/', $contents)) {
557 // 0 string GIF8 GIF image data
558 //error_log("check_feed_favicon: favicon_url=$favicon_url isa GIF image");
559 }
560 elseif (preg_match('/^\x89PNG\x0d\x0a\x1a\x0a/', $contents)) {
561 // 0 string \x89PNG\x0d\x0a\x1a\x0a PNG image data
562 //error_log("check_feed_favicon: favicon_url=$favicon_url isa PNG image");
563 }
564 elseif (preg_match('/^\xff\xd8/', $contents)) {
565 // 0 beshort 0xffd8 JPEG image data
566 //error_log("check_feed_favicon: favicon_url=$favicon_url isa JPG image");
567 }
568 else {
569 //error_log("check_feed_favicon: favicon_url=$favicon_url isa UNKNOWN type");
570 $contents = "";
571 }
572 }
573
574 if ($contents) {
575 $fp = @fopen($icon_file, "w");
576
577 if ($fp) {
578 fwrite($fp, $contents);
579 fclose($fp);
580 chmod($icon_file, 0644);
581 }
582 }
583 }
2cfbb448 584 return $icon_file;
78800912
AD
585 }
586 }
14118af3 587
f175937c 588 function print_select($id, $default, $values, $attributes = "") {
79f3553b 589 print "<select name=\"$id\" id=\"$id\" $attributes>";
a0d53889
AD
590 foreach ($values as $v) {
591 if ($v == $default)
60807300 592 $sel = "selected=\"1\"";
a0d53889
AD
593 else
594 $sel = "";
8d505d78 595
e88c1943
AD
596 $v = trim($v);
597
60807300 598 print "<option value=\"$v\" $sel>$v</option>";
a0d53889
AD
599 }
600 print "</select>";
601 }
40d13c28 602
79f3553b
AD
603 function print_select_hash($id, $default, $values, $attributes = "") {
604 print "<select name=\"$id\" id='$id' $attributes>";
673d54ca
AD
605 foreach (array_keys($values) as $v) {
606 if ($v == $default)
74d5c8fa 607 $sel = 'selected="selected"';
673d54ca
AD
608 else
609 $sel = "";
8d505d78 610
e88c1943
AD
611 $v = trim($v);
612
673d54ca
AD
613 print "<option $sel value=\"$v\">".$values[$v]."</option>";
614 }
615
616 print "</select>";
617 }
618
f541eb78 619 function print_radio($id, $default, $true_is, $values, $attributes = "") {
77e96719 620 foreach ($values as $v) {
8d505d78 621
77e96719 622 if ($v == $default)
5da169d9 623 $sel = "checked";
77e96719 624 else
5da169d9
AD
625 $sel = "";
626
f541eb78 627 if ($v == $true_is) {
5da169d9
AD
628 $sel .= " value=\"1\"";
629 } else {
630 $sel .= " value=\"0\"";
631 }
8d505d78
AD
632
633 print "<input class=\"noborder\" dojoType=\"dijit.form.RadioButton\"
69654950 634 type=\"radio\" $sel $attributes name=\"$id\">&nbsp;$v&nbsp;";
77e96719
AD
635
636 }
637 }
638
a42c55f0 639 function initialize_user_prefs($uid, $profile = false) {
ff485f1d 640
a42c55f0 641 $uid = db_escape_string($uid);
ff485f1d 642
d9084cf2
AD
643 if (!$profile) {
644 $profile = "NULL";
f9aa6a89 645 $profile_qpart = "AND profile IS NULL";
d9084cf2 646 } else {
f9aa6a89 647 $profile_qpart = "AND profile = '$profile'";
d9084cf2
AD
648 }
649
6322ac79 650 if (get_schema_version() < 63) $profile_qpart = "";
f9aa6a89 651
a42c55f0 652 db_query("BEGIN");
ff485f1d 653
a42c55f0 654 $result = db_query("SELECT pref_name,def_value FROM ttrss_prefs");
8d505d78 655
a42c55f0 656 $u_result = db_query("SELECT pref_name
f9aa6a89 657 FROM ttrss_user_prefs WHERE owner_uid = '$uid' $profile_qpart");
ff485f1d
AD
658
659 $active_prefs = array();
660
661 while ($line = db_fetch_assoc($u_result)) {
8d505d78 662 array_push($active_prefs, $line["pref_name"]);
ff485f1d
AD
663 }
664
665 while ($line = db_fetch_assoc($result)) {
666 if (array_search($line["pref_name"], $active_prefs) === FALSE) {
667// print "adding " . $line["pref_name"] . "<br>";
668
a42c55f0
AD
669 $line["def_value"] = db_escape_string($line["def_value"]);
670 $line["pref_name"] = db_escape_string($line["pref_name"]);
d296ba50 671
6322ac79 672 if (get_schema_version() < 63) {
a42c55f0 673 db_query("INSERT INTO ttrss_user_prefs
8d505d78 674 (owner_uid,pref_name,value) VALUES
f9aa6a89
AD
675 ('$uid', '".$line["pref_name"]."','".$line["def_value"]."')");
676
677 } else {
a42c55f0 678 db_query("INSERT INTO ttrss_user_prefs
8d505d78 679 (owner_uid,pref_name,value, profile) VALUES
f9aa6a89
AD
680 ('$uid', '".$line["pref_name"]."','".$line["def_value"]."', $profile)");
681 }
ff485f1d
AD
682
683 }
684 }
685
a42c55f0 686 db_query("COMMIT");
ff485f1d
AD
687
688 }
956c7629 689
8de8bfb8
AD
690 function get_ssl_certificate_id() {
691 if ($_SERVER["REDIRECT_SSL_CLIENT_M_SERIAL"]) {
692 return sha1($_SERVER["REDIRECT_SSL_CLIENT_M_SERIAL"] .
693 $_SERVER["REDIRECT_SSL_CLIENT_V_START"] .
694 $_SERVER["REDIRECT_SSL_CLIENT_V_END"] .
695 $_SERVER["REDIRECT_SSL_CLIENT_S_DN"]);
696 }
ac617ebc
GG
697 if ($_SERVER["SSL_CLIENT_M_SERIAL"]) {
698 return sha1($_SERVER["SSL_CLIENT_M_SERIAL"] .
699 $_SERVER["SSL_CLIENT_V_START"] .
700 $_SERVER["SSL_CLIENT_V_END"] .
701 $_SERVER["SSL_CLIENT_S_DN"]);
702 }
8de8bfb8
AD
703 return "";
704 }
705
a42c55f0 706 function authenticate_user($login, $password, $check_only = false) {
c8437f35 707
131b01b3 708 if (!SINGLE_USER_MODE) {
0d421af8 709 $user_id = false;
0f28f81f 710
1ffe3391 711 foreach (PluginHost::getInstance()->get_hooks(PluginHost::HOOK_AUTH_USER) as $plugin) {
0f28f81f
AD
712
713 $user_id = (int) $plugin->authenticate($login, $password);
714
715 if ($user_id) {
716 $_SESSION["auth_module"] = strtolower(get_class($plugin));
717 break;
718 }
461766f3
AD
719 }
720
0d421af8 721 if ($user_id && !$check_only) {
70400171
AD
722 @session_start();
723
0d421af8 724 $_SESSION["uid"] = $user_id;
3472c4c5 725 $_SESSION["version"] = VERSION_STATIC;
0d421af8 726
a42c55f0 727 $result = db_query("SELECT login,access_level,pwd_hash FROM ttrss_users
0d421af8 728 WHERE id = '$user_id'");
8d505d78 729
131b01b3
AD
730 $_SESSION["name"] = db_fetch_result($result, 0, "login");
731 $_SESSION["access_level"] = db_fetch_result($result, 0, "access_level");
76d78eb2 732 $_SESSION["csrf_token"] = uniqid(rand(), true);
8d505d78 733
a42c55f0 734 db_query("UPDATE ttrss_users SET last_login = NOW() WHERE id = " .
131b01b3 735 $_SESSION["uid"]);
8d505d78 736
131b01b3 737 $_SESSION["ip_address"] = $_SERVER["REMOTE_ADDR"];
837ec70e 738 $_SESSION["user_agent"] = sha1($_SERVER['HTTP_USER_AGENT']);
1a9f4d3c 739 $_SESSION["pwd_hash"] = db_fetch_result($result, 0, "pwd_hash");
91c5f229
AD
740
741 $_SESSION["last_version_check"] = time();
8d505d78 742
a42c55f0 743 initialize_user_prefs($_SESSION["uid"]);
8d505d78 744
131b01b3
AD
745 return true;
746 }
8d505d78 747
131b01b3 748 return false;
503eb349 749
131b01b3 750 } else {
503eb349 751
131b01b3
AD
752 $_SESSION["uid"] = 1;
753 $_SESSION["name"] = "admin";
787e5ebc 754 $_SESSION["access_level"] = 10;
21e42e5f 755
0d421af8
AD
756 $_SESSION["hide_hello"] = true;
757 $_SESSION["hide_logout"] = true;
758
d5fd183d
AD
759 $_SESSION["auth_module"] = false;
760
21e42e5f 761 if (!$_SESSION["csrf_token"]) {
76d78eb2 762 $_SESSION["csrf_token"] = uniqid(rand(), true);
21e42e5f 763 }
f557cd78 764
0bbba72d 765 $_SESSION["ip_address"] = $_SERVER["REMOTE_ADDR"];
8d505d78 766
a42c55f0 767 initialize_user_prefs($_SESSION["uid"]);
8d505d78 768
c8437f35
AD
769 return true;
770 }
c8437f35
AD
771 }
772
e6cb77a0
AD
773 function make_password($length = 8) {
774
85db6213
AD
775 $password = "";
776 $possible = "0123456789abcdfghjkmnpqrstvwxyzABCDFGHJKMNPQRSTVWXYZ";
777
778 $i = 0;
779
780 while ($i < $length) {
781 $char = substr($possible, mt_rand(0, strlen($possible)-1), 1);
782
783 if (!strstr($password, $char)) {
784 $password .= $char;
785 $i++;
786 }
787 }
788 return $password;
e6cb77a0
AD
789 }
790
791 // this is called after user is created to initialize default feeds, labels
792 // or whatever else
8d505d78 793
e6cb77a0
AD
794 // user preferences are checked on every login, not here
795
a42c55f0 796 function initialize_user($uid) {
e6cb77a0 797
a42c55f0 798 db_query("insert into ttrss_feeds (owner_uid,title,feed_url)
74bff337 799 values ('$uid', 'Tiny Tiny RSS: New Releases',
b6d486a3 800 'http://tt-rss.org/releases.rss')");
3b0feb9b 801
a42c55f0 802 db_query("insert into ttrss_feeds (owner_uid,title,feed_url)
cd2cd415 803 values ('$uid', 'Tiny Tiny RSS: Forum',
f0855b88 804 'http://tt-rss.org/forum/rss.php')");
3b0feb9b 805 }
e6cb77a0 806
b8aa49bc 807 function logout_user() {
5ccc1cf5
AD
808 session_destroy();
809 if (isset($_COOKIE[session_name()])) {
810 setcookie(session_name(), '', time()-42000, '/');
811 }
b8aa49bc
AD
812 }
813
8484ce22
AD
814 function validate_csrf($csrf_token) {
815 return $csrf_token == $_SESSION['csrf_token'];
816 }
817
a42c55f0 818 function load_user_plugins($owner_uid) {
6d45a152 819 if ($owner_uid && SCHEMA_VERSION >= 100) {
a42c55f0 820 $plugins = get_pref("_ENABLED_PLUGINS", $owner_uid);
de612e7a 821
1ffe3391 822 PluginHost::getInstance()->load($plugins, PluginHost::KIND_USER, $owner_uid);
e9c04fd4 823
6322ac79 824 if (get_schema_version() > 100) {
1ffe3391 825 PluginHost::getInstance()->load_data();
e9c04fd4 826 }
de612e7a
AD
827 }
828 }
829
6322ac79 830 function login_sequence() {
97acbaf1 831 if (SINGLE_USER_MODE) {
25db6c51 832 @session_start();
a42c55f0 833 authenticate_user("admin", null);
68349f55 834 startup_gettext();
a42c55f0 835 load_user_plugins($_SESSION["uid"]);
97acbaf1 836 } else {
6322ac79 837 if (!validate_session()) $_SESSION["uid"] = false;
d0eef2a3
AD
838
839 if (!$_SESSION["uid"]) {
97acbaf1 840
a42c55f0
AD
841 if (AUTH_AUTO_LOGIN && authenticate_user(null, null)) {
842 $_SESSION["ref_schema_version"] = get_schema_version(true);
97acbaf1 843 } else {
a42c55f0 844 authenticate_user(null, null, true);
97acbaf1
AD
845 }
846
d0eef2a3 847 if (!$_SESSION["uid"]) {
d0eef2a3
AD
848 @session_destroy();
849 setcookie(session_name(), '', time()-42000, '/');
9ce7a554 850
6322ac79 851 render_login_form();
d0eef2a3
AD
852 exit;
853 }
4ad99f23 854
97acbaf1
AD
855 } else {
856 /* bump login timestamp */
a42c55f0 857 db_query("UPDATE ttrss_users SET last_login = NOW() WHERE id = " .
97acbaf1 858 $_SESSION["uid"]);
06b0777f 859 $_SESSION["last_login_update"] = time();
01a87dff
AD
860 }
861
de612e7a 862 if ($_SESSION["uid"]) {
7b149552 863 startup_gettext();
a42c55f0 864 load_user_plugins($_SESSION["uid"]);
b1b1d25f
AD
865
866 /* cleanup ccache */
867
a42c55f0 868 db_query("DELETE FROM ttrss_counters_cache WHERE owner_uid = ".
b1b1d25f
AD
869 $_SESSION["uid"] . " AND
870 (SELECT COUNT(id) FROM ttrss_feeds WHERE
871 ttrss_feeds.id = feed_id) = 0");
872
a42c55f0 873 db_query("DELETE FROM ttrss_cat_counters_cache WHERE owner_uid = ".
b1b1d25f
AD
874 $_SESSION["uid"] . " AND
875 (SELECT COUNT(id) FROM ttrss_feed_categories WHERE
876 ttrss_feed_categories.id = feed_id) = 0");
877
de612e7a 878 }
b1b1d25f 879
b8aa49bc 880 }
afc3cf55 881 }
3547842a 882
411fe209 883 function truncate_string($str, $max_len, $suffix = '&hellip;') {
878a0083 884 if (mb_strlen($str, "utf-8") > $max_len) {
411fe209 885 return mb_substr($str, 0, $max_len, "utf-8") . $suffix;
3547842a
AD
886 } else {
887 return $str;
888 }
889 }
54a60e1a 890
ab4b768f
AD
891 function convert_timestamp($timestamp, $source_tz, $dest_tz) {
892
893 try {
894 $source_tz = new DateTimeZone($source_tz);
895 } catch (Exception $e) {
896 $source_tz = new DateTimeZone('UTC');
897 }
898
899 try {
900 $dest_tz = new DateTimeZone($dest_tz);
901 } catch (Exception $e) {
902 $dest_tz = new DateTimeZone('UTC');
903 }
904
905 $dt = new DateTime(date('Y-m-d H:i:s', $timestamp), $source_tz);
906 return $dt->format('U') + $dest_tz->getOffset($dt);
907 }
908
a42c55f0 909 function make_local_datetime($timestamp, $long, $owner_uid = false,
324944f3
AD
910 $no_smart_dt = false) {
911
912 if (!$owner_uid) $owner_uid = $_SESSION['uid'];
913 if (!$timestamp) $timestamp = '1970-01-01 0:00';
914
7d96bfcd 915 global $utc_tz;
5ddef5ba
AD
916 global $user_tz;
917
918 if (!$utc_tz) $utc_tz = new DateTimeZone('UTC');
324944f3 919
90e5f4f1
AD
920 $timestamp = substr($timestamp, 0, 19);
921
7d96bfcd
AD
922 # We store date in UTC internally
923 $dt = new DateTime($timestamp, $utc_tz);
924
5ddef5ba 925 $user_tz_string = get_pref('USER_TIMEZONE', $owner_uid);
7d96bfcd 926
6bfc97da 927 if ($user_tz_string != 'Automatic') {
324944f3 928
6bfc97da
AD
929 try {
930 if (!$user_tz) $user_tz = new DateTimeZone($user_tz_string);
931 } catch (Exception $e) {
932 $user_tz = $utc_tz;
933 }
934
935 $tz_offset = $user_tz->getOffset($dt);
936 } else {
96f0cbe3 937 $tz_offset = (int) -$_SESSION["clientTzOffset"];
6bfc97da 938 }
5ddef5ba 939
7d96bfcd 940 $user_timestamp = $dt->format('U') + $tz_offset;
324944f3 941
1dc52ae7 942 if (!$no_smart_dt) {
a42c55f0 943 return smart_date_time($user_timestamp,
7d96bfcd 944 $tz_offset, $owner_uid);
324944f3
AD
945 } else {
946 if ($long)
a42c55f0 947 $format = get_pref('LONG_DATE_FORMAT', $owner_uid);
324944f3 948 else
a42c55f0 949 $format = get_pref('SHORT_DATE_FORMAT', $owner_uid);
324944f3
AD
950
951 return date($format, $user_timestamp);
952 }
953 }
954
a42c55f0 955 function smart_date_time($timestamp, $tz_offset = 0, $owner_uid = false) {
2a5c136e
AD
956 if (!$owner_uid) $owner_uid = $_SESSION['uid'];
957
958 if (date("Y.m.d", $timestamp) == date("Y.m.d", time() + $tz_offset)) {
be773442 959 return date("G:i", $timestamp);
2a5c136e 960 } else if (date("Y", $timestamp) == date("Y", time() + $tz_offset)) {
a42c55f0 961 $format = get_pref('SHORT_DATE_FORMAT', $owner_uid);
2a5c136e 962 return date($format, $timestamp);
be773442 963 } else {
a42c55f0 964 $format = get_pref('LONG_DATE_FORMAT', $owner_uid);
2a5c136e 965 return date($format, $timestamp);
be773442
AD
966 }
967 }
968
e3c99f3b 969 function sql_bool_to_bool($s) {
9955a134 970 if ($s == "t" || $s == "1" || strtolower($s) == "true") {
e3c99f3b
AD
971 return true;
972 } else {
973 return false;
974 }
975 }
8d505d78 976
badac687
AD
977 function bool_to_sql_bool($s) {
978 if ($s) {
979 return "true";
980 } else {
981 return "false";
982 }
983 }
e3c99f3b 984
fcfa9ef1
AD
985 // Session caching removed due to causing wrong redirects to upgrade
986 // script when get_schema_version() is called on an obsolete session
987 // created on a previous schema version.
a42c55f0 988 function get_schema_version($nocache = false) {
7d96bfcd
AD
989 global $schema_version;
990
e2cf81e2 991 if (!$schema_version && !$nocache) {
a42c55f0 992 $result = db_query("SELECT schema_version FROM ttrss_version");
199db684 993 $version = db_fetch_result($result, 0, "schema_version");
7d96bfcd 994 $schema_version = $version;
199db684 995 return $version;
7d96bfcd
AD
996 } else {
997 return $schema_version;
998 }
e4c51a6c
AD
999 }
1000
6322ac79 1001 function sanity_check() {
31303c6b 1002 require_once 'errors.php';
ebb948c2 1003
6043fb7e 1004 $error_code = 0;
a42c55f0 1005 $schema_version = get_schema_version(true);
6043fb7e
AD
1006
1007 if ($schema_version != SCHEMA_VERSION) {
1008 $error_code = 5;
1009 }
1010
aec3ce39 1011 if (DB_TYPE == "mysql") {
a42c55f0 1012 $result = db_query("SELECT true", false);
aec3ce39
AD
1013 if (db_num_rows($result) != 1) {
1014 $error_code = 10;
1015 }
1016 }
1017
a42c55f0 1018 if (db_escape_string("testTEST") != "testTEST") {
f29ba148
AD
1019 $error_code = 12;
1020 }
1021
ebb948c2 1022 return array("code" => $error_code, "message" => $ERRORS[$error_code]);
6043fb7e
AD
1023 }
1024
27981ca3 1025 function file_is_locked($filename) {
8ff2a86c
AD
1026 if (file_exists(LOCK_DIRECTORY . "/$filename")) {
1027 if (function_exists('flock')) {
1028 $fp = @fopen(LOCK_DIRECTORY . "/$filename", "r");
1029 if ($fp) {
1030 if (flock($fp, LOCK_EX | LOCK_NB)) {
1031 flock($fp, LOCK_UN);
1032 fclose($fp);
1033 return false;
1034 }
31a6d42d 1035 fclose($fp);
8ff2a86c
AD
1036 return true;
1037 } else {
31a6d42d
AD
1038 return false;
1039 }
27981ca3 1040 }
8ff2a86c
AD
1041 return true; // consider the file always locked and skip the test
1042 } else {
1043 return false;
27981ca3 1044 }
27981ca3
AD
1045 }
1046
8ff2a86c 1047
fcb4c0c9 1048 function make_lockfile($filename) {
cfa43e02 1049 $fp = fopen(LOCK_DIRECTORY . "/$filename", "w");
fcb4c0c9 1050
a44bfcfd 1051 if ($fp && flock($fp, LOCK_EX | LOCK_NB)) {
58fc7095
AD
1052 $stat_h = fstat($fp);
1053 $stat_f = stat(LOCK_DIRECTORY . "/$filename");
1054
1fcebfb3
AD
1055 if (strtoupper(substr(PHP_OS, 0, 3)) !== 'WIN') {
1056 if ($stat_h["ino"] != $stat_f["ino"] ||
1057 $stat_h["dev"] != $stat_f["dev"]) {
1058
1059 return false;
1060 }
58fc7095
AD
1061 }
1062
4c59adb1
AD
1063 if (function_exists('posix_getpid')) {
1064 fwrite($fp, posix_getpid() . "\n");
1065 }
fcb4c0c9
AD
1066 return $fp;
1067 } else {
1068 return false;
1069 }
1070 }
1071
bf7fcde8 1072 function make_stampfile($filename) {
cfa43e02 1073 $fp = fopen(LOCK_DIRECTORY . "/$filename", "w");
bf7fcde8 1074
8e00ae9b 1075 if (flock($fp, LOCK_EX | LOCK_NB)) {
bf7fcde8 1076 fwrite($fp, time() . "\n");
8e00ae9b 1077 flock($fp, LOCK_UN);
bf7fcde8
AD
1078 fclose($fp);
1079 return true;
1080 } else {
1081 return false;
1082 }
1083 }
1084
894ebcf5 1085 function sql_random_function() {
8c0496f7 1086 if (DB_TYPE == "mysql") {
894ebcf5
AD
1087 return "RAND()";
1088 } else {
1089 return "RANDOM()";
1090 }
1091 }
1092
a42c55f0 1093 function catchup_feed($feed, $cat_view, $owner_uid = false, $max_id = false, $mode = 'all') {
c7e51de1
AD
1094
1095 if (!$owner_uid) $owner_uid = $_SESSION['uid'];
88040f57 1096
37c03d3a 1097 //if (preg_match("/^-?[0-9][0-9]*$/", $feed) != false) {
22fdebff 1098
c8b693cf
AD
1099 // Todo: all this interval stuff needs some generic generator function
1100
1101 $date_qpart = "false";
1102
1103 switch ($mode) {
1104 case "1day":
1105 if (DB_TYPE == "pgsql") {
94828a8b 1106 $date_qpart = "date_entered < NOW() - INTERVAL '1 day' ";
c8b693cf 1107 } else {
d5381016 1108 $date_qpart = "date_entered < DATE_SUB(NOW(), INTERVAL 1 DAY) ";
c8b693cf
AD
1109 }
1110 break;
1111 case "1week":
1112 if (DB_TYPE == "pgsql") {
94828a8b 1113 $date_qpart = "date_entered < NOW() - INTERVAL '1 week' ";
c8b693cf 1114 } else {
94828a8b 1115 $date_qpart = "date_entered < DATE_SUB(NOW(), INTERVAL 1 WEEK) ";
c8b693cf
AD
1116 }
1117 break;
8d476359 1118 case "2week":
c8b693cf 1119 if (DB_TYPE == "pgsql") {
94828a8b 1120 $date_qpart = "date_entered < NOW() - INTERVAL '2 week' ";
c8b693cf 1121 } else {
94828a8b 1122 $date_qpart = "date_entered < DATE_SUB(NOW(), INTERVAL 2 WEEK) ";
c8b693cf
AD
1123 }
1124 break;
1125 default:
1126 $date_qpart = "true";
1127 }
1128
37c03d3a 1129 if (is_numeric($feed)) {
23aa0d16
AD
1130 if ($cat_view) {
1131
72a2f4f5 1132 if ($feed >= 0) {
f9fca8cb
AD
1133
1134 if ($feed > 0) {
a42c55f0 1135 $children = getChildCategories($feed, $owner_uid);
bda6afa2
AD
1136 array_push($children, $feed);
1137
1138 $children = join(",", $children);
1139
1140 $cat_qpart = "cat_id IN ($children)";
f9fca8cb
AD
1141 } else {
1142 $cat_qpart = "cat_id IS NULL";
1143 }
8d505d78 1144
a42c55f0 1145 db_query("UPDATE ttrss_user_entries
c8b693cf
AD
1146 SET unread = false, last_read = NOW() WHERE ref_id IN
1147 (SELECT id FROM
1148 (SELECT id FROM ttrss_entries, ttrss_user_entries WHERE ref_id = id
1149 AND owner_uid = $owner_uid AND unread = true AND feed_id IN
1150 (SELECT id FROM ttrss_feeds WHERE $cat_qpart) AND $date_qpart) as tmp)");
23aa0d16 1151
f9fca8cb 1152 } else if ($feed == -2) {
23aa0d16 1153
a42c55f0 1154 db_query("UPDATE ttrss_user_entries
8d505d78 1155 SET unread = false,last_read = NOW() WHERE (SELECT COUNT(*)
15d8bd7d
AD
1156 FROM ttrss_user_labels2, ttrss_entries WHERE article_id = ref_id AND id = ref_id AND $date_qpart) > 0
1157 AND unread = true AND owner_uid = $owner_uid");
23aa0d16
AD
1158 }
1159
1160 } else if ($feed > 0) {
1161
a42c55f0 1162 db_query("UPDATE ttrss_user_entries
c8b693cf
AD
1163 SET unread = false, last_read = NOW() WHERE ref_id IN
1164 (SELECT id FROM
1165 (SELECT id FROM ttrss_entries, ttrss_user_entries WHERE ref_id = id
1166 AND owner_uid = $owner_uid AND unread = true AND feed_id = $feed AND $date_qpart) as tmp)");
8d505d78 1167
f822a8e5 1168 } else if ($feed < 0 && $feed > LABEL_BASE_INDEX) { // special, like starred
23aa0d16
AD
1169
1170 if ($feed == -1) {
a42c55f0 1171 db_query("UPDATE ttrss_user_entries
c8b693cf
AD
1172 SET unread = false, last_read = NOW() WHERE ref_id IN
1173 (SELECT id FROM
1174 (SELECT id FROM ttrss_entries, ttrss_user_entries WHERE ref_id = id
1175 AND owner_uid = $owner_uid AND unread = true AND marked = true AND $date_qpart) as tmp)");
23aa0d16 1176 }
e4f4b46f
AD
1177
1178 if ($feed == -2) {
a42c55f0 1179 db_query("UPDATE ttrss_user_entries
c8b693cf
AD
1180 SET unread = false, last_read = NOW() WHERE ref_id IN
1181 (SELECT id FROM
1182 (SELECT id FROM ttrss_entries, ttrss_user_entries WHERE ref_id = id
1183 AND owner_uid = $owner_uid AND unread = true AND published = true AND $date_qpart) as tmp)");
e4f4b46f
AD
1184 }
1185
2d24f032
AD
1186 if ($feed == -3) {
1187
a42c55f0 1188 $intl = get_pref("FRESH_ARTICLE_MAX_AGE");
c1d7e6c3 1189
2d24f032 1190 if (DB_TYPE == "pgsql") {
cfd34086 1191 $match_part = "date_entered > NOW() - INTERVAL '$intl hour' ";
2d24f032 1192 } else {
cfd34086 1193 $match_part = "date_entered > DATE_SUB(NOW(),
c1d7e6c3 1194 INTERVAL $intl HOUR) ";
2d24f032
AD
1195 }
1196
a42c55f0 1197 db_query("UPDATE ttrss_user_entries
c8b693cf
AD
1198 SET unread = false, last_read = NOW() WHERE ref_id IN
1199 (SELECT id FROM
1200 (SELECT id FROM ttrss_entries, ttrss_user_entries WHERE ref_id = id
cfd34086 1201 AND owner_uid = $owner_uid AND unread = true AND $date_qpart AND $match_part) as tmp)");
2d24f032
AD
1202 }
1203
3584cb11 1204 if ($feed == -4) {
a42c55f0 1205 db_query("UPDATE ttrss_user_entries
c8b693cf
AD
1206 SET unread = false, last_read = NOW() WHERE ref_id IN
1207 (SELECT id FROM
1208 (SELECT id FROM ttrss_entries, ttrss_user_entries WHERE ref_id = id
1209 AND owner_uid = $owner_uid AND unread = true AND $date_qpart) as tmp)");
3584cb11
AD
1210 }
1211
f822a8e5 1212 } else if ($feed < LABEL_BASE_INDEX) { // label
23aa0d16 1213
f822a8e5 1214 $label_id = feed_to_label_id($feed);
23aa0d16 1215
a42c55f0 1216 db_query("UPDATE ttrss_user_entries
c8b693cf
AD
1217 SET unread = false, last_read = NOW() WHERE ref_id IN
1218 (SELECT id FROM
1219 (SELECT ttrss_entries.id FROM ttrss_entries, ttrss_user_entries, ttrss_user_labels2 WHERE ref_id = id
1220 AND label_id = '$label_id' AND ref_id = article_id
1221 AND owner_uid = $owner_uid AND unread = true AND $date_qpart) as tmp)");
23aa0d16 1222
23aa0d16 1223 }
ad0056a8 1224
a42c55f0 1225 ccache_update($feed, $owner_uid, $cat_view);
ad0056a8 1226
23aa0d16 1227 } else { // tag
a42c55f0 1228 db_query("UPDATE ttrss_user_entries
c8b693cf
AD
1229 SET unread = false, last_read = NOW() WHERE ref_id IN
1230 (SELECT id FROM
1231 (SELECT ttrss_entries.id FROM ttrss_entries, ttrss_user_entries, ttrss_tags WHERE ref_id = ttrss_entries.id
1232 AND post_int_id = int_id AND tag_name = '$feed'
1233 AND ttrss_user_entries.owner_uid = $owner_uid AND unread = true AND $date_qpart) as tmp)");
23aa0d16 1234
23aa0d16
AD
1235 }
1236 }
1237
6322ac79
AD
1238 function getAllCounters() {
1239 $data = getGlobalCounters();
8d505d78 1240
6322ac79
AD
1241 $data = array_merge($data, getVirtCounters());
1242 $data = array_merge($data, getLabelCounters());
6f7798b6 1243 $data = array_merge($data, getFeedCounters());
6322ac79 1244 $data = array_merge($data, getCategoryCounters());
6a7817c1
AD
1245
1246 return $data;
8d505d78 1247 }
a9cb1f83 1248
a42c55f0 1249 function getCategoryTitle($cat_id) {
79178062
AD
1250
1251 if ($cat_id == -1) {
1252 return __("Special");
1253 } else if ($cat_id == -2) {
1254 return __("Labels");
1255 } else {
1256
a42c55f0 1257 $result = db_query("SELECT title FROM ttrss_feed_categories WHERE
79178062
AD
1258 id = '$cat_id'");
1259
1260 if (db_num_rows($result) == 1) {
1261 return db_fetch_result($result, 0, "title");
1262 } else {
f99759da 1263 return __("Uncategorized");
79178062
AD
1264 }
1265 }
1266 }
1267
1268
6322ac79 1269 function getCategoryCounters() {
6a7817c1 1270 $ret_arr = array();
bba7c4bf 1271
6a7817c1 1272 /* Labels category */
bba7c4bf 1273
8acc449c 1274 $cv = array("id" => -2, "kind" => "cat",
a42c55f0 1275 "counter" => getCategoryUnread(-2));
bba7c4bf 1276
6a7817c1 1277 array_push($ret_arr, $cv);
bba7c4bf 1278
a42c55f0 1279 $result = db_query("SELECT id AS cat_id, value AS unread,
2c5f231e
AD
1280 (SELECT COUNT(id) FROM ttrss_feed_categories AS c2
1281 WHERE c2.parent_cat = ttrss_feed_categories.id) AS num_children
8d505d78
AD
1282 FROM ttrss_feed_categories, ttrss_cat_counters_cache
1283 WHERE ttrss_cat_counters_cache.feed_id = id AND
fc9de939 1284 ttrss_cat_counters_cache.owner_uid = ttrss_feed_categories.owner_uid AND
31375163 1285 ttrss_feed_categories.owner_uid = " . $_SESSION["uid"]);
a9cb1f83
AD
1286
1287 while ($line = db_fetch_assoc($result)) {
22fdebff 1288 $line["cat_id"] = (int) $line["cat_id"];
8a4c759e 1289
2c5f231e 1290 if ($line["num_children"] > 0) {
a42c55f0 1291 $child_counter = getCategoryChildrenUnread($line["cat_id"], $_SESSION["uid"]);
2c5f231e
AD
1292 } else {
1293 $child_counter = 0;
1294 }
1295
8acc449c 1296 $cv = array("id" => $line["cat_id"], "kind" => "cat",
0ef32f48 1297 "counter" => $line["unread"] + $child_counter);
6a7817c1
AD
1298
1299 array_push($ret_arr, $cv);
a9cb1f83 1300 }
d232a40f
AD
1301
1302 /* Special case: NULL category doesn't actually exist in the DB */
1303
9798b2b4 1304 $cv = array("id" => 0, "kind" => "cat",
a42c55f0 1305 "counter" => (int) ccache_find(0, $_SESSION["uid"], true));
d232a40f 1306
6a7817c1
AD
1307 array_push($ret_arr, $cv);
1308
1309 return $ret_arr;
a9cb1f83
AD
1310 }
1311
2c5f231e 1312 // only accepts real cats (>= 0)
a42c55f0 1313 function getCategoryChildrenUnread($cat, $owner_uid = false) {
2c5f231e
AD
1314 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
1315
a42c55f0 1316 $result = db_query("SELECT id FROM ttrss_feed_categories WHERE parent_cat = '$cat'
2c5f231e
AD
1317 AND owner_uid = $owner_uid");
1318
1319 $unread = 0;
1320
1321 while ($line = db_fetch_assoc($result)) {
a42c55f0
AD
1322 $unread += getCategoryUnread($line["id"], $owner_uid);
1323 $unread += getCategoryChildrenUnread($line["id"], $owner_uid);
2c5f231e
AD
1324 }
1325
1326 return $unread;
1327 }
1328
a42c55f0 1329 function getCategoryUnread($cat, $owner_uid = false) {
b6d486a3
AD
1330
1331 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
f295c368 1332
bba7c4bf 1333 if ($cat >= 0) {
18664970 1334
bba7c4bf
AD
1335 if ($cat != 0) {
1336 $cat_query = "cat_id = '$cat'";
1337 } else {
1338 $cat_query = "cat_id IS NULL";
1339 }
14073c0a 1340
a42c55f0 1341 $result = db_query("SELECT id FROM ttrss_feeds WHERE $cat_query
b6d486a3 1342 AND owner_uid = " . $owner_uid);
8d505d78 1343
bba7c4bf
AD
1344 $cat_feeds = array();
1345 while ($line = db_fetch_assoc($result)) {
1346 array_push($cat_feeds, "feed_id = " . $line["id"]);
1347 }
8d505d78 1348
bba7c4bf 1349 if (count($cat_feeds) == 0) return 0;
8d505d78 1350
bba7c4bf 1351 $match_part = implode(" OR ", $cat_feeds);
8d505d78 1352
a42c55f0 1353 $result = db_query("SELECT COUNT(int_id) AS unread
687bb90d
AD
1354 FROM ttrss_user_entries
1355 WHERE unread = true AND ($match_part)
1356 AND owner_uid = " . $owner_uid);
8d505d78 1357
bba7c4bf 1358 $unread = 0;
8d505d78 1359
bba7c4bf
AD
1360 # this needs to be rewritten
1361 while ($line = db_fetch_assoc($result)) {
1362 $unread += $line["unread"];
1363 }
8d505d78 1364
bba7c4bf
AD
1365 return $unread;
1366 } else if ($cat == -1) {
6f7798b6 1367 return getFeedUnread(-1) + getFeedUnread(-2) + getFeedUnread(-3) + getFeedUnread(0);
bba7c4bf 1368 } else if ($cat == -2) {
f295c368 1369
a42c55f0 1370 $result = db_query("
8d505d78 1371 SELECT COUNT(unread) AS unread FROM
687bb90d
AD
1372 ttrss_user_entries, ttrss_user_labels2
1373 WHERE article_id = ref_id AND unread = true
b2531a28 1374 AND ttrss_user_entries.owner_uid = '$owner_uid'");
ceb30ba4 1375
b2531a28 1376 $unread = db_fetch_result($result, 0, "unread");
f295c368 1377
b2531a28 1378 return $unread;
f295c368 1379
8d505d78 1380 }
f295c368
AD
1381 }
1382
a42c55f0
AD
1383 function getFeedUnread($feed, $is_cat = false) {
1384 return getFeedArticles($feed, $is_cat, true, $_SESSION["uid"]);
bdb7369b
AD
1385 }
1386
a42c55f0 1387 function getLabelUnread($label_id, $owner_uid = false) {
ceb30ba4
AD
1388 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
1389
a42c55f0 1390 $result = db_query("SELECT COUNT(ref_id) AS unread FROM ttrss_user_entries, ttrss_user_labels2
f360b028 1391 WHERE owner_uid = '$owner_uid' AND unread = true AND label_id = '$label_id' AND article_id = ref_id");
ceb30ba4
AD
1392
1393 if (db_num_rows($result) != 0) {
1394 return db_fetch_result($result, 0, "unread");
1395 } else {
1396 return 0;
1397 }
1398 }
1399
a42c55f0 1400 function getFeedArticles($feed, $is_cat = false, $unread_only = false,
2627f2d0
AD
1401 $owner_uid = false) {
1402
22fdebff 1403 $n_feed = (int) $feed;
687bb90d 1404 $need_entries = false;
f295c368 1405
2627f2d0
AD
1406 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
1407
bdb7369b
AD
1408 if ($unread_only) {
1409 $unread_qpart = "unread = true";
1410 } else {
1411 $unread_qpart = "true";
1412 }
1413
f295c368 1414 if ($is_cat) {
a42c55f0 1415 return getCategoryUnread($n_feed, $owner_uid);
5417fbd7
AD
1416 } else if ($n_feed == -6) {
1417 return 0;
1418 } else if ($feed != "0" && $n_feed == 0) {
326469fc 1419
a42c55f0 1420 $feed = db_escape_string($feed);
c5701e70 1421
a42c55f0 1422 $result = db_query("SELECT SUM((SELECT COUNT(int_id)
8d505d78 1423 FROM ttrss_user_entries,ttrss_entries WHERE int_id = post_int_id
687bb90d 1424 AND ref_id = id AND $unread_qpart)) AS count FROM ttrss_tags
326469fc
AD
1425 WHERE owner_uid = $owner_uid AND tag_name = '$feed'");
1426 return db_fetch_result($result, 0, "count");
1427
f295c368 1428 } else if ($n_feed == -1) {
a9cb1f83 1429 $match_part = "marked = true";
e4f4b46f
AD
1430 } else if ($n_feed == -2) {
1431 $match_part = "published = true";
2d24f032 1432 } else if ($n_feed == -3) {
cd2cc43d 1433 $match_part = "unread = true AND score >= 0";
2d24f032 1434
a42c55f0 1435 $intl = get_pref("FRESH_ARTICLE_MAX_AGE", $owner_uid);
c1d7e6c3 1436
2d24f032 1437 if (DB_TYPE == "pgsql") {
924a89eb 1438 $match_part .= " AND date_entered > NOW() - INTERVAL '$intl hour' ";
2d24f032 1439 } else {
924a89eb 1440 $match_part .= " AND date_entered > DATE_SUB(NOW(), INTERVAL $intl HOUR) ";
2d24f032 1441 }
687bb90d
AD
1442
1443 $need_entries = true;
1444
b2531a28
AD
1445 } else if ($n_feed == -4) {
1446 $match_part = "true";
e04c18a2 1447 } else if ($n_feed >= 0) {
831ff047 1448
6e63a7c3
AD
1449 if ($n_feed != 0) {
1450 $match_part = "feed_id = '$n_feed'";
831ff047 1451 } else {
6e63a7c3 1452 $match_part = "feed_id IS NULL";
831ff047 1453 }
6e63a7c3 1454
f822a8e5 1455 } else if ($feed < LABEL_BASE_INDEX) {
318260cc 1456
f822a8e5 1457 $label_id = feed_to_label_id($feed);
a9cb1f83 1458
a42c55f0 1459 return getLabelUnread($label_id, $owner_uid);
a9cb1f83 1460
a9cb1f83
AD
1461 }
1462
1463 if ($match_part) {
e04c18a2 1464
687bb90d 1465 if ($need_entries) {
e04c18a2 1466 $from_qpart = "ttrss_user_entries,ttrss_entries";
687bb90d
AD
1467 $from_where = "ttrss_entries.id = ttrss_user_entries.ref_id AND";
1468 } else {
1469 $from_qpart = "ttrss_user_entries";
60168a8d 1470 $from_where = "";
e04c18a2
AD
1471 }
1472
8d505d78 1473 $query = "SELECT count(int_id) AS unread
e04c18a2 1474 FROM $from_qpart WHERE
687bb90d
AD
1475 $unread_qpart AND $from_where ($match_part) AND ttrss_user_entries.owner_uid = $owner_uid";
1476
1477 //echo "[$feed/$query]\n";
dbfc4365 1478
a42c55f0 1479 $result = db_query($query);
8d505d78 1480
a9cb1f83 1481 } else {
8d505d78 1482
a42c55f0 1483 $result = db_query("SELECT COUNT(post_int_id) AS unread
8d505d78
AD
1484 FROM ttrss_tags,ttrss_user_entries,ttrss_entries
1485 WHERE tag_name = '$feed' AND post_int_id = int_id AND ref_id = ttrss_entries.id
687bb90d 1486 AND $unread_qpart AND ttrss_tags.owner_uid = " . $owner_uid);
a9cb1f83 1487 }
8d505d78 1488
a9cb1f83 1489 $unread = db_fetch_result($result, 0, "unread");
cfb02131 1490
a9cb1f83
AD
1491 return $unread;
1492 }
1493
a42c55f0 1494 function getGlobalUnread($user_id = false) {
f3acc32e
AD
1495
1496 if (!$user_id) {
1497 $user_id = $_SESSION["uid"];
1498 }
1499
a42c55f0 1500 $result = db_query("SELECT SUM(value) AS c_id FROM ttrss_counters_cache
8a4c759e
AD
1501 WHERE owner_uid = '$user_id' AND feed_id > 0");
1502
8d505d78 1503 $c_id = db_fetch_result($result, 0, "c_id");
8a4c759e 1504
a9cb1f83
AD
1505 return $c_id;
1506 }
1507
a42c55f0 1508 function getGlobalCounters($global_unread = -1) {
6a7817c1
AD
1509 $ret_arr = array();
1510
8d505d78 1511 if ($global_unread == -1) {
6322ac79 1512 $global_unread = getGlobalUnread();
a9cb1f83 1513 }
6a7817c1 1514
8d505d78 1515 $cv = array("id" => "global-unread",
12e6de72 1516 "counter" => (int) $global_unread);
6a7817c1
AD
1517
1518 array_push($ret_arr, $cv);
7bf7e4d3 1519
a42c55f0 1520 $result = db_query("SELECT COUNT(id) AS fn FROM
7bf7e4d3
AD
1521 ttrss_feeds WHERE owner_uid = " . $_SESSION["uid"]);
1522
1523 $subscribed_feeds = db_fetch_result($result, 0, "fn");
1524
8d505d78 1525 $cv = array("id" => "subscribed-feeds",
12e6de72 1526 "counter" => (int) $subscribed_feeds);
7bf7e4d3 1527
6a7817c1
AD
1528 array_push($ret_arr, $cv);
1529
1530 return $ret_arr;
a9cb1f83
AD
1531 }
1532
6322ac79 1533 function getVirtCounters() {
a9cb1f83 1534
ef393de7 1535 $ret_arr = array();
bdb7369b 1536
e04c18a2 1537 for ($i = 0; $i >= -4; $i--) {
bdb7369b 1538
a42c55f0 1539 $count = getFeedUnread($i);
6a7817c1 1540
c594eca0
AD
1541 if ($i == 0 || $i == -1 || $i == -2)
1542 $auxctr = getFeedArticles($i, false);
1543 else
1544 $auxctr = 0;
1545
6a7817c1 1546 $cv = array("id" => $i,
c594eca0
AD
1547 "counter" => (int) $count,
1548 "auxcounter" => $auxctr);
8d505d78 1549
a42c55f0
AD
1550// if (get_pref('EXTENDED_FEEDLIST'))
1551// $cv["xmsg"] = getFeedArticles($i)." ".__("total");
bdb7369b 1552
6a7817c1 1553 array_push($ret_arr, $cv);
8d505d78 1554 }
0a6e5382 1555
1ffe3391 1556 $feeds = PluginHost::getInstance()->get_feeds(-1);
a413f53e 1557
1ffe3391
AD
1558 if (is_array($feeds)) {
1559 foreach ($feeds as $feed) {
1560 $cv = array("id" => PluginHost::pfeed_to_feed_id($feed['id']),
1561 "counter" => $feed['sender']->get_unread($feed['id']));
a6a61a8c
AD
1562
1563 if (method_exists($feed['sender'], 'get_total'))
1564 $cv["auxcounter"] = $feed['sender']->get_total($feed['id']);
1565
1566 array_push($ret_arr, $cv);
a413f53e 1567 }
a413f53e
AD
1568 }
1569
0a6e5382
AD
1570 return $ret_arr;
1571 }
1572
a42c55f0 1573 function getLabelCounters($descriptions = false) {
6a7817c1
AD
1574
1575 $ret_arr = array();
0a6e5382 1576
3809b278 1577 $owner_uid = $_SESSION["uid"];
bdb7369b 1578
4d8f4c59 1579 $result = db_query("SELECT id,caption,SUM(CASE WHEN u1.unread = true THEN 1 ELSE 0 END) AS unread, COUNT(u1.unread) AS total
45942238
AD
1580 FROM ttrss_labels2 LEFT JOIN ttrss_user_labels2 ON
1581 (ttrss_labels2.id = label_id)
4d8f4c59 1582 LEFT JOIN ttrss_user_entries AS u1 ON u1.ref_id = article_id
123a7643
AD
1583 WHERE ttrss_labels2.owner_uid = $owner_uid GROUP BY ttrss_labels2.id,
1584 ttrss_labels2.caption");
8d505d78 1585
3809b278 1586 while ($line = db_fetch_assoc($result)) {
2d24f032 1587
f822a8e5 1588 $id = label_to_feed_id($line["id"]);
e4f4b46f 1589
6a7817c1 1590 $cv = array("id" => $id,
d7b5a9e7
AD
1591 "counter" => (int) $line["unread"],
1592 "auxcounter" => (int) $line["total"]);
11232703
AD
1593
1594 if ($descriptions)
d7b5a9e7 1595 $cv["description"] = $line["caption"];
ef393de7 1596
6a7817c1 1597 array_push($ret_arr, $cv);
3809b278 1598 }
8d505d78 1599
ef393de7 1600 return $ret_arr;
a9cb1f83
AD
1601 }
1602
a42c55f0 1603 function getFeedCounters($active_feed = false) {
a9cb1f83 1604
6a7817c1
AD
1605 $ret_arr = array();
1606
41759103 1607 $query = "SELECT ttrss_feeds.id,
8a4c759e 1608 ttrss_feeds.title,
8d505d78 1609 ".SUBSTRING_FOR_DATE."(ttrss_feeds.last_updated,1,19) AS last_updated,
de0a2122
AD
1610 last_error, value AS count
1611 FROM ttrss_feeds, ttrss_counters_cache
8d505d78 1612 WHERE ttrss_feeds.owner_uid = ".$_SESSION["uid"]."
fc9de939 1613 AND ttrss_counters_cache.owner_uid = ttrss_feeds.owner_uid
55e01d7e 1614 AND ttrss_counters_cache.feed_id = id";
a9cb1f83 1615
a42c55f0 1616 $result = db_query($query);
a9cb1f83
AD
1617 $fctrs_modified = false;
1618
1619 while ($line = db_fetch_assoc($result)) {
8d505d78 1620
a9cb1f83 1621 $id = $line["id"];
de0a2122 1622 $count = $line["count"];
a9cb1f83 1623 $last_error = htmlspecialchars($line["last_error"]);
fb1fb4ab 1624
a42c55f0 1625 $last_updated = make_local_datetime($line['last_updated'], false);
fb1fb4ab 1626
7defa089 1627 $has_img = feed_has_icon($id);
a9cb1f83 1628
428b704d
AD
1629 if (date('Y') - date('Y', strtotime($line['last_updated'])) > 2)
1630 $last_updated = '';
1631
6a7817c1 1632 $cv = array("id" => $id,
21884958 1633 "updated" => $last_updated,
12e6de72 1634 "counter" => (int) $count,
6a7817c1 1635 "has_img" => (int) $has_img);
a9cb1f83 1636
6a7817c1
AD
1637 if ($last_error)
1638 $cv["error"] = $last_error;
4ffa126e 1639
a42c55f0
AD
1640// if (get_pref('EXTENDED_FEEDLIST'))
1641// $cv["xmsg"] = getFeedArticles($id)." ".__("total");
bdb7369b 1642
6a7817c1 1643 if ($active_feed && $id == $active_feed)
fbc95c5b 1644 $cv["title"] = truncate_string($line["title"], 30);
6a7817c1
AD
1645
1646 array_push($ret_arr, $cv);
a9cb1f83 1647
a9cb1f83 1648 }
6a7817c1
AD
1649
1650 return $ret_arr;
a9cb1f83
AD
1651 }
1652
6322ac79 1653 function get_pgsql_version() {
a42c55f0 1654 $result = db_query("SELECT version() AS version");
9949bd15 1655 $version = explode(" ", db_fetch_result($result, 0, "version"));
6e7f8d26
AD
1656 return $version[1];
1657 }
1658
2b8290cd 1659 /**
23d2471c
AD
1660 * @return array (code => Status code, message => error message if available)
1661 *
2b8290cd
CW
1662 * 0 - OK, Feed already exists
1663 * 1 - OK, Feed added
1664 * 2 - Invalid URL
9a8ce956
CW
1665 * 3 - URL content is HTML, no feeds available
1666 * 4 - URL content is HTML which contains multiple feeds.
1667 * Here you should call extractfeedurls in rpc-backend
1668 * to get all possible feeds.
5414ad4c 1669 * 5 - Couldn't download the URL content.
ebec81a6 1670 * 6 - Content is an invalid XML.
2b8290cd 1671 */
a42c55f0 1672 function subscribe_to_feed($url, $cat_id = 0,
efc6553d 1673 $auth_login = '', $auth_pass = '') {
bb0f29a4 1674
23d2471c
AD
1675 global $fetch_last_error;
1676
2c08214a
AD
1677 require_once "include/rssfuncs.php";
1678
f0266f51 1679 $url = fix_url($url);
ec39a02c 1680
23d2471c 1681 if (!$url || !validate_feed_url($url)) return array("code" => 2);
a5819bb3 1682
759e5132
AD
1683 $contents = @fetch_file_contents($url, false, $auth_login, $auth_pass);
1684
1685 if (!$contents) {
304aadb9 1686 return array("code" => 5, "message" => $fetch_last_error);
759e5132
AD
1687 }
1688
1689 if (is_html($contents)) {
1690 $feedUrls = get_feeds_from_html($url, $contents);
304aadb9 1691
304aadb9
AD
1692 if (count($feedUrls) == 0) {
1693 return array("code" => 3);
1694 } else if (count($feedUrls) > 1) {
759e5132 1695 return array("code" => 4, "feeds" => $feedUrls);
f6d8345b 1696 }
304aadb9
AD
1697 //use feed url as new URL
1698 $url = key($feedUrls);
1699 }
f6d8345b 1700
9ce600c8 1701 /* libxml_use_internal_errors(true);
ebec81a6 1702 $doc = new DOMDocument();
9ce600c8 1703 $doc->loadXML($contents);
ebec81a6
AD
1704 $error = libxml_get_last_error();
1705 libxml_clear_errors();
1706
1707 if ($error) {
1708 $error_message = format_libxml_error($error);
1709
1710 return array("code" => 6, "message" => $error_message);
9ce600c8 1711 } */
ebec81a6 1712
956c7629
AD
1713 if ($cat_id == "0" || !$cat_id) {
1714 $cat_qpart = "NULL";
1715 } else {
1716 $cat_qpart = "'$cat_id'";
1717 }
8d505d78 1718
6322ac79 1719 $result = db_query(
8d505d78 1720 "SELECT id FROM ttrss_feeds
a5819bb3 1721 WHERE feed_url = '$url' AND owner_uid = ".$_SESSION["uid"]);
8d505d78 1722
044cff2d
AD
1723 if (strlen(FEED_CRYPT_KEY) > 0) {
1724 require_once "crypt.php";
1725 $auth_pass = substr(encrypt_string($auth_pass), 0, 250);
1726 $auth_pass_encrypted = 'true';
1727 } else {
1728 $auth_pass_encrypted = 'false';
1729 }
1730
a42c55f0 1731 $auth_pass = db_escape_string($auth_pass);
41694a95 1732
956c7629 1733 if (db_num_rows($result) == 0) {
6322ac79 1734 $result = db_query(
8d505d78 1735 "INSERT INTO ttrss_feeds
044cff2d 1736 (owner_uid,feed_url,title,cat_id, auth_login,auth_pass,update_method,auth_pass_encrypted)
8d505d78 1737 VALUES ('".$_SESSION["uid"]."', '$url',
044cff2d 1738 '[Unknown]', $cat_qpart, '$auth_login', '$auth_pass', 0, $auth_pass_encrypted)");
8d505d78 1739
6322ac79 1740 $result = db_query(
8d505d78 1741 "SELECT id FROM ttrss_feeds WHERE feed_url = '$url'
f27de515 1742 AND owner_uid = " . $_SESSION["uid"]);
8d505d78 1743
956c7629 1744 $feed_id = db_fetch_result($result, 0, "id");
8d505d78 1745
956c7629 1746 if ($feed_id) {
fd687300 1747 update_rss_feed($feed_id, true);
956c7629
AD
1748 }
1749
23d2471c 1750 return array("code" => 1);
956c7629 1751 } else {
23d2471c 1752 return array("code" => 0);
956c7629
AD
1753 }
1754 }
1755
a42c55f0 1756 function print_feed_select($id, $default_id = "",
4c9d0490
AD
1757 $attributes = "", $include_all_feeds = true,
1758 $root_id = false, $nest_level = 0) {
1759
1760 if (!$root_id) {
1761 print "<select id=\"$id\" name=\"$id\" $attributes>";
1762 if ($include_all_feeds) {
1763 $is_selected = ("0" == $default_id) ? "selected=\"1\"" : "";
1764 print "<option $is_selected value=\"0\">".__('All feeds')."</option>";
1765 }
673d54ca 1766 }
8d505d78 1767
a42c55f0 1768 if (get_pref('ENABLE_FEED_CATS')) {
673d54ca 1769
4c9d0490
AD
1770 if ($root_id)
1771 $parent_qpart = "parent_cat = '$root_id'";
1772 else
1773 $parent_qpart = "parent_cat IS NULL";
673d54ca 1774
a42c55f0 1775 $result = db_query("SELECT id,title,
4c9d0490
AD
1776 (SELECT COUNT(id) FROM ttrss_feed_categories AS c2 WHERE
1777 c2.parent_cat = ttrss_feed_categories.id) AS num_children
1778 FROM ttrss_feed_categories
1779 WHERE owner_uid = ".$_SESSION["uid"]." AND $parent_qpart ORDER BY title");
1780
1781 while ($line = db_fetch_assoc($result)) {
1782
1783 for ($i = 0; $i < $nest_level; $i++)
1784 $line["title"] = " - " . $line["title"];
1785
1786 $is_selected = ("CAT:".$line["id"] == $default_id) ? "selected=\"1\"" : "";
1787
1788 printf("<option $is_selected value='CAT:%d'>%s</option>",
1789 $line["id"], htmlspecialchars($line["title"]));
1790
1791 if ($line["num_children"] > 0)
a42c55f0 1792 print_feed_select($id, $default_id, $attributes,
4c9d0490
AD
1793 $include_all_feeds, $line["id"], $nest_level+1);
1794
a42c55f0 1795 $feed_result = db_query("SELECT id,title FROM ttrss_feeds
4c9d0490
AD
1796 WHERE cat_id = '".$line["id"]."' AND owner_uid = ".$_SESSION["uid"] . " ORDER BY title");
1797
1798 while ($fline = db_fetch_assoc($feed_result)) {
1799 $is_selected = ($fline["id"] == $default_id) ? "selected=\"1\"" : "";
1800
1801 $fline["title"] = " + " . $fline["title"];
1802
1803 for ($i = 0; $i < $nest_level; $i++)
1804 $fline["title"] = " - " . $fline["title"];
1805
1806 printf("<option $is_selected value='%d'>%s</option>",
1807 $fline["id"], htmlspecialchars($fline["title"]));
1808 }
673d54ca 1809 }
b1710666 1810
4c9d0490 1811 if (!$root_id) {
6f7798b6
RL
1812 $default_is_cat = ($default_id == "CAT:0");
1813 $is_selected = $default_is_cat ? "selected=\"1\"" : "";
4c9d0490
AD
1814
1815 printf("<option $is_selected value='CAT:0'>%s</option>",
1816 __("Uncategorized"));
1817
a42c55f0 1818 $feed_result = db_query("SELECT id,title FROM ttrss_feeds
4c9d0490
AD
1819 WHERE cat_id IS NULL AND owner_uid = ".$_SESSION["uid"] . " ORDER BY title");
1820
1821 while ($fline = db_fetch_assoc($feed_result)) {
1822 $is_selected = ($fline["id"] == $default_id && !$default_is_cat) ? "selected=\"1\"" : "";
1823
1824 $fline["title"] = " + " . $fline["title"];
1825
1826 for ($i = 0; $i < $nest_level; $i++)
1827 $fline["title"] = " - " . $fline["title"];
1828
1829 printf("<option $is_selected value='%d'>%s</option>",
1830 $fline["id"], htmlspecialchars($fline["title"]));
1831 }
1832 }
b1710666 1833
4c9d0490 1834 } else {
a42c55f0 1835 $result = db_query("SELECT id,title FROM ttrss_feeds
4c9d0490
AD
1836 WHERE owner_uid = ".$_SESSION["uid"]." ORDER BY title");
1837
1838 while ($line = db_fetch_assoc($result)) {
1839
1840 $is_selected = ($line["id"] == $default_id) ? "selected=\"1\"" : "";
1841
1842 printf("<option $is_selected value='%d'>%s</option>",
1843 $line["id"], htmlspecialchars($line["title"]));
1844 }
673d54ca 1845 }
8d505d78 1846
4c9d0490
AD
1847 if (!$root_id) {
1848 print "</select>";
1849 }
673d54ca
AD
1850 }
1851
a42c55f0 1852 function print_feed_cat_select($id, $default_id,
fbf85cf6 1853 $attributes, $include_all_cats = true, $root_id = false, $nest_level = 0) {
8d505d78 1854
fbf85cf6
AD
1855 if (!$root_id) {
1856 print "<select id=\"$id\" name=\"$id\" default=\"$default_id\" onchange=\"catSelectOnChange(this)\" $attributes>";
1857 }
673d54ca 1858
fbf85cf6
AD
1859 if ($root_id)
1860 $parent_qpart = "parent_cat = '$root_id'";
1861 else
1862 $parent_qpart = "parent_cat IS NULL";
673d54ca 1863
a42c55f0 1864 $result = db_query("SELECT id,title,
fbf85cf6
AD
1865 (SELECT COUNT(id) FROM ttrss_feed_categories AS c2 WHERE
1866 c2.parent_cat = ttrss_feed_categories.id) AS num_children
1867 FROM ttrss_feed_categories
1868 WHERE owner_uid = ".$_SESSION["uid"]." AND $parent_qpart ORDER BY title");
673d54ca 1869
fbf85cf6
AD
1870 while ($line = db_fetch_assoc($result)) {
1871 if ($line["id"] == $default_id) {
1872 $is_selected = "selected=\"1\"";
1873 } else {
1874 $is_selected = "";
1875 }
673d54ca 1876
fbf85cf6
AD
1877 for ($i = 0; $i < $nest_level; $i++)
1878 $line["title"] = " - " . $line["title"];
c00907f2 1879
fbf85cf6
AD
1880 if ($line["title"])
1881 printf("<option $is_selected value='%d'>%s</option>",
1882 $line["id"], htmlspecialchars($line["title"]));
673d54ca 1883
fbf85cf6 1884 if ($line["num_children"] > 0)
a42c55f0 1885 print_feed_cat_select($id, $default_id, $attributes,
fbf85cf6
AD
1886 $include_all_cats, $line["id"], $nest_level+1);
1887 }
5c7c7da9 1888
fbf85cf6
AD
1889 if (!$root_id) {
1890 if ($include_all_cats) {
1891 if (db_num_rows($result) > 0) {
1892 print "<option disabled=\"1\">--------</option>";
1893 }
7e18f8e7
AD
1894
1895 if ($default_id == 0) {
1896 $is_selected = "selected=\"1\"";
1897 } else {
1898 $is_selected = "";
1899 }
1900
1901 print "<option $is_selected value=\"0\">".__('Uncategorized')."</option>";
fbf85cf6
AD
1902 }
1903 print "</select>";
1904 }
1905 }
8d505d78 1906
14f69488
AD
1907 function checkbox_to_sql_bool($val) {
1908 return ($val == "on") ? "true" : "false";
1909 }
86b682ce 1910
a42c55f0 1911 function getFeedCatTitle($id) {
86b682ce 1912 if ($id == -1) {
d1db26aa 1913 return __("Special");
f822a8e5 1914 } else if ($id < LABEL_BASE_INDEX) {
d1db26aa 1915 return __("Labels");
86b682ce 1916 } else if ($id > 0) {
a42c55f0 1917 $result = db_query("SELECT ttrss_feed_categories.title
86b682ce
AD
1918 FROM ttrss_feeds, ttrss_feed_categories WHERE ttrss_feeds.id = '$id' AND
1919 cat_id = ttrss_feed_categories.id");
1920 if (db_num_rows($result) == 1) {
1921 return db_fetch_result($result, 0, "title");
1922 } else {
d1db26aa 1923 return __("Uncategorized");
86b682ce
AD
1924 }
1925 } else {
1926 return "getFeedCatTitle($id) failed";
1927 }
1928
1929 }
1930
9299102f 1931 function getFeedIcon($id) {
af88c48a 1932 switch ($id) {
4bee8b5f
AD
1933 case 0:
1934 return "images/archive.png";
1935 break;
af88c48a 1936 case -1:
2f20dd58 1937 return "images/star.png";
af88c48a
AD
1938 break;
1939 case -2:
2f20dd58 1940 return "images/feed.png";
af88c48a
AD
1941 break;
1942 case -3:
1943 return "images/fresh.png";
1944 break;
1945 case -4:
2f20dd58 1946 return "images/folder.png";
af88c48a 1947 break;
5417fbd7 1948 case -6:
2f20dd58 1949 return "images/time.png";
5417fbd7 1950 break;
af88c48a 1951 default:
f822a8e5 1952 if ($id < LABEL_BASE_INDEX) {
4bee8b5f
AD
1953 return "images/label.png";
1954 } else {
8d505d78 1955 if (file_exists(ICONS_DIR . "/$id.ico"))
e2eda979 1956 return ICONS_URL . "/$id.ico";
4bee8b5f 1957 }
af88c48a
AD
1958 break;
1959 }
89473cb5
AD
1960
1961 return false;
af88c48a
AD
1962 }
1963
a42c55f0 1964 function getFeedTitle($id, $cat = false) {
fd994f1a 1965 if ($cat) {
a42c55f0 1966 return getCategoryTitle($id);
fd994f1a 1967 } else if ($id == -1) {
d1db26aa 1968 return __("Starred articles");
945c243e
AD
1969 } else if ($id == -2) {
1970 return __("Published articles");
2d24f032
AD
1971 } else if ($id == -3) {
1972 return __("Fresh articles");
b2531a28
AD
1973 } else if ($id == -4) {
1974 return __("All articles");
80db1113 1975 } else if ($id === 0 || $id === "0") {
e04c18a2 1976 return __("Archived articles");
5417fbd7
AD
1977 } else if ($id == -6) {
1978 return __("Recently read");
f822a8e5
AD
1979 } else if ($id < LABEL_BASE_INDEX) {
1980 $label_id = feed_to_label_id($id);
a42c55f0 1981 $result = db_query("SELECT caption FROM ttrss_labels2 WHERE id = '$label_id'");
86b682ce 1982 if (db_num_rows($result) == 1) {
ceb30ba4 1983 return db_fetch_result($result, 0, "caption");
86b682ce
AD
1984 } else {
1985 return "Unknown label ($label_id)";
1986 }
1987
147f5632 1988 } else if (is_numeric($id) && $id > 0) {
a42c55f0 1989 $result = db_query("SELECT title FROM ttrss_feeds WHERE id = '$id'");
86b682ce
AD
1990 if (db_num_rows($result) == 1) {
1991 return db_fetch_result($result, 0, "title");
1992 } else {
1993 return "Unknown feed ($id)";
1994 }
1995 } else {
22fdebff 1996 return $id;
86b682ce 1997 }
86b682ce 1998 }
3dd46f19 1999
6322ac79 2000 function make_init_params() {
f1f3a642 2001 $params = array();
c9268ed5 2002
f1f3a642
AD
2003 foreach (array("ON_CATCHUP_SHOW_NEXT_FEED", "HIDE_READ_FEEDS",
2004 "ENABLE_FEED_CATS", "FEEDS_SORT_BY_UNREAD", "CONFIRM_FEED_CATCHUP",
f17cac6b 2005 "CDM_AUTO_CATCHUP", "FRESH_ARTICLE_MAX_AGE",
30b6ee8c 2006 "HIDE_READ_SHOWS_SPECIAL", "COMBINED_DISPLAY_MODE") as $param) {
40496720 2007
a42c55f0 2008 $params[strtolower($param)] = (int) get_pref($param);
f1f3a642 2009 }
40496720 2010
c4f7ba80
AD
2011 $params["icons_url"] = ICONS_URL;
2012 $params["cookie_lifetime"] = SESSION_COOKIE_LIFETIME;
a42c55f0
AD
2013 $params["default_view_mode"] = get_pref("_DEFAULT_VIEW_MODE");
2014 $params["default_view_limit"] = (int) get_pref("_DEFAULT_VIEW_LIMIT");
2015 $params["default_view_order_by"] = get_pref("_DEFAULT_VIEW_ORDER_BY");
c4f7ba80 2016 $params["bw_limit"] = (int) $_SESSION["bw_limit"];
88a41b64 2017 $params["label_base_index"] = (int) LABEL_BASE_INDEX;
59b223d7 2018
a42c55f0 2019 $result = db_query("SELECT MAX(id) AS mid, COUNT(*) AS nf FROM
9b7ecc0a
AD
2020 ttrss_feeds WHERE owner_uid = " . $_SESSION["uid"]);
2021
8cd576a1
AD
2022 $max_feed_id = db_fetch_result($result, 0, "mid");
2023 $num_feeds = db_fetch_result($result, 0, "nf");
9b7ecc0a 2024
8cd576a1 2025 $params["max_feed_id"] = (int) $max_feed_id;
c4f7ba80 2026 $params["num_feeds"] = (int) $num_feeds;
8cd576a1 2027
6322ac79 2028 $params["hotkeys"] = get_hotkeys_map();
9b7ecc0a 2029
8484ce22 2030 $params["csrf_token"] = $_SESSION["csrf_token"];
f03701fe 2031 $params["widescreen"] = (int) $_COOKIE["ttrss_widescreen"];
8484ce22 2032
6b1a4ecd 2033 $params['simple_update'] = defined('SIMPLE_UPDATE_MODE') && SIMPLE_UPDATE_MODE;
8b83bf5f 2034
d8221301 2035 return $params;
3ac2b520 2036 }
f54f515f 2037
6322ac79 2038 function get_hotkeys_info() {
b8cb4d08
AD
2039 $hotkeys = array(
2040 __("Navigation") => array(
2041 "next_feed" => __("Open next feed"),
2042 "prev_feed" => __("Open previous feed"),
2043 "next_article" => __("Open next article"),
2044 "prev_article" => __("Open previous article"),
c22580b5
AD
2045 "next_article_noscroll" => __("Open next article (don't scroll long articles)"),
2046 "prev_article_noscroll" => __("Open previous article (don't scroll long articles)"),
8b35d171
SC
2047 "next_article_noexpand" => __("Move to next article (don't expand or mark read)"),
2048 "prev_article_noexpand" => __("Move to previous article (don't expand or mark read)"),
b8cb4d08
AD
2049 "search_dialog" => __("Show search dialog")),
2050 __("Article") => array(
2051 "toggle_mark" => __("Toggle starred"),
2052 "toggle_publ" => __("Toggle published"),
2053 "toggle_unread" => __("Toggle unread"),
2054 "edit_tags" => __("Edit tags"),
2055 "dismiss_selected" => __("Dismiss selected"),
2056 "dismiss_read" => __("Dismiss read"),
2057 "open_in_new_window" => __("Open in new window"),
2058 "catchup_below" => __("Mark below as read"),
2059 "catchup_above" => __("Mark above as read"),
2060 "article_scroll_down" => __("Scroll down"),
2061 "article_scroll_up" => __("Scroll up"),
2062 "select_article_cursor" => __("Select article under cursor"),
1bcf8f45 2063 "email_article" => __("Email article"),
414191d4 2064 "close_article" => __("Close/collapse article"),
8b35d171 2065 "toggle_expand" => __("Toggle article expansion (combined mode)"),
2ccc7b8e
AD
2066 "toggle_widescreen" => __("Toggle widescreen mode"),
2067 "toggle_embed_original" => __("Toggle embed original")),
b8cb4d08
AD
2068 __("Article selection") => array(
2069 "select_all" => __("Select all articles"),
2070 "select_unread" => __("Select unread"),
2071 "select_marked" => __("Select starred"),
2072 "select_published" => __("Select published"),
2073 "select_invert" => __("Invert selection"),
2074 "select_none" => __("Deselect everything")),
2075 __("Feed") => array(
2076 "feed_refresh" => __("Refresh current feed"),
2077 "feed_unhide_read" => __("Un/hide read feeds"),
2078 "feed_subscribe" => __("Subscribe to feed"),
2079 "feed_edit" => __("Edit feed"),
2080 "feed_catchup" => __("Mark as read"),
2081 "feed_reverse" => __("Reverse headlines"),
43f775de 2082 "feed_debug_update" => __("Debug feed update"),
b8cb4d08 2083 "catchup_all" => __("Mark all feeds as read"),
4b27f0c0 2084 "cat_toggle_collapse" => __("Un/collapse current category"),
60b88b25
AD
2085 "toggle_combined_mode" => __("Toggle combined mode"),
2086 "toggle_cdm_expanded" => __("Toggle auto expand in combined mode")),
b8cb4d08
AD
2087 __("Go to") => array(
2088 "goto_all" => __("All articles"),
2089 "goto_fresh" => __("Fresh"),
2090 "goto_marked" => __("Starred"),
2091 "goto_published" => __("Published"),
2092 "goto_tagcloud" => __("Tag cloud"),
2093 "goto_prefs" => __("Preferences")),
2094 __("Other") => array(
2095 "create_label" => __("Create label"),
2096 "create_filter" => __("Create filter"),
2097 "collapse_sidebar" => __("Un/collapse sidebar"),
2098 "help_dialog" => __("Show help dialog"))
2099 );
2100
1ffe3391 2101 foreach (PluginHost::getInstance()->get_hooks(PluginHost::HOOK_HOTKEY_INFO) as $plugin) {
47854200
DA
2102 $hotkeys = $plugin->hook_hotkey_info($hotkeys);
2103 }
2104
b8cb4d08
AD
2105 return $hotkeys;
2106 }
2107
6322ac79 2108 function get_hotkeys_map() {
a83b58f1 2109 $hotkeys = array(
e218c5f5
AD
2110// "navigation" => array(
2111 "k" => "next_feed",
2112 "j" => "prev_feed",
2113 "n" => "next_article",
2114 "p" => "prev_article",
e5e2cf3b
AD
2115 "(38)|up" => "prev_article",
2116 "(40)|down" => "next_article",
da15c140
AD
2117// "^(38)|Ctrl-up" => "prev_article_noscroll",
2118// "^(40)|Ctrl-down" => "next_article_noscroll",
e5e2cf3b 2119 "(191)|/" => "search_dialog",
e218c5f5
AD
2120// "article" => array(
2121 "s" => "toggle_mark",
5b18c936 2122 "*s" => "toggle_publ",
e218c5f5 2123 "u" => "toggle_unread",
5b18c936
AD
2124 "*t" => "edit_tags",
2125 "*d" => "dismiss_selected",
2126 "*x" => "dismiss_read",
e218c5f5
AD
2127 "o" => "open_in_new_window",
2128 "c p" => "catchup_below",
2129 "c n" => "catchup_above",
5b18c936
AD
2130 "*n" => "article_scroll_down",
2131 "*p" => "article_scroll_up",
d2db81a5
AD
2132 "*(38)|Shift+up" => "article_scroll_up",
2133 "*(40)|Shift+down" => "article_scroll_down",
5b18c936 2134 "a *w" => "toggle_widescreen",
2ccc7b8e 2135 "a e" => "toggle_embed_original",
e218c5f5 2136 "e" => "email_article",
2cda4314 2137 "a q" => "close_article",
e218c5f5
AD
2138// "article_selection" => array(
2139 "a a" => "select_all",
2140 "a u" => "select_unread",
5b18c936 2141 "a *u" => "select_marked",
e218c5f5
AD
2142 "a p" => "select_published",
2143 "a i" => "select_invert",
2144 "a n" => "select_none",
2145// "feed" => array(
2146 "f r" => "feed_refresh",
2147 "f a" => "feed_unhide_read",
2148 "f s" => "feed_subscribe",
2149 "f e" => "feed_edit",
2150 "f q" => "feed_catchup",
2151 "f x" => "feed_reverse",
5b18c936
AD
2152 "f *d" => "feed_debug_update",
2153 "f *c" => "toggle_combined_mode",
60b88b25 2154 "f c" => "toggle_cdm_expanded",
5b18c936 2155 "*q" => "catchup_all",
e218c5f5
AD
2156 "x" => "cat_toggle_collapse",
2157// "goto" => array(
2158 "g a" => "goto_all",
2159 "g f" => "goto_fresh",
2160 "g s" => "goto_marked",
2161 "g p" => "goto_published",
2162 "g t" => "goto_tagcloud",
5b18c936 2163 "g *p" => "goto_prefs",
e218c5f5 2164// "other" => array(
3fb40112 2165 "(9)|Tab" => "select_article_cursor", // tab
e218c5f5
AD
2166 "c l" => "create_label",
2167 "c f" => "create_filter",
2168 "c s" => "collapse_sidebar",
3fb40112 2169 "^(191)|Ctrl+/" => "help_dialog",
a83b58f1
AD
2170 );
2171
a42c55f0 2172 if (get_pref('COMBINED_DISPLAY_MODE')) {
da15c140
AD
2173 $hotkeys["^(38)|Ctrl-up"] = "prev_article_noscroll";
2174 $hotkeys["^(40)|Ctrl-down"] = "next_article_noscroll";
2175 }
2176
1ffe3391 2177 foreach (PluginHost::getInstance()->get_hooks(PluginHost::HOOK_HOTKEY_MAP) as $plugin) {
e218c5f5
AD
2178 $hotkeys = $plugin->hook_hotkey_map($hotkeys);
2179 }
2180
2181 $prefixes = array();
2182
2183 foreach (array_keys($hotkeys) as $hotkey) {
2184 $pair = explode(" ", $hotkey, 2);
2185
2186 if (count($pair) > 1 && !in_array($pair[0], $prefixes)) {
2187 array_push($prefixes, $pair[0]);
2188 }
2189 }
2190
2191 return array($prefixes, $hotkeys);
a83b58f1
AD
2192 }
2193
6322ac79 2194 function make_runtime_info() {
8cd576a1
AD
2195 $data = array();
2196
a42c55f0 2197 $result = db_query("SELECT MAX(id) AS mid, COUNT(*) AS nf FROM
9b7ecc0a
AD
2198 ttrss_feeds WHERE owner_uid = " . $_SESSION["uid"]);
2199
8cd576a1
AD
2200 $max_feed_id = db_fetch_result($result, 0, "mid");
2201 $num_feeds = db_fetch_result($result, 0, "nf");
9b7ecc0a 2202
8cd576a1
AD
2203 $data["max_feed_id"] = (int) $max_feed_id;
2204 $data["num_feeds"] = (int) $num_feeds;
c4f7ba80 2205
6322ac79 2206 $data['last_article_id'] = getLastArticleId();
a42c55f0 2207 $data['cdm_expanded'] = get_pref('CDM_EXPANDED');
f8fb4498 2208
16314dda 2209 $data['dep_ts'] = calculate_dep_timestamp();
4cdb8173 2210 $data['reload_on_ts_change'] = !defined('_NO_RELOAD_ON_TS_CHANGE');
16314dda 2211
dbaa4e4a 2212 if (file_exists(LOCK_DIRECTORY . "/update_daemon.lock")) {
c4f7ba80
AD
2213
2214 $data['daemon_is_running'] = (int) file_is_locked("update_daemon.lock");
8e00ae9b 2215
9041f58b 2216 if (time() - $_SESSION["daemon_stamp_check"] > 30) {
8e00ae9b 2217
fb074239 2218 $stamp = (int) @file_get_contents(LOCK_DIRECTORY . "/update_daemon.stamp");
fbae93d8 2219
8e00ae9b 2220 if ($stamp) {
9041f58b
AD
2221 $stamp_delta = time() - $stamp;
2222
2223 if ($stamp_delta > 1800) {
f6854e44 2224 $stamp_check = 0;
8e00ae9b 2225 } else {
f6854e44
AD
2226 $stamp_check = 1;
2227 $_SESSION["daemon_stamp_check"] = time();
8e00ae9b
AD
2228 }
2229
c4f7ba80 2230 $data['daemon_stamp_ok'] = $stamp_check;
f6854e44 2231
8e00ae9b
AD
2232 $stamp_fmt = date("Y.m.d, G:i", $stamp);
2233
c4f7ba80 2234 $data['daemon_stamp'] = $stamp_fmt;
8e00ae9b 2235 }
8e00ae9b 2236 }
71ad883b 2237 }
8e00ae9b 2238
63855db1 2239 if ($_SESSION["last_version_check"] + 86400 + rand(-1000, 1000) < time()) {
6322ac79 2240 $new_version_details = @check_for_update();
d9fa39f1 2241
63855db1 2242 $data['new_version_available'] = (int) ($new_version_details != false);
d9fa39f1
AD
2243
2244 $_SESSION["last_version_check"] = time();
27211afe 2245 $_SESSION["version_data"] = $new_version_details;
d9fa39f1
AD
2246 }
2247
c4f7ba80 2248 return $data;
f54f515f 2249 }
ef393de7 2250
a42c55f0 2251 function search_to_sql($search) {
ef393de7 2252
88040f57 2253 $search_query_part = "";
e20c9d88 2254
c6d970b8 2255 $keywords = str_getcsv($search, " ");
88040f57 2256 $query_keywords = array();
dd90eb2c 2257 $search_words = array();
e20c9d88 2258
ab4b768f
AD
2259 foreach ($keywords as $k) {
2260 if (strpos($k, "-") === 0) {
2261 $k = substr($k, 1);
2262 $not = "NOT";
2263 } else {
2264 $not = "";
88040f57 2265 }
e20c9d88 2266
9949bd15 2267 $commandpair = explode(":", mb_strtolower($k), 2);
53003548 2268
0fc3930b
AD
2269 switch ($commandpair[0]) {
2270 case "title":
2271 if ($commandpair[1]) {
2272 array_push($query_keywords, "($not (LOWER(ttrss_entries.title) LIKE '%".
a42c55f0 2273 db_escape_string(mb_strtolower($commandpair[1]))."%'))");
efd840d8
AD
2274 } else {
2275 array_push($query_keywords, "(UPPER(ttrss_entries.title) $not LIKE UPPER('%$k%')
2276 OR UPPER(ttrss_entries.content) $not LIKE UPPER('%$k%'))");
dd90eb2c 2277 array_push($search_words, $k);
0fc3930b
AD
2278 }
2279 break;
2280 case "author":
2281 if ($commandpair[1]) {
2282 array_push($query_keywords, "($not (LOWER(author) LIKE '%".
a42c55f0 2283 db_escape_string(mb_strtolower($commandpair[1]))."%'))");
efd840d8
AD
2284 } else {
2285 array_push($query_keywords, "(UPPER(ttrss_entries.title) $not LIKE UPPER('%$k%')
2286 OR UPPER(ttrss_entries.content) $not LIKE UPPER('%$k%'))");
dd90eb2c 2287 array_push($search_words, $k);
0fc3930b
AD
2288 }
2289 break;
2290 case "note":
2291 if ($commandpair[1]) {
2292 if ($commandpair[1] == "true")
2293 array_push($query_keywords, "($not (note IS NOT NULL AND note != ''))");
2294 else if ($commandpair[1] == "false")
2295 array_push($query_keywords, "($not (note IS NULL OR note = ''))");
2296 else
2297 array_push($query_keywords, "($not (LOWER(note) LIKE '%".
a42c55f0 2298 db_escape_string(mb_strtolower($commandpair[1]))."%'))");
efd840d8
AD
2299 } else {
2300 array_push($query_keywords, "(UPPER(ttrss_entries.title) $not LIKE UPPER('%$k%')
2301 OR UPPER(ttrss_entries.content) $not LIKE UPPER('%$k%'))");
dd90eb2c 2302 if (!$not) array_push($search_words, $k);
0fc3930b
AD
2303 }
2304 break;
2305 case "star":
53003548 2306
0fc3930b
AD
2307 if ($commandpair[1]) {
2308 if ($commandpair[1] == "true")
2309 array_push($query_keywords, "($not (marked = true))");
2310 else
2311 array_push($query_keywords, "($not (marked = false))");
efd840d8
AD
2312 } else {
2313 array_push($query_keywords, "(UPPER(ttrss_entries.title) $not LIKE UPPER('%$k%')
2314 OR UPPER(ttrss_entries.content) $not LIKE UPPER('%$k%'))");
dd90eb2c 2315 if (!$not) array_push($search_words, $k);
0fc3930b
AD
2316 }
2317 break;
2318 case "pub":
2319 if ($commandpair[1]) {
2320 if ($commandpair[1] == "true")
2321 array_push($query_keywords, "($not (published = true))");
2322 else
2323 array_push($query_keywords, "($not (published = false))");
53003548 2324
efd840d8
AD
2325 } else {
2326 array_push($query_keywords, "(UPPER(ttrss_entries.title) $not LIKE UPPER('%$k%')
2327 OR UPPER(ttrss_entries.content) $not LIKE UPPER('%$k%'))");
dd90eb2c 2328 if (!$not) array_push($search_words, $k);
0fc3930b
AD
2329 }
2330 break;
2331 default:
2332 if (strpos($k, "@") === 0) {
e20c9d88 2333
a42c55f0 2334 $user_tz_string = get_pref('USER_TIMEZONE', $_SESSION['uid']);
0fc3930b
AD
2335 $orig_ts = strtotime(substr($k, 1));
2336 $k = date("Y-m-d", convert_timestamp($orig_ts, $user_tz_string, 'UTC'));
8d505d78 2337
0fc3930b 2338 //$k = date("Y-m-d", strtotime(substr($k, 1)));
53003548 2339
0fc3930b
AD
2340 array_push($query_keywords, "(".SUBSTRING_FOR_DATE."(updated,1,LENGTH('$k')) $not = '$k')");
2341 } else {
2342 array_push($query_keywords, "(UPPER(ttrss_entries.title) $not LIKE UPPER('%$k%')
2343 OR UPPER(ttrss_entries.content) $not LIKE UPPER('%$k%'))");
dd90eb2c
AD
2344
2345 if (!$not) array_push($search_words, $k);
0fc3930b 2346 }
88040f57
AD
2347 }
2348 }
2349
2350 $search_query_part = implode("AND", $query_keywords);
2351
dd90eb2c 2352 return array($search_query_part, $search_words);
88040f57
AD
2353 }
2354
a42c55f0 2355 function getParentCategories($cat, $owner_uid) {
67bd0b1f
AD
2356 $rv = array();
2357
a42c55f0 2358 $result = db_query("SELECT parent_cat FROM ttrss_feed_categories
67bd0b1f
AD
2359 WHERE id = '$cat' AND parent_cat IS NOT NULL AND owner_uid = $owner_uid");
2360
2361 while ($line = db_fetch_assoc($result)) {
2362 array_push($rv, $line["parent_cat"]);
a42c55f0 2363 $rv = array_merge($rv, getParentCategories($line["parent_cat"], $owner_uid));
67bd0b1f
AD
2364 }
2365
2366 return $rv;
2367 }
2368
a42c55f0 2369 function getChildCategories($cat, $owner_uid) {
6d8d00e8
AD
2370 $rv = array();
2371
a42c55f0 2372 $result = db_query("SELECT id FROM ttrss_feed_categories
6d8d00e8
AD
2373 WHERE parent_cat = '$cat' AND owner_uid = $owner_uid");
2374
2375 while ($line = db_fetch_assoc($result)) {
2376 array_push($rv, $line["id"]);
a42c55f0 2377 $rv = array_merge($rv, getChildCategories($line["id"], $owner_uid));
6d8d00e8
AD
2378 }
2379
2380 return $rv;
2381 }
147f5632 2382
a6a61a8c 2383 function queryFeedHeadlines($feed, $limit, $view_mode, $cat_view, $search, $search_mode, $override_order = false, $offset = 0, $owner_uid = 0, $filter = false, $since_id = 0, $include_children = false, $ignore_vfeed_group = false, $override_strategy = false, $override_vfeed = false) {
c36bf4d5
AD
2384
2385 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
c1a0b534 2386
c3fddd05 2387 $ext_tables_part = "";
dd90eb2c 2388 $search_words = array();
c3fddd05 2389
88040f57 2390 if ($search) {
e4f7f8df
AD
2391
2392 if (SPHINX_ENABLED) {
2393 $ids = join(",", @sphinx_search($search, 0, 500));
2394
8d505d78 2395 if ($ids)
e4f7f8df
AD
2396 $search_query_part = "ref_id IN ($ids) AND ";
2397 else
2398 $search_query_part = "ref_id = -1 AND ";
2399
2400 } else {
dd90eb2c 2401 list($search_query_part, $search_words) = search_to_sql($search);
e4f7f8df 2402 $search_query_part .= " AND ";
8d505d78 2403 }
e20c9d88 2404
ef393de7
AD
2405 } else {
2406 $search_query_part = "";
2407 }
2408
36184020 2409 if ($filter) {
4e02f582
AD
2410
2411 if (DB_TYPE == "pgsql") {
2412 $query_strategy_part .= " AND updated > NOW() - INTERVAL '14 days' ";
2413 } else {
2414 $query_strategy_part .= " AND updated > DATE_SUB(NOW(), INTERVAL 14 DAY) ";
2415 }
2416
2417 $override_order = "updated DESC";
2418
a42c55f0 2419 $filter_query_part = filter_to_sql($filter, $owner_uid);
dd8c36af
AD
2420
2421 // Try to check if SQL regexp implementation chokes on a valid regexp
7711086b
AD
2422
2423
a42c55f0 2424 $result = db_query("SELECT true AS true_val FROM ttrss_entries,
7711086b 2425 ttrss_user_entries, ttrss_feeds
dd8c36af
AD
2426 WHERE $filter_query_part LIMIT 1", false);
2427
7726063c
AD
2428 if ($result) {
2429 $test = db_fetch_result($result, 0, "true_val");
dd8c36af 2430
7726063c
AD
2431 if (!$test) {
2432 $filter_query_part = "false AND";
2433 } else {
2434 $filter_query_part .= " AND";
2435 }
dd8c36af 2436 } else {
7726063c 2437 $filter_query_part = "false AND";
dd8c36af
AD
2438 }
2439
36184020
AD
2440 } else {
2441 $filter_query_part = "";
2442 }
2443
97e5dbb2
AD
2444 if ($since_id) {
2445 $since_id_part = "ttrss_entries.id > $since_id AND ";
2446 } else {
2447 $since_id_part = "";
2448 }
2449
ef393de7 2450 $view_query_part = "";
8d505d78 2451
9b523c01 2452 if ($view_mode == "adaptive") {
ef393de7
AD
2453 if ($search) {
2454 $view_query_part = " ";
2455 } else if ($feed != -1) {
6d8d00e8 2456
a42c55f0 2457 $unread = getFeedUnread($feed, $cat_view);
f4a2f12a 2458
a6adb136 2459 if ($cat_view && $feed > 0 && $include_children)
a42c55f0 2460 $unread += getCategoryChildrenUnread($feed);
f4a2f12a 2461
a6adb136
AD
2462 if ($unread > 0)
2463 $view_query_part = " unread = true AND ";
f4a2f12a 2464
ef393de7
AD
2465 }
2466 }
8d505d78 2467
ef393de7
AD
2468 if ($view_mode == "marked") {
2469 $view_query_part = " marked = true AND ";
2470 }
23d72f39 2471
127aaaa0
AD
2472 if ($view_mode == "has_note") {
2473 $view_query_part = " (note IS NOT NULL AND note != '') AND ";
2474 }
2475
23d72f39
AD
2476 if ($view_mode == "published") {
2477 $view_query_part = " published = true AND ";
2478 }
2479
0bf65987 2480 if ($view_mode == "unread" && $feed != -6) {
ef393de7
AD
2481 $view_query_part = " unread = true AND ";
2482 }
8b09eac8 2483
ef393de7
AD
2484 if ($limit > 0) {
2485 $limit_query_part = "LIMIT " . $limit;
8d505d78 2486 }
ef393de7 2487
8361e724
AD
2488 $allow_archived = false;
2489
ef393de7 2490 $vfeed_query_part = "";
8d505d78 2491
ef393de7
AD
2492 // override query strategy and enable feed display when searching globally
2493 if ($search && $search_mode == "all_feeds") {
7032f2a5 2494 $query_strategy_part = "true";
8d505d78 2495 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
22fdebff 2496 /* tags */
75c648cf 2497 } else if (!is_numeric($feed)) {
7032f2a5 2498 $query_strategy_part = "true";
ef393de7
AD
2499 $vfeed_query_part = "(SELECT title FROM ttrss_feeds WHERE
2500 id = feed_id) as feed_title,";
7032f2a5 2501 } else if ($search && $search_mode == "this_cat") {
8d505d78 2502 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
0a6c4846 2503
7032f2a5
AD
2504 if ($feed > 0) {
2505 if ($include_children) {
a42c55f0 2506 $subcats = getChildCategories($feed, $owner_uid);
7032f2a5
AD
2507 array_push($subcats, $feed);
2508 $cats_qpart = join(",", $subcats);
2509 } else {
2510 $cats_qpart = $feed;
ef393de7 2511 }
8d505d78 2512
7032f2a5 2513 $query_strategy_part = "ttrss_feeds.cat_id IN ($cats_qpart)";
8d505d78 2514
ef393de7 2515 } else {
7032f2a5 2516 $query_strategy_part = "ttrss_feeds.cat_id IS NULL";
ef393de7 2517 }
8d505d78 2518
e04c18a2 2519 } else if ($feed > 0) {
8d505d78 2520
ef393de7 2521 if ($cat_view) {
5c365f60 2522
ef393de7 2523 if ($feed > 0) {
09101297
AD
2524 if ($include_children) {
2525 # sub-cats
a42c55f0 2526 $subcats = getChildCategories($feed, $owner_uid);
09101297 2527
7032f2a5
AD
2528 array_push($subcats, $feed);
2529 $query_strategy_part = "cat_id IN (".
09101297 2530 implode(",", $subcats).")";
7032f2a5 2531
6d8d00e8 2532 } else {
09101297 2533 $query_strategy_part = "cat_id = '$feed'";
6d8d00e8
AD
2534 }
2535
ef393de7
AD
2536 } else {
2537 $query_strategy_part = "cat_id IS NULL";
2538 }
8d505d78 2539
ef393de7 2540 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
5c365f60 2541
8d505d78 2542 } else {
6e63a7c3 2543 $query_strategy_part = "feed_id = '$feed'";
ef393de7 2544 }
bfe5ddfc 2545 } else if ($feed == 0 && !$cat_view) { // archive virtual feed
e04c18a2 2546 $query_strategy_part = "feed_id IS NULL";
8361e724 2547 $allow_archived = true;
bfe5ddfc 2548 } else if ($feed == 0 && $cat_view) { // uncategorized
65dd90f2 2549 $query_strategy_part = "cat_id IS NULL AND feed_id IS NOT NULL";
bfe5ddfc 2550 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
ef393de7
AD
2551 } else if ($feed == -1) { // starred virtual feed
2552 $query_strategy_part = "marked = true";
2553 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
835fb294
AD
2554 $allow_archived = true;
2555
1bd7413f 2556 if (!$override_order) {
b9a06a0e 2557 $override_order = "last_marked DESC, date_entered DESC, updated DESC";
1bd7413f 2558 }
7873d588 2559
e6a38cde
AD
2560 } else if ($feed == -2) { // published virtual feed OR labels category
2561
2562 if (!$cat_view) {
2563 $query_strategy_part = "published = true";
2564 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
8361e724 2565 $allow_archived = true;
46b78149 2566
1bd7413f 2567 if (!$override_order) {
b9a06a0e 2568 $override_order = "last_published DESC, date_entered DESC, updated DESC";
1bd7413f
AD
2569 }
2570
e6a38cde
AD
2571 } else {
2572 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
2573
2574 $ext_tables_part = ",ttrss_labels2,ttrss_user_labels2";
8d505d78 2575
e6a38cde
AD
2576 $query_strategy_part = "ttrss_labels2.id = ttrss_user_labels2.label_id AND
2577 ttrss_user_labels2.article_id = ref_id";
2578
2579 }
5417fbd7 2580 } else if ($feed == -6) { // recently read
5089b30b 2581 $query_strategy_part = "unread = false AND last_read IS NOT NULL";
5417fbd7 2582 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
835fb294 2583 $allow_archived = true;
46b78149
AD
2584
2585 if (!$override_order) $override_order = "last_read DESC";
a6a61a8c
AD
2586
2587/* } else if ($feed == -7) { // shared
2588 $query_strategy_part = "uuid != ''";
2589 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
2590 $allow_archived = true; */
2d24f032 2591 } else if ($feed == -3) { // fresh virtual feed
cd2cc43d 2592 $query_strategy_part = "unread = true AND score >= 0";
2d24f032 2593
a42c55f0 2594 $intl = get_pref("FRESH_ARTICLE_MAX_AGE", $owner_uid);
c1d7e6c3 2595
2d24f032 2596 if (DB_TYPE == "pgsql") {
be574731 2597 $query_strategy_part .= " AND date_entered > NOW() - INTERVAL '$intl hour' ";
2d24f032 2598 } else {
be574731 2599 $query_strategy_part .= " AND date_entered > DATE_SUB(NOW(), INTERVAL $intl HOUR) ";
2d24f032
AD
2600 }
2601
b2531a28
AD
2602 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
2603 } else if ($feed == -4) { // all articles virtual feed
cf57eb3c 2604 $allow_archived = true;
b2531a28 2605 $query_strategy_part = "true";
e4f4b46f 2606 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
f822a8e5
AD
2607 } else if ($feed <= LABEL_BASE_INDEX) { // labels
2608 $label_id = feed_to_label_id($feed);
3de0261a 2609
ceb30ba4
AD
2610 $query_strategy_part = "label_id = '$label_id' AND
2611 ttrss_labels2.id = ttrss_user_labels2.label_id AND
2612 ttrss_user_labels2.article_id = ref_id";
3de0261a 2613
ef393de7 2614 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
ceb30ba4 2615 $ext_tables_part = ",ttrss_labels2,ttrss_user_labels2";
835fb294 2616 $allow_archived = true;
8d505d78 2617
ef393de7 2618 } else {
835fb294 2619 $query_strategy_part = "true";
ef393de7 2620 }
d6e5706d 2621
686852d5 2622 $order_by = "score DESC, date_entered DESC, updated DESC";
e939722a 2623
2e4faaac 2624 if ($view_mode == "unread_first") {
434bf856 2625 $order_by = "unread DESC, $order_by";
2e4faaac
AD
2626 }
2627
e939722a
AD
2628 if ($override_order) {
2629 $order_by = $override_order;
2630 }
8d505d78 2631
a6a61a8c
AD
2632 if ($override_strategy) {
2633 $query_strategy_part = $override_strategy;
2634 }
2635
2636 if ($override_vfeed) {
2637 $vfeed_query_part = $override_vfeed;
2638 }
2639
ef393de7
AD
2640 $feed_title = "";
2641
22fdebff 2642 if ($search) {
7032f2a5 2643 $feed_title = T_sprintf("Search results: %s", $search);
22fdebff 2644 } else {
ef393de7 2645 if ($cat_view) {
a42c55f0 2646 $feed_title = getCategoryTitle($feed);
ef393de7 2647 } else {
147f5632 2648 if (is_numeric($feed) && $feed > 0) {
6e3e8db9 2649 $result = db_query("SELECT title,site_url,last_error,last_updated
22fdebff 2650 FROM ttrss_feeds WHERE id = '$feed' AND owner_uid = $owner_uid");
8d505d78 2651
22fdebff
AD
2652 $feed_title = db_fetch_result($result, 0, "title");
2653 $feed_site_url = db_fetch_result($result, 0, "site_url");
2654 $last_error = db_fetch_result($result, 0, "last_error");
6e3e8db9 2655 $last_updated = db_fetch_result($result, 0, "last_updated");
22fdebff 2656 } else {
a42c55f0 2657 $feed_title = getFeedTitle($feed);
8d505d78 2658 }
88040f57 2659 }
ef393de7
AD
2660 }
2661
3b96b0ed 2662
bf5bcb8e 2663 $content_query_part = "content, ";
62129e67 2664
62129e67 2665
75c648cf 2666 if (is_numeric($feed)) {
8d505d78 2667
ef393de7
AD
2668 if ($feed >= 0) {
2669 $feed_kind = "Feeds";
2670 } else {
2671 $feed_kind = "Labels";
2672 }
8d505d78 2673
95a82c08
AD
2674 if ($limit_query_part) {
2675 $offset_query_part = "OFFSET $offset";
2676 }
2677
7fdf8eca 2678 // proper override_order applied above
a42c55f0 2679 if ($vfeed_query_part && !$ignore_vfeed_group && get_pref('VFEED_GROUP_BY_FEED', $owner_uid)) {
6cfea5c7 2680 if (!$override_order) {
8d505d78 2681 $order_by = "ttrss_feeds.title, $order_by";
7fdf8eca
AD
2682 } else {
2683 $order_by = "ttrss_feeds.title, $override_order";
43fc671f 2684 }
6cfea5c7
AD
2685 }
2686
8361e724 2687 if (!$allow_archived) {
e04c18a2 2688 $from_qpart = "ttrss_entries,ttrss_user_entries,ttrss_feeds$ext_tables_part";
117335bf 2689 $feed_check_qpart = "ttrss_user_entries.feed_id = ttrss_feeds.id AND";
e04c18a2
AD
2690
2691 } else {
835fb294 2692 $from_qpart = "ttrss_entries$ext_tables_part,ttrss_user_entries
e04c18a2
AD
2693 LEFT JOIN ttrss_feeds ON (feed_id = ttrss_feeds.id)";
2694 }
2695
63c323f7
AD
2696 if ($vfeed_query_part)
2697 $vfeed_query_part .= "favicon_avg_color,";
2698
8d505d78 2699 $query = "SELECT DISTINCT
f9b2d27c 2700 date_entered,
1f64b1be 2701 guid,
ef393de7 2702 ttrss_entries.id,ttrss_entries.title,
46921916 2703 updated,
9c506873
AD
2704 label_cache,
2705 tag_cache,
c0644ee4 2706 always_display_enclosures,
d1fc2f92 2707 site_url,
c7e51de1 2708 note,
13992673
AD
2709 num_comments,
2710 comments,
db16ae50 2711 int_id,
abb04b76 2712 uuid,
6b461797 2713 lang,
bfd61d3f 2714 hide_images,
494a64ea 2715 unread,feed_id,marked,published,link,last_read,orig_feed_id,
7873d588 2716 last_marked, last_published,
ef393de7
AD
2717 $vfeed_query_part
2718 $content_query_part
ff6e357a 2719 author,score
ef393de7 2720 FROM
e04c18a2 2721 $from_qpart
ef393de7 2722 WHERE
e04c18a2 2723 $feed_check_qpart
ef393de7 2724 ttrss_user_entries.ref_id = ttrss_entries.id AND
c36bf4d5 2725 ttrss_user_entries.owner_uid = '$owner_uid' AND
ef393de7 2726 $search_query_part
36184020 2727 $filter_query_part
ef393de7 2728 $view_query_part
97e5dbb2 2729 $since_id_part
ef393de7 2730 $query_strategy_part ORDER BY $order_by
95a82c08 2731 $limit_query_part $offset_query_part";
4bc311fc 2732
b4e75b2a 2733 if ($_REQUEST["debug"]) print $query;
4bc311fc 2734
a42c55f0 2735 $result = db_query($query);
8d505d78 2736
ef393de7
AD
2737 } else {
2738 // browsing by tag
8d505d78 2739
147f5632
CM
2740 $select_qpart = "SELECT DISTINCT " .
2741 "date_entered," .
2742 "guid," .
2743 "note," .
2744 "ttrss_entries.id as id," .
2745 "title," .
2746 "updated," .
2747 "unread," .
2748 "feed_id," .
2749 "orig_feed_id," .
2750 "marked," .
d1fc2f92
AD
2751 "num_comments, " .
2752 "comments, " .
c0644ee4
AD
2753 "tag_cache," .
2754 "label_cache," .
147f5632 2755 "link," .
6b461797 2756 "lang," .
abb04b76 2757 "uuid," .
147f5632 2758 "last_read," .
94a567df 2759 "(SELECT hide_images FROM ttrss_feeds WHERE id = feed_id) AS hide_images," .
7873d588 2760 "last_marked, last_published, " .
97e5dbb2 2761 $since_id_part .
147f5632
CM
2762 $vfeed_query_part .
2763 $content_query_part .
147f5632
CM
2764 "score ";
2765
ef393de7 2766 $feed_kind = "Tags";
147f5632
CM
2767 $all_tags = explode(",", $feed);
2768 if ($search_mode == 'any') {
2769 $tag_sql = "tag_name in (" . implode(", ", array_map("db_quote", $all_tags)) . ")";
2770 $from_qpart = " FROM ttrss_entries,ttrss_user_entries,ttrss_tags ";
2771 $where_qpart = " WHERE " .
2772 "ref_id = ttrss_entries.id AND " .
2773 "ttrss_user_entries.owner_uid = $owner_uid AND " .
2774 "post_int_id = int_id AND $tag_sql AND " .
2775 $view_query_part .
2776 $search_query_part .
2777 $query_strategy_part . " ORDER BY $order_by " .
2778 $limit_query_part;
8d505d78 2779
147f5632
CM
2780 } else {
2781 $i = 1;
2782 $sub_selects = array();
2783 $sub_ands = array();
2784 foreach ($all_tags as $term) {
2785 array_push($sub_selects, "(SELECT post_int_id from ttrss_tags WHERE tag_name = " . db_quote($term) . " AND owner_uid = $owner_uid) as A$i");
2786 $i++;
2787 }
2788 if ($i > 2) {
2789 $x = 1;
2790 $y = 2;
2791 do {
2792 array_push($sub_ands, "A$x.post_int_id = A$y.post_int_id");
2793 $x++;
2794 $y++;
2795 } while ($y < $i);
2796 }
2797 array_push($sub_ands, "A1.post_int_id = ttrss_user_entries.int_id and ttrss_user_entries.owner_uid = $owner_uid");
2798 array_push($sub_ands, "ttrss_user_entries.ref_id = ttrss_entries.id");
2799 $from_qpart = " FROM " . implode(", ", $sub_selects) . ", ttrss_user_entries, ttrss_entries";
2800 $where_qpart = " WHERE " . implode(" AND ", $sub_ands);
2801 }
2802 // error_log("TAG SQL: " . $tag_sql);
2803 // $tag_sql = "tag_name = '$feed'"; DEFAULT way
2804
2805 // error_log("[". $select_qpart . "][" . $from_qpart . "][" .$where_qpart . "]");
a42c55f0 2806 $result = db_query($select_qpart . $from_qpart . $where_qpart);
ef393de7
AD
2807 }
2808
dd90eb2c 2809 return array($result, $feed_title, $feed_site_url, $last_error, $last_updated, $search_words);
8d505d78 2810
ef393de7
AD
2811 }
2812
910592b4 2813 function sanitize($str, $force_remove_images = false, $owner = false, $site_url = false, $highlight_words = false, $article_id = false) {
ceb0cab5
AD
2814 if (!$owner) $owner = $_SESSION["uid"];
2815
96811a55
AD
2816 $res = trim($str); if (!$res) return '';
2817
8cc3c778
AD
2818 $charset_hack = '<head>
2819 <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
2820 </head>';
2821
96811a55
AD
2822 $res = trim($res); if (!$res) return '';
2823
8cc3c778
AD
2824 libxml_use_internal_errors(true);
2825
2826 $doc = new DOMDocument();
2827 $doc->loadHTML($charset_hack . $res);
2828 $xpath = new DOMXPath($doc);
8d505d78 2829
8cc3c778
AD
2830 $entries = $xpath->query('(//a[@href]|//img[@src])');
2831
2832 foreach ($entries as $entry) {
2833
2834 if ($site_url) {
2835
5b319e8b 2836 if ($entry->hasAttribute('href')) {
8cc3c778
AD
2837 $entry->setAttribute('href',
2838 rewrite_relative_url($site_url, $entry->getAttribute('href')));
8d505d78 2839
5b319e8b
AD
2840 $entry->setAttribute('rel', 'noreferrer');
2841 }
2842
f0bd8e65
AD
2843 if ($entry->hasAttribute('src')) {
2844 $src = rewrite_relative_url($site_url, $entry->getAttribute('src'));
2845
2846 $cached_filename = CACHE_DIR . '/images/' . sha1($src) . '.png';
2847
2848 if (file_exists($cached_filename)) {
2849 $src = SELF_URL_PATH . '/image.php?hash=' . sha1($src);
2850 }
2851
2852 $entry->setAttribute('src', $src);
2853 }
bfd61d3f
AD
2854
2855 if ($entry->nodeName == 'img') {
a42c55f0 2856 if (($owner && get_pref("STRIP_IMAGES", $owner)) ||
ba79634c 2857 $force_remove_images || $_SESSION["bw_limit"]) {
bfd61d3f
AD
2858
2859 $p = $doc->createElement('p');
2860
2861 $a = $doc->createElement('a');
2862 $a->setAttribute('href', $entry->getAttribute('src'));
2863
2864 $a->appendChild(new DOMText($entry->getAttribute('src')));
2865 $a->setAttribute('target', '_blank');
2866
2867 $p->appendChild($a);
2868
2869 $entry->parentNode->replaceChild($p, $entry);
2870 }
2871 }
8cc3c778
AD
2872 }
2873
fa403733 2874 if (strtolower($entry->nodeName) == "a") {
c401d5c9 2875 $entry->setAttribute("target", "_blank");
fa403733 2876 }
8dccabed 2877 }
8d505d78 2878
254a3f56
AD
2879 $entries = $xpath->query('//iframe');
2880 foreach ($entries as $entry) {
4e404802
AD
2881 $entry->setAttribute('sandbox', 'allow-scripts');
2882
254a3f56 2883 }
8dccabed 2884
1701b965 2885 $allowed_elements = array('a', 'address', 'audio', 'article', 'aside',
2886 'b', 'bdi', 'bdo', 'big', 'blockquote', 'body', 'br',
2887 'caption', 'cite', 'center', 'code', 'col', 'colgroup',
2888 'data', 'dd', 'del', 'details', 'div', 'dl', 'font',
2889 'dt', 'em', 'footer', 'figure', 'figcaption',
2890 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'header', 'html', 'i',
2891 'img', 'ins', 'kbd', 'li', 'main', 'mark', 'nav', 'noscript',
e0d12697 2892 'ol', 'p', 'pre', 'q', 'ruby', 'rp', 'rt', 's', 'samp', 'section',
2893 'small', 'source', 'span', 'strike', 'strong', 'sub', 'summary',
1701b965 2894 'sup', 'table', 'tbody', 'td', 'tfoot', 'th', 'thead', 'time',
b70ccfe6
FE
2895 'tr', 'track', 'tt', 'u', 'ul', 'var', 'wbr', 'video' );
2896
2897 if ($_SESSION['hasSandbox']) $allowed_elements[] = 'iframe';
2898
2899 $disallowed_attributes = array('id', 'style', 'class');
2900
1ffe3391 2901 foreach (PluginHost::getInstance()->get_hooks(PluginHost::HOOK_SANITIZE) as $plugin) {
910592b4 2902 $retval = $plugin->hook_sanitize($doc, $site_url, $allowed_elements, $disallowed_attributes, $article_id);
1ffe3391
AD
2903 if (is_array($retval)) {
2904 $doc = $retval[0];
2905 $allowed_elements = $retval[1];
2906 $disallowed_attributes = $retval[2];
2907 } else {
2908 $doc = $retval;
e9b86f0a
AD
2909 }
2910 }
2911
e198cca7 2912 $doc->removeChild($doc->firstChild); //remove doctype
b70ccfe6 2913 $doc = strip_harmful_tags($doc, $allowed_elements, $disallowed_attributes);
dd90eb2c
AD
2914
2915 if ($highlight_words) {
2916 foreach ($highlight_words as $word) {
2917
d41ad037
AD
2918 // http://stackoverflow.com/questions/4081372/highlight-keywords-in-a-paragraph
2919
79834eda
AD
2920 $elements = $xpath->query("//*/text()");
2921
2922 foreach ($elements as $child) {
79834eda
AD
2923
2924 $fragment = $doc->createDocumentFragment();
2925 $text = $child->textContent;
2926 $stubs = array();
2927
2928 while (($pos = mb_stripos($text, $word)) !== false) {
2929 $fragment->appendChild(new DomText(mb_substr($text, 0, $pos)));
2930 $word = mb_substr($text, $pos, mb_strlen($word));
2931 $highlight = $doc->createElement('span');
2932 $highlight->appendChild(new DomText($word));
2933 $highlight->setAttribute('class', 'highlight');
2934 $fragment->appendChild($highlight);
2935 $text = mb_substr($text, $pos + mb_strlen($word));
2936 }
dd90eb2c 2937
79834eda 2938 if (!empty($text)) $fragment->appendChild(new DomText($text));
dd90eb2c 2939
79834eda 2940 $child->parentNode->replaceChild($fragment, $child);
dd90eb2c
AD
2941 }
2942 }
2943 }
2944
e198cca7 2945 $res = $doc->saveHTML();
dd90eb2c 2946
254a3f56
AD
2947 return $res;
2948 }
16ad9085 2949
b70ccfe6 2950 function strip_harmful_tags($doc, $allowed_elements, $disallowed_attributes) {
dcd7ecaa
AD
2951 $xpath = new DOMXPath($doc);
2952 $entries = $xpath->query('//*');
16ad9085 2953
254a3f56
AD
2954 foreach ($entries as $entry) {
2955 if (!in_array($entry->nodeName, $allowed_elements)) {
2956 $entry->parentNode->removeChild($entry);
2957 }
2958
2959 if ($entry->hasAttributes()) {
5f0081b0
AD
2960 $attrs_to_remove = array();
2961
2962 foreach ($entry->attributes as $attr) {
254a3f56
AD
2963
2964 if (strpos($attr->nodeName, 'on') === 0) {
5f0081b0 2965 array_push($attrs_to_remove, $attr);
254a3f56
AD
2966 }
2967
2968 if (in_array($attr->nodeName, $disallowed_attributes)) {
5f0081b0 2969 array_push($attrs_to_remove, $attr);
254a3f56
AD
2970 }
2971 }
5f0081b0
AD
2972
2973 foreach ($attrs_to_remove as $attr) {
2974 $entry->removeAttributeNode($attr);
2975 }
254a3f56
AD
2976 }
2977 }
2978
2979 return $doc;
183ad07b 2980 }
b72c3ef8 2981
6322ac79 2982 function check_for_update() {
63855db1 2983 if (CHECK_FOR_NEW_VERSION && $_SESSION['access_level'] >= 10) {
f6064662
AD
2984 $version_url = "http://tt-rss.org/version.php?ver=" . VERSION .
2985 "&iid=" . sha1(SELF_URL_PATH);
b72c3ef8 2986
63855db1 2987 $version_data = @fetch_file_contents($version_url);
b72c3ef8 2988
63855db1
AD
2989 if ($version_data) {
2990 $version_data = json_decode($version_data, true);
8d505d78 2991 if ($version_data && $version_data['version']) {
74a8b2f6 2992 if (version_compare(VERSION_STATIC, $version_data['version']) == -1) {
e91ad1e9 2993 return $version_data;
63855db1
AD
2994 }
2995 }
f67d9754 2996 }
b72c3ef8 2997 }
63855db1 2998 return false;
b72c3ef8 2999 }
472782e8 3000
a42c55f0 3001 function catchupArticlesById($ids, $cmode, $owner_uid = false) {
9968d46f
AD
3002
3003 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
ed41f171 3004 if (count($ids) == 0) return;
472782e8
AD
3005
3006 $tmp_ids = array();
3007
3008 foreach ($ids as $id) {
3009 array_push($tmp_ids, "ref_id = '$id'");
3010 }
3011
3012 $ids_qpart = join(" OR ", $tmp_ids);
3013
3014 if ($cmode == 0) {
a42c55f0 3015 db_query("UPDATE ttrss_user_entries SET
472782e8 3016 unread = false,last_read = NOW()
9968d46f 3017 WHERE ($ids_qpart) AND owner_uid = $owner_uid");
472782e8 3018 } else if ($cmode == 1) {
a42c55f0 3019 db_query("UPDATE ttrss_user_entries SET
472782e8 3020 unread = true
9968d46f 3021 WHERE ($ids_qpart) AND owner_uid = $owner_uid");
472782e8 3022 } else {
a42c55f0 3023 db_query("UPDATE ttrss_user_entries SET
472782e8 3024 unread = NOT unread,last_read = NOW()
9968d46f 3025 WHERE ($ids_qpart) AND owner_uid = $owner_uid");
472782e8 3026 }
0737b95a
AD
3027
3028 /* update ccache */
3029
a42c55f0 3030 $result = db_query("SELECT DISTINCT feed_id FROM ttrss_user_entries
0737b95a
AD
3031 WHERE ($ids_qpart) AND owner_uid = $owner_uid");
3032
3033 while ($line = db_fetch_assoc($result)) {
a42c55f0 3034 ccache_update($line["feed_id"], $owner_uid);
0737b95a 3035 }
472782e8
AD
3036 }
3037
a42c55f0 3038 function get_article_tags($id, $owner_uid = 0, $tag_cache = false) {
0b126ac2 3039
a42c55f0 3040 $a_id = db_escape_string($id);
0b126ac2 3041
bc976a8c
AD
3042 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
3043
8d505d78 3044 $query = "SELECT DISTINCT tag_name,
0c3d1c68 3045 owner_uid as owner FROM
0b126ac2 3046 ttrss_tags WHERE post_int_id = (SELECT int_id FROM ttrss_user_entries WHERE
bd3f2ade 3047 ref_id = '$a_id' AND owner_uid = '$owner_uid' LIMIT 1) ORDER BY tag_name";
0b126ac2 3048
8d505d78 3049 $tags = array();
bd3f2ade 3050
0e4a7d7a 3051 /* check cache first */
490c366d 3052
0e4a7d7a 3053 if ($tag_cache === false) {
a42c55f0 3054 $result = db_query("SELECT tag_cache FROM ttrss_user_entries
0e4a7d7a 3055 WHERE ref_id = '$id' AND owner_uid = $owner_uid");
490c366d 3056
0e4a7d7a
AD
3057 $tag_cache = db_fetch_result($result, 0, "tag_cache");
3058 }
bd3f2ade 3059
0e4a7d7a
AD
3060 if ($tag_cache) {
3061 $tags = explode(",", $tag_cache);
3062 } else {
490c366d 3063
0e4a7d7a 3064 /* do it the hard way */
490c366d 3065
a42c55f0 3066 $tmp_result = db_query($query);
490c366d 3067
0e4a7d7a
AD
3068 while ($tmp_line = db_fetch_assoc($tmp_result)) {
3069 array_push($tags, $tmp_line["tag_name"]);
3070 }
490c366d 3071
0e4a7d7a 3072 /* update the cache */
490c366d 3073
a42c55f0 3074 $tags_str = db_escape_string(join(",", $tags));
bd3f2ade 3075
a42c55f0 3076 db_query("UPDATE ttrss_user_entries
0e4a7d7a
AD
3077 SET tag_cache = '$tags_str' WHERE ref_id = '$id'
3078 AND owner_uid = $owner_uid");
0b126ac2
AD
3079 }
3080
3081 return $tags;
3082 }
3083
d62a3b63
AD
3084 function trim_array($array) {
3085 $tmp = $array;
3415b075 3086 array_walk($tmp, 'trim');
d62a3b63
AD
3087 return $tmp;
3088 }
3089
be832a1a 3090 function tag_is_valid($tag) {
ef063748
AD
3091 if ($tag == '') return false;
3092 if (preg_match("/^[0-9]*$/", $tag)) return false;
41f7498a 3093 if (mb_strlen($tag) > 250) return false;
ef063748 3094
ef063748
AD
3095 if (!$tag) return false;
3096
3097 return true;
be832a1a
AD
3098 }
3099
6322ac79 3100 function render_login_form() {
bb399c62
AD
3101 header('Cache-Control: public');
3102
d98e76d9 3103 require_once "login_form.php";
97acbaf1 3104 exit;
01a87dff
AD
3105 }
3106
42395d28 3107 function format_warning($msg, $id = "") {
883fee8d 3108 global $link;
8d505d78 3109 return "<div class=\"warning\" id=\"$id\">
2f20dd58 3110 <span><img src=\"images/alert.png\"></span><span>$msg</span></div>";
0d32b41e
AD
3111 }
3112
08ac193a 3113 function format_notice($msg, $id = "") {
883fee8d 3114 global $link;
8d505d78 3115 return "<div class=\"notice\" id=\"$id\">
2f20dd58 3116 <span><img src=\"images/information.png\"></span><span>$msg</span></div>";
0d32b41e
AD
3117 }
3118
08ac193a 3119 function format_error($msg, $id = "") {
883fee8d 3120 global $link;
8d505d78 3121 return "<div class=\"error\" id=\"$id\">
2f20dd58 3122 <span><img src=\"images/alert.png\"></span><span>$msg</span></div>";
68d2f95e
AD
3123 }
3124
4dccf1ed
AD
3125 function print_notice($msg) {
3126 return print format_notice($msg);
3127 }
3128
3129 function print_warning($msg) {
3130 return print format_warning($msg);
3131 }
3132
68d2f95e
AD
3133 function print_error($msg) {
3134 return print format_error($msg);
3135 }
3136
3137
4dccf1ed
AD
3138 function T_sprintf() {
3139 $args = func_get_args();
3140 return vsprintf(__(array_shift($args)), $args);
3141 }
3142
a42c55f0 3143 function format_inline_player($url, $ctype) {
51682b23
AD
3144
3145 $entry = "";
3146
44cd77b6
AD
3147 $url = htmlspecialchars($url);
3148
8d505d78 3149 if (strpos($ctype, "audio/") === 0) {
c3edc667
AD
3150
3151 if ($_SESSION["hasAudio"] && (strpos($ctype, "ogg") !== false ||
40fe2d73 3152 $_SESSION["hasMp3"])) {
c3edc667 3153
afd0849e 3154 $entry .= "<audio preload=\"none\" controls>
ca3bca99 3155 <source type=\"$ctype\" src=\"$url\"></source>
8d505d78 3156 </audio>";
c3edc667 3157
c3edc667 3158 } else {
8d505d78
AD
3159
3160 $entry .= "<object type=\"application/x-shockwave-flash\"
ad95edc2 3161 data=\"lib/button/musicplayer.swf?song_url=$url\"
8d505d78
AD
3162 width=\"17\" height=\"17\" style='float : left; margin-right : 5px;'>
3163 <param name=\"movie\"
ad95edc2 3164 value=\"lib/button/musicplayer.swf?song_url=$url\" />
8d505d78 3165 </object>";
c3edc667 3166 }
ca3bca99 3167
44cd77b6
AD
3168 if ($entry) $entry .= "&nbsp; <a target=\"_blank\"
3169 href=\"$url\">" . basename($url) . "</a>";
ca3bca99
AD
3170
3171 return $entry;
3172
51682b23
AD
3173 }
3174
ca3bca99
AD
3175 return "";
3176
3177/* $filename = substr($url, strrpos($url, "/")+1);
c3edc667
AD
3178
3179 $entry .= " <a target=\"_blank\" href=\"" . htmlspecialchars($url) . "\">" .
ca3bca99 3180 $filename . " (" . $ctype . ")" . "</a>"; */
c3edc667 3181
51682b23
AD
3182 }
3183
a42c55f0 3184 function format_article($id, $mark_as_read = true, $zoom_mode = false, $owner_uid = false) {
64436e10 3185 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
3de0261a 3186
009646d2
AD
3187 $rv = array();
3188
3189 $rv['id'] = $id;
3190
10eb9da8 3191 /* we can figure out feed_id from article id anyway, why do we
a42c55f0 3192 * pass feed_id here? let's ignore the argument :(*/
10eb9da8 3193
a42c55f0 3194 $result = db_query("SELECT feed_id FROM ttrss_user_entries
10eb9da8
AD
3195 WHERE ref_id = '$id'");
3196
e04c18a2 3197 $feed_id = (int) db_fetch_result($result, 0, "feed_id");
10eb9da8 3198
009646d2
AD
3199 $rv['feed_id'] = $feed_id;
3200
3201 //if (!$zoom_mode) { print "<article id='$id'><![CDATA["; };
3de0261a 3202
3de0261a 3203 if ($mark_as_read) {
a42c55f0 3204 $result = db_query("UPDATE ttrss_user_entries
8d505d78 3205 SET unread = false,last_read = NOW()
64436e10 3206 WHERE ref_id = '$id' AND owner_uid = $owner_uid");
8a4c759e 3207
a42c55f0 3208 ccache_update($feed_id, $owner_uid);
3de0261a
AD
3209 }
3210
6b461797 3211 $result = db_query("SELECT id,title,link,content,feed_id,comments,int_id,lang,
fc2b26a6 3212 ".SUBSTRING_FOR_DATE."(updated,1,16) as updated,
8cc3c778 3213 (SELECT site_url FROM ttrss_feeds WHERE id = feed_id) as site_url,
ff04fe06 3214 (SELECT title FROM ttrss_feeds WHERE id = feed_id) as feed_title,
33de3d37 3215 (SELECT hide_images FROM ttrss_feeds WHERE id = feed_id) as hide_images,
60376e9d 3216 (SELECT always_display_enclosures FROM ttrss_feeds WHERE id = feed_id) as always_display_enclosures,
3de0261a 3217 num_comments,
9c506873 3218 tag_cache,
c7e51de1 3219 author,
ef83538d 3220 orig_feed_id,
c052e25a 3221 note
3de0261a 3222 FROM ttrss_entries,ttrss_user_entries
64436e10 3223 WHERE id = '$id' AND ref_id = id AND owner_uid = $owner_uid");
3de0261a
AD
3224
3225 if ($result) {
3226
3de0261a
AD
3227 $line = db_fetch_assoc($result);
3228
84d952f1
AD
3229 $tag_cache = $line["tag_cache"];
3230
a42c55f0 3231 $line["tags"] = get_article_tags($id, $owner_uid, $line["tag_cache"]);
84d952f1
AD
3232 unset($line["tag_cache"]);
3233
53a49ff8
AD
3234 $line["content"] = sanitize($line["content"],
3235 sql_bool_to_bool($line['hide_images']),
910592b4 3236 $owner_uid, $line["site_url"], false, $line["id"]);
84d952f1 3237
1ffe3391 3238 foreach (PluginHost::getInstance()->get_hooks(PluginHost::HOOK_RENDER_ARTICLE) as $p) {
84d952f1
AD
3239 $line = $p->hook_render_article($line);
3240 }
8cc3c778 3241
3de0261a
AD
3242 $num_comments = $line["num_comments"];
3243 $entry_comments = "";
3244
3245 if ($num_comments > 0) {
3246 if ($line["comments"]) {
6e577ba1 3247 $comments_url = htmlspecialchars($line["comments"]);
3de0261a 3248 } else {
6e577ba1 3249 $comments_url = htmlspecialchars($line["link"]);
3de0261a 3250 }
ff04fe06
AD
3251 $entry_comments = "<a class=\"postComments\"
3252 target='_blank' href=\"$comments_url\">$num_comments ".
3253 _ngettext("comment", "comments", $num_comments)."</a>";
3254
3de0261a
AD
3255 } else {
3256 if ($line["comments"] && $line["link"] != $line["comments"]) {
ff04fe06 3257 $entry_comments = "<a class=\"postComments\" target='_blank' href=\"".htmlspecialchars($line["comments"])."\">".__("comments")."</a>";
8d505d78 3258 }
3de0261a
AD
3259 }
3260
eedfb635
AD
3261 if ($zoom_mode) {
3262 header("Content-Type: text/html");
009646d2 3263 $rv['content'] .= "<html><head>
5bb0cc8e 3264 <meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\"/>
cdbcb277
AD
3265 <title>Tiny Tiny RSS - ".$line["title"]."</title>".
3266 stylesheet_tag("css/tt-rss.css").
5a801bd6
AD
3267 stylesheet_tag("css/zoom.css").
3268 stylesheet_tag("css/dijit.css")."
cdbcb277 3269
d0ee0f52
AD
3270 <link rel=\"shortcut icon\" type=\"image/png\" href=\"images/favicon.png\">
3271 <link rel=\"icon\" type=\"image/png\" sizes=\"72x72\" href=\"images/favicon-72px.png\">
3272
761af552
AD
3273 <script type=\"text/javascript\">
3274 function openSelectedAttachment(elem) {
3275 try {
3276 var url = elem[elem.selectedIndex].value;
3277
3278 if (url) {
3279 window.open(url);
3280 elem.selectedIndex = 0;
3281 }
3282
3283 } catch (e) {
3284 exception_error(\"openSelectedAttachment\", e);
3285 }
3286 }
3287 </script>
b87a625c 3288 </head><body id=\"ttrssZoom\">";
eedfb635
AD
3289 }
3290
009646d2 3291 $rv['content'] .= "<div class=\"postReply\" id=\"POST-$id\">";
bc372fe3 3292
126e639a 3293 $rv['content'] .= "<div class=\"postHeader\" id=\"POSTHDR-$id\">";
3de0261a
AD
3294
3295 $entry_author = $line["author"];
3296
3297 if ($entry_author) {
60164936 3298 $entry_author = __(" - ") . $entry_author;
3de0261a
AD
3299 }
3300
a42c55f0 3301 $parsed_updated = make_local_datetime($line["updated"], true,
64436e10 3302 $owner_uid, true);
324944f3 3303
f035e6dc
AD
3304 if (!$zoom_mode)
3305 $rv['content'] .= "<div class=\"postDate\">$parsed_updated</div>";
3de0261a
AD
3306
3307 if ($line["link"]) {
c6c010d9 3308 $rv['content'] .= "<div class='postTitle'><a target='_blank'
bf1dc420 3309 title=\"".htmlspecialchars($line['title'])."\"
8d505d78 3310 href=\"" .
5c568973 3311 htmlspecialchars($line["link"]) . "\">" .
11bd95b4
AD
3312 $line["title"] . "</a>" .
3313 "<span class='author'>$entry_author</span></div>";
3de0261a 3314 } else {
c6c010d9 3315 $rv['content'] .= "<div class='postTitle'>" . $line["title"] . "$entry_author</div>";
3de0261a
AD
3316 }
3317
ff04fe06
AD
3318 if ($zoom_mode) {
3319 $feed_title = "<a href=\"".htmlspecialchars($line["site_url"]).
3320 "\" target=\"_blank\">".
3321 htmlspecialchars($line["feed_title"])."</a>";
3322
3323 $rv['content'] .= "<div class=\"postFeedTitle\">$feed_title</div>";
3324
f035e6dc 3325 $rv['content'] .= "<div class=\"postDate\">$parsed_updated</div>";
ff04fe06 3326 }
f035e6dc 3327
84d952f1
AD
3328 $tags_str = format_tags_string($line["tags"], $id);
3329 $tags_str_full = join(", ", $line["tags"]);
0780f4f4
AD
3330
3331 if (!$tags_str_full) $tags_str_full = __("no tags");
e7544143 3332
3de0261a
AD
3333 if (!$entry_comments) $entry_comments = "&nbsp;"; # placeholder
3334
f0755b7c 3335 $rv['content'] .= "<div class='postTags' style='float : right'>
2a3b6de0 3336 <img src='images/tag.png'
e9823609 3337 class='tagsPic' alt='Tags' title='Tags'>&nbsp;";
eedfb635
AD
3338
3339 if (!$zoom_mode) {
009646d2 3340 $rv['content'] .= "<span id=\"ATSTR-$id\">$tags_str</span>
8d505d78 3341 <a title=\"".__('Edit tags for this article')."\"
31a53903 3342 href=\"#\" onclick=\"editArticleTags($id, $feed_id)\">(+)</a>";
4710e3dc 3343
0780f4f4
AD
3344 $rv['content'] .= "<div dojoType=\"dijit.Tooltip\"
3345 id=\"ATSTRTIP-$id\" connectId=\"ATSTR-$id\"
3346 position=\"below\">$tags_str_full</div>";
3347
1ffe3391 3348 foreach (PluginHost::getInstance()->get_hooks(PluginHost::HOOK_ARTICLE_BUTTON) as $p) {
19c73507 3349 $rv['content'] .= $p->hook_article_button($line);
411fe209
AD
3350 }
3351
24ecbcae
AD
3352 } else {
3353 $tags_str = strip_tags($tags_str);
009646d2 3354 $rv['content'] .= "<span id=\"ATSTR-$id\">$tags_str</span>";
eedfb635 3355 }
009646d2 3356 $rv['content'] .= "</div>";
ccb2b8dd
AD
3357 $rv['content'] .= "<div clear='both'>";
3358
1ffe3391 3359 foreach (PluginHost::getInstance()->get_hooks(PluginHost::HOOK_ARTICLE_LEFT_BUTTON) as $p) {
ccb2b8dd
AD
3360 $rv['content'] .= $p->hook_article_left_button($line);
3361 }
3362
3363 $rv['content'] .= "$entry_comments</div>";
3de0261a 3364
ef83538d
AD
3365 if ($line["orig_feed_id"]) {
3366
a42c55f0 3367 $tmp_result = db_query("SELECT * FROM ttrss_archived_feeds
ef83538d
AD
3368 WHERE id = ".$line["orig_feed_id"]);
3369
3370 if (db_num_rows($tmp_result) != 0) {
3371
009646d2
AD
3372 $rv['content'] .= "<div clear='both'>";
3373 $rv['content'] .= __("Originally from:");
ef83538d 3374
009646d2 3375 $rv['content'] .= "&nbsp;";
ef83538d
AD
3376
3377 $tmp_line = db_fetch_assoc($tmp_result);
3378
009646d2 3379 $rv['content'] .= "<a target='_blank'
ef83538d
AD
3380 href=' " . htmlspecialchars($tmp_line['site_url']) . "'>" .
3381 $tmp_line['title'] . "</a>";
3382
009646d2 3383 $rv['content'] .= "&nbsp;";
ef83538d 3384
009646d2 3385 $rv['content'] .= "<a target='_blank' href='" . htmlspecialchars($tmp_line['feed_url']) . "'>";
c2167866 3386 $rv['content'] .= "<img title='".__('Feed URL')."'class='tinyFeedIcon' src='images/pub_set.svg'></a>";
ef83538d 3387
009646d2 3388 $rv['content'] .= "</div>";
ef83538d
AD
3389 }
3390 }
3391
009646d2 3392 $rv['content'] .= "</div>";
3de0261a 3393
009646d2 3394 $rv['content'] .= "<div id=\"POSTNOTE-$id\">";
c7e51de1 3395 if ($line['note']) {
16cbc19a 3396 $rv['content'] .= format_article_note($id, $line['note'], !$zoom_mode);
c7e51de1 3397 }
009646d2 3398 $rv['content'] .= "</div>";
c7e51de1 3399
07eb3658
AD
3400 if (!$line['lang']) $line['lang'] = 'en';
3401
6b461797 3402 $rv['content'] .= "<div class=\"postContent\" lang=\"".$line['lang']."\">";
741b6090 3403
84d952f1 3404 $rv['content'] .= $line["content"];
a42c55f0 3405 $rv['content'] .= format_article_enclosures($id,
60376e9d
TE
3406 sql_bool_to_bool($line["always_display_enclosures"]),
3407 $line["content"],
3408 sql_bool_to_bool($line["hide_images"]));
ce53e200 3409
009646d2 3410 $rv['content'] .= "</div>";
dad14b51 3411
009646d2 3412 $rv['content'] .= "</div>";
3de0261a
AD
3413
3414 }
3415
009646d2
AD
3416 if ($zoom_mode) {
3417 $rv['content'] .= "
b87a625c 3418 <div class='footer'>
2ae69126
AD
3419 <button onclick=\"return window.close()\">".
3420 __("Close this window")."</button></div>";
009646d2 3421 $rv['content'] .= "</body></html>";
eedfb635 3422 }
3de0261a 3423
009646d2
AD
3424 return $rv;
3425
3de0261a
AD
3426 }
3427
79178062 3428 function print_checkpoint($n, $s) {
fa9e88c3 3429 $ts = microtime(true);
f8a25082 3430 echo sprintf("<!-- CP[$n] %.4f seconds -->\n", $ts - $s);
79178062
AD
3431 return $ts;
3432 }
3de0261a 3433
79178062
AD
3434 function sanitize_tag($tag) {
3435 $tag = trim($tag);
52d7e7da 3436
79178062 3437 $tag = mb_strtolower($tag, 'utf-8');
bd202c3f 3438
79178062 3439 $tag = preg_replace('/[\'\"\+\>\<]/', "", $tag);
46921916 3440
79178062
AD
3441// $tag = str_replace('"', "", $tag);
3442// $tag = str_replace("+", " ", $tag);
3443 $tag = str_replace("technorati tag: ", "", $tag);
961f4c73 3444
79178062
AD
3445 return $tag;
3446 }
3de0261a 3447
79178062 3448 function get_self_url_prefix() {
51cc3873
AD
3449 if (strrpos(SELF_URL_PATH, "/") === strlen(SELF_URL_PATH)-1) {
3450 return substr(SELF_URL_PATH, 0, strlen(SELF_URL_PATH)-1);
3451 } else {
3452 return SELF_URL_PATH;
3453 }
79178062 3454 }
a9bcfb8f 3455
45004d43
AD
3456 /**
3457 * Compute the Mozilla Firefox feed adding URL from server HOST and REQUEST_URI.
3458 *
3459 * @return string The Mozilla Firefox feed adding URL.
3460 */
3461 function add_feed_url() {
ed102aa0
AD
3462 //$url_path = ($_SERVER['HTTPS'] != "on" ? 'http://' : 'https://') . $_SERVER["HTTP_HOST"] . parse_url($_SERVER["REQUEST_URI"], PHP_URL_PATH);
3463
3464 $url_path = get_self_url_prefix() .
97acbaf1 3465 "/public.php?op=subscribe&feed_url=%s";
755a43ee 3466 return $url_path;
45004d43
AD
3467 } // function add_feed_url
3468
e90053fe
AD
3469 function encrypt_password($pass, $salt = '', $mode2 = false) {
3470 if ($salt && $mode2) {
3471 return "MODE2:" . hash('sha256', $salt . $pass);
3472 } else if ($salt) {
3473 return "SHA1X:" . sha1("$salt:$pass");
1a9f4d3c
AD
3474 } else {
3475 return "SHA1:" . sha1($pass);
3476 }
45004d43
AD
3477 } // function encrypt_password
3478
a42c55f0 3479 function load_filters($feed_id, $owner_uid, $action_id = false) {
fee840fb
AD
3480 $filters = array();
3481
a42c55f0 3482 $cat_id = (int)getFeedCategory($feed_id);
fee840fb 3483
34e55fe8
AD
3484 if ($cat_id == 0)
3485 $null_cat_qpart = "cat_id IS NULL OR";
3486 else
3487 $null_cat_qpart = "";
3488
a42c55f0 3489 $result = db_query("SELECT * FROM ttrss_filters2 WHERE
8e8c8934 3490 owner_uid = $owner_uid AND enabled = true ORDER BY order_id, title");
8d505d78 3491
67bd0b1f 3492 $check_cats = join(",", array_merge(
a42c55f0 3493 getParentCategories($cat_id, $owner_uid),
67bd0b1f
AD
3494 array($cat_id)));
3495
0e4a7d7a 3496 while ($line = db_fetch_assoc($result)) {
6aff7845
AD
3497 $filter_id = $line["id"];
3498
a42c55f0 3499 $result2 = db_query("SELECT
a3a896a1 3500 r.reg_exp, r.inverse, r.feed_id, r.cat_id, r.cat_filter, t.name AS type_name
6aff7845
AD
3501 FROM ttrss_filters2_rules AS r,
3502 ttrss_filter_types AS t
3503 WHERE
34e55fe8 3504 ($null_cat_qpart (cat_id IS NULL AND cat_filter = false) OR cat_id IN ($check_cats)) AND
6aff7845
AD
3505 (feed_id IS NULL OR feed_id = '$feed_id') AND
3506 filter_type = t.id AND filter_id = '$filter_id'");
3507
3508 $rules = array();
3509 $actions = array();
ba975b2e 3510
6aff7845
AD
3511 while ($rule_line = db_fetch_assoc($result2)) {
3512# print_r($rule_line);
8d505d78 3513
6aff7845
AD
3514 $rule = array();
3515 $rule["reg_exp"] = $rule_line["reg_exp"];
3516 $rule["type"] = $rule_line["type_name"];
a3a896a1 3517 $rule["inverse"] = sql_bool_to_bool($rule_line["inverse"]);
6aff7845
AD
3518
3519 array_push($rules, $rule);
3520 }
3521
a42c55f0 3522 $result2 = db_query("SELECT a.action_param,t.name AS type_name
6aff7845
AD
3523 FROM ttrss_filters2_actions AS a,
3524 ttrss_filter_actions AS t
3525 WHERE
3526 action_id = t.id AND filter_id = '$filter_id'");
3527
3528 while ($action_line = db_fetch_assoc($result2)) {
3529# print_r($action_line);
3530
3531 $action = array();
3532 $action["type"] = $action_line["type_name"];
3533 $action["param"] = $action_line["action_param"];
3534
3535 array_push($actions, $action);
0e4a7d7a 3536 }
b8ffa322 3537
b8ffa322 3538
6aff7845
AD
3539 $filter = array();
3540 $filter["match_any_rule"] = sql_bool_to_bool($line["match_any_rule"]);
a3a896a1 3541 $filter["inverse"] = sql_bool_to_bool($line["inverse"]);
6aff7845
AD
3542 $filter["rules"] = $rules;
3543 $filter["actions"] = $actions;
3544
3545 if (count($rules) > 0 && count($actions) > 0) {
3546 array_push($filters, $filter);
3547 }
3548 }
3549
0e4a7d7a 3550 return $filters;
fee840fb 3551 }
1e36af0c
AD
3552
3553 function get_score_pic($score) {
8d505d78
AD
3554 if ($score > 100) {
3555 return "score_high.png";
3556 } else if ($score > 0) {
883fee8d 3557 return "score_half_high.png";
1cce3aca 3558 } else if ($score < -100) {
883fee8d 3559 return "score_low.png";
1cce3aca 3560 } else if ($score < 0) {
883fee8d 3561 return "score_half_low.png";
8d505d78 3562 } else {
883fee8d 3563 return "score_neutral.png";
1e36af0c
AD
3564 }
3565 }
ec92c9d1 3566
7defa089
AD
3567 function feed_has_icon($id) {
3568 return is_file(ICONS_DIR . "/$id.ico") && filesize(ICONS_DIR . "/$id.ico") > 0;
3569 }
f29ba148 3570
6322ac79 3571 function init_plugins() {
1ffe3391 3572 PluginHost::getInstance()->load(PLUGINS, PluginHost::KIND_ALL);
19c73507 3573
ba68b681 3574 return true;
f29ba148 3575 }
5e96ca9d 3576
307d187c 3577 function format_tags_string($tags, $id) {
54b7590c
AD
3578 if (!is_array($tags) || count($tags) == 0) {
3579 return __("no tags");
3580 } else {
3581 $maxtags = min(5, count($tags));
307d187c 3582
54b7590c 3583 for ($i = 0; $i < $maxtags; $i++) {
67f4fe17 3584 $tags_str .= "<a class=\"tag\" href=\"#\" onclick=\"viewfeed('".$tags[$i]."')\">" . $tags[$i] . "</a>, ";
307d187c 3585 }
307d187c 3586
54b7590c 3587 $tags_str = mb_substr($tags_str, 0, mb_strlen($tags_str)-2);
307d187c 3588
54b7590c
AD
3589 if (count($tags) > $maxtags)
3590 $tags_str .= ", &hellip;";
307d187c 3591
54b7590c 3592 return $tags_str;
307d187c 3593 }
307d187c 3594 }
2eb9c95c
AD
3595
3596 function format_article_labels($labels, $id) {
3597
c35d0d8f 3598 if (!is_array($labels)) return '';
76e087b0 3599
2eb9c95c
AD
3600 $labels_str = "";
3601
3602 foreach ($labels as $l) {
8d505d78 3603 $labels_str .= sprintf("<span class='hlLabelRef'
2eb9c95c
AD
3604 style='color : %s; background-color : %s'>%s</span>",
3605 $l[2], $l[3], $l[1]);
3606 }
3607
3608 return $labels_str;
3609
3610 }
c7e51de1 3611
16cbc19a 3612 function format_article_note($id, $note, $allow_edit = true) {
c7e51de1 3613
fcfa9ef1
AD
3614 $str = "<div class='articleNote' onclick=\"editArticleNote($id)\">
3615 <div class='noteEdit' onclick=\"editArticleNote($id)\">".
16cbc19a 3616 ($allow_edit ? __('(edit note)') : "")."</div>$note</div>";
c7e51de1
AD
3617
3618 return $str;
3619 }
7f969260 3620
7e329f13 3621
a42c55f0 3622 function get_feed_category($feed_cat, $parent_cat_id = false) {
d2a317e3
AD
3623 if ($parent_cat_id) {
3624 $parent_qpart = "parent_cat = '$parent_cat_id'";
3625 $parent_insert = "'$parent_cat_id'";
3626 } else {
3627 $parent_qpart = "parent_cat IS NULL";
3628 $parent_insert = "NULL";
3629 }
3630
6322ac79 3631 $result = db_query(
d2a317e3
AD
3632 "SELECT id FROM ttrss_feed_categories
3633 WHERE $parent_qpart AND title = '$feed_cat' AND owner_uid = ".$_SESSION["uid"]);
3634
3635 if (db_num_rows($result) == 0) {
3636 return false;
3637 } else {
3638 return db_fetch_result($result, 0, "id");
3639 }
3640 }
3641
a42c55f0 3642 function add_feed_category($feed_cat, $parent_cat_id = false) {
c00907f2
AD
3643
3644 if (!$feed_cat) return false;
3645
a42c55f0 3646 db_query("BEGIN");
5c7c7da9 3647
d2a317e3
AD
3648 if ($parent_cat_id) {
3649 $parent_qpart = "parent_cat = '$parent_cat_id'";
3650 $parent_insert = "'$parent_cat_id'";
3651 } else {
3652 $parent_qpart = "parent_cat IS NULL";
3653 $parent_insert = "NULL";
3654 }
3655
129562e0
AD
3656 $feed_cat = mb_substr($feed_cat, 0, 250);
3657
6322ac79 3658 $result = db_query(
5c7c7da9 3659 "SELECT id FROM ttrss_feed_categories
d2a317e3 3660 WHERE $parent_qpart AND title = '$feed_cat' AND owner_uid = ".$_SESSION["uid"]);
5c7c7da9
AD
3661
3662 if (db_num_rows($result) == 0) {
8d505d78 3663
6322ac79 3664 $result = db_query(
d2a317e3
AD
3665 "INSERT INTO ttrss_feed_categories (owner_uid,title,parent_cat)
3666 VALUES ('".$_SESSION["uid"]."', '$feed_cat', $parent_insert)");
5c7c7da9 3667
a42c55f0 3668 db_query("COMMIT");
5c7c7da9
AD
3669
3670 return true;
3671 }
3672
3673 return false;
8d505d78 3674 }
5c7c7da9 3675
a42c55f0
AD
3676 function getArticleFeed($id) {
3677 $result = db_query("SELECT feed_id FROM ttrss_user_entries
a545dc31 3678 WHERE ref_id = '$id' AND owner_uid = " . $_SESSION["uid"]);
ab197ae1
AD
3679
3680 if (db_num_rows($result) != 0) {
3681 return db_fetch_result($result, 0, "feed_id");
3682 } else {
3683 return 0;
3684 }
3685 }
a5819bb3 3686
f2c6c008
CW
3687 /**
3688 * Fixes incomplete URLs by prepending "http://".
f0266f51
CW
3689 * Also replaces feed:// with http://, and
3690 * prepends a trailing slash if the url is a domain name only.
f2c6c008
CW
3691 *
3692 * @param string $url Possibly incomplete URL
3693 *
3694 * @return string Fixed URL.
3695 */
3696 function fix_url($url) {
3697 if (strpos($url, '://') === false) {
3698 $url = 'http://' . $url;
f0266f51
CW
3699 } else if (substr($url, 0, 5) == 'feed:') {
3700 $url = 'http:' . substr($url, 5);
3701 }
3702
3703 //prepend slash if the URL has no slash in it
3704 // "http://www.example" -> "http://www.example/"
44453773 3705 if (strpos($url, '/', strpos($url, ':') + 3) === false) {
f0266f51 3706 $url .= '/';
f2c6c008 3707 }
ec39a02c
AD
3708
3709 if ($url != "http:///")
3710 return $url;
3711 else
3712 return '';
f2c6c008
CW
3713 }
3714
a5819bb3
AD
3715 function validate_feed_url($url) {
3716 $parts = parse_url($url);
3717
3718 return ($parts['scheme'] == 'http' || $parts['scheme'] == 'feed' || $parts['scheme'] == 'https');
3719
3720 }
d9084cf2 3721
a42c55f0 3722 function get_article_enclosures($id) {
be35798b 3723
8d505d78 3724 $query = "SELECT * FROM ttrss_enclosures
be35798b
AD
3725 WHERE post_id = '$id' AND content_url != ''";
3726
be35798b
AD
3727 $rv = array();
3728
a42c55f0 3729 $result = db_query($query);
be35798b 3730
0e4a7d7a
AD
3731 if (db_num_rows($result) > 0) {
3732 while ($line = db_fetch_assoc($result)) {
3733 array_push($rv, $line);
be35798b
AD
3734 }
3735 }
3736
3737 return $rv;
3738 }
3739
a42c55f0 3740 function save_email_address($email) {
31a53903
AD
3741 // FIXME: implement persistent storage of emails
3742
8d505d78 3743 if (!$_SESSION['stored_emails'])
31a53903
AD
3744 $_SESSION['stored_emails'] = array();
3745
3746 if (!in_array($email, $_SESSION['stored_emails']))
3747 array_push($_SESSION['stored_emails'], $email);
3748 }
8801fb01 3749
8801fb01 3750
a42c55f0 3751 function get_feed_access_key($feed_id, $is_cat, $owner_uid = false) {
8801fb01
AD
3752
3753 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
3754
3755 $sql_is_cat = bool_to_sql_bool($is_cat);
3756
a42c55f0 3757 $result = db_query("SELECT access_key FROM ttrss_access_keys
8d505d78 3758 WHERE feed_id = '$feed_id' AND is_cat = $sql_is_cat
8801fb01
AD
3759 AND owner_uid = " . $owner_uid);
3760
3761 if (db_num_rows($result) == 1) {
3762 return db_fetch_result($result, 0, "access_key");
3763 } else {
4c63934b 3764 $key = db_escape_string(uniqid(base_convert(rand(), 10, 36)));
8801fb01 3765
a42c55f0 3766 $result = db_query("INSERT INTO ttrss_access_keys
8801fb01
AD
3767 (access_key, feed_id, is_cat, owner_uid)
3768 VALUES ('$key', '$feed_id', $sql_is_cat, '$owner_uid')");
3769
3770 return $key;
3771 }
3772 return false;
3773 }
f0266f51 3774
759e5132 3775 function get_feeds_from_html($url, $content)
f0266f51
CW
3776 {
3777 $url = fix_url($url);
3778 $baseUrl = substr($url, 0, strrpos($url, '/') + 1);
3779
fb074239
AD
3780 libxml_use_internal_errors(true);
3781
f0266f51 3782 $doc = new DOMDocument();
8d505d78 3783 $doc->loadHTML($content);
f0266f51
CW
3784 $xpath = new DOMXPath($doc);
3785 $entries = $xpath->query('/html/head/link[@rel="alternate"]');
3786 $feedUrls = array();
3787 foreach ($entries as $entry) {
3788 if ($entry->hasAttribute('href')) {
3789 $title = $entry->getAttribute('title');
3790 if ($title == '') {
3791 $title = $entry->getAttribute('type');
3792 }
923818fc
CW
3793 $feedUrl = rewrite_relative_url(
3794 $baseUrl, $entry->getAttribute('href')
3795 );
f0266f51
CW
3796 $feedUrls[$feedUrl] = $title;
3797 }
3798 }
3799 return $feedUrls;
3800 }
3801
759e5132 3802 function is_html($content) {
32b86711 3803 return preg_match("/<html|DOCTYPE html/i", substr($content, 0, 20)) !== 0;
759e5132 3804 }
f33479da 3805
759e5132
AD
3806 function url_is_html($url, $login = false, $pass = false) {
3807 return is_html(fetch_file_contents($url, false, $login, $pass));
f33479da 3808 }
24e2bb3a 3809
a42c55f0 3810 function print_label_select($name, $value, $attributes = "") {
24e2bb3a 3811
a42c55f0 3812 $result = db_query("SELECT caption FROM ttrss_labels2
24e2bb3a
AD
3813 WHERE owner_uid = '".$_SESSION["uid"]."' ORDER BY caption");
3814
8d505d78 3815 print "<select default=\"$value\" name=\"" . htmlspecialchars($name) .
d90868d7 3816 "\" $attributes onchange=\"labelSelectOnChange(this)\" >";
24e2bb3a
AD
3817
3818 while ($line = db_fetch_assoc($result)) {
3819
3820 $issel = ($line["caption"] == $value) ? "selected=\"1\"" : "";
3821
d90868d7
AD
3822 print "<option value=\"".htmlspecialchars($line["caption"])."\"
3823 $issel>" . htmlspecialchars($line["caption"]) . "</option>";
24e2bb3a
AD
3824
3825 }
3826
d90868d7 3827# print "<option value=\"ADD_LABEL\">" .__("Add label...") . "</option>";
24e2bb3a
AD
3828
3829 print "</select>";
3830
3831
3832 }
3833
a42c55f0 3834 function format_article_enclosures($id, $always_display_enclosures,
33de3d37 3835 $article_content, $hide_images = false) {
dad14b51 3836
a42c55f0 3837 $result = get_article_enclosures($id);
009646d2 3838 $rv = '';
8d505d78 3839
dad14b51 3840 if (count($result) > 0) {
8d505d78 3841
dad14b51
AD
3842 $entries_html = array();
3843 $entries = array();
ca3bca99 3844 $entries_inline = array();
8d505d78 3845
dad14b51 3846 foreach ($result as $line) {
8d505d78 3847
dad14b51
AD
3848 $url = $line["content_url"];
3849 $ctype = $line["content_type"];
5c54e683 3850 $title = $line["title"];
8d505d78 3851
dad14b51 3852 if (!$ctype) $ctype = __("unknown type");
8d505d78 3853
749b56bd 3854 $filename = substr($url, strrpos($url, "/")+1);
8d505d78 3855
a42c55f0 3856 $player = format_inline_player($url, $ctype);
ca3bca99
AD
3857
3858 if ($player) array_push($entries_inline, $player);
8d505d78 3859
c3edc667
AD
3860# $entry .= " <a target=\"_blank\" href=\"" . htmlspecialchars($url) . "\">" .
3861# $filename . " (" . $ctype . ")" . "</a>";
8d505d78 3862
749b56bd
AD
3863 $entry = "<div onclick=\"window.open('".htmlspecialchars($url)."')\"
3864 dojoType=\"dijit.MenuItem\">$filename ($ctype)</div>";
3865
dad14b51 3866 array_push($entries_html, $entry);
8d505d78 3867
dad14b51 3868 $entry = array();
8d505d78 3869
dad14b51
AD
3870 $entry["type"] = $ctype;
3871 $entry["filename"] = $filename;
3872 $entry["url"] = $url;
5c54e683 3873 $entry["title"] = $title;
8d505d78 3874
dad14b51
AD
3875 array_push($entries, $entry);
3876 }
8d505d78 3877
a42c55f0 3878 if ($_SESSION['uid'] && !get_pref("STRIP_IMAGES") && !$_SESSION["bw_limit"]) {
dad14b51
AD
3879 if ($always_display_enclosures ||
3880 !preg_match("/<img/i", $article_content)) {
8d505d78 3881
dad14b51 3882 foreach ($entries as $entry) {
8d505d78 3883
dad14b51
AD
3884 if (preg_match("/image/", $entry["type"]) ||
3885 preg_match("/\.(jpg|png|gif|bmp)/i", $entry["filename"])) {
8d505d78 3886
33de3d37
AD
3887 if (!$hide_images) {
3888 $rv .= "<p><img
3889 alt=\"".htmlspecialchars($entry["filename"])."\"
3890 src=\"" .htmlspecialchars($entry["url"]) . "\"/></p>";
3891 } else {
3892 $rv .= "<p><a target=\"_blank\"
3893 href=\"".htmlspecialchars($entry["url"])."\"
3894 >" .htmlspecialchars($entry["url"]) . "</a></p>";
5c54e683 3895 }
749b56bd 3896
5c54e683
AD
3897 if ($entry['title']) {
3898 $rv.= "<div class=\"enclosure_title\">${entry['title']}</div>";
33de3d37 3899 }
dad14b51
AD
3900 }
3901 }
3902 }
3903 }
8d505d78 3904
ca3bca99
AD
3905 if (count($entries_inline) > 0) {
3906 $rv .= "<hr clear='both'/>";
3907 foreach ($entries_inline as $entry) { $rv .= $entry; };
3908 $rv .= "<hr clear='both'/>";
3909 }
3910
bf6df236 3911 $rv .= "<select class=\"attachments\" onchange=\"openSelectedAttachment(this)\">".
f9432f26 3912 "<option value=''>" . __('Attachments')."</option>";
8d505d78 3913
f9432f26 3914 foreach ($entries as $entry) {
5c54e683
AD
3915 if ($entry["title"])
3916 $title = "&mdash; " . truncate_string($entry["title"], 30);
3917 else
3918 $title = "";
3919
3920 $rv .= "<option value=\"".htmlspecialchars($entry["url"])."\">" . htmlspecialchars($entry["filename"]) . "$title</option>";
8d505d78 3921
f9432f26
AD
3922 };
3923
3924 $rv .= "</select>";
dad14b51 3925 }
009646d2
AD
3926
3927 return $rv;
dad14b51
AD
3928 }
3929
6322ac79 3930 function getLastArticleId() {
a42c55f0 3931 $result = db_query("SELECT MAX(ref_id) AS id FROM ttrss_user_entries
f8fb4498
AD
3932 WHERE owner_uid = " . $_SESSION["uid"]);
3933
3934 if (db_num_rows($result) == 1) {
3935 return db_fetch_result($result, 0, "id");
3936 } else {
3937 return -1;
3938 }
3939 }
8cc3c778
AD
3940
3941 function build_url($parts) {
3942 return $parts['scheme'] . "://" . $parts['host'] . $parts['path'];
3943 }
3944
f679105c
CW
3945 /**
3946 * Converts a (possibly) relative URL to a absolute one.
3947 *
3948 * @param string $url Base URL (i.e. from where the document is)
3949 * @param string $rel_url Possibly relative URL in the document
3950 *
3951 * @return string Absolute URL
3952 */
8cc3c778 3953 function rewrite_relative_url($url, $rel_url) {
c722c0be 3954 if (strpos($rel_url, ":") !== false) {
b4520bb8
AD
3955 return $rel_url;
3956 } else if (strpos($rel_url, "://") !== false) {
8cc3c778 3957 return $rel_url;
f9052d35 3958 } else if (strpos($rel_url, "//") === 0) {
3959 # protocol-relative URL (rare but they exist)
3960 return $rel_url;
8d505d78 3961 } else if (strpos($rel_url, "/") === 0)
8cc3c778
AD
3962 {
3963 $parts = parse_url($url);
3964 $parts['path'] = $rel_url;
3965
3966 return build_url($parts);
3967
3968 } else {
3969 $parts = parse_url($url);
f679105c
CW
3970 if (!isset($parts['path'])) {
3971 $parts['path'] = '/';
3972 }
3973 $dir = $parts['path'];
3974 if (substr($dir, -1) !== '/') {
3975 $dir = dirname($parts['path']);
3976 $dir !== '/' && $dir .= '/';
3977 }
3978 $parts['path'] = $dir . $rel_url;
8cc3c778
AD
3979
3980 return build_url($parts);
3981 }
3982 }
3983
e4f7f8df 3984 function sphinx_search($query, $offset = 0, $limit = 30) {
030b2a31 3985 require_once 'lib/sphinxapi.php';
31303c6b 3986
e4f7f8df
AD
3987 $sphinxClient = new SphinxClient();
3988
52803a0b
AD
3989 $sphinxpair = explode(":", SPHINX_SERVER, 2);
3990
7c01db43 3991 $sphinxClient->SetServer($sphinxpair[0], (int)$sphinxpair[1]);
e4f7f8df
AD
3992 $sphinxClient->SetConnectTimeout(1);
3993
8d505d78 3994 $sphinxClient->SetFieldWeights(array('title' => 70, 'content' => 30,
e4f7f8df
AD
3995 'feed_title' => 20));
3996
3997 $sphinxClient->SetMatchMode(SPH_MATCH_EXTENDED2);
3998 $sphinxClient->SetRankingMode(SPH_RANK_PROXIMITY_BM25);
3999 $sphinxClient->SetLimits($offset, $limit, 1000);
4000 $sphinxClient->SetArrayResult(false);
4001 $sphinxClient->SetFilter('owner_uid', array($_SESSION['uid']));
8d505d78 4002
e4f7f8df
AD
4003 $result = $sphinxClient->Query($query, SPHINX_INDEX);
4004
4005 $ids = array();
4006
4007 if (is_array($result['matches'])) {
4008 foreach (array_keys($result['matches']) as $int_id) {
4009 $ref_id = $result['matches'][$int_id]['attrs']['ref_id'];
4010 array_push($ids, $ref_id);
4011 }
4012 }
4013
4014 return $ids;
4015 }
4016
a42c55f0 4017 function cleanup_tags($days = 14, $limit = 1000) {
868650e4
AD
4018
4019 if (DB_TYPE == "pgsql") {
4020 $interval_query = "date_updated < NOW() - INTERVAL '$days days'";
4021 } else if (DB_TYPE == "mysql") {
4022 $interval_query = "date_updated < DATE_SUB(NOW(), INTERVAL $days DAY)";
4023 }
4024
b5ec13fa 4025 $tags_deleted = 0;
868650e4 4026
b5ec13fa
AD
4027 while ($limit > 0) {
4028 $limit_part = 500;
4029
8d505d78
AD
4030 $query = "SELECT ttrss_tags.id AS id
4031 FROM ttrss_tags, ttrss_user_entries, ttrss_entries
b5ec13fa
AD
4032 WHERE post_int_id = int_id AND $interval_query AND
4033 ref_id = ttrss_entries.id AND tag_cache != '' LIMIT $limit_part";
8d505d78 4034
a42c55f0 4035 $result = db_query($query);
b5ec13fa
AD
4036
4037 $ids = array();
4038
4039 while ($line = db_fetch_assoc($result)) {
4040 array_push($ids, $line['id']);
4041 }
4042
4043 if (count($ids) > 0) {
4044 $ids = join(",", $ids);
b5ec13fa 4045
a42c55f0
AD
4046 $tmp_result = db_query("DELETE FROM ttrss_tags WHERE id IN ($ids)");
4047 $tags_deleted += db_affected_rows($tmp_result);
b5ec13fa
AD
4048 } else {
4049 break;
4050 }
4051
4052 $limit -= $limit_part;
4053 }
4054
b5ec13fa 4055 return $tags_deleted;
868650e4
AD
4056 }
4057
6322ac79 4058 function print_user_stylesheet() {
a42c55f0 4059 $value = get_pref('USER_STYLESHEET');
88e4e597
AD
4060
4061 if ($value) {
4062 print "<style type=\"text/css\">";
5823f9fb 4063 print str_replace("<br/>", "\n", $value);
88e4e597
AD
4064 print "</style>";
4065 }
4066
4067 }
4068
a42c55f0 4069 function filter_to_sql($filter, $owner_uid) {
4e02f582 4070 $query = array();
36184020 4071
4e02f582
AD
4072 if (DB_TYPE == "pgsql")
4073 $reg_qpart = "~";
4074 else
4075 $reg_qpart = "REGEXP";
36184020 4076
4e02f582 4077 foreach ($filter["rules"] AS $rule) {
4cb2c550 4078 $rule['reg_exp'] = str_replace('/', '\/', $rule["reg_exp"]);
4e02f582
AD
4079 $regexp_valid = preg_match('/' . $rule['reg_exp'] . '/',
4080 $rule['reg_exp']) !== FALSE;
36184020 4081
4e02f582 4082 if ($regexp_valid) {
36184020 4083
a42c55f0 4084 $rule['reg_exp'] = db_escape_string($rule['reg_exp']);
36184020 4085
a3a896a1 4086 switch ($rule["type"]) {
4e02f582
AD
4087 case "title":
4088 $qpart = "LOWER(ttrss_entries.title) $reg_qpart LOWER('".
4089 $rule['reg_exp'] . "')";
4090 break;
4091 case "content":
4092 $qpart = "LOWER(ttrss_entries.content) $reg_qpart LOWER('".
4093 $rule['reg_exp'] . "')";
4094 break;
4095 case "both":
4096 $qpart = "LOWER(ttrss_entries.title) $reg_qpart LOWER('".
4097 $rule['reg_exp'] . "') OR LOWER(" .
4098 "ttrss_entries.content) $reg_qpart LOWER('" . $rule['reg_exp'] . "')";
4099 break;
4100 case "tag":
4101 $qpart = "LOWER(ttrss_user_entries.tag_cache) $reg_qpart LOWER('".
4102 $rule['reg_exp'] . "')";
4103 break;
4104 case "link":
4105 $qpart = "LOWER(ttrss_entries.link) $reg_qpart LOWER('".
4106 $rule['reg_exp'] . "')";
4107 break;
4108 case "author":
4109 $qpart = "LOWER(ttrss_entries.author) $reg_qpart LOWER('".
4110 $rule['reg_exp'] . "')";
4111 break;
4112 }
36184020 4113
ec1f8a3d
AD
4114 if (isset($rule['inverse'])) $qpart = "NOT ($qpart)";
4115
6b218731 4116 if (isset($rule["feed_id"]) && $rule["feed_id"] > 0) {
a42c55f0 4117 $qpart .= " AND feed_id = " . db_escape_string($rule["feed_id"]);
4e02f582 4118 }
6b8b3af8 4119
4e02f582 4120 if (isset($rule["cat_id"])) {
2680295b
AD
4121
4122 if ($rule["cat_id"] > 0) {
a42c55f0 4123 $children = getChildCategories($rule["cat_id"], $owner_uid);
2680295b
AD
4124 array_push($children, $rule["cat_id"]);
4125
4126 $children = join(",", $children);
4127
4128 $cat_qpart = "cat_id IN ($children)";
4129 } else {
4130 $cat_qpart = "cat_id IS NULL";
4131 }
4132
4133 $qpart .= " AND $cat_qpart";
56fbb82c 4134 }
4e02f582 4135
5d4d5918
AD
4136 $qpart .= " AND feed_id IS NOT NULL";
4137
4e02f582
AD
4138 array_push($query, "($qpart)");
4139
56fbb82c 4140 }
4e02f582 4141 }
56fbb82c 4142
4e02f582 4143 if (count($query) > 0) {
a3a896a1 4144 $fullquery = "(" . join($filter["match_any_rule"] ? "OR" : "AND", $query) . ")";
56fbb82c 4145 } else {
a3a896a1 4146 $fullquery = "(false)";
56fbb82c 4147 }
a3a896a1
AD
4148
4149 if ($filter['inverse']) $fullquery = "(NOT $fullquery)";
4150
4151 return $fullquery;
36184020 4152 }
ae5f7bb1 4153
3382bce1
AD
4154 if (!function_exists('gzdecode')) {
4155 function gzdecode($string) { // no support for 2nd argument
4156 return file_get_contents('compress.zlib://data:who/cares;base64,'.
4157 base64_encode($string));
4158 }
4159 }
4160
8db5d8ea
AD
4161 function get_random_bytes($length) {
4162 if (function_exists('openssl_random_pseudo_bytes')) {
4163 return openssl_random_pseudo_bytes($length);
4164 } else {
4165 $output = "";
4166
4167 for ($i = 0; $i < $length; $i++)
4168 $output .= chr(mt_rand(0, 255));
4169
4170 return $output;
4171 }
4172 }
871f0a7a
AD
4173
4174 function read_stdin() {
4175 $fp = fopen("php://stdin", "r");
4176
4177 if ($fp) {
4178 $line = trim(fgets($fp));
4179 fclose($fp);
4180 return $line;
4181 }
4182
4183 return null;
4184 }
e3449aa1
AD
4185
4186 function tmpdirname($path, $prefix) {
4187 // Use PHP's tmpfile function to create a temporary
4188 // directory name. Delete the file and keep the name.
4189 $tempname = tempnam($path,$prefix);
4190 if (!$tempname)
4191 return false;
4192
4193 if (!unlink($tempname))
4194 return false;
4195
4196 return $tempname;
4197 }
4198
a42c55f0
AD
4199 function getFeedCategory($feed) {
4200 $result = db_query("SELECT cat_id FROM ttrss_feeds
6aff7845
AD
4201 WHERE id = '$feed'");
4202
4203 if (db_num_rows($result) > 0) {
4204 return db_fetch_result($result, 0, "cat_id");
4205 } else {
4206 return false;
4207 }
4208
4209 }
4210
8dcb2b47
AD
4211 function implements_interface($class, $interface) {
4212 return in_array($interface, class_implements($class));
4213 }
e88c1943 4214
fe61dc18
AD
4215 function geturl($url, $depth = 0){
4216
4217 if ($depth == 20) return $url;
e2b0054b 4218
3f6f0857
AD
4219 if (!function_exists('curl_init'))
4220 return user_error('CURL Must be installed for geturl function to work. Ask your host to enable it or uncomment extension=php_curl.dll in php.ini', E_USER_ERROR);
e2b0054b
AD
4221
4222 $curl = curl_init();
4223 $header[0] = "Accept: text/xml,application/xml,application/xhtml+xml,";
4224 $header[0] .= "text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5";
4225 $header[] = "Cache-Control: max-age=0";
4226 $header[] = "Connection: keep-alive";
4227 $header[] = "Keep-Alive: 300";
4228 $header[] = "Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7";
4229 $header[] = "Accept-Language: en-us,en;q=0.5";
4230 $header[] = "Pragma: ";
4231
4232 curl_setopt($curl, CURLOPT_URL, $url);
4233 curl_setopt($curl, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 5.1; rv:5.0) Gecko/20100101 Firefox/5.0 Firefox/5.0');
4234 curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
4235 curl_setopt($curl, CURLOPT_HEADER, true);
4236 curl_setopt($curl, CURLOPT_REFERER, $url);
4237 curl_setopt($curl, CURLOPT_ENCODING, 'gzip,deflate');
4238 curl_setopt($curl, CURLOPT_AUTOREFERER, true);
4239 curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
4240 //curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true); //CURLOPT_FOLLOWLOCATION Disabled...
4241 curl_setopt($curl, CURLOPT_TIMEOUT, 60);
40a35a62 4242 curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
e2b0054b 4243
05f14a7d
AD
4244 if (defined('_CURL_HTTP_PROXY')) {
4245 curl_setopt($curl, CURLOPT_PROXY, _CURL_HTTP_PROXY);
4246 }
4247
aefed7f7
AD
4248 if ((OPENSSL_VERSION_NUMBER >= 0x0090808f) && (OPENSSL_VERSION_NUMBER < 0x10000000)) {
4249 curl_setopt($curl, CURLOPT_SSLVERSION, 3);
4250 }
4251
e2b0054b
AD
4252 $html = curl_exec($curl);
4253
4254 $status = curl_getinfo($curl);
e2b0054b
AD
4255
4256 if($status['http_code']!=200){
4257 if($status['http_code'] == 301 || $status['http_code'] == 302) {
e2b4c0b7 4258 curl_close($curl);
e2b0054b
AD
4259 list($header) = explode("\r\n\r\n", $html, 2);
4260 $matches = array();
4261 preg_match("/(Location:|URI:)[^(\n)]*/", $header, $matches);
4262 $url = trim(str_replace($matches[1],"",$matches[0]));
4263 $url_parsed = parse_url($url);
fe61dc18 4264 return (isset($url_parsed))? geturl($url, $depth + 1):'';
e2b0054b 4265 }
e2b4c0b7
RH
4266
4267 global $fetch_last_error;
4268
4269 $fetch_last_error = curl_errno($curl) . " " . curl_error($curl);
4270 curl_close($curl);
4271
e2b0054b
AD
4272 $oline='';
4273 foreach($status as $key=>$eline){$oline.='['.$key.']'.$eline.' ';}
4274 $line =$oline." \r\n ".$url."\r\n-----------------\r\n";
911845b5
AD
4275# $handle = @fopen('./curl.error.log', 'a');
4276# fwrite($handle, $line);
e2b0054b
AD
4277 return FALSE;
4278 }
e2b4c0b7 4279 curl_close($curl);
e2b0054b
AD
4280 return $url;
4281 }
8dcb2b47 4282
c670a80d
AD
4283 function get_minified_js($files) {
4284 require_once 'lib/jshrink/Minifier.php';
4285
4286 $rv = '';
4287
4288 foreach ($files as $js) {
4289 if (!isset($_GET['debug'])) {
32011b9b 4290 $cached_file = CACHE_DIR . "/js/".basename($js).".js";
c670a80d
AD
4291
4292 if (file_exists($cached_file) &&
4293 is_readable($cached_file) &&
4294 filemtime($cached_file) >= filemtime("js/$js.js")) {
4295
4296 $rv .= file_get_contents($cached_file);
4297
4298 } else {
4299 $minified = JShrink\Minifier::minify(file_get_contents("js/$js.js"));
4300 file_put_contents($cached_file, $minified);
4301 $rv .= $minified;
4302 }
4303 } else {
4304 $rv .= file_get_contents("js/$js.js");
4305 }
4306 }
4307
4308 return $rv;
4309 }
4310
b5d4716a
AD
4311 function stylesheet_tag($filename) {
4312 $timestamp = filemtime($filename);
4313
cdbcb277 4314 return "<link rel=\"stylesheet\" type=\"text/css\" href=\"$filename?$timestamp\"/>\n";
b5d4716a
AD
4315 }
4316
4317 function javascript_tag($filename) {
4318 $query = "";
4319
4320 if (!(strpos($filename, "?") === FALSE)) {
4321 $query = substr($filename, strpos($filename, "?")+1);
4322 $filename = substr($filename, 0, strpos($filename, "?"));
4323 }
4324
4325 $timestamp = filemtime($filename);
4326
4327 if ($query) $timestamp .= "&$query";
4328
cdbcb277 4329 return "<script type=\"text/javascript\" charset=\"utf-8\" src=\"$filename?$timestamp\"></script>\n";
b5d4716a
AD
4330 }
4331
16314dda 4332 function calculate_dep_timestamp() {
9717d5de 4333 $files = array_merge(glob("js/*.js"), glob("css/*.css"));
16314dda
AD
4334
4335 $max_ts = -1;
4336
4337 foreach ($files as $file) {
4338 if (filemtime($file) > $max_ts) $max_ts = filemtime($file);
4339 }
4340
4341 return $max_ts;
4342 }
4343
bcbb2ec7
AD
4344 function T_js_decl($s1, $s2) {
4345 if ($s1 && $s2) {
4346 $s1 = preg_replace("/\n/", "", $s1);
4347 $s2 = preg_replace("/\n/", "", $s2);
4348
4349 $s1 = preg_replace("/\"/", "\\\"", $s1);
4350 $s2 = preg_replace("/\"/", "\\\"", $s2);
4351
4352 return "T_messages[\"$s1\"] = \"$s2\";\n";
4353 }
4354 }
4355
4356 function init_js_translations() {
4357
4358 print 'var T_messages = new Object();
4359
4360 function __(msg) {
4361 if (T_messages[msg]) {
4362 return T_messages[msg];
4363 } else {
4364 return msg;
4365 }
4366 }
4367
4368 function ngettext(msg1, msg2, n) {
da07af65 4369 return __((parseInt(n) > 1) ? msg2 : msg1);
bcbb2ec7
AD
4370 }';
4371
4372 $l10n = _get_reader();
4373
4374 for ($i = 0; $i < $l10n->total; $i++) {
4375 $orig = $l10n->get_original_string($i);
da07af65
Y
4376 if(strpos($orig, "\000") !== FALSE) { // Plural forms
4377 $key = explode(chr(0), $orig);
be5e469d 4378 print T_js_decl($key[0], _ngettext($key[0], $key[1], 1)); // Singular
4379 print T_js_decl($key[1], _ngettext($key[0], $key[1], 2)); // Plural
da07af65
Y
4380 } else {
4381 $translation = __($orig);
4382 print T_js_decl($orig, $translation);
4383 }
bcbb2ec7
AD
4384 }
4385 }
4386
f822a8e5
AD
4387 function label_to_feed_id($label) {
4388 return LABEL_BASE_INDEX - 1 - abs($label);
4389 }
4390
4391 function feed_to_label_id($feed) {
4392 return LABEL_BASE_INDEX - 1 + abs($feed);
4393 }
4394
ebec81a6
AD
4395 function format_libxml_error($error) {
4396 return T_sprintf("LibXML error %s at line %d (column %d): %s",
4397 $error->code, $error->line, $error->column,
4398 $error->message);
4399 }
4400
8c0496f7 4401?>