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