functions.php 66 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463
  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. require_once 'lib/pubsubhubbub/Publisher.php';
  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:$pass@" . $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 : SELF_URL_PATH;
  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. function get_self_url_prefix() {
  1403. if (strrpos(SELF_URL_PATH, "/") === strlen(SELF_URL_PATH)-1) {
  1404. return substr(SELF_URL_PATH, 0, strlen(SELF_URL_PATH)-1);
  1405. } else {
  1406. return SELF_URL_PATH;
  1407. }
  1408. }
  1409. /**
  1410. * Compute the Mozilla Firefox feed adding URL from server HOST and REQUEST_URI.
  1411. *
  1412. * @return string The Mozilla Firefox feed adding URL.
  1413. */
  1414. function add_feed_url() {
  1415. //$url_path = ($_SERVER['HTTPS'] != "on" ? 'http://' : 'https://') . $_SERVER["HTTP_HOST"] . parse_url($_SERVER["REQUEST_URI"], PHP_URL_PATH);
  1416. $url_path = get_self_url_prefix() .
  1417. "/public.php?op=subscribe&feed_url=%s";
  1418. return $url_path;
  1419. } // function add_feed_url
  1420. function encrypt_password($pass, $salt = '', $mode2 = false) {
  1421. if ($salt && $mode2) {
  1422. return "MODE2:" . hash('sha256', $salt . $pass);
  1423. } else if ($salt) {
  1424. return "SHA1X:" . sha1("$salt:$pass");
  1425. } else {
  1426. return "SHA1:" . sha1($pass);
  1427. }
  1428. } // function encrypt_password
  1429. function load_filters($feed_id, $owner_uid) {
  1430. $filters = array();
  1431. $cat_id = (int)Feeds::getFeedCategory($feed_id);
  1432. if ($cat_id == 0)
  1433. $null_cat_qpart = "cat_id IS NULL OR";
  1434. else
  1435. $null_cat_qpart = "";
  1436. $result = db_query("SELECT * FROM ttrss_filters2 WHERE
  1437. owner_uid = $owner_uid AND enabled = true ORDER BY order_id, title");
  1438. $check_cats = join(",", array_merge(
  1439. Feeds::getParentCategories($cat_id, $owner_uid),
  1440. array($cat_id)));
  1441. while ($line = db_fetch_assoc($result)) {
  1442. $filter_id = $line["id"];
  1443. $result2 = db_query("SELECT
  1444. r.reg_exp, r.inverse, r.feed_id, r.cat_id, r.cat_filter, t.name AS type_name
  1445. FROM ttrss_filters2_rules AS r,
  1446. ttrss_filter_types AS t
  1447. WHERE
  1448. ($null_cat_qpart (cat_id IS NULL AND cat_filter = false) OR cat_id IN ($check_cats)) AND
  1449. (feed_id IS NULL OR feed_id = '$feed_id') AND
  1450. filter_type = t.id AND filter_id = '$filter_id'");
  1451. $rules = array();
  1452. $actions = array();
  1453. while ($rule_line = db_fetch_assoc($result2)) {
  1454. # print_r($rule_line);
  1455. $rule = array();
  1456. $rule["reg_exp"] = $rule_line["reg_exp"];
  1457. $rule["type"] = $rule_line["type_name"];
  1458. $rule["inverse"] = sql_bool_to_bool($rule_line["inverse"]);
  1459. array_push($rules, $rule);
  1460. }
  1461. $result2 = db_query("SELECT a.action_param,t.name AS type_name
  1462. FROM ttrss_filters2_actions AS a,
  1463. ttrss_filter_actions AS t
  1464. WHERE
  1465. action_id = t.id AND filter_id = '$filter_id'");
  1466. while ($action_line = db_fetch_assoc($result2)) {
  1467. # print_r($action_line);
  1468. $action = array();
  1469. $action["type"] = $action_line["type_name"];
  1470. $action["param"] = $action_line["action_param"];
  1471. array_push($actions, $action);
  1472. }
  1473. $filter = array();
  1474. $filter["match_any_rule"] = sql_bool_to_bool($line["match_any_rule"]);
  1475. $filter["inverse"] = sql_bool_to_bool($line["inverse"]);
  1476. $filter["rules"] = $rules;
  1477. $filter["actions"] = $actions;
  1478. if (count($rules) > 0 && count($actions) > 0) {
  1479. array_push($filters, $filter);
  1480. }
  1481. }
  1482. return $filters;
  1483. }
  1484. function get_score_pic($score) {
  1485. if ($score > 100) {
  1486. return "score_high.png";
  1487. } else if ($score > 0) {
  1488. return "score_half_high.png";
  1489. } else if ($score < -100) {
  1490. return "score_low.png";
  1491. } else if ($score < 0) {
  1492. return "score_half_low.png";
  1493. } else {
  1494. return "score_neutral.png";
  1495. }
  1496. }
  1497. function feed_has_icon($id) {
  1498. return is_file(ICONS_DIR . "/$id.ico") && filesize(ICONS_DIR . "/$id.ico") > 0;
  1499. }
  1500. function init_plugins() {
  1501. PluginHost::getInstance()->load(PLUGINS, PluginHost::KIND_ALL);
  1502. return true;
  1503. }
  1504. function add_feed_category($feed_cat, $parent_cat_id = false) {
  1505. if (!$feed_cat) return false;
  1506. db_query("BEGIN");
  1507. if ($parent_cat_id) {
  1508. $parent_qpart = "parent_cat = '$parent_cat_id'";
  1509. $parent_insert = "'$parent_cat_id'";
  1510. } else {
  1511. $parent_qpart = "parent_cat IS NULL";
  1512. $parent_insert = "NULL";
  1513. }
  1514. $feed_cat = mb_substr($feed_cat, 0, 250);
  1515. $result = db_query(
  1516. "SELECT id FROM ttrss_feed_categories
  1517. WHERE $parent_qpart AND title = '$feed_cat' AND owner_uid = ".$_SESSION["uid"]);
  1518. if (db_num_rows($result) == 0) {
  1519. $result = db_query(
  1520. "INSERT INTO ttrss_feed_categories (owner_uid,title,parent_cat)
  1521. VALUES ('".$_SESSION["uid"]."', '$feed_cat', $parent_insert)");
  1522. db_query("COMMIT");
  1523. return true;
  1524. }
  1525. return false;
  1526. }
  1527. /**
  1528. * Fixes incomplete URLs by prepending "http://".
  1529. * Also replaces feed:// with http://, and
  1530. * prepends a trailing slash if the url is a domain name only.
  1531. *
  1532. * @param string $url Possibly incomplete URL
  1533. *
  1534. * @return string Fixed URL.
  1535. */
  1536. function fix_url($url) {
  1537. // support schema-less urls
  1538. if (strpos($url, '//') === 0) {
  1539. $url = 'https:' . $url;
  1540. }
  1541. if (strpos($url, '://') === false) {
  1542. $url = 'http://' . $url;
  1543. } else if (substr($url, 0, 5) == 'feed:') {
  1544. $url = 'http:' . substr($url, 5);
  1545. }
  1546. //prepend slash if the URL has no slash in it
  1547. // "http://www.example" -> "http://www.example/"
  1548. if (strpos($url, '/', strpos($url, ':') + 3) === false) {
  1549. $url .= '/';
  1550. }
  1551. //convert IDNA hostname to punycode if possible
  1552. if (function_exists("idn_to_ascii")) {
  1553. $parts = parse_url($url);
  1554. if (mb_detect_encoding($parts['host']) != 'ASCII')
  1555. {
  1556. $parts['host'] = idn_to_ascii($parts['host']);
  1557. $url = build_url($parts);
  1558. }
  1559. }
  1560. if ($url != "http:///")
  1561. return $url;
  1562. else
  1563. return '';
  1564. }
  1565. function validate_feed_url($url) {
  1566. $parts = parse_url($url);
  1567. return ($parts['scheme'] == 'http' || $parts['scheme'] == 'feed' || $parts['scheme'] == 'https');
  1568. }
  1569. /* function save_email_address($email) {
  1570. // FIXME: implement persistent storage of emails
  1571. if (!$_SESSION['stored_emails'])
  1572. $_SESSION['stored_emails'] = array();
  1573. if (!in_array($email, $_SESSION['stored_emails']))
  1574. array_push($_SESSION['stored_emails'], $email);
  1575. } */
  1576. function get_feed_access_key($feed_id, $is_cat, $owner_uid = false) {
  1577. if (!$owner_uid) $owner_uid = $_SESSION["uid"];
  1578. $sql_is_cat = bool_to_sql_bool($is_cat);
  1579. $result = db_query("SELECT access_key FROM ttrss_access_keys
  1580. WHERE feed_id = '$feed_id' AND is_cat = $sql_is_cat
  1581. AND owner_uid = " . $owner_uid);
  1582. if (db_num_rows($result) == 1) {
  1583. return db_fetch_result($result, 0, "access_key");
  1584. } else {
  1585. $key = db_escape_string(uniqid_short());
  1586. $result = db_query("INSERT INTO ttrss_access_keys
  1587. (access_key, feed_id, is_cat, owner_uid)
  1588. VALUES ('$key', '$feed_id', $sql_is_cat, '$owner_uid')");
  1589. return $key;
  1590. }
  1591. return false;
  1592. }
  1593. function get_feeds_from_html($url, $content)
  1594. {
  1595. $url = fix_url($url);
  1596. $baseUrl = substr($url, 0, strrpos($url, '/') + 1);
  1597. libxml_use_internal_errors(true);
  1598. $doc = new DOMDocument();
  1599. $doc->loadHTML($content);
  1600. $xpath = new DOMXPath($doc);
  1601. $entries = $xpath->query('/html/head/link[@rel="alternate" and '.
  1602. '(contains(@type,"rss") or contains(@type,"atom"))]|/html/head/link[@rel="feed"]');
  1603. $feedUrls = array();
  1604. foreach ($entries as $entry) {
  1605. if ($entry->hasAttribute('href')) {
  1606. $title = $entry->getAttribute('title');
  1607. if ($title == '') {
  1608. $title = $entry->getAttribute('type');
  1609. }
  1610. $feedUrl = rewrite_relative_url(
  1611. $baseUrl, $entry->getAttribute('href')
  1612. );
  1613. $feedUrls[$feedUrl] = $title;
  1614. }
  1615. }
  1616. return $feedUrls;
  1617. }
  1618. function is_html($content) {
  1619. return preg_match("/<html|DOCTYPE html/i", substr($content, 0, 100)) !== 0;
  1620. }
  1621. function url_is_html($url, $login = false, $pass = false) {
  1622. return is_html(fetch_file_contents($url, false, $login, $pass));
  1623. }
  1624. function build_url($parts) {
  1625. return $parts['scheme'] . "://" . $parts['host'] . $parts['path'];
  1626. }
  1627. function cleanup_url_path($path) {
  1628. $path = str_replace("/./", "/", $path);
  1629. $path = str_replace("//", "/", $path);
  1630. return $path;
  1631. }
  1632. /**
  1633. * Converts a (possibly) relative URL to a absolute one.
  1634. *
  1635. * @param string $url Base URL (i.e. from where the document is)
  1636. * @param string $rel_url Possibly relative URL in the document
  1637. *
  1638. * @return string Absolute URL
  1639. */
  1640. function rewrite_relative_url($url, $rel_url) {
  1641. if (strpos($rel_url, "://") !== false) {
  1642. return $rel_url;
  1643. } else if (strpos($rel_url, "//") === 0) {
  1644. # protocol-relative URL (rare but they exist)
  1645. return $rel_url;
  1646. } else if (preg_match("/^[a-z]+:/i", $rel_url)) {
  1647. # magnet:, feed:, etc
  1648. return $rel_url;
  1649. } else if (strpos($rel_url, "/") === 0) {
  1650. $parts = parse_url($url);
  1651. $parts['path'] = $rel_url;
  1652. $parts['path'] = cleanup_url_path($parts['path']);
  1653. return build_url($parts);
  1654. } else {
  1655. $parts = parse_url($url);
  1656. if (!isset($parts['path'])) {
  1657. $parts['path'] = '/';
  1658. }
  1659. $dir = $parts['path'];
  1660. if (substr($dir, -1) !== '/') {
  1661. $dir = dirname($parts['path']);
  1662. $dir !== '/' && $dir .= '/';
  1663. }
  1664. $parts['path'] = $dir . $rel_url;
  1665. $parts['path'] = cleanup_url_path($parts['path']);
  1666. return build_url($parts);
  1667. }
  1668. }
  1669. function cleanup_tags($days = 14, $limit = 1000) {
  1670. if (DB_TYPE == "pgsql") {
  1671. $interval_query = "date_updated < NOW() - INTERVAL '$days days'";
  1672. } else if (DB_TYPE == "mysql") {
  1673. $interval_query = "date_updated < DATE_SUB(NOW(), INTERVAL $days DAY)";
  1674. }
  1675. $tags_deleted = 0;
  1676. while ($limit > 0) {
  1677. $limit_part = 500;
  1678. $query = "SELECT ttrss_tags.id AS id
  1679. FROM ttrss_tags, ttrss_user_entries, ttrss_entries
  1680. WHERE post_int_id = int_id AND $interval_query AND
  1681. ref_id = ttrss_entries.id AND tag_cache != '' LIMIT $limit_part";
  1682. $result = db_query($query);
  1683. $ids = array();
  1684. while ($line = db_fetch_assoc($result)) {
  1685. array_push($ids, $line['id']);
  1686. }
  1687. if (count($ids) > 0) {
  1688. $ids = join(",", $ids);
  1689. $tmp_result = db_query("DELETE FROM ttrss_tags WHERE id IN ($ids)");
  1690. $tags_deleted += db_affected_rows($tmp_result);
  1691. } else {
  1692. break;
  1693. }
  1694. $limit -= $limit_part;
  1695. }
  1696. return $tags_deleted;
  1697. }
  1698. function print_user_stylesheet() {
  1699. $value = get_pref('USER_STYLESHEET');
  1700. if ($value) {
  1701. print "<style type=\"text/css\">";
  1702. print str_replace("<br/>", "\n", $value);
  1703. print "</style>";
  1704. }
  1705. }
  1706. function filter_to_sql($filter, $owner_uid) {
  1707. $query = array();
  1708. if (DB_TYPE == "pgsql")
  1709. $reg_qpart = "~";
  1710. else
  1711. $reg_qpart = "REGEXP";
  1712. foreach ($filter["rules"] AS $rule) {
  1713. $rule['reg_exp'] = str_replace('/', '\/', $rule["reg_exp"]);
  1714. $regexp_valid = preg_match('/' . $rule['reg_exp'] . '/',
  1715. $rule['reg_exp']) !== FALSE;
  1716. if ($regexp_valid) {
  1717. $rule['reg_exp'] = db_escape_string($rule['reg_exp']);
  1718. switch ($rule["type"]) {
  1719. case "title":
  1720. $qpart = "LOWER(ttrss_entries.title) $reg_qpart LOWER('".
  1721. $rule['reg_exp'] . "')";
  1722. break;
  1723. case "content":
  1724. $qpart = "LOWER(ttrss_entries.content) $reg_qpart LOWER('".
  1725. $rule['reg_exp'] . "')";
  1726. break;
  1727. case "both":
  1728. $qpart = "LOWER(ttrss_entries.title) $reg_qpart LOWER('".
  1729. $rule['reg_exp'] . "') OR LOWER(" .
  1730. "ttrss_entries.content) $reg_qpart LOWER('" . $rule['reg_exp'] . "')";
  1731. break;
  1732. case "tag":
  1733. $qpart = "LOWER(ttrss_user_entries.tag_cache) $reg_qpart LOWER('".
  1734. $rule['reg_exp'] . "')";
  1735. break;
  1736. case "link":
  1737. $qpart = "LOWER(ttrss_entries.link) $reg_qpart LOWER('".
  1738. $rule['reg_exp'] . "')";
  1739. break;
  1740. case "author":
  1741. $qpart = "LOWER(ttrss_entries.author) $reg_qpart LOWER('".
  1742. $rule['reg_exp'] . "')";
  1743. break;
  1744. }
  1745. if (isset($rule['inverse'])) $qpart = "NOT ($qpart)";
  1746. if (isset($rule["feed_id"]) && $rule["feed_id"] > 0) {
  1747. $qpart .= " AND feed_id = " . db_escape_string($rule["feed_id"]);
  1748. }
  1749. if (isset($rule["cat_id"])) {
  1750. if ($rule["cat_id"] > 0) {
  1751. $children = Feeds::getChildCategories($rule["cat_id"], $owner_uid);
  1752. array_push($children, $rule["cat_id"]);
  1753. $children = join(",", $children);
  1754. $cat_qpart = "cat_id IN ($children)";
  1755. } else {
  1756. $cat_qpart = "cat_id IS NULL";
  1757. }
  1758. $qpart .= " AND $cat_qpart";
  1759. }
  1760. $qpart .= " AND feed_id IS NOT NULL";
  1761. array_push($query, "($qpart)");
  1762. }
  1763. }
  1764. if (count($query) > 0) {
  1765. $fullquery = "(" . join($filter["match_any_rule"] ? "OR" : "AND", $query) . ")";
  1766. } else {
  1767. $fullquery = "(false)";
  1768. }
  1769. if ($filter['inverse']) $fullquery = "(NOT $fullquery)";
  1770. return $fullquery;
  1771. }
  1772. if (!function_exists('gzdecode')) {
  1773. function gzdecode($string) { // no support for 2nd argument
  1774. return file_get_contents('compress.zlib://data:who/cares;base64,'.
  1775. base64_encode($string));
  1776. }
  1777. }
  1778. function get_random_bytes($length) {
  1779. if (function_exists('openssl_random_pseudo_bytes')) {
  1780. return openssl_random_pseudo_bytes($length);
  1781. } else {
  1782. $output = "";
  1783. for ($i = 0; $i < $length; $i++)
  1784. $output .= chr(mt_rand(0, 255));
  1785. return $output;
  1786. }
  1787. }
  1788. function read_stdin() {
  1789. $fp = fopen("php://stdin", "r");
  1790. if ($fp) {
  1791. $line = trim(fgets($fp));
  1792. fclose($fp);
  1793. return $line;
  1794. }
  1795. return null;
  1796. }
  1797. function implements_interface($class, $interface) {
  1798. return in_array($interface, class_implements($class));
  1799. }
  1800. function get_minified_js($files) {
  1801. require_once 'lib/jshrink/Minifier.php';
  1802. $rv = '';
  1803. foreach ($files as $js) {
  1804. if (!isset($_GET['debug'])) {
  1805. $cached_file = CACHE_DIR . "/js/".basename($js).".js";
  1806. if (file_exists($cached_file) && is_readable($cached_file) && filemtime($cached_file) >= filemtime("js/$js.js")) {
  1807. list($header, $contents) = explode("\n", file_get_contents($cached_file), 2);
  1808. if ($header && $contents) {
  1809. list($htag, $hversion) = explode(":", $header);
  1810. if ($htag == "tt-rss" && $hversion == VERSION) {
  1811. $rv .= $contents;
  1812. continue;
  1813. }
  1814. }
  1815. }
  1816. $minified = JShrink\Minifier::minify(file_get_contents("js/$js.js"));
  1817. file_put_contents($cached_file, "tt-rss:" . VERSION . "\n" . $minified);
  1818. $rv .= $minified;
  1819. } else {
  1820. $rv .= file_get_contents("js/$js.js"); // no cache in debug mode
  1821. }
  1822. }
  1823. return $rv;
  1824. }
  1825. function calculate_dep_timestamp() {
  1826. $files = array_merge(glob("js/*.js"), glob("css/*.css"));
  1827. $max_ts = -1;
  1828. foreach ($files as $file) {
  1829. if (filemtime($file) > $max_ts) $max_ts = filemtime($file);
  1830. }
  1831. return $max_ts;
  1832. }
  1833. function T_js_decl($s1, $s2) {
  1834. if ($s1 && $s2) {
  1835. $s1 = preg_replace("/\n/", "", $s1);
  1836. $s2 = preg_replace("/\n/", "", $s2);
  1837. $s1 = preg_replace("/\"/", "\\\"", $s1);
  1838. $s2 = preg_replace("/\"/", "\\\"", $s2);
  1839. return "T_messages[\"$s1\"] = \"$s2\";\n";
  1840. }
  1841. }
  1842. function init_js_translations() {
  1843. print 'var T_messages = new Object();
  1844. function __(msg) {
  1845. if (T_messages[msg]) {
  1846. return T_messages[msg];
  1847. } else {
  1848. return msg;
  1849. }
  1850. }
  1851. function ngettext(msg1, msg2, n) {
  1852. return __((parseInt(n) > 1) ? msg2 : msg1);
  1853. }';
  1854. $l10n = _get_reader();
  1855. for ($i = 0; $i < $l10n->total; $i++) {
  1856. $orig = $l10n->get_original_string($i);
  1857. if(strpos($orig, "\000") !== FALSE) { // Plural forms
  1858. $key = explode(chr(0), $orig);
  1859. print T_js_decl($key[0], _ngettext($key[0], $key[1], 1)); // Singular
  1860. print T_js_decl($key[1], _ngettext($key[0], $key[1], 2)); // Plural
  1861. } else {
  1862. $translation = __($orig);
  1863. print T_js_decl($orig, $translation);
  1864. }
  1865. }
  1866. }
  1867. function get_theme_path($theme) {
  1868. $check = "themes/$theme";
  1869. if (file_exists($check)) return $check;
  1870. $check = "themes.local/$theme";
  1871. if (file_exists($check)) return $check;
  1872. }
  1873. function theme_valid($theme) {
  1874. $bundled_themes = [ "default.php", "night.css", "compact.css" ];
  1875. if (in_array($theme, $bundled_themes)) return true;
  1876. $file = "themes/" . basename($theme);
  1877. if (!file_exists($file)) $file = "themes.local/" . basename($theme);
  1878. if (file_exists($file) && is_readable($file)) {
  1879. $fh = fopen($file, "r");
  1880. if ($fh) {
  1881. $header = fgets($fh);
  1882. fclose($fh);
  1883. return strpos($header, "supports-version:" . VERSION_STATIC) !== FALSE;
  1884. }
  1885. }
  1886. return false;
  1887. }
  1888. /**
  1889. * @SuppressWarnings(unused)
  1890. */
  1891. function error_json($code) {
  1892. require_once "errors.php";
  1893. @$message = $ERRORS[$code];
  1894. return json_encode(array("error" =>
  1895. array("code" => $code, "message" => $message)));
  1896. }
  1897. /*function abs_to_rel_path($dir) {
  1898. $tmp = str_replace(dirname(__DIR__), "", $dir);
  1899. if (strlen($tmp) > 0 && substr($tmp, 0, 1) == "/") $tmp = substr($tmp, 1);
  1900. return $tmp;
  1901. }*/
  1902. function get_upload_error_message($code) {
  1903. $errors = array(
  1904. 0 => __('There is no error, the file uploaded with success'),
  1905. 1 => __('The uploaded file exceeds the upload_max_filesize directive in php.ini'),
  1906. 2 => __('The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form'),
  1907. 3 => __('The uploaded file was only partially uploaded'),
  1908. 4 => __('No file was uploaded'),
  1909. 6 => __('Missing a temporary folder'),
  1910. 7 => __('Failed to write file to disk.'),
  1911. 8 => __('A PHP extension stopped the file upload.'),
  1912. );
  1913. return $errors[$code];
  1914. }
  1915. function base64_img($filename) {
  1916. if (file_exists($filename)) {
  1917. $ext = pathinfo($filename, PATHINFO_EXTENSION);
  1918. return "data:image/$ext;base64," . base64_encode(file_get_contents($filename));
  1919. } else {
  1920. return "";
  1921. }
  1922. }