]> git.wh0rd.org Git - tt-rss.git/blob - classes/handler/public.php
login: check for stale session in login handler, instead of authenticate_user()
[tt-rss.git] / classes / handler / public.php
1 <?php
2 class Handler_Public extends Handler {
3
4         private function generate_syndicated_feed($owner_uid, $feed, $is_cat,
5                 $limit, $offset, $search,
6                 $view_mode = false, $format = 'atom', $order = false, $orig_guid = false, $start_ts = false) {
7
8                 require_once "lib/MiniTemplator.class.php";
9
10                 $note_style =   "background-color : #fff7d5;
11                         border-width : 1px; ".
12                         "padding : 5px; border-style : dashed; border-color : #e7d796;".
13                         "margin-bottom : 1em; color : #9a8c59;";
14
15                 if (!$limit) $limit = 60;
16
17                 $date_sort_field = "date_entered DESC, updated DESC";
18
19                 if ($feed == -2 && !$is_cat) {
20                         $date_sort_field = "last_published DESC";
21                 } else if ($feed == -1 && !$is_cat) {
22                         $date_sort_field = "last_marked DESC";
23                 }
24
25                 switch ($order) {
26                 case "title":
27                         $date_sort_field = "ttrss_entries.title, date_entered, updated";
28                         break;
29                 case "date_reverse":
30                         $date_sort_field = "date_entered, updated";
31                         break;
32                 case "feed_dates":
33                         $date_sort_field = "updated DESC";
34                         break;
35                 }
36                 $params = array(
37                         "owner_uid" => $owner_uid,
38                         "feed" => $feed,
39                         "limit" => $limit,
40                         "view_mode" => $view_mode,
41                         "cat_view" => $is_cat,
42                         "search" => $search,
43                         "override_order" => $date_sort_field,
44                         "include_children" => true,
45                         "ignore_vfeed_group" => true,
46                         "offset" => $offset,
47                         "start_ts" => $start_ts
48                 );
49
50                 $qfh_ret = Feeds::queryFeedHeadlines($params);
51
52                 $result = $qfh_ret[0];
53                 $feed_title = htmlspecialchars($qfh_ret[1]);
54                 $feed_site_url = $qfh_ret[2];
55                 /* $last_error = $qfh_ret[3]; */
56
57                 $feed_self_url = get_self_url_prefix() .
58                         "/public.php?op=rss&id=$feed&key=" .
59                         get_feed_access_key($feed, false, $owner_uid);
60
61                 if (!$feed_site_url) $feed_site_url = get_self_url_prefix();
62
63                 if ($format == 'atom') {
64                         $tpl = new MiniTemplator;
65
66                         $tpl->readTemplateFromFile("templates/generated_feed.txt");
67
68                         $tpl->setVariable('FEED_TITLE', $feed_title, true);
69                         $tpl->setVariable('VERSION', VERSION, true);
70                         $tpl->setVariable('FEED_URL', htmlspecialchars($feed_self_url), true);
71
72                         $tpl->setVariable('SELF_URL', htmlspecialchars(get_self_url_prefix()), true);
73                         while ($line = $result->fetch()) {
74
75                                 $line["content_preview"] = sanitize(truncate_string(strip_tags($line["content"]), 100, '...'));
76
77                                 foreach (PluginHost::getInstance()->get_hooks(PluginHost::HOOK_QUERY_HEADLINES) as $p) {
78                                         $line = $p->hook_query_headlines($line);
79                                 }
80
81                                 foreach (PluginHost::getInstance()->get_hooks(PluginHost::HOOK_ARTICLE_EXPORT_FEED) as $p) {
82                                         $line = $p->hook_article_export_feed($line, $feed, $is_cat);
83                                 }
84
85                                 $tpl->setVariable('ARTICLE_ID',
86                                         htmlspecialchars($orig_guid ? $line['link'] :
87                                                         $this->make_article_tag_uri($line['id'], $line['date_entered'])), true);
88                                 $tpl->setVariable('ARTICLE_LINK', htmlspecialchars($line['link']), true);
89                                 $tpl->setVariable('ARTICLE_TITLE', htmlspecialchars($line['title']), true);
90                                 $tpl->setVariable('ARTICLE_EXCERPT', $line["content_preview"], true);
91
92                                 $content = sanitize($line["content"], false, $owner_uid,
93                                         $feed_site_url, false, $line["id"]);
94
95                                 if ($line['note']) {
96                                         $content = "<div style=\"$note_style\">Article note: " . $line['note'] . "</div>" .
97                                                 $content;
98                                         $tpl->setVariable('ARTICLE_NOTE', htmlspecialchars($line['note']), true);
99                                 }
100
101                                 $tpl->setVariable('ARTICLE_CONTENT', $content, true);
102
103                                 $tpl->setVariable('ARTICLE_UPDATED_ATOM',
104                                         date('c', strtotime($line["updated"])), true);
105                                 $tpl->setVariable('ARTICLE_UPDATED_RFC822',
106                                         date(DATE_RFC822, strtotime($line["updated"])), true);
107
108                                 $tpl->setVariable('ARTICLE_AUTHOR', htmlspecialchars($line['author']), true);
109
110                                 $tpl->setVariable('ARTICLE_SOURCE_LINK', htmlspecialchars($line['site_url'] ? $line["site_url"] : get_self_url_prefix()), true);
111                                 $tpl->setVariable('ARTICLE_SOURCE_TITLE', htmlspecialchars($line['feed_title'] ? $line['feed_title'] : $feed_title), true);
112
113                                 $tags = Article::get_article_tags($line["id"], $owner_uid);
114
115                                 foreach ($tags as $tag) {
116                                         $tpl->setVariable('ARTICLE_CATEGORY', htmlspecialchars($tag), true);
117                                         $tpl->addBlock('category');
118                                 }
119
120                                 $enclosures = Article::get_article_enclosures($line["id"]);
121
122                                 foreach ($enclosures as $e) {
123                                         $type = htmlspecialchars($e['content_type']);
124                                         $url = htmlspecialchars($e['content_url']);
125                                         $length = $e['duration'] ? $e['duration'] : 1;
126
127                                         $tpl->setVariable('ARTICLE_ENCLOSURE_URL', $url, true);
128                                         $tpl->setVariable('ARTICLE_ENCLOSURE_TYPE', $type, true);
129                                         $tpl->setVariable('ARTICLE_ENCLOSURE_LENGTH', $length, true);
130
131                                         $tpl->addBlock('enclosure');
132                                 }
133
134                                 $tpl->addBlock('entry');
135                         }
136
137                         $tmp = "";
138
139                         $tpl->addBlock('feed');
140                         $tpl->generateOutputToString($tmp);
141
142                         if (@!clean($_REQUEST["noxml"])) {
143                                 header("Content-Type: text/xml; charset=utf-8");
144                         } else {
145                                 header("Content-Type: text/plain; charset=utf-8");
146                         }
147
148                         print $tmp;
149                 } else if ($format == 'json') {
150
151                         $feed = array();
152
153                         $feed['title'] = $feed_title;
154                         $feed['version'] = VERSION;
155                         $feed['feed_url'] = $feed_self_url;
156
157                         $feed['self_url'] = get_self_url_prefix();
158
159                         $feed['articles'] = array();
160
161                         while ($line = $result->fetch()) {
162
163                                 $line["content_preview"] = sanitize(truncate_string(strip_tags($line["content_preview"]), 100, '...'));
164
165                                 foreach (PluginHost::getInstance()->get_hooks(PluginHost::HOOK_QUERY_HEADLINES) as $p) {
166                                         $line = $p->hook_query_headlines($line, 100);
167                                 }
168
169                                 foreach (PluginHost::getInstance()->get_hooks(PluginHost::HOOK_ARTICLE_EXPORT_FEED) as $p) {
170                                         $line = $p->hook_article_export_feed($line, $feed, $is_cat);
171                                 }
172
173                                 $article = array();
174
175                                 $article['id'] = $line['link'];
176                                 $article['link']        = $line['link'];
177                                 $article['title'] = $line['title'];
178                                 $article['excerpt'] = $line["content_preview"];
179                                 $article['content'] = sanitize($line["content"], false, $owner_uid, $feed_site_url, false, $line["id"]);
180                                 $article['updated'] = date('c', strtotime($line["updated"]));
181
182                                 if ($line['note']) $article['note'] = $line['note'];
183                                 if ($article['author']) $article['author'] = $line['author'];
184
185                                 $tags = Article::get_article_tags($line["id"], $owner_uid);
186
187                                 if (count($tags) > 0) {
188                                         $article['tags'] = array();
189
190                                         foreach ($tags as $tag) {
191                                                 array_push($article['tags'], $tag);
192                                         }
193                                 }
194
195                                 $enclosures = Article::get_article_enclosures($line["id"]);
196
197                                 if (count($enclosures) > 0) {
198                                         $article['enclosures'] = array();
199
200                                         foreach ($enclosures as $e) {
201                                                 $type = $e['content_type'];
202                                                 $url = $e['content_url'];
203                                                 $length = $e['duration'];
204
205                                                 array_push($article['enclosures'], array("url" => $url, "type" => $type, "length" => $length));
206                                         }
207                                 }
208
209                                 array_push($feed['articles'], $article);
210                         }
211
212                         header("Content-Type: text/json; charset=utf-8");
213                         print json_encode($feed);
214
215                 } else {
216                         header("Content-Type: text/plain; charset=utf-8");
217                         print json_encode(array("error" => array("message" => "Unknown format")));
218                 }
219         }
220
221         function getUnread() {
222                 $login = clean($_REQUEST["login"]);
223                 $fresh = clean($_REQUEST["fresh"]) == "1";
224
225                 $sth = $this->pdo->prepare("SELECT id FROM ttrss_users WHERE login = ?");
226                 $sth->execute([$login]);
227
228                 if ($row = $sth->fetch()) {
229                         $uid = $row["id"];
230
231                         print Feeds::getGlobalUnread($uid);
232
233                         if ($fresh) {
234                                 print ";";
235                                 print Feeds::getFeedArticles(-3, false, true, $uid);
236                         }
237
238                 } else {
239                         print "-1;User not found";
240                 }
241         }
242
243         function getProfiles() {
244                 $login = clean($_REQUEST["login"]);
245
246                 $sth = $this->pdo->prepare("SELECT ttrss_settings_profiles.* FROM ttrss_settings_profiles,ttrss_users
247                         WHERE ttrss_users.id = ttrss_settings_profiles.owner_uid AND login = ? ORDER BY title");
248                 $sth->execute([$login]);
249
250                 print "<select dojoType='dijit.form.Select' style='width : 220px; margin : 0px' name='profile'>";
251
252                 print "<option value='0'>" . __("Default profile") . "</option>";
253
254                 while ($line = $sth->fetch()) {
255                         $id = $line["id"];
256                         $title = $line["title"];
257
258                         print "<option value='$id'>$title</option>";
259                 }
260
261                 print "</select>";
262         }
263
264         function logout() {
265                 logout_user();
266                 header("Location: index.php");
267         }
268
269         function share() {
270                 $uuid = clean($_REQUEST["key"]);
271
272                 $sth = $this->pdo->prepare("SELECT ref_id, owner_uid FROM ttrss_user_entries WHERE
273                         uuid = ?");
274                 $sth->execute([$uuid]);
275
276                 if ($row = $sth->fetch()) {
277                         header("Content-Type: text/html");
278
279                         $id = $row["ref_id"];
280                         $owner_uid = $row["owner_uid"];
281
282                         $article = Article::format_article($id, false, true, $owner_uid);
283
284                         print_r($article['content']);
285
286                 } else {
287                         print "Article not found.";
288                 }
289
290         }
291
292         function rss() {
293                 $feed = clean($_REQUEST["id"]);
294                 $key = clean($_REQUEST["key"]);
295                 $is_cat = clean($_REQUEST["is_cat"]);
296                 $limit = (int)clean($_REQUEST["limit"]);
297                 $offset = (int)clean($_REQUEST["offset"]);
298
299                 $search = clean($_REQUEST["q"]);
300                 $view_mode = clean($_REQUEST["view-mode"]);
301                 $order = clean($_REQUEST["order"]);
302                 $start_ts = clean($_REQUEST["ts"]);
303
304                 $format = clean($_REQUEST['format']);
305                 $orig_guid = clean($_REQUEST["orig_guid"]);
306
307                 if (!$format) $format = 'atom';
308
309                 if (SINGLE_USER_MODE) {
310                         authenticate_user("admin", null);
311                 }
312
313                 $owner_id = false;
314
315                 if ($key) {
316                         $sth = $this->pdo->prepare("SELECT owner_uid FROM
317                                 ttrss_access_keys WHERE access_key = ? AND feed_id = ?");
318                         $sth->execute([$key, $feed]);
319
320                         if ($row = $sth->fetch())
321                                 $owner_id = $row["owner_uid"];
322                 }
323
324                 if ($owner_id) {
325                         $this->generate_syndicated_feed($owner_id, $feed, $is_cat, $limit,
326                                 $offset, $search, $view_mode, $format, $order, $orig_guid, $start_ts);
327                 } else {
328                         header('HTTP/1.1 403 Forbidden');
329                 }
330         }
331
332         function updateTask() {
333                 PluginHost::getInstance()->run_hooks(PluginHost::HOOK_UPDATE_TASK, "hook_update_task", false);
334         }
335
336         function housekeepingTask() {
337                 PluginHost::getInstance()->run_hooks(PluginHost::HOOK_HOUSE_KEEPING, "hook_house_keeping", false);
338         }
339
340         function globalUpdateFeeds() {
341                 RPC::updaterandomfeed_real();
342
343                 PluginHost::getInstance()->run_hooks(PluginHost::HOOK_UPDATE_TASK, "hook_update_task", false);
344         }
345
346         function sharepopup() {
347                 if (SINGLE_USER_MODE) {
348                         login_sequence();
349                 }
350
351                 header('Content-Type: text/html; charset=utf-8');
352                 print "<html><head><title>Tiny Tiny RSS</title>
353                 <link rel=\"shortcut icon\" type=\"image/png\" href=\"images/favicon.png\">
354                 <link rel=\"icon\" type=\"image/png\" sizes=\"72x72\" href=\"images/favicon-72px.png\">";
355
356                 echo stylesheet_tag("css/default.css");
357                 echo javascript_tag("lib/prototype.js");
358                 echo javascript_tag("lib/scriptaculous/scriptaculous.js?load=effects,controls");
359                 print "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\"/>
360                         </head><body id='sharepopup' class='ttrss_utility'>";
361
362                 $action = clean($_REQUEST["action"]);
363
364                 if ($_SESSION["uid"]) {
365
366                         if ($action == 'share') {
367
368                                 $title = strip_tags(clean($_REQUEST["title"]));
369                                 $url = strip_tags(clean($_REQUEST["url"]));
370                                 $content = strip_tags(clean($_REQUEST["content"]));
371                                 $labels = strip_tags(clean($_REQUEST["labels"]));
372
373                                 Article::create_published_article($title, $url, $content, $labels,
374                                         $_SESSION["uid"]);
375
376                                 print "<script type='text/javascript'>";
377                                 print "window.close();";
378                                 print "</script>";
379
380                         } else {
381                                 $title = htmlspecialchars(clean($_REQUEST["title"]));
382                                 $url = htmlspecialchars(clean($_REQUEST["url"]));
383
384                                 ?>
385
386                                 <table height='100%' width='100%'><tr><td colspan='2'>
387                                 <h1><?php echo __("Share with Tiny Tiny RSS") ?></h1>
388                                 </td></tr>
389
390                                 <form id='share_form' name='share_form'>
391
392                                 <input type="hidden" name="op" value="sharepopup">
393                                 <input type="hidden" name="action" value="share">
394
395                                 <tr><td align='right'><?php echo __("Title:") ?></td>
396                                 <td width='80%'><input name='title' value="<?php echo $title ?>"></td></tr>
397                                 <tr><td align='right'><?php echo __("URL:") ?></td>
398                                 <td><input name='url' value="<?php echo $url ?>"></td></tr>
399                                 <tr><td align='right'><?php echo __("Content:") ?></td>
400                                 <td><input name='content' value=""></td></tr>
401                                 <tr><td align='right'><?php echo __("Labels:") ?></td>
402                                 <td><input name='labels' id="labels_value"
403                                         placeholder='Alpha, Beta, Gamma' value="">
404                                 </td></tr>
405
406                                 <tr><td>
407                                         <div class="autocomplete" id="labels_choices"
408                                                 style="display : block"></div></td></tr>
409
410                                 <script type='text/javascript'>document.forms[0].title.focus();</script>
411
412                                 <script type='text/javascript'>
413                                         new Ajax.Autocompleter('labels_value', 'labels_choices',
414                                    "backend.php?op=rpc&method=completeLabels",
415                                    { tokens: ',', paramName: "search" });
416                                 </script>
417
418                                 <tr><td colspan='2'>
419                                         <div style='float : right' class='insensitive-small'>
420                                         <?php echo __("Shared article will appear in the Published feed.") ?>
421                                         </div>
422                                         <button type="submit"><?php echo __('Share') ?></button>
423                                         <button onclick="return window.close()"><?php echo __('Cancel') ?></button>
424                                         </td>
425
426                                 </form>
427                                 </td></tr></table>
428                                 </body></html>
429                                 <?php
430
431                         }
432
433                 } else {
434
435                         $return = urlencode($_SERVER["REQUEST_URI"])
436                         ?>
437
438                         <form action="public.php?return=<?php echo $return ?>"
439                                 method="POST" id="loginForm" name="loginForm">
440
441                         <input type="hidden" name="op" value="login">
442
443                         <table height='100%' width='100%'><tr><td colspan='2'>
444                         <h1><?php echo __("Not logged in") ?></h1></td></tr>
445
446                         <tr><td align="right"><?php echo __("Login:") ?></td>
447                         <td align="right"><input name="login"
448                                 value="<?php echo $_SESSION["fake_login"] ?>"></td></tr>
449                                 <tr><td align="right"><?php echo __("Password:") ?></td>
450                                 <td align="right"><input type="password" name="password"
451                                 value="<?php echo $_SESSION["fake_password"] ?>"></td></tr>
452                         <tr><td colspan='2'>
453                                 <button type="submit">
454                                         <?php echo __('Log in') ?></button>
455
456                                 <button onclick="return window.close()">
457                                         <?php echo __('Cancel') ?></button>
458                         </td></tr>
459                         </table>
460
461                         </form>
462                         <?php
463                 }
464         }
465
466         function login() {
467                 if (!SINGLE_USER_MODE) {
468                         /* if a session is started here there's a stale login cookie we need to clean */
469
470                         if (session_status() != PHP_SESSION_NONE) {
471                                 $_SESSION["login_error_msg"] = __("Stale session cookie found, try logging in again");
472
473                                 header("Location: " . get_self_url_prefix());
474                                 exit;
475                         }
476
477                         $login = clean($_POST["login"]);
478                         $password = clean($_POST["password"]);
479                         $remember_me = clean($_POST["remember_me"]);
480
481                         if ($remember_me) {
482                                 session_set_cookie_params(SESSION_COOKIE_LIFETIME);
483                         } else {
484                                 session_set_cookie_params(0);
485                         }
486
487                         if (authenticate_user($login, $password)) {
488                                 $_POST["password"] = "";
489
490                                 if (get_schema_version() >= 120) {
491                                         $_SESSION["language"] = get_pref("USER_LANGUAGE", $_SESSION["uid"]);
492                                 }
493
494                                 $_SESSION["ref_schema_version"] = get_schema_version(true);
495                                 $_SESSION["bw_limit"] = !!clean($_POST["bw_limit"]);
496
497                                 if (clean($_POST["profile"])) {
498
499                                         $profile = clean($_POST["profile"]);
500
501                                         $sth = $this->pdo->prepare("SELECT id FROM ttrss_settings_profiles
502                                                 WHERE id = ? AND owner_uid = ?");
503                                         $sth->execute([$profile, $_SESSION['uid']]);
504
505                                         if ($sth->fetch()) {
506                                                 $_SESSION["profile"] = $profile;
507                                         }
508                                 }
509                         } else {
510
511                                 // start an empty session to deliver login error message
512                                 @session_start();
513
514                                 if (!isset($_SESSION["login_error_msg"]))
515                                         $_SESSION["login_error_msg"] = __("Incorrect username or password");
516
517                                 user_error("Failed login attempt for $login from {$_SERVER['REMOTE_ADDR']}", E_USER_WARNING);
518                         }
519
520                         if (clean($_REQUEST['return'])) {
521                                 header("Location: " . clean($_REQUEST['return']));
522                         } else {
523                                 header("Location: " . get_self_url_prefix());
524                         }
525                 }
526         }
527
528         /* function subtest() {
529                 header("Content-type: text/plain; charset=utf-8");
530
531                 $url = clean($_REQUEST["url"]);
532
533                 print "$url\n\n";
534
535
536                 print_r(get_feeds_from_html($url, fetch_file_contents($url)));
537
538         } */
539
540         function subscribe() {
541                 if (SINGLE_USER_MODE) {
542                         login_sequence();
543                 }
544
545                 if ($_SESSION["uid"]) {
546
547                         $feed_url = trim(clean($_REQUEST["feed_url"]));
548
549                         header('Content-Type: text/html; charset=utf-8');
550                         print "<html>
551                                 <head>
552                                         <title>Tiny Tiny RSS</title>";
553                         print stylesheet_tag("css/default.css");
554
555             print "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\"/>
556                 <link rel=\"shortcut icon\" type=\"image/png\" href=\"images/favicon.png\">
557                 <link rel=\"icon\" type=\"image/png\" sizes=\"72x72\" href=\"images/favicon-72px.png\">
558
559                                 </head>
560                                 <body class='claro ttrss_utility'>
561                                 <img class=\"floatingLogo\" src=\"images/logo_small.png\"
562                                         alt=\"Tiny Tiny RSS\"/>
563                                         <h1>".__("Subscribe to feed...")."</h1><div class='content'>";
564
565                         $rc = Feeds::subscribe_to_feed($feed_url);
566
567                         switch ($rc['code']) {
568                         case 0:
569                                 print_warning(T_sprintf("Already subscribed to <b>%s</b>.", $feed_url));
570                                 break;
571                         case 1:
572                                 print_notice(T_sprintf("Subscribed to <b>%s</b>.", $feed_url));
573                                 break;
574                         case 2:
575                                 print_error(T_sprintf("Could not subscribe to <b>%s</b>.", $feed_url));
576                                 break;
577                         case 3:
578                                 print_error(T_sprintf("No feeds found in <b>%s</b>.", $feed_url));
579                                 break;
580                         case 4:
581                                 print_notice(__("Multiple feed URLs found."));
582                                 $feed_urls = $rc["feeds"];
583                                 break;
584                         case 5:
585                                 print_error(T_sprintf("Could not subscribe to <b>%s</b>.<br>Can't download the Feed URL.", $feed_url));
586                                 break;
587                         }
588
589                         if ($feed_urls) {
590
591                                 print "<form action=\"public.php\">";
592                                 print "<input type=\"hidden\" name=\"op\" value=\"subscribe\">";
593
594                                 print "<select name=\"feed_url\">";
595
596                                 foreach ($feed_urls as $url => $name) {
597                                         $url = htmlspecialchars($url);
598                                         $name = htmlspecialchars($name);
599
600                                         print "<option value=\"$url\">$name</option>";
601                                 }
602
603                                 print "<input type=\"submit\" value=\"".__("Subscribe to selected feed").
604                                         "\">";
605
606                                 print "</form>";
607                         }
608
609                         $tp_uri = get_self_url_prefix() . "/prefs.php";
610                         $tt_uri = get_self_url_prefix();
611
612                         if ($rc['code'] <= 2){
613                             $sth = $this->pdo->prepare("SELECT id FROM ttrss_feeds WHERE
614                                         feed_url = ? AND owner_uid = ?");
615                             $sth->execute([$feed_url, $_SESSION['uid']]);
616                             $row = $sth->fetch();
617
618                                 $feed_id = $row["id"];
619                         } else {
620                                 $feed_id = 0;
621                         }
622                         print "<p>";
623
624                         if ($feed_id) {
625                                 print "<form method=\"GET\" style='display: inline'
626                                         action=\"$tp_uri\">
627                                         <input type=\"hidden\" name=\"tab\" value=\"feedConfig\">
628                                         <input type=\"hidden\" name=\"method\" value=\"editFeed\">
629                                         <input type=\"hidden\" name=\"methodparam\" value=\"$feed_id\">
630                                         <input type=\"submit\" value=\"".__("Edit subscription options")."\">
631                                         </form>";
632                         }
633
634                         print "<form style='display: inline' method=\"GET\" action=\"$tt_uri\">
635                                 <input type=\"submit\" value=\"".__("Return to Tiny Tiny RSS")."\">
636                                 </form></p>";
637
638                         print "</div></body></html>";
639
640                 } else {
641                         render_login_form();
642                 }
643         }
644
645         function index() {
646                 header("Content-Type: text/plain");
647                 print error_json(13);
648         }
649
650         function forgotpass() {
651                 startup_gettext();
652
653                 @$hash = clean($_REQUEST["hash"]);
654
655                 header('Content-Type: text/html; charset=utf-8');
656                 print "<html><head><title>Tiny Tiny RSS</title>
657                 <link rel=\"shortcut icon\" type=\"image/png\" href=\"images/favicon.png\">
658                 <link rel=\"icon\" type=\"image/png\" sizes=\"72x72\" href=\"images/favicon-72px.png\">";
659
660                 echo stylesheet_tag("lib/dijit/themes/claro/claro.css");
661                 echo stylesheet_tag("css/default.css");
662                 echo javascript_tag("lib/prototype.js");
663
664                 print "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\"/>
665                         </head><body class='claro ttrss_utility'>";
666
667                 print '<div class="floatingLogo"><img src="images/logo_small.png"></div>';
668                 print "<h1>".__("Password recovery")."</h1>";
669                 print "<div class='content'>";
670
671                 @$method = clean($_POST['method']);
672
673                 if ($hash) {
674                         $login = clean($_REQUEST["login"]);
675
676                         if ($login) {
677                                 $sth = $this->pdo->prepare("SELECT id, resetpass_token FROM ttrss_users
678                                         WHERE login = ?");
679                                 $sth->execute([$login]);
680
681                                 if ($row = $sth->fetch()) {
682                                         $id = $row["id"];
683                                         $resetpass_token_full = $row["resetpass_token"];
684                                         list($timestamp, $resetpass_token) = explode(":", $resetpass_token_full);
685
686                                         if ($timestamp && $resetpass_token &&
687                                                 $timestamp >= time() - 15*60*60 &&
688                                                 $resetpass_token == $hash) {
689
690                                                         $sth = $this->pdo->prepare("UPDATE ttrss_users SET resetpass_token = NULL
691                                                                 WHERE id = ?");
692                                                         $sth->execute([$id]);
693
694                                                         Pref_Users::resetUserPassword($id, true);
695
696                                                         print "<p>"."Completed."."</p>";
697
698                                         } else {
699                                                 print_error("Some of the information provided is missing or incorrect.");
700                                         }
701                                 } else {
702                                         print_error("Some of the information provided is missing or incorrect.");
703                                 }
704                         } else {
705                                 print_error("Some of the information provided is missing or incorrect.");
706                         }
707
708                         print "<form method=\"GET\" action=\"index.php\">
709                                 <input type=\"submit\" value=\"".__("Return to Tiny Tiny RSS")."\">
710                                 </form>";
711
712                 } else if (!$method) {
713                         print_notice(__("You will need to provide valid account name and email. A password reset link will be sent to your email address."));
714
715                         print "<form method='POST' action='public.php'>";
716                         print "<input type='hidden' name='method' value='do'>";
717                         print "<input type='hidden' name='op' value='forgotpass'>";
718
719                         print "<fieldset>";
720                         print "<label>".__("Login:")."</label>";
721                         print "<input class='input input-text' type='text' name='login' value='' required>";
722                         print "</fieldset>";
723
724                         print "<fieldset>";
725                         print "<label>".__("Email:")."</label>";
726                         print "<input class='input input-text' type='email' name='email' value='' required>";
727                         print "</fieldset>";
728
729                         print "<fieldset>";
730                         print "<label>".__("How much is two plus two:")."</label>";
731                         print "<input class='input input-text' type='text' name='test' value='' required>";
732                         print "</fieldset>";
733
734                         print "<p/>";
735                         print "<button type='submit'>".__("Reset password")."</button>";
736
737                         print "</form>";
738                 } else if ($method == 'do') {
739
740                         $login = clean($_POST["login"]);
741                         $email = clean($_POST["email"]);
742                         $test = clean($_POST["test"]);
743
744                         if (($test != 4 && $test != 'four') || !$email || !$login) {
745                                 print_error(__('Some of the required form parameters are missing or incorrect.'));
746
747                                 print "<form method=\"GET\" action=\"public.php\">
748                                         <input type=\"hidden\" name=\"op\" value=\"forgotpass\">
749                                         <input type=\"submit\" value=\"".__("Go back")."\">
750                                         </form>";
751
752                         } else {
753
754                                 print_notice("Password reset instructions are being sent to your email address.");
755
756                                 $sth = $this->pdo->prepare("SELECT id FROM ttrss_users
757                                         WHERE login = ? AND email = ?");
758                                 $sth->execute([$login, $email]);
759
760                                 if ($row = $sth->fetch()) {
761                                         $id = $row["id"];
762
763                                         if ($id) {
764                                                 $resetpass_token = sha1(get_random_bytes(128));
765                                                 $resetpass_link = get_self_url_prefix() . "/public.php?op=forgotpass&hash=" . $resetpass_token .
766                                                         "&login=" . urlencode($login);
767
768                                                 require_once 'classes/ttrssmailer.php';
769                                                 require_once "lib/MiniTemplator.class.php";
770
771                                                 $tpl = new MiniTemplator;
772
773                                                 $tpl->readTemplateFromFile("templates/resetpass_link_template.txt");
774
775                                                 $tpl->setVariable('LOGIN', $login);
776                                                 $tpl->setVariable('RESETPASS_LINK', $resetpass_link);
777
778                                                 $tpl->addBlock('message');
779
780                                                 $message = "";
781
782                                                 $tpl->generateOutputToString($message);
783
784                                                 $mail = new ttrssMailer();
785
786                                                 $rc = $mail->quickMail($email, $login,
787                                                         __("[tt-rss] Password reset request"),
788                                                         $message, false);
789
790                                                 if (!$rc) print_error($mail->ErrorInfo);
791
792                                                 $resetpass_token_full = time() . ":" . $resetpass_token;
793
794                                                 $sth = $this->pdo->prepare("UPDATE ttrss_users
795                                                         SET resetpass_token = ?
796                                                         WHERE login = ? AND email = ?");
797
798                                                 $sth->execute([$resetpass_token_full, $login, $email]);
799
800                                                 //Pref_Users::resetUserPassword($id, false);
801
802                                                 print "<p>";
803
804                                                 print "<p>"."Completed."."</p>";
805                                         } else {
806                                                 print_error("User ID not found.");
807                                         }
808
809                                         print "<form method=\"GET\" action=\"index.php\">
810                                                 <input type=\"submit\" value=\"".__("Return to Tiny Tiny RSS")."\">
811                                                 </form>";
812
813                                 } else {
814                                         print_error(__("Sorry, login and email combination not found."));
815
816                                         print "<form method=\"GET\" action=\"public.php\">
817                                                 <input type=\"hidden\" name=\"op\" value=\"forgotpass\">
818                                                 <input type=\"submit\" value=\"".__("Go back")."\">
819                                                 </form>";
820
821                                 }
822                         }
823
824                 }
825
826                 print "</div>";
827                 print "</body>";
828                 print "</html>";
829
830         }
831
832         function dbupdate() {
833                 startup_gettext();
834
835                 if (!SINGLE_USER_MODE && $_SESSION["access_level"] < 10) {
836                         $_SESSION["login_error_msg"] = __("Your access level is insufficient to run this script.");
837                         render_login_form();
838                         exit;
839                 }
840
841                 ?><html>
842                         <head>
843                         <title>Database Updater</title>
844                         <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
845                         <link rel="stylesheet" type="text/css" href="css/default.css"/>
846                         <link rel=\"shortcut icon\" type=\"image/png\" href=\"images/favicon.png\">
847                         <link rel=\"icon\" type=\"image/png\" sizes=\"72x72\" href=\"images/favicon-72px.png\">
848                         </head>
849                         <style type="text/css">
850                                 span.ok { color : #009000; font-weight : bold; }
851                                 span.err { color : #ff0000; font-weight : bold; }
852                         </style>
853                 <body class="claro ttrss_utility">
854                         <script type='text/javascript'>
855                         function confirmOP() {
856                                 return confirm("Update the database?");
857                         }
858                         </script>
859
860                         <div class="floatingLogo"><img src="images/logo_small.png"></div>
861
862                         <h1><?php echo __("Database Updater") ?></h1>
863
864                         <div class="content">
865
866                         <?php
867                                 @$op = clean($_REQUEST["subop"]);
868                                 $updater = new DbUpdater(Db::pdo(), DB_TYPE, SCHEMA_VERSION);
869
870                                 if ($op == "performupdate") {
871                                         if ($updater->isUpdateRequired()) {
872
873                                                 print "<h2>Performing updates</h2>";
874
875                                                 print "<h3>Updating to schema version " . SCHEMA_VERSION . "</h3>";
876
877                                                 print "<ul>";
878
879                                                 for ($i = $updater->getSchemaVersion() + 1; $i <= SCHEMA_VERSION; $i++) {
880                                                         print "<li>Performing update up to version $i...";
881
882                                                         $result = $updater->performUpdateTo($i, true);
883
884                                                         if (!$result) {
885                                                                 print "<span class='err'>FAILED!</span></li></ul>";
886
887                                                                 print_warning("One of the updates failed. Either retry the process or perform updates manually.");
888                                                                 print "<p><form method=\"GET\" action=\"index.php\">
889                                                                 <input type=\"submit\" value=\"".__("Return to Tiny Tiny RSS")."\">
890                                                                 </form>";
891
892                                                                 return;
893                                                         } else {
894                                                                 print "<span class='ok'>OK!</span></li>";
895                                                         }
896                                                 }
897
898                                                 print "</ul>";
899
900                                                 print_notice("Your Tiny Tiny RSS database is now updated to the latest version.");
901
902                                                 print "<p><form method=\"GET\" action=\"index.php\">
903                                                 <input type=\"submit\" value=\"".__("Return to Tiny Tiny RSS")."\">
904                                                 </form>";
905
906                                         } else {
907                                                 print "<h2>Your database is up to date.</h2>";
908
909                                                 print "<p><form method=\"GET\" action=\"index.php\">
910                                                 <input type=\"submit\" value=\"".__("Return to Tiny Tiny RSS")."\">
911                                                 </form>";
912                                         }
913                                 } else {
914                                         if ($updater->isUpdateRequired()) {
915
916                                                 print "<h2>Database update required</h2>";
917
918                                                 print_notice("<h4>".
919                                                 sprintf("Your Tiny Tiny RSS database needs update to the latest version: %d to %d.",
920                                                         $updater->getSchemaVersion(), SCHEMA_VERSION).
921                                                 "</h4>");
922
923                                                 print_warning("Please backup your database before proceeding.");
924
925                                                 print "<form method='POST'>
926                                                         <input type='hidden' name='subop' value='performupdate'>
927                                                         <input type='submit' onclick='return confirmOP()' value='".__("Perform updates")."'>
928                                                 </form>";
929
930                                         } else {
931
932                                                 print_notice("Tiny Tiny RSS database is up to date.");
933
934                                                 print "<p><form method=\"GET\" action=\"index.php\">
935                                                         <input type=\"submit\" value=\"".__("Return to Tiny Tiny RSS")."\">
936                                                 </form>";
937
938                                         }
939                                 }
940                         ?>
941
942                         </div>
943                         </body>
944                         </html>
945                 <?php
946         }
947
948         function cached_url() {
949                 @$req_filename = basename($_GET['hash']);
950
951                 // we don't need an extension to find the file, hash is a complete URL
952                 $hash = preg_replace("/\.[^\.]*$/", "", $req_filename);
953
954                 if ($hash) {
955
956                         $filename = CACHE_DIR . '/images/' . $hash;
957
958                         if (file_exists($filename)) {
959                                 header("Content-Disposition: inline; filename=\"$req_filename\"");
960
961                                 send_local_file($filename);
962
963                         } else {
964                                 header($_SERVER["SERVER_PROTOCOL"]." 404 Not Found");
965                                 echo "File not found.";
966                         }
967                 }
968         }
969
970         private function make_article_tag_uri($id, $timestamp) {
971
972                 $timestamp = date("Y-m-d", strtotime($timestamp));
973
974                 return "tag:" . parse_url(get_self_url_prefix(), PHP_URL_HOST) . ",$timestamp:/$id";
975         }
976
977         // this should be used very carefully because this endpoint is exposed to unauthenticated users
978         // plugin data is not loaded because there's no user context and owner_uid/session may or may not be available
979         // in general, don't do anything user-related in here and do not modify $_SESSION
980         public function pluginhandler() {
981                 $host = new PluginHost();
982
983                 $plugin = basename(clean($_REQUEST["plugin"]));
984                 $method = clean($_REQUEST["pmethod"]);
985
986                 $host->load($plugin, PluginHost::KIND_USER, 0);
987                 $host->load_data();
988
989                 $pclass = $host->get_plugin($plugin);
990
991                 if ($pclass) {
992                         if (method_exists($pclass, $method)) {
993                                 if ($pclass->is_public_method($method)) {
994                                         $pclass->$method();
995                                 } else {
996                                         header("Content-Type: text/json");
997                                         print error_json(6);
998                                 }
999                         } else {
1000                                 header("Content-Type: text/json");
1001                                 print error_json(13);
1002                         }
1003                 } else {
1004                         header("Content-Type: text/json");
1005                         print error_json(14);
1006                 }
1007         }
1008 }
1009 ?>