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