functions.php 54 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029
  1. <?php
  2. define('EXPECTED_CONFIG_VERSION', 26);
  3. define('SCHEMA_VERSION', 130);
  4. define('LABEL_BASE_INDEX', -1024);
  5. define('PLUGIN_FEED_BASE_INDEX', -128);
  6. define('COOKIE_LIFETIME_LONG', 86400*365);
  7. $fetch_last_error = false;
  8. $fetch_last_error_code = false;
  9. $fetch_last_content_type = false;
  10. $fetch_last_error_content = false; // curl only for the time being
  11. $fetch_curl_used = false;
  12. $suppress_debugging = false;
  13. libxml_disable_entity_loader(true);
  14. // separate test because this is included before sanity checks
  15. if (function_exists("mb_internal_encoding")) mb_internal_encoding("UTF-8");
  16. date_default_timezone_set('UTC');
  17. if (defined('E_DEPRECATED')) {
  18. error_reporting(E_ALL & ~E_NOTICE & ~E_DEPRECATED);
  19. } else {
  20. error_reporting(E_ALL & ~E_NOTICE);
  21. }
  22. require_once 'config.php';
  23. /**
  24. * Define a constant if not already defined
  25. *
  26. * @param string $name The constant name.
  27. * @param mixed $value The constant value.
  28. * @access public
  29. * @return boolean True if defined successfully or not.
  30. */
  31. function define_default($name, $value) {
  32. defined($name) or define($name, $value);
  33. }
  34. ///// Some defaults that you can override in config.php //////
  35. define_default('FEED_FETCH_TIMEOUT', 45);
  36. // How may seconds to wait for response when requesting feed from a site
  37. define_default('FEED_FETCH_NO_CACHE_TIMEOUT', 15);
  38. // How may seconds to wait for response when requesting feed from a
  39. // site when that feed wasn't cached before
  40. define_default('FILE_FETCH_TIMEOUT', 45);
  41. // Default timeout when fetching files from remote sites
  42. define_default('FILE_FETCH_CONNECT_TIMEOUT', 15);
  43. // How many seconds to wait for initial response from website when
  44. // fetching files from remote sites
  45. if (DB_TYPE == "pgsql") {
  46. define('SUBSTRING_FOR_DATE', 'SUBSTRING_FOR_DATE');
  47. } else {
  48. define('SUBSTRING_FOR_DATE', 'SUBSTRING');
  49. }
  50. /**
  51. * Return available translations names.
  52. *
  53. * @access public
  54. * @return array A array of available translations.
  55. */
  56. function get_translations() {
  57. $tr = array(
  58. "auto" => "Detect automatically",
  59. "ar_SA" => "العربيّة (Arabic)",
  60. "bg_BG" => "Bulgarian",
  61. "da_DA" => "Dansk",
  62. "ca_CA" => "Català",
  63. "cs_CZ" => "Česky",
  64. "en_US" => "English",
  65. "el_GR" => "Ελληνικά",
  66. "es_ES" => "Español (España)",
  67. "es_LA" => "Español",
  68. "de_DE" => "Deutsch",
  69. "fr_FR" => "Français",
  70. "hu_HU" => "Magyar (Hungarian)",
  71. "it_IT" => "Italiano",
  72. "ja_JP" => "日本語 (Japanese)",
  73. "lv_LV" => "Latviešu",
  74. "nb_NO" => "Norwegian bokmål",
  75. "nl_NL" => "Dutch",
  76. "pl_PL" => "Polski",
  77. "ru_RU" => "Русский",
  78. "pt_BR" => "Portuguese/Brazil",
  79. "pt_PT" => "Portuguese/Portugal",
  80. "zh_CN" => "Simplified Chinese",
  81. "zh_TW" => "Traditional Chinese",
  82. "sv_SE" => "Svenska",
  83. "fi_FI" => "Suomi",
  84. "tr_TR" => "Türkçe");
  85. return $tr;
  86. }
  87. require_once "lib/accept-to-gettext.php";
  88. require_once "lib/gettext/gettext.inc";
  89. function startup_gettext() {
  90. # Get locale from Accept-Language header
  91. $lang = al2gt(array_keys(get_translations()), "text/html");
  92. if (defined('_TRANSLATION_OVERRIDE_DEFAULT')) {
  93. $lang = _TRANSLATION_OVERRIDE_DEFAULT;
  94. }
  95. if ($_SESSION["uid"] && get_schema_version() >= 120) {
  96. $pref_lang = get_pref("USER_LANGUAGE", $_SESSION["uid"]);
  97. if ($pref_lang && $pref_lang != 'auto') {
  98. $lang = $pref_lang;
  99. }
  100. }
  101. if ($lang) {
  102. if (defined('LC_MESSAGES')) {
  103. _setlocale(LC_MESSAGES, $lang);
  104. } else if (defined('LC_ALL')) {
  105. _setlocale(LC_ALL, $lang);
  106. }
  107. _bindtextdomain("messages", "locale");
  108. _textdomain("messages");
  109. _bind_textdomain_codeset("messages", "UTF-8");
  110. }
  111. }
  112. require_once 'db-prefs.php';
  113. require_once 'version.php';
  114. require_once 'ccache.php';
  115. require_once 'labels.php';
  116. define('SELF_USER_AGENT', 'Tiny Tiny RSS/' . VERSION . ' (http://tt-rss.org/)');
  117. ini_set('user_agent', SELF_USER_AGENT);
  118. require_once 'lib/pubsubhubbub/publisher.php';
  119. $schema_version = false;
  120. function _debug_suppress($suppress) {
  121. global $suppress_debugging;
  122. $suppress_debugging = $suppress;
  123. }
  124. /**
  125. * Print a timestamped debug message.
  126. *
  127. * @param string $msg The debug message.
  128. * @return void
  129. */
  130. function _debug($msg, $show = true) {
  131. global $suppress_debugging;
  132. //echo "[$suppress_debugging] $msg $show\n";
  133. if ($suppress_debugging) return false;
  134. $ts = strftime("%H:%M:%S", time());
  135. if (function_exists('posix_getpid')) {
  136. $ts = "$ts/" . posix_getpid();
  137. }
  138. if ($show && !(defined('QUIET') && QUIET)) {
  139. print "[$ts] $msg\n";
  140. }
  141. if (defined('LOGFILE')) {
  142. $fp = fopen(LOGFILE, 'a+');
  143. if ($fp) {
  144. $locked = false;
  145. if (function_exists("flock")) {
  146. $tries = 0;
  147. // try to lock logfile for writing
  148. while ($tries < 5 && !$locked = flock($fp, LOCK_EX | LOCK_NB)) {
  149. sleep(1);
  150. ++$tries;
  151. }
  152. if (!$locked) {
  153. fclose($fp);
  154. return;
  155. }
  156. }
  157. fputs($fp, "[$ts] $msg\n");
  158. if (function_exists("flock")) {
  159. flock($fp, LOCK_UN);
  160. }
  161. fclose($fp);
  162. }
  163. }
  164. } // function _debug
  165. /**
  166. * Purge a feed old posts.
  167. *
  168. * @param mixed $link A database connection.
  169. * @param mixed $feed_id The id of the purged feed.
  170. * @param mixed $purge_interval Olderness of purged posts.
  171. * @param boolean $debug Set to True to enable the debug. False by default.
  172. * @access public
  173. * @return void
  174. */
  175. function purge_feed($feed_id, $purge_interval, $debug = false) {
  176. if (!$purge_interval) $purge_interval = feed_purge_interval($feed_id);
  177. $rows = -1;
  178. $result = db_query(
  179. "SELECT owner_uid FROM ttrss_feeds WHERE id = '$feed_id'");
  180. $owner_uid = false;
  181. if (db_num_rows($result) == 1) {
  182. $owner_uid = db_fetch_result($result, 0, "owner_uid");
  183. }
  184. if ($purge_interval == -1 || !$purge_interval) {
  185. if ($owner_uid) {
  186. ccache_update($feed_id, $owner_uid);
  187. }
  188. return;
  189. }
  190. if (!$owner_uid) return;
  191. if (FORCE_ARTICLE_PURGE == 0) {
  192. $purge_unread = get_pref("PURGE_UNREAD_ARTICLES",
  193. $owner_uid, false);
  194. } else {
  195. $purge_unread = true;
  196. $purge_interval = FORCE_ARTICLE_PURGE;
  197. }
  198. if (!$purge_unread) $query_limit = " unread = false AND ";
  199. if (DB_TYPE == "pgsql") {
  200. $result = db_query("DELETE FROM ttrss_user_entries
  201. USING ttrss_entries
  202. WHERE ttrss_entries.id = ref_id AND
  203. marked = false AND
  204. feed_id = '$feed_id' AND
  205. $query_limit
  206. ttrss_entries.date_updated < NOW() - INTERVAL '$purge_interval days'");
  207. } else {
  208. /* $result = db_query("DELETE FROM ttrss_user_entries WHERE
  209. marked = false AND feed_id = '$feed_id' AND
  210. (SELECT date_updated FROM ttrss_entries WHERE
  211. id = ref_id) < DATE_SUB(NOW(), INTERVAL $purge_interval DAY)"); */
  212. $result = db_query("DELETE FROM ttrss_user_entries
  213. USING ttrss_user_entries, ttrss_entries
  214. WHERE ttrss_entries.id = ref_id AND
  215. marked = false AND
  216. feed_id = '$feed_id' AND
  217. $query_limit
  218. ttrss_entries.date_updated < DATE_SUB(NOW(), INTERVAL $purge_interval DAY)");
  219. }
  220. $rows = db_affected_rows($result);
  221. ccache_update($feed_id, $owner_uid);
  222. if ($debug) {
  223. _debug("Purged feed $feed_id ($purge_interval): deleted $rows articles");
  224. }
  225. return $rows;
  226. } // function purge_feed
  227. function feed_purge_interval($feed_id) {
  228. $result = db_query("SELECT purge_interval, owner_uid FROM ttrss_feeds
  229. WHERE id = '$feed_id'");
  230. if (db_num_rows($result) == 1) {
  231. $purge_interval = db_fetch_result($result, 0, "purge_interval");
  232. $owner_uid = db_fetch_result($result, 0, "owner_uid");
  233. if ($purge_interval == 0) $purge_interval = get_pref(
  234. 'PURGE_OLD_DAYS', $owner_uid);
  235. return $purge_interval;
  236. } else {
  237. return -1;
  238. }
  239. }
  240. function purge_orphans($do_output = false) {
  241. // purge orphaned posts in main content table
  242. $result = db_query("DELETE FROM ttrss_entries WHERE
  243. NOT EXISTS (SELECT ref_id FROM ttrss_user_entries WHERE ref_id = id)");
  244. if ($do_output) {
  245. $rows = db_affected_rows($result);
  246. _debug("Purged $rows orphaned posts.");
  247. }
  248. }
  249. function get_feed_update_interval($feed_id) {
  250. $result = db_query("SELECT owner_uid, update_interval FROM
  251. ttrss_feeds WHERE id = '$feed_id'");
  252. if (db_num_rows($result) == 1) {
  253. $update_interval = db_fetch_result($result, 0, "update_interval");
  254. $owner_uid = db_fetch_result($result, 0, "owner_uid");
  255. if ($update_interval != 0) {
  256. return $update_interval;
  257. } else {
  258. return get_pref('DEFAULT_UPDATE_INTERVAL', $owner_uid, false);
  259. }
  260. } else {
  261. return -1;
  262. }
  263. }
  264. // TODO: multiple-argument way is deprecated, first parameter is a hash now
  265. function fetch_file_contents($options /* previously: 0: $url , 1: $type = false, 2: $login = false, 3: $pass = false,
  266. 4: $post_query = false, 5: $timeout = false, 6: $timestamp = 0, 7: $useragent = false*/) {
  267. global $fetch_last_error;
  268. global $fetch_last_error_code;
  269. global $fetch_last_error_content;
  270. global $fetch_last_content_type;
  271. global $fetch_curl_used;
  272. if (!is_array($options)) {
  273. // falling back on compatibility shim
  274. $options = array(
  275. "url" => func_get_arg(0),
  276. "type" => @func_get_arg(1),
  277. "login" => @func_get_arg(2),
  278. "pass" => @func_get_arg(3),
  279. "post_query" => @func_get_arg(4),
  280. "timeout" => @func_get_arg(5),
  281. "timestamp" => @func_get_arg(6),
  282. "useragent" => @func_get_arg(7)
  283. );
  284. }
  285. $url = $options["url"];
  286. $type = isset($options["type"]) ? $options["type"] : false;
  287. $login = isset($options["login"]) ? $options["login"] : false;
  288. $pass = isset($options["pass"]) ? $options["pass"] : false;
  289. $post_query = isset($options["post_query"]) ? $options["post_query"] : false;
  290. $timeout = isset($options["timeout"]) ? $options["timeout"] : false;
  291. $timestamp = isset($options["timestamp"]) ? $options["timestamp"] : 0;
  292. $useragent = isset($options["useragent"]) ? $options["useragent"] : false;
  293. $url = ltrim($url, ' ');
  294. $url = str_replace(' ', '%20', $url);
  295. if (strpos($url, "//") === 0)
  296. $url = 'http:' . $url;
  297. if (!defined('NO_CURL') && function_exists('curl_init') && !ini_get("open_basedir")) {
  298. $fetch_curl_used = true;
  299. $ch = curl_init($url);
  300. if ($timestamp && !$post_query) {
  301. curl_setopt($ch, CURLOPT_HTTPHEADER,
  302. array("If-Modified-Since: ".gmdate('D, d M Y H:i:s \G\M\T', $timestamp)));
  303. }
  304. curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout ? $timeout : FILE_FETCH_CONNECT_TIMEOUT);
  305. curl_setopt($ch, CURLOPT_TIMEOUT, $timeout ? $timeout : FILE_FETCH_TIMEOUT);
  306. curl_setopt($ch, CURLOPT_FOLLOWLOCATION, !ini_get("open_basedir"));
  307. curl_setopt($ch, CURLOPT_MAXREDIRS, 20);
  308. curl_setopt($ch, CURLOPT_BINARYTRANSFER, true);
  309. curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  310. curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
  311. curl_setopt($ch, CURLOPT_USERAGENT, $useragent ? $useragent :
  312. SELF_USER_AGENT);
  313. curl_setopt($ch, CURLOPT_ENCODING, "");
  314. //curl_setopt($ch, CURLOPT_REFERER, $url);
  315. if (!ini_get("open_basedir")) {
  316. curl_setopt($ch, CURLOPT_COOKIEJAR, "/dev/null");
  317. }
  318. if (defined('_CURL_HTTP_PROXY')) {
  319. curl_setopt($ch, CURLOPT_PROXY, _CURL_HTTP_PROXY);
  320. }
  321. if ($post_query) {
  322. curl_setopt($ch, CURLOPT_POST, true);
  323. curl_setopt($ch, CURLOPT_POSTFIELDS, $post_query);
  324. }
  325. if ($login && $pass)
  326. curl_setopt($ch, CURLOPT_USERPWD, "$login:$pass");
  327. $contents = @curl_exec($ch);
  328. if (curl_errno($ch) === 23 || curl_errno($ch) === 61) {
  329. curl_setopt($ch, CURLOPT_ENCODING, 'none');
  330. $contents = @curl_exec($ch);
  331. }
  332. if ($contents === false) {
  333. $fetch_last_error = curl_errno($ch) . " " . curl_error($ch);
  334. curl_close($ch);
  335. return false;
  336. }
  337. $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
  338. $fetch_last_content_type = curl_getinfo($ch, CURLINFO_CONTENT_TYPE);
  339. $fetch_last_error_code = $http_code;
  340. if ($http_code != 200 || $type && strpos($fetch_last_content_type, "$type") === false) {
  341. if (curl_errno($ch) != 0) {
  342. $fetch_last_error = curl_errno($ch) . " " . curl_error($ch);
  343. } else {
  344. $fetch_last_error = "HTTP Code: $http_code";
  345. }
  346. $fetch_last_error_content = $contents;
  347. curl_close($ch);
  348. return false;
  349. }
  350. curl_close($ch);
  351. return $contents;
  352. } else {
  353. $fetch_curl_used = false;
  354. if ($login && $pass){
  355. $url_parts = array();
  356. preg_match("/(^[^:]*):\/\/(.*)/", $url, $url_parts);
  357. $pass = urlencode($pass);
  358. if ($url_parts[1] && $url_parts[2]) {
  359. $url = $url_parts[1] . "://$login:$pass@" . $url_parts[2];
  360. }
  361. }
  362. // TODO: should this support POST requests or not? idk
  363. if (!$post_query && $timestamp) {
  364. $context = stream_context_create(array(
  365. 'http' => array(
  366. 'method' => 'GET',
  367. 'timeout' => $timeout ? $timeout : FILE_FETCH_TIMEOUT,
  368. 'protocol_version'=> 1.1,
  369. 'header' => "If-Modified-Since: ".gmdate("D, d M Y H:i:s \\G\\M\\T\r\n", $timestamp)
  370. )));
  371. } else {
  372. $context = stream_context_create(array(
  373. 'http' => array(
  374. 'method' => 'GET',
  375. 'timeout' => $timeout ? $timeout : FILE_FETCH_TIMEOUT,
  376. 'protocol_version'=> 1.1
  377. )));
  378. }
  379. $old_error = error_get_last();
  380. $data = @file_get_contents($url, false, $context);
  381. $fetch_last_content_type = false; // reset if no type was sent from server
  382. if (isset($http_response_header) && is_array($http_response_header)) {
  383. foreach ($http_response_header as $h) {
  384. if (substr(strtolower($h), 0, 13) == 'content-type:') {
  385. $fetch_last_content_type = substr($h, 14);
  386. // don't abort here b/c there might be more than one
  387. // e.g. if we were being redirected -- last one is the right one
  388. }
  389. if (substr(strtolower($h), 0, 7) == 'http/1.') {
  390. $fetch_last_error_code = (int) substr($h, 9, 3);
  391. }
  392. }
  393. }
  394. if (!$data) {
  395. $error = error_get_last();
  396. if ($error['message'] != $old_error['message']) {
  397. $fetch_last_error = $error["message"];
  398. } else {
  399. $fetch_last_error = "HTTP Code: $fetch_last_error_code";
  400. }
  401. }
  402. return $data;
  403. }
  404. }
  405. /**
  406. * Try to determine the favicon URL for a feed.
  407. * adapted from wordpress favicon plugin by Jeff Minard (http://thecodepro.com/)
  408. * http://dev.wp-plugins.org/file/favatars/trunk/favatars.php
  409. *
  410. * @param string $url A feed or page URL
  411. * @access public
  412. * @return mixed The favicon URL, or false if none was found.
  413. */
  414. function get_favicon_url($url) {
  415. $favicon_url = false;
  416. if ($html = @fetch_file_contents($url)) {
  417. libxml_use_internal_errors(true);
  418. $doc = new DOMDocument();
  419. $doc->loadHTML($html);
  420. $xpath = new DOMXPath($doc);
  421. $base = $xpath->query('/html/head/base');
  422. foreach ($base as $b) {
  423. $url = $b->getAttribute("href");
  424. break;
  425. }
  426. $entries = $xpath->query('/html/head/link[@rel="shortcut icon" or @rel="icon"]');
  427. if (count($entries) > 0) {
  428. foreach ($entries as $entry) {
  429. $favicon_url = rewrite_relative_url($url, $entry->getAttribute("href"));
  430. break;
  431. }
  432. }
  433. }
  434. if (!$favicon_url)
  435. $favicon_url = rewrite_relative_url($url, "/favicon.ico");
  436. return $favicon_url;
  437. } // function get_favicon_url
  438. function check_feed_favicon($site_url, $feed) {
  439. # print "FAVICON [$site_url]: $favicon_url\n";
  440. $icon_file = ICONS_DIR . "/$feed.ico";
  441. if (!file_exists($icon_file)) {
  442. $favicon_url = get_favicon_url($site_url);
  443. if ($favicon_url) {
  444. // Limiting to "image" type misses those served with text/plain
  445. $contents = fetch_file_contents($favicon_url); // , "image");
  446. if ($contents) {
  447. // Crude image type matching.
  448. // Patterns gleaned from the file(1) source code.
  449. if (preg_match('/^\x00\x00\x01\x00/', $contents)) {
  450. // 0 string \000\000\001\000 MS Windows icon resource
  451. //error_log("check_feed_favicon: favicon_url=$favicon_url isa MS Windows icon resource");
  452. }
  453. elseif (preg_match('/^GIF8/', $contents)) {
  454. // 0 string GIF8 GIF image data
  455. //error_log("check_feed_favicon: favicon_url=$favicon_url isa GIF image");
  456. }
  457. elseif (preg_match('/^\x89PNG\x0d\x0a\x1a\x0a/', $contents)) {
  458. // 0 string \x89PNG\x0d\x0a\x1a\x0a PNG image data
  459. //error_log("check_feed_favicon: favicon_url=$favicon_url isa PNG image");
  460. }
  461. elseif (preg_match('/^\xff\xd8/', $contents)) {
  462. // 0 beshort 0xffd8 JPEG image data
  463. //error_log("check_feed_favicon: favicon_url=$favicon_url isa JPG image");
  464. }
  465. else {
  466. //error_log("check_feed_favicon: favicon_url=$favicon_url isa UNKNOWN type");
  467. $contents = "";
  468. }
  469. }
  470. if ($contents) {
  471. $fp = @fopen($icon_file, "w");
  472. if ($fp) {
  473. fwrite($fp, $contents);
  474. fclose($fp);
  475. chmod($icon_file, 0644);
  476. }
  477. }
  478. }
  479. return $icon_file;
  480. }
  481. }
  482. function print_select($id, $default, $values, $attributes = "", $name = "") {
  483. if (!$name) $name = $id;
  484. print "<select name=\"$name\" id=\"$id\" $attributes>";
  485. foreach ($values as $v) {
  486. if ($v == $default)
  487. $sel = "selected=\"1\"";
  488. else
  489. $sel = "";
  490. $v = trim($v);
  491. print "<option value=\"$v\" $sel>$v</option>";
  492. }
  493. print "</select>";
  494. }
  495. function print_select_hash($id, $default, $values, $attributes = "", $name = "") {
  496. if (!$name) $name = $id;
  497. print "<select name=\"$name\" id='$id' $attributes>";
  498. foreach (array_keys($values) as $v) {
  499. if ($v == $default)
  500. $sel = 'selected="selected"';
  501. else
  502. $sel = "";
  503. $v = trim($v);
  504. print "<option $sel value=\"$v\">".$values[$v]."</option>";
  505. }
  506. print "</select>";
  507. }
  508. function print_radio($id, $default, $true_is, $values, $attributes = "") {
  509. foreach ($values as $v) {
  510. if ($v == $default)
  511. $sel = "checked";
  512. else
  513. $sel = "";
  514. if ($v == $true_is) {
  515. $sel .= " value=\"1\"";
  516. } else {
  517. $sel .= " value=\"0\"";
  518. }
  519. print "<input class=\"noborder\" dojoType=\"dijit.form.RadioButton\"
  520. type=\"radio\" $sel $attributes name=\"$id\">&nbsp;$v&nbsp;";
  521. }
  522. }
  523. function initialize_user_prefs($uid, $profile = false) {
  524. $uid = db_escape_string($uid);
  525. if (!$profile) {
  526. $profile = "NULL";
  527. $profile_qpart = "AND profile IS NULL";
  528. } else {
  529. $profile_qpart = "AND profile = '$profile'";
  530. }
  531. if (get_schema_version() < 63) $profile_qpart = "";
  532. db_query("BEGIN");
  533. $result = db_query("SELECT pref_name,def_value FROM ttrss_prefs");
  534. $u_result = db_query("SELECT pref_name
  535. FROM ttrss_user_prefs WHERE owner_uid = '$uid' $profile_qpart");
  536. $active_prefs = array();
  537. while ($line = db_fetch_assoc($u_result)) {
  538. array_push($active_prefs, $line["pref_name"]);
  539. }
  540. while ($line = db_fetch_assoc($result)) {
  541. if (array_search($line["pref_name"], $active_prefs) === FALSE) {
  542. // print "adding " . $line["pref_name"] . "<br>";
  543. $line["def_value"] = db_escape_string($line["def_value"]);
  544. $line["pref_name"] = db_escape_string($line["pref_name"]);
  545. if (get_schema_version() < 63) {
  546. db_query("INSERT INTO ttrss_user_prefs
  547. (owner_uid,pref_name,value) VALUES
  548. ('$uid', '".$line["pref_name"]."','".$line["def_value"]."')");
  549. } else {
  550. db_query("INSERT INTO ttrss_user_prefs
  551. (owner_uid,pref_name,value, profile) VALUES
  552. ('$uid', '".$line["pref_name"]."','".$line["def_value"]."', $profile)");
  553. }
  554. }
  555. }
  556. db_query("COMMIT");
  557. }
  558. function get_ssl_certificate_id() {
  559. if ($_SERVER["REDIRECT_SSL_CLIENT_M_SERIAL"]) {
  560. return sha1($_SERVER["REDIRECT_SSL_CLIENT_M_SERIAL"] .
  561. $_SERVER["REDIRECT_SSL_CLIENT_V_START"] .
  562. $_SERVER["REDIRECT_SSL_CLIENT_V_END"] .
  563. $_SERVER["REDIRECT_SSL_CLIENT_S_DN"]);
  564. }
  565. if ($_SERVER["SSL_CLIENT_M_SERIAL"]) {
  566. return sha1($_SERVER["SSL_CLIENT_M_SERIAL"] .
  567. $_SERVER["SSL_CLIENT_V_START"] .
  568. $_SERVER["SSL_CLIENT_V_END"] .
  569. $_SERVER["SSL_CLIENT_S_DN"]);
  570. }
  571. return "";
  572. }
  573. function authenticate_user($login, $password, $check_only = false) {
  574. if (!SINGLE_USER_MODE) {
  575. $user_id = false;
  576. foreach (PluginHost::getInstance()->get_hooks(PluginHost::HOOK_AUTH_USER) as $plugin) {
  577. $user_id = (int) $plugin->authenticate($login, $password);
  578. if ($user_id) {
  579. $_SESSION["auth_module"] = strtolower(get_class($plugin));
  580. break;
  581. }
  582. }
  583. if ($user_id && !$check_only) {
  584. @session_start();
  585. $_SESSION["uid"] = $user_id;
  586. $_SESSION["version"] = VERSION_STATIC;
  587. $result = db_query("SELECT login,access_level,pwd_hash FROM ttrss_users
  588. WHERE id = '$user_id'");
  589. $_SESSION["name"] = db_fetch_result($result, 0, "login");
  590. $_SESSION["access_level"] = db_fetch_result($result, 0, "access_level");
  591. $_SESSION["csrf_token"] = uniqid_short();
  592. db_query("UPDATE ttrss_users SET last_login = NOW() WHERE id = " .
  593. $_SESSION["uid"]);
  594. $_SESSION["ip_address"] = $_SERVER["REMOTE_ADDR"];
  595. $_SESSION["user_agent"] = sha1($_SERVER['HTTP_USER_AGENT']);
  596. $_SESSION["pwd_hash"] = db_fetch_result($result, 0, "pwd_hash");
  597. $_SESSION["last_version_check"] = time();
  598. initialize_user_prefs($_SESSION["uid"]);
  599. return true;
  600. }
  601. return false;
  602. } else {
  603. $_SESSION["uid"] = 1;
  604. $_SESSION["name"] = "admin";
  605. $_SESSION["access_level"] = 10;
  606. $_SESSION["hide_hello"] = true;
  607. $_SESSION["hide_logout"] = true;
  608. $_SESSION["auth_module"] = false;
  609. if (!$_SESSION["csrf_token"]) {
  610. $_SESSION["csrf_token"] = uniqid_short();
  611. }
  612. $_SESSION["ip_address"] = $_SERVER["REMOTE_ADDR"];
  613. initialize_user_prefs($_SESSION["uid"]);
  614. return true;
  615. }
  616. }
  617. function make_password($length = 8) {
  618. $password = "";
  619. $possible = "0123456789abcdfghjkmnpqrstvwxyzABCDFGHJKMNPQRSTVWXYZ";
  620. $i = 0;
  621. while ($i < $length) {
  622. $char = substr($possible, mt_rand(0, strlen($possible)-1), 1);
  623. if (!strstr($password, $char)) {
  624. $password .= $char;
  625. $i++;
  626. }
  627. }
  628. return $password;
  629. }
  630. // this is called after user is created to initialize default feeds, labels
  631. // or whatever else
  632. // user preferences are checked on every login, not here
  633. function initialize_user($uid) {
  634. db_query("insert into ttrss_feeds (owner_uid,title,feed_url)
  635. values ('$uid', 'Tiny Tiny RSS: Forum',
  636. 'http://tt-rss.org/forum/rss.php')");
  637. }
  638. function logout_user() {
  639. session_destroy();
  640. if (isset($_COOKIE[session_name()])) {
  641. setcookie(session_name(), '', time()-42000, '/');
  642. }
  643. }
  644. function validate_csrf($csrf_token) {
  645. return $csrf_token == $_SESSION['csrf_token'];
  646. }
  647. function load_user_plugins($owner_uid, $pluginhost = false) {
  648. if (!$pluginhost) $pluginhost = PluginHost::getInstance();
  649. if ($owner_uid && SCHEMA_VERSION >= 100) {
  650. $plugins = get_pref("_ENABLED_PLUGINS", $owner_uid);
  651. $pluginhost->load($plugins, PluginHost::KIND_USER, $owner_uid);
  652. if (get_schema_version() > 100) {
  653. $pluginhost->load_data();
  654. }
  655. }
  656. }
  657. function login_sequence() {
  658. if (SINGLE_USER_MODE) {
  659. @session_start();
  660. authenticate_user("admin", null);
  661. startup_gettext();
  662. load_user_plugins($_SESSION["uid"]);
  663. } else {
  664. if (!validate_session()) $_SESSION["uid"] = false;
  665. if (!$_SESSION["uid"]) {
  666. if (AUTH_AUTO_LOGIN && authenticate_user(null, null)) {
  667. $_SESSION["ref_schema_version"] = get_schema_version(true);
  668. } else {
  669. authenticate_user(null, null, true);
  670. }
  671. if (!$_SESSION["uid"]) {
  672. @session_destroy();
  673. setcookie(session_name(), '', time()-42000, '/');
  674. render_login_form();
  675. exit;
  676. }
  677. } else {
  678. /* bump login timestamp */
  679. db_query("UPDATE ttrss_users SET last_login = NOW() WHERE id = " .
  680. $_SESSION["uid"]);
  681. $_SESSION["last_login_update"] = time();
  682. }
  683. if ($_SESSION["uid"]) {
  684. startup_gettext();
  685. load_user_plugins($_SESSION["uid"]);
  686. /* cleanup ccache */
  687. db_query("DELETE FROM ttrss_counters_cache WHERE owner_uid = ".
  688. $_SESSION["uid"] . " AND
  689. (SELECT COUNT(id) FROM ttrss_feeds WHERE
  690. ttrss_feeds.id = feed_id) = 0");
  691. db_query("DELETE FROM ttrss_cat_counters_cache WHERE owner_uid = ".
  692. $_SESSION["uid"] . " AND
  693. (SELECT COUNT(id) FROM ttrss_feed_categories WHERE
  694. ttrss_feed_categories.id = feed_id) = 0");
  695. }
  696. }
  697. }
  698. function truncate_string($str, $max_len, $suffix = '&hellip;') {
  699. if (mb_strlen($str, "utf-8") > $max_len) {
  700. return mb_substr($str, 0, $max_len, "utf-8") . $suffix;
  701. } else {
  702. return $str;
  703. }
  704. }
  705. // is not utf8 clean
  706. function truncate_middle($str, $max_len, $suffix = '&hellip;') {
  707. if (strlen($str) > $max_len) {
  708. return substr_replace($str, $suffix, $max_len / 2, mb_strlen($str) - $max_len);
  709. } else {
  710. return $str;
  711. }
  712. }
  713. function convert_timestamp($timestamp, $source_tz, $dest_tz) {
  714. try {
  715. $source_tz = new DateTimeZone($source_tz);
  716. } catch (Exception $e) {
  717. $source_tz = new DateTimeZone('UTC');
  718. }
  719. try {
  720. $dest_tz = new DateTimeZone($dest_tz);
  721. } catch (Exception $e) {
  722. $dest_tz = new DateTimeZone('UTC');
  723. }
  724. $dt = new DateTime(date('Y-m-d H:i:s', $timestamp), $source_tz);
  725. return $dt->format('U') + $dest_tz->getOffset($dt);
  726. }
  727. function make_local_datetime($timestamp, $long, $owner_uid = false,
  728. $no_smart_dt = false, $eta_min = false) {
  729. if (!$owner_uid) $owner_uid = $_SESSION['uid'];
  730. if (!$timestamp) $timestamp = '1970-01-01 0:00';
  731. global $utc_tz;
  732. global $user_tz;
  733. if (!$utc_tz) $utc_tz = new DateTimeZone('UTC');
  734. $timestamp = substr($timestamp, 0, 19);
  735. # We store date in UTC internally
  736. $dt = new DateTime($timestamp, $utc_tz);
  737. $user_tz_string = get_pref('USER_TIMEZONE', $owner_uid);
  738. if ($user_tz_string != 'Automatic') {
  739. try {
  740. if (!$user_tz) $user_tz = new DateTimeZone($user_tz_string);
  741. } catch (Exception $e) {
  742. $user_tz = $utc_tz;
  743. }
  744. $tz_offset = $user_tz->getOffset($dt);
  745. } else {
  746. $tz_offset = (int) -$_SESSION["clientTzOffset"];
  747. }
  748. $user_timestamp = $dt->format('U') + $tz_offset;
  749. if (!$no_smart_dt) {
  750. return smart_date_time($user_timestamp,
  751. $tz_offset, $owner_uid, $eta_min);
  752. } else {
  753. if ($long)
  754. $format = get_pref('LONG_DATE_FORMAT', $owner_uid);
  755. else
  756. $format = get_pref('SHORT_DATE_FORMAT', $owner_uid);
  757. return date($format, $user_timestamp);
  758. }
  759. }
  760. function smart_date_time($timestamp, $tz_offset = 0, $owner_uid = false, $eta_min = false) {
  761. if (!$owner_uid) $owner_uid = $_SESSION['uid'];
  762. if ($eta_min && time() + $tz_offset - $timestamp < 3600) {
  763. return T_sprintf("%d min", date("i", time() + $tz_offset - $timestamp));
  764. } else if (date("Y.m.d", $timestamp) == date("Y.m.d", time() + $tz_offset)) {
  765. return date("G:i", $timestamp);
  766. } else if (date("Y", $timestamp) == date("Y", time() + $tz_offset)) {
  767. $format = get_pref('SHORT_DATE_FORMAT', $owner_uid);
  768. return date($format, $timestamp);
  769. } else {
  770. $format = get_pref('LONG_DATE_FORMAT', $owner_uid);
  771. return date($format, $timestamp);
  772. }
  773. }
  774. function sql_bool_to_bool($s) {
  775. if ($s == "t" || $s == "1" || strtolower($s) == "true") {
  776. return true;
  777. } else {
  778. return false;
  779. }
  780. }
  781. function bool_to_sql_bool($s) {
  782. if ($s) {
  783. return "true";
  784. } else {
  785. return "false";
  786. }
  787. }
  788. // Session caching removed due to causing wrong redirects to upgrade
  789. // script when get_schema_version() is called on an obsolete session
  790. // created on a previous schema version.
  791. function get_schema_version($nocache = false) {
  792. global $schema_version;
  793. if (!$schema_version && !$nocache) {
  794. $result = db_query("SELECT schema_version FROM ttrss_version");
  795. $version = db_fetch_result($result, 0, "schema_version");
  796. $schema_version = $version;
  797. return $version;
  798. } else {
  799. return $schema_version;
  800. }
  801. }
  802. function sanity_check() {
  803. require_once 'errors.php';
  804. global $ERRORS;
  805. $error_code = 0;
  806. $schema_version = get_schema_version(true);
  807. if ($schema_version != SCHEMA_VERSION) {
  808. $error_code = 5;
  809. }
  810. if (DB_TYPE == "mysql") {
  811. $result = db_query("SELECT true", false);
  812. if (db_num_rows($result) != 1) {
  813. $error_code = 10;
  814. }
  815. }
  816. if (db_escape_string("testTEST") != "testTEST") {
  817. $error_code = 12;
  818. }
  819. return array("code" => $error_code, "message" => $ERRORS[$error_code]);
  820. }
  821. function file_is_locked($filename) {
  822. if (file_exists(LOCK_DIRECTORY . "/$filename")) {
  823. if (function_exists('flock')) {
  824. $fp = @fopen(LOCK_DIRECTORY . "/$filename", "r");
  825. if ($fp) {
  826. if (flock($fp, LOCK_EX | LOCK_NB)) {
  827. flock($fp, LOCK_UN);
  828. fclose($fp);
  829. return false;
  830. }
  831. fclose($fp);
  832. return true;
  833. } else {
  834. return false;
  835. }
  836. }
  837. return true; // consider the file always locked and skip the test
  838. } else {
  839. return false;
  840. }
  841. }
  842. function make_lockfile($filename) {
  843. $fp = fopen(LOCK_DIRECTORY . "/$filename", "w");
  844. if ($fp && flock($fp, LOCK_EX | LOCK_NB)) {
  845. $stat_h = fstat($fp);
  846. $stat_f = stat(LOCK_DIRECTORY . "/$filename");
  847. if (strtoupper(substr(PHP_OS, 0, 3)) !== 'WIN') {
  848. if ($stat_h["ino"] != $stat_f["ino"] ||
  849. $stat_h["dev"] != $stat_f["dev"]) {
  850. return false;
  851. }
  852. }
  853. if (function_exists('posix_getpid')) {
  854. fwrite($fp, posix_getpid() . "\n");
  855. }
  856. return $fp;
  857. } else {
  858. return false;
  859. }
  860. }
  861. function make_stampfile($filename) {
  862. $fp = fopen(LOCK_DIRECTORY . "/$filename", "w");
  863. if (flock($fp, LOCK_EX | LOCK_NB)) {
  864. fwrite($fp, time() . "\n");
  865. flock($fp, LOCK_UN);
  866. fclose($fp);
  867. return true;
  868. } else {
  869. return false;
  870. }
  871. }
  872. function sql_random_function() {
  873. if (DB_TYPE == "mysql") {
  874. return "RAND()";
  875. } else {
  876. return "RANDOM()";
  877. }
  878. }
  879. function catchup_feed($feed, $cat_view, $owner_uid = false, $max_id = false, $mode = 'all') {
  880. if (!$owner_uid) $owner_uid = $_SESSION['uid'];
  881. //if (preg_match("/^-?[0-9][0-9]*$/", $feed) != false) {
  882. // Todo: all this interval stuff needs some generic generator function
  883. $date_qpart = "false";
  884. switch ($mode) {
  885. case "1day":
  886. if (DB_TYPE == "pgsql") {
  887. $date_qpart = "date_entered < NOW() - INTERVAL '1 day' ";
  888. } else {
  889. $date_qpart = "date_entered < DATE_SUB(NOW(), INTERVAL 1 DAY) ";
  890. }
  891. break;
  892. case "1week":
  893. if (DB_TYPE == "pgsql") {
  894. $date_qpart = "date_entered < NOW() - INTERVAL '1 week' ";
  895. } else {
  896. $date_qpart = "date_entered < DATE_SUB(NOW(), INTERVAL 1 WEEK) ";
  897. }
  898. break;
  899. case "2week":
  900. if (DB_TYPE == "pgsql") {
  901. $date_qpart = "date_entered < NOW() - INTERVAL '2 week' ";
  902. } else {
  903. $date_qpart = "date_entered < DATE_SUB(NOW(), INTERVAL 2 WEEK) ";
  904. }
  905. break;
  906. default:
  907. $date_qpart = "true";
  908. }
  909. if (is_numeric($feed)) {
  910. if ($cat_view) {
  911. if ($feed >= 0) {
  912. if ($feed > 0) {
  913. $children = getChildCategories($feed, $owner_uid);
  914. array_push($children, $feed);
  915. $children = join(",", $children);
  916. $cat_qpart = "cat_id IN ($children)";
  917. } else {
  918. $cat_qpart = "cat_id IS NULL";
  919. }
  920. db_query("UPDATE ttrss_user_entries
  921. SET unread = false, last_read = NOW() WHERE ref_id IN
  922. (SELECT id FROM
  923. (SELECT DISTINCT id FROM ttrss_entries, ttrss_user_entries WHERE ref_id = id
  924. AND owner_uid = $owner_uid AND unread = true AND feed_id IN
  925. (SELECT id FROM ttrss_feeds WHERE $cat_qpart) AND $date_qpart) as tmp)");
  926. } else if ($feed == -2) {
  927. db_query("UPDATE ttrss_user_entries
  928. SET unread = false,last_read = NOW() WHERE (SELECT COUNT(*)
  929. FROM ttrss_user_labels2, ttrss_entries WHERE article_id = ref_id AND id = ref_id AND $date_qpart) > 0
  930. AND unread = true AND owner_uid = $owner_uid");
  931. }
  932. } else if ($feed > 0) {
  933. db_query("UPDATE ttrss_user_entries
  934. SET unread = false, last_read = NOW() WHERE ref_id IN
  935. (SELECT id FROM
  936. (SELECT DISTINCT id FROM ttrss_entries, ttrss_user_entries WHERE ref_id = id
  937. AND owner_uid = $owner_uid AND unread = true AND feed_id = $feed AND $date_qpart) as tmp)");
  938. } else if ($feed < 0 && $feed > LABEL_BASE_INDEX) { // special, like starred
  939. if ($feed == -1) {
  940. db_query("UPDATE ttrss_user_entries
  941. SET unread = false, last_read = NOW() WHERE ref_id IN
  942. (SELECT id FROM
  943. (SELECT DISTINCT id FROM ttrss_entries, ttrss_user_entries WHERE ref_id = id
  944. AND owner_uid = $owner_uid AND unread = true AND marked = true AND $date_qpart) as tmp)");
  945. }
  946. if ($feed == -2) {
  947. db_query("UPDATE ttrss_user_entries
  948. SET unread = false, last_read = NOW() WHERE ref_id IN
  949. (SELECT id FROM
  950. (SELECT DISTINCT id FROM ttrss_entries, ttrss_user_entries WHERE ref_id = id
  951. AND owner_uid = $owner_uid AND unread = true AND published = true AND $date_qpart) as tmp)");
  952. }
  953. if ($feed == -3) {
  954. $intl = get_pref("FRESH_ARTICLE_MAX_AGE");
  955. if (DB_TYPE == "pgsql") {
  956. $match_part = "date_entered > NOW() - INTERVAL '$intl hour' ";
  957. } else {
  958. $match_part = "date_entered > DATE_SUB(NOW(),
  959. INTERVAL $intl HOUR) ";
  960. }
  961. db_query("UPDATE ttrss_user_entries
  962. SET unread = false, last_read = NOW() WHERE ref_id IN
  963. (SELECT id FROM
  964. (SELECT DISTINCT id FROM ttrss_entries, ttrss_user_entries WHERE ref_id = id
  965. AND owner_uid = $owner_uid AND score >= 0 AND unread = true AND $date_qpart AND $match_part) as tmp)");
  966. }
  967. if ($feed == -4) {
  968. db_query("UPDATE ttrss_user_entries
  969. SET unread = false, last_read = NOW() WHERE ref_id IN
  970. (SELECT id FROM
  971. (SELECT DISTINCT id FROM ttrss_entries, ttrss_user_entries WHERE ref_id = id
  972. AND owner_uid = $owner_uid AND unread = true AND $date_qpart) as tmp)");
  973. }
  974. } else if ($feed < LABEL_BASE_INDEX) { // label
  975. $label_id = feed_to_label_id($feed);
  976. db_query("UPDATE ttrss_user_entries
  977. SET unread = false, last_read = NOW() WHERE ref_id IN
  978. (SELECT id FROM
  979. (SELECT DISTINCT ttrss_entries.id FROM ttrss_entries, ttrss_user_entries, ttrss_user_labels2 WHERE ref_id = id
  980. AND label_id = '$label_id' AND ref_id = article_id
  981. AND owner_uid = $owner_uid AND unread = true AND $date_qpart) as tmp)");
  982. }
  983. ccache_update($feed, $owner_uid, $cat_view);
  984. } else { // tag
  985. db_query("UPDATE ttrss_user_entries
  986. SET unread = false, last_read = NOW() WHERE ref_id IN
  987. (SELECT id FROM
  988. (SELECT DISTINCT ttrss_entries.id FROM ttrss_entries, ttrss_user_entries, ttrss_tags WHERE ref_id = ttrss_entries.id
  989. AND post_int_id = int_id AND tag_name = '$feed'
  990. AND ttrss_user_entries.owner_uid = $owner_uid AND unread = true AND $date_qpart) as tmp)");
  991. }
  992. }
  993. function getAllCounters() {
  994. $data = getGlobalCounters();
  995. $data = array_merge($data, getVirtCounters());
  996. $data = array_merge($data, getLabelCounters());
  997. $data = array_merge($data, getFeedCounters());
  998. $data = array_merge($data, getCategoryCounters());
  999. return $data;
  1000. }
  1001. function getCategoryTitle($cat_id) {
  1002. if ($cat_id == -1) {
  1003. return __("Special");
  1004. } else if ($cat_id == -2) {
  1005. return __("Labels");
  1006. } else {
  1007. $result = db_query("SELECT title FROM ttrss_feed_categories WHERE
  1008. id = '$cat_id'");
  1009. if (db_num_rows($result) == 1) {
  1010. return db_fetch_result($result, 0, "title");
  1011. } else {
  1012. return __("Uncategorized");
  1013. }
  1014. }
  1015. }
  1016. function getCategoryCounters() {
  1017. $ret_arr = array();
  1018. /* Labels category */
  1019. $cv = array("id" => -2, "kind" => "cat",
  1020. "counter" => getCategoryUnread(-2));
  1021. array_push($ret_arr, $cv);
  1022. $result = db_query("SELECT id AS cat_id, value AS unread,
  1023. (SELECT COUNT(id) FROM ttrss_feed_categories AS c2
  1024. WHERE c2.parent_cat = ttrss_feed_categories.id) AS num_children
  1025. FROM ttrss_feed_categories, ttrss_cat_counters_cache
  1026. WHERE ttrss_cat_counters_cache.feed_id = id AND
  1027. ttrss_cat_counters_cache.owner_uid = ttrss_feed_categories.owner_uid AND
  1028. ttrss_feed_categories.owner_uid = " . $_SESSION["uid"]);
  1029. while ($line = db_fetch_assoc($result)) {
  1030. $line["cat_id"] = (int) $line["cat_id"];
  1031. if ($line["num_children"] > 0) {
  1032. $child_counter = getCategoryChildrenUnread($line["cat_id"], $_SESSION["uid"]);
  1033. } else {
  1034. $child_counter = 0;
  1035. }
  1036. $cv = array("id" => $line["cat_id"], "kind" => "cat",
  1037. "counter" => $line["unread"] + $child_counter);
  1038. array_push($ret_arr, $cv);
  1039. }
  1040. /* Special case: NULL category doesn't actually exist in the DB */
  1041. $cv = array("id" => 0, "kind" => "cat",
  1042. "counter" => (int) ccache_find(0, $_SESSION["uid"], true));
  1043. array_push($ret_arr, $cv);
  1044. return $ret_arr;
  1045. }
  1046. // only accepts real cats (>= 0)
  1047. function getCategoryChildrenUnread($cat, $owner_uid = false) {
  1048. if (!$owner_uid) $owner_uid = $_SESSION["uid"];
  1049. $result = db_query("SELECT id FROM ttrss_feed_categories WHERE parent_cat = '$cat'
  1050. AND owner_uid = $owner_uid");
  1051. $unread = 0;
  1052. while ($line = db_fetch_assoc($result)) {
  1053. $unread += getCategoryUnread($line["id"], $owner_uid);
  1054. $unread += getCategoryChildrenUnread($line["id"], $owner_uid);
  1055. }
  1056. return $unread;
  1057. }
  1058. function getCategoryUnread($cat, $owner_uid = false) {
  1059. if (!$owner_uid) $owner_uid = $_SESSION["uid"];
  1060. if ($cat >= 0) {
  1061. if ($cat != 0) {
  1062. $cat_query = "cat_id = '$cat'";
  1063. } else {
  1064. $cat_query = "cat_id IS NULL";
  1065. }
  1066. $result = db_query("SELECT id FROM ttrss_feeds WHERE $cat_query
  1067. AND owner_uid = " . $owner_uid);
  1068. $cat_feeds = array();
  1069. while ($line = db_fetch_assoc($result)) {
  1070. array_push($cat_feeds, "feed_id = " . $line["id"]);
  1071. }
  1072. if (count($cat_feeds) == 0) return 0;
  1073. $match_part = implode(" OR ", $cat_feeds);
  1074. $result = db_query("SELECT COUNT(int_id) AS unread
  1075. FROM ttrss_user_entries
  1076. WHERE unread = true AND ($match_part)
  1077. AND owner_uid = " . $owner_uid);
  1078. $unread = 0;
  1079. # this needs to be rewritten
  1080. while ($line = db_fetch_assoc($result)) {
  1081. $unread += $line["unread"];
  1082. }
  1083. return $unread;
  1084. } else if ($cat == -1) {
  1085. return getFeedUnread(-1) + getFeedUnread(-2) + getFeedUnread(-3) + getFeedUnread(0);
  1086. } else if ($cat == -2) {
  1087. $result = db_query("
  1088. SELECT COUNT(unread) AS unread FROM
  1089. ttrss_user_entries, ttrss_user_labels2
  1090. WHERE article_id = ref_id AND unread = true
  1091. AND ttrss_user_entries.owner_uid = '$owner_uid'");
  1092. $unread = db_fetch_result($result, 0, "unread");
  1093. return $unread;
  1094. }
  1095. }
  1096. function getFeedUnread($feed, $is_cat = false) {
  1097. return getFeedArticles($feed, $is_cat, true, $_SESSION["uid"]);
  1098. }
  1099. function getLabelUnread($label_id, $owner_uid = false) {
  1100. if (!$owner_uid) $owner_uid = $_SESSION["uid"];
  1101. $result = db_query("SELECT COUNT(ref_id) AS unread FROM ttrss_user_entries, ttrss_user_labels2
  1102. WHERE owner_uid = '$owner_uid' AND unread = true AND label_id = '$label_id' AND article_id = ref_id");
  1103. if (db_num_rows($result) != 0) {
  1104. return db_fetch_result($result, 0, "unread");
  1105. } else {
  1106. return 0;
  1107. }
  1108. }
  1109. function getFeedArticles($feed, $is_cat = false, $unread_only = false,
  1110. $owner_uid = false) {
  1111. $n_feed = (int) $feed;
  1112. $need_entries = false;
  1113. if (!$owner_uid) $owner_uid = $_SESSION["uid"];
  1114. if ($unread_only) {
  1115. $unread_qpart = "unread = true";
  1116. } else {
  1117. $unread_qpart = "true";
  1118. }
  1119. if ($is_cat) {
  1120. return getCategoryUnread($n_feed, $owner_uid);
  1121. } else if ($n_feed == -6) {
  1122. return 0;
  1123. } else if ($feed != "0" && $n_feed == 0) {
  1124. $feed = db_escape_string($feed);
  1125. $result = db_query("SELECT SUM((SELECT COUNT(int_id)
  1126. FROM ttrss_user_entries,ttrss_entries WHERE int_id = post_int_id
  1127. AND ref_id = id AND $unread_qpart)) AS count FROM ttrss_tags
  1128. WHERE owner_uid = $owner_uid AND tag_name = '$feed'");
  1129. return db_fetch_result($result, 0, "count");
  1130. } else if ($n_feed == -1) {
  1131. $match_part = "marked = true";
  1132. } else if ($n_feed == -2) {
  1133. $match_part = "published = true";
  1134. } else if ($n_feed == -3) {
  1135. $match_part = "unread = true AND score >= 0";
  1136. $intl = get_pref("FRESH_ARTICLE_MAX_AGE", $owner_uid);
  1137. if (DB_TYPE == "pgsql") {
  1138. $match_part .= " AND date_entered > NOW() - INTERVAL '$intl hour' ";
  1139. } else {
  1140. $match_part .= " AND date_entered > DATE_SUB(NOW(), INTERVAL $intl HOUR) ";
  1141. }
  1142. $need_entries = true;
  1143. } else if ($n_feed == -4) {
  1144. $match_part = "true";
  1145. } else if ($n_feed >= 0) {
  1146. if ($n_feed != 0) {
  1147. $match_part = "feed_id = '$n_feed'";
  1148. } else {
  1149. $match_part = "feed_id IS NULL";
  1150. }
  1151. } else if ($feed < LABEL_BASE_INDEX) {
  1152. $label_id = feed_to_label_id($feed);
  1153. return getLabelUnread($label_id, $owner_uid);
  1154. }
  1155. if ($match_part) {
  1156. if ($need_entries) {
  1157. $from_qpart = "ttrss_user_entries,ttrss_entries";
  1158. $from_where = "ttrss_entries.id = ttrss_user_entries.ref_id AND";
  1159. } else {
  1160. $from_qpart = "ttrss_user_entries";
  1161. $from_where = "";
  1162. }
  1163. $query = "SELECT count(int_id) AS unread
  1164. FROM $from_qpart WHERE
  1165. $unread_qpart AND $from_where ($match_part) AND ttrss_user_entries.owner_uid = $owner_uid";
  1166. //echo "[$feed/$query]\n";
  1167. $result = db_query($query);
  1168. } else {
  1169. $result = db_query("SELECT COUNT(post_int_id) AS unread
  1170. FROM ttrss_tags,ttrss_user_entries,ttrss_entries
  1171. WHERE tag_name = '$feed' AND post_int_id = int_id AND ref_id = ttrss_entries.id
  1172. AND $unread_qpart AND ttrss_tags.owner_uid = " . $owner_uid);
  1173. }
  1174. $unread = db_fetch_result($result, 0, "unread");
  1175. return $unread;
  1176. }
  1177. function getGlobalUnread($user_id = false) {
  1178. if (!$user_id) {
  1179. $user_id = $_SESSION["uid"];
  1180. }
  1181. $result = db_query("SELECT SUM(value) AS c_id FROM ttrss_counters_cache
  1182. WHERE owner_uid = '$user_id' AND feed_id > 0");
  1183. $c_id = db_fetch_result($result, 0, "c_id");
  1184. return $c_id;
  1185. }
  1186. function getGlobalCounters($global_unread = -1) {
  1187. $ret_arr = array();
  1188. if ($global_unread == -1) {
  1189. $global_unread = getGlobalUnread();
  1190. }
  1191. $cv = array("id" => "global-unread",
  1192. "counter" => (int) $global_unread);
  1193. array_push($ret_arr, $cv);
  1194. $result = db_query("SELECT COUNT(id) AS fn FROM
  1195. ttrss_feeds WHERE owner_uid = " . $_SESSION["uid"]);
  1196. $subscribed_feeds = db_fetch_result($result, 0, "fn");
  1197. $cv = array("id" => "subscribed-feeds",
  1198. "counter" => (int) $subscribed_feeds);
  1199. array_push($ret_arr, $cv);
  1200. return $ret_arr;
  1201. }
  1202. function getVirtCounters() {
  1203. $ret_arr = array();
  1204. for ($i = 0; $i >= -4; $i--) {
  1205. $count = getFeedUnread($i);
  1206. if ($i == 0 || $i == -1 || $i == -2)
  1207. $auxctr = getFeedArticles($i, false);
  1208. else
  1209. $auxctr = 0;
  1210. $cv = array("id" => $i,
  1211. "counter" => (int) $count,
  1212. "auxcounter" => $auxctr);
  1213. // if (get_pref('EXTENDED_FEEDLIST'))
  1214. // $cv["xmsg"] = getFeedArticles($i)." ".__("total");
  1215. array_push($ret_arr, $cv);
  1216. }
  1217. $feeds = PluginHost::getInstance()->get_feeds(-1);
  1218. if (is_array($feeds)) {
  1219. foreach ($feeds as $feed) {
  1220. $cv = array("id" => PluginHost::pfeed_to_feed_id($feed['id']),
  1221. "counter" => $feed['sender']->get_unread($feed['id']));
  1222. if (method_exists($feed['sender'], 'get_total'))
  1223. $cv["auxcounter"] = $feed['sender']->get_total($feed['id']);
  1224. array_push($ret_arr, $cv);
  1225. }
  1226. }
  1227. return $ret_arr;
  1228. }
  1229. function getLabelCounters($descriptions = false) {
  1230. $ret_arr = array();
  1231. $owner_uid = $_SESSION["uid"];
  1232. $result = db_query("SELECT id,caption,SUM(CASE WHEN u1.unread = true THEN 1 ELSE 0 END) AS unread, COUNT(u1.unread) AS total
  1233. FROM ttrss_labels2 LEFT JOIN ttrss_user_labels2 ON
  1234. (ttrss_labels2.id = label_id)
  1235. LEFT JOIN ttrss_user_entries AS u1 ON u1.ref_id = article_id
  1236. WHERE ttrss_labels2.owner_uid = $owner_uid AND u1.owner_uid = $owner_uid
  1237. GROUP BY ttrss_labels2.id,
  1238. ttrss_labels2.caption");
  1239. while ($line = db_fetch_assoc($result)) {
  1240. $id = label_to_feed_id($line["id"]);
  1241. $cv = array("id" => $id,
  1242. "counter" => (int) $line["unread"],
  1243. "auxcounter" => (int) $line["total"]);
  1244. if ($descriptions)
  1245. $cv["description"] = $line["caption"];
  1246. array_push($ret_arr, $cv);
  1247. }
  1248. return $ret_arr;
  1249. }
  1250. function getFeedCounters($active_feed = false) {
  1251. $ret_arr = array();
  1252. $query = "SELECT ttrss_feeds.id,
  1253. ttrss_feeds.title,
  1254. ".SUBSTRING_FOR_DATE."(ttrss_feeds.last_updated,1,19) AS last_updated,
  1255. last_error, value AS count
  1256. FROM ttrss_feeds, ttrss_counters_cache
  1257. WHERE ttrss_feeds.owner_uid = ".$_SESSION["uid"]."
  1258. AND ttrss_counters_cache.owner_uid = ttrss_feeds.owner_uid
  1259. AND ttrss_counters_cache.feed_id = id";
  1260. $result = db_query($query);
  1261. while ($line = db_fetch_assoc($result)) {
  1262. $id = $line["id"];
  1263. $count = $line["count"];
  1264. $last_error = htmlspecialchars($line["last_error"]);
  1265. $last_updated = make_local_datetime($line['last_updated'], false);
  1266. $has_img = feed_has_icon($id);
  1267. if (date('Y') - date('Y', strtotime($line['last_updated'])) > 2)
  1268. $last_updated = '';
  1269. $cv = array("id" => $id,
  1270. "updated" => $last_updated,
  1271. "counter" => (int) $count,
  1272. "has_img" => (int) $has_img);
  1273. if ($last_error)
  1274. $cv["error"] = $last_error;
  1275. // if (get_pref('EXTENDED_FEEDLIST'))
  1276. // $cv["xmsg"] = getFeedArticles($id)." ".__("total");
  1277. if ($active_feed && $id == $active_feed)
  1278. $cv["title"] = truncate_string($line["title"], 30);
  1279. array_push($ret_arr, $cv);
  1280. }
  1281. return $ret_arr;
  1282. }
  1283. function get_pgsql_version() {
  1284. $result = db_query("SELECT version() AS version");
  1285. $version = explode(" ", db_fetch_result($result, 0, "version"));
  1286. return $version[1];
  1287. }
  1288. /**
  1289. * @return array (code => Status code, message => error message if available)
  1290. *
  1291. * 0 - OK, Feed already exists
  1292. * 1 - OK, Feed added
  1293. * 2 - Invalid URL
  1294. * 3 - URL content is HTML, no feeds available
  1295. * 4 - URL content is HTML which contains multiple feeds.
  1296. * Here you should call extractfeedurls in rpc-backend
  1297. * to get all possible feeds.
  1298. * 5 - Couldn't download the URL content.
  1299. * 6 - Content is an invalid XML.
  1300. */
  1301. function subscribe_to_feed($url, $cat_id = 0,
  1302. $auth_login = '', $auth_pass = '') {
  1303. global $fetch_last_error;
  1304. require_once "include/rssfuncs.php";
  1305. $url = fix_url($url);
  1306. if (!$url || !validate_feed_url($url)) return array("code" => 2);
  1307. $contents = @fetch_file_contents($url, false, $auth_login, $auth_pass);
  1308. if (!$contents) {
  1309. return array("code" => 5, "message" => $fetch_last_error);
  1310. }
  1311. foreach (PluginHost::getInstance()->get_hooks(PluginHost::HOOK_SUBSCRIBE_FEED) as $plugin) {
  1312. $contents = $plugin->hook_subscribe_feed($contents, $url, $auth_login, $auth_pass);
  1313. }
  1314. if (is_html($contents)) {
  1315. $feedUrls = get_feeds_from_html($url, $contents);
  1316. if (count($feedUrls) == 0) {
  1317. return array("code" => 3);
  1318. } else if (count($feedUrls) > 1) {
  1319. return array("code" => 4, "feeds" => $feedUrls);
  1320. }
  1321. //use feed url as new URL
  1322. $url = key($feedUrls);
  1323. }
  1324. if ($cat_id == "0" || !$cat_id) {
  1325. $cat_qpart = "NULL";
  1326. } else {
  1327. $cat_qpart = "'$cat_id'";
  1328. }
  1329. $result = db_query(
  1330. "SELECT id FROM ttrss_feeds
  1331. WHERE feed_url = '$url' AND owner_uid = ".$_SESSION["uid"]);
  1332. $auth_pass_encrypted = 'false';
  1333. $auth_pass = db_escape_string($auth_pass);
  1334. if (db_num_rows($result) == 0) {
  1335. $result = db_query(
  1336. "INSERT INTO ttrss_feeds
  1337. (owner_uid,feed_url,title,cat_id, auth_login,auth_pass,update_method,auth_pass_encrypted)
  1338. VALUES ('".$_SESSION["uid"]."', '$url',
  1339. '[Unknown]', $cat_qpart, '$auth_login', '$auth_pass', 0, $auth_pass_encrypted)");
  1340. $result = db_query(
  1341. "SELECT id FROM ttrss_feeds WHERE feed_url = '$url'
  1342. AND owner_uid = " . $_SESSION["uid"]);
  1343. $feed_id = db_fetch_result($result, 0, "id");
  1344. if ($feed_id) {
  1345. set_basic_feed_info($feed_id);
  1346. }
  1347. return array("code" => 1, "feed_id" => (int) $feed_id);
  1348. } else {
  1349. return array("code" => 0, "feed_id" => (int) db_fetch_result($result, 0, "id"));
  1350. }
  1351. }
  1352. function print_feed_select($id, $default_id = "",
  1353. $attributes = "", $include_all_feeds = true,
  1354. $root_id = false, $nest_level = 0) {
  1355. if (!$root_id) {
  1356. print "<select id=\"$id\" name=\"$id\" $attributes>";
  1357. if ($include_all_feeds) {
  1358. $is_selected = ("0" == $default_id) ? "selected=\"1\"" : "";
  1359. print "<option $is_selected value=\"0\">".__('All feeds')."</option>";
  1360. }
  1361. }
  1362. if (get_pref('ENABLE_FEED_CATS')) {
  1363. if ($root_id)
  1364. $parent_qpart = "parent_cat = '$root_id'";
  1365. else
  1366. $parent_qpart = "parent_cat IS NULL";
  1367. $result = db_query("SELECT id,title,
  1368. (SELECT COUNT(id) FROM ttrss_feed_categories AS c2 WHERE
  1369. c2.parent_cat = ttrss_feed_categories.id) AS num_children
  1370. FROM ttrss_feed_categories
  1371. WHERE owner_uid = ".$_SESSION["uid"]." AND $parent_qpart ORDER BY title");
  1372. while ($line = db_fetch_assoc($result)) {
  1373. for ($i = 0; $i < $nest_level; $i++)
  1374. $line["title"] = " - " . $line["title"];
  1375. $is_selected = ("CAT:".$line["id"] == $default_id) ? "selected=\"1\"" : "";
  1376. printf("<option $is_selected value='CAT:%d'>%s</option>",
  1377. $line["id"], htmlspecialchars($line["title"]));
  1378. if ($line["num_children"] > 0)
  1379. print_feed_select($id, $default_id, $attributes,
  1380. $include_all_feeds, $line["id"], $nest_level+1);
  1381. $feed_result = db_query("SELECT id,title FROM ttrss_feeds
  1382. WHERE cat_id = '".$line["id"]."' AND owner_uid = ".$_SESSION["uid"] . " ORDER BY title");
  1383. while ($fline = db_fetch_assoc($feed_result)) {
  1384. $is_selected = ($fline["id"] == $default_id) ? "selected=\"1\"" : "";
  1385. $fline["title"] = " + " . $fline["title"];
  1386. for ($i = 0; $i < $nest_level; $i++)
  1387. $fline["title"] = " - " . $fline["title"];
  1388. printf("<option $is_selected value='%d'>%s</option>",
  1389. $fline["id"], htmlspecialchars($fline["title"]));
  1390. }
  1391. }
  1392. if (!$root_id) {
  1393. $default_is_cat = ($default_id == "CAT:0");
  1394. $is_selected = $default_is_cat ? "selected=\"1\"" : "";
  1395. printf("<option $is_selected value='CAT:0'>%s</option>",
  1396. __("Uncategorized"));
  1397. $feed_result = db_query("SELECT id,title FROM ttrss_feeds
  1398. WHERE cat_id IS NULL AND owner_uid = ".$_SESSION["uid"] . " ORDER BY title");
  1399. while ($fline = db_fetch_assoc($feed_result)) {
  1400. $is_selected = ($fline["id"] == $default_id && !$default_is_cat) ? "selected=\"1\"" : "";
  1401. $fline["title"] = " + " . $fline["title"];
  1402. for ($i = 0; $i < $nest_level; $i++)
  1403. $fline["title"] = " - " . $fline["title"];
  1404. printf("<option $is_selected value='%d'>%s</option>",
  1405. $fline["id"], htmlspecialchars($fline["title"]));
  1406. }
  1407. }
  1408. } else {
  1409. $result = db_query("SELECT id,title FROM ttrss_feeds
  1410. WHERE owner_uid = ".$_SESSION["uid"]." ORDER BY title");
  1411. while ($line = db_fetch_assoc($result)) {
  1412. $is_selected = ($line["id"] == $default_id) ? "selected=\"1\"" : "";
  1413. printf("<option $is_selected value='%d'>%s</option>",
  1414. $line["id"], htmlspecialchars($line["title"]));
  1415. }
  1416. }
  1417. if (!$root_id) {
  1418. print "</select>";
  1419. }
  1420. }
  1421. function print_feed_cat_select($id, $default_id,
  1422. $attributes, $include_all_cats = true, $root_id = false, $nest_level = 0) {
  1423. if (!$root_id) {
  1424. print "<select id=\"$id\" name=\"$id\" default=\"$default_id\" onchange=\"catSelectOnChange(this)\" $attributes>";
  1425. }
  1426. if ($root_id)
  1427. $parent_qpart = "parent_cat = '$root_id'";
  1428. else
  1429. $parent_qpart = "parent_cat IS NULL";
  1430. $result = db_query("SELECT id,title,
  1431. (SELECT COUNT(id) FROM ttrss_feed_categories AS c2 WHERE
  1432. c2.parent_cat = ttrss_feed_categories.id) AS num_children
  1433. FROM ttrss_feed_categories
  1434. WHERE owner_uid = ".$_SESSION["uid"]." AND $parent_qpart ORDER BY title");
  1435. while ($line = db_fetch_assoc($result)) {
  1436. if ($line["id"] == $default_id) {
  1437. $is_selected = "selected=\"1\"";
  1438. } else {
  1439. $is_selected = "";
  1440. }
  1441. for ($i = 0; $i < $nest_level; $i++)
  1442. $line["title"] = " - " . $line["title"];
  1443. if ($line["title"])
  1444. printf("<option $is_selected value='%d'>%s</option>",
  1445. $line["id"], htmlspecialchars($line["title"]));
  1446. if ($line["num_children"] > 0)
  1447. print_feed_cat_select($id, $default_id, $attributes,
  1448. $include_all_cats, $line["id"], $nest_level+1);
  1449. }
  1450. if (!$root_id) {
  1451. if ($include_all_cats) {
  1452. if (db_num_rows($result) > 0) {
  1453. print "<option disabled=\"1\">--------</option>";
  1454. }
  1455. if ($default_id == 0) {
  1456. $is_selected = "selected=\"1\"";
  1457. } else {
  1458. $is_selected = "";
  1459. }
  1460. print "<option $is_selected value=\"0\">".__('Uncategorized')."</option>";
  1461. }
  1462. print "</select>";
  1463. }
  1464. }
  1465. function checkbox_to_sql_bool($val) {
  1466. return ($val == "on") ? "true" : "false";
  1467. }
  1468. function getFeedCatTitle($id) {
  1469. if ($id == -1) {
  1470. return __("Special");
  1471. } else if ($id < LABEL_BASE_INDEX) {
  1472. return __("Labels");
  1473. } else if ($id > 0) {
  1474. $result = db_query("SELECT ttrss_feed_categories.title
  1475. FROM ttrss_feeds, ttrss_feed_categories WHERE ttrss_feeds.id = '$id' AND
  1476. cat_id = ttrss_feed_categories.id");
  1477. if (db_num_rows($result) == 1) {
  1478. return db_fetch_result($result, 0, "title");
  1479. } else {
  1480. return __("Uncategorized");
  1481. }
  1482. } else {
  1483. return "getFeedCatTitle($id) failed";
  1484. }
  1485. }
  1486. function getFeedIcon($id) {
  1487. switch ($id) {
  1488. case 0:
  1489. return "images/archive.png";
  1490. break;
  1491. case -1:
  1492. return "images/star.png";
  1493. break;
  1494. case -2:
  1495. return "images/feed.png";
  1496. break;
  1497. case -3:
  1498. return "images/fresh.png";
  1499. break;
  1500. case -4:
  1501. return "images/folder.png";
  1502. break;
  1503. case -6:
  1504. return "images/time.png";
  1505. break;
  1506. default:
  1507. if ($id < LABEL_BASE_INDEX) {
  1508. return "images/label.png";
  1509. } else {
  1510. if (file_exists(ICONS_DIR . "/$id.ico"))
  1511. return ICONS_URL . "/$id.ico";
  1512. }
  1513. break;
  1514. }
  1515. return false;
  1516. }
  1517. function getFeedTitle($id, $cat = false) {
  1518. if ($cat) {
  1519. return getCategoryTitle($id);
  1520. } else if ($id == -1) {
  1521. return __("Starred articles");
  1522. } else if ($id == -2) {
  1523. return __("Published articles");
  1524. } else if ($id == -3) {
  1525. return __("Fresh articles");
  1526. } else if ($id == -4) {
  1527. return __("All articles");
  1528. } else if ($id === 0 || $id === "0") {
  1529. return __("Archived articles");
  1530. } else if ($id == -6) {
  1531. return __("Recently read");
  1532. } else if ($id < LABEL_BASE_INDEX) {
  1533. $label_id = feed_to_label_id($id);
  1534. $result = db_query("SELECT caption FROM ttrss_labels2 WHERE id = '$label_id'");
  1535. if (db_num_rows($result) == 1) {
  1536. return db_fetch_result($result, 0, "caption");
  1537. } else {
  1538. return "Unknown label ($label_id)";
  1539. }
  1540. } else if (is_numeric($id) && $id > 0) {
  1541. $result = db_query("SELECT title FROM ttrss_feeds WHERE id = '$id'");
  1542. if (db_num_rows($result) == 1) {
  1543. return db_fetch_result($result, 0, "title");
  1544. } else {
  1545. return "Unknown feed ($id)";
  1546. }
  1547. } else {
  1548. return $id;
  1549. }
  1550. }
  1551. function uniqid_short() {
  1552. return uniqid(base_convert(rand(), 10, 36));
  1553. }
  1554. // TODO: less dumb splitting
  1555. require_once "functions2.php";
  1556. ?>