functions2.php 66 KB

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