functions.php 67 KB

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