PageRenderTime 58ms CodeModel.GetById 18ms RepoModel.GetById 0ms app.codeStats 1ms

/include/functions.php

https://github.com/krihal/Tiny-Tiny-RSS
PHP | 4073 lines | 3012 code | 886 blank | 175 comment | 748 complexity | 77e36cc88bc25237d05805388ee41014 MD5 | raw file
Possible License(s): BSD-3-Clause, LGPL-2.0, LGPL-3.0, GPL-2.0
  1. <?php
  2. define('EXPECTED_CONFIG_VERSION', 26);
  3. define('SCHEMA_VERSION', 106);
  4. $fetch_last_error = false;
  5. $pluginhost = false;
  6. function __autoload($class) {
  7. $class_file = str_replace("_", "/", strtolower(basename($class)));
  8. $file = dirname(__FILE__)."/../classes/$class_file.php";
  9. if (file_exists($file)) {
  10. require $file;
  11. }
  12. }
  13. mb_internal_encoding("UTF-8");
  14. date_default_timezone_set('UTC');
  15. if (defined('E_DEPRECATED')) {
  16. error_reporting(E_ALL & ~E_NOTICE & ~E_DEPRECATED);
  17. } else {
  18. error_reporting(E_ALL & ~E_NOTICE);
  19. }
  20. require_once 'config.php';
  21. if (DB_TYPE == "pgsql") {
  22. define('SUBSTRING_FOR_DATE', 'SUBSTRING_FOR_DATE');
  23. } else {
  24. define('SUBSTRING_FOR_DATE', 'SUBSTRING');
  25. }
  26. define('THEME_VERSION_REQUIRED', 1.1);
  27. /**
  28. * Return available translations names.
  29. *
  30. * @access public
  31. * @return array A array of available translations.
  32. */
  33. function get_translations() {
  34. $tr = array(
  35. "auto" => "Detect automatically",
  36. "ca_CA" => "Català",
  37. "en_US" => "English",
  38. "es_ES" => "Español",
  39. "de_DE" => "Deutsch",
  40. "fr_FR" => "Français",
  41. "hu_HU" => "Magyar (Hungarian)",
  42. "it_IT" => "Italiano",
  43. "ja_JP" => "日本語 (Japanese)",
  44. "lv_LV" => "Latviešu",
  45. "nb_NO" => "Norwegian bokmål",
  46. "pl_PL" => "Polski",
  47. "ru_RU" => "Русский",
  48. "pt_BR" => "Portuguese/Brazil",
  49. "zh_CN" => "Simplified Chinese");
  50. return $tr;
  51. }
  52. require_once "lib/accept-to-gettext.php";
  53. require_once "lib/gettext/gettext.inc";
  54. function startup_gettext() {
  55. # Get locale from Accept-Language header
  56. $lang = al2gt(array_keys(get_translations()), "text/html");
  57. if (defined('_TRANSLATION_OVERRIDE_DEFAULT')) {
  58. $lang = _TRANSLATION_OVERRIDE_DEFAULT;
  59. }
  60. /* In login action of mobile version */
  61. if ($_POST["language"] && defined('MOBILE_VERSION')) {
  62. $lang = $_POST["language"];
  63. } else if ($_SESSION["language"] && $_SESSION["language"] != "auto") {
  64. $lang = $_SESSION["language"];
  65. }
  66. if ($lang) {
  67. if (defined('LC_MESSAGES')) {
  68. _setlocale(LC_MESSAGES, $lang);
  69. } else if (defined('LC_ALL')) {
  70. _setlocale(LC_ALL, $lang);
  71. }
  72. if (defined('MOBILE_VERSION')) {
  73. _bindtextdomain("messages", "../locale");
  74. } else {
  75. _bindtextdomain("messages", "locale");
  76. }
  77. _textdomain("messages");
  78. _bind_textdomain_codeset("messages", "UTF-8");
  79. }
  80. }
  81. startup_gettext();
  82. require_once 'db-prefs.php';
  83. require_once 'version.php';
  84. require_once 'ccache.php';
  85. require_once 'labels.php';
  86. define('SELF_USER_AGENT', 'Tiny Tiny RSS/' . VERSION . ' (http://tt-rss.org/)');
  87. ini_set('user_agent', SELF_USER_AGENT);
  88. require_once 'lib/pubsubhubbub/publisher.php';
  89. $tz_offset = -1;
  90. $utc_tz = new DateTimeZone('UTC');
  91. $schema_version = false;
  92. /**
  93. * Print a timestamped debug message.
  94. *
  95. * @param string $msg The debug message.
  96. * @return void
  97. */
  98. function _debug($msg) {
  99. if (defined('QUIET') && QUIET) {
  100. return;
  101. }
  102. $ts = strftime("%H:%M:%S", time());
  103. if (function_exists('posix_getpid')) {
  104. $ts = "$ts/" . posix_getpid();
  105. }
  106. print "[$ts] $msg\n";
  107. } // function _debug
  108. /**
  109. * Purge a feed old posts.
  110. *
  111. * @param mixed $link A database connection.
  112. * @param mixed $feed_id The id of the purged feed.
  113. * @param mixed $purge_interval Olderness of purged posts.
  114. * @param boolean $debug Set to True to enable the debug. False by default.
  115. * @access public
  116. * @return void
  117. */
  118. function purge_feed($link, $feed_id, $purge_interval, $debug = false) {
  119. if (!$purge_interval) $purge_interval = feed_purge_interval($link, $feed_id);
  120. $rows = -1;
  121. $result = db_query($link,
  122. "SELECT owner_uid FROM ttrss_feeds WHERE id = '$feed_id'");
  123. $owner_uid = false;
  124. if (db_num_rows($result) == 1) {
  125. $owner_uid = db_fetch_result($result, 0, "owner_uid");
  126. }
  127. if ($purge_interval == -1 || !$purge_interval) {
  128. if ($owner_uid) {
  129. ccache_update($link, $feed_id, $owner_uid);
  130. }
  131. return;
  132. }
  133. if (!$owner_uid) return;
  134. if (FORCE_ARTICLE_PURGE == 0) {
  135. $purge_unread = get_pref($link, "PURGE_UNREAD_ARTICLES",
  136. $owner_uid, false);
  137. } else {
  138. $purge_unread = true;
  139. $purge_interval = FORCE_ARTICLE_PURGE;
  140. }
  141. if (!$purge_unread) $query_limit = " unread = false AND ";
  142. if (DB_TYPE == "pgsql") {
  143. $pg_version = get_pgsql_version($link);
  144. if (preg_match("/^7\./", $pg_version) || preg_match("/^8\.0/", $pg_version)) {
  145. $result = db_query($link, "DELETE FROM ttrss_user_entries WHERE
  146. ttrss_entries.id = ref_id AND
  147. marked = false AND
  148. feed_id = '$feed_id' AND
  149. $query_limit
  150. ttrss_entries.date_updated < NOW() - INTERVAL '$purge_interval days'");
  151. } else {
  152. $result = db_query($link, "DELETE FROM ttrss_user_entries
  153. USING ttrss_entries
  154. WHERE ttrss_entries.id = ref_id AND
  155. marked = false AND
  156. feed_id = '$feed_id' AND
  157. $query_limit
  158. ttrss_entries.date_updated < NOW() - INTERVAL '$purge_interval days'");
  159. }
  160. $rows = pg_affected_rows($result);
  161. } else {
  162. /* $result = db_query($link, "DELETE FROM ttrss_user_entries WHERE
  163. marked = false AND feed_id = '$feed_id' AND
  164. (SELECT date_updated FROM ttrss_entries WHERE
  165. id = ref_id) < DATE_SUB(NOW(), INTERVAL $purge_interval DAY)"); */
  166. $result = db_query($link, "DELETE FROM ttrss_user_entries
  167. USING ttrss_user_entries, ttrss_entries
  168. WHERE ttrss_entries.id = ref_id AND
  169. marked = false AND
  170. feed_id = '$feed_id' AND
  171. $query_limit
  172. ttrss_entries.date_updated < DATE_SUB(NOW(), INTERVAL $purge_interval DAY)");
  173. $rows = mysql_affected_rows($link);
  174. }
  175. ccache_update($link, $feed_id, $owner_uid);
  176. if ($debug) {
  177. _debug("Purged feed $feed_id ($purge_interval): deleted $rows articles");
  178. }
  179. return $rows;
  180. } // function purge_feed
  181. function feed_purge_interval($link, $feed_id) {
  182. $result = db_query($link, "SELECT purge_interval, owner_uid FROM ttrss_feeds
  183. WHERE id = '$feed_id'");
  184. if (db_num_rows($result) == 1) {
  185. $purge_interval = db_fetch_result($result, 0, "purge_interval");
  186. $owner_uid = db_fetch_result($result, 0, "owner_uid");
  187. if ($purge_interval == 0) $purge_interval = get_pref($link,
  188. 'PURGE_OLD_DAYS', $owner_uid);
  189. return $purge_interval;
  190. } else {
  191. return -1;
  192. }
  193. }
  194. function purge_orphans($link, $do_output = false) {
  195. // purge orphaned posts in main content table
  196. $result = db_query($link, "DELETE FROM ttrss_entries WHERE
  197. (SELECT COUNT(int_id) FROM ttrss_user_entries WHERE ref_id = id) = 0");
  198. if ($do_output) {
  199. $rows = db_affected_rows($link, $result);
  200. _debug("Purged $rows orphaned posts.");
  201. }
  202. }
  203. function get_feed_update_interval($link, $feed_id) {
  204. $result = db_query($link, "SELECT owner_uid, update_interval FROM
  205. ttrss_feeds WHERE id = '$feed_id'");
  206. if (db_num_rows($result) == 1) {
  207. $update_interval = db_fetch_result($result, 0, "update_interval");
  208. $owner_uid = db_fetch_result($result, 0, "owner_uid");
  209. if ($update_interval != 0) {
  210. return $update_interval;
  211. } else {
  212. return get_pref($link, 'DEFAULT_UPDATE_INTERVAL', $owner_uid, false);
  213. }
  214. } else {
  215. return -1;
  216. }
  217. }
  218. function fetch_file_contents($url, $type = false, $login = false, $pass = false, $post_query = false, $timeout = false) {
  219. $login = urlencode($login);
  220. $pass = urlencode($pass);
  221. global $fetch_last_error;
  222. if (function_exists('curl_init') && !ini_get("open_basedir")) {
  223. if (ini_get("safe_mode")) {
  224. $ch = curl_init(geturl($url));
  225. } else {
  226. $ch = curl_init($url);
  227. }
  228. curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout ? $timeout : 15);
  229. curl_setopt($ch, CURLOPT_TIMEOUT, $timeout ? $timeout : 45);
  230. curl_setopt($ch, CURLOPT_FOLLOWLOCATION, !ini_get("safe_mode"));
  231. curl_setopt($ch, CURLOPT_MAXREDIRS, 20);
  232. curl_setopt($ch, CURLOPT_BINARYTRANSFER, true);
  233. curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  234. curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
  235. curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
  236. curl_setopt($ch, CURLOPT_USERAGENT, SELF_USER_AGENT);
  237. curl_setopt($ch, CURLOPT_ENCODING , "gzip");
  238. curl_setopt($ch, CURLOPT_REFERER, $url);
  239. if ($post_query) {
  240. curl_setopt($ch, CURLOPT_POST, true);
  241. curl_setopt($ch, CURLOPT_POSTFIELDS, $post_query);
  242. }
  243. if ($login && $pass)
  244. curl_setopt($ch, CURLOPT_USERPWD, "$login:$pass");
  245. $contents = @curl_exec($ch);
  246. if (curl_errno($ch) === 23 || curl_errno($ch) === 61) {
  247. curl_setopt($ch, CURLOPT_ENCODING, 'none');
  248. $contents = @curl_exec($ch);
  249. }
  250. if ($contents === false) {
  251. $fetch_last_error = curl_errno($ch) . " " . curl_error($ch);
  252. curl_close($ch);
  253. return false;
  254. }
  255. $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
  256. $content_type = curl_getinfo($ch, CURLINFO_CONTENT_TYPE);
  257. if ($http_code != 200 || $type && strpos($content_type, "$type") === false) {
  258. if (curl_errno($ch) != 0) {
  259. $fetch_last_error = curl_errno($ch) . " " . curl_error($ch);
  260. } else {
  261. $fetch_last_error = "HTTP Code: $http_code";
  262. }
  263. curl_close($ch);
  264. return false;
  265. }
  266. curl_close($ch);
  267. return $contents;
  268. } else {
  269. if ($login && $pass ){
  270. $url_parts = array();
  271. preg_match("/(^[^:]*):\/\/(.*)/", $url, $url_parts);
  272. if ($url_parts[1] && $url_parts[2]) {
  273. $url = $url_parts[1] . "://$login:$pass@" . $url_parts[2];
  274. }
  275. }
  276. $data = @file_get_contents($url);
  277. $gzdecoded = gzdecode($data);
  278. if ($gzdecoded) $data = $gzdecoded;
  279. if (!$data && function_exists('error_get_last')) {
  280. $error = error_get_last();
  281. $fetch_last_error = $error["message"];
  282. }
  283. return $data;
  284. }
  285. }
  286. /**
  287. * Try to determine the favicon URL for a feed.
  288. * adapted from wordpress favicon plugin by Jeff Minard (http://thecodepro.com/)
  289. * http://dev.wp-plugins.org/file/favatars/trunk/favatars.php
  290. *
  291. * @param string $url A feed or page URL
  292. * @access public
  293. * @return mixed The favicon URL, or false if none was found.
  294. */
  295. function get_favicon_url($url) {
  296. $favicon_url = false;
  297. if ($html = @fetch_file_contents($url)) {
  298. libxml_use_internal_errors(true);
  299. $doc = new DOMDocument();
  300. $doc->loadHTML($html);
  301. $xpath = new DOMXPath($doc);
  302. $base = $xpath->query('/html/head/base');
  303. foreach ($base as $b) {
  304. $url = $b->getAttribute("href");
  305. break;
  306. }
  307. $entries = $xpath->query('/html/head/link[@rel="shortcut icon" or @rel="icon"]');
  308. if (count($entries) > 0) {
  309. foreach ($entries as $entry) {
  310. $favicon_url = rewrite_relative_url($url, $entry->getAttribute("href"));
  311. break;
  312. }
  313. }
  314. }
  315. if (!$favicon_url)
  316. $favicon_url = rewrite_relative_url($url, "/favicon.ico");
  317. return $favicon_url;
  318. } // function get_favicon_url
  319. function check_feed_favicon($site_url, $feed, $link) {
  320. # print "FAVICON [$site_url]: $favicon_url\n";
  321. $icon_file = ICONS_DIR . "/$feed.ico";
  322. if (!file_exists($icon_file)) {
  323. $favicon_url = get_favicon_url($site_url);
  324. if ($favicon_url) {
  325. // Limiting to "image" type misses those served with text/plain
  326. $contents = fetch_file_contents($favicon_url); // , "image");
  327. if ($contents) {
  328. // Crude image type matching.
  329. // Patterns gleaned from the file(1) source code.
  330. if (preg_match('/^\x00\x00\x01\x00/', $contents)) {
  331. // 0 string \000\000\001\000 MS Windows icon resource
  332. //error_log("check_feed_favicon: favicon_url=$favicon_url isa MS Windows icon resource");
  333. }
  334. elseif (preg_match('/^GIF8/', $contents)) {
  335. // 0 string GIF8 GIF image data
  336. //error_log("check_feed_favicon: favicon_url=$favicon_url isa GIF image");
  337. }
  338. elseif (preg_match('/^\x89PNG\x0d\x0a\x1a\x0a/', $contents)) {
  339. // 0 string \x89PNG\x0d\x0a\x1a\x0a PNG image data
  340. //error_log("check_feed_favicon: favicon_url=$favicon_url isa PNG image");
  341. }
  342. elseif (preg_match('/^\xff\xd8/', $contents)) {
  343. // 0 beshort 0xffd8 JPEG image data
  344. //error_log("check_feed_favicon: favicon_url=$favicon_url isa JPG image");
  345. }
  346. else {
  347. //error_log("check_feed_favicon: favicon_url=$favicon_url isa UNKNOWN type");
  348. $contents = "";
  349. }
  350. }
  351. if ($contents) {
  352. $fp = @fopen($icon_file, "w");
  353. if ($fp) {
  354. fwrite($fp, $contents);
  355. fclose($fp);
  356. chmod($icon_file, 0644);
  357. }
  358. }
  359. }
  360. }
  361. }
  362. function print_select($id, $default, $values, $attributes = "") {
  363. print "<select name=\"$id\" id=\"$id\" $attributes>";
  364. foreach ($values as $v) {
  365. if ($v == $default)
  366. $sel = "selected=\"1\"";
  367. else
  368. $sel = "";
  369. $v = trim($v);
  370. print "<option value=\"$v\" $sel>$v</option>";
  371. }
  372. print "</select>";
  373. }
  374. function print_select_hash($id, $default, $values, $attributes = "") {
  375. print "<select name=\"$id\" id='$id' $attributes>";
  376. foreach (array_keys($values) as $v) {
  377. if ($v == $default)
  378. $sel = 'selected="selected"';
  379. else
  380. $sel = "";
  381. $v = trim($v);
  382. print "<option $sel value=\"$v\">".$values[$v]."</option>";
  383. }
  384. print "</select>";
  385. }
  386. function print_radio($id, $default, $true_is, $values, $attributes = "") {
  387. foreach ($values as $v) {
  388. if ($v == $default)
  389. $sel = "checked";
  390. else
  391. $sel = "";
  392. if ($v == $true_is) {
  393. $sel .= " value=\"1\"";
  394. } else {
  395. $sel .= " value=\"0\"";
  396. }
  397. print "<input class=\"noborder\" dojoType=\"dijit.form.RadioButton\"
  398. type=\"radio\" $sel $attributes name=\"$id\">&nbsp;$v&nbsp;";
  399. }
  400. }
  401. function initialize_user_prefs($link, $uid, $profile = false) {
  402. $uid = db_escape_string($uid);
  403. if (!$profile) {
  404. $profile = "NULL";
  405. $profile_qpart = "AND profile IS NULL";
  406. } else {
  407. $profile_qpart = "AND profile = '$profile'";
  408. }
  409. if (get_schema_version($link) < 63) $profile_qpart = "";
  410. db_query($link, "BEGIN");
  411. $result = db_query($link, "SELECT pref_name,def_value FROM ttrss_prefs");
  412. $u_result = db_query($link, "SELECT pref_name
  413. FROM ttrss_user_prefs WHERE owner_uid = '$uid' $profile_qpart");
  414. $active_prefs = array();
  415. while ($line = db_fetch_assoc($u_result)) {
  416. array_push($active_prefs, $line["pref_name"]);
  417. }
  418. while ($line = db_fetch_assoc($result)) {
  419. if (array_search($line["pref_name"], $active_prefs) === FALSE) {
  420. // print "adding " . $line["pref_name"] . "<br>";
  421. if (get_schema_version($link) < 63) {
  422. db_query($link, "INSERT INTO ttrss_user_prefs
  423. (owner_uid,pref_name,value) VALUES
  424. ('$uid', '".$line["pref_name"]."','".$line["def_value"]."')");
  425. } else {
  426. db_query($link, "INSERT INTO ttrss_user_prefs
  427. (owner_uid,pref_name,value, profile) VALUES
  428. ('$uid', '".$line["pref_name"]."','".$line["def_value"]."', $profile)");
  429. }
  430. }
  431. }
  432. db_query($link, "COMMIT");
  433. }
  434. function get_ssl_certificate_id() {
  435. if ($_SERVER["REDIRECT_SSL_CLIENT_M_SERIAL"]) {
  436. return sha1($_SERVER["REDIRECT_SSL_CLIENT_M_SERIAL"] .
  437. $_SERVER["REDIRECT_SSL_CLIENT_V_START"] .
  438. $_SERVER["REDIRECT_SSL_CLIENT_V_END"] .
  439. $_SERVER["REDIRECT_SSL_CLIENT_S_DN"]);
  440. }
  441. return "";
  442. }
  443. function authenticate_user($link, $login, $password, $check_only = false) {
  444. if (!SINGLE_USER_MODE) {
  445. $user_id = false;
  446. global $pluginhost;
  447. foreach ($pluginhost->get_hooks($pluginhost::HOOK_AUTH_USER) as $plugin) {
  448. $user_id = (int) $plugin->authenticate($login, $password);
  449. if ($user_id) {
  450. $_SESSION["auth_module"] = strtolower(get_class($plugin));
  451. break;
  452. }
  453. }
  454. if ($user_id && !$check_only) {
  455. $_SESSION["uid"] = $user_id;
  456. $result = db_query($link, "SELECT login,access_level,pwd_hash FROM ttrss_users
  457. WHERE id = '$user_id'");
  458. $_SESSION["name"] = db_fetch_result($result, 0, "login");
  459. $_SESSION["access_level"] = db_fetch_result($result, 0, "access_level");
  460. $_SESSION["csrf_token"] = sha1(uniqid(rand(), true));
  461. db_query($link, "UPDATE ttrss_users SET last_login = NOW() WHERE id = " .
  462. $_SESSION["uid"]);
  463. $_SESSION["ip_address"] = $_SERVER["REMOTE_ADDR"];
  464. $_SESSION["pwd_hash"] = db_fetch_result($result, 0, "pwd_hash");
  465. $_SESSION["last_version_check"] = time();
  466. initialize_user_prefs($link, $_SESSION["uid"]);
  467. return true;
  468. }
  469. return false;
  470. } else {
  471. $_SESSION["uid"] = 1;
  472. $_SESSION["name"] = "admin";
  473. $_SESSION["access_level"] = 10;
  474. $_SESSION["hide_hello"] = true;
  475. $_SESSION["hide_logout"] = true;
  476. $_SESSION["auth_module"] = false;
  477. if (!$_SESSION["csrf_token"]) {
  478. $_SESSION["csrf_token"] = sha1(uniqid(rand(), true));
  479. }
  480. $_SESSION["ip_address"] = $_SERVER["REMOTE_ADDR"];
  481. initialize_user_prefs($link, $_SESSION["uid"]);
  482. return true;
  483. }
  484. }
  485. function make_password($length = 8) {
  486. $password = "";
  487. $possible = "0123456789abcdfghjkmnpqrstvwxyzABCDFGHJKMNPQRSTVWXYZ";
  488. $i = 0;
  489. while ($i < $length) {
  490. $char = substr($possible, mt_rand(0, strlen($possible)-1), 1);
  491. if (!strstr($password, $char)) {
  492. $password .= $char;
  493. $i++;
  494. }
  495. }
  496. return $password;
  497. }
  498. // this is called after user is created to initialize default feeds, labels
  499. // or whatever else
  500. // user preferences are checked on every login, not here
  501. function initialize_user($link, $uid) {
  502. db_query($link, "insert into ttrss_feeds (owner_uid,title,feed_url)
  503. values ('$uid', 'Tiny Tiny RSS: New Releases',
  504. 'http://tt-rss.org/releases.rss')");
  505. db_query($link, "insert into ttrss_feeds (owner_uid,title,feed_url)
  506. values ('$uid', 'Tiny Tiny RSS: Forum',
  507. 'http://tt-rss.org/forum/rss.php')");
  508. }
  509. function logout_user() {
  510. session_destroy();
  511. if (isset($_COOKIE[session_name()])) {
  512. setcookie(session_name(), '', time()-42000, '/');
  513. }
  514. }
  515. function validate_csrf($csrf_token) {
  516. return $csrf_token == $_SESSION['csrf_token'];
  517. }
  518. function validate_session($link) {
  519. if (SINGLE_USER_MODE) return true;
  520. $check_ip = $_SESSION['ip_address'];
  521. switch (SESSION_CHECK_ADDRESS) {
  522. case 0:
  523. $check_ip = '';
  524. break;
  525. case 1:
  526. $check_ip = substr($check_ip, 0, strrpos($check_ip, '.')+1);
  527. break;
  528. case 2:
  529. $check_ip = substr($check_ip, 0, strrpos($check_ip, '.'));
  530. $check_ip = substr($check_ip, 0, strrpos($check_ip, '.')+1);
  531. break;
  532. };
  533. if ($check_ip && strpos($_SERVER['REMOTE_ADDR'], $check_ip) !== 0) {
  534. $_SESSION["login_error_msg"] =
  535. __("Session failed to validate (incorrect IP)");
  536. return false;
  537. }
  538. if ($_SESSION["ref_schema_version"] != get_schema_version($link, true))
  539. return false;
  540. if ($_SESSION["uid"]) {
  541. $result = db_query($link,
  542. "SELECT pwd_hash FROM ttrss_users WHERE id = '".$_SESSION["uid"]."'");
  543. $pwd_hash = db_fetch_result($result, 0, "pwd_hash");
  544. if ($pwd_hash != $_SESSION["pwd_hash"]) {
  545. return false;
  546. }
  547. }
  548. /* if ($_SESSION["cookie_lifetime"] && $_SESSION["uid"]) {
  549. //print_r($_SESSION);
  550. if (time() > $_SESSION["cookie_lifetime"]) {
  551. return false;
  552. }
  553. } */
  554. return true;
  555. }
  556. function load_user_plugins($link, $owner_uid) {
  557. if ($owner_uid) {
  558. $plugins = get_pref($link, "_ENABLED_PLUGINS", $owner_uid);
  559. global $pluginhost;
  560. $pluginhost->load($plugins, $pluginhost::KIND_USER, $owner_uid);
  561. if (get_schema_version($link) > 100) {
  562. $pluginhost->load_data();
  563. }
  564. }
  565. }
  566. function login_sequence($link, $login_form = 0) {
  567. $_SESSION["prefs_cache"] = false;
  568. if (SINGLE_USER_MODE) {
  569. authenticate_user($link, "admin", null);
  570. cache_prefs($link);
  571. load_user_plugins($link, $_SESSION["uid"]);
  572. } else {
  573. if (!$_SESSION["uid"] || !validate_session($link)) {
  574. if (AUTH_AUTO_LOGIN && authenticate_user($link, null, null)) {
  575. $_SESSION["ref_schema_version"] = get_schema_version($link, true);
  576. } else {
  577. authenticate_user($link, null, null, true);
  578. }
  579. if (!$_SESSION["uid"]) render_login_form($link, $login_form);
  580. } else {
  581. /* bump login timestamp */
  582. db_query($link, "UPDATE ttrss_users SET last_login = NOW() WHERE id = " .
  583. $_SESSION["uid"]);
  584. }
  585. if ($_SESSION["uid"] && $_SESSION["language"] && SESSION_COOKIE_LIFETIME > 0) {
  586. setcookie("ttrss_lang", $_SESSION["language"],
  587. time() + SESSION_COOKIE_LIFETIME);
  588. }
  589. if ($_SESSION["uid"]) {
  590. cache_prefs($link);
  591. load_user_plugins($link, $_SESSION["uid"]);
  592. }
  593. }
  594. }
  595. function truncate_string($str, $max_len, $suffix = '&hellip;') {
  596. if (mb_strlen($str, "utf-8") > $max_len - 3) {
  597. return mb_substr($str, 0, $max_len, "utf-8") . $suffix;
  598. } else {
  599. return $str;
  600. }
  601. }
  602. // Deprecated, TODO: remove
  603. function theme_image($link, $filename) {
  604. return $filename;
  605. }
  606. function convert_timestamp($timestamp, $source_tz, $dest_tz) {
  607. try {
  608. $source_tz = new DateTimeZone($source_tz);
  609. } catch (Exception $e) {
  610. $source_tz = new DateTimeZone('UTC');
  611. }
  612. try {
  613. $dest_tz = new DateTimeZone($dest_tz);
  614. } catch (Exception $e) {
  615. $dest_tz = new DateTimeZone('UTC');
  616. }
  617. $dt = new DateTime(date('Y-m-d H:i:s', $timestamp), $source_tz);
  618. return $dt->format('U') + $dest_tz->getOffset($dt);
  619. }
  620. function make_local_datetime($link, $timestamp, $long, $owner_uid = false,
  621. $no_smart_dt = false) {
  622. if (!$owner_uid) $owner_uid = $_SESSION['uid'];
  623. if (!$timestamp) $timestamp = '1970-01-01 0:00';
  624. global $utc_tz;
  625. global $tz_offset;
  626. # We store date in UTC internally
  627. $dt = new DateTime($timestamp, $utc_tz);
  628. if ($tz_offset == -1) {
  629. $user_tz_string = get_pref($link, 'USER_TIMEZONE', $owner_uid);
  630. try {
  631. $user_tz = new DateTimeZone($user_tz_string);
  632. } catch (Exception $e) {
  633. $user_tz = $utc_tz;
  634. }
  635. $tz_offset = $user_tz->getOffset($dt);
  636. }
  637. $user_timestamp = $dt->format('U') + $tz_offset;
  638. if (!$no_smart_dt) {
  639. return smart_date_time($link, $user_timestamp,
  640. $tz_offset, $owner_uid);
  641. } else {
  642. if ($long)
  643. $format = get_pref($link, 'LONG_DATE_FORMAT', $owner_uid);
  644. else
  645. $format = get_pref($link, 'SHORT_DATE_FORMAT', $owner_uid);
  646. return date($format, $user_timestamp);
  647. }
  648. }
  649. function smart_date_time($link, $timestamp, $tz_offset = 0, $owner_uid = false) {
  650. if (!$owner_uid) $owner_uid = $_SESSION['uid'];
  651. if (date("Y.m.d", $timestamp) == date("Y.m.d", time() + $tz_offset)) {
  652. return date("G:i", $timestamp);
  653. } else if (date("Y", $timestamp) == date("Y", time() + $tz_offset)) {
  654. $format = get_pref($link, 'SHORT_DATE_FORMAT', $owner_uid);
  655. return date($format, $timestamp);
  656. } else {
  657. $format = get_pref($link, 'LONG_DATE_FORMAT', $owner_uid);
  658. return date($format, $timestamp);
  659. }
  660. }
  661. function sql_bool_to_bool($s) {
  662. if ($s == "t" || $s == "1" || strtolower($s) == "true") {
  663. return true;
  664. } else {
  665. return false;
  666. }
  667. }
  668. function bool_to_sql_bool($s) {
  669. if ($s) {
  670. return "true";
  671. } else {
  672. return "false";
  673. }
  674. }
  675. // Session caching removed due to causing wrong redirects to upgrade
  676. // script when get_schema_version() is called on an obsolete session
  677. // created on a previous schema version.
  678. function get_schema_version($link, $nocache = false) {
  679. global $schema_version;
  680. if (!$schema_version) {
  681. $result = db_query($link, "SELECT schema_version FROM ttrss_version");
  682. $version = db_fetch_result($result, 0, "schema_version");
  683. $schema_version = $version;
  684. return $version;
  685. } else {
  686. return $schema_version;
  687. }
  688. }
  689. function sanity_check($link) {
  690. require_once 'errors.php';
  691. $error_code = 0;
  692. $schema_version = get_schema_version($link, true);
  693. if ($schema_version != SCHEMA_VERSION) {
  694. $error_code = 5;
  695. }
  696. if (DB_TYPE == "mysql") {
  697. $result = db_query($link, "SELECT true", false);
  698. if (db_num_rows($result) != 1) {
  699. $error_code = 10;
  700. }
  701. }
  702. if (db_escape_string("testTEST") != "testTEST") {
  703. $error_code = 12;
  704. }
  705. return array("code" => $error_code, "message" => $ERRORS[$error_code]);
  706. }
  707. function file_is_locked($filename) {
  708. if (function_exists('flock')) {
  709. $fp = @fopen(LOCK_DIRECTORY . "/$filename", "r");
  710. if ($fp) {
  711. if (flock($fp, LOCK_EX | LOCK_NB)) {
  712. flock($fp, LOCK_UN);
  713. fclose($fp);
  714. return false;
  715. }
  716. fclose($fp);
  717. return true;
  718. } else {
  719. return false;
  720. }
  721. }
  722. return true; // consider the file always locked and skip the test
  723. }
  724. function make_lockfile($filename) {
  725. $fp = fopen(LOCK_DIRECTORY . "/$filename", "w");
  726. if ($fp && flock($fp, LOCK_EX | LOCK_NB)) {
  727. if (function_exists('posix_getpid')) {
  728. fwrite($fp, posix_getpid() . "\n");
  729. }
  730. return $fp;
  731. } else {
  732. return false;
  733. }
  734. }
  735. function make_stampfile($filename) {
  736. $fp = fopen(LOCK_DIRECTORY . "/$filename", "w");
  737. if (flock($fp, LOCK_EX | LOCK_NB)) {
  738. fwrite($fp, time() . "\n");
  739. flock($fp, LOCK_UN);
  740. fclose($fp);
  741. return true;
  742. } else {
  743. return false;
  744. }
  745. }
  746. function sql_random_function() {
  747. if (DB_TYPE == "mysql") {
  748. return "RAND()";
  749. } else {
  750. return "RANDOM()";
  751. }
  752. }
  753. function catchup_feed($link, $feed, $cat_view, $owner_uid = false, $max_id = false) {
  754. if (!$owner_uid) $owner_uid = $_SESSION['uid'];
  755. //if (preg_match("/^-?[0-9][0-9]*$/", $feed) != false) {
  756. $ref_check_qpart = ($max_id &&
  757. !get_pref($link, 'REVERSE_HEADLINES')) ? "ref_id <= '$max_id'" : "true";
  758. if (is_numeric($feed)) {
  759. if ($cat_view) {
  760. if ($feed >= 0) {
  761. if ($feed > 0) {
  762. $children = getChildCategories($link, $feed, $owner_uid);
  763. array_push($children, $feed);
  764. $children = join(",", $children);
  765. $cat_qpart = "cat_id IN ($children)";
  766. } else {
  767. $cat_qpart = "cat_id IS NULL";
  768. }
  769. db_query($link, "UPDATE ttrss_user_entries
  770. SET unread = false,last_read = NOW()
  771. WHERE feed_id IN (SELECT id FROM ttrss_feeds WHERE $cat_qpart)
  772. AND $ref_check_qpart AND unread = true
  773. AND owner_uid = $owner_uid");
  774. } else if ($feed == -2) {
  775. db_query($link, "UPDATE ttrss_user_entries
  776. SET unread = false,last_read = NOW() WHERE (SELECT COUNT(*)
  777. FROM ttrss_user_labels2 WHERE article_id = ref_id) > 0
  778. AND $ref_check_qpart
  779. AND unread = true AND owner_uid = $owner_uid");
  780. }
  781. } else if ($feed > 0) {
  782. db_query($link, "UPDATE ttrss_user_entries
  783. SET unread = false,last_read = NOW()
  784. WHERE feed_id = '$feed'
  785. AND $ref_check_qpart AND unread = true
  786. AND owner_uid = $owner_uid");
  787. } else if ($feed < 0 && $feed > -10) { // special, like starred
  788. if ($feed == -1) {
  789. db_query($link, "UPDATE ttrss_user_entries
  790. SET unread = false,last_read = NOW()
  791. WHERE marked = true
  792. AND $ref_check_qpart AND unread = true
  793. AND owner_uid = $owner_uid");
  794. }
  795. if ($feed == -2) {
  796. db_query($link, "UPDATE ttrss_user_entries
  797. SET unread = false,last_read = NOW()
  798. WHERE published = true
  799. AND $ref_check_qpart AND unread = true
  800. AND owner_uid = $owner_uid");
  801. }
  802. if ($feed == -3) {
  803. $intl = get_pref($link, "FRESH_ARTICLE_MAX_AGE");
  804. if (DB_TYPE == "pgsql") {
  805. $match_part = "updated > NOW() - INTERVAL '$intl hour' ";
  806. } else {
  807. $match_part = "updated > DATE_SUB(NOW(),
  808. INTERVAL $intl HOUR) ";
  809. }
  810. $result = db_query($link, "SELECT id FROM ttrss_entries,
  811. ttrss_user_entries WHERE $match_part AND
  812. unread = true AND
  813. ttrss_user_entries.ref_id = ttrss_entries.id AND
  814. owner_uid = $owner_uid");
  815. $affected_ids = array();
  816. while ($line = db_fetch_assoc($result)) {
  817. array_push($affected_ids, $line["id"]);
  818. }
  819. catchupArticlesById($link, $affected_ids, 0);
  820. }
  821. if ($feed == -4) {
  822. db_query($link, "UPDATE ttrss_user_entries
  823. SET unread = false,last_read = NOW()
  824. WHERE $ref_check_qpart AND unread = true AND
  825. owner_uid = $owner_uid");
  826. }
  827. } else if ($feed < -10) { // label
  828. $label_id = -$feed - 11;
  829. db_query($link, "UPDATE ttrss_user_entries, ttrss_user_labels2
  830. SET unread = false, last_read = NOW()
  831. WHERE label_id = '$label_id' AND unread = true
  832. AND $ref_check_qpart
  833. AND owner_uid = '$owner_uid' AND ref_id = article_id");
  834. }
  835. ccache_update($link, $feed, $owner_uid, $cat_view);
  836. } else { // tag
  837. db_query($link, "BEGIN");
  838. $tag_name = db_escape_string($feed);
  839. $result = db_query($link, "SELECT post_int_id FROM ttrss_tags
  840. WHERE tag_name = '$tag_name' AND owner_uid = $owner_uid");
  841. while ($line = db_fetch_assoc($result)) {
  842. db_query($link, "UPDATE ttrss_user_entries SET
  843. unread = false, last_read = NOW()
  844. WHERE $ref_check_qpart AND unread = true
  845. AND int_id = " . $line["post_int_id"]);
  846. }
  847. db_query($link, "COMMIT");
  848. }
  849. }
  850. function getAllCounters($link) {
  851. $data = getGlobalCounters($link);
  852. $data = array_merge($data, getVirtCounters($link));
  853. $data = array_merge($data, getLabelCounters($link));
  854. $data = array_merge($data, getFeedCounters($link, $active_feed));
  855. $data = array_merge($data, getCategoryCounters($link));
  856. return $data;
  857. }
  858. function getCategoryTitle($link, $cat_id) {
  859. if ($cat_id == -1) {
  860. return __("Special");
  861. } else if ($cat_id == -2) {
  862. return __("Labels");
  863. } else {
  864. $result = db_query($link, "SELECT title FROM ttrss_feed_categories WHERE
  865. id = '$cat_id'");
  866. if (db_num_rows($result) == 1) {
  867. return db_fetch_result($result, 0, "title");
  868. } else {
  869. return __("Uncategorized");
  870. }
  871. }
  872. }
  873. function getCategoryCounters($link) {
  874. $ret_arr = array();
  875. /* Labels category */
  876. $cv = array("id" => -2, "kind" => "cat",
  877. "counter" => getCategoryUnread($link, -2));
  878. array_push($ret_arr, $cv);
  879. $result = db_query($link, "SELECT id AS cat_id, value AS unread,
  880. (SELECT COUNT(id) FROM ttrss_feed_categories AS c2
  881. WHERE c2.parent_cat = ttrss_feed_categories.id) AS num_children
  882. FROM ttrss_feed_categories, ttrss_cat_counters_cache
  883. WHERE ttrss_cat_counters_cache.feed_id = id AND
  884. ttrss_cat_counters_cache.owner_uid = ttrss_feed_categories.owner_uid AND
  885. ttrss_feed_categories.owner_uid = " . $_SESSION["uid"]);
  886. while ($line = db_fetch_assoc($result)) {
  887. $line["cat_id"] = (int) $line["cat_id"];
  888. if ($line["num_children"] > 0) {
  889. $child_counter = getCategoryChildrenUnread($link, $line["cat_id"], $_SESSION["uid"]);
  890. } else {
  891. $child_counter = 0;
  892. }
  893. $cv = array("id" => $line["cat_id"], "kind" => "cat",
  894. "counter" => $line["unread"] + $child_counter);
  895. array_push($ret_arr, $cv);
  896. }
  897. /* Special case: NULL category doesn't actually exist in the DB */
  898. $cv = array("id" => 0, "kind" => "cat",
  899. "counter" => (int) ccache_find($link, 0, $_SESSION["uid"], true));
  900. array_push($ret_arr, $cv);
  901. return $ret_arr;
  902. }
  903. // only accepts real cats (>= 0)
  904. function getCategoryChildrenUnread($link, $cat, $owner_uid = false) {
  905. if (!$owner_uid) $owner_uid = $_SESSION["uid"];
  906. $result = db_query($link, "SELECT id FROM ttrss_feed_categories WHERE parent_cat = '$cat'
  907. AND owner_uid = $owner_uid");
  908. $unread = 0;
  909. while ($line = db_fetch_assoc($result)) {
  910. $unread += getCategoryUnread($link, $line["id"], $owner_uid);
  911. $unread += getCategoryChildrenUnread($link, $line["id"], $owner_uid);
  912. }
  913. return $unread;
  914. }
  915. function getCategoryUnread($link, $cat, $owner_uid = false) {
  916. if (!$owner_uid) $owner_uid = $_SESSION["uid"];
  917. if ($cat >= 0) {
  918. if ($cat != 0) {
  919. $cat_query = "cat_id = '$cat'";
  920. } else {
  921. $cat_query = "cat_id IS NULL";
  922. }
  923. $result = db_query($link, "SELECT id FROM ttrss_feeds WHERE $cat_query
  924. AND owner_uid = " . $owner_uid);
  925. $cat_feeds = array();
  926. while ($line = db_fetch_assoc($result)) {
  927. array_push($cat_feeds, "feed_id = " . $line["id"]);
  928. }
  929. if (count($cat_feeds) == 0) return 0;
  930. $match_part = implode(" OR ", $cat_feeds);
  931. $result = db_query($link, "SELECT COUNT(int_id) AS unread
  932. FROM ttrss_user_entries
  933. WHERE unread = true AND ($match_part)
  934. AND owner_uid = " . $owner_uid);
  935. $unread = 0;
  936. # this needs to be rewritten
  937. while ($line = db_fetch_assoc($result)) {
  938. $unread += $line["unread"];
  939. }
  940. return $unread;
  941. } else if ($cat == -1) {
  942. return getFeedUnread($link, -1) + getFeedUnread($link, -2) + getFeedUnread($link, -3) + getFeedUnread($link, 0);
  943. } else if ($cat == -2) {
  944. $result = db_query($link, "
  945. SELECT COUNT(unread) AS unread FROM
  946. ttrss_user_entries, ttrss_user_labels2
  947. WHERE article_id = ref_id AND unread = true
  948. AND ttrss_user_entries.owner_uid = '$owner_uid'");
  949. $unread = db_fetch_result($result, 0, "unread");
  950. return $unread;
  951. }
  952. }
  953. function getFeedUnread($link, $feed, $is_cat = false) {
  954. return getFeedArticles($link, $feed, $is_cat, true, $_SESSION["uid"]);
  955. }
  956. function getLabelUnread($link, $label_id, $owner_uid = false) {
  957. if (!$owner_uid) $owner_uid = $_SESSION["uid"];
  958. $result = db_query($link, "SELECT COUNT(ref_id) AS unread FROM ttrss_user_entries, ttrss_user_labels2
  959. WHERE owner_uid = '$owner_uid' AND unread = true AND label_id = '$label_id' AND article_id = ref_id");
  960. if (db_num_rows($result) != 0) {
  961. return db_fetch_result($result, 0, "unread");
  962. } else {
  963. return 0;
  964. }
  965. }
  966. function getFeedArticles($link, $feed, $is_cat = false, $unread_only = false,
  967. $owner_uid = false) {
  968. $n_feed = (int) $feed;
  969. $need_entries = false;
  970. if (!$owner_uid) $owner_uid = $_SESSION["uid"];
  971. if ($unread_only) {
  972. $unread_qpart = "unread = true";
  973. } else {
  974. $unread_qpart = "true";
  975. }
  976. if ($is_cat) {
  977. return getCategoryUnread($link, $n_feed, $owner_uid);
  978. } else if ($n_feed == -6) {
  979. return 0;
  980. } else if ($feed != "0" && $n_feed == 0) {
  981. $feed = db_escape_string($feed);
  982. $result = db_query($link, "SELECT SUM((SELECT COUNT(int_id)
  983. FROM ttrss_user_entries,ttrss_entries WHERE int_id = post_int_id
  984. AND ref_id = id AND $unread_qpart)) AS count FROM ttrss_tags
  985. WHERE owner_uid = $owner_uid AND tag_name = '$feed'");
  986. return db_fetch_result($result, 0, "count");
  987. } else if ($n_feed == -1) {
  988. $match_part = "marked = true";
  989. } else if ($n_feed == -2) {
  990. $match_part = "published = true";
  991. } else if ($n_feed == -3) {
  992. $match_part = "unread = true AND score >= 0";
  993. $intl = get_pref($link, "FRESH_ARTICLE_MAX_AGE", $owner_uid);
  994. if (DB_TYPE == "pgsql") {
  995. $match_part .= " AND updated > NOW() - INTERVAL '$intl hour' ";
  996. } else {
  997. $match_part .= " AND updated > DATE_SUB(NOW(), INTERVAL $intl HOUR) ";
  998. }
  999. $need_entries = true;
  1000. } else if ($n_feed == -4) {
  1001. $match_part = "true";
  1002. } else if ($n_feed >= 0) {
  1003. if ($n_feed != 0) {
  1004. $match_part = "feed_id = '$n_feed'";
  1005. } else {
  1006. $match_part = "feed_id IS NULL";
  1007. }
  1008. } else if ($feed < -10) {
  1009. $label_id = -$feed - 11;
  1010. return getLabelUnread($link, $label_id, $owner_uid);
  1011. }
  1012. if ($match_part) {
  1013. if ($need_entries) {
  1014. $from_qpart = "ttrss_user_entries,ttrss_entries";
  1015. $from_where = "ttrss_entries.id = ttrss_user_entries.ref_id AND";
  1016. } else {
  1017. $from_qpart = "ttrss_user_entries";
  1018. }
  1019. $query = "SELECT count(int_id) AS unread
  1020. FROM $from_qpart WHERE
  1021. $unread_qpart AND $from_where ($match_part) AND ttrss_user_entries.owner_uid = $owner_uid";
  1022. //echo "[$feed/$query]\n";
  1023. $result = db_query($link, $query);
  1024. } else {
  1025. $result = db_query($link, "SELECT COUNT(post_int_id) AS unread
  1026. FROM ttrss_tags,ttrss_user_entries,ttrss_entries
  1027. WHERE tag_name = '$feed' AND post_int_id = int_id AND ref_id = ttrss_entries.id
  1028. AND $unread_qpart AND ttrss_tags.owner_uid = " . $owner_uid);
  1029. }
  1030. $unread = db_fetch_result($result, 0, "unread");
  1031. return $unread;
  1032. }
  1033. function getGlobalUnread($link, $user_id = false) {
  1034. if (!$user_id) {
  1035. $user_id = $_SESSION["uid"];
  1036. }
  1037. $result = db_query($link, "SELECT SUM(value) AS c_id FROM ttrss_counters_cache
  1038. WHERE owner_uid = '$user_id' AND feed_id > 0");
  1039. $c_id = db_fetch_result($result, 0, "c_id");
  1040. return $c_id;
  1041. }
  1042. function getGlobalCounters($link, $global_unread = -1) {
  1043. $ret_arr = array();
  1044. if ($global_unread == -1) {
  1045. $global_unread = getGlobalUnread($link);
  1046. }
  1047. $cv = array("id" => "global-unread",
  1048. "counter" => (int) $global_unread);
  1049. array_push($ret_arr, $cv);
  1050. $result = db_query($link, "SELECT COUNT(id) AS fn FROM
  1051. ttrss_feeds WHERE owner_uid = " . $_SESSION["uid"]);
  1052. $subscribed_feeds = db_fetch_result($result, 0, "fn");
  1053. $cv = array("id" => "subscribed-feeds",
  1054. "counter" => (int) $subscribed_feeds);
  1055. array_push($ret_arr, $cv);
  1056. return $ret_arr;
  1057. }
  1058. function getVirtCounters($link) {
  1059. $ret_arr = array();
  1060. for ($i = 0; $i >= -4; $i--) {
  1061. $count = getFeedUnread($link, $i);
  1062. $cv = array("id" => $i,
  1063. "counter" => (int) $count);
  1064. // if (get_pref($link, 'EXTENDED_FEEDLIST'))
  1065. // $cv["xmsg"] = getFeedArticles($link, $i)." ".__("total");
  1066. array_push($ret_arr, $cv);
  1067. }
  1068. return $ret_arr;
  1069. }
  1070. function getLabelCounters($link, $descriptions = false) {
  1071. $ret_arr = array();
  1072. $owner_uid = $_SESSION["uid"];
  1073. $result = db_query($link, "SELECT id,caption,COUNT(unread) AS unread
  1074. FROM ttrss_labels2 LEFT JOIN ttrss_user_labels2 ON
  1075. (ttrss_labels2.id = label_id)
  1076. LEFT JOIN ttrss_user_entries ON (ref_id = article_id AND unread = true)
  1077. WHERE ttrss_labels2.owner_uid = $owner_uid GROUP BY ttrss_labels2.id,
  1078. ttrss_labels2.caption");
  1079. while ($line = db_fetch_assoc($result)) {
  1080. $id = -$line["id"] - 11;
  1081. $label_name = $line["caption"];
  1082. $count = $line["unread"];
  1083. $cv = array("id" => $id,
  1084. "counter" => (int) $count);
  1085. if ($descriptions)
  1086. $cv["description"] = $label_name;
  1087. // if (get_pref($link, 'EXTENDED_FEEDLIST'))
  1088. // $cv["xmsg"] = getFeedArticles($link, $id)." ".__("total");
  1089. array_push($ret_arr, $cv);
  1090. }
  1091. return $ret_arr;
  1092. }
  1093. function getFeedCounters($link, $active_feed = false) {
  1094. $ret_arr = array();
  1095. $query = "SELECT ttrss_feeds.id,
  1096. ttrss_feeds.title,
  1097. ".SUBSTRING_FOR_DATE."(ttrss_feeds.last_updated,1,19) AS last_updated,
  1098. last_error, value AS count
  1099. FROM ttrss_feeds, ttrss_counters_cache
  1100. WHERE ttrss_feeds.owner_uid = ".$_SESSION["uid"]."
  1101. AND ttrss_counters_cache.owner_uid = ttrss_feeds.owner_uid
  1102. AND ttrss_counters_cache.feed_id = id";
  1103. $result = db_query($link, $query);
  1104. $fctrs_modified = false;
  1105. while ($line = db_fetch_assoc($result)) {
  1106. $id = $line["id"];
  1107. $count = $line["count"];
  1108. $last_error = htmlspecialchars($line["last_error"]);
  1109. $last_updated = make_local_datetime($link, $line['last_updated'], false);
  1110. $has_img = feed_has_icon($id);
  1111. if (date('Y') - date('Y', strtotime($line['last_updated'])) > 2)
  1112. $last_updated = '';
  1113. $cv = array("id" => $id,
  1114. "updated" => $last_updated,
  1115. "counter" => (int) $count,
  1116. "has_img" => (int) $has_img);
  1117. if ($last_error)
  1118. $cv["error"] = $last_error;
  1119. // if (get_pref($link, 'EXTENDED_FEEDLIST'))
  1120. // $cv["xmsg"] = getFeedArticles($link, $id)." ".__("total");
  1121. if ($active_feed && $id == $active_feed)
  1122. $cv["title"] = truncate_string($line["title"], 30);
  1123. array_push($ret_arr, $cv);
  1124. }
  1125. return $ret_arr;
  1126. }
  1127. function get_pgsql_version($link) {
  1128. $result = db_query($link, "SELECT version() AS version");
  1129. $version = explode(" ", db_fetch_result($result, 0, "version"));
  1130. return $version[1];
  1131. }
  1132. /**
  1133. * @return array (code => Status code, message => error message if available)
  1134. *
  1135. * 0 - OK, Feed already exists
  1136. * 1 - OK, Feed added
  1137. * 2 - Invalid URL
  1138. * 3 - URL content is HTML, no feeds available
  1139. * 4 - URL content is HTML which contains multiple feeds.
  1140. * Here you should call extractfeedurls in rpc-backend
  1141. * to get all possible feeds.
  1142. * 5 - Couldn't download the URL content.
  1143. */
  1144. function subscribe_to_feed($link, $url, $cat_id = 0,
  1145. $auth_login = '', $auth_pass = '', $need_auth = false) {
  1146. global $fetch_last_error;
  1147. require_once "include/rssfuncs.php";
  1148. $url = fix_url($url);
  1149. if (!$url || !validate_feed_url($url)) return array("code" => 2);
  1150. $contents = @fetch_file_contents($url, false, $auth_login, $auth_pass);
  1151. if (!$contents) {
  1152. return array("code" => 5, "message" => $fetch_last_error);
  1153. }
  1154. if (is_html($contents)) {
  1155. $feedUrls = get_feeds_from_html($url, $contents);
  1156. if (count($feedUrls) == 0) {
  1157. return array("code" => 3);
  1158. } else if (count($feedUrls) > 1) {
  1159. return array("code" => 4, "feeds" => $feedUrls);
  1160. }
  1161. //use feed url as new URL
  1162. $url = key($feedUrls);
  1163. }
  1164. if ($cat_id == "0" || !$cat_id) {
  1165. $cat_qpart = "NULL";
  1166. } else {
  1167. $cat_qpart = "'$cat_id'";
  1168. }
  1169. $result = db_query($link,
  1170. "SELECT id FROM ttrss_feeds
  1171. WHERE feed_url = '$url' AND owner_uid = ".$_SESSION["uid"]);
  1172. if (db_num_rows($result) == 0) {
  1173. $result = db_query($link,
  1174. "INSERT INTO ttrss_feeds
  1175. (owner_uid,feed_url,title,cat_id, auth_login,auth_pass,update_method)
  1176. VALUES ('".$_SESSION["uid"]."', '$url',
  1177. '[Unknown]', $cat_qpart, '$auth_login', '$auth_pass', 0)");
  1178. $result = db_query($link,
  1179. "SELECT id FROM ttrss_feeds WHERE feed_url = '$url'
  1180. AND owner_uid = " . $_SESSION["uid"]);
  1181. $feed_id = db_fetch_result($result, 0, "id");
  1182. if ($feed_id) {
  1183. update_rss_feed($link, $feed_id, true);
  1184. }
  1185. return array("code" => 1);
  1186. } else {
  1187. return array("code" => 0);
  1188. }
  1189. }
  1190. function print_feed_select($link, $id, $default_id = "",
  1191. $attributes = "", $include_all_feeds = true,
  1192. $root_id = false, $nest_level = 0) {
  1193. if (!$root_id) {
  1194. print "<select id=\"$id\" name=\"$id\" $attributes>";
  1195. if ($include_all_feeds) {
  1196. $is_selected = ("0" == $default_id) ? "selected=\"1\"" : "";
  1197. print "<option $is_selected value=\"0\">".__('All feeds')."</option>";
  1198. }
  1199. }
  1200. if (get_pref($link, 'ENABLE_FEED_CATS')) {
  1201. if ($root_id)
  1202. $parent_qpart = "parent_cat = '$root_id'";
  1203. else
  1204. $parent_qpart = "parent_cat IS NULL";
  1205. $result = db_query($link, "SELECT id,title,
  1206. (SELECT COUNT(id) FROM ttrss_feed_categories AS c2 WHERE
  1207. c2.parent_cat = ttrss_feed_categories.id) AS num_children
  1208. FROM ttrss_feed_categories
  1209. WHERE owner_uid = ".$_SESSION["uid"]." AND $parent_qpart ORDER BY title");
  1210. while ($line = db_fetch_assoc($result)) {
  1211. for ($i = 0; $i < $nest_level; $i++)
  1212. $line["title"] = " - " . $line["title"];
  1213. $is_selected = ("CAT:".$line["id"] == $default_id) ? "selected=\"1\"" : "";
  1214. printf("<option $is_selected value='CAT:%d'>%s</option>",
  1215. $line["id"], htmlspecialchars($line["title"]));
  1216. if ($line["num_children"] > 0)
  1217. print_feed_select($link, $id, $default_id, $attributes,
  1218. $include_all_feeds, $line["id"], $nest_level+1);
  1219. $feed_result = db_query($link, "SELECT id,title FROM ttrss_feeds
  1220. WHERE cat_id = '".$line["id"]."' AND owner_uid = ".$_SESSION["uid"] . " ORDER BY title");
  1221. while ($fline = db_fetch_assoc($feed_result)) {
  1222. $is_selected = ($fline["id"] == $default_id) ? "selected=\"1\"" : "";
  1223. $fline["title"] = " + " . $fline["title"];
  1224. for ($i = 0; $i < $nest_level; $i++)
  1225. $fline["title"] = " - " . $fline["title"];
  1226. printf("<option $is_selected value='%d'>%s</option>",
  1227. $fline["id"], htmlspecialchars($fline["title"]));
  1228. }
  1229. }
  1230. if (!$root_id) {
  1231. $is_selected = ($default_id == "CAT:0") ? "selected=\"1\"" : "";
  1232. printf("<option $is_selected value='CAT:0'>%s</option>",
  1233. __("Uncategorized"));
  1234. $feed_result = db_query($link, "SELECT id,title FROM ttrss_feeds
  1235. WHERE cat_id IS NULL AND owner_uid = ".$_SESSION["uid"] . " ORDER BY title");
  1236. while ($fline = db_fetch_assoc($feed_result)) {
  1237. $is_selected = ($fline["id"] == $default_id && !$default_is_cat) ? "selected=\"1\"" : "";
  1238. $fline["title"] = " + " . $fline["title"];
  1239. for ($i = 0; $i < $nest_level; $i++)
  1240. $fline["title"] = " - " . $fline["title"];
  1241. printf("<option $is_selected value='%d'>%s</option>",
  1242. $fline["id"], htmlspecialchars($fline["title"]));
  1243. }
  1244. }
  1245. } else {
  1246. $result = db_query($link, "SELECT id,title FROM ttrss_feeds
  1247. WHERE owner_uid = ".$_SESSION["uid"]." ORDER BY title");
  1248. while ($line = db_fetch_assoc($result)) {
  1249. $is_selected = ($line["id"] == $default_id) ? "selected=\"1\"" : "";
  1250. printf("<option $is_selected value='%d'>%s</option>",
  1251. $line["id"], htmlspecialchars($line["title"]));
  1252. }
  1253. }
  1254. if (!$root_id) {
  1255. print "</select>";
  1256. }
  1257. }
  1258. function print_feed_cat_select($link, $id, $default_id,
  1259. $attributes, $include_all_cats = true, $root_id = false, $nest_level = 0) {
  1260. if (!$root_id) {
  1261. print "<select id=\"$id\" name=\"$id\" default=\"$default_id\" onchange=\"catSelectOnChange(this)\" $attributes>";
  1262. }
  1263. if ($root_id)
  1264. $parent_qpart = "parent_cat = '$root_id'";
  1265. else
  1266. $parent_qpart = "parent_cat IS NULL";
  1267. $result = db_query($link, "SELECT id,title,
  1268. (SELECT COUNT(id) FROM ttrss_feed_categories AS c2 WHERE
  1269. c2.parent_cat = ttrss_feed_categories.id) AS num_children
  1270. FROM ttrss_feed_categories
  1271. WHERE owner_uid = ".$_SESSION["uid"]." AND $parent_qpart ORDER BY title");
  1272. while ($line = db_fetch_assoc($result)) {
  1273. if ($line["id"] == $default_id) {
  1274. $is_selected = "selected=\"1\"";
  1275. } else {
  1276. $is_selected = "";
  1277. }
  1278. for ($i = 0; $i < $nest_level; $i++)
  1279. $line["title"] = " - " . $line["title"];
  1280. if ($line["title"])
  1281. printf("<option $is_selected value='%d'>%s</option>",
  1282. $line["id"], htmlspecialchars($line["title"]));
  1283. if ($line["num_children"] > 0)
  1284. print_feed_cat_select($link, $id, $default_id, $attributes,
  1285. $include_all_cats, $line["id"], $nest_level+1);
  1286. }
  1287. if (!$root_id) {
  1288. if ($include_all_cats) {
  1289. if (db_num_rows($result) > 0) {
  1290. print "<option disabled=\"1\">--------</option>";
  1291. }
  1292. if ($default_id == 0) {
  1293. $is_selected = "selected=\"1\"";
  1294. } else {
  1295. $is_selected = "";
  1296. }
  1297. print "<option $is_selected value=\"0\">".__('Uncategorized')."</option>";
  1298. }
  1299. print "</select>";
  1300. }
  1301. }
  1302. function checkbox_to_sql_bool($val) {
  1303. return ($val == "on") ? "true" : "false";
  1304. }
  1305. function getFeedCatTitle($link, $id) {
  1306. if ($id == -1) {
  1307. return __("Special");
  1308. } else if ($id < -10) {
  1309. return __("Labels");
  1310. } else if ($id > 0) {
  1311. $result = db_query($link, "SELECT ttrss_feed_categories.title
  1312. FROM ttrss_feeds, ttrss_feed_categories WHERE ttrss_feeds.id = '$id' AND
  1313. cat_id = ttrss_feed_categories.id");
  1314. if (db_num_rows($result) == 1) {
  1315. return db_fetch_result($result, 0, "title");
  1316. } else {
  1317. return __("Uncategorized");
  1318. }
  1319. } else {
  1320. return "getFeedCatTitle($id) failed";
  1321. }
  1322. }
  1323. function getFeedIcon($id) {
  1324. switch ($id) {
  1325. case 0:
  1326. return "images/archive.png";
  1327. break;
  1328. case -1:
  1329. return "images/mark_set.svg";
  1330. break;
  1331. case -2:
  1332. return "images/pub_set.svg";
  1333. break;
  1334. case -3:
  1335. return "images/fresh.png";
  1336. break;
  1337. case -4:
  1338. return "images/tag.png";
  1339. break;
  1340. case -6:
  1341. return "images/recently_read.png";
  1342. break;
  1343. default:
  1344. if ($id < -10) {
  1345. return "images/label.png";
  1346. } else {
  1347. if (file_exists(ICONS_DIR . "/$id.ico"))
  1348. return ICONS_URL . "/$id.ico";
  1349. }
  1350. break;
  1351. }
  1352. }
  1353. function getFeedTitle($link, $id, $cat = false) {
  1354. if ($cat) {
  1355. return getCategoryTitle($link, $id);
  1356. } else if ($id == -1) {
  1357. return __("Starred articles");
  1358. } else if ($id == -2) {
  1359. return __("Published articles");
  1360. } else if ($id == -3) {
  1361. return __("Fresh articles");
  1362. } else if ($id == -4) {
  1363. return __("All articles");
  1364. } else if ($id === 0 || $id === "0") {
  1365. return __("Archived articles");
  1366. } else if ($id == -6) {
  1367. return __("Recently read");
  1368. } else if ($id < -10) {
  1369. $label_id = -$id - 11;
  1370. $result = db_query($link, "SELECT caption FROM ttrss_labels2 WHERE id = '$label_id'");
  1371. if (db_num_rows($result) == 1) {
  1372. return db_fetch_result($result, 0, "caption");
  1373. } else {
  1374. return "Unknown label ($label_id)";
  1375. }
  1376. } else if (is_numeric($id) && $id > 0) {
  1377. $result = db_query($link, "SELECT title FROM ttrss_feeds WHERE id = '$id'");
  1378. if (db_num_rows($result) == 1) {
  1379. return db_fetch_result($result, 0, "title");
  1380. } else {
  1381. return "Unknown feed ($id)";
  1382. }
  1383. } else {
  1384. return $id;
  1385. }
  1386. }
  1387. function make_init_params($link) {
  1388. $params = array();
  1389. $params["sign_progress"] = theme_image($link, "images/indicator_white.gif");
  1390. $params["sign_progress_tiny"] = theme_image($link, "images/indicator_tiny.gif");
  1391. $params["sign_excl"] = theme_image($link, "images/sign_excl.svg");
  1392. $params["sign_info"] = theme_image($link, "images/sign_info.svg");
  1393. foreach (array("ON_CATCHUP_SHOW_NEXT_FEED", "HIDE_READ_FEEDS",
  1394. "ENABLE_FEED_CATS", "FEEDS_SORT_BY_UNREAD", "CONFIRM_FEED_CATCHUP",
  1395. "CDM_AUTO_CATCHUP", "FRESH_ARTICLE_MAX_AGE", "DEFAULT_ARTICLE_LIMIT",
  1396. "HIDE_READ_SHOWS_SPECIAL", "COMBINED_DISPLAY_MODE") as $param) {
  1397. $params[strtolower($param)] = (int) get_pref($link, $param);
  1398. }
  1399. $params["icons_url"] = ICONS_URL;
  1400. $params["cookie_lifetime"] = SESSION_COOKIE_LIFETIME;
  1401. $params["default_view_mode"] = get_pref($link, "_DEFAULT_VIEW_MODE");
  1402. $params["default_view_limit"] = (int) get_pref($link, "_DEFAULT_VIEW_LIMIT");
  1403. $params["default_view_order_by"] = get_pref($link, "_DEFAULT_VIEW_ORDER_BY");
  1404. $params["bw_limit"] = (int) $_SESSION["bw_limit"];
  1405. $result = db_query($link, "SELECT MAX(id) AS mid, COUNT(*) AS nf FROM
  1406. ttrss_feeds WHERE owner_uid = " . $_SESSION["uid"]);
  1407. $max_feed_id = db_fetch_result($result, 0, "mid");
  1408. $num_feeds = db_fetch_result($result, 0, "nf");
  1409. $params["max_feed_id"] = (int) $max_feed_id;
  1410. $params["num_feeds"] = (int) $num_feeds;
  1411. $params["collapsed_feedlist"] = (int) get_pref($link, "_COLLAPSED_FEEDLIST");
  1412. $params["hotkeys"] = get_hotkeys_map($link);
  1413. $params["csrf_token"] = $_SESSION["csrf_token"];
  1414. $params["widescreen"] = (int) $_COOKIE["ttrss_widescreen"];
  1415. $params['simple_update'] = defined('SIMPLE_UPDATE_MODE') && SIMPLE_UPDATE_MODE;
  1416. return $params;
  1417. }
  1418. function get_hotkeys_info($link) {
  1419. $hotkeys = array(
  1420. __("Navigation") => array(
  1421. "next_feed" => __("Open next feed"),
  1422. "prev_feed" => __("Open previous feed"),
  1423. "next_article" => __("Open next article"),
  1424. "prev_article" => __("Open previous article"),
  1425. "next_article_noscroll" => __("Open next article (don't scroll long articles)"),
  1426. "prev_article_noscroll" => __("Open previous article (don't scroll long articles)"),
  1427. "search_dialog" => __("Show search dialog")),
  1428. __("Article") => array(
  1429. "toggle_mark" => __("Toggle starred"),
  1430. "toggle_publ" => __("Toggle published"),
  1431. "toggle_unread" => __("Toggle unread"),
  1432. "edit_tags" => __("Edit tags"),
  1433. "dismiss_selected" => __("Dismiss selected"),
  1434. "dismiss_read" => __("Dismiss read"),
  1435. "open_in_new_window" => __("Open in new window"),
  1436. "catchup_below" => __("Mark below as read"),
  1437. "catchup_above" => __("Mark above as read"),
  1438. "article_scroll_down" => __("Scroll down"),
  1439. "article_scroll_up" => __("Scroll up"),
  1440. "select_article_cursor" => __("Select article under cursor"),
  1441. "email_article" => __("Email article"),
  1442. "close_article" => __("Close/collapse article"),
  1443. "toggle_widescreen" => __("Toggle widescreen mode")),
  1444. __("Article selection") => array(
  1445. "select_all" => __("Select all articles"),
  1446. "select_unread" => __("Select unread"),
  1447. "select_marked" => __("Select starred"),
  1448. "select_published" => __("Select published"),
  1449. "select_invert" => __("Invert selection"),
  1450. "select_none" => __("Deselect everything")),
  1451. __("Feed") => array(
  1452. "feed_refresh" => __("Refresh current feed"),
  1453. "feed_unhide_read" => __("Un/hide read feeds"),
  1454. "feed_subscribe" => __("Subscribe to feed"),
  1455. "feed_edit" => __("Edit feed"),
  1456. "feed_catchup" => __("Mark as read"),
  1457. "feed_reverse" => __("Reverse headlines"),
  1458. "feed_debug_update" => __("Debug feed update"),
  1459. "catchup_all" => __("Mark all feeds as read"),
  1460. "cat_toggle_collapse" => __("Un/collapse current category"),
  1461. "toggle_combined_mode" => __("Toggle combined mode")),
  1462. __("Go to") => array(
  1463. "goto_all" => __("All articles"),
  1464. "goto_fresh" => __("Fresh"),
  1465. "goto_marked" => __("Starred"),
  1466. "goto_published" => __("Published"),
  1467. "goto_tagcloud" => __("Tag cloud"),
  1468. "goto_prefs" => __("Preferences")),
  1469. __("Other") => array(
  1470. "create_label" => __("Create label"),
  1471. "create_filter" => __("Create filter"),
  1472. "collapse_sidebar" => __("Un/collapse sidebar"),
  1473. "help_dialog" => __("Show help dialog"))
  1474. );
  1475. return $hotkeys;
  1476. }
  1477. function get_hotkeys_map($link) {
  1478. $hotkeys = array(
  1479. // "navigation" => array(
  1480. "k" => "next_feed",
  1481. "j" => "prev_feed",
  1482. "n" => "next_article",
  1483. "p" => "prev_article",
  1484. "(38)|up" => "prev_article",
  1485. "(40)|down" => "next_article",
  1486. // "^(38)|Ctrl-up" => "prev_article_noscroll",
  1487. // "^(40)|Ctrl-down" => "next_article_noscroll",
  1488. "(191)|/" => "search_dialog",
  1489. // "article" => array(
  1490. "s" => "toggle_mark",
  1491. "*s" => "toggle_publ",
  1492. "u" => "toggle_unread",
  1493. "*t" => "edit_tags",
  1494. "*d" => "dismiss_selected",
  1495. "*x" => "dismiss_read",
  1496. "o" => "open_in_new_window",
  1497. "c p" => "catchup_below",
  1498. "c n" => "catchup_above",
  1499. "*n" => "article_scroll_down",
  1500. "*p" => "article_scroll_up",
  1501. "*(38)|Shift+up" => "article_scroll_up",
  1502. "*(40)|Shift+down" => "article_scroll_down",
  1503. "a *w" => "toggle_widescreen",
  1504. "e" => "email_article",
  1505. "a q" => "close_article",
  1506. // "article_selection" => array(
  1507. "a a" => "select_all",
  1508. "a u" => "select_unread",
  1509. "a *u" => "select_marked",
  1510. "a p" => "select_published",
  1511. "a i" => "select_invert",
  1512. "a n" => "select_none",
  1513. // "feed" => array(
  1514. "f r" => "feed_refresh",
  1515. "f a" => "feed_unhide_read",
  1516. "f s" => "feed_subscribe",
  1517. "f e" => "feed_edit",
  1518. "f q" => "feed_catchup",
  1519. "f x" => "feed_reverse",
  1520. "f *d" => "feed_debug_update",
  1521. "f *c" => "toggle_combined_mode",
  1522. "*q" => "catchup_all",
  1523. "x" => "cat_toggle_collapse",
  1524. // "goto" => array(
  1525. "g a" => "goto_all",
  1526. "g f" => "goto_fresh",
  1527. "g s" => "goto_marked",
  1528. "g p" => "goto_published",
  1529. "g t" => "goto_tagcloud",
  1530. "g *p" => "goto_prefs",
  1531. // "other" => array(
  1532. "(9)|Tab" => "select_article_cursor", // tab
  1533. "c l" => "create_label",
  1534. "c f" => "create_filter",
  1535. "c s" => "collapse_sidebar",
  1536. "^(191)|Ctrl+/" => "help_dialog",
  1537. );
  1538. if (get_pref($link, 'COMBINED_DISPLAY_MODE')) {
  1539. $hotkeys["^(38)|Ctrl-up"] = "prev_article_noscroll";
  1540. $hotkeys["^(40)|Ctrl-down"] = "next_article_noscroll";
  1541. }
  1542. global $pluginhost;
  1543. foreach ($pluginhost->get_hooks($pluginhost::HOOK_HOTKEY_MAP) as $plugin) {
  1544. $hotkeys = $plugin->hook_hotkey_map($hotkeys);
  1545. }
  1546. $prefixes = array();
  1547. foreach (array_keys($hotkeys) as $hotkey) {
  1548. $pair = explode(" ", $hotkey, 2);
  1549. if (count($pair) > 1 && !in_array($pair[0], $prefixes)) {
  1550. array_push($prefixes, $pair[0]);
  1551. }
  1552. }
  1553. return array($prefixes, $hotkeys);
  1554. }
  1555. function make_runtime_info($link) {
  1556. $data = array();
  1557. $result = db_query($link, "SELECT MAX(id) AS mid, COUNT(*) AS nf FROM
  1558. ttrss_feeds WHERE owner_uid = " . $_SESSION["uid"]);
  1559. $max_feed_id = db_fetch_result($result, 0, "mid");
  1560. $num_feeds = db_fetch_result($result, 0, "nf");
  1561. $data["max_feed_id"] = (int) $max_feed_id;
  1562. $data["num_feeds"] = (int) $num_feeds;
  1563. $data['last_article_id'] = getLastArticleId($link);
  1564. $data['cdm_expanded'] = get_pref($link, 'CDM_EXPANDED');
  1565. if (file_exists(LOCK_DIRECTORY . "/update_daemon.lock")) {
  1566. $data['daemon_is_running'] = (int) file_is_locked("update_daemon.lock");
  1567. if (time() - $_SESSION["daemon_stamp_check"] > 30) {
  1568. $stamp = (int) @file_get_contents(LOCK_DIRECTORY . "/update_daemon.stamp");
  1569. if ($stamp) {
  1570. $stamp_delta = time() - $stamp;
  1571. if ($stamp_delta > 1800) {
  1572. $stamp_check = 0;
  1573. } else {
  1574. $stamp_check = 1;
  1575. $_SESSION["daemon_stamp_check"] = time();
  1576. }
  1577. $data['daemon_stamp_ok'] = $stamp_check;
  1578. $stamp_fmt = date("Y.m.d, G:i", $stamp);
  1579. $data['daemon_stamp'] = $stamp_fmt;
  1580. }
  1581. }
  1582. }
  1583. if ($_SESSION["last_version_check"] + 86400 + rand(-1000, 1000) < time()) {
  1584. $new_version_details = @check_for_update($link);
  1585. $data['new_version_available'] = (int) ($new_version_details != false);
  1586. $_SESSION["last_version_check"] = time();
  1587. $_SESSION["version_data"] = $new_version_details;
  1588. }
  1589. return $data;
  1590. }
  1591. function search_to_sql($link, $search, $match_on) {
  1592. $search_query_part = "";
  1593. $keywords = explode(" ", $search);
  1594. $query_keywords = array();
  1595. foreach ($keywords as $k) {
  1596. if (strpos($k, "-") === 0) {
  1597. $k = substr($k, 1);
  1598. $not = "NOT";
  1599. } else {
  1600. $not = "";
  1601. }
  1602. $commandpair = explode(":", mb_strtolower($k), 2);
  1603. if ($commandpair[0] == "note" && $commandpair[1]) {
  1604. if ($commandpair[1] == "true")
  1605. array_push($query_keywords, "($not (note IS NOT NULL AND note != ''))");
  1606. else
  1607. array_push($query_keywords, "($not (note IS NULL OR note = ''))");
  1608. } else if ($commandpair[0] == "star" && $commandpair[1]) {
  1609. if ($commandpair[1] == "true")
  1610. array_push($query_keywords, "($not (marked = true))");
  1611. else
  1612. array_push($query_keywords, "($not (marked = false))");
  1613. } else if ($commandpair[0] == "pub" && $commandpair[1]) {
  1614. if ($commandpair[1] == "true")
  1615. array_push($query_keywords, "($not (published = true))");
  1616. else
  1617. array_push($query_keywords, "($not (published = false))");
  1618. } else if (strpos($k, "@") === 0) {
  1619. $user_tz_string = get_pref($link, 'USER_TIMEZONE', $_SESSION['uid']);
  1620. $orig_ts = strtotime(substr($k, 1));
  1621. $k = date("Y-m-d", convert_timestamp($orig_ts, $user_tz_string, 'UTC'));
  1622. //$k = date("Y-m-d", strtotime(substr($k, 1)));
  1623. array_push($query_keywords, "(".SUBSTRING_FOR_DATE."(updated,1,LENGTH('$k')) $not = '$k')");
  1624. } else if ($match_on == "both") {
  1625. array_push($query_keywords, "(UPPER(ttrss_entries.title) $not LIKE UPPER('%$k%')
  1626. OR UPPER(ttrss_entries.content) $not LIKE UPPER('%$k%'))");
  1627. } else if ($match_on == "title") {
  1628. array_push($query_keywords, "(UPPER(ttrss_entries.title) $not LIKE UPPER('%$k%'))");
  1629. } else if ($match_on == "content") {
  1630. array_push($query_keywords, "(UPPER(ttrss_entries.content) $not LIKE UPPER('%$k%'))");
  1631. }
  1632. }
  1633. $search_query_part = implode("AND", $query_keywords);
  1634. return $search_query_part;
  1635. }
  1636. function getParentCategories($link, $cat, $owner_uid) {
  1637. $rv = array();
  1638. $result = db_query($link, "SELECT parent_cat FROM ttrss_feed_categories
  1639. WHERE id = '$cat' AND parent_cat IS NOT NULL AND owner_uid = $owner_uid");
  1640. while ($line = db_fetch_assoc($result)) {
  1641. array_push($rv, $line["parent_cat"]);
  1642. $rv = array_merge($rv, getParentCategories($link, $line["parent_cat"], $owner_uid));
  1643. }
  1644. return $rv;
  1645. }
  1646. function getChildCategories($link, $cat, $owner_uid) {
  1647. $rv = array();
  1648. $result = db_query($link, "SELECT id FROM ttrss_feed_categories
  1649. WHERE parent_cat = '$cat' AND owner_uid = $owner_uid");
  1650. while ($line = db_fetch_assoc($result)) {
  1651. array_push($rv, $line["id"]);
  1652. $rv = array_merge($rv, getChildCategories($link, $line["id"], $owner_uid));
  1653. }
  1654. return $rv;
  1655. }
  1656. 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, $include_children = false, $ignore_vfeed_group = false) {
  1657. if (!$owner_uid) $owner_uid = $_SESSION["uid"];
  1658. $ext_tables_part = "";
  1659. if ($search) {
  1660. if (SPHINX_ENABLED) {
  1661. $ids = join(",", @sphinx_search($search, 0, 500));
  1662. if ($ids)
  1663. $search_query_part = "ref_id IN ($ids) AND ";
  1664. else
  1665. $search_query_part = "ref_id = -1 AND ";
  1666. } else {
  1667. $search_query_part = search_to_sql($link, $search, $match_on);
  1668. $search_query_part .= " AND ";
  1669. }
  1670. } else {
  1671. $search_query_part = "";
  1672. }
  1673. if ($filter) {
  1674. if (DB_TYPE == "pgsql") {
  1675. $query_strategy_part .= " AND updated > NOW() - INTERVAL '14 days' ";
  1676. } else {
  1677. $query_strategy_part .= " AND updated > DATE_SUB(NOW(), INTERVAL 14 DAY) ";
  1678. }
  1679. $override_order = "updated DESC";
  1680. $filter_query_part = filter_to_sql($link, $filter, $owner_uid);
  1681. // Try to check if SQL regexp implementation chokes on a valid regexp
  1682. $result = db_query($link, "SELECT true AS true_val FROM ttrss_entries,
  1683. ttrss_user_entries, ttrss_feeds, ttrss_feed_categories
  1684. WHERE $filter_query_part LIMIT 1", false);
  1685. if ($result) {
  1686. $test = db_fetch_result($result, 0, "true_val");
  1687. if (!$test) {
  1688. $filter_query_part = "false AND";
  1689. } else {
  1690. $filter_query_part .= " AND";
  1691. }
  1692. } else {
  1693. $filter_query_part = "false AND";
  1694. }
  1695. } else {
  1696. $filter_query_part = "";
  1697. }
  1698. if ($since_id) {
  1699. $since_id_part = "ttrss_entries.id > $since_id AND ";
  1700. } else {
  1701. $since_id_part = "";
  1702. }
  1703. $view_query_part = "";
  1704. if ($view_mode == "adaptive" || $view_query_part == "noscores") {
  1705. if ($search) {
  1706. $view_query_part = " ";
  1707. } else if ($feed != -1) {
  1708. $unread = getFeedUnread($link, $feed, $cat_view);
  1709. if ($cat_view && $feed > 0 && $include_children)
  1710. $unread += getCategoryChildrenUnread($link, $feed);
  1711. if ($unread > 0) {
  1712. $view_query_part = " unread = true AND ";
  1713. }
  1714. }
  1715. }
  1716. if ($view_mode == "marked") {
  1717. $view_query_part = " marked = true AND ";
  1718. }
  1719. if ($view_mode == "published") {
  1720. $view_query_part = " published = true AND ";
  1721. }
  1722. if ($view_mode == "unread") {
  1723. $view_query_part = " unread = true AND ";
  1724. }
  1725. if ($view_mode == "updated") {
  1726. $view_query_part = " (last_read is null and unread = false) AND ";
  1727. }
  1728. if ($limit > 0) {
  1729. $limit_query_part = "LIMIT " . $limit;
  1730. }
  1731. $allow_archived = false;
  1732. $vfeed_query_part = "";
  1733. // override query strategy and enable feed display when searching globally
  1734. if ($search && $search_mode == "all_feeds") {
  1735. $query_strategy_part = "true";
  1736. $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
  1737. /* tags */
  1738. } else if (!is_numeric($feed)) {
  1739. $query_strategy_part = "true";
  1740. $vfeed_query_part = "(SELECT title FROM ttrss_feeds WHERE
  1741. id = feed_id) as feed_title,";
  1742. } else if ($search && $search_mode == "this_cat") {
  1743. $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
  1744. if ($feed > 0) {
  1745. if ($include_children) {
  1746. $subcats = getChildCategories($link, $feed, $owner_uid);
  1747. array_push($subcats, $feed);
  1748. $cats_qpart = join(",", $subcats);
  1749. } else {
  1750. $cats_qpart = $feed;
  1751. }
  1752. $query_strategy_part = "ttrss_feeds.cat_id IN ($cats_qpart)";
  1753. } else {
  1754. $query_strategy_part = "ttrss_feeds.cat_id IS NULL";
  1755. }
  1756. } else if ($feed > 0) {
  1757. if ($cat_view) {
  1758. if ($feed > 0) {
  1759. if ($include_children) {
  1760. # sub-cats
  1761. $subcats = getChildCategories($link, $feed, $owner_uid);
  1762. array_push($subcats, $feed);
  1763. $query_strategy_part = "cat_id IN (".
  1764. implode(",", $subcats).")";
  1765. } else {
  1766. $query_strategy_part = "cat_id = '$feed'";
  1767. }
  1768. } else {
  1769. $query_strategy_part = "cat_id IS NULL";
  1770. }
  1771. $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
  1772. } else {
  1773. $query_strategy_part = "feed_id = '$feed'";
  1774. }
  1775. } else if ($feed == 0 && !$cat_view) { // archive virtual feed
  1776. $query_strategy_part = "feed_id IS NULL";
  1777. $allow_archived = true;
  1778. } else if ($feed == 0 && $cat_view) { // uncategorized
  1779. $query_strategy_part = "cat_id IS NULL AND feed_id IS NOT NULL";
  1780. $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
  1781. } else if ($feed == -1) { // starred virtual feed
  1782. $query_strategy_part = "marked = true";
  1783. $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
  1784. $allow_archived = true;
  1785. if (!$override_order) $override_order = "last_marked DESC, updated DESC";
  1786. } else if ($feed == -2) { // published virtual feed OR labels category
  1787. if (!$cat_view) {
  1788. $query_strategy_part = "published = true";
  1789. $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
  1790. $allow_archived = true;
  1791. if (!$override_order) $override_order = "last_published DESC, updated DESC";
  1792. } else {
  1793. $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
  1794. $ext_tables_part = ",ttrss_labels2,ttrss_user_labels2";
  1795. $query_strategy_part = "ttrss_labels2.id = ttrss_user_labels2.label_id AND
  1796. ttrss_user_labels2.article_id = ref_id";
  1797. }
  1798. } else if ($feed == -6) { // recently read
  1799. $query_strategy_part = "unread = false AND last_read IS NOT NULL";
  1800. $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
  1801. $allow_archived = true;
  1802. if (!$override_order) $override_order = "last_read DESC";
  1803. } else if ($feed == -3) { // fresh virtual feed
  1804. $query_strategy_part = "unread = true AND score >= 0";
  1805. $intl = get_pref($link, "FRESH_ARTICLE_MAX_AGE", $owner_uid);
  1806. if (DB_TYPE == "pgsql") {
  1807. $query_strategy_part .= " AND updated > NOW() - INTERVAL '$intl hour' ";
  1808. } else {
  1809. $query_strategy_part .= " AND updated > DATE_SUB(NOW(), INTERVAL $intl HOUR) ";
  1810. }
  1811. $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
  1812. } else if ($feed == -4) { // all articles virtual feed
  1813. $query_strategy_part = "true";
  1814. $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
  1815. } else if ($feed <= -10) { // labels
  1816. $label_id = -$feed - 11;
  1817. $query_strategy_part = "label_id = '$label_id' AND
  1818. ttrss_labels2.id = ttrss_user_labels2.label_id AND
  1819. ttrss_user_labels2.article_id = ref_id";
  1820. $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
  1821. $ext_tables_part = ",ttrss_labels2,ttrss_user_labels2";
  1822. $allow_archived = true;
  1823. } else {
  1824. $query_strategy_part = "true";
  1825. }
  1826. if (get_pref($link, "SORT_HEADLINES_BY_FEED_DATE", $owner_uid)) {
  1827. $date_sort_field = "updated";
  1828. } else {
  1829. $date_sort_field = "date_entered";
  1830. }
  1831. if (get_pref($link, 'REVERSE_HEADLINES', $owner_uid)) {
  1832. $order_by = "$date_sort_field";
  1833. } else {
  1834. $order_by = "$date_sort_field DESC";
  1835. }
  1836. if ($view_mode != "noscores") {
  1837. $order_by = "score DESC, $order_by";
  1838. }
  1839. if ($override_order) {
  1840. $order_by = $override_order;
  1841. }
  1842. $feed_title = "";
  1843. if ($search) {
  1844. $feed_title = T_sprintf("Search results: %s", $search);
  1845. } else {
  1846. if ($cat_view) {
  1847. $feed_title = getCategoryTitle($link, $feed);
  1848. } else {
  1849. if (is_numeric($feed) && $feed > 0) {
  1850. $result = db_query($link, "SELECT title,site_url,last_error
  1851. FROM ttrss_feeds WHERE id = '$feed' AND owner_uid = $owner_uid");
  1852. $feed_title = db_fetch_result($result, 0, "title");
  1853. $feed_site_url = db_fetch_result($result, 0, "site_url");
  1854. $last_error = db_fetch_result($result, 0, "last_error");
  1855. } else {
  1856. $feed_title = getFeedTitle($link, $feed);
  1857. }
  1858. }
  1859. }
  1860. $content_query_part = "content as content_preview, cached_content, ";
  1861. if (is_numeric($feed)) {
  1862. if ($feed >= 0) {
  1863. $feed_kind = "Feeds";
  1864. } else {
  1865. $feed_kind = "Labels";
  1866. }
  1867. if ($limit_query_part) {
  1868. $offset_query_part = "OFFSET $offset";
  1869. }
  1870. // proper override_order applied above
  1871. if ($vfeed_query_part && !$ignore_vfeed_group && get_pref($link, 'VFEED_GROUP_BY_FEED', $owner_uid)) {
  1872. if (!$override_order) {
  1873. $order_by = "ttrss_feeds.title, $order_by";
  1874. } else {
  1875. $order_by = "ttrss_feeds.title, $override_order";
  1876. }
  1877. }
  1878. if (!$allow_archived) {
  1879. $from_qpart = "ttrss_entries,ttrss_user_entries,ttrss_feeds$ext_tables_part";
  1880. $feed_check_qpart = "ttrss_user_entries.feed_id = ttrss_feeds.id AND";
  1881. } else {
  1882. $from_qpart = "ttrss_entries$ext_tables_part,ttrss_user_entries
  1883. LEFT JOIN ttrss_feeds ON (feed_id = ttrss_feeds.id)";
  1884. }
  1885. $query = "SELECT DISTINCT
  1886. date_entered,
  1887. guid,
  1888. ttrss_entries.id,ttrss_entries.title,
  1889. updated,
  1890. label_cache,
  1891. tag_cache,
  1892. always_display_enclosures,
  1893. site_url,
  1894. note,
  1895. num_comments,
  1896. comments,
  1897. int_id,
  1898. hide_images,
  1899. unread,feed_id,marked,published,link,last_read,orig_feed_id,
  1900. last_marked, last_published,
  1901. ".SUBSTRING_FOR_DATE."(last_read,1,19) as last_read_noms,
  1902. $vfeed_query_part
  1903. $content_query_part
  1904. ".SUBSTRING_FOR_DATE."(updated,1,19) as updated_noms,
  1905. author,score
  1906. FROM
  1907. $from_qpart
  1908. WHERE
  1909. $feed_check_qpart
  1910. ttrss_user_entries.ref_id = ttrss_entries.id AND
  1911. ttrss_user_entries.owner_uid = '$owner_uid' AND
  1912. $search_query_part
  1913. $filter_query_part
  1914. $view_query_part
  1915. $since_id_part
  1916. $query_strategy_part ORDER BY $order_by
  1917. $limit_query_part $offset_query_part";
  1918. if ($_REQUEST["debug"]) print $query;
  1919. $result = db_query($link, $query);
  1920. } else {
  1921. // browsing by tag
  1922. $select_qpart = "SELECT DISTINCT " .
  1923. "date_entered," .
  1924. "guid," .
  1925. "note," .
  1926. "ttrss_entries.id as id," .
  1927. "title," .
  1928. "updated," .
  1929. "unread," .
  1930. "feed_id," .
  1931. "orig_feed_id," .
  1932. "marked," .
  1933. "num_comments, " .
  1934. "comments, " .
  1935. "tag_cache," .
  1936. "label_cache," .
  1937. "link," .
  1938. "last_read," .
  1939. "hide_images," .
  1940. "last_marked, last_published, " .
  1941. SUBSTRING_FOR_DATE . "(last_read,1,19) as last_read_noms," .
  1942. $since_id_part .
  1943. $vfeed_query_part .
  1944. $content_query_part .
  1945. SUBSTRING_FOR_DATE . "(updated,1,19) as updated_noms," .
  1946. "score ";
  1947. $feed_kind = "Tags";
  1948. $all_tags = explode(",", $feed);
  1949. if ($search_mode == 'any') {
  1950. $tag_sql = "tag_name in (" . implode(", ", array_map("db_quote", $all_tags)) . ")";
  1951. $from_qpart = " FROM ttrss_entries,ttrss_user_entries,ttrss_tags ";
  1952. $where_qpart = " WHERE " .
  1953. "ref_id = ttrss_entries.id AND " .
  1954. "ttrss_user_entries.owner_uid = $owner_uid AND " .
  1955. "post_int_id = int_id AND $tag_sql AND " .
  1956. $view_query_part .
  1957. $search_query_part .
  1958. $query_strategy_part . " ORDER BY $order_by " .
  1959. $limit_query_part;
  1960. } else {
  1961. $i = 1;
  1962. $sub_selects = array();
  1963. $sub_ands = array();
  1964. foreach ($all_tags as $term) {
  1965. 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");
  1966. $i++;
  1967. }
  1968. if ($i > 2) {
  1969. $x = 1;
  1970. $y = 2;
  1971. do {
  1972. array_push($sub_ands, "A$x.post_int_id = A$y.post_int_id");
  1973. $x++;
  1974. $y++;
  1975. } while ($y < $i);
  1976. }
  1977. array_push($sub_ands, "A1.post_int_id = ttrss_user_entries.int_id and ttrss_user_entries.owner_uid = $owner_uid");
  1978. array_push($sub_ands, "ttrss_user_entries.ref_id = ttrss_entries.id");
  1979. $from_qpart = " FROM " . implode(", ", $sub_selects) . ", ttrss_user_entries, ttrss_entries";
  1980. $where_qpart = " WHERE " . implode(" AND ", $sub_ands);
  1981. }
  1982. // error_log("TAG SQL: " . $tag_sql);
  1983. // $tag_sql = "tag_name = '$feed'"; DEFAULT way
  1984. // error_log("[". $select_qpart . "][" . $from_qpart . "][" .$where_qpart . "]");
  1985. $result = db_query($link, $select_qpart . $from_qpart . $where_qpart);
  1986. }
  1987. return array($result, $feed_title, $feed_site_url, $last_error);
  1988. }
  1989. function sanitize($link, $str, $force_remove_images = false, $owner = false, $site_url = false) {
  1990. if (!$owner) $owner = $_SESSION["uid"];
  1991. $res = trim($str); if (!$res) return '';
  1992. if (strpos($res, "href=") === false)
  1993. $res = rewrite_urls($res);
  1994. $charset_hack = '<head>
  1995. <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
  1996. </head>';
  1997. $res = trim($res); if (!$res) return '';
  1998. libxml_use_internal_errors(true);
  1999. $doc = new DOMDocument();
  2000. $doc->loadHTML($charset_hack . $res);
  2001. $xpath = new DOMXPath($doc);
  2002. $entries = $xpath->query('(//a[@href]|//img[@src])');
  2003. foreach ($entries as $entry) {
  2004. if ($site_url) {
  2005. if ($entry->hasAttribute('href'))
  2006. $entry->setAttribute('href',
  2007. rewrite_relative_url($site_url, $entry->getAttribute('href')));
  2008. if ($entry->hasAttribute('src')) {
  2009. $src = rewrite_relative_url($site_url, $entry->getAttribute('src'));
  2010. $cached_filename = CACHE_DIR . '/images/' . sha1($src) . '.png';
  2011. if (file_exists($cached_filename)) {
  2012. $src = SELF_URL_PATH . '/image.php?hash=' . sha1($src);
  2013. }
  2014. $entry->setAttribute('src', $src);
  2015. }
  2016. if ($entry->nodeName == 'img') {
  2017. if (($owner && get_pref($link, "STRIP_IMAGES", $owner)) ||
  2018. $force_remove_images) {
  2019. $p = $doc->createElement('p');
  2020. $a = $doc->createElement('a');
  2021. $a->setAttribute('href', $entry->getAttribute('src'));
  2022. $a->appendChild(new DOMText($entry->getAttribute('src')));
  2023. $a->setAttribute('target', '_blank');
  2024. $p->appendChild($a);
  2025. $entry->parentNode->replaceChild($p, $entry);
  2026. }
  2027. }
  2028. }
  2029. if (strtolower($entry->nodeName) == "a") {
  2030. $entry->setAttribute("target", "_blank");
  2031. }
  2032. }
  2033. $entries = $xpath->query('//iframe');
  2034. foreach ($entries as $entry) {
  2035. $entry->setAttribute('sandbox', true);
  2036. }
  2037. global $pluginhost;
  2038. if (isset($pluginhost)) {
  2039. foreach ($pluginhost->get_hooks($pluginhost::HOOK_SANITIZE) as $plugin) {
  2040. $doc = $plugin->hook_sanitize($doc, $site_url);
  2041. }
  2042. }
  2043. $doc->removeChild($doc->firstChild); //remove doctype
  2044. $doc = strip_harmful_tags($doc);
  2045. $res = $doc->saveHTML();
  2046. return $res;
  2047. }
  2048. function strip_harmful_tags($doc) {
  2049. $entries = $doc->getElementsByTagName("*");
  2050. $allowed_elements = array('a', 'address', 'audio', 'article',
  2051. 'b', 'big', 'blockquote', 'body', 'br', 'cite',
  2052. 'code', 'dd', 'del', 'details', 'div', 'dl',
  2053. 'dt', 'em', 'footer', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6',
  2054. 'header', 'html', 'i', 'img', 'ins', 'kbd',
  2055. 'li', 'nav', 'ol', 'p', 'pre', 'q', 's','small',
  2056. 'source', 'span', 'strike', 'strong', 'sub', 'summary',
  2057. 'sup', 'table', 'tbody', 'td', 'tfoot', 'th', 'thead',
  2058. 'tr', 'track', 'tt', 'u', 'ul', 'var', 'wbr', 'video' );
  2059. if ($_SESSION['hasSandbox']) array_push($allowed_elements, 'iframe');
  2060. $disallowed_attributes = array('id', 'style', 'class');
  2061. foreach ($entries as $entry) {
  2062. if (!in_array($entry->nodeName, $allowed_elements)) {
  2063. $entry->parentNode->removeChild($entry);
  2064. }
  2065. if ($entry->hasAttributes()) {
  2066. foreach (iterator_to_array($entry->attributes) as $attr) {
  2067. if (strpos($attr->nodeName, 'on') === 0) {
  2068. $entry->removeAttributeNode($attr);
  2069. }
  2070. if (in_array($attr->nodeName, $disallowed_attributes)) {
  2071. $entry->removeAttributeNode($attr);
  2072. }
  2073. }
  2074. }
  2075. }
  2076. return $doc;
  2077. }
  2078. function check_for_update($link) {
  2079. if (CHECK_FOR_NEW_VERSION && $_SESSION['access_level'] >= 10) {
  2080. $version_url = "http://tt-rss.org/version.php?ver=" . VERSION .
  2081. "&iid=" . sha1(SELF_URL_PATH);
  2082. $version_data = @fetch_file_contents($version_url);
  2083. if ($version_data) {
  2084. $version_data = json_decode($version_data, true);
  2085. if ($version_data && $version_data['version']) {
  2086. if (version_compare(VERSION, $version_data['version']) == -1) {
  2087. return $version_data;
  2088. }
  2089. }
  2090. }
  2091. }
  2092. return false;
  2093. }
  2094. function catchupArticlesById($link, $ids, $cmode, $owner_uid = false) {
  2095. if (!$owner_uid) $owner_uid = $_SESSION["uid"];
  2096. if (count($ids) == 0) return;
  2097. $tmp_ids = array();
  2098. foreach ($ids as $id) {
  2099. array_push($tmp_ids, "ref_id = '$id'");
  2100. }
  2101. $ids_qpart = join(" OR ", $tmp_ids);
  2102. if ($cmode == 0) {
  2103. db_query($link, "UPDATE ttrss_user_entries SET
  2104. unread = false,last_read = NOW()
  2105. WHERE ($ids_qpart) AND owner_uid = $owner_uid");
  2106. } else if ($cmode == 1) {
  2107. db_query($link, "UPDATE ttrss_user_entries SET
  2108. unread = true
  2109. WHERE ($ids_qpart) AND owner_uid = $owner_uid");
  2110. } else {
  2111. db_query($link, "UPDATE ttrss_user_entries SET
  2112. unread = NOT unread,last_read = NOW()
  2113. WHERE ($ids_qpart) AND owner_uid = $owner_uid");
  2114. }
  2115. /* update ccache */
  2116. $result = db_query($link, "SELECT DISTINCT feed_id FROM ttrss_user_entries
  2117. WHERE ($ids_qpart) AND owner_uid = $owner_uid");
  2118. while ($line = db_fetch_assoc($result)) {
  2119. ccache_update($link, $line["feed_id"], $owner_uid);
  2120. }
  2121. }
  2122. function get_article_tags($link, $id, $owner_uid = 0, $tag_cache = false) {
  2123. $a_id = db_escape_string($id);
  2124. if (!$owner_uid) $owner_uid = $_SESSION["uid"];
  2125. $query = "SELECT DISTINCT tag_name,
  2126. owner_uid as owner FROM
  2127. ttrss_tags WHERE post_int_id = (SELECT int_id FROM ttrss_user_entries WHERE
  2128. ref_id = '$a_id' AND owner_uid = '$owner_uid' LIMIT 1) ORDER BY tag_name";
  2129. $obj_id = md5("TAGS:$owner_uid:$id");
  2130. $tags = array();
  2131. /* check cache first */
  2132. if ($tag_cache === false) {
  2133. $result = db_query($link, "SELECT tag_cache FROM ttrss_user_entries
  2134. WHERE ref_id = '$id' AND owner_uid = $owner_uid");
  2135. $tag_cache = db_fetch_result($result, 0, "tag_cache");
  2136. }
  2137. if ($tag_cache) {
  2138. $tags = explode(",", $tag_cache);
  2139. } else {
  2140. /* do it the hard way */
  2141. $tmp_result = db_query($link, $query);
  2142. while ($tmp_line = db_fetch_assoc($tmp_result)) {
  2143. array_push($tags, $tmp_line["tag_name"]);
  2144. }
  2145. /* update the cache */
  2146. $tags_str = db_escape_string(join(",", $tags));
  2147. db_query($link, "UPDATE ttrss_user_entries
  2148. SET tag_cache = '$tags_str' WHERE ref_id = '$id'
  2149. AND owner_uid = $owner_uid");
  2150. }
  2151. return $tags;
  2152. }
  2153. function trim_array($array) {
  2154. $tmp = $array;
  2155. array_walk($tmp, 'trim');
  2156. return $tmp;
  2157. }
  2158. function tag_is_valid($tag) {
  2159. if ($tag == '') return false;
  2160. if (preg_match("/^[0-9]*$/", $tag)) return false;
  2161. if (mb_strlen($tag) > 250) return false;
  2162. if (function_exists('iconv')) {
  2163. $tag = iconv("utf-8", "utf-8", $tag);
  2164. }
  2165. if (!$tag) return false;
  2166. return true;
  2167. }
  2168. function render_login_form($link, $form_id = 0) {
  2169. switch ($form_id) {
  2170. case 0:
  2171. require_once "login_form.php";
  2172. break;
  2173. case 1:
  2174. require_once "mobile/login_form.php";
  2175. break;
  2176. }
  2177. exit;
  2178. }
  2179. // from http://developer.apple.com/internet/safari/faq.html
  2180. function no_cache_incantation() {
  2181. header("Expires: Mon, 22 Dec 1980 00:00:00 GMT"); // Happy birthday to me :)
  2182. header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT"); // always modified
  2183. header("Cache-Control: no-store, no-cache, must-revalidate, max-age=0"); // HTTP/1.1
  2184. header("Cache-Control: post-check=0, pre-check=0", false);
  2185. header("Pragma: no-cache"); // HTTP/1.0
  2186. }
  2187. function format_warning($msg, $id = "") {
  2188. global $link;
  2189. return "<div class=\"warning\" id=\"$id\">
  2190. <img src=\"".theme_image($link, "images/sign_excl.svg")."\">$msg</div>";
  2191. }
  2192. function format_notice($msg, $id = "") {
  2193. global $link;
  2194. return "<div class=\"notice\" id=\"$id\">
  2195. <img src=\"".theme_image($link, "images/sign_info.svg")."\">$msg</div>";
  2196. }
  2197. function format_error($msg, $id = "") {
  2198. global $link;
  2199. return "<div class=\"error\" id=\"$id\">
  2200. <img src=\"".theme_image($link, "images/sign_excl.svg")."\">$msg</div>";
  2201. }
  2202. function print_notice($msg) {
  2203. return print format_notice($msg);
  2204. }
  2205. function print_warning($msg) {
  2206. return print format_warning($msg);
  2207. }
  2208. function print_error($msg) {
  2209. return print format_error($msg);
  2210. }
  2211. function T_sprintf() {
  2212. $args = func_get_args();
  2213. return vsprintf(__(array_shift($args)), $args);
  2214. }
  2215. function format_inline_player($link, $url, $ctype) {
  2216. $entry = "";
  2217. $url = htmlspecialchars($url);
  2218. if (strpos($ctype, "audio/") === 0) {
  2219. if ($_SESSION["hasAudio"] && (strpos($ctype, "ogg") !== false ||
  2220. strpos($_SERVER['HTTP_USER_AGENT'], "Chrome") !== false ||
  2221. strpos($_SERVER['HTTP_USER_AGENT'], "Safari") !== false )) {
  2222. $id = 'AUDIO-' . uniqid();
  2223. $entry .= "<audio id=\"$id\"\" controls style='display : none'>
  2224. <source type=\"$ctype\" src=\"$url\"></source>
  2225. </audio>";
  2226. $entry .= "<span onclick=\"player(this)\"
  2227. title=\"".__("Click to play")."\" status=\"0\"
  2228. class=\"player\" audio-id=\"$id\">".__("Play")."</span>";
  2229. } else {
  2230. $entry .= "<object type=\"application/x-shockwave-flash\"
  2231. data=\"lib/button/musicplayer.swf?song_url=$url\"
  2232. width=\"17\" height=\"17\" style='float : left; margin-right : 5px;'>
  2233. <param name=\"movie\"
  2234. value=\"lib/button/musicplayer.swf?song_url=$url\" />
  2235. </object>";
  2236. }
  2237. if ($entry) $entry .= "&nbsp; <a target=\"_blank\"
  2238. href=\"$url\">" . basename($url) . "</a>";
  2239. return $entry;
  2240. }
  2241. return "";
  2242. /* $filename = substr($url, strrpos($url, "/")+1);
  2243. $entry .= " <a target=\"_blank\" href=\"" . htmlspecialchars($url) . "\">" .
  2244. $filename . " (" . $ctype . ")" . "</a>"; */
  2245. }
  2246. function format_article($link, $id, $mark_as_read = true, $zoom_mode = false, $owner_uid = false) {
  2247. if (!$owner_uid) $owner_uid = $_SESSION["uid"];
  2248. $rv = array();
  2249. $rv['id'] = $id;
  2250. /* we can figure out feed_id from article id anyway, why do we
  2251. * pass feed_id here? let's ignore the argument :( */
  2252. $result = db_query($link, "SELECT feed_id FROM ttrss_user_entries
  2253. WHERE ref_id = '$id'");
  2254. $feed_id = (int) db_fetch_result($result, 0, "feed_id");
  2255. $rv['feed_id'] = $feed_id;
  2256. //if (!$zoom_mode) { print "<article id='$id'><![CDATA["; };
  2257. if ($mark_as_read) {
  2258. $result = db_query($link, "UPDATE ttrss_user_entries
  2259. SET unread = false,last_read = NOW()
  2260. WHERE ref_id = '$id' AND owner_uid = $owner_uid");
  2261. ccache_update($link, $feed_id, $owner_uid);
  2262. }
  2263. $result = db_query($link, "SELECT id,title,link,content,feed_id,comments,int_id,
  2264. ".SUBSTRING_FOR_DATE."(updated,1,16) as updated,
  2265. (SELECT site_url FROM ttrss_feeds WHERE id = feed_id) as site_url,
  2266. num_comments,
  2267. tag_cache,
  2268. author,
  2269. orig_feed_id,
  2270. note,
  2271. cached_content
  2272. FROM ttrss_entries,ttrss_user_entries
  2273. WHERE id = '$id' AND ref_id = id AND owner_uid = $owner_uid");
  2274. if ($result) {
  2275. $line = db_fetch_assoc($result);
  2276. $tag_cache = $line["tag_cache"];
  2277. $line["tags"] = get_article_tags($link, $id, $owner_uid, $line["tag_cache"]);
  2278. unset($line["tag_cache"]);
  2279. $line["content"] = sanitize($link, $line["content"], false, $owner_uid, $line["site_url"]);
  2280. global $pluginhost;
  2281. foreach ($pluginhost->get_hooks($pluginhost::HOOK_RENDER_ARTICLE) as $p) {
  2282. $line = $p->hook_render_article($line);
  2283. }
  2284. $num_comments = $line["num_comments"];
  2285. $entry_comments = "";
  2286. if ($num_comments > 0) {
  2287. if ($line["comments"]) {
  2288. $comments_url = htmlspecialchars($line["comments"]);
  2289. } else {
  2290. $comments_url = htmlspecialchars($line["link"]);
  2291. }
  2292. $entry_comments = "<a target='_blank' href=\"$comments_url\">$num_comments comments</a>";
  2293. } else {
  2294. if ($line["comments"] && $line["link"] != $line["comments"]) {
  2295. $entry_comments = "<a target='_blank' href=\"".htmlspecialchars($line["comments"])."\">comments</a>";
  2296. }
  2297. }
  2298. if ($zoom_mode) {
  2299. header("Content-Type: text/html");
  2300. $rv['content'] .= "<html><head>
  2301. <meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\"/>
  2302. <title>Tiny Tiny RSS - ".$line["title"]."</title>
  2303. <link rel=\"stylesheet\" type=\"text/css\" href=\"tt-rss.css\">
  2304. </head><body>";
  2305. }
  2306. $title_escaped = htmlspecialchars($line['title']);
  2307. $rv['content'] .= "<div id=\"PTITLE-FULL-$id\" style=\"display : none\">" .
  2308. strip_tags($line['title']) . "</div>";
  2309. $rv['content'] .= "<div class=\"postReply\" id=\"POST-$id\">";
  2310. $rv['content'] .= "<div class=\"postHeader\" id=\"POSTHDR-$id\">";
  2311. $entry_author = $line["author"];
  2312. if ($entry_author) {
  2313. $entry_author = __(" - ") . $entry_author;
  2314. }
  2315. $parsed_updated = make_local_datetime($link, $line["updated"], true,
  2316. $owner_uid, true);
  2317. $rv['content'] .= "<div class=\"postDate\">$parsed_updated</div>";
  2318. if ($line["link"]) {
  2319. $rv['content'] .= "<div class='postTitle'><a target='_blank'
  2320. title=\"".htmlspecialchars($line['title'])."\"
  2321. href=\"" .
  2322. htmlspecialchars($line["link"]) . "\">" .
  2323. $line["title"] .
  2324. "<span class='author'>$entry_author</span></a></div>";
  2325. } else {
  2326. $rv['content'] .= "<div class='postTitle'>" . $line["title"] . "$entry_author</div>";
  2327. }
  2328. $tags_str = format_tags_string($line["tags"], $id);
  2329. $tags_str_full = join(", ", $line["tags"]);
  2330. if (!$tags_str_full) $tags_str_full = __("no tags");
  2331. if (!$entry_comments) $entry_comments = "&nbsp;"; # placeholder
  2332. $rv['content'] .= "<div class='postTags' style='float : right'>
  2333. <img src='".theme_image($link, 'images/tag.png')."'
  2334. class='tagsPic' alt='Tags' title='Tags'>&nbsp;";
  2335. if (!$zoom_mode) {
  2336. $rv['content'] .= "<span id=\"ATSTR-$id\">$tags_str</span>
  2337. <a title=\"".__('Edit tags for this article')."\"
  2338. href=\"#\" onclick=\"editArticleTags($id, $feed_id)\">(+)</a>";
  2339. $rv['content'] .= "<div dojoType=\"dijit.Tooltip\"
  2340. id=\"ATSTRTIP-$id\" connectId=\"ATSTR-$id\"
  2341. position=\"below\">$tags_str_full</div>";
  2342. global $pluginhost;
  2343. foreach ($pluginhost->get_hooks($pluginhost::HOOK_ARTICLE_BUTTON) as $p) {
  2344. $rv['content'] .= $p->hook_article_button($line);
  2345. }
  2346. } else {
  2347. $tags_str = strip_tags($tags_str);
  2348. $rv['content'] .= "<span id=\"ATSTR-$id\">$tags_str</span>";
  2349. }
  2350. $rv['content'] .= "</div>";
  2351. $rv['content'] .= "<div clear='both'>$entry_comments</div>";
  2352. if ($line["orig_feed_id"]) {
  2353. $tmp_result = db_query($link, "SELECT * FROM ttrss_archived_feeds
  2354. WHERE id = ".$line["orig_feed_id"]);
  2355. if (db_num_rows($tmp_result) != 0) {
  2356. $rv['content'] .= "<div clear='both'>";
  2357. $rv['content'] .= __("Originally from:");
  2358. $rv['content'] .= "&nbsp;";
  2359. $tmp_line = db_fetch_assoc($tmp_result);
  2360. $rv['content'] .= "<a target='_blank'
  2361. href=' " . htmlspecialchars($tmp_line['site_url']) . "'>" .
  2362. $tmp_line['title'] . "</a>";
  2363. $rv['content'] .= "&nbsp;";
  2364. $rv['content'] .= "<a target='_blank' href='" . htmlspecialchars($tmp_line['feed_url']) . "'>";
  2365. $rv['content'] .= "<img title='".__('Feed URL')."'class='tinyFeedIcon' src='images/pub_set.svg'></a>";
  2366. $rv['content'] .= "</div>";
  2367. }
  2368. }
  2369. $rv['content'] .= "</div>";
  2370. $rv['content'] .= "<div id=\"POSTNOTE-$id\">";
  2371. if ($line['note']) {
  2372. $rv['content'] .= format_article_note($id, $line['note'], !$zoom_mode);
  2373. }
  2374. $rv['content'] .= "</div>";
  2375. $rv['content'] .= "<div class=\"postContent\">";
  2376. // N-grams
  2377. if (DB_TYPE == "pgsql" and defined('_NGRAM_TITLE_RELATED_THRESHOLD')) {
  2378. $ngram_result = db_query($link, "SELECT id,title FROM
  2379. ttrss_entries,ttrss_user_entries
  2380. WHERE ref_id = id AND updated >= NOW() - INTERVAL '7 day'
  2381. AND similarity(title, '$title_escaped') >= "._NGRAM_TITLE_RELATED_THRESHOLD."
  2382. AND title != '$title_escaped'
  2383. AND owner_uid = $owner_uid");
  2384. if (db_num_rows($ngram_result) > 0) {
  2385. $rv['content'] .= "<div dojoType=\"dijit.form.DropDownButton\">".
  2386. "<span>" . __('Related')."</span>";
  2387. $rv['content'] .= "<div dojoType=\"dijit.Menu\" style=\"display: none;\">";
  2388. while ($nline = db_fetch_assoc($ngram_result)) {
  2389. $rv['content'] .= "<div onclick=\"hlOpenInNewTab(null,".$nline['id'].")\"
  2390. dojoType=\"dijit.MenuItem\">".$nline['title']."</div>";
  2391. }
  2392. $rv['content'] .= "</div></div><br/";
  2393. }
  2394. }
  2395. $rv['content'] .= $line["content"];
  2396. $rv['content'] .= format_article_enclosures($link, $id,
  2397. $always_display_enclosures, $line["content"]);
  2398. $rv['content'] .= "</div>";
  2399. $rv['content'] .= "</div>";
  2400. }
  2401. if ($zoom_mode) {
  2402. $rv['content'] .= "
  2403. <div style=\"text-align : center\">
  2404. <button onclick=\"return window.close()\">".
  2405. __("Close this window")."</button></div>";
  2406. $rv['content'] .= "</body></html>";
  2407. }
  2408. return $rv;
  2409. }
  2410. function print_checkpoint($n, $s) {
  2411. $ts = microtime(true);
  2412. echo sprintf("<!-- CP[$n] %.4f seconds -->", $ts - $s);
  2413. return $ts;
  2414. }
  2415. function sanitize_tag($tag) {
  2416. $tag = trim($tag);
  2417. $tag = mb_strtolower($tag, 'utf-8');
  2418. $tag = preg_replace('/[\'\"\+\>\<]/', "", $tag);
  2419. // $tag = str_replace('"', "", $tag);
  2420. // $tag = str_replace("+", " ", $tag);
  2421. $tag = str_replace("technorati tag: ", "", $tag);
  2422. return $tag;
  2423. }
  2424. function get_self_url_prefix() {
  2425. if (strrpos(SELF_URL_PATH, "/") === strlen(SELF_URL_PATH)-1) {
  2426. return substr(SELF_URL_PATH, 0, strlen(SELF_URL_PATH)-1);
  2427. } else {
  2428. return SELF_URL_PATH;
  2429. }
  2430. }
  2431. /**
  2432. * Compute the Mozilla Firefox feed adding URL from server HOST and REQUEST_URI.
  2433. *
  2434. * @return string The Mozilla Firefox feed adding URL.
  2435. */
  2436. function add_feed_url() {
  2437. //$url_path = ($_SERVER['HTTPS'] != "on" ? 'http://' : 'https://') . $_SERVER["HTTP_HOST"] . parse_url($_SERVER["REQUEST_URI"], PHP_URL_PATH);
  2438. $url_path = get_self_url_prefix() .
  2439. "/public.php?op=subscribe&feed_url=%s";
  2440. return $url_path;
  2441. } // function add_feed_url
  2442. function encrypt_password($pass, $salt = '', $mode2 = false) {
  2443. if ($salt && $mode2) {
  2444. return "MODE2:" . hash('sha256', $salt . $pass);
  2445. } else if ($salt) {
  2446. return "SHA1X:" . sha1("$salt:$pass");
  2447. } else {
  2448. return "SHA1:" . sha1($pass);
  2449. }
  2450. } // function encrypt_password
  2451. function load_filters($link, $feed_id, $owner_uid, $action_id = false) {
  2452. $filters = array();
  2453. $cat_id = (int)getFeedCategory($link, $feed_id);
  2454. $result = db_query($link, "SELECT * FROM ttrss_filters2 WHERE
  2455. owner_uid = $owner_uid AND enabled = true");
  2456. $check_cats = join(",", array_merge(
  2457. getParentCategories($link, $cat_id, $owner_uid),
  2458. array($cat_id)));
  2459. while ($line = db_fetch_assoc($result)) {
  2460. $filter_id = $line["id"];
  2461. $result2 = db_query($link, "SELECT
  2462. r.reg_exp, r.feed_id, r.cat_id, r.cat_filter, t.name AS type_name
  2463. FROM ttrss_filters2_rules AS r,
  2464. ttrss_filter_types AS t
  2465. WHERE
  2466. (cat_id IS NULL OR cat_id IN ($check_cats)) AND
  2467. (feed_id IS NULL OR feed_id = '$feed_id') AND
  2468. filter_type = t.id AND filter_id = '$filter_id'");
  2469. $rules = array();
  2470. $actions = array();
  2471. while ($rule_line = db_fetch_assoc($result2)) {
  2472. # print_r($rule_line);
  2473. $rule = array();
  2474. $rule["reg_exp"] = $rule_line["reg_exp"];
  2475. $rule["type"] = $rule_line["type_name"];
  2476. array_push($rules, $rule);
  2477. }
  2478. $result2 = db_query($link, "SELECT a.action_param,t.name AS type_name
  2479. FROM ttrss_filters2_actions AS a,
  2480. ttrss_filter_actions AS t
  2481. WHERE
  2482. action_id = t.id AND filter_id = '$filter_id'");
  2483. while ($action_line = db_fetch_assoc($result2)) {
  2484. # print_r($action_line);
  2485. $action = array();
  2486. $action["type"] = $action_line["type_name"];
  2487. $action["param"] = $action_line["action_param"];
  2488. array_push($actions, $action);
  2489. }
  2490. $filter = array();
  2491. $filter["match_any_rule"] = sql_bool_to_bool($line["match_any_rule"]);
  2492. $filter["rules"] = $rules;
  2493. $filter["actions"] = $actions;
  2494. if (count($rules) > 0 && count($actions) > 0) {
  2495. array_push($filters, $filter);
  2496. }
  2497. }
  2498. return $filters;
  2499. }
  2500. function get_score_pic($score) {
  2501. if ($score > 100) {
  2502. return "score_high.png";
  2503. } else if ($score > 0) {
  2504. return "score_half_high.png";
  2505. } else if ($score < -100) {
  2506. return "score_low.png";
  2507. } else if ($score < 0) {
  2508. return "score_half_low.png";
  2509. } else {
  2510. return "score_neutral.png";
  2511. }
  2512. }
  2513. function feed_has_icon($id) {
  2514. return is_file(ICONS_DIR . "/$id.ico") && filesize(ICONS_DIR . "/$id.ico") > 0;
  2515. }
  2516. function init_connection($link) {
  2517. if ($link) {
  2518. if (DB_TYPE == "pgsql") {
  2519. pg_query($link, "set client_encoding = 'UTF-8'");
  2520. pg_set_client_encoding("UNICODE");
  2521. pg_query($link, "set datestyle = 'ISO, european'");
  2522. pg_query($link, "set TIME ZONE 0");
  2523. } else {
  2524. db_query($link, "SET time_zone = '+0:0'");
  2525. if (defined('MYSQL_CHARSET') && MYSQL_CHARSET) {
  2526. db_query($link, "SET NAMES " . MYSQL_CHARSET);
  2527. }
  2528. }
  2529. global $pluginhost;
  2530. $pluginhost = new PluginHost($link);
  2531. $pluginhost->load(PLUGINS, $pluginhost::KIND_ALL);
  2532. return true;
  2533. } else {
  2534. print "Unable to connect to database:" . db_last_error();
  2535. return false;
  2536. }
  2537. }
  2538. function format_tags_string($tags, $id) {
  2539. $tags_str = "";
  2540. $tags_nolinks_str = "";
  2541. $num_tags = 0;
  2542. $tag_limit = 6;
  2543. $formatted_tags = array();
  2544. foreach ($tags as $tag) {
  2545. $num_tags++;
  2546. $tag_escaped = str_replace("'", "\\'", $tag);
  2547. if (mb_strlen($tag) > 30) {
  2548. $tag = truncate_string($tag, 30);
  2549. }
  2550. $tag_str = "<a href=\"javascript:viewfeed('$tag_escaped')\">$tag</a>";
  2551. array_push($formatted_tags, $tag_str);
  2552. $tmp_tags_str = implode(", ", $formatted_tags);
  2553. if ($num_tags == $tag_limit || mb_strlen($tmp_tags_str) > 150) {
  2554. break;
  2555. }
  2556. }
  2557. $tags_str = implode(", ", $formatted_tags);
  2558. if ($num_tags < count($tags)) {
  2559. $tags_str .= ", &hellip;";
  2560. }
  2561. if ($num_tags == 0) {
  2562. $tags_str = __("no tags");
  2563. }
  2564. return $tags_str;
  2565. }
  2566. function format_article_labels($labels, $id) {
  2567. $labels_str = "";
  2568. foreach ($labels as $l) {
  2569. $labels_str .= sprintf("<span class='hlLabelRef'
  2570. style='color : %s; background-color : %s'>%s</span>",
  2571. $l[2], $l[3], $l[1]);
  2572. }
  2573. return $labels_str;
  2574. }
  2575. function format_article_note($id, $note, $allow_edit = true) {
  2576. $str = "<div class='articleNote' onclick=\"editArticleNote($id)\">
  2577. <div class='noteEdit' onclick=\"editArticleNote($id)\">".
  2578. ($allow_edit ? __('(edit note)') : "")."</div>$note</div>";
  2579. return $str;
  2580. }
  2581. function get_feed_category($link, $feed_cat, $parent_cat_id = false) {
  2582. if ($parent_cat_id) {
  2583. $parent_qpart = "parent_cat = '$parent_cat_id'";
  2584. $parent_insert = "'$parent_cat_id'";
  2585. } else {
  2586. $parent_qpart = "parent_cat IS NULL";
  2587. $parent_insert = "NULL";
  2588. }
  2589. $result = db_query($link,
  2590. "SELECT id FROM ttrss_feed_categories
  2591. WHERE $parent_qpart AND title = '$feed_cat' AND owner_uid = ".$_SESSION["uid"]);
  2592. if (db_num_rows($result) == 0) {
  2593. return false;
  2594. } else {
  2595. return db_fetch_result($result, 0, "id");
  2596. }
  2597. }
  2598. function add_feed_category($link, $feed_cat, $parent_cat_id = false) {
  2599. if (!$feed_cat) return false;
  2600. db_query($link, "BEGIN");
  2601. if ($parent_cat_id) {
  2602. $parent_qpart = "parent_cat = '$parent_cat_id'";
  2603. $parent_insert = "'$parent_cat_id'";
  2604. } else {
  2605. $parent_qpart = "parent_cat IS NULL";
  2606. $parent_insert = "NULL";
  2607. }
  2608. $result = db_query($link,
  2609. "SELECT id FROM ttrss_feed_categories
  2610. WHERE $parent_qpart AND title = '$feed_cat' AND owner_uid = ".$_SESSION["uid"]);
  2611. if (db_num_rows($result) == 0) {
  2612. $result = db_query($link,
  2613. "INSERT INTO ttrss_feed_categories (owner_uid,title,parent_cat)
  2614. VALUES ('".$_SESSION["uid"]."', '$feed_cat', $parent_insert)");
  2615. db_query($link, "COMMIT");
  2616. return true;
  2617. }
  2618. return false;
  2619. }
  2620. function getArticleFeed($link, $id) {
  2621. $result = db_query($link, "SELECT feed_id FROM ttrss_user_entries
  2622. WHERE ref_id = '$id' AND owner_uid = " . $_SESSION["uid"]);
  2623. if (db_num_rows($result) != 0) {
  2624. return db_fetch_result($result, 0, "feed_id");
  2625. } else {
  2626. return 0;
  2627. }
  2628. }
  2629. /**
  2630. * Fixes incomplete URLs by prepending "http://".
  2631. * Also replaces feed:// with http://, and
  2632. * prepends a trailing slash if the url is a domain name only.
  2633. *
  2634. * @param string $url Possibly incomplete URL
  2635. *
  2636. * @return string Fixed URL.
  2637. */
  2638. function fix_url($url) {
  2639. if (strpos($url, '://') === false) {
  2640. $url = 'http://' . $url;
  2641. } else if (substr($url, 0, 5) == 'feed:') {
  2642. $url = 'http:' . substr($url, 5);
  2643. }
  2644. //prepend slash if the URL has no slash in it
  2645. // "http://www.example" -> "http://www.example/"
  2646. if (strpos($url, '/', strpos($url, ':') + 3) === false) {
  2647. $url .= '/';
  2648. }
  2649. if ($url != "http:///")
  2650. return $url;
  2651. else
  2652. return '';
  2653. }
  2654. function validate_feed_url($url) {
  2655. $parts = parse_url($url);
  2656. return ($parts['scheme'] == 'http' || $parts['scheme'] == 'feed' || $parts['scheme'] == 'https');
  2657. }
  2658. function get_article_enclosures($link, $id) {
  2659. $query = "SELECT * FROM ttrss_enclosures
  2660. WHERE post_id = '$id' AND content_url != ''";
  2661. $rv = array();
  2662. $result = db_query($link, $query);
  2663. if (db_num_rows($result) > 0) {
  2664. while ($line = db_fetch_assoc($result)) {
  2665. array_push($rv, $line);
  2666. }
  2667. }
  2668. return $rv;
  2669. }
  2670. function save_email_address($link, $email) {
  2671. // FIXME: implement persistent storage of emails
  2672. if (!$_SESSION['stored_emails'])
  2673. $_SESSION['stored_emails'] = array();
  2674. if (!in_array($email, $_SESSION['stored_emails']))
  2675. array_push($_SESSION['stored_emails'], $email);
  2676. }
  2677. function get_feed_access_key($link, $feed_id, $is_cat, $owner_uid = false) {
  2678. if (!$owner_uid) $owner_uid = $_SESSION["uid"];
  2679. $sql_is_cat = bool_to_sql_bool($is_cat);
  2680. $result = db_query($link, "SELECT access_key FROM ttrss_access_keys
  2681. WHERE feed_id = '$feed_id' AND is_cat = $sql_is_cat
  2682. AND owner_uid = " . $owner_uid);
  2683. if (db_num_rows($result) == 1) {
  2684. return db_fetch_result($result, 0, "access_key");
  2685. } else {
  2686. $key = db_escape_string(sha1(uniqid(rand(), true)));
  2687. $result = db_query($link, "INSERT INTO ttrss_access_keys
  2688. (access_key, feed_id, is_cat, owner_uid)
  2689. VALUES ('$key', '$feed_id', $sql_is_cat, '$owner_uid')");
  2690. return $key;
  2691. }
  2692. return false;
  2693. }
  2694. function get_feeds_from_html($url, $content)
  2695. {
  2696. $url = fix_url($url);
  2697. $baseUrl = substr($url, 0, strrpos($url, '/') + 1);
  2698. libxml_use_internal_errors(true);
  2699. $doc = new DOMDocument();
  2700. $doc->loadHTML($content);
  2701. $xpath = new DOMXPath($doc);
  2702. $entries = $xpath->query('/html/head/link[@rel="alternate"]');
  2703. $feedUrls = array();
  2704. foreach ($entries as $entry) {
  2705. if ($entry->hasAttribute('href')) {
  2706. $title = $entry->getAttribute('title');
  2707. if ($title == '') {
  2708. $title = $entry->getAttribute('type');
  2709. }
  2710. $feedUrl = rewrite_relative_url(
  2711. $baseUrl, $entry->getAttribute('href')
  2712. );
  2713. $feedUrls[$feedUrl] = $title;
  2714. }
  2715. }
  2716. return $feedUrls;
  2717. }
  2718. function is_html($content) {
  2719. return preg_match("/<html|DOCTYPE html/i", substr($content, 0, 20)) !== 0;
  2720. }
  2721. function url_is_html($url, $login = false, $pass = false) {
  2722. return is_html(fetch_file_contents($url, false, $login, $pass));
  2723. }
  2724. function print_label_select($link, $name, $value, $attributes = "") {
  2725. $result = db_query($link, "SELECT caption FROM ttrss_labels2
  2726. WHERE owner_uid = '".$_SESSION["uid"]."' ORDER BY caption");
  2727. print "<select default=\"$value\" name=\"" . htmlspecialchars($name) .
  2728. "\" $attributes onchange=\"labelSelectOnChange(this)\" >";
  2729. while ($line = db_fetch_assoc($result)) {
  2730. $issel = ($line["caption"] == $value) ? "selected=\"1\"" : "";
  2731. print "<option value=\"".htmlspecialchars($line["caption"])."\"
  2732. $issel>" . htmlspecialchars($line["caption"]) . "</option>";
  2733. }
  2734. # print "<option value=\"ADD_LABEL\">" .__("Add label...") . "</option>";
  2735. print "</select>";
  2736. }
  2737. function format_article_enclosures($link, $id, $always_display_enclosures,
  2738. $article_content) {
  2739. $result = get_article_enclosures($link, $id);
  2740. $rv = '';
  2741. if (count($result) > 0) {
  2742. $entries_html = array();
  2743. $entries = array();
  2744. $entries_inline = array();
  2745. foreach ($result as $line) {
  2746. $url = $line["content_url"];
  2747. $ctype = $line["content_type"];
  2748. if (!$ctype) $ctype = __("unknown type");
  2749. $filename = substr($url, strrpos($url, "/")+1);
  2750. $player = format_inline_player($link, $url, $ctype);
  2751. if ($player) array_push($entries_inline, $player);
  2752. # $entry .= " <a target=\"_blank\" href=\"" . htmlspecialchars($url) . "\">" .
  2753. # $filename . " (" . $ctype . ")" . "</a>";
  2754. $entry = "<div onclick=\"window.open('".htmlspecialchars($url)."')\"
  2755. dojoType=\"dijit.MenuItem\">$filename ($ctype)</div>";
  2756. array_push($entries_html, $entry);
  2757. $entry = array();
  2758. $entry["type"] = $ctype;
  2759. $entry["filename"] = $filename;
  2760. $entry["url"] = $url;
  2761. array_push($entries, $entry);
  2762. }
  2763. if ($_SESSION['uid'] && !get_pref($link, "STRIP_IMAGES")) {
  2764. if ($always_display_enclosures ||
  2765. !preg_match("/<img/i", $article_content)) {
  2766. foreach ($entries as $entry) {
  2767. if (preg_match("/image/", $entry["type"]) ||
  2768. preg_match("/\.(jpg|png|gif|bmp)/i", $entry["filename"])) {
  2769. $rv .= "<p><img
  2770. alt=\"".htmlspecialchars($entry["filename"])."\"
  2771. src=\"" .htmlspecialchars($entry["url"]) . "\"/></p>";
  2772. }
  2773. }
  2774. }
  2775. }
  2776. if (count($entries_inline) > 0) {
  2777. $rv .= "<hr clear='both'/>";
  2778. foreach ($entries_inline as $entry) { $rv .= $entry; };
  2779. $rv .= "<hr clear='both'/>";
  2780. }
  2781. $rv .= "<br/><div dojoType=\"dijit.form.DropDownButton\">".
  2782. "<span>" . __('Attachments')."</span>";
  2783. $rv .= "<div dojoType=\"dijit.Menu\" style=\"display: none;\">";
  2784. foreach ($entries_html as $entry) { $rv .= $entry; };
  2785. $rv .= "</div></div>";
  2786. }
  2787. return $rv;
  2788. }
  2789. function getLastArticleId($link) {
  2790. $result = db_query($link, "SELECT MAX(ref_id) AS id FROM ttrss_user_entries
  2791. WHERE owner_uid = " . $_SESSION["uid"]);
  2792. if (db_num_rows($result) == 1) {
  2793. return db_fetch_result($result, 0, "id");
  2794. } else {
  2795. return -1;
  2796. }
  2797. }
  2798. function build_url($parts) {
  2799. return $parts['scheme'] . "://" . $parts['host'] . $parts['path'];
  2800. }
  2801. /**
  2802. * Converts a (possibly) relative URL to a absolute one.
  2803. *
  2804. * @param string $url Base URL (i.e. from where the document is)
  2805. * @param string $rel_url Possibly relative URL in the document
  2806. *
  2807. * @return string Absolute URL
  2808. */
  2809. function rewrite_relative_url($url, $rel_url) {
  2810. if (strpos($rel_url, "magnet:") === 0) {
  2811. return $rel_url;
  2812. } else if (strpos($rel_url, "://") !== false) {
  2813. return $rel_url;
  2814. } else if (strpos($rel_url, "//") === 0) {
  2815. # protocol-relative URL (rare but they exist)
  2816. return $rel_url;
  2817. } else if (strpos($rel_url, "/") === 0)
  2818. {
  2819. $parts = parse_url($url);
  2820. $parts['path'] = $rel_url;
  2821. return build_url($parts);
  2822. } else {
  2823. $parts = parse_url($url);
  2824. if (!isset($parts['path'])) {
  2825. $parts['path'] = '/';
  2826. }
  2827. $dir = $parts['path'];
  2828. if (substr($dir, -1) !== '/') {
  2829. $dir = dirname($parts['path']);
  2830. $dir !== '/' && $dir .= '/';
  2831. }
  2832. $parts['path'] = $dir . $rel_url;
  2833. return build_url($parts);
  2834. }
  2835. }
  2836. function sphinx_search($query, $offset = 0, $limit = 30) {
  2837. require_once 'lib/sphinxapi.php';
  2838. $sphinxClient = new SphinxClient();
  2839. $sphinxClient->SetServer('localhost', 9312);
  2840. $sphinxClient->SetConnectTimeout(1);
  2841. $sphinxClient->SetFieldWeights(array('title' => 70, 'content' => 30,
  2842. 'feed_title' => 20));
  2843. $sphinxClient->SetMatchMode(SPH_MATCH_EXTENDED2);
  2844. $sphinxClient->SetRankingMode(SPH_RANK_PROXIMITY_BM25);
  2845. $sphinxClient->SetLimits($offset, $limit, 1000);
  2846. $sphinxClient->SetArrayResult(false);
  2847. $sphinxClient->SetFilter('owner_uid', array($_SESSION['uid']));
  2848. $result = $sphinxClient->Query($query, SPHINX_INDEX);
  2849. $ids = array();
  2850. if (is_array($result['matches'])) {
  2851. foreach (array_keys($result['matches']) as $int_id) {
  2852. $ref_id = $result['matches'][$int_id]['attrs']['ref_id'];
  2853. array_push($ids, $ref_id);
  2854. }
  2855. }
  2856. return $ids;
  2857. }
  2858. function cleanup_tags($link, $days = 14, $limit = 1000) {
  2859. if (DB_TYPE == "pgsql") {
  2860. $interval_query = "date_updated < NOW() - INTERVAL '$days days'";
  2861. } else if (DB_TYPE == "mysql") {
  2862. $interval_query = "date_updated < DATE_SUB(NOW(), INTERVAL $days DAY)";
  2863. }
  2864. $tags_deleted = 0;
  2865. while ($limit > 0) {
  2866. $limit_part = 500;
  2867. $query = "SELECT ttrss_tags.id AS id
  2868. FROM ttrss_tags, ttrss_user_entries, ttrss_entries
  2869. WHERE post_int_id = int_id AND $interval_query AND
  2870. ref_id = ttrss_entries.id AND tag_cache != '' LIMIT $limit_part";
  2871. $result = db_query($link, $query);
  2872. $ids = array();
  2873. while ($line = db_fetch_assoc($result)) {
  2874. array_push($ids, $line['id']);
  2875. }
  2876. if (count($ids) > 0) {
  2877. $ids = join(",", $ids);
  2878. print ".";
  2879. $tmp_result = db_query($link, "DELETE FROM ttrss_tags WHERE id IN ($ids)");
  2880. $tags_deleted += db_affected_rows($link, $tmp_result);
  2881. } else {
  2882. break;
  2883. }
  2884. $limit -= $limit_part;
  2885. }
  2886. print "\n";
  2887. return $tags_deleted;
  2888. }
  2889. function print_user_stylesheet($link) {
  2890. $value = get_pref($link, 'USER_STYLESHEET');
  2891. if ($value) {
  2892. print "<style type=\"text/css\">";
  2893. print str_replace("<br/>", "\n", $value);
  2894. print "</style>";
  2895. }
  2896. }
  2897. function rewrite_urls($html) {
  2898. libxml_use_internal_errors(true);
  2899. $charset_hack = '<head>
  2900. <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
  2901. </head>';
  2902. $doc = new DOMDocument();
  2903. $doc->loadHTML($charset_hack . $html);
  2904. $xpath = new DOMXPath($doc);
  2905. $entries = $xpath->query('//*/text()');
  2906. foreach ($entries as $entry) {
  2907. if (strstr($entry->wholeText, "://") !== false) {
  2908. $text = preg_replace("/((?<!=.)((http|https|ftp)+):\/\/[^ ,!]+)/i",
  2909. "<a target=\"_blank\" href=\"\\1\">\\1</a>", $entry->wholeText);
  2910. if ($text != $entry->wholeText) {
  2911. $cdoc = new DOMDocument();
  2912. $cdoc->loadHTML($charset_hack . $text);
  2913. foreach ($cdoc->childNodes as $cnode) {
  2914. $cnode = $doc->importNode($cnode, true);
  2915. if ($cnode) {
  2916. $entry->parentNode->insertBefore($cnode);
  2917. }
  2918. }
  2919. $entry->parentNode->removeChild($entry);
  2920. }
  2921. }
  2922. }
  2923. $node = $doc->getElementsByTagName('body')->item(0);
  2924. // http://tt-rss.org/forum/viewtopic.php?f=1&t=970
  2925. if ($node)
  2926. return $doc->saveXML($node);
  2927. else
  2928. return $html;
  2929. }
  2930. function filter_to_sql($link, $filter, $owner_uid) {
  2931. $query = array();
  2932. if (DB_TYPE == "pgsql")
  2933. $reg_qpart = "~";
  2934. else
  2935. $reg_qpart = "REGEXP";
  2936. foreach ($filter["rules"] AS $rule) {
  2937. $regexp_valid = preg_match('/' . $rule['reg_exp'] . '/',
  2938. $rule['reg_exp']) !== FALSE;
  2939. if ($regexp_valid) {
  2940. $rule['reg_exp'] = db_escape_string($rule['reg_exp']);
  2941. switch ($rule["type"]) {
  2942. case "title":
  2943. $qpart = "LOWER(ttrss_entries.title) $reg_qpart LOWER('".
  2944. $rule['reg_exp'] . "')";
  2945. break;
  2946. case "content":
  2947. $qpart = "LOWER(ttrss_entries.content) $reg_qpart LOWER('".
  2948. $rule['reg_exp'] . "')";
  2949. break;
  2950. case "both":
  2951. $qpart = "LOWER(ttrss_entries.title) $reg_qpart LOWER('".
  2952. $rule['reg_exp'] . "') OR LOWER(" .
  2953. "ttrss_entries.content) $reg_qpart LOWER('" . $rule['reg_exp'] . "')";
  2954. break;
  2955. case "tag":
  2956. $qpart = "LOWER(ttrss_user_entries.tag_cache) $reg_qpart LOWER('".
  2957. $rule['reg_exp'] . "')";
  2958. break;
  2959. case "link":
  2960. $qpart = "LOWER(ttrss_entries.link) $reg_qpart LOWER('".
  2961. $rule['reg_exp'] . "')";
  2962. break;
  2963. case "author":
  2964. $qpart = "LOWER(ttrss_entries.author) $reg_qpart LOWER('".
  2965. $rule['reg_exp'] . "')";
  2966. break;
  2967. }
  2968. if (isset($rule["feed_id"]) && $rule["feed_id"] > 0) {
  2969. $qpart .= " AND feed_id = " . db_escape_string($rule["feed_id"]);
  2970. }
  2971. if (isset($rule["cat_id"])) {
  2972. if ($rule["cat_id"] > 0) {
  2973. $children = getChildCategories($link, $rule["cat_id"], $owner_uid);
  2974. array_push($children, $rule["cat_id"]);
  2975. $children = join(",", $children);
  2976. $cat_qpart = "cat_id IN ($children)";
  2977. } else {
  2978. $cat_qpart = "cat_id IS NULL";
  2979. }
  2980. $qpart .= " AND $cat_qpart";
  2981. }
  2982. array_push($query, "($qpart)");
  2983. }
  2984. }
  2985. if (count($query) > 0) {
  2986. return "(" . join($filter["match_any_rule"] ? "OR" : "AND", $query) . ")";
  2987. } else {
  2988. return "(false)";
  2989. }
  2990. }
  2991. if (!function_exists('gzdecode')) {
  2992. function gzdecode($string) { // no support for 2nd argument
  2993. return file_get_contents('compress.zlib://data:who/cares;base64,'.
  2994. base64_encode($string));
  2995. }
  2996. }
  2997. function get_random_bytes($length) {
  2998. if (function_exists('openssl_random_pseudo_bytes')) {
  2999. return openssl_random_pseudo_bytes($length);
  3000. } else {
  3001. $output = "";
  3002. for ($i = 0; $i < $length; $i++)
  3003. $output .= chr(mt_rand(0, 255));
  3004. return $output;
  3005. }
  3006. }
  3007. function read_stdin() {
  3008. $fp = fopen("php://stdin", "r");
  3009. if ($fp) {
  3010. $line = trim(fgets($fp));
  3011. fclose($fp);
  3012. return $line;
  3013. }
  3014. return null;
  3015. }
  3016. function tmpdirname($path, $prefix) {
  3017. // Use PHP's tmpfile function to create a temporary
  3018. // directory name. Delete the file and keep the name.
  3019. $tempname = tempnam($path,$prefix);
  3020. if (!$tempname)
  3021. return false;
  3022. if (!unlink($tempname))
  3023. return false;
  3024. return $tempname;
  3025. }
  3026. function getFeedCategory($link, $feed) {
  3027. $result = db_query($link, "SELECT cat_id FROM ttrss_feeds
  3028. WHERE id = '$feed'");
  3029. if (db_num_rows($result) > 0) {
  3030. return db_fetch_result($result, 0, "cat_id");
  3031. } else {
  3032. return false;
  3033. }
  3034. }
  3035. function implements_interface($class, $interface) {
  3036. return in_array($interface, class_implements($class));
  3037. }
  3038. function geturl($url){
  3039. (function_exists('curl_init')) ? '' : die('cURL Must be installed for geturl function to work. Ask your host to enable it or uncomment extension=php_curl.dll in php.ini');
  3040. $curl = curl_init();
  3041. $header[0] = "Accept: text/xml,application/xml,application/xhtml+xml,";
  3042. $header[0] .= "text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5";
  3043. $header[] = "Cache-Control: max-age=0";
  3044. $header[] = "Connection: keep-alive";
  3045. $header[] = "Keep-Alive: 300";
  3046. $header[] = "Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7";
  3047. $header[] = "Accept-Language: en-us,en;q=0.5";
  3048. $header[] = "Pragma: ";
  3049. curl_setopt($curl, CURLOPT_URL, $url);
  3050. curl_setopt($curl, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 5.1; rv:5.0) Gecko/20100101 Firefox/5.0 Firefox/5.0');
  3051. curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
  3052. curl_setopt($curl, CURLOPT_HEADER, true);
  3053. curl_setopt($curl, CURLOPT_REFERER, $url);
  3054. curl_setopt($curl, CURLOPT_ENCODING, 'gzip,deflate');
  3055. curl_setopt($curl, CURLOPT_AUTOREFERER, true);
  3056. curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
  3057. //curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true); //CURLOPT_FOLLOWLOCATION Disabled...
  3058. curl_setopt($curl, CURLOPT_TIMEOUT, 60);
  3059. $html = curl_exec($curl);
  3060. $status = curl_getinfo($curl);
  3061. curl_close($curl);
  3062. if($status['http_code']!=200){
  3063. if($status['http_code'] == 301 || $status['http_code'] == 302) {
  3064. list($header) = explode("\r\n\r\n", $html, 2);
  3065. $matches = array();
  3066. preg_match("/(Location:|URI:)[^(\n)]*/", $header, $matches);
  3067. $url = trim(str_replace($matches[1],"",$matches[0]));
  3068. $url_parsed = parse_url($url);
  3069. return (isset($url_parsed))? geturl($url, $referer):'';
  3070. }
  3071. $oline='';
  3072. foreach($status as $key=>$eline){$oline.='['.$key.']'.$eline.' ';}
  3073. $line =$oline." \r\n ".$url."\r\n-----------------\r\n";
  3074. # $handle = @fopen('./curl.error.log', 'a');
  3075. # fwrite($handle, $line);
  3076. return FALSE;
  3077. }
  3078. return $url;
  3079. }
  3080. function get_minified_js($files) {
  3081. require_once 'lib/jshrink/Minifier.php';
  3082. $rv = '';
  3083. foreach ($files as $js) {
  3084. if (!isset($_GET['debug'])) {
  3085. $cached_file = CACHE_DIR . "/js/$js.js";
  3086. if (file_exists($cached_file) &&
  3087. is_readable($cached_file) &&
  3088. filemtime($cached_file) >= filemtime("js/$js.js")) {
  3089. $rv .= file_get_contents($cached_file);
  3090. } else {
  3091. $minified = JShrink\Minifier::minify(file_get_contents("js/$js.js"));
  3092. file_put_contents($cached_file, $minified);
  3093. $rv .= $minified;
  3094. }
  3095. } else {
  3096. $rv .= file_get_contents("js/$js.js");
  3097. }
  3098. }
  3099. return $rv;
  3100. }
  3101. ?>