functions2.php 67 KB

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