functions.php 71 KB

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