functions.php 69 KB

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