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