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