functions2.php 67 KB

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