]> git.wh0rd.org - tt-rss.git/blob - include/functions.php
3dea5677a9970515e22e546ca193e3f57737e169
[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
140 define('SELF_USER_AGENT', 'Tiny Tiny RSS/' . VERSION . ' (http://tt-rss.org/)');
141 ini_set('user_agent', SELF_USER_AGENT);
142
143 require_once 'lib/pubsubhubbub/publisher.php';
144
145 $schema_version = false;
146
147 function _debug_suppress($suppress) {
148 global $suppress_debugging;
149
150 $suppress_debugging = $suppress;
151 }
152
153 /**
154 * Print a timestamped debug message.
155 *
156 * @param string $msg The debug message.
157 * @return void
158 */
159 function _debug($msg, $show = true) {
160 global $suppress_debugging;
161
162 //echo "[$suppress_debugging] $msg $show\n";
163
164 if ($suppress_debugging) return false;
165
166 $ts = strftime("%H:%M:%S", time());
167 if (function_exists('posix_getpid')) {
168 $ts = "$ts/" . posix_getpid();
169 }
170
171 if ($show && !(defined('QUIET') && QUIET)) {
172 print "[$ts] $msg\n";
173 }
174
175 if (defined('LOGFILE')) {
176 $fp = fopen(LOGFILE, 'a+');
177
178 if ($fp) {
179 $locked = false;
180
181 if (function_exists("flock")) {
182 $tries = 0;
183
184 // try to lock logfile for writing
185 while ($tries < 5 && !$locked = flock($fp, LOCK_EX | LOCK_NB)) {
186 sleep(1);
187 ++$tries;
188 }
189
190 if (!$locked) {
191 fclose($fp);
192 return;
193 }
194 }
195
196 fputs($fp, "[$ts] $msg\n");
197
198 if (function_exists("flock")) {
199 flock($fp, LOCK_UN);
200 }
201
202 fclose($fp);
203 }
204 }
205
206 } // function _debug
207
208 /**
209 * Purge a feed old posts.
210 *
211 * @param mixed $link A database connection.
212 * @param mixed $feed_id The id of the purged feed.
213 * @param mixed $purge_interval Olderness of purged posts.
214 * @param boolean $debug Set to True to enable the debug. False by default.
215 * @access public
216 * @return void
217 */
218 function purge_feed($feed_id, $purge_interval, $debug = false) {
219
220 if (!$purge_interval) $purge_interval = feed_purge_interval($feed_id);
221
222 $rows = -1;
223
224 $result = db_query(
225 "SELECT owner_uid FROM ttrss_feeds WHERE id = '$feed_id'");
226
227 $owner_uid = false;
228
229 if (db_num_rows($result) == 1) {
230 $owner_uid = db_fetch_result($result, 0, "owner_uid");
231 }
232
233 if ($purge_interval == -1 || !$purge_interval) {
234 if ($owner_uid) {
235 ccache_update($feed_id, $owner_uid);
236 }
237 return;
238 }
239
240 if (!$owner_uid) return;
241
242 if (FORCE_ARTICLE_PURGE == 0) {
243 $purge_unread = get_pref("PURGE_UNREAD_ARTICLES",
244 $owner_uid, false);
245 } else {
246 $purge_unread = true;
247 $purge_interval = FORCE_ARTICLE_PURGE;
248 }
249
250 if (!$purge_unread) $query_limit = " unread = false AND ";
251
252 if (DB_TYPE == "pgsql") {
253 $result = db_query("DELETE FROM ttrss_user_entries
254 USING ttrss_entries
255 WHERE ttrss_entries.id = ref_id AND
256 marked = false AND
257 feed_id = '$feed_id' AND
258 $query_limit
259 ttrss_entries.date_updated < NOW() - INTERVAL '$purge_interval days'");
260
261 } else {
262
263 /* $result = db_query("DELETE FROM ttrss_user_entries WHERE
264 marked = false AND feed_id = '$feed_id' AND
265 (SELECT date_updated FROM ttrss_entries WHERE
266 id = ref_id) < DATE_SUB(NOW(), INTERVAL $purge_interval DAY)"); */
267
268 $result = db_query("DELETE FROM ttrss_user_entries
269 USING ttrss_user_entries, ttrss_entries
270 WHERE ttrss_entries.id = ref_id AND
271 marked = false AND
272 feed_id = '$feed_id' AND
273 $query_limit
274 ttrss_entries.date_updated < DATE_SUB(NOW(), INTERVAL $purge_interval DAY)");
275 }
276
277 $rows = db_affected_rows($result);
278
279 ccache_update($feed_id, $owner_uid);
280
281 if ($debug) {
282 _debug("Purged feed $feed_id ($purge_interval): deleted $rows articles");
283 }
284
285 return $rows;
286 } // function purge_feed
287
288 function feed_purge_interval($feed_id) {
289
290 $result = db_query("SELECT purge_interval, owner_uid FROM ttrss_feeds
291 WHERE id = '$feed_id'");
292
293 if (db_num_rows($result) == 1) {
294 $purge_interval = db_fetch_result($result, 0, "purge_interval");
295 $owner_uid = db_fetch_result($result, 0, "owner_uid");
296
297 if ($purge_interval == 0) $purge_interval = get_pref(
298 'PURGE_OLD_DAYS', $owner_uid);
299
300 return $purge_interval;
301
302 } else {
303 return -1;
304 }
305 }
306
307 function purge_orphans($do_output = false) {
308
309 // purge orphaned posts in main content table
310 $result = db_query("DELETE FROM ttrss_entries WHERE
311 NOT EXISTS (SELECT ref_id FROM ttrss_user_entries WHERE ref_id = id)");
312
313 if ($do_output) {
314 $rows = db_affected_rows($result);
315 _debug("Purged $rows orphaned posts.");
316 }
317 }
318
319 function get_feed_update_interval($feed_id) {
320 $result = db_query("SELECT owner_uid, update_interval FROM
321 ttrss_feeds WHERE id = '$feed_id'");
322
323 if (db_num_rows($result) == 1) {
324 $update_interval = db_fetch_result($result, 0, "update_interval");
325 $owner_uid = db_fetch_result($result, 0, "owner_uid");
326
327 if ($update_interval != 0) {
328 return $update_interval;
329 } else {
330 return get_pref('DEFAULT_UPDATE_INTERVAL', $owner_uid, false);
331 }
332
333 } else {
334 return -1;
335 }
336 }
337
338 // TODO: multiple-argument way is deprecated, first parameter is a hash now
339 function fetch_file_contents($options /* previously: 0: $url , 1: $type = false, 2: $login = false, 3: $pass = false,
340 4: $post_query = false, 5: $timeout = false, 6: $timestamp = 0, 7: $useragent = false*/) {
341
342 global $fetch_last_error;
343 global $fetch_last_error_code;
344 global $fetch_last_error_content;
345 global $fetch_last_content_type;
346 global $fetch_curl_used;
347
348 if (!is_array($options)) {
349
350 // falling back on compatibility shim
351 $options = array(
352 "url" => func_get_arg(0),
353 "type" => @func_get_arg(1),
354 "login" => @func_get_arg(2),
355 "pass" => @func_get_arg(3),
356 "post_query" => @func_get_arg(4),
357 "timeout" => @func_get_arg(5),
358 "timestamp" => @func_get_arg(6),
359 "useragent" => @func_get_arg(7)
360 );
361 }
362
363 $url = $options["url"];
364 $type = isset($options["type"]) ? $options["type"] : false;
365 $login = isset($options["login"]) ? $options["login"] : false;
366 $pass = isset($options["pass"]) ? $options["pass"] : false;
367 $post_query = isset($options["post_query"]) ? $options["post_query"] : false;
368 $timeout = isset($options["timeout"]) ? $options["timeout"] : false;
369 $timestamp = isset($options["timestamp"]) ? $options["timestamp"] : 0;
370 $useragent = isset($options["useragent"]) ? $options["useragent"] : false;
371
372 $url = ltrim($url, ' ');
373 $url = str_replace(' ', '%20', $url);
374
375 if (strpos($url, "//") === 0)
376 $url = 'http:' . $url;
377
378 if (!defined('NO_CURL') && function_exists('curl_init') && !ini_get("open_basedir")) {
379
380 $fetch_curl_used = true;
381
382 $ch = curl_init($url);
383
384 if ($timestamp && !$post_query) {
385 curl_setopt($ch, CURLOPT_HTTPHEADER,
386 array("If-Modified-Since: ".gmdate('D, d M Y H:i:s \G\M\T', $timestamp)));
387 }
388
389 curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout ? $timeout : FILE_FETCH_CONNECT_TIMEOUT);
390 curl_setopt($ch, CURLOPT_TIMEOUT, $timeout ? $timeout : FILE_FETCH_TIMEOUT);
391 curl_setopt($ch, CURLOPT_FOLLOWLOCATION, !ini_get("open_basedir"));
392 curl_setopt($ch, CURLOPT_MAXREDIRS, 20);
393 curl_setopt($ch, CURLOPT_BINARYTRANSFER, true);
394 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
395 curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
396 curl_setopt($ch, CURLOPT_USERAGENT, $useragent ? $useragent :
397 SELF_USER_AGENT);
398 curl_setopt($ch, CURLOPT_ENCODING, "");
399 //curl_setopt($ch, CURLOPT_REFERER, $url);
400
401 if (!ini_get("open_basedir")) {
402 curl_setopt($ch, CURLOPT_COOKIEJAR, "/dev/null");
403 }
404
405 if (defined('_CURL_HTTP_PROXY')) {
406 curl_setopt($ch, CURLOPT_PROXY, _CURL_HTTP_PROXY);
407 }
408
409 if ($post_query) {
410 curl_setopt($ch, CURLOPT_POST, true);
411 curl_setopt($ch, CURLOPT_POSTFIELDS, $post_query);
412 }
413
414 if ($login && $pass)
415 curl_setopt($ch, CURLOPT_USERPWD, "$login:$pass");
416
417 $contents = @curl_exec($ch);
418
419 if (curl_errno($ch) === 23 || curl_errno($ch) === 61) {
420 curl_setopt($ch, CURLOPT_ENCODING, 'none');
421 $contents = @curl_exec($ch);
422 }
423
424 if ($contents === false) {
425 $fetch_last_error = curl_errno($ch) . " " . curl_error($ch);
426 curl_close($ch);
427 return false;
428 }
429
430 $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
431 $fetch_last_content_type = curl_getinfo($ch, CURLINFO_CONTENT_TYPE);
432
433 $fetch_last_error_code = $http_code;
434
435 if ($http_code != 200 || $type && strpos($fetch_last_content_type, "$type") === false) {
436 if (curl_errno($ch) != 0) {
437 $fetch_last_error = curl_errno($ch) . " " . curl_error($ch);
438 } else {
439 $fetch_last_error = "HTTP Code: $http_code";
440 }
441 $fetch_last_error_content = $contents;
442 curl_close($ch);
443 return false;
444 }
445
446 curl_close($ch);
447
448 return $contents;
449 } else {
450
451 $fetch_curl_used = false;
452
453 if ($login && $pass){
454 $url_parts = array();
455
456 preg_match("/(^[^:]*):\/\/(.*)/", $url, $url_parts);
457
458 $pass = urlencode($pass);
459
460 if ($url_parts[1] && $url_parts[2]) {
461 $url = $url_parts[1] . "://$login:$pass@" . $url_parts[2];
462 }
463 }
464
465 if (!$post_query && $timestamp) {
466 $context = stream_context_create(array(
467 'http' => array(
468 'method' => 'GET',
469 'protocol_version'=> 1.1,
470 'header' => "If-Modified-Since: ".gmdate("D, d M Y H:i:s \\G\\M\\T\r\n", $timestamp)
471 )));
472 } else {
473 $context = stream_context_create(array(
474 'http' => array(
475 'method' => 'GET',
476 'protocol_version'=> 1.1
477 )));
478 }
479
480 $old_error = error_get_last();
481
482 $data = @file_get_contents($url, false, $context);
483
484 $fetch_last_content_type = false; // reset if no type was sent from server
485 if (isset($http_response_header) && is_array($http_response_header)) {
486 foreach ($http_response_header as $h) {
487 if (substr(strtolower($h), 0, 13) == 'content-type:') {
488 $fetch_last_content_type = substr($h, 14);
489 // don't abort here b/c there might be more than one
490 // e.g. if we were being redirected -- last one is the right one
491 }
492
493 if (substr(strtolower($h), 0, 7) == 'http/1.') {
494 $fetch_last_error_code = (int) substr($h, 9, 3);
495 }
496 }
497 }
498
499 if (!$data) {
500 $error = error_get_last();
501
502 if ($error['message'] != $old_error['message']) {
503 $fetch_last_error = $error["message"];
504 } else {
505 $fetch_last_error = "HTTP Code: $fetch_last_error_code";
506 }
507 }
508 return $data;
509 }
510
511 }
512
513 /**
514 * Try to determine the favicon URL for a feed.
515 * adapted from wordpress favicon plugin by Jeff Minard (http://thecodepro.com/)
516 * http://dev.wp-plugins.org/file/favatars/trunk/favatars.php
517 *
518 * @param string $url A feed or page URL
519 * @access public
520 * @return mixed The favicon URL, or false if none was found.
521 */
522 function get_favicon_url($url) {
523
524 $favicon_url = false;
525
526 if ($html = @fetch_file_contents($url)) {
527
528 libxml_use_internal_errors(true);
529
530 $doc = new DOMDocument();
531 $doc->loadHTML($html);
532 $xpath = new DOMXPath($doc);
533
534 $base = $xpath->query('/html/head/base');
535 foreach ($base as $b) {
536 $url = $b->getAttribute("href");
537 break;
538 }
539
540 $entries = $xpath->query('/html/head/link[@rel="shortcut icon" or @rel="icon"]');
541 if (count($entries) > 0) {
542 foreach ($entries as $entry) {
543 $favicon_url = rewrite_relative_url($url, $entry->getAttribute("href"));
544 break;
545 }
546 }
547 }
548
549 if (!$favicon_url)
550 $favicon_url = rewrite_relative_url($url, "/favicon.ico");
551
552 return $favicon_url;
553 } // function get_favicon_url
554
555 function check_feed_favicon($site_url, $feed) {
556 # print "FAVICON [$site_url]: $favicon_url\n";
557
558 $icon_file = ICONS_DIR . "/$feed.ico";
559
560 if (!file_exists($icon_file)) {
561 $favicon_url = get_favicon_url($site_url);
562
563 if ($favicon_url) {
564 // Limiting to "image" type misses those served with text/plain
565 $contents = fetch_file_contents($favicon_url); // , "image");
566
567 if ($contents) {
568 // Crude image type matching.
569 // Patterns gleaned from the file(1) source code.
570 if (preg_match('/^\x00\x00\x01\x00/', $contents)) {
571 // 0 string \000\000\001\000 MS Windows icon resource
572 //error_log("check_feed_favicon: favicon_url=$favicon_url isa MS Windows icon resource");
573 }
574 elseif (preg_match('/^GIF8/', $contents)) {
575 // 0 string GIF8 GIF image data
576 //error_log("check_feed_favicon: favicon_url=$favicon_url isa GIF image");
577 }
578 elseif (preg_match('/^\x89PNG\x0d\x0a\x1a\x0a/', $contents)) {
579 // 0 string \x89PNG\x0d\x0a\x1a\x0a PNG image data
580 //error_log("check_feed_favicon: favicon_url=$favicon_url isa PNG image");
581 }
582 elseif (preg_match('/^\xff\xd8/', $contents)) {
583 // 0 beshort 0xffd8 JPEG image data
584 //error_log("check_feed_favicon: favicon_url=$favicon_url isa JPG image");
585 }
586 else {
587 //error_log("check_feed_favicon: favicon_url=$favicon_url isa UNKNOWN type");
588 $contents = "";
589 }
590 }
591
592 if ($contents) {
593 $fp = @fopen($icon_file, "w");
594
595 if ($fp) {
596 fwrite($fp, $contents);
597 fclose($fp);
598 chmod($icon_file, 0644);
599 }
600 }
601 }
602 return $icon_file;
603 }
604 }
605
606 function print_select($id, $default, $values, $attributes = "", $name = "") {
607 if (!$name) $name = $id;
608
609 print "<select name=\"$name\" id=\"$id\" $attributes>";
610 foreach ($values as $v) {
611 if ($v == $default)
612 $sel = "selected=\"1\"";
613 else
614 $sel = "";
615
616 $v = trim($v);
617
618 print "<option value=\"$v\" $sel>$v</option>";
619 }
620 print "</select>";
621 }
622
623 function print_select_hash($id, $default, $values, $attributes = "", $name = "") {
624 if (!$name) $name = $id;
625
626 print "<select name=\"$name\" id='$id' $attributes>";
627 foreach (array_keys($values) as $v) {
628 if ($v == $default)
629 $sel = 'selected="selected"';
630 else
631 $sel = "";
632
633 $v = trim($v);
634
635 print "<option $sel value=\"$v\">".$values[$v]."</option>";
636 }
637
638 print "</select>";
639 }
640
641 function print_radio($id, $default, $true_is, $values, $attributes = "") {
642 foreach ($values as $v) {
643
644 if ($v == $default)
645 $sel = "checked";
646 else
647 $sel = "";
648
649 if ($v == $true_is) {
650 $sel .= " value=\"1\"";
651 } else {
652 $sel .= " value=\"0\"";
653 }
654
655 print "<input class=\"noborder\" dojoType=\"dijit.form.RadioButton\"
656 type=\"radio\" $sel $attributes name=\"$id\">&nbsp;$v&nbsp;";
657
658 }
659 }
660
661 function initialize_user_prefs($uid, $profile = false) {
662
663 $uid = db_escape_string($uid);
664
665 if (!$profile) {
666 $profile = "NULL";
667 $profile_qpart = "AND profile IS NULL";
668 } else {
669 $profile_qpart = "AND profile = '$profile'";
670 }
671
672 if (get_schema_version() < 63) $profile_qpart = "";
673
674 db_query("BEGIN");
675
676 $result = db_query("SELECT pref_name,def_value FROM ttrss_prefs");
677
678 $u_result = db_query("SELECT pref_name
679 FROM ttrss_user_prefs WHERE owner_uid = '$uid' $profile_qpart");
680
681 $active_prefs = array();
682
683 while ($line = db_fetch_assoc($u_result)) {
684 array_push($active_prefs, $line["pref_name"]);
685 }
686
687 while ($line = db_fetch_assoc($result)) {
688 if (array_search($line["pref_name"], $active_prefs) === FALSE) {
689 // print "adding " . $line["pref_name"] . "<br>";
690
691 $line["def_value"] = db_escape_string($line["def_value"]);
692 $line["pref_name"] = db_escape_string($line["pref_name"]);
693
694 if (get_schema_version() < 63) {
695 db_query("INSERT INTO ttrss_user_prefs
696 (owner_uid,pref_name,value) VALUES
697 ('$uid', '".$line["pref_name"]."','".$line["def_value"]."')");
698
699 } else {
700 db_query("INSERT INTO ttrss_user_prefs
701 (owner_uid,pref_name,value, profile) VALUES
702 ('$uid', '".$line["pref_name"]."','".$line["def_value"]."', $profile)");
703 }
704
705 }
706 }
707
708 db_query("COMMIT");
709
710 }
711
712 function get_ssl_certificate_id() {
713 if ($_SERVER["REDIRECT_SSL_CLIENT_M_SERIAL"]) {
714 return sha1($_SERVER["REDIRECT_SSL_CLIENT_M_SERIAL"] .
715 $_SERVER["REDIRECT_SSL_CLIENT_V_START"] .
716 $_SERVER["REDIRECT_SSL_CLIENT_V_END"] .
717 $_SERVER["REDIRECT_SSL_CLIENT_S_DN"]);
718 }
719 if ($_SERVER["SSL_CLIENT_M_SERIAL"]) {
720 return sha1($_SERVER["SSL_CLIENT_M_SERIAL"] .
721 $_SERVER["SSL_CLIENT_V_START"] .
722 $_SERVER["SSL_CLIENT_V_END"] .
723 $_SERVER["SSL_CLIENT_S_DN"]);
724 }
725 return "";
726 }
727
728 function authenticate_user($login, $password, $check_only = false) {
729
730 if (!SINGLE_USER_MODE) {
731 $user_id = false;
732
733 foreach (PluginHost::getInstance()->get_hooks(PluginHost::HOOK_AUTH_USER) as $plugin) {
734
735 $user_id = (int) $plugin->authenticate($login, $password);
736
737 if ($user_id) {
738 $_SESSION["auth_module"] = strtolower(get_class($plugin));
739 break;
740 }
741 }
742
743 if ($user_id && !$check_only) {
744 @session_start();
745
746 $_SESSION["uid"] = $user_id;
747 $_SESSION["version"] = VERSION_STATIC;
748
749 $result = db_query("SELECT login,access_level,pwd_hash FROM ttrss_users
750 WHERE id = '$user_id'");
751
752 $_SESSION["name"] = db_fetch_result($result, 0, "login");
753 $_SESSION["access_level"] = db_fetch_result($result, 0, "access_level");
754 $_SESSION["csrf_token"] = uniqid_short();
755
756 db_query("UPDATE ttrss_users SET last_login = NOW() WHERE id = " .
757 $_SESSION["uid"]);
758
759 $_SESSION["ip_address"] = $_SERVER["REMOTE_ADDR"];
760 $_SESSION["user_agent"] = sha1($_SERVER['HTTP_USER_AGENT']);
761 $_SESSION["pwd_hash"] = db_fetch_result($result, 0, "pwd_hash");
762
763 $_SESSION["last_version_check"] = time();
764
765 initialize_user_prefs($_SESSION["uid"]);
766
767 return true;
768 }
769
770 return false;
771
772 } else {
773
774 $_SESSION["uid"] = 1;
775 $_SESSION["name"] = "admin";
776 $_SESSION["access_level"] = 10;
777
778 $_SESSION["hide_hello"] = true;
779 $_SESSION["hide_logout"] = true;
780
781 $_SESSION["auth_module"] = false;
782
783 if (!$_SESSION["csrf_token"]) {
784 $_SESSION["csrf_token"] = uniqid_short();
785 }
786
787 $_SESSION["ip_address"] = $_SERVER["REMOTE_ADDR"];
788
789 initialize_user_prefs($_SESSION["uid"]);
790
791 return true;
792 }
793 }
794
795 function make_password($length = 8) {
796
797 $password = "";
798 $possible = "0123456789abcdfghjkmnpqrstvwxyzABCDFGHJKMNPQRSTVWXYZ";
799
800 $i = 0;
801
802 while ($i < $length) {
803 $char = substr($possible, mt_rand(0, strlen($possible)-1), 1);
804
805 if (!strstr($password, $char)) {
806 $password .= $char;
807 $i++;
808 }
809 }
810 return $password;
811 }
812
813 // this is called after user is created to initialize default feeds, labels
814 // or whatever else
815
816 // user preferences are checked on every login, not here
817
818 function initialize_user($uid) {
819
820 db_query("insert into ttrss_feeds (owner_uid,title,feed_url)
821 values ('$uid', 'Tiny Tiny RSS: Forum',
822 'http://tt-rss.org/forum/rss.php')");
823 }
824
825 function logout_user() {
826 session_destroy();
827 if (isset($_COOKIE[session_name()])) {
828 setcookie(session_name(), '', time()-42000, '/');
829 }
830 }
831
832 function validate_csrf($csrf_token) {
833 return $csrf_token == $_SESSION['csrf_token'];
834 }
835
836 function load_user_plugins($owner_uid, $pluginhost = false) {
837
838 if (!$pluginhost) $pluginhost = PluginHost::getInstance();
839
840 if ($owner_uid && SCHEMA_VERSION >= 100) {
841 $plugins = get_pref("_ENABLED_PLUGINS", $owner_uid);
842
843 $pluginhost->load($plugins, PluginHost::KIND_USER, $owner_uid);
844
845 if (get_schema_version() > 100) {
846 $pluginhost->load_data();
847 }
848 }
849 }
850
851 function login_sequence() {
852 if (SINGLE_USER_MODE) {
853 @session_start();
854 authenticate_user("admin", null);
855 startup_gettext();
856 load_user_plugins($_SESSION["uid"]);
857 } else {
858 if (!validate_session()) $_SESSION["uid"] = false;
859
860 if (!$_SESSION["uid"]) {
861
862 if (AUTH_AUTO_LOGIN && authenticate_user(null, null)) {
863 $_SESSION["ref_schema_version"] = get_schema_version(true);
864 } else {
865 authenticate_user(null, null, true);
866 }
867
868 if (!$_SESSION["uid"]) {
869 @session_destroy();
870 setcookie(session_name(), '', time()-42000, '/');
871
872 render_login_form();
873 exit;
874 }
875
876 } else {
877 /* bump login timestamp */
878 db_query("UPDATE ttrss_users SET last_login = NOW() WHERE id = " .
879 $_SESSION["uid"]);
880 $_SESSION["last_login_update"] = time();
881 }
882
883 if ($_SESSION["uid"]) {
884 startup_gettext();
885 load_user_plugins($_SESSION["uid"]);
886
887 /* cleanup ccache */
888
889 db_query("DELETE FROM ttrss_counters_cache WHERE owner_uid = ".
890 $_SESSION["uid"] . " AND
891 (SELECT COUNT(id) FROM ttrss_feeds WHERE
892 ttrss_feeds.id = feed_id) = 0");
893
894 db_query("DELETE FROM ttrss_cat_counters_cache WHERE owner_uid = ".
895 $_SESSION["uid"] . " AND
896 (SELECT COUNT(id) FROM ttrss_feed_categories WHERE
897 ttrss_feed_categories.id = feed_id) = 0");
898
899 }
900
901 }
902 }
903
904 function truncate_string($str, $max_len, $suffix = '&hellip;') {
905 if (mb_strlen($str, "utf-8") > $max_len) {
906 return mb_substr($str, 0, $max_len, "utf-8") . $suffix;
907 } else {
908 return $str;
909 }
910 }
911
912 // is not utf8 clean
913 function truncate_middle($str, $max_len, $suffix = '&hellip;') {
914 if (strlen($str) > $max_len) {
915 return substr_replace($str, $suffix, $max_len / 2, mb_strlen($str) - $max_len);
916 } else {
917 return $str;
918 }
919 }
920
921 function convert_timestamp($timestamp, $source_tz, $dest_tz) {
922
923 try {
924 $source_tz = new DateTimeZone($source_tz);
925 } catch (Exception $e) {
926 $source_tz = new DateTimeZone('UTC');
927 }
928
929 try {
930 $dest_tz = new DateTimeZone($dest_tz);
931 } catch (Exception $e) {
932 $dest_tz = new DateTimeZone('UTC');
933 }
934
935 $dt = new DateTime(date('Y-m-d H:i:s', $timestamp), $source_tz);
936 return $dt->format('U') + $dest_tz->getOffset($dt);
937 }
938
939 function make_local_datetime($timestamp, $long, $owner_uid = false,
940 $no_smart_dt = false, $eta_min = false) {
941
942 if (!$owner_uid) $owner_uid = $_SESSION['uid'];
943 if (!$timestamp) $timestamp = '1970-01-01 0:00';
944
945 global $utc_tz;
946 global $user_tz;
947
948 if (!$utc_tz) $utc_tz = new DateTimeZone('UTC');
949
950 $timestamp = substr($timestamp, 0, 19);
951
952 # We store date in UTC internally
953 $dt = new DateTime($timestamp, $utc_tz);
954
955 $user_tz_string = get_pref('USER_TIMEZONE', $owner_uid);
956
957 if ($user_tz_string != 'Automatic') {
958
959 try {
960 if (!$user_tz) $user_tz = new DateTimeZone($user_tz_string);
961 } catch (Exception $e) {
962 $user_tz = $utc_tz;
963 }
964
965 $tz_offset = $user_tz->getOffset($dt);
966 } else {
967 $tz_offset = (int) -$_SESSION["clientTzOffset"];
968 }
969
970 $user_timestamp = $dt->format('U') + $tz_offset;
971
972 if (!$no_smart_dt) {
973 return smart_date_time($user_timestamp,
974 $tz_offset, $owner_uid, $eta_min);
975 } else {
976 if ($long)
977 $format = get_pref('LONG_DATE_FORMAT', $owner_uid);
978 else
979 $format = get_pref('SHORT_DATE_FORMAT', $owner_uid);
980
981 return date($format, $user_timestamp);
982 }
983 }
984
985 function smart_date_time($timestamp, $tz_offset = 0, $owner_uid = false, $eta_min = false) {
986 if (!$owner_uid) $owner_uid = $_SESSION['uid'];
987
988 if ($eta_min && time() + $tz_offset - $timestamp < 3600) {
989 return T_sprintf("%d min", date("i", time() + $tz_offset - $timestamp));
990 } else if (date("Y.m.d", $timestamp) == date("Y.m.d", time() + $tz_offset)) {
991 return date("G:i", $timestamp);
992 } else if (date("Y", $timestamp) == date("Y", time() + $tz_offset)) {
993 $format = get_pref('SHORT_DATE_FORMAT', $owner_uid);
994 return date($format, $timestamp);
995 } else {
996 $format = get_pref('LONG_DATE_FORMAT', $owner_uid);
997 return date($format, $timestamp);
998 }
999 }
1000
1001 function sql_bool_to_bool($s) {
1002 if ($s == "t" || $s == "1" || strtolower($s) == "true") {
1003 return true;
1004 } else {
1005 return false;
1006 }
1007 }
1008
1009 function bool_to_sql_bool($s) {
1010 if ($s) {
1011 return "true";
1012 } else {
1013 return "false";
1014 }
1015 }
1016
1017 // Session caching removed due to causing wrong redirects to upgrade
1018 // script when get_schema_version() is called on an obsolete session
1019 // created on a previous schema version.
1020 function get_schema_version($nocache = false) {
1021 global $schema_version;
1022
1023 if (!$schema_version && !$nocache) {
1024 $result = db_query("SELECT schema_version FROM ttrss_version");
1025 $version = db_fetch_result($result, 0, "schema_version");
1026 $schema_version = $version;
1027 return $version;
1028 } else {
1029 return $schema_version;
1030 }
1031 }
1032
1033 function sanity_check() {
1034 require_once 'errors.php';
1035 global $ERRORS;
1036
1037 $error_code = 0;
1038 $schema_version = get_schema_version(true);
1039
1040 if ($schema_version != SCHEMA_VERSION) {
1041 $error_code = 5;
1042 }
1043
1044 if (DB_TYPE == "mysql") {
1045 $result = db_query("SELECT true", false);
1046 if (db_num_rows($result) != 1) {
1047 $error_code = 10;
1048 }
1049 }
1050
1051 if (db_escape_string("testTEST") != "testTEST") {
1052 $error_code = 12;
1053 }
1054
1055 return array("code" => $error_code, "message" => $ERRORS[$error_code]);
1056 }
1057
1058 function file_is_locked($filename) {
1059 if (file_exists(LOCK_DIRECTORY . "/$filename")) {
1060 if (function_exists('flock')) {
1061 $fp = @fopen(LOCK_DIRECTORY . "/$filename", "r");
1062 if ($fp) {
1063 if (flock($fp, LOCK_EX | LOCK_NB)) {
1064 flock($fp, LOCK_UN);
1065 fclose($fp);
1066 return false;
1067 }
1068 fclose($fp);
1069 return true;
1070 } else {
1071 return false;
1072 }
1073 }
1074 return true; // consider the file always locked and skip the test
1075 } else {
1076 return false;
1077 }
1078 }
1079
1080
1081 function make_lockfile($filename) {
1082 $fp = fopen(LOCK_DIRECTORY . "/$filename", "w");
1083
1084 if ($fp && flock($fp, LOCK_EX | LOCK_NB)) {
1085 $stat_h = fstat($fp);
1086 $stat_f = stat(LOCK_DIRECTORY . "/$filename");
1087
1088 if (strtoupper(substr(PHP_OS, 0, 3)) !== 'WIN') {
1089 if ($stat_h["ino"] != $stat_f["ino"] ||
1090 $stat_h["dev"] != $stat_f["dev"]) {
1091
1092 return false;
1093 }
1094 }
1095
1096 if (function_exists('posix_getpid')) {
1097 fwrite($fp, posix_getpid() . "\n");
1098 }
1099 return $fp;
1100 } else {
1101 return false;
1102 }
1103 }
1104
1105 function make_stampfile($filename) {
1106 $fp = fopen(LOCK_DIRECTORY . "/$filename", "w");
1107
1108 if (flock($fp, LOCK_EX | LOCK_NB)) {
1109 fwrite($fp, time() . "\n");
1110 flock($fp, LOCK_UN);
1111 fclose($fp);
1112 return true;
1113 } else {
1114 return false;
1115 }
1116 }
1117
1118 function sql_random_function() {
1119 if (DB_TYPE == "mysql") {
1120 return "RAND()";
1121 } else {
1122 return "RANDOM()";
1123 }
1124 }
1125
1126 function catchup_feed($feed, $cat_view, $owner_uid = false, $max_id = false, $mode = 'all') {
1127
1128 if (!$owner_uid) $owner_uid = $_SESSION['uid'];
1129
1130 //if (preg_match("/^-?[0-9][0-9]*$/", $feed) != false) {
1131
1132 // Todo: all this interval stuff needs some generic generator function
1133
1134 $date_qpart = "false";
1135
1136 switch ($mode) {
1137 case "1day":
1138 if (DB_TYPE == "pgsql") {
1139 $date_qpart = "date_entered < NOW() - INTERVAL '1 day' ";
1140 } else {
1141 $date_qpart = "date_entered < DATE_SUB(NOW(), INTERVAL 1 DAY) ";
1142 }
1143 break;
1144 case "1week":
1145 if (DB_TYPE == "pgsql") {
1146 $date_qpart = "date_entered < NOW() - INTERVAL '1 week' ";
1147 } else {
1148 $date_qpart = "date_entered < DATE_SUB(NOW(), INTERVAL 1 WEEK) ";
1149 }
1150 break;
1151 case "2week":
1152 if (DB_TYPE == "pgsql") {
1153 $date_qpart = "date_entered < NOW() - INTERVAL '2 week' ";
1154 } else {
1155 $date_qpart = "date_entered < DATE_SUB(NOW(), INTERVAL 2 WEEK) ";
1156 }
1157 break;
1158 default:
1159 $date_qpart = "true";
1160 }
1161
1162 if (is_numeric($feed)) {
1163 if ($cat_view) {
1164
1165 if ($feed >= 0) {
1166
1167 if ($feed > 0) {
1168 $children = getChildCategories($feed, $owner_uid);
1169 array_push($children, $feed);
1170
1171 $children = join(",", $children);
1172
1173 $cat_qpart = "cat_id IN ($children)";
1174 } else {
1175 $cat_qpart = "cat_id IS NULL";
1176 }
1177
1178 db_query("UPDATE ttrss_user_entries
1179 SET unread = false, last_read = NOW() WHERE ref_id IN
1180 (SELECT id FROM
1181 (SELECT DISTINCT id FROM ttrss_entries, ttrss_user_entries WHERE ref_id = id
1182 AND owner_uid = $owner_uid AND unread = true AND feed_id IN
1183 (SELECT id FROM ttrss_feeds WHERE $cat_qpart) AND $date_qpart) as tmp)");
1184
1185 } else if ($feed == -2) {
1186
1187 db_query("UPDATE ttrss_user_entries
1188 SET unread = false,last_read = NOW() WHERE (SELECT COUNT(*)
1189 FROM ttrss_user_labels2, ttrss_entries WHERE article_id = ref_id AND id = ref_id AND $date_qpart) > 0
1190 AND unread = true AND owner_uid = $owner_uid");
1191 }
1192
1193 } else if ($feed > 0) {
1194
1195 db_query("UPDATE ttrss_user_entries
1196 SET unread = false, last_read = NOW() WHERE ref_id IN
1197 (SELECT id FROM
1198 (SELECT DISTINCT id FROM ttrss_entries, ttrss_user_entries WHERE ref_id = id
1199 AND owner_uid = $owner_uid AND unread = true AND feed_id = $feed AND $date_qpart) as tmp)");
1200
1201 } else if ($feed < 0 && $feed > LABEL_BASE_INDEX) { // special, like starred
1202
1203 if ($feed == -1) {
1204 db_query("UPDATE ttrss_user_entries
1205 SET unread = false, last_read = NOW() WHERE ref_id IN
1206 (SELECT id FROM
1207 (SELECT DISTINCT id FROM ttrss_entries, ttrss_user_entries WHERE ref_id = id
1208 AND owner_uid = $owner_uid AND unread = true AND marked = true AND $date_qpart) as tmp)");
1209 }
1210
1211 if ($feed == -2) {
1212 db_query("UPDATE ttrss_user_entries
1213 SET unread = false, last_read = NOW() WHERE ref_id IN
1214 (SELECT id FROM
1215 (SELECT DISTINCT id FROM ttrss_entries, ttrss_user_entries WHERE ref_id = id
1216 AND owner_uid = $owner_uid AND unread = true AND published = true AND $date_qpart) as tmp)");
1217 }
1218
1219 if ($feed == -3) {
1220
1221 $intl = get_pref("FRESH_ARTICLE_MAX_AGE");
1222
1223 if (DB_TYPE == "pgsql") {
1224 $match_part = "date_entered > NOW() - INTERVAL '$intl hour' ";
1225 } else {
1226 $match_part = "date_entered > DATE_SUB(NOW(),
1227 INTERVAL $intl HOUR) ";
1228 }
1229
1230 db_query("UPDATE ttrss_user_entries
1231 SET unread = false, last_read = NOW() WHERE ref_id IN
1232 (SELECT id FROM
1233 (SELECT DISTINCT id FROM ttrss_entries, ttrss_user_entries WHERE ref_id = id
1234 AND owner_uid = $owner_uid AND score >= 0 AND unread = true AND $date_qpart AND $match_part) as tmp)");
1235 }
1236
1237 if ($feed == -4) {
1238 db_query("UPDATE ttrss_user_entries
1239 SET unread = false, last_read = NOW() WHERE ref_id IN
1240 (SELECT id FROM
1241 (SELECT DISTINCT id FROM ttrss_entries, ttrss_user_entries WHERE ref_id = id
1242 AND owner_uid = $owner_uid AND unread = true AND $date_qpart) as tmp)");
1243 }
1244
1245 } else if ($feed < LABEL_BASE_INDEX) { // label
1246
1247 $label_id = feed_to_label_id($feed);
1248
1249 db_query("UPDATE ttrss_user_entries
1250 SET unread = false, last_read = NOW() WHERE ref_id IN
1251 (SELECT id FROM
1252 (SELECT DISTINCT ttrss_entries.id FROM ttrss_entries, ttrss_user_entries, ttrss_user_labels2 WHERE ref_id = id
1253 AND label_id = '$label_id' AND ref_id = article_id
1254 AND owner_uid = $owner_uid AND unread = true AND $date_qpart) as tmp)");
1255
1256 }
1257
1258 ccache_update($feed, $owner_uid, $cat_view);
1259
1260 } else { // tag
1261 db_query("UPDATE ttrss_user_entries
1262 SET unread = false, last_read = NOW() WHERE ref_id IN
1263 (SELECT id FROM
1264 (SELECT DISTINCT ttrss_entries.id FROM ttrss_entries, ttrss_user_entries, ttrss_tags WHERE ref_id = ttrss_entries.id
1265 AND post_int_id = int_id AND tag_name = '$feed'
1266 AND ttrss_user_entries.owner_uid = $owner_uid AND unread = true AND $date_qpart) as tmp)");
1267
1268 }
1269 }
1270
1271 function getAllCounters() {
1272 $data = getGlobalCounters();
1273
1274 $data = array_merge($data, getVirtCounters());
1275 $data = array_merge($data, getLabelCounters());
1276 $data = array_merge($data, getFeedCounters());
1277 $data = array_merge($data, getCategoryCounters());
1278
1279 return $data;
1280 }
1281
1282 function getCategoryTitle($cat_id) {
1283
1284 if ($cat_id == -1) {
1285 return __("Special");
1286 } else if ($cat_id == -2) {
1287 return __("Labels");
1288 } else {
1289
1290 $result = db_query("SELECT title FROM ttrss_feed_categories WHERE
1291 id = '$cat_id'");
1292
1293 if (db_num_rows($result) == 1) {
1294 return db_fetch_result($result, 0, "title");
1295 } else {
1296 return __("Uncategorized");
1297 }
1298 }
1299 }
1300
1301
1302 function getCategoryCounters() {
1303 $ret_arr = array();
1304
1305 /* Labels category */
1306
1307 $cv = array("id" => -2, "kind" => "cat",
1308 "counter" => getCategoryUnread(-2));
1309
1310 array_push($ret_arr, $cv);
1311
1312 $result = db_query("SELECT id AS cat_id, value AS unread,
1313 (SELECT COUNT(id) FROM ttrss_feed_categories AS c2
1314 WHERE c2.parent_cat = ttrss_feed_categories.id) AS num_children
1315 FROM ttrss_feed_categories, ttrss_cat_counters_cache
1316 WHERE ttrss_cat_counters_cache.feed_id = id AND
1317 ttrss_cat_counters_cache.owner_uid = ttrss_feed_categories.owner_uid AND
1318 ttrss_feed_categories.owner_uid = " . $_SESSION["uid"]);
1319
1320 while ($line = db_fetch_assoc($result)) {
1321 $line["cat_id"] = (int) $line["cat_id"];
1322
1323 if ($line["num_children"] > 0) {
1324 $child_counter = getCategoryChildrenUnread($line["cat_id"], $_SESSION["uid"]);
1325 } else {
1326 $child_counter = 0;
1327 }
1328
1329 $cv = array("id" => $line["cat_id"], "kind" => "cat",
1330 "counter" => $line["unread"] + $child_counter);
1331
1332 array_push($ret_arr, $cv);
1333 }
1334
1335 /* Special case: NULL category doesn't actually exist in the DB */
1336
1337 $cv = array("id" => 0, "kind" => "cat",
1338 "counter" => (int) ccache_find(0, $_SESSION["uid"], true));
1339
1340 array_push($ret_arr, $cv);
1341
1342 return $ret_arr;
1343 }
1344
1345 // only accepts real cats (>= 0)
1346 function getCategoryChildrenUnread($cat, $owner_uid = false) {
1347 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
1348
1349 $result = db_query("SELECT id FROM ttrss_feed_categories WHERE parent_cat = '$cat'
1350 AND owner_uid = $owner_uid");
1351
1352 $unread = 0;
1353
1354 while ($line = db_fetch_assoc($result)) {
1355 $unread += getCategoryUnread($line["id"], $owner_uid);
1356 $unread += getCategoryChildrenUnread($line["id"], $owner_uid);
1357 }
1358
1359 return $unread;
1360 }
1361
1362 function getCategoryUnread($cat, $owner_uid = false) {
1363
1364 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
1365
1366 if ($cat >= 0) {
1367
1368 if ($cat != 0) {
1369 $cat_query = "cat_id = '$cat'";
1370 } else {
1371 $cat_query = "cat_id IS NULL";
1372 }
1373
1374 $result = db_query("SELECT id FROM ttrss_feeds WHERE $cat_query
1375 AND owner_uid = " . $owner_uid);
1376
1377 $cat_feeds = array();
1378 while ($line = db_fetch_assoc($result)) {
1379 array_push($cat_feeds, "feed_id = " . $line["id"]);
1380 }
1381
1382 if (count($cat_feeds) == 0) return 0;
1383
1384 $match_part = implode(" OR ", $cat_feeds);
1385
1386 $result = db_query("SELECT COUNT(int_id) AS unread
1387 FROM ttrss_user_entries
1388 WHERE unread = true AND ($match_part)
1389 AND owner_uid = " . $owner_uid);
1390
1391 $unread = 0;
1392
1393 # this needs to be rewritten
1394 while ($line = db_fetch_assoc($result)) {
1395 $unread += $line["unread"];
1396 }
1397
1398 return $unread;
1399 } else if ($cat == -1) {
1400 return getFeedUnread(-1) + getFeedUnread(-2) + getFeedUnread(-3) + getFeedUnread(0);
1401 } else if ($cat == -2) {
1402
1403 $result = db_query("
1404 SELECT COUNT(unread) AS unread FROM
1405 ttrss_user_entries, ttrss_user_labels2
1406 WHERE article_id = ref_id AND unread = true
1407 AND ttrss_user_entries.owner_uid = '$owner_uid'");
1408
1409 $unread = db_fetch_result($result, 0, "unread");
1410
1411 return $unread;
1412
1413 }
1414 }
1415
1416 function getFeedUnread($feed, $is_cat = false) {
1417 return getFeedArticles($feed, $is_cat, true, $_SESSION["uid"]);
1418 }
1419
1420 function getLabelUnread($label_id, $owner_uid = false) {
1421 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
1422
1423 $result = db_query("SELECT COUNT(ref_id) AS unread FROM ttrss_user_entries, ttrss_user_labels2
1424 WHERE owner_uid = '$owner_uid' AND unread = true AND label_id = '$label_id' AND article_id = ref_id");
1425
1426 if (db_num_rows($result) != 0) {
1427 return db_fetch_result($result, 0, "unread");
1428 } else {
1429 return 0;
1430 }
1431 }
1432
1433 function getFeedArticles($feed, $is_cat = false, $unread_only = false,
1434 $owner_uid = false) {
1435
1436 $n_feed = (int) $feed;
1437 $need_entries = false;
1438
1439 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
1440
1441 if ($unread_only) {
1442 $unread_qpart = "unread = true";
1443 } else {
1444 $unread_qpart = "true";
1445 }
1446
1447 if ($is_cat) {
1448 return getCategoryUnread($n_feed, $owner_uid);
1449 } else if ($n_feed == -6) {
1450 return 0;
1451 } else if ($feed != "0" && $n_feed == 0) {
1452
1453 $feed = db_escape_string($feed);
1454
1455 $result = db_query("SELECT SUM((SELECT COUNT(int_id)
1456 FROM ttrss_user_entries,ttrss_entries WHERE int_id = post_int_id
1457 AND ref_id = id AND $unread_qpart)) AS count FROM ttrss_tags
1458 WHERE owner_uid = $owner_uid AND tag_name = '$feed'");
1459 return db_fetch_result($result, 0, "count");
1460
1461 } else if ($n_feed == -1) {
1462 $match_part = "marked = true";
1463 } else if ($n_feed == -2) {
1464 $match_part = "published = true";
1465 } else if ($n_feed == -3) {
1466 $match_part = "unread = true AND score >= 0";
1467
1468 $intl = get_pref("FRESH_ARTICLE_MAX_AGE", $owner_uid);
1469
1470 if (DB_TYPE == "pgsql") {
1471 $match_part .= " AND date_entered > NOW() - INTERVAL '$intl hour' ";
1472 } else {
1473 $match_part .= " AND date_entered > DATE_SUB(NOW(), INTERVAL $intl HOUR) ";
1474 }
1475
1476 $need_entries = true;
1477
1478 } else if ($n_feed == -4) {
1479 $match_part = "true";
1480 } else if ($n_feed >= 0) {
1481
1482 if ($n_feed != 0) {
1483 $match_part = "feed_id = '$n_feed'";
1484 } else {
1485 $match_part = "feed_id IS NULL";
1486 }
1487
1488 } else if ($feed < LABEL_BASE_INDEX) {
1489
1490 $label_id = feed_to_label_id($feed);
1491
1492 return getLabelUnread($label_id, $owner_uid);
1493
1494 }
1495
1496 if ($match_part) {
1497
1498 if ($need_entries) {
1499 $from_qpart = "ttrss_user_entries,ttrss_entries";
1500 $from_where = "ttrss_entries.id = ttrss_user_entries.ref_id AND";
1501 } else {
1502 $from_qpart = "ttrss_user_entries";
1503 $from_where = "";
1504 }
1505
1506 $query = "SELECT count(int_id) AS unread
1507 FROM $from_qpart WHERE
1508 $unread_qpart AND $from_where ($match_part) AND ttrss_user_entries.owner_uid = $owner_uid";
1509
1510 //echo "[$feed/$query]\n";
1511
1512 $result = db_query($query);
1513
1514 } else {
1515
1516 $result = db_query("SELECT COUNT(post_int_id) AS unread
1517 FROM ttrss_tags,ttrss_user_entries,ttrss_entries
1518 WHERE tag_name = '$feed' AND post_int_id = int_id AND ref_id = ttrss_entries.id
1519 AND $unread_qpart AND ttrss_tags.owner_uid = " . $owner_uid);
1520 }
1521
1522 $unread = db_fetch_result($result, 0, "unread");
1523
1524 return $unread;
1525 }
1526
1527 function getGlobalUnread($user_id = false) {
1528
1529 if (!$user_id) {
1530 $user_id = $_SESSION["uid"];
1531 }
1532
1533 $result = db_query("SELECT SUM(value) AS c_id FROM ttrss_counters_cache
1534 WHERE owner_uid = '$user_id' AND feed_id > 0");
1535
1536 $c_id = db_fetch_result($result, 0, "c_id");
1537
1538 return $c_id;
1539 }
1540
1541 function getGlobalCounters($global_unread = -1) {
1542 $ret_arr = array();
1543
1544 if ($global_unread == -1) {
1545 $global_unread = getGlobalUnread();
1546 }
1547
1548 $cv = array("id" => "global-unread",
1549 "counter" => (int) $global_unread);
1550
1551 array_push($ret_arr, $cv);
1552
1553 $result = db_query("SELECT COUNT(id) AS fn FROM
1554 ttrss_feeds WHERE owner_uid = " . $_SESSION["uid"]);
1555
1556 $subscribed_feeds = db_fetch_result($result, 0, "fn");
1557
1558 $cv = array("id" => "subscribed-feeds",
1559 "counter" => (int) $subscribed_feeds);
1560
1561 array_push($ret_arr, $cv);
1562
1563 return $ret_arr;
1564 }
1565
1566 function getVirtCounters() {
1567
1568 $ret_arr = array();
1569
1570 for ($i = 0; $i >= -4; $i--) {
1571
1572 $count = getFeedUnread($i);
1573
1574 if ($i == 0 || $i == -1 || $i == -2)
1575 $auxctr = getFeedArticles($i, false);
1576 else
1577 $auxctr = 0;
1578
1579 $cv = array("id" => $i,
1580 "counter" => (int) $count,
1581 "auxcounter" => $auxctr);
1582
1583 // if (get_pref('EXTENDED_FEEDLIST'))
1584 // $cv["xmsg"] = getFeedArticles($i)." ".__("total");
1585
1586 array_push($ret_arr, $cv);
1587 }
1588
1589 $feeds = PluginHost::getInstance()->get_feeds(-1);
1590
1591 if (is_array($feeds)) {
1592 foreach ($feeds as $feed) {
1593 $cv = array("id" => PluginHost::pfeed_to_feed_id($feed['id']),
1594 "counter" => $feed['sender']->get_unread($feed['id']));
1595
1596 if (method_exists($feed['sender'], 'get_total'))
1597 $cv["auxcounter"] = $feed['sender']->get_total($feed['id']);
1598
1599 array_push($ret_arr, $cv);
1600 }
1601 }
1602
1603 return $ret_arr;
1604 }
1605
1606 function getLabelCounters($descriptions = false) {
1607
1608 $ret_arr = array();
1609
1610 $owner_uid = $_SESSION["uid"];
1611
1612 $result = db_query("SELECT id,caption,SUM(CASE WHEN u1.unread = true THEN 1 ELSE 0 END) AS unread, COUNT(u1.unread) AS total
1613 FROM ttrss_labels2 LEFT JOIN ttrss_user_labels2 ON
1614 (ttrss_labels2.id = label_id)
1615 LEFT JOIN ttrss_user_entries AS u1 ON u1.ref_id = article_id
1616 WHERE ttrss_labels2.owner_uid = $owner_uid AND u1.owner_uid = $owner_uid
1617 GROUP BY ttrss_labels2.id,
1618 ttrss_labels2.caption");
1619
1620 while ($line = db_fetch_assoc($result)) {
1621
1622 $id = label_to_feed_id($line["id"]);
1623
1624 $cv = array("id" => $id,
1625 "counter" => (int) $line["unread"],
1626 "auxcounter" => (int) $line["total"]);
1627
1628 if ($descriptions)
1629 $cv["description"] = $line["caption"];
1630
1631 array_push($ret_arr, $cv);
1632 }
1633
1634 return $ret_arr;
1635 }
1636
1637 function getFeedCounters($active_feed = false) {
1638
1639 $ret_arr = array();
1640
1641 $query = "SELECT ttrss_feeds.id,
1642 ttrss_feeds.title,
1643 ".SUBSTRING_FOR_DATE."(ttrss_feeds.last_updated,1,19) AS last_updated,
1644 last_error, value AS count
1645 FROM ttrss_feeds, ttrss_counters_cache
1646 WHERE ttrss_feeds.owner_uid = ".$_SESSION["uid"]."
1647 AND ttrss_counters_cache.owner_uid = ttrss_feeds.owner_uid
1648 AND ttrss_counters_cache.feed_id = id";
1649
1650 $result = db_query($query);
1651
1652 while ($line = db_fetch_assoc($result)) {
1653
1654 $id = $line["id"];
1655 $count = $line["count"];
1656 $last_error = htmlspecialchars($line["last_error"]);
1657
1658 $last_updated = make_local_datetime($line['last_updated'], false);
1659
1660 $has_img = feed_has_icon($id);
1661
1662 if (date('Y') - date('Y', strtotime($line['last_updated'])) > 2)
1663 $last_updated = '';
1664
1665 $cv = array("id" => $id,
1666 "updated" => $last_updated,
1667 "counter" => (int) $count,
1668 "has_img" => (int) $has_img);
1669
1670 if ($last_error)
1671 $cv["error"] = $last_error;
1672
1673 // if (get_pref('EXTENDED_FEEDLIST'))
1674 // $cv["xmsg"] = getFeedArticles($id)." ".__("total");
1675
1676 if ($active_feed && $id == $active_feed)
1677 $cv["title"] = truncate_string($line["title"], 30);
1678
1679 array_push($ret_arr, $cv);
1680
1681 }
1682
1683 return $ret_arr;
1684 }
1685
1686 function get_pgsql_version() {
1687 $result = db_query("SELECT version() AS version");
1688 $version = explode(" ", db_fetch_result($result, 0, "version"));
1689 return $version[1];
1690 }
1691
1692 /**
1693 * @return array (code => Status code, message => error message if available)
1694 *
1695 * 0 - OK, Feed already exists
1696 * 1 - OK, Feed added
1697 * 2 - Invalid URL
1698 * 3 - URL content is HTML, no feeds available
1699 * 4 - URL content is HTML which contains multiple feeds.
1700 * Here you should call extractfeedurls in rpc-backend
1701 * to get all possible feeds.
1702 * 5 - Couldn't download the URL content.
1703 * 6 - Content is an invalid XML.
1704 */
1705 function subscribe_to_feed($url, $cat_id = 0,
1706 $auth_login = '', $auth_pass = '') {
1707
1708 global $fetch_last_error;
1709
1710 require_once "include/rssfuncs.php";
1711
1712 $url = fix_url($url);
1713
1714 if (!$url || !validate_feed_url($url)) return array("code" => 2);
1715
1716 $contents = @fetch_file_contents($url, false, $auth_login, $auth_pass);
1717
1718 if (!$contents) {
1719 return array("code" => 5, "message" => $fetch_last_error);
1720 }
1721
1722 foreach (PluginHost::getInstance()->get_hooks(PluginHost::HOOK_SUBSCRIBE_FEED) as $plugin) {
1723 $contents = $plugin->hook_subscribe_feed($contents, $url, $auth_login, $auth_pass);
1724 }
1725
1726 if (is_html($contents)) {
1727 $feedUrls = get_feeds_from_html($url, $contents);
1728
1729 if (count($feedUrls) == 0) {
1730 return array("code" => 3);
1731 } else if (count($feedUrls) > 1) {
1732 return array("code" => 4, "feeds" => $feedUrls);
1733 }
1734 //use feed url as new URL
1735 $url = key($feedUrls);
1736 }
1737
1738 if ($cat_id == "0" || !$cat_id) {
1739 $cat_qpart = "NULL";
1740 } else {
1741 $cat_qpart = "'$cat_id'";
1742 }
1743
1744 $result = db_query(
1745 "SELECT id FROM ttrss_feeds
1746 WHERE feed_url = '$url' AND owner_uid = ".$_SESSION["uid"]);
1747
1748 if (strlen(FEED_CRYPT_KEY) > 0) {
1749 require_once "crypt.php";
1750 $auth_pass = substr(encrypt_string($auth_pass), 0, 250);
1751 $auth_pass_encrypted = 'true';
1752 } else {
1753 $auth_pass_encrypted = 'false';
1754 }
1755
1756 $auth_pass = db_escape_string($auth_pass);
1757
1758 if (db_num_rows($result) == 0) {
1759 $result = db_query(
1760 "INSERT INTO ttrss_feeds
1761 (owner_uid,feed_url,title,cat_id, auth_login,auth_pass,update_method,auth_pass_encrypted)
1762 VALUES ('".$_SESSION["uid"]."', '$url',
1763 '[Unknown]', $cat_qpart, '$auth_login', '$auth_pass', 0, $auth_pass_encrypted)");
1764
1765 $result = db_query(
1766 "SELECT id FROM ttrss_feeds WHERE feed_url = '$url'
1767 AND owner_uid = " . $_SESSION["uid"]);
1768
1769 $feed_id = db_fetch_result($result, 0, "id");
1770
1771 if ($feed_id) {
1772 set_basic_feed_info($feed_id);
1773 }
1774
1775 return array("code" => 1, "feed_id" => (int) $feed_id);
1776 } else {
1777 return array("code" => 0, "feed_id" => (int) db_fetch_result($result, 0, "id"));
1778 }
1779 }
1780
1781 function print_feed_select($id, $default_id = "",
1782 $attributes = "", $include_all_feeds = true,
1783 $root_id = false, $nest_level = 0) {
1784
1785 if (!$root_id) {
1786 print "<select id=\"$id\" name=\"$id\" $attributes>";
1787 if ($include_all_feeds) {
1788 $is_selected = ("0" == $default_id) ? "selected=\"1\"" : "";
1789 print "<option $is_selected value=\"0\">".__('All feeds')."</option>";
1790 }
1791 }
1792
1793 if (get_pref('ENABLE_FEED_CATS')) {
1794
1795 if ($root_id)
1796 $parent_qpart = "parent_cat = '$root_id'";
1797 else
1798 $parent_qpart = "parent_cat IS NULL";
1799
1800 $result = db_query("SELECT id,title,
1801 (SELECT COUNT(id) FROM ttrss_feed_categories AS c2 WHERE
1802 c2.parent_cat = ttrss_feed_categories.id) AS num_children
1803 FROM ttrss_feed_categories
1804 WHERE owner_uid = ".$_SESSION["uid"]." AND $parent_qpart ORDER BY title");
1805
1806 while ($line = db_fetch_assoc($result)) {
1807
1808 for ($i = 0; $i < $nest_level; $i++)
1809 $line["title"] = " - " . $line["title"];
1810
1811 $is_selected = ("CAT:".$line["id"] == $default_id) ? "selected=\"1\"" : "";
1812
1813 printf("<option $is_selected value='CAT:%d'>%s</option>",
1814 $line["id"], htmlspecialchars($line["title"]));
1815
1816 if ($line["num_children"] > 0)
1817 print_feed_select($id, $default_id, $attributes,
1818 $include_all_feeds, $line["id"], $nest_level+1);
1819
1820 $feed_result = db_query("SELECT id,title FROM ttrss_feeds
1821 WHERE cat_id = '".$line["id"]."' AND owner_uid = ".$_SESSION["uid"] . " ORDER BY title");
1822
1823 while ($fline = db_fetch_assoc($feed_result)) {
1824 $is_selected = ($fline["id"] == $default_id) ? "selected=\"1\"" : "";
1825
1826 $fline["title"] = " + " . $fline["title"];
1827
1828 for ($i = 0; $i < $nest_level; $i++)
1829 $fline["title"] = " - " . $fline["title"];
1830
1831 printf("<option $is_selected value='%d'>%s</option>",
1832 $fline["id"], htmlspecialchars($fline["title"]));
1833 }
1834 }
1835
1836 if (!$root_id) {
1837 $default_is_cat = ($default_id == "CAT:0");
1838 $is_selected = $default_is_cat ? "selected=\"1\"" : "";
1839
1840 printf("<option $is_selected value='CAT:0'>%s</option>",
1841 __("Uncategorized"));
1842
1843 $feed_result = db_query("SELECT id,title FROM ttrss_feeds
1844 WHERE cat_id IS NULL AND owner_uid = ".$_SESSION["uid"] . " ORDER BY title");
1845
1846 while ($fline = db_fetch_assoc($feed_result)) {
1847 $is_selected = ($fline["id"] == $default_id && !$default_is_cat) ? "selected=\"1\"" : "";
1848
1849 $fline["title"] = " + " . $fline["title"];
1850
1851 for ($i = 0; $i < $nest_level; $i++)
1852 $fline["title"] = " - " . $fline["title"];
1853
1854 printf("<option $is_selected value='%d'>%s</option>",
1855 $fline["id"], htmlspecialchars($fline["title"]));
1856 }
1857 }
1858
1859 } else {
1860 $result = db_query("SELECT id,title FROM ttrss_feeds
1861 WHERE owner_uid = ".$_SESSION["uid"]." ORDER BY title");
1862
1863 while ($line = db_fetch_assoc($result)) {
1864
1865 $is_selected = ($line["id"] == $default_id) ? "selected=\"1\"" : "";
1866
1867 printf("<option $is_selected value='%d'>%s</option>",
1868 $line["id"], htmlspecialchars($line["title"]));
1869 }
1870 }
1871
1872 if (!$root_id) {
1873 print "</select>";
1874 }
1875 }
1876
1877 function print_feed_cat_select($id, $default_id,
1878 $attributes, $include_all_cats = true, $root_id = false, $nest_level = 0) {
1879
1880 if (!$root_id) {
1881 print "<select id=\"$id\" name=\"$id\" default=\"$default_id\" onchange=\"catSelectOnChange(this)\" $attributes>";
1882 }
1883
1884 if ($root_id)
1885 $parent_qpart = "parent_cat = '$root_id'";
1886 else
1887 $parent_qpart = "parent_cat IS NULL";
1888
1889 $result = db_query("SELECT id,title,
1890 (SELECT COUNT(id) FROM ttrss_feed_categories AS c2 WHERE
1891 c2.parent_cat = ttrss_feed_categories.id) AS num_children
1892 FROM ttrss_feed_categories
1893 WHERE owner_uid = ".$_SESSION["uid"]." AND $parent_qpart ORDER BY title");
1894
1895 while ($line = db_fetch_assoc($result)) {
1896 if ($line["id"] == $default_id) {
1897 $is_selected = "selected=\"1\"";
1898 } else {
1899 $is_selected = "";
1900 }
1901
1902 for ($i = 0; $i < $nest_level; $i++)
1903 $line["title"] = " - " . $line["title"];
1904
1905 if ($line["title"])
1906 printf("<option $is_selected value='%d'>%s</option>",
1907 $line["id"], htmlspecialchars($line["title"]));
1908
1909 if ($line["num_children"] > 0)
1910 print_feed_cat_select($id, $default_id, $attributes,
1911 $include_all_cats, $line["id"], $nest_level+1);
1912 }
1913
1914 if (!$root_id) {
1915 if ($include_all_cats) {
1916 if (db_num_rows($result) > 0) {
1917 print "<option disabled=\"1\">--------</option>";
1918 }
1919
1920 if ($default_id == 0) {
1921 $is_selected = "selected=\"1\"";
1922 } else {
1923 $is_selected = "";
1924 }
1925
1926 print "<option $is_selected value=\"0\">".__('Uncategorized')."</option>";
1927 }
1928 print "</select>";
1929 }
1930 }
1931
1932 function checkbox_to_sql_bool($val) {
1933 return ($val == "on") ? "true" : "false";
1934 }
1935
1936 function getFeedCatTitle($id) {
1937 if ($id == -1) {
1938 return __("Special");
1939 } else if ($id < LABEL_BASE_INDEX) {
1940 return __("Labels");
1941 } else if ($id > 0) {
1942 $result = db_query("SELECT ttrss_feed_categories.title
1943 FROM ttrss_feeds, ttrss_feed_categories WHERE ttrss_feeds.id = '$id' AND
1944 cat_id = ttrss_feed_categories.id");
1945 if (db_num_rows($result) == 1) {
1946 return db_fetch_result($result, 0, "title");
1947 } else {
1948 return __("Uncategorized");
1949 }
1950 } else {
1951 return "getFeedCatTitle($id) failed";
1952 }
1953
1954 }
1955
1956 function getFeedIcon($id) {
1957 switch ($id) {
1958 case 0:
1959 return "images/archive.png";
1960 break;
1961 case -1:
1962 return "images/star.png";
1963 break;
1964 case -2:
1965 return "images/feed.png";
1966 break;
1967 case -3:
1968 return "images/fresh.png";
1969 break;
1970 case -4:
1971 return "images/folder.png";
1972 break;
1973 case -6:
1974 return "images/time.png";
1975 break;
1976 default:
1977 if ($id < LABEL_BASE_INDEX) {
1978 return "images/label.png";
1979 } else {
1980 if (file_exists(ICONS_DIR . "/$id.ico"))
1981 return ICONS_URL . "/$id.ico";
1982 }
1983 break;
1984 }
1985
1986 return false;
1987 }
1988
1989 function getFeedTitle($id, $cat = false) {
1990 if ($cat) {
1991 return getCategoryTitle($id);
1992 } else if ($id == -1) {
1993 return __("Starred articles");
1994 } else if ($id == -2) {
1995 return __("Published articles");
1996 } else if ($id == -3) {
1997 return __("Fresh articles");
1998 } else if ($id == -4) {
1999 return __("All articles");
2000 } else if ($id === 0 || $id === "0") {
2001 return __("Archived articles");
2002 } else if ($id == -6) {
2003 return __("Recently read");
2004 } else if ($id < LABEL_BASE_INDEX) {
2005 $label_id = feed_to_label_id($id);
2006 $result = db_query("SELECT caption FROM ttrss_labels2 WHERE id = '$label_id'");
2007 if (db_num_rows($result) == 1) {
2008 return db_fetch_result($result, 0, "caption");
2009 } else {
2010 return "Unknown label ($label_id)";
2011 }
2012
2013 } else if (is_numeric($id) && $id > 0) {
2014 $result = db_query("SELECT title FROM ttrss_feeds WHERE id = '$id'");
2015 if (db_num_rows($result) == 1) {
2016 return db_fetch_result($result, 0, "title");
2017 } else {
2018 return "Unknown feed ($id)";
2019 }
2020 } else {
2021 return $id;
2022 }
2023 }
2024
2025 function uniqid_short() {
2026 return uniqid(base_convert(rand(), 10, 36));
2027 }
2028
2029 // TODO: less dumb splitting
2030 require_once "functions2.php";
2031
2032 ?>