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; // implies canPost if true
62 protected $canPost = false; // can this action handle POST method?
64 // The currently scoped profile (normally Profile::current; from $this->auth_user for API)
65 protected $scoped = null;
67 // Related to front-end user representation
68 protected $format = null;
69 protected $error = null;
70 protected $msg = null;
75 * Just wraps the HTMLOutputter constructor.
77 * @param string $output URI to output to, default = stdout
78 * @param boolean $indent Whether to indent output, default true
80 * @see XMLOutputter::__construct
81 * @see HTMLOutputter::__construct
83 function __construct($output='php://output', $indent=null)
85 parent::__construct($output, $indent);
98 public function handleError($e)
100 if ($e instanceof ClientException) {
101 $this->clientError($e->getMessage(), $e->getCode());
102 } elseif ($e instanceof ServerException) {
103 $this->serverError($e->getMessage(), $e->getCode());
105 // If it wasn't specified more closely which kind of exception it was
106 $this->serverError($e->getMessage(), 500);
110 static public function run(array $args=array(), $output='php://output', $indent=null) {
111 $class = get_called_class();
112 $action = new $class($output, $indent);
113 set_exception_handler(array($action, 'handleError'));
114 $action->execute($args);
118 public function execute(array $args=array()) {
120 if (common_config('db', 'mirror') && $this->isReadOnly($args)) {
121 if (is_array(common_config('db', 'mirror'))) {
122 // "load balancing", ha ha
123 $arr = common_config('db', 'mirror');
124 $k = array_rand($arr);
127 $mirror = common_config('db', 'mirror');
130 // everyone else uses the mirror
131 common_config_set('db', 'database', $mirror);
134 if (Event::handle('StartActionExecute', array($this, &$args))) {
135 $prepared = $this->prepare($args);
137 $this->handle($args);
139 common_debug('Prepare failed for Action.');
143 Event::handle('EndActionExecute', array($this));
148 * For initializing members of the class.
150 * @param array $argarray misc. arguments
152 * @return boolean true
154 protected function prepare(array $args=array())
156 if ($this->needPost && !$this->isPost()) {
157 // TRANS: Client error. POST is a HTTP command. It should not be translated.
158 $this->clientError(_('This method requires a POST.'), 405);
161 // needPost, of course, overrides canPost if true
162 if (!$this->canPost) {
163 $this->canPost = $this->needPost;
166 $this->args = common_copy_args($args);
168 // This could be set with get_called_action and then
169 // chop off 'Action' from the class name. In lower case.
170 $this->action = strtolower($this->trimmed('action'));
172 if ($this->ajax || $this->boolean('ajax')) {
173 // check with GNUsocial::isAjax()
174 GNUsocial::setAjax(true);
177 if ($this->needLogin) {
178 $this->checkLogin(); // if not logged in, this redirs/excepts
181 $this->updateScopedProfile();
186 public function updateScopedProfile()
188 $this->scoped = Profile::current();
189 return $this->scoped;
192 public function getScoped()
194 return ($this->scoped instanceof Profile) ? $this->scoped : null;
197 // Must be run _after_ prepare
198 public function getActionName()
200 return $this->action;
203 public function isAction(array $names)
205 foreach ($names as $class) {
206 // PHP is case insensitive, and we have stuff like ApiUpperCaseAction,
207 // but we at least make a point out of wanting to do stuff case-sensitive.
208 $class = ucfirst($class) . 'Action';
209 if ($this instanceof $class) {
217 * Show page, a template method.
221 public function showPage()
223 if (GNUsocial::isAjax()) {
227 if (Event::handle('StartShowHTML', array($this))) {
230 Event::handle('EndShowHTML', array($this));
232 if (Event::handle('StartShowHead', array($this))) {
235 Event::handle('EndShowHead', array($this));
237 if (Event::handle('StartShowBody', array($this))) {
239 Event::handle('EndShowBody', array($this));
241 if (Event::handle('StartEndHTML', array($this))) {
243 Event::handle('EndEndHTML', array($this));
247 public function showAjax()
249 $this->startHTML('text/xml;charset=utf-8');
250 $this->elementStart('head');
251 // TRANS: Title for conversation page.
252 $this->element('title', null, $this->title());
253 $this->elementEnd('head');
254 $this->elementStart('body');
255 if ($this->getError()) {
256 $this->element('p', array('id'=>'error'), $this->getError());
258 $this->showContent();
260 $this->elementEnd('body');
268 if (isset($_startTime)) {
269 $endTime = microtime(true);
270 $diff = round(($endTime - $_startTime) * 1000);
271 $this->raw("<!-- ${diff}ms -->");
274 return parent::endHTML();
278 * Show head, a template method.
284 // XXX: attributes (profile?)
285 $this->elementStart('head');
286 if (Event::handle('StartShowHeadElements', array($this))) {
287 if (Event::handle('StartShowHeadTitle', array($this))) {
289 Event::handle('EndShowHeadTitle', array($this));
291 $this->showShortcutIcon();
292 $this->showStylesheets();
293 $this->showOpenSearch();
295 $this->showDescription();
297 Event::handle('EndShowHeadElements', array($this));
299 $this->elementEnd('head');
303 * Show title, a template method.
309 $this->element('title', null,
310 // TRANS: Page title. %1$s is the title, %2$s is the site name.
311 sprintf(_('%1$s - %2$s'),
313 common_config('site', 'name')));
317 * Returns the page title
321 * @return string page title
326 // TRANS: Page title for a page without a title set.
327 return _('Untitled page');
331 * Show themed shortcut icon
335 function showShortcutIcon()
337 if (is_readable(INSTALLDIR . '/theme/' . common_config('site', 'theme') . '/favicon.ico')) {
338 $this->element('link', array('rel' => 'shortcut icon',
339 'href' => Theme::path('favicon.ico')));
341 // favicon.ico should be HTTPS if the rest of the page is
342 $this->element('link', array('rel' => 'shortcut icon',
343 'href' => common_path('favicon.ico', GNUsocial::isHTTPS())));
346 if (common_config('site', 'mobile')) {
347 if (is_readable(INSTALLDIR . '/theme/' . common_config('site', 'theme') . '/apple-touch-icon.png')) {
348 $this->element('link', array('rel' => 'apple-touch-icon',
349 'href' => Theme::path('apple-touch-icon.png')));
351 $this->element('link', array('rel' => 'apple-touch-icon',
352 'href' => common_path('apple-touch-icon.png')));
362 function showStylesheets()
364 if (Event::handle('StartShowStyles', array($this))) {
366 // Use old name for StatusNet for compatibility on events
368 if (Event::handle('StartShowStylesheets', array($this))) {
369 $this->primaryCssLink(null, 'screen, projection, tv, print');
370 Event::handle('EndShowStylesheets', array($this));
373 $this->cssLink('js/extlib/jquery-ui/css/smoothness/jquery-ui.css');
375 if (Event::handle('StartShowUAStyles', array($this))) {
376 Event::handle('EndShowUAStyles', array($this));
379 Event::handle('EndShowStyles', array($this));
381 if (common_config('custom_css', 'enabled')) {
382 $css = common_config('custom_css', 'css');
383 if (Event::handle('StartShowCustomCss', array($this, &$css))) {
384 if (trim($css) != '') {
387 Event::handle('EndShowCustomCss', array($this));
393 function primaryCssLink($mainTheme=null, $media=null)
395 $theme = new Theme($mainTheme);
397 // Some themes may have external stylesheets
398 foreach ($theme->getExternals() as $url) {
399 $this->cssLink($url, $mainTheme, $media);
402 // If the currently-selected theme has dependencies on other themes,
403 // we'll need to load their display.css files as well in order.
404 $baseThemes = $theme->getDeps();
405 foreach ($baseThemes as $baseTheme) {
406 $this->cssLink('css/display.css', $baseTheme, $media);
408 $this->cssLink('css/display.css', $mainTheme, $media);
410 // Additional styles for RTL languages
411 if (is_rtl(common_language())) {
412 if (file_exists(Theme::file('css/rtl.css'))) {
413 $this->cssLink('css/rtl.css', $mainTheme, $media);
419 * Show javascript headers
423 function showScripts()
425 if (Event::handle('StartShowScripts', array($this))) {
426 if (Event::handle('StartShowJQueryScripts', array($this))) {
427 $this->script('extlib/jquery.js');
428 $this->script('extlib/jquery.form.js');
429 $this->script('extlib/jquery-ui/jquery-ui.js');
430 $this->script('extlib/jquery.cookie.js');
432 Event::handle('EndShowJQueryScripts', array($this));
434 if (Event::handle('StartShowStatusNetScripts', array($this))) {
435 $this->script('util.js');
436 $this->script('xbImportNode.js');
438 // This route isn't available in single-user mode.
439 // Not sure why, but it causes errors here.
440 $this->inlineScript('var _peopletagAC = "' .
441 common_local_url('peopletagautocomplete') . '";');
442 $this->showScriptMessages();
443 $this->showScriptVariables();
444 // Anti-framing code to avoid clickjacking attacks in older browsers.
445 // This will show a blank page if the page is being framed, which is
446 // consistent with the behavior of the 'X-Frame-Options: SAMEORIGIN'
447 // header, which prevents framing in newer browser.
448 if (common_config('javascript', 'bustframes')) {
449 $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 = ""; }; }');
451 Event::handle('EndShowStatusNetScripts', array($this));
453 Event::handle('EndShowScripts', array($this));
458 * Exports a map of localized text strings to JavaScript code.
460 * Plugins can add to what's exported by hooking the StartScriptMessages or EndScriptMessages
461 * events and appending to the array. Try to avoid adding strings that won't be used, as
462 * they'll be added to HTML output.
464 function showScriptMessages()
468 if (Event::handle('StartScriptMessages', array($this, &$messages))) {
469 // Common messages needed for timeline views etc...
471 // TRANS: Localized tooltip for '...' expansion button on overlong remote messages.
472 $messages['showmore_tooltip'] = _m('TOOLTIP', 'Show more');
473 $messages['popup_close_button'] = _m('TOOLTIP', 'Close popup');
475 $messages = array_merge($messages, $this->getScriptMessages());
477 Event::handle('EndScriptMessages', array($this, &$messages));
480 if (!empty($messages)) {
481 $this->inlineScript('SN.messages=' . json_encode($messages));
487 protected function showScriptVariables()
491 if (Event::handle('StartScriptVariables', array($this, &$vars))) {
492 $vars['urlNewNotice'] = common_local_url('newnotice');
493 $vars['xhrTimeout'] = ini_get('max_execution_time')*1000; // milliseconds
494 Event::handle('EndScriptVariables', array($this, &$vars));
497 $this->inlineScript('SN.V = ' . json_encode($vars) . ';');
503 * If the action will need localizable text strings, export them here like so:
505 * return array('pool_deepend' => _('Deep end'),
506 * 'pool_shallow' => _('Shallow end'));
508 * The exported map will be available via SN.msg() to JS code:
510 * $('#pool').html('<div class="deepend"></div><div class="shallow"></div>');
511 * $('#pool .deepend').text(SN.msg('pool_deepend'));
512 * $('#pool .shallow').text(SN.msg('pool_shallow'));
514 * Exports a map of localized text strings to JavaScript code.
516 * Plugins can add to what's exported on any action by hooking the StartScriptMessages or
517 * EndScriptMessages events and appending to the array. Try to avoid adding strings that won't
518 * be used, as they'll be added to HTML output.
520 function getScriptMessages()
526 * Show OpenSearch headers
530 function showOpenSearch()
532 $this->element('link', array('rel' => 'search',
533 'type' => 'application/opensearchdescription+xml',
534 'href' => common_local_url('opensearch', array('type' => 'people')),
535 'title' => common_config('site', 'name').' People Search'));
536 $this->element('link', array('rel' => 'search', 'type' => 'application/opensearchdescription+xml',
537 'href' => common_local_url('opensearch', array('type' => 'notice')),
538 'title' => common_config('site', 'name').' Notice Search'));
550 foreach ($this->getFeeds() as $feed) {
551 $this->element('link', array('rel' => $feed->rel(),
552 'href' => $feed->url,
553 'type' => $feed->mimeType(),
554 'title' => $feed->title));
565 function showDescription()
567 // does nothing by default
571 * Show extra stuff in <head>.
579 // does nothing by default
585 * Calls template methods
591 $params = array('id' => $this->getActionName());
592 if ($this->scoped instanceof Profile) {
593 $params['class'] = 'user_in';
595 $this->elementStart('body', $params);
596 $this->elementStart('div', array('id' => 'wrap'));
597 if (Event::handle('StartShowHeader', array($this))) {
600 Event::handle('EndShowHeader', array($this));
604 if (Event::handle('StartShowFooter', array($this))) {
607 Event::handle('EndShowFooter', array($this));
609 $this->elementEnd('div');
610 $this->showScripts();
611 $this->elementEnd('body');
615 * Show header of the page.
617 * Calls template methods
621 function showHeader()
623 $this->elementStart('div', array('id' => 'header'));
625 $this->showPrimaryNav();
626 if (Event::handle('StartShowSiteNotice', array($this))) {
627 $this->showSiteNotice();
629 Event::handle('EndShowSiteNotice', array($this));
632 $this->elementEnd('div');
636 * Show configured logo.
642 $this->elementStart('address', array('id' => 'site_contact', 'class' => 'h-card'));
643 if (Event::handle('StartAddressData', array($this))) {
644 if (common_config('singleuser', 'enabled')) {
645 $user = User::singleUser();
646 $url = common_local_url('showstream',
647 array('nickname' => $user->nickname));
648 } else if (common_logged_in()) {
649 $cur = common_current_user();
650 $url = common_local_url('all', array('nickname' => $cur->nickname));
652 $url = common_local_url('public');
655 $this->elementStart('a', array('class' => 'home bookmark',
658 if (GNUsocial::isHTTPS()) {
659 $logoUrl = common_config('site', 'ssllogo');
660 if (empty($logoUrl)) {
661 // if logo is an uploaded file, try to fall back to HTTPS file URL
662 $httpUrl = common_config('site', 'logo');
663 if (!empty($httpUrl)) {
665 $f = File::getByUrl($httpUrl);
666 if (!empty($f->filename)) {
667 // this will handle the HTTPS case
668 $logoUrl = File::url($f->filename);
670 } catch (NoResultException $e) {
676 $logoUrl = common_config('site', 'logo');
679 if (empty($logoUrl) && file_exists(Theme::file('logo.png'))) {
680 // This should handle the HTTPS case internally
681 $logoUrl = Theme::path('logo.png');
684 if (!empty($logoUrl)) {
685 $this->element('img', array('class' => 'logo u-photo p-name',
687 'alt' => common_config('site', 'name')));
690 $this->elementEnd('a');
692 Event::handle('EndAddressData', array($this));
694 $this->elementEnd('address');
698 * Show primary navigation.
702 function showPrimaryNav()
704 $this->elementStart('div', array('id' => 'site_nav_global_primary'));
706 $user = common_current_user();
708 if (!empty($user) || !common_config('site', 'private')) {
709 $form = new SearchForm($this);
713 $pn = new PrimaryNav($this);
715 $this->elementEnd('div');
723 function showSiteNotice()
725 // Revist. Should probably do an hAtom pattern here
726 $text = common_config('site', 'notice');
728 $this->elementStart('div', array('id' => 'site_notice',
729 'class' => 'system_notice'));
731 $this->elementEnd('div');
738 * MAY overload if no notice form needed... or direct message box????
742 function showNoticeForm()
744 // TRANS: Tab on the notice form.
745 $tabs = array('status' => array('title' => _m('TAB','Status'),
746 'href' => common_local_url('newnotice')));
748 $this->elementStart('div', 'input_forms');
750 $this->element('label', array('for'=>'input_form_nav'), _m('TAB', 'Share your:'));
752 if (Event::handle('StartShowEntryForms', array(&$tabs))) {
753 $this->elementStart('ul', array('class' => 'nav',
754 'id' => 'input_form_nav'));
756 foreach ($tabs as $tag => $data) {
757 $tag = htmlspecialchars($tag);
758 $attrs = array('id' => 'input_form_nav_'.$tag,
759 'class' => 'input_form_nav_tab');
761 if ($tag == 'status') {
762 $attrs['class'] .= ' current';
764 $this->elementStart('li', $attrs);
767 array('onclick' => 'return SN.U.switchInputFormTab("'.$tag.'");',
768 'href' => $data['href']),
770 $this->elementEnd('li');
773 $this->elementEnd('ul');
775 foreach ($tabs as $tag => $data) {
776 $attrs = array('class' => 'input_form',
777 'id' => 'input_form_'.$tag);
778 if ($tag == 'status') {
779 $attrs['class'] .= ' current';
782 $this->elementStart('div', $attrs);
786 if (Event::handle('StartMakeEntryForm', array($tag, $this, &$form))) {
787 if ($tag == 'status') {
788 $options = $this->noticeFormOptions();
789 $form = new NoticeForm($this, $options);
791 Event::handle('EndMakeEntryForm', array($tag, $this, $form));
798 $this->elementEnd('div');
802 $this->elementEnd('div');
805 function noticeFormOptions()
811 * Show anonymous message.
817 function showAnonymousMessage()
819 // needs to be defined by the class
825 * Shows local navigation, content block and aside.
831 $this->elementStart('div', array('id' => 'core'));
832 $this->elementStart('div', array('id' => 'aside_primary_wrapper'));
833 $this->elementStart('div', array('id' => 'content_wrapper'));
834 $this->elementStart('div', array('id' => 'site_nav_local_views_wrapper'));
835 if (Event::handle('StartShowLocalNavBlock', array($this))) {
836 $this->showLocalNavBlock();
838 Event::handle('EndShowLocalNavBlock', array($this));
840 if (Event::handle('StartShowContentBlock', array($this))) {
841 $this->showContentBlock();
843 Event::handle('EndShowContentBlock', array($this));
845 if (Event::handle('StartShowAside', array($this))) {
848 Event::handle('EndShowAside', array($this));
850 $this->elementEnd('div');
851 $this->elementEnd('div');
852 $this->elementEnd('div');
853 $this->elementEnd('div');
857 * Show local navigation block.
861 function showLocalNavBlock()
863 // Need to have this ID for CSS; I'm too lazy to add it to
865 $this->elementStart('div', array('id' => 'site_nav_local_views'));
866 // Cheat cheat cheat!
867 $this->showLocalNav();
868 $this->elementEnd('div');
872 * If there's a logged-in user, show a bit of login context
876 function showProfileBlock()
878 if (common_logged_in()) {
879 $block = new DefaultProfileBlock($this);
885 * Show local navigation.
891 function showLocalNav()
893 $nav = new DefaultLocalNav($this);
898 * Show menu for an object (group, profile)
900 * This block will only show if a subclass has overridden
901 * the showObjectNav() method.
905 function showObjectNavBlock()
907 $rmethod = new ReflectionMethod($this, 'showObjectNav');
908 $dclass = $rmethod->getDeclaringClass()->getName();
910 if ($dclass != 'Action') {
911 // Need to have this ID for CSS; I'm too lazy to add it to
913 $this->elementStart('div', array('id' => 'site_nav_object',
914 'class' => 'section'));
915 $this->showObjectNav();
916 $this->elementEnd('div');
921 * Show object navigation.
923 * If there are things to do with this object, show it here.
927 function showObjectNav()
933 * Show content block.
937 function showContentBlock()
939 $this->elementStart('div', array('id' => 'content'));
940 if (common_logged_in()) {
941 if (Event::handle('StartShowNoticeForm', array($this))) {
942 $this->showNoticeForm();
943 Event::handle('EndShowNoticeForm', array($this));
946 if (Event::handle('StartShowPageTitle', array($this))) {
947 $this->showPageTitle();
948 Event::handle('EndShowPageTitle', array($this));
950 $this->showPageNoticeBlock();
951 $this->elementStart('div', array('id' => 'content_inner'));
952 // show the actual content (forms, lists, whatever)
953 $this->showContent();
954 $this->elementEnd('div');
955 $this->elementEnd('div');
963 function showPageTitle()
965 $this->element('h1', null, $this->title());
969 * Show page notice block.
971 * Only show the block if a subclassed action has overrided
972 * Action::showPageNotice(), or an event handler is registered for
973 * the StartShowPageNotice event, in which case we assume the
974 * 'page_notice' definition list is desired. This is to prevent
975 * empty 'page_notice' definition lists from being output everywhere.
979 function showPageNoticeBlock()
981 $rmethod = new ReflectionMethod($this, 'showPageNotice');
982 $dclass = $rmethod->getDeclaringClass()->getName();
984 if ($dclass != 'Action' || Event::hasHandler('StartShowPageNotice')) {
986 $this->elementStart('div', array('id' => 'page_notice',
987 'class' => 'system_notice'));
988 if (Event::handle('StartShowPageNotice', array($this))) {
989 $this->showPageNotice();
990 Event::handle('EndShowPageNotice', array($this));
992 $this->elementEnd('div');
999 * SHOULD overload (unless there's not a notice)
1003 function showPageNotice()
1010 * MUST overload (unless there's not a notice)
1014 protected function showContent()
1023 function showAside()
1025 $this->elementStart('div', array('id' => 'aside_primary',
1026 'class' => 'aside'));
1027 $this->showProfileBlock();
1028 if (Event::handle('StartShowObjectNavBlock', array($this))) {
1029 $this->showObjectNavBlock();
1030 Event::handle('EndShowObjectNavBlock', array($this));
1032 if (Event::handle('StartShowSections', array($this))) {
1033 $this->showSections();
1034 Event::handle('EndShowSections', array($this));
1036 if (Event::handle('StartShowExportData', array($this))) {
1037 $this->showExportData();
1038 Event::handle('EndShowExportData', array($this));
1040 $this->elementEnd('div');
1044 * Show export data feeds.
1048 function showExportData()
1050 $feeds = $this->getFeeds();
1051 if (!empty($feeds)) {
1052 $fl = new FeedList($this, $feeds);
1064 function showSections()
1066 // for each section, show it
1074 function showFooter()
1076 $this->elementStart('div', array('id' => 'footer'));
1077 if (Event::handle('StartShowInsideFooter', array($this))) {
1078 $this->showSecondaryNav();
1079 $this->showLicenses();
1080 Event::handle('EndShowInsideFooter', array($this));
1082 $this->elementEnd('div');
1086 * Show secondary navigation.
1090 function showSecondaryNav()
1092 $sn = new SecondaryNav($this);
1101 function showLicenses()
1103 $this->showGNUsocialLicense();
1104 $this->showContentLicense();
1108 * Show GNU social license.
1112 function showGNUsocialLicense()
1114 if (common_config('site', 'broughtby')) {
1115 // TRANS: First sentence of the GNU social site license. Used if 'broughtby' is set.
1116 // TRANS: Text between [] is a link description, text between () is the link itself.
1117 // TRANS: Make sure there is no whitespace between "]" and "(".
1118 // TRANS: "%%site.broughtby%%" is the value of the variable site.broughtby
1119 $instr = _('**%%site.name%%** is a social network, courtesy of [%%site.broughtby%%](%%site.broughtbyurl%%).');
1121 // TRANS: First sentence of the GNU social site license. Used if 'broughtby' is not set.
1122 $instr = _('**%%site.name%%** is a social network.');
1125 // TRANS: Second sentence of the GNU social site license. Mentions the GNU social source code license.
1126 // TRANS: Make sure there is no whitespace between "]" and "(".
1127 // TRANS: [%1$s](%2$s) is a link description followed by the link itself
1128 // TRANS: %3$s is the version of GNU social that is being used.
1129 $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);
1130 $output = common_markup_to_html($instr);
1131 $this->raw($output);
1136 * Show content license.
1140 function showContentLicense()
1142 if (Event::handle('StartShowContentLicense', array($this))) {
1143 switch (common_config('license', 'type')) {
1145 // TRANS: Content license displayed when license is set to 'private'.
1146 // TRANS: %1$s is the site name.
1147 $this->element('p', null, sprintf(_('Content and data of %1$s are private and confidential.'),
1148 common_config('site', 'name')));
1150 case 'allrightsreserved':
1151 if (common_config('license', 'owner')) {
1152 // TRANS: Content license displayed when license is set to 'allrightsreserved'.
1153 // TRANS: %1$s is the copyright owner.
1154 $this->element('p', null, sprintf(_('Content and data copyright by %1$s. All rights reserved.'),
1155 common_config('license', 'owner')));
1157 // TRANS: Content license displayed when license is set to 'allrightsreserved' and no owner is set.
1158 $this->element('p', null, _('Content and data copyright by contributors. All rights reserved.'));
1161 case 'cc': // fall through
1163 $this->elementStart('p');
1165 $image = common_config('license', 'image');
1166 $sslimage = common_config('license', 'sslimage');
1168 if (GNUsocial::isHTTPS()) {
1169 if (!empty($sslimage)) {
1171 } else if (preg_match('#^http://i.creativecommons.org/#', $image)) {
1172 // CC support HTTPS on their images
1173 $url = preg_replace('/^http/', 'https', $image, 1);
1175 // Better to show mixed content than no content
1182 $this->element('img', array('id' => 'license_cc',
1184 'alt' => common_config('license', 'title'),
1188 // TRANS: license message in footer.
1189 // TRANS: %1$s is the site name, %2$s is a link to the license URL, with a licence name set in configuration.
1190 $notice = _('All %1$s content and data are available under the %2$s license.');
1191 $link = sprintf('<a class="license" rel="external license" href="%1$s">%2$s</a>',
1192 htmlspecialchars(common_config('license', 'url')),
1193 htmlspecialchars(common_config('license', 'title')));
1194 $this->raw(@sprintf(htmlspecialchars($notice),
1195 htmlspecialchars(common_config('site', 'name')),
1197 $this->elementEnd('p');
1201 Event::handle('EndShowContentLicense', array($this));
1206 * Return last modified, if applicable.
1210 * @return string last modified http header
1212 function lastModified()
1214 // For comparison with If-Last-Modified
1215 // If not applicable, return null
1220 * Return etag, if applicable.
1224 * @return string etag http header
1232 * Return true if read only.
1236 * @param array $args other arguments
1238 * @return boolean is read only action?
1240 function isReadOnly($args)
1246 * Returns query argument or default value if not found
1248 * @param string $key requested argument
1249 * @param string $def default value to return if $key is not provided
1251 * @return boolean is read only action?
1253 function arg($key, $def=null)
1255 if (array_key_exists($key, $this->args)) {
1256 return $this->args[$key];
1263 * Returns trimmed query argument or default value if not found
1265 * @param string $key requested argument
1266 * @param string $def default value to return if $key is not provided
1268 * @return boolean is read only action?
1270 function trimmed($key, $def=null)
1272 $arg = $this->arg($key, $def);
1273 return is_string($arg) ? trim($arg) : $arg;
1279 * @return boolean is read only action?
1281 protected function handle()
1283 header('Vary: Accept-Encoding,Cookie');
1285 $lm = $this->lastModified();
1286 $etag = $this->etag();
1289 header('ETag: ' . $etag);
1293 header('Last-Modified: ' . date(DATE_RFC1123, $lm));
1294 if ($this->isCacheable()) {
1295 header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', 0 ) . ' GMT' );
1296 header( "Cache-Control: private, must-revalidate, max-age=0" );
1303 $if_none_match = (array_key_exists('HTTP_IF_NONE_MATCH', $_SERVER)) ?
1304 $_SERVER['HTTP_IF_NONE_MATCH'] : null;
1305 if ($if_none_match) {
1306 // If this check fails, ignore the if-modified-since below.
1308 if ($this->_hasEtag($etag, $if_none_match)) {
1309 header('HTTP/1.1 304 Not Modified');
1310 // Better way to do this?
1316 if (!$checked && $lm && array_key_exists('HTTP_IF_MODIFIED_SINCE', $_SERVER)) {
1317 $if_modified_since = $_SERVER['HTTP_IF_MODIFIED_SINCE'];
1318 $ims = strtotime($if_modified_since);
1320 header('HTTP/1.1 304 Not Modified');
1321 // Better way to do this?
1328 * Is this action cacheable?
1330 * If the action returns a last-modified
1332 * @param array $argarray is ignored since it's now passed in in prepare()
1334 * @return boolean is read only action?
1336 function isCacheable()
1342 * Has etag? (private)
1344 * @param string $etag etag http header
1345 * @param string $if_none_match ifNoneMatch http header
1349 function _hasEtag($etag, $if_none_match)
1351 $etags = explode(',', $if_none_match);
1352 return in_array($etag, $etags) || in_array('*', $etags);
1356 * Boolean understands english (yes, no, true, false)
1358 * @param string $key query key we're interested in
1359 * @param string $def default value
1361 * @return boolean interprets yes/no strings as boolean
1363 function boolean($key, $def=false)
1365 $arg = strtolower($this->trimmed($key));
1367 if (is_null($arg)) {
1369 } else if (in_array($arg, array('true', 'yes', '1', 'on'))) {
1371 } else if (in_array($arg, array('false', 'no', '0'))) {
1379 * This is a cheap hack to avoid a bug in DB_DataObject
1380 * where '' is non-type-aware compared to 0, which means it
1381 * will always be true for values like false and 0 too...
1384 * https://pear.php.net/bugs/bug.php?id=20291
1386 function booleanintstring($key, $def=false)
1388 return $this->boolean($key, $def) ? '1' : '0';
1392 * Integer value of an argument
1394 * @param string $key query key we're interested in
1395 * @param string $defValue optional default value (default null)
1396 * @param string $maxValue optional max value (default null)
1397 * @param string $minValue optional min value (default null)
1399 * @return integer integer value
1401 function int($key, $defValue=null, $maxValue=null, $minValue=null)
1403 $arg = intval($this->arg($key));
1405 if (!is_numeric($this->arg($key)) || $arg != $this->arg($key)) {
1409 if (!is_null($maxValue)) {
1410 $arg = min($arg, $maxValue);
1413 if (!is_null($minValue)) {
1414 $arg = max($arg, $minValue);
1423 * @param string $msg error message to display
1424 * @param integer $code http error code, 500 by default
1428 function serverError($msg, $code=500, $format=null)
1430 if ($format === null) {
1431 $format = $this->format;
1434 common_debug("Server error '{$code}' on '{$this->action}': {$msg}", __FILE__);
1436 if (!array_key_exists($code, ServerErrorAction::$status)) {
1440 $status_string = ServerErrorAction::$status[$code];
1444 header("HTTP/1.1 {$code} {$status_string}");
1445 $this->initDocument('xml');
1446 $this->elementStart('hash');
1447 $this->element('error', null, $msg);
1448 $this->element('request', null, $_SERVER['REQUEST_URI']);
1449 $this->elementEnd('hash');
1450 $this->endDocument('xml');
1453 if (!isset($this->callback)) {
1454 header("HTTP/1.1 {$code} {$status_string}");
1456 $this->initDocument('json');
1457 $error_array = array('error' => $msg, 'request' => $_SERVER['REQUEST_URI']);
1458 print(json_encode($error_array));
1459 $this->endDocument('json');
1462 common_log(LOG_ERR, 'Handled serverError ('._ve($code).') but cannot output into desired format ('._ve($this->format).'): '._ve($msg));
1463 $action = new ServerErrorAction($msg, $code);
1473 * @param string $msg error message to display
1474 * @param integer $code http error code, 400 by default
1475 * @param string $format error format (json, xml, text) for ApiAction
1478 * @throws ClientException always
1480 function clientError($msg, $code=400, $format=null)
1482 // $format is currently only relevant for an ApiAction anyway
1483 if ($format === null) {
1484 $format = $this->format;
1487 common_debug("User error '{$code}' on '{$this->action}': {$msg}", __FILE__);
1489 if (!array_key_exists($code, ClientErrorAction::$status)) {
1493 $status_string = ClientErrorAction::$status[$code];
1497 header("HTTP/1.1 {$code} {$status_string}");
1498 $this->initDocument('xml');
1499 $this->elementStart('hash');
1500 $this->element('error', null, $msg);
1501 $this->element('request', null, $_SERVER['REQUEST_URI']);
1502 $this->elementEnd('hash');
1503 $this->endDocument('xml');
1506 if (!isset($this->callback)) {
1507 header("HTTP/1.1 {$code} {$status_string}");
1509 $this->initDocument('json');
1510 $error_array = array('error' => $msg, 'request' => $_SERVER['REQUEST_URI']);
1511 print(json_encode($error_array));
1512 $this->endDocument('json');
1515 header("HTTP/1.1 {$code} {$status_string}");
1516 header('Content-Type: text/plain; charset=utf-8');
1520 common_log(LOG_ERR, 'Handled clientError ('._ve($code).') but cannot output into desired format ('._ve($this->format).'): '._ve($msg));
1521 $action = new ClientErrorAction($msg, $code);
1528 * If not logged in, take appropriate action (redir or exception)
1530 * @param boolean $redir Redirect to login if not logged in
1532 * @return boolean true if logged in (never returns if not)
1534 public function checkLogin($redir=true)
1536 if (common_logged_in()) {
1541 common_set_returnto($_SERVER['REQUEST_URI']);
1542 common_redirect(common_local_url('login'));
1545 // TRANS: Error message displayed when trying to perform an action that requires a logged in user.
1546 $this->clientError(_('Not logged in.'), 403);
1550 * Returns the current URL
1552 * @return string current URL
1556 list($action, $args) = $this->returnToArgs();
1557 return common_local_url($action, $args);
1561 * Returns arguments sufficient for re-constructing URL
1563 * @return array two elements: action, other args
1565 function returnToArgs()
1567 $action = $this->getActionName();
1568 $args = $this->args;
1569 unset($args['action']);
1570 if (common_config('site', 'fancy')) {
1573 if (array_key_exists('submit', $args)) {
1574 unset($args['submit']);
1576 foreach (array_keys($_COOKIE) as $cookie) {
1577 unset($args[$cookie]);
1579 return array($action, $args);
1583 * Generate a menu item
1585 * @param string $url menu URL
1586 * @param string $text menu name
1587 * @param string $title title attribute, null by default
1588 * @param boolean $is_selected current menu item, false by default
1589 * @param string $id element id, null by default
1593 function menuItem($url, $text, $title=null, $is_selected=false, $id=null, $class=null)
1595 // Added @id to li for some control.
1596 // XXX: We might want to move this to htmloutputter.php
1599 if ($class !== null) {
1600 $classes[] = trim($class);
1603 $classes[] = 'current';
1606 if (!empty($classes)) {
1607 $lattrs['class'] = implode(' ', $classes);
1610 if (!is_null($id)) {
1611 $lattrs['id'] = $id;
1614 $this->elementStart('li', $lattrs);
1615 $attrs['href'] = $url;
1617 $attrs['title'] = $title;
1619 $this->element('a', $attrs, $text);
1620 $this->elementEnd('li');
1624 * Generate pagination links
1626 * @param boolean $have_before is there something before?
1627 * @param boolean $have_after is there something after?
1628 * @param integer $page current page
1629 * @param string $action current action
1630 * @param array $args rest of query arguments
1634 // XXX: The messages in this pagination method only tailor to navigating
1635 // notices. In other lists, "Previous"/"Next" type navigation is
1636 // desirable, but not available.
1637 function pagination($have_before, $have_after, $page, $action, $args=null)
1639 // Does a little before-after block for next/prev page
1640 if ($have_before || $have_after) {
1641 $this->elementStart('ul', array('class' => 'nav',
1642 'id' => 'pagination'));
1645 $pargs = array('page' => $page-1);
1646 $this->elementStart('li', array('class' => 'nav_prev'));
1647 $this->element('a', array('href' => common_local_url($action, $args, $pargs),
1649 // TRANS: Pagination message to go to a page displaying information more in the
1650 // TRANS: present than the currently displayed information.
1652 $this->elementEnd('li');
1655 $pargs = array('page' => $page+1);
1656 $this->elementStart('li', array('class' => 'nav_next'));
1657 $this->element('a', array('href' => common_local_url($action, $args, $pargs),
1659 // TRANS: Pagination message to go to a page displaying information more in the
1660 // TRANS: past than the currently displayed information.
1662 $this->elementEnd('li');
1664 if ($have_before || $have_after) {
1665 $this->elementEnd('ul');
1670 * An array of feeds for this action.
1672 * Returns an array of potential feeds for this action.
1674 * @return array Feed object to show in head and links
1682 * Check the session token.
1684 * Checks that the current form has the correct session token,
1685 * and throw an exception if it does not.
1689 // XXX: Finding this type of check with the same message about 50 times.
1690 // Possible to refactor?
1691 function checkSessionToken()
1694 $token = $this->trimmed('token');
1695 if (empty($token) || $token != common_session_token()) {
1696 // TRANS: Client error text when there is a problem with the session token.
1697 $this->clientError(_('There was a problem with your session token.'));
1702 * Check if the current request is a POST
1704 * @return boolean true if POST; otherwise false.
1709 return ($_SERVER['REQUEST_METHOD'] == 'POST');