]> git.wh0rd.org Git - tt-rss.git/blob - classes/feeds.php
70e8ade939655a8cb8ee218c561a922d88f9bcca
[tt-rss.git] / classes / feeds.php
1 <?php
2 require_once "colors.php";
3
4 class Feeds extends Handler_Protected {
5
6     private $params;
7
8     function csrf_ignore($method) {
9                 $csrf_ignored = array("index", "feedbrowser", "quickaddfeed", "search");
10
11                 return array_search($method, $csrf_ignored) !== false;
12         }
13
14         private function format_headline_subtoolbar($feed_site_url, $feed_title,
15                         $feed_id, $is_cat, $search,
16                         $error, $feed_last_updated) {
17
18                 $catchup_sel_link = "catchupSelection()";
19
20                 $archive_sel_link = "archiveSelection()";
21                 $delete_sel_link = "deleteSelection()";
22
23                 $sel_all_link = "selectArticles('all')";
24                 $sel_unread_link = "selectArticles('unread')";
25                 $sel_none_link = "selectArticles('none')";
26                 $sel_inv_link = "selectArticles('invert')";
27
28                 $tog_unread_link = "selectionToggleUnread()";
29                 $tog_marked_link = "selectionToggleMarked()";
30                 $tog_published_link = "selectionTogglePublished()";
31
32                 $set_score_link = "setSelectionScore()";
33
34                 if ($is_cat) $cat_q = "&is_cat=$is_cat";
35
36                 if ($search) {
37                         $search_q = "&q=$search";
38                 } else {
39                         $search_q = "";
40                 }
41
42                 $reply = "<span class=\"holder\">";
43
44                 $rss_link = htmlspecialchars(get_self_url_prefix() .
45                         "/public.php?op=rss&id=$feed_id$cat_q$search_q");
46
47                 // right part
48
49                 $error_class = $error ? "error" : "";
50
51                 $reply .= "<span class='r'>
52                         <a href=\"#\"
53                                 title=\"".__("View as RSS feed")."\"
54                                 onclick=\"displayDlg('".__("View as RSS")."','generatedFeed', '$feed_id:$is_cat:$rss_link')\">
55                                 <img class=\"noborder\" src=\"images/pub_set.png\"></a>";
56
57
58 #               $reply .= "<span>";
59                 $reply .= "<span id='feed_title' class='$error_class'>";
60
61                 if ($feed_site_url) {
62                         $last_updated = T_sprintf("Last updated: %s",
63                                 $feed_last_updated);
64
65                         $target = "target=\"_blank\"";
66                         $reply .= "<a title=\"$last_updated\" $target href=\"$feed_site_url\">".
67                                 truncate_string($feed_title, 30)."</a>";
68
69                         if ($error) {
70                                 $error = htmlspecialchars($error);
71                                 $reply .= "&nbsp;<img title=\"$error\" src='images/error.png' alt='error' class=\"noborder\">";
72                         }
73
74                 } else {
75                         $reply .= $feed_title;
76                 }
77
78                 $reply .= "</span>";
79
80                 $reply .= "</span>";
81
82 #               $reply .= "</span>";
83
84                 // left part
85
86                 $reply .= "<span class=\"main\">";
87                 $reply .= "<span id='selected_prompt'></span>";
88
89                 /*$reply .= "<span class=\"sel_links\">
90                         <a href=\"#\" onclick=\"$sel_all_link\">".__('All')."</a>,
91                         <a href=\"#\" onclick=\"$sel_unread_link\">".__('Unread')."</a>,
92                         <a href=\"#\" onclick=\"$sel_inv_link\">".__('Invert')."</a>,
93                         <a href=\"#\" onclick=\"$sel_none_link\">".__('None')."</a></li>";
94
95                 $reply .= "</span> "; */
96
97                 $reply .= "<select dojoType=\"dijit.form.Select\"
98                         onchange=\"headlineActionsChange(this)\">";
99
100                 $reply .= "<option value=\"0\" disabled='1'>".__('Select...')."</option>";
101
102                 $reply .= "<option value=\"$sel_all_link\">".__('All')."</option>";
103                 $reply .= "<option value=\"$sel_unread_link\">".__('Unread')."</option>";
104                 $reply .= "<option value=\"$sel_inv_link\">".__('Invert')."</option>";
105                 $reply .= "<option value=\"$sel_none_link\">".__('None')."</option>";
106
107                 $reply .= "<option value=\"0\" disabled=\"1\">".__('Selection toggle:')."</option>";
108
109                 $reply .= "<option value=\"$tog_unread_link\">".__('Unread')."</option>
110                         <option value=\"$tog_marked_link\">".__('Starred')."</option>
111                         <option value=\"$tog_published_link\">".__('Published')."</option>";
112
113                 $reply .= "<option value=\"0\" disabled=\"1\">".__('Selection:')."</option>";
114
115                 $reply .= "<option value=\"$catchup_sel_link\">".__('Mark as read')."</option>";
116                 $reply .= "<option value=\"$set_score_link\">".__('Set score')."</option>";
117
118                 if ($feed_id != "0") {
119                         $reply .= "<option value=\"$archive_sel_link\">".__('Archive')."</option>";
120                 } else {
121                         $reply .= "<option value=\"$archive_sel_link\">".__('Move back')."</option>";
122                         $reply .= "<option value=\"$delete_sel_link\">".__('Delete')."</option>";
123
124                 }
125
126                 if (PluginHost::getInstance()->get_plugin("mail")) {
127                         $reply .= "<option value=\"emailArticle(false)\">".__('Forward by email').
128                                 "</option>";
129                 }
130
131                 if (PluginHost::getInstance()->get_plugin("mailto")) {
132                         $reply .= "<option value=\"mailtoArticle(false)\">".__('Forward by email').
133                                 "</option>";
134                 }
135
136                 $reply .= "<option value=\"0\" disabled=\"1\">".__('Feed:')."</option>";
137
138                 //$reply .= "<option value=\"catchupPage()\">".__('Mark as read')."</option>";
139
140                 $reply .= "<option value=\"displayDlg('".__("View as RSS")."','generatedFeed', '$feed_id:$is_cat:$rss_link')\">".__('View as RSS')."</option>";
141
142                 $reply .= "</select>";
143
144                 //$reply .= "</h2";
145
146                 foreach (PluginHost::getInstance()->get_hooks(PluginHost::HOOK_HEADLINE_TOOLBAR_BUTTON) as $p) {
147                          $reply .= $p->hook_headline_toolbar_button($feed_id, $is_cat);
148                 }
149
150                 $reply .= "</span></span>";
151
152                 return $reply;
153         }
154
155         private function format_headlines_list($feed, $method, $view_mode, $limit, $cat_view,
156                                         $offset, $vgr_last_feed = false,
157                                         $override_order = false, $include_children = false, $check_first_id = false,
158                                         $skip_first_id_check = false) {
159
160                 $disable_cache = false;
161
162                 $reply = array();
163
164                 $rgba_cache = array();
165
166                 $timing_info = microtime(true);
167
168                 $topmost_article_ids = array();
169
170                 if (!$offset) $offset = 0;
171                 if ($method == "undefined") $method = "";
172
173                 $method_split = explode(":", $method);
174
175                 if ($method == "ForceUpdate" && $feed > 0 && is_numeric($feed)) {
176                         // Update the feed if required with some basic flood control
177
178                         $any_needs_curl = false;
179
180                         if (ini_get("open_basedir")) {
181                                 $pluginhost = PluginHost::getInstance();
182                                 foreach ($pluginhost->get_plugins() as $plugin) {
183                                         $flags = $plugin->flags();
184
185                                         if (isset($flags["needs_curl"]) && $flags["needs_curl"]) {
186                                                 $any_needs_curl = true;
187                                                 break;
188                                         }
189                                 }
190                         }
191
192                         //if ($_REQUEST["debug"]) print "<!-- any_needs_curl: $any_needs_curl -->";
193
194                         if (!$any_needs_curl) {
195
196                                 $sth = $this->pdo->prepare("SELECT cache_images," . SUBSTRING_FOR_DATE . "(last_updated,1,19) AS last_updated
197                                                 FROM ttrss_feeds WHERE id = ?");
198                                 $sth->execute([$feed]);
199
200                                 if ($row = $sth->fetch()) {
201                                         $last_updated = strtotime($row["last_updated"]);
202                                         $cache_images = $row["cache_images"];
203
204                                         if (!$cache_images && time() - $last_updated > 120) {
205                                                 RSSUtils::update_rss_feed($feed, true);
206                                         } else {
207                                                 $sth = $this->pdo->prepare("UPDATE ttrss_feeds 
208                                 SET last_updated = '1970-01-01', last_update_started = '1970-01-01'
209                                                                 WHERE id = ?");
210                                                 $sth->execute([$feed]);
211                                         }
212                                 }
213                         } else {
214                                 $sth = $this->pdo->prepare("UPDATE ttrss_feeds 
215                                 SET last_updated = '1970-01-01', last_update_started = '1970-01-01'
216                                                                 WHERE id = ?");
217                                 $sth->execute([$feed]);
218                         }
219                 }
220
221                 if ($method_split[0] == "MarkAllReadGR")  {
222                         $this->catchup_feed($method_split[1], false);
223                 }
224
225                 // FIXME: might break tag display?
226
227                 if (is_numeric($feed) && $feed > 0 && !$cat_view) {
228                         $sth = $this->pdo->prepare("SELECT id FROM ttrss_feeds WHERE id = ? LIMIT 1");
229                         $sth->execute([$feed]);
230
231                         if (!$sth->fetch()) {
232                                 $reply['content'] = "<div align='center'>".__('Feed not found.')."</div>";
233                         }
234                 }
235
236                 @$search = $_REQUEST["query"];
237                 @$search_language = $_REQUEST["search_language"]; // PGSQL only
238
239                 if ($search) {
240                         $disable_cache = true;
241                 }
242
243                 if ($_REQUEST["debug"]) $timing_info = print_checkpoint("H0", $timing_info);
244
245                 if (!$cat_view && is_numeric($feed) && $feed < PLUGIN_FEED_BASE_INDEX && $feed > LABEL_BASE_INDEX) {
246                         $handler = PluginHost::getInstance()->get_feed_handler(
247                                 PluginHost::feed_to_pfeed_id($feed));
248
249                         if ($handler) {
250                                 $options = array(
251                                         "limit" => $limit,
252                                         "view_mode" => $view_mode,
253                                         "cat_view" => $cat_view,
254                                         "search" => $search,
255                                         "override_order" => $override_order,
256                                         "offset" => $offset,
257                                         "owner_uid" => $_SESSION["uid"],
258                                         "filter" => false,
259                                         "since_id" => 0,
260                                         "include_children" => $include_children);
261
262                                 $qfh_ret = $handler->get_headlines(PluginHost::feed_to_pfeed_id($feed),
263                                         $options);
264                         }
265
266                 } else {
267
268                         $params = array(
269                                 "feed" => $feed,
270                                 "limit" => $limit,
271                                 "view_mode" => $view_mode,
272                                 "cat_view" => $cat_view,
273                                 "search" => $search,
274                                 "search_language" => $search_language,
275                                 "override_order" => $override_order,
276                                 "offset" => $offset,
277                                 "include_children" => $include_children,
278                                 "check_first_id" => $check_first_id,
279                                 "skip_first_id_check" => $skip_first_id_check
280                         );
281
282                         $qfh_ret = $this->queryFeedHeadlines($params);
283                 }
284
285                 $vfeed_group_enabled = get_pref("VFEED_GROUP_BY_FEED") && $feed != -6;
286
287                 if ($_REQUEST["debug"]) $timing_info = print_checkpoint("H1", $timing_info);
288
289                 $result = $qfh_ret[0];
290                 $feed_title = $qfh_ret[1];
291                 $feed_site_url = $qfh_ret[2];
292                 $last_error = $qfh_ret[3];
293                 $last_updated = strpos($qfh_ret[4], '1970-') === FALSE ?
294                         make_local_datetime($qfh_ret[4], false) : __("Never");
295                 $highlight_words = $qfh_ret[5];
296                 $reply['first_id'] = $qfh_ret[6];
297                 $reply['search_query'] = [$search, $search_language];
298
299                 $vgroup_last_feed = $vgr_last_feed;
300
301                 $reply['toolbar'] = $this->format_headline_subtoolbar($feed_site_url,
302                         $feed_title,
303                         $feed, $cat_view, $search,
304                         $last_error, $last_updated);
305
306                 if ($offset == 0) {
307                         foreach (PluginHost::getInstance()->get_hooks(PluginHost::HOOK_HEADLINES_BEFORE) as $p) {
308                                  $reply['content'] .= $p->hook_headlines_before($feed, $cat_view, $qfh_ret);
309                         }
310                 }
311
312                 $reply['content'] = '';
313
314                 $headlines_count = 0;
315
316         $lnum = $offset;
317         $num_unread = 0;
318         if ($_REQUEST["debug"]) $timing_info = print_checkpoint("PS", $timing_info);
319         $expand_cdm = get_pref('CDM_EXPANDED');
320
321         while ($line = $result->fetch()) {
322
323             ++$headlines_count;
324
325             $line["content_preview"] =  "&mdash; " . truncate_string(strip_tags($line["content"]), 250);
326
327             foreach (PluginHost::getInstance()->get_hooks(PluginHost::HOOK_QUERY_HEADLINES) as $p) {
328                 $line = $p->hook_query_headlines($line, 250, false);
329             }
330
331             if (get_pref('SHOW_CONTENT_PREVIEW')) {
332                 $content_preview =  $line["content_preview"];
333             }
334
335             $id = $line["id"];
336             $feed_id = $line["feed_id"];
337             $label_cache = $line["label_cache"];
338             $labels = false;
339
340             if ($label_cache) {
341                 $label_cache = json_decode($label_cache, true);
342
343                 if ($label_cache) {
344                     if ($label_cache["no-labels"] == 1)
345                         $labels = array();
346                     else
347                         $labels = $label_cache;
348                 }
349             }
350
351             if (!is_array($labels)) $labels = Article::get_article_labels($id);
352
353             $labels_str = "<span class=\"HLLCTR-$id\">";
354             $labels_str .= Article::format_article_labels($labels);
355             $labels_str .= "</span>";
356
357             if (count($topmost_article_ids) < 3) {
358                 array_push($topmost_article_ids, $id);
359             }
360
361             $class = "";
362
363             if ($line["unread"]) {
364                 $class .= " Unread";
365                 ++$num_unread;
366             }
367
368             if ($line["marked"]) {
369                 $marked_pic = "<img
370                     src=\"images/mark_set.png\"
371                     class=\"markedPic\" alt=\"Unstar article\"
372                     onclick='toggleMark($id)'>";
373                 $class .= " marked";
374             } else {
375                 $marked_pic = "<img
376                     src=\"images/mark_unset.png\"
377                     class=\"markedPic\" alt=\"Star article\"
378                     onclick='toggleMark($id)'>";
379             }
380
381             if ($line["published"]) {
382                 $published_pic = "<img src=\"images/pub_set.png\"
383                     class=\"pubPic\"
384                         alt=\"Unpublish article\" onclick='togglePub($id)'>";
385                 $class .= " published";
386             } else {
387                 $published_pic = "<img src=\"images/pub_unset.png\"
388                     class=\"pubPic\"
389                     alt=\"Publish article\" onclick='togglePub($id)'>";
390             }
391
392             $updated_fmt = make_local_datetime($line["updated"], false, false, false, true);
393             $date_entered_fmt = T_sprintf("Imported at %s",
394                 make_local_datetime($line["date_entered"], false));
395
396             $score = $line["score"];
397
398             $score_pic = "images/" . get_score_pic($score);
399
400             $score_pic = "<img class='hlScorePic' score='$score' onclick='changeScore($id, this)' src=\"$score_pic\"
401                 title=\"$score\">";
402
403             if ($score > 500) {
404                 $hlc_suffix = "high";
405             } else if ($score < -100) {
406                 $hlc_suffix = "low";
407             } else {
408                 $hlc_suffix = "";
409             }
410
411             $entry_author = $line["author"];
412
413             if ($entry_author) {
414                 $entry_author = " &mdash; $entry_author";
415             }
416
417             $has_feed_icon = feed_has_icon($feed_id);
418
419             if ($has_feed_icon) {
420                 $feed_icon_img = "<img class=\"tinyFeedIcon\" src=\"".ICONS_URL."/$feed_id.ico\" alt=\"\">";
421             } else {
422                 $feed_icon_img = "<img class=\"tinyFeedIcon\" src=\"images/pub_set.png\" alt=\"\">";
423             }
424
425             $entry_site_url = $line["site_url"];
426
427             //setting feed headline background color, needs to change text color based on dark/light
428             $fav_color = $line['favicon_avg_color'];
429
430             require_once "colors.php";
431
432             if ($fav_color && $fav_color != 'fail') {
433                 if (!isset($rgba_cache[$feed_id])) {
434                     $rgba_cache[$feed_id] = join(",", _color_unpack($fav_color));
435                 }
436             }
437
438             if (!get_pref('COMBINED_DISPLAY_MODE')) {
439
440                 if ($vfeed_group_enabled) {
441                     if ($feed_id != $vgroup_last_feed && $line["feed_title"]) {
442
443                         $cur_feed_title = $line["feed_title"];
444                         $vgroup_last_feed = $feed_id;
445
446                         $cur_feed_title = htmlspecialchars($cur_feed_title);
447
448                         $vf_catchup_link = "<a class='catchup' onclick='catchupFeedInGroup($feed_id);' href='#'>".__('mark feed as read')."</a>";
449
450                         $reply['content'] .= "<div data-feed-id='$feed_id' id='FTITLE-$feed_id' class='cdmFeedTitle'>".
451                             "<div style='float : right'>$feed_icon_img</div>".
452                             "<a class='title' href=\"#\" onclick=\"viewfeed({feed:$feed_id})\">".
453                             $line["feed_title"]."</a>
454                             $vf_catchup_link</div>";
455
456
457                     }
458                 }
459
460                 $mouseover_attrs = "onmouseover='postMouseIn(event, $id)'
461                     onmouseout='postMouseOut($id)'";
462
463                 $reply['content'] .= "<div class='hl hlMenuAttach $class' data-orig-feed-id='$feed_id' data-article-id='$id' id='RROW-$id' $mouseover_attrs>";
464
465                 $reply['content'] .= "<div class='hlLeft'>";
466
467                 $reply['content'] .= "<input dojoType=\"dijit.form.CheckBox\"
468                         type=\"checkbox\" onclick=\"toggleSelectRow2(this)\"
469                         class='rchk'>";
470
471                 $reply['content'] .= "$marked_pic";
472                 $reply['content'] .= "$published_pic";
473
474                 $reply['content'] .= "</div>";
475
476                 $reply['content'] .= "<div onclick='return hlClicked(event, $id)'
477                     class=\"hlTitle\"><span class='hlContent $hlc_suffix'>";
478                 $reply['content'] .= "<a id=\"RTITLE-$id\" class=\"title $hlc_suffix\"
479                     href=\"" . htmlspecialchars($line["link"]) . "\"
480                     onclick=\"\">" .
481                     truncate_string($line["title"], 200);
482
483                 if (get_pref('SHOW_CONTENT_PREVIEW')) {
484                         $reply['content'] .= "<span class=\"contentPreview\">" . $line["content_preview"] . "</span>";
485                 }
486
487                 $reply['content'] .= "</a></span>";
488
489                 $reply['content'] .= $labels_str;
490
491                 $reply['content'] .= "</div>";
492
493                 if (!$vfeed_group_enabled) {
494                     if (@$line["feed_title"]) {
495                         $rgba = @$rgba_cache[$feed_id];
496
497                         $reply['content'] .= "<span class=\"hlFeed\"><a style=\"background : rgba($rgba, 0.3)\" href=\"#\" onclick=\"viewfeed({feed:$feed_id})\">".
498                             truncate_string($line["feed_title"],30)."</a></span>";
499                     }
500                 }
501
502
503                 $reply['content'] .= "<span class=\"hlUpdated\">";
504
505                 $reply['content'] .= "<div title='$date_entered_fmt'>$updated_fmt</div>
506                     </span>";
507
508                 $reply['content'] .= "<div class=\"hlRight\">";
509
510                 $reply['content'] .= $score_pic;
511
512                 if ($line["feed_title"] && !$vfeed_group_enabled) {
513
514                     $reply['content'] .= "<span onclick=\"viewfeed({feed:$feed_id})\"
515                         style=\"cursor : pointer\"
516                         title=\"".htmlspecialchars($line['feed_title'])."\">
517                         $feed_icon_img</span>";
518                 }
519
520                 $reply['content'] .= "</div>";
521                 $reply['content'] .= "</div>";
522
523             } else {
524
525                 if ($line["tag_cache"])
526                     $tags = explode(",", $line["tag_cache"]);
527                 else
528                     $tags = false;
529
530                 $line["content"] = sanitize($line["content"],
531                         $line['hide_images'], false, $entry_site_url, $highlight_words, $line["id"]);
532
533                 foreach (PluginHost::getInstance()->get_hooks(PluginHost::HOOK_RENDER_ARTICLE_CDM) as $p) {
534                     $line = $p->hook_render_article_cdm($line);
535                 }
536
537                 if ($vfeed_group_enabled && $line["feed_title"]) {
538                     if ($feed_id != $vgroup_last_feed) {
539
540                         $cur_feed_title = $line["feed_title"];
541                         $vgroup_last_feed = $feed_id;
542
543                         $cur_feed_title = htmlspecialchars($cur_feed_title);
544
545                         $vf_catchup_link = "<a class='catchup' onclick='catchupFeedInGroup($feed_id);' href='#'>".__('mark feed as read')."</a>";
546
547                         $has_feed_icon = feed_has_icon($feed_id);
548
549                         if ($has_feed_icon) {
550                             $feed_icon_img = "<img class=\"tinyFeedIcon\" src=\"".ICONS_URL."/$feed_id.ico\" alt=\"\">";
551                         } else {
552                             //$feed_icon_img = "<img class=\"tinyFeedIcon\" src=\"images/blank_icon.gif\" alt=\"\">";
553                         }
554
555                         $reply['content'] .= "<div data-feed-id='$feed_id' id='FTITLE-$feed_id' class='cdmFeedTitle'>".
556                             "<div style=\"float : right\">$feed_icon_img</div>".
557                             "<a href=\"#\" class='title' onclick=\"viewfeed({feed:$feed_id})\">".
558                             $line["feed_title"]."</a> $vf_catchup_link</div>";
559
560                     }
561                 }
562
563                 $mouseover_attrs = "onmouseover='postMouseIn(event, $id)'
564                     onmouseout='postMouseOut($id)'";
565
566                 $expanded_class = $expand_cdm ? "expanded" : "expandable";
567
568                 $tmp_content = "<div class=\"cdm $hlc_suffix $expanded_class $class\"
569                     id=\"RROW-$id\" data-article-id='$id' data-orig-feed-id='$feed_id' $mouseover_attrs>";
570
571                 $tmp_content .= "<div class=\"cdmHeader\">";
572                 $tmp_content .= "<div style=\"vertical-align : middle\">";
573
574                 $tmp_content .= "<input dojoType=\"dijit.form.CheckBox\"
575                         type=\"checkbox\" onclick=\"toggleSelectRow2(this, false, true)\"
576                         class='rchk'>";
577
578                 $tmp_content .= "$marked_pic";
579                 $tmp_content .= "$published_pic";
580
581                 $tmp_content .= "</div>";
582
583                 if ($highlight_words && count($highlight_words > 0)) {
584                     foreach ($highlight_words as $word) {
585                         $line["title"] = preg_replace("/(\Q$word\E)/i",
586                             "<span class=\"highlight\">$1</span>", $line["title"]);
587                     }
588                 }
589
590                 // data-article-id included for context menu
591                 $tmp_content .= "<span id=\"RTITLE-$id\"
592                     onclick=\"return cdmClicked(event, $id);\"
593                     data-article-id=\"$id\"
594                     class=\"titleWrap hlMenuAttach $hlc_suffix\">                                               
595                     <a class=\"title $hlc_suffix\"
596                     title=\"".htmlspecialchars($line["title"])."\"
597                     target=\"_blank\" rel=\"noopener noreferrer\" href=\"".
598                     htmlspecialchars($line["link"])."\">".
599                     $line["title"] .
600                     "</a> <span class=\"author\">$entry_author</span>";
601
602                 $tmp_content .= $labels_str;
603
604                 $tmp_content .= "<span class='collapseBtn' style='display : none'>
605                     <img src=\"images/collapse.png\" onclick=\"cdmCollapseArticle(event, $id)\"
606                     title=\"".__("Collapse article")."\"/></span>";
607
608                 if (!$expand_cdm)
609                     $content_hidden = "style=\"display : none\"";
610                 else
611                     $excerpt_hidden = "style=\"display : none\"";
612
613                 $tmp_content .= "<span $excerpt_hidden id=\"CEXC-$id\" class=\"cdmExcerpt\">" . $content_preview . "</span>";
614
615                 $tmp_content .= "</span>";
616
617                 if (!$vfeed_group_enabled) {
618                     if (@$line["feed_title"]) {
619                         $rgba = @$rgba_cache[$feed_id];
620
621                         $tmp_content .= "<div class=\"hlFeed\">
622                             <a href=\"#\" style=\"background-color: rgba($rgba,0.3)\"
623                             onclick=\"viewfeed({feed:$feed_id})\">".
624                             truncate_string($line["feed_title"],30)."</a>
625                         </div>";
626                     }
627                 }
628
629                 $tmp_content .= "<span class='updated' title='$date_entered_fmt'>$updated_fmt</span>";
630
631                 $tmp_content .= "<div class='scoreWrap' style=\"vertical-align : middle\">";
632                 $tmp_content .= "$score_pic";
633
634                 if (!get_pref("VFEED_GROUP_BY_FEED") && $line["feed_title"]) {
635                     $tmp_content .= "<span style=\"cursor : pointer\"
636                         title=\"".htmlspecialchars($line["feed_title"])."\"
637                         onclick=\"viewfeed({feed:$feed_id})\">$feed_icon_img</span>";
638                 }
639                 $tmp_content .= "</div>"; //scoreWrap
640
641                 $tmp_content .= "</div>"; //cdmHeader
642
643                 $tmp_content .= "<div class=\"cdmContent\" $content_hidden
644                     onclick=\"return cdmClicked(event, $id, true);\"
645                     id=\"CICD-$id\">";
646
647                 $tmp_content .= "<div id=\"POSTNOTE-$id\">";
648                 if ($line['note']) {
649                     $tmp_content .= Article::format_article_note($id, $line['note']);
650                 }
651                 $tmp_content .= "</div>"; //POSTNOTE
652
653                 if (!$line['lang']) $line['lang'] = 'en';
654
655                 $tmp_content .= "<div class=\"cdmContentInner\" lang=\"".$line['lang']."\">";
656
657                 if ($line["orig_feed_id"]) {
658
659                     $ofgh = $this->pdo->prepare("SELECT * FROM ttrss_archived_feeds
660                         WHERE id = ? AND owner_uid = ?");
661                     $ofgh->execute([$line["orig_feed_id"], $_SESSION['uid']]);
662
663                     if ($tmp_line = $ofgh->fetch()) {
664
665                         $tmp_content .= "<div clear='both'>";
666                         $tmp_content .= __("Originally from:");
667
668                         $tmp_content .= "&nbsp;";
669
670                         $tmp_content .= "<a target='_blank' rel='noopener noreferrer'
671                             href=' " . htmlspecialchars($tmp_line['site_url']) . "'>" .
672                             $tmp_line['title'] . "</a>";
673
674                         $tmp_content .= "&nbsp;";
675
676                         $tmp_content .= "<a target='_blank' rel='noopener noreferrer' href='" . htmlspecialchars($tmp_line['feed_url']) . "'>";
677                         $tmp_content .= "<img title='".__('Feed URL')."'class='tinyFeedIcon' src='images/pub_unset.png'></a>";
678
679                         $tmp_content .= "</div>";
680                     }
681                 }
682
683                 $tmp_content .= "<span id=\"CWRAP-$id\">";
684                 $tmp_content .= "<span id=\"CENCW-$id\" class=\"cencw\" style=\"display : none\">";
685                 $tmp_content .= htmlspecialchars($line["content"]);
686                 $tmp_content .= "</span>";
687                 $tmp_content .= "</span>";
688
689                 $tmp_content .= "</div>"; //cdmContentInner
690
691                 $tmp_content .= "<div class=\"cdmIntermediate\">";
692
693                 $always_display_enclosures = $line["always_display_enclosures"];
694                 $tmp_content .= Article::format_article_enclosures($id, $always_display_enclosures,
695                     $line["content"], $line["hide_images"]);
696
697                 $tmp_content .= "</div>"; // cdmIntermediate
698
699                 $tmp_content .= "<div class=\"cdmFooter\" onclick=\"cdmFooterClick(event)\">";
700
701                 foreach (PluginHost::getInstance()->get_hooks(PluginHost::HOOK_ARTICLE_LEFT_BUTTON) as $p) {
702                     $tmp_content .= $p->hook_article_left_button($line);
703                 }
704
705                 $tags_str = Article::format_tags_string($tags, $id);
706
707                 $tmp_content .= "<span class='left'>";
708
709                 $tmp_content .= "<img src='images/tag.png' alt='Tags' title='Tags'>
710                     <span id=\"ATSTR-$id\">$tags_str</span>
711                     <a title=\"".__('Edit tags for this article')."\"
712                     href=\"#\" onclick=\"editArticleTags($id)\">(+)</a>";
713
714                 $num_comments = (int) $line["num_comments"];
715                 $entry_comments = "";
716
717                 if ($num_comments > 0) {
718                     if ($line["comments"]) {
719                         $comments_url = htmlspecialchars($line["comments"]);
720                     } else {
721                         $comments_url = htmlspecialchars($line["link"]);
722                     }
723                     $entry_comments = "<a class=\"postComments\"
724                         target='_blank' rel='noopener noreferrer' href=\"$comments_url\">$num_comments ".
725                         _ngettext("comment", "comments", $num_comments)."</a>";
726
727                 } else {
728                     if ($line["comments"] && $line["link"] != $line["comments"]) {
729                         $entry_comments = "<a class=\"postComments\" target='_blank' rel='noopener noreferrer' href=\"".htmlspecialchars($line["comments"])."\">".__("comments")."</a>";
730                     }
731                 }
732
733                 if ($entry_comments) $tmp_content .= "&nbsp;($entry_comments)";
734
735                 $tmp_content .= "</span>";
736                 $tmp_content .= "<div>";
737
738                 foreach (PluginHost::getInstance()->get_hooks(PluginHost::HOOK_ARTICLE_BUTTON) as $p) {
739                     $tmp_content .= $p->hook_article_button($line);
740                 }
741
742                 $tmp_content .= "</div>"; // buttons
743
744                 $tmp_content .= "</div>"; // cdmFooter
745                 $tmp_content .= "</div>"; // cdmContent
746                 $tmp_content .= "</div>"; // RROW.cdm
747
748                 foreach (PluginHost::getInstance()->get_hooks(PluginHost::HOOK_FORMAT_ARTICLE_CDM) as $p) {
749                     $tmp_content = $p->hook_format_article_cdm($tmp_content, $line);
750                 }
751
752                 $reply['content'] .= $tmp_content;
753             }
754
755             ++$lnum;
756         }
757
758         if ($_REQUEST["debug"]) $timing_info = print_checkpoint("PE", $timing_info);
759
760                 if (!$headlines_count) {
761
762                         if (!is_numeric($result)) {
763
764                                 switch ($view_mode) {
765                                         case "unread":
766                                                 $message = __("No unread articles found to display.");
767                                                 break;
768                                         case "updated":
769                                                 $message = __("No updated articles found to display.");
770                                                 break;
771                                         case "marked":
772                                                 $message = __("No starred articles found to display.");
773                                                 break;
774                                         default:
775                                                 if ($feed < LABEL_BASE_INDEX) {
776                                                         $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.");
777                                                 } else {
778                                                         $message = __("No articles found to display.");
779                                                 }
780                                 }
781
782                                 if (!$offset && $message) {
783                                         $reply['content'] = "<div class='whiteBox'>$message";
784
785                                         $reply['content'] .= "<p><span class=\"insensitive\">";
786
787                                         $sth = $this->pdo->prepare("SELECT " . SUBSTRING_FOR_DATE . "(MAX(last_updated), 1, 19) AS last_updated FROM ttrss_feeds
788                         WHERE owner_uid = ?");
789                                         $sth->execute([$_SESSION['uid']]);
790                                         $row = $sth->fetch();
791
792                                         $last_updated = make_local_datetime($row["last_updated"], false);
793
794                                         $reply['content'] .= sprintf(__("Feeds last updated at %s"), $last_updated);
795
796                                         $sth = $this->pdo->prepare("SELECT COUNT(id) AS num_errors
797                         FROM ttrss_feeds WHERE last_error != '' AND owner_uid = ?");
798                                         $sth->execute([$_SESSION['uid']]);
799                                         $row = $sth->fetch();
800
801                                         $num_errors = $row["num_errors"];
802
803                                         if ($num_errors > 0) {
804                                                 $reply['content'] .= "<br/>";
805                                                 $reply['content'] .= "<a class=\"insensitive\" href=\"#\" onclick=\"showFeedsWithErrors()\">" .
806                                                         __('Some feeds have update errors (click for details)') . "</a>";
807                                         }
808                                         $reply['content'] .= "</span></p></div>";
809
810                                 }
811                         } else if (is_numeric($result) && $result == -1) {
812                                 $reply['first_id_changed'] = true;
813                         }
814                 }
815
816                 if ($_REQUEST["debug"]) $timing_info = print_checkpoint("H2", $timing_info);
817
818                 return array($topmost_article_ids, $headlines_count, $feed, $disable_cache,
819                         $vgroup_last_feed, $reply);
820         }
821
822         function catchupAll() {
823                 $sth = $this->pdo->prepare("UPDATE ttrss_user_entries SET
824                                                 last_read = NOW(), unread = false WHERE unread = true AND owner_uid = ?");
825                 $sth->execute([$_SESSION['uid']]);
826
827                 CCache::zero_all($_SESSION["uid"]);
828         }
829
830         function view() {
831                 $timing_info = microtime(true);
832
833                 $reply = array();
834
835                 if ($_REQUEST["debug"]) $timing_info = print_checkpoint("0", $timing_info);
836
837                 $feed = $_REQUEST["feed"];
838                 $method = $_REQUEST["m"];
839                 $view_mode = $_REQUEST["view_mode"];
840                 $limit = 30;
841                 @$cat_view = $_REQUEST["cat"] == "true";
842                 @$next_unread_feed = $_REQUEST["nuf"];
843                 @$offset = $_REQUEST["skip"];
844                 @$vgroup_last_feed = $_REQUEST["vgrlf"];
845                 $order_by = $_REQUEST["order_by"];
846                 $check_first_id = $_REQUEST["fid"];
847
848                 if (is_numeric($feed)) $feed = (int) $feed;
849
850                 /* Feed -5 is a special case: it is used to display auxiliary information
851                  * when there's nothing to load - e.g. no stuff in fresh feed */
852
853                 if ($feed == -5) {
854                         print json_encode($this->generate_dashboard_feed());
855                         return;
856                 }
857
858                 $sth = false;
859                 if ($feed < LABEL_BASE_INDEX) {
860
861                         $label_feed = Labels::feed_to_label_id($feed);
862
863                         $sth = $this->pdo->prepare("SELECT id FROM ttrss_labels2 WHERE
864                                                         id = ? AND owner_uid = ?");
865                         $sth->execute([$label_feed, $_SESSION['uid']]);
866
867                 } else if (!$cat_view && is_numeric($feed) && $feed > 0) {
868
869                         $sth = $this->pdo->prepare("SELECT id FROM ttrss_feeds WHERE
870                                                         id = ? AND owner_uid = ?");
871                         $sth->execute([$feed, $_SESSION['uid']]);
872
873                 } else if ($cat_view && is_numeric($feed) && $feed > 0) {
874
875                         $sth = $this->pdo->prepare("SELECT id FROM ttrss_feed_categories WHERE
876                                                         id = ? AND owner_uid = ?");
877
878                         $sth->execute([$feed, $_SESSION['uid']]);
879                 }
880
881                 if ($sth && !$sth->fetch()) {
882                         print json_encode($this->generate_error_feed(__("Feed not found.")));
883                         return;
884                 }
885
886                 /* Updating a label ccache means recalculating all of the caches
887                  * so for performance reasons we don't do that here */
888
889                 if ($feed >= 0) {
890                         CCache::update($feed, $_SESSION["uid"], $cat_view);
891                 }
892
893                 set_pref("_DEFAULT_VIEW_MODE", $view_mode);
894                 set_pref("_DEFAULT_VIEW_ORDER_BY", $order_by);
895
896                 /* bump login timestamp if needed */
897                 if (time() - $_SESSION["last_login_update"] > 3600) {
898                         $sth = $this->pdo->prepare("UPDATE ttrss_users SET last_login = NOW() WHERE id = ?");
899                         $sth->execute([$_SESSION['uid']]);
900
901                         $_SESSION["last_login_update"] = time();
902                 }
903
904                 if (!$cat_view && is_numeric($feed) && $feed > 0) {
905                         $sth = $this->pdo->prepare("UPDATE ttrss_feeds SET last_viewed = NOW()
906                                                         WHERE id = ? AND owner_uid = ?");
907                         $sth->execute([$feed, $_SESSION['uid']]);
908                 }
909
910                 $reply['headlines'] = array();
911
912                 $override_order = false;
913                 $skip_first_id_check = false;
914
915                 switch ($order_by) {
916                 case "title":
917                         $override_order = "ttrss_entries.title, date_entered, updated";
918                         break;
919                 case "date_reverse":
920                         $override_order = "score DESC, date_entered, updated";
921                         $skip_first_id_check = true;
922                         break;
923                 case "feed_dates":
924                         $override_order = "updated DESC";
925                         break;
926                 }
927
928                 if ($_REQUEST["debug"]) $timing_info = print_checkpoint("04", $timing_info);
929
930                 $ret = $this->format_headlines_list($feed, $method,
931                         $view_mode, $limit, $cat_view, $offset,
932                         $vgroup_last_feed, $override_order, true, $check_first_id, $skip_first_id_check);
933
934                 //$topmost_article_ids = $ret[0];
935                 $headlines_count = $ret[1];
936                 /* $returned_feed = $ret[2]; */
937                 $disable_cache = $ret[3];
938                 $vgroup_last_feed = $ret[4];
939
940                 //$reply['headlines']['content'] =& $ret[5]['content'];
941                 //$reply['headlines']['toolbar'] =& $ret[5]['toolbar'];
942
943                 $reply['headlines'] = $ret[5];
944
945                 if (!$next_unread_feed)
946                         $reply['headlines']['id'] = $feed;
947                 else
948                         $reply['headlines']['id'] = $next_unread_feed;
949
950                 $reply['headlines']['is_cat'] = (bool) $cat_view;
951
952                 if ($_REQUEST["debug"]) $timing_info = print_checkpoint("05", $timing_info);
953
954                 $reply['headlines-info'] = array("count" => (int) $headlines_count,
955                                                 "vgroup_last_feed" => $vgroup_last_feed,
956                                                 "disable_cache" => (bool) $disable_cache);
957
958                 if ($_REQUEST["debug"]) $timing_info = print_checkpoint("30", $timing_info);
959
960                 $reply['runtime-info'] = make_runtime_info();
961
962                 print json_encode($reply);
963
964         }
965
966         private function generate_dashboard_feed() {
967                 $reply = array();
968
969                 $reply['headlines']['id'] = -5;
970                 $reply['headlines']['is_cat'] = false;
971
972                 $reply['headlines']['toolbar'] = '';
973
974                 $reply['headlines']['content'] = "<div class='whiteBox'>".__('No feed selected.');
975
976                 $reply['headlines']['content'] .= "<p><span class=\"insensitive\">";
977
978                 $sth = $this->pdo->prepare("SELECT ".SUBSTRING_FOR_DATE."(MAX(last_updated), 1, 19) AS last_updated FROM ttrss_feeds
979                         WHERE owner_uid = ?");
980                 $sth->execute([$_SESSION['uid']]);
981                 $row = $sth->fetch();
982
983                 $last_updated = make_local_datetime($row["last_updated"], false);
984
985                 $reply['headlines']['content'] .= sprintf(__("Feeds last updated at %s"), $last_updated);
986
987                 $sth = $this->pdo->prepare("SELECT COUNT(id) AS num_errors
988                         FROM ttrss_feeds WHERE last_error != '' AND owner_uid = ?");
989                 $sth->execute([$_SESSION['uid']]);
990                 $row = $sth->fetch();
991
992                 $num_errors = $row["num_errors"];
993
994                 if ($num_errors > 0) {
995                         $reply['headlines']['content'] .= "<br/>";
996                         $reply['headlines']['content'] .= "<a class=\"insensitive\" href=\"#\" onclick=\"showFeedsWithErrors()\">".
997                                 __('Some feeds have update errors (click for details)')."</a>";
998                 }
999                 $reply['headlines']['content'] .= "</span></p>";
1000
1001                 $reply['headlines-info'] = array("count" => 0,
1002                         "vgroup_last_feed" => '',
1003                         "unread" => 0,
1004                         "disable_cache" => true);
1005
1006                 return $reply;
1007         }
1008
1009         private function generate_error_feed($error) {
1010                 $reply = array();
1011
1012                 $reply['headlines']['id'] = -7;
1013                 $reply['headlines']['is_cat'] = false;
1014
1015                 $reply['headlines']['toolbar'] = '';
1016                 $reply['headlines']['content'] = "<div class='whiteBox'>". $error . "</div>";
1017
1018                 $reply['headlines-info'] = array("count" => 0,
1019                         "vgroup_last_feed" => '',
1020                         "unread" => 0,
1021                         "disable_cache" => true);
1022
1023                 return $reply;
1024         }
1025
1026         function quickAddFeed() {
1027                 print_hidden("op", "rpc");
1028                 print_hidden("method", "addfeed");
1029
1030                 print "<div id='fadd_error_message' style='display : none' class='alert alert-danger'></div>";
1031
1032                 print "<div id='fadd_multiple_notify' style='display : none'>";
1033                 print_notice("Provided URL is a HTML page referencing multiple feeds, please select required feed from the dropdown menu below.");
1034                 print "<p></div>";
1035
1036                 print "<div class=\"dlgSec\">".__("Feed or site URL")."</div>";
1037                 print "<div class=\"dlgSecCont\">";
1038
1039                 print "<div style='float : right'>
1040                         <img style='display : none'
1041                                 id='feed_add_spinner' src='images/indicator_white.gif'></div>";
1042
1043                 print "<input style=\"font-size : 16px; width : 20em;\"
1044                         placeHolder=\"".__("Feed or site URL")."\"
1045                         dojoType=\"dijit.form.ValidationTextBox\" required=\"1\" name=\"feed\" id=\"feedDlg_feedUrl\">";
1046
1047                 print "<hr/>";
1048
1049                 if (get_pref('ENABLE_FEED_CATS')) {
1050                         print __('Place in category:') . " ";
1051                         print_feed_cat_select("cat", false, 'dojoType="dijit.form.Select"');
1052                 }
1053
1054                 print "</div>";
1055
1056                 print '<div id="feedDlg_feedsContainer" style="display : none">
1057
1058                                 <div class="dlgSec">' . __('Available feeds') . '</div>
1059                                 <div class="dlgSecCont">'.
1060                                 '<select id="feedDlg_feedContainerSelect"
1061                                         dojoType="dijit.form.Select" size="3">
1062                                         <script type="dojo/method" event="onChange" args="value">
1063                                                 dijit.byId("feedDlg_feedUrl").attr("value", value);
1064                                         </script>
1065                                 </select>'.
1066                                 '</div></div>';
1067
1068                 print "<div id='feedDlg_loginContainer' style='display : none'>
1069
1070                                 <div class=\"dlgSec\">".__("Authentication")."</div>
1071                                 <div class=\"dlgSecCont\">".
1072
1073                                 " <input dojoType=\"dijit.form.TextBox\" name='login'\"
1074                                         placeHolder=\"".__("Login")."\"
1075                                         autocomplete=\"new-password\"
1076                                         style=\"width : 10em;\"> ".
1077                                 " <input
1078                                         placeHolder=\"".__("Password")."\"
1079                                         dojoType=\"dijit.form.TextBox\" type='password'
1080                                         autocomplete=\"new-password\"
1081                                         style=\"width : 10em;\" name='pass'\">
1082                         </div></div>";
1083
1084
1085                 print "<div style=\"clear : both\">
1086                         <input type=\"checkbox\" name=\"need_auth\" dojoType=\"dijit.form.CheckBox\" id=\"feedDlg_loginCheck\"
1087                                         onclick='checkboxToggleElement(this, \"feedDlg_loginContainer\")'>
1088                                 <label for=\"feedDlg_loginCheck\">".
1089                                 __('This feed requires authentication.')."</div>";
1090
1091                 print "</form>";
1092
1093                 print "<div class=\"dlgButtons\">
1094                         <button dojoType=\"dijit.form.Button\" onclick=\"return dijit.byId('feedAddDlg').execute()\">".__('Subscribe')."</button>";
1095
1096                 if (!(defined('_DISABLE_FEED_BROWSER') && _DISABLE_FEED_BROWSER)) {
1097                         print "<button dojoType=\"dijit.form.Button\" onclick=\"return feedBrowser()\">".__('More feeds')."</button>";
1098                 }
1099
1100                 print "<button dojoType=\"dijit.form.Button\" onclick=\"return dijit.byId('feedAddDlg').hide()\">".__('Cancel')."</button>
1101                         </div>";
1102
1103                 //return;
1104         }
1105
1106         function feedBrowser() {
1107                 if (defined('_DISABLE_FEED_BROWSER') && _DISABLE_FEED_BROWSER) return;
1108
1109                 $browser_search = $_REQUEST["search"];
1110
1111                 print_hidden("op", "rpc");
1112                 print_hidden("method", "updateFeedBrowser");
1113
1114                 print "<div dojoType=\"dijit.Toolbar\">
1115                         <div style='float : right'>
1116                         <img style='display : none'
1117                                 id='feed_browser_spinner' src='images/indicator_white.gif'>
1118                         <input name=\"search\" dojoType=\"dijit.form.TextBox\" size=\"20\" type=\"search\"
1119                                 onchange=\"dijit.byId('feedBrowserDlg').update()\" value=\"$browser_search\">
1120                         <button dojoType=\"dijit.form.Button\" onclick=\"dijit.byId('feedBrowserDlg').update()\">".__('Search')."</button>
1121                 </div>";
1122
1123                 print " <select name=\"mode\" dojoType=\"dijit.form.Select\" onchange=\"dijit.byId('feedBrowserDlg').update()\">
1124                         <option value='1'>" . __('Popular feeds') . "</option>
1125                         <option value='2'>" . __('Feed archive') . "</option>
1126                         </select> ";
1127
1128                 print __("limit:");
1129
1130                 print " <select dojoType=\"dijit.form.Select\" name=\"limit\" onchange=\"dijit.byId('feedBrowserDlg').update()\">";
1131
1132                 foreach (array(25, 50, 100, 200) as $l) {
1133                         //$issel = ($l == $limit) ? "selected=\"1\"" : "";
1134                         print "<option value=\"$l\">$l</option>";
1135                 }
1136
1137                 print "</select> ";
1138
1139                 print "</div>";
1140
1141                 require_once "feedbrowser.php";
1142
1143                 print "<ul class='browseFeedList' id='browseFeedList'>";
1144                 print make_feed_browser("", 25);
1145                 print "</ul>";
1146
1147                 print "<div align='center'>
1148                         <button dojoType=\"dijit.form.Button\" onclick=\"dijit.byId('feedBrowserDlg').execute()\">".__('Subscribe')."</button>
1149                         <button dojoType=\"dijit.form.Button\" style='display : none' id='feed_archive_remove' onclick=\"dijit.byId('feedBrowserDlg').removeFromArchive()\">".__('Remove')."</button>
1150                         <button dojoType=\"dijit.form.Button\" onclick=\"dijit.byId('feedBrowserDlg').hide()\" >".__('Cancel')."</button></div>";
1151
1152         }
1153
1154         function search() {
1155                 $this->params = explode(":", $_REQUEST["param"], 2);
1156
1157                 $active_feed_id = sprintf("%d", $this->params[0]);
1158                 $is_cat = $this->params[1] != "false";
1159
1160                 print "<div class=\"dlgSec\">".__('Look for')."</div>";
1161
1162                 print "<div class=\"dlgSecCont\">";
1163
1164                 print "<input dojoType=\"dijit.form.ValidationTextBox\"
1165                         style=\"font-size : 16px; width : 20em;\"
1166                         required=\"1\" name=\"query\" type=\"search\" value=''>";
1167
1168                 print "<hr/><span style='float : right'>".T_sprintf('in %s', $this->getFeedTitle($active_feed_id, $is_cat))."</span>";
1169
1170                 if (DB_TYPE == "pgsql") {
1171                         print "<hr/>";
1172                         print_select("search_language", "", Pref_Feeds::$feed_languages,
1173                                 "dojoType='dijit.form.Select' title=\"".__('Used for word stemming')."\"");
1174                 }
1175
1176                 print "</div>";
1177
1178                 print "<div class=\"dlgButtons\">";
1179
1180                 if (count(PluginHost::getInstance()->get_hooks(PluginHost::HOOK_SEARCH)) == 0) {
1181                         print "<div style=\"float : left\">
1182                                 <a class=\"visibleLink\" target=\"_blank\" href=\"http://tt-rss.org/wiki/SearchSyntax\">".__("Search syntax")."</a>
1183                                 </div>";
1184                 }
1185
1186                 print "<button dojoType=\"dijit.form.Button\" onclick=\"dijit.byId('searchDlg').execute()\">".__('Search')."</button>
1187                 <button dojoType=\"dijit.form.Button\" onclick=\"dijit.byId('searchDlg').hide()\">".__('Cancel')."</button>
1188                 </div>";
1189         }
1190
1191         function update_debugger() {
1192                 header("Content-type: text/html");
1193
1194                 $feed_id = (int)$_REQUEST["feed_id"];
1195                 @$do_update = $_REQUEST["action"] == "do_update";
1196                 $csrf_token = $_REQUEST["csrf_token"];
1197
1198                 $refetch_checked = isset($_REQUEST["force_refetch"]) ? "checked" : "";
1199                 $rehash_checked = isset($_REQUEST["force_rehash"]) ? "checked" : "";
1200
1201                 ?>
1202                 <html>
1203                 <head>
1204                         <link rel="stylesheet" type="text/css" href="css/utility.css">
1205                         <title>Feed Debugger</title>
1206                 </head>
1207                 <body class="small_margins">
1208                 <h1>Feed Debugger: <?php echo "$feed_id: " . $this->getFeedTitle($feed_id) ?></h1>
1209                 <form method="GET" action="">
1210                         <input type="hidden" name="op" value="feeds">
1211                         <input type="hidden" name="method" value="update_debugger">
1212                         <input type="hidden" name="xdebug" value="1">
1213                         <input type="hidden" name="csrf_token" value="<?php echo $csrf_token ?>">
1214                         <input type="hidden" name="action" value="do_update">
1215                         <input type="hidden" name="feed_id" value="<?php echo $feed_id ?>">
1216                         <input type="checkbox" name="force_refetch" value="1" <?php echo $refetch_checked ?>> Force refetch<br/>
1217                         <input type="checkbox" name="force_rehash" value="1" <?php echo $rehash_checked ?>> Force rehash<br/>
1218
1219                         <p/><button type="submit">Continue</button>
1220                 </form>
1221
1222                 <hr>
1223
1224                 <pre><?php
1225
1226                 if ($do_update) {
1227                         RSSUtils::update_rss_feed($feed_id, true);
1228                 }
1229
1230                 ?></pre>
1231
1232                 </body>
1233                 </html>
1234                 <?php
1235
1236         }
1237
1238         static function catchup_feed($feed, $cat_view, $owner_uid = false, $mode = 'all', $search = false) {
1239
1240                 if (!$owner_uid) $owner_uid = $_SESSION['uid'];
1241
1242                 $pdo = Db::pdo();
1243
1244                 // Todo: all this interval stuff needs some generic generator function
1245
1246                 $search_qpart = is_array($search) && $search[0] ? search_to_sql($search[0], $search[1])[0] : 'true';
1247
1248                 switch ($mode) {
1249                         case "1day":
1250                                 if (DB_TYPE == "pgsql") {
1251                                         $date_qpart = "date_entered < NOW() - INTERVAL '1 day' ";
1252                                 } else {
1253                                         $date_qpart = "date_entered < DATE_SUB(NOW(), INTERVAL 1 DAY) ";
1254                                 }
1255                                 break;
1256                         case "1week":
1257                                 if (DB_TYPE == "pgsql") {
1258                                         $date_qpart = "date_entered < NOW() - INTERVAL '1 week' ";
1259                                 } else {
1260                                         $date_qpart = "date_entered < DATE_SUB(NOW(), INTERVAL 1 WEEK) ";
1261                                 }
1262                                 break;
1263                         case "2week":
1264                                 if (DB_TYPE == "pgsql") {
1265                                         $date_qpart = "date_entered < NOW() - INTERVAL '2 week' ";
1266                                 } else {
1267                                         $date_qpart = "date_entered < DATE_SUB(NOW(), INTERVAL 2 WEEK) ";
1268                                 }
1269                                 break;
1270                         default:
1271                                 $date_qpart = "true";
1272                 }
1273
1274                 if (is_numeric($feed)) {
1275                         if ($cat_view) {
1276
1277                                 if ($feed >= 0) {
1278
1279                                         if ($feed > 0) {
1280                                                 $children = Feeds::getChildCategories($feed, $owner_uid);
1281                                                 array_push($children, $feed);
1282
1283                                                 $children = join(",", $children);
1284
1285                                                 $cat_qpart = "cat_id IN ($children)";
1286                                         } else {
1287                                                 $cat_qpart = "cat_id IS NULL";
1288                                         }
1289
1290                                         $sth = $pdo->prepare("UPDATE ttrss_user_entries
1291                                                 SET unread = false, last_read = NOW() WHERE ref_id IN
1292                                                         (SELECT id FROM
1293                                                                 (SELECT DISTINCT id FROM ttrss_entries, ttrss_user_entries WHERE ref_id = id
1294                                                                         AND owner_uid = ? AND unread = true AND feed_id IN
1295                                                                                 (SELECT id FROM ttrss_feeds WHERE $cat_qpart) AND $date_qpart AND $search_qpart) as tmp)");
1296                                         $sth->execute([$owner_uid]);
1297
1298                                 } else if ($feed == -2) {
1299
1300                                         $sth = $pdo->prepare("UPDATE ttrss_user_entries
1301                                                 SET unread = false,last_read = NOW() WHERE (SELECT COUNT(*)
1302                                                         FROM ttrss_user_labels2, ttrss_entries WHERE article_id = ref_id AND id = ref_id AND $date_qpart AND $search_qpart) > 0
1303                                                         AND unread = true AND owner_uid = ?");
1304                                         $sth->execute([$owner_uid]);
1305                                 }
1306
1307                         } else if ($feed > 0) {
1308
1309                                 $sth = $pdo->prepare("UPDATE ttrss_user_entries
1310                                         SET unread = false, last_read = NOW() WHERE ref_id IN
1311                                                 (SELECT id FROM
1312                                                         (SELECT DISTINCT id FROM ttrss_entries, ttrss_user_entries WHERE ref_id = id
1313                                                                 AND owner_uid = ? AND unread = true AND feed_id = ? AND $date_qpart AND $search_qpart) as tmp)");
1314                                 $sth->execute([$owner_uid, $feed]);
1315
1316                         } else if ($feed < 0 && $feed > LABEL_BASE_INDEX) { // special, like starred
1317
1318                                 if ($feed == -1) {
1319                                         $sth = $pdo->prepare("UPDATE ttrss_user_entries
1320                                                 SET unread = false, last_read = NOW() WHERE ref_id IN
1321                                                         (SELECT id FROM
1322                                                                 (SELECT DISTINCT id FROM ttrss_entries, ttrss_user_entries WHERE ref_id = id
1323                                                                         AND owner_uid = ? AND unread = true AND marked = true AND $date_qpart AND $search_qpart) as tmp)");
1324                                         $sth->execute([$owner_uid]);
1325                                 }
1326
1327                                 if ($feed == -2) {
1328                                         $sth = $pdo->prepare("UPDATE ttrss_user_entries
1329                                                 SET unread = false, last_read = NOW() WHERE ref_id IN
1330                                                         (SELECT id FROM
1331                                                                 (SELECT DISTINCT id FROM ttrss_entries, ttrss_user_entries WHERE ref_id = id
1332                                                                         AND owner_uid = ? AND unread = true AND published = true AND $date_qpart AND $search_qpart) as tmp)");
1333                                         $sth->execute([$owner_uid]);
1334                                 }
1335
1336                                 if ($feed == -3) {
1337
1338                                         $intl = (int) get_pref("FRESH_ARTICLE_MAX_AGE");
1339
1340                                         if (DB_TYPE == "pgsql") {
1341                                                 $match_part = "date_entered > NOW() - INTERVAL '$intl hour' ";
1342                                         } else {
1343                                                 $match_part = "date_entered > DATE_SUB(NOW(),
1344                                                         INTERVAL $intl HOUR) ";
1345                                         }
1346
1347                                         $sth = $pdo->prepare("UPDATE ttrss_user_entries
1348                                                 SET unread = false, last_read = NOW() WHERE ref_id IN
1349                                                         (SELECT id FROM
1350                                                                 (SELECT DISTINCT id FROM ttrss_entries, ttrss_user_entries WHERE ref_id = id
1351                                                                         AND owner_uid = ? AND score >= 0 AND unread = true AND $date_qpart AND $match_part AND $search_qpart) as tmp)");
1352                                         $sth->execute([$owner_uid]);
1353                                 }
1354
1355                                 if ($feed == -4) {
1356                                         $sth = $pdo->prepare("UPDATE ttrss_user_entries
1357                                                 SET unread = false, last_read = NOW() WHERE ref_id IN
1358                                                         (SELECT id FROM
1359                                                                 (SELECT DISTINCT id FROM ttrss_entries, ttrss_user_entries WHERE ref_id = id
1360                                                                         AND owner_uid = ? AND unread = true AND $date_qpart AND $search_qpart) as tmp)");
1361                                         $sth->execute([$owner_uid]);
1362                                 }
1363
1364                         } else if ($feed < LABEL_BASE_INDEX) { // label
1365
1366                                 $label_id = Labels::feed_to_label_id($feed);
1367
1368                                 $sth = $pdo->prepare("UPDATE ttrss_user_entries
1369                                         SET unread = false, last_read = NOW() WHERE ref_id IN
1370                                                 (SELECT id FROM
1371                                                         (SELECT DISTINCT ttrss_entries.id FROM ttrss_entries, ttrss_user_entries, ttrss_user_labels2 WHERE ref_id = id
1372                                                                 AND label_id = ? AND ref_id = article_id
1373                                                                 AND owner_uid = ? AND unread = true AND $date_qpart AND $search_qpart) as tmp)");
1374                                 $sth->execute([$label_id, $owner_uid]);
1375
1376                         }
1377
1378                         CCache::update($feed, $owner_uid, $cat_view);
1379
1380                 } else { // tag
1381                         $sth = $pdo->prepare("UPDATE ttrss_user_entries
1382                                 SET unread = false, last_read = NOW() WHERE ref_id IN
1383                                         (SELECT id FROM
1384                                                 (SELECT DISTINCT ttrss_entries.id FROM ttrss_entries, ttrss_user_entries, ttrss_tags WHERE ref_id = ttrss_entries.id
1385                                                         AND post_int_id = int_id AND tag_name = ?
1386                                                         AND ttrss_user_entries.owner_uid = ? AND unread = true AND $date_qpart AND $search_qpart) as tmp)");
1387                         $sth->execute([$feed, $owner_uid]);
1388
1389                 }
1390         }
1391
1392         static function getFeedArticles($feed, $is_cat = false, $unread_only = false,
1393                                                          $owner_uid = false) {
1394
1395                 $n_feed = (int) $feed;
1396                 $need_entries = false;
1397
1398                 $pdo = Db::pdo();
1399
1400                 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
1401
1402                 if ($unread_only) {
1403                         $unread_qpart = "unread = true";
1404                 } else {
1405                         $unread_qpart = "true";
1406                 }
1407
1408                 $match_part = "";
1409
1410                 if ($is_cat) {
1411                         return Feeds::getCategoryUnread($n_feed, $owner_uid);
1412                 } else if ($n_feed == -6) {
1413                         return 0;
1414                 } else if ($feed != "0" && $n_feed == 0) {
1415
1416                         $sth = $pdo->prepare("SELECT SUM((SELECT COUNT(int_id)
1417                                 FROM ttrss_user_entries,ttrss_entries WHERE int_id = post_int_id
1418                                         AND ref_id = id AND $unread_qpart)) AS count FROM ttrss_tags
1419                                 WHERE owner_uid = ? AND tag_name = ?");
1420
1421                         $sth->execute([$owner_uid, $feed]);
1422                         $row = $sth->fetch();
1423
1424                         return $row["count"];
1425
1426                 } else if ($n_feed == -1) {
1427                         $match_part = "marked = true";
1428                 } else if ($n_feed == -2) {
1429                         $match_part = "published = true";
1430                 } else if ($n_feed == -3) {
1431                         $match_part = "unread = true AND score >= 0";
1432
1433                         $intl = (int) get_pref("FRESH_ARTICLE_MAX_AGE", $owner_uid);
1434
1435                         if (DB_TYPE == "pgsql") {
1436                                 $match_part .= " AND date_entered > NOW() - INTERVAL '$intl hour' ";
1437                         } else {
1438                                 $match_part .= " AND date_entered > DATE_SUB(NOW(), INTERVAL $intl HOUR) ";
1439                         }
1440
1441                         $need_entries = true;
1442
1443                 } else if ($n_feed == -4) {
1444                         $match_part = "true";
1445                 } else if ($n_feed >= 0) {
1446
1447                         if ($n_feed != 0) {
1448                                 $match_part = "feed_id = '$n_feed'";
1449                         } else {
1450                                 $match_part = "feed_id IS NULL";
1451                         }
1452
1453                 } else if ($feed < LABEL_BASE_INDEX) {
1454
1455                         $label_id = Labels::feed_to_label_id($feed);
1456
1457                         return Feeds::getLabelUnread($label_id, $owner_uid);
1458                 }
1459
1460                 if ($match_part) {
1461
1462                         if ($need_entries) {
1463                                 $from_qpart = "ttrss_user_entries,ttrss_entries";
1464                                 $from_where = "ttrss_entries.id = ttrss_user_entries.ref_id AND";
1465                         } else {
1466                                 $from_qpart = "ttrss_user_entries";
1467                                 $from_where = "";
1468                         }
1469
1470                         $sth = $pdo->prepare("SELECT count(int_id) AS unread
1471                                 FROM $from_qpart WHERE
1472                                 $unread_qpart AND $from_where ($match_part) AND ttrss_user_entries.owner_uid = ?");
1473                         $sth->execute([$owner_uid]);
1474                         $row = $sth->fetch();
1475
1476                         return $row["unread"];
1477
1478                 } else {
1479
1480                         $sth = $pdo->prepare("SELECT COUNT(post_int_id) AS unread
1481                                 FROM ttrss_tags,ttrss_user_entries,ttrss_entries
1482                                 WHERE tag_name = ? AND post_int_id = int_id AND ref_id = ttrss_entries.id
1483                                 AND $unread_qpart AND ttrss_tags.owner_uid = ,");
1484
1485                         $sth->execute([$feed, $owner_uid]);
1486                         $row = $sth->fetch();
1487
1488                         return $row["unread"];
1489                 }
1490         }
1491
1492         /**
1493          * @return array (code => Status code, message => error message if available)
1494          *
1495          *                 0 - OK, Feed already exists
1496          *                 1 - OK, Feed added
1497          *                 2 - Invalid URL
1498          *                 3 - URL content is HTML, no feeds available
1499          *                 4 - URL content is HTML which contains multiple feeds.
1500          *                     Here you should call extractfeedurls in rpc-backend
1501          *                     to get all possible feeds.
1502          *                 5 - Couldn't download the URL content.
1503          *                 6 - Content is an invalid XML.
1504          */
1505         static function subscribe_to_feed($url, $cat_id = 0,
1506                                                            $auth_login = '', $auth_pass = '') {
1507
1508                 global $fetch_last_error;
1509                 global $fetch_last_error_content;
1510
1511                 $pdo = Db::pdo();
1512
1513                 $url = fix_url($url);
1514
1515                 if (!$url || !validate_feed_url($url)) return array("code" => 2);
1516
1517                 $contents = @fetch_file_contents($url, false, $auth_login, $auth_pass);
1518
1519                 if (!$contents) {
1520                         if (preg_match("/cloudflare\.com/", $fetch_last_error_content)) {
1521                                 $fetch_last_error .= " (feed behind Cloudflare)";
1522                         }
1523
1524                         return array("code" => 5, "message" => $fetch_last_error);
1525                 }
1526
1527                 foreach (PluginHost::getInstance()->get_hooks(PluginHost::HOOK_SUBSCRIBE_FEED) as $plugin) {
1528                         $contents = $plugin->hook_subscribe_feed($contents, $url, $auth_login, $auth_pass);
1529                 }
1530
1531                 if (is_html($contents)) {
1532                         $feedUrls = get_feeds_from_html($url, $contents);
1533
1534                         if (count($feedUrls) == 0) {
1535                                 return array("code" => 3);
1536                         } else if (count($feedUrls) > 1) {
1537                                 return array("code" => 4, "feeds" => $feedUrls);
1538                         }
1539                         //use feed url as new URL
1540                         $url = key($feedUrls);
1541                 }
1542
1543                 if ($cat_id == "0" || !$cat_id) {
1544                         $cat_qpart = "NULL";
1545                 } else {
1546                         $cat_qpart = "'$cat_id'";
1547                 }
1548
1549                 if (!(int)$cat_id) $cat_id = null;
1550
1551                 $sth = $pdo->prepare("SELECT id FROM ttrss_feeds
1552                         WHERE feed_url = ? AND owner_uid = ?");
1553                 $sth->execute([$url, $_SESSION['uid']]);
1554
1555                 if ($row = $sth->fetch()) {
1556                         return array("code" => 0, "feed_id" => (int) $row["id"]);
1557                 } else {
1558                         $sth = $pdo->prepare(
1559                                 "INSERT INTO ttrss_feeds
1560                                         (owner_uid,feed_url,title,cat_id, auth_login,auth_pass,update_method,auth_pass_encrypted)
1561                                 VALUES (?, ?, ?, ?, ?, ?, 0, false)");
1562
1563                         $sth->execute([$_SESSION['uid'], $url, "[Unknown]", $cat_id, $auth_login, $auth_pass]);
1564
1565                         $sth = $pdo->prepare("SELECT id FROM ttrss_feeds WHERE feed_url = ?
1566                                         AND owner_uid = ?");
1567                         $sth->execute([$url, $_SESSION['uid']]);
1568                         $row = $sth->fetch();
1569
1570                         $feed_id = $row["id"];
1571
1572                         if ($feed_id) {
1573                                 RSSUtils::set_basic_feed_info($feed_id);
1574                         }
1575
1576                         return array("code" => 1, "feed_id" => (int) $feed_id);
1577
1578                 }
1579         }
1580
1581         static function getFeedIcon($id) {
1582                 switch ($id) {
1583                         case 0:
1584                                 return "images/archive.png";
1585                                 break;
1586                         case -1:
1587                                 return "images/star.png";
1588                                 break;
1589                         case -2:
1590                                 return "images/feed.png";
1591                                 break;
1592                         case -3:
1593                                 return "images/fresh.png";
1594                                 break;
1595                         case -4:
1596                                 return "images/folder.png";
1597                                 break;
1598                         case -6:
1599                                 return "images/time.png";
1600                                 break;
1601                         default:
1602                                 if ($id < LABEL_BASE_INDEX) {
1603                                         return "images/label.png";
1604                                 } else {
1605                                         if (file_exists(ICONS_DIR . "/$id.ico"))
1606                                                 return ICONS_URL . "/$id.ico";
1607                                 }
1608                                 break;
1609                 }
1610
1611                 return false;
1612         }
1613
1614         static function getFeedTitle($id, $cat = false) {
1615             $pdo = Db::pdo();
1616
1617                 if ($cat) {
1618                         return Feeds::getCategoryTitle($id);
1619                 } else if ($id == -1) {
1620                         return __("Starred articles");
1621                 } else if ($id == -2) {
1622                         return __("Published articles");
1623                 } else if ($id == -3) {
1624                         return __("Fresh articles");
1625                 } else if ($id == -4) {
1626                         return __("All articles");
1627                 } else if ($id === 0 || $id === "0") {
1628                         return __("Archived articles");
1629                 } else if ($id == -6) {
1630                         return __("Recently read");
1631                 } else if ($id < LABEL_BASE_INDEX) {
1632
1633                         $label_id = Labels::feed_to_label_id($id);
1634
1635                         $sth = $pdo->prepare("SELECT caption FROM ttrss_labels2 WHERE id = ?");
1636                         $sth->execute([$label_id]);
1637
1638                         if ($row = $sth->fetch()) {
1639                                 return $row["caption"];
1640                         } else {
1641                                 return "Unknown label ($label_id)";
1642                         }
1643
1644                 } else if (is_numeric($id) && $id > 0) {
1645
1646                     $sth = $pdo->prepare("SELECT title FROM ttrss_feeds WHERE id = ?");
1647                     $sth->execute([$id]);
1648
1649                     if ($row = $sth->fetch()) {
1650                                 return $row["title"];
1651                         } else {
1652                                 return "Unknown feed ($id)";
1653                         }
1654
1655                 } else {
1656                         return $id;
1657                 }
1658         }
1659
1660         static function getCategoryUnread($cat, $owner_uid = false) {
1661
1662                 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
1663
1664                 $pdo = Db::pdo();
1665
1666                 if ($cat >= 0) {
1667
1668                     if (!$cat) $cat = null;
1669
1670                         $sth = $pdo->prepare("SELECT id FROM ttrss_feeds
1671                     WHERE (cat_id = :cat OR (:cat IS NULL AND cat_id IS NULL))
1672                                         AND owner_uid = :uid");
1673
1674                         $sth->execute([":cat" => $cat, ":uid" => $owner_uid]);
1675
1676                         $cat_feeds = array();
1677                         while ($line = $sth->fetch()) {
1678                                 array_push($cat_feeds, "feed_id = " . $line["id"]);
1679                         }
1680
1681                         if (count($cat_feeds) == 0) return 0;
1682
1683                         $match_part = implode(" OR ", $cat_feeds);
1684
1685                         $sth = $pdo->prepare("SELECT COUNT(int_id) AS unread
1686                                 FROM ttrss_user_entries
1687                                 WHERE   unread = true AND ($match_part)
1688                                 AND owner_uid = ?");
1689                         $sth->execute([$owner_uid]);
1690
1691                         $unread = 0;
1692
1693                         # this needs to be rewritten
1694                         while ($line = $sth->fetch()) {
1695                                 $unread += $line["unread"];
1696                         }
1697
1698                         return $unread;
1699                 } else if ($cat == -1) {
1700                         return getFeedUnread(-1) + getFeedUnread(-2) + getFeedUnread(-3) + getFeedUnread(0);
1701                 } else if ($cat == -2) {
1702
1703                         $sth = $pdo->prepare("SELECT COUNT(unread) AS unread FROM
1704                                         ttrss_user_entries, ttrss_user_labels2
1705                                 WHERE article_id = ref_id AND unread = true
1706                                         AND ttrss_user_entries.owner_uid = ?");
1707                         $sth->execute([$owner_uid]);
1708             $row = $sth->fetch();
1709
1710                         return $row["unread"];
1711                 }
1712         }
1713
1714         // only accepts real cats (>= 0)
1715         static function getCategoryChildrenUnread($cat, $owner_uid = false) {
1716                 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
1717
1718                 $pdo = Db::pdo();
1719
1720                 $sth = $pdo->prepare("SELECT id FROM ttrss_feed_categories WHERE parent_cat = ?
1721                                 AND owner_uid = ?");
1722                 $sth->execute([$cat, $owner_uid]);
1723
1724                 $unread = 0;
1725
1726                 while ($line = $sth->fetch()) {
1727                         $unread += Feeds::getCategoryUnread($line["id"], $owner_uid);
1728                         $unread += Feeds::getCategoryChildrenUnread($line["id"], $owner_uid);
1729                 }
1730
1731                 return $unread;
1732         }
1733
1734         static function getGlobalUnread($user_id = false) {
1735
1736                 if (!$user_id) $user_id = $_SESSION["uid"];
1737
1738                 $pdo = Db::pdo();
1739
1740                 $sth = $pdo->prepare("SELECT SUM(value) AS c_id FROM ttrss_counters_cache
1741                         WHERE owner_uid = ? AND feed_id > 0");
1742                 $sth->execute([$user_id]);
1743                 $row = $sth->fetch();
1744
1745                 return $row["c_id"];
1746         }
1747
1748         static function getCategoryTitle($cat_id) {
1749
1750                 if ($cat_id == -1) {
1751                         return __("Special");
1752                 } else if ($cat_id == -2) {
1753                         return __("Labels");
1754                 } else {
1755
1756                     $pdo = Db::pdo();
1757
1758                         $sth = $pdo->prepare("SELECT title FROM ttrss_feed_categories WHERE
1759                                 id = ?");
1760                         $sth->execute([$cat_id]);
1761
1762                         if ($row = $sth->fetch()) {
1763                                 return $row["title"];
1764                         } else {
1765                                 return __("Uncategorized");
1766                         }
1767                 }
1768         }
1769
1770         static function getLabelUnread($label_id, $owner_uid = false) {
1771                 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
1772
1773                 $pdo = Db::pdo();
1774
1775                 $sth = $pdo->prepare("SELECT COUNT(ref_id) AS unread FROM ttrss_user_entries, ttrss_user_labels2
1776                         WHERE owner_uid = ? AND unread = true AND label_id = ? AND article_id = ref_id");
1777
1778                 $sth->execute([$owner_uid, $label_id]);
1779
1780                 if ($row = $sth->fetch()) {
1781                         return $row["unread"];
1782                 } else {
1783                         return 0;
1784                 }
1785         }
1786
1787         static function queryFeedHeadlines($params) {
1788
1789                 $pdo = Db::pdo();
1790
1791                 // WARNING: due to highly dynamic nature of this query its going to quote parameters
1792         // right before adding them to SQL part
1793
1794                 $feed = $params["feed"];
1795                 $limit = isset($params["limit"]) ? $params["limit"] : 30;
1796                 $view_mode = $params["view_mode"];
1797                 $cat_view = isset($params["cat_view"]) ? $params["cat_view"] : false;
1798                 $search = isset($params["search"]) ? $params["search"] : false;
1799                 $search_language = isset($params["search_language"]) ? $params["search_language"] : "";
1800                 $override_order = isset($params["override_order"]) ? $params["override_order"] : false;
1801                 $offset = isset($params["offset"]) ? $params["offset"] : 0;
1802                 $owner_uid = isset($params["owner_uid"]) ? $params["owner_uid"] : $_SESSION["uid"];
1803                 $since_id = isset($params["since_id"]) ? $params["since_id"] : 0;
1804                 $include_children = isset($params["include_children"]) ? $params["include_children"] : false;
1805                 $ignore_vfeed_group = isset($params["ignore_vfeed_group"]) ? $params["ignore_vfeed_group"] : false;
1806                 $override_strategy = isset($params["override_strategy"]) ? $params["override_strategy"] : false;
1807                 $override_vfeed = isset($params["override_vfeed"]) ? $params["override_vfeed"] : false;
1808                 $start_ts = isset($params["start_ts"]) ? $params["start_ts"] : false;
1809                 $check_first_id = isset($params["check_first_id"]) ? $params["check_first_id"] : false;
1810                 $skip_first_id_check = isset($params["skip_first_id_check"]) ? $params["skip_first_id_check"] : false;
1811
1812                 $ext_tables_part = "";
1813                 $limit_query_part = "";
1814
1815                 $search_words = array();
1816
1817                 if ($search) {
1818                         foreach (PluginHost::getInstance()->get_hooks(PluginHost::HOOK_SEARCH) as $plugin) {
1819                                 list($search_query_part, $search_words) = $plugin->hook_search($search);
1820                                 break;
1821                         }
1822
1823                         // fall back in case of no plugins
1824                         if (!$search_query_part) {
1825                                 list($search_query_part, $search_words) = search_to_sql($search, $search_language);
1826                         }
1827                         $search_query_part .= " AND ";
1828                 } else {
1829                         $search_query_part = "";
1830                 }
1831
1832                 if ($since_id) {
1833                         $since_id_part = "ttrss_entries.id > ".$pdo->quote($since_id)." AND ";
1834                 } else {
1835                         $since_id_part = "";
1836                 }
1837
1838                 $view_query_part = "";
1839
1840                 if ($view_mode == "adaptive") {
1841                         if ($search) {
1842                                 $view_query_part = " ";
1843                         } else if ($feed != -1) {
1844
1845                                 $unread = getFeedUnread($feed, $cat_view);
1846
1847                                 if ($cat_view && $feed > 0 && $include_children)
1848                                         $unread += Feeds::getCategoryChildrenUnread($feed);
1849
1850                                 if ($unread > 0) {
1851                                         $view_query_part = " unread = true AND ";
1852                                 }
1853                         }
1854                 }
1855
1856                 if ($view_mode == "marked") {
1857                         $view_query_part = " marked = true AND ";
1858                 }
1859
1860                 if ($view_mode == "has_note") {
1861                         $view_query_part = " (note IS NOT NULL AND note != '') AND ";
1862                 }
1863
1864                 if ($view_mode == "published") {
1865                         $view_query_part = " published = true AND ";
1866                 }
1867
1868                 if ($view_mode == "unread" && $feed != -6) {
1869                         $view_query_part = " unread = true AND ";
1870                 }
1871
1872                 if ($limit > 0) {
1873                         $limit_query_part = "LIMIT " . (int)$limit;
1874                 }
1875
1876                 $allow_archived = false;
1877
1878                 $vfeed_query_part = "";
1879
1880                 /* tags */
1881                 if (!is_numeric($feed)) {
1882                         $query_strategy_part = "true";
1883                         $vfeed_query_part = "(SELECT title FROM ttrss_feeds WHERE
1884                                         id = feed_id) as feed_title,";
1885                 } else if ($feed > 0) {
1886
1887                         if ($cat_view) {
1888
1889                                 if ($feed > 0) {
1890                                         if ($include_children) {
1891                                                 # sub-cats
1892                                                 $subcats = Feeds::getChildCategories($feed, $owner_uid);
1893
1894                                                 array_push($subcats, $feed);
1895                                                 $query_strategy_part = "cat_id IN (".
1896                                                         implode(",", $subcats).")";
1897
1898                                         } else {
1899                                                 $query_strategy_part = "cat_id = " . $pdo->quote($feed);
1900                                         }
1901
1902                                 } else {
1903                                         $query_strategy_part = "cat_id IS NULL";
1904                                 }
1905
1906                                 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
1907
1908                         } else {
1909                                 $query_strategy_part = "feed_id = " . $pdo->quote($feed);
1910                         }
1911                 } else if ($feed == 0 && !$cat_view) { // archive virtual feed
1912                         $query_strategy_part = "feed_id IS NULL";
1913                         $allow_archived = true;
1914                 } else if ($feed == 0 && $cat_view) { // uncategorized
1915                         $query_strategy_part = "cat_id IS NULL AND feed_id IS NOT NULL";
1916                         $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
1917                 } else if ($feed == -1) { // starred virtual feed
1918                         $query_strategy_part = "marked = true";
1919                         $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
1920                         $allow_archived = true;
1921
1922                         if (!$override_order) {
1923                                 $override_order = "last_marked DESC, date_entered DESC, updated DESC";
1924                         }
1925
1926                 } else if ($feed == -2) { // published virtual feed OR labels category
1927
1928                         if (!$cat_view) {
1929                                 $query_strategy_part = "published = true";
1930                                 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
1931                                 $allow_archived = true;
1932
1933                                 if (!$override_order) {
1934                                         $override_order = "last_published DESC, date_entered DESC, updated DESC";
1935                                 }
1936
1937                         } else {
1938                                 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
1939
1940                                 $ext_tables_part = "ttrss_labels2,ttrss_user_labels2,";
1941
1942                                 $query_strategy_part = "ttrss_labels2.id = ttrss_user_labels2.label_id AND
1943                                                 ttrss_user_labels2.article_id = ref_id";
1944
1945                         }
1946                 } else if ($feed == -6) { // recently read
1947                         $query_strategy_part = "unread = false AND last_read IS NOT NULL";
1948
1949                         if (DB_TYPE == "pgsql") {
1950                                 $query_strategy_part .= " AND last_read > NOW() - INTERVAL '1 DAY' ";
1951                         } else {
1952                                 $query_strategy_part .= " AND last_read > DATE_SUB(NOW(), INTERVAL 1 DAY) ";
1953                         }
1954
1955                         $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
1956                         $allow_archived = true;
1957                         $ignore_vfeed_group = true;
1958
1959                         if (!$override_order) $override_order = "last_read DESC";
1960
1961                 } else if ($feed == -3) { // fresh virtual feed
1962                         $query_strategy_part = "unread = true AND score >= 0";
1963
1964                         $intl = (int) get_pref("FRESH_ARTICLE_MAX_AGE", $owner_uid);
1965
1966                         if (DB_TYPE == "pgsql") {
1967                                 $query_strategy_part .= " AND date_entered > NOW() - INTERVAL '$intl hour' ";
1968                         } else {
1969                                 $query_strategy_part .= " AND date_entered > DATE_SUB(NOW(), INTERVAL $intl HOUR) ";
1970                         }
1971
1972                         $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
1973                 } else if ($feed == -4) { // all articles virtual feed
1974                         $allow_archived = true;
1975                         $query_strategy_part = "true";
1976                         $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
1977                 } else if ($feed <= LABEL_BASE_INDEX) { // labels
1978                         $label_id = Labels::feed_to_label_id($feed);
1979
1980                         $query_strategy_part = "label_id = ".$pdo->quote($label_id)." AND
1981                                         ttrss_labels2.id = ttrss_user_labels2.label_id AND
1982                                         ttrss_user_labels2.article_id = ref_id";
1983
1984                         $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
1985                         $ext_tables_part = "ttrss_labels2,ttrss_user_labels2,";
1986                         $allow_archived = true;
1987
1988                 } else {
1989                         $query_strategy_part = "true";
1990                 }
1991
1992                 $order_by = "score DESC, date_entered DESC, updated DESC";
1993
1994                 if ($override_order) {
1995                         $order_by = $override_order;
1996                 }
1997
1998                 if ($override_strategy) {
1999                         $query_strategy_part = $override_strategy;
2000                 }
2001
2002                 if ($override_vfeed) {
2003                         $vfeed_query_part = $override_vfeed;
2004                 }
2005
2006                 if ($search) {
2007                         $feed_title = T_sprintf("Search results: %s", $search);
2008                 } else {
2009                         if ($cat_view) {
2010                                 $feed_title = Feeds::getCategoryTitle($feed);
2011                         } else {
2012                                 if (is_numeric($feed) && $feed > 0) {
2013                                         $ssth = $pdo->prepare("SELECT title,site_url,last_error,last_updated
2014                                                         FROM ttrss_feeds WHERE id = ? AND owner_uid = ?");
2015                                         $ssth->execute([$feed, $owner_uid]);
2016                     $row = $ssth->fetch();
2017
2018                                         $feed_title = $row["title"];
2019                                         $feed_site_url = $row["site_url"];
2020                                         $last_error = $row["last_error"];
2021                                         $last_updated = $row["last_updated"];
2022                                 } else {
2023                                         $feed_title = Feeds::getFeedTitle($feed);
2024                                 }
2025                         }
2026                 }
2027
2028                 $content_query_part = "content, ";
2029
2030                 if ($limit_query_part) {
2031                         $offset_query_part = "OFFSET " . (int)$offset;
2032                 } else {
2033                         $offset_query_part = "";
2034                 }
2035
2036                 if (is_numeric($feed)) {
2037                         // proper override_order applied above
2038                         if ($vfeed_query_part && !$ignore_vfeed_group && get_pref('VFEED_GROUP_BY_FEED', $owner_uid)) {
2039                                 if (!$override_order) {
2040                                         $order_by = "ttrss_feeds.title, ".$pdo->quote($order_by);
2041                                 } else {
2042                                         $order_by = "ttrss_feeds.title, ".$pdo->quote($override_order);
2043                                 }
2044                         }
2045
2046                         if (!$allow_archived) {
2047                                 $from_qpart = "${ext_tables_part}ttrss_entries LEFT JOIN ttrss_user_entries ON (ref_id = ttrss_entries.id),ttrss_feeds";
2048                                 $feed_check_qpart = "ttrss_user_entries.feed_id = ttrss_feeds.id AND";
2049
2050                         } else {
2051                                 $from_qpart = "${ext_tables_part}ttrss_entries LEFT JOIN ttrss_user_entries ON (ref_id = ttrss_entries.id)
2052                                                 LEFT JOIN ttrss_feeds ON (feed_id = ttrss_feeds.id)";
2053                         }
2054
2055                         if ($vfeed_query_part) $vfeed_query_part .= "favicon_avg_color,";
2056
2057                         if ($start_ts) {
2058                                 $start_ts_formatted = date("Y/m/d H:i:s", strtotime($start_ts));
2059                                 $start_ts_query_part = "date_entered >= '$start_ts_formatted' AND";
2060                         } else {
2061                                 $start_ts_query_part = "";
2062                         }
2063
2064                         $first_id = 0;
2065                         $first_id_query_strategy_part = $query_strategy_part;
2066
2067                         if ($feed == -3)
2068                                 $first_id_query_strategy_part = "true";
2069
2070                         if (DB_TYPE == "pgsql") {
2071                                 $sanity_interval_qpart = "date_entered >= NOW() - INTERVAL '1 hour' AND";
2072                         } else {
2073                                 $sanity_interval_qpart = "date_entered >= DATE_SUB(NOW(), INTERVAL 1 hour) AND";
2074                         }
2075
2076                         if (!$search && !$skip_first_id_check) {
2077                                 // if previous topmost article id changed that means our current pagination is no longer valid
2078                                 $query = "SELECT DISTINCT
2079                                                         ttrss_feeds.title,
2080                                                         date_entered,
2081                                                         guid,
2082                                                         ttrss_entries.id,
2083                                                         ttrss_entries.title,
2084                                                         updated,
2085                                                         score,
2086                                                         marked,
2087                                                         published,
2088                                                         last_marked,
2089                                                         last_published,
2090                                                         last_read
2091                                                 FROM
2092                                                         $from_qpart
2093                                                 WHERE
2094                                                 $feed_check_qpart
2095                                                 ttrss_user_entries.owner_uid = ".$pdo->quote($owner_uid)." AND
2096                                                 $search_query_part
2097                                                 $start_ts_query_part
2098                                                 $since_id_part
2099                                                 $sanity_interval_qpart
2100                                                 $first_id_query_strategy_part ORDER BY $order_by LIMIT 1";
2101
2102                                 if ($_REQUEST["debug"]) {
2103                                         print $query;
2104                                 }
2105
2106                                 $res = $pdo->query($query);
2107
2108                                 if ($row = $res->fetch()) {
2109                                         $first_id = (int)$row["id"];
2110
2111                                         if ($offset > 0 && $first_id && $check_first_id && $first_id != $check_first_id) {
2112                                                 return array(-1, $feed_title, $feed_site_url, $last_error, $last_updated, $search_words, $first_id);
2113                                         }
2114                                 }
2115                         }
2116
2117                         $query = "SELECT DISTINCT
2118                                                 date_entered,
2119                                                 guid,
2120                                                 ttrss_entries.id,ttrss_entries.title,
2121                                                 updated,
2122                                                 label_cache,
2123                                                 tag_cache,
2124                                                 always_display_enclosures,
2125                                                 site_url,
2126                                                 note,
2127                                                 num_comments,
2128                                                 comments,
2129                                                 int_id,
2130                                                 uuid,
2131                                                 lang,
2132                                                 hide_images,
2133                                                 unread,feed_id,marked,published,link,last_read,orig_feed_id,
2134                                                 last_marked, last_published,
2135                                                 $vfeed_query_part
2136                                                 $content_query_part
2137                                                 author,score
2138                                         FROM
2139                                                 $from_qpart
2140                                         WHERE
2141                                         $feed_check_qpart
2142                                         ttrss_user_entries.owner_uid = ".$pdo->quote($owner_uid)." AND
2143                                         $search_query_part
2144                                         $start_ts_query_part
2145                                         $view_query_part
2146                                         $since_id_part
2147                                         $query_strategy_part ORDER BY $order_by
2148                                         $limit_query_part $offset_query_part";
2149
2150                         if ($_REQUEST["debug"]) print $query;
2151
2152                         $res = $pdo->query($query);
2153
2154                 } else {
2155                         // browsing by tag
2156
2157                         $query = "SELECT DISTINCT
2158                                                         date_entered,
2159                                                         guid,
2160                                                         note,
2161                                                         ttrss_entries.id as id,
2162                                                         title,
2163                                                         updated,
2164                                                         unread,
2165                                                         feed_id,
2166                                                         orig_feed_id,
2167                                                         marked,
2168                                                         num_comments,
2169                                                         comments,
2170                                                         int_id,
2171                                                         tag_cache,
2172                                                         label_cache,
2173                                                         link,
2174                                                         lang,
2175                                                         uuid,
2176                                                         last_read,
2177                                                         (SELECT hide_images FROM ttrss_feeds WHERE id = feed_id) AS hide_images,
2178                                                         last_marked, last_published,
2179                                                         $since_id_part
2180                                                         $vfeed_query_part
2181                                                         $content_query_part
2182                                                         author, score
2183                                                 FROM ttrss_entries, ttrss_user_entries, ttrss_tags
2184                                                 WHERE
2185                                                         ref_id = ttrss_entries.id AND
2186                                                         ttrss_user_entries.owner_uid = ".$pdo->quote($owner_uid)." AND
2187                                                         post_int_id = int_id AND
2188                                                         tag_name = ".$pdo->quote($feed)." AND
2189                                                         $view_query_part
2190                                                         $search_query_part
2191                                                         $query_strategy_part ORDER BY $order_by
2192                                                         $limit_query_part $offset_query_part";
2193
2194                         if ($_REQUEST["debug"]) print $query;
2195
2196                         $res = $pdo->query($query);
2197                 }
2198
2199                 return array($res, $feed_title, $feed_site_url, $last_error, $last_updated, $search_words, $first_id);
2200
2201         }
2202
2203         static function getParentCategories($cat, $owner_uid) {
2204                 $rv = array();
2205
2206                 $pdo = Db::pdo();
2207
2208                 $sth = $pdo->prepare("SELECT parent_cat FROM ttrss_feed_categories
2209                         WHERE id = ? AND parent_cat IS NOT NULL AND owner_uid = ?");
2210                 $sth->execute([$cat, $owner_uid]);
2211
2212                 while ($line = $sth->fetch()) {
2213                         array_push($rv, $line["parent_cat"]);
2214                         $rv = array_merge($rv, Feeds::getParentCategories($line["parent_cat"], $owner_uid));
2215                 }
2216
2217                 return $rv;
2218         }
2219
2220         static function getChildCategories($cat, $owner_uid) {
2221                 $rv = array();
2222
2223                 $pdo = Db::pdo();
2224
2225                 $sth = $pdo->prepare("SELECT id FROM ttrss_feed_categories
2226                         WHERE parent_cat = ? AND owner_uid = ?");
2227                 $sth->execute([$cat, $owner_uid]);
2228
2229                 while ($line = $sth->fetch()) {
2230                         array_push($rv, $line["id"]);
2231                         $rv = array_merge($rv, Feeds::getChildCategories($line["id"], $owner_uid));
2232                 }
2233
2234                 return $rv;
2235         }
2236
2237         static function getFeedCategory($feed) {
2238                 $pdo = Db::pdo();
2239
2240             $sth = $pdo->prepare("SELECT cat_id FROM ttrss_feeds
2241                                 WHERE id = ?");
2242             $sth->execute([$feed]);
2243
2244                 if ($row = $sth->fetch()) {
2245                         return $row["cat_id"];
2246                 } else {
2247                         return false;
2248                 }
2249
2250         }
2251
2252
2253 }
2254