2 define('EXPECTED_CONFIG_VERSION', 25);
3 define('SCHEMA_VERSION', 92);
5 date_default_timezone_set('UTC');
6 if (defined('E_DEPRECATED')) {
7 error_reporting(E_ALL
& ~E_NOTICE
& ~E_DEPRECATED
);
9 error_reporting(E_ALL
& ~E_NOTICE
);
12 require_once 'config.php';
14 if (DB_TYPE
== "pgsql") {
15 define('SUBSTRING_FOR_DATE', 'SUBSTRING_FOR_DATE');
17 define('SUBSTRING_FOR_DATE', 'SUBSTRING');
20 define('THEME_VERSION_REQUIRED', 1.1);
23 * Return available translations names.
26 * @return array A array of available translations.
28 function get_translations() {
30 "auto" => "Detect automatically",
35 "fr_FR" => "Français",
36 "hu_HU" => "Magyar (Hungarian)",
37 "it_IT" => "Italiano",
38 "ja_JP" => "日本語 (Japanese)",
39 "nb_NO" => "Norwegian bokmål",
41 "pt_BR" => "Portuguese/Brazil",
42 "zh_CN" => "Simplified Chinese");
47 require_once "lib/accept-to-gettext.php";
48 require_once "lib/gettext/gettext.inc";
50 function startup_gettext() {
52 # Get locale from Accept-Language header
53 $lang = al2gt(array_keys(get_translations()), "text/html");
55 if (defined('_TRANSLATION_OVERRIDE_DEFAULT')) {
56 $lang = _TRANSLATION_OVERRIDE_DEFAULT
;
59 if ($_COOKIE["ttrss_lang"] && $_COOKIE["ttrss_lang"] != "auto") {
60 $lang = $_COOKIE["ttrss_lang"];
63 /* In login action of mobile version */
64 if ($_POST["language"] && defined('MOBILE_VERSION')) {
65 $lang = $_POST["language"];
66 $_COOKIE["ttrss_lang"] = $lang;
70 if (defined('LC_MESSAGES')) {
71 _setlocale(LC_MESSAGES
, $lang);
72 } else if (defined('LC_ALL')) {
73 _setlocale(LC_ALL
, $lang);
76 if (defined('MOBILE_VERSION')) {
77 _bindtextdomain("messages", "../locale");
79 _bindtextdomain("messages", "locale");
82 _textdomain("messages");
83 _bind_textdomain_codeset("messages", "UTF-8");
89 require_once 'db-prefs.php';
90 require_once 'version.php';
92 define('MAGPIE_OUTPUT_ENCODING', 'UTF-8');
94 define('SELF_USER_AGENT', 'Tiny Tiny RSS/' . VERSION
. ' (http://tt-rss.org/)');
95 define('MAGPIE_USER_AGENT', SELF_USER_AGENT
);
97 ini_set('user_agent', SELF_USER_AGENT
);
99 require_once 'lib/pubsubhubbub/publisher.php';
104 $utc_tz = new DateTimeZone('UTC');
105 $schema_version = false;
108 * Print a timestamped debug message.
110 * @param string $msg The debug message.
113 function _debug($msg) {
114 $ts = strftime("%H:%M:%S", time());
115 if (function_exists('posix_getpid')) {
116 $ts = "$ts/" . posix_getpid();
118 print "[$ts] $msg\n";
122 * Purge a feed old posts.
124 * @param mixed $link A database connection.
125 * @param mixed $feed_id The id of the purged feed.
126 * @param mixed $purge_interval Olderness of purged posts.
127 * @param boolean $debug Set to True to enable the debug. False by default.
131 function purge_feed($link, $feed_id, $purge_interval, $debug = false) {
133 if (!$purge_interval) $purge_interval = feed_purge_interval($link, $feed_id);
137 $result = db_query($link,
138 "SELECT owner_uid FROM ttrss_feeds WHERE id = '$feed_id'");
142 if (db_num_rows($result) == 1) {
143 $owner_uid = db_fetch_result($result, 0, "owner_uid");
146 if ($purge_interval == -1 ||
!$purge_interval) {
148 ccache_update($link, $feed_id, $owner_uid);
153 if (!$owner_uid) return;
155 if (FORCE_ARTICLE_PURGE
== 0) {
156 $purge_unread = get_pref($link, "PURGE_UNREAD_ARTICLES",
159 $purge_unread = true;
160 $purge_interval = FORCE_ARTICLE_PURGE
;
163 if (!$purge_unread) $query_limit = " unread = false AND ";
165 if (DB_TYPE
== "pgsql") {
166 $pg_version = get_pgsql_version($link);
168 if (preg_match("/^7\./", $pg_version) ||
preg_match("/^8\.0/", $pg_version)) {
170 $result = db_query($link, "DELETE FROM ttrss_user_entries WHERE
171 ttrss_entries.id = ref_id AND
173 feed_id = '$feed_id' AND
175 ttrss_entries.date_updated < NOW() - INTERVAL '$purge_interval days'");
179 $result = db_query($link, "DELETE FROM ttrss_user_entries
181 WHERE ttrss_entries.id = ref_id AND
183 feed_id = '$feed_id' AND
185 ttrss_entries.date_updated < NOW() - INTERVAL '$purge_interval days'");
188 $rows = pg_affected_rows($result);
192 /* $result = db_query($link, "DELETE FROM ttrss_user_entries WHERE
193 marked = false AND feed_id = '$feed_id' AND
194 (SELECT date_updated FROM ttrss_entries WHERE
195 id = ref_id) < DATE_SUB(NOW(), INTERVAL $purge_interval DAY)"); */
197 $result = db_query($link, "DELETE FROM ttrss_user_entries
198 USING ttrss_user_entries, ttrss_entries
199 WHERE ttrss_entries.id = ref_id AND
201 feed_id = '$feed_id' AND
203 ttrss_entries.date_updated < DATE_SUB(NOW(), INTERVAL $purge_interval DAY)");
205 $rows = mysql_affected_rows($link);
209 ccache_update($link, $feed_id, $owner_uid);
212 _debug("Purged feed $feed_id ($purge_interval): deleted $rows articles");
214 } // function purge_feed
216 function feed_purge_interval($link, $feed_id) {
218 $result = db_query($link, "SELECT purge_interval, owner_uid FROM ttrss_feeds
219 WHERE id = '$feed_id'");
221 if (db_num_rows($result) == 1) {
222 $purge_interval = db_fetch_result($result, 0, "purge_interval");
223 $owner_uid = db_fetch_result($result, 0, "owner_uid");
225 if ($purge_interval == 0) $purge_interval = get_pref($link,
226 'PURGE_OLD_DAYS', $owner_uid);
228 return $purge_interval;
235 function purge_orphans($link, $do_output = false) {
237 // purge orphaned posts in main content table
238 $result = db_query($link, "DELETE FROM ttrss_entries WHERE
239 (SELECT COUNT(int_id) FROM ttrss_user_entries WHERE ref_id = id) = 0");
242 $rows = db_affected_rows($link, $result);
243 _debug("Purged $rows orphaned posts.");
247 function get_feed_update_interval($link, $feed_id) {
248 $result = db_query($link, "SELECT owner_uid, update_interval FROM
249 ttrss_feeds WHERE id = '$feed_id'");
251 if (db_num_rows($result) == 1) {
252 $update_interval = db_fetch_result($result, 0, "update_interval");
253 $owner_uid = db_fetch_result($result, 0, "owner_uid");
255 if ($update_interval != 0) {
256 return $update_interval;
258 return get_pref($link, 'DEFAULT_UPDATE_INTERVAL', $owner_uid, false);
266 function fetch_file_contents($url, $type = false, $login = false, $pass = false, $post_query = false) {
267 $login = urlencode($login);
268 $pass = urlencode($pass);
270 if (function_exists('curl_init') && !ini_get("open_basedir")) {
271 $ch = curl_init($url);
273 curl_setopt($ch, CURLOPT_CONNECTTIMEOUT
, 15);
274 curl_setopt($ch, CURLOPT_TIMEOUT
, 45);
275 curl_setopt($ch, CURLOPT_FOLLOWLOCATION
, true);
276 curl_setopt($ch, CURLOPT_MAXREDIRS
, 20);
277 curl_setopt($ch, CURLOPT_BINARYTRANSFER
, true);
278 curl_setopt($ch, CURLOPT_RETURNTRANSFER
, true);
279 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER
, false);
280 curl_setopt($ch, CURLOPT_HTTPAUTH
, CURLAUTH_ANY
);
281 curl_setopt($ch, CURLOPT_USERAGENT
, SELF_USER_AGENT
);
282 curl_setopt($ch, CURLOPT_ENCODING
, "gzip");
285 curl_setopt($ch, CURLOPT_POST
, true);
286 curl_setopt($ch, CURLOPT_POSTFIELDS
, $post_query);
290 curl_setopt($ch, CURLOPT_USERPWD
, "$login:$pass");
292 $contents = @curl_exec
($ch);
294 if ($contents === false) {
299 $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE
);
300 $content_type = curl_getinfo($ch, CURLINFO_CONTENT_TYPE
);
303 if ($http_code != 200 ||
$type && strpos($content_type, "$type") === false) {
309 if ($login && $pass ){
310 $url_parts = array();
312 preg_match("/(^[^:]*):\/\/(.*)/", $url, $url_parts);
314 if ($url_parts[1] && $url_parts[2]) {
315 $url = $url_parts[1] . "://$login:$pass@" . $url_parts[2];
319 return @file_get_contents
($url);
325 * Try to determine the favicon URL for a feed.
326 * adapted from wordpress favicon plugin by Jeff Minard (http://thecodepro.com/)
327 * http://dev.wp-plugins.org/file/favatars/trunk/favatars.php
329 * @param string $url A feed or page URL
331 * @return mixed The favicon URL, or false if none was found.
333 function get_favicon_url($url) {
335 $favicon_url = false;
337 if ($html = @fetch_file_contents
($url)) {
339 libxml_use_internal_errors(true);
341 $doc = new DOMDocument();
342 $doc->loadHTML($html);
343 $xpath = new DOMXPath($doc);
345 $base = $xpath->query('/html/head/base');
346 foreach ($base as $b) {
347 $url = $b->getAttribute("href");
351 $entries = $xpath->query('/html/head/link[@rel="shortcut icon" or @rel="icon"]');
352 if (count($entries) > 0) {
353 foreach ($entries as $entry) {
354 $favicon_url = rewrite_relative_url($url, $entry->getAttribute("href"));
361 $favicon_url = rewrite_relative_url($url, "/favicon.ico");
364 } // function get_favicon_url
366 function check_feed_favicon($site_url, $feed, $link) {
367 # print "FAVICON [$site_url]: $favicon_url\n";
369 $icon_file = ICONS_DIR
. "/$feed.ico";
371 if (!file_exists($icon_file)) {
372 $favicon_url = get_favicon_url($site_url);
375 // Limiting to "image" type misses those served with text/plain
376 $contents = fetch_file_contents($favicon_url); // , "image");
379 // Crude image type matching.
380 // Patterns gleaned from the file(1) source code.
381 if (preg_match('/^\x00\x00\x01\x00/', $contents)) {
382 // 0 string \000\000\001\000 MS Windows icon resource
383 //error_log("check_feed_favicon: favicon_url=$favicon_url isa MS Windows icon resource");
385 elseif (preg_match('/^GIF8/', $contents)) {
386 // 0 string GIF8 GIF image data
387 //error_log("check_feed_favicon: favicon_url=$favicon_url isa GIF image");
389 elseif (preg_match('/^\x89PNG\x0d\x0a\x1a\x0a/', $contents)) {
390 // 0 string \x89PNG\x0d\x0a\x1a\x0a PNG image data
391 //error_log("check_feed_favicon: favicon_url=$favicon_url isa PNG image");
393 elseif (preg_match('/^\xff\xd8/', $contents)) {
394 // 0 beshort 0xffd8 JPEG image data
395 //error_log("check_feed_favicon: favicon_url=$favicon_url isa JPG image");
398 //error_log("check_feed_favicon: favicon_url=$favicon_url isa UNKNOWN type");
404 $fp = @fopen
($icon_file, "w");
407 fwrite($fp, $contents);
409 chmod($icon_file, 0644);
416 function print_select($id, $default, $values, $attributes = "") {
417 print "<select name=\"$id\" id=\"$id\" $attributes>";
418 foreach ($values as $v) {
420 $sel = "selected=\"1\"";
424 print "<option value=\"$v\" $sel>$v</option>";
429 function print_select_hash($id, $default, $values, $attributes = "") {
430 print "<select name=\"$id\" id='$id' $attributes>";
431 foreach (array_keys($values) as $v) {
433 $sel = 'selected="selected"';
437 print "<option $sel value=\"$v\">".$values[$v]."</option>";
443 function get_article_filters($filters, $title, $content, $link, $timestamp, $author, $tags) {
446 if ($filters["title"]) {
447 foreach ($filters["title"] as $filter) {
448 $reg_exp = $filter["reg_exp"];
449 $inverse = $filter["inverse"];
450 if ((!$inverse && @preg_match
("/$reg_exp/i", $title)) ||
451 ($inverse && !@preg_match
("/$reg_exp/i", $title))) {
453 array_push($matches, array($filter["action"], $filter["action_param"]));
458 if ($filters["content"]) {
459 foreach ($filters["content"] as $filter) {
460 $reg_exp = $filter["reg_exp"];
461 $inverse = $filter["inverse"];
463 if ((!$inverse && @preg_match
("/$reg_exp/i", $content)) ||
464 ($inverse && !@preg_match
("/$reg_exp/i", $content))) {
466 array_push($matches, array($filter["action"], $filter["action_param"]));
471 if ($filters["both"]) {
472 foreach ($filters["both"] as $filter) {
473 $reg_exp = $filter["reg_exp"];
474 $inverse = $filter["inverse"];
477 if (!@preg_match
("/$reg_exp/i", $title) && !preg_match("/$reg_exp/i", $content)) {
478 array_push($matches, array($filter["action"], $filter["action_param"]));
481 if (@preg_match
("/$reg_exp/i", $title) ||
preg_match("/$reg_exp/i", $content)) {
482 array_push($matches, array($filter["action"], $filter["action_param"]));
488 if ($filters["link"]) {
489 $reg_exp = $filter["reg_exp"];
490 foreach ($filters["link"] as $filter) {
491 $reg_exp = $filter["reg_exp"];
492 $inverse = $filter["inverse"];
494 if ((!$inverse && @preg_match
("/$reg_exp/i", $link)) ||
495 ($inverse && !@preg_match
("/$reg_exp/i", $link))) {
497 array_push($matches, array($filter["action"], $filter["action_param"]));
502 if ($filters["date"]) {
503 $reg_exp = $filter["reg_exp"];
504 foreach ($filters["date"] as $filter) {
505 $date_modifier = $filter["filter_param"];
506 $inverse = $filter["inverse"];
507 $check_timestamp = strtotime($filter["reg_exp"]);
509 # no-op when timestamp doesn't parse to prevent misfires
511 if ($check_timestamp) {
514 if ($date_modifier == "before" && $timestamp < $check_timestamp ||
515 $date_modifier == "after" && $timestamp > $check_timestamp) {
519 if ($inverse) $match_ok = !$match_ok;
522 array_push($matches, array($filter["action"], $filter["action_param"]));
528 if ($filters["author"]) {
529 foreach ($filters["author"] as $filter) {
530 $reg_exp = $filter["reg_exp"];
531 $inverse = $filter["inverse"];
532 if ((!$inverse && @preg_match
("/$reg_exp/i", $author)) ||
533 ($inverse && !@preg_match
("/$reg_exp/i", $author))) {
535 array_push($matches, array($filter["action"], $filter["action_param"]));
540 if ($filters["tag"]) {
542 $tag_string = join(",", $tags);
544 foreach ($filters["tag"] as $filter) {
545 $reg_exp = $filter["reg_exp"];
546 $inverse = $filter["inverse"];
548 if ((!$inverse && @preg_match
("/$reg_exp/i", $tag_string)) ||
549 ($inverse && !@preg_match
("/$reg_exp/i", $tag_string))) {
551 array_push($matches, array($filter["action"], $filter["action_param"]));
560 function find_article_filter($filters, $filter_name) {
561 foreach ($filters as $f) {
562 if ($f[0] == $filter_name) {
569 function calculate_article_score($filters) {
572 foreach ($filters as $f) {
573 if ($f[0] == "score") {
580 function assign_article_to_labels($link, $id, $filters, $owner_uid) {
581 foreach ($filters as $f) {
582 if ($f[0] == "label") {
583 label_add_article($link, $id, $f[1], $owner_uid);
588 function getmicrotime() {
589 list($usec, $sec) = explode(" ",microtime());
590 return ((float)$usec +
(float)$sec);
593 function print_radio($id, $default, $true_is, $values, $attributes = "") {
594 foreach ($values as $v) {
601 if ($v == $true_is) {
602 $sel .= " value=\"1\"";
604 $sel .= " value=\"0\"";
607 print "<input class=\"noborder\" dojoType=\"dijit.form.RadioButton\"
608 type=\"radio\" $sel $attributes name=\"$id\"> $v ";
613 function initialize_user_prefs($link, $uid, $profile = false) {
615 $uid = db_escape_string($uid);
619 $profile_qpart = "AND profile IS NULL";
621 $profile_qpart = "AND profile = '$profile'";
624 if (get_schema_version($link) < 63) $profile_qpart = "";
626 db_query($link, "BEGIN");
628 $result = db_query($link, "SELECT pref_name,def_value FROM ttrss_prefs");
630 $u_result = db_query($link, "SELECT pref_name
631 FROM ttrss_user_prefs WHERE owner_uid = '$uid' $profile_qpart");
633 $active_prefs = array();
635 while ($line = db_fetch_assoc($u_result)) {
636 array_push($active_prefs, $line["pref_name"]);
639 while ($line = db_fetch_assoc($result)) {
640 if (array_search($line["pref_name"], $active_prefs) === FALSE) {
641 // print "adding " . $line["pref_name"] . "<br>";
643 if (get_schema_version($link) < 63) {
644 db_query($link, "INSERT INTO ttrss_user_prefs
645 (owner_uid,pref_name,value) VALUES
646 ('$uid', '".$line["pref_name"]."','".$line["def_value"]."')");
649 db_query($link, "INSERT INTO ttrss_user_prefs
650 (owner_uid,pref_name,value, profile) VALUES
651 ('$uid', '".$line["pref_name"]."','".$line["def_value"]."', $profile)");
657 db_query($link, "COMMIT");
661 function get_ssl_certificate_id() {
662 if ($_SERVER["REDIRECT_SSL_CLIENT_M_SERIAL"]) {
663 return sha1($_SERVER["REDIRECT_SSL_CLIENT_M_SERIAL"] .
664 $_SERVER["REDIRECT_SSL_CLIENT_V_START"] .
665 $_SERVER["REDIRECT_SSL_CLIENT_V_END"] .
666 $_SERVER["REDIRECT_SSL_CLIENT_S_DN"]);
671 function get_login_by_ssl_certificate($link) {
673 $cert_serial = db_escape_string(get_ssl_certificate_id());
676 $result = db_query($link, "SELECT login FROM ttrss_user_prefs, ttrss_users
677 WHERE pref_name = 'SSL_CERT_SERIAL' AND value = '$cert_serial' AND
678 owner_uid = ttrss_users.id");
680 if (db_num_rows($result) != 0) {
681 return db_escape_string(db_fetch_result($result, 0, "login"));
688 function get_remote_user($link) {
690 if (defined('ALLOW_REMOTE_USER_AUTH') && ALLOW_REMOTE_USER_AUTH
) {
691 return db_escape_string($_SERVER["REMOTE_USER"]);
694 return db_escape_string(get_login_by_ssl_certificate($link));
697 function get_remote_fakepass($link) {
698 if (get_remote_user($link))
704 function authenticate_user($link, $login, $password, $force_auth = false) {
706 if (!SINGLE_USER_MODE
) {
708 $pwd_hash1 = encrypt_password($password);
709 $pwd_hash2 = encrypt_password($password, $login);
710 $login = db_escape_string($login);
712 $remote_user = get_remote_user($link);
714 if ($remote_user && $remote_user == $login && $login != "admin") {
716 $login = $remote_user;
718 $query = "SELECT id,login,access_level,pwd_hash
719 FROM ttrss_users WHERE
722 if (defined('AUTO_CREATE_USER') && AUTO_CREATE_USER
723 && $_SERVER["REMOTE_USER"]) {
724 $result = db_query($link, $query);
727 if (db_num_rows($result) == 0) {
728 $salt = substr(bin2hex(get_random_bytes(125)), 0, 250);
729 $pwd_hash = encrypt_password($password, $salt, true);
731 $query2 = "INSERT INTO ttrss_users
732 (login,access_level,last_login,created,pwd_hash,salt)
733 VALUES ('$login', 0, null, NOW(), '$pwd_hash','$salt')";
734 db_query($link, $query2);
738 } else if (get_schema_version($link) > 87) {
739 $result = db_query($link, "SELECT salt FROM ttrss_users WHERE
742 if (db_num_rows($result) != 1) {
746 $salt = db_fetch_result($result, 0, "salt");
750 $query = "SELECT id,login,access_level,pwd_hash
751 FROM ttrss_users WHERE
752 login = '$login' AND (pwd_hash = '$pwd_hash1' OR
753 pwd_hash = '$pwd_hash2')";
755 // verify and upgrade password to new salt base
757 $result = db_query($link, $query);
759 if (db_num_rows($result) == 1) {
760 // upgrade password to MODE2
762 $salt = substr(bin2hex(get_random_bytes(125)), 0, 250);
763 $pwd_hash = encrypt_password($password, $salt, true);
765 db_query($link, "UPDATE ttrss_users SET
766 pwd_hash = '$pwd_hash', salt = '$salt' WHERE login = '$login'");
768 $query = "SELECT id,login,access_level,pwd_hash
769 FROM ttrss_users WHERE
770 login = '$login' AND pwd_hash = '$pwd_hash'";
778 $pwd_hash = encrypt_password($password, $salt, true);
780 $query = "SELECT id,login,access_level,pwd_hash
781 FROM ttrss_users WHERE
782 login = '$login' AND pwd_hash = '$pwd_hash'";
786 $query = "SELECT id,login,access_level,pwd_hash
787 FROM ttrss_users WHERE
788 login = '$login' AND (pwd_hash = '$pwd_hash1' OR
789 pwd_hash = '$pwd_hash2')";
792 $result = db_query($link, $query);
794 if (db_num_rows($result) == 1) {
795 $_SESSION["uid"] = db_fetch_result($result, 0, "id");
796 $_SESSION["name"] = db_fetch_result($result, 0, "login");
797 $_SESSION["access_level"] = db_fetch_result($result, 0, "access_level");
798 $_SESSION["csrf_token"] = sha1(uniqid(rand(), true));
800 db_query($link, "UPDATE ttrss_users SET last_login = NOW() WHERE id = " .
804 // LemonLDAP can send user informations via HTTP HEADER
805 if (defined('AUTO_CREATE_USER') && AUTO_CREATE_USER
){
807 $fullname = $_SERVER['HTTP_USER_NAME'] ?
$_SERVER['HTTP_USER_NAME'] : $_SERVER['AUTHENTICATE_CN'];
809 $fullname = db_escape_string($fullname);
810 db_query($link, "UPDATE ttrss_users SET full_name = '$fullname' WHERE id = " .
814 $email = $_SERVER['HTTP_USER_MAIL'] ?
$_SERVER['HTTP_USER_MAIL'] : $_SERVER['AUTHENTICATE_MAIL'];
816 $email = db_escape_string($email);
817 db_query($link, "UPDATE ttrss_users SET email = '$email' WHERE id = " .
822 $_SESSION["ip_address"] = $_SERVER["REMOTE_ADDR"];
823 $_SESSION["pwd_hash"] = db_fetch_result($result, 0, "pwd_hash");
825 $_SESSION["last_version_check"] = time();
827 initialize_user_prefs($link, $_SESSION["uid"]);
836 $_SESSION["uid"] = 1;
837 $_SESSION["name"] = "admin";
838 $_SESSION["access_level"] = 10;
840 if (!$_SESSION["csrf_token"]) {
841 $_SESSION["csrf_token"] = sha1(uniqid(rand(), true));
844 $_SESSION["ip_address"] = $_SERVER["REMOTE_ADDR"];
846 initialize_user_prefs($link, $_SESSION["uid"]);
852 function make_password($length = 8) {
855 $possible = "0123456789abcdfghjkmnpqrstvwxyzABCDFGHJKMNPQRSTVWXYZ";
859 while ($i < $length) {
860 $char = substr($possible, mt_rand(0, strlen($possible)-1), 1);
862 if (!strstr($password, $char)) {
870 // this is called after user is created to initialize default feeds, labels
873 // user preferences are checked on every login, not here
875 function initialize_user($link, $uid) {
877 db_query($link, "insert into ttrss_feeds (owner_uid,title,feed_url)
878 values ('$uid', 'Tiny Tiny RSS: New Releases',
879 'http://tt-rss.org/releases.rss')");
881 db_query($link, "insert into ttrss_feeds (owner_uid,title,feed_url)
882 values ('$uid', 'Tiny Tiny RSS: Forum',
883 'http://tt-rss.org/forum/rss.php')");
886 function logout_user() {
888 if (isset($_COOKIE[session_name()])) {
889 setcookie(session_name(), '', time()-42000, '/');
893 function validate_csrf($csrf_token) {
894 return $csrf_token == $_SESSION['csrf_token'];
897 function validate_session($link) {
898 if (SINGLE_USER_MODE
) return true;
900 $check_ip = $_SESSION['ip_address'];
902 switch (SESSION_CHECK_ADDRESS
) {
907 $check_ip = substr($check_ip, 0, strrpos($check_ip, '.')+
1);
910 $check_ip = substr($check_ip, 0, strrpos($check_ip, '.'));
911 $check_ip = substr($check_ip, 0, strrpos($check_ip, '.')+
1);
915 if ($check_ip && strpos($_SERVER['REMOTE_ADDR'], $check_ip) !== 0) {
916 $_SESSION["login_error_msg"] =
917 __("Session failed to validate (incorrect IP)");
921 if ($_SESSION["ref_schema_version"] != get_schema_version($link, true))
924 if ($_SESSION["uid"]) {
926 $result = db_query($link,
927 "SELECT pwd_hash FROM ttrss_users WHERE id = '".$_SESSION["uid"]."'");
929 $pwd_hash = db_fetch_result($result, 0, "pwd_hash");
931 if ($pwd_hash != $_SESSION["pwd_hash"]) {
936 /* if ($_SESSION["cookie_lifetime"] && $_SESSION["uid"]) {
938 //print_r($_SESSION);
940 if (time() > $_SESSION["cookie_lifetime"]) {
948 function login_sequence($link, $mobile = false) {
949 $_SESSION["prefs_cache"] = array();
951 if (!SINGLE_USER_MODE
) {
953 $login_action = $_POST["login_action"];
955 # try to authenticate user if called from login form
956 if ($login_action == "do_login") {
957 $login = db_escape_string($_POST["login"]);
958 $password = $_POST["password"];
959 $remember_me = $_POST["remember_me"];
961 if (authenticate_user($link, $login, $password)) {
962 $_POST["password"] = "";
964 $_SESSION["language"] = $_POST["language"];
965 $_SESSION["ref_schema_version"] = get_schema_version($link, true);
966 $_SESSION["bw_limit"] = !!$_POST["bw_limit"];
968 if ($_POST["profile"]) {
970 $profile = db_escape_string($_POST["profile"]);
972 $result = db_query($link, "SELECT id FROM ttrss_settings_profiles
973 WHERE id = '$profile' AND owner_uid = " . $_SESSION["uid"]);
975 if (db_num_rows($result) != 0) {
976 $_SESSION["profile"] = $profile;
977 $_SESSION["prefs_cache"] = array();
981 if ($_REQUEST['return']) {
982 header("Location: " . $_REQUEST['return']);
984 header("Location: " . $_SERVER["REQUEST_URI"]);
991 $_SESSION["login_error_msg"] = __("Incorrect username or password");
995 if (!$_SESSION["uid"] ||
!validate_session($link)) {
997 if (get_remote_user($link) && AUTO_LOGIN
) {
998 authenticate_user($link, get_remote_user($link), null);
999 $_SESSION["ref_schema_version"] = get_schema_version($link, true);
1001 render_login_form($link, $mobile);
1002 //header("Location: login.php");
1006 /* bump login timestamp */
1007 db_query($link, "UPDATE ttrss_users SET last_login = NOW() WHERE id = " .
1010 if ($_SESSION["language"] && SESSION_COOKIE_LIFETIME
> 0) {
1011 setcookie("ttrss_lang", $_SESSION["language"],
1012 time() + SESSION_COOKIE_LIFETIME
);
1015 // try to remove possible duplicates from feed counter cache
1016 // ccache_cleanup($link, $_SESSION["uid"]);
1020 return authenticate_user($link, "admin", null);
1024 function truncate_string($str, $max_len, $suffix = '…') {
1025 if (mb_strlen($str, "utf-8") > $max_len - 3) {
1026 return mb_substr($str, 0, $max_len, "utf-8") . $suffix;
1032 function theme_image($link, $filename) {
1034 $theme_path = get_user_theme_path($link);
1036 if ($theme_path && is_file($theme_path.$filename)) {
1037 return $theme_path.$filename;
1046 function get_user_theme($link) {
1048 if (get_schema_version($link) >= 63 && $_SESSION["uid"]) {
1049 $theme_name = get_pref($link, "_THEME_ID");
1050 if (is_dir("themes/$theme_name")) {
1061 function get_user_theme_path($link) {
1064 if (get_schema_version($link) >= 63 && $_SESSION["uid"]) {
1065 $theme_name = get_pref($link, "_THEME_ID");
1067 if ($theme_name && is_dir("themes/$theme_name")) {
1068 $theme_path = "themes/$theme_name/";
1077 if (is_file("$theme_path/theme.ini")) {
1078 $ini = parse_ini_file("$theme_path/theme.ini", true);
1079 if ($ini['theme']['version'] >= THEME_VERSION_REQUIRED
) {
1087 function get_user_theme_options($link) {
1088 $t = get_user_theme_path($link);
1091 if (is_file("$t/theme.ini")) {
1092 $ini = parse_ini_file("$t/theme.ini", true);
1093 if ($ini['theme']['version']) {
1094 return $ini['theme']['options'];
1101 function print_theme_includes($link) {
1103 $t = get_user_theme_path($link);
1107 print "<link rel=\"stylesheet\" type=\"text/css\"
1108 href=\"$t/theme.css?$time \">";
1109 if (file_exists("$t/theme.js")) {
1110 print "<script type=\"text/javascript\" src=\"$t/theme.js?$time\">
1116 function get_all_themes() {
1117 $themes = glob("themes/*");
1123 foreach ($themes as $t) {
1124 if (is_file("$t/theme.ini")) {
1125 $ini = parse_ini_file("$t/theme.ini", true);
1126 if ($ini['theme']['version'] >= THEME_VERSION_REQUIRED
&&
1127 !$ini['theme']['disabled']) {
1129 $entry["path"] = $t;
1130 $entry["base"] = basename($t);
1131 $entry["name"] = $ini['theme']['name'];
1132 $entry["version"] = $ini['theme']['version'];
1133 $entry["author"] = $ini['theme']['author'];
1134 $entry["options"] = $ini['theme']['options'];
1135 array_push($rv, $entry);
1143 function convert_timestamp($timestamp, $source_tz, $dest_tz) {
1146 $source_tz = new DateTimeZone($source_tz);
1147 } catch (Exception
$e) {
1148 $source_tz = new DateTimeZone('UTC');
1152 $dest_tz = new DateTimeZone($dest_tz);
1153 } catch (Exception
$e) {
1154 $dest_tz = new DateTimeZone('UTC');
1157 $dt = new DateTime(date('Y-m-d H:i:s', $timestamp), $source_tz);
1158 return $dt->format('U') +
$dest_tz->getOffset($dt);
1161 function make_local_datetime($link, $timestamp, $long, $owner_uid = false,
1162 $no_smart_dt = false) {
1164 if (!$owner_uid) $owner_uid = $_SESSION['uid'];
1165 if (!$timestamp) $timestamp = '1970-01-01 0:00';
1170 # We store date in UTC internally
1171 $dt = new DateTime($timestamp, $utc_tz);
1173 if ($tz_offset == -1) {
1175 $user_tz_string = get_pref($link, 'USER_TIMEZONE', $owner_uid);
1178 $user_tz = new DateTimeZone($user_tz_string);
1179 } catch (Exception
$e) {
1183 $tz_offset = $user_tz->getOffset($dt);
1186 $user_timestamp = $dt->format('U') +
$tz_offset;
1188 if (!$no_smart_dt) {
1189 return smart_date_time($link, $user_timestamp,
1190 $tz_offset, $owner_uid);
1193 $format = get_pref($link, 'LONG_DATE_FORMAT', $owner_uid);
1195 $format = get_pref($link, 'SHORT_DATE_FORMAT', $owner_uid);
1197 return date($format, $user_timestamp);
1201 function smart_date_time($link, $timestamp, $tz_offset = 0, $owner_uid = false) {
1202 if (!$owner_uid) $owner_uid = $_SESSION['uid'];
1204 if (date("Y.m.d", $timestamp) == date("Y.m.d", time() +
$tz_offset)) {
1205 return date("G:i", $timestamp);
1206 } else if (date("Y", $timestamp) == date("Y", time() +
$tz_offset)) {
1207 $format = get_pref($link, 'SHORT_DATE_FORMAT', $owner_uid);
1208 return date($format, $timestamp);
1210 $format = get_pref($link, 'LONG_DATE_FORMAT', $owner_uid);
1211 return date($format, $timestamp);
1215 function sql_bool_to_bool($s) {
1216 if ($s == "t" ||
$s == "1" ||
$s == "true") {
1223 function bool_to_sql_bool($s) {
1231 // Session caching removed due to causing wrong redirects to upgrade
1232 // script when get_schema_version() is called on an obsolete session
1233 // created on a previous schema version.
1234 function get_schema_version($link, $nocache = false) {
1235 global $schema_version;
1237 if (!$schema_version) {
1238 $result = db_query($link, "SELECT schema_version FROM ttrss_version");
1239 $version = db_fetch_result($result, 0, "schema_version");
1240 $schema_version = $version;
1243 return $schema_version;
1247 function sanity_check($link) {
1248 require_once 'errors.php';
1251 $schema_version = get_schema_version($link, true);
1253 if ($schema_version != SCHEMA_VERSION
) {
1257 if (DB_TYPE
== "mysql") {
1258 $result = db_query($link, "SELECT true", false);
1259 if (db_num_rows($result) != 1) {
1264 if (db_escape_string("testTEST") != "testTEST") {
1268 return array("code" => $error_code, "message" => $ERRORS[$error_code]);
1271 function file_is_locked($filename) {
1272 if (function_exists('flock')) {
1273 $fp = @fopen
(LOCK_DIRECTORY
. "/$filename", "r");
1275 if (flock($fp, LOCK_EX | LOCK_NB
)) {
1276 flock($fp, LOCK_UN
);
1286 return true; // consider the file always locked and skip the test
1289 function make_lockfile($filename) {
1290 $fp = fopen(LOCK_DIRECTORY
. "/$filename", "w");
1292 if (flock($fp, LOCK_EX | LOCK_NB
)) {
1293 if (function_exists('posix_getpid')) {
1294 fwrite($fp, posix_getpid() . "\n");
1302 function make_stampfile($filename) {
1303 $fp = fopen(LOCK_DIRECTORY
. "/$filename", "w");
1305 if (flock($fp, LOCK_EX | LOCK_NB
)) {
1306 fwrite($fp, time() . "\n");
1307 flock($fp, LOCK_UN
);
1315 function sql_random_function() {
1316 if (DB_TYPE
== "mysql") {
1323 function catchup_feed($link, $feed, $cat_view, $owner_uid = false, $max_id = false) {
1325 if (!$owner_uid) $owner_uid = $_SESSION['uid'];
1327 //if (preg_match("/^-?[0-9][0-9]*$/", $feed) != false) {
1329 $ref_check_qpart = ($max_id &&
1330 !get_pref($link, 'REVERSE_HEADLINES')) ?
"ref_id <= '$max_id'" : "true";
1332 if (is_numeric($feed)) {
1338 $cat_qpart = "cat_id = '$feed'";
1340 $cat_qpart = "cat_id IS NULL";
1343 $tmp_result = db_query($link, "SELECT id
1344 FROM ttrss_feeds WHERE $cat_qpart AND owner_uid = $owner_uid");
1346 while ($tmp_line = db_fetch_assoc($tmp_result)) {
1348 $tmp_feed = $tmp_line["id"];
1350 db_query($link, "UPDATE ttrss_user_entries
1351 SET unread = false,last_read = NOW()
1352 WHERE feed_id = '$tmp_feed'
1353 AND $ref_check_qpart
1354 AND owner_uid = $owner_uid");
1356 } else if ($feed == -2) {
1358 db_query($link, "UPDATE ttrss_user_entries
1359 SET unread = false,last_read = NOW() WHERE (SELECT COUNT(*)
1360 FROM ttrss_user_labels2 WHERE article_id = ref_id) > 0
1361 AND $ref_check_qpart
1362 AND unread = true AND owner_uid = $owner_uid");
1365 } else if ($feed > 0) {
1367 db_query($link, "UPDATE ttrss_user_entries
1368 SET unread = false,last_read = NOW()
1369 WHERE feed_id = '$feed'
1370 AND $ref_check_qpart
1371 AND owner_uid = $owner_uid");
1373 } else if ($feed < 0 && $feed > -10) { // special, like starred
1376 db_query($link, "UPDATE ttrss_user_entries
1377 SET unread = false,last_read = NOW()
1379 AND $ref_check_qpart
1380 AND owner_uid = $owner_uid");
1384 db_query($link, "UPDATE ttrss_user_entries
1385 SET unread = false,last_read = NOW()
1386 WHERE published = true
1387 AND $ref_check_qpart
1388 AND owner_uid = $owner_uid");
1393 $intl = get_pref($link, "FRESH_ARTICLE_MAX_AGE");
1395 if (DB_TYPE
== "pgsql") {
1396 $match_part = "updated > NOW() - INTERVAL '$intl hour' ";
1398 $match_part = "updated > DATE_SUB(NOW(),
1399 INTERVAL $intl HOUR) ";
1402 $result = db_query($link, "SELECT id FROM ttrss_entries,
1403 ttrss_user_entries WHERE $match_part AND
1405 ttrss_user_entries.ref_id = ttrss_entries.id AND
1406 owner_uid = $owner_uid");
1408 $affected_ids = array();
1410 while ($line = db_fetch_assoc($result)) {
1411 array_push($affected_ids, $line["id"]);
1414 catchupArticlesById($link, $affected_ids, 0);
1418 db_query($link, "UPDATE ttrss_user_entries
1419 SET unread = false,last_read = NOW()
1420 WHERE $ref_check_qpart AND owner_uid = $owner_uid");
1423 } else if ($feed < -10) { // label
1425 $label_id = -$feed - 11;
1427 db_query($link, "UPDATE ttrss_user_entries, ttrss_user_labels2
1428 SET unread = false, last_read = NOW()
1429 WHERE label_id = '$label_id' AND unread = true
1430 AND $ref_check_qpart
1431 AND owner_uid = '$owner_uid' AND ref_id = article_id");
1435 ccache_update($link, $feed, $owner_uid, $cat_view);
1438 db_query($link, "BEGIN");
1440 $tag_name = db_escape_string($feed);
1442 $result = db_query($link, "SELECT post_int_id FROM ttrss_tags
1443 WHERE tag_name = '$tag_name' AND owner_uid = $owner_uid");
1445 while ($line = db_fetch_assoc($result)) {
1446 db_query($link, "UPDATE ttrss_user_entries SET
1447 unread = false, last_read = NOW()
1448 WHERE $ref_check_qpart AND int_id = " . $line["post_int_id"]);
1450 db_query($link, "COMMIT");
1454 function getAllCounters($link, $omode = "flc", $active_feed = false) {
1456 if (!$omode) $omode = "flc";
1458 $data = getGlobalCounters($link);
1460 $data = array_merge($data, getVirtCounters($link));
1462 if (strchr($omode, "l")) $data = array_merge($data, getLabelCounters($link));
1463 if (strchr($omode, "f")) $data = array_merge($data, getFeedCounters($link, $active_feed));
1464 if (strchr($omode, "t")) $data = array_merge($data, getTagCounters($link));
1465 if (strchr($omode, "c")) $data = array_merge($data, getCategoryCounters($link));
1470 function getCategoryTitle($link, $cat_id) {
1472 if ($cat_id == -1) {
1473 return __("Special");
1474 } else if ($cat_id == -2) {
1475 return __("Labels");
1478 $result = db_query($link, "SELECT title FROM ttrss_feed_categories WHERE
1481 if (db_num_rows($result) == 1) {
1482 return db_fetch_result($result, 0, "title");
1484 return "Uncategorized";
1490 function getCategoryCounters($link) {
1493 /* Labels category */
1495 $cv = array("id" => -2, "kind" => "cat",
1496 "counter" => getCategoryUnread($link, -2));
1498 array_push($ret_arr, $cv);
1500 $result = db_query($link, "SELECT id AS cat_id, value AS unread
1501 FROM ttrss_feed_categories, ttrss_cat_counters_cache
1502 WHERE ttrss_cat_counters_cache.feed_id = id AND
1503 ttrss_feed_categories.owner_uid = " . $_SESSION["uid"]);
1505 while ($line = db_fetch_assoc($result)) {
1506 $line["cat_id"] = (int) $line["cat_id"];
1508 $cv = array("id" => $line["cat_id"], "kind" => "cat",
1509 "counter" => $line["unread"]);
1511 array_push($ret_arr, $cv);
1514 /* Special case: NULL category doesn't actually exist in the DB */
1516 $cv = array("id" => 0, "kind" => "cat",
1517 "counter" => ccache_find($link, 0, $_SESSION["uid"], true));
1519 array_push($ret_arr, $cv);
1524 function getCategoryUnread($link, $cat, $owner_uid = false) {
1526 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
1531 $cat_query = "cat_id = '$cat'";
1533 $cat_query = "cat_id IS NULL";
1536 $result = db_query($link, "SELECT id FROM ttrss_feeds WHERE $cat_query
1537 AND owner_uid = " . $owner_uid);
1539 $cat_feeds = array();
1540 while ($line = db_fetch_assoc($result)) {
1541 array_push($cat_feeds, "feed_id = " . $line["id"]);
1544 if (count($cat_feeds) == 0) return 0;
1546 $match_part = implode(" OR ", $cat_feeds);
1548 $result = db_query($link, "SELECT COUNT(int_id) AS unread
1549 FROM ttrss_user_entries
1550 WHERE unread = true AND ($match_part)
1551 AND owner_uid = " . $owner_uid);
1555 # this needs to be rewritten
1556 while ($line = db_fetch_assoc($result)) {
1557 $unread +
= $line["unread"];
1561 } else if ($cat == -1) {
1562 return getFeedUnread($link, -1) +
getFeedUnread($link, -2) +
getFeedUnread($link, -3) +
getFeedUnread($link, 0);
1563 } else if ($cat == -2) {
1565 $result = db_query($link, "
1566 SELECT COUNT(unread) AS unread FROM
1567 ttrss_user_entries, ttrss_user_labels2
1568 WHERE article_id = ref_id AND unread = true
1569 AND ttrss_user_entries.owner_uid = '$owner_uid'");
1571 $unread = db_fetch_result($result, 0, "unread");
1578 function getFeedUnread($link, $feed, $is_cat = false) {
1579 return getFeedArticles($link, $feed, $is_cat, true, $_SESSION["uid"]);
1582 function getLabelUnread($link, $label_id, $owner_uid = false) {
1583 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
1585 $result = db_query($link, "SELECT COUNT(ref_id) AS unread FROM ttrss_user_entries, ttrss_user_labels2
1586 WHERE owner_uid = '$owner_uid' AND unread = true AND label_id = '$label_id' AND article_id = ref_id");
1588 if (db_num_rows($result) != 0) {
1589 return db_fetch_result($result, 0, "unread");
1595 function getFeedArticles($link, $feed, $is_cat = false, $unread_only = false,
1596 $owner_uid = false) {
1598 $n_feed = (int) $feed;
1599 $need_entries = false;
1601 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
1604 $unread_qpart = "unread = true";
1606 $unread_qpart = "true";
1610 return getCategoryUnread($link, $n_feed, $owner_uid);
1611 } if ($feed != "0" && $n_feed == 0) {
1613 $feed = db_escape_string($feed);
1615 $result = db_query($link, "SELECT SUM((SELECT COUNT(int_id)
1616 FROM ttrss_user_entries,ttrss_entries WHERE int_id = post_int_id
1617 AND ref_id = id AND $unread_qpart)) AS count FROM ttrss_tags
1618 WHERE owner_uid = $owner_uid AND tag_name = '$feed'");
1619 return db_fetch_result($result, 0, "count");
1621 } else if ($n_feed == -1) {
1622 $match_part = "marked = true";
1623 } else if ($n_feed == -2) {
1624 $match_part = "published = true";
1625 } else if ($n_feed == -3) {
1626 $match_part = "unread = true AND score >= 0";
1628 $intl = get_pref($link, "FRESH_ARTICLE_MAX_AGE", $owner_uid);
1630 if (DB_TYPE
== "pgsql") {
1631 $match_part .= " AND updated > NOW() - INTERVAL '$intl hour' ";
1633 $match_part .= " AND updated > DATE_SUB(NOW(), INTERVAL $intl HOUR) ";
1636 $need_entries = true;
1638 } else if ($n_feed == -4) {
1639 $match_part = "true";
1640 } else if ($n_feed >= 0) {
1643 $match_part = "feed_id = '$n_feed'";
1645 $match_part = "feed_id IS NULL";
1648 } else if ($feed < -10) {
1650 $label_id = -$feed - 11;
1652 return getLabelUnread($link, $label_id, $owner_uid);
1658 if ($need_entries) {
1659 $from_qpart = "ttrss_user_entries,ttrss_entries";
1660 $from_where = "ttrss_entries.id = ttrss_user_entries.ref_id AND";
1662 $from_qpart = "ttrss_user_entries";
1665 $query = "SELECT count(int_id) AS unread
1666 FROM $from_qpart WHERE
1667 $unread_qpart AND $from_where ($match_part) AND ttrss_user_entries.owner_uid = $owner_uid";
1669 //echo "[$feed/$query]\n";
1671 $result = db_query($link, $query);
1675 $result = db_query($link, "SELECT COUNT(post_int_id) AS unread
1676 FROM ttrss_tags,ttrss_user_entries,ttrss_entries
1677 WHERE tag_name = '$feed' AND post_int_id = int_id AND ref_id = ttrss_entries.id
1678 AND $unread_qpart AND ttrss_tags.owner_uid = " . $owner_uid);
1681 $unread = db_fetch_result($result, 0, "unread");
1686 function getGlobalUnread($link, $user_id = false) {
1689 $user_id = $_SESSION["uid"];
1692 $result = db_query($link, "SELECT SUM(value) AS c_id FROM ttrss_counters_cache
1693 WHERE owner_uid = '$user_id' AND feed_id > 0");
1695 $c_id = db_fetch_result($result, 0, "c_id");
1700 function getGlobalCounters($link, $global_unread = -1) {
1703 if ($global_unread == -1) {
1704 $global_unread = getGlobalUnread($link);
1707 $cv = array("id" => "global-unread",
1708 "counter" => $global_unread);
1710 array_push($ret_arr, $cv);
1712 $result = db_query($link, "SELECT COUNT(id) AS fn FROM
1713 ttrss_feeds WHERE owner_uid = " . $_SESSION["uid"]);
1715 $subscribed_feeds = db_fetch_result($result, 0, "fn");
1717 $cv = array("id" => "subscribed-feeds",
1718 "counter" => $subscribed_feeds);
1720 array_push($ret_arr, $cv);
1725 function getTagCounters($link) {
1729 $result = db_query($link, "SELECT tag_name,SUM((SELECT COUNT(int_id)
1730 FROM ttrss_user_entries,ttrss_entries WHERE int_id = post_int_id
1731 AND ref_id = id AND unread = true)) AS count FROM ttrss_tags
1732 WHERE owner_uid = ".$_SESSION['uid']." GROUP BY tag_name
1733 ORDER BY count DESC LIMIT 55");
1737 while ($line = db_fetch_assoc($result)) {
1738 $tags[$line["tag_name"]] +
= $line["count"];
1741 foreach (array_keys($tags) as $tag) {
1742 $unread = $tags[$tag];
1743 $tag = htmlspecialchars($tag);
1745 $cv = array("id" => $tag,
1747 "counter" => $unread);
1749 array_push($ret_arr, $cv);
1755 function getVirtCounters($link) {
1759 for ($i = 0; $i >= -4; $i--) {
1761 $count = getFeedUnread($link, $i);
1763 $cv = array("id" => $i,
1764 "counter" => $count);
1766 // if (get_pref($link, 'EXTENDED_FEEDLIST'))
1767 // $cv["xmsg"] = getFeedArticles($link, $i)." ".__("total");
1769 array_push($ret_arr, $cv);
1775 function getLabelCounters($link, $descriptions = false) {
1779 $owner_uid = $_SESSION["uid"];
1781 $result = db_query($link, "SELECT id, caption FROM ttrss_labels2
1782 WHERE owner_uid = '$owner_uid'");
1784 while ($line = db_fetch_assoc($result)) {
1786 $id = -$line["id"] - 11;
1788 $label_name = $line["caption"];
1789 $count = getFeedUnread($link, $id);
1791 $cv = array("id" => $id,
1792 "counter" => $count);
1795 $cv["description"] = $label_name;
1797 // if (get_pref($link, 'EXTENDED_FEEDLIST'))
1798 // $cv["xmsg"] = getFeedArticles($link, $id)." ".__("total");
1800 array_push($ret_arr, $cv);
1806 function getFeedCounters($link, $active_feed = false) {
1810 $query = "SELECT ttrss_feeds.id,
1812 ".SUBSTRING_FOR_DATE
."(ttrss_feeds.last_updated,1,19) AS last_updated,
1813 last_error, value AS count
1814 FROM ttrss_feeds, ttrss_counters_cache
1815 WHERE ttrss_feeds.owner_uid = ".$_SESSION["uid"]."
1816 AND ttrss_counters_cache.feed_id = id";
1818 $result = db_query($link, $query);
1819 $fctrs_modified = false;
1821 while ($line = db_fetch_assoc($result)) {
1824 $count = $line["count"];
1825 $last_error = htmlspecialchars($line["last_error"]);
1827 $last_updated = make_local_datetime($link, $line['last_updated'], false);
1829 $has_img = feed_has_icon($id);
1831 if (date('Y') - date('Y', strtotime($line['last_updated'])) > 2)
1834 $cv = array("id" => $id,
1835 "updated" => $last_updated,
1836 "counter" => $count,
1837 "has_img" => (int) $has_img);
1840 $cv["error"] = $last_error;
1842 // if (get_pref($link, 'EXTENDED_FEEDLIST'))
1843 // $cv["xmsg"] = getFeedArticles($link, $id)." ".__("total");
1845 if ($active_feed && $id == $active_feed)
1846 $cv["title"] = truncate_string($line["title"], 30);
1848 array_push($ret_arr, $cv);
1855 function get_pgsql_version($link) {
1856 $result = db_query($link, "SELECT version() AS version");
1857 $version = explode(" ", db_fetch_result($result, 0, "version"));
1862 * @return integer Status code:
1863 * 0 - OK, Feed already exists
1864 * 1 - OK, Feed added
1866 * 3 - URL content is HTML, no feeds available
1867 * 4 - URL content is HTML which contains multiple feeds.
1868 * Here you should call extractfeedurls in rpc-backend
1869 * to get all possible feeds.
1870 * 5 - Couldn't download the URL content.
1872 function subscribe_to_feed($link, $url, $cat_id = 0,
1873 $auth_login = '', $auth_pass = '', $need_auth = false) {
1875 require_once "include/rssfuncs.php";
1877 $url = fix_url($url);
1879 if (!$url ||
!validate_feed_url($url)) return 2;
1883 $result = db_query($link, "SELECT twitter_oauth FROM ttrss_users
1884 WHERE id = ".$_SESSION['uid']);
1886 $has_oauth = db_fetch_result($result, 0, 'twitter_oauth');
1888 if (!$need_auth ||
!$has_oauth ||
strpos($url, '://api.twitter.com') === false) {
1889 if (!fetch_file_contents($url, false, $auth_login, $auth_pass)) return 5;
1891 if (url_is_html($url, $auth_login, $auth_pass)) {
1892 $feedUrls = get_feeds_from_html($url, $auth_login, $auth_pass);
1893 if (count($feedUrls) == 0) {
1895 } else if (count($feedUrls) > 1) {
1898 //use feed url as new URL
1899 $url = key($feedUrls);
1903 if (!fetch_twitter_rss($link, $url, $_SESSION['uid']))
1908 if ($cat_id == "0" ||
!$cat_id) {
1909 $cat_qpart = "NULL";
1911 $cat_qpart = "'$cat_id'";
1914 $result = db_query($link,
1915 "SELECT id FROM ttrss_feeds
1916 WHERE feed_url = '$url' AND owner_uid = ".$_SESSION["uid"]);
1918 if (db_num_rows($result) == 0) {
1919 $result = db_query($link,
1920 "INSERT INTO ttrss_feeds
1921 (owner_uid,feed_url,title,cat_id, auth_login,auth_pass,update_method)
1922 VALUES ('".$_SESSION["uid"]."', '$url',
1923 '[Unknown]', $cat_qpart, '$auth_login', '$auth_pass', '$update_method')");
1925 $result = db_query($link,
1926 "SELECT id FROM ttrss_feeds WHERE feed_url = '$url'
1927 AND owner_uid = " . $_SESSION["uid"]);
1929 $feed_id = db_fetch_result($result, 0, "id");
1932 update_rss_feed($link, $feed_id, true);
1941 function print_feed_select($link, $id, $default_id = "",
1942 $attributes = "", $include_all_feeds = true) {
1944 print "<select id=\"$id\" name=\"$id\" $attributes>";
1945 if ($include_all_feeds) {
1946 print "<option value=\"0\">".__('All feeds')."</option>";
1949 $result = db_query($link, "SELECT id,title FROM ttrss_feeds
1950 WHERE owner_uid = ".$_SESSION["uid"]." ORDER BY title");
1952 if (db_num_rows($result) > 0 && $include_all_feeds) {
1953 print "<option disabled>--------</option>";
1956 while ($line = db_fetch_assoc($result)) {
1957 if ($line["id"] == $default_id) {
1958 $is_selected = "selected=\"1\"";
1963 $title = truncate_string(htmlspecialchars($line["title"]), 40);
1965 printf("<option $is_selected value='%d'>%s</option>",
1966 $line["id"], $title);
1972 function print_feed_cat_select($link, $id, $default_id = "",
1973 $attributes = "", $include_all_cats = true) {
1975 print "<select id=\"$id\" name=\"$id\" default=\"$default_id\" onchange=\"catSelectOnChange(this)\" $attributes>";
1977 if ($include_all_cats) {
1978 print "<option value=\"0\">".__('Uncategorized')."</option>";
1981 $result = db_query($link, "SELECT id,title FROM ttrss_feed_categories
1982 WHERE owner_uid = ".$_SESSION["uid"]." ORDER BY title");
1984 if (db_num_rows($result) > 0 && $include_all_cats) {
1985 print "<option disabled=\"1\">--------</option>";
1988 while ($line = db_fetch_assoc($result)) {
1989 if ($line["id"] == $default_id) {
1990 $is_selected = "selected=\"1\"";
1996 printf("<option $is_selected value='%d'>%s</option>",
1997 $line["id"], htmlspecialchars($line["title"]));
2000 # print "<option value=\"ADD_CAT\">" .__("Add category...") . "</option>";
2005 function checkbox_to_sql_bool($val) {
2006 return ($val == "on") ?
"true" : "false";
2009 function getFeedCatTitle($link, $id) {
2011 return __("Special");
2012 } else if ($id < -10) {
2013 return __("Labels");
2014 } else if ($id > 0) {
2015 $result = db_query($link, "SELECT ttrss_feed_categories.title
2016 FROM ttrss_feeds, ttrss_feed_categories WHERE ttrss_feeds.id = '$id' AND
2017 cat_id = ttrss_feed_categories.id");
2018 if (db_num_rows($result) == 1) {
2019 return db_fetch_result($result, 0, "title");
2021 return __("Uncategorized");
2024 return "getFeedCatTitle($id) failed";
2029 function getFeedIcon($id) {
2032 return "images/archive.png";
2035 return "images/mark_set.png";
2038 return "images/pub_set.png";
2041 return "images/fresh.png";
2044 return "images/tag.png";
2048 return "images/label.png";
2050 if (file_exists(ICONS_DIR
. "/$id.ico"))
2051 return ICONS_URL
. "/$id.ico";
2057 function getFeedTitle($link, $id) {
2059 return __("Starred articles");
2060 } else if ($id == -2) {
2061 return __("Published articles");
2062 } else if ($id == -3) {
2063 return __("Fresh articles");
2064 } else if ($id == -4) {
2065 return __("All articles");
2066 } else if ($id === 0 ||
$id === "0") {
2067 return __("Archived articles");
2068 } else if ($id < -10) {
2069 $label_id = -$id - 11;
2070 $result = db_query($link, "SELECT caption FROM ttrss_labels2 WHERE id = '$label_id'");
2071 if (db_num_rows($result) == 1) {
2072 return db_fetch_result($result, 0, "caption");
2074 return "Unknown label ($label_id)";
2077 } else if (is_numeric($id) && $id > 0) {
2078 $result = db_query($link, "SELECT title FROM ttrss_feeds WHERE id = '$id'");
2079 if (db_num_rows($result) == 1) {
2080 return db_fetch_result($result, 0, "title");
2082 return "Unknown feed ($id)";
2089 function make_init_params($link) {
2092 $params["theme"] = get_user_theme($link);
2093 $params["theme_options"] = get_user_theme_options($link);
2095 $params["sign_progress"] = theme_image($link, "images/indicator_white.gif");
2096 $params["sign_progress_tiny"] = theme_image($link, "images/indicator_tiny.gif");
2097 $params["sign_excl"] = theme_image($link, "images/sign_excl.png");
2098 $params["sign_info"] = theme_image($link, "images/sign_info.png");
2100 foreach (array("ON_CATCHUP_SHOW_NEXT_FEED", "HIDE_READ_FEEDS",
2101 "ENABLE_FEED_CATS", "FEEDS_SORT_BY_UNREAD", "CONFIRM_FEED_CATCHUP",
2102 "CDM_AUTO_CATCHUP", "FRESH_ARTICLE_MAX_AGE", "DEFAULT_ARTICLE_LIMIT",
2103 "HIDE_READ_SHOWS_SPECIAL", "COMBINED_DISPLAY_MODE") as $param) {
2105 $params[strtolower($param)] = (int) get_pref($link, $param);
2108 $params["icons_url"] = ICONS_URL
;
2109 $params["cookie_lifetime"] = SESSION_COOKIE_LIFETIME
;
2110 $params["default_view_mode"] = get_pref($link, "_DEFAULT_VIEW_MODE");
2111 $params["default_view_limit"] = (int) get_pref($link, "_DEFAULT_VIEW_LIMIT");
2112 $params["default_view_order_by"] = get_pref($link, "_DEFAULT_VIEW_ORDER_BY");
2113 $params["bw_limit"] = (int) $_SESSION["bw_limit"];
2115 $result = db_query($link, "SELECT MAX(id) AS mid, COUNT(*) AS nf FROM
2116 ttrss_feeds WHERE owner_uid = " . $_SESSION["uid"]);
2118 $max_feed_id = db_fetch_result($result, 0, "mid");
2119 $num_feeds = db_fetch_result($result, 0, "nf");
2121 $params["max_feed_id"] = (int) $max_feed_id;
2122 $params["num_feeds"] = (int) $num_feeds;
2124 $params["collapsed_feedlist"] = (int) get_pref($link, "_COLLAPSED_FEEDLIST");
2126 $params["csrf_token"] = $_SESSION["csrf_token"];
2131 function make_runtime_info($link) {
2134 $result = db_query($link, "SELECT MAX(id) AS mid, COUNT(*) AS nf FROM
2135 ttrss_feeds WHERE owner_uid = " . $_SESSION["uid"]);
2137 $max_feed_id = db_fetch_result($result, 0, "mid");
2138 $num_feeds = db_fetch_result($result, 0, "nf");
2140 $data["max_feed_id"] = (int) $max_feed_id;
2141 $data["num_feeds"] = (int) $num_feeds;
2143 $data['last_article_id'] = getLastArticleId($link);
2144 $data['cdm_expanded'] = get_pref($link, 'CDM_EXPANDED');
2146 if (file_exists(LOCK_DIRECTORY
. "/update_daemon.lock")) {
2148 $data['daemon_is_running'] = (int) file_is_locked("update_daemon.lock");
2150 if (time() - $_SESSION["daemon_stamp_check"] > 30) {
2152 $stamp = (int) @file_get_contents
(LOCK_DIRECTORY
. "/update_daemon.stamp");
2155 $stamp_delta = time() - $stamp;
2157 if ($stamp_delta > 1800) {
2161 $_SESSION["daemon_stamp_check"] = time();
2164 $data['daemon_stamp_ok'] = $stamp_check;
2166 $stamp_fmt = date("Y.m.d, G:i", $stamp);
2168 $data['daemon_stamp'] = $stamp_fmt;
2173 if ($_SESSION["last_version_check"] +
86400 +
rand(-1000, 1000) < time()) {
2174 $new_version_details = @check_for_update
($link);
2176 $data['new_version_available'] = (int) ($new_version_details != false);
2178 $_SESSION["last_version_check"] = time();
2184 function search_to_sql($link, $search, $match_on) {
2186 $search_query_part = "";
2188 $keywords = explode(" ", $search);
2189 $query_keywords = array();
2191 foreach ($keywords as $k) {
2192 if (strpos($k, "-") === 0) {
2199 $commandpair = explode(":", mb_strtolower($k), 2);
2201 if ($commandpair[0] == "note" && $commandpair[1]) {
2203 if ($commandpair[1] == "true")
2204 array_push($query_keywords, "($not (note IS NOT NULL AND note != ''))");
2206 array_push($query_keywords, "($not (note IS NULL OR note = ''))");
2208 } else if ($commandpair[0] == "star" && $commandpair[1]) {
2210 if ($commandpair[1] == "true")
2211 array_push($query_keywords, "($not (marked = true))");
2213 array_push($query_keywords, "($not (marked = false))");
2215 } else if ($commandpair[0] == "pub" && $commandpair[1]) {
2217 if ($commandpair[1] == "true")
2218 array_push($query_keywords, "($not (published = true))");
2220 array_push($query_keywords, "($not (published = false))");
2222 } else if (strpos($k, "@") === 0) {
2224 $user_tz_string = get_pref($link, 'USER_TIMEZONE', $_SESSION['uid']);
2225 $orig_ts = strtotime(substr($k, 1));
2226 $k = date("Y-m-d", convert_timestamp($orig_ts, $user_tz_string, 'UTC'));
2228 //$k = date("Y-m-d", strtotime(substr($k, 1)));
2230 array_push($query_keywords, "(".SUBSTRING_FOR_DATE
."(updated,1,LENGTH('$k')) $not = '$k')");
2231 } else if ($match_on == "both") {
2232 array_push($query_keywords, "(UPPER(ttrss_entries.title) $not LIKE UPPER('%$k%')
2233 OR UPPER(ttrss_entries.content) $not LIKE UPPER('%$k%'))");
2234 } else if ($match_on == "title") {
2235 array_push($query_keywords, "(UPPER(ttrss_entries.title) $not LIKE UPPER('%$k%'))");
2236 } else if ($match_on == "content") {
2237 array_push($query_keywords, "(UPPER(ttrss_entries.content) $not LIKE UPPER('%$k%'))");
2241 $search_query_part = implode("AND", $query_keywords);
2243 return $search_query_part;
2247 function queryFeedHeadlines($link, $feed, $limit, $view_mode, $cat_view, $search, $search_mode, $match_on, $override_order = false, $offset = 0, $owner_uid = 0, $filter = false, $since_id = 0) {
2249 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
2251 $ext_tables_part = "";
2255 if (SPHINX_ENABLED
) {
2256 $ids = join(",", @sphinx_search
($search, 0, 500));
2259 $search_query_part = "ref_id IN ($ids) AND ";
2261 $search_query_part = "ref_id = -1 AND ";
2264 $search_query_part = search_to_sql($link, $search, $match_on);
2265 $search_query_part .= " AND ";
2269 $search_query_part = "";
2273 $filter_query_part = filter_to_sql($filter);
2275 $filter_query_part = "";
2279 $since_id_part = "ttrss_entries.id > $since_id AND ";
2281 $since_id_part = "";
2284 $view_query_part = "";
2286 if ($view_mode == "adaptive" ||
$view_query_part == "noscores") {
2288 $view_query_part = " ";
2289 } else if ($feed != -1) {
2290 $unread = getFeedUnread($link, $feed, $cat_view);
2292 $view_query_part = " unread = true AND ";
2297 if ($view_mode == "marked") {
2298 $view_query_part = " marked = true AND ";
2301 if ($view_mode == "published") {
2302 $view_query_part = " published = true AND ";
2305 if ($view_mode == "unread") {
2306 $view_query_part = " unread = true AND ";
2309 if ($view_mode == "updated") {
2310 $view_query_part = " (last_read is null and unread = false) AND ";
2314 $limit_query_part = "LIMIT " . $limit;
2317 $vfeed_query_part = "";
2319 // override query strategy and enable feed display when searching globally
2320 if ($search && $search_mode == "all_feeds") {
2321 $query_strategy_part = "ttrss_entries.id > 0";
2322 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
2324 } else if (preg_match("/^-?[0-9][0-9]*$/", $feed) == false) {
2325 $query_strategy_part = "ttrss_entries.id > 0";
2326 $vfeed_query_part = "(SELECT title FROM ttrss_feeds WHERE
2327 id = feed_id) as feed_title,";
2328 } else if ($feed > 0 && $search && $search_mode == "this_cat") {
2330 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
2332 $tmp_result = false;
2335 $tmp_result = db_query($link, "SELECT id
2336 FROM ttrss_feeds WHERE cat_id = '$feed'");
2338 $tmp_result = db_query($link, "SELECT id
2339 FROM ttrss_feeds WHERE cat_id = (SELECT cat_id FROM ttrss_feeds
2340 WHERE id = '$feed') AND id != '$feed'");
2343 $cat_siblings = array();
2345 if (db_num_rows($tmp_result) > 0) {
2346 while ($p = db_fetch_assoc($tmp_result)) {
2347 array_push($cat_siblings, "feed_id = " . $p["id"]);
2350 $query_strategy_part = sprintf("(feed_id = %d OR %s)",
2351 $feed, implode(" OR ", $cat_siblings));
2354 $query_strategy_part = "ttrss_entries.id > 0";
2357 } else if ($feed > 0) {
2362 $query_strategy_part = "cat_id = '$feed'";
2364 $query_strategy_part = "cat_id IS NULL";
2367 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
2370 $query_strategy_part = "feed_id = '$feed'";
2372 } else if ($feed == 0 && !$cat_view) { // archive virtual feed
2373 $query_strategy_part = "feed_id IS NULL";
2374 } else if ($feed == 0 && $cat_view) { // uncategorized
2375 $query_strategy_part = "cat_id IS NULL AND feed_id IS NOT NULL";
2376 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
2377 } else if ($feed == -1) { // starred virtual feed
2378 $query_strategy_part = "marked = true";
2379 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
2380 } else if ($feed == -2) { // published virtual feed OR labels category
2383 $query_strategy_part = "published = true";
2384 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
2386 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
2388 $ext_tables_part = ",ttrss_labels2,ttrss_user_labels2";
2390 $query_strategy_part = "ttrss_labels2.id = ttrss_user_labels2.label_id AND
2391 ttrss_user_labels2.article_id = ref_id";
2395 } else if ($feed == -3) { // fresh virtual feed
2396 $query_strategy_part = "unread = true AND score >= 0";
2398 $intl = get_pref($link, "FRESH_ARTICLE_MAX_AGE", $owner_uid);
2400 if (DB_TYPE
== "pgsql") {
2401 $query_strategy_part .= " AND updated > NOW() - INTERVAL '$intl hour' ";
2403 $query_strategy_part .= " AND updated > DATE_SUB(NOW(), INTERVAL $intl HOUR) ";
2406 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
2407 } else if ($feed == -4) { // all articles virtual feed
2408 $query_strategy_part = "true";
2409 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
2410 } else if ($feed <= -10) { // labels
2411 $label_id = -$feed - 11;
2413 $query_strategy_part = "label_id = '$label_id' AND
2414 ttrss_labels2.id = ttrss_user_labels2.label_id AND
2415 ttrss_user_labels2.article_id = ref_id";
2417 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
2418 $ext_tables_part = ",ttrss_labels2,ttrss_user_labels2";
2421 $query_strategy_part = "id > 0"; // dumb
2424 if (get_pref($link, "SORT_HEADLINES_BY_FEED_DATE", $owner_uid)) {
2425 $date_sort_field = "updated";
2427 $date_sort_field = "date_entered";
2430 if (get_pref($link, 'REVERSE_HEADLINES', $owner_uid)) {
2431 $order_by = "$date_sort_field";
2433 $order_by = "$date_sort_field DESC";
2436 if ($view_mode != "noscores") {
2437 $order_by = "score DESC, $order_by";
2440 if ($override_order) {
2441 $order_by = $override_order;
2447 $feed_title = "Search results";
2450 $feed_title = getCategoryTitle($link, $feed);
2452 if (is_numeric($feed) && $feed > 0) {
2453 $result = db_query($link, "SELECT title,site_url,last_error
2454 FROM ttrss_feeds WHERE id = '$feed' AND owner_uid = $owner_uid");
2456 $feed_title = db_fetch_result($result, 0, "title");
2457 $feed_site_url = db_fetch_result($result, 0, "site_url");
2458 $last_error = db_fetch_result($result, 0, "last_error");
2460 $feed_title = getFeedTitle($link, $feed);
2465 $content_query_part = "content as content_preview,";
2467 if (preg_match("/^-?[0-9][0-9]*$/", $feed) != false) {
2470 $feed_kind = "Feeds";
2472 $feed_kind = "Labels";
2475 if ($limit_query_part) {
2476 $offset_query_part = "OFFSET $offset";
2479 if ($vfeed_query_part && get_pref($link, 'VFEED_GROUP_BY_FEED', $owner_uid)) {
2480 if (!$override_order) {
2481 $order_by = "ttrss_feeds.title, $order_by";
2486 $from_qpart = "ttrss_entries,ttrss_user_entries,ttrss_feeds$ext_tables_part";
2487 $feed_check_qpart = "ttrss_user_entries.feed_id = ttrss_feeds.id AND";
2490 $from_qpart = "ttrss_entries,ttrss_user_entries$ext_tables_part
2491 LEFT JOIN ttrss_feeds ON (feed_id = ttrss_feeds.id)";
2494 $query = "SELECT DISTINCT
2497 ttrss_entries.id,ttrss_entries.title,
2501 always_display_enclosures,
2507 unread,feed_id,marked,published,link,last_read,orig_feed_id,
2508 ".SUBSTRING_FOR_DATE
."(last_read,1,19) as last_read_noms,
2511 ".SUBSTRING_FOR_DATE
."(updated,1,19) as updated_noms,
2517 ttrss_user_entries.ref_id = ttrss_entries.id AND
2518 ttrss_user_entries.owner_uid = '$owner_uid' AND
2523 $query_strategy_part ORDER BY $order_by
2524 $limit_query_part $offset_query_part";
2526 if ($_REQUEST["debug"]) print $query;
2528 $result = db_query($link, $query);
2533 $select_qpart = "SELECT DISTINCT " .
2537 "ttrss_entries.id as id," .
2550 SUBSTRING_FOR_DATE
. "(last_read,1,19) as last_read_noms," .
2553 $content_query_part .
2554 SUBSTRING_FOR_DATE
. "(updated,1,19) as updated_noms," .
2557 $feed_kind = "Tags";
2558 $all_tags = explode(",", $feed);
2559 if ($search_mode == 'any') {
2560 $tag_sql = "tag_name in (" . implode(", ", array_map("db_quote", $all_tags)) . ")";
2561 $from_qpart = " FROM ttrss_entries,ttrss_user_entries,ttrss_tags ";
2562 $where_qpart = " WHERE " .
2563 "ref_id = ttrss_entries.id AND " .
2564 "ttrss_user_entries.owner_uid = $owner_uid AND " .
2565 "post_int_id = int_id AND $tag_sql AND " .
2567 $search_query_part .
2568 $query_strategy_part . " ORDER BY $order_by " .
2573 $sub_selects = array();
2574 $sub_ands = array();
2575 foreach ($all_tags as $term) {
2576 array_push($sub_selects, "(SELECT post_int_id from ttrss_tags WHERE tag_name = " . db_quote($term) . " AND owner_uid = $owner_uid) as A$i");
2583 array_push($sub_ands, "A$x.post_int_id = A$y.post_int_id");
2588 array_push($sub_ands, "A1.post_int_id = ttrss_user_entries.int_id and ttrss_user_entries.owner_uid = $owner_uid");
2589 array_push($sub_ands, "ttrss_user_entries.ref_id = ttrss_entries.id");
2590 $from_qpart = " FROM " . implode(", ", $sub_selects) . ", ttrss_user_entries, ttrss_entries";
2591 $where_qpart = " WHERE " . implode(" AND ", $sub_ands);
2593 // error_log("TAG SQL: " . $tag_sql);
2594 // $tag_sql = "tag_name = '$feed'"; DEFAULT way
2596 // error_log("[". $select_qpart . "][" . $from_qpart . "][" .$where_qpart . "]");
2597 $result = db_query($link, $select_qpart . $from_qpart . $where_qpart);
2600 return array($result, $feed_title, $feed_site_url, $last_error);
2604 function sanitize($link, $str, $force_strip_tags = false, $owner = false, $site_url = false) {
2607 if (!$owner) $owner = $_SESSION["uid"];
2609 $res = trim($str); if (!$res) return '';
2611 // create global Purifier object if needed
2613 require_once 'lib/htmlpurifier/library/HTMLPurifier.auto.php';
2615 $config = HTMLPurifier_Config
::createDefault();
2617 $allowed = "p,a[href],i,em,b,strong,code,pre,blockquote,br,img[src|alt|title|align|hspace],ul,ol,li,h1,h2,h3,h4,s,object[classid|type|id|name|width|height|codebase],param[name|value],table,tr,td,span[class]";
2619 $config->set('HTML.SafeObject', true);
2620 @$config->set('HTML', 'Allowed', $allowed);
2621 $config->set('Output.FlashCompat', true);
2622 $config->set('Attr.EnableID', true);
2623 if (!defined('MOBILE_VERSION')) {
2624 @$config->set('Cache', 'SerializerPath', CACHE_DIR
. "/htmlpurifier");
2626 @$config->set('Cache', 'SerializerPath', "../" . CACHE_DIR
. "/htmlpurifier");
2629 $config->set('Filter.YouTube', true);
2631 $purifier = new HTMLPurifier($config);
2634 $res = $purifier->purify($res);
2636 if (get_pref($link, "STRIP_IMAGES", $owner)) {
2637 $res = preg_replace('/<img[^>]+>/is', '', $res);
2640 if (strpos($res, "href=") === false)
2641 $res = rewrite_urls($res);
2643 $charset_hack = '<head>
2644 <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
2647 $res = trim($res); if (!$res) return '';
2649 libxml_use_internal_errors(true);
2651 $doc = new DOMDocument();
2652 $doc->loadHTML($charset_hack . $res);
2653 $xpath = new DOMXPath($doc);
2655 $entries = $xpath->query('(//a[@href]|//img[@src])');
2658 foreach ($entries as $entry) {
2662 if ($entry->hasAttribute('href'))
2663 $entry->setAttribute('href',
2664 rewrite_relative_url($site_url, $entry->getAttribute('href')));
2666 if ($entry->hasAttribute('src'))
2667 if (preg_match('/^image.php\?i=[a-z0-9]+$/', $entry->getAttribute('src')) == 0)
2668 $entry->setAttribute('src',
2669 rewrite_relative_url($site_url, $entry->getAttribute('src')));
2672 if (strtolower($entry->nodeName
) == "a") {
2673 $entry->setAttribute("target", "_blank");
2676 if (strtolower($entry->nodeName
) == "img" && !$br_inserted) {
2677 $br = $doc->createElement("br");
2679 if ($entry->parentNode
->nextSibling
) {
2680 $entry->parentNode
->insertBefore($br, $entry->nextSibling
);
2687 $node = $doc->getElementsByTagName('body')->item(0);
2689 return $doc->saveXML($node, LIBXML_NOEMPTYTAG
);
2693 * Send by mail a digest of last articles.
2695 * @param mixed $link The database connection.
2696 * @param integer $limit The maximum number of articles by digest.
2697 * @return boolean Return false if digests are not enabled.
2699 function send_headlines_digests($link, $debug = false) {
2701 require_once 'lib/phpmailer/class.phpmailer.php';
2703 $user_limit = 15; // amount of users to process (e.g. emails to send out)
2704 $limit = 1000; // maximum amount of headlines to include
2706 if ($debug) _debug("Sending digests, batch of max $user_limit users, headline limit = $limit");
2708 if (DB_TYPE
== "pgsql") {
2709 $interval_query = "last_digest_sent < NOW() - INTERVAL '1 days'";
2710 } else if (DB_TYPE
== "mysql") {
2711 $interval_query = "last_digest_sent < DATE_SUB(NOW(), INTERVAL 1 DAY)";
2714 $result = db_query($link, "SELECT id,email FROM ttrss_users
2715 WHERE email != '' AND (last_digest_sent IS NULL OR $interval_query)");
2717 while ($line = db_fetch_assoc($result)) {
2719 if (get_pref($link, 'DIGEST_ENABLE', $line['id'], false)) {
2720 $preferred_ts = strtotime(get_pref($link, 'DIGEST_PREFERRED_TIME', $line['id'], '00:00'));
2722 // try to send digests within 2 hours of preferred time
2723 if ($preferred_ts && time() >= $preferred_ts &&
2724 time() - $preferred_ts <= 7200) {
2726 if ($debug) print "Sending digest for UID:" . $line['id'] . " - " . $line["email"] . " ... ";
2728 $do_catchup = get_pref($link, 'DIGEST_CATCHUP', $line['id'], false);
2732 // reset tz_offset global to prevent tz cache clash between users
2735 $tuple = prepare_headlines_digest($link, $line["id"], 1, $limit);
2736 $digest = $tuple[0];
2737 $headlines_count = $tuple[1];
2738 $affected_ids = $tuple[2];
2739 $digest_text = $tuple[3];
2741 if ($headlines_count > 0) {
2743 $mail = new PHPMailer();
2745 $mail->PluginDir
= "lib/phpmailer/";
2746 $mail->SetLanguage("en", "lib/phpmailer/language/");
2748 $mail->CharSet
= "UTF-8";
2750 $mail->From
= SMTP_FROM_ADDRESS
;
2751 $mail->FromName
= SMTP_FROM_NAME
;
2752 $mail->AddAddress($line["email"], $line["login"]);
2755 $mail->Host
= SMTP_HOST
;
2756 $mail->Mailer
= "smtp";
2757 $mail->SMTPAuth
= SMTP_LOGIN
!= '';
2758 $mail->Username
= SMTP_LOGIN
;
2759 $mail->Password
= SMTP_PASSWORD
;
2762 $mail->IsHTML(true);
2763 $mail->Subject
= DIGEST_SUBJECT
;
2764 $mail->Body
= $digest;
2765 $mail->AltBody
= $digest_text;
2767 $rc = $mail->Send();
2769 if (!$rc && $debug) print "ERROR: " . $mail->ErrorInfo
;
2771 if ($debug) print "RC=$rc\n";
2773 if ($rc && $do_catchup) {
2774 if ($debug) print "Marking affected articles as read...\n";
2775 catchupArticlesById($link, $affected_ids, 0, $line["id"]);
2778 if ($debug) print "No headlines\n";
2781 db_query($link, "UPDATE ttrss_users SET last_digest_sent = NOW()
2782 WHERE id = " . $line["id"]);
2788 if ($debug) _debug("All done.");
2792 function prepare_headlines_digest($link, $user_id, $days = 1, $limit = 1000) {
2794 require_once "lib/MiniTemplator.class.php";
2796 $tpl = new MiniTemplator
;
2797 $tpl_t = new MiniTemplator
;
2799 $tpl->readTemplateFromFile("templates/digest_template_html.txt");
2800 $tpl_t->readTemplateFromFile("templates/digest_template.txt");
2802 $user_tz_string = get_pref($link, 'USER_TIMEZONE', $user_id);
2803 $local_ts = convert_timestamp(time(), 'UTC', $user_tz_string);
2805 $tpl->setVariable('CUR_DATE', date('Y/m/d', $local_ts));
2806 $tpl->setVariable('CUR_TIME', date('G:i', $local_ts));
2808 $tpl_t->setVariable('CUR_DATE', date('Y/m/d', $local_ts));
2809 $tpl_t->setVariable('CUR_TIME', date('G:i', $local_ts));
2811 $affected_ids = array();
2813 if (DB_TYPE
== "pgsql") {
2814 $interval_query = "ttrss_entries.date_updated > NOW() - INTERVAL '$days days'";
2815 } else if (DB_TYPE
== "mysql") {
2816 $interval_query = "ttrss_entries.date_updated > DATE_SUB(NOW(), INTERVAL $days DAY)";
2819 $result = db_query($link, "SELECT ttrss_entries.title,
2820 ttrss_feeds.title AS feed_title,
2821 COALESCE(ttrss_feed_categories.title, '".__('Uncategorized')."') AS cat_title,
2823 ttrss_user_entries.ref_id,
2827 ".SUBSTRING_FOR_DATE
."(last_updated,1,19) AS last_updated
2829 ttrss_user_entries,ttrss_entries,ttrss_feeds
2831 ttrss_feed_categories ON (cat_id = ttrss_feed_categories.id)
2833 ref_id = ttrss_entries.id AND feed_id = ttrss_feeds.id
2834 AND include_in_digest = true
2836 AND ttrss_user_entries.owner_uid = $user_id
2839 ORDER BY ttrss_feed_categories.title, ttrss_feeds.title, score DESC, date_updated DESC
2842 $cur_feed_title = "";
2844 $headlines_count = db_num_rows($result);
2846 $headlines = array();
2848 while ($line = db_fetch_assoc($result)) {
2849 array_push($headlines, $line);
2852 for ($i = 0; $i < sizeof($headlines); $i++
) {
2854 $line = $headlines[$i];
2856 array_push($affected_ids, $line["ref_id"]);
2858 $updated = make_local_datetime($link, $line['last_updated'], false,
2861 /* if ($line["score"] != 0) {
2862 if ($line["score"] > 0) $line["score"] = '+' . $line["score"];
2864 $line["title"] .= " (".$line['score'].")";
2867 if (get_pref($link, 'ENABLE_FEED_CATS', $user_id)) {
2868 $line['feed_title'] = $line['cat_title'] . " / " . $line['feed_title'];
2871 $tpl->setVariable('FEED_TITLE', $line["feed_title"]);
2872 $tpl->setVariable('ARTICLE_TITLE', $line["title"]);
2873 $tpl->setVariable('ARTICLE_LINK', $line["link"]);
2874 $tpl->setVariable('ARTICLE_UPDATED', $updated);
2875 $tpl->setVariable('ARTICLE_EXCERPT',
2876 truncate_string(strip_tags($line["content"]), 300));
2877 // $tpl->setVariable('ARTICLE_CONTENT',
2878 // strip_tags($article_content));
2880 $tpl->addBlock('article');
2882 $tpl_t->setVariable('FEED_TITLE', $line["feed_title"]);
2883 $tpl_t->setVariable('ARTICLE_TITLE', $line["title"]);
2884 $tpl_t->setVariable('ARTICLE_LINK', $line["link"]);
2885 $tpl_t->setVariable('ARTICLE_UPDATED', $updated);
2886 // $tpl_t->setVariable('ARTICLE_EXCERPT',
2887 // truncate_string(strip_tags($line["excerpt"]), 100));
2889 $tpl_t->addBlock('article');
2891 if ($headlines[$i]['feed_title'] != $headlines[$i+
1]['feed_title']) {
2892 $tpl->addBlock('feed');
2893 $tpl_t->addBlock('feed');
2898 $tpl->addBlock('digest');
2899 $tpl->generateOutputToString($tmp);
2901 $tpl_t->addBlock('digest');
2902 $tpl_t->generateOutputToString($tmp_t);
2904 return array($tmp, $headlines_count, $affected_ids, $tmp_t);
2907 function check_for_update($link) {
2908 if (CHECK_FOR_NEW_VERSION
&& $_SESSION['access_level'] >= 10) {
2909 $version_url = "http://tt-rss.org/version.php?ver=" . VERSION
;
2911 $version_data = @fetch_file_contents
($version_url);
2913 if ($version_data) {
2914 $version_data = json_decode($version_data, true);
2915 if ($version_data && $version_data['version']) {
2917 if (version_compare(VERSION
, $version_data['version']) == -1) {
2918 return $version_data;
2926 function markArticlesById($link, $ids, $cmode) {
2930 foreach ($ids as $id) {
2931 array_push($tmp_ids, "ref_id = '$id'");
2934 $ids_qpart = join(" OR ", $tmp_ids);
2937 db_query($link, "UPDATE ttrss_user_entries SET
2938 marked = false,last_read = NOW()
2939 WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
2940 } else if ($cmode == 1) {
2941 db_query($link, "UPDATE ttrss_user_entries SET
2943 WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
2945 db_query($link, "UPDATE ttrss_user_entries SET
2946 marked = NOT marked,last_read = NOW()
2947 WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
2951 function publishArticlesById($link, $ids, $cmode) {
2955 foreach ($ids as $id) {
2956 array_push($tmp_ids, "ref_id = '$id'");
2959 $ids_qpart = join(" OR ", $tmp_ids);
2962 db_query($link, "UPDATE ttrss_user_entries SET
2963 published = false,last_read = NOW()
2964 WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
2965 } else if ($cmode == 1) {
2966 db_query($link, "UPDATE ttrss_user_entries SET
2968 WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
2970 db_query($link, "UPDATE ttrss_user_entries SET
2971 published = NOT published,last_read = NOW()
2972 WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
2975 if (PUBSUBHUBBUB_HUB
) {
2976 $rss_link = get_self_url_prefix() .
2977 "/public.php?op=rss&id=-2&key=" .
2978 get_feed_access_key($link, -2, false);
2980 $p = new Publisher(PUBSUBHUBBUB_HUB
);
2982 $pubsub_result = $p->publish_update($rss_link);
2986 function catchupArticlesById($link, $ids, $cmode, $owner_uid = false) {
2988 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
2989 if (count($ids) == 0) return;
2993 foreach ($ids as $id) {
2994 array_push($tmp_ids, "ref_id = '$id'");
2997 $ids_qpart = join(" OR ", $tmp_ids);
3000 db_query($link, "UPDATE ttrss_user_entries SET
3001 unread = false,last_read = NOW()
3002 WHERE ($ids_qpart) AND owner_uid = $owner_uid");
3003 } else if ($cmode == 1) {
3004 db_query($link, "UPDATE ttrss_user_entries SET
3006 WHERE ($ids_qpart) AND owner_uid = $owner_uid");
3008 db_query($link, "UPDATE ttrss_user_entries SET
3009 unread = NOT unread,last_read = NOW()
3010 WHERE ($ids_qpart) AND owner_uid = $owner_uid");
3015 $result = db_query($link, "SELECT DISTINCT feed_id FROM ttrss_user_entries
3016 WHERE ($ids_qpart) AND owner_uid = $owner_uid");
3018 while ($line = db_fetch_assoc($result)) {
3019 ccache_update($link, $line["feed_id"], $owner_uid);
3023 function catchupArticleById($link, $id, $cmode) {
3026 db_query($link, "UPDATE ttrss_user_entries SET
3027 unread = false,last_read = NOW()
3028 WHERE ref_id = '$id' AND owner_uid = " . $_SESSION["uid"]);
3029 } else if ($cmode == 1) {
3030 db_query($link, "UPDATE ttrss_user_entries SET
3032 WHERE ref_id = '$id' AND owner_uid = " . $_SESSION["uid"]);
3034 db_query($link, "UPDATE ttrss_user_entries SET
3035 unread = NOT unread,last_read = NOW()
3036 WHERE ref_id = '$id' AND owner_uid = " . $_SESSION["uid"]);
3039 $feed_id = getArticleFeed($link, $id);
3040 ccache_update($link, $feed_id, $_SESSION["uid"]);
3043 function make_guid_from_title($title) {
3044 return preg_replace("/[ \"\',.:;]/", "-",
3045 mb_strtolower(strip_tags($title), 'utf-8'));
3048 function get_article_tags($link, $id, $owner_uid = 0, $tag_cache = false) {
3050 $a_id = db_escape_string($id);
3052 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
3054 $query = "SELECT DISTINCT tag_name,
3055 owner_uid as owner FROM
3056 ttrss_tags WHERE post_int_id = (SELECT int_id FROM ttrss_user_entries WHERE
3057 ref_id = '$a_id' AND owner_uid = '$owner_uid' LIMIT 1) ORDER BY tag_name";
3059 $obj_id = md5("TAGS:$owner_uid:$id");
3062 /* check cache first */
3064 if ($tag_cache === false) {
3065 $result = db_query($link, "SELECT tag_cache FROM ttrss_user_entries
3066 WHERE ref_id = '$id' AND owner_uid = $owner_uid");
3068 $tag_cache = db_fetch_result($result, 0, "tag_cache");
3072 $tags = explode(",", $tag_cache);
3075 /* do it the hard way */
3077 $tmp_result = db_query($link, $query);
3079 while ($tmp_line = db_fetch_assoc($tmp_result)) {
3080 array_push($tags, $tmp_line["tag_name"]);
3083 /* update the cache */
3085 $tags_str = db_escape_string(join(",", $tags));
3087 db_query($link, "UPDATE ttrss_user_entries
3088 SET tag_cache = '$tags_str' WHERE ref_id = '$id'
3089 AND owner_uid = $owner_uid");
3095 function trim_array($array) {
3097 array_walk($tmp, 'trim');
3101 function tag_is_valid($tag) {
3102 if ($tag == '') return false;
3103 if (preg_match("/^[0-9]*$/", $tag)) return false;
3104 if (mb_strlen($tag) > 250) return false;
3106 if (function_exists('iconv')) {
3107 $tag = iconv("utf-8", "utf-8", $tag);
3110 if (!$tag) return false;
3115 function render_login_form($link, $mobile = 0) {
3118 require_once "login_form.php";
3121 require_once "mobile/login_form.php";
3124 require_once "mobile/classic/login_form.php";
3128 // from http://developer.apple.com/internet/safari/faq.html
3129 function no_cache_incantation() {
3130 header("Expires: Mon, 22 Dec 1980 00:00:00 GMT"); // Happy birthday to me :)
3131 header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT"); // always modified
3132 header("Cache-Control: no-store, no-cache, must-revalidate, max-age=0"); // HTTP/1.1
3133 header("Cache-Control: post-check=0, pre-check=0", false);
3134 header("Pragma: no-cache"); // HTTP/1.0
3137 function format_warning($msg, $id = "") {
3139 return "<div class=\"warning\" id=\"$id\">
3140 <img src=\"".theme_image($link, "images/sign_excl.png")."\">$msg</div>";
3143 function format_notice($msg, $id = "") {
3145 return "<div class=\"notice\" id=\"$id\">
3146 <img src=\"".theme_image($link, "images/sign_info.png")."\">$msg</div>";
3149 function format_error($msg, $id = "") {
3151 return "<div class=\"error\" id=\"$id\">
3152 <img src=\"".theme_image($link, "images/sign_excl.png")."\">$msg</div>";
3155 function print_notice($msg) {
3156 return print format_notice($msg);
3159 function print_warning($msg) {
3160 return print format_warning($msg);
3163 function print_error($msg) {
3164 return print format_error($msg);
3168 function T_sprintf() {
3169 $args = func_get_args();
3170 return vsprintf(__(array_shift($args)), $args);
3173 function format_inline_player($link, $url, $ctype) {
3177 if (strpos($ctype, "audio/") === 0) {
3179 if ($_SESSION["hasAudio"] && (strpos($ctype, "ogg") !== false ||
3180 strpos($_SERVER['HTTP_USER_AGENT'], "Chrome") !== false ||
3181 strpos($_SERVER['HTTP_USER_AGENT'], "Safari") !== false )) {
3183 $id = 'AUDIO-' . uniqid();
3185 $entry .= "<audio id=\"$id\"\">
3186 <source src=\"$url\"></source>
3189 $entry .= "<span onclick=\"player(this)\"
3190 title=\"".__("Click to play")."\" status=\"0\"
3191 class=\"player\" audio-id=\"$id\">".__("Play")."</span>";
3195 $entry .= "<object type=\"application/x-shockwave-flash\"
3196 data=\"lib/button/musicplayer.swf?song_url=$url\"
3197 width=\"17\" height=\"17\" style='float : left; margin-right : 5px;'>
3198 <param name=\"movie\"
3199 value=\"lib/button/musicplayer.swf?song_url=$url\" />
3204 $filename = substr($url, strrpos($url, "/")+
1);
3206 $entry .= " <a target=\"_blank\" href=\"" . htmlspecialchars($url) . "\">" .
3207 $filename . " (" . $ctype . ")" . "</a>";
3212 function format_article($link, $id, $mark_as_read = true, $zoom_mode = false, $owner_uid = false) {
3214 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
3220 /* we can figure out feed_id from article id anyway, why do we
3221 * pass feed_id here? let's ignore the argument :( */
3223 $result = db_query($link, "SELECT feed_id FROM ttrss_user_entries
3224 WHERE ref_id = '$id'");
3226 $feed_id = (int) db_fetch_result($result, 0, "feed_id");
3228 $rv['feed_id'] = $feed_id;
3230 //if (!$zoom_mode) { print "<article id='$id'><![CDATA["; };
3232 $result = db_query($link, "SELECT rtl_content, always_display_enclosures FROM ttrss_feeds
3233 WHERE id = '$feed_id' AND owner_uid = $owner_uid");
3235 if (db_num_rows($result) == 1) {
3236 $rtl_content = sql_bool_to_bool(db_fetch_result($result, 0, "rtl_content"));
3237 $always_display_enclosures = sql_bool_to_bool(db_fetch_result($result, 0, "always_display_enclosures"));
3239 $rtl_content = false;
3240 $always_display_enclosures = false;
3244 $rtl_tag = "dir=\"RTL\"";
3251 if ($mark_as_read) {
3252 $result = db_query($link, "UPDATE ttrss_user_entries
3253 SET unread = false,last_read = NOW()
3254 WHERE ref_id = '$id' AND owner_uid = $owner_uid");
3256 ccache_update($link, $feed_id, $owner_uid);
3259 $result = db_query($link, "SELECT title,link,content,feed_id,comments,int_id,
3260 ".SUBSTRING_FOR_DATE
."(updated,1,16) as updated,
3261 (SELECT icon_url FROM ttrss_feeds WHERE id = feed_id) as icon_url,
3262 (SELECT site_url FROM ttrss_feeds WHERE id = feed_id) as site_url,
3268 FROM ttrss_entries,ttrss_user_entries
3269 WHERE id = '$id' AND ref_id = id AND owner_uid = $owner_uid");
3273 $line = db_fetch_assoc($result);
3275 if ($line["icon_url"]) {
3276 $feed_icon = "<img src=\"" . $line["icon_url"] . "\">";
3278 $feed_icon = " ";
3281 $feed_site_url = $line['site_url'];
3283 $num_comments = $line["num_comments"];
3284 $entry_comments = "";
3286 if ($num_comments > 0) {
3287 if ($line["comments"]) {
3288 $comments_url = $line["comments"];
3290 $comments_url = $line["link"];
3292 $entry_comments = "<a target='_blank' href=\"$comments_url\">$num_comments comments</a>";
3294 if ($line["comments"] && $line["link"] != $line["comments"]) {
3295 $entry_comments = "<a target='_blank' href=\"".$line["comments"]."\">comments</a>";
3300 header("Content-Type: text/html");
3301 $rv['content'] .= "<html><head>
3302 <meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\"/>
3303 <title>Tiny Tiny RSS - ".$line["title"]."</title>
3304 <link rel=\"stylesheet\" type=\"text/css\" href=\"tt-rss.css\">
3308 $title_escaped = db_escape_string($line['title']);
3310 $rv['content'] .= "<div id=\"PTITLE-$id\" style=\"display : none\">" .
3311 truncate_string(strip_tags($line['title']), 15) . "</div>";
3313 $rv['content'] .= "<div id=\"PTITLE-FULL-$id\" style=\"display : none\">" .
3314 strip_tags($line['title']) . "</div>";
3316 $rv['content'] .= "<div class=\"postReply\" id=\"POST-$id\">";
3318 $rv['content'] .= "<div onclick=\"return postClicked(event, $id)\"
3319 class=\"postHeader\" id=\"POSTHDR-$id\">";
3321 $entry_author = $line["author"];
3323 if ($entry_author) {
3324 $entry_author = __(" - ") . $entry_author;
3327 $parsed_updated = make_local_datetime($link, $line["updated"], true,
3330 $rv['content'] .= "<div class=\"postDate$rtl_class\">$parsed_updated</div>";
3332 if ($line["link"]) {
3333 $rv['content'] .= "<div class='postTitle' clear='both'><a target='_blank'
3334 title=\"".htmlspecialchars($line['title'])."\"
3336 $line["link"] . "\">" .
3337 truncate_string($line["title"], 100) .
3338 "<span class='author'>$entry_author</span></a></div>";
3340 $rv['content'] .= "<div class='postTitle' clear='both'>" . $line["title"] . "$entry_author</div>";
3343 $tag_cache = $line["tag_cache"];
3346 $tags = get_article_tags($link, $id, $owner_uid);
3348 $tags = explode(",", $tag_cache);
3350 $tags_str = format_tags_string($tags, $id);
3351 $tags_str_full = join(", ", $tags);
3353 if (!$tags_str_full) $tags_str_full = __("no tags");
3355 if (!$entry_comments) $entry_comments = " "; # placeholder
3357 $rv['content'] .= "<div class='postTags' style='float : right'>
3358 <img src='".theme_image($link, 'images/tag.png')."'
3359 class='tagsPic' alt='Tags' title='Tags'> ";
3362 $rv['content'] .= "<span id=\"ATSTR-$id\">$tags_str</span>
3363 <a title=\"".__('Edit tags for this article')."\"
3364 href=\"#\" onclick=\"editArticleTags($id, $feed_id)\">(+)</a>";
3366 $rv['content'] .= "<div dojoType=\"dijit.Tooltip\"
3367 id=\"ATSTRTIP-$id\" connectId=\"ATSTR-$id\"
3368 position=\"below\">$tags_str_full</div>";
3370 $rv['content'] .= "<img src=\"".theme_image($link, 'images/art-zoom.png')."\"
3371 class='tagsPic' style=\"cursor : pointer\"
3372 onclick=\"postOpenInNewTab(event, $id)\"
3373 alt='Zoom' title='".__('Open article in new tab')."'>";
3375 $button_plugins = explode(",", ARTICLE_BUTTON_PLUGINS
);
3377 foreach ($button_plugins as $p) {
3378 $pclass = trim("${p}_button");
3380 if (class_exists($pclass)) {
3381 $plugin = new $pclass($link);
3382 $rv['content'] .= $plugin->render($id, $line);
3386 $rv['content'] .= "<img src=\"".theme_image($link, 'images/digest_checkbox.png')."\"
3387 class='tagsPic' style=\"cursor : pointer\"
3388 onclick=\"closeArticlePanel($id)\"
3389 title='".__('Close article')."'>";
3392 $tags_str = strip_tags($tags_str);
3393 $rv['content'] .= "<span id=\"ATSTR-$id\">$tags_str</span>";
3395 $rv['content'] .= "</div>";
3396 $rv['content'] .= "<div clear='both'>$entry_comments</div>";
3398 if ($line["orig_feed_id"]) {
3400 $tmp_result = db_query($link, "SELECT * FROM ttrss_archived_feeds
3401 WHERE id = ".$line["orig_feed_id"]);
3403 if (db_num_rows($tmp_result) != 0) {
3405 $rv['content'] .= "<div clear='both'>";
3406 $rv['content'] .= __("Originally from:");
3408 $rv['content'] .= " ";
3410 $tmp_line = db_fetch_assoc($tmp_result);
3412 $rv['content'] .= "<a target='_blank'
3413 href=' " . htmlspecialchars($tmp_line['site_url']) . "'>" .
3414 $tmp_line['title'] . "</a>";
3416 $rv['content'] .= " ";
3418 $rv['content'] .= "<a target='_blank' href='" . htmlspecialchars($tmp_line['feed_url']) . "'>";
3419 $rv['content'] .= "<img title='".__('Feed URL')."'class='tinyFeedIcon' src='images/pub_set.png'></a>";
3421 $rv['content'] .= "</div>";
3425 $rv['content'] .= "</div>";
3427 $rv['content'] .= "<div id=\"POSTNOTE-$id\">";
3428 if ($line['note']) {
3429 $rv['content'] .= format_article_note($id, $line['note']);
3431 $rv['content'] .= "</div>";
3433 $rv['content'] .= "<div class=\"postIcon\">" .
3434 "<a target=\"_blank\" title=\"".__("Visit the website")."\"$
3435 href=\"".htmlspecialchars($feed_site_url)."\">".
3436 $feed_icon . "</a></div>";
3438 $rv['content'] .= "<div class=\"postContent\">";
3442 if (DB_TYPE
== "pgsql" and defined('_NGRAM_TITLE_RELATED_THRESHOLD')) {
3444 $ngram_result = db_query($link, "SELECT id,title FROM
3445 ttrss_entries,ttrss_user_entries
3446 WHERE ref_id = id AND updated >= NOW() - INTERVAL '7 day'
3447 AND similarity(title, '$title_escaped') >= "._NGRAM_TITLE_RELATED_THRESHOLD
."
3448 AND title != '$title_escaped'
3449 AND owner_uid = $owner_uid");
3451 if (db_num_rows($ngram_result) > 0) {
3452 $rv['content'] .= "<div dojoType=\"dijit.form.DropDownButton\">".
3453 "<span>" . __('Related')."</span>";
3454 $rv['content'] .= "<div dojoType=\"dijit.Menu\" style=\"display: none;\">";
3456 while ($nline = db_fetch_assoc($ngram_result)) {
3457 $rv['content'] .= "<div onclick=\"hlOpenInNewTab(null,".$nline['id'].")\"
3458 dojoType=\"dijit.MenuItem\">".$nline['title']."</div>";
3461 $rv['content'] .= "</div></div><br/";
3465 $article_content = sanitize($link, $line["content"], false, $owner_uid,
3468 $rv['content'] .= $article_content;
3470 $rv['content'] .= format_article_enclosures($link, $id,
3471 $always_display_enclosures, $article_content);
3473 $rv['content'] .= "</div>";
3475 $rv['content'] .= "</div>";
3481 <div style=\"text-align : center\">
3482 <button onclick=\"return window.close()\">".
3483 __("Close this window")."</button></div>";
3484 $rv['content'] .= "</body></html>";
3491 function print_checkpoint($n, $s) {
3492 $ts = getmicrotime();
3493 echo sprintf("<!-- CP[$n] %.4f seconds -->", $ts - $s);
3497 function sanitize_tag($tag) {
3500 $tag = mb_strtolower($tag, 'utf-8');
3502 $tag = preg_replace('/[\'\"\+\>\<]/', "", $tag);
3504 // $tag = str_replace('"', "", $tag);
3505 // $tag = str_replace("+", " ", $tag);
3506 $tag = str_replace("technorati tag: ", "", $tag);
3511 function get_self_url_prefix() {
3512 return SELF_URL_PATH
;
3515 function opml_publish_url($link){
3517 $url_path = get_self_url_prefix();
3518 $url_path .= "/opml.php?op=publish&key=" .
3519 get_feed_access_key($link, 'OPML:Publish', false, $_SESSION["uid"]);
3525 * Purge a feed contents, marked articles excepted.
3527 * @param mixed $link The database connection.
3528 * @param integer $id The id of the feed to purge.
3531 function clear_feed_articles($link, $id) {
3534 $result = db_query($link, "DELETE FROM ttrss_user_entries
3535 WHERE feed_id = '$id' AND marked = false AND owner_uid = " . $_SESSION["uid"]);
3537 $result = db_query($link, "DELETE FROM ttrss_user_entries
3538 WHERE feed_id IS NULL AND marked = false AND owner_uid = " . $_SESSION["uid"]);
3541 $result = db_query($link, "DELETE FROM ttrss_entries WHERE
3542 (SELECT COUNT(int_id) FROM ttrss_user_entries WHERE ref_id = id) = 0");
3544 ccache_update($link, $id, $_SESSION['uid']);
3545 } // function clear_feed_articles
3548 * Compute the Mozilla Firefox feed adding URL from server HOST and REQUEST_URI.
3550 * @return string The Mozilla Firefox feed adding URL.
3552 function add_feed_url() {
3553 //$url_path = ($_SERVER['HTTPS'] != "on" ? 'http://' : 'https://') . $_SERVER["HTTP_HOST"] . parse_url($_SERVER["REQUEST_URI"], PHP_URL_PATH);
3555 $url_path = get_self_url_prefix() .
3556 "/backend.php?op=pref-feeds&quiet=1&method=add&feed_url=%s";
3558 } // function add_feed_url
3560 function encrypt_password($pass, $salt = '', $mode2 = false) {
3561 if ($salt && $mode2) {
3562 return "MODE2:" . hash('sha256', $salt . $pass);
3564 return "SHA1X:" . sha1("$salt:$pass");
3566 return "SHA1:" . sha1($pass);
3568 } // function encrypt_password
3570 function sanitize_article_content($text) {
3571 # we don't support CDATA sections in articles, they break our own escaping
3572 $text = preg_replace("/\[\[CDATA/", "", $text);
3573 $text = preg_replace("/\]\]\>/", "", $text);
3577 function load_filters($link, $feed, $owner_uid, $action_id = false) {
3581 if ($action_id) $ftype_query_part = "action_id = '$action_id' AND";
3583 $result = db_query($link, "SELECT reg_exp,
3584 ttrss_filter_types.name AS name,
3585 ttrss_filter_actions.name AS action,
3590 LEFT JOIN ttrss_feeds ON (ttrss_feeds.id = '$feed'),
3591 ttrss_filter_types,ttrss_filter_actions
3595 ttrss_filters.owner_uid = $owner_uid AND
3596 ttrss_filter_types.id = filter_type AND
3597 ttrss_filter_actions.id = action_id AND
3598 ((cat_filter = true AND ttrss_feeds.cat_id = ttrss_filters.cat_id) OR
3599 (cat_filter = true AND ttrss_feeds.cat_id IS NULL AND
3600 ttrss_filters.cat_id IS NULL) OR
3601 (cat_filter = false AND (feed_id IS NULL OR feed_id = '$feed')))
3604 while ($line = db_fetch_assoc($result)) {
3606 if (!$filters[$line["name"]]) $filters[$line["name"]] = array();
3607 $filter["reg_exp"] = $line["reg_exp"];
3608 $filter["action"] = $line["action"];
3609 $filter["action_param"] = $line["action_param"];
3610 $filter["filter_param"] = $line["filter_param"];
3611 $filter["inverse"] = sql_bool_to_bool($line["inverse"]);
3613 array_push($filters[$line["name"]], $filter);
3620 function get_score_pic($score) {
3622 return "score_high.png";
3623 } else if ($score > 0) {
3624 return "score_half_high.png";
3625 } else if ($score < -100) {
3626 return "score_low.png";
3627 } else if ($score < 0) {
3628 return "score_half_low.png";
3630 return "score_neutral.png";
3634 function feed_has_icon($id) {
3635 return is_file(ICONS_DIR
. "/$id.ico") && filesize(ICONS_DIR
. "/$id.ico") > 0;
3638 function init_connection($link) {
3641 if (DB_TYPE
== "pgsql") {
3642 pg_query($link, "set client_encoding = 'UTF-8'");
3643 pg_set_client_encoding("UNICODE");
3644 pg_query($link, "set datestyle = 'ISO, european'");
3645 pg_query($link, "set TIME ZONE 0");
3647 db_query($link, "SET time_zone = '+0:0'");
3649 if (defined('MYSQL_CHARSET') && MYSQL_CHARSET
) {
3650 db_query($link, "SET NAMES " . MYSQL_CHARSET
);
3655 print "Unable to connect to database:" . db_last_error();
3660 /* function ccache_zero($link, $feed_id, $owner_uid) {
3661 db_query($link, "UPDATE ttrss_counters_cache SET
3662 value = 0, updated = NOW() WHERE
3663 feed_id = '$feed_id' AND owner_uid = '$owner_uid'");
3666 function ccache_zero_all($link, $owner_uid) {
3667 db_query($link, "UPDATE ttrss_counters_cache SET
3668 value = 0 WHERE owner_uid = '$owner_uid'");
3670 db_query($link, "UPDATE ttrss_cat_counters_cache SET
3671 value = 0 WHERE owner_uid = '$owner_uid'");
3674 function ccache_remove($link, $feed_id, $owner_uid, $is_cat = false) {
3677 $table = "ttrss_counters_cache";
3679 $table = "ttrss_cat_counters_cache";
3682 db_query($link, "DELETE FROM $table WHERE
3683 feed_id = '$feed_id' AND owner_uid = '$owner_uid'");
3687 function ccache_update_all($link, $owner_uid) {
3689 if (get_pref($link, 'ENABLE_FEED_CATS', $owner_uid)) {
3691 $result = db_query($link, "SELECT feed_id FROM ttrss_cat_counters_cache
3692 WHERE feed_id > 0 AND owner_uid = '$owner_uid'");
3694 while ($line = db_fetch_assoc($result)) {
3695 ccache_update($link, $line["feed_id"], $owner_uid, true);
3698 /* We have to manually include category 0 */
3700 ccache_update($link, 0, $owner_uid, true);
3703 $result = db_query($link, "SELECT feed_id FROM ttrss_counters_cache
3704 WHERE feed_id > 0 AND owner_uid = '$owner_uid'");
3706 while ($line = db_fetch_assoc($result)) {
3707 print ccache_update($link, $line["feed_id"], $owner_uid);
3714 function ccache_find($link, $feed_id, $owner_uid, $is_cat = false,
3715 $no_update = false) {
3717 if (!is_numeric($feed_id)) return;
3720 $table = "ttrss_counters_cache";
3722 $tmp_result = db_query($link, "SELECT owner_uid FROM ttrss_feeds
3723 WHERE id = '$feed_id'");
3724 $owner_uid = db_fetch_result($tmp_result, 0, "owner_uid");
3727 $table = "ttrss_cat_counters_cache";
3730 if (DB_TYPE
== "pgsql") {
3731 $date_qpart = "updated > NOW() - INTERVAL '15 minutes'";
3732 } else if (DB_TYPE
== "mysql") {
3733 $date_qpart = "updated > DATE_SUB(NOW(), INTERVAL 15 MINUTE)";
3736 $result = db_query($link, "SELECT value FROM $table
3737 WHERE owner_uid = '$owner_uid' AND feed_id = '$feed_id'
3740 if (db_num_rows($result) == 1) {
3741 return db_fetch_result($result, 0, "value");
3746 return ccache_update($link, $feed_id, $owner_uid, $is_cat);
3752 function ccache_update($link, $feed_id, $owner_uid, $is_cat = false,
3753 $update_pcat = true) {
3755 if (!is_numeric($feed_id)) return;
3757 if (!$is_cat && $feed_id > 0) {
3758 $tmp_result = db_query($link, "SELECT owner_uid FROM ttrss_feeds
3759 WHERE id = '$feed_id'");
3760 $owner_uid = db_fetch_result($tmp_result, 0, "owner_uid");
3763 $prev_unread = ccache_find($link, $feed_id, $owner_uid, $is_cat, true);
3765 /* When updating a label, all we need to do is recalculate feed counters
3766 * because labels are not cached */
3769 ccache_update_all($link, $owner_uid);
3774 $table = "ttrss_counters_cache";
3776 $table = "ttrss_cat_counters_cache";
3779 if ($is_cat && $feed_id >= 0) {
3780 if ($feed_id != 0) {
3781 $cat_qpart = "cat_id = '$feed_id'";
3783 $cat_qpart = "cat_id IS NULL";
3786 /* Recalculate counters for child feeds */
3788 $result = db_query($link, "SELECT id FROM ttrss_feeds
3789 WHERE owner_uid = '$owner_uid' AND $cat_qpart");
3791 while ($line = db_fetch_assoc($result)) {
3792 ccache_update($link, $line["id"], $owner_uid, false, false);
3795 $result = db_query($link, "SELECT SUM(value) AS sv
3796 FROM ttrss_counters_cache, ttrss_feeds
3797 WHERE id = feed_id AND $cat_qpart AND
3798 ttrss_feeds.owner_uid = '$owner_uid'");
3800 $unread = (int) db_fetch_result($result, 0, "sv");
3803 $unread = (int) getFeedArticles($link, $feed_id, $is_cat, true, $owner_uid);
3806 db_query($link, "BEGIN");
3808 $result = db_query($link, "SELECT feed_id FROM $table
3809 WHERE owner_uid = '$owner_uid' AND feed_id = '$feed_id' LIMIT 1");
3811 if (db_num_rows($result) == 1) {
3812 db_query($link, "UPDATE $table SET
3813 value = '$unread', updated = NOW() WHERE
3814 feed_id = '$feed_id' AND owner_uid = '$owner_uid'");
3817 db_query($link, "INSERT INTO $table
3818 (feed_id, value, owner_uid, updated)
3820 ($feed_id, $unread, $owner_uid, NOW())");
3823 db_query($link, "COMMIT");
3825 if ($feed_id > 0 && $prev_unread != $unread) {
3829 /* Update parent category */
3833 $result = db_query($link, "SELECT cat_id FROM ttrss_feeds
3834 WHERE owner_uid = '$owner_uid' AND id = '$feed_id'");
3836 $cat_id = (int) db_fetch_result($result, 0, "cat_id");
3838 ccache_update($link, $cat_id, $owner_uid, true);
3842 } else if ($feed_id < 0) {
3843 ccache_update_all($link, $owner_uid);
3849 /* function ccache_cleanup($link, $owner_uid) {
3851 if (DB_TYPE == "pgsql") {
3852 db_query($link, "DELETE FROM ttrss_counters_cache AS c1 WHERE
3853 (SELECT count(*) FROM ttrss_counters_cache AS c2
3854 WHERE c1.feed_id = c2.feed_id AND c2.owner_uid = c1.owner_uid) > 1
3855 AND owner_uid = '$owner_uid'");
3857 db_query($link, "DELETE FROM ttrss_cat_counters_cache AS c1 WHERE
3858 (SELECT count(*) FROM ttrss_cat_counters_cache AS c2
3859 WHERE c1.feed_id = c2.feed_id AND c2.owner_uid = c1.owner_uid) > 1
3860 AND owner_uid = '$owner_uid'");
3862 db_query($link, "DELETE c1 FROM
3863 ttrss_counters_cache AS c1,
3864 ttrss_counters_cache AS c2
3866 c1.owner_uid = '$owner_uid' AND
3867 c1.owner_uid = c2.owner_uid AND
3868 c1.feed_id = c2.feed_id");
3870 db_query($link, "DELETE c1 FROM
3871 ttrss_cat_counters_cache AS c1,
3872 ttrss_cat_counters_cache AS c2
3874 c1.owner_uid = '$owner_uid' AND
3875 c1.owner_uid = c2.owner_uid AND
3876 c1.feed_id = c2.feed_id");
3881 function label_find_id($link, $label, $owner_uid) {
3882 $result = db_query($link,
3883 "SELECT id FROM ttrss_labels2 WHERE caption = '$label'
3884 AND owner_uid = '$owner_uid' LIMIT 1");
3886 if (db_num_rows($result) == 1) {
3887 return db_fetch_result($result, 0, "id");
3893 function get_article_labels($link, $id) {
3897 $result = db_query($link, "SELECT label_cache FROM
3898 ttrss_user_entries WHERE ref_id = '$id' AND owner_uid = " .
3901 $label_cache = db_fetch_result($result, 0, "label_cache");
3905 $label_cache = json_decode($label_cache, true);
3907 if ($label_cache["no-labels"] == 1)
3910 return $label_cache;
3913 $result = db_query($link,
3914 "SELECT DISTINCT label_id,caption,fg_color,bg_color
3915 FROM ttrss_labels2, ttrss_user_labels2
3917 AND article_id = '$id'
3918 AND owner_uid = ".$_SESSION["uid"] . "
3921 while ($line = db_fetch_assoc($result)) {
3922 $rk = array($line["label_id"], $line["caption"], $line["fg_color"],
3924 array_push($rv, $rk);
3928 label_update_cache($link, $id, $rv);
3930 label_update_cache($link, $id, array("no-labels" => 1));
3936 function label_find_caption($link, $label, $owner_uid) {
3937 $result = db_query($link,
3938 "SELECT caption FROM ttrss_labels2 WHERE id = '$label'
3939 AND owner_uid = '$owner_uid' LIMIT 1");
3941 if (db_num_rows($result) == 1) {
3942 return db_fetch_result($result, 0, "caption");
3948 function label_update_cache($link, $id, $labels = false, $force = false) {
3951 label_clear_cache($link, $id);
3954 $labels = get_article_labels($link, $id);
3956 $labels = db_escape_string(json_encode($labels));
3958 db_query($link, "UPDATE ttrss_user_entries SET
3959 label_cache = '$labels' WHERE ref_id = '$id'");
3963 function label_clear_cache($link, $id) {
3965 db_query($link, "UPDATE ttrss_user_entries SET
3966 label_cache = '' WHERE ref_id = '$id'");
3970 function label_remove_article($link, $id, $label, $owner_uid) {
3972 $label_id = label_find_id($link, $label, $owner_uid);
3974 if (!$label_id) return;
3976 $result = db_query($link,
3977 "DELETE FROM ttrss_user_labels2
3979 label_id = '$label_id' AND
3980 article_id = '$id'");
3982 label_clear_cache($link, $id);
3985 function label_add_article($link, $id, $label, $owner_uid) {
3987 $label_id = label_find_id($link, $label, $owner_uid);
3989 if (!$label_id) return;
3991 $result = db_query($link,
3993 article_id FROM ttrss_labels2, ttrss_user_labels2
3996 label_id = '$label_id' AND
3997 article_id = '$id' AND owner_uid = '$owner_uid'
4000 if (db_num_rows($result) == 0) {
4001 db_query($link, "INSERT INTO ttrss_user_labels2
4002 (label_id, article_id) VALUES ('$label_id', '$id')");
4005 label_clear_cache($link, $id);
4009 function label_remove($link, $id, $owner_uid) {
4010 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
4012 db_query($link, "BEGIN");
4014 $result = db_query($link, "SELECT caption FROM ttrss_labels2
4017 $caption = db_fetch_result($result, 0, "caption");
4019 $result = db_query($link, "DELETE FROM ttrss_labels2 WHERE id = '$id'
4020 AND owner_uid = " . $owner_uid);
4022 if (db_affected_rows($link, $result) != 0 && $caption) {
4024 /* Remove access key for the label */
4026 $ext_id = -11 - $id;
4028 db_query($link, "DELETE FROM ttrss_access_keys WHERE
4029 feed_id = '$ext_id' AND owner_uid = $owner_uid");
4031 /* Disable filters that reference label being removed */
4033 db_query($link, "UPDATE ttrss_filters SET
4034 enabled = false WHERE action_param = '$caption'
4036 AND owner_uid = " . $owner_uid);
4038 /* Remove cached data */
4040 db_query($link, "UPDATE ttrss_user_entries SET label_cache = ''
4041 WHERE label_cache LIKE '%$caption%' AND owner_uid = " . $owner_uid);
4045 db_query($link, "COMMIT");
4048 function label_create($link, $caption, $fg_color = '', $bg_color = '', $owner_uid) {
4050 if (!$owner_uid) $owner_uid = $_SESSION['uid'];
4052 db_query($link, "BEGIN");
4056 $result = db_query($link, "SELECT id FROM ttrss_labels2
4057 WHERE caption = '$caption' AND owner_uid = $owner_uid");
4059 if (db_num_rows($result) == 0) {
4060 $result = db_query($link,
4061 "INSERT INTO ttrss_labels2 (caption,owner_uid,fg_color,bg_color)
4062 VALUES ('$caption', '$owner_uid', '$fg_color', '$bg_color')");
4064 $result = db_affected_rows($link, $result) != 0;
4067 db_query($link, "COMMIT");
4072 function format_tags_string($tags, $id) {
4075 $tags_nolinks_str = "";
4081 $formatted_tags = array();
4083 foreach ($tags as $tag) {
4085 $tag_escaped = str_replace("'", "\\'", $tag);
4087 if (mb_strlen($tag) > 30) {
4088 $tag = truncate_string($tag, 30);
4091 $tag_str = "<a href=\"javascript:viewfeed('$tag_escaped')\">$tag</a>";
4093 array_push($formatted_tags, $tag_str);
4095 $tmp_tags_str = implode(", ", $formatted_tags);
4097 if ($num_tags == $tag_limit ||
mb_strlen($tmp_tags_str) > 150) {
4102 $tags_str = implode(", ", $formatted_tags);
4104 if ($num_tags < count($tags)) {
4105 $tags_str .= ", …";
4108 if ($num_tags == 0) {
4109 $tags_str = __("no tags");
4116 function format_article_labels($labels, $id) {
4120 foreach ($labels as $l) {
4121 $labels_str .= sprintf("<span class='hlLabelRef'
4122 style='color : %s; background-color : %s'>%s</span>",
4123 $l[2], $l[3], $l[1]);
4130 function format_article_note($id, $note) {
4132 $str = "<div class='articleNote' onclick=\"editArticleNote($id)\">
4133 <div class='noteEdit' onclick=\"editArticleNote($id)\">".
4134 __('(edit note)')."</div>$note</div>";
4139 function toggle_collapse_cat($link, $cat_id, $mode) {
4141 $mode = bool_to_sql_bool($mode);
4143 db_query($link, "UPDATE ttrss_feed_categories SET
4144 collapsed = $mode WHERE id = '$cat_id' AND owner_uid = " .
4151 $pref_name = '_COLLAPSED_SPECIAL';
4154 $pref_name = '_COLLAPSED_LABELS';
4157 $pref_name = '_COLLAPSED_UNCAT';
4163 set_pref($link, $pref_name, 'true');
4165 set_pref($link, $pref_name, 'false');
4171 function remove_feed($link, $id, $owner_uid) {
4175 /* save starred articles in Archived feed */
4177 db_query($link, "BEGIN");
4179 /* prepare feed if necessary */
4181 $result = db_query($link, "SELECT id FROM ttrss_archived_feeds
4184 if (db_num_rows($result) == 0) {
4185 db_query($link, "INSERT INTO ttrss_archived_feeds
4186 (id, owner_uid, title, feed_url, site_url)
4187 SELECT id, owner_uid, title, feed_url, site_url from ttrss_feeds
4191 db_query($link, "UPDATE ttrss_user_entries SET feed_id = NULL,
4192 orig_feed_id = '$id' WHERE feed_id = '$id' AND
4193 marked = true AND owner_uid = $owner_uid");
4195 /* Remove access key for the feed */
4197 db_query($link, "DELETE FROM ttrss_access_keys WHERE
4198 feed_id = '$id' AND owner_uid = $owner_uid");
4200 /* remove the feed */
4202 db_query($link, "DELETE FROM ttrss_feeds
4203 WHERE id = '$id' AND owner_uid = $owner_uid");
4205 db_query($link, "COMMIT");
4207 if (file_exists(ICONS_DIR
. "/$id.ico")) {
4208 unlink(ICONS_DIR
. "/$id.ico");
4211 ccache_remove($link, $id, $owner_uid);
4214 label_remove($link, -11-$id, $owner_uid);
4215 ccache_remove($link, -11-$id, $owner_uid);
4219 function add_feed_category($link, $feed_cat) {
4221 if (!$feed_cat) return false;
4223 db_query($link, "BEGIN");
4225 $result = db_query($link,
4226 "SELECT id FROM ttrss_feed_categories
4227 WHERE title = '$feed_cat' AND owner_uid = ".$_SESSION["uid"]);
4229 if (db_num_rows($result) == 0) {
4231 $result = db_query($link,
4232 "INSERT INTO ttrss_feed_categories (owner_uid,title)
4233 VALUES ('".$_SESSION["uid"]."', '$feed_cat')");
4235 db_query($link, "COMMIT");
4243 function remove_feed_category($link, $id, $owner_uid) {
4245 db_query($link, "DELETE FROM ttrss_feed_categories
4246 WHERE id = '$id' AND owner_uid = $owner_uid");
4248 ccache_remove($link, $id, $owner_uid, true);
4251 function archive_article($link, $id, $owner_uid) {
4252 db_query($link, "BEGIN");
4254 $result = db_query($link, "SELECT feed_id FROM ttrss_user_entries
4255 WHERE ref_id = '$id' AND owner_uid = $owner_uid");
4257 if (db_num_rows($result) != 0) {
4259 /* prepare the archived table */
4261 $feed_id = (int) db_fetch_result($result, 0, "feed_id");
4264 $result = db_query($link, "SELECT id FROM ttrss_archived_feeds
4265 WHERE id = '$feed_id'");
4267 if (db_num_rows($result) == 0) {
4268 db_query($link, "INSERT INTO ttrss_archived_feeds
4269 (id, owner_uid, title, feed_url, site_url)
4270 SELECT id, owner_uid, title, feed_url, site_url from ttrss_feeds
4271 WHERE id = '$feed_id'");
4274 db_query($link, "UPDATE ttrss_user_entries
4275 SET orig_feed_id = feed_id, feed_id = NULL
4276 WHERE ref_id = '$id' AND owner_uid = " . $_SESSION["uid"]);
4280 db_query($link, "COMMIT");
4283 function getArticleFeed($link, $id) {
4284 $result = db_query($link, "SELECT feed_id FROM ttrss_user_entries
4285 WHERE ref_id = '$id' AND owner_uid = " . $_SESSION["uid"]);
4287 if (db_num_rows($result) != 0) {
4288 return db_fetch_result($result, 0, "feed_id");
4295 * Fixes incomplete URLs by prepending "http://".
4296 * Also replaces feed:// with http://, and
4297 * prepends a trailing slash if the url is a domain name only.
4299 * @param string $url Possibly incomplete URL
4301 * @return string Fixed URL.
4303 function fix_url($url) {
4304 if (strpos($url, '://') === false) {
4305 $url = 'http://' . $url;
4306 } else if (substr($url, 0, 5) == 'feed:') {
4307 $url = 'http:' . substr($url, 5);
4310 //prepend slash if the URL has no slash in it
4311 // "http://www.example" -> "http://www.example/"
4312 if (strpos($url, '/', strpos($url, ':') +
3) === false) {
4316 if ($url != "http:///")
4322 function validate_feed_url($url) {
4323 $parts = parse_url($url);
4325 return ($parts['scheme'] == 'http' ||
$parts['scheme'] == 'feed' ||
$parts['scheme'] == 'https');
4329 function get_article_enclosures($link, $id) {
4331 $query = "SELECT * FROM ttrss_enclosures
4332 WHERE post_id = '$id' AND content_url != ''";
4336 $result = db_query($link, $query);
4338 if (db_num_rows($result) > 0) {
4339 while ($line = db_fetch_assoc($result)) {
4340 array_push($rv, $line);
4347 function api_get_feeds($link, $cat_id, $unread_only, $limit, $offset) {
4353 if ($cat_id == -4 ||
$cat_id == -2) {
4354 $counters = getLabelCounters($link, true);
4356 foreach (array_values($counters) as $cv) {
4358 $unread = $cv["counter"];
4360 if ($unread ||
!$unread_only) {
4364 "title" => $cv["description"],
4365 "unread" => $cv["counter"],
4369 array_push($feeds, $row);
4376 if ($cat_id == -4 ||
$cat_id == -1) {
4377 foreach (array(-1, -2, -3, -4, 0) as $i) {
4378 $unread = getFeedUnread($link, $i);
4380 if ($unread ||
!$unread_only) {
4381 $title = getFeedTitle($link, $i);
4386 "unread" => $unread,
4389 array_push($feeds, $row);
4398 $limit_qpart = "LIMIT $limit OFFSET $offset";
4403 if ($cat_id == -4 ||
$cat_id == -3) {
4404 $result = db_query($link, "SELECT
4405 id, feed_url, cat_id, title, order_id, ".
4406 SUBSTRING_FOR_DATE
."(last_updated,1,19) AS last_updated
4407 FROM ttrss_feeds WHERE owner_uid = " . $_SESSION["uid"] .
4408 " ORDER BY cat_id, title " . $limit_qpart);
4412 $cat_qpart = "cat_id = '$cat_id'";
4414 $cat_qpart = "cat_id IS NULL";
4416 $result = db_query($link, "SELECT
4417 id, feed_url, cat_id, title, order_id, ".
4418 SUBSTRING_FOR_DATE
."(last_updated,1,19) AS last_updated
4419 FROM ttrss_feeds WHERE
4420 $cat_qpart AND owner_uid = " . $_SESSION["uid"] .
4421 " ORDER BY cat_id, title " . $limit_qpart);
4424 while ($line = db_fetch_assoc($result)) {
4426 $unread = getFeedUnread($link, $line["id"]);
4428 $has_icon = feed_has_icon($line['id']);
4430 if ($unread ||
!$unread_only) {
4433 "feed_url" => $line["feed_url"],
4434 "title" => $line["title"],
4435 "id" => (int)$line["id"],
4436 "unread" => (int)$unread,
4437 "has_icon" => $has_icon,
4438 "cat_id" => (int)$line["cat_id"],
4439 "last_updated" => strtotime($line["last_updated"]),
4440 "order_id" => (int) $line["order_id"],
4443 array_push($feeds, $row);
4450 function api_get_headlines($link, $feed_id, $limit, $offset,
4451 $filter, $is_cat, $show_excerpt, $show_content, $view_mode, $order,
4452 $include_attachments, $since_id,
4453 $search = "", $search_mode = "", $match_on = "") {
4455 $qfh_ret = queryFeedHeadlines($link, $feed_id, $limit,
4456 $view_mode, $is_cat, $search, $search_mode, $match_on,
4457 $order, $offset, 0, false, $since_id);
4459 $result = $qfh_ret[0];
4460 $feed_title = $qfh_ret[1];
4462 $headlines = array();
4464 while ($line = db_fetch_assoc($result)) {
4465 $is_updated = ($line["last_read"] == "" &&
4466 ($line["unread"] != "t" && $line["unread"] != "1"));
4468 $tags = explode(",", $line["tag_cache"]);
4469 $labels = json_decode($line["label_cache"], true);
4471 //if (!$tags) $tags = get_article_tags($link, $line["id"]);
4472 //if (!$labels) $labels = get_article_labels($link, $line["id"]);
4474 $headline_row = array(
4475 "id" => (int)$line["id"],
4476 "unread" => sql_bool_to_bool($line["unread"]),
4477 "marked" => sql_bool_to_bool($line["marked"]),
4478 "published" => sql_bool_to_bool($line["published"]),
4479 "updated" => strtotime($line["updated"]),
4480 "is_updated" => $is_updated,
4481 "title" => $line["title"],
4482 "link" => $line["link"],
4483 "feed_id" => $line["feed_id"],
4487 if ($include_attachments)
4488 $headline_row['attachments'] = get_article_enclosures($link,
4491 if ($show_excerpt) {
4492 $excerpt = truncate_string(strip_tags($line["content_preview"]), 100);
4493 $headline_row["excerpt"] = $excerpt;
4496 if ($show_content) {
4497 $headline_row["content"] = $line["content_preview"];
4500 // unify label output to ease parsing
4501 if ($labels["no-labels"] == 1) $labels = array();
4503 $headline_row["labels"] = $labels;
4505 $headline_row["feed_title"] = $line["feed_title"];
4507 array_push($headlines, $headline_row);
4513 function generate_error_feed($link, $error) {
4516 $reply['headlines']['id'] = -6;
4517 $reply['headlines']['is_cat'] = false;
4519 $reply['headlines']['toolbar'] = '';
4520 $reply['headlines']['content'] = "<div class='whiteBox'>". $error . "</div>";
4522 $reply['headlines-info'] = array("count" => 0,
4523 "vgroup_last_feed" => '',
4525 "disable_cache" => true);
4531 function generate_dashboard_feed($link) {
4534 $reply['headlines']['id'] = -5;
4535 $reply['headlines']['is_cat'] = false;
4537 $reply['headlines']['toolbar'] = '';
4538 $reply['headlines']['content'] = "<div class='whiteBox'>".__('No feed selected.');
4540 $reply['headlines']['content'] .= "<p class=\"small\"><span class=\"insensitive\">";
4542 $result = db_query($link, "SELECT ".SUBSTRING_FOR_DATE
."(MAX(last_updated), 1, 19) AS last_updated FROM ttrss_feeds
4543 WHERE owner_uid = " . $_SESSION['uid']);
4545 $last_updated = db_fetch_result($result, 0, "last_updated");
4546 $last_updated = make_local_datetime($link, $last_updated, false);
4548 $reply['headlines']['content'] .= sprintf(__("Feeds last updated at %s"), $last_updated);
4550 $result = db_query($link, "SELECT COUNT(id) AS num_errors
4551 FROM ttrss_feeds WHERE last_error != '' AND owner_uid = ".$_SESSION["uid"]);
4553 $num_errors = db_fetch_result($result, 0, "num_errors");
4555 if ($num_errors > 0) {
4556 $reply['headlines']['content'] .= "<br/>";
4557 $reply['headlines']['content'] .= "<a class=\"insensitive\" href=\"#\" onclick=\"showFeedsWithErrors()\">".
4558 __('Some feeds have update errors (click for details)')."</a>";
4560 $reply['headlines']['content'] .= "</span></p>";
4562 $reply['headlines-info'] = array("count" => 0,
4563 "vgroup_last_feed" => '',
4565 "disable_cache" => true);
4570 function save_email_address($link, $email) {
4571 // FIXME: implement persistent storage of emails
4573 if (!$_SESSION['stored_emails'])
4574 $_SESSION['stored_emails'] = array();
4576 if (!in_array($email, $_SESSION['stored_emails']))
4577 array_push($_SESSION['stored_emails'], $email);
4580 function update_feed_access_key($link, $feed_id, $is_cat, $owner_uid = false) {
4581 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
4583 $sql_is_cat = bool_to_sql_bool($is_cat);
4585 $result = db_query($link, "SELECT access_key FROM ttrss_access_keys
4586 WHERE feed_id = '$feed_id' AND is_cat = $sql_is_cat
4587 AND owner_uid = " . $owner_uid);
4589 if (db_num_rows($result) == 1) {
4590 $key = db_escape_string(sha1(uniqid(rand(), true)));
4592 db_query($link, "UPDATE ttrss_access_keys SET access_key = '$key'
4593 WHERE feed_id = '$feed_id' AND is_cat = $sql_is_cat
4594 AND owner_uid = " . $owner_uid);
4599 return get_feed_access_key($link, $feed_id, $is_cat, $owner_uid);
4603 function get_feed_access_key($link, $feed_id, $is_cat, $owner_uid = false) {
4605 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
4607 $sql_is_cat = bool_to_sql_bool($is_cat);
4609 $result = db_query($link, "SELECT access_key FROM ttrss_access_keys
4610 WHERE feed_id = '$feed_id' AND is_cat = $sql_is_cat
4611 AND owner_uid = " . $owner_uid);
4613 if (db_num_rows($result) == 1) {
4614 return db_fetch_result($result, 0, "access_key");
4616 $key = db_escape_string(sha1(uniqid(rand(), true)));
4618 $result = db_query($link, "INSERT INTO ttrss_access_keys
4619 (access_key, feed_id, is_cat, owner_uid)
4620 VALUES ('$key', '$feed_id', $sql_is_cat, '$owner_uid')");
4628 * Extracts RSS/Atom feed URLs from the given HTML URL.
4630 * @param string $url HTML page URL
4632 * @return array Array of feeds. Key is the full URL, value the title
4634 function get_feeds_from_html($url, $login = false, $pass = false)
4636 $url = fix_url($url);
4637 $baseUrl = substr($url, 0, strrpos($url, '/') +
1);
4639 libxml_use_internal_errors(true);
4641 $content = @fetch_file_contents
($url, false, $login, $pass);
4643 $doc = new DOMDocument();
4644 $doc->loadHTML($content);
4645 $xpath = new DOMXPath($doc);
4646 $entries = $xpath->query('/html/head/link[@rel="alternate"]');
4647 $feedUrls = array();
4648 foreach ($entries as $entry) {
4649 if ($entry->hasAttribute('href')) {
4650 $title = $entry->getAttribute('title');
4652 $title = $entry->getAttribute('type');
4654 $feedUrl = rewrite_relative_url(
4655 $baseUrl, $entry->getAttribute('href')
4657 $feedUrls[$feedUrl] = $title;
4664 * Checks if the content behind the given URL is a HTML file
4666 * @param string $url URL to check
4668 * @return boolean True if the URL contains HTML content
4670 function url_is_html($url, $login = false, $pass = false) {
4671 $content = substr(fetch_file_contents($url, false, $login, $pass), 0, 1000);
4673 if (stripos($content, '<html>') === false
4674 && stripos($content, '<html ') === false
4682 function print_label_select($link, $name, $value, $attributes = "") {
4684 $result = db_query($link, "SELECT caption FROM ttrss_labels2
4685 WHERE owner_uid = '".$_SESSION["uid"]."' ORDER BY caption");
4687 print "<select default=\"$value\" name=\"" . htmlspecialchars($name) .
4688 "\" $attributes onchange=\"labelSelectOnChange(this)\" >";
4690 while ($line = db_fetch_assoc($result)) {
4692 $issel = ($line["caption"] == $value) ?
"selected=\"1\"" : "";
4694 print "<option value=\"".htmlspecialchars($line["caption"])."\"
4695 $issel>" . htmlspecialchars($line["caption"]) . "</option>";
4699 # print "<option value=\"ADD_LABEL\">" .__("Add label...") . "</option>";
4706 function format_article_enclosures($link, $id, $always_display_enclosures,
4709 $result = get_article_enclosures($link, $id);
4712 if (count($result) > 0) {
4714 $entries_html = array();
4717 foreach ($result as $line) {
4719 $url = $line["content_url"];
4720 $ctype = $line["content_type"];
4722 if (!$ctype) $ctype = __("unknown type");
4724 $filename = substr($url, strrpos($url, "/")+
1);
4726 # $player = format_inline_player($link, $url, $ctype);
4728 # $entry .= " <a target=\"_blank\" href=\"" . htmlspecialchars($url) . "\">" .
4729 # $filename . " (" . $ctype . ")" . "</a>";
4731 $entry = "<div onclick=\"window.open('".htmlspecialchars($url)."')\"
4732 dojoType=\"dijit.MenuItem\">$filename ($ctype)</div>";
4734 array_push($entries_html, $entry);
4738 $entry["type"] = $ctype;
4739 $entry["filename"] = $filename;
4740 $entry["url"] = $url;
4742 array_push($entries, $entry);
4745 if (!get_pref($link, "STRIP_IMAGES")) {
4746 if ($always_display_enclosures ||
4747 !preg_match("/<img/i", $article_content)) {
4749 foreach ($entries as $entry) {
4751 if (preg_match("/image/", $entry["type"]) ||
4752 preg_match("/\.(jpg|png|gif|bmp)/i", $entry["filename"])) {
4755 alt=\"".htmlspecialchars($entry["filename"])."\"
4756 src=\"" .htmlspecialchars($entry["url"]) . "\"/></p>";
4763 $rv .= "<div dojoType=\"dijit.form.DropDownButton\">".
4764 "<span>" . __('Attachments')."</span>";
4765 $rv .= "<div dojoType=\"dijit.Menu\" style=\"display: none;\">";
4767 foreach ($entries_html as $entry) { $rv .= $entry; };
4769 $rv .= "</div></div>";
4775 function getLastArticleId($link) {
4776 $result = db_query($link, "SELECT MAX(ref_id) AS id FROM ttrss_user_entries
4777 WHERE owner_uid = " . $_SESSION["uid"]);
4779 if (db_num_rows($result) == 1) {
4780 return db_fetch_result($result, 0, "id");
4786 function build_url($parts) {
4787 return $parts['scheme'] . "://" . $parts['host'] . $parts['path'];
4791 * Converts a (possibly) relative URL to a absolute one.
4793 * @param string $url Base URL (i.e. from where the document is)
4794 * @param string $rel_url Possibly relative URL in the document
4796 * @return string Absolute URL
4798 function rewrite_relative_url($url, $rel_url) {
4799 if (strpos($rel_url, "magnet:") === 0) {
4801 } else if (strpos($rel_url, "://") !== false) {
4803 } else if (strpos($rel_url, "//") === 0) {
4804 # protocol-relative URL (rare but they exist)
4806 } else if (strpos($rel_url, "/") === 0)
4808 $parts = parse_url($url);
4809 $parts['path'] = $rel_url;
4811 return build_url($parts);
4814 $parts = parse_url($url);
4815 if (!isset($parts['path'])) {
4816 $parts['path'] = '/';
4818 $dir = $parts['path'];
4819 if (substr($dir, -1) !== '/') {
4820 $dir = dirname($parts['path']);
4821 $dir !== '/' && $dir .= '/';
4823 $parts['path'] = $dir . $rel_url;
4825 return build_url($parts);
4829 function sphinx_search($query, $offset = 0, $limit = 30) {
4830 require_once 'lib/sphinxapi.php';
4832 $sphinxClient = new SphinxClient();
4834 $sphinxClient->SetServer('localhost', 9312);
4835 $sphinxClient->SetConnectTimeout(1);
4837 $sphinxClient->SetFieldWeights(array('title' => 70, 'content' => 30,
4838 'feed_title' => 20));
4840 $sphinxClient->SetMatchMode(SPH_MATCH_EXTENDED2
);
4841 $sphinxClient->SetRankingMode(SPH_RANK_PROXIMITY_BM25
);
4842 $sphinxClient->SetLimits($offset, $limit, 1000);
4843 $sphinxClient->SetArrayResult(false);
4844 $sphinxClient->SetFilter('owner_uid', array($_SESSION['uid']));
4846 $result = $sphinxClient->Query($query, SPHINX_INDEX
);
4850 if (is_array($result['matches'])) {
4851 foreach (array_keys($result['matches']) as $int_id) {
4852 $ref_id = $result['matches'][$int_id]['attrs']['ref_id'];
4853 array_push($ids, $ref_id);
4860 function cleanup_tags($link, $days = 14, $limit = 1000) {
4862 if (DB_TYPE
== "pgsql") {
4863 $interval_query = "date_updated < NOW() - INTERVAL '$days days'";
4864 } else if (DB_TYPE
== "mysql") {
4865 $interval_query = "date_updated < DATE_SUB(NOW(), INTERVAL $days DAY)";
4870 while ($limit > 0) {
4873 $query = "SELECT ttrss_tags.id AS id
4874 FROM ttrss_tags, ttrss_user_entries, ttrss_entries
4875 WHERE post_int_id = int_id AND $interval_query AND
4876 ref_id = ttrss_entries.id AND tag_cache != '' LIMIT $limit_part";
4878 $result = db_query($link, $query);
4882 while ($line = db_fetch_assoc($result)) {
4883 array_push($ids, $line['id']);
4886 if (count($ids) > 0) {
4887 $ids = join(",", $ids);
4890 $tmp_result = db_query($link, "DELETE FROM ttrss_tags WHERE id IN ($ids)");
4891 $tags_deleted +
= db_affected_rows($link, $tmp_result);
4896 $limit -= $limit_part;
4901 return $tags_deleted;
4904 function print_user_stylesheet($link) {
4905 $value = get_pref($link, 'USER_STYLESHEET');
4908 print "<style type=\"text/css\">";
4909 print str_replace("<br/>", "\n", $value);
4915 /* function rewrite_urls($line) {
4920 $result = preg_replace("/((?<!=.)((http|https|ftp)+):\/\/[^ ,!]+)/i",
4921 "<a target=\"_blank\" href=\"\\1\">\\1</a>", $line);
4926 function rewrite_urls($html) {
4927 libxml_use_internal_errors(true);
4929 $charset_hack = '<head>
4930 <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
4933 $doc = new DOMDocument();
4934 $doc->loadHTML($charset_hack . $html);
4935 $xpath = new DOMXPath($doc);
4937 $entries = $xpath->query('//*/text()');
4939 foreach ($entries as $entry) {
4940 if (strstr($entry->wholeText
, "://") !== false) {
4941 $text = preg_replace("/((?<!=.)((http|https|ftp)+):\/\/[^ ,!]+)/i",
4942 "<a target=\"_blank\" href=\"\\1\">\\1</a>", $entry->wholeText
);
4944 if ($text != $entry->wholeText
) {
4945 $cdoc = new DOMDocument();
4946 $cdoc->loadHTML($charset_hack . $text);
4949 foreach ($cdoc->childNodes
as $cnode) {
4950 $cnode = $doc->importNode($cnode, true);
4953 $entry->parentNode
->insertBefore($cnode);
4957 $entry->parentNode
->removeChild($entry);
4963 $node = $doc->getElementsByTagName('body')->item(0);
4965 // http://tt-rss.org/forum/viewtopic.php?f=1&t=970
4967 return $doc->saveXML($node, LIBXML_NOEMPTYTAG
);
4972 function filter_to_sql($filter) {
4975 $regexp_valid = preg_match('/' . $filter['reg_exp'] . '/',
4976 $filter['reg_exp']) !== FALSE;
4978 if ($regexp_valid) {
4980 if (DB_TYPE
== "pgsql")
4983 $reg_qpart = "REGEXP";
4985 switch ($filter["type"]) {
4987 $query = "LOWER(ttrss_entries.title) $reg_qpart LOWER('".
4988 $filter['reg_exp'] . "')";
4991 $query = "LOWER(ttrss_entries.content) $reg_qpart LOWER('".
4992 $filter['reg_exp'] . "')";
4995 $query = "LOWER(ttrss_entries.title) $reg_qpart LOWER('".
4996 $filter['reg_exp'] . "') OR LOWER(" .
4997 "ttrss_entries.content) $reg_qpart LOWER('" . $filter['reg_exp'] . "')";
5000 $query = "LOWER(ttrss_user_entries.tag_cache) $reg_qpart LOWER('".
5001 $filter['reg_exp'] . "')";
5004 $query = "LOWER(ttrss_entries.link) $reg_qpart LOWER('".
5005 $filter['reg_exp'] . "')";
5009 if ($filter["filter_param"] == "before")
5014 $timestamp = date("Y-m-d H:N:s", strtotime($filter["reg_exp"]));
5015 $query = "ttrss_entries.date_entered $cmp_qpart '$timestamp'";
5018 $query = "LOWER(ttrss_entries.author) $reg_qpart LOWER('".
5019 $filter['reg_exp'] . "')";
5023 if ($filter["inverse"])
5024 $query = "NOT ($query)";
5027 if (DB_TYPE
== "pgsql") {
5028 $query = " ($query) AND ttrss_entries.date_entered > NOW() - INTERVAL '14 days'";
5030 $query = " ($query) AND ttrss_entries.date_entered > DATE_SUB(NOW(), INTERVAL 14 DAY)";
5042 // -1 - never connected
5043 // 0 - no data received
5044 // 1 - data received successfully
5045 // 2 - did not receive valid data
5046 // >10 - server error, code + 10 (e.g. 16 means server error 6)
5048 function get_linked_feeds($link, $instance_id = false) {
5050 $instance_qpart = "id = '$instance_id' AND ";
5052 $instance_qpart = "";
5054 if (DB_TYPE
== "pgsql") {
5055 $date_qpart = "last_connected < NOW() - INTERVAL '6 hours'";
5057 $date_qpart = "last_connected < DATE_SUB(NOW(), INTERVAL 6 HOUR)";
5060 $result = db_query($link, "SELECT id, access_key, access_url FROM ttrss_linked_instances
5061 WHERE $instance_qpart $date_qpart ORDER BY last_connected");
5063 while ($line = db_fetch_assoc($result)) {
5066 _debug("Updating: " . $line['access_url'] . " ($id)");
5068 $fetch_url = $line['access_url'] . '/public.php?op=fbexport';
5069 $post_query = 'key=' . $line['access_key'];
5071 $feeds = fetch_file_contents($fetch_url, false, false, false, $post_query);
5073 // try doing it the old way
5075 $fetch_url = $line['access_url'] . '/backend.php?op=fbexport';
5076 $feeds = fetch_file_contents($fetch_url, false, false, false, $post_query);
5080 $feeds = json_decode($feeds, true);
5083 if ($feeds['error']) {
5084 $status = $feeds['error']['code'] +
10;
5088 if (count($feeds['feeds']) > 0) {
5090 db_query($link, "DELETE FROM ttrss_linked_feeds
5091 WHERE instance_id = '$id'");
5093 foreach ($feeds['feeds'] as $feed) {
5094 $feed_url = db_escape_string($feed['feed_url']);
5095 $title = db_escape_string($feed['title']);
5096 $subscribers = db_escape_string($feed['subscribers']);
5097 $site_url = db_escape_string($feed['site_url']);
5099 db_query($link, "INSERT INTO ttrss_linked_feeds
5100 (feed_url, site_url, title, subscribers, instance_id, created, updated)
5102 ('$feed_url', '$site_url', '$title', '$subscribers', '$id', NOW(), NOW())");
5105 // received 0 feeds, this might indicate that
5106 // the instance on the other hand is rebuilding feedbrowser cache
5107 // we will try again later
5109 // TODO: maybe perform expiration based on updated here?
5112 _debug("Processed " . count($feeds['feeds']) . " feeds.");
5122 _debug("Status: $status");
5124 db_query($link, "UPDATE ttrss_linked_instances SET
5125 last_status_out = '$status', last_connected = NOW() WHERE id = '$id'");
5130 function make_feed_browser($link, $search, $limit, $mode = 1) {
5132 $owner_uid = $_SESSION["uid"];
5136 $search_qpart = "AND (UPPER(feed_url) LIKE UPPER('%$search%') OR
5137 UPPER(title) LIKE UPPER('%$search%'))";
5143 /* $result = db_query($link, "SELECT feed_url, subscribers FROM
5144 ttrss_feedbrowser_cache WHERE (SELECT COUNT(id) = 0 FROM ttrss_feeds AS tf
5145 WHERE tf.feed_url = ttrss_feedbrowser_cache.feed_url
5146 AND owner_uid = '$owner_uid') $search_qpart
5147 ORDER BY subscribers DESC LIMIT $limit"); */
5149 $result = db_query($link, "SELECT feed_url, site_url, title, SUM(subscribers) AS subscribers FROM
5150 (SELECT feed_url, site_url, title, subscribers FROM ttrss_feedbrowser_cache UNION ALL
5151 SELECT feed_url, site_url, title, subscribers FROM ttrss_linked_feeds) AS qqq
5153 (SELECT COUNT(id) = 0 FROM ttrss_feeds AS tf
5154 WHERE tf.feed_url = qqq.feed_url
5155 AND owner_uid = '$owner_uid') $search_qpart
5156 GROUP BY feed_url, site_url, title ORDER BY subscribers DESC LIMIT $limit");
5158 } else if ($mode == 2) {
5159 $result = db_query($link, "SELECT *,
5160 (SELECT COUNT(*) FROM ttrss_user_entries WHERE
5161 orig_feed_id = ttrss_archived_feeds.id) AS articles_archived
5163 ttrss_archived_feeds
5165 (SELECT COUNT(*) FROM ttrss_feeds
5166 WHERE ttrss_feeds.feed_url = ttrss_archived_feeds.feed_url AND
5167 owner_uid = '$owner_uid') = 0 AND
5168 owner_uid = '$owner_uid' $search_qpart
5169 ORDER BY id DESC LIMIT $limit");
5174 while ($line = db_fetch_assoc($result)) {
5178 $feed_url = htmlspecialchars($line["feed_url"]);
5179 $site_url = htmlspecialchars($line["site_url"]);
5180 $subscribers = $line["subscribers"];
5182 $check_box = "<input onclick='toggleSelectListRow2(this)'
5183 dojoType=\"dijit.form.CheckBox\"
5184 type=\"checkbox\" \">";
5186 $class = ($feedctr %
2) ?
"even" : "odd";
5188 $site_url = "<a target=\"_blank\"
5190 <span class=\"fb_feedTitle\">".
5191 htmlspecialchars($line["title"])."</span></a>";
5193 $feed_url = "<a target=\"_blank\" class=\"fb_feedUrl\"
5194 href=\"$feed_url\"><img src='images/feed-icon-12x12.png'
5195 style='vertical-align : middle'></a>";
5197 $rv .= "<li>$check_box $feed_url $site_url".
5198 " <span class='subscribers'>($subscribers)</span></li>";
5200 } else if ($mode == 2) {
5201 $feed_url = htmlspecialchars($line["feed_url"]);
5202 $site_url = htmlspecialchars($line["site_url"]);
5203 $title = htmlspecialchars($line["title"]);
5205 $check_box = "<input onclick='toggleSelectListRow2(this)' dojoType=\"dijit.form.CheckBox\"
5206 type=\"checkbox\">";
5208 $class = ($feedctr %
2) ?
"even" : "odd";
5210 if ($line['articles_archived'] > 0) {
5211 $archived = sprintf(__("%d archived articles"), $line['articles_archived']);
5212 $archived = " <span class='subscribers'>($archived)</span>";
5217 $site_url = "<a target=\"_blank\"
5219 <span class=\"fb_feedTitle\">".
5220 htmlspecialchars($line["title"])."</span></a>";
5222 $feed_url = "<a target=\"_blank\" class=\"fb_feedUrl\"
5223 href=\"$feed_url\"><img src='images/feed-icon-12x12.png'
5224 style='vertical-align : middle'></a>";
5227 $rv .= "<li id=\"FBROW-".$line["id"]."\">".
5228 "$check_box $feed_url $site_url $archived</li>";
5234 if ($feedctr == 0) {
5235 $rv .= "<li style=\"text-align : center\"><p>".__('No feeds found.')."</p></li>";
5241 if (!function_exists('gzdecode')) {
5242 function gzdecode($string) { // no support for 2nd argument
5243 return file_get_contents('compress.zlib://data:who/cares;base64,'.
5244 base64_encode($string));
5248 function perform_data_import($link, $filename, $owner_uid) {
5252 $num_feeds_created = 0;
5254 $doc = @DOMDocument
::load($filename);
5257 $contents = file_get_contents($filename);
5260 $data = @gzuncompress
($contents);
5264 $data = @gzdecode
($contents);
5268 $doc = DOMDocument
::loadXML($data);
5273 $xpath = new DOMXpath($doc);
5275 $container = $doc->firstChild
;
5277 if ($container && $container->hasAttribute('schema-version')) {
5278 $schema_version = $container->getAttribute('schema-version');
5280 if ($schema_version != SCHEMA_VERSION
) {
5281 print "<p>" .__("Could not import: incorrect schema version.") . "</p>";
5286 print "<p>" . __("Could not import: unrecognized document format.") . "</p>";
5290 $articles = $xpath->query("//article");
5292 foreach ($articles as $article_node) {
5293 if ($article_node->childNodes
) {
5299 foreach ($article_node->childNodes
as $child) {
5300 if ($child->nodeName
!= 'label_cache')
5301 $article[$child->nodeName
] = db_escape_string($child->nodeValue
);
5303 $article[$child->nodeName
] = $child->nodeValue
;
5306 //print_r($article);
5308 if ($article['guid']) {
5312 //db_query($link, "BEGIN");
5314 //print 'GUID:' . $article['guid'] . "\n";
5316 $result = db_query($link, "SELECT id FROM ttrss_entries
5317 WHERE guid = '".$article['guid']."'");
5319 if (db_num_rows($result) == 0) {
5321 $result = db_query($link,
5322 "INSERT INTO ttrss_entries
5336 ('".$article['title']."',
5337 '".$article['guid']."',
5338 '".$article['link']."',
5339 '".$article['updated']."',
5340 '".$article['content']."',
5341 '".sha1($article['content'])."',
5349 $result = db_query($link, "SELECT id FROM ttrss_entries
5350 WHERE guid = '".$article['guid']."'");
5352 if (db_num_rows($result) != 0) {
5353 $ref_id = db_fetch_result($result, 0, "id");
5357 $ref_id = db_fetch_result($result, 0, "id");
5360 //print "Got ref ID: $ref_id\n";
5364 $feed_url = $article['feed_url'];
5365 $feed_title = $article['feed_title'];
5369 if ($feed_url && $feed_title) {
5370 $result = db_query($link, "SELECT id FROM ttrss_feeds
5371 WHERE feed_url = '$feed_url' AND owner_uid = '$owner_uid'");
5373 if (db_num_rows($result) != 0) {
5374 $feed = db_fetch_result($result, 0, "id");
5376 // try autocreating feed in Uncategorized...
5378 $result = db_query($link, "INSERT INTO ttrss_feeds (owner_uid,
5379 feed_url, title) VALUES ($owner_uid, '$feed_url', '$feed_title')");
5381 $result = db_query($link, "SELECT id FROM ttrss_feeds
5382 WHERE feed_url = '$feed_url' AND owner_uid = '$owner_uid'");
5384 if (db_num_rows($result) != 0) {
5385 ++
$num_feeds_created;
5387 $feed = db_fetch_result($result, 0, "id");
5392 if ($feed != 'NULL')
5393 $feed_qpart = "feed_id = $feed";
5395 $feed_qpart = "feed_id IS NULL";
5397 //print "$ref_id / $feed / " . $article['title'] . "\n";
5399 $result = db_query($link, "SELECT int_id FROM ttrss_user_entries
5400 WHERE ref_id = '$ref_id' AND owner_uid = '$owner_uid' AND $feed_qpart");
5402 if (db_num_rows($result) == 0) {
5404 $marked = bool_to_sql_bool(sql_bool_to_bool($article['marked']));
5405 $published = bool_to_sql_bool(sql_bool_to_bool($article['published']));
5406 $score = (int) $article['score'];
5408 $tag_cache = $article['tag_cache'];
5409 $label_cache = db_escape_string($article['label_cache']);
5410 $note = $article['note'];
5412 //print "Importing " . $article['title'] . "<br/>";
5416 $result = db_query($link,
5417 "INSERT INTO ttrss_user_entries
5418 (ref_id, owner_uid, feed_id, unread, last_read, marked,
5419 published, score, tag_cache, label_cache, uuid, note)
5420 VALUES ($ref_id, $owner_uid, $feed, false,
5421 NULL, $marked, $published, $score, '$tag_cache',
5422 '$label_cache', '', '$note')");
5424 $label_cache = json_decode($label_cache, true);
5426 if (is_array($label_cache) && $label_cache["no-labels"] != 1) {
5427 foreach ($label_cache as $label) {
5429 label_create($link, $label[1],
5430 $label[2], $label[3], $owner_uid);
5432 label_add_article($link, $ref_id, $label[1], $owner_uid);
5437 //db_query($link, "COMMIT");
5445 T_sprintf("Finished: %d articles processed, %d imported, %d feeds created.",
5446 $num_processed, $num_imported, $num_feeds_created) .
5451 print "<p>" . __("Could not load XML document.") . "</p>";
5456 function get_random_bytes($length) {
5457 if (function_exists('openssl_random_pseudo_bytes')) {
5458 return openssl_random_pseudo_bytes($length);
5462 for ($i = 0; $i < $length; $i++
)
5463 $output .= chr(mt_rand(0, 255));