]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - lib/action.php
[CORE][ROUTER] Fix wrong parameter in all/:tag by XRevan86
[quix0rs-gnu-social.git] / lib / action.php
1 <?php
2 /**
3  * StatusNet, the distributed open-source microblogging tool
4  *
5  * Base class for all actions (~views)
6  *
7  * PHP version 5
8  *
9  * LICENCE: This program is free software: you can redistribute it and/or modify
10  * it under the terms of the GNU Affero General Public License as published by
11  * the Free Software Foundation, either version 3 of the License, or
12  * (at your option) any later version.
13  *
14  * This program is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17  * GNU Affero General Public License for more details.
18  *
19  * You should have received a copy of the GNU Affero General Public License
20  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
21  *
22  * @category  Action
23  * @package   StatusNet
24  * @author    Evan Prodromou <evan@status.net>
25  * @author    Sarven Capadisli <csarven@status.net>
26  * @copyright 2008 StatusNet, Inc.
27  * @license   http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
28  * @link      http://status.net/
29  */
30
31 if (!defined('GNUSOCIAL')) {
32     exit(1);
33 }
34
35 /**
36  * Base class for all actions
37  *
38  * This is the base class for all actions in the package. An action is
39  * more or less a "view" in an MVC framework.
40  *
41  * Actions are responsible for extracting and validating parameters; using
42  * model classes to read and write to the database; and doing ouput.
43  *
44  * @category Output
45  * @package  StatusNet
46  * @author   Evan Prodromou <evan@status.net>
47  * @author   Sarven Capadisli <csarven@status.net>
48  * @license  http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
49  * @link     http://status.net/
50  *
51  * @see      HTMLOutputter
52  */
53 class Action extends HTMLOutputter // lawsuit
54 {
55     // This should be protected/private in the future
56     public $args = [];
57
58     // Action properties, set per-class
59     protected $action = false;
60     protected $ajax = false;
61     protected $menus = true;
62     protected $needLogin = false;
63     protected $redirectAfterLogin = false;
64     protected $needPost = false;    // implies canPost if true
65     protected $canPost = false;     // can this action handle POST method?
66
67     // The currently scoped profile (normally Profile::current; from $this->auth_user for API)
68     protected $scoped = null;
69
70     // Related to front-end user representation
71     protected $format = null;
72     protected $error = null;
73     protected $msg = null;
74
75     /**
76      * Constructor
77      *
78      * Just wraps the HTMLOutputter constructor.
79      *
80      * @param string $output URI to output to, default = stdout
81      * @param boolean $indent Whether to indent output, default true
82      *
83      * @see XMLOutputter::__construct
84      * @see HTMLOutputter::__construct
85      */
86     public function __construct($output = 'php://output', $indent = null)
87     {
88         parent::__construct($output, $indent);
89     }
90
91     public static function run(array $args = [], $output = 'php://output', $indent = null)
92     {
93         $class = get_called_class();
94         $action = new $class($output, $indent);
95         set_exception_handler(array($action, 'handleError'));
96         $action->execute($args);
97         return $action;
98     }
99
100     public function getInfo()
101     {
102         return $this->msg;
103     }
104
105     public function handleError($e)
106     {
107         if ($e instanceof ClientException) {
108             $this->clientError($e->getMessage(), $e->getCode());
109         } elseif ($e instanceof ServerException) {
110             $this->serverError($e->getMessage(), $e->getCode());
111         } else {
112             // If it wasn't specified more closely which kind of exception it was
113             $this->serverError($e->getMessage(), 500);
114         }
115     }
116
117     /**
118      * Client error
119      *
120      * @param string $msg error message to display
121      * @param integer $code http error code, 400 by default
122      * @param string $format error format (json, xml, text) for ApiAction
123      *
124      * @return void
125      * @throws ClientException always
126      */
127     public function clientError($msg, $code = 400, $format = null)
128     {
129         // $format is currently only relevant for an ApiAction anyway
130         if ($format === null) {
131             $format = $this->format;
132         }
133
134         common_debug("User error '{$code}' on '{$this->action}': {$msg}", __FILE__);
135
136         if (!array_key_exists($code, ClientErrorAction::$status)) {
137             $code = 400;
138         }
139
140         $status_string = ClientErrorAction::$status[$code];
141
142         switch ($format) {
143             case 'xml':
144                 header("HTTP/1.1 {$code} {$status_string}");
145                 $this->initDocument('xml');
146                 $this->elementStart('hash');
147                 $this->element('error', null, $msg);
148                 $this->element('request', null, $_SERVER['REQUEST_URI']);
149                 $this->elementEnd('hash');
150                 $this->endDocument('xml');
151                 break;
152             case 'json':
153                 if (!isset($this->callback)) {
154                     header("HTTP/1.1 {$code} {$status_string}");
155                 }
156                 $this->initDocument('json');
157                 $error_array = array('error' => $msg, 'request' => $_SERVER['REQUEST_URI']);
158                 print(json_encode($error_array));
159                 $this->endDocument('json');
160                 break;
161             case 'text':
162                 header("HTTP/1.1 {$code} {$status_string}");
163                 header('Content-Type: text/plain; charset=utf-8');
164                 echo $msg;
165                 break;
166             default:
167                 common_log(LOG_ERR, 'Handled clientError (' . _ve($code) . ') but cannot output into desired format (' . _ve($this->format) . '): ' . _ve($msg));
168                 $action = new ClientErrorAction($msg, $code);
169                 $action->execute();
170         }
171         exit((int)$code);
172     }
173
174     public function execute(array $args = [])
175     {
176         // checkMirror stuff
177         if (common_config('db', 'mirror') && $this->isReadOnly($args)) {
178             if (is_array(common_config('db', 'mirror'))) {
179                 // "load balancing", ha ha
180                 $arr = common_config('db', 'mirror');
181                 $k = array_rand($arr);
182                 $mirror = $arr[$k];
183             } else {
184                 $mirror = common_config('db', 'mirror');
185             }
186
187             // everyone else uses the mirror
188             common_config_set('db', 'database', $mirror);
189         }
190
191         if (Event::handle('StartActionExecute', array($this, &$args))) {
192             $prepared = $this->prepare($args);
193             if ($prepared) {
194                 $this->handle();
195             } else {
196                 common_debug('Prepare failed for Action.');
197             }
198
199             $this->flush();
200             Event::handle('EndActionExecute', array($this));
201         }
202     }
203
204     /**
205      * Return true if read only.
206      *
207      * MAY override
208      *
209      * @param array $args other arguments
210      *
211      * @return boolean is read only action?
212      */
213     public function isReadOnly($args)
214     {
215         return false;
216     }
217
218     /**
219      * For initializing members of the class.
220      *
221      * @param array $args misc. arguments
222      *
223      * @return boolean true
224      * @throws ClientException
225      */
226     protected function prepare(array $args = [])
227     {
228         if ($this->needPost && !$this->isPost()) {
229             // TRANS: Client error. POST is a HTTP command. It should not be translated.
230             $this->clientError(_('This method requires a POST.'), 405);
231         }
232
233         // needPost, of course, overrides canPost if true
234         if (!$this->canPost) {
235             $this->canPost = $this->needPost;
236         }
237
238         $this->args = common_copy_args($args);
239
240         // This could be set with get_called_action and then
241         // chop off 'Action' from the class name. In lower case.
242         $this->action = strtolower($this->trimmed('action'));
243
244         if ($this->ajax || $this->boolean('ajax')) {
245             // check with GNUsocial::isAjax()
246             GNUsocial::setAjax(true);
247         }
248
249         if ($this->needLogin) {
250             $this->checkLogin(); // if not logged in, this redirs/excepts
251         }
252         
253         if ($this->redirectAfterLogin) {
254             common_set_returnto($this->selfUrl());
255         }
256
257         $this->updateScopedProfile();
258
259         return true;
260     }
261
262     /**
263      * Check if the current request is a POST
264      *
265      * @return boolean true if POST; otherwise false.
266      */
267
268     public function isPost()
269     {
270         return ($_SERVER['REQUEST_METHOD'] == 'POST');
271     }
272
273     // Must be run _after_ prepare
274
275     /**
276      * Returns trimmed query argument or default value if not found
277      *
278      * @param string $key requested argument
279      * @param string $def default value to return if $key is not provided
280      *
281      * @return boolean is read only action?
282      */
283     public function trimmed($key, $def = null)
284     {
285         $arg = $this->arg($key, $def);
286         return is_string($arg) ? trim($arg) : $arg;
287     }
288
289     /**
290      * Returns query argument or default value if not found
291      *
292      * @param string $key requested argument
293      * @param string $def default value to return if $key is not provided
294      *
295      * @return boolean is read only action?
296      */
297     public function arg($key, $def = null)
298     {
299         if (array_key_exists($key, $this->args)) {
300             return $this->args[$key];
301         } else {
302             return $def;
303         }
304     }
305
306     /**
307      * Boolean understands english (yes, no, true, false)
308      *
309      * @param string $key query key we're interested in
310      * @param string $def default value
311      *
312      * @return boolean interprets yes/no strings as boolean
313      */
314     public function boolean($key, $def = false)
315     {
316         $arg = strtolower($this->trimmed($key));
317
318         if (is_null($arg)) {
319             return $def;
320         } elseif (in_array($arg, array('true', 'yes', '1', 'on'))) {
321             return true;
322         } elseif (in_array($arg, array('false', 'no', '0'))) {
323             return false;
324         } else {
325             return $def;
326         }
327     }
328
329     /**
330      * If not logged in, take appropriate action (redir or exception)
331      *
332      * @param boolean $redir Redirect to login if not logged in
333      *
334      * @return boolean true if logged in (never returns if not)
335      * @throws ClientException
336      */
337     public function checkLogin($redir = true)
338     {
339         if (common_logged_in()) {
340             return true;
341         }
342
343         if ($redir == true) {
344             common_set_returnto($_SERVER['REQUEST_URI']);
345             common_redirect(common_local_url('login'));
346         }
347
348         // TRANS: Error message displayed when trying to perform an action that requires a logged in user.
349         $this->clientError(_('Not logged in.'), 403);
350     }
351
352     public function updateScopedProfile()
353     {
354         $this->scoped = Profile::current();
355         return $this->scoped;
356     }
357
358     /**
359      * Handler method
360      */
361     protected function handle()
362     {
363         header('Vary: Accept-Encoding,Cookie');
364
365         $lm = $this->lastModified();
366         $etag = $this->etag();
367
368         if ($etag) {
369             header('ETag: ' . $etag);
370         }
371
372         if ($lm) {
373             header('Last-Modified: ' . date(DATE_RFC1123, $lm));
374             if ($this->isCacheable()) {
375                 header('Expires: ' . gmdate('D, d M Y H:i:s', 0) . ' GMT');
376                 header("Cache-Control: private, must-revalidate, max-age=0");
377                 header("Pragma:");
378             }
379         }
380
381         $checked = false;
382         if ($etag) {
383             $if_none_match = (array_key_exists('HTTP_IF_NONE_MATCH', $_SERVER)) ?
384                 $_SERVER['HTTP_IF_NONE_MATCH'] : null;
385             if ($if_none_match) {
386                 // If this check fails, ignore the if-modified-since below.
387                 $checked = true;
388                 if ($this->_hasEtag($etag, $if_none_match)) {
389                     header('HTTP/1.1 304 Not Modified');
390                     // Better way to do this?
391                     exit(0);
392                 }
393             }
394         }
395
396         if (!$checked && $lm && array_key_exists('HTTP_IF_MODIFIED_SINCE', $_SERVER)) {
397             $if_modified_since = $_SERVER['HTTP_IF_MODIFIED_SINCE'];
398             $ims = strtotime($if_modified_since);
399             if ($lm <= $ims) {
400                 header('HTTP/1.1 304 Not Modified');
401                 // Better way to do this?
402                 exit(0);
403             }
404         }
405     }
406
407     /**
408      * Return last modified, if applicable.
409      *
410      * MAY override
411      *
412      * @return string last modified http header
413      */
414     public function lastModified()
415     {
416         // For comparison with If-Last-Modified
417         // If not applicable, return null
418         return null;
419     }
420
421     /**
422      * Return etag, if applicable.
423      *
424      * MAY override
425      *
426      * @return string etag http header
427      */
428     public function etag()
429     {
430         return null;
431     }
432
433     /**
434      * Is this action cacheable?
435      *
436      * If the action returns a last-modified
437      *
438      * @return boolean is read only action?
439      */
440     public function isCacheable()
441     {
442         return true;
443     }
444
445     /**
446      * Has etag? (private)
447      *
448      * @param string $etag etag http header
449      * @param string $if_none_match ifNoneMatch http header
450      *
451      * @return boolean
452      */
453     public function _hasEtag($etag, $if_none_match)
454     {
455         $etags = explode(',', $if_none_match);
456         return in_array($etag, $etags) || in_array('*', $etags);
457     }
458
459     /**
460      * Server error
461      *
462      * @param string $msg error message to display
463      * @param integer $code http error code, 500 by default
464      *
465      * @param string $format
466      * @return void
467      */
468     public function serverError($msg, $code = 500, $format = null)
469     {
470         if ($format === null) {
471             $format = $this->format;
472         }
473
474         common_debug("Server error '{$code}' on '{$this->action}': {$msg}", __FILE__);
475
476         if (!array_key_exists($code, ServerErrorAction::$status)) {
477             $code = 500;
478         }
479
480         $status_string = ServerErrorAction::$status[$code];
481
482         switch ($format) {
483             case 'xml':
484                 header("HTTP/1.1 {$code} {$status_string}");
485                 $this->initDocument('xml');
486                 $this->elementStart('hash');
487                 $this->element('error', null, $msg);
488                 $this->element('request', null, $_SERVER['REQUEST_URI']);
489                 $this->elementEnd('hash');
490                 $this->endDocument('xml');
491                 break;
492             case 'json':
493                 if (!isset($this->callback)) {
494                     header("HTTP/1.1 {$code} {$status_string}");
495                 }
496                 $this->initDocument('json');
497                 $error_array = array('error' => $msg, 'request' => $_SERVER['REQUEST_URI']);
498                 print(json_encode($error_array));
499                 $this->endDocument('json');
500                 break;
501             default:
502                 common_log(LOG_ERR, 'Handled serverError (' . _ve($code) . ') but cannot output into desired format (' . _ve($this->format) . '): ' . _ve($msg));
503                 $action = new ServerErrorAction($msg, $code);
504                 $action->execute();
505         }
506
507         exit((int)$code);
508     }
509
510     public function getScoped()
511     {
512         return ($this->scoped instanceof Profile) ? $this->scoped : null;
513     }
514
515     public function isAction(array $names)
516     {
517         foreach ($names as $class) {
518             // PHP is case insensitive, and we have stuff like ApiUpperCaseAction,
519             // but we at least make a point out of wanting to do stuff case-sensitive.
520             $class = ucfirst($class) . 'Action';
521             if ($this instanceof $class) {
522                 return true;
523             }
524         }
525         return false;
526     }
527
528     /**
529      * Show page, a template method.
530      *
531      * @return void
532      * @throws ClientException
533      * @throws ReflectionException
534      * @throws ServerException
535      */
536     public function showPage()
537     {
538         if (GNUsocial::isAjax()) {
539             self::showAjax();
540             return;
541         }
542         if (Event::handle('StartShowHTML', array($this))) {
543             $this->startHTML();
544             $this->flush();
545             Event::handle('EndShowHTML', array($this));
546         }
547         if (Event::handle('StartShowHead', array($this))) {
548             $this->showHead();
549             $this->flush();
550             Event::handle('EndShowHead', array($this));
551         }
552         if (Event::handle('StartShowBody', array($this))) {
553             $this->showBody();
554             Event::handle('EndShowBody', array($this));
555         }
556         if (Event::handle('StartEndHTML', array($this))) {
557             $this->endHTML();
558             Event::handle('EndEndHTML', array($this));
559         }
560     }
561
562     public function showAjax()
563     {
564         $this->startHTML('text/xml;charset=utf-8');
565         $this->elementStart('head');
566         // TRANS: Title for conversation page.
567         $this->element('title', null, $this->title());
568         $this->elementEnd('head');
569         $this->elementStart('body');
570         if ($this->getError()) {
571             $this->element('p', array('id' => 'error'), $this->getError());
572         } else {
573             $this->showContent();
574         }
575         $this->elementEnd('body');
576         $this->endHTML();
577     }
578
579     /**
580      * Returns the page title
581      *
582      * SHOULD overload
583      *
584      * @return string page title
585      */
586
587     public function title()
588     {
589         // TRANS: Page title for a page without a title set.
590         return _('Untitled page');
591     }
592
593     public function getError()
594     {
595         return $this->error;
596     }
597
598     /**
599      * Show content.
600      *
601      * MUST overload (unless there's not a notice)
602      *
603      * @return void
604      */
605     protected function showContent()
606     {
607     }
608
609     public function endHTML()
610     {
611         global $_startTime;
612
613         if (isset($_startTime)) {
614             $endTime = microtime(true);
615             $diff = round(($endTime - $_startTime) * 1000);
616             $this->raw("<!-- ${diff}ms -->");
617         }
618
619         parent::endHTML();
620     }
621
622     /**
623      * Show head, a template method.
624      *
625      * @return void
626      */
627     public function showHead()
628     {
629         // XXX: attributes (profile?)
630         $this->elementStart('head');
631         if (Event::handle('StartShowHeadElements', array($this))) {
632             if (Event::handle('StartShowHeadTitle', array($this))) {
633                 $this->showTitle();
634                 Event::handle('EndShowHeadTitle', array($this));
635             }
636             $this->showShortcutIcon();
637             $this->showStylesheets();
638             $this->showOpenSearch();
639             $this->showFeeds();
640             $this->showDescription();
641             $this->extraHead();
642             Event::handle('EndShowHeadElements', array($this));
643         }
644         $this->elementEnd('head');
645     }
646
647     /**
648      * Show title, a template method.
649      *
650      * @return void
651      */
652     public function showTitle()
653     {
654         $this->element(
655             'title',
656             null,
657             // TRANS: Page title. %1$s is the title, %2$s is the site name.
658             sprintf(
659                 _('%1$s - %2$s'),
660                 $this->title(),
661                 common_config('site', 'name')
662             )
663         );
664     }
665
666     /**
667      * Show themed shortcut icon
668      *
669      * @return void
670      */
671     public function showShortcutIcon()
672     {
673         if (is_readable(INSTALLDIR . '/theme/' . common_config('site', 'theme') . '/favicon.ico')) {
674             $this->element('link', array('rel' => 'shortcut icon',
675                 'href' => Theme::path('favicon.ico')));
676         } else {
677             // favicon.ico should be HTTPS if the rest of the page is
678             $this->element('link', array('rel' => 'shortcut icon',
679                 'href' => common_path('favicon.ico', GNUsocial::isHTTPS())));
680         }
681
682         if (common_config('site', 'mobile')) {
683             if (is_readable(INSTALLDIR . '/theme/' . common_config('site', 'theme') . '/apple-touch-icon.png')) {
684                 $this->element('link', array('rel' => 'apple-touch-icon',
685                     'href' => Theme::path('apple-touch-icon.png')));
686             } else {
687                 $this->element('link', array('rel' => 'apple-touch-icon',
688                     'href' => common_path('apple-touch-icon.png')));
689             }
690         }
691     }
692
693     /**
694      * Show stylesheets
695      *
696      * @return void
697      */
698     public function showStylesheets()
699     {
700         if (Event::handle('StartShowStyles', array($this))) {
701
702             // Use old name for StatusNet for compatibility on events
703
704             if (Event::handle('StartShowStylesheets', array($this))) {
705                 $this->primaryCssLink(null, 'screen, projection, tv, print');
706                 Event::handle('EndShowStylesheets', array($this));
707             }
708
709             $this->cssLink('js/extlib/jquery-ui/css/smoothness/jquery-ui.css');
710
711             if (Event::handle('StartShowUAStyles', array($this))) {
712                 Event::handle('EndShowUAStyles', array($this));
713             }
714
715             Event::handle('EndShowStyles', array($this));
716
717             if (common_config('custom_css', 'enabled')) {
718                 $css = common_config('custom_css', 'css');
719                 if (Event::handle('StartShowCustomCss', array($this, &$css))) {
720                     if (trim($css) != '') {
721                         $this->style($css);
722                     }
723                     Event::handle('EndShowCustomCss', array($this));
724                 }
725             }
726         }
727     }
728
729     public function primaryCssLink($mainTheme = null, $media = null)
730     {
731         $theme = new Theme($mainTheme);
732
733         // Some themes may have external stylesheets
734         foreach ($theme->getExternals() as $url) {
735             $this->cssLink($url, $mainTheme, $media);
736         }
737
738         // If the currently-selected theme has dependencies on other themes,
739         // we'll need to load their display.css files as well in order.
740         $baseThemes = $theme->getDeps();
741         foreach ($baseThemes as $baseTheme) {
742             $this->cssLink('css/display.css', $baseTheme, $media);
743         }
744         $this->cssLink('css/display.css', $mainTheme, $media);
745
746         // Additional styles for RTL languages
747         if (is_rtl(common_language())) {
748             if (file_exists(Theme::file('css/rtl.css'))) {
749                 $this->cssLink('css/rtl.css', $mainTheme, $media);
750             }
751         }
752     }
753
754     /**
755      * Show OpenSearch headers
756      *
757      * @return void
758      */
759     public function showOpenSearch()
760     {
761         $this->element('link', array('rel' => 'search',
762             'type' => 'application/opensearchdescription+xml',
763             'href' => common_local_url('opensearch', array('type' => 'people')),
764             'title' => common_config('site', 'name') . ' People Search'));
765         $this->element('link', array('rel' => 'search', 'type' => 'application/opensearchdescription+xml',
766             'href' => common_local_url('opensearch', array('type' => 'notice')),
767             'title' => common_config('site', 'name') . ' Notice Search'));
768     }
769
770     /**
771      * Show feed headers
772      *
773      * MAY overload
774      *
775      * @return void
776      */
777     public function showFeeds()
778     {
779         foreach ($this->getFeeds() as $feed) {
780             $this->element('link', array('rel' => $feed->rel(),
781                 'href' => $feed->url,
782                 'type' => $feed->mimeType(),
783                 'title' => $feed->title));
784         }
785     }
786
787     /**
788      * An array of feeds for this action.
789      *
790      * Returns an array of potential feeds for this action.
791      *
792      * @return array Feed object to show in head and links
793      */
794     public function getFeeds()
795     {
796         return [];
797     }
798
799     /**
800      * Show description.
801      *
802      * SHOULD overload
803      *
804      * @return void
805      */
806     public function showDescription()
807     {
808         // does nothing by default
809     }
810
811     /**
812      * Show extra stuff in <head>.
813      *
814      * MAY overload
815      *
816      * @return void
817      */
818     public function extraHead()
819     {
820         // does nothing by default
821     }
822
823     /**
824      * Show body.
825      *
826      * Calls template methods
827      *
828      * @return void
829      * @throws ServerException
830      * @throws ReflectionException
831      */
832     public function showBody()
833     {
834         $params = array('id' => $this->getActionName());
835         if ($this->scoped instanceof Profile) {
836             $params['class'] = 'user_in';
837         }
838         $this->elementStart('body', $params);
839         $this->elementStart('div', array('id' => 'wrap'));
840         if (Event::handle('StartShowHeader', array($this))) {
841             $this->showHeader();
842             $this->flush();
843             Event::handle('EndShowHeader', array($this));
844         }
845         $this->showCore();
846         $this->flush();
847         if (Event::handle('StartShowFooter', array($this))) {
848             $this->showFooter();
849             $this->flush();
850             Event::handle('EndShowFooter', array($this));
851         }
852         $this->elementEnd('div');
853         $this->showScripts();
854         $this->elementEnd('body');
855     }
856
857     public function getActionName()
858     {
859         return $this->action;
860     }
861
862     /**
863      * Show header of the page.
864      *
865      * Calls template methods
866      *
867      * @return void
868      * @throws ServerException
869      */
870     public function showHeader()
871     {
872         $this->elementStart('div', array('id' => 'header'));
873         $this->showLogo();
874         $this->showPrimaryNav();
875         if (Event::handle('StartShowSiteNotice', array($this))) {
876             $this->showSiteNotice();
877
878             Event::handle('EndShowSiteNotice', array($this));
879         }
880
881         $this->elementEnd('div');
882     }
883
884     /**
885      * Show configured logo.
886      *
887      * @return void
888      * @throws ServerException
889      */
890     public function showLogo()
891     {
892         $this->elementStart('address', array('id' => 'site_contact', 'class' => 'h-card'));
893         if (Event::handle('StartAddressData', array($this))) {
894             if (common_config('singleuser', 'enabled')) {
895                 $user = User::singleUser();
896                 $url = common_local_url(
897                     'showstream',
898                     array('nickname' => $user->nickname)
899                 );
900             } elseif (common_logged_in()) {
901                 $cur = common_current_user();
902                 $url = common_local_url('all', array('nickname' => $cur->nickname));
903             } else {
904                 $url = common_local_url('public');
905             }
906
907             $this->elementStart('a', array('class' => 'home bookmark',
908                 'href' => $url));
909
910             if (GNUsocial::isHTTPS()) {
911                 $logoUrl = common_config('site', 'ssllogo');
912                 if (empty($logoUrl)) {
913                     // if logo is an uploaded file, try to fall back to HTTPS file URL
914                     $httpUrl = common_config('site', 'logo');
915                     if (!empty($httpUrl)) {
916                         try {
917                             $f = File::getByUrl($httpUrl);
918                             if (!empty($f->filename)) {
919                                 // this will handle the HTTPS case
920                                 $logoUrl = File::url($f->filename);
921                             }
922                         } catch (NoResultException $e) {
923                             // no match
924                         }
925                     }
926                 }
927             } else {
928                 $logoUrl = common_config('site', 'logo');
929             }
930
931             if (empty($logoUrl) && file_exists(Theme::file('logo.png'))) {
932                 // This should handle the HTTPS case internally
933                 $logoUrl = Theme::path('logo.png');
934             }
935
936             if (!empty($logoUrl)) {
937                 $this->element('img', array('class' => 'logo u-photo p-name',
938                     'src' => $logoUrl,
939                     'alt' => common_config('site', 'name')));
940             }
941
942             $this->elementEnd('a');
943
944             Event::handle('EndAddressData', array($this));
945         }
946         $this->elementEnd('address');
947     }
948
949     /**
950      * Show primary navigation.
951      *
952      * @return void
953      */
954     public function showPrimaryNav()
955     {
956         $this->elementStart('div', array('id' => 'site_nav_global_primary'));
957
958         $user = common_current_user();
959
960         if (!empty($user) || !common_config('site', 'private')) {
961             $form = new SearchForm($this);
962             $form->show();
963         }
964
965         $pn = new PrimaryNav($this);
966         $pn->show();
967         $this->elementEnd('div');
968     }
969
970     /**
971      * Show site notice.
972      *
973      * @return void
974      */
975     public function showSiteNotice()
976     {
977         // Revist. Should probably do an hAtom pattern here
978         $text = common_config('site', 'notice');
979         if ($text) {
980             $this->elementStart('div', array('id' => 'site_notice',
981                 'class' => 'system_notice'));
982             $this->raw($text);
983             $this->elementEnd('div');
984         }
985     }
986
987     /**
988      * Show core.
989      *
990      * Shows local navigation, content block and aside.
991      *
992      * @return void
993      * @throws ReflectionException
994      */
995     public function showCore()
996     {
997         $this->elementStart('div', array('id' => 'core'));
998         $this->elementStart('div', array('id' => 'aside_primary_wrapper'));
999         $this->elementStart('div', array('id' => 'content_wrapper'));
1000         $this->elementStart('div', array('id' => 'site_nav_local_views_wrapper'));
1001         if (Event::handle('StartShowLocalNavBlock', array($this))) {
1002             $this->showLocalNavBlock();
1003             $this->flush();
1004             Event::handle('EndShowLocalNavBlock', array($this));
1005         }
1006         if (Event::handle('StartShowContentBlock', array($this))) {
1007             $this->showContentBlock();
1008             $this->flush();
1009             Event::handle('EndShowContentBlock', array($this));
1010         }
1011         if (Event::handle('StartShowAside', array($this))) {
1012             $this->showAside();
1013             $this->flush();
1014             Event::handle('EndShowAside', array($this));
1015         }
1016         $this->elementEnd('div');
1017         $this->elementEnd('div');
1018         $this->elementEnd('div');
1019         $this->elementEnd('div');
1020     }
1021
1022     /**
1023      * Show local navigation block.
1024      *
1025      * @return void
1026      */
1027     public function showLocalNavBlock()
1028     {
1029         // Need to have this ID for CSS; I'm too lazy to add it to
1030         // all menus
1031         $this->elementStart('div', array('id' => 'site_nav_local_views'));
1032         // Cheat cheat cheat!
1033         $this->showLocalNav();
1034         $this->elementEnd('div');
1035     }
1036
1037     /**
1038      * Show local navigation.
1039      *
1040      * SHOULD overload
1041      *
1042      * @return void
1043      */
1044     public function showLocalNav()
1045     {
1046         $nav = new DefaultLocalNav($this);
1047         $nav->show();
1048     }
1049
1050     /**
1051      * Show content block.
1052      *
1053      * @return void
1054      * @throws ReflectionException
1055      */
1056     public function showContentBlock()
1057     {
1058         $this->elementStart('div', array('id' => 'content'));
1059         if (common_logged_in()) {
1060             if (Event::handle('StartShowNoticeForm', array($this))) {
1061                 $this->showNoticeForm();
1062                 Event::handle('EndShowNoticeForm', array($this));
1063             }
1064         }
1065         if (Event::handle('StartShowPageTitle', array($this))) {
1066             $this->showPageTitle();
1067             Event::handle('EndShowPageTitle', array($this));
1068         }
1069         $this->showPageNoticeBlock();
1070         $this->elementStart('div', array('id' => 'content_inner'));
1071         // show the actual content (forms, lists, whatever)
1072         $this->showContent();
1073         $this->elementEnd('div');
1074         $this->elementEnd('div');
1075     }
1076
1077     /**
1078      * Show notice form.
1079      *
1080      * MAY overload if no notice form needed... or direct message box????
1081      *
1082      * @return void
1083      */
1084     public function showNoticeForm()
1085     {
1086         // TRANS: Tab on the notice form.
1087         $tabs = array('status' => array('title' => _m('TAB', 'Status'),
1088             'href' => common_local_url('newnotice')));
1089
1090         $this->elementStart('div', 'input_forms');
1091
1092         $this->element('label', array('for' => 'input_form_nav'), _m('TAB', 'Share your:'));
1093
1094         if (Event::handle('StartShowEntryForms', array(&$tabs))) {
1095             $this->elementStart('ul', array('class' => 'nav',
1096                 'id' => 'input_form_nav'));
1097
1098             foreach ($tabs as $tag => $data) {
1099                 $tag = htmlspecialchars($tag);
1100                 $attrs = array('id' => 'input_form_nav_' . $tag,
1101                     'class' => 'input_form_nav_tab');
1102
1103                 if ($tag == 'status') {
1104                     $attrs['class'] .= ' current';
1105                 }
1106                 $this->elementStart('li', $attrs);
1107
1108                 $this->element(
1109                     'a',
1110                     array('onclick' => 'return SN.U.switchInputFormTab("' . $tag . '");',
1111                         'href' => $data['href']),
1112                     $data['title']
1113                 );
1114                 $this->elementEnd('li');
1115             }
1116
1117             $this->elementEnd('ul');
1118
1119             foreach ($tabs as $tag => $data) {
1120                 $attrs = array('class' => 'input_form',
1121                     'id' => 'input_form_' . $tag);
1122                 if ($tag == 'status') {
1123                     $attrs['class'] .= ' current';
1124                 }
1125
1126                 $this->elementStart('div', $attrs);
1127
1128                 $form = null;
1129
1130                 if (Event::handle('StartMakeEntryForm', array($tag, $this, &$form))) {
1131                     if ($tag == 'status') {
1132                         $options = $this->noticeFormOptions();
1133                         $form = new NoticeForm($this, $options);
1134                     }
1135                     Event::handle('EndMakeEntryForm', array($tag, $this, $form));
1136                 }
1137
1138                 if (!empty($form)) {
1139                     $form->show();
1140                 }
1141
1142                 $this->elementEnd('div');
1143             }
1144         }
1145
1146         $this->elementEnd('div');
1147     }
1148
1149     public function noticeFormOptions()
1150     {
1151         return [];
1152     }
1153
1154     /**
1155      * Show page title.
1156      *
1157      * @return void
1158      */
1159     public function showPageTitle()
1160     {
1161         $this->element('h1', null, $this->title());
1162     }
1163
1164     /**
1165      * Show page notice block.
1166      *
1167      * Only show the block if a subclassed action has overrided
1168      * Action::showPageNotice(), or an event handler is registered for
1169      * the StartShowPageNotice event, in which case we assume the
1170      * 'page_notice' definition list is desired.  This is to prevent
1171      * empty 'page_notice' definition lists from being output everywhere.
1172      *
1173      * @return void
1174      * @throws ReflectionException
1175      */
1176     public function showPageNoticeBlock()
1177     {
1178         $rmethod = new ReflectionMethod($this, 'showPageNotice');
1179         $dclass = $rmethod->getDeclaringClass()->getName();
1180
1181         if ($dclass != 'Action' || Event::hasHandler('StartShowPageNotice')) {
1182             $this->elementStart('div', array('id' => 'page_notice',
1183                 'class' => 'system_notice'));
1184             if (Event::handle('StartShowPageNotice', array($this))) {
1185                 $this->showPageNotice();
1186                 Event::handle('EndShowPageNotice', array($this));
1187             }
1188             $this->elementEnd('div');
1189         }
1190     }
1191
1192     /**
1193      * Show page notice.
1194      *
1195      * SHOULD overload (unless there's not a notice)
1196      *
1197      * @return void
1198      */
1199     public function showPageNotice()
1200     {
1201     }
1202
1203     /**
1204      * Show Aside.
1205      *
1206      * @return void
1207      * @throws ReflectionException
1208      */
1209     public function showAside()
1210     {
1211         $this->elementStart('div', array('id' => 'aside_primary',
1212             'class' => 'aside'));
1213         $this->showProfileBlock();
1214         if (Event::handle('StartShowObjectNavBlock', array($this))) {
1215             $this->showObjectNavBlock();
1216             Event::handle('EndShowObjectNavBlock', array($this));
1217         }
1218         if (Event::handle('StartShowSections', array($this))) {
1219             $this->showSections();
1220             Event::handle('EndShowSections', array($this));
1221         }
1222         if (Event::handle('StartShowExportData', array($this))) {
1223             $this->showExportData();
1224             Event::handle('EndShowExportData', array($this));
1225         }
1226         $this->elementEnd('div');
1227     }
1228
1229     /**
1230      * If there's a logged-in user, show a bit of login context
1231      *
1232      * @return void
1233      * @throws Exception
1234      */
1235     public function showProfileBlock()
1236     {
1237         if (common_logged_in()) {
1238             $block = new DefaultProfileBlock($this);
1239             $block->show();
1240         }
1241     }
1242
1243     /**
1244      * Show menu for an object (group, profile)
1245      *
1246      * This block will only show if a subclass has overridden
1247      * the showObjectNav() method.
1248      *
1249      * @return void
1250      * @throws ReflectionException
1251      */
1252     public function showObjectNavBlock()
1253     {
1254         $rmethod = new ReflectionMethod($this, 'showObjectNav');
1255         $dclass = $rmethod->getDeclaringClass()->getName();
1256
1257         if ($dclass != 'Action') {
1258             // Need to have this ID for CSS; I'm too lazy to add it to
1259             // all menus
1260             $this->elementStart('div', array('id' => 'site_nav_object',
1261                 'class' => 'section'));
1262             $this->showObjectNav();
1263             $this->elementEnd('div');
1264         }
1265     }
1266
1267     /**
1268      * Show object navigation.
1269      *
1270      * If there are things to do with this object, show it here.
1271      *
1272      * @return void
1273      */
1274     public function showObjectNav()
1275     {
1276         /* Nothing here. */
1277     }
1278
1279     /**
1280      * Show sections.
1281      *
1282      * SHOULD overload
1283      *
1284      * @return void
1285      */
1286     public function showSections()
1287     {
1288         // for each section, show it
1289     }
1290
1291     /**
1292      * Show export data feeds.
1293      *
1294      * @return void
1295      */
1296     public function showExportData()
1297     {
1298         $feeds = $this->getFeeds();
1299         if (!empty($feeds)) {
1300             $fl = new FeedList($this, $feeds);
1301             $fl->show();
1302         }
1303     }
1304
1305     /**
1306      * Show footer.
1307      *
1308      * @return void
1309      */
1310     public function showFooter()
1311     {
1312         $this->elementStart('div', array('id' => 'footer'));
1313         if (Event::handle('StartShowInsideFooter', array($this))) {
1314             $this->showSecondaryNav();
1315             $this->showLicenses();
1316             Event::handle('EndShowInsideFooter', array($this));
1317         }
1318         $this->elementEnd('div');
1319     }
1320
1321     /**
1322      * Show secondary navigation.
1323      *
1324      * @return void
1325      */
1326     public function showSecondaryNav()
1327     {
1328         $sn = new SecondaryNav($this);
1329         $sn->show();
1330     }
1331
1332     /**
1333      * Show licenses.
1334      *
1335      * @return void
1336      */
1337     public function showLicenses()
1338     {
1339         $this->showGNUsocialLicense();
1340         $this->showContentLicense();
1341     }
1342
1343     /**
1344      * Show GNU social license.
1345      *
1346      * @return void
1347      */
1348     public function showGNUsocialLicense()
1349     {
1350         if (common_config('site', 'broughtby')) {
1351             // TRANS: First sentence of the GNU social site license. Used if 'broughtby' is set.
1352             // TRANS: Text between [] is a link description, text between () is the link itself.
1353             // TRANS: Make sure there is no whitespace between "]" and "(".
1354             // TRANS: "%%site.broughtby%%" is the value of the variable site.broughtby
1355             $instr = _('**%%site.name%%** is a social network, courtesy of [%%site.broughtby%%](%%site.broughtbyurl%%).');
1356         } else {
1357             // TRANS: First sentence of the GNU social site license. Used if 'broughtby' is not set.
1358             $instr = _('**%%site.name%%** is a social network.');
1359         }
1360         $instr .= ' ';
1361         // TRANS: Second sentence of the GNU social site license. Mentions the GNU social source code license.
1362         // TRANS: Make sure there is no whitespace between "]" and "(".
1363         // TRANS: [%1$s](%2$s) is a link description followed by the link itself
1364         // TRANS: %3$s is the version of GNU social that is being used.
1365         $instr .= sprintf(_('It runs on [%1$s](%2$s), version %3$s, available under the [GNU Affero General Public License](http://www.fsf.org/licensing/licenses/agpl-3.0.html).'), GNUSOCIAL_ENGINE, GNUSOCIAL_ENGINE_URL, GNUSOCIAL_VERSION);
1366         $output = common_markup_to_html($instr);
1367         $this->raw($output);
1368         // do it
1369     }
1370
1371     /**
1372      * Show content license.
1373      *
1374      * @return void
1375      */
1376     public function showContentLicense()
1377     {
1378         if (Event::handle('StartShowContentLicense', array($this))) {
1379             switch (common_config('license', 'type')) {
1380                 case 'private':
1381                     // TRANS: Content license displayed when license is set to 'private'.
1382                     // TRANS: %1$s is the site name.
1383                     $this->element('p', null, sprintf(
1384                         _('Content and data of %1$s are private and confidential.'),
1385                         common_config('site', 'name')
1386                     ));
1387                 // fall through
1388                 // no break
1389                 case 'allrightsreserved':
1390                     if (common_config('license', 'owner')) {
1391                         // TRANS: Content license displayed when license is set to 'allrightsreserved'.
1392                         // TRANS: %1$s is the copyright owner.
1393                         $this->element('p', null, sprintf(
1394                             _('Content and data copyright by %1$s. All rights reserved.'),
1395                             common_config('license', 'owner')
1396                         ));
1397                     } else {
1398                         // TRANS: Content license displayed when license is set to 'allrightsreserved' and no owner is set.
1399                         $this->element('p', null, _('Content and data copyright by contributors. All rights reserved.'));
1400                     }
1401                     break;
1402                 case 'cc': // fall through
1403                 default:
1404                     $this->elementStart('p');
1405
1406                     $image = common_config('license', 'image');
1407                     $sslimage = common_config('license', 'sslimage');
1408
1409                     if (GNUsocial::isHTTPS()) {
1410                         if (!empty($sslimage)) {
1411                             $url = $sslimage;
1412                         } elseif (preg_match('#^http://i.creativecommons.org/#', $image)) {
1413                             // CC support HTTPS on their images
1414                             $url = preg_replace('/^http/', 'https', $image, 1);
1415                         } else {
1416                             // Better to show mixed content than no content
1417                             $url = $image;
1418                         }
1419                     } else {
1420                         $url = $image;
1421                     }
1422
1423                     $this->element('img', array('id' => 'license_cc',
1424                         'src' => $url,
1425                         'alt' => common_config('license', 'title'),
1426                         'width' => '80',
1427                         'height' => '15'));
1428                     $this->text(' ');
1429                     // TRANS: license message in footer.
1430                     // TRANS: %1$s is the site name, %2$s is a link to the license URL, with a licence name set in configuration.
1431                     $notice = _('All %1$s content and data are available under the %2$s license.');
1432                     $link = sprintf(
1433                         '<a class="license" rel="external license" href="%1$s">%2$s</a>',
1434                         htmlspecialchars(common_config('license', 'url')),
1435                         htmlspecialchars(common_config('license', 'title'))
1436                     );
1437                     $this->raw(@sprintf(
1438                         htmlspecialchars($notice),
1439                         htmlspecialchars(common_config('site', 'name')),
1440                         $link
1441                     ));
1442                     $this->elementEnd('p');
1443                     break;
1444             }
1445
1446             Event::handle('EndShowContentLicense', array($this));
1447         }
1448     }
1449
1450     /**
1451      * Show javascript headers
1452      *
1453      * @return void
1454      */
1455     public function showScripts()
1456     {
1457         if (Event::handle('StartShowScripts', array($this))) {
1458             if (Event::handle('StartShowJQueryScripts', array($this))) {
1459                 $this->script('extlib/jquery.js');
1460                 $this->script('extlib/jquery.form.js');
1461                 $this->script('extlib/jquery-ui/jquery-ui.js');
1462                 $this->script('extlib/jquery.cookie.js');
1463
1464                 Event::handle('EndShowJQueryScripts', array($this));
1465             }
1466             if (Event::handle('StartShowStatusNetScripts', array($this))) {
1467                 $this->script('util.js');
1468                 $this->script('xbImportNode.js');
1469
1470                 // This route isn't available in single-user mode.
1471                 // Not sure why, but it causes errors here.
1472                 $this->inlineScript('var _peopletagAC = "' .
1473                     common_local_url('peopletagautocomplete') . '";');
1474                 $this->showScriptMessages();
1475                 $this->showScriptVariables();
1476                 // Anti-framing code to avoid clickjacking attacks in older browsers.
1477                 // This will show a blank page if the page is being framed, which is
1478                 // consistent with the behavior of the 'X-Frame-Options: SAMEORIGIN'
1479                 // header, which prevents framing in newer browser.
1480                 if (common_config('javascript', 'bustframes')) {
1481                     $this->inlineScript('if (window.top !== window.self) { document.write = ""; window.top.location = window.self.location; setTimeout(function () { document.body.innerHTML = ""; }, 1); window.self.onload = function () { document.body.innerHTML = ""; }; }');
1482                 }
1483                 Event::handle('EndShowStatusNetScripts', array($this));
1484             }
1485             Event::handle('EndShowScripts', array($this));
1486         }
1487     }
1488
1489     /**
1490      * Exports a map of localized text strings to JavaScript code.
1491      *
1492      * Plugins can add to what's exported by hooking the StartScriptMessages or EndScriptMessages
1493      * events and appending to the array. Try to avoid adding strings that won't be used, as
1494      * they'll be added to HTML output.
1495      */
1496     public function showScriptMessages()
1497     {
1498         $messages = [];
1499
1500         if (Event::handle('StartScriptMessages', array($this, &$messages))) {
1501             // Common messages needed for timeline views etc...
1502
1503             // TRANS: Localized tooltip for '...' expansion button on overlong remote messages.
1504             $messages['showmore_tooltip'] = _m('TOOLTIP', 'Show more');
1505             $messages['popup_close_button'] = _m('TOOLTIP', 'Close popup');
1506
1507             $messages = array_merge($messages, $this->getScriptMessages());
1508
1509             Event::handle('EndScriptMessages', array($this, &$messages));
1510         }
1511
1512         if (!empty($messages)) {
1513             $this->inlineScript('SN.messages=' . json_encode($messages));
1514         }
1515
1516         return $messages;
1517     }
1518
1519     /**
1520      * If the action will need localizable text strings, export them here like so:
1521      *
1522      * return array('pool_deepend' => _('Deep end'),
1523      *              'pool_shallow' => _('Shallow end'));
1524      *
1525      * The exported map will be available via SN.msg() to JS code:
1526      *
1527      *   $('#pool').html('<div class="deepend"></div><div class="shallow"></div>');
1528      *   $('#pool .deepend').text(SN.msg('pool_deepend'));
1529      *   $('#pool .shallow').text(SN.msg('pool_shallow'));
1530      *
1531      * Exports a map of localized text strings to JavaScript code.
1532      *
1533      * Plugins can add to what's exported on any action by hooking the StartScriptMessages or
1534      * EndScriptMessages events and appending to the array. Try to avoid adding strings that won't
1535      * be used, as they'll be added to HTML output.
1536      */
1537     public function getScriptMessages()
1538     {
1539         return [];
1540     }
1541
1542     protected function showScriptVariables()
1543     {
1544         $vars = [];
1545
1546         if (Event::handle('StartScriptVariables', array($this, &$vars))) {
1547             $vars['urlNewNotice'] = common_local_url('newnotice');
1548             $vars['xhrTimeout'] = ini_get('max_execution_time') * 1000;   // milliseconds
1549             Event::handle('EndScriptVariables', array($this, &$vars));
1550         }
1551
1552         $this->inlineScript('SN.V = ' . json_encode($vars) . ';');
1553
1554         return $vars;
1555     }
1556
1557     /**
1558      * Show anonymous message.
1559      *
1560      * SHOULD overload
1561      *
1562      * @return void
1563      */
1564     public function showAnonymousMessage()
1565     {
1566         // needs to be defined by the class
1567     }
1568
1569     /**
1570      * This is a cheap hack to avoid a bug in DB_DataObject
1571      * where '' is non-type-aware compared to 0, which means it
1572      * will always be true for values like false and 0 too...
1573      *
1574      * Upstream bug is::
1575      * https://pear.php.net/bugs/bug.php?id=20291
1576      */
1577     public function booleanintstring($key, $def = false)
1578     {
1579         return $this->boolean($key, $def) ? '1' : '0';
1580     }
1581
1582     /**
1583      * Integer value of an argument
1584      *
1585      * @param string $key query key we're interested in
1586      * @param string $defValue optional default value (default null)
1587      * @param string $maxValue optional max value (default null)
1588      * @param string $minValue optional min value (default null)
1589      *
1590      * @return integer integer value
1591      */
1592     public function int($key, $defValue = null, $maxValue = null, $minValue = null)
1593     {
1594         $arg = intval($this->arg($key));
1595
1596         if (!is_numeric($this->arg($key)) || $arg != $this->arg($key)) {
1597             return $defValue;
1598         }
1599
1600         if (!is_null($maxValue)) {
1601             $arg = min($arg, $maxValue);
1602         }
1603
1604         if (!is_null($minValue)) {
1605             $arg = max($arg, $minValue);
1606         }
1607
1608         return $arg;
1609     }
1610
1611     /**
1612      * Returns the current URL
1613      *
1614      * @return string current URL
1615      */
1616     public function selfUrl()
1617     {
1618         list($action, $args) = $this->returnToArgs();
1619         return common_local_url($action, $args);
1620     }
1621
1622     /**
1623      * Generate pagination links
1624      *
1625      * @param boolean $have_before is there something before?
1626      * @param boolean $have_after is there something after?
1627      * @param integer $page current page
1628      * @param string $action current action
1629      * @param array $args rest of query arguments
1630      *
1631      * @return void
1632      */
1633     // XXX: The messages in this pagination method only tailor to navigating
1634     //      notices. In other lists, "Previous"/"Next" type navigation is
1635     //      desirable, but not available.
1636     /**
1637      * Returns arguments sufficient for re-constructing URL
1638      *
1639      * @return array two elements: action, other args
1640      */
1641     public function returnToArgs()
1642     {
1643         $action = $this->getActionName();
1644         $args = $this->args;
1645         unset($args['action']);
1646         if (common_config('site', 'fancy')) {
1647             unset($args['p']);
1648         }
1649         if (array_key_exists('submit', $args)) {
1650             unset($args['submit']);
1651         }
1652         foreach (array_keys($_COOKIE) as $cookie) {
1653             unset($args[$cookie]);
1654         }
1655         return array($action, $args);
1656     }
1657
1658     /**
1659      * Generate a menu item
1660      *
1661      * @param string $url menu URL
1662      * @param string $text menu name
1663      * @param string $title title attribute, null by default
1664      * @param boolean $is_selected current menu item, false by default
1665      * @param string $id element id, null by default
1666      *
1667      * @return void
1668      */
1669     public function menuItem($url, $text, $title = null, $is_selected = false, $id = null, $class = null)
1670     {
1671         // Added @id to li for some control.
1672         // XXX: We might want to move this to htmloutputter.php
1673         $lattrs = [];
1674         $classes = [];
1675         if ($class !== null) {
1676             $classes[] = trim($class);
1677         }
1678         if ($is_selected) {
1679             $classes[] = 'current';
1680         }
1681
1682         if (!empty($classes)) {
1683             $lattrs['class'] = implode(' ', $classes);
1684         }
1685
1686         if (!is_null($id)) {
1687             $lattrs['id'] = $id;
1688         }
1689
1690         $this->elementStart('li', $lattrs);
1691         $attrs['href'] = $url;
1692         if ($title) {
1693             $attrs['title'] = $title;
1694         }
1695         $this->element('a', $attrs, $text);
1696         $this->elementEnd('li');
1697     }
1698
1699     /**
1700      * Check the session token.
1701      *
1702      * Checks that the current form has the correct session token,
1703      * and throw an exception if it does not.
1704      *
1705      * @return void
1706      */
1707     // XXX: Finding this type of check with the same message about 50 times.
1708     //      Possible to refactor?
1709
1710     public function pagination($have_before, $have_after, $page, $action, $args = null)
1711     {
1712         // Does a little before-after block for next/prev page
1713         if ($have_before || $have_after) {
1714             $this->elementStart('ul', array('class' => 'nav',
1715                 'id' => 'pagination'));
1716         }
1717         if ($have_before) {
1718             $pargs = array('page' => $page - 1);
1719             $this->elementStart('li', array('class' => 'nav_prev'));
1720             $this->element(
1721                 'a',
1722                 array('href' => common_local_url($action, $args, $pargs),
1723                     'rel' => 'prev'),
1724                 // TRANS: Pagination message to go to a page displaying information more in the
1725                 // TRANS: present than the currently displayed information.
1726                 _('After')
1727             );
1728             $this->elementEnd('li');
1729         }
1730         if ($have_after) {
1731             $pargs = array('page' => $page + 1);
1732             $this->elementStart('li', array('class' => 'nav_next'));
1733             $this->element(
1734                 'a',
1735                 array('href' => common_local_url($action, $args, $pargs),
1736                     'rel' => 'next'),
1737                 // TRANS: Pagination message to go to a page displaying information more in the
1738                 // TRANS: past than the currently displayed information.
1739                 _('Before')
1740             );
1741             $this->elementEnd('li');
1742         }
1743         if ($have_before || $have_after) {
1744             $this->elementEnd('ul');
1745         }
1746     }
1747
1748
1749     public function checkSessionToken()
1750     {
1751         // CSRF protection
1752         $token = $this->trimmed('token');
1753         if (empty($token) || $token != common_session_token()) {
1754             // TRANS: Client error text when there is a problem with the session token.
1755             $this->clientError(_('There was a problem with your session token.'));
1756         }
1757     }
1758 }