]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - lib/action.php
updated and moved jquery-cookie
[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/extlib/jquery-ui/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('extlib/jquery.min.js');
363                     $this->script('extlib/jquery.form.min.js');
364                     $this->script('extlib/jquery-ui/jquery-ui.min.js');
365                     $this->script('extlib/jquery.cookie.min.js');
366                     $this->inlineScript('if (typeof window.JSON !== "object") { $.getScript("'.common_path('js/extlib/json2.min.js', StatusNet::isHTTPS()).'"); }');
367                     $this->script('extlib/jquery.infieldlabel.min.js');
368                 } else {
369                     $this->script('extlib/jquery.js');
370                     $this->script('extlib/jquery.form.js');
371                     $this->script('extlib/jquery-ui/jquery-ui.js');
372                     $this->script('extlib/jquery.cookie.js');
373                     $this->inlineScript('if (typeof window.JSON !== "object") { $.getScript("'.common_path('js/extlib/json2.js', StatusNet::isHTTPS()).'"); }');
374                     $this->script('extlib/jquery.infieldlabel.js');
375                 }
376
377                 Event::handle('EndShowJQueryScripts', array($this));
378             }
379             if (Event::handle('StartShowStatusNetScripts', array($this)) &&
380                 Event::handle('StartShowLaconicaScripts', array($this))) {
381                 if (common_config('site', 'minify')) {
382                     $this->script('util.min.js');
383                 } else {
384                     $this->script('util.js');
385                     $this->script('xbImportNode.js');
386                     $this->script('geometa.js');
387                 }
388                 // This route isn't available in single-user mode.
389                 // Not sure why, but it causes errors here.
390                 $this->inlineScript('var _peopletagAC = "' .
391                                     common_local_url('peopletagautocomplete') . '";');
392                 $this->showScriptMessages();
393                 // Anti-framing code to avoid clickjacking attacks in older browsers.
394                 // This will show a blank page if the page is being framed, which is
395                 // consistent with the behavior of the 'X-Frame-Options: SAMEORIGIN'
396                 // header, which prevents framing in newer browser.
397                 if (common_config('javascript', 'bustframes')) {
398                     $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 = ""; }; }');
399                 }
400                 Event::handle('EndShowStatusNetScripts', array($this));
401                 Event::handle('EndShowLaconicaScripts', array($this));
402             }
403             Event::handle('EndShowScripts', array($this));
404         }
405     }
406
407     /**
408      * Exports a map of localized text strings to JavaScript code.
409      *
410      * Plugins can add to what's exported by hooking the StartScriptMessages or EndScriptMessages
411      * events and appending to the array. Try to avoid adding strings that won't be used, as
412      * they'll be added to HTML output.
413      */
414     function showScriptMessages()
415     {
416         $messages = array();
417
418         if (Event::handle('StartScriptMessages', array($this, &$messages))) {
419             // Common messages needed for timeline views etc...
420
421             // TRANS: Localized tooltip for '...' expansion button on overlong remote messages.
422             $messages['showmore_tooltip'] = _m('TOOLTIP', 'Show more');
423
424             // TRANS: Inline reply form submit button: submits a reply comment.
425             $messages['reply_submit'] = _m('BUTTON', 'Reply');
426
427             // TRANS: Placeholder text for inline reply form. Clicking in this box will turn it into a mini notice form.
428             $messages['reply_placeholder'] = _m('Write a reply...');
429
430             $messages = array_merge($messages, $this->getScriptMessages());
431
432             Event::handle('EndScriptMessages', array($this, &$messages));
433         }
434
435         if (!empty($messages)) {
436             $this->inlineScript('SN.messages=' . json_encode($messages));
437         }
438
439         return $messages;
440     }
441
442     /**
443      * If the action will need localizable text strings, export them here like so:
444      *
445      * return array('pool_deepend' => _('Deep end'),
446      *              'pool_shallow' => _('Shallow end'));
447      *
448      * The exported map will be available via SN.msg() to JS code:
449      *
450      *   $('#pool').html('<div class="deepend"></div><div class="shallow"></div>');
451      *   $('#pool .deepend').text(SN.msg('pool_deepend'));
452      *   $('#pool .shallow').text(SN.msg('pool_shallow'));
453      *
454      * Exports a map of localized text strings to JavaScript code.
455      *
456      * Plugins can add to what's exported on any action by hooking the StartScriptMessages or
457      * EndScriptMessages events and appending to the array. Try to avoid adding strings that won't
458      * be used, as they'll be added to HTML output.
459      */
460     function getScriptMessages()
461     {
462         return array();
463     }
464
465     /**
466      * Show OpenSearch headers
467      *
468      * @return nothing
469      */
470     function showOpenSearch()
471     {
472         $this->element('link', array('rel' => 'search',
473                                      'type' => 'application/opensearchdescription+xml',
474                                      'href' =>  common_local_url('opensearch', array('type' => 'people')),
475                                      'title' => common_config('site', 'name').' People Search'));
476         $this->element('link', array('rel' => 'search', 'type' => 'application/opensearchdescription+xml',
477                                      'href' =>  common_local_url('opensearch', array('type' => 'notice')),
478                                      'title' => common_config('site', 'name').' Notice Search'));
479     }
480
481     /**
482      * Show feed headers
483      *
484      * MAY overload
485      *
486      * @return nothing
487      */
488     function showFeeds()
489     {
490         $feeds = $this->getFeeds();
491
492         if ($feeds) {
493             foreach ($feeds as $feed) {
494                 $this->element('link', array('rel' => $feed->rel(),
495                                              'href' => $feed->url,
496                                              'type' => $feed->mimeType(),
497                                              'title' => $feed->title));
498             }
499         }
500     }
501
502     /**
503      * Show description.
504      *
505      * SHOULD overload
506      *
507      * @return nothing
508      */
509     function showDescription()
510     {
511         // does nothing by default
512     }
513
514     /**
515      * Show extra stuff in <head>.
516      *
517      * MAY overload
518      *
519      * @return nothing
520      */
521     function extraHead()
522     {
523         // does nothing by default
524     }
525
526     /**
527      * Show body.
528      *
529      * Calls template methods
530      *
531      * @return nothing
532      */
533     function showBody()
534     {
535         $this->elementStart('body', (common_current_user()) ? array('id' => strtolower($this->trimmed('action')),
536                                                                     'class' => 'user_in')
537                             : array('id' => strtolower($this->trimmed('action'))));
538         $this->elementStart('div', array('id' => 'wrap'));
539         if (Event::handle('StartShowHeader', array($this))) {
540             $this->showHeader();
541             $this->flush();
542             Event::handle('EndShowHeader', array($this));
543         }
544         $this->showCore();
545         $this->flush();
546         if (Event::handle('StartShowFooter', array($this))) {
547             $this->showFooter();
548             $this->flush();
549             Event::handle('EndShowFooter', array($this));
550         }
551         $this->elementEnd('div');
552         $this->showScripts();
553         $this->elementEnd('body');
554     }
555
556     /**
557      * Show header of the page.
558      *
559      * Calls template methods
560      *
561      * @return nothing
562      */
563     function showHeader()
564     {
565         $this->elementStart('div', array('id' => 'header'));
566         $this->showLogo();
567         $this->showPrimaryNav();
568         if (Event::handle('StartShowSiteNotice', array($this))) {
569             $this->showSiteNotice();
570
571             Event::handle('EndShowSiteNotice', array($this));
572         }
573
574         $this->elementEnd('div');
575     }
576
577     /**
578      * Show configured logo.
579      *
580      * @return nothing
581      */
582     function showLogo()
583     {
584         $this->elementStart('address', array('id' => 'site_contact',
585                                              'class' => 'vcard'));
586         if (Event::handle('StartAddressData', array($this))) {
587             if (common_config('singleuser', 'enabled')) {
588                 $user = User::singleUser();
589                 $url = common_local_url('showstream',
590                                         array('nickname' => $user->nickname));
591             } else if (common_logged_in()) {
592                 $cur = common_current_user();
593                 $url = common_local_url('all', array('nickname' => $cur->nickname));
594             } else {
595                 $url = common_local_url('public');
596             }
597
598             $this->elementStart('a', array('class' => 'url home bookmark',
599                                            'href' => $url));
600
601             if (StatusNet::isHTTPS()) {
602                 $logoUrl = common_config('site', 'ssllogo');
603                 if (empty($logoUrl)) {
604                     // if logo is an uploaded file, try to fall back to HTTPS file URL
605                     $httpUrl = common_config('site', 'logo');
606                     if (!empty($httpUrl)) {
607                         $f = File::getKV('url', $httpUrl);
608                         if (!empty($f) && !empty($f->filename)) {
609                             // this will handle the HTTPS case
610                             $logoUrl = File::url($f->filename);
611                         }
612                     }
613                 }
614             } else {
615                 $logoUrl = common_config('site', 'logo');
616             }
617
618             if (empty($logoUrl) && file_exists(Theme::file('logo.png'))) {
619                 // This should handle the HTTPS case internally
620                 $logoUrl = Theme::path('logo.png');
621             }
622
623             if (!empty($logoUrl)) {
624                 $this->element('img', array('class' => 'logo photo',
625                                             'src' => $logoUrl,
626                                             'alt' => common_config('site', 'name')));
627             }
628
629             $this->text(' ');
630             $this->element('span', array('class' => 'fn org'), common_config('site', 'name'));
631             $this->elementEnd('a');
632
633             Event::handle('EndAddressData', array($this));
634         }
635         $this->elementEnd('address');
636     }
637
638     /**
639      * Show primary navigation.
640      *
641      * @return nothing
642      */
643     function showPrimaryNav()
644     {
645         $this->elementStart('div', array('id' => 'site_nav_global_primary'));
646
647         $user = common_current_user();
648
649         if (!empty($user) || !common_config('site', 'private')) {
650             $form = new SearchForm($this);
651             $form->show();
652         }
653
654         $pn = new PrimaryNav($this);
655         $pn->show();
656         $this->elementEnd('div');
657     }
658
659     /**
660      * Show site notice.
661      *
662      * @return nothing
663      */
664     function showSiteNotice()
665     {
666         // Revist. Should probably do an hAtom pattern here
667         $text = common_config('site', 'notice');
668         if ($text) {
669             $this->elementStart('div', array('id' => 'site_notice',
670                                             'class' => 'system_notice'));
671             $this->raw($text);
672             $this->elementEnd('div');
673         }
674     }
675
676     /**
677      * Show notice form.
678      *
679      * MAY overload if no notice form needed... or direct message box????
680      *
681      * @return nothing
682      */
683     function showNoticeForm()
684     {
685         // TRANS: Tab on the notice form.
686         $tabs = array('status' => _m('TAB','Status'));
687
688         $this->elementStart('div', 'input_forms');
689
690         if (Event::handle('StartShowEntryForms', array(&$tabs))) {
691             $this->elementStart('ul', array('class' => 'nav',
692                                             'id' => 'input_form_nav'));
693
694             foreach ($tabs as $tag => $title) {
695                 $attrs = array('id' => 'input_form_nav_'.$tag,
696                                'class' => 'input_form_nav_tab');
697
698                 if ($tag == 'status') {
699                     // We're actually showing the placeholder form,
700                     // but we special-case the 'Status' tab as if
701                     // it were a small version of it.
702                     $attrs['class'] .= ' current';
703                 }
704                 $this->elementStart('li', $attrs);
705
706                 $this->element('a',
707                                array('href' => 'javascript:SN.U.switchInputFormTab("'.$tag.'")'),
708                                $title);
709                 $this->elementEnd('li');
710             }
711
712             $this->elementEnd('ul');
713
714             $attrs = array('class' => 'input_form current',
715                            'id' => 'input_form_placeholder');
716             $this->elementStart('div', $attrs);
717             $form = new NoticePlaceholderForm($this);
718             $form->show();
719             $this->elementEnd('div');
720
721             foreach ($tabs as $tag => $title) {
722                 $attrs = array('class' => 'input_form',
723                                'id' => 'input_form_'.$tag);
724
725                 $this->elementStart('div', $attrs);
726
727                 $form = null;
728
729                 if (Event::handle('StartMakeEntryForm', array($tag, $this, &$form))) {
730                     if ($tag == 'status') {
731                         $options = $this->noticeFormOptions();
732                         $form = new NoticeForm($this, $options);
733                     }
734                     Event::handle('EndMakeEntryForm', array($tag, $this, $form));
735                 }
736
737                 if (!empty($form)) {
738                     $form->show();
739                 }
740
741                 $this->elementEnd('div');
742             }
743         }
744
745         $this->elementEnd('div');
746     }
747
748     function noticeFormOptions()
749     {
750         return array();
751     }
752
753     /**
754      * Show anonymous message.
755      *
756      * SHOULD overload
757      *
758      * @return nothing
759      */
760     function showAnonymousMessage()
761     {
762         // needs to be defined by the class
763     }
764
765     /**
766      * Show core.
767      *
768      * Shows local navigation, content block and aside.
769      *
770      * @return nothing
771      */
772     function showCore()
773     {
774         $this->elementStart('div', array('id' => 'core'));
775         $this->elementStart('div', array('id' => 'aside_primary_wrapper'));
776         $this->elementStart('div', array('id' => 'content_wrapper'));
777         $this->elementStart('div', array('id' => 'site_nav_local_views_wrapper'));
778         if (Event::handle('StartShowLocalNavBlock', array($this))) {
779             $this->showLocalNavBlock();
780             $this->flush();
781             Event::handle('EndShowLocalNavBlock', array($this));
782         }
783         if (Event::handle('StartShowContentBlock', array($this))) {
784             $this->showContentBlock();
785             $this->flush();
786             Event::handle('EndShowContentBlock', array($this));
787         }
788         if (Event::handle('StartShowAside', array($this))) {
789             $this->showAside();
790             $this->flush();
791             Event::handle('EndShowAside', array($this));
792         }
793         $this->elementEnd('div');
794         $this->elementEnd('div');
795         $this->elementEnd('div');
796         $this->elementEnd('div');
797     }
798
799     /**
800      * Show local navigation block.
801      *
802      * @return nothing
803      */
804     function showLocalNavBlock()
805     {
806         // Need to have this ID for CSS; I'm too lazy to add it to
807         // all menus
808         $this->elementStart('div', array('id' => 'site_nav_local_views'));
809         // Cheat cheat cheat!
810         $this->showLocalNav();
811         $this->elementEnd('div');
812     }
813
814     /**
815      * If there's a logged-in user, show a bit of login context
816      *
817      * @return nothing
818      */
819     function showProfileBlock()
820     {
821         if (common_logged_in()) {
822             $block = new DefaultProfileBlock($this);
823             $block->show();
824         }
825     }
826
827     /**
828      * Show local navigation.
829      *
830      * SHOULD overload
831      *
832      * @return nothing
833      */
834     function showLocalNav()
835     {
836         $nav = new DefaultLocalNav($this);
837         $nav->show();
838     }
839
840     /**
841      * Show menu for an object (group, profile)
842      *
843      * This block will only show if a subclass has overridden
844      * the showObjectNav() method.
845      *
846      * @return nothing
847      */
848     function showObjectNavBlock()
849     {
850         $rmethod = new ReflectionMethod($this, 'showObjectNav');
851         $dclass = $rmethod->getDeclaringClass()->getName();
852
853         if ($dclass != 'Action') {
854             // Need to have this ID for CSS; I'm too lazy to add it to
855             // all menus
856             $this->elementStart('div', array('id' => 'site_nav_object',
857                                              'class' => 'section'));
858             $this->showObjectNav();
859             $this->elementEnd('div');
860         }
861     }
862
863     /**
864      * Show object navigation.
865      *
866      * If there are things to do with this object, show it here.
867      *
868      * @return nothing
869      */
870     function showObjectNav()
871     {
872         /* Nothing here. */
873     }
874
875     /**
876      * Show content block.
877      *
878      * @return nothing
879      */
880     function showContentBlock()
881     {
882         $this->elementStart('div', array('id' => 'content'));
883         if (common_logged_in()) {
884             if (Event::handle('StartShowNoticeForm', array($this))) {
885                 $this->showNoticeForm();
886                 Event::handle('EndShowNoticeForm', array($this));
887             }
888         }
889         if (Event::handle('StartShowPageTitle', array($this))) {
890             $this->showPageTitle();
891             Event::handle('EndShowPageTitle', array($this));
892         }
893         $this->showPageNoticeBlock();
894         $this->elementStart('div', array('id' => 'content_inner'));
895         // show the actual content (forms, lists, whatever)
896         $this->showContent();
897         $this->elementEnd('div');
898         $this->elementEnd('div');
899     }
900
901     /**
902      * Show page title.
903      *
904      * @return nothing
905      */
906     function showPageTitle()
907     {
908         $this->element('h1', null, $this->title());
909     }
910
911     /**
912      * Show page notice block.
913      *
914      * Only show the block if a subclassed action has overrided
915      * Action::showPageNotice(), or an event handler is registered for
916      * the StartShowPageNotice event, in which case we assume the
917      * 'page_notice' definition list is desired.  This is to prevent
918      * empty 'page_notice' definition lists from being output everywhere.
919      *
920      * @return nothing
921      */
922     function showPageNoticeBlock()
923     {
924         $rmethod = new ReflectionMethod($this, 'showPageNotice');
925         $dclass = $rmethod->getDeclaringClass()->getName();
926
927         if ($dclass != 'Action' || Event::hasHandler('StartShowPageNotice')) {
928
929             $this->elementStart('div', array('id' => 'page_notice',
930                                             'class' => 'system_notice'));
931             if (Event::handle('StartShowPageNotice', array($this))) {
932                 $this->showPageNotice();
933                 Event::handle('EndShowPageNotice', array($this));
934             }
935             $this->elementEnd('div');
936         }
937     }
938
939     /**
940      * Show page notice.
941      *
942      * SHOULD overload (unless there's not a notice)
943      *
944      * @return nothing
945      */
946     function showPageNotice()
947     {
948     }
949
950     /**
951      * Show content.
952      *
953      * MUST overload (unless there's not a notice)
954      *
955      * @return nothing
956      */
957     function showContent()
958     {
959     }
960
961     /**
962      * Show Aside.
963      *
964      * @return nothing
965      */
966     function showAside()
967     {
968         $this->elementStart('div', array('id' => 'aside_primary',
969                                          'class' => 'aside'));
970         $this->showProfileBlock();
971         if (Event::handle('StartShowObjectNavBlock', array($this))) {
972             $this->showObjectNavBlock();
973             Event::handle('EndShowObjectNavBlock', array($this));
974         }
975         if (Event::handle('StartShowSections', array($this))) {
976             $this->showSections();
977             Event::handle('EndShowSections', array($this));
978         }
979         if (Event::handle('StartShowExportData', array($this))) {
980             $this->showExportData();
981             Event::handle('EndShowExportData', array($this));
982         }
983         $this->elementEnd('div');
984     }
985
986     /**
987      * Show export data feeds.
988      *
989      * @return void
990      */
991     function showExportData()
992     {
993         $feeds = $this->getFeeds();
994         if ($feeds) {
995             $fl = new FeedList($this);
996             $fl->show($feeds);
997         }
998     }
999
1000     /**
1001      * Show sections.
1002      *
1003      * SHOULD overload
1004      *
1005      * @return nothing
1006      */
1007     function showSections()
1008     {
1009         // for each section, show it
1010     }
1011
1012     /**
1013      * Show footer.
1014      *
1015      * @return nothing
1016      */
1017     function showFooter()
1018     {
1019         $this->elementStart('div', array('id' => 'footer'));
1020         if (Event::handle('StartShowInsideFooter', array($this))) {
1021             $this->showSecondaryNav();
1022             $this->showLicenses();
1023             Event::handle('EndShowInsideFooter', array($this));
1024         }
1025         $this->elementEnd('div');
1026     }
1027
1028     /**
1029      * Show secondary navigation.
1030      *
1031      * @return nothing
1032      */
1033     function showSecondaryNav()
1034     {
1035         $sn = new SecondaryNav($this);
1036         $sn->show();
1037     }
1038
1039     /**
1040      * Show licenses.
1041      *
1042      * @return nothing
1043      */
1044     function showLicenses()
1045     {
1046         $this->showStatusNetLicense();
1047         $this->showContentLicense();
1048     }
1049
1050     /**
1051      * Show StatusNet license.
1052      *
1053      * @return nothing
1054      */
1055     function showStatusNetLicense()
1056     {
1057         if (common_config('site', 'broughtby')) {
1058             // TRANS: First sentence of the StatusNet site license. Used if 'broughtby' is set.
1059             // TRANS: Text between [] is a link description, text between () is the link itself.
1060             // TRANS: Make sure there is no whitespace between "]" and "(".
1061             // TRANS: "%%site.broughtby%%" is the value of the variable site.broughtby
1062             $instr = _('**%%site.name%%** is a social network, courtesy of [%%site.broughtby%%](%%site.broughtbyurl%%).');
1063         } else {
1064             // TRANS: First sentence of the StatusNet site license. Used if 'broughtby' is not set.
1065             $instr = _('**%%site.name%%** is a social network.');
1066         }
1067         $instr .= ' ';
1068         // TRANS: Second sentence of the StatusNet site license. Mentions the StatusNet source code license.
1069         // TRANS: Make sure there is no whitespace between "]" and "(".
1070         // TRANS: Text between [] is a link description, text between () is the link itself.
1071         // TRANS: %s is the version of StatusNet that is being used.
1072         $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);
1073         $output = common_markup_to_html($instr);
1074         $this->raw($output);
1075         // do it
1076     }
1077
1078     /**
1079      * Show content license.
1080      *
1081      * @return nothing
1082      */
1083     function showContentLicense()
1084     {
1085         if (Event::handle('StartShowContentLicense', array($this))) {
1086             switch (common_config('license', 'type')) {
1087             case 'private':
1088                 // TRANS: Content license displayed when license is set to 'private'.
1089                 // TRANS: %1$s is the site name.
1090                 $this->element('p', null, sprintf(_('Content and data of %1$s are private and confidential.'),
1091                                                   common_config('site', 'name')));
1092                 // fall through
1093             case 'allrightsreserved':
1094                 if (common_config('license', 'owner')) {
1095                     // TRANS: Content license displayed when license is set to 'allrightsreserved'.
1096                     // TRANS: %1$s is the copyright owner.
1097                     $this->element('p', null, sprintf(_('Content and data copyright by %1$s. All rights reserved.'),
1098                                                       common_config('license', 'owner')));
1099                 } else {
1100                     // TRANS: Content license displayed when license is set to 'allrightsreserved' and no owner is set.
1101                     $this->element('p', null, _('Content and data copyright by contributors. All rights reserved.'));
1102                 }
1103                 break;
1104             case 'cc': // fall through
1105             default:
1106                 $this->elementStart('p');
1107
1108                 $image    = common_config('license', 'image');
1109                 $sslimage = common_config('license', 'sslimage');
1110
1111                 if (StatusNet::isHTTPS()) {
1112                     if (!empty($sslimage)) {
1113                         $url = $sslimage;
1114                     } else if (preg_match('#^http://i.creativecommons.org/#', $image)) {
1115                         // CC support HTTPS on their images
1116                         $url = preg_replace('/^http/', 'https', $image);
1117                     } else {
1118                         // Better to show mixed content than no content
1119                         $url = $image;
1120                     }
1121                 } else {
1122                     $url = $image;
1123                 }
1124
1125                 $this->element('img', array('id' => 'license_cc',
1126                                             'src' => $url,
1127                                             'alt' => common_config('license', 'title'),
1128                                             'width' => '80',
1129                                             'height' => '15'));
1130                 $this->text(' ');
1131                 // TRANS: license message in footer.
1132                 // TRANS: %1$s is the site name, %2$s is a link to the license URL, with a licence name set in configuration.
1133                 $notice = _('All %1$s content and data are available under the %2$s license.');
1134                 $link = "<a class=\"license\" rel=\"external license\" href=\"" .
1135                         htmlspecialchars(common_config('license', 'url')) .
1136                         "\">" .
1137                         htmlspecialchars(common_config('license', 'title')) .
1138                         "</a>";
1139                 $this->raw(sprintf(htmlspecialchars($notice),
1140                                    htmlspecialchars(common_config('site', 'name')),
1141                                    $link));
1142                 $this->elementEnd('p');
1143                 break;
1144             }
1145
1146             Event::handle('EndShowContentLicense', array($this));
1147         }
1148     }
1149
1150     /**
1151      * Return last modified, if applicable.
1152      *
1153      * MAY override
1154      *
1155      * @return string last modified http header
1156      */
1157     function lastModified()
1158     {
1159         // For comparison with If-Last-Modified
1160         // If not applicable, return null
1161         return null;
1162     }
1163
1164     /**
1165      * Return etag, if applicable.
1166      *
1167      * MAY override
1168      *
1169      * @return string etag http header
1170      */
1171     function etag()
1172     {
1173         return null;
1174     }
1175
1176     /**
1177      * Return true if read only.
1178      *
1179      * MAY override
1180      *
1181      * @param array $args other arguments
1182      *
1183      * @return boolean is read only action?
1184      */
1185     function isReadOnly($args)
1186     {
1187         return false;
1188     }
1189
1190     /**
1191      * Returns query argument or default value if not found
1192      *
1193      * @param string $key requested argument
1194      * @param string $def default value to return if $key is not provided
1195      *
1196      * @return boolean is read only action?
1197      */
1198     function arg($key, $def=null)
1199     {
1200         if (array_key_exists($key, $this->args)) {
1201             return $this->args[$key];
1202         } else {
1203             return $def;
1204         }
1205     }
1206
1207     /**
1208      * Returns trimmed query argument or default value if not found
1209      *
1210      * @param string $key requested argument
1211      * @param string $def default value to return if $key is not provided
1212      *
1213      * @return boolean is read only action?
1214      */
1215     function trimmed($key, $def=null)
1216     {
1217         $arg = $this->arg($key, $def);
1218         return is_string($arg) ? trim($arg) : $arg;
1219     }
1220
1221     /**
1222      * Handler method
1223      *
1224      * @return boolean is read only action?
1225      */
1226     protected function handle()
1227     {
1228         header('Vary: Accept-Encoding,Cookie');
1229
1230         $lm   = $this->lastModified();
1231         $etag = $this->etag();
1232
1233         if ($etag) {
1234             header('ETag: ' . $etag);
1235         }
1236
1237         if ($lm) {
1238             header('Last-Modified: ' . date(DATE_RFC1123, $lm));
1239             if ($this->isCacheable()) {
1240                 header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', 0 ) . ' GMT' );
1241                 header( "Cache-Control: private, must-revalidate, max-age=0" );
1242                 header( "Pragma:");
1243             }
1244         }
1245
1246         $checked = false;
1247         if ($etag) {
1248             $if_none_match = (array_key_exists('HTTP_IF_NONE_MATCH', $_SERVER)) ?
1249               $_SERVER['HTTP_IF_NONE_MATCH'] : null;
1250             if ($if_none_match) {
1251                 // If this check fails, ignore the if-modified-since below.
1252                 $checked = true;
1253                 if ($this->_hasEtag($etag, $if_none_match)) {
1254                     header('HTTP/1.1 304 Not Modified');
1255                     // Better way to do this?
1256                     exit(0);
1257                 }
1258             }
1259         }
1260
1261         if (!$checked && $lm && array_key_exists('HTTP_IF_MODIFIED_SINCE', $_SERVER)) {
1262             $if_modified_since = $_SERVER['HTTP_IF_MODIFIED_SINCE'];
1263             $ims = strtotime($if_modified_since);
1264             if ($lm <= $ims) {
1265                 header('HTTP/1.1 304 Not Modified');
1266                 // Better way to do this?
1267                 exit(0);
1268             }
1269         }
1270     }
1271
1272     /**
1273      * Is this action cacheable?
1274      *
1275      * If the action returns a last-modified
1276      *
1277      * @param array $argarray is ignored since it's now passed in in prepare()
1278      *
1279      * @return boolean is read only action?
1280      */
1281     function isCacheable()
1282     {
1283         return true;
1284     }
1285
1286     /**
1287      * Has etag? (private)
1288      *
1289      * @param string $etag          etag http header
1290      * @param string $if_none_match ifNoneMatch http header
1291      *
1292      * @return boolean
1293      */
1294     function _hasEtag($etag, $if_none_match)
1295     {
1296         $etags = explode(',', $if_none_match);
1297         return in_array($etag, $etags) || in_array('*', $etags);
1298     }
1299
1300     /**
1301      * Boolean understands english (yes, no, true, false)
1302      *
1303      * @param string $key query key we're interested in
1304      * @param string $def default value
1305      *
1306      * @return boolean interprets yes/no strings as boolean
1307      */
1308     function boolean($key, $def=false)
1309     {
1310         $arg = strtolower($this->trimmed($key));
1311
1312         if (is_null($arg)) {
1313             return $def;
1314         } else if (in_array($arg, array('true', 'yes', '1', 'on'))) {
1315             return true;
1316         } else if (in_array($arg, array('false', 'no', '0'))) {
1317             return false;
1318         } else {
1319             return $def;
1320         }
1321     }
1322
1323     /**
1324      * Integer value of an argument
1325      *
1326      * @param string $key      query key we're interested in
1327      * @param string $defValue optional default value (default null)
1328      * @param string $maxValue optional max value (default null)
1329      * @param string $minValue optional min value (default null)
1330      *
1331      * @return integer integer value
1332      */
1333     function int($key, $defValue=null, $maxValue=null, $minValue=null)
1334     {
1335         $arg = strtolower($this->trimmed($key));
1336
1337         if (is_null($arg) || !is_integer($arg)) {
1338             return $defValue;
1339         }
1340
1341         if (!is_null($maxValue)) {
1342             $arg = min($arg, $maxValue);
1343         }
1344
1345         if (!is_null($minValue)) {
1346             $arg = max($arg, $minValue);
1347         }
1348
1349         return $arg;
1350     }
1351
1352     /**
1353      * Server error
1354      *
1355      * @param string  $msg  error message to display
1356      * @param integer $code http error code, 500 by default
1357      *
1358      * @return nothing
1359      */
1360     function serverError($msg, $code=500)
1361     {
1362         $action = $this->trimmed('action');
1363         common_debug("Server error '$code' on '$action': $msg", __FILE__);
1364         throw new ServerException($msg, $code);
1365     }
1366
1367     /**
1368      * Client error
1369      *
1370      * @param string  $msg  error message to display
1371      * @param integer $code http error code, 400 by default
1372      *
1373      * @return nothing
1374      */
1375     function clientError($msg, $code=400)
1376     {
1377         $action = $this->trimmed('action');
1378         common_debug("User error '$code' on '$action': $msg", __FILE__);
1379         throw new ClientException($msg, $code);
1380     }
1381
1382     /**
1383      * If not logged in, take appropriate action (redir or exception)
1384      *
1385      * @param boolean $redir Redirect to login if not logged in
1386      *
1387      * @return boolean true if logged in (never returns if not)
1388      */
1389     public function checkLogin($redir=true)
1390     {
1391         if (common_logged_in()) {
1392             return true;
1393         }
1394
1395         if ($redir==true) {
1396             common_set_returnto($_SERVER['REQUEST_URI']);
1397             common_redirect(common_local_url('login'));
1398         }
1399
1400         // TRANS: Error message displayed when trying to perform an action that requires a logged in user.
1401         $this->clientError(_('Not logged in.'), 403);
1402     }
1403
1404     /**
1405      * Returns the current URL
1406      *
1407      * @return string current URL
1408      */
1409     function selfUrl()
1410     {
1411         list($action, $args) = $this->returnToArgs();
1412         return common_local_url($action, $args);
1413     }
1414
1415     /**
1416      * Returns arguments sufficient for re-constructing URL
1417      *
1418      * @return array two elements: action, other args
1419      */
1420     function returnToArgs()
1421     {
1422         $action = $this->trimmed('action');
1423         $args   = $this->args;
1424         unset($args['action']);
1425         if (common_config('site', 'fancy')) {
1426             unset($args['p']);
1427         }
1428         if (array_key_exists('submit', $args)) {
1429             unset($args['submit']);
1430         }
1431         foreach (array_keys($_COOKIE) as $cookie) {
1432             unset($args[$cookie]);
1433         }
1434         return array($action, $args);
1435     }
1436
1437     /**
1438      * Generate a menu item
1439      *
1440      * @param string  $url         menu URL
1441      * @param string  $text        menu name
1442      * @param string  $title       title attribute, null by default
1443      * @param boolean $is_selected current menu item, false by default
1444      * @param string  $id          element id, null by default
1445      *
1446      * @return nothing
1447      */
1448     function menuItem($url, $text, $title=null, $is_selected=false, $id=null, $class=null)
1449     {
1450         // Added @id to li for some control.
1451         // XXX: We might want to move this to htmloutputter.php
1452         $lattrs  = array();
1453         $classes = array();
1454         if ($class !== null) {
1455             $classes[] = trim($class);
1456         }
1457         if ($is_selected) {
1458             $classes[] = 'current';
1459         }
1460
1461         if (!empty($classes)) {
1462             $lattrs['class'] = implode(' ', $classes);
1463         }
1464
1465         if (!is_null($id)) {
1466             $lattrs['id'] = $id;
1467         }
1468
1469         $this->elementStart('li', $lattrs);
1470         $attrs['href'] = $url;
1471         if ($title) {
1472             $attrs['title'] = $title;
1473         }
1474         $this->element('a', $attrs, $text);
1475         $this->elementEnd('li');
1476     }
1477
1478     /**
1479      * Generate pagination links
1480      *
1481      * @param boolean $have_before is there something before?
1482      * @param boolean $have_after  is there something after?
1483      * @param integer $page        current page
1484      * @param string  $action      current action
1485      * @param array   $args        rest of query arguments
1486      *
1487      * @return nothing
1488      */
1489     // XXX: The messages in this pagination method only tailor to navigating
1490     //      notices. In other lists, "Previous"/"Next" type navigation is
1491     //      desirable, but not available.
1492     function pagination($have_before, $have_after, $page, $action, $args=null)
1493     {
1494         // Does a little before-after block for next/prev page
1495         if ($have_before || $have_after) {
1496             $this->elementStart('ul', array('class' => 'nav',
1497                                             'id' => 'pagination'));
1498         }
1499         if ($have_before) {
1500             $pargs   = array('page' => $page-1);
1501             $this->elementStart('li', array('class' => 'nav_prev'));
1502             $this->element('a', array('href' => common_local_url($action, $args, $pargs),
1503                                       'rel' => 'prev'),
1504                            // TRANS: Pagination message to go to a page displaying information more in the
1505                            // TRANS: present than the currently displayed information.
1506                            _('After'));
1507             $this->elementEnd('li');
1508         }
1509         if ($have_after) {
1510             $pargs   = array('page' => $page+1);
1511             $this->elementStart('li', array('class' => 'nav_next'));
1512             $this->element('a', array('href' => common_local_url($action, $args, $pargs),
1513                                       'rel' => 'next'),
1514                            // TRANS: Pagination message to go to a page displaying information more in the
1515                            // TRANS: past than the currently displayed information.
1516                            _('Before'));
1517             $this->elementEnd('li');
1518         }
1519         if ($have_before || $have_after) {
1520             $this->elementEnd('ul');
1521         }
1522     }
1523
1524     /**
1525      * An array of feeds for this action.
1526      *
1527      * Returns an array of potential feeds for this action.
1528      *
1529      * @return array Feed object to show in head and links
1530      */
1531     function getFeeds()
1532     {
1533         return null;
1534     }
1535
1536     /**
1537      * Check the session token.
1538      *
1539      * Checks that the current form has the correct session token,
1540      * and throw an exception if it does not.
1541      *
1542      * @return void
1543      */
1544     // XXX: Finding this type of check with the same message about 50 times.
1545     //      Possible to refactor?
1546     function checkSessionToken()
1547     {
1548         // CSRF protection
1549         $token = $this->trimmed('token');
1550         if (empty($token) || $token != common_session_token()) {
1551             // TRANS: Client error text when there is a problem with the session token.
1552             $this->clientError(_('There was a problem with your session token.'));
1553         }
1554     }
1555
1556     /**
1557      * Check if the current request is a POST
1558      *
1559      * @return boolean true if POST; otherwise false.
1560      */
1561
1562     function isPost()
1563     {
1564         return ($_SERVER['REQUEST_METHOD'] == 'POST');
1565     }
1566 }