functions2.php 67 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446
  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(array("url" => "http://tt-rss.org/version.json", "timeout" => 5));
  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($disable_update_check = false) {
  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 && !$disable_update_check && $_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. /* strip everything outside of <body>...</body> */
  837. $res_frag = array();
  838. if (preg_match('/<body>(.*)<\/body>/is', $res, $res_frag)) {
  839. return $res_frag[1];
  840. } else {
  841. return $res;
  842. }
  843. }
  844. function strip_harmful_tags($doc, $allowed_elements, $disallowed_attributes) {
  845. $xpath = new DOMXPath($doc);
  846. $entries = $xpath->query('//*');
  847. foreach ($entries as $entry) {
  848. if (!in_array($entry->nodeName, $allowed_elements)) {
  849. $entry->parentNode->removeChild($entry);
  850. }
  851. if ($entry->hasAttributes()) {
  852. $attrs_to_remove = array();
  853. foreach ($entry->attributes as $attr) {
  854. if (strpos($attr->nodeName, 'on') === 0) {
  855. array_push($attrs_to_remove, $attr);
  856. }
  857. if (in_array($attr->nodeName, $disallowed_attributes)) {
  858. array_push($attrs_to_remove, $attr);
  859. }
  860. }
  861. foreach ($attrs_to_remove as $attr) {
  862. $entry->removeAttributeNode($attr);
  863. }
  864. }
  865. }
  866. return $doc;
  867. }
  868. function catchupArticlesById($ids, $cmode, $owner_uid = false) {
  869. if (!$owner_uid) $owner_uid = $_SESSION["uid"];
  870. if (count($ids) == 0) return;
  871. $tmp_ids = array();
  872. foreach ($ids as $id) {
  873. array_push($tmp_ids, "ref_id = '$id'");
  874. }
  875. $ids_qpart = join(" OR ", $tmp_ids);
  876. if ($cmode == 0) {
  877. db_query("UPDATE ttrss_user_entries SET
  878. unread = false,last_read = NOW()
  879. WHERE ($ids_qpart) AND owner_uid = $owner_uid");
  880. } else if ($cmode == 1) {
  881. db_query("UPDATE ttrss_user_entries SET
  882. unread = true
  883. WHERE ($ids_qpart) AND owner_uid = $owner_uid");
  884. } else {
  885. db_query("UPDATE ttrss_user_entries SET
  886. unread = NOT unread,last_read = NOW()
  887. WHERE ($ids_qpart) AND owner_uid = $owner_uid");
  888. }
  889. /* update ccache */
  890. $result = db_query("SELECT DISTINCT feed_id FROM ttrss_user_entries
  891. WHERE ($ids_qpart) AND owner_uid = $owner_uid");
  892. while ($line = db_fetch_assoc($result)) {
  893. ccache_update($line["feed_id"], $owner_uid);
  894. }
  895. }
  896. function get_article_tags($id, $owner_uid = 0, $tag_cache = false) {
  897. $a_id = db_escape_string($id);
  898. if (!$owner_uid) $owner_uid = $_SESSION["uid"];
  899. $query = "SELECT DISTINCT tag_name,
  900. owner_uid as owner FROM
  901. ttrss_tags WHERE post_int_id = (SELECT int_id FROM ttrss_user_entries WHERE
  902. ref_id = '$a_id' AND owner_uid = '$owner_uid' LIMIT 1) ORDER BY tag_name";
  903. $tags = array();
  904. /* check cache first */
  905. if ($tag_cache === false) {
  906. $result = db_query("SELECT tag_cache FROM ttrss_user_entries
  907. WHERE ref_id = '$id' AND owner_uid = $owner_uid");
  908. if (db_num_rows($result) != 0)
  909. $tag_cache = db_fetch_result($result, 0, "tag_cache");
  910. }
  911. if ($tag_cache) {
  912. $tags = explode(",", $tag_cache);
  913. } else {
  914. /* do it the hard way */
  915. $tmp_result = db_query($query);
  916. while ($tmp_line = db_fetch_assoc($tmp_result)) {
  917. array_push($tags, $tmp_line["tag_name"]);
  918. }
  919. /* update the cache */
  920. $tags_str = db_escape_string(join(",", $tags));
  921. db_query("UPDATE ttrss_user_entries
  922. SET tag_cache = '$tags_str' WHERE ref_id = '$id'
  923. AND owner_uid = $owner_uid");
  924. }
  925. return $tags;
  926. }
  927. function trim_array($array) {
  928. $tmp = $array;
  929. array_walk($tmp, 'trim');
  930. return $tmp;
  931. }
  932. function tag_is_valid($tag) {
  933. if ($tag == '') return false;
  934. if (is_numeric($tag)) return false;
  935. if (mb_strlen($tag) > 250) return false;
  936. if (!$tag) return false;
  937. return true;
  938. }
  939. function render_login_form() {
  940. header('Cache-Control: public');
  941. require_once "login_form.php";
  942. exit;
  943. }
  944. function format_warning($msg, $id = "") {
  945. return "<div class=\"alert\" id=\"$id\">$msg</div>";
  946. }
  947. function format_notice($msg, $id = "") {
  948. return "<div class=\"alert alert-info\" id=\"$id\">$msg</div>";
  949. }
  950. function format_error($msg, $id = "") {
  951. return "<div class=\"alert alert-danger\" id=\"$id\">$msg</div>";
  952. }
  953. function print_notice($msg) {
  954. return print format_notice($msg);
  955. }
  956. function print_warning($msg) {
  957. return print format_warning($msg);
  958. }
  959. function print_error($msg) {
  960. return print format_error($msg);
  961. }
  962. function T_sprintf() {
  963. $args = func_get_args();
  964. return vsprintf(__(array_shift($args)), $args);
  965. }
  966. function format_inline_player($url, $ctype) {
  967. $entry = "";
  968. $url = htmlspecialchars($url);
  969. if (strpos($ctype, "audio/") === 0) {
  970. if ($_SESSION["hasAudio"] && (strpos($ctype, "ogg") !== false ||
  971. $_SESSION["hasMp3"])) {
  972. $entry .= "<audio preload=\"none\" controls>
  973. <source type=\"$ctype\" src=\"$url\"/>
  974. </audio>";
  975. } else {
  976. $entry .= "<object type=\"application/x-shockwave-flash\"
  977. data=\"lib/button/musicplayer.swf?song_url=$url\"
  978. width=\"17\" height=\"17\" style='float : left; margin-right : 5px;'>
  979. <param name=\"movie\"
  980. value=\"lib/button/musicplayer.swf?song_url=$url\" />
  981. </object>";
  982. }
  983. if ($entry) $entry .= "&nbsp; <a target=\"_blank\"
  984. href=\"$url\">" . basename($url) . "</a>";
  985. return $entry;
  986. }
  987. return "";
  988. /* $filename = substr($url, strrpos($url, "/")+1);
  989. $entry .= " <a target=\"_blank\" href=\"" . htmlspecialchars($url) . "\">" .
  990. $filename . " (" . $ctype . ")" . "</a>"; */
  991. }
  992. function format_article($id, $mark_as_read = true, $zoom_mode = false, $owner_uid = false) {
  993. if (!$owner_uid) $owner_uid = $_SESSION["uid"];
  994. $rv = array();
  995. $rv['id'] = $id;
  996. /* we can figure out feed_id from article id anyway, why do we
  997. * pass feed_id here? let's ignore the argument :(*/
  998. $result = db_query("SELECT feed_id FROM ttrss_user_entries
  999. WHERE ref_id = '$id'");
  1000. $feed_id = (int) db_fetch_result($result, 0, "feed_id");
  1001. $rv['feed_id'] = $feed_id;
  1002. //if (!$zoom_mode) { print "<article id='$id'><![CDATA["; };
  1003. if ($mark_as_read) {
  1004. $result = db_query("UPDATE ttrss_user_entries
  1005. SET unread = false,last_read = NOW()
  1006. WHERE ref_id = '$id' AND owner_uid = $owner_uid");
  1007. ccache_update($feed_id, $owner_uid);
  1008. }
  1009. $result = db_query("SELECT id,title,link,content,feed_id,comments,int_id,lang,
  1010. ".SUBSTRING_FOR_DATE."(updated,1,16) as updated,
  1011. (SELECT site_url FROM ttrss_feeds WHERE id = feed_id) as site_url,
  1012. (SELECT title FROM ttrss_feeds WHERE id = feed_id) as feed_title,
  1013. (SELECT hide_images FROM ttrss_feeds WHERE id = feed_id) as hide_images,
  1014. (SELECT always_display_enclosures FROM ttrss_feeds WHERE id = feed_id) as always_display_enclosures,
  1015. num_comments,
  1016. tag_cache,
  1017. author,
  1018. orig_feed_id,
  1019. note
  1020. FROM ttrss_entries,ttrss_user_entries
  1021. WHERE id = '$id' AND ref_id = id AND owner_uid = $owner_uid");
  1022. if ($result) {
  1023. $line = db_fetch_assoc($result);
  1024. $line["tags"] = get_article_tags($id, $owner_uid, $line["tag_cache"]);
  1025. unset($line["tag_cache"]);
  1026. $line["content"] = sanitize($line["content"],
  1027. sql_bool_to_bool($line['hide_images']),
  1028. $owner_uid, $line["site_url"], false, $line["id"]);
  1029. foreach (PluginHost::getInstance()->get_hooks(PluginHost::HOOK_RENDER_ARTICLE) as $p) {
  1030. $line = $p->hook_render_article($line);
  1031. }
  1032. $num_comments = $line["num_comments"];
  1033. $entry_comments = "";
  1034. if ($num_comments > 0) {
  1035. if ($line["comments"]) {
  1036. $comments_url = htmlspecialchars($line["comments"]);
  1037. } else {
  1038. $comments_url = htmlspecialchars($line["link"]);
  1039. }
  1040. $entry_comments = "<a class=\"postComments\"
  1041. target='_blank' href=\"$comments_url\">$num_comments ".
  1042. _ngettext("comment", "comments", $num_comments)."</a>";
  1043. } else {
  1044. if ($line["comments"] && $line["link"] != $line["comments"]) {
  1045. $entry_comments = "<a class=\"postComments\" target='_blank' href=\"".htmlspecialchars($line["comments"])."\">".__("comments")."</a>";
  1046. }
  1047. }
  1048. if ($zoom_mode) {
  1049. header("Content-Type: text/html");
  1050. $rv['content'] .= "<html><head>
  1051. <meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\"/>
  1052. <title>Tiny Tiny RSS - ".$line["title"]."</title>".
  1053. stylesheet_tag("css/tt-rss.css").
  1054. stylesheet_tag("css/zoom.css").
  1055. stylesheet_tag("css/dijit.css")."
  1056. <link rel=\"shortcut icon\" type=\"image/png\" href=\"images/favicon.png\">
  1057. <link rel=\"icon\" type=\"image/png\" sizes=\"72x72\" href=\"images/favicon-72px.png\">
  1058. </head><body id=\"ttrssZoom\">";
  1059. }
  1060. $rv['content'] .= "<div class=\"postReply\" id=\"POST-$id\">";
  1061. $rv['content'] .= "<div class=\"postHeader\" id=\"POSTHDR-$id\">";
  1062. $entry_author = $line["author"];
  1063. if ($entry_author) {
  1064. $entry_author = __(" - ") . $entry_author;
  1065. }
  1066. $parsed_updated = make_local_datetime($line["updated"], true,
  1067. $owner_uid, true);
  1068. if (!$zoom_mode)
  1069. $rv['content'] .= "<div class=\"postDate\">$parsed_updated</div>";
  1070. if ($line["link"]) {
  1071. $rv['content'] .= "<div class='postTitle'><a target='_blank'
  1072. title=\"".htmlspecialchars($line['title'])."\"
  1073. href=\"" .
  1074. htmlspecialchars($line["link"]) . "\">" .
  1075. $line["title"] . "</a>" .
  1076. "<span class='author'>$entry_author</span></div>";
  1077. } else {
  1078. $rv['content'] .= "<div class='postTitle'>" . $line["title"] . "$entry_author</div>";
  1079. }
  1080. if ($zoom_mode) {
  1081. $feed_title = "<a href=\"".htmlspecialchars($line["site_url"]).
  1082. "\" target=\"_blank\">".
  1083. htmlspecialchars($line["feed_title"])."</a>";
  1084. $rv['content'] .= "<div class=\"postFeedTitle\">$feed_title</div>";
  1085. $rv['content'] .= "<div class=\"postDate\">$parsed_updated</div>";
  1086. }
  1087. $tags_str = format_tags_string($line["tags"], $id);
  1088. $tags_str_full = join(", ", $line["tags"]);
  1089. if (!$tags_str_full) $tags_str_full = __("no tags");
  1090. if (!$entry_comments) $entry_comments = "&nbsp;"; # placeholder
  1091. $rv['content'] .= "<div class='postTags' style='float : right'>
  1092. <img src='images/tag.png'
  1093. class='tagsPic' alt='Tags' title='Tags'>&nbsp;";
  1094. if (!$zoom_mode) {
  1095. $rv['content'] .= "<span id=\"ATSTR-$id\">$tags_str</span>
  1096. <a title=\"".__('Edit tags for this article')."\"
  1097. href=\"#\" onclick=\"editArticleTags($id, $feed_id)\">(+)</a>";
  1098. $rv['content'] .= "<div dojoType=\"dijit.Tooltip\"
  1099. id=\"ATSTRTIP-$id\" connectId=\"ATSTR-$id\"
  1100. position=\"below\">$tags_str_full</div>";
  1101. foreach (PluginHost::getInstance()->get_hooks(PluginHost::HOOK_ARTICLE_BUTTON) as $p) {
  1102. $rv['content'] .= $p->hook_article_button($line);
  1103. }
  1104. } else {
  1105. $tags_str = strip_tags($tags_str);
  1106. $rv['content'] .= "<span id=\"ATSTR-$id\">$tags_str</span>";
  1107. }
  1108. $rv['content'] .= "</div>";
  1109. $rv['content'] .= "<div clear='both'>";
  1110. foreach (PluginHost::getInstance()->get_hooks(PluginHost::HOOK_ARTICLE_LEFT_BUTTON) as $p) {
  1111. $rv['content'] .= $p->hook_article_left_button($line);
  1112. }
  1113. $rv['content'] .= "$entry_comments</div>";
  1114. if ($line["orig_feed_id"]) {
  1115. $tmp_result = db_query("SELECT * FROM ttrss_archived_feeds
  1116. WHERE id = ".$line["orig_feed_id"] . " AND owner_uid = " . $_SESSION["uid"]);
  1117. if (db_num_rows($tmp_result) != 0) {
  1118. $rv['content'] .= "<div clear='both'>";
  1119. $rv['content'] .= __("Originally from:");
  1120. $rv['content'] .= "&nbsp;";
  1121. $tmp_line = db_fetch_assoc($tmp_result);
  1122. $rv['content'] .= "<a target='_blank'
  1123. href=' " . htmlspecialchars($tmp_line['site_url']) . "'>" .
  1124. $tmp_line['title'] . "</a>";
  1125. $rv['content'] .= "&nbsp;";
  1126. $rv['content'] .= "<a target='_blank' href='" . htmlspecialchars($tmp_line['feed_url']) . "'>";
  1127. $rv['content'] .= "<img title='".__('Feed URL')."' class='tinyFeedIcon' src='images/pub_set.png'></a>";
  1128. $rv['content'] .= "</div>";
  1129. }
  1130. }
  1131. $rv['content'] .= "</div>";
  1132. $rv['content'] .= "<div id=\"POSTNOTE-$id\">";
  1133. if ($line['note']) {
  1134. $rv['content'] .= format_article_note($id, $line['note'], !$zoom_mode);
  1135. }
  1136. $rv['content'] .= "</div>";
  1137. if (!$line['lang']) $line['lang'] = 'en';
  1138. $rv['content'] .= "<div class=\"postContent\" lang=\"".$line['lang']."\">";
  1139. $rv['content'] .= $line["content"];
  1140. if (!$zoom_mode) {
  1141. $rv['content'] .= format_article_enclosures($id,
  1142. sql_bool_to_bool($line["always_display_enclosures"]),
  1143. $line["content"],
  1144. sql_bool_to_bool($line["hide_images"]));
  1145. }
  1146. $rv['content'] .= "</div>";
  1147. $rv['content'] .= "</div>";
  1148. }
  1149. if ($zoom_mode) {
  1150. $rv['content'] .= "
  1151. <div class='footer'>
  1152. <button onclick=\"return window.close()\">".
  1153. __("Close this window")."</button></div>";
  1154. $rv['content'] .= "</body></html>";
  1155. }
  1156. return $rv;
  1157. }
  1158. function print_checkpoint($n, $s) {
  1159. $ts = microtime(true);
  1160. echo sprintf("<!-- CP[$n] %.4f seconds -->\n", $ts - $s);
  1161. return $ts;
  1162. }
  1163. function sanitize_tag($tag) {
  1164. $tag = trim($tag);
  1165. $tag = mb_strtolower($tag, 'utf-8');
  1166. $tag = preg_replace('/[,\'\"\+\>\<]/', "", $tag);
  1167. if (DB_TYPE == "mysql") {
  1168. $tag = preg_replace('/[\x{10000}-\x{10FFFF}]/u', "\xEF\xBF\xBD", $tag);
  1169. }
  1170. return $tag;
  1171. }
  1172. function get_self_url_prefix() {
  1173. if (strrpos(SELF_URL_PATH, "/") === strlen(SELF_URL_PATH)-1) {
  1174. return substr(SELF_URL_PATH, 0, strlen(SELF_URL_PATH)-1);
  1175. } else {
  1176. return SELF_URL_PATH;
  1177. }
  1178. }
  1179. /**
  1180. * Compute the Mozilla Firefox feed adding URL from server HOST and REQUEST_URI.
  1181. *
  1182. * @return string The Mozilla Firefox feed adding URL.
  1183. */
  1184. function add_feed_url() {
  1185. //$url_path = ($_SERVER['HTTPS'] != "on" ? 'http://' : 'https://') . $_SERVER["HTTP_HOST"] . parse_url($_SERVER["REQUEST_URI"], PHP_URL_PATH);
  1186. $url_path = get_self_url_prefix() .
  1187. "/public.php?op=subscribe&feed_url=%s";
  1188. return $url_path;
  1189. } // function add_feed_url
  1190. function encrypt_password($pass, $salt = '', $mode2 = false) {
  1191. if ($salt && $mode2) {
  1192. return "MODE2:" . hash('sha256', $salt . $pass);
  1193. } else if ($salt) {
  1194. return "SHA1X:" . sha1("$salt:$pass");
  1195. } else {
  1196. return "SHA1:" . sha1($pass);
  1197. }
  1198. } // function encrypt_password
  1199. function load_filters($feed_id, $owner_uid, $action_id = false) {
  1200. $filters = array();
  1201. $cat_id = (int)getFeedCategory($feed_id);
  1202. if ($cat_id == 0)
  1203. $null_cat_qpart = "cat_id IS NULL OR";
  1204. else
  1205. $null_cat_qpart = "";
  1206. $result = db_query("SELECT * FROM ttrss_filters2 WHERE
  1207. owner_uid = $owner_uid AND enabled = true ORDER BY order_id, title");
  1208. $check_cats = join(",", array_merge(
  1209. getParentCategories($cat_id, $owner_uid),
  1210. array($cat_id)));
  1211. while ($line = db_fetch_assoc($result)) {
  1212. $filter_id = $line["id"];
  1213. $result2 = db_query("SELECT
  1214. r.reg_exp, r.inverse, r.feed_id, r.cat_id, r.cat_filter, t.name AS type_name
  1215. FROM ttrss_filters2_rules AS r,
  1216. ttrss_filter_types AS t
  1217. WHERE
  1218. ($null_cat_qpart (cat_id IS NULL AND cat_filter = false) OR cat_id IN ($check_cats)) AND
  1219. (feed_id IS NULL OR feed_id = '$feed_id') AND
  1220. filter_type = t.id AND filter_id = '$filter_id'");
  1221. $rules = array();
  1222. $actions = array();
  1223. while ($rule_line = db_fetch_assoc($result2)) {
  1224. # print_r($rule_line);
  1225. $rule = array();
  1226. $rule["reg_exp"] = $rule_line["reg_exp"];
  1227. $rule["type"] = $rule_line["type_name"];
  1228. $rule["inverse"] = sql_bool_to_bool($rule_line["inverse"]);
  1229. array_push($rules, $rule);
  1230. }
  1231. $result2 = db_query("SELECT a.action_param,t.name AS type_name
  1232. FROM ttrss_filters2_actions AS a,
  1233. ttrss_filter_actions AS t
  1234. WHERE
  1235. action_id = t.id AND filter_id = '$filter_id'");
  1236. while ($action_line = db_fetch_assoc($result2)) {
  1237. # print_r($action_line);
  1238. $action = array();
  1239. $action["type"] = $action_line["type_name"];
  1240. $action["param"] = $action_line["action_param"];
  1241. array_push($actions, $action);
  1242. }
  1243. $filter = array();
  1244. $filter["match_any_rule"] = sql_bool_to_bool($line["match_any_rule"]);
  1245. $filter["inverse"] = sql_bool_to_bool($line["inverse"]);
  1246. $filter["rules"] = $rules;
  1247. $filter["actions"] = $actions;
  1248. if (count($rules) > 0 && count($actions) > 0) {
  1249. array_push($filters, $filter);
  1250. }
  1251. }
  1252. return $filters;
  1253. }
  1254. function get_score_pic($score) {
  1255. if ($score > 100) {
  1256. return "score_high.png";
  1257. } else if ($score > 0) {
  1258. return "score_half_high.png";
  1259. } else if ($score < -100) {
  1260. return "score_low.png";
  1261. } else if ($score < 0) {
  1262. return "score_half_low.png";
  1263. } else {
  1264. return "score_neutral.png";
  1265. }
  1266. }
  1267. function feed_has_icon($id) {
  1268. return is_file(ICONS_DIR . "/$id.ico") && filesize(ICONS_DIR . "/$id.ico") > 0;
  1269. }
  1270. function init_plugins() {
  1271. PluginHost::getInstance()->load(PLUGINS, PluginHost::KIND_ALL);
  1272. return true;
  1273. }
  1274. function format_tags_string($tags, $id) {
  1275. if (!is_array($tags) || count($tags) == 0) {
  1276. return __("no tags");
  1277. } else {
  1278. $maxtags = min(5, count($tags));
  1279. $tags_str = "";
  1280. for ($i = 0; $i < $maxtags; $i++) {
  1281. $tags_str .= "<a class=\"tag\" href=\"#\" onclick=\"viewfeed({feed:'".$tags[$i]."'})\">" . $tags[$i] . "</a>, ";
  1282. }
  1283. $tags_str = mb_substr($tags_str, 0, mb_strlen($tags_str)-2);
  1284. if (count($tags) > $maxtags)
  1285. $tags_str .= ", &hellip;";
  1286. return $tags_str;
  1287. }
  1288. }
  1289. function format_article_labels($labels, $id) {
  1290. if (!is_array($labels)) return '';
  1291. $labels_str = "";
  1292. foreach ($labels as $l) {
  1293. $labels_str .= sprintf("<span class='hlLabelRef'
  1294. style='color : %s; background-color : %s'>%s</span>",
  1295. $l[2], $l[3], $l[1]);
  1296. }
  1297. return $labels_str;
  1298. }
  1299. function format_article_note($id, $note, $allow_edit = true) {
  1300. $str = "<div class='articleNote' onclick=\"editArticleNote($id)\">
  1301. <div class='noteEdit' onclick=\"editArticleNote($id)\">".
  1302. ($allow_edit ? __('(edit note)') : "")."</div>$note</div>";
  1303. return $str;
  1304. }
  1305. function get_feed_category($feed_cat, $parent_cat_id = false) {
  1306. if ($parent_cat_id) {
  1307. $parent_qpart = "parent_cat = '$parent_cat_id'";
  1308. $parent_insert = "'$parent_cat_id'";
  1309. } else {
  1310. $parent_qpart = "parent_cat IS NULL";
  1311. $parent_insert = "NULL";
  1312. }
  1313. $result = db_query(
  1314. "SELECT id FROM ttrss_feed_categories
  1315. WHERE $parent_qpart AND title = '$feed_cat' AND owner_uid = ".$_SESSION["uid"]);
  1316. if (db_num_rows($result) == 0) {
  1317. return false;
  1318. } else {
  1319. return db_fetch_result($result, 0, "id");
  1320. }
  1321. }
  1322. function add_feed_category($feed_cat, $parent_cat_id = false) {
  1323. if (!$feed_cat) return false;
  1324. db_query("BEGIN");
  1325. if ($parent_cat_id) {
  1326. $parent_qpart = "parent_cat = '$parent_cat_id'";
  1327. $parent_insert = "'$parent_cat_id'";
  1328. } else {
  1329. $parent_qpart = "parent_cat IS NULL";
  1330. $parent_insert = "NULL";
  1331. }
  1332. $feed_cat = mb_substr($feed_cat, 0, 250);
  1333. $result = db_query(
  1334. "SELECT id FROM ttrss_feed_categories
  1335. WHERE $parent_qpart AND title = '$feed_cat' AND owner_uid = ".$_SESSION["uid"]);
  1336. if (db_num_rows($result) == 0) {
  1337. $result = db_query(
  1338. "INSERT INTO ttrss_feed_categories (owner_uid,title,parent_cat)
  1339. VALUES ('".$_SESSION["uid"]."', '$feed_cat', $parent_insert)");
  1340. db_query("COMMIT");
  1341. return true;
  1342. }
  1343. return false;
  1344. }
  1345. function getArticleFeed($id) {
  1346. $result = db_query("SELECT feed_id FROM ttrss_user_entries
  1347. WHERE ref_id = '$id' AND owner_uid = " . $_SESSION["uid"]);
  1348. if (db_num_rows($result) != 0) {
  1349. return db_fetch_result($result, 0, "feed_id");
  1350. } else {
  1351. return 0;
  1352. }
  1353. }
  1354. /**
  1355. * Fixes incomplete URLs by prepending "http://".
  1356. * Also replaces feed:// with http://, and
  1357. * prepends a trailing slash if the url is a domain name only.
  1358. *
  1359. * @param string $url Possibly incomplete URL
  1360. *
  1361. * @return string Fixed URL.
  1362. */
  1363. function fix_url($url) {
  1364. // support schema-less urls
  1365. if (strpos($url, '//') === 0) {
  1366. $url = 'https:' . $url;
  1367. }
  1368. if (strpos($url, '://') === false) {
  1369. $url = 'http://' . $url;
  1370. } else if (substr($url, 0, 5) == 'feed:') {
  1371. $url = 'http:' . substr($url, 5);
  1372. }
  1373. //prepend slash if the URL has no slash in it
  1374. // "http://www.example" -> "http://www.example/"
  1375. if (strpos($url, '/', strpos($url, ':') + 3) === false) {
  1376. $url .= '/';
  1377. }
  1378. if ($url != "http:///")
  1379. return $url;
  1380. else
  1381. return '';
  1382. }
  1383. function validate_feed_url($url) {
  1384. $parts = parse_url($url);
  1385. return ($parts['scheme'] == 'http' || $parts['scheme'] == 'feed' || $parts['scheme'] == 'https');
  1386. }
  1387. function get_article_enclosures($id) {
  1388. $query = "SELECT * FROM ttrss_enclosures
  1389. WHERE post_id = '$id' AND content_url != ''";
  1390. $rv = array();
  1391. $result = db_query($query);
  1392. if (db_num_rows($result) > 0) {
  1393. while ($line = db_fetch_assoc($result)) {
  1394. array_push($rv, $line);
  1395. }
  1396. }
  1397. return $rv;
  1398. }
  1399. /* function save_email_address($email) {
  1400. // FIXME: implement persistent storage of emails
  1401. if (!$_SESSION['stored_emails'])
  1402. $_SESSION['stored_emails'] = array();
  1403. if (!in_array($email, $_SESSION['stored_emails']))
  1404. array_push($_SESSION['stored_emails'], $email);
  1405. } */
  1406. function get_feed_access_key($feed_id, $is_cat, $owner_uid = false) {
  1407. if (!$owner_uid) $owner_uid = $_SESSION["uid"];
  1408. $sql_is_cat = bool_to_sql_bool($is_cat);
  1409. $result = db_query("SELECT access_key FROM ttrss_access_keys
  1410. WHERE feed_id = '$feed_id' AND is_cat = $sql_is_cat
  1411. AND owner_uid = " . $owner_uid);
  1412. if (db_num_rows($result) == 1) {
  1413. return db_fetch_result($result, 0, "access_key");
  1414. } else {
  1415. $key = db_escape_string(uniqid_short());
  1416. $result = db_query("INSERT INTO ttrss_access_keys
  1417. (access_key, feed_id, is_cat, owner_uid)
  1418. VALUES ('$key', '$feed_id', $sql_is_cat, '$owner_uid')");
  1419. return $key;
  1420. }
  1421. return false;
  1422. }
  1423. function get_feeds_from_html($url, $content)
  1424. {
  1425. $url = fix_url($url);
  1426. $baseUrl = substr($url, 0, strrpos($url, '/') + 1);
  1427. libxml_use_internal_errors(true);
  1428. $doc = new DOMDocument();
  1429. $doc->loadHTML($content);
  1430. $xpath = new DOMXPath($doc);
  1431. $entries = $xpath->query('/html/head/link[@rel="alternate" and '.
  1432. '(contains(@type,"rss") or contains(@type,"atom"))]|/html/head/link[@rel="feed"]');
  1433. $feedUrls = array();
  1434. foreach ($entries as $entry) {
  1435. if ($entry->hasAttribute('href')) {
  1436. $title = $entry->getAttribute('title');
  1437. if ($title == '') {
  1438. $title = $entry->getAttribute('type');
  1439. }
  1440. $feedUrl = rewrite_relative_url(
  1441. $baseUrl, $entry->getAttribute('href')
  1442. );
  1443. $feedUrls[$feedUrl] = $title;
  1444. }
  1445. }
  1446. return $feedUrls;
  1447. }
  1448. function is_html($content) {
  1449. return preg_match("/<html|DOCTYPE html/i", substr($content, 0, 100)) !== 0;
  1450. }
  1451. function url_is_html($url, $login = false, $pass = false) {
  1452. return is_html(fetch_file_contents($url, false, $login, $pass));
  1453. }
  1454. function print_label_select($name, $value, $attributes = "") {
  1455. $result = db_query("SELECT caption FROM ttrss_labels2
  1456. WHERE owner_uid = '".$_SESSION["uid"]."' ORDER BY caption");
  1457. print "<select default=\"$value\" name=\"" . htmlspecialchars($name) .
  1458. "\" $attributes onchange=\"labelSelectOnChange(this)\" >";
  1459. while ($line = db_fetch_assoc($result)) {
  1460. $issel = ($line["caption"] == $value) ? "selected=\"1\"" : "";
  1461. print "<option value=\"".htmlspecialchars($line["caption"])."\"
  1462. $issel>" . htmlspecialchars($line["caption"]) . "</option>";
  1463. }
  1464. # print "<option value=\"ADD_LABEL\">" .__("Add label...") . "</option>";
  1465. print "</select>";
  1466. }
  1467. function format_article_enclosures($id, $always_display_enclosures,
  1468. $article_content, $hide_images = false) {
  1469. $result = get_article_enclosures($id);
  1470. $rv = '';
  1471. foreach (PluginHost::getInstance()->get_hooks(PluginHost::HOOK_FORMAT_ENCLOSURES) as $plugin) {
  1472. $retval = $plugin->hook_format_enclosures($rv, $result, $id, $always_display_enclosures, $article_content, $hide_images);
  1473. if (is_array($retval)) {
  1474. $rv = $retval[0];
  1475. $result = $retval[1];
  1476. } else {
  1477. $rv = $retval;
  1478. }
  1479. }
  1480. unset($retval); // Unset to prevent breaking render if there are no HOOK_RENDER_ENCLOSURE hooks below.
  1481. if ($rv === '' && !empty($result)) {
  1482. $entries_html = array();
  1483. $entries = array();
  1484. $entries_inline = array();
  1485. foreach ($result as $line) {
  1486. $url = $line["content_url"];
  1487. $ctype = $line["content_type"];
  1488. $title = $line["title"];
  1489. $width = $line["width"];
  1490. $height = $line["height"];
  1491. if (!$ctype) $ctype = __("unknown type");
  1492. $filename = substr($url, strrpos($url, "/")+1);
  1493. $player = format_inline_player($url, $ctype);
  1494. if ($player) array_push($entries_inline, $player);
  1495. # $entry .= " <a target=\"_blank\" href=\"" . htmlspecialchars($url) . "\">" .
  1496. # $filename . " (" . $ctype . ")" . "</a>";
  1497. $entry = "<div onclick=\"window.open('".htmlspecialchars($url)."')\"
  1498. dojoType=\"dijit.MenuItem\">$filename ($ctype)</div>";
  1499. array_push($entries_html, $entry);
  1500. $entry = array();
  1501. $entry["type"] = $ctype;
  1502. $entry["filename"] = $filename;
  1503. $entry["url"] = $url;
  1504. $entry["title"] = $title;
  1505. $entry["width"] = $width;
  1506. $entry["height"] = $height;
  1507. array_push($entries, $entry);
  1508. }
  1509. if ($_SESSION['uid'] && !get_pref("STRIP_IMAGES") && !$_SESSION["bw_limit"]) {
  1510. if ($always_display_enclosures ||
  1511. !preg_match("/<img/i", $article_content)) {
  1512. foreach ($entries as $entry) {
  1513. foreach (PluginHost::getInstance()->get_hooks(PluginHost::HOOK_RENDER_ENCLOSURE) as $plugin)
  1514. $retval = $plugin->hook_render_enclosure($entry, $hide_images);
  1515. if ($retval) {
  1516. $rv .= $retval;
  1517. } else {
  1518. if (preg_match("/image/", $entry["type"]) ||
  1519. preg_match("/\.(jpg|png|gif|bmp)/i", $entry["filename"])) {
  1520. if (!$hide_images) {
  1521. $encsize = '';
  1522. if ($entry['height'] > 0)
  1523. $encsize .= ' height="' . intval($entry['height']) . '"';
  1524. if ($entry['width'] > 0)
  1525. $encsize .= ' width="' . intval($entry['width']) . '"';
  1526. $rv .= "<p><img
  1527. alt=\"".htmlspecialchars($entry["filename"])."\"
  1528. src=\"" .htmlspecialchars($entry["url"]) . "\"
  1529. " . $encsize . " /></p>";
  1530. } else {
  1531. $rv .= "<p><a target=\"_blank\"
  1532. href=\"".htmlspecialchars($entry["url"])."\"
  1533. >" .htmlspecialchars($entry["url"]) . "</a></p>";
  1534. }
  1535. if ($entry['title']) {
  1536. $rv.= "<div class=\"enclosure_title\">${entry['title']}</div>";
  1537. }
  1538. }
  1539. }
  1540. }
  1541. }
  1542. }
  1543. if (count($entries_inline) > 0) {
  1544. $rv .= "<hr clear='both'/>";
  1545. foreach ($entries_inline as $entry) { $rv .= $entry; };
  1546. $rv .= "<hr clear='both'/>";
  1547. }
  1548. $rv .= "<div class=\"attachments\" dojoType=\"dijit.form.DropDownButton\">".
  1549. "<span>" . __('Attachments')."</span>";
  1550. $rv .= "<div dojoType=\"dijit.Menu\" style=\"display: none;\">";
  1551. foreach ($entries as $entry) {
  1552. if ($entry["title"])
  1553. $title = "&mdash; " . truncate_string($entry["title"], 30);
  1554. else
  1555. $title = "";
  1556. $rv .= "<div onclick='window.open(\"".htmlspecialchars($entry["url"])."\")'
  1557. dojoType=\"dijit.MenuItem\">".htmlspecialchars($entry["filename"])."$title</div>";
  1558. };
  1559. $rv .= "</div>";
  1560. $rv .= "</div>";
  1561. }
  1562. return $rv;
  1563. }
  1564. function getLastArticleId() {
  1565. $result = db_query("SELECT ref_id AS id FROM ttrss_user_entries
  1566. WHERE owner_uid = " . $_SESSION["uid"] . " ORDER BY ref_id DESC LIMIT 1");
  1567. if (db_num_rows($result) == 1) {
  1568. return db_fetch_result($result, 0, "id");
  1569. } else {
  1570. return -1;
  1571. }
  1572. }
  1573. function build_url($parts) {
  1574. return $parts['scheme'] . "://" . $parts['host'] . $parts['path'];
  1575. }
  1576. /**
  1577. * Converts a (possibly) relative URL to a absolute one.
  1578. *
  1579. * @param string $url Base URL (i.e. from where the document is)
  1580. * @param string $rel_url Possibly relative URL in the document
  1581. *
  1582. * @return string Absolute URL
  1583. */
  1584. function rewrite_relative_url($url, $rel_url) {
  1585. if (strpos($rel_url, "://") !== false) {
  1586. return $rel_url;
  1587. } else if (strpos($rel_url, "//") === 0) {
  1588. # protocol-relative URL (rare but they exist)
  1589. return $rel_url;
  1590. } else if (preg_match("/^[a-z]+:/i", $rel_url)) {
  1591. # magnet:, feed:, etc
  1592. return $rel_url;
  1593. } else if (strpos($rel_url, "/") === 0) {
  1594. $parts = parse_url($url);
  1595. $parts['path'] = $rel_url;
  1596. return build_url($parts);
  1597. } else {
  1598. $parts = parse_url($url);
  1599. if (!isset($parts['path'])) {
  1600. $parts['path'] = '/';
  1601. }
  1602. $dir = $parts['path'];
  1603. if (substr($dir, -1) !== '/') {
  1604. $dir = dirname($parts['path']);
  1605. $dir !== '/' && $dir .= '/';
  1606. }
  1607. $parts['path'] = $dir . $rel_url;
  1608. return build_url($parts);
  1609. }
  1610. }
  1611. function cleanup_tags($days = 14, $limit = 1000) {
  1612. if (DB_TYPE == "pgsql") {
  1613. $interval_query = "date_updated < NOW() - INTERVAL '$days days'";
  1614. } else if (DB_TYPE == "mysql") {
  1615. $interval_query = "date_updated < DATE_SUB(NOW(), INTERVAL $days DAY)";
  1616. }
  1617. $tags_deleted = 0;
  1618. while ($limit > 0) {
  1619. $limit_part = 500;
  1620. $query = "SELECT ttrss_tags.id AS id
  1621. FROM ttrss_tags, ttrss_user_entries, ttrss_entries
  1622. WHERE post_int_id = int_id AND $interval_query AND
  1623. ref_id = ttrss_entries.id AND tag_cache != '' LIMIT $limit_part";
  1624. $result = db_query($query);
  1625. $ids = array();
  1626. while ($line = db_fetch_assoc($result)) {
  1627. array_push($ids, $line['id']);
  1628. }
  1629. if (count($ids) > 0) {
  1630. $ids = join(",", $ids);
  1631. $tmp_result = db_query("DELETE FROM ttrss_tags WHERE id IN ($ids)");
  1632. $tags_deleted += db_affected_rows($tmp_result);
  1633. } else {
  1634. break;
  1635. }
  1636. $limit -= $limit_part;
  1637. }
  1638. return $tags_deleted;
  1639. }
  1640. function print_user_stylesheet() {
  1641. $value = get_pref('USER_STYLESHEET');
  1642. if ($value) {
  1643. print "<style type=\"text/css\">";
  1644. print str_replace("<br/>", "\n", $value);
  1645. print "</style>";
  1646. }
  1647. }
  1648. function filter_to_sql($filter, $owner_uid) {
  1649. $query = array();
  1650. if (DB_TYPE == "pgsql")
  1651. $reg_qpart = "~";
  1652. else
  1653. $reg_qpart = "REGEXP";
  1654. foreach ($filter["rules"] AS $rule) {
  1655. $rule['reg_exp'] = str_replace('/', '\/', $rule["reg_exp"]);
  1656. $regexp_valid = preg_match('/' . $rule['reg_exp'] . '/',
  1657. $rule['reg_exp']) !== FALSE;
  1658. if ($regexp_valid) {
  1659. $rule['reg_exp'] = db_escape_string($rule['reg_exp']);
  1660. switch ($rule["type"]) {
  1661. case "title":
  1662. $qpart = "LOWER(ttrss_entries.title) $reg_qpart LOWER('".
  1663. $rule['reg_exp'] . "')";
  1664. break;
  1665. case "content":
  1666. $qpart = "LOWER(ttrss_entries.content) $reg_qpart LOWER('".
  1667. $rule['reg_exp'] . "')";
  1668. break;
  1669. case "both":
  1670. $qpart = "LOWER(ttrss_entries.title) $reg_qpart LOWER('".
  1671. $rule['reg_exp'] . "') OR LOWER(" .
  1672. "ttrss_entries.content) $reg_qpart LOWER('" . $rule['reg_exp'] . "')";
  1673. break;
  1674. case "tag":
  1675. $qpart = "LOWER(ttrss_user_entries.tag_cache) $reg_qpart LOWER('".
  1676. $rule['reg_exp'] . "')";
  1677. break;
  1678. case "link":
  1679. $qpart = "LOWER(ttrss_entries.link) $reg_qpart LOWER('".
  1680. $rule['reg_exp'] . "')";
  1681. break;
  1682. case "author":
  1683. $qpart = "LOWER(ttrss_entries.author) $reg_qpart LOWER('".
  1684. $rule['reg_exp'] . "')";
  1685. break;
  1686. }
  1687. if (isset($rule['inverse'])) $qpart = "NOT ($qpart)";
  1688. if (isset($rule["feed_id"]) && $rule["feed_id"] > 0) {
  1689. $qpart .= " AND feed_id = " . db_escape_string($rule["feed_id"]);
  1690. }
  1691. if (isset($rule["cat_id"])) {
  1692. if ($rule["cat_id"] > 0) {
  1693. $children = getChildCategories($rule["cat_id"], $owner_uid);
  1694. array_push($children, $rule["cat_id"]);
  1695. $children = join(",", $children);
  1696. $cat_qpart = "cat_id IN ($children)";
  1697. } else {
  1698. $cat_qpart = "cat_id IS NULL";
  1699. }
  1700. $qpart .= " AND $cat_qpart";
  1701. }
  1702. $qpart .= " AND feed_id IS NOT NULL";
  1703. array_push($query, "($qpart)");
  1704. }
  1705. }
  1706. if (count($query) > 0) {
  1707. $fullquery = "(" . join($filter["match_any_rule"] ? "OR" : "AND", $query) . ")";
  1708. } else {
  1709. $fullquery = "(false)";
  1710. }
  1711. if ($filter['inverse']) $fullquery = "(NOT $fullquery)";
  1712. return $fullquery;
  1713. }
  1714. if (!function_exists('gzdecode')) {
  1715. function gzdecode($string) { // no support for 2nd argument
  1716. return file_get_contents('compress.zlib://data:who/cares;base64,'.
  1717. base64_encode($string));
  1718. }
  1719. }
  1720. function get_random_bytes($length) {
  1721. if (function_exists('openssl_random_pseudo_bytes')) {
  1722. return openssl_random_pseudo_bytes($length);
  1723. } else {
  1724. $output = "";
  1725. for ($i = 0; $i < $length; $i++)
  1726. $output .= chr(mt_rand(0, 255));
  1727. return $output;
  1728. }
  1729. }
  1730. function read_stdin() {
  1731. $fp = fopen("php://stdin", "r");
  1732. if ($fp) {
  1733. $line = trim(fgets($fp));
  1734. fclose($fp);
  1735. return $line;
  1736. }
  1737. return null;
  1738. }
  1739. function tmpdirname($path, $prefix) {
  1740. // Use PHP's tmpfile function to create a temporary
  1741. // directory name. Delete the file and keep the name.
  1742. $tempname = tempnam($path,$prefix);
  1743. if (!$tempname)
  1744. return false;
  1745. if (!unlink($tempname))
  1746. return false;
  1747. return $tempname;
  1748. }
  1749. function getFeedCategory($feed) {
  1750. $result = db_query("SELECT cat_id FROM ttrss_feeds
  1751. WHERE id = '$feed'");
  1752. if (db_num_rows($result) > 0) {
  1753. return db_fetch_result($result, 0, "cat_id");
  1754. } else {
  1755. return false;
  1756. }
  1757. }
  1758. function implements_interface($class, $interface) {
  1759. return in_array($interface, class_implements($class));
  1760. }
  1761. function get_minified_js($files) {
  1762. require_once 'lib/jshrink/Minifier.php';
  1763. $rv = '';
  1764. foreach ($files as $js) {
  1765. if (!isset($_GET['debug'])) {
  1766. $cached_file = CACHE_DIR . "/js/".basename($js).".js";
  1767. if (file_exists($cached_file) && is_readable($cached_file) && filemtime($cached_file) >= filemtime("js/$js.js")) {
  1768. list($header, $contents) = explode("\n", file_get_contents($cached_file), 2);
  1769. if ($header && $contents) {
  1770. list($htag, $hversion) = explode(":", $header);
  1771. if ($htag == "tt-rss" && $hversion == VERSION) {
  1772. $rv .= $contents;
  1773. continue;
  1774. }
  1775. }
  1776. }
  1777. $minified = JShrink\Minifier::minify(file_get_contents("js/$js.js"));
  1778. file_put_contents($cached_file, "tt-rss:" . VERSION . "\n" . $minified);
  1779. $rv .= $minified;
  1780. } else {
  1781. $rv .= file_get_contents("js/$js.js"); // no cache in debug mode
  1782. }
  1783. }
  1784. return $rv;
  1785. }
  1786. function stylesheet_tag($filename) {
  1787. $timestamp = filemtime($filename);
  1788. return "<link rel=\"stylesheet\" type=\"text/css\" href=\"$filename?$timestamp\"/>\n";
  1789. }
  1790. function javascript_tag($filename) {
  1791. $query = "";
  1792. if (!(strpos($filename, "?") === FALSE)) {
  1793. $query = substr($filename, strpos($filename, "?")+1);
  1794. $filename = substr($filename, 0, strpos($filename, "?"));
  1795. }
  1796. $timestamp = filemtime($filename);
  1797. if ($query) $timestamp .= "&$query";
  1798. return "<script type=\"text/javascript\" charset=\"utf-8\" src=\"$filename?$timestamp\"></script>\n";
  1799. }
  1800. function calculate_dep_timestamp() {
  1801. $files = array_merge(glob("js/*.js"), glob("css/*.css"));
  1802. $max_ts = -1;
  1803. foreach ($files as $file) {
  1804. if (filemtime($file) > $max_ts) $max_ts = filemtime($file);
  1805. }
  1806. return $max_ts;
  1807. }
  1808. function T_js_decl($s1, $s2) {
  1809. if ($s1 && $s2) {
  1810. $s1 = preg_replace("/\n/", "", $s1);
  1811. $s2 = preg_replace("/\n/", "", $s2);
  1812. $s1 = preg_replace("/\"/", "\\\"", $s1);
  1813. $s2 = preg_replace("/\"/", "\\\"", $s2);
  1814. return "T_messages[\"$s1\"] = \"$s2\";\n";
  1815. }
  1816. }
  1817. function init_js_translations() {
  1818. print 'var T_messages = new Object();
  1819. function __(msg) {
  1820. if (T_messages[msg]) {
  1821. return T_messages[msg];
  1822. } else {
  1823. return msg;
  1824. }
  1825. }
  1826. function ngettext(msg1, msg2, n) {
  1827. return __((parseInt(n) > 1) ? msg2 : msg1);
  1828. }';
  1829. $l10n = _get_reader();
  1830. for ($i = 0; $i < $l10n->total; $i++) {
  1831. $orig = $l10n->get_original_string($i);
  1832. if(strpos($orig, "\000") !== FALSE) { // Plural forms
  1833. $key = explode(chr(0), $orig);
  1834. print T_js_decl($key[0], _ngettext($key[0], $key[1], 1)); // Singular
  1835. print T_js_decl($key[1], _ngettext($key[0], $key[1], 2)); // Plural
  1836. } else {
  1837. $translation = __($orig);
  1838. print T_js_decl($orig, $translation);
  1839. }
  1840. }
  1841. }
  1842. function label_to_feed_id($label) {
  1843. return LABEL_BASE_INDEX - 1 - abs($label);
  1844. }
  1845. function feed_to_label_id($feed) {
  1846. return LABEL_BASE_INDEX - 1 + abs($feed);
  1847. }
  1848. function get_theme_path($theme) {
  1849. $check = "themes/$theme";
  1850. if (file_exists($check)) return $check;
  1851. $check = "themes.local/$theme";
  1852. if (file_exists($check)) return $check;
  1853. }
  1854. function theme_valid($theme) {
  1855. if ($theme == "default.css" || $theme == "night.css") return true; // needed for array_filter
  1856. $file = "themes/" . basename($theme);
  1857. if (!file_exists($file)) $file = "themes.local/" . basename($theme);
  1858. if (file_exists($file) && is_readable($file)) {
  1859. $fh = fopen($file, "r");
  1860. if ($fh) {
  1861. $header = fgets($fh);
  1862. fclose($fh);
  1863. return strpos($header, "supports-version:" . VERSION_STATIC) !== FALSE;
  1864. }
  1865. }
  1866. return false;
  1867. }
  1868. function error_json($code) {
  1869. require_once "errors.php";
  1870. @$message = $ERRORS[$code];
  1871. return json_encode(array("error" =>
  1872. array("code" => $code, "message" => $message)));
  1873. }
  1874. function abs_to_rel_path($dir) {
  1875. $tmp = str_replace(dirname(__DIR__), "", $dir);
  1876. if (strlen($tmp) > 0 && substr($tmp, 0, 1) == "/") $tmp = substr($tmp, 1);
  1877. return $tmp;
  1878. }
  1879. ?>