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')) {
36 * Base class for all actions
38 * This is the base class for all actions in the package. An action is
39 * more or less a "view" in an MVC framework.
41 * Actions are responsible for extracting and validating parameters; using
42 * model classes to read and write to the database; and doing ouput.
46 * @author Evan Prodromou <evan@status.net>
47 * @author Sarven Capadisli <csarven@status.net>
48 * @license http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
49 * @link http://status.net/
53 class Action extends HTMLOutputter // lawsuit
55 // This should be protected/private in the future
58 // Action properties, set per-class
59 protected $action = false;
60 protected $ajax = false;
61 protected $menus = true;
62 protected $needLogin = false;
63 protected $redirectAfterLogin = false;
64 protected $needPost = false; // implies canPost if true
65 protected $canPost = false; // can this action handle POST method?
67 // The currently scoped profile (normally Profile::current; from $this->auth_user for API)
68 protected $scoped = null;
70 // Related to front-end user representation
71 protected $format = null;
72 protected $error = null;
73 protected $msg = null;
78 * Just wraps the HTMLOutputter constructor.
80 * @param string $output URI to output to, default = stdout
81 * @param boolean $indent Whether to indent output, default true
83 * @see XMLOutputter::__construct
84 * @see HTMLOutputter::__construct
86 public function __construct($output = 'php://output', $indent = null)
88 parent::__construct($output, $indent);
91 public static function run(array $args = [], $output = 'php://output', $indent = null)
93 $class = get_called_class();
94 $action = new $class($output, $indent);
95 set_exception_handler(array($action, 'handleError'));
96 $action->execute($args);
100 public function getInfo()
105 public function handleError($e)
107 if ($e instanceof ClientException) {
108 $this->clientError($e->getMessage(), $e->getCode());
109 } elseif ($e instanceof ServerException) {
110 $this->serverError($e->getMessage(), $e->getCode());
112 // If it wasn't specified more closely which kind of exception it was
113 $this->serverError($e->getMessage(), 500);
120 * @param string $msg error message to display
121 * @param integer $code http error code, 400 by default
122 * @param string $format error format (json, xml, text) for ApiAction
125 * @throws ClientException always
127 public function clientError($msg, $code = 400, $format = null)
129 // $format is currently only relevant for an ApiAction anyway
130 if ($format === null) {
131 $format = $this->format;
134 common_debug("User error '{$code}' on '{$this->action}': {$msg}", __FILE__);
136 if (!array_key_exists($code, ClientErrorAction::$status)) {
140 $status_string = ClientErrorAction::$status[$code];
144 header("HTTP/1.1 {$code} {$status_string}");
145 $this->initDocument('xml');
146 $this->elementStart('hash');
147 $this->element('error', null, $msg);
148 $this->element('request', null, $_SERVER['REQUEST_URI']);
149 $this->elementEnd('hash');
150 $this->endDocument('xml');
153 if (!isset($this->callback)) {
154 header("HTTP/1.1 {$code} {$status_string}");
156 $this->initDocument('json');
157 $error_array = array('error' => $msg, 'request' => $_SERVER['REQUEST_URI']);
158 print(json_encode($error_array));
159 $this->endDocument('json');
162 header("HTTP/1.1 {$code} {$status_string}");
163 header('Content-Type: text/plain; charset=utf-8');
167 common_log(LOG_ERR, 'Handled clientError (' . _ve($code) . ') but cannot output into desired format (' . _ve($this->format) . '): ' . _ve($msg));
168 $action = new ClientErrorAction($msg, $code);
174 public function execute(array $args = [])
177 if (common_config('db', 'mirror') && $this->isReadOnly($args)) {
178 if (is_array(common_config('db', 'mirror'))) {
179 // "load balancing", ha ha
180 $arr = common_config('db', 'mirror');
181 $k = array_rand($arr);
184 $mirror = common_config('db', 'mirror');
187 // everyone else uses the mirror
188 common_config_set('db', 'database', $mirror);
191 if (Event::handle('StartActionExecute', array($this, &$args))) {
192 $prepared = $this->prepare($args);
196 common_debug('Prepare failed for Action.');
200 Event::handle('EndActionExecute', array($this));
205 * Return true if read only.
209 * @param array $args other arguments
211 * @return boolean is read only action?
213 public function isReadOnly($args)
219 * For initializing members of the class.
221 * @param array $args misc. arguments
223 * @return boolean true
224 * @throws ClientException
226 protected function prepare(array $args = [])
228 if ($this->needPost && !$this->isPost()) {
229 // TRANS: Client error. POST is a HTTP command. It should not be translated.
230 $this->clientError(_('This method requires a POST.'), 405);
233 // needPost, of course, overrides canPost if true
234 if (!$this->canPost) {
235 $this->canPost = $this->needPost;
238 $this->args = common_copy_args($args);
240 // This could be set with get_called_action and then
241 // chop off 'Action' from the class name. In lower case.
242 $this->action = strtolower($this->trimmed('action'));
244 if ($this->ajax || $this->boolean('ajax')) {
245 // check with GNUsocial::isAjax()
246 GNUsocial::setAjax(true);
249 if ($this->needLogin) {
250 $this->checkLogin(); // if not logged in, this redirs/excepts
253 if ($this->redirectAfterLogin) {
254 common_set_returnto($this->selfUrl());
257 $this->updateScopedProfile();
263 * Check if the current request is a POST
265 * @return boolean true if POST; otherwise false.
268 public function isPost()
270 return ($_SERVER['REQUEST_METHOD'] == 'POST');
273 // Must be run _after_ prepare
276 * Returns trimmed query argument or default value if not found
278 * @param string $key requested argument
279 * @param string $def default value to return if $key is not provided
281 * @return boolean is read only action?
283 public function trimmed($key, $def = null)
285 $arg = $this->arg($key, $def);
286 return is_string($arg) ? trim($arg) : $arg;
290 * Returns query argument or default value if not found
292 * @param string $key requested argument
293 * @param string $def default value to return if $key is not provided
295 * @return boolean is read only action?
297 public function arg($key, $def = null)
299 if (array_key_exists($key, $this->args)) {
300 return $this->args[$key];
307 * Boolean understands english (yes, no, true, false)
309 * @param string $key query key we're interested in
310 * @param string $def default value
312 * @return boolean interprets yes/no strings as boolean
314 public function boolean($key, $def = false)
316 $arg = strtolower($this->trimmed($key));
320 } elseif (in_array($arg, array('true', 'yes', '1', 'on'))) {
322 } elseif (in_array($arg, array('false', 'no', '0'))) {
330 * If not logged in, take appropriate action (redir or exception)
332 * @param boolean $redir Redirect to login if not logged in
334 * @return boolean true if logged in (never returns if not)
335 * @throws ClientException
337 public function checkLogin($redir = true)
339 if (common_logged_in()) {
343 if ($redir == true) {
344 common_set_returnto($_SERVER['REQUEST_URI']);
345 common_redirect(common_local_url('login'));
348 // TRANS: Error message displayed when trying to perform an action that requires a logged in user.
349 $this->clientError(_('Not logged in.'), 403);
352 public function updateScopedProfile()
354 $this->scoped = Profile::current();
355 return $this->scoped;
361 protected function handle()
363 header('Vary: Accept-Encoding,Cookie');
365 $lm = $this->lastModified();
366 $etag = $this->etag();
369 header('ETag: ' . $etag);
373 header('Last-Modified: ' . date(DATE_RFC1123, $lm));
374 if ($this->isCacheable()) {
375 header('Expires: ' . gmdate('D, d M Y H:i:s', 0) . ' GMT');
376 header("Cache-Control: private, must-revalidate, max-age=0");
383 $if_none_match = (array_key_exists('HTTP_IF_NONE_MATCH', $_SERVER)) ?
384 $_SERVER['HTTP_IF_NONE_MATCH'] : null;
385 if ($if_none_match) {
386 // If this check fails, ignore the if-modified-since below.
388 if ($this->_hasEtag($etag, $if_none_match)) {
389 header('HTTP/1.1 304 Not Modified');
390 // Better way to do this?
396 if (!$checked && $lm && array_key_exists('HTTP_IF_MODIFIED_SINCE', $_SERVER)) {
397 $if_modified_since = $_SERVER['HTTP_IF_MODIFIED_SINCE'];
398 $ims = strtotime($if_modified_since);
400 header('HTTP/1.1 304 Not Modified');
401 // Better way to do this?
408 * Return last modified, if applicable.
412 * @return string last modified http header
414 public function lastModified()
416 // For comparison with If-Last-Modified
417 // If not applicable, return null
422 * Return etag, if applicable.
426 * @return string etag http header
428 public function etag()
434 * Is this action cacheable?
436 * If the action returns a last-modified
438 * @return boolean is read only action?
440 public function isCacheable()
446 * Has etag? (private)
448 * @param string $etag etag http header
449 * @param string $if_none_match ifNoneMatch http header
453 public function _hasEtag($etag, $if_none_match)
455 $etags = explode(',', $if_none_match);
456 return in_array($etag, $etags) || in_array('*', $etags);
462 * @param string $msg error message to display
463 * @param integer $code http error code, 500 by default
465 * @param string $format
468 public function serverError($msg, $code = 500, $format = null)
470 if ($format === null) {
471 $format = $this->format;
474 common_debug("Server error '{$code}' on '{$this->action}': {$msg}", __FILE__);
476 if (!array_key_exists($code, ServerErrorAction::$status)) {
480 $status_string = ServerErrorAction::$status[$code];
484 header("HTTP/1.1 {$code} {$status_string}");
485 $this->initDocument('xml');
486 $this->elementStart('hash');
487 $this->element('error', null, $msg);
488 $this->element('request', null, $_SERVER['REQUEST_URI']);
489 $this->elementEnd('hash');
490 $this->endDocument('xml');
493 if (!isset($this->callback)) {
494 header("HTTP/1.1 {$code} {$status_string}");
496 $this->initDocument('json');
497 $error_array = array('error' => $msg, 'request' => $_SERVER['REQUEST_URI']);
498 print(json_encode($error_array));
499 $this->endDocument('json');
502 common_log(LOG_ERR, 'Handled serverError (' . _ve($code) . ') but cannot output into desired format (' . _ve($this->format) . '): ' . _ve($msg));
503 $action = new ServerErrorAction($msg, $code);
510 public function getScoped()
512 return ($this->scoped instanceof Profile) ? $this->scoped : null;
515 public function isAction(array $names)
517 foreach ($names as $class) {
518 // PHP is case insensitive, and we have stuff like ApiUpperCaseAction,
519 // but we at least make a point out of wanting to do stuff case-sensitive.
520 $class = ucfirst($class) . 'Action';
521 if ($this instanceof $class) {
529 * Show page, a template method.
532 * @throws ClientException
533 * @throws ReflectionException
534 * @throws ServerException
536 public function showPage()
538 if (GNUsocial::isAjax()) {
542 if (Event::handle('StartShowHTML', array($this))) {
545 Event::handle('EndShowHTML', array($this));
547 if (Event::handle('StartShowHead', array($this))) {
550 Event::handle('EndShowHead', array($this));
552 if (Event::handle('StartShowBody', array($this))) {
554 Event::handle('EndShowBody', array($this));
556 if (Event::handle('StartEndHTML', array($this))) {
558 Event::handle('EndEndHTML', array($this));
562 public function showAjax()
564 $this->startHTML('text/xml;charset=utf-8');
565 $this->elementStart('head');
566 // TRANS: Title for conversation page.
567 $this->element('title', null, $this->title());
568 $this->elementEnd('head');
569 $this->elementStart('body');
570 if ($this->getError()) {
571 $this->element('p', array('id' => 'error'), $this->getError());
573 $this->showContent();
575 $this->elementEnd('body');
580 * Returns the page title
584 * @return string page title
587 public function title()
589 // TRANS: Page title for a page without a title set.
590 return _('Untitled page');
593 public function getError()
601 * MUST overload (unless there's not a notice)
605 protected function showContent()
609 public function endHTML()
613 if (isset($_startTime)) {
614 $endTime = microtime(true);
615 $diff = round(($endTime - $_startTime) * 1000);
616 $this->raw("<!-- ${diff}ms -->");
623 * Show head, a template method.
627 public function showHead()
629 // XXX: attributes (profile?)
630 $this->elementStart('head');
631 if (Event::handle('StartShowHeadElements', array($this))) {
632 if (Event::handle('StartShowHeadTitle', array($this))) {
634 Event::handle('EndShowHeadTitle', array($this));
636 $this->showShortcutIcon();
637 $this->showStylesheets();
638 $this->showOpenSearch();
640 $this->showDescription();
642 Event::handle('EndShowHeadElements', array($this));
644 $this->elementEnd('head');
648 * Show title, a template method.
652 public function showTitle()
657 // TRANS: Page title. %1$s is the title, %2$s is the site name.
661 common_config('site', 'name')
667 * Show themed shortcut icon
671 public function showShortcutIcon()
673 if (is_readable(INSTALLDIR . '/theme/' . common_config('site', 'theme') . '/favicon.ico')) {
674 $this->element('link', array('rel' => 'shortcut icon',
675 'href' => Theme::path('favicon.ico')));
677 // favicon.ico should be HTTPS if the rest of the page is
678 $this->element('link', array('rel' => 'shortcut icon',
679 'href' => common_path('favicon.ico', GNUsocial::isHTTPS())));
682 if (common_config('site', 'mobile')) {
683 if (is_readable(INSTALLDIR . '/theme/' . common_config('site', 'theme') . '/apple-touch-icon.png')) {
684 $this->element('link', array('rel' => 'apple-touch-icon',
685 'href' => Theme::path('apple-touch-icon.png')));
687 $this->element('link', array('rel' => 'apple-touch-icon',
688 'href' => common_path('apple-touch-icon.png')));
698 public function showStylesheets()
700 if (Event::handle('StartShowStyles', array($this))) {
702 // Use old name for StatusNet for compatibility on events
704 if (Event::handle('StartShowStylesheets', array($this))) {
705 $this->primaryCssLink(null, 'screen, projection, tv, print');
706 Event::handle('EndShowStylesheets', array($this));
709 $this->cssLink('js/extlib/jquery-ui/css/smoothness/jquery-ui.css');
711 if (Event::handle('StartShowUAStyles', array($this))) {
712 Event::handle('EndShowUAStyles', array($this));
715 Event::handle('EndShowStyles', array($this));
717 if (common_config('custom_css', 'enabled')) {
718 $css = common_config('custom_css', 'css');
719 if (Event::handle('StartShowCustomCss', array($this, &$css))) {
720 if (trim($css) != '') {
723 Event::handle('EndShowCustomCss', array($this));
729 public function primaryCssLink($mainTheme = null, $media = null)
731 $theme = new Theme($mainTheme);
733 // Some themes may have external stylesheets
734 foreach ($theme->getExternals() as $url) {
735 $this->cssLink($url, $mainTheme, $media);
738 // If the currently-selected theme has dependencies on other themes,
739 // we'll need to load their display.css files as well in order.
740 $baseThemes = $theme->getDeps();
741 foreach ($baseThemes as $baseTheme) {
742 $this->cssLink('css/display.css', $baseTheme, $media);
744 $this->cssLink('css/display.css', $mainTheme, $media);
746 // Additional styles for RTL languages
747 if (is_rtl(common_language())) {
748 if (file_exists(Theme::file('css/rtl.css'))) {
749 $this->cssLink('css/rtl.css', $mainTheme, $media);
755 * Show OpenSearch headers
759 public function showOpenSearch()
761 $this->element('link', array('rel' => 'search',
762 'type' => 'application/opensearchdescription+xml',
763 'href' => common_local_url('opensearch', array('type' => 'people')),
764 'title' => common_config('site', 'name') . ' People Search'));
765 $this->element('link', array('rel' => 'search', 'type' => 'application/opensearchdescription+xml',
766 'href' => common_local_url('opensearch', array('type' => 'notice')),
767 'title' => common_config('site', 'name') . ' Notice Search'));
777 public function showFeeds()
779 foreach ($this->getFeeds() as $feed) {
780 $this->element('link', array('rel' => $feed->rel(),
781 'href' => $feed->url,
782 'type' => $feed->mimeType(),
783 'title' => $feed->title));
788 * An array of feeds for this action.
790 * Returns an array of potential feeds for this action.
792 * @return array Feed object to show in head and links
794 public function getFeeds()
806 public function showDescription()
808 // does nothing by default
812 * Show extra stuff in <head>.
818 public function extraHead()
820 // does nothing by default
826 * Calls template methods
829 * @throws ServerException
830 * @throws ReflectionException
832 public function showBody()
834 $params = array('id' => $this->getActionName());
835 if ($this->scoped instanceof Profile) {
836 $params['class'] = 'user_in';
838 $this->elementStart('body', $params);
839 $this->elementStart('div', array('id' => 'wrap'));
840 if (Event::handle('StartShowHeader', array($this))) {
843 Event::handle('EndShowHeader', array($this));
847 if (Event::handle('StartShowFooter', array($this))) {
850 Event::handle('EndShowFooter', array($this));
852 $this->elementEnd('div');
853 $this->showScripts();
854 $this->elementEnd('body');
857 public function getActionName()
859 return $this->action;
863 * Show header of the page.
865 * Calls template methods
868 * @throws ServerException
870 public function showHeader()
872 $this->elementStart('div', array('id' => 'header'));
874 $this->showPrimaryNav();
875 if (Event::handle('StartShowSiteNotice', array($this))) {
876 $this->showSiteNotice();
878 Event::handle('EndShowSiteNotice', array($this));
881 $this->elementEnd('div');
885 * Show configured logo.
888 * @throws ServerException
890 public function showLogo()
892 $this->elementStart('address', array('id' => 'site_contact', 'class' => 'h-card'));
893 if (Event::handle('StartAddressData', array($this))) {
894 if (common_config('singleuser', 'enabled')) {
895 $user = User::singleUser();
896 $url = common_local_url(
898 array('nickname' => $user->nickname)
900 } elseif (common_logged_in()) {
901 $cur = common_current_user();
902 $url = common_local_url('all', array('nickname' => $cur->nickname));
904 $url = common_local_url('public');
907 $this->elementStart('a', array('class' => 'home bookmark',
910 if (GNUsocial::isHTTPS()) {
911 $logoUrl = common_config('site', 'ssllogo');
912 if (empty($logoUrl)) {
913 // if logo is an uploaded file, try to fall back to HTTPS file URL
914 $httpUrl = common_config('site', 'logo');
915 if (!empty($httpUrl)) {
917 $f = File::getByUrl($httpUrl);
918 if (!empty($f->filename)) {
919 // this will handle the HTTPS case
920 $logoUrl = File::url($f->filename);
922 } catch (NoResultException $e) {
928 $logoUrl = common_config('site', 'logo');
931 if (empty($logoUrl) && file_exists(Theme::file('logo.png'))) {
932 // This should handle the HTTPS case internally
933 $logoUrl = Theme::path('logo.png');
936 if (!empty($logoUrl)) {
937 $this->element('img', array('class' => 'logo u-photo p-name',
939 'alt' => common_config('site', 'name')));
942 $this->elementEnd('a');
944 Event::handle('EndAddressData', array($this));
946 $this->elementEnd('address');
950 * Show primary navigation.
954 public function showPrimaryNav()
956 $this->elementStart('div', array('id' => 'site_nav_global_primary'));
958 $user = common_current_user();
960 if (!empty($user) || !common_config('site', 'private')) {
961 $form = new SearchForm($this);
965 $pn = new PrimaryNav($this);
967 $this->elementEnd('div');
975 public function showSiteNotice()
977 // Revist. Should probably do an hAtom pattern here
978 $text = common_config('site', 'notice');
980 $this->elementStart('div', array('id' => 'site_notice',
981 'class' => 'system_notice'));
983 $this->elementEnd('div');
990 * Shows local navigation, content block and aside.
993 * @throws ReflectionException
995 public function showCore()
997 $this->elementStart('div', array('id' => 'core'));
998 $this->elementStart('div', array('id' => 'aside_primary_wrapper'));
999 $this->elementStart('div', array('id' => 'content_wrapper'));
1000 $this->elementStart('div', array('id' => 'site_nav_local_views_wrapper'));
1001 if (Event::handle('StartShowLocalNavBlock', array($this))) {
1002 $this->showLocalNavBlock();
1004 Event::handle('EndShowLocalNavBlock', array($this));
1006 if (Event::handle('StartShowContentBlock', array($this))) {
1007 $this->showContentBlock();
1009 Event::handle('EndShowContentBlock', array($this));
1011 if (Event::handle('StartShowAside', array($this))) {
1014 Event::handle('EndShowAside', array($this));
1016 $this->elementEnd('div');
1017 $this->elementEnd('div');
1018 $this->elementEnd('div');
1019 $this->elementEnd('div');
1023 * Show local navigation block.
1027 public function showLocalNavBlock()
1029 // Need to have this ID for CSS; I'm too lazy to add it to
1031 $this->elementStart('div', array('id' => 'site_nav_local_views'));
1032 // Cheat cheat cheat!
1033 $this->showLocalNav();
1034 $this->elementEnd('div');
1038 * Show local navigation.
1044 public function showLocalNav()
1046 $nav = new DefaultLocalNav($this);
1051 * Show content block.
1054 * @throws ReflectionException
1056 public function showContentBlock()
1058 $this->elementStart('div', array('id' => 'content'));
1059 if (common_logged_in()) {
1060 if (Event::handle('StartShowNoticeForm', array($this))) {
1061 $this->showNoticeForm();
1062 Event::handle('EndShowNoticeForm', array($this));
1065 if (Event::handle('StartShowPageTitle', array($this))) {
1066 $this->showPageTitle();
1067 Event::handle('EndShowPageTitle', array($this));
1069 $this->showPageNoticeBlock();
1070 $this->elementStart('div', array('id' => 'content_inner'));
1071 // show the actual content (forms, lists, whatever)
1072 $this->showContent();
1073 $this->elementEnd('div');
1074 $this->elementEnd('div');
1080 * MAY overload if no notice form needed... or direct message box????
1084 public function showNoticeForm()
1086 // TRANS: Tab on the notice form.
1087 $tabs = array('status' => array('title' => _m('TAB', 'Status'),
1088 'href' => common_local_url('newnotice')));
1090 $this->elementStart('div', 'input_forms');
1092 $this->element('label', array('for' => 'input_form_nav'), _m('TAB', 'Share your:'));
1094 if (Event::handle('StartShowEntryForms', array(&$tabs))) {
1095 $this->elementStart('ul', array('class' => 'nav',
1096 'id' => 'input_form_nav'));
1098 foreach ($tabs as $tag => $data) {
1099 $tag = htmlspecialchars($tag);
1100 $attrs = array('id' => 'input_form_nav_' . $tag,
1101 'class' => 'input_form_nav_tab');
1103 if ($tag == 'status') {
1104 $attrs['class'] .= ' current';
1106 $this->elementStart('li', $attrs);
1110 array('onclick' => 'return SN.U.switchInputFormTab("' . $tag . '");',
1111 'href' => $data['href']),
1114 $this->elementEnd('li');
1117 $this->elementEnd('ul');
1119 foreach ($tabs as $tag => $data) {
1120 $attrs = array('class' => 'input_form',
1121 'id' => 'input_form_' . $tag);
1122 if ($tag == 'status') {
1123 $attrs['class'] .= ' current';
1126 $this->elementStart('div', $attrs);
1130 if (Event::handle('StartMakeEntryForm', array($tag, $this, &$form))) {
1131 if ($tag == 'status') {
1132 $options = $this->noticeFormOptions();
1133 $form = new NoticeForm($this, $options);
1135 Event::handle('EndMakeEntryForm', array($tag, $this, $form));
1138 if (!empty($form)) {
1142 $this->elementEnd('div');
1146 $this->elementEnd('div');
1149 public function noticeFormOptions()
1159 public function showPageTitle()
1161 $this->element('h1', null, $this->title());
1165 * Show page notice block.
1167 * Only show the block if a subclassed action has overrided
1168 * Action::showPageNotice(), or an event handler is registered for
1169 * the StartShowPageNotice event, in which case we assume the
1170 * 'page_notice' definition list is desired. This is to prevent
1171 * empty 'page_notice' definition lists from being output everywhere.
1174 * @throws ReflectionException
1176 public function showPageNoticeBlock()
1178 $rmethod = new ReflectionMethod($this, 'showPageNotice');
1179 $dclass = $rmethod->getDeclaringClass()->getName();
1181 if ($dclass != 'Action' || Event::hasHandler('StartShowPageNotice')) {
1182 $this->elementStart('div', array('id' => 'page_notice',
1183 'class' => 'system_notice'));
1184 if (Event::handle('StartShowPageNotice', array($this))) {
1185 $this->showPageNotice();
1186 Event::handle('EndShowPageNotice', array($this));
1188 $this->elementEnd('div');
1195 * SHOULD overload (unless there's not a notice)
1199 public function showPageNotice()
1207 * @throws ReflectionException
1209 public function showAside()
1211 $this->elementStart('div', array('id' => 'aside_primary',
1212 'class' => 'aside'));
1213 $this->showProfileBlock();
1214 if (Event::handle('StartShowObjectNavBlock', array($this))) {
1215 $this->showObjectNavBlock();
1216 Event::handle('EndShowObjectNavBlock', array($this));
1218 if (Event::handle('StartShowSections', array($this))) {
1219 $this->showSections();
1220 Event::handle('EndShowSections', array($this));
1222 if (Event::handle('StartShowExportData', array($this))) {
1223 $this->showExportData();
1224 Event::handle('EndShowExportData', array($this));
1226 $this->elementEnd('div');
1230 * If there's a logged-in user, show a bit of login context
1235 public function showProfileBlock()
1237 if (common_logged_in()) {
1238 $block = new DefaultProfileBlock($this);
1244 * Show menu for an object (group, profile)
1246 * This block will only show if a subclass has overridden
1247 * the showObjectNav() method.
1250 * @throws ReflectionException
1252 public function showObjectNavBlock()
1254 $rmethod = new ReflectionMethod($this, 'showObjectNav');
1255 $dclass = $rmethod->getDeclaringClass()->getName();
1257 if ($dclass != 'Action') {
1258 // Need to have this ID for CSS; I'm too lazy to add it to
1260 $this->elementStart('div', array('id' => 'site_nav_object',
1261 'class' => 'section'));
1262 $this->showObjectNav();
1263 $this->elementEnd('div');
1268 * Show object navigation.
1270 * If there are things to do with this object, show it here.
1274 public function showObjectNav()
1286 public function showSections()
1288 // for each section, show it
1292 * Show export data feeds.
1296 public function showExportData()
1298 $feeds = $this->getFeeds();
1299 if (!empty($feeds)) {
1300 $fl = new FeedList($this, $feeds);
1310 public function showFooter()
1312 $this->elementStart('div', array('id' => 'footer'));
1313 if (Event::handle('StartShowInsideFooter', array($this))) {
1314 $this->showSecondaryNav();
1315 $this->showLicenses();
1316 Event::handle('EndShowInsideFooter', array($this));
1318 $this->elementEnd('div');
1322 * Show secondary navigation.
1326 public function showSecondaryNav()
1328 $sn = new SecondaryNav($this);
1337 public function showLicenses()
1339 $this->showGNUsocialLicense();
1340 $this->showContentLicense();
1344 * Show GNU social license.
1348 public function showGNUsocialLicense()
1350 if (common_config('site', 'broughtby')) {
1351 // TRANS: First sentence of the GNU social site license. Used if 'broughtby' is set.
1352 // TRANS: Text between [] is a link description, text between () is the link itself.
1353 // TRANS: Make sure there is no whitespace between "]" and "(".
1354 // TRANS: "%%site.broughtby%%" is the value of the variable site.broughtby
1355 $instr = _('**%%site.name%%** is a social network, courtesy of [%%site.broughtby%%](%%site.broughtbyurl%%).');
1357 // TRANS: First sentence of the GNU social site license. Used if 'broughtby' is not set.
1358 $instr = _('**%%site.name%%** is a social network.');
1361 // TRANS: Second sentence of the GNU social site license. Mentions the GNU social source code license.
1362 // TRANS: Make sure there is no whitespace between "]" and "(".
1363 // TRANS: [%1$s](%2$s) is a link description followed by the link itself
1364 // TRANS: %3$s is the version of GNU social that is being used.
1365 $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);
1366 $output = common_markup_to_html($instr);
1367 $this->raw($output);
1372 * Show content license.
1376 public function showContentLicense()
1378 if (Event::handle('StartShowContentLicense', array($this))) {
1379 switch (common_config('license', 'type')) {
1381 // TRANS: Content license displayed when license is set to 'private'.
1382 // TRANS: %1$s is the site name.
1383 $this->element('p', null, sprintf(
1384 _('Content and data of %1$s are private and confidential.'),
1385 common_config('site', 'name')
1389 case 'allrightsreserved':
1390 if (common_config('license', 'owner')) {
1391 // TRANS: Content license displayed when license is set to 'allrightsreserved'.
1392 // TRANS: %1$s is the copyright owner.
1393 $this->element('p', null, sprintf(
1394 _('Content and data copyright by %1$s. All rights reserved.'),
1395 common_config('license', 'owner')
1398 // TRANS: Content license displayed when license is set to 'allrightsreserved' and no owner is set.
1399 $this->element('p', null, _('Content and data copyright by contributors. All rights reserved.'));
1402 case 'cc': // fall through
1404 $this->elementStart('p');
1406 $image = common_config('license', 'image');
1407 $sslimage = common_config('license', 'sslimage');
1409 if (GNUsocial::isHTTPS()) {
1410 if (!empty($sslimage)) {
1412 } elseif (preg_match('#^http://i.creativecommons.org/#', $image)) {
1413 // CC support HTTPS on their images
1414 $url = preg_replace('/^http/', 'https', $image, 1);
1416 // Better to show mixed content than no content
1423 $this->element('img', array('id' => 'license_cc',
1425 'alt' => common_config('license', 'title'),
1429 // TRANS: license message in footer.
1430 // TRANS: %1$s is the site name, %2$s is a link to the license URL, with a licence name set in configuration.
1431 $notice = _('All %1$s content and data are available under the %2$s license.');
1433 '<a class="license" rel="external license" href="%1$s">%2$s</a>',
1434 htmlspecialchars(common_config('license', 'url')),
1435 htmlspecialchars(common_config('license', 'title'))
1437 $this->raw(@sprintf(
1438 htmlspecialchars($notice),
1439 htmlspecialchars(common_config('site', 'name')),
1442 $this->elementEnd('p');
1446 Event::handle('EndShowContentLicense', array($this));
1451 * Show javascript headers
1455 public function showScripts()
1457 if (Event::handle('StartShowScripts', array($this))) {
1458 if (Event::handle('StartShowJQueryScripts', array($this))) {
1459 $this->script('extlib/jquery.js');
1460 $this->script('extlib/jquery.form.js');
1461 $this->script('extlib/jquery-ui/jquery-ui.js');
1462 $this->script('extlib/jquery.cookie.js');
1464 Event::handle('EndShowJQueryScripts', array($this));
1466 if (Event::handle('StartShowStatusNetScripts', array($this))) {
1467 $this->script('util.js');
1468 $this->script('xbImportNode.js');
1470 // This route isn't available in single-user mode.
1471 // Not sure why, but it causes errors here.
1472 $this->inlineScript('var _peopletagAC = "' .
1473 common_local_url('peopletagautocomplete') . '";');
1474 $this->showScriptMessages();
1475 $this->showScriptVariables();
1476 // Anti-framing code to avoid clickjacking attacks in older browsers.
1477 // This will show a blank page if the page is being framed, which is
1478 // consistent with the behavior of the 'X-Frame-Options: SAMEORIGIN'
1479 // header, which prevents framing in newer browser.
1480 if (common_config('javascript', 'bustframes')) {
1481 $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 = ""; }; }');
1483 Event::handle('EndShowStatusNetScripts', array($this));
1485 Event::handle('EndShowScripts', array($this));
1490 * Exports a map of localized text strings to JavaScript code.
1492 * Plugins can add to what's exported by hooking the StartScriptMessages or EndScriptMessages
1493 * events and appending to the array. Try to avoid adding strings that won't be used, as
1494 * they'll be added to HTML output.
1496 public function showScriptMessages()
1500 if (Event::handle('StartScriptMessages', array($this, &$messages))) {
1501 // Common messages needed for timeline views etc...
1503 // TRANS: Localized tooltip for '...' expansion button on overlong remote messages.
1504 $messages['showmore_tooltip'] = _m('TOOLTIP', 'Show more');
1505 $messages['popup_close_button'] = _m('TOOLTIP', 'Close popup');
1507 $messages = array_merge($messages, $this->getScriptMessages());
1509 Event::handle('EndScriptMessages', array($this, &$messages));
1512 if (!empty($messages)) {
1513 $this->inlineScript('SN.messages=' . json_encode($messages));
1520 * If the action will need localizable text strings, export them here like so:
1522 * return array('pool_deepend' => _('Deep end'),
1523 * 'pool_shallow' => _('Shallow end'));
1525 * The exported map will be available via SN.msg() to JS code:
1527 * $('#pool').html('<div class="deepend"></div><div class="shallow"></div>');
1528 * $('#pool .deepend').text(SN.msg('pool_deepend'));
1529 * $('#pool .shallow').text(SN.msg('pool_shallow'));
1531 * Exports a map of localized text strings to JavaScript code.
1533 * Plugins can add to what's exported on any action by hooking the StartScriptMessages or
1534 * EndScriptMessages events and appending to the array. Try to avoid adding strings that won't
1535 * be used, as they'll be added to HTML output.
1537 public function getScriptMessages()
1542 protected function showScriptVariables()
1546 if (Event::handle('StartScriptVariables', array($this, &$vars))) {
1547 $vars['urlNewNotice'] = common_local_url('newnotice');
1548 $vars['xhrTimeout'] = ini_get('max_execution_time') * 1000; // milliseconds
1549 Event::handle('EndScriptVariables', array($this, &$vars));
1552 $this->inlineScript('SN.V = ' . json_encode($vars) . ';');
1558 * Show anonymous message.
1564 public function showAnonymousMessage()
1566 // needs to be defined by the class
1570 * This is a cheap hack to avoid a bug in DB_DataObject
1571 * where '' is non-type-aware compared to 0, which means it
1572 * will always be true for values like false and 0 too...
1575 * https://pear.php.net/bugs/bug.php?id=20291
1577 public function booleanintstring($key, $def = false)
1579 return $this->boolean($key, $def) ? '1' : '0';
1583 * Integer value of an argument
1585 * @param string $key query key we're interested in
1586 * @param string $defValue optional default value (default null)
1587 * @param string $maxValue optional max value (default null)
1588 * @param string $minValue optional min value (default null)
1590 * @return integer integer value
1592 public function int($key, $defValue = null, $maxValue = null, $minValue = null)
1594 $arg = intval($this->arg($key));
1596 if (!is_numeric($this->arg($key)) || $arg != $this->arg($key)) {
1600 if (!is_null($maxValue)) {
1601 $arg = min($arg, $maxValue);
1604 if (!is_null($minValue)) {
1605 $arg = max($arg, $minValue);
1612 * Returns the current URL
1614 * @return string current URL
1616 public function selfUrl()
1618 list($action, $args) = $this->returnToArgs();
1619 return common_local_url($action, $args);
1623 * Generate pagination links
1625 * @param boolean $have_before is there something before?
1626 * @param boolean $have_after is there something after?
1627 * @param integer $page current page
1628 * @param string $action current action
1629 * @param array $args rest of query arguments
1633 // XXX: The messages in this pagination method only tailor to navigating
1634 // notices. In other lists, "Previous"/"Next" type navigation is
1635 // desirable, but not available.
1637 * Returns arguments sufficient for re-constructing URL
1639 * @return array two elements: action, other args
1641 public function returnToArgs()
1643 $action = $this->getActionName();
1644 $args = $this->args;
1645 unset($args['action']);
1646 if (common_config('site', 'fancy')) {
1649 if (array_key_exists('submit', $args)) {
1650 unset($args['submit']);
1652 foreach (array_keys($_COOKIE) as $cookie) {
1653 unset($args[$cookie]);
1655 return array($action, $args);
1659 * Generate a menu item
1661 * @param string $url menu URL
1662 * @param string $text menu name
1663 * @param string $title title attribute, null by default
1664 * @param boolean $is_selected current menu item, false by default
1665 * @param string $id element id, null by default
1669 public function menuItem($url, $text, $title = null, $is_selected = false, $id = null, $class = null)
1671 // Added @id to li for some control.
1672 // XXX: We might want to move this to htmloutputter.php
1675 if ($class !== null) {
1676 $classes[] = trim($class);
1679 $classes[] = 'current';
1682 if (!empty($classes)) {
1683 $lattrs['class'] = implode(' ', $classes);
1686 if (!is_null($id)) {
1687 $lattrs['id'] = $id;
1690 $this->elementStart('li', $lattrs);
1691 $attrs['href'] = $url;
1693 $attrs['title'] = $title;
1695 $this->element('a', $attrs, $text);
1696 $this->elementEnd('li');
1700 * Check the session token.
1702 * Checks that the current form has the correct session token,
1703 * and throw an exception if it does not.
1707 // XXX: Finding this type of check with the same message about 50 times.
1708 // Possible to refactor?
1710 public function pagination($have_before, $have_after, $page, $action, $args = null)
1712 // Does a little before-after block for next/prev page
1713 if ($have_before || $have_after) {
1714 $this->elementStart('ul', array('class' => 'nav',
1715 'id' => 'pagination'));
1718 $pargs = array('page' => $page - 1);
1719 $this->elementStart('li', array('class' => 'nav_prev'));
1722 array('href' => common_local_url($action, $args, $pargs),
1724 // TRANS: Pagination message to go to a page displaying information more in the
1725 // TRANS: present than the currently displayed information.
1728 $this->elementEnd('li');
1731 $pargs = array('page' => $page + 1);
1732 $this->elementStart('li', array('class' => 'nav_next'));
1735 array('href' => common_local_url($action, $args, $pargs),
1737 // TRANS: Pagination message to go to a page displaying information more in the
1738 // TRANS: past than the currently displayed information.
1741 $this->elementEnd('li');
1743 if ($have_before || $have_after) {
1744 $this->elementEnd('ul');
1749 public function checkSessionToken()
1752 $token = $this->trimmed('token');
1753 if (empty($token) || $token != common_session_token()) {
1754 // TRANS: Client error text when there is a problem with the session token.
1755 $this->clientError(_('There was a problem with your session token.'));