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