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 $status = $this->prepare($args);
123 $this->handle($args);
125 common_debug('Prepare failed for Action.');
130 Event::handle('EndActionExecute', array($status, $this));
134 * For initializing members of the class.
136 * @param array $argarray misc. arguments
138 * @return boolean true
140 protected function prepare(array $args=array())
142 if ($this->needPost && !$this->isPost()) {
143 // TRANS: Client error. POST is a HTTP command. It should not be translated.
144 $this->clientError(_('This method requires a POST.'), 405);
147 // needPost, of course, overrides canPost if true
148 if (!$this->canPost) {
149 $this->canPost = $this->needPost;
152 $this->args = common_copy_args($args);
154 // This could be set with get_called_action and then
155 // chop off 'Action' from the class name. In lower case.
156 $this->action = strtolower($this->trimmed('action'));
158 if ($this->ajax || $this->boolean('ajax')) {
159 // check with StatusNet::isAjax()
160 StatusNet::setAjax(true);
163 if ($this->needLogin) {
164 $this->checkLogin(); // if not logged in, this redirs/excepts
167 $this->updateScopedProfile();
172 function updateScopedProfile() {
173 $this->scoped = Profile::current();
174 return $this->scoped;
177 // Must be run _after_ prepare
178 public function getActionName()
180 return $this->action;
184 * Show page, a template method.
190 if (Event::handle('StartShowHTML', array($this))) {
193 Event::handle('EndShowHTML', array($this));
195 if (Event::handle('StartShowHead', array($this))) {
198 Event::handle('EndShowHead', array($this));
200 if (Event::handle('StartShowBody', array($this))) {
202 Event::handle('EndShowBody', array($this));
204 if (Event::handle('StartEndHTML', array($this))) {
206 Event::handle('EndEndHTML', array($this));
214 if (isset($_startTime)) {
215 $endTime = microtime(true);
216 $diff = round(($endTime - $_startTime) * 1000);
217 $this->raw("<!-- ${diff}ms -->");
220 return parent::endHTML();
224 * Show head, a template method.
230 // XXX: attributes (profile?)
231 $this->elementStart('head');
232 if (Event::handle('StartShowHeadElements', array($this))) {
233 if (Event::handle('StartShowHeadTitle', array($this))) {
235 Event::handle('EndShowHeadTitle', array($this));
237 $this->showShortcutIcon();
238 $this->showStylesheets();
239 $this->showOpenSearch();
241 $this->showDescription();
243 Event::handle('EndShowHeadElements', array($this));
245 $this->elementEnd('head');
249 * Show title, a template method.
255 $this->element('title', null,
256 // TRANS: Page title. %1$s is the title, %2$s is the site name.
257 sprintf(_('%1$s - %2$s'),
259 common_config('site', 'name')));
263 * Returns the page title
267 * @return string page title
272 // TRANS: Page title for a page without a title set.
273 return _('Untitled page');
277 * Show themed shortcut icon
281 function showShortcutIcon()
283 if (is_readable(INSTALLDIR . '/theme/' . common_config('site', 'theme') . '/favicon.ico')) {
284 $this->element('link', array('rel' => 'shortcut icon',
285 'href' => Theme::path('favicon.ico')));
287 // favicon.ico should be HTTPS if the rest of the page is
288 $this->element('link', array('rel' => 'shortcut icon',
289 'href' => common_path('favicon.ico', StatusNet::isHTTPS())));
292 if (common_config('site', 'mobile')) {
293 if (is_readable(INSTALLDIR . '/theme/' . common_config('site', 'theme') . '/apple-touch-icon.png')) {
294 $this->element('link', array('rel' => 'apple-touch-icon',
295 'href' => Theme::path('apple-touch-icon.png')));
297 $this->element('link', array('rel' => 'apple-touch-icon',
298 'href' => common_path('apple-touch-icon.png')));
308 function showStylesheets()
310 if (Event::handle('StartShowStyles', array($this))) {
312 // Use old name for StatusNet for compatibility on events
314 if (Event::handle('StartShowStylesheets', array($this))) {
315 $this->primaryCssLink(null, 'screen, projection, tv, print');
316 Event::handle('EndShowStylesheets', array($this));
319 $this->cssLink('js/extlib/jquery-ui/css/smoothness/jquery-ui.css');
321 if (Event::handle('StartShowUAStyles', array($this))) {
322 Event::handle('EndShowUAStyles', array($this));
325 Event::handle('EndShowStyles', array($this));
327 if (common_config('custom_css', 'enabled')) {
328 $css = common_config('custom_css', 'css');
329 if (Event::handle('StartShowCustomCss', array($this, &$css))) {
330 if (trim($css) != '') {
333 Event::handle('EndShowCustomCss', array($this));
339 function primaryCssLink($mainTheme=null, $media=null)
341 $theme = new Theme($mainTheme);
343 // Some themes may have external stylesheets, such as using the
344 // Google Font APIs to load webfonts.
345 foreach ($theme->getExternals() as $url) {
346 $this->cssLink($url, $mainTheme, $media);
349 // If the currently-selected theme has dependencies on other themes,
350 // we'll need to load their display.css files as well in order.
351 $baseThemes = $theme->getDeps();
352 foreach ($baseThemes as $baseTheme) {
353 $this->cssLink('css/display.css', $baseTheme, $media);
355 $this->cssLink('css/display.css', $mainTheme, $media);
357 // Additional styles for RTL languages
358 if (is_rtl(common_language())) {
359 if (file_exists(Theme::file('css/rtl.css'))) {
360 $this->cssLink('css/rtl.css', $mainTheme, $media);
366 * Show javascript headers
370 function showScripts()
372 if (Event::handle('StartShowScripts', array($this))) {
373 if (Event::handle('StartShowJQueryScripts', array($this))) {
374 $this->script('extlib/jquery.js');
375 $this->script('extlib/jquery.form.js');
376 $this->script('extlib/jquery-ui/jquery-ui.js');
377 $this->script('extlib/jquery.cookie.js');
378 $this->inlineScript('if (typeof window.JSON !== "object") { $.getScript("'.common_path('js/extlib/json2.js', StatusNet::isHTTPS()).'"); }');
379 $this->script('extlib/jquery.infieldlabel.js');
381 Event::handle('EndShowJQueryScripts', array($this));
383 if (Event::handle('StartShowStatusNetScripts', array($this))) {
384 $this->script('util.js');
385 $this->script('xbImportNode.js');
386 $this->script('geometa.js');
388 // This route isn't available in single-user mode.
389 // Not sure why, but it causes errors here.
390 $this->inlineScript('var _peopletagAC = "' .
391 common_local_url('peopletagautocomplete') . '";');
392 $this->showScriptMessages();
393 // Anti-framing code to avoid clickjacking attacks in older browsers.
394 // This will show a blank page if the page is being framed, which is
395 // consistent with the behavior of the 'X-Frame-Options: SAMEORIGIN'
396 // header, which prevents framing in newer browser.
397 if (common_config('javascript', 'bustframes')) {
398 $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 = ""; }; }');
400 Event::handle('EndShowStatusNetScripts', array($this));
402 Event::handle('EndShowScripts', array($this));
407 * Exports a map of localized text strings to JavaScript code.
409 * Plugins can add to what's exported by hooking the StartScriptMessages or EndScriptMessages
410 * events and appending to the array. Try to avoid adding strings that won't be used, as
411 * they'll be added to HTML output.
413 function showScriptMessages()
417 if (Event::handle('StartScriptMessages', array($this, &$messages))) {
418 // Common messages needed for timeline views etc...
420 // TRANS: Localized tooltip for '...' expansion button on overlong remote messages.
421 $messages['showmore_tooltip'] = _m('TOOLTIP', 'Show more');
423 // TRANS: Inline reply form submit button: submits a reply comment.
424 $messages['reply_submit'] = _m('BUTTON', 'Reply');
426 // TRANS: Placeholder text for inline reply form. Clicking in this box will turn it into a mini notice form.
427 $messages['reply_placeholder'] = _m('Write a reply...');
429 $messages = array_merge($messages, $this->getScriptMessages());
431 Event::handle('EndScriptMessages', array($this, &$messages));
434 if (!empty($messages)) {
435 $this->inlineScript('SN.messages=' . json_encode($messages));
442 * If the action will need localizable text strings, export them here like so:
444 * return array('pool_deepend' => _('Deep end'),
445 * 'pool_shallow' => _('Shallow end'));
447 * The exported map will be available via SN.msg() to JS code:
449 * $('#pool').html('<div class="deepend"></div><div class="shallow"></div>');
450 * $('#pool .deepend').text(SN.msg('pool_deepend'));
451 * $('#pool .shallow').text(SN.msg('pool_shallow'));
453 * Exports a map of localized text strings to JavaScript code.
455 * Plugins can add to what's exported on any action by hooking the StartScriptMessages or
456 * EndScriptMessages events and appending to the array. Try to avoid adding strings that won't
457 * be used, as they'll be added to HTML output.
459 function getScriptMessages()
465 * Show OpenSearch headers
469 function showOpenSearch()
471 $this->element('link', array('rel' => 'search',
472 'type' => 'application/opensearchdescription+xml',
473 'href' => common_local_url('opensearch', array('type' => 'people')),
474 'title' => common_config('site', 'name').' People Search'));
475 $this->element('link', array('rel' => 'search', 'type' => 'application/opensearchdescription+xml',
476 'href' => common_local_url('opensearch', array('type' => 'notice')),
477 'title' => common_config('site', 'name').' Notice Search'));
489 $feeds = $this->getFeeds();
492 foreach ($feeds as $feed) {
493 $this->element('link', array('rel' => $feed->rel(),
494 'href' => $feed->url,
495 'type' => $feed->mimeType(),
496 'title' => $feed->title));
508 function showDescription()
510 // does nothing by default
514 * Show extra stuff in <head>.
522 // does nothing by default
528 * Calls template methods
534 $params = array('id' => $this->getActionName());
535 if ($this->scoped instanceof Profile) {
536 $params['class'] = 'user_in';
538 $this->elementStart('body', $params);
539 $this->elementStart('div', array('id' => 'wrap'));
540 if (Event::handle('StartShowHeader', array($this))) {
543 Event::handle('EndShowHeader', array($this));
547 if (Event::handle('StartShowFooter', array($this))) {
550 Event::handle('EndShowFooter', array($this));
552 $this->elementEnd('div');
553 $this->showScripts();
554 $this->elementEnd('body');
558 * Show header of the page.
560 * Calls template methods
564 function showHeader()
566 $this->elementStart('div', array('id' => 'header'));
568 $this->showPrimaryNav();
569 if (Event::handle('StartShowSiteNotice', array($this))) {
570 $this->showSiteNotice();
572 Event::handle('EndShowSiteNotice', array($this));
575 $this->elementEnd('div');
579 * Show configured logo.
585 $this->elementStart('address', array('id' => 'site_contact', 'class' => 'h-card'));
586 if (Event::handle('StartAddressData', array($this))) {
587 if (common_config('singleuser', 'enabled')) {
588 $user = User::singleUser();
589 $url = common_local_url('showstream',
590 array('nickname' => $user->nickname));
591 } else if (common_logged_in()) {
592 $cur = common_current_user();
593 $url = common_local_url('all', array('nickname' => $cur->nickname));
595 $url = common_local_url('public');
598 $this->elementStart('a', array('class' => 'home bookmark',
601 if (StatusNet::isHTTPS()) {
602 $logoUrl = common_config('site', 'ssllogo');
603 if (empty($logoUrl)) {
604 // if logo is an uploaded file, try to fall back to HTTPS file URL
605 $httpUrl = common_config('site', 'logo');
606 if (!empty($httpUrl)) {
607 $f = File::getKV('url', $httpUrl);
608 if (!empty($f) && !empty($f->filename)) {
609 // this will handle the HTTPS case
610 $logoUrl = File::url($f->filename);
615 $logoUrl = common_config('site', 'logo');
618 if (empty($logoUrl) && file_exists(Theme::file('logo.png'))) {
619 // This should handle the HTTPS case internally
620 $logoUrl = Theme::path('logo.png');
623 if (!empty($logoUrl)) {
624 $this->element('img', array('class' => 'logo u-photo p-name',
626 'alt' => common_config('site', 'name')));
629 $this->elementEnd('a');
631 Event::handle('EndAddressData', array($this));
633 $this->elementEnd('address');
637 * Show primary navigation.
641 function showPrimaryNav()
643 $this->elementStart('div', array('id' => 'site_nav_global_primary'));
645 $user = common_current_user();
647 if (!empty($user) || !common_config('site', 'private')) {
648 $form = new SearchForm($this);
652 $pn = new PrimaryNav($this);
654 $this->elementEnd('div');
662 function showSiteNotice()
664 // Revist. Should probably do an hAtom pattern here
665 $text = common_config('site', 'notice');
667 $this->elementStart('div', array('id' => 'site_notice',
668 'class' => 'system_notice'));
670 $this->elementEnd('div');
677 * MAY overload if no notice form needed... or direct message box????
681 function showNoticeForm()
683 // TRANS: Tab on the notice form.
684 $tabs = array('status' => array('title' => _m('TAB','Status'),
685 'href' => common_local_url('newnotice')));
687 $this->elementStart('div', 'input_forms');
689 if (Event::handle('StartShowEntryForms', array(&$tabs))) {
690 $this->elementStart('ul', array('class' => 'nav',
691 'id' => 'input_form_nav'));
693 foreach ($tabs as $tag => $data) {
694 $tag = htmlspecialchars($tag);
695 $attrs = array('id' => 'input_form_nav_'.$tag,
696 'class' => 'input_form_nav_tab');
698 if ($tag == 'status') {
699 // We're actually showing the placeholder form,
700 // but we special-case the 'Status' tab as if
701 // it were a small version of it.
702 $attrs['class'] .= ' current';
704 $this->elementStart('li', $attrs);
707 array('onclick' => 'return SN.U.switchInputFormTab("'.$tag.'");',
708 'href' => $data['href']),
710 $this->elementEnd('li');
713 $this->elementEnd('ul');
715 $attrs = array('class' => 'input_form current',
716 'id' => 'input_form_placeholder');
717 $this->elementStart('div', $attrs);
718 $form = new NoticePlaceholderForm($this);
720 $this->elementEnd('div');
722 foreach ($tabs as $tag => $data) {
723 $attrs = array('class' => 'input_form',
724 'id' => 'input_form_'.$tag);
726 $this->elementStart('div', $attrs);
730 if (Event::handle('StartMakeEntryForm', array($tag, $this, &$form))) {
731 if ($tag == 'status') {
732 $options = $this->noticeFormOptions();
733 $form = new NoticeForm($this, $options);
735 Event::handle('EndMakeEntryForm', array($tag, $this, $form));
742 $this->elementEnd('div');
746 $this->elementEnd('div');
749 function noticeFormOptions()
755 * Show anonymous message.
761 function showAnonymousMessage()
763 // needs to be defined by the class
769 * Shows local navigation, content block and aside.
775 $this->elementStart('div', array('id' => 'core'));
776 $this->elementStart('div', array('id' => 'aside_primary_wrapper'));
777 $this->elementStart('div', array('id' => 'content_wrapper'));
778 $this->elementStart('div', array('id' => 'site_nav_local_views_wrapper'));
779 if (Event::handle('StartShowLocalNavBlock', array($this))) {
780 $this->showLocalNavBlock();
782 Event::handle('EndShowLocalNavBlock', array($this));
784 if (Event::handle('StartShowContentBlock', array($this))) {
785 $this->showContentBlock();
787 Event::handle('EndShowContentBlock', array($this));
789 if (Event::handle('StartShowAside', array($this))) {
792 Event::handle('EndShowAside', array($this));
794 $this->elementEnd('div');
795 $this->elementEnd('div');
796 $this->elementEnd('div');
797 $this->elementEnd('div');
801 * Show local navigation block.
805 function showLocalNavBlock()
807 // Need to have this ID for CSS; I'm too lazy to add it to
809 $this->elementStart('div', array('id' => 'site_nav_local_views'));
810 // Cheat cheat cheat!
811 $this->showLocalNav();
812 $this->elementEnd('div');
816 * If there's a logged-in user, show a bit of login context
820 function showProfileBlock()
822 if (common_logged_in()) {
823 $block = new DefaultProfileBlock($this);
829 * Show local navigation.
835 function showLocalNav()
837 $nav = new DefaultLocalNav($this);
842 * Show menu for an object (group, profile)
844 * This block will only show if a subclass has overridden
845 * the showObjectNav() method.
849 function showObjectNavBlock()
851 $rmethod = new ReflectionMethod($this, 'showObjectNav');
852 $dclass = $rmethod->getDeclaringClass()->getName();
854 if ($dclass != 'Action') {
855 // Need to have this ID for CSS; I'm too lazy to add it to
857 $this->elementStart('div', array('id' => 'site_nav_object',
858 'class' => 'section'));
859 $this->showObjectNav();
860 $this->elementEnd('div');
865 * Show object navigation.
867 * If there are things to do with this object, show it here.
871 function showObjectNav()
877 * Show content block.
881 function showContentBlock()
883 $this->elementStart('div', array('id' => 'content'));
884 if (common_logged_in()) {
885 if (Event::handle('StartShowNoticeForm', array($this))) {
886 $this->showNoticeForm();
887 Event::handle('EndShowNoticeForm', array($this));
890 if (Event::handle('StartShowPageTitle', array($this))) {
891 $this->showPageTitle();
892 Event::handle('EndShowPageTitle', array($this));
894 $this->showPageNoticeBlock();
895 $this->elementStart('div', array('id' => 'content_inner'));
896 // show the actual content (forms, lists, whatever)
897 $this->showContent();
898 $this->elementEnd('div');
899 $this->elementEnd('div');
907 function showPageTitle()
909 $this->element('h1', null, $this->title());
913 * Show page notice block.
915 * Only show the block if a subclassed action has overrided
916 * Action::showPageNotice(), or an event handler is registered for
917 * the StartShowPageNotice event, in which case we assume the
918 * 'page_notice' definition list is desired. This is to prevent
919 * empty 'page_notice' definition lists from being output everywhere.
923 function showPageNoticeBlock()
925 $rmethod = new ReflectionMethod($this, 'showPageNotice');
926 $dclass = $rmethod->getDeclaringClass()->getName();
928 if ($dclass != 'Action' || Event::hasHandler('StartShowPageNotice')) {
930 $this->elementStart('div', array('id' => 'page_notice',
931 'class' => 'system_notice'));
932 if (Event::handle('StartShowPageNotice', array($this))) {
933 $this->showPageNotice();
934 Event::handle('EndShowPageNotice', array($this));
936 $this->elementEnd('div');
943 * SHOULD overload (unless there's not a notice)
947 function showPageNotice()
954 * MUST overload (unless there's not a notice)
958 protected function showContent()
969 $this->elementStart('div', array('id' => 'aside_primary',
970 'class' => 'aside'));
971 $this->showProfileBlock();
972 if (Event::handle('StartShowObjectNavBlock', array($this))) {
973 $this->showObjectNavBlock();
974 Event::handle('EndShowObjectNavBlock', array($this));
976 if (Event::handle('StartShowSections', array($this))) {
977 $this->showSections();
978 Event::handle('EndShowSections', array($this));
980 if (Event::handle('StartShowExportData', array($this))) {
981 $this->showExportData();
982 Event::handle('EndShowExportData', array($this));
984 $this->elementEnd('div');
988 * Show export data feeds.
992 function showExportData()
994 $feeds = $this->getFeeds();
996 $fl = new FeedList($this);
1008 function showSections()
1010 // for each section, show it
1018 function showFooter()
1020 $this->elementStart('div', array('id' => 'footer'));
1021 if (Event::handle('StartShowInsideFooter', array($this))) {
1022 $this->showSecondaryNav();
1023 $this->showLicenses();
1024 Event::handle('EndShowInsideFooter', array($this));
1026 $this->elementEnd('div');
1030 * Show secondary navigation.
1034 function showSecondaryNav()
1036 $sn = new SecondaryNav($this);
1045 function showLicenses()
1047 $this->showGNUsocialLicense();
1048 $this->showContentLicense();
1052 * Show GNU social license.
1056 function showGNUsocialLicense()
1058 if (common_config('site', 'broughtby')) {
1059 // TRANS: First sentence of the GNU social site license. Used if 'broughtby' is set.
1060 // TRANS: Text between [] is a link description, text between () is the link itself.
1061 // TRANS: Make sure there is no whitespace between "]" and "(".
1062 // TRANS: "%%site.broughtby%%" is the value of the variable site.broughtby
1063 $instr = _('**%%site.name%%** is a social network, courtesy of [%%site.broughtby%%](%%site.broughtbyurl%%).');
1065 // TRANS: First sentence of the GNU social site license. Used if 'broughtby' is not set.
1066 $instr = _('**%%site.name%%** is a social network.');
1069 // TRANS: Second sentence of the GNU social site license. Mentions the GNU social source code license.
1070 // TRANS: Make sure there is no whitespace between "]" and "(".
1071 // TRANS: [%1$s](%2$s) is a link description followed by the link itself
1072 // TRANS: %3$s is the version of GNU social that is being used.
1073 $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);
1074 $output = common_markup_to_html($instr);
1075 $this->raw($output);
1080 * Show content license.
1084 function showContentLicense()
1086 if (Event::handle('StartShowContentLicense', array($this))) {
1087 switch (common_config('license', 'type')) {
1089 // TRANS: Content license displayed when license is set to 'private'.
1090 // TRANS: %1$s is the site name.
1091 $this->element('p', null, sprintf(_('Content and data of %1$s are private and confidential.'),
1092 common_config('site', 'name')));
1094 case 'allrightsreserved':
1095 if (common_config('license', 'owner')) {
1096 // TRANS: Content license displayed when license is set to 'allrightsreserved'.
1097 // TRANS: %1$s is the copyright owner.
1098 $this->element('p', null, sprintf(_('Content and data copyright by %1$s. All rights reserved.'),
1099 common_config('license', 'owner')));
1101 // TRANS: Content license displayed when license is set to 'allrightsreserved' and no owner is set.
1102 $this->element('p', null, _('Content and data copyright by contributors. All rights reserved.'));
1105 case 'cc': // fall through
1107 $this->elementStart('p');
1109 $image = common_config('license', 'image');
1110 $sslimage = common_config('license', 'sslimage');
1112 if (StatusNet::isHTTPS()) {
1113 if (!empty($sslimage)) {
1115 } else if (preg_match('#^http://i.creativecommons.org/#', $image)) {
1116 // CC support HTTPS on their images
1117 $url = preg_replace('/^http/', 'https', $image);
1119 // Better to show mixed content than no content
1126 $this->element('img', array('id' => 'license_cc',
1128 'alt' => common_config('license', 'title'),
1132 // TRANS: license message in footer.
1133 // TRANS: %1$s is the site name, %2$s is a link to the license URL, with a licence name set in configuration.
1134 $notice = _('All %1$s content and data are available under the %2$s license.');
1135 $link = "<a class=\"license\" rel=\"external license\" href=\"" .
1136 htmlspecialchars(common_config('license', 'url')) .
1138 htmlspecialchars(common_config('license', 'title')) .
1140 $this->raw(sprintf(htmlspecialchars($notice),
1141 htmlspecialchars(common_config('site', 'name')),
1143 $this->elementEnd('p');
1147 Event::handle('EndShowContentLicense', array($this));
1152 * Return last modified, if applicable.
1156 * @return string last modified http header
1158 function lastModified()
1160 // For comparison with If-Last-Modified
1161 // If not applicable, return null
1166 * Return etag, if applicable.
1170 * @return string etag http header
1178 * Return true if read only.
1182 * @param array $args other arguments
1184 * @return boolean is read only action?
1186 function isReadOnly($args)
1192 * Returns query argument or default value if not found
1194 * @param string $key requested argument
1195 * @param string $def default value to return if $key is not provided
1197 * @return boolean is read only action?
1199 function arg($key, $def=null)
1201 if (array_key_exists($key, $this->args)) {
1202 return $this->args[$key];
1209 * Returns trimmed query argument or default value if not found
1211 * @param string $key requested argument
1212 * @param string $def default value to return if $key is not provided
1214 * @return boolean is read only action?
1216 function trimmed($key, $def=null)
1218 $arg = $this->arg($key, $def);
1219 return is_string($arg) ? trim($arg) : $arg;
1225 * @return boolean is read only action?
1227 protected function handle()
1229 header('Vary: Accept-Encoding,Cookie');
1231 $lm = $this->lastModified();
1232 $etag = $this->etag();
1235 header('ETag: ' . $etag);
1239 header('Last-Modified: ' . date(DATE_RFC1123, $lm));
1240 if ($this->isCacheable()) {
1241 header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', 0 ) . ' GMT' );
1242 header( "Cache-Control: private, must-revalidate, max-age=0" );
1249 $if_none_match = (array_key_exists('HTTP_IF_NONE_MATCH', $_SERVER)) ?
1250 $_SERVER['HTTP_IF_NONE_MATCH'] : null;
1251 if ($if_none_match) {
1252 // If this check fails, ignore the if-modified-since below.
1254 if ($this->_hasEtag($etag, $if_none_match)) {
1255 header('HTTP/1.1 304 Not Modified');
1256 // Better way to do this?
1262 if (!$checked && $lm && array_key_exists('HTTP_IF_MODIFIED_SINCE', $_SERVER)) {
1263 $if_modified_since = $_SERVER['HTTP_IF_MODIFIED_SINCE'];
1264 $ims = strtotime($if_modified_since);
1266 header('HTTP/1.1 304 Not Modified');
1267 // Better way to do this?
1274 * Is this action cacheable?
1276 * If the action returns a last-modified
1278 * @param array $argarray is ignored since it's now passed in in prepare()
1280 * @return boolean is read only action?
1282 function isCacheable()
1288 * Has etag? (private)
1290 * @param string $etag etag http header
1291 * @param string $if_none_match ifNoneMatch http header
1295 function _hasEtag($etag, $if_none_match)
1297 $etags = explode(',', $if_none_match);
1298 return in_array($etag, $etags) || in_array('*', $etags);
1302 * Boolean understands english (yes, no, true, false)
1304 * @param string $key query key we're interested in
1305 * @param string $def default value
1307 * @return boolean interprets yes/no strings as boolean
1309 function boolean($key, $def=false)
1311 $arg = strtolower($this->trimmed($key));
1313 if (is_null($arg)) {
1315 } else if (in_array($arg, array('true', 'yes', '1', 'on'))) {
1317 } else if (in_array($arg, array('false', 'no', '0'))) {
1325 * Integer value of an argument
1327 * @param string $key query key we're interested in
1328 * @param string $defValue optional default value (default null)
1329 * @param string $maxValue optional max value (default null)
1330 * @param string $minValue optional min value (default null)
1332 * @return integer integer value
1334 function int($key, $defValue=null, $maxValue=null, $minValue=null)
1336 $arg = intval($this->arg($key));
1338 if (!is_numeric($this->arg($key)) || $arg != $this->arg($key)) {
1342 if (!is_null($maxValue)) {
1343 $arg = min($arg, $maxValue);
1346 if (!is_null($minValue)) {
1347 $arg = max($arg, $minValue);
1356 * @param string $msg error message to display
1357 * @param integer $code http error code, 500 by default
1361 function serverError($msg, $code=500, $format=null)
1363 if ($format === null) {
1364 $format = $this->format;
1367 common_debug("Server error '{$code}' on '{$this->action}': {$msg}", __FILE__);
1369 if (!array_key_exists($code, ServerErrorAction::$status)) {
1373 $status_string = ServerErrorAction::$status[$code];
1377 header("HTTP/1.1 {$code} {$status_string}");
1378 $this->initDocument('xml');
1379 $this->elementStart('hash');
1380 $this->element('error', null, $msg);
1381 $this->element('request', null, $_SERVER['REQUEST_URI']);
1382 $this->elementEnd('hash');
1383 $this->endDocument('xml');
1386 if (!isset($this->callback)) {
1387 header("HTTP/1.1 {$code} {$status_string}");
1389 $this->initDocument('json');
1390 $error_array = array('error' => $msg, 'request' => $_SERVER['REQUEST_URI']);
1391 print(json_encode($error_array));
1392 $this->endDocument('json');
1395 throw new ServerException($msg, $code);
1404 * @param string $msg error message to display
1405 * @param integer $code http error code, 400 by default
1406 * @param string $format error format (json, xml, text) for ApiAction
1409 * @throws ClientException always
1411 function clientError($msg, $code=400, $format=null)
1413 // $format is currently only relevant for an ApiAction anyway
1414 if ($format === null) {
1415 $format = $this->format;
1418 common_debug("User error '{$code}' on '{$this->action}': {$msg}", __FILE__);
1420 if (!array_key_exists($code, ClientErrorAction::$status)) {
1424 $status_string = ClientErrorAction::$status[$code];
1428 header("HTTP/1.1 {$code} {$status_string}");
1429 $this->initDocument('xml');
1430 $this->elementStart('hash');
1431 $this->element('error', null, $msg);
1432 $this->element('request', null, $_SERVER['REQUEST_URI']);
1433 $this->elementEnd('hash');
1434 $this->endDocument('xml');
1437 if (!isset($this->callback)) {
1438 header("HTTP/1.1 {$code} {$status_string}");
1440 $this->initDocument('json');
1441 $error_array = array('error' => $msg, 'request' => $_SERVER['REQUEST_URI']);
1442 $this->text(json_encode($error_array));
1443 $this->endDocument('json');
1446 header("HTTP/1.1 {$code} {$status_string}");
1447 header('Content-Type: text/plain; charset=utf-8');
1451 throw new ClientException($msg, $code);
1457 * If not logged in, take appropriate action (redir or exception)
1459 * @param boolean $redir Redirect to login if not logged in
1461 * @return boolean true if logged in (never returns if not)
1463 public function checkLogin($redir=true)
1465 if (common_logged_in()) {
1470 common_set_returnto($_SERVER['REQUEST_URI']);
1471 common_redirect(common_local_url('login'));
1474 // TRANS: Error message displayed when trying to perform an action that requires a logged in user.
1475 $this->clientError(_('Not logged in.'), 403);
1479 * Returns the current URL
1481 * @return string current URL
1485 list($action, $args) = $this->returnToArgs();
1486 return common_local_url($action, $args);
1490 * Returns arguments sufficient for re-constructing URL
1492 * @return array two elements: action, other args
1494 function returnToArgs()
1496 $action = $this->getActionName();
1497 $args = $this->args;
1498 unset($args['action']);
1499 if (common_config('site', 'fancy')) {
1502 if (array_key_exists('submit', $args)) {
1503 unset($args['submit']);
1505 foreach (array_keys($_COOKIE) as $cookie) {
1506 unset($args[$cookie]);
1508 return array($action, $args);
1512 * Generate a menu item
1514 * @param string $url menu URL
1515 * @param string $text menu name
1516 * @param string $title title attribute, null by default
1517 * @param boolean $is_selected current menu item, false by default
1518 * @param string $id element id, null by default
1522 function menuItem($url, $text, $title=null, $is_selected=false, $id=null, $class=null)
1524 // Added @id to li for some control.
1525 // XXX: We might want to move this to htmloutputter.php
1528 if ($class !== null) {
1529 $classes[] = trim($class);
1532 $classes[] = 'current';
1535 if (!empty($classes)) {
1536 $lattrs['class'] = implode(' ', $classes);
1539 if (!is_null($id)) {
1540 $lattrs['id'] = $id;
1543 $this->elementStart('li', $lattrs);
1544 $attrs['href'] = $url;
1546 $attrs['title'] = $title;
1548 $this->element('a', $attrs, $text);
1549 $this->elementEnd('li');
1553 * Generate pagination links
1555 * @param boolean $have_before is there something before?
1556 * @param boolean $have_after is there something after?
1557 * @param integer $page current page
1558 * @param string $action current action
1559 * @param array $args rest of query arguments
1563 // XXX: The messages in this pagination method only tailor to navigating
1564 // notices. In other lists, "Previous"/"Next" type navigation is
1565 // desirable, but not available.
1566 function pagination($have_before, $have_after, $page, $action, $args=null)
1568 // Does a little before-after block for next/prev page
1569 if ($have_before || $have_after) {
1570 $this->elementStart('ul', array('class' => 'nav',
1571 'id' => 'pagination'));
1574 $pargs = array('page' => $page-1);
1575 $this->elementStart('li', array('class' => 'nav_prev'));
1576 $this->element('a', array('href' => common_local_url($action, $args, $pargs),
1578 // TRANS: Pagination message to go to a page displaying information more in the
1579 // TRANS: present than the currently displayed information.
1581 $this->elementEnd('li');
1584 $pargs = array('page' => $page+1);
1585 $this->elementStart('li', array('class' => 'nav_next'));
1586 $this->element('a', array('href' => common_local_url($action, $args, $pargs),
1588 // TRANS: Pagination message to go to a page displaying information more in the
1589 // TRANS: past than the currently displayed information.
1591 $this->elementEnd('li');
1593 if ($have_before || $have_after) {
1594 $this->elementEnd('ul');
1599 * An array of feeds for this action.
1601 * Returns an array of potential feeds for this action.
1603 * @return array Feed object to show in head and links
1611 * Check the session token.
1613 * Checks that the current form has the correct session token,
1614 * and throw an exception if it does not.
1618 // XXX: Finding this type of check with the same message about 50 times.
1619 // Possible to refactor?
1620 function checkSessionToken()
1623 $token = $this->trimmed('token');
1624 if (empty($token) || $token != common_session_token()) {
1625 // TRANS: Client error text when there is a problem with the session token.
1626 $this->clientError(_('There was a problem with your session token.'));
1631 * Check if the current request is a POST
1633 * @return boolean true if POST; otherwise false.
1638 return ($_SERVER['REQUEST_METHOD'] == 'POST');