functions2.php 70 KB

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