]> git.wh0rd.org - tt-rss.git/blob - include/functions.php
17c3d8c4b397b9cbdaeea109d8a8bdb4b44e8ca8
[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 purge_orphans($do_output = false) {
309
310 // purge orphaned posts in main content table
311 $result = db_query("DELETE FROM ttrss_entries WHERE
312 NOT EXISTS (SELECT ref_id FROM ttrss_user_entries WHERE ref_id = id)");
313
314 if ($do_output) {
315 $rows = db_affected_rows($result);
316 _debug("Purged $rows orphaned posts.");
317 }
318 }
319
320 function get_feed_update_interval($feed_id) {
321 $result = db_query("SELECT owner_uid, update_interval FROM
322 ttrss_feeds WHERE id = '$feed_id'");
323
324 if (db_num_rows($result) == 1) {
325 $update_interval = db_fetch_result($result, 0, "update_interval");
326 $owner_uid = db_fetch_result($result, 0, "owner_uid");
327
328 if ($update_interval != 0) {
329 return $update_interval;
330 } else {
331 return get_pref('DEFAULT_UPDATE_INTERVAL', $owner_uid, false);
332 }
333
334 } else {
335 return -1;
336 }
337 }
338
339 // TODO: multiple-argument way is deprecated, first parameter is a hash now
340 function fetch_file_contents($options /* previously: 0: $url , 1: $type = false, 2: $login = false, 3: $pass = false,
341 4: $post_query = false, 5: $timeout = false, 6: $timestamp = 0, 7: $useragent = false*/) {
342
343 global $fetch_last_error;
344 global $fetch_last_error_code;
345 global $fetch_last_error_content;
346 global $fetch_last_content_type;
347 global $fetch_curl_used;
348
349 $fetch_last_error = false;
350 $fetch_last_error_code = -1;
351 $fetch_last_error_content = "";
352 $fetch_last_content_type = "";
353 $fetch_curl_used = false;
354
355 if (!is_array($options)) {
356
357 // falling back on compatibility shim
358 $option_names = [ "url", "type", "login", "pass", "post_query", "timeout", "timestamp", "useragent" ];
359 $tmp = [];
360
361 for ($i = 0; $i < func_num_args(); $i++) {
362 $tmp[$option_names[$i]] = func_get_arg($i);
363 }
364
365 $options = $tmp;
366
367 /*$options = array(
368 "url" => func_get_arg(0),
369 "type" => @func_get_arg(1),
370 "login" => @func_get_arg(2),
371 "pass" => @func_get_arg(3),
372 "post_query" => @func_get_arg(4),
373 "timeout" => @func_get_arg(5),
374 "timestamp" => @func_get_arg(6),
375 "useragent" => @func_get_arg(7)
376 ); */
377 }
378
379 $url = $options["url"];
380 $type = isset($options["type"]) ? $options["type"] : false;
381 $login = isset($options["login"]) ? $options["login"] : false;
382 $pass = isset($options["pass"]) ? $options["pass"] : false;
383 $post_query = isset($options["post_query"]) ? $options["post_query"] : false;
384 $timeout = isset($options["timeout"]) ? $options["timeout"] : false;
385 $timestamp = isset($options["timestamp"]) ? $options["timestamp"] : 0;
386 $useragent = isset($options["useragent"]) ? $options["useragent"] : false;
387 $followlocation = isset($options["followlocation"]) ? $options["followlocation"] : true;
388
389 $url = ltrim($url, ' ');
390 $url = str_replace(' ', '%20', $url);
391
392 if (strpos($url, "//") === 0)
393 $url = 'http:' . $url;
394
395 if (!defined('NO_CURL') && function_exists('curl_init') && !ini_get("open_basedir")) {
396
397 $fetch_curl_used = true;
398
399 $ch = curl_init($url);
400
401 if ($timestamp && !$post_query) {
402 curl_setopt($ch, CURLOPT_HTTPHEADER,
403 array("If-Modified-Since: ".gmdate('D, d M Y H:i:s \G\M\T', $timestamp)));
404 }
405
406 curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout ? $timeout : FILE_FETCH_CONNECT_TIMEOUT);
407 curl_setopt($ch, CURLOPT_TIMEOUT, $timeout ? $timeout : FILE_FETCH_TIMEOUT);
408 curl_setopt($ch, CURLOPT_FOLLOWLOCATION, !ini_get("open_basedir") && $followlocation);
409 curl_setopt($ch, CURLOPT_MAXREDIRS, 20);
410 curl_setopt($ch, CURLOPT_BINARYTRANSFER, true);
411 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
412 curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
413 curl_setopt($ch, CURLOPT_USERAGENT, $useragent ? $useragent :
414 SELF_USER_AGENT);
415 curl_setopt($ch, CURLOPT_ENCODING, "");
416 //curl_setopt($ch, CURLOPT_REFERER, $url);
417
418 if (!ini_get("open_basedir")) {
419 curl_setopt($ch, CURLOPT_COOKIEJAR, "/dev/null");
420 }
421
422 if (defined('_CURL_HTTP_PROXY')) {
423 curl_setopt($ch, CURLOPT_PROXY, _CURL_HTTP_PROXY);
424 }
425
426 if ($post_query) {
427 curl_setopt($ch, CURLOPT_POST, true);
428 curl_setopt($ch, CURLOPT_POSTFIELDS, $post_query);
429 }
430
431 if ($login && $pass)
432 curl_setopt($ch, CURLOPT_USERPWD, "$login:$pass");
433
434 $contents = @curl_exec($ch);
435
436 if (curl_errno($ch) === 23 || curl_errno($ch) === 61) {
437 curl_setopt($ch, CURLOPT_ENCODING, 'none');
438 $contents = @curl_exec($ch);
439 }
440
441 if ($contents === false) {
442 $fetch_last_error = curl_errno($ch) . " " . curl_error($ch);
443 curl_close($ch);
444 return false;
445 }
446
447 $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
448 $fetch_last_content_type = curl_getinfo($ch, CURLINFO_CONTENT_TYPE);
449
450 $fetch_last_error_code = $http_code;
451
452 if ($http_code != 200 || $type && strpos($fetch_last_content_type, "$type") === false) {
453 if (curl_errno($ch) != 0) {
454 $fetch_last_error = curl_errno($ch) . " " . curl_error($ch);
455 } else {
456 $fetch_last_error = "HTTP Code: $http_code";
457 }
458 $fetch_last_error_content = $contents;
459 curl_close($ch);
460 return false;
461 }
462
463 curl_close($ch);
464
465 return $contents;
466 } else {
467
468 $fetch_curl_used = false;
469
470 if ($login && $pass){
471 $url_parts = array();
472
473 preg_match("/(^[^:]*):\/\/(.*)/", $url, $url_parts);
474
475 $pass = urlencode($pass);
476
477 if ($url_parts[1] && $url_parts[2]) {
478 $url = $url_parts[1] . "://$login:$pass@" . $url_parts[2];
479 }
480 }
481
482 // TODO: should this support POST requests or not? idk
483
484 if (!$post_query && $timestamp) {
485 $context = stream_context_create(array(
486 'http' => array(
487 'method' => 'GET',
488 'ignore_errors' => true,
489 'timeout' => $timeout ? $timeout : FILE_FETCH_TIMEOUT,
490 'protocol_version'=> 1.1,
491 'header' => "If-Modified-Since: ".gmdate("D, d M Y H:i:s \\G\\M\\T\r\n", $timestamp)
492 )));
493 } else {
494 $context = stream_context_create(array(
495 'http' => array(
496 'method' => 'GET',
497 'ignore_errors' => true,
498 'timeout' => $timeout ? $timeout : FILE_FETCH_TIMEOUT,
499 'protocol_version'=> 1.1
500 )));
501 }
502
503 $old_error = error_get_last();
504
505 $data = @file_get_contents($url, false, $context);
506
507 if (isset($http_response_header) && is_array($http_response_header)) {
508 foreach ($http_response_header as $h) {
509 if (substr(strtolower($h), 0, 13) == 'content-type:') {
510 $fetch_last_content_type = substr($h, 14);
511 // don't abort here b/c there might be more than one
512 // e.g. if we were being redirected -- last one is the right one
513 }
514
515 if (substr(strtolower($h), 0, 7) == 'http/1.') {
516 $fetch_last_error_code = (int) substr($h, 9, 3);
517 }
518 }
519 }
520
521 if ($fetch_last_error_code != 200) {
522 $error = error_get_last();
523
524 if ($error['message'] != $old_error['message']) {
525 $fetch_last_error = $error["message"];
526 } else {
527 $fetch_last_error = "HTTP Code: $fetch_last_error_code";
528 }
529
530 $fetch_last_error_content = $data;
531
532 return false;
533 }
534 return $data;
535 }
536
537 }
538
539 /**
540 * Try to determine the favicon URL for a feed.
541 * adapted from wordpress favicon plugin by Jeff Minard (http://thecodepro.com/)
542 * http://dev.wp-plugins.org/file/favatars/trunk/favatars.php
543 *
544 * @param string $url A feed or page URL
545 * @access public
546 * @return mixed The favicon URL, or false if none was found.
547 */
548 function get_favicon_url($url) {
549
550 $favicon_url = false;
551
552 if ($html = @fetch_file_contents($url)) {
553
554 libxml_use_internal_errors(true);
555
556 $doc = new DOMDocument();
557 $doc->loadHTML($html);
558 $xpath = new DOMXPath($doc);
559
560 $base = $xpath->query('/html/head/base');
561 foreach ($base as $b) {
562 $url = $b->getAttribute("href");
563 break;
564 }
565
566 $entries = $xpath->query('/html/head/link[@rel="shortcut icon" or @rel="icon"]');
567 if (count($entries) > 0) {
568 foreach ($entries as $entry) {
569 $favicon_url = rewrite_relative_url($url, $entry->getAttribute("href"));
570 break;
571 }
572 }
573 }
574
575 if (!$favicon_url)
576 $favicon_url = rewrite_relative_url($url, "/favicon.ico");
577
578 return $favicon_url;
579 } // function get_favicon_url
580
581 function check_feed_favicon($site_url, $feed) {
582 # print "FAVICON [$site_url]: $favicon_url\n";
583
584 $icon_file = ICONS_DIR . "/$feed.ico";
585
586 if (!file_exists($icon_file)) {
587 $favicon_url = get_favicon_url($site_url);
588
589 if ($favicon_url) {
590 // Limiting to "image" type misses those served with text/plain
591 $contents = fetch_file_contents($favicon_url); // , "image");
592
593 if ($contents) {
594 // Crude image type matching.
595 // Patterns gleaned from the file(1) source code.
596 if (preg_match('/^\x00\x00\x01\x00/', $contents)) {
597 // 0 string \000\000\001\000 MS Windows icon resource
598 //error_log("check_feed_favicon: favicon_url=$favicon_url isa MS Windows icon resource");
599 }
600 elseif (preg_match('/^GIF8/', $contents)) {
601 // 0 string GIF8 GIF image data
602 //error_log("check_feed_favicon: favicon_url=$favicon_url isa GIF image");
603 }
604 elseif (preg_match('/^\x89PNG\x0d\x0a\x1a\x0a/', $contents)) {
605 // 0 string \x89PNG\x0d\x0a\x1a\x0a PNG image data
606 //error_log("check_feed_favicon: favicon_url=$favicon_url isa PNG image");
607 }
608 elseif (preg_match('/^\xff\xd8/', $contents)) {
609 // 0 beshort 0xffd8 JPEG image data
610 //error_log("check_feed_favicon: favicon_url=$favicon_url isa JPG image");
611 }
612 else {
613 //error_log("check_feed_favicon: favicon_url=$favicon_url isa UNKNOWN type");
614 $contents = "";
615 }
616 }
617
618 if ($contents) {
619 $fp = @fopen($icon_file, "w");
620
621 if ($fp) {
622 fwrite($fp, $contents);
623 fclose($fp);
624 chmod($icon_file, 0644);
625 }
626 }
627 }
628 return $icon_file;
629 }
630 }
631
632 function initialize_user_prefs($uid, $profile = false) {
633
634 $uid = db_escape_string($uid);
635
636 if (!$profile) {
637 $profile = "NULL";
638 $profile_qpart = "AND profile IS NULL";
639 } else {
640 $profile_qpart = "AND profile = '$profile'";
641 }
642
643 if (get_schema_version() < 63) $profile_qpart = "";
644
645 db_query("BEGIN");
646
647 $result = db_query("SELECT pref_name,def_value FROM ttrss_prefs");
648
649 $u_result = db_query("SELECT pref_name
650 FROM ttrss_user_prefs WHERE owner_uid = '$uid' $profile_qpart");
651
652 $active_prefs = array();
653
654 while ($line = db_fetch_assoc($u_result)) {
655 array_push($active_prefs, $line["pref_name"]);
656 }
657
658 while ($line = db_fetch_assoc($result)) {
659 if (array_search($line["pref_name"], $active_prefs) === FALSE) {
660 // print "adding " . $line["pref_name"] . "<br>";
661
662 $line["def_value"] = db_escape_string($line["def_value"]);
663 $line["pref_name"] = db_escape_string($line["pref_name"]);
664
665 if (get_schema_version() < 63) {
666 db_query("INSERT INTO ttrss_user_prefs
667 (owner_uid,pref_name,value) VALUES
668 ('$uid', '".$line["pref_name"]."','".$line["def_value"]."')");
669
670 } else {
671 db_query("INSERT INTO ttrss_user_prefs
672 (owner_uid,pref_name,value, profile) VALUES
673 ('$uid', '".$line["pref_name"]."','".$line["def_value"]."', $profile)");
674 }
675
676 }
677 }
678
679 db_query("COMMIT");
680
681 }
682
683 function get_ssl_certificate_id() {
684 if ($_SERVER["REDIRECT_SSL_CLIENT_M_SERIAL"]) {
685 return sha1($_SERVER["REDIRECT_SSL_CLIENT_M_SERIAL"] .
686 $_SERVER["REDIRECT_SSL_CLIENT_V_START"] .
687 $_SERVER["REDIRECT_SSL_CLIENT_V_END"] .
688 $_SERVER["REDIRECT_SSL_CLIENT_S_DN"]);
689 }
690 if ($_SERVER["SSL_CLIENT_M_SERIAL"]) {
691 return sha1($_SERVER["SSL_CLIENT_M_SERIAL"] .
692 $_SERVER["SSL_CLIENT_V_START"] .
693 $_SERVER["SSL_CLIENT_V_END"] .
694 $_SERVER["SSL_CLIENT_S_DN"]);
695 }
696 return "";
697 }
698
699 function authenticate_user($login, $password, $check_only = false) {
700
701 if (!SINGLE_USER_MODE) {
702 $user_id = false;
703
704 foreach (PluginHost::getInstance()->get_hooks(PluginHost::HOOK_AUTH_USER) as $plugin) {
705
706 $user_id = (int) $plugin->authenticate($login, $password);
707
708 if ($user_id) {
709 $_SESSION["auth_module"] = strtolower(get_class($plugin));
710 break;
711 }
712 }
713
714 if ($user_id && !$check_only) {
715 @session_start();
716
717 $_SESSION["uid"] = $user_id;
718 $_SESSION["version"] = VERSION_STATIC;
719
720 $result = db_query("SELECT login,access_level,pwd_hash FROM ttrss_users
721 WHERE id = '$user_id'");
722
723 $_SESSION["name"] = db_fetch_result($result, 0, "login");
724 $_SESSION["access_level"] = db_fetch_result($result, 0, "access_level");
725 $_SESSION["csrf_token"] = uniqid_short();
726
727 db_query("UPDATE ttrss_users SET last_login = NOW() WHERE id = " .
728 $_SESSION["uid"]);
729
730 $_SESSION["ip_address"] = $_SERVER["REMOTE_ADDR"];
731 $_SESSION["user_agent"] = sha1($_SERVER['HTTP_USER_AGENT']);
732 $_SESSION["pwd_hash"] = db_fetch_result($result, 0, "pwd_hash");
733
734 $_SESSION["last_version_check"] = time();
735
736 initialize_user_prefs($_SESSION["uid"]);
737
738 return true;
739 }
740
741 return false;
742
743 } else {
744
745 $_SESSION["uid"] = 1;
746 $_SESSION["name"] = "admin";
747 $_SESSION["access_level"] = 10;
748
749 $_SESSION["hide_hello"] = true;
750 $_SESSION["hide_logout"] = true;
751
752 $_SESSION["auth_module"] = false;
753
754 if (!$_SESSION["csrf_token"]) {
755 $_SESSION["csrf_token"] = uniqid_short();
756 }
757
758 $_SESSION["ip_address"] = $_SERVER["REMOTE_ADDR"];
759
760 initialize_user_prefs($_SESSION["uid"]);
761
762 return true;
763 }
764 }
765
766 function make_password($length = 8) {
767
768 $password = "";
769 $possible = "0123456789abcdfghjkmnpqrstvwxyzABCDFGHJKMNPQRSTVWXYZ";
770
771 $i = 0;
772
773 while ($i < $length) {
774 $char = substr($possible, mt_rand(0, strlen($possible)-1), 1);
775
776 if (!strstr($password, $char)) {
777 $password .= $char;
778 $i++;
779 }
780 }
781 return $password;
782 }
783
784 // this is called after user is created to initialize default feeds, labels
785 // or whatever else
786
787 // user preferences are checked on every login, not here
788
789 function initialize_user($uid) {
790
791 db_query("insert into ttrss_feeds (owner_uid,title,feed_url)
792 values ('$uid', 'Tiny Tiny RSS: Forum',
793 'http://tt-rss.org/forum/rss.php')");
794 }
795
796 function logout_user() {
797 session_destroy();
798 if (isset($_COOKIE[session_name()])) {
799 setcookie(session_name(), '', time()-42000, '/');
800 }
801 }
802
803 function validate_csrf($csrf_token) {
804 return $csrf_token == $_SESSION['csrf_token'];
805 }
806
807 function load_user_plugins($owner_uid, $pluginhost = false) {
808
809 if (!$pluginhost) $pluginhost = PluginHost::getInstance();
810
811 if ($owner_uid && SCHEMA_VERSION >= 100) {
812 $plugins = get_pref("_ENABLED_PLUGINS", $owner_uid);
813
814 $pluginhost->load($plugins, PluginHost::KIND_USER, $owner_uid);
815
816 if (get_schema_version() > 100) {
817 $pluginhost->load_data();
818 }
819 }
820 }
821
822 function login_sequence() {
823 if (SINGLE_USER_MODE) {
824 @session_start();
825 authenticate_user("admin", null);
826 startup_gettext();
827 load_user_plugins($_SESSION["uid"]);
828 } else {
829 if (!validate_session()) $_SESSION["uid"] = false;
830
831 if (!$_SESSION["uid"]) {
832
833 if (AUTH_AUTO_LOGIN && authenticate_user(null, null)) {
834 $_SESSION["ref_schema_version"] = get_schema_version(true);
835 } else {
836 authenticate_user(null, null, true);
837 }
838
839 if (!$_SESSION["uid"]) {
840 @session_destroy();
841 setcookie(session_name(), '', time()-42000, '/');
842
843 render_login_form();
844 exit;
845 }
846
847 } else {
848 /* bump login timestamp */
849 db_query("UPDATE ttrss_users SET last_login = NOW() WHERE id = " .
850 $_SESSION["uid"]);
851 $_SESSION["last_login_update"] = time();
852 }
853
854 if ($_SESSION["uid"]) {
855 startup_gettext();
856 load_user_plugins($_SESSION["uid"]);
857
858 /* cleanup ccache */
859
860 db_query("DELETE FROM ttrss_counters_cache WHERE owner_uid = ".
861 $_SESSION["uid"] . " AND
862 (SELECT COUNT(id) FROM ttrss_feeds WHERE
863 ttrss_feeds.id = feed_id) = 0");
864
865 db_query("DELETE FROM ttrss_cat_counters_cache WHERE owner_uid = ".
866 $_SESSION["uid"] . " AND
867 (SELECT COUNT(id) FROM ttrss_feed_categories WHERE
868 ttrss_feed_categories.id = feed_id) = 0");
869
870 }
871
872 }
873 }
874
875 function truncate_string($str, $max_len, $suffix = '&hellip;') {
876 if (mb_strlen($str, "utf-8") > $max_len) {
877 return mb_substr($str, 0, $max_len, "utf-8") . $suffix;
878 } else {
879 return $str;
880 }
881 }
882
883 // is not utf8 clean
884 function truncate_middle($str, $max_len, $suffix = '&hellip;') {
885 if (strlen($str) > $max_len) {
886 return substr_replace($str, $suffix, $max_len / 2, mb_strlen($str) - $max_len);
887 } else {
888 return $str;
889 }
890 }
891
892 function convert_timestamp($timestamp, $source_tz, $dest_tz) {
893
894 try {
895 $source_tz = new DateTimeZone($source_tz);
896 } catch (Exception $e) {
897 $source_tz = new DateTimeZone('UTC');
898 }
899
900 try {
901 $dest_tz = new DateTimeZone($dest_tz);
902 } catch (Exception $e) {
903 $dest_tz = new DateTimeZone('UTC');
904 }
905
906 $dt = new DateTime(date('Y-m-d H:i:s', $timestamp), $source_tz);
907 return $dt->format('U') + $dest_tz->getOffset($dt);
908 }
909
910 function make_local_datetime($timestamp, $long, $owner_uid = false,
911 $no_smart_dt = false, $eta_min = false) {
912
913 if (!$owner_uid) $owner_uid = $_SESSION['uid'];
914 if (!$timestamp) $timestamp = '1970-01-01 0:00';
915
916 global $utc_tz;
917 global $user_tz;
918
919 if (!$utc_tz) $utc_tz = new DateTimeZone('UTC');
920
921 $timestamp = substr($timestamp, 0, 19);
922
923 # We store date in UTC internally
924 $dt = new DateTime($timestamp, $utc_tz);
925
926 $user_tz_string = get_pref('USER_TIMEZONE', $owner_uid);
927
928 if ($user_tz_string != 'Automatic') {
929
930 try {
931 if (!$user_tz) $user_tz = new DateTimeZone($user_tz_string);
932 } catch (Exception $e) {
933 $user_tz = $utc_tz;
934 }
935
936 $tz_offset = $user_tz->getOffset($dt);
937 } else {
938 $tz_offset = (int) -$_SESSION["clientTzOffset"];
939 }
940
941 $user_timestamp = $dt->format('U') + $tz_offset;
942
943 if (!$no_smart_dt) {
944 return smart_date_time($user_timestamp,
945 $tz_offset, $owner_uid, $eta_min);
946 } else {
947 if ($long)
948 $format = get_pref('LONG_DATE_FORMAT', $owner_uid);
949 else
950 $format = get_pref('SHORT_DATE_FORMAT', $owner_uid);
951
952 return date($format, $user_timestamp);
953 }
954 }
955
956 function smart_date_time($timestamp, $tz_offset = 0, $owner_uid = false, $eta_min = false) {
957 if (!$owner_uid) $owner_uid = $_SESSION['uid'];
958
959 if ($eta_min && time() + $tz_offset - $timestamp < 3600) {
960 return T_sprintf("%d min", date("i", time() + $tz_offset - $timestamp));
961 } else if (date("Y.m.d", $timestamp) == date("Y.m.d", time() + $tz_offset)) {
962 return date("G:i", $timestamp);
963 } else if (date("Y", $timestamp) == date("Y", time() + $tz_offset)) {
964 $format = get_pref('SHORT_DATE_FORMAT', $owner_uid);
965 return date($format, $timestamp);
966 } else {
967 $format = get_pref('LONG_DATE_FORMAT', $owner_uid);
968 return date($format, $timestamp);
969 }
970 }
971
972 function sql_bool_to_bool($s) {
973 if ($s == "t" || $s == "1" || strtolower($s) == "true") {
974 return true;
975 } else {
976 return false;
977 }
978 }
979
980 function bool_to_sql_bool($s) {
981 if ($s) {
982 return "true";
983 } else {
984 return "false";
985 }
986 }
987
988 // Session caching removed due to causing wrong redirects to upgrade
989 // script when get_schema_version() is called on an obsolete session
990 // created on a previous schema version.
991 function get_schema_version($nocache = false) {
992 global $schema_version;
993
994 if (!$schema_version && !$nocache) {
995 $result = db_query("SELECT schema_version FROM ttrss_version");
996 $version = db_fetch_result($result, 0, "schema_version");
997 $schema_version = $version;
998 return $version;
999 } else {
1000 return $schema_version;
1001 }
1002 }
1003
1004 function sanity_check() {
1005 require_once 'errors.php';
1006 global $ERRORS;
1007
1008 $error_code = 0;
1009 $schema_version = get_schema_version(true);
1010
1011 if ($schema_version != SCHEMA_VERSION) {
1012 $error_code = 5;
1013 }
1014
1015 if (DB_TYPE == "mysql") {
1016 $result = db_query("SELECT true", false);
1017 if (db_num_rows($result) != 1) {
1018 $error_code = 10;
1019 }
1020 }
1021
1022 if (db_escape_string("testTEST") != "testTEST") {
1023 $error_code = 12;
1024 }
1025
1026 return array("code" => $error_code, "message" => $ERRORS[$error_code]);
1027 }
1028
1029 function file_is_locked($filename) {
1030 if (file_exists(LOCK_DIRECTORY . "/$filename")) {
1031 if (function_exists('flock')) {
1032 $fp = @fopen(LOCK_DIRECTORY . "/$filename", "r");
1033 if ($fp) {
1034 if (flock($fp, LOCK_EX | LOCK_NB)) {
1035 flock($fp, LOCK_UN);
1036 fclose($fp);
1037 return false;
1038 }
1039 fclose($fp);
1040 return true;
1041 } else {
1042 return false;
1043 }
1044 }
1045 return true; // consider the file always locked and skip the test
1046 } else {
1047 return false;
1048 }
1049 }
1050
1051
1052 function make_lockfile($filename) {
1053 $fp = fopen(LOCK_DIRECTORY . "/$filename", "w");
1054
1055 if ($fp && flock($fp, LOCK_EX | LOCK_NB)) {
1056 $stat_h = fstat($fp);
1057 $stat_f = stat(LOCK_DIRECTORY . "/$filename");
1058
1059 if (strtoupper(substr(PHP_OS, 0, 3)) !== 'WIN') {
1060 if ($stat_h["ino"] != $stat_f["ino"] ||
1061 $stat_h["dev"] != $stat_f["dev"]) {
1062
1063 return false;
1064 }
1065 }
1066
1067 if (function_exists('posix_getpid')) {
1068 fwrite($fp, posix_getpid() . "\n");
1069 }
1070 return $fp;
1071 } else {
1072 return false;
1073 }
1074 }
1075
1076 function make_stampfile($filename) {
1077 $fp = fopen(LOCK_DIRECTORY . "/$filename", "w");
1078
1079 if (flock($fp, LOCK_EX | LOCK_NB)) {
1080 fwrite($fp, time() . "\n");
1081 flock($fp, LOCK_UN);
1082 fclose($fp);
1083 return true;
1084 } else {
1085 return false;
1086 }
1087 }
1088
1089 function sql_random_function() {
1090 if (DB_TYPE == "mysql") {
1091 return "RAND()";
1092 } else {
1093 return "RANDOM()";
1094 }
1095 }
1096
1097 function getAllCounters() {
1098 $data = getGlobalCounters();
1099
1100 $data = array_merge($data, getVirtCounters());
1101 $data = array_merge($data, getLabelCounters());
1102 $data = array_merge($data, getFeedCounters());
1103 $data = array_merge($data, getCategoryCounters());
1104
1105 return $data;
1106 }
1107
1108 function getCategoryTitle($cat_id) {
1109
1110 if ($cat_id == -1) {
1111 return __("Special");
1112 } else if ($cat_id == -2) {
1113 return __("Labels");
1114 } else {
1115
1116 $result = db_query("SELECT title FROM ttrss_feed_categories WHERE
1117 id = '$cat_id'");
1118
1119 if (db_num_rows($result) == 1) {
1120 return db_fetch_result($result, 0, "title");
1121 } else {
1122 return __("Uncategorized");
1123 }
1124 }
1125 }
1126
1127
1128 function getCategoryCounters() {
1129 $ret_arr = array();
1130
1131 /* Labels category */
1132
1133 $cv = array("id" => -2, "kind" => "cat",
1134 "counter" => Feeds::getCategoryUnread(-2));
1135
1136 array_push($ret_arr, $cv);
1137
1138 $result = db_query("SELECT id AS cat_id, value AS unread,
1139 (SELECT COUNT(id) FROM ttrss_feed_categories AS c2
1140 WHERE c2.parent_cat = ttrss_feed_categories.id) AS num_children
1141 FROM ttrss_feed_categories, ttrss_cat_counters_cache
1142 WHERE ttrss_cat_counters_cache.feed_id = id AND
1143 ttrss_cat_counters_cache.owner_uid = ttrss_feed_categories.owner_uid AND
1144 ttrss_feed_categories.owner_uid = " . $_SESSION["uid"]);
1145
1146 while ($line = db_fetch_assoc($result)) {
1147 $line["cat_id"] = (int) $line["cat_id"];
1148
1149 if ($line["num_children"] > 0) {
1150 $child_counter = getCategoryChildrenUnread($line["cat_id"], $_SESSION["uid"]);
1151 } else {
1152 $child_counter = 0;
1153 }
1154
1155 $cv = array("id" => $line["cat_id"], "kind" => "cat",
1156 "counter" => $line["unread"] + $child_counter);
1157
1158 array_push($ret_arr, $cv);
1159 }
1160
1161 /* Special case: NULL category doesn't actually exist in the DB */
1162
1163 $cv = array("id" => 0, "kind" => "cat",
1164 "counter" => (int) ccache_find(0, $_SESSION["uid"], true));
1165
1166 array_push($ret_arr, $cv);
1167
1168 return $ret_arr;
1169 }
1170
1171 function getFeedUnread($feed, $is_cat = false) {
1172 return Feeds::getFeedArticles($feed, $is_cat, true, $_SESSION["uid"]);
1173 }
1174
1175 function getLabelUnread($label_id, $owner_uid = false) {
1176 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
1177
1178 $result = db_query("SELECT COUNT(ref_id) AS unread FROM ttrss_user_entries, ttrss_user_labels2
1179 WHERE owner_uid = '$owner_uid' AND unread = true AND label_id = '$label_id' AND article_id = ref_id");
1180
1181 if (db_num_rows($result) != 0) {
1182 return db_fetch_result($result, 0, "unread");
1183 } else {
1184 return 0;
1185 }
1186 }
1187
1188 function getGlobalUnread($user_id = false) {
1189
1190 if (!$user_id) {
1191 $user_id = $_SESSION["uid"];
1192 }
1193
1194 $result = db_query("SELECT SUM(value) AS c_id FROM ttrss_counters_cache
1195 WHERE owner_uid = '$user_id' AND feed_id > 0");
1196
1197 $c_id = db_fetch_result($result, 0, "c_id");
1198
1199 return $c_id;
1200 }
1201
1202 function getGlobalCounters($global_unread = -1) {
1203 $ret_arr = array();
1204
1205 if ($global_unread == -1) {
1206 $global_unread = getGlobalUnread();
1207 }
1208
1209 $cv = array("id" => "global-unread",
1210 "counter" => (int) $global_unread);
1211
1212 array_push($ret_arr, $cv);
1213
1214 $result = db_query("SELECT COUNT(id) AS fn FROM
1215 ttrss_feeds WHERE owner_uid = " . $_SESSION["uid"]);
1216
1217 $subscribed_feeds = db_fetch_result($result, 0, "fn");
1218
1219 $cv = array("id" => "subscribed-feeds",
1220 "counter" => (int) $subscribed_feeds);
1221
1222 array_push($ret_arr, $cv);
1223
1224 return $ret_arr;
1225 }
1226
1227 function getVirtCounters() {
1228
1229 $ret_arr = array();
1230
1231 for ($i = 0; $i >= -4; $i--) {
1232
1233 $count = getFeedUnread($i);
1234
1235 if ($i == 0 || $i == -1 || $i == -2)
1236 $auxctr = Feeds::getFeedArticles($i, false);
1237 else
1238 $auxctr = 0;
1239
1240 $cv = array("id" => $i,
1241 "counter" => (int) $count,
1242 "auxcounter" => (int) $auxctr);
1243
1244 // if (get_pref('EXTENDED_FEEDLIST'))
1245 // $cv["xmsg"] = getFeedArticles($i)." ".__("total");
1246
1247 array_push($ret_arr, $cv);
1248 }
1249
1250 $feeds = PluginHost::getInstance()->get_feeds(-1);
1251
1252 if (is_array($feeds)) {
1253 foreach ($feeds as $feed) {
1254 $cv = array("id" => PluginHost::pfeed_to_feed_id($feed['id']),
1255 "counter" => $feed['sender']->get_unread($feed['id']));
1256
1257 if (method_exists($feed['sender'], 'get_total'))
1258 $cv["auxcounter"] = $feed['sender']->get_total($feed['id']);
1259
1260 array_push($ret_arr, $cv);
1261 }
1262 }
1263
1264 return $ret_arr;
1265 }
1266
1267 function getLabelCounters($descriptions = false) {
1268
1269 $ret_arr = array();
1270
1271 $owner_uid = $_SESSION["uid"];
1272
1273 $result = db_query("SELECT id,caption,SUM(CASE WHEN u1.unread = true THEN 1 ELSE 0 END) AS unread, COUNT(u1.unread) AS total
1274 FROM ttrss_labels2 LEFT JOIN ttrss_user_labels2 ON
1275 (ttrss_labels2.id = label_id)
1276 LEFT JOIN ttrss_user_entries AS u1 ON u1.ref_id = article_id
1277 WHERE ttrss_labels2.owner_uid = $owner_uid AND u1.owner_uid = $owner_uid
1278 GROUP BY ttrss_labels2.id,
1279 ttrss_labels2.caption");
1280
1281 while ($line = db_fetch_assoc($result)) {
1282
1283 $id = label_to_feed_id($line["id"]);
1284
1285 $cv = array("id" => $id,
1286 "counter" => (int) $line["unread"],
1287 "auxcounter" => (int) $line["total"]);
1288
1289 if ($descriptions)
1290 $cv["description"] = $line["caption"];
1291
1292 array_push($ret_arr, $cv);
1293 }
1294
1295 return $ret_arr;
1296 }
1297
1298 function getFeedCounters($active_feed = false) {
1299
1300 $ret_arr = array();
1301
1302 $query = "SELECT ttrss_feeds.id,
1303 ttrss_feeds.title,
1304 ".SUBSTRING_FOR_DATE."(ttrss_feeds.last_updated,1,19) AS last_updated,
1305 last_error, value AS count
1306 FROM ttrss_feeds, ttrss_counters_cache
1307 WHERE ttrss_feeds.owner_uid = ".$_SESSION["uid"]."
1308 AND ttrss_counters_cache.owner_uid = ttrss_feeds.owner_uid
1309 AND ttrss_counters_cache.feed_id = id";
1310
1311 $result = db_query($query);
1312
1313 while ($line = db_fetch_assoc($result)) {
1314
1315 $id = $line["id"];
1316 $count = $line["count"];
1317 $last_error = htmlspecialchars($line["last_error"]);
1318
1319 $last_updated = make_local_datetime($line['last_updated'], false);
1320
1321 $has_img = feed_has_icon($id);
1322
1323 if (date('Y') - date('Y', strtotime($line['last_updated'])) > 2)
1324 $last_updated = '';
1325
1326 $cv = array("id" => $id,
1327 "updated" => $last_updated,
1328 "counter" => (int) $count,
1329 "has_img" => (int) $has_img);
1330
1331 if ($last_error)
1332 $cv["error"] = $last_error;
1333
1334 // if (get_pref('EXTENDED_FEEDLIST'))
1335 // $cv["xmsg"] = getFeedArticles($id)." ".__("total");
1336
1337 if ($active_feed && $id == $active_feed)
1338 $cv["title"] = truncate_string($line["title"], 30);
1339
1340 array_push($ret_arr, $cv);
1341
1342 }
1343
1344 return $ret_arr;
1345 }
1346
1347 /*function get_pgsql_version() {
1348 $result = db_query("SELECT version() AS version");
1349 $version = explode(" ", db_fetch_result($result, 0, "version"));
1350 return $version[1];
1351 }*/
1352
1353 function checkbox_to_sql_bool($val) {
1354 return ($val == "on") ? "true" : "false";
1355 }
1356
1357 /*function getFeedCatTitle($id) {
1358 if ($id == -1) {
1359 return __("Special");
1360 } else if ($id < LABEL_BASE_INDEX) {
1361 return __("Labels");
1362 } else if ($id > 0) {
1363 $result = db_query("SELECT ttrss_feed_categories.title
1364 FROM ttrss_feeds, ttrss_feed_categories WHERE ttrss_feeds.id = '$id' AND
1365 cat_id = ttrss_feed_categories.id");
1366 if (db_num_rows($result) == 1) {
1367 return db_fetch_result($result, 0, "title");
1368 } else {
1369 return __("Uncategorized");
1370 }
1371 } else {
1372 return "getFeedCatTitle($id) failed";
1373 }
1374
1375 }*/
1376
1377 function uniqid_short() {
1378 return uniqid(base_convert(rand(), 10, 36));
1379 }
1380
1381 // TODO: less dumb splitting
1382 require_once "functions2.php";