3 * StatusNet, the distributed open-source microblogging tool
5 * Base class for all actions (~views)
9 * LICENCE: This program is free software: you can redistribute it and/or modify
10 * it under the terms of the GNU Affero General Public License as published by
11 * the Free Software Foundation, either version 3 of the License, or
12 * (at your option) any later version.
14 * This program is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 * GNU Affero General Public License for more details.
19 * You should have received a copy of the GNU Affero General Public License
20 * along with this program. If not, see <http://www.gnu.org/licenses/>.
24 * @author Evan Prodromou <evan@status.net>
25 * @author Sarven Capadisli <csarven@status.net>
26 * @copyright 2008 StatusNet, Inc.
27 * @license http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
28 * @link http://status.net/
31 if (!defined('GNUSOCIAL')) { exit(1); }
34 * Base class for all actions
36 * This is the base class for all actions in the package. An action is
37 * more or less a "view" in an MVC framework.
39 * Actions are responsible for extracting and validating parameters; using
40 * model classes to read and write to the database; and doing ouput.
44 * @author Evan Prodromou <evan@status.net>
45 * @author Sarven Capadisli <csarven@status.net>
46 * @license http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
47 * @link http://status.net/
51 class Action extends HTMLOutputter // lawsuit
53 // This should be protected/private in the future
54 public $args = array();
56 // Action properties, set per-class
57 protected $action = false;
58 protected $ajax = false;
59 protected $menus = true;
60 protected $needLogin = false;
61 protected $needPost = false;
63 // The currently scoped profile (normally Profile::current; from $this->auth_user for API)
64 protected $scoped = null;
66 // Related to front-end user representation
67 protected $format = null;
68 protected $error = null;
69 protected $msg = null;
74 * Just wraps the HTMLOutputter constructor.
76 * @param string $output URI to output to, default = stdout
77 * @param boolean $indent Whether to indent output, default true
79 * @see XMLOutputter::__construct
80 * @see HTMLOutputter::__construct
82 function __construct($output='php://output', $indent=null)
84 parent::__construct($output, $indent);
97 static public function run(array $args=array(), $output='php://output', $indent=null) {
98 $class = get_called_class();
99 $action = new $class($output, $indent);
100 $action->execute($args);
104 public function execute(array $args=array()) {
106 if (common_config('db', 'mirror') && $this->isReadOnly($args)) {
107 if (is_array(common_config('db', 'mirror'))) {
108 // "load balancing", ha ha
109 $arr = common_config('db', 'mirror');
110 $k = array_rand($arr);
113 $mirror = common_config('db', 'mirror');
116 // everyone else uses the mirror
117 common_config_set('db', 'database', $mirror);
120 if ($this->prepare($args)) {
121 $this->handle($args);
126 * For initializing members of the class.
128 * @param array $argarray misc. arguments
130 * @return boolean true
132 protected function prepare(array $args=array())
134 if ($this->needPost && !$this->isPost()) {
135 // TRANS: Client error. POST is a HTTP command. It should not be translated.
136 $this->clientError(_('This method requires a POST.'), 405);
139 $this->args = common_copy_args($args);
141 $this->action = $this->trimmed('action');
143 if ($this->ajax || $this->boolean('ajax')) {
144 // check with StatusNet::isAjax()
145 StatusNet::setAjax(true);
148 if ($this->needLogin) {
149 $this->checkLogin(); // if not logged in, this redirs/excepts
152 $this->updateScopedProfile();
157 function updateScopedProfile() {
158 $this->scoped = Profile::current();
159 return $this->scoped;
163 * Show page, a template method.
169 if (Event::handle('StartShowHTML', array($this))) {
172 Event::handle('EndShowHTML', array($this));
174 if (Event::handle('StartShowHead', array($this))) {
177 Event::handle('EndShowHead', array($this));
179 if (Event::handle('StartShowBody', array($this))) {
181 Event::handle('EndShowBody', array($this));
183 if (Event::handle('StartEndHTML', array($this))) {
185 Event::handle('EndEndHTML', array($this));
193 if (isset($_startTime)) {
194 $endTime = microtime(true);
195 $diff = round(($endTime - $_startTime) * 1000);
196 $this->raw("<!-- ${diff}ms -->");
199 return parent::endHTML();
203 * Show head, a template method.
209 // XXX: attributes (profile?)
210 $this->elementStart('head');
211 if (Event::handle('StartShowHeadElements', array($this))) {
212 if (Event::handle('StartShowHeadTitle', array($this))) {
214 Event::handle('EndShowHeadTitle', array($this));
216 $this->showShortcutIcon();
217 $this->showStylesheets();
218 $this->showOpenSearch();
220 $this->showDescription();
222 Event::handle('EndShowHeadElements', array($this));
224 $this->elementEnd('head');
228 * Show title, a template method.
234 $this->element('title', null,
235 // TRANS: Page title. %1$s is the title, %2$s is the site name.
236 sprintf(_('%1$s - %2$s'),
238 common_config('site', 'name')));
242 * Returns the page title
246 * @return string page title
251 // TRANS: Page title for a page without a title set.
252 return _('Untitled page');
256 * Show themed shortcut icon
260 function showShortcutIcon()
262 if (is_readable(INSTALLDIR . '/theme/' . common_config('site', 'theme') . '/favicon.ico')) {
263 $this->element('link', array('rel' => 'shortcut icon',
264 'href' => Theme::path('favicon.ico')));
266 // favicon.ico should be HTTPS if the rest of the page is
267 $this->element('link', array('rel' => 'shortcut icon',
268 'href' => common_path('favicon.ico', StatusNet::isHTTPS())));
271 if (common_config('site', 'mobile')) {
272 if (is_readable(INSTALLDIR . '/theme/' . common_config('site', 'theme') . '/apple-touch-icon.png')) {
273 $this->element('link', array('rel' => 'apple-touch-icon',
274 'href' => Theme::path('apple-touch-icon.png')));
276 $this->element('link', array('rel' => 'apple-touch-icon',
277 'href' => common_path('apple-touch-icon.png')));
287 function showStylesheets()
289 if (Event::handle('StartShowStyles', array($this))) {
291 // Use old name for StatusNet for compatibility on events
293 if (Event::handle('StartShowStylesheets', array($this))) {
294 $this->primaryCssLink(null, 'screen, projection, tv, print');
295 Event::handle('EndShowStylesheets', array($this));
298 $this->cssLink('js/extlib/jquery-ui/css/smoothness/jquery-ui.css');
300 if (Event::handle('StartShowUAStyles', array($this))) {
301 $this->comment('[if IE]><link rel="stylesheet" type="text/css" '.
302 'href="'.Theme::path('css/ie.css', 'base').'?version='.GNUSOCIAL_VERSION.'" /><![endif]');
303 foreach (array(6,7) as $ver) {
304 if (file_exists(Theme::file('css/ie'.$ver.'.css', 'base'))) {
305 // Yes, IE people should be put in jail.
306 $this->comment('[if lte IE '.$ver.']><link rel="stylesheet" type="text/css" '.
307 'href="'.Theme::path('css/ie'.$ver.'.css', 'base').'?version='.GNUSOCIAL_VERSION.'" /><![endif]');
310 if (file_exists(Theme::file('css/ie.css'))) {
311 $this->comment('[if IE]><link rel="stylesheet" type="text/css" '.
312 'href="'.Theme::path('css/ie.css', null).'?version='.GNUSOCIAL_VERSION.'" /><![endif]');
314 Event::handle('EndShowUAStyles', array($this));
317 Event::handle('EndShowStyles', array($this));
319 if (common_config('custom_css', 'enabled')) {
320 $css = common_config('custom_css', 'css');
321 if (Event::handle('StartShowCustomCss', array($this, &$css))) {
322 if (trim($css) != '') {
325 Event::handle('EndShowCustomCss', array($this));
331 function primaryCssLink($mainTheme=null, $media=null)
333 $theme = new Theme($mainTheme);
335 // Some themes may have external stylesheets, such as using the
336 // Google Font APIs to load webfonts.
337 foreach ($theme->getExternals() as $url) {
338 $this->cssLink($url, $mainTheme, $media);
341 // If the currently-selected theme has dependencies on other themes,
342 // we'll need to load their display.css files as well in order.
343 $baseThemes = $theme->getDeps();
344 foreach ($baseThemes as $baseTheme) {
345 $this->cssLink('css/display.css', $baseTheme, $media);
347 $this->cssLink('css/display.css', $mainTheme, $media);
349 // Additional styles for RTL languages
350 if (is_rtl(common_language())) {
351 if (file_exists(Theme::file('css/rtl.css'))) {
352 $this->cssLink('css/rtl.css', $mainTheme, $media);
358 * Show javascript headers
362 function showScripts()
364 if (Event::handle('StartShowScripts', array($this))) {
365 if (Event::handle('StartShowJQueryScripts', array($this))) {
366 if (common_config('site', 'minify')) {
367 $this->script('extlib/jquery.min.js');
368 $this->script('extlib/jquery.form.min.js');
369 $this->script('extlib/jquery-ui/jquery-ui.min.js');
370 $this->script('extlib/jquery.cookie.min.js');
371 $this->inlineScript('if (typeof window.JSON !== "object") { $.getScript("'.common_path('js/extlib/json2.min.js', StatusNet::isHTTPS()).'"); }');
372 $this->script('extlib/jquery.infieldlabel.min.js');
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');
382 Event::handle('EndShowJQueryScripts', array($this));
384 if (Event::handle('StartShowStatusNetScripts', array($this)) &&
385 Event::handle('StartShowLaconicaScripts', array($this))) {
386 if (common_config('site', 'minify')) {
387 $this->script('util.min.js');
389 $this->script('util.js');
390 $this->script('xbImportNode.js');
391 $this->script('geometa.js');
393 // This route isn't available in single-user mode.
394 // Not sure why, but it causes errors here.
395 $this->inlineScript('var _peopletagAC = "' .
396 common_local_url('peopletagautocomplete') . '";');
397 $this->showScriptMessages();
398 // Anti-framing code to avoid clickjacking attacks in older browsers.
399 // This will show a blank page if the page is being framed, which is
400 // consistent with the behavior of the 'X-Frame-Options: SAMEORIGIN'
401 // header, which prevents framing in newer browser.
402 if (common_config('javascript', 'bustframes')) {
403 $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 = ""; }; }');
405 Event::handle('EndShowStatusNetScripts', array($this));
406 Event::handle('EndShowLaconicaScripts', array($this));
408 Event::handle('EndShowScripts', array($this));
413 * Exports a map of localized text strings to JavaScript code.
415 * Plugins can add to what's exported by hooking the StartScriptMessages or EndScriptMessages
416 * events and appending to the array. Try to avoid adding strings that won't be used, as
417 * they'll be added to HTML output.
419 function showScriptMessages()
423 if (Event::handle('StartScriptMessages', array($this, &$messages))) {
424 // Common messages needed for timeline views etc...
426 // TRANS: Localized tooltip for '...' expansion button on overlong remote messages.
427 $messages['showmore_tooltip'] = _m('TOOLTIP', 'Show more');
429 // TRANS: Inline reply form submit button: submits a reply comment.
430 $messages['reply_submit'] = _m('BUTTON', 'Reply');
432 // TRANS: Placeholder text for inline reply form. Clicking in this box will turn it into a mini notice form.
433 $messages['reply_placeholder'] = _m('Write a reply...');
435 $messages = array_merge($messages, $this->getScriptMessages());
437 Event::handle('EndScriptMessages', array($this, &$messages));
440 if (!empty($messages)) {
441 $this->inlineScript('SN.messages=' . json_encode($messages));
448 * If the action will need localizable text strings, export them here like so:
450 * return array('pool_deepend' => _('Deep end'),
451 * 'pool_shallow' => _('Shallow end'));
453 * The exported map will be available via SN.msg() to JS code:
455 * $('#pool').html('<div class="deepend"></div><div class="shallow"></div>');
456 * $('#pool .deepend').text(SN.msg('pool_deepend'));
457 * $('#pool .shallow').text(SN.msg('pool_shallow'));
459 * Exports a map of localized text strings to JavaScript code.
461 * Plugins can add to what's exported on any action by hooking the StartScriptMessages or
462 * EndScriptMessages events and appending to the array. Try to avoid adding strings that won't
463 * be used, as they'll be added to HTML output.
465 function getScriptMessages()
471 * Show OpenSearch headers
475 function showOpenSearch()
477 $this->element('link', array('rel' => 'search',
478 'type' => 'application/opensearchdescription+xml',
479 'href' => common_local_url('opensearch', array('type' => 'people')),
480 'title' => common_config('site', 'name').' People Search'));
481 $this->element('link', array('rel' => 'search', 'type' => 'application/opensearchdescription+xml',
482 'href' => common_local_url('opensearch', array('type' => 'notice')),
483 'title' => common_config('site', 'name').' Notice Search'));
495 $feeds = $this->getFeeds();
498 foreach ($feeds as $feed) {
499 $this->element('link', array('rel' => $feed->rel(),
500 'href' => $feed->url,
501 'type' => $feed->mimeType(),
502 'title' => $feed->title));
514 function showDescription()
516 // does nothing by default
520 * Show extra stuff in <head>.
528 // does nothing by default
534 * Calls template methods
540 $this->elementStart('body', (common_current_user()) ? array('id' => strtolower($this->trimmed('action')),
541 'class' => 'user_in')
542 : array('id' => strtolower($this->trimmed('action'))));
543 $this->elementStart('div', array('id' => 'wrap'));
544 if (Event::handle('StartShowHeader', array($this))) {
547 Event::handle('EndShowHeader', array($this));
551 if (Event::handle('StartShowFooter', array($this))) {
554 Event::handle('EndShowFooter', array($this));
556 $this->elementEnd('div');
557 $this->showScripts();
558 $this->elementEnd('body');
562 * Show header of the page.
564 * Calls template methods
568 function showHeader()
570 $this->elementStart('div', array('id' => 'header'));
572 $this->showPrimaryNav();
573 if (Event::handle('StartShowSiteNotice', array($this))) {
574 $this->showSiteNotice();
576 Event::handle('EndShowSiteNotice', array($this));
579 $this->elementEnd('div');
583 * Show configured logo.
589 $this->elementStart('address', array('id' => 'site_contact',
590 'class' => 'vcard'));
591 if (Event::handle('StartAddressData', array($this))) {
592 if (common_config('singleuser', 'enabled')) {
593 $user = User::singleUser();
594 $url = common_local_url('showstream',
595 array('nickname' => $user->nickname));
596 } else if (common_logged_in()) {
597 $cur = common_current_user();
598 $url = common_local_url('all', array('nickname' => $cur->nickname));
600 $url = common_local_url('public');
603 $this->elementStart('a', array('class' => 'url home bookmark',
606 if (StatusNet::isHTTPS()) {
607 $logoUrl = common_config('site', 'ssllogo');
608 if (empty($logoUrl)) {
609 // if logo is an uploaded file, try to fall back to HTTPS file URL
610 $httpUrl = common_config('site', 'logo');
611 if (!empty($httpUrl)) {
612 $f = File::getKV('url', $httpUrl);
613 if (!empty($f) && !empty($f->filename)) {
614 // this will handle the HTTPS case
615 $logoUrl = File::url($f->filename);
620 $logoUrl = common_config('site', 'logo');
623 if (empty($logoUrl) && file_exists(Theme::file('logo.png'))) {
624 // This should handle the HTTPS case internally
625 $logoUrl = Theme::path('logo.png');
628 if (!empty($logoUrl)) {
629 $this->element('img', array('class' => 'logo photo',
631 'alt' => common_config('site', 'name')));
635 $this->element('span', array('class' => 'fn org'), common_config('site', 'name'));
636 $this->elementEnd('a');
638 Event::handle('EndAddressData', array($this));
640 $this->elementEnd('address');
644 * Show primary navigation.
648 function showPrimaryNav()
650 $this->elementStart('div', array('id' => 'site_nav_global_primary'));
652 $user = common_current_user();
654 if (!empty($user) || !common_config('site', 'private')) {
655 $form = new SearchForm($this);
659 $pn = new PrimaryNav($this);
661 $this->elementEnd('div');
669 function showSiteNotice()
671 // Revist. Should probably do an hAtom pattern here
672 $text = common_config('site', 'notice');
674 $this->elementStart('div', array('id' => 'site_notice',
675 'class' => 'system_notice'));
677 $this->elementEnd('div');
684 * MAY overload if no notice form needed... or direct message box????
688 function showNoticeForm()
690 // TRANS: Tab on the notice form.
691 $tabs = array('status' => _m('TAB','Status'));
693 $this->elementStart('div', 'input_forms');
695 if (Event::handle('StartShowEntryForms', array(&$tabs))) {
696 $this->elementStart('ul', array('class' => 'nav',
697 'id' => 'input_form_nav'));
699 foreach ($tabs as $tag => $title) {
700 $attrs = array('id' => 'input_form_nav_'.$tag,
701 'class' => 'input_form_nav_tab');
703 if ($tag == 'status') {
704 // We're actually showing the placeholder form,
705 // but we special-case the 'Status' tab as if
706 // it were a small version of it.
707 $attrs['class'] .= ' current';
709 $this->elementStart('li', $attrs);
712 array('href' => 'javascript:SN.U.switchInputFormTab("'.$tag.'")'),
714 $this->elementEnd('li');
717 $this->elementEnd('ul');
719 $attrs = array('class' => 'input_form current',
720 'id' => 'input_form_placeholder');
721 $this->elementStart('div', $attrs);
722 $form = new NoticePlaceholderForm($this);
724 $this->elementEnd('div');
726 foreach ($tabs as $tag => $title) {
727 $attrs = array('class' => 'input_form',
728 'id' => 'input_form_'.$tag);
730 $this->elementStart('div', $attrs);
734 if (Event::handle('StartMakeEntryForm', array($tag, $this, &$form))) {
735 if ($tag == 'status') {
736 $options = $this->noticeFormOptions();
737 $form = new NoticeForm($this, $options);
739 Event::handle('EndMakeEntryForm', array($tag, $this, $form));
746 $this->elementEnd('div');
750 $this->elementEnd('div');
753 function noticeFormOptions()
759 * Show anonymous message.
765 function showAnonymousMessage()
767 // needs to be defined by the class
773 * Shows local navigation, content block and aside.
779 $this->elementStart('div', array('id' => 'core'));
780 $this->elementStart('div', array('id' => 'aside_primary_wrapper'));
781 $this->elementStart('div', array('id' => 'content_wrapper'));
782 $this->elementStart('div', array('id' => 'site_nav_local_views_wrapper'));
783 if (Event::handle('StartShowLocalNavBlock', array($this))) {
784 $this->showLocalNavBlock();
786 Event::handle('EndShowLocalNavBlock', array($this));
788 if (Event::handle('StartShowContentBlock', array($this))) {
789 $this->showContentBlock();
791 Event::handle('EndShowContentBlock', array($this));
793 if (Event::handle('StartShowAside', array($this))) {
796 Event::handle('EndShowAside', array($this));
798 $this->elementEnd('div');
799 $this->elementEnd('div');
800 $this->elementEnd('div');
801 $this->elementEnd('div');
805 * Show local navigation block.
809 function showLocalNavBlock()
811 // Need to have this ID for CSS; I'm too lazy to add it to
813 $this->elementStart('div', array('id' => 'site_nav_local_views'));
814 // Cheat cheat cheat!
815 $this->showLocalNav();
816 $this->elementEnd('div');
820 * If there's a logged-in user, show a bit of login context
824 function showProfileBlock()
826 if (common_logged_in()) {
827 $block = new DefaultProfileBlock($this);
833 * Show local navigation.
839 function showLocalNav()
841 $nav = new DefaultLocalNav($this);
846 * Show menu for an object (group, profile)
848 * This block will only show if a subclass has overridden
849 * the showObjectNav() method.
853 function showObjectNavBlock()
855 $rmethod = new ReflectionMethod($this, 'showObjectNav');
856 $dclass = $rmethod->getDeclaringClass()->getName();
858 if ($dclass != 'Action') {
859 // Need to have this ID for CSS; I'm too lazy to add it to
861 $this->elementStart('div', array('id' => 'site_nav_object',
862 'class' => 'section'));
863 $this->showObjectNav();
864 $this->elementEnd('div');
869 * Show object navigation.
871 * If there are things to do with this object, show it here.
875 function showObjectNav()
881 * Show content block.
885 function showContentBlock()
887 $this->elementStart('div', array('id' => 'content'));
888 if (common_logged_in()) {
889 if (Event::handle('StartShowNoticeForm', array($this))) {
890 $this->showNoticeForm();
891 Event::handle('EndShowNoticeForm', array($this));
894 if (Event::handle('StartShowPageTitle', array($this))) {
895 $this->showPageTitle();
896 Event::handle('EndShowPageTitle', array($this));
898 $this->showPageNoticeBlock();
899 $this->elementStart('div', array('id' => 'content_inner'));
900 // show the actual content (forms, lists, whatever)
901 $this->showContent();
902 $this->elementEnd('div');
903 $this->elementEnd('div');
911 function showPageTitle()
913 $this->element('h1', null, $this->title());
917 * Show page notice block.
919 * Only show the block if a subclassed action has overrided
920 * Action::showPageNotice(), or an event handler is registered for
921 * the StartShowPageNotice event, in which case we assume the
922 * 'page_notice' definition list is desired. This is to prevent
923 * empty 'page_notice' definition lists from being output everywhere.
927 function showPageNoticeBlock()
929 $rmethod = new ReflectionMethod($this, 'showPageNotice');
930 $dclass = $rmethod->getDeclaringClass()->getName();
932 if ($dclass != 'Action' || Event::hasHandler('StartShowPageNotice')) {
934 $this->elementStart('div', array('id' => 'page_notice',
935 'class' => 'system_notice'));
936 if (Event::handle('StartShowPageNotice', array($this))) {
937 $this->showPageNotice();
938 Event::handle('EndShowPageNotice', array($this));
940 $this->elementEnd('div');
947 * SHOULD overload (unless there's not a notice)
951 function showPageNotice()
958 * MUST overload (unless there's not a notice)
962 function showContent()
973 $this->elementStart('div', array('id' => 'aside_primary',
974 'class' => 'aside'));
975 $this->showProfileBlock();
976 if (Event::handle('StartShowObjectNavBlock', array($this))) {
977 $this->showObjectNavBlock();
978 Event::handle('EndShowObjectNavBlock', array($this));
980 if (Event::handle('StartShowSections', array($this))) {
981 $this->showSections();
982 Event::handle('EndShowSections', array($this));
984 if (Event::handle('StartShowExportData', array($this))) {
985 $this->showExportData();
986 Event::handle('EndShowExportData', array($this));
988 $this->elementEnd('div');
992 * Show export data feeds.
996 function showExportData()
998 $feeds = $this->getFeeds();
1000 $fl = new FeedList($this);
1012 function showSections()
1014 // for each section, show it
1022 function showFooter()
1024 $this->elementStart('div', array('id' => 'footer'));
1025 if (Event::handle('StartShowInsideFooter', array($this))) {
1026 $this->showSecondaryNav();
1027 $this->showLicenses();
1028 Event::handle('EndShowInsideFooter', array($this));
1030 $this->elementEnd('div');
1034 * Show secondary navigation.
1038 function showSecondaryNav()
1040 $sn = new SecondaryNav($this);
1049 function showLicenses()
1051 $this->showGNUsocialLicense();
1052 $this->showContentLicense();
1056 * Show GNU social license.
1060 function showGNUsocialLicense()
1062 if (common_config('site', 'broughtby')) {
1063 // TRANS: First sentence of the GNU social site license. Used if 'broughtby' is set.
1064 // TRANS: Text between [] is a link description, text between () is the link itself.
1065 // TRANS: Make sure there is no whitespace between "]" and "(".
1066 // TRANS: "%%site.broughtby%%" is the value of the variable site.broughtby
1067 $instr = _('**%%site.name%%** is a social network, courtesy of [%%site.broughtby%%](%%site.broughtbyurl%%).');
1069 // TRANS: First sentence of the GNU social site license. Used if 'broughtby' is not set.
1070 $instr = _('**%%site.name%%** is a social network.');
1073 // TRANS: Second sentence of the GNU social site license. Mentions the GNU social source code license.
1074 // TRANS: Make sure there is no whitespace between "]" and "(".
1075 // TRANS: [%1$s](%2$s) is a link description followed by the link itself
1076 // TRANS: %3$s is the version of GNU social that is being used.
1077 $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);
1078 $output = common_markup_to_html($instr);
1079 $this->raw($output);
1084 * Show content license.
1088 function showContentLicense()
1090 if (Event::handle('StartShowContentLicense', array($this))) {
1091 switch (common_config('license', 'type')) {
1093 // TRANS: Content license displayed when license is set to 'private'.
1094 // TRANS: %1$s is the site name.
1095 $this->element('p', null, sprintf(_('Content and data of %1$s are private and confidential.'),
1096 common_config('site', 'name')));
1098 case 'allrightsreserved':
1099 if (common_config('license', 'owner')) {
1100 // TRANS: Content license displayed when license is set to 'allrightsreserved'.
1101 // TRANS: %1$s is the copyright owner.
1102 $this->element('p', null, sprintf(_('Content and data copyright by %1$s. All rights reserved.'),
1103 common_config('license', 'owner')));
1105 // TRANS: Content license displayed when license is set to 'allrightsreserved' and no owner is set.
1106 $this->element('p', null, _('Content and data copyright by contributors. All rights reserved.'));
1109 case 'cc': // fall through
1111 $this->elementStart('p');
1113 $image = common_config('license', 'image');
1114 $sslimage = common_config('license', 'sslimage');
1116 if (StatusNet::isHTTPS()) {
1117 if (!empty($sslimage)) {
1119 } else if (preg_match('#^http://i.creativecommons.org/#', $image)) {
1120 // CC support HTTPS on their images
1121 $url = preg_replace('/^http/', 'https', $image);
1123 // Better to show mixed content than no content
1130 $this->element('img', array('id' => 'license_cc',
1132 'alt' => common_config('license', 'title'),
1136 // TRANS: license message in footer.
1137 // TRANS: %1$s is the site name, %2$s is a link to the license URL, with a licence name set in configuration.
1138 $notice = _('All %1$s content and data are available under the %2$s license.');
1139 $link = "<a class=\"license\" rel=\"external license\" href=\"" .
1140 htmlspecialchars(common_config('license', 'url')) .
1142 htmlspecialchars(common_config('license', 'title')) .
1144 $this->raw(sprintf(htmlspecialchars($notice),
1145 htmlspecialchars(common_config('site', 'name')),
1147 $this->elementEnd('p');
1151 Event::handle('EndShowContentLicense', array($this));
1156 * Return last modified, if applicable.
1160 * @return string last modified http header
1162 function lastModified()
1164 // For comparison with If-Last-Modified
1165 // If not applicable, return null
1170 * Return etag, if applicable.
1174 * @return string etag http header
1182 * Return true if read only.
1186 * @param array $args other arguments
1188 * @return boolean is read only action?
1190 function isReadOnly($args)
1196 * Returns query argument or default value if not found
1198 * @param string $key requested argument
1199 * @param string $def default value to return if $key is not provided
1201 * @return boolean is read only action?
1203 function arg($key, $def=null)
1205 if (array_key_exists($key, $this->args)) {
1206 return $this->args[$key];
1213 * Returns trimmed query argument or default value if not found
1215 * @param string $key requested argument
1216 * @param string $def default value to return if $key is not provided
1218 * @return boolean is read only action?
1220 function trimmed($key, $def=null)
1222 $arg = $this->arg($key, $def);
1223 return is_string($arg) ? trim($arg) : $arg;
1229 * @return boolean is read only action?
1231 protected function handle()
1233 header('Vary: Accept-Encoding,Cookie');
1235 $lm = $this->lastModified();
1236 $etag = $this->etag();
1239 header('ETag: ' . $etag);
1243 header('Last-Modified: ' . date(DATE_RFC1123, $lm));
1244 if ($this->isCacheable()) {
1245 header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', 0 ) . ' GMT' );
1246 header( "Cache-Control: private, must-revalidate, max-age=0" );
1253 $if_none_match = (array_key_exists('HTTP_IF_NONE_MATCH', $_SERVER)) ?
1254 $_SERVER['HTTP_IF_NONE_MATCH'] : null;
1255 if ($if_none_match) {
1256 // If this check fails, ignore the if-modified-since below.
1258 if ($this->_hasEtag($etag, $if_none_match)) {
1259 header('HTTP/1.1 304 Not Modified');
1260 // Better way to do this?
1266 if (!$checked && $lm && array_key_exists('HTTP_IF_MODIFIED_SINCE', $_SERVER)) {
1267 $if_modified_since = $_SERVER['HTTP_IF_MODIFIED_SINCE'];
1268 $ims = strtotime($if_modified_since);
1270 header('HTTP/1.1 304 Not Modified');
1271 // Better way to do this?
1278 * Is this action cacheable?
1280 * If the action returns a last-modified
1282 * @param array $argarray is ignored since it's now passed in in prepare()
1284 * @return boolean is read only action?
1286 function isCacheable()
1292 * Has etag? (private)
1294 * @param string $etag etag http header
1295 * @param string $if_none_match ifNoneMatch http header
1299 function _hasEtag($etag, $if_none_match)
1301 $etags = explode(',', $if_none_match);
1302 return in_array($etag, $etags) || in_array('*', $etags);
1306 * Boolean understands english (yes, no, true, false)
1308 * @param string $key query key we're interested in
1309 * @param string $def default value
1311 * @return boolean interprets yes/no strings as boolean
1313 function boolean($key, $def=false)
1315 $arg = strtolower($this->trimmed($key));
1317 if (is_null($arg)) {
1319 } else if (in_array($arg, array('true', 'yes', '1', 'on'))) {
1321 } else if (in_array($arg, array('false', 'no', '0'))) {
1329 * Integer value of an argument
1331 * @param string $key query key we're interested in
1332 * @param string $defValue optional default value (default null)
1333 * @param string $maxValue optional max value (default null)
1334 * @param string $minValue optional min value (default null)
1336 * @return integer integer value
1338 function int($key, $defValue=null, $maxValue=null, $minValue=null)
1340 $arg = strtolower($this->trimmed($key));
1342 if (is_null($arg) || !is_integer($arg)) {
1346 if (!is_null($maxValue)) {
1347 $arg = min($arg, $maxValue);
1350 if (!is_null($minValue)) {
1351 $arg = max($arg, $minValue);
1360 * @param string $msg error message to display
1361 * @param integer $code http error code, 500 by default
1365 function serverError($msg, $code=500, $format=null)
1367 if ($format === null) {
1368 $format = $this->format;
1371 common_debug("Server error '{$code}' on '{$this->action}': {$msg}", __FILE__);
1373 if (!array_key_exists($code, ServerErrorAction::$status)) {
1377 $status_string = ServerErrorAction::$status[$code];
1381 header("HTTP/1.1 {$code} {$status_string}");
1382 $this->initDocument('xml');
1383 $this->elementStart('hash');
1384 $this->element('error', null, $msg);
1385 $this->element('request', null, $_SERVER['REQUEST_URI']);
1386 $this->elementEnd('hash');
1387 $this->endDocument('xml');
1390 if (!isset($this->callback)) {
1391 header("HTTP/1.1 {$code} {$status_string}");
1393 $this->initDocument('json');
1394 $error_array = array('error' => $msg, 'request' => $_SERVER['REQUEST_URI']);
1395 print(json_encode($error_array));
1396 $this->endDocument('json');
1399 throw new ServerException($msg, $code);
1408 * @param string $msg error message to display
1409 * @param integer $code http error code, 400 by default
1410 * @param string $format error format (json, xml, text) for ApiAction
1413 * @throws ClientException always
1415 function clientError($msg, $code=400, $format=null)
1417 // $format is currently only relevant for an ApiAction anyway
1418 if ($format === null) {
1419 $format = $this->format;
1422 common_debug("User error '{$code}' on '{$this->action}': {$msg}", __FILE__);
1424 if (!array_key_exists($code, ClientErrorAction::$status)) {
1428 $status_string = ClientErrorAction::$status[$code];
1432 header("HTTP/1.1 {$code} {$status_string}");
1433 $this->initDocument('xml');
1434 $this->elementStart('hash');
1435 $this->element('error', null, $msg);
1436 $this->element('request', null, $_SERVER['REQUEST_URI']);
1437 $this->elementEnd('hash');
1438 $this->endDocument('xml');
1441 if (!isset($this->callback)) {
1442 header("HTTP/1.1 {$code} {$status_string}");
1444 $this->initDocument('json');
1445 $error_array = array('error' => $msg, 'request' => $_SERVER['REQUEST_URI']);
1446 $this->text(json_encode($error_array));
1447 $this->endDocument('json');
1450 header("HTTP/1.1 {$code} {$status_string}");
1451 header('Content-Type: text/plain; charset=utf-8');
1455 throw new ClientException($msg, $code);
1461 * If not logged in, take appropriate action (redir or exception)
1463 * @param boolean $redir Redirect to login if not logged in
1465 * @return boolean true if logged in (never returns if not)
1467 public function checkLogin($redir=true)
1469 if (common_logged_in()) {
1474 common_set_returnto($_SERVER['REQUEST_URI']);
1475 common_redirect(common_local_url('login'));
1478 // TRANS: Error message displayed when trying to perform an action that requires a logged in user.
1479 $this->clientError(_('Not logged in.'), 403);
1483 * Returns the current URL
1485 * @return string current URL
1489 list($action, $args) = $this->returnToArgs();
1490 return common_local_url($action, $args);
1494 * Returns arguments sufficient for re-constructing URL
1496 * @return array two elements: action, other args
1498 function returnToArgs()
1500 $action = $this->trimmed('action');
1501 $args = $this->args;
1502 unset($args['action']);
1503 if (common_config('site', 'fancy')) {
1506 if (array_key_exists('submit', $args)) {
1507 unset($args['submit']);
1509 foreach (array_keys($_COOKIE) as $cookie) {
1510 unset($args[$cookie]);
1512 return array($action, $args);
1516 * Generate a menu item
1518 * @param string $url menu URL
1519 * @param string $text menu name
1520 * @param string $title title attribute, null by default
1521 * @param boolean $is_selected current menu item, false by default
1522 * @param string $id element id, null by default
1526 function menuItem($url, $text, $title=null, $is_selected=false, $id=null, $class=null)
1528 // Added @id to li for some control.
1529 // XXX: We might want to move this to htmloutputter.php
1532 if ($class !== null) {
1533 $classes[] = trim($class);
1536 $classes[] = 'current';
1539 if (!empty($classes)) {
1540 $lattrs['class'] = implode(' ', $classes);
1543 if (!is_null($id)) {
1544 $lattrs['id'] = $id;
1547 $this->elementStart('li', $lattrs);
1548 $attrs['href'] = $url;
1550 $attrs['title'] = $title;
1552 $this->element('a', $attrs, $text);
1553 $this->elementEnd('li');
1557 * Generate pagination links
1559 * @param boolean $have_before is there something before?
1560 * @param boolean $have_after is there something after?
1561 * @param integer $page current page
1562 * @param string $action current action
1563 * @param array $args rest of query arguments
1567 // XXX: The messages in this pagination method only tailor to navigating
1568 // notices. In other lists, "Previous"/"Next" type navigation is
1569 // desirable, but not available.
1570 function pagination($have_before, $have_after, $page, $action, $args=null)
1572 // Does a little before-after block for next/prev page
1573 if ($have_before || $have_after) {
1574 $this->elementStart('ul', array('class' => 'nav',
1575 'id' => 'pagination'));
1578 $pargs = array('page' => $page-1);
1579 $this->elementStart('li', array('class' => 'nav_prev'));
1580 $this->element('a', array('href' => common_local_url($action, $args, $pargs),
1582 // TRANS: Pagination message to go to a page displaying information more in the
1583 // TRANS: present than the currently displayed information.
1585 $this->elementEnd('li');
1588 $pargs = array('page' => $page+1);
1589 $this->elementStart('li', array('class' => 'nav_next'));
1590 $this->element('a', array('href' => common_local_url($action, $args, $pargs),
1592 // TRANS: Pagination message to go to a page displaying information more in the
1593 // TRANS: past than the currently displayed information.
1595 $this->elementEnd('li');
1597 if ($have_before || $have_after) {
1598 $this->elementEnd('ul');
1603 * An array of feeds for this action.
1605 * Returns an array of potential feeds for this action.
1607 * @return array Feed object to show in head and links
1615 * Check the session token.
1617 * Checks that the current form has the correct session token,
1618 * and throw an exception if it does not.
1622 // XXX: Finding this type of check with the same message about 50 times.
1623 // Possible to refactor?
1624 function checkSessionToken()
1627 $token = $this->trimmed('token');
1628 if (empty($token) || $token != common_session_token()) {
1629 // TRANS: Client error text when there is a problem with the session token.
1630 $this->clientError(_('There was a problem with your session token.'));
1635 * Check if the current request is a POST
1637 * @return boolean true if POST; otherwise false.
1642 return ($_SERVER['REQUEST_METHOD'] == 'POST');