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