feeds.php 61 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074
  1. <?php
  2. require_once "colors.php";
  3. class Feeds extends Handler_Protected {
  4. private $params;
  5. function csrf_ignore($method) {
  6. $csrf_ignored = array("index", "quickaddfeed", "search");
  7. return array_search($method, $csrf_ignored) !== false;
  8. }
  9. private function format_headline_subtoolbar($feed_site_url, $feed_title,
  10. $feed_id, $is_cat, $search,
  11. $error, $feed_last_updated) {
  12. if ($is_cat) $cat_q = "&is_cat=$is_cat";
  13. if ($search) {
  14. $search_q = "&q=$search";
  15. } else {
  16. $search_q = "";
  17. }
  18. $reply = "";
  19. $rss_link = htmlspecialchars(get_self_url_prefix() .
  20. "/public.php?op=rss&id=$feed_id$cat_q$search_q");
  21. $reply .= "<span class='left'>";
  22. $reply .= "<a href=\"#\"
  23. title=\"".__("Show as feed")."\"
  24. onclick=\"App.displayDlg('".__("Show as feed")."','generatedFeed', '$feed_id:$is_cat:$rss_link')\">
  25. <i class='icon-syndicate material-icons'>rss_feed</i></a>";
  26. $reply .= "<span id='feed_title'>";
  27. if ($feed_site_url) {
  28. $last_updated = T_sprintf("Last updated: %s", $feed_last_updated);
  29. $reply .= "<a title=\"$last_updated\" target='_blank' href=\"$feed_site_url\">".
  30. truncate_string(strip_tags($feed_title), 30)."</a>";
  31. } else {
  32. $reply .= strip_tags($feed_title);
  33. }
  34. if ($error)
  35. $reply .= " <i title=\"" . htmlspecialchars($error) . "\" class='material-icons icon-error'>error</i>";
  36. $reply .= "</span></span>";
  37. $reply .= "<span class=\"right\">";
  38. $reply .= "<span id='selected_prompt'></span>";
  39. $reply .= "&nbsp;";
  40. $reply .= "<select dojoType=\"fox.form.Select\"
  41. onchange=\"Headlines.onActionChanged(this)\">";
  42. $reply .= "<option value=\"0\" disabled='1'>".__('Select...')."</option>";
  43. $reply .= "<option value=\"Headlines.select('all')\">".__('All')."</option>";
  44. $reply .= "<option value=\"Headlines.select('unread')\">".__('Unread')."</option>";
  45. $reply .= "<option value=\"Headlines.select('invert')\">".__('Invert')."</option>";
  46. $reply .= "<option value=\"Headlines.select('none')\">".__('None')."</option>";
  47. $reply .= "<option value=\"0\" disabled=\"1\">".__('Selection toggle:')."</option>";
  48. $reply .= "<option value=\"Headlines.selectionToggleUnread()\">".__('Unread')."</option>
  49. <option value=\"Headlines.selectionToggleMarked()\">".__('Starred')."</option>
  50. <option value=\"Headlines.selectionTogglePublished()\">".__('Published')."</option>";
  51. $reply .= "<option value=\"0\" disabled=\"1\">".__('Selection:')."</option>";
  52. $reply .= "<option value=\"Headlines.catchupSelection()\">".__('Mark as read')."</option>";
  53. $reply .= "<option value=\"Article.selectionSetScore()\">".__('Set score')."</option>";
  54. if ($feed_id == 0 && !$is_cat) {
  55. $reply .= "<option value=\"Headlines.archiveSelection()\">".__('Move back')."</option>";
  56. $reply .= "<option value=\"Headlines.deleteSelection()\">".__('Delete')."</option>";
  57. } else {
  58. $reply .= "<option value=\"Headlines.archiveSelection()\">".__('Archive')."</option>";
  59. }
  60. if (PluginHost::getInstance()->get_plugin("mail")) {
  61. $reply .= "<option value=\"Plugins.Mail.send()\">".__('Forward by email').
  62. "</option>";
  63. }
  64. if (PluginHost::getInstance()->get_plugin("mailto")) {
  65. $reply .= "<option value=\"Plugins.Mailto.send()\">".__('Forward by email').
  66. "</option>";
  67. }
  68. $reply .= "<option value=\"0\" disabled=\"1\">".__('Feed:')."</option>";
  69. //$reply .= "<option value=\"catchupPage()\">".__('Mark as read')."</option>";
  70. $reply .= "<option value=\"App.displayDlg('".__("Show as feed")."','generatedFeed', '$feed_id:$is_cat:$rss_link')\">".
  71. __('Show as feed')."</option>";
  72. $reply .= "</select>";
  73. //$reply .= "</h2";
  74. foreach (PluginHost::getInstance()->get_hooks(PluginHost::HOOK_HEADLINE_TOOLBAR_BUTTON) as $p) {
  75. $reply .= $p->hook_headline_toolbar_button($feed_id, $is_cat);
  76. }
  77. $reply .= "</span>";
  78. return $reply;
  79. }
  80. private function format_headlines_list($feed, $method, $view_mode, $limit, $cat_view,
  81. $offset, $override_order = false, $include_children = false, $check_first_id = false,
  82. $skip_first_id_check = false, $order_by = false) {
  83. $disable_cache = false;
  84. $reply = array();
  85. $rgba_cache = array();
  86. $topmost_article_ids = array();
  87. if (!$offset) $offset = 0;
  88. if ($method == "undefined") $method = "";
  89. $method_split = explode(":", $method);
  90. if ($method == "ForceUpdate" && $feed > 0 && is_numeric($feed)) {
  91. $sth = $this->pdo->prepare("UPDATE ttrss_feeds
  92. SET last_updated = '1970-01-01', last_update_started = '1970-01-01'
  93. WHERE id = ?");
  94. $sth->execute([$feed]);
  95. }
  96. if ($method_split[0] == "MarkAllReadGR") {
  97. $this->catchup_feed($method_split[1], false);
  98. }
  99. // FIXME: might break tag display?
  100. if (is_numeric($feed) && $feed > 0 && !$cat_view) {
  101. $sth = $this->pdo->prepare("SELECT id FROM ttrss_feeds WHERE id = ? LIMIT 1");
  102. $sth->execute([$feed]);
  103. if (!$sth->fetch()) {
  104. $reply['content'] = "<div align='center'>".__('Feed not found.')."</div>";
  105. }
  106. }
  107. @$search = $_REQUEST["query"];
  108. @$search_language = $_REQUEST["search_language"]; // PGSQL only
  109. if ($search) {
  110. $disable_cache = true;
  111. }
  112. if (!$cat_view && is_numeric($feed) && $feed < PLUGIN_FEED_BASE_INDEX && $feed > LABEL_BASE_INDEX) {
  113. $handler = PluginHost::getInstance()->get_feed_handler(
  114. PluginHost::feed_to_pfeed_id($feed));
  115. if ($handler) {
  116. $options = array(
  117. "limit" => $limit,
  118. "view_mode" => $view_mode,
  119. "cat_view" => $cat_view,
  120. "search" => $search,
  121. "override_order" => $override_order,
  122. "offset" => $offset,
  123. "owner_uid" => $_SESSION["uid"],
  124. "filter" => false,
  125. "since_id" => 0,
  126. "include_children" => $include_children,
  127. "order_by" => $order_by);
  128. $qfh_ret = $handler->get_headlines(PluginHost::feed_to_pfeed_id($feed),
  129. $options);
  130. }
  131. } else {
  132. $params = array(
  133. "feed" => $feed,
  134. "limit" => $limit,
  135. "view_mode" => $view_mode,
  136. "cat_view" => $cat_view,
  137. "search" => $search,
  138. "search_language" => $search_language,
  139. "override_order" => $override_order,
  140. "offset" => $offset,
  141. "include_children" => $include_children,
  142. "check_first_id" => $check_first_id,
  143. "skip_first_id_check" => $skip_first_id_check,
  144. "order_by" => $order_by
  145. );
  146. $qfh_ret = $this->queryFeedHeadlines($params);
  147. }
  148. $vfeed_group_enabled = get_pref("VFEED_GROUP_BY_FEED") && $feed != -6;
  149. $result = $qfh_ret[0]; // this could be either a PDO query result or a -1 if first id changed
  150. $feed_title = $qfh_ret[1];
  151. $feed_site_url = $qfh_ret[2];
  152. $last_error = $qfh_ret[3];
  153. $last_updated = strpos($qfh_ret[4], '1970-') === FALSE ?
  154. make_local_datetime($qfh_ret[4], false) : __("Never");
  155. $highlight_words = $qfh_ret[5];
  156. $reply['first_id'] = $qfh_ret[6];
  157. $reply['is_vfeed'] = $qfh_ret[7];
  158. $query_error_override = $qfh_ret[8];
  159. $reply['search_query'] = [$search, $search_language];
  160. $reply['vfeed_group_enabled'] = $vfeed_group_enabled;
  161. $reply['toolbar'] = $this->format_headline_subtoolbar($feed_site_url,
  162. $feed_title,
  163. $feed, $cat_view, $search,
  164. $last_error, $last_updated);
  165. if ($offset == 0) {
  166. foreach (PluginHost::getInstance()->get_hooks(PluginHost::HOOK_HEADLINES_BEFORE) as $p) {
  167. $reply['content'] .= $p->hook_headlines_before($feed, $cat_view, $qfh_ret);
  168. }
  169. }
  170. $reply['content'] = [];
  171. $headlines_count = 0;
  172. if (is_object($result)) {
  173. while ($line = $result->fetch(PDO::FETCH_ASSOC)) {
  174. ++$headlines_count;
  175. if (!get_pref('SHOW_CONTENT_PREVIEW')) {
  176. $line["content_preview"] = "";
  177. } else {
  178. $line["content_preview"] = "&mdash; " . truncate_string(strip_tags($line["content"]), 250);
  179. foreach (PluginHost::getInstance()->get_hooks(PluginHost::HOOK_QUERY_HEADLINES) as $p) {
  180. $line = $p->hook_query_headlines($line, 250, false);
  181. }
  182. }
  183. $id = $line["id"];
  184. // frontend doesn't expect pdo returning booleans as strings on mysql
  185. if (DB_TYPE == "mysql") {
  186. foreach (["unread", "marked", "published"] as $k) {
  187. $line[$k] = $line[$k] === "1";
  188. }
  189. }
  190. // normalize archived feed
  191. if ($line['feed_id'] === null) {
  192. $line['feed_id'] = 0;
  193. $line["feed_title"] = __("Archived articles");
  194. }
  195. $feed_id = $line["feed_id"];
  196. $label_cache = $line["label_cache"];
  197. $labels = false;
  198. if ($label_cache) {
  199. $label_cache = json_decode($label_cache, true);
  200. if ($label_cache) {
  201. if ($label_cache["no-labels"] == 1)
  202. $labels = array();
  203. else
  204. $labels = $label_cache;
  205. }
  206. }
  207. if (!is_array($labels)) $labels = Article::get_article_labels($id);
  208. $labels_str = "<span class=\"HLLCTR-$id\">";
  209. $labels_str .= Article::format_article_labels($labels);
  210. $labels_str .= "</span>";
  211. $line["labels"] = $labels_str;
  212. if (count($topmost_article_ids) < 3) {
  213. array_push($topmost_article_ids, $id);
  214. }
  215. if (!$line["feed_title"]) $line["feed_title"] = "";
  216. $line["buttons_left"] = "";
  217. foreach (PluginHost::getInstance()->get_hooks(PluginHost::HOOK_ARTICLE_LEFT_BUTTON) as $p) {
  218. $line["buttons_left"] .= $p->hook_article_left_button($line);
  219. }
  220. $line["buttons"] = "";
  221. foreach (PluginHost::getInstance()->get_hooks(PluginHost::HOOK_ARTICLE_BUTTON) as $p) {
  222. $line["buttons"] .= $p->hook_article_button($line);
  223. }
  224. $line["content"] = sanitize($line["content"],
  225. $line['hide_images'], false, $line["site_url"], $highlight_words, $line["id"]);
  226. foreach (PluginHost::getInstance()->get_hooks(PluginHost::HOOK_RENDER_ARTICLE_CDM) as $p) {
  227. $line = $p->hook_render_article_cdm($line);
  228. }
  229. $line['content'] = rewrite_cached_urls($line['content']);
  230. if ($line['note'])
  231. $line['note'] = Article::format_article_note($id, $line['note']);
  232. else
  233. $line['note'] = "";
  234. if (!get_pref("CDM_EXPANDED")) {
  235. $line["cdm_excerpt"] = "<span class='collapse'>
  236. <i class='material-icons' onclick='return Article.cdmUnsetActive(event)'
  237. title=\"" . __("Collapse article") . "\">remove_circle</i></span>";
  238. if (get_pref('SHOW_CONTENT_PREVIEW')) {
  239. $line["cdm_excerpt"] .= "<span class='excerpt'>" . $line["content_preview"] . "</span>";
  240. }
  241. }
  242. $line["enclosures"] = Article::format_article_enclosures($id, $line["always_display_enclosures"],
  243. $line["content"], $line["hide_images"]);
  244. if ($line["orig_feed_id"]) {
  245. $ofgh = $this->pdo->prepare("SELECT * FROM ttrss_archived_feeds
  246. WHERE id = ? AND owner_uid = ?");
  247. $ofgh->execute([$line["orig_feed_id"], $_SESSION['uid']]);
  248. if ($tmp_line = $ofgh->fetch()) {
  249. $line["orig_feed"] = [ $tmp_line["title"], $tmp_line["site_url"], $tmp_line["feed_url"] ];
  250. }
  251. }
  252. $line["updated_long"] = make_local_datetime($line["updated"],true);
  253. $line["updated"] = make_local_datetime($line["updated"], false, false, false, true);
  254. $line['imported'] = T_sprintf("Imported at %s",
  255. make_local_datetime($line["date_entered"], false));
  256. if ($line["tag_cache"])
  257. $tags = explode(",", $line["tag_cache"]);
  258. else
  259. $tags = false;
  260. $line["tags_str"] = Article::format_tags_string($tags, $id);
  261. if (feeds::feedHasIcon($feed_id)) {
  262. $line['feed_icon'] = "<img class=\"icon\" src=\"".ICONS_URL."/$feed_id.ico\" alt=\"\">";
  263. } else {
  264. $line['feed_icon'] = "<i class='icon-no-feed material-icons'>rss_feed</i>";
  265. }
  266. //setting feed headline background color, needs to change text color based on dark/light
  267. $fav_color = $line['favicon_avg_color'];
  268. require_once "colors.php";
  269. if (!isset($rgba_cache[$feed_id])) {
  270. if ($fav_color && $fav_color != 'fail') {
  271. $rgba_cache[$feed_id] = _color_unpack($fav_color);
  272. } else {
  273. $rgba_cache[$feed_id] = _color_unpack($this->color_of($line['feed_title']));
  274. }
  275. }
  276. if (isset($rgba_cache[$feed_id])) {
  277. $line['feed_bg_color'] = 'rgba(' . implode(",", $rgba_cache[$feed_id]) . ',0.3)';
  278. }
  279. /* we don't need those */
  280. foreach (["date_entered", "guid", "last_published", "last_marked", "tag_cache", "favicon_avg_color",
  281. "uuid", "label_cache", "yyiw"] as $k)
  282. unset($line[$k]);
  283. array_push($reply['content'], $line);
  284. }
  285. }
  286. if (!$headlines_count) {
  287. if (is_object($result)) {
  288. if ($query_error_override) {
  289. $message = $query_error_override;
  290. } else {
  291. switch ($view_mode) {
  292. case "unread":
  293. $message = __("No unread articles found to display.");
  294. break;
  295. case "updated":
  296. $message = __("No updated articles found to display.");
  297. break;
  298. case "marked":
  299. $message = __("No starred articles found to display.");
  300. break;
  301. default:
  302. if ($feed < LABEL_BASE_INDEX) {
  303. $message = __("No articles found to display. You can assign articles to labels manually from article header context menu (applies to all selected articles) or use a filter.");
  304. } else {
  305. $message = __("No articles found to display.");
  306. }
  307. }
  308. }
  309. if (!$offset && $message) {
  310. $reply['content'] = "<div class='whiteBox'>$message";
  311. $reply['content'] .= "<p><span class=\"text-muted\">";
  312. $sth = $this->pdo->prepare("SELECT " . SUBSTRING_FOR_DATE . "(MAX(last_updated), 1, 19) AS last_updated FROM ttrss_feeds
  313. WHERE owner_uid = ?");
  314. $sth->execute([$_SESSION['uid']]);
  315. $row = $sth->fetch();
  316. $last_updated = make_local_datetime($row["last_updated"], false);
  317. $reply['content'] .= sprintf(__("Feeds last updated at %s"), $last_updated);
  318. $sth = $this->pdo->prepare("SELECT COUNT(id) AS num_errors
  319. FROM ttrss_feeds WHERE last_error != '' AND owner_uid = ?");
  320. $sth->execute([$_SESSION['uid']]);
  321. $row = $sth->fetch();
  322. $num_errors = $row["num_errors"];
  323. if ($num_errors > 0) {
  324. $reply['content'] .= "<br/>";
  325. $reply['content'] .= "<a class=\"text-muted\" href=\"#\" onclick=\"CommonDialogs.showFeedsWithErrors()\">" .
  326. __('Some feeds have update errors (click for details)') . "</a>";
  327. }
  328. $reply['content'] .= "</span></p></div>";
  329. }
  330. } else if (is_numeric($result) && $result == -1) {
  331. $reply['first_id_changed'] = true;
  332. }
  333. }
  334. return array($topmost_article_ids, $headlines_count, $feed, $disable_cache, $reply);
  335. }
  336. function catchupAll() {
  337. $sth = $this->pdo->prepare("UPDATE ttrss_user_entries SET
  338. last_read = NOW(), unread = false WHERE unread = true AND owner_uid = ?");
  339. $sth->execute([$_SESSION['uid']]);
  340. CCache::zero_all($_SESSION["uid"]);
  341. }
  342. function view() {
  343. $reply = array();
  344. $feed = $_REQUEST["feed"];
  345. $method = $_REQUEST["m"];
  346. $view_mode = $_REQUEST["view_mode"];
  347. $limit = 30;
  348. @$cat_view = $_REQUEST["cat"] == "true";
  349. @$next_unread_feed = $_REQUEST["nuf"];
  350. @$offset = $_REQUEST["skip"];
  351. $order_by = $_REQUEST["order_by"];
  352. $check_first_id = $_REQUEST["fid"];
  353. if (is_numeric($feed)) $feed = (int) $feed;
  354. /* Feed -5 is a special case: it is used to display auxiliary information
  355. * when there's nothing to load - e.g. no stuff in fresh feed */
  356. if ($feed == -5) {
  357. print json_encode($this->generate_dashboard_feed());
  358. return;
  359. }
  360. $sth = false;
  361. if ($feed < LABEL_BASE_INDEX) {
  362. $label_feed = Labels::feed_to_label_id($feed);
  363. $sth = $this->pdo->prepare("SELECT id FROM ttrss_labels2 WHERE
  364. id = ? AND owner_uid = ?");
  365. $sth->execute([$label_feed, $_SESSION['uid']]);
  366. } else if (!$cat_view && is_numeric($feed) && $feed > 0) {
  367. $sth = $this->pdo->prepare("SELECT id FROM ttrss_feeds WHERE
  368. id = ? AND owner_uid = ?");
  369. $sth->execute([$feed, $_SESSION['uid']]);
  370. } else if ($cat_view && is_numeric($feed) && $feed > 0) {
  371. $sth = $this->pdo->prepare("SELECT id FROM ttrss_feed_categories WHERE
  372. id = ? AND owner_uid = ?");
  373. $sth->execute([$feed, $_SESSION['uid']]);
  374. }
  375. if ($sth && !$sth->fetch()) {
  376. print json_encode($this->generate_error_feed(__("Feed not found.")));
  377. return;
  378. }
  379. /* Updating a label ccache means recalculating all of the caches
  380. * so for performance reasons we don't do that here */
  381. if ($feed >= 0) {
  382. CCache::update($feed, $_SESSION["uid"], $cat_view);
  383. }
  384. set_pref("_DEFAULT_VIEW_MODE", $view_mode);
  385. set_pref("_DEFAULT_VIEW_ORDER_BY", $order_by);
  386. /* bump login timestamp if needed */
  387. if (time() - $_SESSION["last_login_update"] > 3600) {
  388. $sth = $this->pdo->prepare("UPDATE ttrss_users SET last_login = NOW() WHERE id = ?");
  389. $sth->execute([$_SESSION['uid']]);
  390. $_SESSION["last_login_update"] = time();
  391. }
  392. if (!$cat_view && is_numeric($feed) && $feed > 0) {
  393. $sth = $this->pdo->prepare("UPDATE ttrss_feeds SET last_viewed = NOW()
  394. WHERE id = ? AND owner_uid = ?");
  395. $sth->execute([$feed, $_SESSION['uid']]);
  396. }
  397. $reply['headlines'] = [];
  398. $override_order = false;
  399. $skip_first_id_check = false;
  400. switch ($order_by) {
  401. case "title":
  402. $override_order = "ttrss_entries.title, date_entered, updated";
  403. break;
  404. case "date_reverse":
  405. $override_order = "score DESC, date_entered, updated";
  406. $skip_first_id_check = true;
  407. break;
  408. case "feed_dates":
  409. $override_order = "updated DESC";
  410. break;
  411. }
  412. $ret = $this->format_headlines_list($feed, $method,
  413. $view_mode, $limit, $cat_view, $offset,
  414. $override_order, true, $check_first_id, $skip_first_id_check, $order_by);
  415. $headlines_count = $ret[1];
  416. $disable_cache = $ret[3];
  417. $reply['headlines'] = $ret[4];
  418. if (!$next_unread_feed)
  419. $reply['headlines']['id'] = $feed;
  420. else
  421. $reply['headlines']['id'] = $next_unread_feed;
  422. $reply['headlines']['is_cat'] = (bool) $cat_view;
  423. $reply['headlines-info'] = ["count" => (int) $headlines_count,
  424. "disable_cache" => (bool) $disable_cache];
  425. // this is parsed by handleRpcJson() on first viewfeed() to set cdm expanded, etc
  426. $reply['runtime-info'] = make_runtime_info();
  427. $reply_json = json_encode($reply);
  428. if (!$reply_json) {
  429. $reply_json = json_encode(["error" => ["code" => 15,
  430. "message" => json_last_error_msg()]]);
  431. }
  432. print $reply_json;
  433. }
  434. private function generate_dashboard_feed() {
  435. $reply = array();
  436. $reply['headlines']['id'] = -5;
  437. $reply['headlines']['is_cat'] = false;
  438. $reply['headlines']['toolbar'] = '';
  439. $reply['headlines']['content'] = "<div class='whiteBox'>".__('No feed selected.');
  440. $reply['headlines']['content'] .= "<p><span class=\"text-muted\">";
  441. $sth = $this->pdo->prepare("SELECT ".SUBSTRING_FOR_DATE."(MAX(last_updated), 1, 19) AS last_updated FROM ttrss_feeds
  442. WHERE owner_uid = ?");
  443. $sth->execute([$_SESSION['uid']]);
  444. $row = $sth->fetch();
  445. $last_updated = make_local_datetime($row["last_updated"], false);
  446. $reply['headlines']['content'] .= sprintf(__("Feeds last updated at %s"), $last_updated);
  447. $sth = $this->pdo->prepare("SELECT COUNT(id) AS num_errors
  448. FROM ttrss_feeds WHERE last_error != '' AND owner_uid = ?");
  449. $sth->execute([$_SESSION['uid']]);
  450. $row = $sth->fetch();
  451. $num_errors = $row["num_errors"];
  452. if ($num_errors > 0) {
  453. $reply['headlines']['content'] .= "<br/>";
  454. $reply['headlines']['content'] .= "<a class=\"text-muted\" href=\"#\" onclick=\"CommonDialogs.showFeedsWithErrors()\">".
  455. __('Some feeds have update errors (click for details)')."</a>";
  456. }
  457. $reply['headlines']['content'] .= "</span></p>";
  458. $reply['headlines-info'] = array("count" => 0,
  459. "unread" => 0,
  460. "disable_cache" => true);
  461. return $reply;
  462. }
  463. private function generate_error_feed($error) {
  464. $reply = array();
  465. $reply['headlines']['id'] = -7;
  466. $reply['headlines']['is_cat'] = false;
  467. $reply['headlines']['toolbar'] = '';
  468. $reply['headlines']['content'] = "<div class='whiteBox'>". $error . "</div>";
  469. $reply['headlines-info'] = array("count" => 0,
  470. "unread" => 0,
  471. "disable_cache" => true);
  472. return $reply;
  473. }
  474. function quickAddFeed() {
  475. print "<form onsubmit='return false'>";
  476. print_hidden("op", "rpc");
  477. print_hidden("method", "addfeed");
  478. print "<div id='fadd_error_message' style='display : none' class='alert alert-danger'></div>";
  479. print "<div id='fadd_multiple_notify' style='display : none'>";
  480. print_notice("Provided URL is a HTML page referencing multiple feeds, please select required feed from the dropdown menu below.");
  481. print "<p></div>";
  482. print "<section>";
  483. print "<fieldset>";
  484. print "<div style='float : right'><img style='display : none' id='feed_add_spinner' src='images/indicator_white.gif'></div>";
  485. print "<input style='font-size : 16px; width : 500px;'
  486. placeHolder=\"".__("Feed or site URL")."\"
  487. dojoType='dijit.form.ValidationTextBox' required='1' name='feed' id='feedDlg_feedUrl'>";
  488. print "</fieldset>";
  489. print "<fieldset>";
  490. if (get_pref('ENABLE_FEED_CATS')) {
  491. print "<label class='inline'>" . __('Place in category:') . "</label> ";
  492. print_feed_cat_select("cat", false, 'dojoType="fox.form.Select"');
  493. }
  494. print "</fieldset>";
  495. print "</section>";
  496. print '<div id="feedDlg_feedsContainer" style="display : none">
  497. <header>' . __('Available feeds') . '</header>
  498. <section>
  499. <fieldset>
  500. <select id="feedDlg_feedContainerSelect"
  501. dojoType="fox.form.Select" size="3">
  502. <script type="dojo/method" event="onChange" args="value">
  503. dijit.byId("feedDlg_feedUrl").attr("value", value);
  504. </script>
  505. </select>
  506. </fieldset>
  507. </section>
  508. </div>';
  509. print "<div id='feedDlg_loginContainer' style='display : none'>
  510. <section>
  511. <fieldset>
  512. <input dojoType=\"dijit.form.TextBox\" name='login'\"
  513. placeHolder=\"".__("Login")."\"
  514. autocomplete=\"new-password\"
  515. style=\"width : 10em;\">
  516. <input
  517. placeHolder=\"".__("Password")."\"
  518. dojoType=\"dijit.form.TextBox\" type='password'
  519. autocomplete=\"new-password\"
  520. style=\"width : 10em;\" name='pass'\">
  521. </fieldset>
  522. </section>
  523. </div>";
  524. print "<section>";
  525. print "<label>
  526. <label class='checkbox'><input type='checkbox' name='need_auth' dojoType='dijit.form.CheckBox' id='feedDlg_loginCheck'
  527. onclick='displayIfChecked(this, \"feedDlg_loginContainer\")'>
  528. ".__('This feed requires authentication.')."</label>";
  529. print "</section>";
  530. print "<footer>";
  531. print "<button dojoType='dijit.form.Button' class='alt-primary' type='submit'
  532. onclick=\"return dijit.byId('feedAddDlg').execute()\">".__('Subscribe')."</button>";
  533. print "<button dojoType='dijit.form.Button' onclick=\"return dijit.byId('feedAddDlg').hide()\">".__('Cancel')."</button>";
  534. print "</footer>";
  535. print "</form>";
  536. }
  537. function search() {
  538. $this->params = explode(":", $_REQUEST["param"], 2);
  539. $active_feed_id = sprintf("%d", $this->params[0]);
  540. $is_cat = $this->params[1] != "false";
  541. print "<form onsubmit='return false;'>";
  542. print "<section>";
  543. print "<fieldset>";
  544. print "<input dojoType='dijit.form.ValidationTextBox' id='search_query'
  545. style='font-size : 16px; width : 540px;'
  546. placeHolder=\"".T_sprintf("Search %s...", $this->getFeedTitle($active_feed_id, $is_cat))."\"
  547. name='query' type='search' value=''>";
  548. print "</fieldset>";
  549. if (DB_TYPE == "pgsql") {
  550. print "<fieldset>";
  551. print "<label class='inline'>" . __("Language:") . "</label>";
  552. print_select("search_language", get_pref('DEFAULT_SEARCH_LANGUAGE'), Pref_Feeds::get_ts_languages(),
  553. "dojoType='fox.form.Select' title=\"".__('Used for word stemming')."\"");
  554. print "</fieldset>";
  555. }
  556. print "</section>";
  557. print "<footer>";
  558. if (count(PluginHost::getInstance()->get_hooks(PluginHost::HOOK_SEARCH)) == 0) {
  559. print "<button dojoType='dijit.form.Button' style='float : left' class='alt-info' onclick='window.open(\"https://tt-rss.org/wiki/SearchSyntax\")'>
  560. <i class='material-icons'>help</i> ".__("Search syntax")."</button>";
  561. }
  562. print "<button dojoType='dijit.form.Button' type='submit' class='alt-primary' onclick=\"dijit.byId('searchDlg').execute()\">".__('Search')."</button>
  563. <button dojoType='dijit.form.Button' onclick=\"dijit.byId('searchDlg').hide()\">".__('Cancel')."</button>";
  564. print "</footer>";
  565. print "</form>";
  566. }
  567. function update_debugger() {
  568. header("Content-type: text/html");
  569. Debug::set_enabled(true);
  570. Debug::set_loglevel($_REQUEST["xdebug"]);
  571. $feed_id = (int)$_REQUEST["feed_id"];
  572. @$do_update = $_REQUEST["action"] == "do_update";
  573. $csrf_token = $_REQUEST["csrf_token"];
  574. $sth = $this->pdo->prepare("SELECT id FROM ttrss_feeds WHERE id = ? AND owner_uid = ?");
  575. $sth->execute([$feed_id, $_SESSION['uid']]);
  576. if (!$sth->fetch()) {
  577. print "Access denied.";
  578. return;
  579. }
  580. $refetch_checked = isset($_REQUEST["force_refetch"]) ? "checked" : "";
  581. $rehash_checked = isset($_REQUEST["force_rehash"]) ? "checked" : "";
  582. ?>
  583. <!DOCTYPE html>
  584. <html>
  585. <head>
  586. <?php echo stylesheet_tag("css/default.css") ?>
  587. <title>Feed Debugger</title>
  588. <?php
  589. echo stylesheet_tag("css/default.css");
  590. echo javascript_tag("lib/prototype.js");
  591. echo javascript_tag("lib/dojo/dojo.js");
  592. echo javascript_tag("lib/dojo/tt-rss-layer.js");
  593. ?>
  594. </head>
  595. <body class="flat ttrss_utility feed_debugger">
  596. <script type="text/javascript">
  597. require(['dojo/parser', "dojo/ready", 'dijit/form/Button','dijit/form/CheckBox', 'dijit/form/Form',
  598. 'dijit/form/Select','dijit/form/TextBox','dijit/form/ValidationTextBox'],function(parser, ready){
  599. ready(function() {
  600. parser.parse();
  601. });
  602. });
  603. </script>
  604. <div class="container">
  605. <h1>Feed Debugger: <?php echo "$feed_id: " . $this->getFeedTitle($feed_id) ?></h1>
  606. <div class="content">
  607. <form method="GET" action="">
  608. <input type="hidden" name="op" value="feeds">
  609. <input type="hidden" name="method" value="update_debugger">
  610. <input type="hidden" name="xdebug" value="1">
  611. <input type="hidden" name="csrf_token" value="<?php echo $csrf_token ?>">
  612. <input type="hidden" name="action" value="do_update">
  613. <input type="hidden" name="feed_id" value="<?php echo $feed_id ?>">
  614. <fieldset class="narrow">
  615. <label class="checkbox"><input dojoType="dijit.form.CheckBox" type="checkbox" name="force_refetch" value="1" <?php echo $refetch_checked ?>> Force refetch</label>
  616. </fieldset>
  617. <fieldset class="narrow">
  618. <label class="checkbox"><input dojoType="dijit.form.CheckBox" type="checkbox" name="force_rehash" value="1" <?php echo $rehash_checked ?>> Force rehash</label>
  619. </fieldset>
  620. <button type="submit" dojoType="dijit.form.Button" class="alt-primary">Continue</button>
  621. </form>
  622. <hr>
  623. <pre><?php
  624. if ($do_update) {
  625. RSSUtils::update_rss_feed($feed_id, true);
  626. }
  627. ?></pre>
  628. </div>
  629. </div>
  630. </body>
  631. </html>
  632. <?php
  633. }
  634. static function catchup_feed($feed, $cat_view, $owner_uid = false, $mode = 'all', $search = false) {
  635. if (!$owner_uid) $owner_uid = $_SESSION['uid'];
  636. $pdo = Db::pdo();
  637. if (is_array($search) && $search[0]) {
  638. $search_qpart = "";
  639. foreach (PluginHost::getInstance()->get_hooks(PluginHost::HOOK_SEARCH) as $plugin) {
  640. list($search_qpart, $search_words) = $plugin->hook_search($search[0]);
  641. break;
  642. }
  643. // fall back in case of no plugins
  644. if (!$search_qpart) {
  645. list($search_qpart, $search_words) = search_to_sql($search[0], $search[1]);
  646. }
  647. } else {
  648. $search_qpart = "true";
  649. }
  650. // TODO: all this interval stuff needs some generic generator function
  651. switch ($mode) {
  652. case "1day":
  653. if (DB_TYPE == "pgsql") {
  654. $date_qpart = "date_entered < NOW() - INTERVAL '1 day' ";
  655. } else {
  656. $date_qpart = "date_entered < DATE_SUB(NOW(), INTERVAL 1 DAY) ";
  657. }
  658. break;
  659. case "1week":
  660. if (DB_TYPE == "pgsql") {
  661. $date_qpart = "date_entered < NOW() - INTERVAL '1 week' ";
  662. } else {
  663. $date_qpart = "date_entered < DATE_SUB(NOW(), INTERVAL 1 WEEK) ";
  664. }
  665. break;
  666. case "2week":
  667. if (DB_TYPE == "pgsql") {
  668. $date_qpart = "date_entered < NOW() - INTERVAL '2 week' ";
  669. } else {
  670. $date_qpart = "date_entered < DATE_SUB(NOW(), INTERVAL 2 WEEK) ";
  671. }
  672. break;
  673. default:
  674. $date_qpart = "true";
  675. }
  676. if (is_numeric($feed)) {
  677. if ($cat_view) {
  678. if ($feed >= 0) {
  679. if ($feed > 0) {
  680. $children = Feeds::getChildCategories($feed, $owner_uid);
  681. array_push($children, $feed);
  682. $children = array_map("intval", $children);
  683. $children = join(",", $children);
  684. $cat_qpart = "cat_id IN ($children)";
  685. } else {
  686. $cat_qpart = "cat_id IS NULL";
  687. }
  688. $sth = $pdo->prepare("UPDATE ttrss_user_entries
  689. SET unread = false, last_read = NOW() WHERE ref_id IN
  690. (SELECT id FROM
  691. (SELECT DISTINCT id FROM ttrss_entries, ttrss_user_entries WHERE ref_id = id
  692. AND owner_uid = ? AND unread = true AND feed_id IN
  693. (SELECT id FROM ttrss_feeds WHERE $cat_qpart) AND $date_qpart AND $search_qpart) as tmp)");
  694. $sth->execute([$owner_uid]);
  695. } else if ($feed == -2) {
  696. $sth = $pdo->prepare("UPDATE ttrss_user_entries
  697. SET unread = false,last_read = NOW() WHERE (SELECT COUNT(*)
  698. FROM ttrss_user_labels2, ttrss_entries WHERE article_id = ref_id AND id = ref_id AND $date_qpart AND $search_qpart) > 0
  699. AND unread = true AND owner_uid = ?");
  700. $sth->execute([$owner_uid]);
  701. }
  702. } else if ($feed > 0) {
  703. $sth = $pdo->prepare("UPDATE ttrss_user_entries
  704. SET unread = false, last_read = NOW() WHERE ref_id IN
  705. (SELECT id FROM
  706. (SELECT DISTINCT id FROM ttrss_entries, ttrss_user_entries WHERE ref_id = id
  707. AND owner_uid = ? AND unread = true AND feed_id = ? AND $date_qpart AND $search_qpart) as tmp)");
  708. $sth->execute([$owner_uid, $feed]);
  709. } else if ($feed < 0 && $feed > LABEL_BASE_INDEX) { // special, like starred
  710. if ($feed == -1) {
  711. $sth = $pdo->prepare("UPDATE ttrss_user_entries
  712. SET unread = false, last_read = NOW() WHERE ref_id IN
  713. (SELECT id FROM
  714. (SELECT DISTINCT id FROM ttrss_entries, ttrss_user_entries WHERE ref_id = id
  715. AND owner_uid = ? AND unread = true AND marked = true AND $date_qpart AND $search_qpart) as tmp)");
  716. $sth->execute([$owner_uid]);
  717. }
  718. if ($feed == -2) {
  719. $sth = $pdo->prepare("UPDATE ttrss_user_entries
  720. SET unread = false, last_read = NOW() WHERE ref_id IN
  721. (SELECT id FROM
  722. (SELECT DISTINCT id FROM ttrss_entries, ttrss_user_entries WHERE ref_id = id
  723. AND owner_uid = ? AND unread = true AND published = true AND $date_qpart AND $search_qpart) as tmp)");
  724. $sth->execute([$owner_uid]);
  725. }
  726. if ($feed == -3) {
  727. $intl = (int) get_pref("FRESH_ARTICLE_MAX_AGE");
  728. if (DB_TYPE == "pgsql") {
  729. $match_part = "date_entered > NOW() - INTERVAL '$intl hour' ";
  730. } else {
  731. $match_part = "date_entered > DATE_SUB(NOW(),
  732. INTERVAL $intl HOUR) ";
  733. }
  734. $sth = $pdo->prepare("UPDATE ttrss_user_entries
  735. SET unread = false, last_read = NOW() WHERE ref_id IN
  736. (SELECT id FROM
  737. (SELECT DISTINCT id FROM ttrss_entries, ttrss_user_entries WHERE ref_id = id
  738. AND owner_uid = ? AND score >= 0 AND unread = true AND $date_qpart AND $match_part AND $search_qpart) as tmp)");
  739. $sth->execute([$owner_uid]);
  740. }
  741. if ($feed == -4) {
  742. $sth = $pdo->prepare("UPDATE ttrss_user_entries
  743. SET unread = false, last_read = NOW() WHERE ref_id IN
  744. (SELECT id FROM
  745. (SELECT DISTINCT id FROM ttrss_entries, ttrss_user_entries WHERE ref_id = id
  746. AND owner_uid = ? AND unread = true AND $date_qpart AND $search_qpart) as tmp)");
  747. $sth->execute([$owner_uid]);
  748. }
  749. } else if ($feed < LABEL_BASE_INDEX) { // label
  750. $label_id = Labels::feed_to_label_id($feed);
  751. $sth = $pdo->prepare("UPDATE ttrss_user_entries
  752. SET unread = false, last_read = NOW() WHERE ref_id IN
  753. (SELECT id FROM
  754. (SELECT DISTINCT ttrss_entries.id FROM ttrss_entries, ttrss_user_entries, ttrss_user_labels2 WHERE ref_id = id
  755. AND label_id = ? AND ref_id = article_id
  756. AND owner_uid = ? AND unread = true AND $date_qpart AND $search_qpart) as tmp)");
  757. $sth->execute([$label_id, $owner_uid]);
  758. }
  759. CCache::update($feed, $owner_uid, $cat_view);
  760. } else { // tag
  761. $sth = $pdo->prepare("UPDATE ttrss_user_entries
  762. SET unread = false, last_read = NOW() WHERE ref_id IN
  763. (SELECT id FROM
  764. (SELECT DISTINCT ttrss_entries.id FROM ttrss_entries, ttrss_user_entries, ttrss_tags WHERE ref_id = ttrss_entries.id
  765. AND post_int_id = int_id AND tag_name = ?
  766. AND ttrss_user_entries.owner_uid = ? AND unread = true AND $date_qpart AND $search_qpart) as tmp)");
  767. $sth->execute([$feed, $owner_uid]);
  768. }
  769. }
  770. static function getFeedArticles($feed, $is_cat = false, $unread_only = false,
  771. $owner_uid = false) {
  772. $n_feed = (int) $feed;
  773. $need_entries = false;
  774. $pdo = Db::pdo();
  775. if (!$owner_uid) $owner_uid = $_SESSION["uid"];
  776. if ($unread_only) {
  777. $unread_qpart = "unread = true";
  778. } else {
  779. $unread_qpart = "true";
  780. }
  781. $match_part = "";
  782. if ($is_cat) {
  783. return Feeds::getCategoryUnread($n_feed, $owner_uid);
  784. } else if ($n_feed == -6) {
  785. return 0;
  786. } else if ($feed != "0" && $n_feed == 0) {
  787. $sth = $pdo->prepare("SELECT SUM((SELECT COUNT(int_id)
  788. FROM ttrss_user_entries,ttrss_entries WHERE int_id = post_int_id
  789. AND ref_id = id AND $unread_qpart)) AS count FROM ttrss_tags
  790. WHERE owner_uid = ? AND tag_name = ?");
  791. $sth->execute([$owner_uid, $feed]);
  792. $row = $sth->fetch();
  793. return $row["count"];
  794. } else if ($n_feed == -1) {
  795. $match_part = "marked = true";
  796. } else if ($n_feed == -2) {
  797. $match_part = "published = true";
  798. } else if ($n_feed == -3) {
  799. $match_part = "unread = true AND score >= 0";
  800. $intl = (int) get_pref("FRESH_ARTICLE_MAX_AGE", $owner_uid);
  801. if (DB_TYPE == "pgsql") {
  802. $match_part .= " AND date_entered > NOW() - INTERVAL '$intl hour' ";
  803. } else {
  804. $match_part .= " AND date_entered > DATE_SUB(NOW(), INTERVAL $intl HOUR) ";
  805. }
  806. $need_entries = true;
  807. } else if ($n_feed == -4) {
  808. $match_part = "true";
  809. } else if ($n_feed >= 0) {
  810. if ($n_feed != 0) {
  811. $match_part = "feed_id = " . (int)$n_feed;
  812. } else {
  813. $match_part = "feed_id IS NULL";
  814. }
  815. } else if ($feed < LABEL_BASE_INDEX) {
  816. $label_id = Labels::feed_to_label_id($feed);
  817. return Feeds::getLabelUnread($label_id, $owner_uid);
  818. }
  819. if ($match_part) {
  820. if ($need_entries) {
  821. $from_qpart = "ttrss_user_entries,ttrss_entries";
  822. $from_where = "ttrss_entries.id = ttrss_user_entries.ref_id AND";
  823. } else {
  824. $from_qpart = "ttrss_user_entries";
  825. $from_where = "";
  826. }
  827. $sth = $pdo->prepare("SELECT count(int_id) AS unread
  828. FROM $from_qpart WHERE
  829. $unread_qpart AND $from_where ($match_part) AND ttrss_user_entries.owner_uid = ?");
  830. $sth->execute([$owner_uid]);
  831. $row = $sth->fetch();
  832. return $row["unread"];
  833. } else {
  834. $sth = $pdo->prepare("SELECT COUNT(post_int_id) AS unread
  835. FROM ttrss_tags,ttrss_user_entries,ttrss_entries
  836. WHERE tag_name = ? AND post_int_id = int_id AND ref_id = ttrss_entries.id
  837. AND $unread_qpart AND ttrss_tags.owner_uid = ,");
  838. $sth->execute([$feed, $owner_uid]);
  839. $row = $sth->fetch();
  840. return $row["unread"];
  841. }
  842. }
  843. /**
  844. * @return array (code => Status code, message => error message if available)
  845. *
  846. * 0 - OK, Feed already exists
  847. * 1 - OK, Feed added
  848. * 2 - Invalid URL
  849. * 3 - URL content is HTML, no feeds available
  850. * 4 - URL content is HTML which contains multiple feeds.
  851. * Here you should call extractfeedurls in rpc-backend
  852. * to get all possible feeds.
  853. * 5 - Couldn't download the URL content.
  854. * 6 - Content is an invalid XML.
  855. */
  856. static function subscribe_to_feed($url, $cat_id = 0,
  857. $auth_login = '', $auth_pass = '') {
  858. global $fetch_last_error;
  859. global $fetch_last_error_content;
  860. global $fetch_last_content_type;
  861. $pdo = Db::pdo();
  862. $url = Feeds::fix_url($url);
  863. if (!$url || !Feeds::validate_feed_url($url)) return array("code" => 2);
  864. $contents = @fetch_file_contents($url, false, $auth_login, $auth_pass);
  865. foreach (PluginHost::getInstance()->get_hooks(PluginHost::HOOK_SUBSCRIBE_FEED) as $plugin) {
  866. $contents = $plugin->hook_subscribe_feed($contents, $url, $auth_login, $auth_pass);
  867. }
  868. if (!$contents) {
  869. if (preg_match("/cloudflare\.com/", $fetch_last_error_content)) {
  870. $fetch_last_error .= " (feed behind Cloudflare)";
  871. }
  872. return array("code" => 5, "message" => $fetch_last_error);
  873. }
  874. if (mb_strpos($fetch_last_content_type, "html") !== FALSE && Feeds::is_html($contents)) {
  875. $feedUrls = Feeds::get_feeds_from_html($url, $contents);
  876. if (count($feedUrls) == 0) {
  877. return array("code" => 3);
  878. } else if (count($feedUrls) > 1) {
  879. return array("code" => 4, "feeds" => $feedUrls);
  880. }
  881. //use feed url as new URL
  882. $url = key($feedUrls);
  883. }
  884. if (!$cat_id) $cat_id = null;
  885. $sth = $pdo->prepare("SELECT id FROM ttrss_feeds
  886. WHERE feed_url = ? AND owner_uid = ?");
  887. $sth->execute([$url, $_SESSION['uid']]);
  888. if ($row = $sth->fetch()) {
  889. return array("code" => 0, "feed_id" => (int) $row["id"]);
  890. } else {
  891. $sth = $pdo->prepare(
  892. "INSERT INTO ttrss_feeds
  893. (owner_uid,feed_url,title,cat_id, auth_login,auth_pass,update_method,auth_pass_encrypted)
  894. VALUES (?, ?, ?, ?, ?, ?, 0, false)");
  895. $sth->execute([$_SESSION['uid'], $url, "[Unknown]", $cat_id, (string)$auth_login, (string)$auth_pass]);
  896. $sth = $pdo->prepare("SELECT id FROM ttrss_feeds WHERE feed_url = ?
  897. AND owner_uid = ?");
  898. $sth->execute([$url, $_SESSION['uid']]);
  899. $row = $sth->fetch();
  900. $feed_id = $row["id"];
  901. if ($feed_id) {
  902. RSSUtils::set_basic_feed_info($feed_id);
  903. }
  904. return array("code" => 1, "feed_id" => (int) $feed_id);
  905. }
  906. }
  907. static function getIconFile($feed_id) {
  908. return ICONS_DIR . "/$feed_id.ico";
  909. }
  910. static function feedHasIcon($id) {
  911. return is_file(ICONS_DIR . "/$id.ico") && filesize(ICONS_DIR . "/$id.ico") > 0;
  912. }
  913. static function getFeedIcon($id) {
  914. switch ($id) {
  915. case 0:
  916. return "archive";
  917. break;
  918. case -1:
  919. return "star";
  920. break;
  921. case -2:
  922. return "rss_feed";
  923. break;
  924. case -3:
  925. return "whatshot";
  926. break;
  927. case -4:
  928. return "inbox";
  929. break;
  930. case -6:
  931. return "restore";
  932. break;
  933. default:
  934. if ($id < LABEL_BASE_INDEX) {
  935. return "label";
  936. } else {
  937. $icon = self::getIconFile($id);
  938. if ($icon && file_exists($icon)) {
  939. return ICONS_URL . "/" . basename($icon) . "?" . filemtime($icon);
  940. }
  941. }
  942. break;
  943. }
  944. return false;
  945. }
  946. static function getFeedTitle($id, $cat = false) {
  947. $pdo = Db::pdo();
  948. if ($cat) {
  949. return Feeds::getCategoryTitle($id);
  950. } else if ($id == -1) {
  951. return __("Starred articles");
  952. } else if ($id == -2) {
  953. return __("Published articles");
  954. } else if ($id == -3) {
  955. return __("Fresh articles");
  956. } else if ($id == -4) {
  957. return __("All articles");
  958. } else if ($id === 0 || $id === "0") {
  959. return __("Archived articles");
  960. } else if ($id == -6) {
  961. return __("Recently read");
  962. } else if ($id < LABEL_BASE_INDEX) {
  963. $label_id = Labels::feed_to_label_id($id);
  964. $sth = $pdo->prepare("SELECT caption FROM ttrss_labels2 WHERE id = ?");
  965. $sth->execute([$label_id]);
  966. if ($row = $sth->fetch()) {
  967. return $row["caption"];
  968. } else {
  969. return "Unknown label ($label_id)";
  970. }
  971. } else if (is_numeric($id) && $id > 0) {
  972. $sth = $pdo->prepare("SELECT title FROM ttrss_feeds WHERE id = ?");
  973. $sth->execute([$id]);
  974. if ($row = $sth->fetch()) {
  975. return $row["title"];
  976. } else {
  977. return "Unknown feed ($id)";
  978. }
  979. } else {
  980. return $id;
  981. }
  982. }
  983. static function getCategoryUnread($cat, $owner_uid = false) {
  984. if (!$owner_uid) $owner_uid = $_SESSION["uid"];
  985. $pdo = Db::pdo();
  986. if ($cat >= 0) {
  987. if (!$cat) $cat = null;
  988. $sth = $pdo->prepare("SELECT id FROM ttrss_feeds
  989. WHERE (cat_id = :cat OR (:cat IS NULL AND cat_id IS NULL))
  990. AND owner_uid = :uid");
  991. $sth->execute([":cat" => $cat, ":uid" => $owner_uid]);
  992. $cat_feeds = array();
  993. while ($line = $sth->fetch()) {
  994. array_push($cat_feeds, "feed_id = " . (int)$line["id"]);
  995. }
  996. if (count($cat_feeds) == 0) return 0;
  997. $match_part = implode(" OR ", $cat_feeds);
  998. $sth = $pdo->prepare("SELECT COUNT(int_id) AS unread
  999. FROM ttrss_user_entries
  1000. WHERE unread = true AND ($match_part)
  1001. AND owner_uid = ?");
  1002. $sth->execute([$owner_uid]);
  1003. $unread = 0;
  1004. # this needs to be rewritten
  1005. while ($line = $sth->fetch()) {
  1006. $unread += $line["unread"];
  1007. }
  1008. return $unread;
  1009. } else if ($cat == -1) {
  1010. return getFeedUnread(-1) + getFeedUnread(-2) + getFeedUnread(-3) + getFeedUnread(0);
  1011. } else if ($cat == -2) {
  1012. $sth = $pdo->prepare("SELECT COUNT(unread) AS unread FROM
  1013. ttrss_user_entries, ttrss_user_labels2
  1014. WHERE article_id = ref_id AND unread = true
  1015. AND ttrss_user_entries.owner_uid = ?");
  1016. $sth->execute([$owner_uid]);
  1017. $row = $sth->fetch();
  1018. return $row["unread"];
  1019. }
  1020. }
  1021. // only accepts real cats (>= 0)
  1022. static function getCategoryChildrenUnread($cat, $owner_uid = false) {
  1023. if (!$owner_uid) $owner_uid = $_SESSION["uid"];
  1024. $pdo = Db::pdo();
  1025. $sth = $pdo->prepare("SELECT id FROM ttrss_feed_categories WHERE parent_cat = ?
  1026. AND owner_uid = ?");
  1027. $sth->execute([$cat, $owner_uid]);
  1028. $unread = 0;
  1029. while ($line = $sth->fetch()) {
  1030. $unread += Feeds::getCategoryUnread($line["id"], $owner_uid);
  1031. $unread += Feeds::getCategoryChildrenUnread($line["id"], $owner_uid);
  1032. }
  1033. return $unread;
  1034. }
  1035. static function getGlobalUnread($user_id = false) {
  1036. if (!$user_id) $user_id = $_SESSION["uid"];
  1037. $pdo = Db::pdo();
  1038. $sth = $pdo->prepare("SELECT SUM(value) AS c_id FROM ttrss_counters_cache
  1039. WHERE owner_uid = ? AND feed_id > 0");
  1040. $sth->execute([$user_id]);
  1041. $row = $sth->fetch();
  1042. return $row["c_id"];
  1043. }
  1044. static function getCategoryTitle($cat_id) {
  1045. if ($cat_id == -1) {
  1046. return __("Special");
  1047. } else if ($cat_id == -2) {
  1048. return __("Labels");
  1049. } else {
  1050. $pdo = Db::pdo();
  1051. $sth = $pdo->prepare("SELECT title FROM ttrss_feed_categories WHERE
  1052. id = ?");
  1053. $sth->execute([$cat_id]);
  1054. if ($row = $sth->fetch()) {
  1055. return $row["title"];
  1056. } else {
  1057. return __("Uncategorized");
  1058. }
  1059. }
  1060. }
  1061. static function getLabelUnread($label_id, $owner_uid = false) {
  1062. if (!$owner_uid) $owner_uid = $_SESSION["uid"];
  1063. $pdo = Db::pdo();
  1064. $sth = $pdo->prepare("SELECT COUNT(ref_id) AS unread FROM ttrss_user_entries, ttrss_user_labels2
  1065. WHERE owner_uid = ? AND unread = true AND label_id = ? AND article_id = ref_id");
  1066. $sth->execute([$owner_uid, $label_id]);
  1067. if ($row = $sth->fetch()) {
  1068. return $row["unread"];
  1069. } else {
  1070. return 0;
  1071. }
  1072. }
  1073. static function queryFeedHeadlines($params) {
  1074. $pdo = Db::pdo();
  1075. // WARNING: due to highly dynamic nature of this query its going to quote parameters
  1076. // right before adding them to SQL part
  1077. $feed = $params["feed"];
  1078. $limit = isset($params["limit"]) ? $params["limit"] : 30;
  1079. $view_mode = $params["view_mode"];
  1080. $cat_view = isset($params["cat_view"]) ? $params["cat_view"] : false;
  1081. $search = isset($params["search"]) ? $params["search"] : false;
  1082. $search_language = isset($params["search_language"]) ? $params["search_language"] : "";
  1083. $override_order = isset($params["override_order"]) ? $params["override_order"] : false;
  1084. $offset = isset($params["offset"]) ? $params["offset"] : 0;
  1085. $owner_uid = isset($params["owner_uid"]) ? $params["owner_uid"] : $_SESSION["uid"];
  1086. $since_id = isset($params["since_id"]) ? $params["since_id"] : 0;
  1087. $include_children = isset($params["include_children"]) ? $params["include_children"] : false;
  1088. $ignore_vfeed_group = isset($params["ignore_vfeed_group"]) ? $params["ignore_vfeed_group"] : false;
  1089. $override_strategy = isset($params["override_strategy"]) ? $params["override_strategy"] : false;
  1090. $override_vfeed = isset($params["override_vfeed"]) ? $params["override_vfeed"] : false;
  1091. $start_ts = isset($params["start_ts"]) ? $params["start_ts"] : false;
  1092. $check_first_id = isset($params["check_first_id"]) ? $params["check_first_id"] : false;
  1093. $skip_first_id_check = isset($params["skip_first_id_check"]) ? $params["skip_first_id_check"] : false;
  1094. $order_by = isset($params["order_by"]) ? $params["order_by"] : false;
  1095. $ext_tables_part = "";
  1096. $limit_query_part = "";
  1097. $query_error_override = "";
  1098. $search_words = [];
  1099. if ($search) {
  1100. $search_query_part = "";
  1101. foreach (PluginHost::getInstance()->get_hooks(PluginHost::HOOK_SEARCH) as $plugin) {
  1102. list($search_query_part, $search_words) = $plugin->hook_search($search);
  1103. break;
  1104. }
  1105. // fall back in case of no plugins
  1106. if (!$search_query_part) {
  1107. list($search_query_part, $search_words) = search_to_sql($search, $search_language);
  1108. }
  1109. if (DB_TYPE == "pgsql") {
  1110. $test_sth = $pdo->prepare("select $search_query_part
  1111. FROM ttrss_entries, ttrss_user_entries WHERE id = ref_id limit 1");
  1112. try {
  1113. $test_sth->execute();
  1114. } catch (PDOException $e) {
  1115. // looks like tsquery syntax is invalid
  1116. $search_query_part = "false";
  1117. $query_error_override = T_sprintf("Incorrect search syntax: %s.", implode(" ", $search_words));
  1118. }
  1119. }
  1120. $search_query_part .= " AND ";
  1121. } else {
  1122. $search_query_part = "";
  1123. }
  1124. if ($since_id) {
  1125. $since_id_part = "ttrss_entries.id > ".$pdo->quote($since_id)." AND ";
  1126. } else {
  1127. $since_id_part = "";
  1128. }
  1129. $view_query_part = "";
  1130. if ($view_mode == "adaptive") {
  1131. if ($search) {
  1132. $view_query_part = " ";
  1133. } else if ($feed != -1) {
  1134. $unread = getFeedUnread($feed, $cat_view);
  1135. if ($cat_view && $feed > 0 && $include_children)
  1136. $unread += Feeds::getCategoryChildrenUnread($feed);
  1137. if ($unread > 0) {
  1138. $view_query_part = " unread = true AND ";
  1139. }
  1140. }
  1141. }
  1142. if ($view_mode == "marked") {
  1143. $view_query_part = " marked = true AND ";
  1144. }
  1145. if ($view_mode == "has_note") {
  1146. $view_query_part = " (note IS NOT NULL AND note != '') AND ";
  1147. }
  1148. if ($view_mode == "published") {
  1149. $view_query_part = " published = true AND ";
  1150. }
  1151. if ($view_mode == "unread" && $feed != -6) {
  1152. $view_query_part = " unread = true AND ";
  1153. }
  1154. if ($limit > 0) {
  1155. $limit_query_part = "LIMIT " . (int)$limit;
  1156. }
  1157. $allow_archived = false;
  1158. $vfeed_query_part = "";
  1159. /* tags */
  1160. if (!is_numeric($feed)) {
  1161. $query_strategy_part = "true";
  1162. $vfeed_query_part = "(SELECT title FROM ttrss_feeds WHERE
  1163. id = feed_id) as feed_title,";
  1164. } else if ($feed > 0) {
  1165. if ($cat_view) {
  1166. if ($feed > 0) {
  1167. if ($include_children) {
  1168. # sub-cats
  1169. $subcats = Feeds::getChildCategories($feed, $owner_uid);
  1170. array_push($subcats, $feed);
  1171. $subcats = array_map("intval", $subcats);
  1172. $query_strategy_part = "cat_id IN (".
  1173. implode(",", $subcats).")";
  1174. } else {
  1175. $query_strategy_part = "cat_id = " . $pdo->quote($feed);
  1176. }
  1177. } else {
  1178. $query_strategy_part = "cat_id IS NULL";
  1179. }
  1180. $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
  1181. } else {
  1182. $query_strategy_part = "feed_id = " . $pdo->quote($feed);
  1183. }
  1184. } else if ($feed == 0 && !$cat_view) { // archive virtual feed
  1185. $query_strategy_part = "feed_id IS NULL";
  1186. $allow_archived = true;
  1187. } else if ($feed == 0 && $cat_view) { // uncategorized
  1188. $query_strategy_part = "cat_id IS NULL AND feed_id IS NOT NULL";
  1189. $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
  1190. } else if ($feed == -1) { // starred virtual feed
  1191. $query_strategy_part = "marked = true";
  1192. $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
  1193. $allow_archived = true;
  1194. if (!$override_order) {
  1195. $override_order = "last_marked DESC, date_entered DESC, updated DESC";
  1196. }
  1197. } else if ($feed == -2) { // published virtual feed OR labels category
  1198. if (!$cat_view) {
  1199. $query_strategy_part = "published = true";
  1200. $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
  1201. $allow_archived = true;
  1202. if (!$override_order) {
  1203. $override_order = "last_published DESC, date_entered DESC, updated DESC";
  1204. }
  1205. } else {
  1206. $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
  1207. $ext_tables_part = "ttrss_labels2,ttrss_user_labels2,";
  1208. $query_strategy_part = "ttrss_labels2.id = ttrss_user_labels2.label_id AND
  1209. ttrss_user_labels2.article_id = ref_id";
  1210. }
  1211. } else if ($feed == -6) { // recently read
  1212. $query_strategy_part = "unread = false AND last_read IS NOT NULL";
  1213. if (DB_TYPE == "pgsql") {
  1214. $query_strategy_part .= " AND last_read > NOW() - INTERVAL '1 DAY' ";
  1215. } else {
  1216. $query_strategy_part .= " AND last_read > DATE_SUB(NOW(), INTERVAL 1 DAY) ";
  1217. }
  1218. $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
  1219. $allow_archived = true;
  1220. $ignore_vfeed_group = true;
  1221. if (!$override_order) $override_order = "last_read DESC";
  1222. } else if ($feed == -3) { // fresh virtual feed
  1223. $query_strategy_part = "unread = true AND score >= 0";
  1224. $intl = (int) get_pref("FRESH_ARTICLE_MAX_AGE", $owner_uid);
  1225. if (DB_TYPE == "pgsql") {
  1226. $query_strategy_part .= " AND date_entered > NOW() - INTERVAL '$intl hour' ";
  1227. } else {
  1228. $query_strategy_part .= " AND date_entered > DATE_SUB(NOW(), INTERVAL $intl HOUR) ";
  1229. }
  1230. $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
  1231. } else if ($feed == -4) { // all articles virtual feed
  1232. $allow_archived = true;
  1233. $query_strategy_part = "true";
  1234. $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
  1235. } else if ($feed <= LABEL_BASE_INDEX) { // labels
  1236. $label_id = Labels::feed_to_label_id($feed);
  1237. $query_strategy_part = "label_id = ".$pdo->quote($label_id)." AND
  1238. ttrss_labels2.id = ttrss_user_labels2.label_id AND
  1239. ttrss_user_labels2.article_id = ref_id";
  1240. $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
  1241. $ext_tables_part = "ttrss_labels2,ttrss_user_labels2,";
  1242. $allow_archived = true;
  1243. } else {
  1244. $query_strategy_part = "true";
  1245. }
  1246. $order_by = "score DESC, date_entered DESC, updated DESC";
  1247. if ($override_order) {
  1248. $order_by = $override_order;
  1249. }
  1250. if ($override_strategy) {
  1251. $query_strategy_part = $override_strategy;
  1252. }
  1253. if ($override_vfeed) {
  1254. $vfeed_query_part = $override_vfeed;
  1255. }
  1256. if ($search) {
  1257. $feed_title = T_sprintf("Search results: %s", $search);
  1258. } else {
  1259. if ($cat_view) {
  1260. $feed_title = Feeds::getCategoryTitle($feed);
  1261. } else {
  1262. if (is_numeric($feed) && $feed > 0) {
  1263. $ssth = $pdo->prepare("SELECT title,site_url,last_error,last_updated
  1264. FROM ttrss_feeds WHERE id = ? AND owner_uid = ?");
  1265. $ssth->execute([$feed, $owner_uid]);
  1266. $row = $ssth->fetch();
  1267. $feed_title = $row["title"];
  1268. $feed_site_url = $row["site_url"];
  1269. $last_error = $row["last_error"];
  1270. $last_updated = $row["last_updated"];
  1271. } else {
  1272. $feed_title = Feeds::getFeedTitle($feed);
  1273. }
  1274. }
  1275. }
  1276. $content_query_part = "content, ";
  1277. if ($limit_query_part) {
  1278. $offset_query_part = "OFFSET " . (int)$offset;
  1279. } else {
  1280. $offset_query_part = "";
  1281. }
  1282. if ($start_ts) {
  1283. $start_ts_formatted = date("Y/m/d H:i:s", strtotime($start_ts));
  1284. $start_ts_query_part = "date_entered >= '$start_ts_formatted' AND";
  1285. } else {
  1286. $start_ts_query_part = "";
  1287. }
  1288. if (is_numeric($feed)) {
  1289. // proper override_order applied above
  1290. if ($vfeed_query_part && !$ignore_vfeed_group && get_pref('VFEED_GROUP_BY_FEED', $owner_uid)) {
  1291. $yyiw_desc = $order_by == "date_reverse" ? "" : "desc";
  1292. if (!$override_order) {
  1293. $order_by = "yyiw $yyiw_desc, ttrss_feeds.title, ".$order_by;
  1294. } else {
  1295. $order_by = "yyiw $yyiw_desc, ttrss_feeds.title, ".$override_order;
  1296. }
  1297. }
  1298. if (!$allow_archived) {
  1299. $from_qpart = "${ext_tables_part}ttrss_entries LEFT JOIN ttrss_user_entries ON (ref_id = ttrss_entries.id),ttrss_feeds";
  1300. $feed_check_qpart = "ttrss_user_entries.feed_id = ttrss_feeds.id AND";
  1301. } else {
  1302. $from_qpart = "${ext_tables_part}ttrss_entries LEFT JOIN ttrss_user_entries ON (ref_id = ttrss_entries.id)
  1303. LEFT JOIN ttrss_feeds ON (feed_id = ttrss_feeds.id)";
  1304. }
  1305. if ($vfeed_query_part) $vfeed_query_part .= "favicon_avg_color,";
  1306. $first_id = 0;
  1307. $first_id_query_strategy_part = $query_strategy_part;
  1308. if ($feed == -3)
  1309. $first_id_query_strategy_part = "true";
  1310. if (DB_TYPE == "pgsql") {
  1311. $sanity_interval_qpart = "date_entered >= NOW() - INTERVAL '1 hour' AND";
  1312. $yyiw_qpart = "to_char(date_entered, 'IYYY-IW') AS yyiw";
  1313. } else {
  1314. $sanity_interval_qpart = "date_entered >= DATE_SUB(NOW(), INTERVAL 1 hour) AND";
  1315. $yyiw_qpart = "date_format(date_entered, '%Y-%u') AS yyiw";
  1316. }
  1317. if (!$search && !$skip_first_id_check) {
  1318. // if previous topmost article id changed that means our current pagination is no longer valid
  1319. $query = "SELECT DISTINCT
  1320. ttrss_feeds.title,
  1321. date_entered,
  1322. $yyiw_qpart,
  1323. guid,
  1324. ttrss_entries.id,
  1325. ttrss_entries.title,
  1326. updated,
  1327. score,
  1328. marked,
  1329. published,
  1330. last_marked,
  1331. last_published,
  1332. last_read
  1333. FROM
  1334. $from_qpart
  1335. WHERE
  1336. $feed_check_qpart
  1337. ttrss_user_entries.owner_uid = ".$pdo->quote($owner_uid)." AND
  1338. $search_query_part
  1339. $start_ts_query_part
  1340. $since_id_part
  1341. $sanity_interval_qpart
  1342. $first_id_query_strategy_part ORDER BY $order_by LIMIT 1";
  1343. /*if ($_REQUEST["debug"]) {
  1344. print $query;
  1345. }*/
  1346. $res = $pdo->query($query);
  1347. if ($row = $res->fetch()) {
  1348. $first_id = (int)$row["id"];
  1349. if ($offset > 0 && $first_id && $check_first_id && $first_id != $check_first_id) {
  1350. return array(-1, $feed_title, $feed_site_url, $last_error, $last_updated, $search_words, $first_id, $vfeed_query_part != "", $query_error_override);
  1351. }
  1352. }
  1353. }
  1354. $query = "SELECT DISTINCT
  1355. date_entered,
  1356. $yyiw_qpart,
  1357. guid,
  1358. ttrss_entries.id,ttrss_entries.title,
  1359. updated,
  1360. label_cache,
  1361. tag_cache,
  1362. always_display_enclosures,
  1363. site_url,
  1364. note,
  1365. num_comments,
  1366. comments,
  1367. int_id,
  1368. uuid,
  1369. lang,
  1370. hide_images,
  1371. unread,feed_id,marked,published,link,last_read,orig_feed_id,
  1372. last_marked, last_published,
  1373. $vfeed_query_part
  1374. $content_query_part
  1375. author,score
  1376. FROM
  1377. $from_qpart
  1378. WHERE
  1379. $feed_check_qpart
  1380. ttrss_user_entries.owner_uid = ".$pdo->quote($owner_uid)." AND
  1381. $search_query_part
  1382. $start_ts_query_part
  1383. $view_query_part
  1384. $since_id_part
  1385. $query_strategy_part ORDER BY $order_by
  1386. $limit_query_part $offset_query_part";
  1387. //if ($_REQUEST["debug"]) print $query;
  1388. $res = $pdo->query($query);
  1389. } else {
  1390. // browsing by tag
  1391. $query = "SELECT DISTINCT
  1392. date_entered,
  1393. guid,
  1394. note,
  1395. ttrss_entries.id as id,
  1396. title,
  1397. updated,
  1398. unread,
  1399. feed_id,
  1400. orig_feed_id,
  1401. marked,
  1402. published,
  1403. num_comments,
  1404. comments,
  1405. int_id,
  1406. tag_cache,
  1407. label_cache,
  1408. link,
  1409. lang,
  1410. uuid,
  1411. last_read,
  1412. (SELECT hide_images FROM ttrss_feeds WHERE id = feed_id) AS hide_images,
  1413. last_marked, last_published,
  1414. $since_id_part
  1415. $vfeed_query_part
  1416. $content_query_part
  1417. author, score
  1418. FROM ttrss_entries, ttrss_user_entries, ttrss_tags
  1419. WHERE
  1420. ref_id = ttrss_entries.id AND
  1421. ttrss_user_entries.owner_uid = ".$pdo->quote($owner_uid)." AND
  1422. post_int_id = int_id AND
  1423. tag_name = ".$pdo->quote($feed)." AND
  1424. $view_query_part
  1425. $search_query_part
  1426. $start_ts_query_part
  1427. $query_strategy_part ORDER BY $order_by
  1428. $limit_query_part $offset_query_part";
  1429. if ($_REQUEST["debug"]) print $query;
  1430. $res = $pdo->query($query);
  1431. }
  1432. return array($res, $feed_title, $feed_site_url, $last_error, $last_updated, $search_words, $first_id, $vfeed_query_part != "", $query_error_override);
  1433. }
  1434. static function getParentCategories($cat, $owner_uid) {
  1435. $rv = array();
  1436. $pdo = Db::pdo();
  1437. $sth = $pdo->prepare("SELECT parent_cat FROM ttrss_feed_categories
  1438. WHERE id = ? AND parent_cat IS NOT NULL AND owner_uid = ?");
  1439. $sth->execute([$cat, $owner_uid]);
  1440. while ($line = $sth->fetch()) {
  1441. array_push($rv, $line["parent_cat"]);
  1442. $rv = array_merge($rv, Feeds::getParentCategories($line["parent_cat"], $owner_uid));
  1443. }
  1444. return $rv;
  1445. }
  1446. static function getChildCategories($cat, $owner_uid) {
  1447. $rv = array();
  1448. $pdo = Db::pdo();
  1449. $sth = $pdo->prepare("SELECT id FROM ttrss_feed_categories
  1450. WHERE parent_cat = ? AND owner_uid = ?");
  1451. $sth->execute([$cat, $owner_uid]);
  1452. while ($line = $sth->fetch()) {
  1453. array_push($rv, $line["id"]);
  1454. $rv = array_merge($rv, Feeds::getChildCategories($line["id"], $owner_uid));
  1455. }
  1456. return $rv;
  1457. }
  1458. static function getFeedCategory($feed) {
  1459. $pdo = Db::pdo();
  1460. $sth = $pdo->prepare("SELECT cat_id FROM ttrss_feeds
  1461. WHERE id = ?");
  1462. $sth->execute([$feed]);
  1463. if ($row = $sth->fetch()) {
  1464. return $row["cat_id"];
  1465. } else {
  1466. return false;
  1467. }
  1468. }
  1469. function color_of($name) {
  1470. $colormap = [ "#1cd7d7","#d91111","#1212d7","#8e16e5","#7b7b7b",
  1471. "#39f110","#0bbea6","#ec0e0e","#1534f2","#b9e416",
  1472. "#479af2","#f36b14","#10c7e9","#1e8fe7","#e22727" ];
  1473. $sum = 0;
  1474. for ($i = 0; $i < strlen($name); $i++) {
  1475. $sum += ord($name{$i});
  1476. }
  1477. $sum %= count($colormap);
  1478. return $colormap[$sum];
  1479. }
  1480. static function get_feeds_from_html($url, $content) {
  1481. $url = Feeds::fix_url($url);
  1482. $baseUrl = substr($url, 0, strrpos($url, '/') + 1);
  1483. libxml_use_internal_errors(true);
  1484. $feedUrls = [];
  1485. $doc = new DOMDocument();
  1486. if ($doc->loadHTML($content)) {
  1487. $xpath = new DOMXPath($doc);
  1488. $entries = $xpath->query('/html/head/link[@rel="alternate" and '.
  1489. '(contains(@type,"rss") or contains(@type,"atom"))]|/html/head/link[@rel="feed"]');
  1490. foreach ($entries as $entry) {
  1491. if ($entry->hasAttribute('href')) {
  1492. $title = $entry->getAttribute('title');
  1493. if ($title == '') {
  1494. $title = $entry->getAttribute('type');
  1495. }
  1496. $feedUrl = rewrite_relative_url(
  1497. $baseUrl, $entry->getAttribute('href')
  1498. );
  1499. $feedUrls[$feedUrl] = $title;
  1500. }
  1501. }
  1502. }
  1503. return $feedUrls;
  1504. }
  1505. static function is_html($content) {
  1506. return preg_match("/<html|DOCTYPE html/i", substr($content, 0, 8192)) !== 0;
  1507. }
  1508. static function validate_feed_url($url) {
  1509. $parts = parse_url($url);
  1510. return ($parts['scheme'] == 'http' || $parts['scheme'] == 'feed' || $parts['scheme'] == 'https');
  1511. }
  1512. /**
  1513. * Fixes incomplete URLs by prepending "http://".
  1514. * Also replaces feed:// with http://, and
  1515. * prepends a trailing slash if the url is a domain name only.
  1516. *
  1517. * @param string $url Possibly incomplete URL
  1518. *
  1519. * @return string Fixed URL.
  1520. */
  1521. static function fix_url($url) {
  1522. // support schema-less urls
  1523. if (strpos($url, '//') === 0) {
  1524. $url = 'https:' . $url;
  1525. }
  1526. if (strpos($url, '://') === false) {
  1527. $url = 'http://' . $url;
  1528. } else if (substr($url, 0, 5) == 'feed:') {
  1529. $url = 'http:' . substr($url, 5);
  1530. }
  1531. //prepend slash if the URL has no slash in it
  1532. // "http://www.example" -> "http://www.example/"
  1533. if (strpos($url, '/', strpos($url, ':') + 3) === false) {
  1534. $url .= '/';
  1535. }
  1536. //convert IDNA hostname to punycode if possible
  1537. if (function_exists("idn_to_ascii")) {
  1538. $parts = parse_url($url);
  1539. if (mb_detect_encoding($parts['host']) != 'ASCII')
  1540. {
  1541. $parts['host'] = idn_to_ascii($parts['host']);
  1542. $url = build_url($parts);
  1543. }
  1544. }
  1545. if ($url != "http:///")
  1546. return $url;
  1547. else
  1548. return '';
  1549. }
  1550. static function add_feed_category($feed_cat, $parent_cat_id = false, $order_id = 0) {
  1551. if (!$feed_cat) return false;
  1552. $feed_cat = mb_substr($feed_cat, 0, 250);
  1553. if (!$parent_cat_id) $parent_cat_id = null;
  1554. $pdo = Db::pdo();
  1555. $tr_in_progress = false;
  1556. try {
  1557. $pdo->beginTransaction();
  1558. } catch (Exception $e) {
  1559. $tr_in_progress = true;
  1560. }
  1561. $sth = $pdo->prepare("SELECT id FROM ttrss_feed_categories
  1562. WHERE (parent_cat = :parent OR (:parent IS NULL AND parent_cat IS NULL))
  1563. AND title = :title AND owner_uid = :uid");
  1564. $sth->execute([':parent' => $parent_cat_id, ':title' => $feed_cat, ':uid' => $_SESSION['uid']]);
  1565. if (!$sth->fetch()) {
  1566. $sth = $pdo->prepare("INSERT INTO ttrss_feed_categories (owner_uid,title,parent_cat,order_id)
  1567. VALUES (?, ?, ?, ?)");
  1568. $sth->execute([$_SESSION['uid'], $feed_cat, $parent_cat_id, (int)$order_id]);
  1569. if (!$tr_in_progress) $pdo->commit();
  1570. return true;
  1571. }
  1572. $pdo->commit();
  1573. return false;
  1574. }
  1575. static function get_feed_access_key($feed_id, $is_cat, $owner_uid = false) {
  1576. if (!$owner_uid) $owner_uid = $_SESSION["uid"];
  1577. $is_cat = bool_to_sql_bool($is_cat);
  1578. $pdo = Db::pdo();
  1579. $sth = $pdo->prepare("SELECT access_key FROM ttrss_access_keys
  1580. WHERE feed_id = ? AND is_cat = ?
  1581. AND owner_uid = ?");
  1582. $sth->execute([$feed_id, $is_cat, $owner_uid]);
  1583. if ($row = $sth->fetch()) {
  1584. return $row["access_key"];
  1585. } else {
  1586. $key = uniqid_short();
  1587. $sth = $pdo->prepare("INSERT INTO ttrss_access_keys
  1588. (access_key, feed_id, is_cat, owner_uid)
  1589. VALUES (?, ?, ?, ?)");
  1590. $sth->execute([$key, $feed_id, $is_cat, $owner_uid]);
  1591. return $key;
  1592. }
  1593. }
  1594. }