functions.php 70 KB

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