]> git.wh0rd.org - tt-rss.git/blame - include/functions.php
move to Article:
[tt-rss.git] / include / functions.php
CommitLineData
1d3a17c7 1<?php
6e658547 2 define('EXPECTED_CONFIG_VERSION', 26);
6497fb65 3 define('SCHEMA_VERSION', 130);
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;
cf0231f9 13 $fetch_last_error_content = false; // curl only for the time being
3f6f0857 14 $fetch_curl_used = false;
4f71d743 15 $suppress_debugging = false;
23d2471c 16
584411fe
AD
17 libxml_disable_entity_loader(true);
18
e6905f7f
AD
19 // separate test because this is included before sanity checks
20 if (function_exists("mb_internal_encoding")) mb_internal_encoding("UTF-8");
21
324944f3 22 date_default_timezone_set('UTC');
8a7f5767
CW
23 if (defined('E_DEPRECATED')) {
24 error_reporting(E_ALL & ~E_NOTICE & ~E_DEPRECATED);
25 } else {
26 error_reporting(E_ALL & ~E_NOTICE);
27 }
cce28758 28
40d13c28 29 require_once 'config.php';
cc17c205 30
046ec657
BK
31 /**
32 * Define a constant if not already defined
33 *
34 * @param string $name The constant name.
35 * @param mixed $value The constant value.
36 * @access public
37 * @return boolean True if defined successfully or not.
38 */
39 function define_default($name, $value) {
046ec657
BK
40 defined($name) or define($name, $value);
41 }
42
9ef8798b
BK
43 ///// Some defaults that you can override in config.php //////
44
45 define_default('FEED_FETCH_TIMEOUT', 45);
46 // How may seconds to wait for response when requesting feed from a site
47 define_default('FEED_FETCH_NO_CACHE_TIMEOUT', 15);
48 // How may seconds to wait for response when requesting feed from a
49 // site when that feed wasn't cached before
50 define_default('FILE_FETCH_TIMEOUT', 45);
51 // Default timeout when fetching files from remote sites
52 define_default('FILE_FETCH_CONNECT_TIMEOUT', 15);
53 // How many seconds to wait for initial response from website when
54 // fetching files from remote sites
046ec657 55
fc2b26a6
AD
56 if (DB_TYPE == "pgsql") {
57 define('SUBSTRING_FOR_DATE', 'SUBSTRING_FOR_DATE');
58 } else {
59 define('SUBSTRING_FOR_DATE', 'SUBSTRING');
60 }
61
9632f884
AD
62 /**
63 * Return available translations names.
8d505d78 64 *
9632f884
AD
65 * @access public
66 * @return array A array of available translations.
67 */
f8c612d4 68 function get_translations() {
6a214f92 69 $tr = array(
8d505d78 70 "auto" => "Detect automatically",
ca6ef932 71 "ar_SA" => "العربيّة (Arabic)",
51faa115 72 "bg_BG" => "Bulgarian",
c2aa0593 73 "da_DA" => "Dansk",
a3162add 74 "ca_CA" => "Català",
a06b79c4 75 "cs_CZ" => "Česky",
6a214f92 76 "en_US" => "English",
c2aa0593 77 "el_GR" => "Ελληνικά",
1f16ede0 78 "es_ES" => "Español (España)",
c2aa0593 79 "es_LA" => "Español",
a927fe7b 80 "de_DE" => "Deutsch",
6a214f92 81 "fr_FR" => "Français",
e78fd196 82 "hu_HU" => "Magyar (Hungarian)",
bb5d3960 83 "it_IT" => "Italiano",
1d004f12 84 "ja_JP" => "日本語 (Japanese)",
7b6c1ca7 85 "lv_LV" => "Latviešu",
592535d7 86 "nb_NO" => "Norwegian bokmål",
9e7f1f12 87 "nl_NL" => "Dutch",
ea45791a 88 "pl_PL" => "Polski",
d3b923c9 89 "ru_RU" => "Русский",
9a063469 90 "pt_BR" => "Portuguese/Brazil",
1c776ade 91 "pt_PT" => "Portuguese/Portugal",
5d608138 92 "zh_CN" => "Simplified Chinese",
8dc5e7f0 93 "zh_TW" => "Traditional Chinese",
2324f153 94 "sv_SE" => "Svenska",
76d78eb2 95 "fi_FI" => "Suomi",
42a5abdc 96 "tr_TR" => "Türkçe");
f8c612d4
AD
97
98 return $tr;
99 }
100
7b26a148
AD
101 require_once "lib/accept-to-gettext.php";
102 require_once "lib/gettext/gettext.inc";
aba609e0 103
7b26a148 104 function startup_gettext() {
8d505d78 105
7b26a148
AD
106 # Get locale from Accept-Language header
107 $lang = al2gt(array_keys(get_translations()), "text/html");
89cb787e 108
7b26a148
AD
109 if (defined('_TRANSLATION_OVERRIDE_DEFAULT')) {
110 $lang = _TRANSLATION_OVERRIDE_DEFAULT;
111 }
89cb787e 112
b18d109f
AD
113 if ($_SESSION["uid"] && get_schema_version() >= 120) {
114 $pref_lang = get_pref("USER_LANGUAGE", $_SESSION["uid"]);
1ee4900a 115
c4db796f 116 if ($pref_lang && $pref_lang != 'auto') {
7b149552
AD
117 $lang = $pref_lang;
118 }
7b26a148 119 }
7c33dbd4 120
7b26a148
AD
121 if ($lang) {
122 if (defined('LC_MESSAGES')) {
123 _setlocale(LC_MESSAGES, $lang);
124 } else if (defined('LC_ALL')) {
125 _setlocale(LC_ALL, $lang);
8d039718 126 }
aba609e0 127
d98e76d9 128 _bindtextdomain("messages", "locale");
865220a4 129
7b26a148
AD
130 _textdomain("messages");
131 _bind_textdomain_codeset("messages", "UTF-8");
865220a4 132 }
7b26a148
AD
133 }
134
b619ff15 135 require_once 'db-prefs.php';
8911ac8b 136 require_once 'version.php';
87d7e850
AD
137 require_once 'ccache.php';
138 require_once 'labels.php';
9549e33c 139 require_once 'controls.php';
40d13c28 140
fb850eec 141 define('SELF_USER_AGENT', 'Tiny Tiny RSS/' . VERSION . ' (http://tt-rss.org/)');
500943a4
AD
142 ini_set('user_agent', SELF_USER_AGENT);
143
5ddc3e27 144 require_once 'lib/pubsubhubbub/Publisher.php';
010efc9b 145
7d96bfcd
AD
146 $schema_version = false;
147
4f71d743
AD
148 function _debug_suppress($suppress) {
149 global $suppress_debugging;
150
151 $suppress_debugging = $suppress;
152 }
153
45004d43
AD
154 /**
155 * Print a timestamped debug message.
8d505d78 156 *
45004d43
AD
157 * @param string $msg The debug message.
158 * @return void
159 */
68cccafc 160 function _debug($msg, $show = true) {
4f71d743
AD
161 global $suppress_debugging;
162
163 //echo "[$suppress_debugging] $msg $show\n";
164
165 if ($suppress_debugging) return false;
9ec10352 166
6f9e33e4 167 $ts = strftime("%H:%M:%S", time());
2a6a9395
AD
168 if (function_exists('posix_getpid')) {
169 $ts = "$ts/" . posix_getpid();
170 }
2191eb7a 171
68cccafc 172 if ($show && !(defined('QUIET') && QUIET)) {
2191eb7a
AD
173 print "[$ts] $msg\n";
174 }
175
176 if (defined('LOGFILE')) {
177 $fp = fopen(LOGFILE, 'a+');
178
179 if ($fp) {
a33558a6
AD
180 $locked = false;
181
182 if (function_exists("flock")) {
183 $tries = 0;
184
185 // try to lock logfile for writing
186 while ($tries < 5 && !$locked = flock($fp, LOCK_EX | LOCK_NB)) {
187 sleep(1);
188 ++$tries;
189 }
190
191 if (!$locked) {
192 fclose($fp);
193 return;
194 }
195 }
196
2191eb7a 197 fputs($fp, "[$ts] $msg\n");
a33558a6
AD
198
199 if (function_exists("flock")) {
200 flock($fp, LOCK_UN);
201 }
202
2191eb7a
AD
203 fclose($fp);
204 }
205 }
206
45004d43 207 } // function _debug
6f9e33e4 208
9632f884
AD
209 /**
210 * Purge a feed old posts.
8d505d78 211 *
9632f884
AD
212 * @param mixed $link A database connection.
213 * @param mixed $feed_id The id of the purged feed.
214 * @param mixed $purge_interval Olderness of purged posts.
215 * @param boolean $debug Set to True to enable the debug. False by default.
216 * @access public
217 * @return void
218 */
a42c55f0 219 function purge_feed($feed_id, $purge_interval, $debug = false) {
ad507f85 220
a42c55f0 221 if (!$purge_interval) $purge_interval = feed_purge_interval($feed_id);
8d505d78 222
ad507f85 223 $rows = -1;
4c193675 224
6322ac79 225 $result = db_query(
07d0efe9
AD
226 "SELECT owner_uid FROM ttrss_feeds WHERE id = '$feed_id'");
227
228 $owner_uid = false;
229
230 if (db_num_rows($result) == 1) {
231 $owner_uid = db_fetch_result($result, 0, "owner_uid");
232 }
233
ab954dff
AD
234 if ($purge_interval == -1 || !$purge_interval) {
235 if ($owner_uid) {
a42c55f0 236 ccache_update($feed_id, $owner_uid);
ab954dff
AD
237 }
238 return;
239 }
240
07d0efe9
AD
241 if (!$owner_uid) return;
242
3907ef71 243 if (FORCE_ARTICLE_PURGE == 0) {
a42c55f0 244 $purge_unread = get_pref("PURGE_UNREAD_ARTICLES",
3907ef71
AD
245 $owner_uid, false);
246 } else {
247 $purge_unread = true;
248 $purge_interval = FORCE_ARTICLE_PURGE;
249 }
07d0efe9
AD
250
251 if (!$purge_unread) $query_limit = " unread = false AND ";
252
fefa6ca3 253 if (DB_TYPE == "pgsql") {
6b3160cf
AD
254 $result = db_query("DELETE FROM ttrss_user_entries
255 USING ttrss_entries
256 WHERE ttrss_entries.id = ref_id AND
257 marked = false AND
258 feed_id = '$feed_id' AND
259 $query_limit
260 ttrss_entries.date_updated < NOW() - INTERVAL '$purge_interval days'");
ad507f85 261
fefa6ca3 262 } else {
8d505d78 263
a42c55f0 264/* $result = db_query("DELETE FROM ttrss_user_entries WHERE
fefa6ca3 265 marked = false AND feed_id = '$feed_id' AND
8d505d78 266 (SELECT date_updated FROM ttrss_entries WHERE
30f1746f
AD
267 id = ref_id) < DATE_SUB(NOW(), INTERVAL $purge_interval DAY)"); */
268
a42c55f0 269 $result = db_query("DELETE FROM ttrss_user_entries
8d505d78
AD
270 USING ttrss_user_entries, ttrss_entries
271 WHERE ttrss_entries.id = ref_id AND
272 marked = false AND
273 feed_id = '$feed_id' AND
07d0efe9 274 $query_limit
25ea2805 275 ttrss_entries.date_updated < DATE_SUB(NOW(), INTERVAL $purge_interval DAY)");
ad507f85
AD
276 }
277
a08f94bd 278 $rows = db_affected_rows($result);
3f6f0857 279
a42c55f0 280 ccache_update($feed_id, $owner_uid);
ced46404 281
ad507f85 282 if ($debug) {
6f9e33e4 283 _debug("Purged feed $feed_id ($purge_interval): deleted $rows articles");
fefa6ca3 284 }
2ea09bde
AD
285
286 return $rows;
9632f884 287 } // function purge_feed
fefa6ca3 288
a42c55f0 289 function feed_purge_interval($feed_id) {
07d0efe9 290
a42c55f0 291 $result = db_query("SELECT purge_interval, owner_uid FROM ttrss_feeds
07d0efe9
AD
292 WHERE id = '$feed_id'");
293
294 if (db_num_rows($result) == 1) {
295 $purge_interval = db_fetch_result($result, 0, "purge_interval");
296 $owner_uid = db_fetch_result($result, 0, "owner_uid");
297
6322ac79 298 if ($purge_interval == 0) $purge_interval = get_pref(
863be6ca 299 'PURGE_OLD_DAYS', $owner_uid);
07d0efe9
AD
300
301 return $purge_interval;
302
303 } else {
304 return -1;
305 }
306 }
307
a230bf88 308 /*function get_feed_update_interval($feed_id) {
a42c55f0 309 $result = db_query("SELECT owner_uid, update_interval FROM
c7d57b66
AD
310 ttrss_feeds WHERE id = '$feed_id'");
311
312 if (db_num_rows($result) == 1) {
313 $update_interval = db_fetch_result($result, 0, "update_interval");
314 $owner_uid = db_fetch_result($result, 0, "owner_uid");
315
316 if ($update_interval != 0) {
317 return $update_interval;
318 } else {
a42c55f0 319 return get_pref('DEFAULT_UPDATE_INTERVAL', $owner_uid, false);
c7d57b66
AD
320 }
321
322 } else {
323 return -1;
324 }
a230bf88 325 }*/
c7d57b66 326
465fb16d
AD
327 // TODO: multiple-argument way is deprecated, first parameter is a hash now
328 function fetch_file_contents($options /* previously: 0: $url , 1: $type = false, 2: $login = false, 3: $pass = false,
329 4: $post_query = false, 5: $timeout = false, 6: $timestamp = 0, 7: $useragent = false*/) {
8d505d78 330
23d2471c 331 global $fetch_last_error;
7a01dc77 332 global $fetch_last_error_code;
cf0231f9 333 global $fetch_last_error_content;
ef39be2b 334 global $fetch_last_content_type;
3f6f0857 335 global $fetch_curl_used;
33373eca 336
24c7e413
AD
337 $fetch_last_error = false;
338 $fetch_last_error_code = -1;
339 $fetch_last_error_content = "";
340 $fetch_last_content_type = "";
341 $fetch_curl_used = false;
342
c71add38 343 if (!is_array($options)) {
465fb16d
AD
344
345 // falling back on compatibility shim
e934d63e
AD
346 $option_names = [ "url", "type", "login", "pass", "post_query", "timeout", "timestamp", "useragent" ];
347 $tmp = [];
348
349 for ($i = 0; $i < func_num_args(); $i++) {
350 $tmp[$option_names[$i]] = func_get_arg($i);
351 }
352
353 $options = $tmp;
354
355 /*$options = array(
465fb16d
AD
356 "url" => func_get_arg(0),
357 "type" => @func_get_arg(1),
358 "login" => @func_get_arg(2),
359 "pass" => @func_get_arg(3),
360 "post_query" => @func_get_arg(4),
361 "timeout" => @func_get_arg(5),
362 "timestamp" => @func_get_arg(6),
363 "useragent" => @func_get_arg(7)
e934d63e 364 ); */
465fb16d
AD
365 }
366
e3bc4591
AD
367 $url = $options["url"];
368 $type = isset($options["type"]) ? $options["type"] : false;
369 $login = isset($options["login"]) ? $options["login"] : false;
465fb16d 370 $pass = isset($options["pass"]) ? $options["pass"] : false;
e3bc4591
AD
371 $post_query = isset($options["post_query"]) ? $options["post_query"] : false;
372 $timeout = isset($options["timeout"]) ? $options["timeout"] : false;
373 $timestamp = isset($options["timestamp"]) ? $options["timestamp"] : 0;
374 $useragent = isset($options["useragent"]) ? $options["useragent"] : false;
fabfb9fc 375 $followlocation = isset($options["followlocation"]) ? $options["followlocation"] : true;
465fb16d 376
32703cc6 377 $url = ltrim($url, ' ');
2375b6b6 378 $url = str_replace(' ', '%20', $url);
23d2471c 379
9fd58133
AD
380 if (strpos($url, "//") === 0)
381 $url = 'http:' . $url;
382
312742db 383 if (!defined('NO_CURL') && function_exists('curl_init') && !ini_get("open_basedir")) {
3f6f0857
AD
384
385 $fetch_curl_used = true;
b799dc8b 386
4c467026 387 $ch = curl_init($url);
a1af1574 388
81c20663 389 if ($timestamp && !$post_query) {
7a01dc77
AD
390 curl_setopt($ch, CURLOPT_HTTPHEADER,
391 array("If-Modified-Since: ".gmdate('D, d M Y H:i:s \G\M\T', $timestamp)));
392 }
393
8401101d
BK
394 curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout ? $timeout : FILE_FETCH_CONNECT_TIMEOUT);
395 curl_setopt($ch, CURLOPT_TIMEOUT, $timeout ? $timeout : FILE_FETCH_TIMEOUT);
fabfb9fc 396 curl_setopt($ch, CURLOPT_FOLLOWLOCATION, !ini_get("open_basedir") && $followlocation);
a1af1574
AD
397 curl_setopt($ch, CURLOPT_MAXREDIRS, 20);
398 curl_setopt($ch, CURLOPT_BINARYTRANSFER, true);
399 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
5f6804bc 400 curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
f826070c
AD
401 curl_setopt($ch, CURLOPT_USERAGENT, $useragent ? $useragent :
402 SELF_USER_AGENT);
3f6f0857 403 curl_setopt($ch, CURLOPT_ENCODING, "");
1fd733c8 404 //curl_setopt($ch, CURLOPT_REFERER, $url);
0f6b9263 405
4c467026 406 if (!ini_get("open_basedir")) {
0f6b9263
AD
407 curl_setopt($ch, CURLOPT_COOKIEJAR, "/dev/null");
408 }
8d505d78 409
05f14a7d
AD
410 if (defined('_CURL_HTTP_PROXY')) {
411 curl_setopt($ch, CURLOPT_PROXY, _CURL_HTTP_PROXY);
412 }
413
ae5f7bb1
AD
414 if ($post_query) {
415 curl_setopt($ch, CURLOPT_POST, true);
416 curl_setopt($ch, CURLOPT_POSTFIELDS, $post_query);
417 }
418
8d505d78
AD
419 if ($login && $pass)
420 curl_setopt($ch, CURLOPT_USERPWD, "$login:$pass");
a1af1574 421
fb074239 422 $contents = @curl_exec($ch);
268a06dc 423
48b657fc
AD
424 if (curl_errno($ch) === 23 || curl_errno($ch) === 61) {
425 curl_setopt($ch, CURLOPT_ENCODING, 'none');
426 $contents = @curl_exec($ch);
fb850eec
AD
427 }
428
a1af1574 429 if ($contents === false) {
fb850eec 430 $fetch_last_error = curl_errno($ch) . " " . curl_error($ch);
a1af1574
AD
431 curl_close($ch);
432 return false;
4065b60b
AD
433 }
434
8d505d78 435 $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
ef39be2b 436 $fetch_last_content_type = curl_getinfo($ch, CURLINFO_CONTENT_TYPE);
4065b60b 437
7a01dc77
AD
438 $fetch_last_error_code = $http_code;
439
ef39be2b 440 if ($http_code != 200 || $type && strpos($fetch_last_content_type, "$type") === false) {
fb850eec
AD
441 if (curl_errno($ch) != 0) {
442 $fetch_last_error = curl_errno($ch) . " " . curl_error($ch);
443 } else {
444 $fetch_last_error = "HTTP Code: $http_code";
445 }
cf0231f9 446 $fetch_last_error_content = $contents;
fb850eec 447 curl_close($ch);
a1af1574
AD
448 return false;
449 }
4065b60b 450
fb850eec
AD
451 curl_close($ch);
452
a1af1574 453 return $contents;
4065b60b 454 } else {
3f6f0857
AD
455
456 $fetch_curl_used = false;
457
d3911f80 458 if ($login && $pass){
8d505d78
AD
459 $url_parts = array();
460
461 preg_match("/(^[^:]*):\/\/(.*)/", $url, $url_parts);
462
d3911f80
AD
463 $pass = urlencode($pass);
464
8d505d78
AD
465 if ($url_parts[1] && $url_parts[2]) {
466 $url = $url_parts[1] . "://$login:$pass@" . $url_parts[2];
467 }
468 }
469
3bba9c39
AD
470 // TODO: should this support POST requests or not? idk
471
01311d86 472 if (!$post_query && $timestamp) {
45913edd
AD
473 $context = stream_context_create(array(
474 'http' => array(
475 'method' => 'GET',
24c7e413 476 'ignore_errors' => true,
3bba9c39 477 'timeout' => $timeout ? $timeout : FILE_FETCH_TIMEOUT,
45913edd
AD
478 'protocol_version'=> 1.1,
479 'header' => "If-Modified-Since: ".gmdate("D, d M Y H:i:s \\G\\M\\T\r\n", $timestamp)
480 )));
01311d86 481 } else {
45913edd
AD
482 $context = stream_context_create(array(
483 'http' => array(
484 'method' => 'GET',
24c7e413 485 'ignore_errors' => true,
3bba9c39 486 'timeout' => $timeout ? $timeout : FILE_FETCH_TIMEOUT,
45913edd
AD
487 'protocol_version'=> 1.1
488 )));
7475580b 489 }
01311d86 490
6122c449
AD
491 $old_error = error_get_last();
492
01311d86 493 $data = @file_get_contents($url, false, $context);
23d2471c 494
37ddf5b7 495 if (isset($http_response_header) && is_array($http_response_header)) {
df25e4d2
AD
496 foreach ($http_response_header as $h) {
497 if (substr(strtolower($h), 0, 13) == 'content-type:') {
498 $fetch_last_content_type = substr($h, 14);
499 // don't abort here b/c there might be more than one
500 // e.g. if we were being redirected -- last one is the right one
501 }
01311d86
AD
502
503 if (substr(strtolower($h), 0, 7) == 'http/1.') {
504 $fetch_last_error_code = (int) substr($h, 9, 3);
505 }
ef39be2b
MB
506 }
507 }
508
24c7e413 509 if ($fetch_last_error_code != 200) {
23d2471c 510 $error = error_get_last();
6122c449
AD
511
512 if ($error['message'] != $old_error['message']) {
513 $fetch_last_error = $error["message"];
514 } else {
515 $fetch_last_error = "HTTP Code: $fetch_last_error_code";
516 }
24c7e413
AD
517
518 $fetch_last_error_content = $data;
519
520 return false;
23d2471c
AD
521 }
522 return $data;
4065b60b
AD
523 }
524
525 }
78800912 526
9632f884
AD
527 /**
528 * Try to determine the favicon URL for a feed.
529 * adapted from wordpress favicon plugin by Jeff Minard (http://thecodepro.com/)
530 * http://dev.wp-plugins.org/file/favatars/trunk/favatars.php
8d505d78 531 *
9632f884
AD
532 * @param string $url A feed or page URL
533 * @access public
534 * @return mixed The favicon URL, or false if none was found.
535 */
1bd11fdf 536 function get_favicon_url($url) {
99331724 537
1bd11fdf 538 $favicon_url = false;
ed214298 539
4065b60b 540 if ($html = @fetch_file_contents($url)) {
78800912 541
ed214298 542 libxml_use_internal_errors(true);
c798704b 543
ed214298
AD
544 $doc = new DOMDocument();
545 $doc->loadHTML($html);
546 $xpath = new DOMXPath($doc);
717f5e64 547
a712429e
AD
548 $base = $xpath->query('/html/head/base');
549 foreach ($base as $b) {
550 $url = $b->getAttribute("href");
551 break;
552 }
553
1bd11fdf 554 $entries = $xpath->query('/html/head/link[@rel="shortcut icon" or @rel="icon"]');
ed214298
AD
555 if (count($entries) > 0) {
556 foreach ($entries as $entry) {
1bd11fdf
AD
557 $favicon_url = rewrite_relative_url($url, $entry->getAttribute("href"));
558 break;
ed214298 559 }
8d505d78 560 }
4065b60b 561 }
c798704b 562
1bd11fdf
AD
563 if (!$favicon_url)
564 $favicon_url = rewrite_relative_url($url, "/favicon.ico");
565
566 return $favicon_url;
567 } // function get_favicon_url
568
a42c55f0 569 function initialize_user_prefs($uid, $profile = false) {
ff485f1d 570
a42c55f0 571 $uid = db_escape_string($uid);
ff485f1d 572
d9084cf2
AD
573 if (!$profile) {
574 $profile = "NULL";
f9aa6a89 575 $profile_qpart = "AND profile IS NULL";
d9084cf2 576 } else {
f9aa6a89 577 $profile_qpart = "AND profile = '$profile'";
d9084cf2
AD
578 }
579
6322ac79 580 if (get_schema_version() < 63) $profile_qpart = "";
f9aa6a89 581
a42c55f0 582 db_query("BEGIN");
ff485f1d 583
a42c55f0 584 $result = db_query("SELECT pref_name,def_value FROM ttrss_prefs");
8d505d78 585
a42c55f0 586 $u_result = db_query("SELECT pref_name
f9aa6a89 587 FROM ttrss_user_prefs WHERE owner_uid = '$uid' $profile_qpart");
ff485f1d
AD
588
589 $active_prefs = array();
590
591 while ($line = db_fetch_assoc($u_result)) {
8d505d78 592 array_push($active_prefs, $line["pref_name"]);
ff485f1d
AD
593 }
594
595 while ($line = db_fetch_assoc($result)) {
596 if (array_search($line["pref_name"], $active_prefs) === FALSE) {
597// print "adding " . $line["pref_name"] . "<br>";
598
a42c55f0
AD
599 $line["def_value"] = db_escape_string($line["def_value"]);
600 $line["pref_name"] = db_escape_string($line["pref_name"]);
d296ba50 601
6322ac79 602 if (get_schema_version() < 63) {
a42c55f0 603 db_query("INSERT INTO ttrss_user_prefs
8d505d78 604 (owner_uid,pref_name,value) VALUES
f9aa6a89
AD
605 ('$uid', '".$line["pref_name"]."','".$line["def_value"]."')");
606
607 } else {
a42c55f0 608 db_query("INSERT INTO ttrss_user_prefs
8d505d78 609 (owner_uid,pref_name,value, profile) VALUES
f9aa6a89
AD
610 ('$uid', '".$line["pref_name"]."','".$line["def_value"]."', $profile)");
611 }
ff485f1d
AD
612
613 }
614 }
615
a42c55f0 616 db_query("COMMIT");
ff485f1d
AD
617
618 }
956c7629 619
8de8bfb8
AD
620 function get_ssl_certificate_id() {
621 if ($_SERVER["REDIRECT_SSL_CLIENT_M_SERIAL"]) {
622 return sha1($_SERVER["REDIRECT_SSL_CLIENT_M_SERIAL"] .
623 $_SERVER["REDIRECT_SSL_CLIENT_V_START"] .
624 $_SERVER["REDIRECT_SSL_CLIENT_V_END"] .
625 $_SERVER["REDIRECT_SSL_CLIENT_S_DN"]);
626 }
ac617ebc
GG
627 if ($_SERVER["SSL_CLIENT_M_SERIAL"]) {
628 return sha1($_SERVER["SSL_CLIENT_M_SERIAL"] .
629 $_SERVER["SSL_CLIENT_V_START"] .
630 $_SERVER["SSL_CLIENT_V_END"] .
631 $_SERVER["SSL_CLIENT_S_DN"]);
632 }
8de8bfb8
AD
633 return "";
634 }
635
a42c55f0 636 function authenticate_user($login, $password, $check_only = false) {
c8437f35 637
131b01b3 638 if (!SINGLE_USER_MODE) {
0d421af8 639 $user_id = false;
0f28f81f 640
1ffe3391 641 foreach (PluginHost::getInstance()->get_hooks(PluginHost::HOOK_AUTH_USER) as $plugin) {
0f28f81f
AD
642
643 $user_id = (int) $plugin->authenticate($login, $password);
644
645 if ($user_id) {
646 $_SESSION["auth_module"] = strtolower(get_class($plugin));
647 break;
648 }
461766f3
AD
649 }
650
0d421af8 651 if ($user_id && !$check_only) {
70400171
AD
652 @session_start();
653
0d421af8 654 $_SESSION["uid"] = $user_id;
3472c4c5 655 $_SESSION["version"] = VERSION_STATIC;
0d421af8 656
a42c55f0 657 $result = db_query("SELECT login,access_level,pwd_hash FROM ttrss_users
0d421af8 658 WHERE id = '$user_id'");
8d505d78 659
131b01b3
AD
660 $_SESSION["name"] = db_fetch_result($result, 0, "login");
661 $_SESSION["access_level"] = db_fetch_result($result, 0, "access_level");
3ceb893f 662 $_SESSION["csrf_token"] = uniqid_short();
8d505d78 663
a42c55f0 664 db_query("UPDATE ttrss_users SET last_login = NOW() WHERE id = " .
131b01b3 665 $_SESSION["uid"]);
8d505d78 666
131b01b3 667 $_SESSION["ip_address"] = $_SERVER["REMOTE_ADDR"];
837ec70e 668 $_SESSION["user_agent"] = sha1($_SERVER['HTTP_USER_AGENT']);
1a9f4d3c 669 $_SESSION["pwd_hash"] = db_fetch_result($result, 0, "pwd_hash");
91c5f229
AD
670
671 $_SESSION["last_version_check"] = time();
8d505d78 672
a42c55f0 673 initialize_user_prefs($_SESSION["uid"]);
8d505d78 674
131b01b3
AD
675 return true;
676 }
8d505d78 677
131b01b3 678 return false;
503eb349 679
131b01b3 680 } else {
503eb349 681
131b01b3
AD
682 $_SESSION["uid"] = 1;
683 $_SESSION["name"] = "admin";
787e5ebc 684 $_SESSION["access_level"] = 10;
21e42e5f 685
0d421af8
AD
686 $_SESSION["hide_hello"] = true;
687 $_SESSION["hide_logout"] = true;
688
d5fd183d
AD
689 $_SESSION["auth_module"] = false;
690
21e42e5f 691 if (!$_SESSION["csrf_token"]) {
3ceb893f 692 $_SESSION["csrf_token"] = uniqid_short();
21e42e5f 693 }
f557cd78 694
0bbba72d 695 $_SESSION["ip_address"] = $_SERVER["REMOTE_ADDR"];
8d505d78 696
a42c55f0 697 initialize_user_prefs($_SESSION["uid"]);
8d505d78 698
c8437f35
AD
699 return true;
700 }
c8437f35
AD
701 }
702
e6cb77a0
AD
703 function make_password($length = 8) {
704
85db6213
AD
705 $password = "";
706 $possible = "0123456789abcdfghjkmnpqrstvwxyzABCDFGHJKMNPQRSTVWXYZ";
707
708 $i = 0;
709
710 while ($i < $length) {
711 $char = substr($possible, mt_rand(0, strlen($possible)-1), 1);
712
713 if (!strstr($password, $char)) {
714 $password .= $char;
715 $i++;
716 }
717 }
718 return $password;
e6cb77a0
AD
719 }
720
721 // this is called after user is created to initialize default feeds, labels
722 // or whatever else
8d505d78 723
e6cb77a0
AD
724 // user preferences are checked on every login, not here
725
a42c55f0 726 function initialize_user($uid) {
e6cb77a0 727
a42c55f0 728 db_query("insert into ttrss_feeds (owner_uid,title,feed_url)
cd2cd415 729 values ('$uid', 'Tiny Tiny RSS: Forum',
f0855b88 730 'http://tt-rss.org/forum/rss.php')");
3b0feb9b 731 }
e6cb77a0 732
b8aa49bc 733 function logout_user() {
5ccc1cf5
AD
734 session_destroy();
735 if (isset($_COOKIE[session_name()])) {
736 setcookie(session_name(), '', time()-42000, '/');
737 }
b8aa49bc
AD
738 }
739
8484ce22
AD
740 function validate_csrf($csrf_token) {
741 return $csrf_token == $_SESSION['csrf_token'];
742 }
743
5cbd1fe8
AD
744 function load_user_plugins($owner_uid, $pluginhost = false) {
745
746 if (!$pluginhost) $pluginhost = PluginHost::getInstance();
747
6d45a152 748 if ($owner_uid && SCHEMA_VERSION >= 100) {
a42c55f0 749 $plugins = get_pref("_ENABLED_PLUGINS", $owner_uid);
de612e7a 750
5cbd1fe8 751 $pluginhost->load($plugins, PluginHost::KIND_USER, $owner_uid);
e9c04fd4 752
6322ac79 753 if (get_schema_version() > 100) {
5cbd1fe8 754 $pluginhost->load_data();
e9c04fd4 755 }
de612e7a
AD
756 }
757 }
758
6322ac79 759 function login_sequence() {
97acbaf1 760 if (SINGLE_USER_MODE) {
25db6c51 761 @session_start();
a42c55f0 762 authenticate_user("admin", null);
68349f55 763 startup_gettext();
a42c55f0 764 load_user_plugins($_SESSION["uid"]);
97acbaf1 765 } else {
6322ac79 766 if (!validate_session()) $_SESSION["uid"] = false;
d0eef2a3
AD
767
768 if (!$_SESSION["uid"]) {
97acbaf1 769
a42c55f0
AD
770 if (AUTH_AUTO_LOGIN && authenticate_user(null, null)) {
771 $_SESSION["ref_schema_version"] = get_schema_version(true);
97acbaf1 772 } else {
a42c55f0 773 authenticate_user(null, null, true);
97acbaf1
AD
774 }
775
d0eef2a3 776 if (!$_SESSION["uid"]) {
d0eef2a3
AD
777 @session_destroy();
778 setcookie(session_name(), '', time()-42000, '/');
9ce7a554 779
6322ac79 780 render_login_form();
d0eef2a3
AD
781 exit;
782 }
4ad99f23 783
97acbaf1
AD
784 } else {
785 /* bump login timestamp */
a42c55f0 786 db_query("UPDATE ttrss_users SET last_login = NOW() WHERE id = " .
97acbaf1 787 $_SESSION["uid"]);
06b0777f 788 $_SESSION["last_login_update"] = time();
01a87dff
AD
789 }
790
de612e7a 791 if ($_SESSION["uid"]) {
7b149552 792 startup_gettext();
a42c55f0 793 load_user_plugins($_SESSION["uid"]);
b1b1d25f
AD
794
795 /* cleanup ccache */
796
a42c55f0 797 db_query("DELETE FROM ttrss_counters_cache WHERE owner_uid = ".
b1b1d25f
AD
798 $_SESSION["uid"] . " AND
799 (SELECT COUNT(id) FROM ttrss_feeds WHERE
800 ttrss_feeds.id = feed_id) = 0");
801
a42c55f0 802 db_query("DELETE FROM ttrss_cat_counters_cache WHERE owner_uid = ".
b1b1d25f
AD
803 $_SESSION["uid"] . " AND
804 (SELECT COUNT(id) FROM ttrss_feed_categories WHERE
805 ttrss_feed_categories.id = feed_id) = 0");
806
de612e7a 807 }
b1b1d25f 808
b8aa49bc 809 }
afc3cf55 810 }
3547842a 811
411fe209 812 function truncate_string($str, $max_len, $suffix = '&hellip;') {
878a0083 813 if (mb_strlen($str, "utf-8") > $max_len) {
411fe209 814 return mb_substr($str, 0, $max_len, "utf-8") . $suffix;
3547842a
AD
815 } else {
816 return $str;
817 }
818 }
54a60e1a 819
cc43e19b
AD
820 // is not utf8 clean
821 function truncate_middle($str, $max_len, $suffix = '&hellip;') {
822 if (strlen($str) > $max_len) {
823 return substr_replace($str, $suffix, $max_len / 2, mb_strlen($str) - $max_len);
824 } else {
825 return $str;
826 }
827 }
828
ab4b768f
AD
829 function convert_timestamp($timestamp, $source_tz, $dest_tz) {
830
831 try {
832 $source_tz = new DateTimeZone($source_tz);
833 } catch (Exception $e) {
834 $source_tz = new DateTimeZone('UTC');
835 }
836
837 try {
838 $dest_tz = new DateTimeZone($dest_tz);
839 } catch (Exception $e) {
840 $dest_tz = new DateTimeZone('UTC');
841 }
842
843 $dt = new DateTime(date('Y-m-d H:i:s', $timestamp), $source_tz);
844 return $dt->format('U') + $dest_tz->getOffset($dt);
845 }
846
a42c55f0 847 function make_local_datetime($timestamp, $long, $owner_uid = false,
b6714c77 848 $no_smart_dt = false, $eta_min = false) {
324944f3
AD
849
850 if (!$owner_uid) $owner_uid = $_SESSION['uid'];
851 if (!$timestamp) $timestamp = '1970-01-01 0:00';
852
7d96bfcd 853 global $utc_tz;
5ddef5ba
AD
854 global $user_tz;
855
856 if (!$utc_tz) $utc_tz = new DateTimeZone('UTC');
324944f3 857
90e5f4f1
AD
858 $timestamp = substr($timestamp, 0, 19);
859
7d96bfcd
AD
860 # We store date in UTC internally
861 $dt = new DateTime($timestamp, $utc_tz);
862
5ddef5ba 863 $user_tz_string = get_pref('USER_TIMEZONE', $owner_uid);
7d96bfcd 864
6bfc97da 865 if ($user_tz_string != 'Automatic') {
324944f3 866
6bfc97da
AD
867 try {
868 if (!$user_tz) $user_tz = new DateTimeZone($user_tz_string);
869 } catch (Exception $e) {
870 $user_tz = $utc_tz;
871 }
872
873 $tz_offset = $user_tz->getOffset($dt);
874 } else {
96f0cbe3 875 $tz_offset = (int) -$_SESSION["clientTzOffset"];
6bfc97da 876 }
5ddef5ba 877
7d96bfcd 878 $user_timestamp = $dt->format('U') + $tz_offset;
324944f3 879
1dc52ae7 880 if (!$no_smart_dt) {
a42c55f0 881 return smart_date_time($user_timestamp,
b6714c77 882 $tz_offset, $owner_uid, $eta_min);
324944f3
AD
883 } else {
884 if ($long)
a42c55f0 885 $format = get_pref('LONG_DATE_FORMAT', $owner_uid);
324944f3 886 else
a42c55f0 887 $format = get_pref('SHORT_DATE_FORMAT', $owner_uid);
324944f3
AD
888
889 return date($format, $user_timestamp);
890 }
891 }
892
b6714c77 893 function smart_date_time($timestamp, $tz_offset = 0, $owner_uid = false, $eta_min = false) {
2a5c136e
AD
894 if (!$owner_uid) $owner_uid = $_SESSION['uid'];
895
97aa917c 896 if ($eta_min && time() + $tz_offset - $timestamp < 3600) {
46973af5
AD
897 return T_sprintf("%d min", date("i", time() + $tz_offset - $timestamp));
898 } else if (date("Y.m.d", $timestamp) == date("Y.m.d", time() + $tz_offset)) {
be773442 899 return date("G:i", $timestamp);
2a5c136e 900 } else if (date("Y", $timestamp) == date("Y", time() + $tz_offset)) {
a42c55f0 901 $format = get_pref('SHORT_DATE_FORMAT', $owner_uid);
2a5c136e 902 return date($format, $timestamp);
be773442 903 } else {
a42c55f0 904 $format = get_pref('LONG_DATE_FORMAT', $owner_uid);
2a5c136e 905 return date($format, $timestamp);
be773442
AD
906 }
907 }
908
e3c99f3b 909 function sql_bool_to_bool($s) {
9955a134 910 if ($s == "t" || $s == "1" || strtolower($s) == "true") {
e3c99f3b
AD
911 return true;
912 } else {
913 return false;
914 }
915 }
8d505d78 916
badac687
AD
917 function bool_to_sql_bool($s) {
918 if ($s) {
919 return "true";
920 } else {
921 return "false";
922 }
923 }
e3c99f3b 924
fcfa9ef1
AD
925 // Session caching removed due to causing wrong redirects to upgrade
926 // script when get_schema_version() is called on an obsolete session
927 // created on a previous schema version.
a42c55f0 928 function get_schema_version($nocache = false) {
7d96bfcd
AD
929 global $schema_version;
930
e2cf81e2 931 if (!$schema_version && !$nocache) {
a42c55f0 932 $result = db_query("SELECT schema_version FROM ttrss_version");
199db684 933 $version = db_fetch_result($result, 0, "schema_version");
7d96bfcd 934 $schema_version = $version;
199db684 935 return $version;
7d96bfcd
AD
936 } else {
937 return $schema_version;
938 }
e4c51a6c
AD
939 }
940
6322ac79 941 function sanity_check() {
31303c6b 942 require_once 'errors.php';
cacc1877 943 global $ERRORS;
ebb948c2 944
6043fb7e 945 $error_code = 0;
a42c55f0 946 $schema_version = get_schema_version(true);
6043fb7e
AD
947
948 if ($schema_version != SCHEMA_VERSION) {
949 $error_code = 5;
950 }
951
aec3ce39 952 if (DB_TYPE == "mysql") {
a42c55f0 953 $result = db_query("SELECT true", false);
aec3ce39
AD
954 if (db_num_rows($result) != 1) {
955 $error_code = 10;
956 }
957 }
958
a42c55f0 959 if (db_escape_string("testTEST") != "testTEST") {
f29ba148
AD
960 $error_code = 12;
961 }
962
ebb948c2 963 return array("code" => $error_code, "message" => $ERRORS[$error_code]);
6043fb7e
AD
964 }
965
27981ca3 966 function file_is_locked($filename) {
8ff2a86c
AD
967 if (file_exists(LOCK_DIRECTORY . "/$filename")) {
968 if (function_exists('flock')) {
969 $fp = @fopen(LOCK_DIRECTORY . "/$filename", "r");
970 if ($fp) {
971 if (flock($fp, LOCK_EX | LOCK_NB)) {
972 flock($fp, LOCK_UN);
973 fclose($fp);
974 return false;
975 }
31a6d42d 976 fclose($fp);
8ff2a86c
AD
977 return true;
978 } else {
31a6d42d
AD
979 return false;
980 }
27981ca3 981 }
8ff2a86c
AD
982 return true; // consider the file always locked and skip the test
983 } else {
984 return false;
27981ca3 985 }
27981ca3
AD
986 }
987
8ff2a86c 988
fcb4c0c9 989 function make_lockfile($filename) {
cfa43e02 990 $fp = fopen(LOCK_DIRECTORY . "/$filename", "w");
fcb4c0c9 991
a44bfcfd 992 if ($fp && flock($fp, LOCK_EX | LOCK_NB)) {
58fc7095
AD
993 $stat_h = fstat($fp);
994 $stat_f = stat(LOCK_DIRECTORY . "/$filename");
995
1fcebfb3
AD
996 if (strtoupper(substr(PHP_OS, 0, 3)) !== 'WIN') {
997 if ($stat_h["ino"] != $stat_f["ino"] ||
998 $stat_h["dev"] != $stat_f["dev"]) {
999
1000 return false;
1001 }
58fc7095
AD
1002 }
1003
4c59adb1
AD
1004 if (function_exists('posix_getpid')) {
1005 fwrite($fp, posix_getpid() . "\n");
1006 }
fcb4c0c9
AD
1007 return $fp;
1008 } else {
1009 return false;
1010 }
1011 }
1012
bf7fcde8 1013 function make_stampfile($filename) {
cfa43e02 1014 $fp = fopen(LOCK_DIRECTORY . "/$filename", "w");
bf7fcde8 1015
8e00ae9b 1016 if (flock($fp, LOCK_EX | LOCK_NB)) {
bf7fcde8 1017 fwrite($fp, time() . "\n");
8e00ae9b 1018 flock($fp, LOCK_UN);
bf7fcde8
AD
1019 fclose($fp);
1020 return true;
1021 } else {
1022 return false;
1023 }
1024 }
1025
894ebcf5 1026 function sql_random_function() {
8c0496f7 1027 if (DB_TYPE == "mysql") {
894ebcf5
AD
1028 return "RAND()";
1029 } else {
1030 return "RANDOM()";
1031 }
1032 }
1033
6322ac79
AD
1034 function getAllCounters() {
1035 $data = getGlobalCounters();
8d505d78 1036
6322ac79
AD
1037 $data = array_merge($data, getVirtCounters());
1038 $data = array_merge($data, getLabelCounters());
6f7798b6 1039 $data = array_merge($data, getFeedCounters());
6322ac79 1040 $data = array_merge($data, getCategoryCounters());
6a7817c1
AD
1041
1042 return $data;
8d505d78 1043 }
a9cb1f83 1044
ff5cc7d7
AD
1045 function getCategoryCounters() {
1046 $ret_arr = array();
1047
1048 /* Labels category */
1049
1050 $cv = array("id" => -2, "kind" => "cat",
86a8351c 1051 "counter" => Feeds::getCategoryUnread(-2));
ff5cc7d7
AD
1052
1053 array_push($ret_arr, $cv);
1054
1055 $result = db_query("SELECT id AS cat_id, value AS unread,
1056 (SELECT COUNT(id) FROM ttrss_feed_categories AS c2
1057 WHERE c2.parent_cat = ttrss_feed_categories.id) AS num_children
1058 FROM ttrss_feed_categories, ttrss_cat_counters_cache
1059 WHERE ttrss_cat_counters_cache.feed_id = id AND
1060 ttrss_cat_counters_cache.owner_uid = ttrss_feed_categories.owner_uid AND
1061 ttrss_feed_categories.owner_uid = " . $_SESSION["uid"]);
1062
1063 while ($line = db_fetch_assoc($result)) {
1064 $line["cat_id"] = (int) $line["cat_id"];
1065
1066 if ($line["num_children"] > 0) {
a230bf88 1067 $child_counter = Feeds::getCategoryChildrenUnread($line["cat_id"], $_SESSION["uid"]);
ff5cc7d7
AD
1068 } else {
1069 $child_counter = 0;
1070 }
1071
1072 $cv = array("id" => $line["cat_id"], "kind" => "cat",
1073 "counter" => $line["unread"] + $child_counter);
1074
1075 array_push($ret_arr, $cv);
1076 }
1077
1078 /* Special case: NULL category doesn't actually exist in the DB */
1079
1080 $cv = array("id" => 0, "kind" => "cat",
1081 "counter" => (int) ccache_find(0, $_SESSION["uid"], true));
1082
1083 array_push($ret_arr, $cv);
1084
1085 return $ret_arr;
1086 }
1087
ff5cc7d7 1088 function getFeedUnread($feed, $is_cat = false) {
86a8351c 1089 return Feeds::getFeedArticles($feed, $is_cat, true, $_SESSION["uid"]);
ff5cc7d7
AD
1090 }
1091
ff5cc7d7
AD
1092 function getGlobalCounters($global_unread = -1) {
1093 $ret_arr = array();
1094
1095 if ($global_unread == -1) {
a230bf88 1096 $global_unread = Feeds::getGlobalUnread();
ff5cc7d7
AD
1097 }
1098
1099 $cv = array("id" => "global-unread",
1100 "counter" => (int) $global_unread);
1101
1102 array_push($ret_arr, $cv);
1103
1104 $result = db_query("SELECT COUNT(id) AS fn FROM
1105 ttrss_feeds WHERE owner_uid = " . $_SESSION["uid"]);
1106
1107 $subscribed_feeds = db_fetch_result($result, 0, "fn");
1108
1109 $cv = array("id" => "subscribed-feeds",
1110 "counter" => (int) $subscribed_feeds);
1111
1112 array_push($ret_arr, $cv);
1113
1114 return $ret_arr;
1115 }
1116
1117 function getVirtCounters() {
1118
1119 $ret_arr = array();
1120
1121 for ($i = 0; $i >= -4; $i--) {
1122
1123 $count = getFeedUnread($i);
1124
1125 if ($i == 0 || $i == -1 || $i == -2)
86a8351c 1126 $auxctr = Feeds::getFeedArticles($i, false);
ff5cc7d7
AD
1127 else
1128 $auxctr = 0;
1129
1130 $cv = array("id" => $i,
1131 "counter" => (int) $count,
70c5b2bf 1132 "auxcounter" => (int) $auxctr);
ff5cc7d7
AD
1133
1134// if (get_pref('EXTENDED_FEEDLIST'))
1135// $cv["xmsg"] = getFeedArticles($i)." ".__("total");
1136
1137 array_push($ret_arr, $cv);
1138 }
1139
1140 $feeds = PluginHost::getInstance()->get_feeds(-1);
1141
1142 if (is_array($feeds)) {
1143 foreach ($feeds as $feed) {
1144 $cv = array("id" => PluginHost::pfeed_to_feed_id($feed['id']),
1145 "counter" => $feed['sender']->get_unread($feed['id']));
1146
1147 if (method_exists($feed['sender'], 'get_total'))
1148 $cv["auxcounter"] = $feed['sender']->get_total($feed['id']);
1149
1150 array_push($ret_arr, $cv);
1151 }
1152 }
1153
1154 return $ret_arr;
1155 }
1156
1157 function getLabelCounters($descriptions = false) {
1158
1159 $ret_arr = array();
1160
1161 $owner_uid = $_SESSION["uid"];
1162
1163 $result = db_query("SELECT id,caption,SUM(CASE WHEN u1.unread = true THEN 1 ELSE 0 END) AS unread, COUNT(u1.unread) AS total
1164 FROM ttrss_labels2 LEFT JOIN ttrss_user_labels2 ON
1165 (ttrss_labels2.id = label_id)
1166 LEFT JOIN ttrss_user_entries AS u1 ON u1.ref_id = article_id
7475580b
AD
1167 WHERE ttrss_labels2.owner_uid = $owner_uid AND u1.owner_uid = $owner_uid
1168 GROUP BY ttrss_labels2.id,
ff5cc7d7
AD
1169 ttrss_labels2.caption");
1170
1171 while ($line = db_fetch_assoc($result)) {
1172
1173 $id = label_to_feed_id($line["id"]);
1174
1175 $cv = array("id" => $id,
1176 "counter" => (int) $line["unread"],
1177 "auxcounter" => (int) $line["total"]);
1178
1179 if ($descriptions)
1180 $cv["description"] = $line["caption"];
1181
1182 array_push($ret_arr, $cv);
1183 }
1184
1185 return $ret_arr;
1186 }
1187
1188 function getFeedCounters($active_feed = false) {
1189
1190 $ret_arr = array();
1191
1192 $query = "SELECT ttrss_feeds.id,
1193 ttrss_feeds.title,
1194 ".SUBSTRING_FOR_DATE."(ttrss_feeds.last_updated,1,19) AS last_updated,
1195 last_error, value AS count
1196 FROM ttrss_feeds, ttrss_counters_cache
1197 WHERE ttrss_feeds.owner_uid = ".$_SESSION["uid"]."
1198 AND ttrss_counters_cache.owner_uid = ttrss_feeds.owner_uid
1199 AND ttrss_counters_cache.feed_id = id";
1200
1201 $result = db_query($query);
1202
1203 while ($line = db_fetch_assoc($result)) {
1204
1205 $id = $line["id"];
1206 $count = $line["count"];
1207 $last_error = htmlspecialchars($line["last_error"]);
1208
1209 $last_updated = make_local_datetime($line['last_updated'], false);
1210
1211 $has_img = feed_has_icon($id);
1212
1213 if (date('Y') - date('Y', strtotime($line['last_updated'])) > 2)
1214 $last_updated = '';
1215
1216 $cv = array("id" => $id,
1217 "updated" => $last_updated,
1218 "counter" => (int) $count,
1219 "has_img" => (int) $has_img);
1220
1221 if ($last_error)
1222 $cv["error"] = $last_error;
1223
1224// if (get_pref('EXTENDED_FEEDLIST'))
1225// $cv["xmsg"] = getFeedArticles($id)." ".__("total");
1226
1227 if ($active_feed && $id == $active_feed)
1228 $cv["title"] = truncate_string($line["title"], 30);
1229
1230 array_push($ret_arr, $cv);
1231
1232 }
1233
1234 return $ret_arr;
1235 }
1236
86a8351c 1237 /*function get_pgsql_version() {
ff5cc7d7
AD
1238 $result = db_query("SELECT version() AS version");
1239 $version = explode(" ", db_fetch_result($result, 0, "version"));
1240 return $version[1];
86a8351c 1241 }*/
ff5cc7d7 1242
ff5cc7d7
AD
1243 function checkbox_to_sql_bool($val) {
1244 return ($val == "on") ? "true" : "false";
1245 }
1246
86a8351c 1247 /*function getFeedCatTitle($id) {
ff5cc7d7
AD
1248 if ($id == -1) {
1249 return __("Special");
1250 } else if ($id < LABEL_BASE_INDEX) {
1251 return __("Labels");
1252 } else if ($id > 0) {
1253 $result = db_query("SELECT ttrss_feed_categories.title
1254 FROM ttrss_feeds, ttrss_feed_categories WHERE ttrss_feeds.id = '$id' AND
1255 cat_id = ttrss_feed_categories.id");
1256 if (db_num_rows($result) == 1) {
1257 return db_fetch_result($result, 0, "title");
1258 } else {
1259 return __("Uncategorized");
1260 }
1261 } else {
1262 return "getFeedCatTitle($id) failed";
1263 }
1264
86a8351c 1265 }*/
ff5cc7d7 1266
3ceb893f
AD
1267 function uniqid_short() {
1268 return uniqid(base_convert(rand(), 10, 36));
1269 }
1270
ff5cc7d7
AD
1271 // TODO: less dumb splitting
1272 require_once "functions2.php";