functions.php 71 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655
  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 'controls.php';
  115. define('SELF_USER_AGENT', 'Tiny Tiny RSS/' . VERSION . ' (http://tt-rss.org/)');
  116. ini_set('user_agent', SELF_USER_AGENT);
  117. require_once 'lib/pubsubhubbub/Publisher.php';
  118. $schema_version = false;
  119. function _debug_suppress($suppress) {
  120. global $suppress_debugging;
  121. $suppress_debugging = $suppress;
  122. }
  123. /**
  124. * Print a timestamped debug message.
  125. *
  126. * @param string $msg The debug message.
  127. * @return void
  128. */
  129. function _debug($msg, $show = true) {
  130. global $suppress_debugging;
  131. //echo "[$suppress_debugging] $msg $show\n";
  132. if ($suppress_debugging) return false;
  133. $ts = strftime("%H:%M:%S", time());
  134. if (function_exists('posix_getpid')) {
  135. $ts = "$ts/" . posix_getpid();
  136. }
  137. if ($show && !(defined('QUIET') && QUIET)) {
  138. print "[$ts] $msg\n";
  139. }
  140. if (defined('LOGFILE')) {
  141. $fp = fopen(LOGFILE, 'a+');
  142. if ($fp) {
  143. $locked = false;
  144. if (function_exists("flock")) {
  145. $tries = 0;
  146. // try to lock logfile for writing
  147. while ($tries < 5 && !$locked = flock($fp, LOCK_EX | LOCK_NB)) {
  148. sleep(1);
  149. ++$tries;
  150. }
  151. if (!$locked) {
  152. fclose($fp);
  153. return;
  154. }
  155. }
  156. fputs($fp, "[$ts] $msg\n");
  157. if (function_exists("flock")) {
  158. flock($fp, LOCK_UN);
  159. }
  160. fclose($fp);
  161. }
  162. }
  163. } // function _debug
  164. /**
  165. * Purge a feed old posts.
  166. *
  167. * @param mixed $link A database connection.
  168. * @param mixed $feed_id The id of the purged feed.
  169. * @param mixed $purge_interval Olderness of purged posts.
  170. * @param boolean $debug Set to True to enable the debug. False by default.
  171. * @access public
  172. * @return void
  173. */
  174. function purge_feed($feed_id, $purge_interval, $debug = false) {
  175. if (!$purge_interval) $purge_interval = feed_purge_interval($feed_id);
  176. $rows = -1;
  177. $result = db_query(
  178. "SELECT owner_uid FROM ttrss_feeds WHERE id = '$feed_id'");
  179. $owner_uid = false;
  180. if (db_num_rows($result) == 1) {
  181. $owner_uid = db_fetch_result($result, 0, "owner_uid");
  182. }
  183. if ($purge_interval == -1 || !$purge_interval) {
  184. if ($owner_uid) {
  185. CCache::update($feed_id, $owner_uid);
  186. }
  187. return;
  188. }
  189. if (!$owner_uid) return;
  190. if (FORCE_ARTICLE_PURGE == 0) {
  191. $purge_unread = get_pref("PURGE_UNREAD_ARTICLES",
  192. $owner_uid, false);
  193. } else {
  194. $purge_unread = true;
  195. $purge_interval = FORCE_ARTICLE_PURGE;
  196. }
  197. if (!$purge_unread) $query_limit = " unread = false AND ";
  198. if (DB_TYPE == "pgsql") {
  199. $result = db_query("DELETE FROM ttrss_user_entries
  200. USING ttrss_entries
  201. WHERE ttrss_entries.id = ref_id AND
  202. marked = false AND
  203. feed_id = '$feed_id' AND
  204. $query_limit
  205. ttrss_entries.date_updated < NOW() - INTERVAL '$purge_interval days'");
  206. } else {
  207. /* $result = db_query("DELETE FROM ttrss_user_entries WHERE
  208. marked = false AND feed_id = '$feed_id' AND
  209. (SELECT date_updated FROM ttrss_entries WHERE
  210. id = ref_id) < DATE_SUB(NOW(), INTERVAL $purge_interval DAY)"); */
  211. $result = db_query("DELETE FROM ttrss_user_entries
  212. USING ttrss_user_entries, ttrss_entries
  213. WHERE ttrss_entries.id = ref_id AND
  214. marked = false AND
  215. feed_id = '$feed_id' AND
  216. $query_limit
  217. ttrss_entries.date_updated < DATE_SUB(NOW(), INTERVAL $purge_interval DAY)");
  218. }
  219. $rows = db_affected_rows($result);
  220. CCache::update($feed_id, $owner_uid);
  221. if ($debug) {
  222. _debug("Purged feed $feed_id ($purge_interval): deleted $rows articles");
  223. }
  224. return $rows;
  225. } // function purge_feed
  226. function feed_purge_interval($feed_id) {
  227. $result = db_query("SELECT purge_interval, owner_uid FROM ttrss_feeds
  228. WHERE id = '$feed_id'");
  229. if (db_num_rows($result) == 1) {
  230. $purge_interval = db_fetch_result($result, 0, "purge_interval");
  231. $owner_uid = db_fetch_result($result, 0, "owner_uid");
  232. if ($purge_interval == 0) $purge_interval = get_pref(
  233. 'PURGE_OLD_DAYS', $owner_uid);
  234. return $purge_interval;
  235. } else {
  236. return -1;
  237. }
  238. }
  239. /*function get_feed_update_interval($feed_id) {
  240. $result = db_query("SELECT owner_uid, update_interval FROM
  241. ttrss_feeds WHERE id = '$feed_id'");
  242. if (db_num_rows($result) == 1) {
  243. $update_interval = db_fetch_result($result, 0, "update_interval");
  244. $owner_uid = db_fetch_result($result, 0, "owner_uid");
  245. if ($update_interval != 0) {
  246. return $update_interval;
  247. } else {
  248. return get_pref('DEFAULT_UPDATE_INTERVAL', $owner_uid, false);
  249. }
  250. } else {
  251. return -1;
  252. }
  253. }*/
  254. // TODO: multiple-argument way is deprecated, first parameter is a hash now
  255. function fetch_file_contents($options /* previously: 0: $url , 1: $type = false, 2: $login = false, 3: $pass = false,
  256. 4: $post_query = false, 5: $timeout = false, 6: $timestamp = 0, 7: $useragent = false*/) {
  257. global $fetch_last_error;
  258. global $fetch_last_error_code;
  259. global $fetch_last_error_content;
  260. global $fetch_last_content_type;
  261. global $fetch_curl_used;
  262. $fetch_last_error = false;
  263. $fetch_last_error_code = -1;
  264. $fetch_last_error_content = "";
  265. $fetch_last_content_type = "";
  266. $fetch_curl_used = false;
  267. if (!is_array($options)) {
  268. // falling back on compatibility shim
  269. $option_names = [ "url", "type", "login", "pass", "post_query", "timeout", "timestamp", "useragent" ];
  270. $tmp = [];
  271. for ($i = 0; $i < func_num_args(); $i++) {
  272. $tmp[$option_names[$i]] = func_get_arg($i);
  273. }
  274. $options = $tmp;
  275. /*$options = array(
  276. "url" => func_get_arg(0),
  277. "type" => @func_get_arg(1),
  278. "login" => @func_get_arg(2),
  279. "pass" => @func_get_arg(3),
  280. "post_query" => @func_get_arg(4),
  281. "timeout" => @func_get_arg(5),
  282. "timestamp" => @func_get_arg(6),
  283. "useragent" => @func_get_arg(7)
  284. ); */
  285. }
  286. $url = $options["url"];
  287. $type = isset($options["type"]) ? $options["type"] : false;
  288. $login = isset($options["login"]) ? $options["login"] : false;
  289. $pass = isset($options["pass"]) ? $options["pass"] : false;
  290. $post_query = isset($options["post_query"]) ? $options["post_query"] : false;
  291. $timeout = isset($options["timeout"]) ? $options["timeout"] : false;
  292. $timestamp = isset($options["timestamp"]) ? $options["timestamp"] : 0;
  293. $useragent = isset($options["useragent"]) ? $options["useragent"] : false;
  294. $followlocation = isset($options["followlocation"]) ? $options["followlocation"] : true;
  295. $url = ltrim($url, ' ');
  296. $url = str_replace(' ', '%20', $url);
  297. if (strpos($url, "//") === 0)
  298. $url = 'http:' . $url;
  299. if (!defined('NO_CURL') && function_exists('curl_init') && !ini_get("open_basedir")) {
  300. $fetch_curl_used = true;
  301. $ch = curl_init($url);
  302. if ($timestamp && !$post_query) {
  303. curl_setopt($ch, CURLOPT_HTTPHEADER,
  304. array("If-Modified-Since: ".gmdate('D, d M Y H:i:s \G\M\T', $timestamp)));
  305. }
  306. curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout ? $timeout : FILE_FETCH_CONNECT_TIMEOUT);
  307. curl_setopt($ch, CURLOPT_TIMEOUT, $timeout ? $timeout : FILE_FETCH_TIMEOUT);
  308. curl_setopt($ch, CURLOPT_FOLLOWLOCATION, !ini_get("open_basedir") && $followlocation);
  309. curl_setopt($ch, CURLOPT_MAXREDIRS, 20);
  310. curl_setopt($ch, CURLOPT_BINARYTRANSFER, true);
  311. curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  312. curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
  313. curl_setopt($ch, CURLOPT_USERAGENT, $useragent ? $useragent :
  314. SELF_USER_AGENT);
  315. curl_setopt($ch, CURLOPT_ENCODING, "");
  316. //curl_setopt($ch, CURLOPT_REFERER, $url);
  317. if (!ini_get("open_basedir")) {
  318. curl_setopt($ch, CURLOPT_COOKIEJAR, "/dev/null");
  319. }
  320. if (defined('_CURL_HTTP_PROXY')) {
  321. curl_setopt($ch, CURLOPT_PROXY, _CURL_HTTP_PROXY);
  322. }
  323. if ($post_query) {
  324. curl_setopt($ch, CURLOPT_POST, true);
  325. curl_setopt($ch, CURLOPT_POSTFIELDS, $post_query);
  326. }
  327. if ($login && $pass)
  328. curl_setopt($ch, CURLOPT_USERPWD, "$login:$pass");
  329. $contents = @curl_exec($ch);
  330. if (curl_errno($ch) === 23 || curl_errno($ch) === 61) {
  331. curl_setopt($ch, CURLOPT_ENCODING, 'none');
  332. $contents = @curl_exec($ch);
  333. }
  334. if ($contents === false) {
  335. $fetch_last_error = curl_errno($ch) . " " . curl_error($ch);
  336. curl_close($ch);
  337. return false;
  338. }
  339. $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
  340. $fetch_last_content_type = curl_getinfo($ch, CURLINFO_CONTENT_TYPE);
  341. $fetch_last_error_code = $http_code;
  342. if ($http_code != 200 || $type && strpos($fetch_last_content_type, "$type") === false) {
  343. if (curl_errno($ch) != 0) {
  344. $fetch_last_error = curl_errno($ch) . " " . curl_error($ch);
  345. } else {
  346. $fetch_last_error = "HTTP Code: $http_code";
  347. }
  348. $fetch_last_error_content = $contents;
  349. curl_close($ch);
  350. return false;
  351. }
  352. curl_close($ch);
  353. return $contents;
  354. } else {
  355. $fetch_curl_used = false;
  356. if ($login && $pass){
  357. $url_parts = array();
  358. preg_match("/(^[^:]*):\/\/(.*)/", $url, $url_parts);
  359. $pass = urlencode($pass);
  360. if ($url_parts[1] && $url_parts[2]) {
  361. $url = $url_parts[1] . "://$login:$pass@" . $url_parts[2];
  362. }
  363. }
  364. // TODO: should this support POST requests or not? idk
  365. if (!$post_query && $timestamp) {
  366. $context = stream_context_create(array(
  367. 'http' => array(
  368. 'method' => 'GET',
  369. 'ignore_errors' => true,
  370. 'timeout' => $timeout ? $timeout : FILE_FETCH_TIMEOUT,
  371. 'protocol_version'=> 1.1,
  372. 'header' => "If-Modified-Since: ".gmdate("D, d M Y H:i:s \\G\\M\\T\r\n", $timestamp)
  373. )));
  374. } else {
  375. $context = stream_context_create(array(
  376. 'http' => array(
  377. 'method' => 'GET',
  378. 'ignore_errors' => true,
  379. 'timeout' => $timeout ? $timeout : FILE_FETCH_TIMEOUT,
  380. 'protocol_version'=> 1.1
  381. )));
  382. }
  383. $old_error = error_get_last();
  384. $data = @file_get_contents($url, false, $context);
  385. if (isset($http_response_header) && is_array($http_response_header)) {
  386. foreach ($http_response_header as $h) {
  387. if (substr(strtolower($h), 0, 13) == 'content-type:') {
  388. $fetch_last_content_type = substr($h, 14);
  389. // don't abort here b/c there might be more than one
  390. // e.g. if we were being redirected -- last one is the right one
  391. }
  392. if (substr(strtolower($h), 0, 7) == 'http/1.') {
  393. $fetch_last_error_code = (int) substr($h, 9, 3);
  394. }
  395. }
  396. }
  397. if ($fetch_last_error_code != 200) {
  398. $error = error_get_last();
  399. if ($error['message'] != $old_error['message']) {
  400. $fetch_last_error = $error["message"];
  401. } else {
  402. $fetch_last_error = "HTTP Code: $fetch_last_error_code";
  403. }
  404. $fetch_last_error_content = $data;
  405. return false;
  406. }
  407. return $data;
  408. }
  409. }
  410. /**
  411. * Try to determine the favicon URL for a feed.
  412. * adapted from wordpress favicon plugin by Jeff Minard (http://thecodepro.com/)
  413. * http://dev.wp-plugins.org/file/favatars/trunk/favatars.php
  414. *
  415. * @param string $url A feed or page URL
  416. * @access public
  417. * @return mixed The favicon URL, or false if none was found.
  418. */
  419. function get_favicon_url($url) {
  420. $favicon_url = false;
  421. if ($html = @fetch_file_contents($url)) {
  422. libxml_use_internal_errors(true);
  423. $doc = new DOMDocument();
  424. $doc->loadHTML($html);
  425. $xpath = new DOMXPath($doc);
  426. $base = $xpath->query('/html/head/base');
  427. foreach ($base as $b) {
  428. $url = $b->getAttribute("href");
  429. break;
  430. }
  431. $entries = $xpath->query('/html/head/link[@rel="shortcut icon" or @rel="icon"]');
  432. if (count($entries) > 0) {
  433. foreach ($entries as $entry) {
  434. $favicon_url = rewrite_relative_url($url, $entry->getAttribute("href"));
  435. break;
  436. }
  437. }
  438. }
  439. if (!$favicon_url)
  440. $favicon_url = rewrite_relative_url($url, "/favicon.ico");
  441. return $favicon_url;
  442. } // function get_favicon_url
  443. function initialize_user_prefs($uid, $profile = false) {
  444. $uid = db_escape_string($uid);
  445. if (!$profile) {
  446. $profile = "NULL";
  447. $profile_qpart = "AND profile IS NULL";
  448. } else {
  449. $profile_qpart = "AND profile = '$profile'";
  450. }
  451. if (get_schema_version() < 63) $profile_qpart = "";
  452. db_query("BEGIN");
  453. $result = db_query("SELECT pref_name,def_value FROM ttrss_prefs");
  454. $u_result = db_query("SELECT pref_name
  455. FROM ttrss_user_prefs WHERE owner_uid = '$uid' $profile_qpart");
  456. $active_prefs = array();
  457. while ($line = db_fetch_assoc($u_result)) {
  458. array_push($active_prefs, $line["pref_name"]);
  459. }
  460. while ($line = db_fetch_assoc($result)) {
  461. if (array_search($line["pref_name"], $active_prefs) === FALSE) {
  462. // print "adding " . $line["pref_name"] . "<br>";
  463. $line["def_value"] = db_escape_string($line["def_value"]);
  464. $line["pref_name"] = db_escape_string($line["pref_name"]);
  465. if (get_schema_version() < 63) {
  466. db_query("INSERT INTO ttrss_user_prefs
  467. (owner_uid,pref_name,value) VALUES
  468. ('$uid', '".$line["pref_name"]."','".$line["def_value"]."')");
  469. } else {
  470. db_query("INSERT INTO ttrss_user_prefs
  471. (owner_uid,pref_name,value, profile) VALUES
  472. ('$uid', '".$line["pref_name"]."','".$line["def_value"]."', $profile)");
  473. }
  474. }
  475. }
  476. db_query("COMMIT");
  477. }
  478. function get_ssl_certificate_id() {
  479. if ($_SERVER["REDIRECT_SSL_CLIENT_M_SERIAL"]) {
  480. return sha1($_SERVER["REDIRECT_SSL_CLIENT_M_SERIAL"] .
  481. $_SERVER["REDIRECT_SSL_CLIENT_V_START"] .
  482. $_SERVER["REDIRECT_SSL_CLIENT_V_END"] .
  483. $_SERVER["REDIRECT_SSL_CLIENT_S_DN"]);
  484. }
  485. if ($_SERVER["SSL_CLIENT_M_SERIAL"]) {
  486. return sha1($_SERVER["SSL_CLIENT_M_SERIAL"] .
  487. $_SERVER["SSL_CLIENT_V_START"] .
  488. $_SERVER["SSL_CLIENT_V_END"] .
  489. $_SERVER["SSL_CLIENT_S_DN"]);
  490. }
  491. return "";
  492. }
  493. function authenticate_user($login, $password, $check_only = false) {
  494. if (!SINGLE_USER_MODE) {
  495. $user_id = false;
  496. foreach (PluginHost::getInstance()->get_hooks(PluginHost::HOOK_AUTH_USER) as $plugin) {
  497. $user_id = (int) $plugin->authenticate($login, $password);
  498. if ($user_id) {
  499. $_SESSION["auth_module"] = strtolower(get_class($plugin));
  500. break;
  501. }
  502. }
  503. if ($user_id && !$check_only) {
  504. @session_start();
  505. $_SESSION["uid"] = $user_id;
  506. $_SESSION["version"] = VERSION_STATIC;
  507. $result = db_query("SELECT login,access_level,pwd_hash FROM ttrss_users
  508. WHERE id = '$user_id'");
  509. $_SESSION["name"] = db_fetch_result($result, 0, "login");
  510. $_SESSION["access_level"] = db_fetch_result($result, 0, "access_level");
  511. $_SESSION["csrf_token"] = uniqid_short();
  512. db_query("UPDATE ttrss_users SET last_login = NOW() WHERE id = " .
  513. $_SESSION["uid"]);
  514. $_SESSION["ip_address"] = $_SERVER["REMOTE_ADDR"];
  515. $_SESSION["user_agent"] = sha1($_SERVER['HTTP_USER_AGENT']);
  516. $_SESSION["pwd_hash"] = db_fetch_result($result, 0, "pwd_hash");
  517. $_SESSION["last_version_check"] = time();
  518. initialize_user_prefs($_SESSION["uid"]);
  519. return true;
  520. }
  521. return false;
  522. } else {
  523. $_SESSION["uid"] = 1;
  524. $_SESSION["name"] = "admin";
  525. $_SESSION["access_level"] = 10;
  526. $_SESSION["hide_hello"] = true;
  527. $_SESSION["hide_logout"] = true;
  528. $_SESSION["auth_module"] = false;
  529. if (!$_SESSION["csrf_token"]) {
  530. $_SESSION["csrf_token"] = uniqid_short();
  531. }
  532. $_SESSION["ip_address"] = $_SERVER["REMOTE_ADDR"];
  533. initialize_user_prefs($_SESSION["uid"]);
  534. return true;
  535. }
  536. }
  537. function make_password($length = 8) {
  538. $password = "";
  539. $possible = "0123456789abcdfghjkmnpqrstvwxyzABCDFGHJKMNPQRSTVWXYZ";
  540. $i = 0;
  541. while ($i < $length) {
  542. $char = substr($possible, mt_rand(0, strlen($possible)-1), 1);
  543. if (!strstr($password, $char)) {
  544. $password .= $char;
  545. $i++;
  546. }
  547. }
  548. return $password;
  549. }
  550. // this is called after user is created to initialize default feeds, labels
  551. // or whatever else
  552. // user preferences are checked on every login, not here
  553. function initialize_user($uid) {
  554. db_query("insert into ttrss_feeds (owner_uid,title,feed_url)
  555. values ('$uid', 'Tiny Tiny RSS: Forum',
  556. 'http://tt-rss.org/forum/rss.php')");
  557. }
  558. function logout_user() {
  559. session_destroy();
  560. if (isset($_COOKIE[session_name()])) {
  561. setcookie(session_name(), '', time()-42000, '/');
  562. }
  563. }
  564. function validate_csrf($csrf_token) {
  565. return $csrf_token == $_SESSION['csrf_token'];
  566. }
  567. function load_user_plugins($owner_uid, $pluginhost = false) {
  568. if (!$pluginhost) $pluginhost = PluginHost::getInstance();
  569. if ($owner_uid && SCHEMA_VERSION >= 100) {
  570. $plugins = get_pref("_ENABLED_PLUGINS", $owner_uid);
  571. $pluginhost->load($plugins, PluginHost::KIND_USER, $owner_uid);
  572. if (get_schema_version() > 100) {
  573. $pluginhost->load_data();
  574. }
  575. }
  576. }
  577. function login_sequence() {
  578. if (SINGLE_USER_MODE) {
  579. @session_start();
  580. authenticate_user("admin", null);
  581. startup_gettext();
  582. load_user_plugins($_SESSION["uid"]);
  583. } else {
  584. if (!validate_session()) $_SESSION["uid"] = false;
  585. if (!$_SESSION["uid"]) {
  586. if (AUTH_AUTO_LOGIN && authenticate_user(null, null)) {
  587. $_SESSION["ref_schema_version"] = get_schema_version(true);
  588. } else {
  589. authenticate_user(null, null, true);
  590. }
  591. if (!$_SESSION["uid"]) {
  592. @session_destroy();
  593. setcookie(session_name(), '', time()-42000, '/');
  594. render_login_form();
  595. exit;
  596. }
  597. } else {
  598. /* bump login timestamp */
  599. db_query("UPDATE ttrss_users SET last_login = NOW() WHERE id = " .
  600. $_SESSION["uid"]);
  601. $_SESSION["last_login_update"] = time();
  602. }
  603. if ($_SESSION["uid"]) {
  604. startup_gettext();
  605. load_user_plugins($_SESSION["uid"]);
  606. /* cleanup ccache */
  607. db_query("DELETE FROM ttrss_counters_cache WHERE owner_uid = ".
  608. $_SESSION["uid"] . " AND
  609. (SELECT COUNT(id) FROM ttrss_feeds WHERE
  610. ttrss_feeds.id = feed_id) = 0");
  611. db_query("DELETE FROM ttrss_cat_counters_cache WHERE owner_uid = ".
  612. $_SESSION["uid"] . " AND
  613. (SELECT COUNT(id) FROM ttrss_feed_categories WHERE
  614. ttrss_feed_categories.id = feed_id) = 0");
  615. }
  616. }
  617. }
  618. function truncate_string($str, $max_len, $suffix = '&hellip;') {
  619. if (mb_strlen($str, "utf-8") > $max_len) {
  620. return mb_substr($str, 0, $max_len, "utf-8") . $suffix;
  621. } else {
  622. return $str;
  623. }
  624. }
  625. // is not utf8 clean
  626. function truncate_middle($str, $max_len, $suffix = '&hellip;') {
  627. if (strlen($str) > $max_len) {
  628. return substr_replace($str, $suffix, $max_len / 2, mb_strlen($str) - $max_len);
  629. } else {
  630. return $str;
  631. }
  632. }
  633. function convert_timestamp($timestamp, $source_tz, $dest_tz) {
  634. try {
  635. $source_tz = new DateTimeZone($source_tz);
  636. } catch (Exception $e) {
  637. $source_tz = new DateTimeZone('UTC');
  638. }
  639. try {
  640. $dest_tz = new DateTimeZone($dest_tz);
  641. } catch (Exception $e) {
  642. $dest_tz = new DateTimeZone('UTC');
  643. }
  644. $dt = new DateTime(date('Y-m-d H:i:s', $timestamp), $source_tz);
  645. return $dt->format('U') + $dest_tz->getOffset($dt);
  646. }
  647. function make_local_datetime($timestamp, $long, $owner_uid = false,
  648. $no_smart_dt = false, $eta_min = false) {
  649. if (!$owner_uid) $owner_uid = $_SESSION['uid'];
  650. if (!$timestamp) $timestamp = '1970-01-01 0:00';
  651. global $utc_tz;
  652. global $user_tz;
  653. if (!$utc_tz) $utc_tz = new DateTimeZone('UTC');
  654. $timestamp = substr($timestamp, 0, 19);
  655. # We store date in UTC internally
  656. $dt = new DateTime($timestamp, $utc_tz);
  657. $user_tz_string = get_pref('USER_TIMEZONE', $owner_uid);
  658. if ($user_tz_string != 'Automatic') {
  659. try {
  660. if (!$user_tz) $user_tz = new DateTimeZone($user_tz_string);
  661. } catch (Exception $e) {
  662. $user_tz = $utc_tz;
  663. }
  664. $tz_offset = $user_tz->getOffset($dt);
  665. } else {
  666. $tz_offset = (int) -$_SESSION["clientTzOffset"];
  667. }
  668. $user_timestamp = $dt->format('U') + $tz_offset;
  669. if (!$no_smart_dt) {
  670. return smart_date_time($user_timestamp,
  671. $tz_offset, $owner_uid, $eta_min);
  672. } else {
  673. if ($long)
  674. $format = get_pref('LONG_DATE_FORMAT', $owner_uid);
  675. else
  676. $format = get_pref('SHORT_DATE_FORMAT', $owner_uid);
  677. return date($format, $user_timestamp);
  678. }
  679. }
  680. function smart_date_time($timestamp, $tz_offset = 0, $owner_uid = false, $eta_min = false) {
  681. if (!$owner_uid) $owner_uid = $_SESSION['uid'];
  682. if ($eta_min && time() + $tz_offset - $timestamp < 3600) {
  683. return T_sprintf("%d min", date("i", time() + $tz_offset - $timestamp));
  684. } else if (date("Y.m.d", $timestamp) == date("Y.m.d", time() + $tz_offset)) {
  685. return date("G:i", $timestamp);
  686. } else if (date("Y", $timestamp) == date("Y", time() + $tz_offset)) {
  687. $format = get_pref('SHORT_DATE_FORMAT', $owner_uid);
  688. return date($format, $timestamp);
  689. } else {
  690. $format = get_pref('LONG_DATE_FORMAT', $owner_uid);
  691. return date($format, $timestamp);
  692. }
  693. }
  694. function sql_bool_to_bool($s) {
  695. if ($s == "t" || $s == "1" || strtolower($s) == "true") {
  696. return true;
  697. } else {
  698. return false;
  699. }
  700. }
  701. function bool_to_sql_bool($s) {
  702. if ($s) {
  703. return "true";
  704. } else {
  705. return "false";
  706. }
  707. }
  708. // Session caching removed due to causing wrong redirects to upgrade
  709. // script when get_schema_version() is called on an obsolete session
  710. // created on a previous schema version.
  711. function get_schema_version($nocache = false) {
  712. global $schema_version;
  713. if (!$schema_version && !$nocache) {
  714. $result = db_query("SELECT schema_version FROM ttrss_version");
  715. $version = db_fetch_result($result, 0, "schema_version");
  716. $schema_version = $version;
  717. return $version;
  718. } else {
  719. return $schema_version;
  720. }
  721. }
  722. function sanity_check() {
  723. require_once 'errors.php';
  724. global $ERRORS;
  725. $error_code = 0;
  726. $schema_version = get_schema_version(true);
  727. if ($schema_version != SCHEMA_VERSION) {
  728. $error_code = 5;
  729. }
  730. if (DB_TYPE == "mysql") {
  731. $result = db_query("SELECT true", false);
  732. if (db_num_rows($result) != 1) {
  733. $error_code = 10;
  734. }
  735. }
  736. if (db_escape_string("testTEST") != "testTEST") {
  737. $error_code = 12;
  738. }
  739. return array("code" => $error_code, "message" => $ERRORS[$error_code]);
  740. }
  741. function file_is_locked($filename) {
  742. if (file_exists(LOCK_DIRECTORY . "/$filename")) {
  743. if (function_exists('flock')) {
  744. $fp = @fopen(LOCK_DIRECTORY . "/$filename", "r");
  745. if ($fp) {
  746. if (flock($fp, LOCK_EX | LOCK_NB)) {
  747. flock($fp, LOCK_UN);
  748. fclose($fp);
  749. return false;
  750. }
  751. fclose($fp);
  752. return true;
  753. } else {
  754. return false;
  755. }
  756. }
  757. return true; // consider the file always locked and skip the test
  758. } else {
  759. return false;
  760. }
  761. }
  762. function make_lockfile($filename) {
  763. $fp = fopen(LOCK_DIRECTORY . "/$filename", "w");
  764. if ($fp && flock($fp, LOCK_EX | LOCK_NB)) {
  765. $stat_h = fstat($fp);
  766. $stat_f = stat(LOCK_DIRECTORY . "/$filename");
  767. if (strtoupper(substr(PHP_OS, 0, 3)) !== 'WIN') {
  768. if ($stat_h["ino"] != $stat_f["ino"] ||
  769. $stat_h["dev"] != $stat_f["dev"]) {
  770. return false;
  771. }
  772. }
  773. if (function_exists('posix_getpid')) {
  774. fwrite($fp, posix_getpid() . "\n");
  775. }
  776. return $fp;
  777. } else {
  778. return false;
  779. }
  780. }
  781. function make_stampfile($filename) {
  782. $fp = fopen(LOCK_DIRECTORY . "/$filename", "w");
  783. if (flock($fp, LOCK_EX | LOCK_NB)) {
  784. fwrite($fp, time() . "\n");
  785. flock($fp, LOCK_UN);
  786. fclose($fp);
  787. return true;
  788. } else {
  789. return false;
  790. }
  791. }
  792. function sql_random_function() {
  793. if (DB_TYPE == "mysql") {
  794. return "RAND()";
  795. } else {
  796. return "RANDOM()";
  797. }
  798. }
  799. function getAllCounters() {
  800. $data = getGlobalCounters();
  801. $data = array_merge($data, getVirtCounters());
  802. $data = array_merge($data, getLabelCounters());
  803. $data = array_merge($data, getFeedCounters());
  804. $data = array_merge($data, getCategoryCounters());
  805. return $data;
  806. }
  807. function getCategoryCounters() {
  808. $ret_arr = array();
  809. /* Labels category */
  810. $cv = array("id" => -2, "kind" => "cat",
  811. "counter" => Feeds::getCategoryUnread(-2));
  812. array_push($ret_arr, $cv);
  813. $result = db_query("SELECT id AS cat_id, value AS unread,
  814. (SELECT COUNT(id) FROM ttrss_feed_categories AS c2
  815. WHERE c2.parent_cat = ttrss_feed_categories.id) AS num_children
  816. FROM ttrss_feed_categories, ttrss_cat_counters_cache
  817. WHERE ttrss_cat_counters_cache.feed_id = id AND
  818. ttrss_cat_counters_cache.owner_uid = ttrss_feed_categories.owner_uid AND
  819. ttrss_feed_categories.owner_uid = " . $_SESSION["uid"]);
  820. while ($line = db_fetch_assoc($result)) {
  821. $line["cat_id"] = (int) $line["cat_id"];
  822. if ($line["num_children"] > 0) {
  823. $child_counter = Feeds::getCategoryChildrenUnread($line["cat_id"], $_SESSION["uid"]);
  824. } else {
  825. $child_counter = 0;
  826. }
  827. $cv = array("id" => $line["cat_id"], "kind" => "cat",
  828. "counter" => $line["unread"] + $child_counter);
  829. array_push($ret_arr, $cv);
  830. }
  831. /* Special case: NULL category doesn't actually exist in the DB */
  832. $cv = array("id" => 0, "kind" => "cat",
  833. "counter" => (int) CCache::find(0, $_SESSION["uid"], true));
  834. array_push($ret_arr, $cv);
  835. return $ret_arr;
  836. }
  837. function getFeedUnread($feed, $is_cat = false) {
  838. return Feeds::getFeedArticles($feed, $is_cat, true, $_SESSION["uid"]);
  839. }
  840. function getGlobalCounters($global_unread = -1) {
  841. $ret_arr = array();
  842. if ($global_unread == -1) {
  843. $global_unread = Feeds::getGlobalUnread();
  844. }
  845. $cv = array("id" => "global-unread",
  846. "counter" => (int) $global_unread);
  847. array_push($ret_arr, $cv);
  848. $result = db_query("SELECT COUNT(id) AS fn FROM
  849. ttrss_feeds WHERE owner_uid = " . $_SESSION["uid"]);
  850. $subscribed_feeds = db_fetch_result($result, 0, "fn");
  851. $cv = array("id" => "subscribed-feeds",
  852. "counter" => (int) $subscribed_feeds);
  853. array_push($ret_arr, $cv);
  854. return $ret_arr;
  855. }
  856. function getVirtCounters() {
  857. $ret_arr = array();
  858. for ($i = 0; $i >= -4; $i--) {
  859. $count = getFeedUnread($i);
  860. if ($i == 0 || $i == -1 || $i == -2)
  861. $auxctr = Feeds::getFeedArticles($i, false);
  862. else
  863. $auxctr = 0;
  864. $cv = array("id" => $i,
  865. "counter" => (int) $count,
  866. "auxcounter" => (int) $auxctr);
  867. // if (get_pref('EXTENDED_FEEDLIST'))
  868. // $cv["xmsg"] = getFeedArticles($i)." ".__("total");
  869. array_push($ret_arr, $cv);
  870. }
  871. $feeds = PluginHost::getInstance()->get_feeds(-1);
  872. if (is_array($feeds)) {
  873. foreach ($feeds as $feed) {
  874. $cv = array("id" => PluginHost::pfeed_to_feed_id($feed['id']),
  875. "counter" => $feed['sender']->get_unread($feed['id']));
  876. if (method_exists($feed['sender'], 'get_total'))
  877. $cv["auxcounter"] = $feed['sender']->get_total($feed['id']);
  878. array_push($ret_arr, $cv);
  879. }
  880. }
  881. return $ret_arr;
  882. }
  883. function getLabelCounters($descriptions = false) {
  884. $ret_arr = array();
  885. $owner_uid = $_SESSION["uid"];
  886. $result = db_query("SELECT id,caption,SUM(CASE WHEN u1.unread = true THEN 1 ELSE 0 END) AS unread, COUNT(u1.unread) AS total
  887. FROM ttrss_labels2 LEFT JOIN ttrss_user_labels2 ON
  888. (ttrss_labels2.id = label_id)
  889. LEFT JOIN ttrss_user_entries AS u1 ON u1.ref_id = article_id
  890. WHERE ttrss_labels2.owner_uid = $owner_uid AND u1.owner_uid = $owner_uid
  891. GROUP BY ttrss_labels2.id,
  892. ttrss_labels2.caption");
  893. while ($line = db_fetch_assoc($result)) {
  894. $id = Labels::label_to_feed_id($line["id"]);
  895. $cv = array("id" => $id,
  896. "counter" => (int) $line["unread"],
  897. "auxcounter" => (int) $line["total"]);
  898. if ($descriptions)
  899. $cv["description"] = $line["caption"];
  900. array_push($ret_arr, $cv);
  901. }
  902. return $ret_arr;
  903. }
  904. function getFeedCounters($active_feed = false) {
  905. $ret_arr = array();
  906. $query = "SELECT ttrss_feeds.id,
  907. ttrss_feeds.title,
  908. ".SUBSTRING_FOR_DATE."(ttrss_feeds.last_updated,1,19) AS last_updated,
  909. last_error, value AS count
  910. FROM ttrss_feeds, ttrss_counters_cache
  911. WHERE ttrss_feeds.owner_uid = ".$_SESSION["uid"]."
  912. AND ttrss_counters_cache.owner_uid = ttrss_feeds.owner_uid
  913. AND ttrss_counters_cache.feed_id = id";
  914. $result = db_query($query);
  915. while ($line = db_fetch_assoc($result)) {
  916. $id = $line["id"];
  917. $count = $line["count"];
  918. $last_error = htmlspecialchars($line["last_error"]);
  919. $last_updated = make_local_datetime($line['last_updated'], false);
  920. $has_img = feed_has_icon($id);
  921. if (date('Y') - date('Y', strtotime($line['last_updated'])) > 2)
  922. $last_updated = '';
  923. $cv = array("id" => $id,
  924. "updated" => $last_updated,
  925. "counter" => (int) $count,
  926. "has_img" => (int) $has_img);
  927. if ($last_error)
  928. $cv["error"] = $last_error;
  929. // if (get_pref('EXTENDED_FEEDLIST'))
  930. // $cv["xmsg"] = getFeedArticles($id)." ".__("total");
  931. if ($active_feed && $id == $active_feed)
  932. $cv["title"] = truncate_string($line["title"], 30);
  933. array_push($ret_arr, $cv);
  934. }
  935. return $ret_arr;
  936. }
  937. /*function get_pgsql_version() {
  938. $result = db_query("SELECT version() AS version");
  939. $version = explode(" ", db_fetch_result($result, 0, "version"));
  940. return $version[1];
  941. }*/
  942. function checkbox_to_sql_bool($val) {
  943. return ($val == "on") ? "true" : "false";
  944. }
  945. /*function getFeedCatTitle($id) {
  946. if ($id == -1) {
  947. return __("Special");
  948. } else if ($id < LABEL_BASE_INDEX) {
  949. return __("Labels");
  950. } else if ($id > 0) {
  951. $result = db_query("SELECT ttrss_feed_categories.title
  952. FROM ttrss_feeds, ttrss_feed_categories WHERE ttrss_feeds.id = '$id' AND
  953. cat_id = ttrss_feed_categories.id");
  954. if (db_num_rows($result) == 1) {
  955. return db_fetch_result($result, 0, "title");
  956. } else {
  957. return __("Uncategorized");
  958. }
  959. } else {
  960. return "getFeedCatTitle($id) failed";
  961. }
  962. }*/
  963. function uniqid_short() {
  964. return uniqid(base_convert(rand(), 10, 36));
  965. }
  966. function make_init_params() {
  967. $params = array();
  968. foreach (array("ON_CATCHUP_SHOW_NEXT_FEED", "HIDE_READ_FEEDS",
  969. "ENABLE_FEED_CATS", "FEEDS_SORT_BY_UNREAD", "CONFIRM_FEED_CATCHUP",
  970. "CDM_AUTO_CATCHUP", "FRESH_ARTICLE_MAX_AGE",
  971. "HIDE_READ_SHOWS_SPECIAL", "COMBINED_DISPLAY_MODE") as $param) {
  972. $params[strtolower($param)] = (int) get_pref($param);
  973. }
  974. $params["icons_url"] = ICONS_URL;
  975. $params["cookie_lifetime"] = SESSION_COOKIE_LIFETIME;
  976. $params["default_view_mode"] = get_pref("_DEFAULT_VIEW_MODE");
  977. $params["default_view_limit"] = (int) get_pref("_DEFAULT_VIEW_LIMIT");
  978. $params["default_view_order_by"] = get_pref("_DEFAULT_VIEW_ORDER_BY");
  979. $params["bw_limit"] = (int) $_SESSION["bw_limit"];
  980. $params["label_base_index"] = (int) LABEL_BASE_INDEX;
  981. $theme = get_pref( "USER_CSS_THEME", false, false);
  982. $params["theme"] = theme_valid("$theme") ? $theme : "";
  983. $params["plugins"] = implode(", ", PluginHost::getInstance()->get_plugin_names());
  984. $params["php_platform"] = PHP_OS;
  985. $params["php_version"] = PHP_VERSION;
  986. $params["sanity_checksum"] = sha1(file_get_contents("include/sanity_check.php"));
  987. $result = db_query("SELECT MAX(id) AS mid, COUNT(*) AS nf FROM
  988. ttrss_feeds WHERE owner_uid = " . $_SESSION["uid"]);
  989. $max_feed_id = db_fetch_result($result, 0, "mid");
  990. $num_feeds = db_fetch_result($result, 0, "nf");
  991. $params["max_feed_id"] = (int) $max_feed_id;
  992. $params["num_feeds"] = (int) $num_feeds;
  993. $params["hotkeys"] = get_hotkeys_map();
  994. $params["csrf_token"] = $_SESSION["csrf_token"];
  995. $params["widescreen"] = (int) $_COOKIE["ttrss_widescreen"];
  996. $params['simple_update'] = defined('SIMPLE_UPDATE_MODE') && SIMPLE_UPDATE_MODE;
  997. $params["icon_alert"] = base64_img("images/alert.png");
  998. $params["icon_information"] = base64_img("images/information.png");
  999. $params["icon_cross"] = base64_img("images/cross.png");
  1000. $params["icon_indicator_white"] = base64_img("images/indicator_white.gif");
  1001. return $params;
  1002. }
  1003. function get_hotkeys_info() {
  1004. $hotkeys = array(
  1005. __("Navigation") => array(
  1006. "next_feed" => __("Open next feed"),
  1007. "prev_feed" => __("Open previous feed"),
  1008. "next_article" => __("Open next article"),
  1009. "prev_article" => __("Open previous article"),
  1010. "next_article_noscroll" => __("Open next article (don't scroll long articles)"),
  1011. "prev_article_noscroll" => __("Open previous article (don't scroll long articles)"),
  1012. "next_article_noexpand" => __("Move to next article (don't expand or mark read)"),
  1013. "prev_article_noexpand" => __("Move to previous article (don't expand or mark read)"),
  1014. "search_dialog" => __("Show search dialog")),
  1015. __("Article") => array(
  1016. "toggle_mark" => __("Toggle starred"),
  1017. "toggle_publ" => __("Toggle published"),
  1018. "toggle_unread" => __("Toggle unread"),
  1019. "edit_tags" => __("Edit tags"),
  1020. "open_in_new_window" => __("Open in new window"),
  1021. "catchup_below" => __("Mark below as read"),
  1022. "catchup_above" => __("Mark above as read"),
  1023. "article_scroll_down" => __("Scroll down"),
  1024. "article_scroll_up" => __("Scroll up"),
  1025. "select_article_cursor" => __("Select article under cursor"),
  1026. "email_article" => __("Email article"),
  1027. "close_article" => __("Close/collapse article"),
  1028. "toggle_expand" => __("Toggle article expansion (combined mode)"),
  1029. "toggle_widescreen" => __("Toggle widescreen mode"),
  1030. "toggle_embed_original" => __("Toggle embed original")),
  1031. __("Article selection") => array(
  1032. "select_all" => __("Select all articles"),
  1033. "select_unread" => __("Select unread"),
  1034. "select_marked" => __("Select starred"),
  1035. "select_published" => __("Select published"),
  1036. "select_invert" => __("Invert selection"),
  1037. "select_none" => __("Deselect everything")),
  1038. __("Feed") => array(
  1039. "feed_refresh" => __("Refresh current feed"),
  1040. "feed_unhide_read" => __("Un/hide read feeds"),
  1041. "feed_subscribe" => __("Subscribe to feed"),
  1042. "feed_edit" => __("Edit feed"),
  1043. "feed_catchup" => __("Mark as read"),
  1044. "feed_reverse" => __("Reverse headlines"),
  1045. "feed_toggle_vgroup" => __("Toggle headline grouping"),
  1046. "feed_debug_update" => __("Debug feed update"),
  1047. "feed_debug_viewfeed" => __("Debug viewfeed()"),
  1048. "catchup_all" => __("Mark all feeds as read"),
  1049. "cat_toggle_collapse" => __("Un/collapse current category"),
  1050. "toggle_combined_mode" => __("Toggle combined mode"),
  1051. "toggle_cdm_expanded" => __("Toggle auto expand in combined mode")),
  1052. __("Go to") => array(
  1053. "goto_all" => __("All articles"),
  1054. "goto_fresh" => __("Fresh"),
  1055. "goto_marked" => __("Starred"),
  1056. "goto_published" => __("Published"),
  1057. "goto_tagcloud" => __("Tag cloud"),
  1058. "goto_prefs" => __("Preferences")),
  1059. __("Other") => array(
  1060. "create_label" => __("Create label"),
  1061. "create_filter" => __("Create filter"),
  1062. "collapse_sidebar" => __("Un/collapse sidebar"),
  1063. "help_dialog" => __("Show help dialog"))
  1064. );
  1065. foreach (PluginHost::getInstance()->get_hooks(PluginHost::HOOK_HOTKEY_INFO) as $plugin) {
  1066. $hotkeys = $plugin->hook_hotkey_info($hotkeys);
  1067. }
  1068. return $hotkeys;
  1069. }
  1070. function get_hotkeys_map() {
  1071. $hotkeys = array(
  1072. // "navigation" => array(
  1073. "k" => "next_feed",
  1074. "j" => "prev_feed",
  1075. "n" => "next_article",
  1076. "p" => "prev_article",
  1077. "(38)|up" => "prev_article",
  1078. "(40)|down" => "next_article",
  1079. // "^(38)|Ctrl-up" => "prev_article_noscroll",
  1080. // "^(40)|Ctrl-down" => "next_article_noscroll",
  1081. "(191)|/" => "search_dialog",
  1082. // "article" => array(
  1083. "s" => "toggle_mark",
  1084. "*s" => "toggle_publ",
  1085. "u" => "toggle_unread",
  1086. "*t" => "edit_tags",
  1087. "o" => "open_in_new_window",
  1088. "c p" => "catchup_below",
  1089. "c n" => "catchup_above",
  1090. "*n" => "article_scroll_down",
  1091. "*p" => "article_scroll_up",
  1092. "*(38)|Shift+up" => "article_scroll_up",
  1093. "*(40)|Shift+down" => "article_scroll_down",
  1094. "a *w" => "toggle_widescreen",
  1095. "a e" => "toggle_embed_original",
  1096. "e" => "email_article",
  1097. "a q" => "close_article",
  1098. // "article_selection" => array(
  1099. "a a" => "select_all",
  1100. "a u" => "select_unread",
  1101. "a *u" => "select_marked",
  1102. "a p" => "select_published",
  1103. "a i" => "select_invert",
  1104. "a n" => "select_none",
  1105. // "feed" => array(
  1106. "f r" => "feed_refresh",
  1107. "f a" => "feed_unhide_read",
  1108. "f s" => "feed_subscribe",
  1109. "f e" => "feed_edit",
  1110. "f q" => "feed_catchup",
  1111. "f x" => "feed_reverse",
  1112. "f g" => "feed_toggle_vgroup",
  1113. "f *d" => "feed_debug_update",
  1114. "f *g" => "feed_debug_viewfeed",
  1115. "f *c" => "toggle_combined_mode",
  1116. "f c" => "toggle_cdm_expanded",
  1117. "*q" => "catchup_all",
  1118. "x" => "cat_toggle_collapse",
  1119. // "goto" => array(
  1120. "g a" => "goto_all",
  1121. "g f" => "goto_fresh",
  1122. "g s" => "goto_marked",
  1123. "g p" => "goto_published",
  1124. "g t" => "goto_tagcloud",
  1125. "g *p" => "goto_prefs",
  1126. // "other" => array(
  1127. "(9)|Tab" => "select_article_cursor", // tab
  1128. "c l" => "create_label",
  1129. "c f" => "create_filter",
  1130. "c s" => "collapse_sidebar",
  1131. "^(191)|Ctrl+/" => "help_dialog",
  1132. );
  1133. if (get_pref('COMBINED_DISPLAY_MODE')) {
  1134. $hotkeys["^(38)|Ctrl-up"] = "prev_article_noscroll";
  1135. $hotkeys["^(40)|Ctrl-down"] = "next_article_noscroll";
  1136. }
  1137. foreach (PluginHost::getInstance()->get_hooks(PluginHost::HOOK_HOTKEY_MAP) as $plugin) {
  1138. $hotkeys = $plugin->hook_hotkey_map($hotkeys);
  1139. }
  1140. $prefixes = array();
  1141. foreach (array_keys($hotkeys) as $hotkey) {
  1142. $pair = explode(" ", $hotkey, 2);
  1143. if (count($pair) > 1 && !in_array($pair[0], $prefixes)) {
  1144. array_push($prefixes, $pair[0]);
  1145. }
  1146. }
  1147. return array($prefixes, $hotkeys);
  1148. }
  1149. function check_for_update() {
  1150. if (defined("GIT_VERSION_TIMESTAMP")) {
  1151. $content = @fetch_file_contents(array("url" => "http://tt-rss.org/version.json", "timeout" => 5));
  1152. if ($content) {
  1153. $content = json_decode($content, true);
  1154. if ($content && isset($content["changeset"])) {
  1155. if ((int)GIT_VERSION_TIMESTAMP < (int)$content["changeset"]["timestamp"] &&
  1156. GIT_VERSION_HEAD != $content["changeset"]["id"]) {
  1157. return $content["changeset"]["id"];
  1158. }
  1159. }
  1160. }
  1161. }
  1162. return "";
  1163. }
  1164. function make_runtime_info($disable_update_check = false) {
  1165. $data = array();
  1166. $result = db_query("SELECT MAX(id) AS mid, COUNT(*) AS nf FROM
  1167. ttrss_feeds WHERE owner_uid = " . $_SESSION["uid"]);
  1168. $max_feed_id = db_fetch_result($result, 0, "mid");
  1169. $num_feeds = db_fetch_result($result, 0, "nf");
  1170. $data["max_feed_id"] = (int) $max_feed_id;
  1171. $data["num_feeds"] = (int) $num_feeds;
  1172. $data['last_article_id'] = Article::getLastArticleId();
  1173. $data['cdm_expanded'] = get_pref('CDM_EXPANDED');
  1174. $data['dep_ts'] = calculate_dep_timestamp();
  1175. $data['reload_on_ts_change'] = !defined('_NO_RELOAD_ON_TS_CHANGE');
  1176. if (CHECK_FOR_UPDATES && !$disable_update_check && $_SESSION["last_version_check"] + 86400 + rand(-1000, 1000) < time()) {
  1177. $update_result = @check_for_update();
  1178. $data["update_result"] = $update_result;
  1179. $_SESSION["last_version_check"] = time();
  1180. }
  1181. if (file_exists(LOCK_DIRECTORY . "/update_daemon.lock")) {
  1182. $data['daemon_is_running'] = (int) file_is_locked("update_daemon.lock");
  1183. if (time() - $_SESSION["daemon_stamp_check"] > 30) {
  1184. $stamp = (int) @file_get_contents(LOCK_DIRECTORY . "/update_daemon.stamp");
  1185. if ($stamp) {
  1186. $stamp_delta = time() - $stamp;
  1187. if ($stamp_delta > 1800) {
  1188. $stamp_check = 0;
  1189. } else {
  1190. $stamp_check = 1;
  1191. $_SESSION["daemon_stamp_check"] = time();
  1192. }
  1193. $data['daemon_stamp_ok'] = $stamp_check;
  1194. $stamp_fmt = date("Y.m.d, G:i", $stamp);
  1195. $data['daemon_stamp'] = $stamp_fmt;
  1196. }
  1197. }
  1198. }
  1199. return $data;
  1200. }
  1201. function search_to_sql($search, $search_language) {
  1202. $keywords = str_getcsv(trim($search), " ");
  1203. $query_keywords = array();
  1204. $search_words = array();
  1205. $search_query_leftover = array();
  1206. if ($search_language)
  1207. $search_language = db_escape_string(mb_strtolower($search_language));
  1208. else
  1209. $search_language = "english";
  1210. foreach ($keywords as $k) {
  1211. if (strpos($k, "-") === 0) {
  1212. $k = substr($k, 1);
  1213. $not = "NOT";
  1214. } else {
  1215. $not = "";
  1216. }
  1217. $commandpair = explode(":", mb_strtolower($k), 2);
  1218. switch ($commandpair[0]) {
  1219. case "title":
  1220. if ($commandpair[1]) {
  1221. array_push($query_keywords, "($not (LOWER(ttrss_entries.title) LIKE '%".
  1222. db_escape_string(mb_strtolower($commandpair[1]))."%'))");
  1223. } else {
  1224. array_push($query_keywords, "(UPPER(ttrss_entries.title) $not LIKE UPPER('%$k%')
  1225. OR UPPER(ttrss_entries.content) $not LIKE UPPER('%$k%'))");
  1226. array_push($search_words, $k);
  1227. }
  1228. break;
  1229. case "author":
  1230. if ($commandpair[1]) {
  1231. array_push($query_keywords, "($not (LOWER(author) LIKE '%".
  1232. db_escape_string(mb_strtolower($commandpair[1]))."%'))");
  1233. } else {
  1234. array_push($query_keywords, "(UPPER(ttrss_entries.title) $not LIKE UPPER('%$k%')
  1235. OR UPPER(ttrss_entries.content) $not LIKE UPPER('%$k%'))");
  1236. array_push($search_words, $k);
  1237. }
  1238. break;
  1239. case "note":
  1240. if ($commandpair[1]) {
  1241. if ($commandpair[1] == "true")
  1242. array_push($query_keywords, "($not (note IS NOT NULL AND note != ''))");
  1243. else if ($commandpair[1] == "false")
  1244. array_push($query_keywords, "($not (note IS NULL OR note = ''))");
  1245. else
  1246. array_push($query_keywords, "($not (LOWER(note) LIKE '%".
  1247. db_escape_string(mb_strtolower($commandpair[1]))."%'))");
  1248. } else {
  1249. array_push($query_keywords, "(UPPER(ttrss_entries.title) $not LIKE UPPER('%$k%')
  1250. OR UPPER(ttrss_entries.content) $not LIKE UPPER('%$k%'))");
  1251. if (!$not) array_push($search_words, $k);
  1252. }
  1253. break;
  1254. case "star":
  1255. if ($commandpair[1]) {
  1256. if ($commandpair[1] == "true")
  1257. array_push($query_keywords, "($not (marked = true))");
  1258. else
  1259. array_push($query_keywords, "($not (marked = false))");
  1260. } else {
  1261. array_push($query_keywords, "(UPPER(ttrss_entries.title) $not LIKE UPPER('%$k%')
  1262. OR UPPER(ttrss_entries.content) $not LIKE UPPER('%$k%'))");
  1263. if (!$not) array_push($search_words, $k);
  1264. }
  1265. break;
  1266. case "pub":
  1267. if ($commandpair[1]) {
  1268. if ($commandpair[1] == "true")
  1269. array_push($query_keywords, "($not (published = true))");
  1270. else
  1271. array_push($query_keywords, "($not (published = false))");
  1272. } else {
  1273. array_push($query_keywords, "(UPPER(ttrss_entries.title) $not LIKE UPPER('%$k%')
  1274. OR UPPER(ttrss_entries.content) $not LIKE UPPER('%$k%'))");
  1275. if (!$not) array_push($search_words, $k);
  1276. }
  1277. break;
  1278. case "unread":
  1279. if ($commandpair[1]) {
  1280. if ($commandpair[1] == "true")
  1281. array_push($query_keywords, "($not (unread = true))");
  1282. else
  1283. array_push($query_keywords, "($not (unread = false))");
  1284. } else {
  1285. array_push($query_keywords, "(UPPER(ttrss_entries.title) $not LIKE UPPER('%$k%')
  1286. OR UPPER(ttrss_entries.content) $not LIKE UPPER('%$k%'))");
  1287. if (!$not) array_push($search_words, $k);
  1288. }
  1289. break;
  1290. default:
  1291. if (strpos($k, "@") === 0) {
  1292. $user_tz_string = get_pref('USER_TIMEZONE', $_SESSION['uid']);
  1293. $orig_ts = strtotime(substr($k, 1));
  1294. $k = date("Y-m-d", convert_timestamp($orig_ts, $user_tz_string, 'UTC'));
  1295. //$k = date("Y-m-d", strtotime(substr($k, 1)));
  1296. array_push($query_keywords, "(".SUBSTRING_FOR_DATE."(updated,1,LENGTH('$k')) $not = '$k')");
  1297. } else {
  1298. if (DB_TYPE == "pgsql") {
  1299. $k = mb_strtolower($k);
  1300. array_push($search_query_leftover, $not ? "!$k" : $k);
  1301. } else {
  1302. array_push($query_keywords, "(UPPER(ttrss_entries.title) $not LIKE UPPER('%$k%')
  1303. OR UPPER(ttrss_entries.content) $not LIKE UPPER('%$k%'))");
  1304. }
  1305. if (!$not) array_push($search_words, $k);
  1306. }
  1307. }
  1308. }
  1309. if (count($search_query_leftover) > 0) {
  1310. $search_query_leftover = db_escape_string(implode(" & ", $search_query_leftover));
  1311. if (DB_TYPE == "pgsql") {
  1312. array_push($query_keywords,
  1313. "(tsvector_combined @@ to_tsquery('$search_language', '$search_query_leftover'))");
  1314. }
  1315. }
  1316. $search_query_part = implode("AND", $query_keywords);
  1317. return array($search_query_part, $search_words);
  1318. }
  1319. function iframe_whitelisted($entry) {
  1320. $whitelist = array("youtube.com", "youtu.be", "vimeo.com", "player.vimeo.com");
  1321. @$src = parse_url($entry->getAttribute("src"), PHP_URL_HOST);
  1322. if ($src) {
  1323. foreach ($whitelist as $w) {
  1324. if ($src == $w || $src == "www.$w")
  1325. return true;
  1326. }
  1327. }
  1328. return false;
  1329. }
  1330. function sanitize($str, $force_remove_images = false, $owner = false, $site_url = false, $highlight_words = false, $article_id = false) {
  1331. if (!$owner) $owner = $_SESSION["uid"];
  1332. $res = trim($str); if (!$res) return '';
  1333. $charset_hack = '<head>
  1334. <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
  1335. </head>';
  1336. $res = trim($res); if (!$res) return '';
  1337. libxml_use_internal_errors(true);
  1338. $doc = new DOMDocument();
  1339. $doc->loadHTML($charset_hack . $res);
  1340. $xpath = new DOMXPath($doc);
  1341. $ttrss_uses_https = parse_url(get_self_url_prefix(), PHP_URL_SCHEME) === 'https';
  1342. $rewrite_base_url = $site_url ? $site_url : SELF_URL_PATH;
  1343. $entries = $xpath->query('(//a[@href]|//img[@src]|//video/source[@src]|//audio/source[@src])');
  1344. foreach ($entries as $entry) {
  1345. if ($entry->hasAttribute('href')) {
  1346. $entry->setAttribute('href',
  1347. rewrite_relative_url($rewrite_base_url, $entry->getAttribute('href')));
  1348. $entry->setAttribute('rel', 'noopener noreferrer');
  1349. }
  1350. if ($entry->hasAttribute('src')) {
  1351. $src = rewrite_relative_url($rewrite_base_url, $entry->getAttribute('src'));
  1352. $cached_filename = CACHE_DIR . '/images/' . sha1($src);
  1353. if (file_exists($cached_filename)) {
  1354. // this is strictly cosmetic
  1355. if ($entry->tagName == 'img') {
  1356. $suffix = ".png";
  1357. } else if ($entry->parentNode && $entry->parentNode->tagName == "video") {
  1358. $suffix = ".mp4";
  1359. } else if ($entry->parentNode && $entry->parentNode->tagName == "audio") {
  1360. $suffix = ".ogg";
  1361. } else {
  1362. $suffix = "";
  1363. }
  1364. $src = get_self_url_prefix() . '/public.php?op=cached_url&hash=' . sha1($src) . $suffix;
  1365. if ($entry->hasAttribute('srcset')) {
  1366. $entry->removeAttribute('srcset');
  1367. }
  1368. if ($entry->hasAttribute('sizes')) {
  1369. $entry->removeAttribute('sizes');
  1370. }
  1371. }
  1372. $entry->setAttribute('src', $src);
  1373. }
  1374. if ($entry->nodeName == 'img') {
  1375. if ($entry->hasAttribute('src')) {
  1376. $is_https_url = parse_url($entry->getAttribute('src'), PHP_URL_SCHEME) === 'https';
  1377. if ($ttrss_uses_https && !$is_https_url) {
  1378. if ($entry->hasAttribute('srcset')) {
  1379. $entry->removeAttribute('srcset');
  1380. }
  1381. if ($entry->hasAttribute('sizes')) {
  1382. $entry->removeAttribute('sizes');
  1383. }
  1384. }
  1385. }
  1386. if (($owner && get_pref("STRIP_IMAGES", $owner)) ||
  1387. $force_remove_images || $_SESSION["bw_limit"]) {
  1388. $p = $doc->createElement('p');
  1389. $a = $doc->createElement('a');
  1390. $a->setAttribute('href', $entry->getAttribute('src'));
  1391. $a->appendChild(new DOMText($entry->getAttribute('src')));
  1392. $a->setAttribute('target', '_blank');
  1393. $a->setAttribute('rel', 'noopener noreferrer');
  1394. $p->appendChild($a);
  1395. $entry->parentNode->replaceChild($p, $entry);
  1396. }
  1397. }
  1398. if (strtolower($entry->nodeName) == "a") {
  1399. $entry->setAttribute("target", "_blank");
  1400. $entry->setAttribute("rel", "noopener noreferrer");
  1401. }
  1402. }
  1403. $entries = $xpath->query('//iframe');
  1404. foreach ($entries as $entry) {
  1405. if (!iframe_whitelisted($entry)) {
  1406. $entry->setAttribute('sandbox', 'allow-scripts');
  1407. } else {
  1408. if ($_SERVER['HTTPS'] == "on") {
  1409. $entry->setAttribute("src",
  1410. str_replace("http://", "https://",
  1411. $entry->getAttribute("src")));
  1412. }
  1413. }
  1414. }
  1415. $allowed_elements = array('a', 'address', 'acronym', 'audio', 'article', 'aside',
  1416. 'b', 'bdi', 'bdo', 'big', 'blockquote', 'body', 'br',
  1417. 'caption', 'cite', 'center', 'code', 'col', 'colgroup',
  1418. 'data', 'dd', 'del', 'details', 'description', 'dfn', 'div', 'dl', 'font',
  1419. 'dt', 'em', 'footer', 'figure', 'figcaption',
  1420. 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'header', 'html', 'i',
  1421. 'img', 'ins', 'kbd', 'li', 'main', 'mark', 'nav', 'noscript',
  1422. 'ol', 'p', 'pre', 'q', 'ruby', 'rp', 'rt', 's', 'samp', 'section',
  1423. 'small', 'source', 'span', 'strike', 'strong', 'sub', 'summary',
  1424. 'sup', 'table', 'tbody', 'td', 'tfoot', 'th', 'thead', 'time',
  1425. 'tr', 'track', 'tt', 'u', 'ul', 'var', 'wbr', 'video', 'xml:namespace' );
  1426. if ($_SESSION['hasSandbox']) $allowed_elements[] = 'iframe';
  1427. $disallowed_attributes = array('id', 'style', 'class');
  1428. foreach (PluginHost::getInstance()->get_hooks(PluginHost::HOOK_SANITIZE) as $plugin) {
  1429. $retval = $plugin->hook_sanitize($doc, $site_url, $allowed_elements, $disallowed_attributes, $article_id);
  1430. if (is_array($retval)) {
  1431. $doc = $retval[0];
  1432. $allowed_elements = $retval[1];
  1433. $disallowed_attributes = $retval[2];
  1434. } else {
  1435. $doc = $retval;
  1436. }
  1437. }
  1438. $doc->removeChild($doc->firstChild); //remove doctype
  1439. $doc = strip_harmful_tags($doc, $allowed_elements, $disallowed_attributes);
  1440. if ($highlight_words) {
  1441. foreach ($highlight_words as $word) {
  1442. // http://stackoverflow.com/questions/4081372/highlight-keywords-in-a-paragraph
  1443. $elements = $xpath->query("//*/text()");
  1444. foreach ($elements as $child) {
  1445. $fragment = $doc->createDocumentFragment();
  1446. $text = $child->textContent;
  1447. while (($pos = mb_stripos($text, $word)) !== false) {
  1448. $fragment->appendChild(new DomText(mb_substr($text, 0, $pos)));
  1449. $word = mb_substr($text, $pos, mb_strlen($word));
  1450. $highlight = $doc->createElement('span');
  1451. $highlight->appendChild(new DomText($word));
  1452. $highlight->setAttribute('class', 'highlight');
  1453. $fragment->appendChild($highlight);
  1454. $text = mb_substr($text, $pos + mb_strlen($word));
  1455. }
  1456. if (!empty($text)) $fragment->appendChild(new DomText($text));
  1457. $child->parentNode->replaceChild($fragment, $child);
  1458. }
  1459. }
  1460. }
  1461. $res = $doc->saveHTML();
  1462. /* strip everything outside of <body>...</body> */
  1463. $res_frag = array();
  1464. if (preg_match('/<body>(.*)<\/body>/is', $res, $res_frag)) {
  1465. return $res_frag[1];
  1466. } else {
  1467. return $res;
  1468. }
  1469. }
  1470. function strip_harmful_tags($doc, $allowed_elements, $disallowed_attributes) {
  1471. $xpath = new DOMXPath($doc);
  1472. $entries = $xpath->query('//*');
  1473. foreach ($entries as $entry) {
  1474. if (!in_array($entry->nodeName, $allowed_elements)) {
  1475. $entry->parentNode->removeChild($entry);
  1476. }
  1477. if ($entry->hasAttributes()) {
  1478. $attrs_to_remove = array();
  1479. foreach ($entry->attributes as $attr) {
  1480. if (strpos($attr->nodeName, 'on') === 0) {
  1481. array_push($attrs_to_remove, $attr);
  1482. }
  1483. if ($attr->nodeName == 'href' && stripos($attr->value, 'javascript:') === 0) {
  1484. array_push($attrs_to_remove, $attr);
  1485. }
  1486. if (in_array($attr->nodeName, $disallowed_attributes)) {
  1487. array_push($attrs_to_remove, $attr);
  1488. }
  1489. }
  1490. foreach ($attrs_to_remove as $attr) {
  1491. $entry->removeAttributeNode($attr);
  1492. }
  1493. }
  1494. }
  1495. return $doc;
  1496. }
  1497. function trim_array($array) {
  1498. $tmp = $array;
  1499. array_walk($tmp, 'trim');
  1500. return $tmp;
  1501. }
  1502. function tag_is_valid($tag) {
  1503. if ($tag == '') return false;
  1504. if (is_numeric($tag)) return false;
  1505. if (mb_strlen($tag) > 250) return false;
  1506. if (!$tag) return false;
  1507. return true;
  1508. }
  1509. function render_login_form() {
  1510. header('Cache-Control: public');
  1511. require_once "login_form.php";
  1512. exit;
  1513. }
  1514. function T_sprintf() {
  1515. $args = func_get_args();
  1516. return vsprintf(__(array_shift($args)), $args);
  1517. }
  1518. function print_checkpoint($n, $s) {
  1519. $ts = microtime(true);
  1520. echo sprintf("<!-- CP[$n] %.4f seconds -->\n", $ts - $s);
  1521. return $ts;
  1522. }
  1523. function sanitize_tag($tag) {
  1524. $tag = trim($tag);
  1525. $tag = mb_strtolower($tag, 'utf-8');
  1526. $tag = preg_replace('/[,\'\"\+\>\<]/', "", $tag);
  1527. if (DB_TYPE == "mysql") {
  1528. $tag = preg_replace('/[\x{10000}-\x{10FFFF}]/u', "\xEF\xBF\xBD", $tag);
  1529. }
  1530. return $tag;
  1531. }
  1532. function get_self_url_prefix() {
  1533. if (strrpos(SELF_URL_PATH, "/") === strlen(SELF_URL_PATH)-1) {
  1534. return substr(SELF_URL_PATH, 0, strlen(SELF_URL_PATH)-1);
  1535. } else {
  1536. return SELF_URL_PATH;
  1537. }
  1538. }
  1539. /**
  1540. * Compute the Mozilla Firefox feed adding URL from server HOST and REQUEST_URI.
  1541. *
  1542. * @return string The Mozilla Firefox feed adding URL.
  1543. */
  1544. function add_feed_url() {
  1545. //$url_path = ($_SERVER['HTTPS'] != "on" ? 'http://' : 'https://') . $_SERVER["HTTP_HOST"] . parse_url($_SERVER["REQUEST_URI"], PHP_URL_PATH);
  1546. $url_path = get_self_url_prefix() .
  1547. "/public.php?op=subscribe&feed_url=%s";
  1548. return $url_path;
  1549. } // function add_feed_url
  1550. function encrypt_password($pass, $salt = '', $mode2 = false) {
  1551. if ($salt && $mode2) {
  1552. return "MODE2:" . hash('sha256', $salt . $pass);
  1553. } else if ($salt) {
  1554. return "SHA1X:" . sha1("$salt:$pass");
  1555. } else {
  1556. return "SHA1:" . sha1($pass);
  1557. }
  1558. } // function encrypt_password
  1559. function load_filters($feed_id, $owner_uid) {
  1560. $filters = array();
  1561. $cat_id = (int)Feeds::getFeedCategory($feed_id);
  1562. if ($cat_id == 0)
  1563. $null_cat_qpart = "cat_id IS NULL OR";
  1564. else
  1565. $null_cat_qpart = "";
  1566. $result = db_query("SELECT * FROM ttrss_filters2 WHERE
  1567. owner_uid = $owner_uid AND enabled = true ORDER BY order_id, title");
  1568. $check_cats = join(",", array_merge(
  1569. Feeds::getParentCategories($cat_id, $owner_uid),
  1570. array($cat_id)));
  1571. while ($line = db_fetch_assoc($result)) {
  1572. $filter_id = $line["id"];
  1573. $result2 = db_query("SELECT
  1574. r.reg_exp, r.inverse, r.feed_id, r.cat_id, r.cat_filter, t.name AS type_name
  1575. FROM ttrss_filters2_rules AS r,
  1576. ttrss_filter_types AS t
  1577. WHERE
  1578. ($null_cat_qpart (cat_id IS NULL AND cat_filter = false) OR cat_id IN ($check_cats)) AND
  1579. (feed_id IS NULL OR feed_id = '$feed_id') AND
  1580. filter_type = t.id AND filter_id = '$filter_id'");
  1581. $rules = array();
  1582. $actions = array();
  1583. while ($rule_line = db_fetch_assoc($result2)) {
  1584. # print_r($rule_line);
  1585. $rule = array();
  1586. $rule["reg_exp"] = $rule_line["reg_exp"];
  1587. $rule["type"] = $rule_line["type_name"];
  1588. $rule["inverse"] = sql_bool_to_bool($rule_line["inverse"]);
  1589. array_push($rules, $rule);
  1590. }
  1591. $result2 = db_query("SELECT a.action_param,t.name AS type_name
  1592. FROM ttrss_filters2_actions AS a,
  1593. ttrss_filter_actions AS t
  1594. WHERE
  1595. action_id = t.id AND filter_id = '$filter_id'");
  1596. while ($action_line = db_fetch_assoc($result2)) {
  1597. # print_r($action_line);
  1598. $action = array();
  1599. $action["type"] = $action_line["type_name"];
  1600. $action["param"] = $action_line["action_param"];
  1601. array_push($actions, $action);
  1602. }
  1603. $filter = array();
  1604. $filter["match_any_rule"] = sql_bool_to_bool($line["match_any_rule"]);
  1605. $filter["inverse"] = sql_bool_to_bool($line["inverse"]);
  1606. $filter["rules"] = $rules;
  1607. $filter["actions"] = $actions;
  1608. if (count($rules) > 0 && count($actions) > 0) {
  1609. array_push($filters, $filter);
  1610. }
  1611. }
  1612. return $filters;
  1613. }
  1614. function get_score_pic($score) {
  1615. if ($score > 100) {
  1616. return "score_high.png";
  1617. } else if ($score > 0) {
  1618. return "score_half_high.png";
  1619. } else if ($score < -100) {
  1620. return "score_low.png";
  1621. } else if ($score < 0) {
  1622. return "score_half_low.png";
  1623. } else {
  1624. return "score_neutral.png";
  1625. }
  1626. }
  1627. function feed_has_icon($id) {
  1628. return is_file(ICONS_DIR . "/$id.ico") && filesize(ICONS_DIR . "/$id.ico") > 0;
  1629. }
  1630. function init_plugins() {
  1631. PluginHost::getInstance()->load(PLUGINS, PluginHost::KIND_ALL);
  1632. return true;
  1633. }
  1634. function add_feed_category($feed_cat, $parent_cat_id = false) {
  1635. if (!$feed_cat) return false;
  1636. db_query("BEGIN");
  1637. if ($parent_cat_id) {
  1638. $parent_qpart = "parent_cat = '$parent_cat_id'";
  1639. $parent_insert = "'$parent_cat_id'";
  1640. } else {
  1641. $parent_qpart = "parent_cat IS NULL";
  1642. $parent_insert = "NULL";
  1643. }
  1644. $feed_cat = mb_substr($feed_cat, 0, 250);
  1645. $result = db_query(
  1646. "SELECT id FROM ttrss_feed_categories
  1647. WHERE $parent_qpart AND title = '$feed_cat' AND owner_uid = ".$_SESSION["uid"]);
  1648. if (db_num_rows($result) == 0) {
  1649. $result = db_query(
  1650. "INSERT INTO ttrss_feed_categories (owner_uid,title,parent_cat)
  1651. VALUES ('".$_SESSION["uid"]."', '$feed_cat', $parent_insert)");
  1652. db_query("COMMIT");
  1653. return true;
  1654. }
  1655. return false;
  1656. }
  1657. /**
  1658. * Fixes incomplete URLs by prepending "http://".
  1659. * Also replaces feed:// with http://, and
  1660. * prepends a trailing slash if the url is a domain name only.
  1661. *
  1662. * @param string $url Possibly incomplete URL
  1663. *
  1664. * @return string Fixed URL.
  1665. */
  1666. function fix_url($url) {
  1667. // support schema-less urls
  1668. if (strpos($url, '//') === 0) {
  1669. $url = 'https:' . $url;
  1670. }
  1671. if (strpos($url, '://') === false) {
  1672. $url = 'http://' . $url;
  1673. } else if (substr($url, 0, 5) == 'feed:') {
  1674. $url = 'http:' . substr($url, 5);
  1675. }
  1676. //prepend slash if the URL has no slash in it
  1677. // "http://www.example" -> "http://www.example/"
  1678. if (strpos($url, '/', strpos($url, ':') + 3) === false) {
  1679. $url .= '/';
  1680. }
  1681. //convert IDNA hostname to punycode if possible
  1682. if (function_exists("idn_to_ascii")) {
  1683. $parts = parse_url($url);
  1684. if (mb_detect_encoding($parts['host']) != 'ASCII')
  1685. {
  1686. $parts['host'] = idn_to_ascii($parts['host']);
  1687. $url = build_url($parts);
  1688. }
  1689. }
  1690. if ($url != "http:///")
  1691. return $url;
  1692. else
  1693. return '';
  1694. }
  1695. function validate_feed_url($url) {
  1696. $parts = parse_url($url);
  1697. return ($parts['scheme'] == 'http' || $parts['scheme'] == 'feed' || $parts['scheme'] == 'https');
  1698. }
  1699. /* function save_email_address($email) {
  1700. // FIXME: implement persistent storage of emails
  1701. if (!$_SESSION['stored_emails'])
  1702. $_SESSION['stored_emails'] = array();
  1703. if (!in_array($email, $_SESSION['stored_emails']))
  1704. array_push($_SESSION['stored_emails'], $email);
  1705. } */
  1706. function get_feed_access_key($feed_id, $is_cat, $owner_uid = false) {
  1707. if (!$owner_uid) $owner_uid = $_SESSION["uid"];
  1708. $sql_is_cat = bool_to_sql_bool($is_cat);
  1709. $result = db_query("SELECT access_key FROM ttrss_access_keys
  1710. WHERE feed_id = '$feed_id' AND is_cat = $sql_is_cat
  1711. AND owner_uid = " . $owner_uid);
  1712. if (db_num_rows($result) == 1) {
  1713. return db_fetch_result($result, 0, "access_key");
  1714. } else {
  1715. $key = db_escape_string(uniqid_short());
  1716. $result = db_query("INSERT INTO ttrss_access_keys
  1717. (access_key, feed_id, is_cat, owner_uid)
  1718. VALUES ('$key', '$feed_id', $sql_is_cat, '$owner_uid')");
  1719. return $key;
  1720. }
  1721. return false;
  1722. }
  1723. function get_feeds_from_html($url, $content)
  1724. {
  1725. $url = fix_url($url);
  1726. $baseUrl = substr($url, 0, strrpos($url, '/') + 1);
  1727. libxml_use_internal_errors(true);
  1728. $doc = new DOMDocument();
  1729. $doc->loadHTML($content);
  1730. $xpath = new DOMXPath($doc);
  1731. $entries = $xpath->query('/html/head/link[@rel="alternate" and '.
  1732. '(contains(@type,"rss") or contains(@type,"atom"))]|/html/head/link[@rel="feed"]');
  1733. $feedUrls = array();
  1734. foreach ($entries as $entry) {
  1735. if ($entry->hasAttribute('href')) {
  1736. $title = $entry->getAttribute('title');
  1737. if ($title == '') {
  1738. $title = $entry->getAttribute('type');
  1739. }
  1740. $feedUrl = rewrite_relative_url(
  1741. $baseUrl, $entry->getAttribute('href')
  1742. );
  1743. $feedUrls[$feedUrl] = $title;
  1744. }
  1745. }
  1746. return $feedUrls;
  1747. }
  1748. function is_html($content) {
  1749. return preg_match("/<html|DOCTYPE html/i", substr($content, 0, 100)) !== 0;
  1750. }
  1751. function url_is_html($url, $login = false, $pass = false) {
  1752. return is_html(fetch_file_contents($url, false, $login, $pass));
  1753. }
  1754. function build_url($parts) {
  1755. return $parts['scheme'] . "://" . $parts['host'] . $parts['path'];
  1756. }
  1757. function cleanup_url_path($path) {
  1758. $path = str_replace("/./", "/", $path);
  1759. $path = str_replace("//", "/", $path);
  1760. return $path;
  1761. }
  1762. /**
  1763. * Converts a (possibly) relative URL to a absolute one.
  1764. *
  1765. * @param string $url Base URL (i.e. from where the document is)
  1766. * @param string $rel_url Possibly relative URL in the document
  1767. *
  1768. * @return string Absolute URL
  1769. */
  1770. function rewrite_relative_url($url, $rel_url) {
  1771. if (strpos($rel_url, "://") !== false) {
  1772. return $rel_url;
  1773. } else if (strpos($rel_url, "//") === 0) {
  1774. # protocol-relative URL (rare but they exist)
  1775. return $rel_url;
  1776. } else if (preg_match("/^[a-z]+:/i", $rel_url)) {
  1777. # magnet:, feed:, etc
  1778. return $rel_url;
  1779. } else if (strpos($rel_url, "/") === 0) {
  1780. $parts = parse_url($url);
  1781. $parts['path'] = $rel_url;
  1782. $parts['path'] = cleanup_url_path($parts['path']);
  1783. return build_url($parts);
  1784. } else {
  1785. $parts = parse_url($url);
  1786. if (!isset($parts['path'])) {
  1787. $parts['path'] = '/';
  1788. }
  1789. $dir = $parts['path'];
  1790. if (substr($dir, -1) !== '/') {
  1791. $dir = dirname($parts['path']);
  1792. $dir !== '/' && $dir .= '/';
  1793. }
  1794. $parts['path'] = $dir . $rel_url;
  1795. $parts['path'] = cleanup_url_path($parts['path']);
  1796. return build_url($parts);
  1797. }
  1798. }
  1799. function cleanup_tags($days = 14, $limit = 1000) {
  1800. if (DB_TYPE == "pgsql") {
  1801. $interval_query = "date_updated < NOW() - INTERVAL '$days days'";
  1802. } else if (DB_TYPE == "mysql") {
  1803. $interval_query = "date_updated < DATE_SUB(NOW(), INTERVAL $days DAY)";
  1804. }
  1805. $tags_deleted = 0;
  1806. while ($limit > 0) {
  1807. $limit_part = 500;
  1808. $query = "SELECT ttrss_tags.id AS id
  1809. FROM ttrss_tags, ttrss_user_entries, ttrss_entries
  1810. WHERE post_int_id = int_id AND $interval_query AND
  1811. ref_id = ttrss_entries.id AND tag_cache != '' LIMIT $limit_part";
  1812. $result = db_query($query);
  1813. $ids = array();
  1814. while ($line = db_fetch_assoc($result)) {
  1815. array_push($ids, $line['id']);
  1816. }
  1817. if (count($ids) > 0) {
  1818. $ids = join(",", $ids);
  1819. $tmp_result = db_query("DELETE FROM ttrss_tags WHERE id IN ($ids)");
  1820. $tags_deleted += db_affected_rows($tmp_result);
  1821. } else {
  1822. break;
  1823. }
  1824. $limit -= $limit_part;
  1825. }
  1826. return $tags_deleted;
  1827. }
  1828. function print_user_stylesheet() {
  1829. $value = get_pref('USER_STYLESHEET');
  1830. if ($value) {
  1831. print "<style type=\"text/css\">";
  1832. print str_replace("<br/>", "\n", $value);
  1833. print "</style>";
  1834. }
  1835. }
  1836. function filter_to_sql($filter, $owner_uid) {
  1837. $query = array();
  1838. if (DB_TYPE == "pgsql")
  1839. $reg_qpart = "~";
  1840. else
  1841. $reg_qpart = "REGEXP";
  1842. foreach ($filter["rules"] AS $rule) {
  1843. $rule['reg_exp'] = str_replace('/', '\/', $rule["reg_exp"]);
  1844. $regexp_valid = preg_match('/' . $rule['reg_exp'] . '/',
  1845. $rule['reg_exp']) !== FALSE;
  1846. if ($regexp_valid) {
  1847. $rule['reg_exp'] = db_escape_string($rule['reg_exp']);
  1848. switch ($rule["type"]) {
  1849. case "title":
  1850. $qpart = "LOWER(ttrss_entries.title) $reg_qpart LOWER('".
  1851. $rule['reg_exp'] . "')";
  1852. break;
  1853. case "content":
  1854. $qpart = "LOWER(ttrss_entries.content) $reg_qpart LOWER('".
  1855. $rule['reg_exp'] . "')";
  1856. break;
  1857. case "both":
  1858. $qpart = "LOWER(ttrss_entries.title) $reg_qpart LOWER('".
  1859. $rule['reg_exp'] . "') OR LOWER(" .
  1860. "ttrss_entries.content) $reg_qpart LOWER('" . $rule['reg_exp'] . "')";
  1861. break;
  1862. case "tag":
  1863. $qpart = "LOWER(ttrss_user_entries.tag_cache) $reg_qpart LOWER('".
  1864. $rule['reg_exp'] . "')";
  1865. break;
  1866. case "link":
  1867. $qpart = "LOWER(ttrss_entries.link) $reg_qpart LOWER('".
  1868. $rule['reg_exp'] . "')";
  1869. break;
  1870. case "author":
  1871. $qpart = "LOWER(ttrss_entries.author) $reg_qpart LOWER('".
  1872. $rule['reg_exp'] . "')";
  1873. break;
  1874. }
  1875. if (isset($rule['inverse'])) $qpart = "NOT ($qpart)";
  1876. if (isset($rule["feed_id"]) && $rule["feed_id"] > 0) {
  1877. $qpart .= " AND feed_id = " . db_escape_string($rule["feed_id"]);
  1878. }
  1879. if (isset($rule["cat_id"])) {
  1880. if ($rule["cat_id"] > 0) {
  1881. $children = Feeds::getChildCategories($rule["cat_id"], $owner_uid);
  1882. array_push($children, $rule["cat_id"]);
  1883. $children = join(",", $children);
  1884. $cat_qpart = "cat_id IN ($children)";
  1885. } else {
  1886. $cat_qpart = "cat_id IS NULL";
  1887. }
  1888. $qpart .= " AND $cat_qpart";
  1889. }
  1890. $qpart .= " AND feed_id IS NOT NULL";
  1891. array_push($query, "($qpart)");
  1892. }
  1893. }
  1894. if (count($query) > 0) {
  1895. $fullquery = "(" . join($filter["match_any_rule"] ? "OR" : "AND", $query) . ")";
  1896. } else {
  1897. $fullquery = "(false)";
  1898. }
  1899. if ($filter['inverse']) $fullquery = "(NOT $fullquery)";
  1900. return $fullquery;
  1901. }
  1902. if (!function_exists('gzdecode')) {
  1903. function gzdecode($string) { // no support for 2nd argument
  1904. return file_get_contents('compress.zlib://data:who/cares;base64,'.
  1905. base64_encode($string));
  1906. }
  1907. }
  1908. function get_random_bytes($length) {
  1909. if (function_exists('openssl_random_pseudo_bytes')) {
  1910. return openssl_random_pseudo_bytes($length);
  1911. } else {
  1912. $output = "";
  1913. for ($i = 0; $i < $length; $i++)
  1914. $output .= chr(mt_rand(0, 255));
  1915. return $output;
  1916. }
  1917. }
  1918. function read_stdin() {
  1919. $fp = fopen("php://stdin", "r");
  1920. if ($fp) {
  1921. $line = trim(fgets($fp));
  1922. fclose($fp);
  1923. return $line;
  1924. }
  1925. return null;
  1926. }
  1927. function implements_interface($class, $interface) {
  1928. return in_array($interface, class_implements($class));
  1929. }
  1930. function get_minified_js($files) {
  1931. require_once 'lib/jshrink/Minifier.php';
  1932. $rv = '';
  1933. foreach ($files as $js) {
  1934. if (!isset($_GET['debug'])) {
  1935. $cached_file = CACHE_DIR . "/js/".basename($js).".js";
  1936. if (file_exists($cached_file) && is_readable($cached_file) && filemtime($cached_file) >= filemtime("js/$js.js")) {
  1937. list($header, $contents) = explode("\n", file_get_contents($cached_file), 2);
  1938. if ($header && $contents) {
  1939. list($htag, $hversion) = explode(":", $header);
  1940. if ($htag == "tt-rss" && $hversion == VERSION) {
  1941. $rv .= $contents;
  1942. continue;
  1943. }
  1944. }
  1945. }
  1946. $minified = JShrink\Minifier::minify(file_get_contents("js/$js.js"));
  1947. file_put_contents($cached_file, "tt-rss:" . VERSION . "\n" . $minified);
  1948. $rv .= $minified;
  1949. } else {
  1950. $rv .= file_get_contents("js/$js.js"); // no cache in debug mode
  1951. }
  1952. }
  1953. return $rv;
  1954. }
  1955. function calculate_dep_timestamp() {
  1956. $files = array_merge(glob("js/*.js"), glob("css/*.css"));
  1957. $max_ts = -1;
  1958. foreach ($files as $file) {
  1959. if (filemtime($file) > $max_ts) $max_ts = filemtime($file);
  1960. }
  1961. return $max_ts;
  1962. }
  1963. function T_js_decl($s1, $s2) {
  1964. if ($s1 && $s2) {
  1965. $s1 = preg_replace("/\n/", "", $s1);
  1966. $s2 = preg_replace("/\n/", "", $s2);
  1967. $s1 = preg_replace("/\"/", "\\\"", $s1);
  1968. $s2 = preg_replace("/\"/", "\\\"", $s2);
  1969. return "T_messages[\"$s1\"] = \"$s2\";\n";
  1970. }
  1971. }
  1972. function init_js_translations() {
  1973. print 'var T_messages = new Object();
  1974. function __(msg) {
  1975. if (T_messages[msg]) {
  1976. return T_messages[msg];
  1977. } else {
  1978. return msg;
  1979. }
  1980. }
  1981. function ngettext(msg1, msg2, n) {
  1982. return __((parseInt(n) > 1) ? msg2 : msg1);
  1983. }';
  1984. $l10n = _get_reader();
  1985. for ($i = 0; $i < $l10n->total; $i++) {
  1986. $orig = $l10n->get_original_string($i);
  1987. if(strpos($orig, "\000") !== FALSE) { // Plural forms
  1988. $key = explode(chr(0), $orig);
  1989. print T_js_decl($key[0], _ngettext($key[0], $key[1], 1)); // Singular
  1990. print T_js_decl($key[1], _ngettext($key[0], $key[1], 2)); // Plural
  1991. } else {
  1992. $translation = __($orig);
  1993. print T_js_decl($orig, $translation);
  1994. }
  1995. }
  1996. }
  1997. function get_theme_path($theme) {
  1998. $check = "themes/$theme";
  1999. if (file_exists($check)) return $check;
  2000. $check = "themes.local/$theme";
  2001. if (file_exists($check)) return $check;
  2002. }
  2003. function theme_valid($theme) {
  2004. $bundled_themes = [ "default.php", "night.css", "compact.css" ];
  2005. if (in_array($theme, $bundled_themes)) return true;
  2006. $file = "themes/" . basename($theme);
  2007. if (!file_exists($file)) $file = "themes.local/" . basename($theme);
  2008. if (file_exists($file) && is_readable($file)) {
  2009. $fh = fopen($file, "r");
  2010. if ($fh) {
  2011. $header = fgets($fh);
  2012. fclose($fh);
  2013. return strpos($header, "supports-version:" . VERSION_STATIC) !== FALSE;
  2014. }
  2015. }
  2016. return false;
  2017. }
  2018. /**
  2019. * @SuppressWarnings(unused)
  2020. */
  2021. function error_json($code) {
  2022. require_once "errors.php";
  2023. @$message = $ERRORS[$code];
  2024. return json_encode(array("error" =>
  2025. array("code" => $code, "message" => $message)));
  2026. }
  2027. /*function abs_to_rel_path($dir) {
  2028. $tmp = str_replace(dirname(__DIR__), "", $dir);
  2029. if (strlen($tmp) > 0 && substr($tmp, 0, 1) == "/") $tmp = substr($tmp, 1);
  2030. return $tmp;
  2031. }*/
  2032. function get_upload_error_message($code) {
  2033. $errors = array(
  2034. 0 => __('There is no error, the file uploaded with success'),
  2035. 1 => __('The uploaded file exceeds the upload_max_filesize directive in php.ini'),
  2036. 2 => __('The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form'),
  2037. 3 => __('The uploaded file was only partially uploaded'),
  2038. 4 => __('No file was uploaded'),
  2039. 6 => __('Missing a temporary folder'),
  2040. 7 => __('Failed to write file to disk.'),
  2041. 8 => __('A PHP extension stopped the file upload.'),
  2042. );
  2043. return $errors[$code];
  2044. }
  2045. function base64_img($filename) {
  2046. if (file_exists($filename)) {
  2047. $ext = pathinfo($filename, PATHINFO_EXTENSION);
  2048. return "data:image/$ext;base64," . base64_encode(file_get_contents($filename));
  2049. } else {
  2050. return "";
  2051. }
  2052. }