functions.php 65 KB

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