3 * StatusNet, the distributed open-source microblogging tool
5 * Base class for all actions (~views)
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.
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.
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/>.
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/
31 if (!defined('GNUSOCIAL')) { exit(1); }
34 * Base class for all actions
36 * This is the base class for all actions in the package. An action is
37 * more or less a "view" in an MVC framework.
39 * Actions are responsible for extracting and validating parameters; using
40 * model classes to read and write to the database; and doing ouput.
44 * @author Evan Prodromou <evan@status.net>
45 * @author Sarven Capadisli <csarven@status.net>
46 * @license http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
47 * @link http://status.net/
51 class Action extends HTMLOutputter // lawsuit
53 // This should be protected/private in the future
54 public $args = array();
56 // Action properties, set per-class
57 protected $action = false;
58 protected $ajax = false;
59 protected $menus = true;
60 protected $needLogin = false;
61 protected $needPost = false;
63 // The currently scoped profile (normally Profile::current; from $this->auth_user for API)
64 protected $scoped = null;
66 // Related to front-end user representation
67 protected $format = null;
68 protected $error = null;
69 protected $msg = null;
74 * Just wraps the HTMLOutputter constructor.
76 * @param string $output URI to output to, default = stdout
77 * @param boolean $indent Whether to indent output, default true
79 * @see XMLOutputter::__construct
80 * @see HTMLOutputter::__construct
82 function __construct($output='php://output', $indent=null)
84 parent::__construct($output, $indent);
97 static public function run(array $args=array(), $output='php://output', $indent=null) {
98 $class = get_called_class();
99 $action = new $class($output, $indent);
100 $action->execute($args);
104 public function execute(array $args=array()) {
106 if (common_config('db', 'mirror') && $this->isReadOnly($args)) {
107 if (is_array(common_config('db', 'mirror'))) {
108 // "load balancing", ha ha
109 $arr = common_config('db', 'mirror');
110 $k = array_rand($arr);
113 $mirror = common_config('db', 'mirror');
116 // everyone else uses the mirror
117 common_config_set('db', 'database', $mirror);
120 $status = $this->prepare($args);
122 $this->handle($args);
124 common_debug('Prepare failed for Action.');
129 Event::handle('EndActionExecute', array($status, $this));
133 * For initializing members of the class.
135 * @param array $argarray misc. arguments
137 * @return boolean true
139 protected function prepare(array $args=array())
141 if ($this->needPost && !$this->isPost()) {
142 // TRANS: Client error. POST is a HTTP command. It should not be translated.
143 $this->clientError(_('This method requires a POST.'), 405);
146 $this->args = common_copy_args($args);
148 $this->action = $this->trimmed('action');
150 if ($this->ajax || $this->boolean('ajax')) {
151 // check with StatusNet::isAjax()
152 StatusNet::setAjax(true);
155 if ($this->needLogin) {
156 $this->checkLogin(); // if not logged in, this redirs/excepts
159 $this->updateScopedProfile();
164 function updateScopedProfile() {
165 $this->scoped = Profile::current();
166 return $this->scoped;
170 * Show page, a template method.
176 if (Event::handle('StartShowHTML', array($this))) {
179 Event::handle('EndShowHTML', array($this));
181 if (Event::handle('StartShowHead', array($this))) {
184 Event::handle('EndShowHead', array($this));
186 if (Event::handle('StartShowBody', array($this))) {
188 Event::handle('EndShowBody', array($this));
190 if (Event::handle('StartEndHTML', array($this))) {
192 Event::handle('EndEndHTML', array($this));
200 if (isset($_startTime)) {
201 $endTime = microtime(true);
202 $diff = round(($endTime - $_startTime) * 1000);
203 $this->raw("<!-- ${diff}ms -->");
206 return parent::endHTML();
210 * Show head, a template method.
216 // XXX: attributes (profile?)
217 $this->elementStart('head');
218 if (Event::handle('StartShowHeadElements', array($this))) {
219 if (Event::handle('StartShowHeadTitle', array($this))) {
221 Event::handle('EndShowHeadTitle', array($this));
223 $this->showShortcutIcon();
224 $this->showStylesheets();
225 $this->showOpenSearch();
227 $this->showDescription();
229 Event::handle('EndShowHeadElements', array($this));
231 $this->elementEnd('head');
235 * Show title, a template method.
241 $this->element('title', null,
242 // TRANS: Page title. %1$s is the title, %2$s is the site name.
243 sprintf(_('%1$s - %2$s'),
245 common_config('site', 'name')));
249 * Returns the page title
253 * @return string page title
258 // TRANS: Page title for a page without a title set.
259 return _('Untitled page');
263 * Show themed shortcut icon
267 function showShortcutIcon()
269 if (is_readable(INSTALLDIR . '/theme/' . common_config('site', 'theme') . '/favicon.ico')) {
270 $this->element('link', array('rel' => 'shortcut icon',
271 'href' => Theme::path('favicon.ico')));
273 // favicon.ico should be HTTPS if the rest of the page is
274 $this->element('link', array('rel' => 'shortcut icon',
275 'href' => common_path('favicon.ico', StatusNet::isHTTPS())));
278 if (common_config('site', 'mobile')) {
279 if (is_readable(INSTALLDIR . '/theme/' . common_config('site', 'theme') . '/apple-touch-icon.png')) {
280 $this->element('link', array('rel' => 'apple-touch-icon',
281 'href' => Theme::path('apple-touch-icon.png')));
283 $this->element('link', array('rel' => 'apple-touch-icon',
284 'href' => common_path('apple-touch-icon.png')));
294 function showStylesheets()
296 if (Event::handle('StartShowStyles', array($this))) {
298 // Use old name for StatusNet for compatibility on events
300 if (Event::handle('StartShowStylesheets', array($this))) {
301 $this->primaryCssLink(null, 'screen, projection, tv, print');
302 Event::handle('EndShowStylesheets', array($this));
305 $this->cssLink('js/extlib/jquery-ui/css/smoothness/jquery-ui.css');
307 if (Event::handle('StartShowUAStyles', array($this))) {
308 $this->comment('[if IE]><link rel="stylesheet" type="text/css" '.
309 'href="'.Theme::path('css/ie.css', 'base').'?version='.GNUSOCIAL_VERSION.'" /><![endif]');
310 foreach (array(6,7) as $ver) {
311 if (file_exists(Theme::file('css/ie'.$ver.'.css', 'base'))) {
312 // Yes, IE people should be put in jail.
313 $this->comment('[if lte IE '.$ver.']><link rel="stylesheet" type="text/css" '.
314 'href="'.Theme::path('css/ie'.$ver.'.css', 'base').'?version='.GNUSOCIAL_VERSION.'" /><![endif]');
317 if (file_exists(Theme::file('css/ie.css'))) {
318 $this->comment('[if IE]><link rel="stylesheet" type="text/css" '.
319 'href="'.Theme::path('css/ie.css', null).'?version='.GNUSOCIAL_VERSION.'" /><![endif]');
321 Event::handle('EndShowUAStyles', array($this));
324 Event::handle('EndShowStyles', array($this));
326 if (common_config('custom_css', 'enabled')) {
327 $css = common_config('custom_css', 'css');
328 if (Event::handle('StartShowCustomCss', array($this, &$css))) {
329 if (trim($css) != '') {
332 Event::handle('EndShowCustomCss', array($this));
338 function primaryCssLink($mainTheme=null, $media=null)
340 $theme = new Theme($mainTheme);
342 // Some themes may have external stylesheets, such as using the
343 // Google Font APIs to load webfonts.
344 foreach ($theme->getExternals() as $url) {
345 $this->cssLink($url, $mainTheme, $media);
348 // If the currently-selected theme has dependencies on other themes,
349 // we'll need to load their display.css files as well in order.
350 $baseThemes = $theme->getDeps();
351 foreach ($baseThemes as $baseTheme) {
352 $this->cssLink('css/display.css', $baseTheme, $media);
354 $this->cssLink('css/display.css', $mainTheme, $media);
356 // Additional styles for RTL languages
357 if (is_rtl(common_language())) {
358 if (file_exists(Theme::file('css/rtl.css'))) {
359 $this->cssLink('css/rtl.css', $mainTheme, $media);
365 * Show javascript headers
369 function showScripts()
371 if (Event::handle('StartShowScripts', array($this))) {
372 if (Event::handle('StartShowJQueryScripts', array($this))) {
373 $this->script('extlib/jquery.js');
374 $this->script('extlib/jquery.form.js');
375 $this->script('extlib/jquery-ui/jquery-ui.js');
376 $this->script('extlib/jquery.cookie.js');
377 $this->inlineScript('if (typeof window.JSON !== "object") { $.getScript("'.common_path('js/extlib/json2.js', StatusNet::isHTTPS()).'"); }');
378 $this->script('extlib/jquery.infieldlabel.js');
380 Event::handle('EndShowJQueryScripts', array($this));
382 if (Event::handle('StartShowStatusNetScripts', array($this))) {
383 $this->script('util.js');
384 $this->script('xbImportNode.js');
385 $this->script('geometa.js');
387 // This route isn't available in single-user mode.
388 // Not sure why, but it causes errors here.
389 $this->inlineScript('var _peopletagAC = "' .
390 common_local_url('peopletagautocomplete') . '";');
391 $this->showScriptMessages();
392 // Anti-framing code to avoid clickjacking attacks in older browsers.
393 // This will show a blank page if the page is being framed, which is
394 // consistent with the behavior of the 'X-Frame-Options: SAMEORIGIN'
395 // header, which prevents framing in newer browser.
396 if (common_config('javascript', 'bustframes')) {
397 $this->inlineScript('if (window.top !== window.self) { document.write = ""; window.top.location = window.self.location; setTimeout(function () { document.body.innerHTML = ""; }, 1); window.self.onload = function () { document.body.innerHTML = ""; }; }');
399 Event::handle('EndShowStatusNetScripts', array($this));
401 Event::handle('EndShowScripts', array($this));
406 * Exports a map of localized text strings to JavaScript code.
408 * Plugins can add to what's exported by hooking the StartScriptMessages or EndScriptMessages
409 * events and appending to the array. Try to avoid adding strings that won't be used, as
410 * they'll be added to HTML output.
412 function showScriptMessages()
416 if (Event::handle('StartScriptMessages', array($this, &$messages))) {
417 // Common messages needed for timeline views etc...
419 // TRANS: Localized tooltip for '...' expansion button on overlong remote messages.
420 $messages['showmore_tooltip'] = _m('TOOLTIP', 'Show more');
422 // TRANS: Inline reply form submit button: submits a reply comment.
423 $messages['reply_submit'] = _m('BUTTON', 'Reply');
425 // TRANS: Placeholder text for inline reply form. Clicking in this box will turn it into a mini notice form.
426 $messages['reply_placeholder'] = _m('Write a reply...');
428 $messages = array_merge($messages, $this->getScriptMessages());
430 Event::handle('EndScriptMessages', array($this, &$messages));
433 if (!empty($messages)) {
434 $this->inlineScript('SN.messages=' . json_encode($messages));
441 * If the action will need localizable text strings, export them here like so:
443 * return array('pool_deepend' => _('Deep end'),
444 * 'pool_shallow' => _('Shallow end'));
446 * The exported map will be available via SN.msg() to JS code:
448 * $('#pool').html('<div class="deepend"></div><div class="shallow"></div>');
449 * $('#pool .deepend').text(SN.msg('pool_deepend'));
450 * $('#pool .shallow').text(SN.msg('pool_shallow'));
452 * Exports a map of localized text strings to JavaScript code.
454 * Plugins can add to what's exported on any action by hooking the StartScriptMessages or
455 * EndScriptMessages events and appending to the array. Try to avoid adding strings that won't
456 * be used, as they'll be added to HTML output.
458 function getScriptMessages()
464 * Show OpenSearch headers
468 function showOpenSearch()
470 $this->element('link', array('rel' => 'search',
471 'type' => 'application/opensearchdescription+xml',
472 'href' => common_local_url('opensearch', array('type' => 'people')),
473 'title' => common_config('site', 'name').' People Search'));
474 $this->element('link', array('rel' => 'search', 'type' => 'application/opensearchdescription+xml',
475 'href' => common_local_url('opensearch', array('type' => 'notice')),
476 'title' => common_config('site', 'name').' Notice Search'));
488 $feeds = $this->getFeeds();
491 foreach ($feeds as $feed) {
492 $this->element('link', array('rel' => $feed->rel(),
493 'href' => $feed->url,
494 'type' => $feed->mimeType(),
495 'title' => $feed->title));
507 function showDescription()
509 // does nothing by default
513 * Show extra stuff in <head>.
521 // does nothing by default
527 * Calls template methods
533 $this->elementStart('body', (common_current_user()) ? array('id' => strtolower($this->trimmed('action')),
534 'class' => 'user_in')
535 : array('id' => strtolower($this->trimmed('action'))));
536 $this->elementStart('div', array('id' => 'wrap'));
537 if (Event::handle('StartShowHeader', array($this))) {
540 Event::handle('EndShowHeader', array($this));
544 if (Event::handle('StartShowFooter', array($this))) {
547 Event::handle('EndShowFooter', array($this));
549 $this->elementEnd('div');
550 $this->showScripts();
551 $this->elementEnd('body');
555 * Show header of the page.
557 * Calls template methods
561 function showHeader()
563 $this->elementStart('div', array('id' => 'header'));
565 $this->showPrimaryNav();
566 if (Event::handle('StartShowSiteNotice', array($this))) {
567 $this->showSiteNotice();
569 Event::handle('EndShowSiteNotice', array($this));
572 $this->elementEnd('div');
576 * Show configured logo.
582 $this->elementStart('address', array('id' => 'site_contact',
583 'class' => 'vcard'));
584 if (Event::handle('StartAddressData', array($this))) {
585 if (common_config('singleuser', 'enabled')) {
586 $user = User::singleUser();
587 $url = common_local_url('showstream',
588 array('nickname' => $user->nickname));
589 } else if (common_logged_in()) {
590 $cur = common_current_user();
591 $url = common_local_url('all', array('nickname' => $cur->nickname));
593 $url = common_local_url('public');
596 $this->elementStart('a', array('class' => 'url home bookmark',
599 if (StatusNet::isHTTPS()) {
600 $logoUrl = common_config('site', 'ssllogo');
601 if (empty($logoUrl)) {
602 // if logo is an uploaded file, try to fall back to HTTPS file URL
603 $httpUrl = common_config('site', 'logo');
604 if (!empty($httpUrl)) {
605 $f = File::getKV('url', $httpUrl);
606 if (!empty($f) && !empty($f->filename)) {
607 // this will handle the HTTPS case
608 $logoUrl = File::url($f->filename);
613 $logoUrl = common_config('site', 'logo');
616 if (empty($logoUrl) && file_exists(Theme::file('logo.png'))) {
617 // This should handle the HTTPS case internally
618 $logoUrl = Theme::path('logo.png');
621 if (!empty($logoUrl)) {
622 $this->element('img', array('class' => 'logo photo',
624 'alt' => common_config('site', 'name')));
628 $this->element('span', array('class' => 'fn org'), common_config('site', 'name'));
629 $this->elementEnd('a');
631 Event::handle('EndAddressData', array($this));
633 $this->elementEnd('address');
637 * Show primary navigation.
641 function showPrimaryNav()
643 $this->elementStart('div', array('id' => 'site_nav_global_primary'));
645 $user = common_current_user();
647 if (!empty($user) || !common_config('site', 'private')) {
648 $form = new SearchForm($this);
652 $pn = new PrimaryNav($this);
654 $this->elementEnd('div');
662 function showSiteNotice()
664 // Revist. Should probably do an hAtom pattern here
665 $text = common_config('site', 'notice');
667 $this->elementStart('div', array('id' => 'site_notice',
668 'class' => 'system_notice'));
670 $this->elementEnd('div');
677 * MAY overload if no notice form needed... or direct message box????
681 function showNoticeForm()
683 // TRANS: Tab on the notice form.
684 $tabs = array('status' => _m('TAB','Status'));
686 $this->elementStart('div', 'input_forms');
688 if (Event::handle('StartShowEntryForms', array(&$tabs))) {
689 $this->elementStart('ul', array('class' => 'nav',
690 'id' => 'input_form_nav'));
692 foreach ($tabs as $tag => $title) {
693 $attrs = array('id' => 'input_form_nav_'.$tag,
694 'class' => 'input_form_nav_tab');
696 if ($tag == 'status') {
697 // We're actually showing the placeholder form,
698 // but we special-case the 'Status' tab as if
699 // it were a small version of it.
700 $attrs['class'] .= ' current';
702 $this->elementStart('li', $attrs);
705 array('href' => 'javascript:SN.U.switchInputFormTab("'.$tag.'")'),
707 $this->elementEnd('li');
710 $this->elementEnd('ul');
712 $attrs = array('class' => 'input_form current',
713 'id' => 'input_form_placeholder');
714 $this->elementStart('div', $attrs);
715 $form = new NoticePlaceholderForm($this);
717 $this->elementEnd('div');
719 foreach ($tabs as $tag => $title) {
720 $attrs = array('class' => 'input_form',
721 'id' => 'input_form_'.$tag);
723 $this->elementStart('div', $attrs);
727 if (Event::handle('StartMakeEntryForm', array($tag, $this, &$form))) {
728 if ($tag == 'status') {
729 $options = $this->noticeFormOptions();
730 $form = new NoticeForm($this, $options);
732 Event::handle('EndMakeEntryForm', array($tag, $this, $form));
739 $this->elementEnd('div');
743 $this->elementEnd('div');
746 function noticeFormOptions()
752 * Show anonymous message.
758 function showAnonymousMessage()
760 // needs to be defined by the class
766 * Shows local navigation, content block and aside.
772 $this->elementStart('div', array('id' => 'core'));
773 $this->elementStart('div', array('id' => 'aside_primary_wrapper'));
774 $this->elementStart('div', array('id' => 'content_wrapper'));
775 $this->elementStart('div', array('id' => 'site_nav_local_views_wrapper'));
776 if (Event::handle('StartShowLocalNavBlock', array($this))) {
777 $this->showLocalNavBlock();
779 Event::handle('EndShowLocalNavBlock', array($this));
781 if (Event::handle('StartShowContentBlock', array($this))) {
782 $this->showContentBlock();
784 Event::handle('EndShowContentBlock', array($this));
786 if (Event::handle('StartShowAside', array($this))) {
789 Event::handle('EndShowAside', array($this));
791 $this->elementEnd('div');
792 $this->elementEnd('div');
793 $this->elementEnd('div');
794 $this->elementEnd('div');
798 * Show local navigation block.
802 function showLocalNavBlock()
804 // Need to have this ID for CSS; I'm too lazy to add it to
806 $this->elementStart('div', array('id' => 'site_nav_local_views'));
807 // Cheat cheat cheat!
808 $this->showLocalNav();
809 $this->elementEnd('div');
813 * If there's a logged-in user, show a bit of login context
817 function showProfileBlock()
819 if (common_logged_in()) {
820 $block = new DefaultProfileBlock($this);
826 * Show local navigation.
832 function showLocalNav()
834 $nav = new DefaultLocalNav($this);
839 * Show menu for an object (group, profile)
841 * This block will only show if a subclass has overridden
842 * the showObjectNav() method.
846 function showObjectNavBlock()
848 $rmethod = new ReflectionMethod($this, 'showObjectNav');
849 $dclass = $rmethod->getDeclaringClass()->getName();
851 if ($dclass != 'Action') {
852 // Need to have this ID for CSS; I'm too lazy to add it to
854 $this->elementStart('div', array('id' => 'site_nav_object',
855 'class' => 'section'));
856 $this->showObjectNav();
857 $this->elementEnd('div');
862 * Show object navigation.
864 * If there are things to do with this object, show it here.
868 function showObjectNav()
874 * Show content block.
878 function showContentBlock()
880 $this->elementStart('div', array('id' => 'content'));
881 if (common_logged_in()) {
882 if (Event::handle('StartShowNoticeForm', array($this))) {
883 $this->showNoticeForm();
884 Event::handle('EndShowNoticeForm', array($this));
887 if (Event::handle('StartShowPageTitle', array($this))) {
888 $this->showPageTitle();
889 Event::handle('EndShowPageTitle', array($this));
891 $this->showPageNoticeBlock();
892 $this->elementStart('div', array('id' => 'content_inner'));
893 // show the actual content (forms, lists, whatever)
894 $this->showContent();
895 $this->elementEnd('div');
896 $this->elementEnd('div');
904 function showPageTitle()
906 $this->element('h1', null, $this->title());
910 * Show page notice block.
912 * Only show the block if a subclassed action has overrided
913 * Action::showPageNotice(), or an event handler is registered for
914 * the StartShowPageNotice event, in which case we assume the
915 * 'page_notice' definition list is desired. This is to prevent
916 * empty 'page_notice' definition lists from being output everywhere.
920 function showPageNoticeBlock()
922 $rmethod = new ReflectionMethod($this, 'showPageNotice');
923 $dclass = $rmethod->getDeclaringClass()->getName();
925 if ($dclass != 'Action' || Event::hasHandler('StartShowPageNotice')) {
927 $this->elementStart('div', array('id' => 'page_notice',
928 'class' => 'system_notice'));
929 if (Event::handle('StartShowPageNotice', array($this))) {
930 $this->showPageNotice();
931 Event::handle('EndShowPageNotice', array($this));
933 $this->elementEnd('div');
940 * SHOULD overload (unless there's not a notice)
944 function showPageNotice()
951 * MUST overload (unless there's not a notice)
955 function showContent()
966 $this->elementStart('div', array('id' => 'aside_primary',
967 'class' => 'aside'));
968 $this->showProfileBlock();
969 if (Event::handle('StartShowObjectNavBlock', array($this))) {
970 $this->showObjectNavBlock();
971 Event::handle('EndShowObjectNavBlock', array($this));
973 if (Event::handle('StartShowSections', array($this))) {
974 $this->showSections();
975 Event::handle('EndShowSections', array($this));
977 if (Event::handle('StartShowExportData', array($this))) {
978 $this->showExportData();
979 Event::handle('EndShowExportData', array($this));
981 $this->elementEnd('div');
985 * Show export data feeds.
989 function showExportData()
991 $feeds = $this->getFeeds();
993 $fl = new FeedList($this);
1005 function showSections()
1007 // for each section, show it
1015 function showFooter()
1017 $this->elementStart('div', array('id' => 'footer'));
1018 if (Event::handle('StartShowInsideFooter', array($this))) {
1019 $this->showSecondaryNav();
1020 $this->showLicenses();
1021 Event::handle('EndShowInsideFooter', array($this));
1023 $this->elementEnd('div');
1027 * Show secondary navigation.
1031 function showSecondaryNav()
1033 $sn = new SecondaryNav($this);
1042 function showLicenses()
1044 $this->showGNUsocialLicense();
1045 $this->showContentLicense();
1049 * Show GNU social license.
1053 function showGNUsocialLicense()
1055 if (common_config('site', 'broughtby')) {
1056 // TRANS: First sentence of the GNU social site license. Used if 'broughtby' is set.
1057 // TRANS: Text between [] is a link description, text between () is the link itself.
1058 // TRANS: Make sure there is no whitespace between "]" and "(".
1059 // TRANS: "%%site.broughtby%%" is the value of the variable site.broughtby
1060 $instr = _('**%%site.name%%** is a social network, courtesy of [%%site.broughtby%%](%%site.broughtbyurl%%).');
1062 // TRANS: First sentence of the GNU social site license. Used if 'broughtby' is not set.
1063 $instr = _('**%%site.name%%** is a social network.');
1066 // TRANS: Second sentence of the GNU social site license. Mentions the GNU social source code license.
1067 // TRANS: Make sure there is no whitespace between "]" and "(".
1068 // TRANS: [%1$s](%2$s) is a link description followed by the link itself
1069 // TRANS: %3$s is the version of GNU social that is being used.
1070 $instr .= sprintf(_('It runs on [%1$s](%2$s), version %3$s, available under the [GNU Affero General Public License](http://www.fsf.org/licensing/licenses/agpl-3.0.html).'), GNUSOCIAL_ENGINE, GNUSOCIAL_ENGINE_URL, GNUSOCIAL_VERSION);
1071 $output = common_markup_to_html($instr);
1072 $this->raw($output);
1077 * Show content license.
1081 function showContentLicense()
1083 if (Event::handle('StartShowContentLicense', array($this))) {
1084 switch (common_config('license', 'type')) {
1086 // TRANS: Content license displayed when license is set to 'private'.
1087 // TRANS: %1$s is the site name.
1088 $this->element('p', null, sprintf(_('Content and data of %1$s are private and confidential.'),
1089 common_config('site', 'name')));
1091 case 'allrightsreserved':
1092 if (common_config('license', 'owner')) {
1093 // TRANS: Content license displayed when license is set to 'allrightsreserved'.
1094 // TRANS: %1$s is the copyright owner.
1095 $this->element('p', null, sprintf(_('Content and data copyright by %1$s. All rights reserved.'),
1096 common_config('license', 'owner')));
1098 // TRANS: Content license displayed when license is set to 'allrightsreserved' and no owner is set.
1099 $this->element('p', null, _('Content and data copyright by contributors. All rights reserved.'));
1102 case 'cc': // fall through
1104 $this->elementStart('p');
1106 $image = common_config('license', 'image');
1107 $sslimage = common_config('license', 'sslimage');
1109 if (StatusNet::isHTTPS()) {
1110 if (!empty($sslimage)) {
1112 } else if (preg_match('#^http://i.creativecommons.org/#', $image)) {
1113 // CC support HTTPS on their images
1114 $url = preg_replace('/^http/', 'https', $image);
1116 // Better to show mixed content than no content
1123 $this->element('img', array('id' => 'license_cc',
1125 'alt' => common_config('license', 'title'),
1129 // TRANS: license message in footer.
1130 // TRANS: %1$s is the site name, %2$s is a link to the license URL, with a licence name set in configuration.
1131 $notice = _('All %1$s content and data are available under the %2$s license.');
1132 $link = "<a class=\"license\" rel=\"external license\" href=\"" .
1133 htmlspecialchars(common_config('license', 'url')) .
1135 htmlspecialchars(common_config('license', 'title')) .
1137 $this->raw(sprintf(htmlspecialchars($notice),
1138 htmlspecialchars(common_config('site', 'name')),
1140 $this->elementEnd('p');
1144 Event::handle('EndShowContentLicense', array($this));
1149 * Return last modified, if applicable.
1153 * @return string last modified http header
1155 function lastModified()
1157 // For comparison with If-Last-Modified
1158 // If not applicable, return null
1163 * Return etag, if applicable.
1167 * @return string etag http header
1175 * Return true if read only.
1179 * @param array $args other arguments
1181 * @return boolean is read only action?
1183 function isReadOnly($args)
1189 * Returns query argument or default value if not found
1191 * @param string $key requested argument
1192 * @param string $def default value to return if $key is not provided
1194 * @return boolean is read only action?
1196 function arg($key, $def=null)
1198 if (array_key_exists($key, $this->args)) {
1199 return $this->args[$key];
1206 * Returns trimmed query argument or default value if not found
1208 * @param string $key requested argument
1209 * @param string $def default value to return if $key is not provided
1211 * @return boolean is read only action?
1213 function trimmed($key, $def=null)
1215 $arg = $this->arg($key, $def);
1216 return is_string($arg) ? trim($arg) : $arg;
1222 * @return boolean is read only action?
1224 protected function handle()
1226 header('Vary: Accept-Encoding,Cookie');
1228 $lm = $this->lastModified();
1229 $etag = $this->etag();
1232 header('ETag: ' . $etag);
1236 header('Last-Modified: ' . date(DATE_RFC1123, $lm));
1237 if ($this->isCacheable()) {
1238 header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', 0 ) . ' GMT' );
1239 header( "Cache-Control: private, must-revalidate, max-age=0" );
1246 $if_none_match = (array_key_exists('HTTP_IF_NONE_MATCH', $_SERVER)) ?
1247 $_SERVER['HTTP_IF_NONE_MATCH'] : null;
1248 if ($if_none_match) {
1249 // If this check fails, ignore the if-modified-since below.
1251 if ($this->_hasEtag($etag, $if_none_match)) {
1252 header('HTTP/1.1 304 Not Modified');
1253 // Better way to do this?
1259 if (!$checked && $lm && array_key_exists('HTTP_IF_MODIFIED_SINCE', $_SERVER)) {
1260 $if_modified_since = $_SERVER['HTTP_IF_MODIFIED_SINCE'];
1261 $ims = strtotime($if_modified_since);
1263 header('HTTP/1.1 304 Not Modified');
1264 // Better way to do this?
1271 * Is this action cacheable?
1273 * If the action returns a last-modified
1275 * @param array $argarray is ignored since it's now passed in in prepare()
1277 * @return boolean is read only action?
1279 function isCacheable()
1285 * Has etag? (private)
1287 * @param string $etag etag http header
1288 * @param string $if_none_match ifNoneMatch http header
1292 function _hasEtag($etag, $if_none_match)
1294 $etags = explode(',', $if_none_match);
1295 return in_array($etag, $etags) || in_array('*', $etags);
1299 * Boolean understands english (yes, no, true, false)
1301 * @param string $key query key we're interested in
1302 * @param string $def default value
1304 * @return boolean interprets yes/no strings as boolean
1306 function boolean($key, $def=false)
1308 $arg = strtolower($this->trimmed($key));
1310 if (is_null($arg)) {
1312 } else if (in_array($arg, array('true', 'yes', '1', 'on'))) {
1314 } else if (in_array($arg, array('false', 'no', '0'))) {
1322 * Integer value of an argument
1324 * @param string $key query key we're interested in
1325 * @param string $defValue optional default value (default null)
1326 * @param string $maxValue optional max value (default null)
1327 * @param string $minValue optional min value (default null)
1329 * @return integer integer value
1331 function int($key, $defValue=null, $maxValue=null, $minValue=null)
1333 $arg = strtolower($this->trimmed($key));
1335 if (is_null($arg) || !is_integer($arg)) {
1339 if (!is_null($maxValue)) {
1340 $arg = min($arg, $maxValue);
1343 if (!is_null($minValue)) {
1344 $arg = max($arg, $minValue);
1353 * @param string $msg error message to display
1354 * @param integer $code http error code, 500 by default
1358 function serverError($msg, $code=500, $format=null)
1360 if ($format === null) {
1361 $format = $this->format;
1364 common_debug("Server error '{$code}' on '{$this->action}': {$msg}", __FILE__);
1366 if (!array_key_exists($code, ServerErrorAction::$status)) {
1370 $status_string = ServerErrorAction::$status[$code];
1374 header("HTTP/1.1 {$code} {$status_string}");
1375 $this->initDocument('xml');
1376 $this->elementStart('hash');
1377 $this->element('error', null, $msg);
1378 $this->element('request', null, $_SERVER['REQUEST_URI']);
1379 $this->elementEnd('hash');
1380 $this->endDocument('xml');
1383 if (!isset($this->callback)) {
1384 header("HTTP/1.1 {$code} {$status_string}");
1386 $this->initDocument('json');
1387 $error_array = array('error' => $msg, 'request' => $_SERVER['REQUEST_URI']);
1388 print(json_encode($error_array));
1389 $this->endDocument('json');
1392 throw new ServerException($msg, $code);
1401 * @param string $msg error message to display
1402 * @param integer $code http error code, 400 by default
1403 * @param string $format error format (json, xml, text) for ApiAction
1406 * @throws ClientException always
1408 function clientError($msg, $code=400, $format=null)
1410 // $format is currently only relevant for an ApiAction anyway
1411 if ($format === null) {
1412 $format = $this->format;
1415 common_debug("User error '{$code}' on '{$this->action}': {$msg}", __FILE__);
1417 if (!array_key_exists($code, ClientErrorAction::$status)) {
1421 $status_string = ClientErrorAction::$status[$code];
1425 header("HTTP/1.1 {$code} {$status_string}");
1426 $this->initDocument('xml');
1427 $this->elementStart('hash');
1428 $this->element('error', null, $msg);
1429 $this->element('request', null, $_SERVER['REQUEST_URI']);
1430 $this->elementEnd('hash');
1431 $this->endDocument('xml');
1434 if (!isset($this->callback)) {
1435 header("HTTP/1.1 {$code} {$status_string}");
1437 $this->initDocument('json');
1438 $error_array = array('error' => $msg, 'request' => $_SERVER['REQUEST_URI']);
1439 $this->text(json_encode($error_array));
1440 $this->endDocument('json');
1443 header("HTTP/1.1 {$code} {$status_string}");
1444 header('Content-Type: text/plain; charset=utf-8');
1448 throw new ClientException($msg, $code);
1454 * If not logged in, take appropriate action (redir or exception)
1456 * @param boolean $redir Redirect to login if not logged in
1458 * @return boolean true if logged in (never returns if not)
1460 public function checkLogin($redir=true)
1462 if (common_logged_in()) {
1467 common_set_returnto($_SERVER['REQUEST_URI']);
1468 common_redirect(common_local_url('login'));
1471 // TRANS: Error message displayed when trying to perform an action that requires a logged in user.
1472 $this->clientError(_('Not logged in.'), 403);
1476 * Returns the current URL
1478 * @return string current URL
1482 list($action, $args) = $this->returnToArgs();
1483 return common_local_url($action, $args);
1487 * Returns arguments sufficient for re-constructing URL
1489 * @return array two elements: action, other args
1491 function returnToArgs()
1493 $action = $this->trimmed('action');
1494 $args = $this->args;
1495 unset($args['action']);
1496 if (common_config('site', 'fancy')) {
1499 if (array_key_exists('submit', $args)) {
1500 unset($args['submit']);
1502 foreach (array_keys($_COOKIE) as $cookie) {
1503 unset($args[$cookie]);
1505 return array($action, $args);
1509 * Generate a menu item
1511 * @param string $url menu URL
1512 * @param string $text menu name
1513 * @param string $title title attribute, null by default
1514 * @param boolean $is_selected current menu item, false by default
1515 * @param string $id element id, null by default
1519 function menuItem($url, $text, $title=null, $is_selected=false, $id=null, $class=null)
1521 // Added @id to li for some control.
1522 // XXX: We might want to move this to htmloutputter.php
1525 if ($class !== null) {
1526 $classes[] = trim($class);
1529 $classes[] = 'current';
1532 if (!empty($classes)) {
1533 $lattrs['class'] = implode(' ', $classes);
1536 if (!is_null($id)) {
1537 $lattrs['id'] = $id;
1540 $this->elementStart('li', $lattrs);
1541 $attrs['href'] = $url;
1543 $attrs['title'] = $title;
1545 $this->element('a', $attrs, $text);
1546 $this->elementEnd('li');
1550 * Generate pagination links
1552 * @param boolean $have_before is there something before?
1553 * @param boolean $have_after is there something after?
1554 * @param integer $page current page
1555 * @param string $action current action
1556 * @param array $args rest of query arguments
1560 // XXX: The messages in this pagination method only tailor to navigating
1561 // notices. In other lists, "Previous"/"Next" type navigation is
1562 // desirable, but not available.
1563 function pagination($have_before, $have_after, $page, $action, $args=null)
1565 // Does a little before-after block for next/prev page
1566 if ($have_before || $have_after) {
1567 $this->elementStart('ul', array('class' => 'nav',
1568 'id' => 'pagination'));
1571 $pargs = array('page' => $page-1);
1572 $this->elementStart('li', array('class' => 'nav_prev'));
1573 $this->element('a', array('href' => common_local_url($action, $args, $pargs),
1575 // TRANS: Pagination message to go to a page displaying information more in the
1576 // TRANS: present than the currently displayed information.
1578 $this->elementEnd('li');
1581 $pargs = array('page' => $page+1);
1582 $this->elementStart('li', array('class' => 'nav_next'));
1583 $this->element('a', array('href' => common_local_url($action, $args, $pargs),
1585 // TRANS: Pagination message to go to a page displaying information more in the
1586 // TRANS: past than the currently displayed information.
1588 $this->elementEnd('li');
1590 if ($have_before || $have_after) {
1591 $this->elementEnd('ul');
1596 * An array of feeds for this action.
1598 * Returns an array of potential feeds for this action.
1600 * @return array Feed object to show in head and links
1608 * Check the session token.
1610 * Checks that the current form has the correct session token,
1611 * and throw an exception if it does not.
1615 // XXX: Finding this type of check with the same message about 50 times.
1616 // Possible to refactor?
1617 function checkSessionToken()
1620 $token = $this->trimmed('token');
1621 if (empty($token) || $token != common_session_token()) {
1622 // TRANS: Client error text when there is a problem with the session token.
1623 $this->clientError(_('There was a problem with your session token.'));
1628 * Check if the current request is a POST
1630 * @return boolean true if POST; otherwise false.
1635 return ($_SERVER['REQUEST_METHOD'] == 'POST');