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 if (common_config('site', 'minify')) {
374 $this->script('extlib/jquery.min.js');
375 $this->script('extlib/jquery.form.min.js');
376 $this->script('extlib/jquery-ui/jquery-ui.min.js');
377 $this->script('extlib/jquery.cookie.min.js');
378 $this->inlineScript('if (typeof window.JSON !== "object") { $.getScript("'.common_path('js/extlib/json2.min.js', StatusNet::isHTTPS()).'"); }');
379 $this->script('extlib/jquery.infieldlabel.min.js');
381 $this->script('extlib/jquery.js');
382 $this->script('extlib/jquery.form.js');
383 $this->script('extlib/jquery-ui/jquery-ui.js');
384 $this->script('extlib/jquery.cookie.js');
385 $this->inlineScript('if (typeof window.JSON !== "object") { $.getScript("'.common_path('js/extlib/json2.js', StatusNet::isHTTPS()).'"); }');
386 $this->script('extlib/jquery.infieldlabel.js');
389 Event::handle('EndShowJQueryScripts', array($this));
391 if (Event::handle('StartShowStatusNetScripts', array($this))) {
392 $this->script('util.js');
393 $this->script('xbImportNode.js');
394 $this->script('geometa.js');
396 // This route isn't available in single-user mode.
397 // Not sure why, but it causes errors here.
398 $this->inlineScript('var _peopletagAC = "' .
399 common_local_url('peopletagautocomplete') . '";');
400 $this->showScriptMessages();
401 // Anti-framing code to avoid clickjacking attacks in older browsers.
402 // This will show a blank page if the page is being framed, which is
403 // consistent with the behavior of the 'X-Frame-Options: SAMEORIGIN'
404 // header, which prevents framing in newer browser.
405 if (common_config('javascript', 'bustframes')) {
406 $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 = ""; }; }');
408 Event::handle('EndShowStatusNetScripts', array($this));
410 Event::handle('EndShowScripts', array($this));
415 * Exports a map of localized text strings to JavaScript code.
417 * Plugins can add to what's exported by hooking the StartScriptMessages or EndScriptMessages
418 * events and appending to the array. Try to avoid adding strings that won't be used, as
419 * they'll be added to HTML output.
421 function showScriptMessages()
425 if (Event::handle('StartScriptMessages', array($this, &$messages))) {
426 // Common messages needed for timeline views etc...
428 // TRANS: Localized tooltip for '...' expansion button on overlong remote messages.
429 $messages['showmore_tooltip'] = _m('TOOLTIP', 'Show more');
431 // TRANS: Inline reply form submit button: submits a reply comment.
432 $messages['reply_submit'] = _m('BUTTON', 'Reply');
434 // TRANS: Placeholder text for inline reply form. Clicking in this box will turn it into a mini notice form.
435 $messages['reply_placeholder'] = _m('Write a reply...');
437 $messages = array_merge($messages, $this->getScriptMessages());
439 Event::handle('EndScriptMessages', array($this, &$messages));
442 if (!empty($messages)) {
443 $this->inlineScript('SN.messages=' . json_encode($messages));
450 * If the action will need localizable text strings, export them here like so:
452 * return array('pool_deepend' => _('Deep end'),
453 * 'pool_shallow' => _('Shallow end'));
455 * The exported map will be available via SN.msg() to JS code:
457 * $('#pool').html('<div class="deepend"></div><div class="shallow"></div>');
458 * $('#pool .deepend').text(SN.msg('pool_deepend'));
459 * $('#pool .shallow').text(SN.msg('pool_shallow'));
461 * Exports a map of localized text strings to JavaScript code.
463 * Plugins can add to what's exported on any action by hooking the StartScriptMessages or
464 * EndScriptMessages events and appending to the array. Try to avoid adding strings that won't
465 * be used, as they'll be added to HTML output.
467 function getScriptMessages()
473 * Show OpenSearch headers
477 function showOpenSearch()
479 $this->element('link', array('rel' => 'search',
480 'type' => 'application/opensearchdescription+xml',
481 'href' => common_local_url('opensearch', array('type' => 'people')),
482 'title' => common_config('site', 'name').' People Search'));
483 $this->element('link', array('rel' => 'search', 'type' => 'application/opensearchdescription+xml',
484 'href' => common_local_url('opensearch', array('type' => 'notice')),
485 'title' => common_config('site', 'name').' Notice Search'));
497 $feeds = $this->getFeeds();
500 foreach ($feeds as $feed) {
501 $this->element('link', array('rel' => $feed->rel(),
502 'href' => $feed->url,
503 'type' => $feed->mimeType(),
504 'title' => $feed->title));
516 function showDescription()
518 // does nothing by default
522 * Show extra stuff in <head>.
530 // does nothing by default
536 * Calls template methods
542 $this->elementStart('body', (common_current_user()) ? array('id' => strtolower($this->trimmed('action')),
543 'class' => 'user_in')
544 : array('id' => strtolower($this->trimmed('action'))));
545 $this->elementStart('div', array('id' => 'wrap'));
546 if (Event::handle('StartShowHeader', array($this))) {
549 Event::handle('EndShowHeader', array($this));
553 if (Event::handle('StartShowFooter', array($this))) {
556 Event::handle('EndShowFooter', array($this));
558 $this->elementEnd('div');
559 $this->showScripts();
560 $this->elementEnd('body');
564 * Show header of the page.
566 * Calls template methods
570 function showHeader()
572 $this->elementStart('div', array('id' => 'header'));
574 $this->showPrimaryNav();
575 if (Event::handle('StartShowSiteNotice', array($this))) {
576 $this->showSiteNotice();
578 Event::handle('EndShowSiteNotice', array($this));
581 $this->elementEnd('div');
585 * Show configured logo.
591 $this->elementStart('address', array('id' => 'site_contact',
592 'class' => 'vcard'));
593 if (Event::handle('StartAddressData', array($this))) {
594 if (common_config('singleuser', 'enabled')) {
595 $user = User::singleUser();
596 $url = common_local_url('showstream',
597 array('nickname' => $user->nickname));
598 } else if (common_logged_in()) {
599 $cur = common_current_user();
600 $url = common_local_url('all', array('nickname' => $cur->nickname));
602 $url = common_local_url('public');
605 $this->elementStart('a', array('class' => 'url home bookmark',
608 if (StatusNet::isHTTPS()) {
609 $logoUrl = common_config('site', 'ssllogo');
610 if (empty($logoUrl)) {
611 // if logo is an uploaded file, try to fall back to HTTPS file URL
612 $httpUrl = common_config('site', 'logo');
613 if (!empty($httpUrl)) {
614 $f = File::getKV('url', $httpUrl);
615 if (!empty($f) && !empty($f->filename)) {
616 // this will handle the HTTPS case
617 $logoUrl = File::url($f->filename);
622 $logoUrl = common_config('site', 'logo');
625 if (empty($logoUrl) && file_exists(Theme::file('logo.png'))) {
626 // This should handle the HTTPS case internally
627 $logoUrl = Theme::path('logo.png');
630 if (!empty($logoUrl)) {
631 $this->element('img', array('class' => 'logo photo',
633 'alt' => common_config('site', 'name')));
637 $this->element('span', array('class' => 'fn org'), common_config('site', 'name'));
638 $this->elementEnd('a');
640 Event::handle('EndAddressData', array($this));
642 $this->elementEnd('address');
646 * Show primary navigation.
650 function showPrimaryNav()
652 $this->elementStart('div', array('id' => 'site_nav_global_primary'));
654 $user = common_current_user();
656 if (!empty($user) || !common_config('site', 'private')) {
657 $form = new SearchForm($this);
661 $pn = new PrimaryNav($this);
663 $this->elementEnd('div');
671 function showSiteNotice()
673 // Revist. Should probably do an hAtom pattern here
674 $text = common_config('site', 'notice');
676 $this->elementStart('div', array('id' => 'site_notice',
677 'class' => 'system_notice'));
679 $this->elementEnd('div');
686 * MAY overload if no notice form needed... or direct message box????
690 function showNoticeForm()
692 // TRANS: Tab on the notice form.
693 $tabs = array('status' => _m('TAB','Status'));
695 $this->elementStart('div', 'input_forms');
697 if (Event::handle('StartShowEntryForms', array(&$tabs))) {
698 $this->elementStart('ul', array('class' => 'nav',
699 'id' => 'input_form_nav'));
701 foreach ($tabs as $tag => $title) {
702 $attrs = array('id' => 'input_form_nav_'.$tag,
703 'class' => 'input_form_nav_tab');
705 if ($tag == 'status') {
706 // We're actually showing the placeholder form,
707 // but we special-case the 'Status' tab as if
708 // it were a small version of it.
709 $attrs['class'] .= ' current';
711 $this->elementStart('li', $attrs);
714 array('href' => 'javascript:SN.U.switchInputFormTab("'.$tag.'")'),
716 $this->elementEnd('li');
719 $this->elementEnd('ul');
721 $attrs = array('class' => 'input_form current',
722 'id' => 'input_form_placeholder');
723 $this->elementStart('div', $attrs);
724 $form = new NoticePlaceholderForm($this);
726 $this->elementEnd('div');
728 foreach ($tabs as $tag => $title) {
729 $attrs = array('class' => 'input_form',
730 'id' => 'input_form_'.$tag);
732 $this->elementStart('div', $attrs);
736 if (Event::handle('StartMakeEntryForm', array($tag, $this, &$form))) {
737 if ($tag == 'status') {
738 $options = $this->noticeFormOptions();
739 $form = new NoticeForm($this, $options);
741 Event::handle('EndMakeEntryForm', array($tag, $this, $form));
748 $this->elementEnd('div');
752 $this->elementEnd('div');
755 function noticeFormOptions()
761 * Show anonymous message.
767 function showAnonymousMessage()
769 // needs to be defined by the class
775 * Shows local navigation, content block and aside.
781 $this->elementStart('div', array('id' => 'core'));
782 $this->elementStart('div', array('id' => 'aside_primary_wrapper'));
783 $this->elementStart('div', array('id' => 'content_wrapper'));
784 $this->elementStart('div', array('id' => 'site_nav_local_views_wrapper'));
785 if (Event::handle('StartShowLocalNavBlock', array($this))) {
786 $this->showLocalNavBlock();
788 Event::handle('EndShowLocalNavBlock', array($this));
790 if (Event::handle('StartShowContentBlock', array($this))) {
791 $this->showContentBlock();
793 Event::handle('EndShowContentBlock', array($this));
795 if (Event::handle('StartShowAside', array($this))) {
798 Event::handle('EndShowAside', array($this));
800 $this->elementEnd('div');
801 $this->elementEnd('div');
802 $this->elementEnd('div');
803 $this->elementEnd('div');
807 * Show local navigation block.
811 function showLocalNavBlock()
813 // Need to have this ID for CSS; I'm too lazy to add it to
815 $this->elementStart('div', array('id' => 'site_nav_local_views'));
816 // Cheat cheat cheat!
817 $this->showLocalNav();
818 $this->elementEnd('div');
822 * If there's a logged-in user, show a bit of login context
826 function showProfileBlock()
828 if (common_logged_in()) {
829 $block = new DefaultProfileBlock($this);
835 * Show local navigation.
841 function showLocalNav()
843 $nav = new DefaultLocalNav($this);
848 * Show menu for an object (group, profile)
850 * This block will only show if a subclass has overridden
851 * the showObjectNav() method.
855 function showObjectNavBlock()
857 $rmethod = new ReflectionMethod($this, 'showObjectNav');
858 $dclass = $rmethod->getDeclaringClass()->getName();
860 if ($dclass != 'Action') {
861 // Need to have this ID for CSS; I'm too lazy to add it to
863 $this->elementStart('div', array('id' => 'site_nav_object',
864 'class' => 'section'));
865 $this->showObjectNav();
866 $this->elementEnd('div');
871 * Show object navigation.
873 * If there are things to do with this object, show it here.
877 function showObjectNav()
883 * Show content block.
887 function showContentBlock()
889 $this->elementStart('div', array('id' => 'content'));
890 if (common_logged_in()) {
891 if (Event::handle('StartShowNoticeForm', array($this))) {
892 $this->showNoticeForm();
893 Event::handle('EndShowNoticeForm', array($this));
896 if (Event::handle('StartShowPageTitle', array($this))) {
897 $this->showPageTitle();
898 Event::handle('EndShowPageTitle', array($this));
900 $this->showPageNoticeBlock();
901 $this->elementStart('div', array('id' => 'content_inner'));
902 // show the actual content (forms, lists, whatever)
903 $this->showContent();
904 $this->elementEnd('div');
905 $this->elementEnd('div');
913 function showPageTitle()
915 $this->element('h1', null, $this->title());
919 * Show page notice block.
921 * Only show the block if a subclassed action has overrided
922 * Action::showPageNotice(), or an event handler is registered for
923 * the StartShowPageNotice event, in which case we assume the
924 * 'page_notice' definition list is desired. This is to prevent
925 * empty 'page_notice' definition lists from being output everywhere.
929 function showPageNoticeBlock()
931 $rmethod = new ReflectionMethod($this, 'showPageNotice');
932 $dclass = $rmethod->getDeclaringClass()->getName();
934 if ($dclass != 'Action' || Event::hasHandler('StartShowPageNotice')) {
936 $this->elementStart('div', array('id' => 'page_notice',
937 'class' => 'system_notice'));
938 if (Event::handle('StartShowPageNotice', array($this))) {
939 $this->showPageNotice();
940 Event::handle('EndShowPageNotice', array($this));
942 $this->elementEnd('div');
949 * SHOULD overload (unless there's not a notice)
953 function showPageNotice()
960 * MUST overload (unless there's not a notice)
964 function showContent()
975 $this->elementStart('div', array('id' => 'aside_primary',
976 'class' => 'aside'));
977 $this->showProfileBlock();
978 if (Event::handle('StartShowObjectNavBlock', array($this))) {
979 $this->showObjectNavBlock();
980 Event::handle('EndShowObjectNavBlock', array($this));
982 if (Event::handle('StartShowSections', array($this))) {
983 $this->showSections();
984 Event::handle('EndShowSections', array($this));
986 if (Event::handle('StartShowExportData', array($this))) {
987 $this->showExportData();
988 Event::handle('EndShowExportData', array($this));
990 $this->elementEnd('div');
994 * Show export data feeds.
998 function showExportData()
1000 $feeds = $this->getFeeds();
1002 $fl = new FeedList($this);
1014 function showSections()
1016 // for each section, show it
1024 function showFooter()
1026 $this->elementStart('div', array('id' => 'footer'));
1027 if (Event::handle('StartShowInsideFooter', array($this))) {
1028 $this->showSecondaryNav();
1029 $this->showLicenses();
1030 Event::handle('EndShowInsideFooter', array($this));
1032 $this->elementEnd('div');
1036 * Show secondary navigation.
1040 function showSecondaryNav()
1042 $sn = new SecondaryNav($this);
1051 function showLicenses()
1053 $this->showGNUsocialLicense();
1054 $this->showContentLicense();
1058 * Show GNU social license.
1062 function showGNUsocialLicense()
1064 if (common_config('site', 'broughtby')) {
1065 // TRANS: First sentence of the GNU social site license. Used if 'broughtby' is set.
1066 // TRANS: Text between [] is a link description, text between () is the link itself.
1067 // TRANS: Make sure there is no whitespace between "]" and "(".
1068 // TRANS: "%%site.broughtby%%" is the value of the variable site.broughtby
1069 $instr = _('**%%site.name%%** is a social network, courtesy of [%%site.broughtby%%](%%site.broughtbyurl%%).');
1071 // TRANS: First sentence of the GNU social site license. Used if 'broughtby' is not set.
1072 $instr = _('**%%site.name%%** is a social network.');
1075 // TRANS: Second sentence of the GNU social site license. Mentions the GNU social source code license.
1076 // TRANS: Make sure there is no whitespace between "]" and "(".
1077 // TRANS: [%1$s](%2$s) is a link description followed by the link itself
1078 // TRANS: %3$s is the version of GNU social that is being used.
1079 $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);
1080 $output = common_markup_to_html($instr);
1081 $this->raw($output);
1086 * Show content license.
1090 function showContentLicense()
1092 if (Event::handle('StartShowContentLicense', array($this))) {
1093 switch (common_config('license', 'type')) {
1095 // TRANS: Content license displayed when license is set to 'private'.
1096 // TRANS: %1$s is the site name.
1097 $this->element('p', null, sprintf(_('Content and data of %1$s are private and confidential.'),
1098 common_config('site', 'name')));
1100 case 'allrightsreserved':
1101 if (common_config('license', 'owner')) {
1102 // TRANS: Content license displayed when license is set to 'allrightsreserved'.
1103 // TRANS: %1$s is the copyright owner.
1104 $this->element('p', null, sprintf(_('Content and data copyright by %1$s. All rights reserved.'),
1105 common_config('license', 'owner')));
1107 // TRANS: Content license displayed when license is set to 'allrightsreserved' and no owner is set.
1108 $this->element('p', null, _('Content and data copyright by contributors. All rights reserved.'));
1111 case 'cc': // fall through
1113 $this->elementStart('p');
1115 $image = common_config('license', 'image');
1116 $sslimage = common_config('license', 'sslimage');
1118 if (StatusNet::isHTTPS()) {
1119 if (!empty($sslimage)) {
1121 } else if (preg_match('#^http://i.creativecommons.org/#', $image)) {
1122 // CC support HTTPS on their images
1123 $url = preg_replace('/^http/', 'https', $image);
1125 // Better to show mixed content than no content
1132 $this->element('img', array('id' => 'license_cc',
1134 'alt' => common_config('license', 'title'),
1138 // TRANS: license message in footer.
1139 // TRANS: %1$s is the site name, %2$s is a link to the license URL, with a licence name set in configuration.
1140 $notice = _('All %1$s content and data are available under the %2$s license.');
1141 $link = "<a class=\"license\" rel=\"external license\" href=\"" .
1142 htmlspecialchars(common_config('license', 'url')) .
1144 htmlspecialchars(common_config('license', 'title')) .
1146 $this->raw(sprintf(htmlspecialchars($notice),
1147 htmlspecialchars(common_config('site', 'name')),
1149 $this->elementEnd('p');
1153 Event::handle('EndShowContentLicense', array($this));
1158 * Return last modified, if applicable.
1162 * @return string last modified http header
1164 function lastModified()
1166 // For comparison with If-Last-Modified
1167 // If not applicable, return null
1172 * Return etag, if applicable.
1176 * @return string etag http header
1184 * Return true if read only.
1188 * @param array $args other arguments
1190 * @return boolean is read only action?
1192 function isReadOnly($args)
1198 * Returns query argument or default value if not found
1200 * @param string $key requested argument
1201 * @param string $def default value to return if $key is not provided
1203 * @return boolean is read only action?
1205 function arg($key, $def=null)
1207 if (array_key_exists($key, $this->args)) {
1208 return $this->args[$key];
1215 * Returns trimmed query argument or default value if not found
1217 * @param string $key requested argument
1218 * @param string $def default value to return if $key is not provided
1220 * @return boolean is read only action?
1222 function trimmed($key, $def=null)
1224 $arg = $this->arg($key, $def);
1225 return is_string($arg) ? trim($arg) : $arg;
1231 * @return boolean is read only action?
1233 protected function handle()
1235 header('Vary: Accept-Encoding,Cookie');
1237 $lm = $this->lastModified();
1238 $etag = $this->etag();
1241 header('ETag: ' . $etag);
1245 header('Last-Modified: ' . date(DATE_RFC1123, $lm));
1246 if ($this->isCacheable()) {
1247 header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', 0 ) . ' GMT' );
1248 header( "Cache-Control: private, must-revalidate, max-age=0" );
1255 $if_none_match = (array_key_exists('HTTP_IF_NONE_MATCH', $_SERVER)) ?
1256 $_SERVER['HTTP_IF_NONE_MATCH'] : null;
1257 if ($if_none_match) {
1258 // If this check fails, ignore the if-modified-since below.
1260 if ($this->_hasEtag($etag, $if_none_match)) {
1261 header('HTTP/1.1 304 Not Modified');
1262 // Better way to do this?
1268 if (!$checked && $lm && array_key_exists('HTTP_IF_MODIFIED_SINCE', $_SERVER)) {
1269 $if_modified_since = $_SERVER['HTTP_IF_MODIFIED_SINCE'];
1270 $ims = strtotime($if_modified_since);
1272 header('HTTP/1.1 304 Not Modified');
1273 // Better way to do this?
1280 * Is this action cacheable?
1282 * If the action returns a last-modified
1284 * @param array $argarray is ignored since it's now passed in in prepare()
1286 * @return boolean is read only action?
1288 function isCacheable()
1294 * Has etag? (private)
1296 * @param string $etag etag http header
1297 * @param string $if_none_match ifNoneMatch http header
1301 function _hasEtag($etag, $if_none_match)
1303 $etags = explode(',', $if_none_match);
1304 return in_array($etag, $etags) || in_array('*', $etags);
1308 * Boolean understands english (yes, no, true, false)
1310 * @param string $key query key we're interested in
1311 * @param string $def default value
1313 * @return boolean interprets yes/no strings as boolean
1315 function boolean($key, $def=false)
1317 $arg = strtolower($this->trimmed($key));
1319 if (is_null($arg)) {
1321 } else if (in_array($arg, array('true', 'yes', '1', 'on'))) {
1323 } else if (in_array($arg, array('false', 'no', '0'))) {
1331 * Integer value of an argument
1333 * @param string $key query key we're interested in
1334 * @param string $defValue optional default value (default null)
1335 * @param string $maxValue optional max value (default null)
1336 * @param string $minValue optional min value (default null)
1338 * @return integer integer value
1340 function int($key, $defValue=null, $maxValue=null, $minValue=null)
1342 $arg = strtolower($this->trimmed($key));
1344 if (is_null($arg) || !is_integer($arg)) {
1348 if (!is_null($maxValue)) {
1349 $arg = min($arg, $maxValue);
1352 if (!is_null($minValue)) {
1353 $arg = max($arg, $minValue);
1362 * @param string $msg error message to display
1363 * @param integer $code http error code, 500 by default
1367 function serverError($msg, $code=500, $format=null)
1369 if ($format === null) {
1370 $format = $this->format;
1373 common_debug("Server error '{$code}' on '{$this->action}': {$msg}", __FILE__);
1375 if (!array_key_exists($code, ServerErrorAction::$status)) {
1379 $status_string = ServerErrorAction::$status[$code];
1383 header("HTTP/1.1 {$code} {$status_string}");
1384 $this->initDocument('xml');
1385 $this->elementStart('hash');
1386 $this->element('error', null, $msg);
1387 $this->element('request', null, $_SERVER['REQUEST_URI']);
1388 $this->elementEnd('hash');
1389 $this->endDocument('xml');
1392 if (!isset($this->callback)) {
1393 header("HTTP/1.1 {$code} {$status_string}");
1395 $this->initDocument('json');
1396 $error_array = array('error' => $msg, 'request' => $_SERVER['REQUEST_URI']);
1397 print(json_encode($error_array));
1398 $this->endDocument('json');
1401 throw new ServerException($msg, $code);
1410 * @param string $msg error message to display
1411 * @param integer $code http error code, 400 by default
1412 * @param string $format error format (json, xml, text) for ApiAction
1415 * @throws ClientException always
1417 function clientError($msg, $code=400, $format=null)
1419 // $format is currently only relevant for an ApiAction anyway
1420 if ($format === null) {
1421 $format = $this->format;
1424 common_debug("User error '{$code}' on '{$this->action}': {$msg}", __FILE__);
1426 if (!array_key_exists($code, ClientErrorAction::$status)) {
1430 $status_string = ClientErrorAction::$status[$code];
1434 header("HTTP/1.1 {$code} {$status_string}");
1435 $this->initDocument('xml');
1436 $this->elementStart('hash');
1437 $this->element('error', null, $msg);
1438 $this->element('request', null, $_SERVER['REQUEST_URI']);
1439 $this->elementEnd('hash');
1440 $this->endDocument('xml');
1443 if (!isset($this->callback)) {
1444 header("HTTP/1.1 {$code} {$status_string}");
1446 $this->initDocument('json');
1447 $error_array = array('error' => $msg, 'request' => $_SERVER['REQUEST_URI']);
1448 $this->text(json_encode($error_array));
1449 $this->endDocument('json');
1452 header("HTTP/1.1 {$code} {$status_string}");
1453 header('Content-Type: text/plain; charset=utf-8');
1457 throw new ClientException($msg, $code);
1463 * If not logged in, take appropriate action (redir or exception)
1465 * @param boolean $redir Redirect to login if not logged in
1467 * @return boolean true if logged in (never returns if not)
1469 public function checkLogin($redir=true)
1471 if (common_logged_in()) {
1476 common_set_returnto($_SERVER['REQUEST_URI']);
1477 common_redirect(common_local_url('login'));
1480 // TRANS: Error message displayed when trying to perform an action that requires a logged in user.
1481 $this->clientError(_('Not logged in.'), 403);
1485 * Returns the current URL
1487 * @return string current URL
1491 list($action, $args) = $this->returnToArgs();
1492 return common_local_url($action, $args);
1496 * Returns arguments sufficient for re-constructing URL
1498 * @return array two elements: action, other args
1500 function returnToArgs()
1502 $action = $this->trimmed('action');
1503 $args = $this->args;
1504 unset($args['action']);
1505 if (common_config('site', 'fancy')) {
1508 if (array_key_exists('submit', $args)) {
1509 unset($args['submit']);
1511 foreach (array_keys($_COOKIE) as $cookie) {
1512 unset($args[$cookie]);
1514 return array($action, $args);
1518 * Generate a menu item
1520 * @param string $url menu URL
1521 * @param string $text menu name
1522 * @param string $title title attribute, null by default
1523 * @param boolean $is_selected current menu item, false by default
1524 * @param string $id element id, null by default
1528 function menuItem($url, $text, $title=null, $is_selected=false, $id=null, $class=null)
1530 // Added @id to li for some control.
1531 // XXX: We might want to move this to htmloutputter.php
1534 if ($class !== null) {
1535 $classes[] = trim($class);
1538 $classes[] = 'current';
1541 if (!empty($classes)) {
1542 $lattrs['class'] = implode(' ', $classes);
1545 if (!is_null($id)) {
1546 $lattrs['id'] = $id;
1549 $this->elementStart('li', $lattrs);
1550 $attrs['href'] = $url;
1552 $attrs['title'] = $title;
1554 $this->element('a', $attrs, $text);
1555 $this->elementEnd('li');
1559 * Generate pagination links
1561 * @param boolean $have_before is there something before?
1562 * @param boolean $have_after is there something after?
1563 * @param integer $page current page
1564 * @param string $action current action
1565 * @param array $args rest of query arguments
1569 // XXX: The messages in this pagination method only tailor to navigating
1570 // notices. In other lists, "Previous"/"Next" type navigation is
1571 // desirable, but not available.
1572 function pagination($have_before, $have_after, $page, $action, $args=null)
1574 // Does a little before-after block for next/prev page
1575 if ($have_before || $have_after) {
1576 $this->elementStart('ul', array('class' => 'nav',
1577 'id' => 'pagination'));
1580 $pargs = array('page' => $page-1);
1581 $this->elementStart('li', array('class' => 'nav_prev'));
1582 $this->element('a', array('href' => common_local_url($action, $args, $pargs),
1584 // TRANS: Pagination message to go to a page displaying information more in the
1585 // TRANS: present than the currently displayed information.
1587 $this->elementEnd('li');
1590 $pargs = array('page' => $page+1);
1591 $this->elementStart('li', array('class' => 'nav_next'));
1592 $this->element('a', array('href' => common_local_url($action, $args, $pargs),
1594 // TRANS: Pagination message to go to a page displaying information more in the
1595 // TRANS: past than the currently displayed information.
1597 $this->elementEnd('li');
1599 if ($have_before || $have_after) {
1600 $this->elementEnd('ul');
1605 * An array of feeds for this action.
1607 * Returns an array of potential feeds for this action.
1609 * @return array Feed object to show in head and links
1617 * Check the session token.
1619 * Checks that the current form has the correct session token,
1620 * and throw an exception if it does not.
1624 // XXX: Finding this type of check with the same message about 50 times.
1625 // Possible to refactor?
1626 function checkSessionToken()
1629 $token = $this->trimmed('token');
1630 if (empty($token) || $token != common_session_token()) {
1631 // TRANS: Client error text when there is a problem with the session token.
1632 $this->clientError(_('There was a problem with your session token.'));
1637 * Check if the current request is a POST
1639 * @return boolean true if POST; otherwise false.
1644 return ($_SERVER['REQUEST_METHOD'] == 'POST');