functions.php 69 KB

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