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 static public function run(array $args=array(), $output='php://output', $indent=null) {
99 $class = get_called_class();
100 $action = new $class($output, $indent);
101 $action->execute($args);
105 public function execute(array $args=array()) {
107 if (common_config('db', 'mirror') && $this->isReadOnly($args)) {
108 if (is_array(common_config('db', 'mirror'))) {
109 // "load balancing", ha ha
110 $arr = common_config('db', 'mirror');
111 $k = array_rand($arr);
114 $mirror = common_config('db', 'mirror');
117 // everyone else uses the mirror
118 common_config_set('db', 'database', $mirror);
121 if (Event::handle('StartActionExecute', array($this, &$args))) {
122 $prepared = $this->prepare($args);
124 $this->handle($args);
126 common_debug('Prepare failed for Action.');
130 Event::handle('EndActionExecute', array($this));
135 * For initializing members of the class.
137 * @param array $argarray misc. arguments
139 * @return boolean true
141 protected function prepare(array $args=array())
143 if ($this->needPost && !$this->isPost()) {
144 // TRANS: Client error. POST is a HTTP command. It should not be translated.
145 $this->clientError(_('This method requires a POST.'), 405);
148 // needPost, of course, overrides canPost if true
149 if (!$this->canPost) {
150 $this->canPost = $this->needPost;
153 $this->args = common_copy_args($args);
155 // This could be set with get_called_action and then
156 // chop off 'Action' from the class name. In lower case.
157 $this->action = strtolower($this->trimmed('action'));
159 if ($this->ajax || $this->boolean('ajax')) {
160 // check with GNUsocial::isAjax()
161 GNUsocial::setAjax(true);
164 if ($this->needLogin) {
165 $this->checkLogin(); // if not logged in, this redirs/excepts
168 $this->updateScopedProfile();
173 public function updateScopedProfile()
175 $this->scoped = Profile::current();
176 return $this->scoped;
179 public function getScoped()
181 return ($this->scoped instanceof Profile) ? $this->scoped : null;
184 // Must be run _after_ prepare
185 public function getActionName()
187 return $this->action;
190 public function isAction(array $names)
192 foreach ($names as $class) {
193 // PHP is case insensitive, and we have stuff like ApiUpperCaseAction,
194 // but we at least make a point out of wanting to do stuff case-sensitive.
195 $class = ucfirst($class) . 'Action';
196 if ($this instanceof $class) {
204 * Show page, a template method.
210 if (GNUsocial::isAjax()) {
214 if (Event::handle('StartShowHTML', array($this))) {
217 Event::handle('EndShowHTML', array($this));
219 if (Event::handle('StartShowHead', array($this))) {
222 Event::handle('EndShowHead', array($this));
224 if (Event::handle('StartShowBody', array($this))) {
226 Event::handle('EndShowBody', array($this));
228 if (Event::handle('StartEndHTML', array($this))) {
230 Event::handle('EndEndHTML', array($this));
234 public function showAjax()
236 $this->startHTML('text/xml;charset=utf-8');
237 $this->elementStart('head');
238 // TRANS: Title for conversation page.
239 $this->element('title', null, $this->title());
240 $this->elementEnd('head');
241 $this->elementStart('body');
242 if ($this->getError()) {
243 $this->element('p', array('id'=>'error'), $this->getError());
245 $this->showContent();
247 $this->elementEnd('body');
255 if (isset($_startTime)) {
256 $endTime = microtime(true);
257 $diff = round(($endTime - $_startTime) * 1000);
258 $this->raw("<!-- ${diff}ms -->");
261 return parent::endHTML();
265 * Show head, a template method.
271 // XXX: attributes (profile?)
272 $this->elementStart('head');
273 if (Event::handle('StartShowHeadElements', array($this))) {
274 if (Event::handle('StartShowHeadTitle', array($this))) {
276 Event::handle('EndShowHeadTitle', array($this));
278 $this->showShortcutIcon();
279 $this->showStylesheets();
280 $this->showOpenSearch();
282 $this->showDescription();
284 Event::handle('EndShowHeadElements', array($this));
286 $this->elementEnd('head');
290 * Show title, a template method.
296 $this->element('title', null,
297 // TRANS: Page title. %1$s is the title, %2$s is the site name.
298 sprintf(_('%1$s - %2$s'),
300 common_config('site', 'name')));
304 * Returns the page title
308 * @return string page title
313 // TRANS: Page title for a page without a title set.
314 return _('Untitled page');
318 * Show themed shortcut icon
322 function showShortcutIcon()
324 if (is_readable(INSTALLDIR . '/theme/' . common_config('site', 'theme') . '/favicon.ico')) {
325 $this->element('link', array('rel' => 'shortcut icon',
326 'href' => Theme::path('favicon.ico')));
328 // favicon.ico should be HTTPS if the rest of the page is
329 $this->element('link', array('rel' => 'shortcut icon',
330 'href' => common_path('favicon.ico', GNUsocial::isHTTPS())));
333 if (common_config('site', 'mobile')) {
334 if (is_readable(INSTALLDIR . '/theme/' . common_config('site', 'theme') . '/apple-touch-icon.png')) {
335 $this->element('link', array('rel' => 'apple-touch-icon',
336 'href' => Theme::path('apple-touch-icon.png')));
338 $this->element('link', array('rel' => 'apple-touch-icon',
339 'href' => common_path('apple-touch-icon.png')));
349 function showStylesheets()
351 if (Event::handle('StartShowStyles', array($this))) {
353 // Use old name for StatusNet for compatibility on events
355 if (Event::handle('StartShowStylesheets', array($this))) {
356 $this->primaryCssLink(null, 'screen, projection, tv, print');
357 Event::handle('EndShowStylesheets', array($this));
360 $this->cssLink('js/extlib/jquery-ui/css/smoothness/jquery-ui.css');
362 if (Event::handle('StartShowUAStyles', array($this))) {
363 Event::handle('EndShowUAStyles', array($this));
366 Event::handle('EndShowStyles', array($this));
368 if (common_config('custom_css', 'enabled')) {
369 $css = common_config('custom_css', 'css');
370 if (Event::handle('StartShowCustomCss', array($this, &$css))) {
371 if (trim($css) != '') {
374 Event::handle('EndShowCustomCss', array($this));
380 function primaryCssLink($mainTheme=null, $media=null)
382 $theme = new Theme($mainTheme);
384 // Some themes may have external stylesheets, such as using the
385 // Google Font APIs to load webfonts.
386 foreach ($theme->getExternals() as $url) {
387 $this->cssLink($url, $mainTheme, $media);
390 // If the currently-selected theme has dependencies on other themes,
391 // we'll need to load their display.css files as well in order.
392 $baseThemes = $theme->getDeps();
393 foreach ($baseThemes as $baseTheme) {
394 $this->cssLink('css/display.css', $baseTheme, $media);
396 $this->cssLink('css/display.css', $mainTheme, $media);
398 // Additional styles for RTL languages
399 if (is_rtl(common_language())) {
400 if (file_exists(Theme::file('css/rtl.css'))) {
401 $this->cssLink('css/rtl.css', $mainTheme, $media);
407 * Show javascript headers
411 function showScripts()
413 if (Event::handle('StartShowScripts', array($this))) {
414 if (Event::handle('StartShowJQueryScripts', array($this))) {
415 $this->script('extlib/jquery.js');
416 $this->script('extlib/jquery.form.js');
417 $this->script('extlib/jquery-ui/jquery-ui.js');
418 $this->script('extlib/jquery.cookie.js');
419 $this->inlineScript('if (typeof window.JSON !== "object") { $.getScript("'.common_path('js/extlib/json2.js', GNUsocial::isHTTPS()).'"); }');
421 Event::handle('EndShowJQueryScripts', array($this));
423 if (Event::handle('StartShowStatusNetScripts', array($this))) {
424 $this->script('util.js');
425 $this->script('xbImportNode.js');
426 $this->script('geometa.js');
428 // This route isn't available in single-user mode.
429 // Not sure why, but it causes errors here.
430 $this->inlineScript('var _peopletagAC = "' .
431 common_local_url('peopletagautocomplete') . '";');
432 $this->showScriptMessages();
433 $this->showScriptVariables();
434 // Anti-framing code to avoid clickjacking attacks in older browsers.
435 // This will show a blank page if the page is being framed, which is
436 // consistent with the behavior of the 'X-Frame-Options: SAMEORIGIN'
437 // header, which prevents framing in newer browser.
438 if (common_config('javascript', 'bustframes')) {
439 $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 = ""; }; }');
441 Event::handle('EndShowStatusNetScripts', array($this));
443 Event::handle('EndShowScripts', array($this));
448 * Exports a map of localized text strings to JavaScript code.
450 * Plugins can add to what's exported by hooking the StartScriptMessages or EndScriptMessages
451 * events and appending to the array. Try to avoid adding strings that won't be used, as
452 * they'll be added to HTML output.
454 function showScriptMessages()
458 if (Event::handle('StartScriptMessages', array($this, &$messages))) {
459 // Common messages needed for timeline views etc...
461 // TRANS: Localized tooltip for '...' expansion button on overlong remote messages.
462 $messages['showmore_tooltip'] = _m('TOOLTIP', 'Show more');
464 $messages = array_merge($messages, $this->getScriptMessages());
466 Event::handle('EndScriptMessages', array($this, &$messages));
469 if (!empty($messages)) {
470 $this->inlineScript('SN.messages=' . json_encode($messages));
476 protected function showScriptVariables()
480 if (Event::handle('StartScriptVariables', array($this, &$vars))) {
481 $vars['urlNewNotice'] = common_local_url('newnotice');
484 $this->inlineScript('SN.V = ' . json_encode($vars));
490 * If the action will need localizable text strings, export them here like so:
492 * return array('pool_deepend' => _('Deep end'),
493 * 'pool_shallow' => _('Shallow end'));
495 * The exported map will be available via SN.msg() to JS code:
497 * $('#pool').html('<div class="deepend"></div><div class="shallow"></div>');
498 * $('#pool .deepend').text(SN.msg('pool_deepend'));
499 * $('#pool .shallow').text(SN.msg('pool_shallow'));
501 * Exports a map of localized text strings to JavaScript code.
503 * Plugins can add to what's exported on any action by hooking the StartScriptMessages or
504 * EndScriptMessages events and appending to the array. Try to avoid adding strings that won't
505 * be used, as they'll be added to HTML output.
507 function getScriptMessages()
513 * Show OpenSearch headers
517 function showOpenSearch()
519 $this->element('link', array('rel' => 'search',
520 'type' => 'application/opensearchdescription+xml',
521 'href' => common_local_url('opensearch', array('type' => 'people')),
522 'title' => common_config('site', 'name').' People Search'));
523 $this->element('link', array('rel' => 'search', 'type' => 'application/opensearchdescription+xml',
524 'href' => common_local_url('opensearch', array('type' => 'notice')),
525 'title' => common_config('site', 'name').' Notice Search'));
537 foreach ($this->getFeeds() as $feed) {
538 $this->element('link', array('rel' => $feed->rel(),
539 'href' => $feed->url,
540 'type' => $feed->mimeType(),
541 'title' => $feed->title));
552 function showDescription()
554 // does nothing by default
558 * Show extra stuff in <head>.
566 // does nothing by default
572 * Calls template methods
578 $params = array('id' => $this->getActionName());
579 if ($this->scoped instanceof Profile) {
580 $params['class'] = 'user_in';
582 $this->elementStart('body', $params);
583 $this->elementStart('div', array('id' => 'wrap'));
584 if (Event::handle('StartShowHeader', array($this))) {
587 Event::handle('EndShowHeader', array($this));
591 if (Event::handle('StartShowFooter', array($this))) {
594 Event::handle('EndShowFooter', array($this));
596 $this->elementEnd('div');
597 $this->showScripts();
598 $this->elementEnd('body');
602 * Show header of the page.
604 * Calls template methods
608 function showHeader()
610 $this->elementStart('div', array('id' => 'header'));
612 $this->showPrimaryNav();
613 if (Event::handle('StartShowSiteNotice', array($this))) {
614 $this->showSiteNotice();
616 Event::handle('EndShowSiteNotice', array($this));
619 $this->elementEnd('div');
623 * Show configured logo.
629 $this->elementStart('address', array('id' => 'site_contact', 'class' => 'h-card'));
630 if (Event::handle('StartAddressData', array($this))) {
631 if (common_config('singleuser', 'enabled')) {
632 $user = User::singleUser();
633 $url = common_local_url('showstream',
634 array('nickname' => $user->nickname));
635 } else if (common_logged_in()) {
636 $cur = common_current_user();
637 $url = common_local_url('all', array('nickname' => $cur->nickname));
639 $url = common_local_url('public');
642 $this->elementStart('a', array('class' => 'home bookmark',
645 if (GNUsocial::isHTTPS()) {
646 $logoUrl = common_config('site', 'ssllogo');
647 if (empty($logoUrl)) {
648 // if logo is an uploaded file, try to fall back to HTTPS file URL
649 $httpUrl = common_config('site', 'logo');
650 if (!empty($httpUrl)) {
651 $f = File::getKV('url', $httpUrl);
652 if (!empty($f) && !empty($f->filename)) {
653 // this will handle the HTTPS case
654 $logoUrl = File::url($f->filename);
659 $logoUrl = common_config('site', 'logo');
662 if (empty($logoUrl) && file_exists(Theme::file('logo.png'))) {
663 // This should handle the HTTPS case internally
664 $logoUrl = Theme::path('logo.png');
667 if (!empty($logoUrl)) {
668 $this->element('img', array('class' => 'logo u-photo p-name',
670 'alt' => common_config('site', 'name')));
673 $this->elementEnd('a');
675 Event::handle('EndAddressData', array($this));
677 $this->elementEnd('address');
681 * Show primary navigation.
685 function showPrimaryNav()
687 $this->elementStart('div', array('id' => 'site_nav_global_primary'));
689 $user = common_current_user();
691 if (!empty($user) || !common_config('site', 'private')) {
692 $form = new SearchForm($this);
696 $pn = new PrimaryNav($this);
698 $this->elementEnd('div');
706 function showSiteNotice()
708 // Revist. Should probably do an hAtom pattern here
709 $text = common_config('site', 'notice');
711 $this->elementStart('div', array('id' => 'site_notice',
712 'class' => 'system_notice'));
714 $this->elementEnd('div');
721 * MAY overload if no notice form needed... or direct message box????
725 function showNoticeForm()
727 // TRANS: Tab on the notice form.
728 $tabs = array('status' => array('title' => _m('TAB','Status'),
729 'href' => common_local_url('newnotice')));
731 $this->elementStart('div', 'input_forms');
733 $this->element('label', array('for'=>'input_form_nav'), _m('TAB', 'Share your:'));
735 if (Event::handle('StartShowEntryForms', array(&$tabs))) {
736 $this->elementStart('ul', array('class' => 'nav',
737 'id' => 'input_form_nav'));
739 foreach ($tabs as $tag => $data) {
740 $tag = htmlspecialchars($tag);
741 $attrs = array('id' => 'input_form_nav_'.$tag,
742 'class' => 'input_form_nav_tab');
744 if ($tag == 'status') {
745 $attrs['class'] .= ' current';
747 $this->elementStart('li', $attrs);
750 array('onclick' => 'return SN.U.switchInputFormTab("'.$tag.'");',
751 'href' => $data['href']),
753 $this->elementEnd('li');
756 $this->elementEnd('ul');
758 foreach ($tabs as $tag => $data) {
759 $attrs = array('class' => 'input_form',
760 'id' => 'input_form_'.$tag);
761 if ($tag == 'status') {
762 $attrs['class'] .= ' current';
765 $this->elementStart('div', $attrs);
769 if (Event::handle('StartMakeEntryForm', array($tag, $this, &$form))) {
770 if ($tag == 'status') {
771 $options = $this->noticeFormOptions();
772 $form = new NoticeForm($this, $options);
774 Event::handle('EndMakeEntryForm', array($tag, $this, $form));
781 $this->elementEnd('div');
785 $this->elementEnd('div');
788 function noticeFormOptions()
794 * Show anonymous message.
800 function showAnonymousMessage()
802 // needs to be defined by the class
808 * Shows local navigation, content block and aside.
814 $this->elementStart('div', array('id' => 'core'));
815 $this->elementStart('div', array('id' => 'aside_primary_wrapper'));
816 $this->elementStart('div', array('id' => 'content_wrapper'));
817 $this->elementStart('div', array('id' => 'site_nav_local_views_wrapper'));
818 if (Event::handle('StartShowLocalNavBlock', array($this))) {
819 $this->showLocalNavBlock();
821 Event::handle('EndShowLocalNavBlock', array($this));
823 if (Event::handle('StartShowContentBlock', array($this))) {
824 $this->showContentBlock();
826 Event::handle('EndShowContentBlock', array($this));
828 if (Event::handle('StartShowAside', array($this))) {
831 Event::handle('EndShowAside', array($this));
833 $this->elementEnd('div');
834 $this->elementEnd('div');
835 $this->elementEnd('div');
836 $this->elementEnd('div');
840 * Show local navigation block.
844 function showLocalNavBlock()
846 // Need to have this ID for CSS; I'm too lazy to add it to
848 $this->elementStart('div', array('id' => 'site_nav_local_views'));
849 // Cheat cheat cheat!
850 $this->showLocalNav();
851 $this->elementEnd('div');
855 * If there's a logged-in user, show a bit of login context
859 function showProfileBlock()
861 if (common_logged_in()) {
862 $block = new DefaultProfileBlock($this);
868 * Show local navigation.
874 function showLocalNav()
876 $nav = new DefaultLocalNav($this);
881 * Show menu for an object (group, profile)
883 * This block will only show if a subclass has overridden
884 * the showObjectNav() method.
888 function showObjectNavBlock()
890 $rmethod = new ReflectionMethod($this, 'showObjectNav');
891 $dclass = $rmethod->getDeclaringClass()->getName();
893 if ($dclass != 'Action') {
894 // Need to have this ID for CSS; I'm too lazy to add it to
896 $this->elementStart('div', array('id' => 'site_nav_object',
897 'class' => 'section'));
898 $this->showObjectNav();
899 $this->elementEnd('div');
904 * Show object navigation.
906 * If there are things to do with this object, show it here.
910 function showObjectNav()
916 * Show content block.
920 function showContentBlock()
922 $this->elementStart('div', array('id' => 'content'));
923 if (common_logged_in()) {
924 if (Event::handle('StartShowNoticeForm', array($this))) {
925 $this->showNoticeForm();
926 Event::handle('EndShowNoticeForm', array($this));
929 if (Event::handle('StartShowPageTitle', array($this))) {
930 $this->showPageTitle();
931 Event::handle('EndShowPageTitle', array($this));
933 $this->showPageNoticeBlock();
934 $this->elementStart('div', array('id' => 'content_inner'));
935 // show the actual content (forms, lists, whatever)
936 $this->showContent();
937 $this->elementEnd('div');
938 $this->elementEnd('div');
946 function showPageTitle()
948 $this->element('h1', null, $this->title());
952 * Show page notice block.
954 * Only show the block if a subclassed action has overrided
955 * Action::showPageNotice(), or an event handler is registered for
956 * the StartShowPageNotice event, in which case we assume the
957 * 'page_notice' definition list is desired. This is to prevent
958 * empty 'page_notice' definition lists from being output everywhere.
962 function showPageNoticeBlock()
964 $rmethod = new ReflectionMethod($this, 'showPageNotice');
965 $dclass = $rmethod->getDeclaringClass()->getName();
967 if ($dclass != 'Action' || Event::hasHandler('StartShowPageNotice')) {
969 $this->elementStart('div', array('id' => 'page_notice',
970 'class' => 'system_notice'));
971 if (Event::handle('StartShowPageNotice', array($this))) {
972 $this->showPageNotice();
973 Event::handle('EndShowPageNotice', array($this));
975 $this->elementEnd('div');
982 * SHOULD overload (unless there's not a notice)
986 function showPageNotice()
993 * MUST overload (unless there's not a notice)
997 protected function showContent()
1006 function showAside()
1008 $this->elementStart('div', array('id' => 'aside_primary',
1009 'class' => 'aside'));
1010 $this->showProfileBlock();
1011 if (Event::handle('StartShowObjectNavBlock', array($this))) {
1012 $this->showObjectNavBlock();
1013 Event::handle('EndShowObjectNavBlock', array($this));
1015 if (Event::handle('StartShowSections', array($this))) {
1016 $this->showSections();
1017 Event::handle('EndShowSections', array($this));
1019 if (Event::handle('StartShowExportData', array($this))) {
1020 $this->showExportData();
1021 Event::handle('EndShowExportData', array($this));
1023 $this->elementEnd('div');
1027 * Show export data feeds.
1031 function showExportData()
1033 $feeds = $this->getFeeds();
1034 if (!empty($feeds)) {
1035 $fl = new FeedList($this, $feeds);
1047 function showSections()
1049 // for each section, show it
1057 function showFooter()
1059 $this->elementStart('div', array('id' => 'footer'));
1060 if (Event::handle('StartShowInsideFooter', array($this))) {
1061 $this->showSecondaryNav();
1062 $this->showLicenses();
1063 Event::handle('EndShowInsideFooter', array($this));
1065 $this->elementEnd('div');
1069 * Show secondary navigation.
1073 function showSecondaryNav()
1075 $sn = new SecondaryNav($this);
1084 function showLicenses()
1086 $this->showGNUsocialLicense();
1087 $this->showContentLicense();
1091 * Show GNU social license.
1095 function showGNUsocialLicense()
1097 if (common_config('site', 'broughtby')) {
1098 // TRANS: First sentence of the GNU social site license. Used if 'broughtby' is set.
1099 // TRANS: Text between [] is a link description, text between () is the link itself.
1100 // TRANS: Make sure there is no whitespace between "]" and "(".
1101 // TRANS: "%%site.broughtby%%" is the value of the variable site.broughtby
1102 $instr = _('**%%site.name%%** is a social network, courtesy of [%%site.broughtby%%](%%site.broughtbyurl%%).');
1104 // TRANS: First sentence of the GNU social site license. Used if 'broughtby' is not set.
1105 $instr = _('**%%site.name%%** is a social network.');
1108 // TRANS: Second sentence of the GNU social site license. Mentions the GNU social source code license.
1109 // TRANS: Make sure there is no whitespace between "]" and "(".
1110 // TRANS: [%1$s](%2$s) is a link description followed by the link itself
1111 // TRANS: %3$s is the version of GNU social that is being used.
1112 $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);
1113 $output = common_markup_to_html($instr);
1114 $this->raw($output);
1119 * Show content license.
1123 function showContentLicense()
1125 if (Event::handle('StartShowContentLicense', array($this))) {
1126 switch (common_config('license', 'type')) {
1128 // TRANS: Content license displayed when license is set to 'private'.
1129 // TRANS: %1$s is the site name.
1130 $this->element('p', null, sprintf(_('Content and data of %1$s are private and confidential.'),
1131 common_config('site', 'name')));
1133 case 'allrightsreserved':
1134 if (common_config('license', 'owner')) {
1135 // TRANS: Content license displayed when license is set to 'allrightsreserved'.
1136 // TRANS: %1$s is the copyright owner.
1137 $this->element('p', null, sprintf(_('Content and data copyright by %1$s. All rights reserved.'),
1138 common_config('license', 'owner')));
1140 // TRANS: Content license displayed when license is set to 'allrightsreserved' and no owner is set.
1141 $this->element('p', null, _('Content and data copyright by contributors. All rights reserved.'));
1144 case 'cc': // fall through
1146 $this->elementStart('p');
1148 $image = common_config('license', 'image');
1149 $sslimage = common_config('license', 'sslimage');
1151 if (GNUsocial::isHTTPS()) {
1152 if (!empty($sslimage)) {
1154 } else if (preg_match('#^http://i.creativecommons.org/#', $image)) {
1155 // CC support HTTPS on their images
1156 $url = preg_replace('/^http/', 'https', $image);
1158 // Better to show mixed content than no content
1165 $this->element('img', array('id' => 'license_cc',
1167 'alt' => common_config('license', 'title'),
1171 // TRANS: license message in footer.
1172 // TRANS: %1$s is the site name, %2$s is a link to the license URL, with a licence name set in configuration.
1173 $notice = _('All %1$s content and data are available under the %2$s license.');
1174 $link = sprintf('<a class="license" rel="external license" href="%1$s">%2$s</a>',
1175 htmlspecialchars(common_config('license', 'url')),
1176 htmlspecialchars(common_config('license', 'title')));
1177 $this->raw(@sprintf(htmlspecialchars($notice),
1178 htmlspecialchars(common_config('site', 'name')),
1180 $this->elementEnd('p');
1184 Event::handle('EndShowContentLicense', array($this));
1189 * Return last modified, if applicable.
1193 * @return string last modified http header
1195 function lastModified()
1197 // For comparison with If-Last-Modified
1198 // If not applicable, return null
1203 * Return etag, if applicable.
1207 * @return string etag http header
1215 * Return true if read only.
1219 * @param array $args other arguments
1221 * @return boolean is read only action?
1223 function isReadOnly($args)
1229 * Returns query argument or default value if not found
1231 * @param string $key requested argument
1232 * @param string $def default value to return if $key is not provided
1234 * @return boolean is read only action?
1236 function arg($key, $def=null)
1238 if (array_key_exists($key, $this->args)) {
1239 return $this->args[$key];
1246 * Returns trimmed 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 trimmed($key, $def=null)
1255 $arg = $this->arg($key, $def);
1256 return is_string($arg) ? trim($arg) : $arg;
1262 * @return boolean is read only action?
1264 protected function handle()
1266 header('Vary: Accept-Encoding,Cookie');
1268 $lm = $this->lastModified();
1269 $etag = $this->etag();
1272 header('ETag: ' . $etag);
1276 header('Last-Modified: ' . date(DATE_RFC1123, $lm));
1277 if ($this->isCacheable()) {
1278 header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', 0 ) . ' GMT' );
1279 header( "Cache-Control: private, must-revalidate, max-age=0" );
1286 $if_none_match = (array_key_exists('HTTP_IF_NONE_MATCH', $_SERVER)) ?
1287 $_SERVER['HTTP_IF_NONE_MATCH'] : null;
1288 if ($if_none_match) {
1289 // If this check fails, ignore the if-modified-since below.
1291 if ($this->_hasEtag($etag, $if_none_match)) {
1292 header('HTTP/1.1 304 Not Modified');
1293 // Better way to do this?
1299 if (!$checked && $lm && array_key_exists('HTTP_IF_MODIFIED_SINCE', $_SERVER)) {
1300 $if_modified_since = $_SERVER['HTTP_IF_MODIFIED_SINCE'];
1301 $ims = strtotime($if_modified_since);
1303 header('HTTP/1.1 304 Not Modified');
1304 // Better way to do this?
1311 * Is this action cacheable?
1313 * If the action returns a last-modified
1315 * @param array $argarray is ignored since it's now passed in in prepare()
1317 * @return boolean is read only action?
1319 function isCacheable()
1325 * Has etag? (private)
1327 * @param string $etag etag http header
1328 * @param string $if_none_match ifNoneMatch http header
1332 function _hasEtag($etag, $if_none_match)
1334 $etags = explode(',', $if_none_match);
1335 return in_array($etag, $etags) || in_array('*', $etags);
1339 * Boolean understands english (yes, no, true, false)
1341 * @param string $key query key we're interested in
1342 * @param string $def default value
1344 * @return boolean interprets yes/no strings as boolean
1346 function boolean($key, $def=false)
1348 $arg = strtolower($this->trimmed($key));
1350 if (is_null($arg)) {
1352 } else if (in_array($arg, array('true', 'yes', '1', 'on'))) {
1354 } else if (in_array($arg, array('false', 'no', '0'))) {
1362 * This is a cheap hack to avoid a bug in DB_DataObject
1363 * where '' is non-type-aware compared to 0, which means it
1364 * will always be true for values like false and 0 too...
1367 * https://pear.php.net/bugs/bug.php?id=20291
1369 function booleanintstring($key, $def=false)
1371 return $this->boolean($key, $def) ? '1' : '0';
1375 * Integer value of an argument
1377 * @param string $key query key we're interested in
1378 * @param string $defValue optional default value (default null)
1379 * @param string $maxValue optional max value (default null)
1380 * @param string $minValue optional min value (default null)
1382 * @return integer integer value
1384 function int($key, $defValue=null, $maxValue=null, $minValue=null)
1386 $arg = intval($this->arg($key));
1388 if (!is_numeric($this->arg($key)) || $arg != $this->arg($key)) {
1392 if (!is_null($maxValue)) {
1393 $arg = min($arg, $maxValue);
1396 if (!is_null($minValue)) {
1397 $arg = max($arg, $minValue);
1406 * @param string $msg error message to display
1407 * @param integer $code http error code, 500 by default
1411 function serverError($msg, $code=500, $format=null)
1413 if ($format === null) {
1414 $format = $this->format;
1417 common_debug("Server error '{$code}' on '{$this->action}': {$msg}", __FILE__);
1419 if (!array_key_exists($code, ServerErrorAction::$status)) {
1423 $status_string = ServerErrorAction::$status[$code];
1427 header("HTTP/1.1 {$code} {$status_string}");
1428 $this->initDocument('xml');
1429 $this->elementStart('hash');
1430 $this->element('error', null, $msg);
1431 $this->element('request', null, $_SERVER['REQUEST_URI']);
1432 $this->elementEnd('hash');
1433 $this->endDocument('xml');
1436 if (!isset($this->callback)) {
1437 header("HTTP/1.1 {$code} {$status_string}");
1439 $this->initDocument('json');
1440 $error_array = array('error' => $msg, 'request' => $_SERVER['REQUEST_URI']);
1441 print(json_encode($error_array));
1442 $this->endDocument('json');
1445 throw new ServerException($msg, $code);
1454 * @param string $msg error message to display
1455 * @param integer $code http error code, 400 by default
1456 * @param string $format error format (json, xml, text) for ApiAction
1459 * @throws ClientException always
1461 function clientError($msg, $code=400, $format=null)
1463 // $format is currently only relevant for an ApiAction anyway
1464 if ($format === null) {
1465 $format = $this->format;
1468 common_debug("User error '{$code}' on '{$this->action}': {$msg}", __FILE__);
1470 if (!array_key_exists($code, ClientErrorAction::$status)) {
1474 $status_string = ClientErrorAction::$status[$code];
1478 header("HTTP/1.1 {$code} {$status_string}");
1479 $this->initDocument('xml');
1480 $this->elementStart('hash');
1481 $this->element('error', null, $msg);
1482 $this->element('request', null, $_SERVER['REQUEST_URI']);
1483 $this->elementEnd('hash');
1484 $this->endDocument('xml');
1487 if (!isset($this->callback)) {
1488 header("HTTP/1.1 {$code} {$status_string}");
1490 $this->initDocument('json');
1491 $error_array = array('error' => $msg, 'request' => $_SERVER['REQUEST_URI']);
1492 $this->text(json_encode($error_array));
1493 $this->endDocument('json');
1496 header("HTTP/1.1 {$code} {$status_string}");
1497 header('Content-Type: text/plain; charset=utf-8');
1501 throw new ClientException($msg, $code);
1507 * If not logged in, take appropriate action (redir or exception)
1509 * @param boolean $redir Redirect to login if not logged in
1511 * @return boolean true if logged in (never returns if not)
1513 public function checkLogin($redir=true)
1515 if (common_logged_in()) {
1520 common_set_returnto($_SERVER['REQUEST_URI']);
1521 common_redirect(common_local_url('login'));
1524 // TRANS: Error message displayed when trying to perform an action that requires a logged in user.
1525 $this->clientError(_('Not logged in.'), 403);
1529 * Returns the current URL
1531 * @return string current URL
1535 list($action, $args) = $this->returnToArgs();
1536 return common_local_url($action, $args);
1540 * Returns arguments sufficient for re-constructing URL
1542 * @return array two elements: action, other args
1544 function returnToArgs()
1546 $action = $this->getActionName();
1547 $args = $this->args;
1548 unset($args['action']);
1549 if (common_config('site', 'fancy')) {
1552 if (array_key_exists('submit', $args)) {
1553 unset($args['submit']);
1555 foreach (array_keys($_COOKIE) as $cookie) {
1556 unset($args[$cookie]);
1558 return array($action, $args);
1562 * Generate a menu item
1564 * @param string $url menu URL
1565 * @param string $text menu name
1566 * @param string $title title attribute, null by default
1567 * @param boolean $is_selected current menu item, false by default
1568 * @param string $id element id, null by default
1572 function menuItem($url, $text, $title=null, $is_selected=false, $id=null, $class=null)
1574 // Added @id to li for some control.
1575 // XXX: We might want to move this to htmloutputter.php
1578 if ($class !== null) {
1579 $classes[] = trim($class);
1582 $classes[] = 'current';
1585 if (!empty($classes)) {
1586 $lattrs['class'] = implode(' ', $classes);
1589 if (!is_null($id)) {
1590 $lattrs['id'] = $id;
1593 $this->elementStart('li', $lattrs);
1594 $attrs['href'] = $url;
1596 $attrs['title'] = $title;
1598 $this->element('a', $attrs, $text);
1599 $this->elementEnd('li');
1603 * Generate pagination links
1605 * @param boolean $have_before is there something before?
1606 * @param boolean $have_after is there something after?
1607 * @param integer $page current page
1608 * @param string $action current action
1609 * @param array $args rest of query arguments
1613 // XXX: The messages in this pagination method only tailor to navigating
1614 // notices. In other lists, "Previous"/"Next" type navigation is
1615 // desirable, but not available.
1616 function pagination($have_before, $have_after, $page, $action, $args=null)
1618 // Does a little before-after block for next/prev page
1619 if ($have_before || $have_after) {
1620 $this->elementStart('ul', array('class' => 'nav',
1621 'id' => 'pagination'));
1624 $pargs = array('page' => $page-1);
1625 $this->elementStart('li', array('class' => 'nav_prev'));
1626 $this->element('a', array('href' => common_local_url($action, $args, $pargs),
1628 // TRANS: Pagination message to go to a page displaying information more in the
1629 // TRANS: present than the currently displayed information.
1631 $this->elementEnd('li');
1634 $pargs = array('page' => $page+1);
1635 $this->elementStart('li', array('class' => 'nav_next'));
1636 $this->element('a', array('href' => common_local_url($action, $args, $pargs),
1638 // TRANS: Pagination message to go to a page displaying information more in the
1639 // TRANS: past than the currently displayed information.
1641 $this->elementEnd('li');
1643 if ($have_before || $have_after) {
1644 $this->elementEnd('ul');
1649 * An array of feeds for this action.
1651 * Returns an array of potential feeds for this action.
1653 * @return array Feed object to show in head and links
1661 * Check the session token.
1663 * Checks that the current form has the correct session token,
1664 * and throw an exception if it does not.
1668 // XXX: Finding this type of check with the same message about 50 times.
1669 // Possible to refactor?
1670 function checkSessionToken()
1673 $token = $this->trimmed('token');
1674 if (empty($token) || $token != common_session_token()) {
1675 // TRANS: Client error text when there is a problem with the session token.
1676 $this->clientError(_('There was a problem with your session token.'));
1681 * Check if the current request is a POST
1683 * @return boolean true if POST; otherwise false.
1688 return ($_SERVER['REQUEST_METHOD'] == 'POST');