functions.php 70 KB

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