]> git.wh0rd.org - tt-rss.git/blob - include/functions.php
d5a75843f10d86200b33f7e2676fb4ef39d31dfa
[tt-rss.git] / include / functions.php
1 <?php
2 define('EXPECTED_CONFIG_VERSION', 26);
3 define('SCHEMA_VERSION', 130);
4
5 define('LABEL_BASE_INDEX', -1024);
6 define('PLUGIN_FEED_BASE_INDEX', -128);
7
8 define('COOKIE_LIFETIME_LONG', 86400*365);
9
10 $fetch_last_error = false;
11 $fetch_last_error_code = false;
12 $fetch_last_content_type = false;
13 $fetch_last_error_content = false; // curl only for the time being
14 $fetch_curl_used = false;
15 $suppress_debugging = false;
16
17 libxml_disable_entity_loader(true);
18
19 // separate test because this is included before sanity checks
20 if (function_exists("mb_internal_encoding")) mb_internal_encoding("UTF-8");
21
22 date_default_timezone_set('UTC');
23 if (defined('E_DEPRECATED')) {
24 error_reporting(E_ALL & ~E_NOTICE & ~E_DEPRECATED);
25 } else {
26 error_reporting(E_ALL & ~E_NOTICE);
27 }
28
29 require_once 'config.php';
30
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) {
40 defined($name) or define($name, $value);
41 }
42
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
55
56 if (DB_TYPE == "pgsql") {
57 define('SUBSTRING_FOR_DATE', 'SUBSTRING_FOR_DATE');
58 } else {
59 define('SUBSTRING_FOR_DATE', 'SUBSTRING');
60 }
61
62 /**
63 * Return available translations names.
64 *
65 * @access public
66 * @return array A array of available translations.
67 */
68 function get_translations() {
69 $tr = array(
70 "auto" => "Detect automatically",
71 "ar_SA" => "العربيّة (Arabic)",
72 "bg_BG" => "Bulgarian",
73 "da_DA" => "Dansk",
74 "ca_CA" => "Català",
75 "cs_CZ" => "Česky",
76 "en_US" => "English",
77 "el_GR" => "Ελληνικά",
78 "es_ES" => "Español (España)",
79 "es_LA" => "Español",
80 "de_DE" => "Deutsch",
81 "fr_FR" => "Français",
82 "hu_HU" => "Magyar (Hungarian)",
83 "it_IT" => "Italiano",
84 "ja_JP" => "日本語 (Japanese)",
85 "lv_LV" => "Latviešu",
86 "nb_NO" => "Norwegian bokmål",
87 "nl_NL" => "Dutch",
88 "pl_PL" => "Polski",
89 "ru_RU" => "Русский",
90 "pt_BR" => "Portuguese/Brazil",
91 "pt_PT" => "Portuguese/Portugal",
92 "zh_CN" => "Simplified Chinese",
93 "zh_TW" => "Traditional Chinese",
94 "sv_SE" => "Svenska",
95 "fi_FI" => "Suomi",
96 "tr_TR" => "Türkçe");
97
98 return $tr;
99 }
100
101 require_once "lib/accept-to-gettext.php";
102 require_once "lib/gettext/gettext.inc";
103
104 function startup_gettext() {
105
106 # Get locale from Accept-Language header
107 $lang = al2gt(array_keys(get_translations()), "text/html");
108
109 if (defined('_TRANSLATION_OVERRIDE_DEFAULT')) {
110 $lang = _TRANSLATION_OVERRIDE_DEFAULT;
111 }
112
113 if ($_SESSION["uid"] && get_schema_version() >= 120) {
114 $pref_lang = get_pref("USER_LANGUAGE", $_SESSION["uid"]);
115
116 if ($pref_lang && $pref_lang != 'auto') {
117 $lang = $pref_lang;
118 }
119 }
120
121 if ($lang) {
122 if (defined('LC_MESSAGES')) {
123 _setlocale(LC_MESSAGES, $lang);
124 } else if (defined('LC_ALL')) {
125 _setlocale(LC_ALL, $lang);
126 }
127
128 _bindtextdomain("messages", "locale");
129
130 _textdomain("messages");
131 _bind_textdomain_codeset("messages", "UTF-8");
132 }
133 }
134
135 require_once 'db-prefs.php';
136 require_once 'version.php';
137 require_once 'ccache.php';
138 require_once 'labels.php';
139 require_once 'controls.php';
140
141 define('SELF_USER_AGENT', 'Tiny Tiny RSS/' . VERSION . ' (http://tt-rss.org/)');
142 ini_set('user_agent', SELF_USER_AGENT);
143
144 require_once 'lib/pubsubhubbub/Publisher.php';
145
146 $schema_version = false;
147
148 function _debug_suppress($suppress) {
149 global $suppress_debugging;
150
151 $suppress_debugging = $suppress;
152 }
153
154 /**
155 * Print a timestamped debug message.
156 *
157 * @param string $msg The debug message.
158 * @return void
159 */
160 function _debug($msg, $show = true) {
161 global $suppress_debugging;
162
163 //echo "[$suppress_debugging] $msg $show\n";
164
165 if ($suppress_debugging) return false;
166
167 $ts = strftime("%H:%M:%S", time());
168 if (function_exists('posix_getpid')) {
169 $ts = "$ts/" . posix_getpid();
170 }
171
172 if ($show && !(defined('QUIET') && QUIET)) {
173 print "[$ts] $msg\n";
174 }
175
176 if (defined('LOGFILE')) {
177 $fp = fopen(LOGFILE, 'a+');
178
179 if ($fp) {
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
197 fputs($fp, "[$ts] $msg\n");
198
199 if (function_exists("flock")) {
200 flock($fp, LOCK_UN);
201 }
202
203 fclose($fp);
204 }
205 }
206
207 } // function _debug
208
209 /**
210 * Purge a feed old posts.
211 *
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 */
219 function purge_feed($feed_id, $purge_interval, $debug = false) {
220
221 if (!$purge_interval) $purge_interval = feed_purge_interval($feed_id);
222
223 $rows = -1;
224
225 $result = db_query(
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
234 if ($purge_interval == -1 || !$purge_interval) {
235 if ($owner_uid) {
236 ccache_update($feed_id, $owner_uid);
237 }
238 return;
239 }
240
241 if (!$owner_uid) return;
242
243 if (FORCE_ARTICLE_PURGE == 0) {
244 $purge_unread = get_pref("PURGE_UNREAD_ARTICLES",
245 $owner_uid, false);
246 } else {
247 $purge_unread = true;
248 $purge_interval = FORCE_ARTICLE_PURGE;
249 }
250
251 if (!$purge_unread) $query_limit = " unread = false AND ";
252
253 if (DB_TYPE == "pgsql") {
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'");
261
262 } else {
263
264 /* $result = db_query("DELETE FROM ttrss_user_entries WHERE
265 marked = false AND feed_id = '$feed_id' AND
266 (SELECT date_updated FROM ttrss_entries WHERE
267 id = ref_id) < DATE_SUB(NOW(), INTERVAL $purge_interval DAY)"); */
268
269 $result = db_query("DELETE FROM ttrss_user_entries
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
274 $query_limit
275 ttrss_entries.date_updated < DATE_SUB(NOW(), INTERVAL $purge_interval DAY)");
276 }
277
278 $rows = db_affected_rows($result);
279
280 ccache_update($feed_id, $owner_uid);
281
282 if ($debug) {
283 _debug("Purged feed $feed_id ($purge_interval): deleted $rows articles");
284 }
285
286 return $rows;
287 } // function purge_feed
288
289 function feed_purge_interval($feed_id) {
290
291 $result = db_query("SELECT purge_interval, owner_uid FROM ttrss_feeds
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
298 if ($purge_interval == 0) $purge_interval = get_pref(
299 'PURGE_OLD_DAYS', $owner_uid);
300
301 return $purge_interval;
302
303 } else {
304 return -1;
305 }
306 }
307
308 /*function get_feed_update_interval($feed_id) {
309 $result = db_query("SELECT owner_uid, update_interval FROM
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 {
319 return get_pref('DEFAULT_UPDATE_INTERVAL', $owner_uid, false);
320 }
321
322 } else {
323 return -1;
324 }
325 }*/
326
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*/) {
330
331 global $fetch_last_error;
332 global $fetch_last_error_code;
333 global $fetch_last_error_content;
334 global $fetch_last_content_type;
335 global $fetch_curl_used;
336
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
343 if (!is_array($options)) {
344
345 // falling back on compatibility shim
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(
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)
364 ); */
365 }
366
367 $url = $options["url"];
368 $type = isset($options["type"]) ? $options["type"] : false;
369 $login = isset($options["login"]) ? $options["login"] : false;
370 $pass = isset($options["pass"]) ? $options["pass"] : false;
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;
375 $followlocation = isset($options["followlocation"]) ? $options["followlocation"] : true;
376
377 $url = ltrim($url, ' ');
378 $url = str_replace(' ', '%20', $url);
379
380 if (strpos($url, "//") === 0)
381 $url = 'http:' . $url;
382
383 if (!defined('NO_CURL') && function_exists('curl_init') && !ini_get("open_basedir")) {
384
385 $fetch_curl_used = true;
386
387 $ch = curl_init($url);
388
389 if ($timestamp && !$post_query) {
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
394 curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout ? $timeout : FILE_FETCH_CONNECT_TIMEOUT);
395 curl_setopt($ch, CURLOPT_TIMEOUT, $timeout ? $timeout : FILE_FETCH_TIMEOUT);
396 curl_setopt($ch, CURLOPT_FOLLOWLOCATION, !ini_get("open_basedir") && $followlocation);
397 curl_setopt($ch, CURLOPT_MAXREDIRS, 20);
398 curl_setopt($ch, CURLOPT_BINARYTRANSFER, true);
399 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
400 curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
401 curl_setopt($ch, CURLOPT_USERAGENT, $useragent ? $useragent :
402 SELF_USER_AGENT);
403 curl_setopt($ch, CURLOPT_ENCODING, "");
404 //curl_setopt($ch, CURLOPT_REFERER, $url);
405
406 if (!ini_get("open_basedir")) {
407 curl_setopt($ch, CURLOPT_COOKIEJAR, "/dev/null");
408 }
409
410 if (defined('_CURL_HTTP_PROXY')) {
411 curl_setopt($ch, CURLOPT_PROXY, _CURL_HTTP_PROXY);
412 }
413
414 if ($post_query) {
415 curl_setopt($ch, CURLOPT_POST, true);
416 curl_setopt($ch, CURLOPT_POSTFIELDS, $post_query);
417 }
418
419 if ($login && $pass)
420 curl_setopt($ch, CURLOPT_USERPWD, "$login:$pass");
421
422 $contents = @curl_exec($ch);
423
424 if (curl_errno($ch) === 23 || curl_errno($ch) === 61) {
425 curl_setopt($ch, CURLOPT_ENCODING, 'none');
426 $contents = @curl_exec($ch);
427 }
428
429 if ($contents === false) {
430 $fetch_last_error = curl_errno($ch) . " " . curl_error($ch);
431 curl_close($ch);
432 return false;
433 }
434
435 $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
436 $fetch_last_content_type = curl_getinfo($ch, CURLINFO_CONTENT_TYPE);
437
438 $fetch_last_error_code = $http_code;
439
440 if ($http_code != 200 || $type && strpos($fetch_last_content_type, "$type") === false) {
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 }
446 $fetch_last_error_content = $contents;
447 curl_close($ch);
448 return false;
449 }
450
451 curl_close($ch);
452
453 return $contents;
454 } else {
455
456 $fetch_curl_used = false;
457
458 if ($login && $pass){
459 $url_parts = array();
460
461 preg_match("/(^[^:]*):\/\/(.*)/", $url, $url_parts);
462
463 $pass = urlencode($pass);
464
465 if ($url_parts[1] && $url_parts[2]) {
466 $url = $url_parts[1] . "://$login:$pass@" . $url_parts[2];
467 }
468 }
469
470 // TODO: should this support POST requests or not? idk
471
472 if (!$post_query && $timestamp) {
473 $context = stream_context_create(array(
474 'http' => array(
475 'method' => 'GET',
476 'ignore_errors' => true,
477 'timeout' => $timeout ? $timeout : FILE_FETCH_TIMEOUT,
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 )));
481 } else {
482 $context = stream_context_create(array(
483 'http' => array(
484 'method' => 'GET',
485 'ignore_errors' => true,
486 'timeout' => $timeout ? $timeout : FILE_FETCH_TIMEOUT,
487 'protocol_version'=> 1.1
488 )));
489 }
490
491 $old_error = error_get_last();
492
493 $data = @file_get_contents($url, false, $context);
494
495 if (isset($http_response_header) && is_array($http_response_header)) {
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 }
502
503 if (substr(strtolower($h), 0, 7) == 'http/1.') {
504 $fetch_last_error_code = (int) substr($h, 9, 3);
505 }
506 }
507 }
508
509 if ($fetch_last_error_code != 200) {
510 $error = error_get_last();
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 }
517
518 $fetch_last_error_content = $data;
519
520 return false;
521 }
522 return $data;
523 }
524
525 }
526
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
531 *
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 */
536 function get_favicon_url($url) {
537
538 $favicon_url = false;
539
540 if ($html = @fetch_file_contents($url)) {
541
542 libxml_use_internal_errors(true);
543
544 $doc = new DOMDocument();
545 $doc->loadHTML($html);
546 $xpath = new DOMXPath($doc);
547
548 $base = $xpath->query('/html/head/base');
549 foreach ($base as $b) {
550 $url = $b->getAttribute("href");
551 break;
552 }
553
554 $entries = $xpath->query('/html/head/link[@rel="shortcut icon" or @rel="icon"]');
555 if (count($entries) > 0) {
556 foreach ($entries as $entry) {
557 $favicon_url = rewrite_relative_url($url, $entry->getAttribute("href"));
558 break;
559 }
560 }
561 }
562
563 if (!$favicon_url)
564 $favicon_url = rewrite_relative_url($url, "/favicon.ico");
565
566 return $favicon_url;
567 } // function get_favicon_url
568
569 function initialize_user_prefs($uid, $profile = false) {
570
571 $uid = db_escape_string($uid);
572
573 if (!$profile) {
574 $profile = "NULL";
575 $profile_qpart = "AND profile IS NULL";
576 } else {
577 $profile_qpart = "AND profile = '$profile'";
578 }
579
580 if (get_schema_version() < 63) $profile_qpart = "";
581
582 db_query("BEGIN");
583
584 $result = db_query("SELECT pref_name,def_value FROM ttrss_prefs");
585
586 $u_result = db_query("SELECT pref_name
587 FROM ttrss_user_prefs WHERE owner_uid = '$uid' $profile_qpart");
588
589 $active_prefs = array();
590
591 while ($line = db_fetch_assoc($u_result)) {
592 array_push($active_prefs, $line["pref_name"]);
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
599 $line["def_value"] = db_escape_string($line["def_value"]);
600 $line["pref_name"] = db_escape_string($line["pref_name"]);
601
602 if (get_schema_version() < 63) {
603 db_query("INSERT INTO ttrss_user_prefs
604 (owner_uid,pref_name,value) VALUES
605 ('$uid', '".$line["pref_name"]."','".$line["def_value"]."')");
606
607 } else {
608 db_query("INSERT INTO ttrss_user_prefs
609 (owner_uid,pref_name,value, profile) VALUES
610 ('$uid', '".$line["pref_name"]."','".$line["def_value"]."', $profile)");
611 }
612
613 }
614 }
615
616 db_query("COMMIT");
617
618 }
619
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 }
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 }
633 return "";
634 }
635
636 function authenticate_user($login, $password, $check_only = false) {
637
638 if (!SINGLE_USER_MODE) {
639 $user_id = false;
640
641 foreach (PluginHost::getInstance()->get_hooks(PluginHost::HOOK_AUTH_USER) as $plugin) {
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 }
649 }
650
651 if ($user_id && !$check_only) {
652 @session_start();
653
654 $_SESSION["uid"] = $user_id;
655 $_SESSION["version"] = VERSION_STATIC;
656
657 $result = db_query("SELECT login,access_level,pwd_hash FROM ttrss_users
658 WHERE id = '$user_id'");
659
660 $_SESSION["name"] = db_fetch_result($result, 0, "login");
661 $_SESSION["access_level"] = db_fetch_result($result, 0, "access_level");
662 $_SESSION["csrf_token"] = uniqid_short();
663
664 db_query("UPDATE ttrss_users SET last_login = NOW() WHERE id = " .
665 $_SESSION["uid"]);
666
667 $_SESSION["ip_address"] = $_SERVER["REMOTE_ADDR"];
668 $_SESSION["user_agent"] = sha1($_SERVER['HTTP_USER_AGENT']);
669 $_SESSION["pwd_hash"] = db_fetch_result($result, 0, "pwd_hash");
670
671 $_SESSION["last_version_check"] = time();
672
673 initialize_user_prefs($_SESSION["uid"]);
674
675 return true;
676 }
677
678 return false;
679
680 } else {
681
682 $_SESSION["uid"] = 1;
683 $_SESSION["name"] = "admin";
684 $_SESSION["access_level"] = 10;
685
686 $_SESSION["hide_hello"] = true;
687 $_SESSION["hide_logout"] = true;
688
689 $_SESSION["auth_module"] = false;
690
691 if (!$_SESSION["csrf_token"]) {
692 $_SESSION["csrf_token"] = uniqid_short();
693 }
694
695 $_SESSION["ip_address"] = $_SERVER["REMOTE_ADDR"];
696
697 initialize_user_prefs($_SESSION["uid"]);
698
699 return true;
700 }
701 }
702
703 function make_password($length = 8) {
704
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;
719 }
720
721 // this is called after user is created to initialize default feeds, labels
722 // or whatever else
723
724 // user preferences are checked on every login, not here
725
726 function initialize_user($uid) {
727
728 db_query("insert into ttrss_feeds (owner_uid,title,feed_url)
729 values ('$uid', 'Tiny Tiny RSS: Forum',
730 'http://tt-rss.org/forum/rss.php')");
731 }
732
733 function logout_user() {
734 session_destroy();
735 if (isset($_COOKIE[session_name()])) {
736 setcookie(session_name(), '', time()-42000, '/');
737 }
738 }
739
740 function validate_csrf($csrf_token) {
741 return $csrf_token == $_SESSION['csrf_token'];
742 }
743
744 function load_user_plugins($owner_uid, $pluginhost = false) {
745
746 if (!$pluginhost) $pluginhost = PluginHost::getInstance();
747
748 if ($owner_uid && SCHEMA_VERSION >= 100) {
749 $plugins = get_pref("_ENABLED_PLUGINS", $owner_uid);
750
751 $pluginhost->load($plugins, PluginHost::KIND_USER, $owner_uid);
752
753 if (get_schema_version() > 100) {
754 $pluginhost->load_data();
755 }
756 }
757 }
758
759 function login_sequence() {
760 if (SINGLE_USER_MODE) {
761 @session_start();
762 authenticate_user("admin", null);
763 startup_gettext();
764 load_user_plugins($_SESSION["uid"]);
765 } else {
766 if (!validate_session()) $_SESSION["uid"] = false;
767
768 if (!$_SESSION["uid"]) {
769
770 if (AUTH_AUTO_LOGIN && authenticate_user(null, null)) {
771 $_SESSION["ref_schema_version"] = get_schema_version(true);
772 } else {
773 authenticate_user(null, null, true);
774 }
775
776 if (!$_SESSION["uid"]) {
777 @session_destroy();
778 setcookie(session_name(), '', time()-42000, '/');
779
780 render_login_form();
781 exit;
782 }
783
784 } else {
785 /* bump login timestamp */
786 db_query("UPDATE ttrss_users SET last_login = NOW() WHERE id = " .
787 $_SESSION["uid"]);
788 $_SESSION["last_login_update"] = time();
789 }
790
791 if ($_SESSION["uid"]) {
792 startup_gettext();
793 load_user_plugins($_SESSION["uid"]);
794
795 /* cleanup ccache */
796
797 db_query("DELETE FROM ttrss_counters_cache WHERE owner_uid = ".
798 $_SESSION["uid"] . " AND
799 (SELECT COUNT(id) FROM ttrss_feeds WHERE
800 ttrss_feeds.id = feed_id) = 0");
801
802 db_query("DELETE FROM ttrss_cat_counters_cache WHERE owner_uid = ".
803 $_SESSION["uid"] . " AND
804 (SELECT COUNT(id) FROM ttrss_feed_categories WHERE
805 ttrss_feed_categories.id = feed_id) = 0");
806
807 }
808
809 }
810 }
811
812 function truncate_string($str, $max_len, $suffix = '&hellip;') {
813 if (mb_strlen($str, "utf-8") > $max_len) {
814 return mb_substr($str, 0, $max_len, "utf-8") . $suffix;
815 } else {
816 return $str;
817 }
818 }
819
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
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
847 function make_local_datetime($timestamp, $long, $owner_uid = false,
848 $no_smart_dt = false, $eta_min = false) {
849
850 if (!$owner_uid) $owner_uid = $_SESSION['uid'];
851 if (!$timestamp) $timestamp = '1970-01-01 0:00';
852
853 global $utc_tz;
854 global $user_tz;
855
856 if (!$utc_tz) $utc_tz = new DateTimeZone('UTC');
857
858 $timestamp = substr($timestamp, 0, 19);
859
860 # We store date in UTC internally
861 $dt = new DateTime($timestamp, $utc_tz);
862
863 $user_tz_string = get_pref('USER_TIMEZONE', $owner_uid);
864
865 if ($user_tz_string != 'Automatic') {
866
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 {
875 $tz_offset = (int) -$_SESSION["clientTzOffset"];
876 }
877
878 $user_timestamp = $dt->format('U') + $tz_offset;
879
880 if (!$no_smart_dt) {
881 return smart_date_time($user_timestamp,
882 $tz_offset, $owner_uid, $eta_min);
883 } else {
884 if ($long)
885 $format = get_pref('LONG_DATE_FORMAT', $owner_uid);
886 else
887 $format = get_pref('SHORT_DATE_FORMAT', $owner_uid);
888
889 return date($format, $user_timestamp);
890 }
891 }
892
893 function smart_date_time($timestamp, $tz_offset = 0, $owner_uid = false, $eta_min = false) {
894 if (!$owner_uid) $owner_uid = $_SESSION['uid'];
895
896 if ($eta_min && time() + $tz_offset - $timestamp < 3600) {
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)) {
899 return date("G:i", $timestamp);
900 } else if (date("Y", $timestamp) == date("Y", time() + $tz_offset)) {
901 $format = get_pref('SHORT_DATE_FORMAT', $owner_uid);
902 return date($format, $timestamp);
903 } else {
904 $format = get_pref('LONG_DATE_FORMAT', $owner_uid);
905 return date($format, $timestamp);
906 }
907 }
908
909 function sql_bool_to_bool($s) {
910 if ($s == "t" || $s == "1" || strtolower($s) == "true") {
911 return true;
912 } else {
913 return false;
914 }
915 }
916
917 function bool_to_sql_bool($s) {
918 if ($s) {
919 return "true";
920 } else {
921 return "false";
922 }
923 }
924
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.
928 function get_schema_version($nocache = false) {
929 global $schema_version;
930
931 if (!$schema_version && !$nocache) {
932 $result = db_query("SELECT schema_version FROM ttrss_version");
933 $version = db_fetch_result($result, 0, "schema_version");
934 $schema_version = $version;
935 return $version;
936 } else {
937 return $schema_version;
938 }
939 }
940
941 function sanity_check() {
942 require_once 'errors.php';
943 global $ERRORS;
944
945 $error_code = 0;
946 $schema_version = get_schema_version(true);
947
948 if ($schema_version != SCHEMA_VERSION) {
949 $error_code = 5;
950 }
951
952 if (DB_TYPE == "mysql") {
953 $result = db_query("SELECT true", false);
954 if (db_num_rows($result) != 1) {
955 $error_code = 10;
956 }
957 }
958
959 if (db_escape_string("testTEST") != "testTEST") {
960 $error_code = 12;
961 }
962
963 return array("code" => $error_code, "message" => $ERRORS[$error_code]);
964 }
965
966 function file_is_locked($filename) {
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 }
976 fclose($fp);
977 return true;
978 } else {
979 return false;
980 }
981 }
982 return true; // consider the file always locked and skip the test
983 } else {
984 return false;
985 }
986 }
987
988
989 function make_lockfile($filename) {
990 $fp = fopen(LOCK_DIRECTORY . "/$filename", "w");
991
992 if ($fp && flock($fp, LOCK_EX | LOCK_NB)) {
993 $stat_h = fstat($fp);
994 $stat_f = stat(LOCK_DIRECTORY . "/$filename");
995
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 }
1002 }
1003
1004 if (function_exists('posix_getpid')) {
1005 fwrite($fp, posix_getpid() . "\n");
1006 }
1007 return $fp;
1008 } else {
1009 return false;
1010 }
1011 }
1012
1013 function make_stampfile($filename) {
1014 $fp = fopen(LOCK_DIRECTORY . "/$filename", "w");
1015
1016 if (flock($fp, LOCK_EX | LOCK_NB)) {
1017 fwrite($fp, time() . "\n");
1018 flock($fp, LOCK_UN);
1019 fclose($fp);
1020 return true;
1021 } else {
1022 return false;
1023 }
1024 }
1025
1026 function sql_random_function() {
1027 if (DB_TYPE == "mysql") {
1028 return "RAND()";
1029 } else {
1030 return "RANDOM()";
1031 }
1032 }
1033
1034 function getAllCounters() {
1035 $data = getGlobalCounters();
1036
1037 $data = array_merge($data, getVirtCounters());
1038 $data = array_merge($data, getLabelCounters());
1039 $data = array_merge($data, getFeedCounters());
1040 $data = array_merge($data, getCategoryCounters());
1041
1042 return $data;
1043 }
1044
1045 function getCategoryCounters() {
1046 $ret_arr = array();
1047
1048 /* Labels category */
1049
1050 $cv = array("id" => -2, "kind" => "cat",
1051 "counter" => Feeds::getCategoryUnread(-2));
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) {
1067 $child_counter = Feeds::getCategoryChildrenUnread($line["cat_id"], $_SESSION["uid"]);
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
1088 function getFeedUnread($feed, $is_cat = false) {
1089 return Feeds::getFeedArticles($feed, $is_cat, true, $_SESSION["uid"]);
1090 }
1091
1092 function getGlobalCounters($global_unread = -1) {
1093 $ret_arr = array();
1094
1095 if ($global_unread == -1) {
1096 $global_unread = Feeds::getGlobalUnread();
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)
1126 $auxctr = Feeds::getFeedArticles($i, false);
1127 else
1128 $auxctr = 0;
1129
1130 $cv = array("id" => $i,
1131 "counter" => (int) $count,
1132 "auxcounter" => (int) $auxctr);
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
1167 WHERE ttrss_labels2.owner_uid = $owner_uid AND u1.owner_uid = $owner_uid
1168 GROUP BY ttrss_labels2.id,
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
1237 /*function get_pgsql_version() {
1238 $result = db_query("SELECT version() AS version");
1239 $version = explode(" ", db_fetch_result($result, 0, "version"));
1240 return $version[1];
1241 }*/
1242
1243 function checkbox_to_sql_bool($val) {
1244 return ($val == "on") ? "true" : "false";
1245 }
1246
1247 /*function getFeedCatTitle($id) {
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
1265 }*/
1266
1267 function uniqid_short() {
1268 return uniqid(base_convert(rand(), 10, 36));
1269 }
1270
1271 // TODO: less dumb splitting
1272 require_once "functions2.php";