functions2.php 68 KB

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