functions.php 54 KB

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