functions2.php 68 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466
  1. <?php
  2. function make_init_params() {
  3. $params = array();
  4. foreach (array("ON_CATCHUP_SHOW_NEXT_FEED", "HIDE_READ_FEEDS",
  5. "ENABLE_FEED_CATS", "FEEDS_SORT_BY_UNREAD", "CONFIRM_FEED_CATCHUP",
  6. "CDM_AUTO_CATCHUP", "FRESH_ARTICLE_MAX_AGE",
  7. "HIDE_READ_SHOWS_SPECIAL", "COMBINED_DISPLAY_MODE") as $param) {
  8. $params[strtolower($param)] = (int) get_pref($param);
  9. }
  10. $params["icons_url"] = ICONS_URL;
  11. $params["cookie_lifetime"] = SESSION_COOKIE_LIFETIME;
  12. $params["default_view_mode"] = get_pref("_DEFAULT_VIEW_MODE");
  13. $params["default_view_limit"] = (int) get_pref("_DEFAULT_VIEW_LIMIT");
  14. $params["default_view_order_by"] = get_pref("_DEFAULT_VIEW_ORDER_BY");
  15. $params["bw_limit"] = (int) $_SESSION["bw_limit"];
  16. $params["label_base_index"] = (int) LABEL_BASE_INDEX;
  17. $theme = get_pref( "USER_CSS_THEME", false, false);
  18. $params["theme"] = theme_valid("$theme") ? $theme : "";
  19. $params["plugins"] = implode(", ", PluginHost::getInstance()->get_plugin_names());
  20. $params["php_platform"] = PHP_OS;
  21. $params["php_version"] = PHP_VERSION;
  22. $params["sanity_checksum"] = sha1(file_get_contents("include/sanity_check.php"));
  23. $result = db_query("SELECT MAX(id) AS mid, COUNT(*) AS nf FROM
  24. ttrss_feeds WHERE owner_uid = " . $_SESSION["uid"]);
  25. $max_feed_id = db_fetch_result($result, 0, "mid");
  26. $num_feeds = db_fetch_result($result, 0, "nf");
  27. $params["max_feed_id"] = (int) $max_feed_id;
  28. $params["num_feeds"] = (int) $num_feeds;
  29. $params["hotkeys"] = get_hotkeys_map();
  30. $params["csrf_token"] = $_SESSION["csrf_token"];
  31. $params["widescreen"] = (int) $_COOKIE["ttrss_widescreen"];
  32. $params['simple_update'] = defined('SIMPLE_UPDATE_MODE') && SIMPLE_UPDATE_MODE;
  33. return $params;
  34. }
  35. function get_hotkeys_info() {
  36. $hotkeys = array(
  37. __("Navigation") => array(
  38. "next_feed" => __("Open next feed"),
  39. "prev_feed" => __("Open previous feed"),
  40. "next_article" => __("Open next article"),
  41. "prev_article" => __("Open previous article"),
  42. "next_article_noscroll" => __("Open next article (don't scroll long articles)"),
  43. "prev_article_noscroll" => __("Open previous article (don't scroll long articles)"),
  44. "next_article_noexpand" => __("Move to next article (don't expand or mark read)"),
  45. "prev_article_noexpand" => __("Move to previous article (don't expand or mark read)"),
  46. "search_dialog" => __("Show search dialog")),
  47. __("Article") => array(
  48. "toggle_mark" => __("Toggle starred"),
  49. "toggle_publ" => __("Toggle published"),
  50. "toggle_unread" => __("Toggle unread"),
  51. "edit_tags" => __("Edit tags"),
  52. "open_in_new_window" => __("Open in new window"),
  53. "catchup_below" => __("Mark below as read"),
  54. "catchup_above" => __("Mark above as read"),
  55. "article_scroll_down" => __("Scroll down"),
  56. "article_scroll_up" => __("Scroll up"),
  57. "select_article_cursor" => __("Select article under cursor"),
  58. "email_article" => __("Email article"),
  59. "close_article" => __("Close/collapse article"),
  60. "toggle_expand" => __("Toggle article expansion (combined mode)"),
  61. "toggle_widescreen" => __("Toggle widescreen mode"),
  62. "toggle_embed_original" => __("Toggle embed original")),
  63. __("Article selection") => array(
  64. "select_all" => __("Select all articles"),
  65. "select_unread" => __("Select unread"),
  66. "select_marked" => __("Select starred"),
  67. "select_published" => __("Select published"),
  68. "select_invert" => __("Invert selection"),
  69. "select_none" => __("Deselect everything")),
  70. __("Feed") => array(
  71. "feed_refresh" => __("Refresh current feed"),
  72. "feed_unhide_read" => __("Un/hide read feeds"),
  73. "feed_subscribe" => __("Subscribe to feed"),
  74. "feed_edit" => __("Edit feed"),
  75. "feed_catchup" => __("Mark as read"),
  76. "feed_reverse" => __("Reverse headlines"),
  77. "feed_toggle_vgroup" => __("Toggle headline grouping"),
  78. "feed_debug_update" => __("Debug feed update"),
  79. "feed_debug_viewfeed" => __("Debug viewfeed()"),
  80. "catchup_all" => __("Mark all feeds as read"),
  81. "cat_toggle_collapse" => __("Un/collapse current category"),
  82. "toggle_combined_mode" => __("Toggle combined mode"),
  83. "toggle_cdm_expanded" => __("Toggle auto expand in combined mode")),
  84. __("Go to") => array(
  85. "goto_all" => __("All articles"),
  86. "goto_fresh" => __("Fresh"),
  87. "goto_marked" => __("Starred"),
  88. "goto_published" => __("Published"),
  89. "goto_tagcloud" => __("Tag cloud"),
  90. "goto_prefs" => __("Preferences")),
  91. __("Other") => array(
  92. "create_label" => __("Create label"),
  93. "create_filter" => __("Create filter"),
  94. "collapse_sidebar" => __("Un/collapse sidebar"),
  95. "help_dialog" => __("Show help dialog"))
  96. );
  97. foreach (PluginHost::getInstance()->get_hooks(PluginHost::HOOK_HOTKEY_INFO) as $plugin) {
  98. $hotkeys = $plugin->hook_hotkey_info($hotkeys);
  99. }
  100. return $hotkeys;
  101. }
  102. function get_hotkeys_map() {
  103. $hotkeys = array(
  104. // "navigation" => array(
  105. "k" => "next_feed",
  106. "j" => "prev_feed",
  107. "n" => "next_article",
  108. "p" => "prev_article",
  109. "(38)|up" => "prev_article",
  110. "(40)|down" => "next_article",
  111. // "^(38)|Ctrl-up" => "prev_article_noscroll",
  112. // "^(40)|Ctrl-down" => "next_article_noscroll",
  113. "(191)|/" => "search_dialog",
  114. // "article" => array(
  115. "s" => "toggle_mark",
  116. "*s" => "toggle_publ",
  117. "u" => "toggle_unread",
  118. "*t" => "edit_tags",
  119. "o" => "open_in_new_window",
  120. "c p" => "catchup_below",
  121. "c n" => "catchup_above",
  122. "*n" => "article_scroll_down",
  123. "*p" => "article_scroll_up",
  124. "*(38)|Shift+up" => "article_scroll_up",
  125. "*(40)|Shift+down" => "article_scroll_down",
  126. "a *w" => "toggle_widescreen",
  127. "a e" => "toggle_embed_original",
  128. "e" => "email_article",
  129. "a q" => "close_article",
  130. // "article_selection" => array(
  131. "a a" => "select_all",
  132. "a u" => "select_unread",
  133. "a *u" => "select_marked",
  134. "a p" => "select_published",
  135. "a i" => "select_invert",
  136. "a n" => "select_none",
  137. // "feed" => array(
  138. "f r" => "feed_refresh",
  139. "f a" => "feed_unhide_read",
  140. "f s" => "feed_subscribe",
  141. "f e" => "feed_edit",
  142. "f q" => "feed_catchup",
  143. "f x" => "feed_reverse",
  144. "f g" => "feed_toggle_vgroup",
  145. "f *d" => "feed_debug_update",
  146. "f *g" => "feed_debug_viewfeed",
  147. "f *c" => "toggle_combined_mode",
  148. "f c" => "toggle_cdm_expanded",
  149. "*q" => "catchup_all",
  150. "x" => "cat_toggle_collapse",
  151. // "goto" => array(
  152. "g a" => "goto_all",
  153. "g f" => "goto_fresh",
  154. "g s" => "goto_marked",
  155. "g p" => "goto_published",
  156. "g t" => "goto_tagcloud",
  157. "g *p" => "goto_prefs",
  158. // "other" => array(
  159. "(9)|Tab" => "select_article_cursor", // tab
  160. "c l" => "create_label",
  161. "c f" => "create_filter",
  162. "c s" => "collapse_sidebar",
  163. "^(191)|Ctrl+/" => "help_dialog",
  164. );
  165. if (get_pref('COMBINED_DISPLAY_MODE')) {
  166. $hotkeys["^(38)|Ctrl-up"] = "prev_article_noscroll";
  167. $hotkeys["^(40)|Ctrl-down"] = "next_article_noscroll";
  168. }
  169. foreach (PluginHost::getInstance()->get_hooks(PluginHost::HOOK_HOTKEY_MAP) as $plugin) {
  170. $hotkeys = $plugin->hook_hotkey_map($hotkeys);
  171. }
  172. $prefixes = array();
  173. foreach (array_keys($hotkeys) as $hotkey) {
  174. $pair = explode(" ", $hotkey, 2);
  175. if (count($pair) > 1 && !in_array($pair[0], $prefixes)) {
  176. array_push($prefixes, $pair[0]);
  177. }
  178. }
  179. return array($prefixes, $hotkeys);
  180. }
  181. function check_for_update() {
  182. if (defined("GIT_VERSION_TIMESTAMP")) {
  183. $content = @fetch_file_contents(array("url" => "http://tt-rss.org/version.json", "timeout" => 5));
  184. if ($content) {
  185. $content = json_decode($content, true);
  186. if ($content && isset($content["changeset"])) {
  187. if ((int)GIT_VERSION_TIMESTAMP < (int)$content["changeset"]["timestamp"] &&
  188. GIT_VERSION_HEAD != $content["changeset"]["id"]) {
  189. return $content["changeset"]["id"];
  190. }
  191. }
  192. }
  193. }
  194. return "";
  195. }
  196. function make_runtime_info($disable_update_check = false) {
  197. $data = array();
  198. $result = db_query("SELECT MAX(id) AS mid, COUNT(*) AS nf FROM
  199. ttrss_feeds WHERE owner_uid = " . $_SESSION["uid"]);
  200. $max_feed_id = db_fetch_result($result, 0, "mid");
  201. $num_feeds = db_fetch_result($result, 0, "nf");
  202. $data["max_feed_id"] = (int) $max_feed_id;
  203. $data["num_feeds"] = (int) $num_feeds;
  204. $data['last_article_id'] = getLastArticleId();
  205. $data['cdm_expanded'] = get_pref('CDM_EXPANDED');
  206. $data['dep_ts'] = calculate_dep_timestamp();
  207. $data['reload_on_ts_change'] = !defined('_NO_RELOAD_ON_TS_CHANGE');
  208. if (CHECK_FOR_UPDATES && !$disable_update_check && $_SESSION["last_version_check"] + 86400 + rand(-1000, 1000) < time()) {
  209. $update_result = @check_for_update();
  210. $data["update_result"] = $update_result;
  211. $_SESSION["last_version_check"] = time();
  212. }
  213. if (file_exists(LOCK_DIRECTORY . "/update_daemon.lock")) {
  214. $data['daemon_is_running'] = (int) file_is_locked("update_daemon.lock");
  215. if (time() - $_SESSION["daemon_stamp_check"] > 30) {
  216. $stamp = (int) @file_get_contents(LOCK_DIRECTORY . "/update_daemon.stamp");
  217. if ($stamp) {
  218. $stamp_delta = time() - $stamp;
  219. if ($stamp_delta > 1800) {
  220. $stamp_check = 0;
  221. } else {
  222. $stamp_check = 1;
  223. $_SESSION["daemon_stamp_check"] = time();
  224. }
  225. $data['daemon_stamp_ok'] = $stamp_check;
  226. $stamp_fmt = date("Y.m.d, G:i", $stamp);
  227. $data['daemon_stamp'] = $stamp_fmt;
  228. }
  229. }
  230. }
  231. return $data;
  232. }
  233. function search_to_sql($search, $search_language) {
  234. $keywords = str_getcsv(trim($search), " ");
  235. $query_keywords = array();
  236. $search_words = array();
  237. $search_query_leftover = array();
  238. if ($search_language)
  239. $search_language = db_escape_string(mb_strtolower($search_language));
  240. else
  241. $search_language = "english";
  242. foreach ($keywords as $k) {
  243. if (strpos($k, "-") === 0) {
  244. $k = substr($k, 1);
  245. $not = "NOT";
  246. } else {
  247. $not = "";
  248. }
  249. $commandpair = explode(":", mb_strtolower($k), 2);
  250. switch ($commandpair[0]) {
  251. case "title":
  252. if ($commandpair[1]) {
  253. array_push($query_keywords, "($not (LOWER(ttrss_entries.title) LIKE '%".
  254. db_escape_string(mb_strtolower($commandpair[1]))."%'))");
  255. } else {
  256. array_push($query_keywords, "(UPPER(ttrss_entries.title) $not LIKE UPPER('%$k%')
  257. OR UPPER(ttrss_entries.content) $not LIKE UPPER('%$k%'))");
  258. array_push($search_words, $k);
  259. }
  260. break;
  261. case "author":
  262. if ($commandpair[1]) {
  263. array_push($query_keywords, "($not (LOWER(author) LIKE '%".
  264. db_escape_string(mb_strtolower($commandpair[1]))."%'))");
  265. } else {
  266. array_push($query_keywords, "(UPPER(ttrss_entries.title) $not LIKE UPPER('%$k%')
  267. OR UPPER(ttrss_entries.content) $not LIKE UPPER('%$k%'))");
  268. array_push($search_words, $k);
  269. }
  270. break;
  271. case "note":
  272. if ($commandpair[1]) {
  273. if ($commandpair[1] == "true")
  274. array_push($query_keywords, "($not (note IS NOT NULL AND note != ''))");
  275. else if ($commandpair[1] == "false")
  276. array_push($query_keywords, "($not (note IS NULL OR note = ''))");
  277. else
  278. array_push($query_keywords, "($not (LOWER(note) LIKE '%".
  279. db_escape_string(mb_strtolower($commandpair[1]))."%'))");
  280. } else {
  281. array_push($query_keywords, "(UPPER(ttrss_entries.title) $not LIKE UPPER('%$k%')
  282. OR UPPER(ttrss_entries.content) $not LIKE UPPER('%$k%'))");
  283. if (!$not) array_push($search_words, $k);
  284. }
  285. break;
  286. case "star":
  287. if ($commandpair[1]) {
  288. if ($commandpair[1] == "true")
  289. array_push($query_keywords, "($not (marked = true))");
  290. else
  291. array_push($query_keywords, "($not (marked = false))");
  292. } else {
  293. array_push($query_keywords, "(UPPER(ttrss_entries.title) $not LIKE UPPER('%$k%')
  294. OR UPPER(ttrss_entries.content) $not LIKE UPPER('%$k%'))");
  295. if (!$not) array_push($search_words, $k);
  296. }
  297. break;
  298. case "pub":
  299. if ($commandpair[1]) {
  300. if ($commandpair[1] == "true")
  301. array_push($query_keywords, "($not (published = true))");
  302. else
  303. array_push($query_keywords, "($not (published = false))");
  304. } else {
  305. array_push($query_keywords, "(UPPER(ttrss_entries.title) $not LIKE UPPER('%$k%')
  306. OR UPPER(ttrss_entries.content) $not LIKE UPPER('%$k%'))");
  307. if (!$not) array_push($search_words, $k);
  308. }
  309. break;
  310. case "unread":
  311. if ($commandpair[1]) {
  312. if ($commandpair[1] == "true")
  313. array_push($query_keywords, "($not (unread = true))");
  314. else
  315. array_push($query_keywords, "($not (unread = false))");
  316. } else {
  317. array_push($query_keywords, "(UPPER(ttrss_entries.title) $not LIKE UPPER('%$k%')
  318. OR UPPER(ttrss_entries.content) $not LIKE UPPER('%$k%'))");
  319. if (!$not) array_push($search_words, $k);
  320. }
  321. break;
  322. default:
  323. if (strpos($k, "@") === 0) {
  324. $user_tz_string = get_pref('USER_TIMEZONE', $_SESSION['uid']);
  325. $orig_ts = strtotime(substr($k, 1));
  326. $k = date("Y-m-d", convert_timestamp($orig_ts, $user_tz_string, 'UTC'));
  327. //$k = date("Y-m-d", strtotime(substr($k, 1)));
  328. array_push($query_keywords, "(".SUBSTRING_FOR_DATE."(updated,1,LENGTH('$k')) $not = '$k')");
  329. } else {
  330. if (DB_TYPE == "pgsql") {
  331. $k = mb_strtolower($k);
  332. array_push($search_query_leftover, $not ? "!$k" : $k);
  333. } else {
  334. array_push($query_keywords, "(UPPER(ttrss_entries.title) $not LIKE UPPER('%$k%')
  335. OR UPPER(ttrss_entries.content) $not LIKE UPPER('%$k%'))");
  336. }
  337. if (!$not) array_push($search_words, $k);
  338. }
  339. }
  340. }
  341. if (count($search_query_leftover) > 0) {
  342. $search_query_leftover = db_escape_string(implode(" & ", $search_query_leftover));
  343. if (DB_TYPE == "pgsql") {
  344. array_push($query_keywords,
  345. "(tsvector_combined @@ to_tsquery('$search_language', '$search_query_leftover'))");
  346. }
  347. }
  348. $search_query_part = implode("AND", $query_keywords);
  349. return array($search_query_part, $search_words);
  350. }
  351. function getParentCategories($cat, $owner_uid) {
  352. $rv = array();
  353. $result = db_query("SELECT parent_cat FROM ttrss_feed_categories
  354. WHERE id = '$cat' AND parent_cat IS NOT NULL AND owner_uid = $owner_uid");
  355. while ($line = db_fetch_assoc($result)) {
  356. array_push($rv, $line["parent_cat"]);
  357. $rv = array_merge($rv, getParentCategories($line["parent_cat"], $owner_uid));
  358. }
  359. return $rv;
  360. }
  361. function getChildCategories($cat, $owner_uid) {
  362. $rv = array();
  363. $result = db_query("SELECT id FROM ttrss_feed_categories
  364. WHERE parent_cat = '$cat' AND owner_uid = $owner_uid");
  365. while ($line = db_fetch_assoc($result)) {
  366. array_push($rv, $line["id"]);
  367. $rv = array_merge($rv, getChildCategories($line["id"], $owner_uid));
  368. }
  369. return $rv;
  370. }
  371. function queryFeedHeadlines($params) {
  372. $feed = $params["feed"];
  373. $limit = isset($params["limit"]) ? $params["limit"] : 30;
  374. $view_mode = $params["view_mode"];
  375. $cat_view = isset($params["cat_view"]) ? $params["cat_view"] : false;
  376. $search = isset($params["search"]) ? $params["search"] : false;
  377. $search_language = isset($params["search_language"]) ? $params["search_language"] : "";
  378. $override_order = isset($params["override_order"]) ? $params["override_order"] : false;
  379. $offset = isset($params["offset"]) ? $params["offset"] : 0;
  380. $owner_uid = isset($params["owner_uid"]) ? $params["owner_uid"] : $_SESSION["uid"];
  381. $since_id = isset($params["since_id"]) ? $params["since_id"] : 0;
  382. $include_children = isset($params["include_children"]) ? $params["include_children"] : false;
  383. $ignore_vfeed_group = isset($params["ignore_vfeed_group"]) ? $params["ignore_vfeed_group"] : false;
  384. $override_strategy = isset($params["override_strategy"]) ? $params["override_strategy"] : false;
  385. $override_vfeed = isset($params["override_vfeed"]) ? $params["override_vfeed"] : false;
  386. $start_ts = isset($params["start_ts"]) ? $params["start_ts"] : false;
  387. $check_first_id = isset($params["check_first_id"]) ? $params["check_first_id"] : false;
  388. $skip_first_id_check = isset($params["skip_first_id_check"]) ? $params["skip_first_id_check"] : false;
  389. $ext_tables_part = "";
  390. $query_strategy_part = "";
  391. $search_words = array();
  392. if ($search) {
  393. foreach (PluginHost::getInstance()->get_hooks(PluginHost::HOOK_SEARCH) as $plugin) {
  394. list($search_query_part, $search_words) = $plugin->hook_search($search);
  395. break;
  396. }
  397. // fall back in case of no plugins
  398. if (!$search_query_part) {
  399. list($search_query_part, $search_words) = search_to_sql($search, $search_language);
  400. }
  401. $search_query_part .= " AND ";
  402. } else {
  403. $search_query_part = "";
  404. }
  405. if ($since_id) {
  406. $since_id_part = "ttrss_entries.id > $since_id AND ";
  407. } else {
  408. $since_id_part = "";
  409. }
  410. $view_query_part = "";
  411. if ($view_mode == "adaptive") {
  412. if ($search) {
  413. $view_query_part = " ";
  414. } else if ($feed != -1) {
  415. $unread = getFeedUnread($feed, $cat_view);
  416. if ($cat_view && $feed > 0 && $include_children)
  417. $unread += getCategoryChildrenUnread($feed);
  418. if ($unread > 0) {
  419. $view_query_part = " unread = true AND ";
  420. }
  421. }
  422. }
  423. if ($view_mode == "marked") {
  424. $view_query_part = " marked = true AND ";
  425. }
  426. if ($view_mode == "has_note") {
  427. $view_query_part = " (note IS NOT NULL AND note != '') AND ";
  428. }
  429. if ($view_mode == "published") {
  430. $view_query_part = " published = true AND ";
  431. }
  432. if ($view_mode == "unread" && $feed != -6) {
  433. $view_query_part = " unread = true AND ";
  434. }
  435. if ($limit > 0) {
  436. $limit_query_part = "LIMIT " . $limit;
  437. }
  438. $allow_archived = false;
  439. $vfeed_query_part = "";
  440. /* tags */
  441. if (!is_numeric($feed)) {
  442. $query_strategy_part = "true";
  443. $vfeed_query_part = "(SELECT title FROM ttrss_feeds WHERE
  444. id = feed_id) as feed_title,";
  445. } else if ($feed > 0) {
  446. if ($cat_view) {
  447. if ($feed > 0) {
  448. if ($include_children) {
  449. # sub-cats
  450. $subcats = getChildCategories($feed, $owner_uid);
  451. array_push($subcats, $feed);
  452. $query_strategy_part = "cat_id IN (".
  453. implode(",", $subcats).")";
  454. } else {
  455. $query_strategy_part = "cat_id = '$feed'";
  456. }
  457. } else {
  458. $query_strategy_part = "cat_id IS NULL";
  459. }
  460. $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
  461. } else {
  462. $query_strategy_part = "feed_id = '$feed'";
  463. }
  464. } else if ($feed == 0 && !$cat_view) { // archive virtual feed
  465. $query_strategy_part = "feed_id IS NULL";
  466. $allow_archived = true;
  467. } else if ($feed == 0 && $cat_view) { // uncategorized
  468. $query_strategy_part = "cat_id IS NULL AND feed_id IS NOT NULL";
  469. $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
  470. } else if ($feed == -1) { // starred virtual feed
  471. $query_strategy_part = "marked = true";
  472. $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
  473. $allow_archived = true;
  474. if (!$override_order) {
  475. $override_order = "last_marked DESC, date_entered DESC, updated DESC";
  476. }
  477. } else if ($feed == -2) { // published virtual feed OR labels category
  478. if (!$cat_view) {
  479. $query_strategy_part = "published = true";
  480. $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
  481. $allow_archived = true;
  482. if (!$override_order) {
  483. $override_order = "last_published DESC, date_entered DESC, updated DESC";
  484. }
  485. } else {
  486. $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
  487. $ext_tables_part = "ttrss_labels2,ttrss_user_labels2,";
  488. $query_strategy_part = "ttrss_labels2.id = ttrss_user_labels2.label_id AND
  489. ttrss_user_labels2.article_id = ref_id";
  490. }
  491. } else if ($feed == -6) { // recently read
  492. $query_strategy_part = "unread = false AND last_read IS NOT NULL";
  493. if (DB_TYPE == "pgsql") {
  494. $query_strategy_part .= " AND last_read > NOW() - INTERVAL '1 DAY' ";
  495. } else {
  496. $query_strategy_part .= " AND last_read > DATE_SUB(NOW(), INTERVAL 1 DAY) ";
  497. }
  498. $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
  499. $allow_archived = true;
  500. $ignore_vfeed_group = true;
  501. if (!$override_order) $override_order = "last_read DESC";
  502. } else if ($feed == -3) { // fresh virtual feed
  503. $query_strategy_part = "unread = true AND score >= 0";
  504. $intl = get_pref("FRESH_ARTICLE_MAX_AGE", $owner_uid);
  505. if (DB_TYPE == "pgsql") {
  506. $query_strategy_part .= " AND date_entered > NOW() - INTERVAL '$intl hour' ";
  507. } else {
  508. $query_strategy_part .= " AND date_entered > DATE_SUB(NOW(), INTERVAL $intl HOUR) ";
  509. }
  510. $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
  511. } else if ($feed == -4) { // all articles virtual feed
  512. $allow_archived = true;
  513. $query_strategy_part = "true";
  514. $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
  515. } else if ($feed <= LABEL_BASE_INDEX) { // labels
  516. $label_id = feed_to_label_id($feed);
  517. $query_strategy_part = "label_id = '$label_id' AND
  518. ttrss_labels2.id = ttrss_user_labels2.label_id AND
  519. ttrss_user_labels2.article_id = ref_id";
  520. $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
  521. $ext_tables_part = "ttrss_labels2,ttrss_user_labels2,";
  522. $allow_archived = true;
  523. } else {
  524. $query_strategy_part = "true";
  525. }
  526. $order_by = "score DESC, date_entered DESC, updated DESC";
  527. if ($override_order) {
  528. $order_by = $override_order;
  529. }
  530. if ($override_strategy) {
  531. $query_strategy_part = $override_strategy;
  532. }
  533. if ($override_vfeed) {
  534. $vfeed_query_part = $override_vfeed;
  535. }
  536. $feed_title = "";
  537. if ($search) {
  538. $feed_title = T_sprintf("Search results: %s", $search);
  539. } else {
  540. if ($cat_view) {
  541. $feed_title = getCategoryTitle($feed);
  542. } else {
  543. if (is_numeric($feed) && $feed > 0) {
  544. $result = db_query("SELECT title,site_url,last_error,last_updated
  545. FROM ttrss_feeds WHERE id = '$feed' AND owner_uid = $owner_uid");
  546. $feed_title = db_fetch_result($result, 0, "title");
  547. $feed_site_url = db_fetch_result($result, 0, "site_url");
  548. $last_error = db_fetch_result($result, 0, "last_error");
  549. $last_updated = db_fetch_result($result, 0, "last_updated");
  550. } else {
  551. $feed_title = getFeedTitle($feed);
  552. }
  553. }
  554. }
  555. $content_query_part = "content, ";
  556. if ($limit_query_part) {
  557. $offset_query_part = "OFFSET $offset";
  558. } else {
  559. $offset_query_part = "";
  560. }
  561. if (is_numeric($feed)) {
  562. // proper override_order applied above
  563. if ($vfeed_query_part && !$ignore_vfeed_group && get_pref('VFEED_GROUP_BY_FEED', $owner_uid)) {
  564. if (!$override_order) {
  565. $order_by = "ttrss_feeds.title, $order_by";
  566. } else {
  567. $order_by = "ttrss_feeds.title, $override_order";
  568. }
  569. }
  570. if (!$allow_archived) {
  571. $from_qpart = "${ext_tables_part}ttrss_entries LEFT JOIN ttrss_user_entries ON (ref_id = ttrss_entries.id),ttrss_feeds";
  572. $feed_check_qpart = "ttrss_user_entries.feed_id = ttrss_feeds.id AND";
  573. } else {
  574. $from_qpart = "${ext_tables_part}ttrss_entries LEFT JOIN ttrss_user_entries ON (ref_id = ttrss_entries.id)
  575. LEFT JOIN ttrss_feeds ON (feed_id = ttrss_feeds.id)";
  576. }
  577. if ($vfeed_query_part) $vfeed_query_part .= "favicon_avg_color,";
  578. if ($start_ts) {
  579. $start_ts_formatted = date("Y/m/d H:i:s", strtotime($start_ts));
  580. $start_ts_query_part = "date_entered >= '$start_ts_formatted' AND";
  581. } else {
  582. $start_ts_query_part = "";
  583. }
  584. $first_id = 0;
  585. $first_id_query_strategy_part = $query_strategy_part;
  586. if ($feed == -3)
  587. $first_id_query_strategy_part = "true";
  588. if (DB_TYPE == "pgsql") {
  589. $sanity_interval_qpart = "date_entered >= NOW() - INTERVAL '1 hour' AND";
  590. } else {
  591. $sanity_interval_qpart = "date_entered >= DATE_SUB(NOW(), INTERVAL 1 hour) AND";
  592. }
  593. if (!$search && !$skip_first_id_check) {
  594. // if previous topmost article id changed that means our current pagination is no longer valid
  595. $query = "SELECT DISTINCT
  596. ttrss_feeds.title,
  597. date_entered,
  598. guid,
  599. ttrss_entries.id,
  600. ttrss_entries.title,
  601. updated,
  602. score,
  603. marked,
  604. published,
  605. last_marked,
  606. last_published,
  607. last_read
  608. FROM
  609. $from_qpart
  610. WHERE
  611. $feed_check_qpart
  612. ttrss_user_entries.owner_uid = '$owner_uid' AND
  613. $search_query_part
  614. $start_ts_query_part
  615. $since_id_part
  616. $sanity_interval_qpart
  617. $first_id_query_strategy_part ORDER BY $order_by LIMIT 1";
  618. if ($_REQUEST["debug"]) {
  619. print $query;
  620. }
  621. $result = db_query($query);
  622. if ($result && db_num_rows($result) > 0) {
  623. $first_id = (int)db_fetch_result($result, 0, "id");
  624. if ($offset > 0 && $first_id && $check_first_id && $first_id != $check_first_id) {
  625. return array(-1, $feed_title, $feed_site_url, $last_error, $last_updated, $search_words, $first_id);
  626. }
  627. }
  628. }
  629. $query = "SELECT DISTINCT
  630. date_entered,
  631. guid,
  632. ttrss_entries.id,ttrss_entries.title,
  633. updated,
  634. label_cache,
  635. tag_cache,
  636. always_display_enclosures,
  637. site_url,
  638. note,
  639. num_comments,
  640. comments,
  641. int_id,
  642. uuid,
  643. lang,
  644. hide_images,
  645. unread,feed_id,marked,published,link,last_read,orig_feed_id,
  646. last_marked, last_published,
  647. $vfeed_query_part
  648. $content_query_part
  649. author,score
  650. FROM
  651. $from_qpart
  652. WHERE
  653. $feed_check_qpart
  654. ttrss_user_entries.owner_uid = '$owner_uid' AND
  655. $search_query_part
  656. $start_ts_query_part
  657. $view_query_part
  658. $since_id_part
  659. $query_strategy_part ORDER BY $order_by
  660. $limit_query_part $offset_query_part";
  661. if ($_REQUEST["debug"]) print $query;
  662. $result = db_query($query);
  663. } else {
  664. // browsing by tag
  665. $query = "SELECT DISTINCT
  666. date_entered,
  667. guid,
  668. note,
  669. ttrss_entries.id as id,
  670. title,
  671. updated,
  672. unread,
  673. feed_id,
  674. orig_feed_id,
  675. marked,
  676. num_comments,
  677. comments,
  678. int_id,
  679. tag_cache,
  680. label_cache,
  681. link,
  682. lang,
  683. uuid,
  684. last_read,
  685. (SELECT hide_images FROM ttrss_feeds WHERE id = feed_id) AS hide_images,
  686. last_marked, last_published,
  687. $since_id_part
  688. $vfeed_query_part
  689. $content_query_part
  690. author, score
  691. FROM ttrss_entries, ttrss_user_entries, ttrss_tags
  692. WHERE
  693. ref_id = ttrss_entries.id AND
  694. ttrss_user_entries.owner_uid = $owner_uid AND
  695. post_int_id = int_id AND
  696. tag_name = '$feed' AND
  697. $view_query_part
  698. $search_query_part
  699. $query_strategy_part ORDER BY $order_by
  700. $limit_query_part $offset_query_part";
  701. if ($_REQUEST["debug"]) print $query;
  702. $result = db_query($query);
  703. }
  704. return array($result, $feed_title, $feed_site_url, $last_error, $last_updated, $search_words, $first_id);
  705. }
  706. function iframe_whitelisted($entry) {
  707. $whitelist = array("youtube.com", "youtu.be", "vimeo.com", "player.vimeo.com");
  708. @$src = parse_url($entry->getAttribute("src"), PHP_URL_HOST);
  709. if ($src) {
  710. foreach ($whitelist as $w) {
  711. if ($src == $w || $src == "www.$w")
  712. return true;
  713. }
  714. }
  715. return false;
  716. }
  717. function sanitize($str, $force_remove_images = false, $owner = false, $site_url = false, $highlight_words = false, $article_id = false) {
  718. if (!$owner) $owner = $_SESSION["uid"];
  719. $res = trim($str); if (!$res) return '';
  720. $charset_hack = '<head>
  721. <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
  722. </head>';
  723. $res = trim($res); if (!$res) return '';
  724. libxml_use_internal_errors(true);
  725. $doc = new DOMDocument();
  726. $doc->loadHTML($charset_hack . $res);
  727. $xpath = new DOMXPath($doc);
  728. $entries = $xpath->query('(//a[@href]|//img[@src])');
  729. $ttrss_uses_https = parse_url(get_self_url_prefix(), PHP_URL_SCHEME) === 'https';
  730. foreach ($entries as $entry) {
  731. if ($site_url) {
  732. if ($entry->hasAttribute('href')) {
  733. $entry->setAttribute('href',
  734. rewrite_relative_url($site_url, $entry->getAttribute('href')));
  735. $entry->setAttribute('rel', 'noreferrer');
  736. }
  737. if ($entry->hasAttribute('src')) {
  738. $src = rewrite_relative_url($site_url, $entry->getAttribute('src'));
  739. $cached_filename = CACHE_DIR . '/images/' . sha1($src) . '.png';
  740. if (file_exists($cached_filename)) {
  741. $src = SELF_URL_PATH . '/public.php?op=cached_image&hash=' . sha1($src);
  742. if ($entry->hasAttribute('srcset')) {
  743. $entry->removeAttribute('srcset');
  744. }
  745. if ($entry->hasAttribute('sizes')) {
  746. $entry->removeAttribute('sizes');
  747. }
  748. }
  749. $entry->setAttribute('src', $src);
  750. }
  751. if ($entry->nodeName == 'img') {
  752. if ($entry->hasAttribute('src')) {
  753. $is_https_url = parse_url($entry->getAttribute('src'), PHP_URL_SCHEME) === 'https';
  754. if ($ttrss_uses_https && !$is_https_url) {
  755. if ($entry->hasAttribute('srcset')) {
  756. $entry->removeAttribute('srcset');
  757. }
  758. if ($entry->hasAttribute('sizes')) {
  759. $entry->removeAttribute('sizes');
  760. }
  761. }
  762. }
  763. if (($owner && get_pref("STRIP_IMAGES", $owner)) ||
  764. $force_remove_images || $_SESSION["bw_limit"]) {
  765. $p = $doc->createElement('p');
  766. $a = $doc->createElement('a');
  767. $a->setAttribute('href', $entry->getAttribute('src'));
  768. $a->appendChild(new DOMText($entry->getAttribute('src')));
  769. $a->setAttribute('target', '_blank');
  770. $p->appendChild($a);
  771. $entry->parentNode->replaceChild($p, $entry);
  772. }
  773. }
  774. }
  775. if (strtolower($entry->nodeName) == "a") {
  776. $entry->setAttribute("target", "_blank");
  777. }
  778. }
  779. $entries = $xpath->query('//iframe');
  780. foreach ($entries as $entry) {
  781. if (!iframe_whitelisted($entry)) {
  782. $entry->setAttribute('sandbox', 'allow-scripts');
  783. } else {
  784. if ($_SERVER['HTTPS'] == "on") {
  785. $entry->setAttribute("src",
  786. str_replace("http://", "https://",
  787. $entry->getAttribute("src")));
  788. }
  789. }
  790. }
  791. $allowed_elements = array('a', 'address', 'audio', 'article', 'aside',
  792. 'b', 'bdi', 'bdo', 'big', 'blockquote', 'body', 'br',
  793. 'caption', 'cite', 'center', 'code', 'col', 'colgroup',
  794. 'data', 'dd', 'del', 'details', 'description', 'div', 'dl', 'font',
  795. 'dt', 'em', 'footer', 'figure', 'figcaption',
  796. 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'header', 'html', 'i',
  797. 'img', 'ins', 'kbd', 'li', 'main', 'mark', 'nav', 'noscript',
  798. 'ol', 'p', 'pre', 'q', 'ruby', 'rp', 'rt', 's', 'samp', 'section',
  799. 'small', 'source', 'span', 'strike', 'strong', 'sub', 'summary',
  800. 'sup', 'table', 'tbody', 'td', 'tfoot', 'th', 'thead', 'time',
  801. 'tr', 'track', 'tt', 'u', 'ul', 'var', 'wbr', 'video', 'xml:namespace' );
  802. if ($_SESSION['hasSandbox']) $allowed_elements[] = 'iframe';
  803. $disallowed_attributes = array('id', 'style', 'class');
  804. foreach (PluginHost::getInstance()->get_hooks(PluginHost::HOOK_SANITIZE) as $plugin) {
  805. $retval = $plugin->hook_sanitize($doc, $site_url, $allowed_elements, $disallowed_attributes, $article_id);
  806. if (is_array($retval)) {
  807. $doc = $retval[0];
  808. $allowed_elements = $retval[1];
  809. $disallowed_attributes = $retval[2];
  810. } else {
  811. $doc = $retval;
  812. }
  813. }
  814. $doc->removeChild($doc->firstChild); //remove doctype
  815. $doc = strip_harmful_tags($doc, $allowed_elements, $disallowed_attributes);
  816. if ($highlight_words) {
  817. foreach ($highlight_words as $word) {
  818. // http://stackoverflow.com/questions/4081372/highlight-keywords-in-a-paragraph
  819. $elements = $xpath->query("//*/text()");
  820. foreach ($elements as $child) {
  821. $fragment = $doc->createDocumentFragment();
  822. $text = $child->textContent;
  823. while (($pos = mb_stripos($text, $word)) !== false) {
  824. $fragment->appendChild(new DomText(mb_substr($text, 0, $pos)));
  825. $word = mb_substr($text, $pos, mb_strlen($word));
  826. $highlight = $doc->createElement('span');
  827. $highlight->appendChild(new DomText($word));
  828. $highlight->setAttribute('class', 'highlight');
  829. $fragment->appendChild($highlight);
  830. $text = mb_substr($text, $pos + mb_strlen($word));
  831. }
  832. if (!empty($text)) $fragment->appendChild(new DomText($text));
  833. $child->parentNode->replaceChild($fragment, $child);
  834. }
  835. }
  836. }
  837. $res = $doc->saveHTML();
  838. /* strip everything outside of <body>...</body> */
  839. $res_frag = array();
  840. if (preg_match('/<body>(.*)<\/body>/is', $res, $res_frag)) {
  841. return $res_frag[1];
  842. } else {
  843. return $res;
  844. }
  845. }
  846. function strip_harmful_tags($doc, $allowed_elements, $disallowed_attributes) {
  847. $xpath = new DOMXPath($doc);
  848. $entries = $xpath->query('//*');
  849. foreach ($entries as $entry) {
  850. if (!in_array($entry->nodeName, $allowed_elements)) {
  851. $entry->parentNode->removeChild($entry);
  852. }
  853. if ($entry->hasAttributes()) {
  854. $attrs_to_remove = array();
  855. foreach ($entry->attributes as $attr) {
  856. if (strpos($attr->nodeName, 'on') === 0) {
  857. array_push($attrs_to_remove, $attr);
  858. }
  859. if ($attr->nodeName == 'href' && stripos($attr->value, 'javascript:') === 0) {
  860. array_push($attrs_to_remove, $attr);
  861. }
  862. if (in_array($attr->nodeName, $disallowed_attributes)) {
  863. array_push($attrs_to_remove, $attr);
  864. }
  865. }
  866. foreach ($attrs_to_remove as $attr) {
  867. $entry->removeAttributeNode($attr);
  868. }
  869. }
  870. }
  871. return $doc;
  872. }
  873. function catchupArticlesById($ids, $cmode, $owner_uid = false) {
  874. if (!$owner_uid) $owner_uid = $_SESSION["uid"];
  875. if (count($ids) == 0) return;
  876. $tmp_ids = array();
  877. foreach ($ids as $id) {
  878. array_push($tmp_ids, "ref_id = '$id'");
  879. }
  880. $ids_qpart = join(" OR ", $tmp_ids);
  881. if ($cmode == 0) {
  882. db_query("UPDATE ttrss_user_entries SET
  883. unread = false,last_read = NOW()
  884. WHERE ($ids_qpart) AND owner_uid = $owner_uid");
  885. } else if ($cmode == 1) {
  886. db_query("UPDATE ttrss_user_entries SET
  887. unread = true
  888. WHERE ($ids_qpart) AND owner_uid = $owner_uid");
  889. } else {
  890. db_query("UPDATE ttrss_user_entries SET
  891. unread = NOT unread,last_read = NOW()
  892. WHERE ($ids_qpart) AND owner_uid = $owner_uid");
  893. }
  894. /* update ccache */
  895. $result = db_query("SELECT DISTINCT feed_id FROM ttrss_user_entries
  896. WHERE ($ids_qpart) AND owner_uid = $owner_uid");
  897. while ($line = db_fetch_assoc($result)) {
  898. ccache_update($line["feed_id"], $owner_uid);
  899. }
  900. }
  901. function get_article_tags($id, $owner_uid = 0, $tag_cache = false) {
  902. $a_id = db_escape_string($id);
  903. if (!$owner_uid) $owner_uid = $_SESSION["uid"];
  904. $query = "SELECT DISTINCT tag_name,
  905. owner_uid as owner FROM
  906. ttrss_tags WHERE post_int_id = (SELECT int_id FROM ttrss_user_entries WHERE
  907. ref_id = '$a_id' AND owner_uid = '$owner_uid' LIMIT 1) ORDER BY tag_name";
  908. $tags = array();
  909. /* check cache first */
  910. if ($tag_cache === false) {
  911. $result = db_query("SELECT tag_cache FROM ttrss_user_entries
  912. WHERE ref_id = '$id' AND owner_uid = $owner_uid");
  913. if (db_num_rows($result) != 0)
  914. $tag_cache = db_fetch_result($result, 0, "tag_cache");
  915. }
  916. if ($tag_cache) {
  917. $tags = explode(",", $tag_cache);
  918. } else {
  919. /* do it the hard way */
  920. $tmp_result = db_query($query);
  921. while ($tmp_line = db_fetch_assoc($tmp_result)) {
  922. array_push($tags, $tmp_line["tag_name"]);
  923. }
  924. /* update the cache */
  925. $tags_str = db_escape_string(join(",", $tags));
  926. db_query("UPDATE ttrss_user_entries
  927. SET tag_cache = '$tags_str' WHERE ref_id = '$id'
  928. AND owner_uid = $owner_uid");
  929. }
  930. return $tags;
  931. }
  932. function trim_array($array) {
  933. $tmp = $array;
  934. array_walk($tmp, 'trim');
  935. return $tmp;
  936. }
  937. function tag_is_valid($tag) {
  938. if ($tag == '') return false;
  939. if (is_numeric($tag)) return false;
  940. if (mb_strlen($tag) > 250) return false;
  941. if (!$tag) return false;
  942. return true;
  943. }
  944. function render_login_form() {
  945. header('Cache-Control: public');
  946. require_once "login_form.php";
  947. exit;
  948. }
  949. function format_warning($msg, $id = "") {
  950. return "<div class=\"alert\" id=\"$id\">$msg</div>";
  951. }
  952. function format_notice($msg, $id = "") {
  953. return "<div class=\"alert alert-info\" id=\"$id\">$msg</div>";
  954. }
  955. function format_error($msg, $id = "") {
  956. return "<div class=\"alert alert-danger\" id=\"$id\">$msg</div>";
  957. }
  958. function print_notice($msg) {
  959. return print format_notice($msg);
  960. }
  961. function print_warning($msg) {
  962. return print format_warning($msg);
  963. }
  964. function print_error($msg) {
  965. return print format_error($msg);
  966. }
  967. function T_sprintf() {
  968. $args = func_get_args();
  969. return vsprintf(__(array_shift($args)), $args);
  970. }
  971. function format_inline_player($url, $ctype) {
  972. $entry = "";
  973. $url = htmlspecialchars($url);
  974. if (strpos($ctype, "audio/") === 0) {
  975. if ($_SESSION["hasAudio"] && (strpos($ctype, "ogg") !== false ||
  976. $_SESSION["hasMp3"])) {
  977. $entry .= "<audio preload=\"none\" controls>
  978. <source type=\"$ctype\" src=\"$url\"/>
  979. </audio>";
  980. } else {
  981. $entry .= "<object type=\"application/x-shockwave-flash\"
  982. data=\"lib/button/musicplayer.swf?song_url=$url\"
  983. width=\"17\" height=\"17\" style='float : left; margin-right : 5px;'>
  984. <param name=\"movie\"
  985. value=\"lib/button/musicplayer.swf?song_url=$url\" />
  986. </object>";
  987. }
  988. if ($entry) $entry .= "&nbsp; <a target=\"_blank\"
  989. href=\"$url\">" . basename($url) . "</a>";
  990. return $entry;
  991. }
  992. return "";
  993. /* $filename = substr($url, strrpos($url, "/")+1);
  994. $entry .= " <a target=\"_blank\" href=\"" . htmlspecialchars($url) . "\">" .
  995. $filename . " (" . $ctype . ")" . "</a>"; */
  996. }
  997. function format_article($id, $mark_as_read = true, $zoom_mode = false, $owner_uid = false) {
  998. if (!$owner_uid) $owner_uid = $_SESSION["uid"];
  999. $rv = array();
  1000. $rv['id'] = $id;
  1001. /* we can figure out feed_id from article id anyway, why do we
  1002. * pass feed_id here? let's ignore the argument :(*/
  1003. $result = db_query("SELECT feed_id FROM ttrss_user_entries
  1004. WHERE ref_id = '$id'");
  1005. $feed_id = (int) db_fetch_result($result, 0, "feed_id");
  1006. $rv['feed_id'] = $feed_id;
  1007. //if (!$zoom_mode) { print "<article id='$id'><![CDATA["; };
  1008. if ($mark_as_read) {
  1009. $result = db_query("UPDATE ttrss_user_entries
  1010. SET unread = false,last_read = NOW()
  1011. WHERE ref_id = '$id' AND owner_uid = $owner_uid");
  1012. ccache_update($feed_id, $owner_uid);
  1013. }
  1014. $result = db_query("SELECT id,title,link,content,feed_id,comments,int_id,lang,
  1015. ".SUBSTRING_FOR_DATE."(updated,1,16) as updated,
  1016. (SELECT site_url FROM ttrss_feeds WHERE id = feed_id) as site_url,
  1017. (SELECT title FROM ttrss_feeds WHERE id = feed_id) as feed_title,
  1018. (SELECT hide_images FROM ttrss_feeds WHERE id = feed_id) as hide_images,
  1019. (SELECT always_display_enclosures FROM ttrss_feeds WHERE id = feed_id) as always_display_enclosures,
  1020. num_comments,
  1021. tag_cache,
  1022. author,
  1023. orig_feed_id,
  1024. note
  1025. FROM ttrss_entries,ttrss_user_entries
  1026. WHERE id = '$id' AND ref_id = id AND owner_uid = $owner_uid");
  1027. if ($result) {
  1028. $line = db_fetch_assoc($result);
  1029. $line["tags"] = get_article_tags($id, $owner_uid, $line["tag_cache"]);
  1030. unset($line["tag_cache"]);
  1031. $line["content"] = sanitize($line["content"],
  1032. sql_bool_to_bool($line['hide_images']),
  1033. $owner_uid, $line["site_url"], false, $line["id"]);
  1034. foreach (PluginHost::getInstance()->get_hooks(PluginHost::HOOK_RENDER_ARTICLE) as $p) {
  1035. $line = $p->hook_render_article($line);
  1036. }
  1037. $num_comments = $line["num_comments"];
  1038. $entry_comments = "";
  1039. if ($num_comments > 0) {
  1040. if ($line["comments"]) {
  1041. $comments_url = htmlspecialchars($line["comments"]);
  1042. } else {
  1043. $comments_url = htmlspecialchars($line["link"]);
  1044. }
  1045. $entry_comments = "<a class=\"postComments\"
  1046. target='_blank' href=\"$comments_url\">$num_comments ".
  1047. _ngettext("comment", "comments", $num_comments)."</a>";
  1048. } else {
  1049. if ($line["comments"] && $line["link"] != $line["comments"]) {
  1050. $entry_comments = "<a class=\"postComments\" target='_blank' href=\"".htmlspecialchars($line["comments"])."\">".__("comments")."</a>";
  1051. }
  1052. }
  1053. if ($zoom_mode) {
  1054. header("Content-Type: text/html");
  1055. $rv['content'] .= "<html><head>
  1056. <meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\"/>
  1057. <title>Tiny Tiny RSS - ".$line["title"]."</title>".
  1058. stylesheet_tag("css/tt-rss.css").
  1059. stylesheet_tag("css/zoom.css").
  1060. stylesheet_tag("css/dijit.css")."
  1061. <link rel=\"shortcut icon\" type=\"image/png\" href=\"images/favicon.png\">
  1062. <link rel=\"icon\" type=\"image/png\" sizes=\"72x72\" href=\"images/favicon-72px.png\">
  1063. </head><body id=\"ttrssZoom\">";
  1064. }
  1065. $rv['content'] .= "<div class=\"postReply\" id=\"POST-$id\">";
  1066. $rv['content'] .= "<div class=\"postHeader\" id=\"POSTHDR-$id\">";
  1067. $entry_author = $line["author"];
  1068. if ($entry_author) {
  1069. $entry_author = __(" - ") . $entry_author;
  1070. }
  1071. $parsed_updated = make_local_datetime($line["updated"], true,
  1072. $owner_uid, true);
  1073. if (!$zoom_mode)
  1074. $rv['content'] .= "<div class=\"postDate\">$parsed_updated</div>";
  1075. if ($line["link"]) {
  1076. $rv['content'] .= "<div class='postTitle'><a target='_blank'
  1077. title=\"".htmlspecialchars($line['title'])."\"
  1078. href=\"" .
  1079. htmlspecialchars($line["link"]) . "\">" .
  1080. $line["title"] . "</a>" .
  1081. "<span class='author'>$entry_author</span></div>";
  1082. } else {
  1083. $rv['content'] .= "<div class='postTitle'>" . $line["title"] . "$entry_author</div>";
  1084. }
  1085. if ($zoom_mode) {
  1086. $feed_title = htmlspecialchars($line["feed_title"]);
  1087. $rv['content'] .= "<div class=\"postFeedTitle\">$feed_title</div>";
  1088. $rv['content'] .= "<div class=\"postDate\">$parsed_updated</div>";
  1089. }
  1090. $tags_str = format_tags_string($line["tags"], $id);
  1091. $tags_str_full = join(", ", $line["tags"]);
  1092. if (!$tags_str_full) $tags_str_full = __("no tags");
  1093. if (!$entry_comments) $entry_comments = "&nbsp;"; # placeholder
  1094. $rv['content'] .= "<div class='postTags' style='float : right'>
  1095. <img src='images/tag.png'
  1096. class='tagsPic' alt='Tags' title='Tags'>&nbsp;";
  1097. if (!$zoom_mode) {
  1098. $rv['content'] .= "<span id=\"ATSTR-$id\">$tags_str</span>
  1099. <a title=\"".__('Edit tags for this article')."\"
  1100. href=\"#\" onclick=\"editArticleTags($id, $feed_id)\">(+)</a>";
  1101. $rv['content'] .= "<div dojoType=\"dijit.Tooltip\"
  1102. id=\"ATSTRTIP-$id\" connectId=\"ATSTR-$id\"
  1103. position=\"below\">$tags_str_full</div>";
  1104. foreach (PluginHost::getInstance()->get_hooks(PluginHost::HOOK_ARTICLE_BUTTON) as $p) {
  1105. $rv['content'] .= $p->hook_article_button($line);
  1106. }
  1107. } else {
  1108. $tags_str = strip_tags($tags_str);
  1109. $rv['content'] .= "<span id=\"ATSTR-$id\">$tags_str</span>";
  1110. }
  1111. $rv['content'] .= "</div>";
  1112. $rv['content'] .= "<div clear='both'>";
  1113. foreach (PluginHost::getInstance()->get_hooks(PluginHost::HOOK_ARTICLE_LEFT_BUTTON) as $p) {
  1114. $rv['content'] .= $p->hook_article_left_button($line);
  1115. }
  1116. $rv['content'] .= "$entry_comments</div>";
  1117. if ($line["orig_feed_id"]) {
  1118. $tmp_result = db_query("SELECT * FROM ttrss_archived_feeds
  1119. WHERE id = ".$line["orig_feed_id"] . " AND owner_uid = " . $_SESSION["uid"]);
  1120. if (db_num_rows($tmp_result) != 0) {
  1121. $rv['content'] .= "<div clear='both'>";
  1122. $rv['content'] .= __("Originally from:");
  1123. $rv['content'] .= "&nbsp;";
  1124. $tmp_line = db_fetch_assoc($tmp_result);
  1125. $rv['content'] .= "<a target='_blank'
  1126. href=' " . htmlspecialchars($tmp_line['site_url']) . "'>" .
  1127. $tmp_line['title'] . "</a>";
  1128. $rv['content'] .= "&nbsp;";
  1129. $rv['content'] .= "<a target='_blank' href='" . htmlspecialchars($tmp_line['feed_url']) . "'>";
  1130. $rv['content'] .= "<img title='".__('Feed URL')."' class='tinyFeedIcon' src='images/pub_set.png'></a>";
  1131. $rv['content'] .= "</div>";
  1132. }
  1133. }
  1134. $rv['content'] .= "</div>";
  1135. $rv['content'] .= "<div id=\"POSTNOTE-$id\">";
  1136. if ($line['note']) {
  1137. $rv['content'] .= format_article_note($id, $line['note'], !$zoom_mode);
  1138. }
  1139. $rv['content'] .= "</div>";
  1140. if (!$line['lang']) $line['lang'] = 'en';
  1141. $rv['content'] .= "<div class=\"postContent\" lang=\"".$line['lang']."\">";
  1142. $rv['content'] .= $line["content"];
  1143. if (!$zoom_mode) {
  1144. $rv['content'] .= format_article_enclosures($id,
  1145. sql_bool_to_bool($line["always_display_enclosures"]),
  1146. $line["content"],
  1147. sql_bool_to_bool($line["hide_images"]));
  1148. }
  1149. $rv['content'] .= "</div>";
  1150. $rv['content'] .= "</div>";
  1151. }
  1152. if ($zoom_mode) {
  1153. $rv['content'] .= "
  1154. <div class='footer'>
  1155. <button onclick=\"return window.close()\">".
  1156. __("Close this window")."</button></div>";
  1157. $rv['content'] .= "</body></html>";
  1158. }
  1159. return $rv;
  1160. }
  1161. function print_checkpoint($n, $s) {
  1162. $ts = microtime(true);
  1163. echo sprintf("<!-- CP[$n] %.4f seconds -->\n", $ts - $s);
  1164. return $ts;
  1165. }
  1166. function sanitize_tag($tag) {
  1167. $tag = trim($tag);
  1168. $tag = mb_strtolower($tag, 'utf-8');
  1169. $tag = preg_replace('/[,\'\"\+\>\<]/', "", $tag);
  1170. if (DB_TYPE == "mysql") {
  1171. $tag = preg_replace('/[\x{10000}-\x{10FFFF}]/u', "\xEF\xBF\xBD", $tag);
  1172. }
  1173. return $tag;
  1174. }
  1175. function get_self_url_prefix() {
  1176. if (strrpos(SELF_URL_PATH, "/") === strlen(SELF_URL_PATH)-1) {
  1177. return substr(SELF_URL_PATH, 0, strlen(SELF_URL_PATH)-1);
  1178. } else {
  1179. return SELF_URL_PATH;
  1180. }
  1181. }
  1182. /**
  1183. * Compute the Mozilla Firefox feed adding URL from server HOST and REQUEST_URI.
  1184. *
  1185. * @return string The Mozilla Firefox feed adding URL.
  1186. */
  1187. function add_feed_url() {
  1188. //$url_path = ($_SERVER['HTTPS'] != "on" ? 'http://' : 'https://') . $_SERVER["HTTP_HOST"] . parse_url($_SERVER["REQUEST_URI"], PHP_URL_PATH);
  1189. $url_path = get_self_url_prefix() .
  1190. "/public.php?op=subscribe&feed_url=%s";
  1191. return $url_path;
  1192. } // function add_feed_url
  1193. function encrypt_password($pass, $salt = '', $mode2 = false) {
  1194. if ($salt && $mode2) {
  1195. return "MODE2:" . hash('sha256', $salt . $pass);
  1196. } else if ($salt) {
  1197. return "SHA1X:" . sha1("$salt:$pass");
  1198. } else {
  1199. return "SHA1:" . sha1($pass);
  1200. }
  1201. } // function encrypt_password
  1202. function load_filters($feed_id, $owner_uid, $action_id = false) {
  1203. $filters = array();
  1204. $cat_id = (int)getFeedCategory($feed_id);
  1205. if ($cat_id == 0)
  1206. $null_cat_qpart = "cat_id IS NULL OR";
  1207. else
  1208. $null_cat_qpart = "";
  1209. $result = db_query("SELECT * FROM ttrss_filters2 WHERE
  1210. owner_uid = $owner_uid AND enabled = true ORDER BY order_id, title");
  1211. $check_cats = join(",", array_merge(
  1212. getParentCategories($cat_id, $owner_uid),
  1213. array($cat_id)));
  1214. while ($line = db_fetch_assoc($result)) {
  1215. $filter_id = $line["id"];
  1216. $result2 = db_query("SELECT
  1217. r.reg_exp, r.inverse, r.feed_id, r.cat_id, r.cat_filter, t.name AS type_name
  1218. FROM ttrss_filters2_rules AS r,
  1219. ttrss_filter_types AS t
  1220. WHERE
  1221. ($null_cat_qpart (cat_id IS NULL AND cat_filter = false) OR cat_id IN ($check_cats)) AND
  1222. (feed_id IS NULL OR feed_id = '$feed_id') AND
  1223. filter_type = t.id AND filter_id = '$filter_id'");
  1224. $rules = array();
  1225. $actions = array();
  1226. while ($rule_line = db_fetch_assoc($result2)) {
  1227. # print_r($rule_line);
  1228. $rule = array();
  1229. $rule["reg_exp"] = $rule_line["reg_exp"];
  1230. $rule["type"] = $rule_line["type_name"];
  1231. $rule["inverse"] = sql_bool_to_bool($rule_line["inverse"]);
  1232. array_push($rules, $rule);
  1233. }
  1234. $result2 = db_query("SELECT a.action_param,t.name AS type_name
  1235. FROM ttrss_filters2_actions AS a,
  1236. ttrss_filter_actions AS t
  1237. WHERE
  1238. action_id = t.id AND filter_id = '$filter_id'");
  1239. while ($action_line = db_fetch_assoc($result2)) {
  1240. # print_r($action_line);
  1241. $action = array();
  1242. $action["type"] = $action_line["type_name"];
  1243. $action["param"] = $action_line["action_param"];
  1244. array_push($actions, $action);
  1245. }
  1246. $filter = array();
  1247. $filter["match_any_rule"] = sql_bool_to_bool($line["match_any_rule"]);
  1248. $filter["inverse"] = sql_bool_to_bool($line["inverse"]);
  1249. $filter["rules"] = $rules;
  1250. $filter["actions"] = $actions;
  1251. if (count($rules) > 0 && count($actions) > 0) {
  1252. array_push($filters, $filter);
  1253. }
  1254. }
  1255. return $filters;
  1256. }
  1257. function get_score_pic($score) {
  1258. if ($score > 100) {
  1259. return "score_high.png";
  1260. } else if ($score > 0) {
  1261. return "score_half_high.png";
  1262. } else if ($score < -100) {
  1263. return "score_low.png";
  1264. } else if ($score < 0) {
  1265. return "score_half_low.png";
  1266. } else {
  1267. return "score_neutral.png";
  1268. }
  1269. }
  1270. function feed_has_icon($id) {
  1271. return is_file(ICONS_DIR . "/$id.ico") && filesize(ICONS_DIR . "/$id.ico") > 0;
  1272. }
  1273. function init_plugins() {
  1274. PluginHost::getInstance()->load(PLUGINS, PluginHost::KIND_ALL);
  1275. return true;
  1276. }
  1277. function format_tags_string($tags, $id) {
  1278. if (!is_array($tags) || count($tags) == 0) {
  1279. return __("no tags");
  1280. } else {
  1281. $maxtags = min(5, count($tags));
  1282. $tags_str = "";
  1283. for ($i = 0; $i < $maxtags; $i++) {
  1284. $tags_str .= "<a class=\"tag\" href=\"#\" onclick=\"viewfeed({feed:'".$tags[$i]."'})\">" . $tags[$i] . "</a>, ";
  1285. }
  1286. $tags_str = mb_substr($tags_str, 0, mb_strlen($tags_str)-2);
  1287. if (count($tags) > $maxtags)
  1288. $tags_str .= ", &hellip;";
  1289. return $tags_str;
  1290. }
  1291. }
  1292. function format_article_labels($labels, $id) {
  1293. if (!is_array($labels)) return '';
  1294. $labels_str = "";
  1295. foreach ($labels as $l) {
  1296. $labels_str .= sprintf("<span class='hlLabelRef'
  1297. style='color : %s; background-color : %s'>%s</span>",
  1298. $l[2], $l[3], $l[1]);
  1299. }
  1300. return $labels_str;
  1301. }
  1302. function format_article_note($id, $note, $allow_edit = true) {
  1303. $str = "<div class='articleNote' onclick=\"editArticleNote($id)\">
  1304. <div class='noteEdit' onclick=\"editArticleNote($id)\">".
  1305. ($allow_edit ? __('(edit note)') : "")."</div>$note</div>";
  1306. return $str;
  1307. }
  1308. function get_feed_category($feed_cat, $parent_cat_id = false) {
  1309. if ($parent_cat_id) {
  1310. $parent_qpart = "parent_cat = '$parent_cat_id'";
  1311. $parent_insert = "'$parent_cat_id'";
  1312. } else {
  1313. $parent_qpart = "parent_cat IS NULL";
  1314. $parent_insert = "NULL";
  1315. }
  1316. $result = db_query(
  1317. "SELECT id FROM ttrss_feed_categories
  1318. WHERE $parent_qpart AND title = '$feed_cat' AND owner_uid = ".$_SESSION["uid"]);
  1319. if (db_num_rows($result) == 0) {
  1320. return false;
  1321. } else {
  1322. return db_fetch_result($result, 0, "id");
  1323. }
  1324. }
  1325. function add_feed_category($feed_cat, $parent_cat_id = false) {
  1326. if (!$feed_cat) return false;
  1327. db_query("BEGIN");
  1328. if ($parent_cat_id) {
  1329. $parent_qpart = "parent_cat = '$parent_cat_id'";
  1330. $parent_insert = "'$parent_cat_id'";
  1331. } else {
  1332. $parent_qpart = "parent_cat IS NULL";
  1333. $parent_insert = "NULL";
  1334. }
  1335. $feed_cat = mb_substr($feed_cat, 0, 250);
  1336. $result = db_query(
  1337. "SELECT id FROM ttrss_feed_categories
  1338. WHERE $parent_qpart AND title = '$feed_cat' AND owner_uid = ".$_SESSION["uid"]);
  1339. if (db_num_rows($result) == 0) {
  1340. $result = db_query(
  1341. "INSERT INTO ttrss_feed_categories (owner_uid,title,parent_cat)
  1342. VALUES ('".$_SESSION["uid"]."', '$feed_cat', $parent_insert)");
  1343. db_query("COMMIT");
  1344. return true;
  1345. }
  1346. return false;
  1347. }
  1348. function getArticleFeed($id) {
  1349. $result = db_query("SELECT feed_id FROM ttrss_user_entries
  1350. WHERE ref_id = '$id' AND owner_uid = " . $_SESSION["uid"]);
  1351. if (db_num_rows($result) != 0) {
  1352. return db_fetch_result($result, 0, "feed_id");
  1353. } else {
  1354. return 0;
  1355. }
  1356. }
  1357. /**
  1358. * Fixes incomplete URLs by prepending "http://".
  1359. * Also replaces feed:// with http://, and
  1360. * prepends a trailing slash if the url is a domain name only.
  1361. *
  1362. * @param string $url Possibly incomplete URL
  1363. *
  1364. * @return string Fixed URL.
  1365. */
  1366. function fix_url($url) {
  1367. // support schema-less urls
  1368. if (strpos($url, '//') === 0) {
  1369. $url = 'https:' . $url;
  1370. }
  1371. if (strpos($url, '://') === false) {
  1372. $url = 'http://' . $url;
  1373. } else if (substr($url, 0, 5) == 'feed:') {
  1374. $url = 'http:' . substr($url, 5);
  1375. }
  1376. //prepend slash if the URL has no slash in it
  1377. // "http://www.example" -> "http://www.example/"
  1378. if (strpos($url, '/', strpos($url, ':') + 3) === false) {
  1379. $url .= '/';
  1380. }
  1381. if ($url != "http:///")
  1382. return $url;
  1383. else
  1384. return '';
  1385. }
  1386. function validate_feed_url($url) {
  1387. $parts = parse_url($url);
  1388. return ($parts['scheme'] == 'http' || $parts['scheme'] == 'feed' || $parts['scheme'] == 'https');
  1389. }
  1390. function get_article_enclosures($id) {
  1391. $query = "SELECT * FROM ttrss_enclosures
  1392. WHERE post_id = '$id' AND content_url != ''";
  1393. $rv = array();
  1394. $result = db_query($query);
  1395. if (db_num_rows($result) > 0) {
  1396. while ($line = db_fetch_assoc($result)) {
  1397. array_push($rv, $line);
  1398. }
  1399. }
  1400. return $rv;
  1401. }
  1402. /* function save_email_address($email) {
  1403. // FIXME: implement persistent storage of emails
  1404. if (!$_SESSION['stored_emails'])
  1405. $_SESSION['stored_emails'] = array();
  1406. if (!in_array($email, $_SESSION['stored_emails']))
  1407. array_push($_SESSION['stored_emails'], $email);
  1408. } */
  1409. function get_feed_access_key($feed_id, $is_cat, $owner_uid = false) {
  1410. if (!$owner_uid) $owner_uid = $_SESSION["uid"];
  1411. $sql_is_cat = bool_to_sql_bool($is_cat);
  1412. $result = db_query("SELECT access_key FROM ttrss_access_keys
  1413. WHERE feed_id = '$feed_id' AND is_cat = $sql_is_cat
  1414. AND owner_uid = " . $owner_uid);
  1415. if (db_num_rows($result) == 1) {
  1416. return db_fetch_result($result, 0, "access_key");
  1417. } else {
  1418. $key = db_escape_string(uniqid_short());
  1419. $result = db_query("INSERT INTO ttrss_access_keys
  1420. (access_key, feed_id, is_cat, owner_uid)
  1421. VALUES ('$key', '$feed_id', $sql_is_cat, '$owner_uid')");
  1422. return $key;
  1423. }
  1424. return false;
  1425. }
  1426. function get_feeds_from_html($url, $content)
  1427. {
  1428. $url = fix_url($url);
  1429. $baseUrl = substr($url, 0, strrpos($url, '/') + 1);
  1430. libxml_use_internal_errors(true);
  1431. $doc = new DOMDocument();
  1432. $doc->loadHTML($content);
  1433. $xpath = new DOMXPath($doc);
  1434. $entries = $xpath->query('/html/head/link[@rel="alternate" and '.
  1435. '(contains(@type,"rss") or contains(@type,"atom"))]|/html/head/link[@rel="feed"]');
  1436. $feedUrls = array();
  1437. foreach ($entries as $entry) {
  1438. if ($entry->hasAttribute('href')) {
  1439. $title = $entry->getAttribute('title');
  1440. if ($title == '') {
  1441. $title = $entry->getAttribute('type');
  1442. }
  1443. $feedUrl = rewrite_relative_url(
  1444. $baseUrl, $entry->getAttribute('href')
  1445. );
  1446. $feedUrls[$feedUrl] = $title;
  1447. }
  1448. }
  1449. return $feedUrls;
  1450. }
  1451. function is_html($content) {
  1452. return preg_match("/<html|DOCTYPE html/i", substr($content, 0, 100)) !== 0;
  1453. }
  1454. function url_is_html($url, $login = false, $pass = false) {
  1455. return is_html(fetch_file_contents($url, false, $login, $pass));
  1456. }
  1457. function print_label_select($name, $value, $attributes = "") {
  1458. $result = db_query("SELECT caption FROM ttrss_labels2
  1459. WHERE owner_uid = '".$_SESSION["uid"]."' ORDER BY caption");
  1460. print "<select default=\"$value\" name=\"" . htmlspecialchars($name) .
  1461. "\" $attributes onchange=\"labelSelectOnChange(this)\" >";
  1462. while ($line = db_fetch_assoc($result)) {
  1463. $issel = ($line["caption"] == $value) ? "selected=\"1\"" : "";
  1464. print "<option value=\"".htmlspecialchars($line["caption"])."\"
  1465. $issel>" . htmlspecialchars($line["caption"]) . "</option>";
  1466. }
  1467. # print "<option value=\"ADD_LABEL\">" .__("Add label...") . "</option>";
  1468. print "</select>";
  1469. }
  1470. function format_article_enclosures($id, $always_display_enclosures,
  1471. $article_content, $hide_images = false) {
  1472. $result = get_article_enclosures($id);
  1473. $rv = '';
  1474. foreach (PluginHost::getInstance()->get_hooks(PluginHost::HOOK_FORMAT_ENCLOSURES) as $plugin) {
  1475. $retval = $plugin->hook_format_enclosures($rv, $result, $id, $always_display_enclosures, $article_content, $hide_images);
  1476. if (is_array($retval)) {
  1477. $rv = $retval[0];
  1478. $result = $retval[1];
  1479. } else {
  1480. $rv = $retval;
  1481. }
  1482. }
  1483. unset($retval); // Unset to prevent breaking render if there are no HOOK_RENDER_ENCLOSURE hooks below.
  1484. if ($rv === '' && !empty($result)) {
  1485. $entries_html = array();
  1486. $entries = array();
  1487. $entries_inline = array();
  1488. foreach ($result as $line) {
  1489. $url = $line["content_url"];
  1490. $ctype = $line["content_type"];
  1491. $title = $line["title"];
  1492. $width = $line["width"];
  1493. $height = $line["height"];
  1494. if (!$ctype) $ctype = __("unknown type");
  1495. $filename = substr($url, strrpos($url, "/")+1);
  1496. $player = format_inline_player($url, $ctype);
  1497. if ($player) array_push($entries_inline, $player);
  1498. # $entry .= " <a target=\"_blank\" href=\"" . htmlspecialchars($url) . "\">" .
  1499. # $filename . " (" . $ctype . ")" . "</a>";
  1500. $entry = "<div onclick=\"window.open('".htmlspecialchars($url)."')\"
  1501. dojoType=\"dijit.MenuItem\">$filename ($ctype)</div>";
  1502. array_push($entries_html, $entry);
  1503. $entry = array();
  1504. $entry["type"] = $ctype;
  1505. $entry["filename"] = $filename;
  1506. $entry["url"] = $url;
  1507. $entry["title"] = $title;
  1508. $entry["width"] = $width;
  1509. $entry["height"] = $height;
  1510. array_push($entries, $entry);
  1511. }
  1512. if ($_SESSION['uid'] && !get_pref("STRIP_IMAGES") && !$_SESSION["bw_limit"]) {
  1513. if ($always_display_enclosures ||
  1514. !preg_match("/<img/i", $article_content)) {
  1515. foreach ($entries as $entry) {
  1516. foreach (PluginHost::getInstance()->get_hooks(PluginHost::HOOK_RENDER_ENCLOSURE) as $plugin)
  1517. $retval = $plugin->hook_render_enclosure($entry, $hide_images);
  1518. if ($retval) {
  1519. $rv .= $retval;
  1520. } else {
  1521. if (preg_match("/image/", $entry["type"]) ||
  1522. preg_match("/\.(jpg|png|gif|bmp)/i", $entry["filename"])) {
  1523. if (!$hide_images) {
  1524. $encsize = '';
  1525. if ($entry['height'] > 0)
  1526. $encsize .= ' height="' . intval($entry['height']) . '"';
  1527. if ($entry['width'] > 0)
  1528. $encsize .= ' width="' . intval($entry['width']) . '"';
  1529. $rv .= "<p><img
  1530. alt=\"".htmlspecialchars($entry["filename"])."\"
  1531. src=\"" .htmlspecialchars($entry["url"]) . "\"
  1532. " . $encsize . " /></p>";
  1533. } else {
  1534. $rv .= "<p><a target=\"_blank\"
  1535. href=\"".htmlspecialchars($entry["url"])."\"
  1536. >" .htmlspecialchars($entry["url"]) . "</a></p>";
  1537. }
  1538. if ($entry['title']) {
  1539. $rv.= "<div class=\"enclosure_title\">${entry['title']}</div>";
  1540. }
  1541. }
  1542. }
  1543. }
  1544. }
  1545. }
  1546. if (count($entries_inline) > 0) {
  1547. $rv .= "<hr clear='both'/>";
  1548. foreach ($entries_inline as $entry) { $rv .= $entry; };
  1549. $rv .= "<hr clear='both'/>";
  1550. }
  1551. $rv .= "<div class=\"attachments\" dojoType=\"dijit.form.DropDownButton\">".
  1552. "<span>" . __('Attachments')."</span>";
  1553. $rv .= "<div dojoType=\"dijit.Menu\" style=\"display: none;\">";
  1554. foreach ($entries as $entry) {
  1555. if ($entry["title"])
  1556. $title = "&mdash; " . truncate_string($entry["title"], 30);
  1557. else
  1558. $title = "";
  1559. $rv .= "<div onclick='window.open(\"".htmlspecialchars($entry["url"])."\")'
  1560. dojoType=\"dijit.MenuItem\">".htmlspecialchars($entry["filename"])."$title</div>";
  1561. };
  1562. $rv .= "</div>";
  1563. $rv .= "</div>";
  1564. }
  1565. return $rv;
  1566. }
  1567. function getLastArticleId() {
  1568. $result = db_query("SELECT ref_id AS id FROM ttrss_user_entries
  1569. WHERE owner_uid = " . $_SESSION["uid"] . " ORDER BY ref_id DESC LIMIT 1");
  1570. if (db_num_rows($result) == 1) {
  1571. return db_fetch_result($result, 0, "id");
  1572. } else {
  1573. return -1;
  1574. }
  1575. }
  1576. function build_url($parts) {
  1577. return $parts['scheme'] . "://" . $parts['host'] . $parts['path'];
  1578. }
  1579. /**
  1580. * Converts a (possibly) relative URL to a absolute one.
  1581. *
  1582. * @param string $url Base URL (i.e. from where the document is)
  1583. * @param string $rel_url Possibly relative URL in the document
  1584. *
  1585. * @return string Absolute URL
  1586. */
  1587. function rewrite_relative_url($url, $rel_url) {
  1588. if (strpos($rel_url, "://") !== false) {
  1589. return $rel_url;
  1590. } else if (strpos($rel_url, "//") === 0) {
  1591. # protocol-relative URL (rare but they exist)
  1592. return $rel_url;
  1593. } else if (preg_match("/^[a-z]+:/i", $rel_url)) {
  1594. # magnet:, feed:, etc
  1595. return $rel_url;
  1596. } else if (strpos($rel_url, "/") === 0) {
  1597. $parts = parse_url($url);
  1598. $parts['path'] = $rel_url;
  1599. return build_url($parts);
  1600. } else {
  1601. $parts = parse_url($url);
  1602. if (!isset($parts['path'])) {
  1603. $parts['path'] = '/';
  1604. }
  1605. $dir = $parts['path'];
  1606. if (substr($dir, -1) !== '/') {
  1607. $dir = dirname($parts['path']);
  1608. $dir !== '/' && $dir .= '/';
  1609. }
  1610. $parts['path'] = $dir . $rel_url;
  1611. return build_url($parts);
  1612. }
  1613. }
  1614. function cleanup_tags($days = 14, $limit = 1000) {
  1615. if (DB_TYPE == "pgsql") {
  1616. $interval_query = "date_updated < NOW() - INTERVAL '$days days'";
  1617. } else if (DB_TYPE == "mysql") {
  1618. $interval_query = "date_updated < DATE_SUB(NOW(), INTERVAL $days DAY)";
  1619. }
  1620. $tags_deleted = 0;
  1621. while ($limit > 0) {
  1622. $limit_part = 500;
  1623. $query = "SELECT ttrss_tags.id AS id
  1624. FROM ttrss_tags, ttrss_user_entries, ttrss_entries
  1625. WHERE post_int_id = int_id AND $interval_query AND
  1626. ref_id = ttrss_entries.id AND tag_cache != '' LIMIT $limit_part";
  1627. $result = db_query($query);
  1628. $ids = array();
  1629. while ($line = db_fetch_assoc($result)) {
  1630. array_push($ids, $line['id']);
  1631. }
  1632. if (count($ids) > 0) {
  1633. $ids = join(",", $ids);
  1634. $tmp_result = db_query("DELETE FROM ttrss_tags WHERE id IN ($ids)");
  1635. $tags_deleted += db_affected_rows($tmp_result);
  1636. } else {
  1637. break;
  1638. }
  1639. $limit -= $limit_part;
  1640. }
  1641. return $tags_deleted;
  1642. }
  1643. function print_user_stylesheet() {
  1644. $value = get_pref('USER_STYLESHEET');
  1645. if ($value) {
  1646. print "<style type=\"text/css\">";
  1647. print str_replace("<br/>", "\n", $value);
  1648. print "</style>";
  1649. }
  1650. }
  1651. function filter_to_sql($filter, $owner_uid) {
  1652. $query = array();
  1653. if (DB_TYPE == "pgsql")
  1654. $reg_qpart = "~";
  1655. else
  1656. $reg_qpart = "REGEXP";
  1657. foreach ($filter["rules"] AS $rule) {
  1658. $rule['reg_exp'] = str_replace('/', '\/', $rule["reg_exp"]);
  1659. $regexp_valid = preg_match('/' . $rule['reg_exp'] . '/',
  1660. $rule['reg_exp']) !== FALSE;
  1661. if ($regexp_valid) {
  1662. $rule['reg_exp'] = db_escape_string($rule['reg_exp']);
  1663. switch ($rule["type"]) {
  1664. case "title":
  1665. $qpart = "LOWER(ttrss_entries.title) $reg_qpart LOWER('".
  1666. $rule['reg_exp'] . "')";
  1667. break;
  1668. case "content":
  1669. $qpart = "LOWER(ttrss_entries.content) $reg_qpart LOWER('".
  1670. $rule['reg_exp'] . "')";
  1671. break;
  1672. case "both":
  1673. $qpart = "LOWER(ttrss_entries.title) $reg_qpart LOWER('".
  1674. $rule['reg_exp'] . "') OR LOWER(" .
  1675. "ttrss_entries.content) $reg_qpart LOWER('" . $rule['reg_exp'] . "')";
  1676. break;
  1677. case "tag":
  1678. $qpart = "LOWER(ttrss_user_entries.tag_cache) $reg_qpart LOWER('".
  1679. $rule['reg_exp'] . "')";
  1680. break;
  1681. case "link":
  1682. $qpart = "LOWER(ttrss_entries.link) $reg_qpart LOWER('".
  1683. $rule['reg_exp'] . "')";
  1684. break;
  1685. case "author":
  1686. $qpart = "LOWER(ttrss_entries.author) $reg_qpart LOWER('".
  1687. $rule['reg_exp'] . "')";
  1688. break;
  1689. }
  1690. if (isset($rule['inverse'])) $qpart = "NOT ($qpart)";
  1691. if (isset($rule["feed_id"]) && $rule["feed_id"] > 0) {
  1692. $qpart .= " AND feed_id = " . db_escape_string($rule["feed_id"]);
  1693. }
  1694. if (isset($rule["cat_id"])) {
  1695. if ($rule["cat_id"] > 0) {
  1696. $children = getChildCategories($rule["cat_id"], $owner_uid);
  1697. array_push($children, $rule["cat_id"]);
  1698. $children = join(",", $children);
  1699. $cat_qpart = "cat_id IN ($children)";
  1700. } else {
  1701. $cat_qpart = "cat_id IS NULL";
  1702. }
  1703. $qpart .= " AND $cat_qpart";
  1704. }
  1705. $qpart .= " AND feed_id IS NOT NULL";
  1706. array_push($query, "($qpart)");
  1707. }
  1708. }
  1709. if (count($query) > 0) {
  1710. $fullquery = "(" . join($filter["match_any_rule"] ? "OR" : "AND", $query) . ")";
  1711. } else {
  1712. $fullquery = "(false)";
  1713. }
  1714. if ($filter['inverse']) $fullquery = "(NOT $fullquery)";
  1715. return $fullquery;
  1716. }
  1717. if (!function_exists('gzdecode')) {
  1718. function gzdecode($string) { // no support for 2nd argument
  1719. return file_get_contents('compress.zlib://data:who/cares;base64,'.
  1720. base64_encode($string));
  1721. }
  1722. }
  1723. function get_random_bytes($length) {
  1724. if (function_exists('openssl_random_pseudo_bytes')) {
  1725. return openssl_random_pseudo_bytes($length);
  1726. } else {
  1727. $output = "";
  1728. for ($i = 0; $i < $length; $i++)
  1729. $output .= chr(mt_rand(0, 255));
  1730. return $output;
  1731. }
  1732. }
  1733. function read_stdin() {
  1734. $fp = fopen("php://stdin", "r");
  1735. if ($fp) {
  1736. $line = trim(fgets($fp));
  1737. fclose($fp);
  1738. return $line;
  1739. }
  1740. return null;
  1741. }
  1742. function tmpdirname($path, $prefix) {
  1743. // Use PHP's tmpfile function to create a temporary
  1744. // directory name. Delete the file and keep the name.
  1745. $tempname = tempnam($path,$prefix);
  1746. if (!$tempname)
  1747. return false;
  1748. if (!unlink($tempname))
  1749. return false;
  1750. return $tempname;
  1751. }
  1752. function getFeedCategory($feed) {
  1753. $result = db_query("SELECT cat_id FROM ttrss_feeds
  1754. WHERE id = '$feed'");
  1755. if (db_num_rows($result) > 0) {
  1756. return db_fetch_result($result, 0, "cat_id");
  1757. } else {
  1758. return false;
  1759. }
  1760. }
  1761. function implements_interface($class, $interface) {
  1762. return in_array($interface, class_implements($class));
  1763. }
  1764. function get_minified_js($files) {
  1765. require_once 'lib/jshrink/Minifier.php';
  1766. $rv = '';
  1767. foreach ($files as $js) {
  1768. if (!isset($_GET['debug'])) {
  1769. $cached_file = CACHE_DIR . "/js/".basename($js).".js";
  1770. if (file_exists($cached_file) && is_readable($cached_file) && filemtime($cached_file) >= filemtime("js/$js.js")) {
  1771. list($header, $contents) = explode("\n", file_get_contents($cached_file), 2);
  1772. if ($header && $contents) {
  1773. list($htag, $hversion) = explode(":", $header);
  1774. if ($htag == "tt-rss" && $hversion == VERSION) {
  1775. $rv .= $contents;
  1776. continue;
  1777. }
  1778. }
  1779. }
  1780. $minified = JShrink\Minifier::minify(file_get_contents("js/$js.js"));
  1781. file_put_contents($cached_file, "tt-rss:" . VERSION . "\n" . $minified);
  1782. $rv .= $minified;
  1783. } else {
  1784. $rv .= file_get_contents("js/$js.js"); // no cache in debug mode
  1785. }
  1786. }
  1787. return $rv;
  1788. }
  1789. function stylesheet_tag($filename) {
  1790. $timestamp = filemtime($filename);
  1791. return "<link rel=\"stylesheet\" type=\"text/css\" href=\"$filename?$timestamp\"/>\n";
  1792. }
  1793. function javascript_tag($filename) {
  1794. $query = "";
  1795. if (!(strpos($filename, "?") === FALSE)) {
  1796. $query = substr($filename, strpos($filename, "?")+1);
  1797. $filename = substr($filename, 0, strpos($filename, "?"));
  1798. }
  1799. $timestamp = filemtime($filename);
  1800. if ($query) $timestamp .= "&$query";
  1801. return "<script type=\"text/javascript\" charset=\"utf-8\" src=\"$filename?$timestamp\"></script>\n";
  1802. }
  1803. function calculate_dep_timestamp() {
  1804. $files = array_merge(glob("js/*.js"), glob("css/*.css"));
  1805. $max_ts = -1;
  1806. foreach ($files as $file) {
  1807. if (filemtime($file) > $max_ts) $max_ts = filemtime($file);
  1808. }
  1809. return $max_ts;
  1810. }
  1811. function T_js_decl($s1, $s2) {
  1812. if ($s1 && $s2) {
  1813. $s1 = preg_replace("/\n/", "", $s1);
  1814. $s2 = preg_replace("/\n/", "", $s2);
  1815. $s1 = preg_replace("/\"/", "\\\"", $s1);
  1816. $s2 = preg_replace("/\"/", "\\\"", $s2);
  1817. return "T_messages[\"$s1\"] = \"$s2\";\n";
  1818. }
  1819. }
  1820. function init_js_translations() {
  1821. print 'var T_messages = new Object();
  1822. function __(msg) {
  1823. if (T_messages[msg]) {
  1824. return T_messages[msg];
  1825. } else {
  1826. return msg;
  1827. }
  1828. }
  1829. function ngettext(msg1, msg2, n) {
  1830. return __((parseInt(n) > 1) ? msg2 : msg1);
  1831. }';
  1832. $l10n = _get_reader();
  1833. for ($i = 0; $i < $l10n->total; $i++) {
  1834. $orig = $l10n->get_original_string($i);
  1835. if(strpos($orig, "\000") !== FALSE) { // Plural forms
  1836. $key = explode(chr(0), $orig);
  1837. print T_js_decl($key[0], _ngettext($key[0], $key[1], 1)); // Singular
  1838. print T_js_decl($key[1], _ngettext($key[0], $key[1], 2)); // Plural
  1839. } else {
  1840. $translation = __($orig);
  1841. print T_js_decl($orig, $translation);
  1842. }
  1843. }
  1844. }
  1845. function label_to_feed_id($label) {
  1846. return LABEL_BASE_INDEX - 1 - abs($label);
  1847. }
  1848. function feed_to_label_id($feed) {
  1849. return LABEL_BASE_INDEX - 1 + abs($feed);
  1850. }
  1851. function get_theme_path($theme) {
  1852. $check = "themes/$theme";
  1853. if (file_exists($check)) return $check;
  1854. $check = "themes.local/$theme";
  1855. if (file_exists($check)) return $check;
  1856. }
  1857. function theme_valid($theme) {
  1858. if ($theme == "default.css" || $theme == "night.css") return true; // needed for array_filter
  1859. $file = "themes/" . basename($theme);
  1860. if (!file_exists($file)) $file = "themes.local/" . basename($theme);
  1861. if (file_exists($file) && is_readable($file)) {
  1862. $fh = fopen($file, "r");
  1863. if ($fh) {
  1864. $header = fgets($fh);
  1865. fclose($fh);
  1866. return strpos($header, "supports-version:" . VERSION_STATIC) !== FALSE;
  1867. }
  1868. }
  1869. return false;
  1870. }
  1871. function error_json($code) {
  1872. require_once "errors.php";
  1873. @$message = $ERRORS[$code];
  1874. return json_encode(array("error" =>
  1875. array("code" => $code, "message" => $message)));
  1876. }
  1877. function abs_to_rel_path($dir) {
  1878. $tmp = str_replace(dirname(__DIR__), "", $dir);
  1879. if (strlen($tmp) > 0 && substr($tmp, 0, 1) == "/") $tmp = substr($tmp, 1);
  1880. return $tmp;
  1881. }
  1882. function get_upload_error_message($code) {
  1883. $errors = array(
  1884. 0 => __('There is no error, the file uploaded with success'),
  1885. 1 => __('The uploaded file exceeds the upload_max_filesize directive in php.ini'),
  1886. 2 => __('The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form'),
  1887. 3 => __('The uploaded file was only partially uploaded'),
  1888. 4 => __('No file was uploaded'),
  1889. 6 => __('Missing a temporary folder'),
  1890. 7 => __('Failed to write file to disk.'),
  1891. 8 => __('A PHP extension stopped the file upload.'),
  1892. );
  1893. return $errors[$code];
  1894. }
  1895. ?>