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); }
33 require_once INSTALLDIR.'/lib/noticeform.php';
34 require_once INSTALLDIR.'/lib/htmloutputter.php';
37 * Base class for all actions
39 * This is the base class for all actions in the package. An action is
40 * more or less a "view" in an MVC framework.
42 * Actions are responsible for extracting and validating parameters; using
43 * model classes to read and write to the database; and doing ouput.
47 * @author Evan Prodromou <evan@status.net>
48 * @author Sarven Capadisli <csarven@status.net>
49 * @license http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
50 * @link http://status.net/
54 class Action extends HTMLOutputter // lawsuit
56 // This should be protected/private in the future
57 public $args = array();
59 // Action properties, set per-class
60 protected $action = false;
61 protected $ajax = false;
62 protected $menus = true;
63 protected $needLogin = false;
64 protected $needPost = false;
66 // The currently scoped profile (normally Profile::current; from $this->auth_user for API)
67 protected $scoped = null;
69 // Related to front-end user representation
70 protected $format = null;
71 protected $error = null;
72 protected $msg = null;
77 * Just wraps the HTMLOutputter constructor.
79 * @param string $output URI to output to, default = stdout
80 * @param boolean $indent Whether to indent output, default true
82 * @see XMLOutputter::__construct
83 * @see HTMLOutputter::__construct
85 function __construct($output='php://output', $indent=null)
87 parent::__construct($output, $indent);
100 static public function run(array $args=array(), $output='php://output', $indent=null) {
101 $class = get_called_class();
102 $action = new $class($output, $indent);
103 $action->execute($args);
107 public function execute(array $args=array()) {
109 if (common_config('db', 'mirror') && $this->isReadOnly($args)) {
110 if (is_array(common_config('db', 'mirror'))) {
111 // "load balancing", ha ha
112 $arr = common_config('db', 'mirror');
113 $k = array_rand($arr);
116 $mirror = common_config('db', 'mirror');
119 // everyone else uses the mirror
120 common_config_set('db', 'database', $mirror);
123 if ($this->prepare($args)) {
124 $this->handle($args);
129 * For initializing members of the class.
131 * @param array $argarray misc. arguments
133 * @return boolean true
135 protected function prepare(array $args=array())
137 if ($this->needPost && !$this->isPost()) {
138 // TRANS: Client error. POST is a HTTP command. It should not be translated.
139 $this->clientError(_('This method requires a POST.'), 405);
142 $this->args = common_copy_args($args);
144 $this->action = $this->trimmed('action');
146 if ($this->ajax || $this->boolean('ajax')) {
147 // check with StatusNet::isAjax()
148 StatusNet::setAjax(true);
151 if ($this->needLogin) {
152 $this->checkLogin(); // if not logged in, this redirs/excepts
155 $this->scoped = Profile::current();
161 * Show page, a template method.
167 if (Event::handle('StartShowHTML', array($this))) {
170 Event::handle('EndShowHTML', array($this));
172 if (Event::handle('StartShowHead', array($this))) {
175 Event::handle('EndShowHead', array($this));
177 if (Event::handle('StartShowBody', array($this))) {
179 Event::handle('EndShowBody', array($this));
181 if (Event::handle('StartEndHTML', array($this))) {
183 Event::handle('EndEndHTML', array($this));
191 if (isset($_startTime)) {
192 $endTime = microtime(true);
193 $diff = round(($endTime - $_startTime) * 1000);
194 $this->raw("<!-- ${diff}ms -->");
197 return parent::endHTML();
201 * Show head, a template method.
207 // XXX: attributes (profile?)
208 $this->elementStart('head');
209 if (Event::handle('StartShowHeadElements', array($this))) {
210 if (Event::handle('StartShowHeadTitle', array($this))) {
212 Event::handle('EndShowHeadTitle', array($this));
214 $this->showShortcutIcon();
215 $this->showStylesheets();
216 $this->showOpenSearch();
218 $this->showDescription();
220 Event::handle('EndShowHeadElements', array($this));
222 $this->elementEnd('head');
226 * Show title, a template method.
232 $this->element('title', null,
233 // TRANS: Page title. %1$s is the title, %2$s is the site name.
234 sprintf(_('%1$s - %2$s'),
236 common_config('site', 'name')));
240 * Returns the page title
244 * @return string page title
249 // TRANS: Page title for a page without a title set.
250 return _('Untitled page');
254 * Show themed shortcut icon
258 function showShortcutIcon()
260 if (is_readable(INSTALLDIR . '/theme/' . common_config('site', 'theme') . '/favicon.ico')) {
261 $this->element('link', array('rel' => 'shortcut icon',
262 'href' => Theme::path('favicon.ico')));
264 // favicon.ico should be HTTPS if the rest of the page is
265 $this->element('link', array('rel' => 'shortcut icon',
266 'href' => common_path('favicon.ico', StatusNet::isHTTPS())));
269 if (common_config('site', 'mobile')) {
270 if (is_readable(INSTALLDIR . '/theme/' . common_config('site', 'theme') . '/apple-touch-icon.png')) {
271 $this->element('link', array('rel' => 'apple-touch-icon',
272 'href' => Theme::path('apple-touch-icon.png')));
274 $this->element('link', array('rel' => 'apple-touch-icon',
275 'href' => common_path('apple-touch-icon.png')));
285 function showStylesheets()
287 if (Event::handle('StartShowStyles', array($this))) {
289 // Use old name for StatusNet for compatibility on events
291 if (Event::handle('StartShowStylesheets', array($this))) {
292 $this->primaryCssLink(null, 'screen, projection, tv, print');
293 Event::handle('EndShowStylesheets', array($this));
296 $this->cssLink('js/extlib/jquery-ui/css/smoothness/jquery-ui.css');
298 if (Event::handle('StartShowUAStyles', array($this))) {
299 $this->comment('[if IE]><link rel="stylesheet" type="text/css" '.
300 'href="'.Theme::path('css/ie.css', 'base').'?version='.STATUSNET_VERSION.'" /><![endif]');
301 foreach (array(6,7) as $ver) {
302 if (file_exists(Theme::file('css/ie'.$ver.'.css', 'base'))) {
303 // Yes, IE people should be put in jail.
304 $this->comment('[if lte IE '.$ver.']><link rel="stylesheet" type="text/css" '.
305 'href="'.Theme::path('css/ie'.$ver.'.css', 'base').'?version='.STATUSNET_VERSION.'" /><![endif]');
308 if (file_exists(Theme::file('css/ie.css'))) {
309 $this->comment('[if IE]><link rel="stylesheet" type="text/css" '.
310 'href="'.Theme::path('css/ie.css', null).'?version='.STATUSNET_VERSION.'" /><![endif]');
312 Event::handle('EndShowUAStyles', array($this));
315 Event::handle('EndShowStyles', array($this));
317 if (common_config('custom_css', 'enabled')) {
318 $css = common_config('custom_css', 'css');
319 if (Event::handle('StartShowCustomCss', array($this, &$css))) {
320 if (trim($css) != '') {
323 Event::handle('EndShowCustomCss', array($this));
329 function primaryCssLink($mainTheme=null, $media=null)
331 $theme = new Theme($mainTheme);
333 // Some themes may have external stylesheets, such as using the
334 // Google Font APIs to load webfonts.
335 foreach ($theme->getExternals() as $url) {
336 $this->cssLink($url, $mainTheme, $media);
339 // If the currently-selected theme has dependencies on other themes,
340 // we'll need to load their display.css files as well in order.
341 $baseThemes = $theme->getDeps();
342 foreach ($baseThemes as $baseTheme) {
343 $this->cssLink('css/display.css', $baseTheme, $media);
345 $this->cssLink('css/display.css', $mainTheme, $media);
347 // Additional styles for RTL languages
348 if (is_rtl(common_language())) {
349 if (file_exists(Theme::file('css/rtl.css'))) {
350 $this->cssLink('css/rtl.css', $mainTheme, $media);
356 * Show javascript headers
360 function showScripts()
362 if (Event::handle('StartShowScripts', array($this))) {
363 if (Event::handle('StartShowJQueryScripts', array($this))) {
364 if (common_config('site', 'minify')) {
365 $this->script('extlib/jquery.min.js');
366 $this->script('extlib/jquery.form.min.js');
367 $this->script('extlib/jquery-ui/jquery-ui.min.js');
368 $this->script('extlib/jquery.cookie.min.js');
369 $this->inlineScript('if (typeof window.JSON !== "object") { $.getScript("'.common_path('js/extlib/json2.min.js', StatusNet::isHTTPS()).'"); }');
370 $this->script('extlib/jquery.infieldlabel.min.js');
372 $this->script('extlib/jquery.js');
373 $this->script('extlib/jquery.form.js');
374 $this->script('extlib/jquery-ui/jquery-ui.js');
375 $this->script('extlib/jquery.cookie.js');
376 $this->inlineScript('if (typeof window.JSON !== "object") { $.getScript("'.common_path('js/extlib/json2.js', StatusNet::isHTTPS()).'"); }');
377 $this->script('extlib/jquery.infieldlabel.js');
380 Event::handle('EndShowJQueryScripts', array($this));
382 if (Event::handle('StartShowStatusNetScripts', array($this)) &&
383 Event::handle('StartShowLaconicaScripts', array($this))) {
384 if (common_config('site', 'minify')) {
385 $this->script('util.min.js');
387 $this->script('util.js');
388 $this->script('xbImportNode.js');
389 $this->script('geometa.js');
391 // This route isn't available in single-user mode.
392 // Not sure why, but it causes errors here.
393 $this->inlineScript('var _peopletagAC = "' .
394 common_local_url('peopletagautocomplete') . '";');
395 $this->showScriptMessages();
396 // Anti-framing code to avoid clickjacking attacks in older browsers.
397 // This will show a blank page if the page is being framed, which is
398 // consistent with the behavior of the 'X-Frame-Options: SAMEORIGIN'
399 // header, which prevents framing in newer browser.
400 if (common_config('javascript', 'bustframes')) {
401 $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 = ""; }; }');
403 Event::handle('EndShowStatusNetScripts', array($this));
404 Event::handle('EndShowLaconicaScripts', array($this));
406 Event::handle('EndShowScripts', array($this));
411 * Exports a map of localized text strings to JavaScript code.
413 * Plugins can add to what's exported by hooking the StartScriptMessages or EndScriptMessages
414 * events and appending to the array. Try to avoid adding strings that won't be used, as
415 * they'll be added to HTML output.
417 function showScriptMessages()
421 if (Event::handle('StartScriptMessages', array($this, &$messages))) {
422 // Common messages needed for timeline views etc...
424 // TRANS: Localized tooltip for '...' expansion button on overlong remote messages.
425 $messages['showmore_tooltip'] = _m('TOOLTIP', 'Show more');
427 // TRANS: Inline reply form submit button: submits a reply comment.
428 $messages['reply_submit'] = _m('BUTTON', 'Reply');
430 // TRANS: Placeholder text for inline reply form. Clicking in this box will turn it into a mini notice form.
431 $messages['reply_placeholder'] = _m('Write a reply...');
433 $messages = array_merge($messages, $this->getScriptMessages());
435 Event::handle('EndScriptMessages', array($this, &$messages));
438 if (!empty($messages)) {
439 $this->inlineScript('SN.messages=' . json_encode($messages));
446 * If the action will need localizable text strings, export them here like so:
448 * return array('pool_deepend' => _('Deep end'),
449 * 'pool_shallow' => _('Shallow end'));
451 * The exported map will be available via SN.msg() to JS code:
453 * $('#pool').html('<div class="deepend"></div><div class="shallow"></div>');
454 * $('#pool .deepend').text(SN.msg('pool_deepend'));
455 * $('#pool .shallow').text(SN.msg('pool_shallow'));
457 * Exports a map of localized text strings to JavaScript code.
459 * Plugins can add to what's exported on any action by hooking the StartScriptMessages or
460 * EndScriptMessages events and appending to the array. Try to avoid adding strings that won't
461 * be used, as they'll be added to HTML output.
463 function getScriptMessages()
469 * Show OpenSearch headers
473 function showOpenSearch()
475 $this->element('link', array('rel' => 'search',
476 'type' => 'application/opensearchdescription+xml',
477 'href' => common_local_url('opensearch', array('type' => 'people')),
478 'title' => common_config('site', 'name').' People Search'));
479 $this->element('link', array('rel' => 'search', 'type' => 'application/opensearchdescription+xml',
480 'href' => common_local_url('opensearch', array('type' => 'notice')),
481 'title' => common_config('site', 'name').' Notice Search'));
493 $feeds = $this->getFeeds();
496 foreach ($feeds as $feed) {
497 $this->element('link', array('rel' => $feed->rel(),
498 'href' => $feed->url,
499 'type' => $feed->mimeType(),
500 'title' => $feed->title));
512 function showDescription()
514 // does nothing by default
518 * Show extra stuff in <head>.
526 // does nothing by default
532 * Calls template methods
538 $this->elementStart('body', (common_current_user()) ? array('id' => strtolower($this->trimmed('action')),
539 'class' => 'user_in')
540 : array('id' => strtolower($this->trimmed('action'))));
541 $this->elementStart('div', array('id' => 'wrap'));
542 if (Event::handle('StartShowHeader', array($this))) {
545 Event::handle('EndShowHeader', array($this));
549 if (Event::handle('StartShowFooter', array($this))) {
552 Event::handle('EndShowFooter', array($this));
554 $this->elementEnd('div');
555 $this->showScripts();
556 $this->elementEnd('body');
560 * Show header of the page.
562 * Calls template methods
566 function showHeader()
568 $this->elementStart('div', array('id' => 'header'));
570 $this->showPrimaryNav();
571 if (Event::handle('StartShowSiteNotice', array($this))) {
572 $this->showSiteNotice();
574 Event::handle('EndShowSiteNotice', array($this));
577 $this->elementEnd('div');
581 * Show configured logo.
587 $this->elementStart('address', array('id' => 'site_contact',
588 'class' => 'vcard'));
589 if (Event::handle('StartAddressData', array($this))) {
590 if (common_config('singleuser', 'enabled')) {
591 $user = User::singleUser();
592 $url = common_local_url('showstream',
593 array('nickname' => $user->nickname));
594 } else if (common_logged_in()) {
595 $cur = common_current_user();
596 $url = common_local_url('all', array('nickname' => $cur->nickname));
598 $url = common_local_url('public');
601 $this->elementStart('a', array('class' => 'url home bookmark',
604 if (StatusNet::isHTTPS()) {
605 $logoUrl = common_config('site', 'ssllogo');
606 if (empty($logoUrl)) {
607 // if logo is an uploaded file, try to fall back to HTTPS file URL
608 $httpUrl = common_config('site', 'logo');
609 if (!empty($httpUrl)) {
610 $f = File::getKV('url', $httpUrl);
611 if (!empty($f) && !empty($f->filename)) {
612 // this will handle the HTTPS case
613 $logoUrl = File::url($f->filename);
618 $logoUrl = common_config('site', 'logo');
621 if (empty($logoUrl) && file_exists(Theme::file('logo.png'))) {
622 // This should handle the HTTPS case internally
623 $logoUrl = Theme::path('logo.png');
626 if (!empty($logoUrl)) {
627 $this->element('img', array('class' => 'logo photo',
629 'alt' => common_config('site', 'name')));
633 $this->element('span', array('class' => 'fn org'), common_config('site', 'name'));
634 $this->elementEnd('a');
636 Event::handle('EndAddressData', array($this));
638 $this->elementEnd('address');
642 * Show primary navigation.
646 function showPrimaryNav()
648 $this->elementStart('div', array('id' => 'site_nav_global_primary'));
650 $user = common_current_user();
652 if (!empty($user) || !common_config('site', 'private')) {
653 $form = new SearchForm($this);
657 $pn = new PrimaryNav($this);
659 $this->elementEnd('div');
667 function showSiteNotice()
669 // Revist. Should probably do an hAtom pattern here
670 $text = common_config('site', 'notice');
672 $this->elementStart('div', array('id' => 'site_notice',
673 'class' => 'system_notice'));
675 $this->elementEnd('div');
682 * MAY overload if no notice form needed... or direct message box????
686 function showNoticeForm()
688 // TRANS: Tab on the notice form.
689 $tabs = array('status' => _m('TAB','Status'));
691 $this->elementStart('div', 'input_forms');
693 if (Event::handle('StartShowEntryForms', array(&$tabs))) {
694 $this->elementStart('ul', array('class' => 'nav',
695 'id' => 'input_form_nav'));
697 foreach ($tabs as $tag => $title) {
698 $attrs = array('id' => 'input_form_nav_'.$tag,
699 'class' => 'input_form_nav_tab');
701 if ($tag == 'status') {
702 // We're actually showing the placeholder form,
703 // but we special-case the 'Status' tab as if
704 // it were a small version of it.
705 $attrs['class'] .= ' current';
707 $this->elementStart('li', $attrs);
710 array('href' => 'javascript:SN.U.switchInputFormTab("'.$tag.'")'),
712 $this->elementEnd('li');
715 $this->elementEnd('ul');
717 $attrs = array('class' => 'input_form current',
718 'id' => 'input_form_placeholder');
719 $this->elementStart('div', $attrs);
720 $form = new NoticePlaceholderForm($this);
722 $this->elementEnd('div');
724 foreach ($tabs as $tag => $title) {
725 $attrs = array('class' => 'input_form',
726 'id' => 'input_form_'.$tag);
728 $this->elementStart('div', $attrs);
732 if (Event::handle('StartMakeEntryForm', array($tag, $this, &$form))) {
733 if ($tag == 'status') {
734 $options = $this->noticeFormOptions();
735 $form = new NoticeForm($this, $options);
737 Event::handle('EndMakeEntryForm', array($tag, $this, $form));
744 $this->elementEnd('div');
748 $this->elementEnd('div');
751 function noticeFormOptions()
757 * Show anonymous message.
763 function showAnonymousMessage()
765 // needs to be defined by the class
771 * Shows local navigation, content block and aside.
777 $this->elementStart('div', array('id' => 'core'));
778 $this->elementStart('div', array('id' => 'aside_primary_wrapper'));
779 $this->elementStart('div', array('id' => 'content_wrapper'));
780 $this->elementStart('div', array('id' => 'site_nav_local_views_wrapper'));
781 if (Event::handle('StartShowLocalNavBlock', array($this))) {
782 $this->showLocalNavBlock();
784 Event::handle('EndShowLocalNavBlock', array($this));
786 if (Event::handle('StartShowContentBlock', array($this))) {
787 $this->showContentBlock();
789 Event::handle('EndShowContentBlock', array($this));
791 if (Event::handle('StartShowAside', array($this))) {
794 Event::handle('EndShowAside', array($this));
796 $this->elementEnd('div');
797 $this->elementEnd('div');
798 $this->elementEnd('div');
799 $this->elementEnd('div');
803 * Show local navigation block.
807 function showLocalNavBlock()
809 // Need to have this ID for CSS; I'm too lazy to add it to
811 $this->elementStart('div', array('id' => 'site_nav_local_views'));
812 // Cheat cheat cheat!
813 $this->showLocalNav();
814 $this->elementEnd('div');
818 * If there's a logged-in user, show a bit of login context
822 function showProfileBlock()
824 if (common_logged_in()) {
825 $block = new DefaultProfileBlock($this);
831 * Show local navigation.
837 function showLocalNav()
839 $nav = new DefaultLocalNav($this);
844 * Show menu for an object (group, profile)
846 * This block will only show if a subclass has overridden
847 * the showObjectNav() method.
851 function showObjectNavBlock()
853 $rmethod = new ReflectionMethod($this, 'showObjectNav');
854 $dclass = $rmethod->getDeclaringClass()->getName();
856 if ($dclass != 'Action') {
857 // Need to have this ID for CSS; I'm too lazy to add it to
859 $this->elementStart('div', array('id' => 'site_nav_object',
860 'class' => 'section'));
861 $this->showObjectNav();
862 $this->elementEnd('div');
867 * Show object navigation.
869 * If there are things to do with this object, show it here.
873 function showObjectNav()
879 * Show content block.
883 function showContentBlock()
885 $this->elementStart('div', array('id' => 'content'));
886 if (common_logged_in()) {
887 if (Event::handle('StartShowNoticeForm', array($this))) {
888 $this->showNoticeForm();
889 Event::handle('EndShowNoticeForm', array($this));
892 if (Event::handle('StartShowPageTitle', array($this))) {
893 $this->showPageTitle();
894 Event::handle('EndShowPageTitle', array($this));
896 $this->showPageNoticeBlock();
897 $this->elementStart('div', array('id' => 'content_inner'));
898 // show the actual content (forms, lists, whatever)
899 $this->showContent();
900 $this->elementEnd('div');
901 $this->elementEnd('div');
909 function showPageTitle()
911 $this->element('h1', null, $this->title());
915 * Show page notice block.
917 * Only show the block if a subclassed action has overrided
918 * Action::showPageNotice(), or an event handler is registered for
919 * the StartShowPageNotice event, in which case we assume the
920 * 'page_notice' definition list is desired. This is to prevent
921 * empty 'page_notice' definition lists from being output everywhere.
925 function showPageNoticeBlock()
927 $rmethod = new ReflectionMethod($this, 'showPageNotice');
928 $dclass = $rmethod->getDeclaringClass()->getName();
930 if ($dclass != 'Action' || Event::hasHandler('StartShowPageNotice')) {
932 $this->elementStart('div', array('id' => 'page_notice',
933 'class' => 'system_notice'));
934 if (Event::handle('StartShowPageNotice', array($this))) {
935 $this->showPageNotice();
936 Event::handle('EndShowPageNotice', array($this));
938 $this->elementEnd('div');
945 * SHOULD overload (unless there's not a notice)
949 function showPageNotice()
956 * MUST overload (unless there's not a notice)
960 function showContent()
971 $this->elementStart('div', array('id' => 'aside_primary',
972 'class' => 'aside'));
973 $this->showProfileBlock();
974 if (Event::handle('StartShowObjectNavBlock', array($this))) {
975 $this->showObjectNavBlock();
976 Event::handle('EndShowObjectNavBlock', array($this));
978 if (Event::handle('StartShowSections', array($this))) {
979 $this->showSections();
980 Event::handle('EndShowSections', array($this));
982 if (Event::handle('StartShowExportData', array($this))) {
983 $this->showExportData();
984 Event::handle('EndShowExportData', array($this));
986 $this->elementEnd('div');
990 * Show export data feeds.
994 function showExportData()
996 $feeds = $this->getFeeds();
998 $fl = new FeedList($this);
1010 function showSections()
1012 // for each section, show it
1020 function showFooter()
1022 $this->elementStart('div', array('id' => 'footer'));
1023 if (Event::handle('StartShowInsideFooter', array($this))) {
1024 $this->showSecondaryNav();
1025 $this->showLicenses();
1026 Event::handle('EndShowInsideFooter', array($this));
1028 $this->elementEnd('div');
1032 * Show secondary navigation.
1036 function showSecondaryNav()
1038 $sn = new SecondaryNav($this);
1047 function showLicenses()
1049 $this->showStatusNetLicense();
1050 $this->showContentLicense();
1054 * Show StatusNet license.
1058 function showStatusNetLicense()
1060 if (common_config('site', 'broughtby')) {
1061 // TRANS: First sentence of the StatusNet site license. Used if 'broughtby' is set.
1062 // TRANS: Text between [] is a link description, text between () is the link itself.
1063 // TRANS: Make sure there is no whitespace between "]" and "(".
1064 // TRANS: "%%site.broughtby%%" is the value of the variable site.broughtby
1065 $instr = _('**%%site.name%%** is a social network, courtesy of [%%site.broughtby%%](%%site.broughtbyurl%%).');
1067 // TRANS: First sentence of the StatusNet site license. Used if 'broughtby' is not set.
1068 $instr = _('**%%site.name%%** is a social network.');
1071 // TRANS: Second sentence of the StatusNet site license. Mentions the StatusNet source code license.
1072 // TRANS: Make sure there is no whitespace between "]" and "(".
1073 // TRANS: Text between [] is a link description, text between () is the link itself.
1074 // TRANS: %s is the version of StatusNet that is being used.
1075 $instr .= sprintf(_('It runs on [GNU social](http://www.gnu.org/software/social/), version %s, available under the [GNU Affero General Public License](http://www.fsf.org/licensing/licenses/agpl-3.0.html).'), STATUSNET_VERSION);
1076 $output = common_markup_to_html($instr);
1077 $this->raw($output);
1082 * Show content license.
1086 function showContentLicense()
1088 if (Event::handle('StartShowContentLicense', array($this))) {
1089 switch (common_config('license', 'type')) {
1091 // TRANS: Content license displayed when license is set to 'private'.
1092 // TRANS: %1$s is the site name.
1093 $this->element('p', null, sprintf(_('Content and data of %1$s are private and confidential.'),
1094 common_config('site', 'name')));
1096 case 'allrightsreserved':
1097 if (common_config('license', 'owner')) {
1098 // TRANS: Content license displayed when license is set to 'allrightsreserved'.
1099 // TRANS: %1$s is the copyright owner.
1100 $this->element('p', null, sprintf(_('Content and data copyright by %1$s. All rights reserved.'),
1101 common_config('license', 'owner')));
1103 // TRANS: Content license displayed when license is set to 'allrightsreserved' and no owner is set.
1104 $this->element('p', null, _('Content and data copyright by contributors. All rights reserved.'));
1107 case 'cc': // fall through
1109 $this->elementStart('p');
1111 $image = common_config('license', 'image');
1112 $sslimage = common_config('license', 'sslimage');
1114 if (StatusNet::isHTTPS()) {
1115 if (!empty($sslimage)) {
1117 } else if (preg_match('#^http://i.creativecommons.org/#', $image)) {
1118 // CC support HTTPS on their images
1119 $url = preg_replace('/^http/', 'https', $image);
1121 // Better to show mixed content than no content
1128 $this->element('img', array('id' => 'license_cc',
1130 'alt' => common_config('license', 'title'),
1134 // TRANS: license message in footer.
1135 // TRANS: %1$s is the site name, %2$s is a link to the license URL, with a licence name set in configuration.
1136 $notice = _('All %1$s content and data are available under the %2$s license.');
1137 $link = "<a class=\"license\" rel=\"external license\" href=\"" .
1138 htmlspecialchars(common_config('license', 'url')) .
1140 htmlspecialchars(common_config('license', 'title')) .
1142 $this->raw(sprintf(htmlspecialchars($notice),
1143 htmlspecialchars(common_config('site', 'name')),
1145 $this->elementEnd('p');
1149 Event::handle('EndShowContentLicense', array($this));
1154 * Return last modified, if applicable.
1158 * @return string last modified http header
1160 function lastModified()
1162 // For comparison with If-Last-Modified
1163 // If not applicable, return null
1168 * Return etag, if applicable.
1172 * @return string etag http header
1180 * Return true if read only.
1184 * @param array $args other arguments
1186 * @return boolean is read only action?
1188 function isReadOnly($args)
1194 * Returns query argument or default value if not found
1196 * @param string $key requested argument
1197 * @param string $def default value to return if $key is not provided
1199 * @return boolean is read only action?
1201 function arg($key, $def=null)
1203 if (array_key_exists($key, $this->args)) {
1204 return $this->args[$key];
1211 * Returns trimmed query argument or default value if not found
1213 * @param string $key requested argument
1214 * @param string $def default value to return if $key is not provided
1216 * @return boolean is read only action?
1218 function trimmed($key, $def=null)
1220 $arg = $this->arg($key, $def);
1221 return is_string($arg) ? trim($arg) : $arg;
1227 * @return boolean is read only action?
1229 protected function handle()
1231 header('Vary: Accept-Encoding,Cookie');
1233 $lm = $this->lastModified();
1234 $etag = $this->etag();
1237 header('ETag: ' . $etag);
1241 header('Last-Modified: ' . date(DATE_RFC1123, $lm));
1242 if ($this->isCacheable()) {
1243 header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', 0 ) . ' GMT' );
1244 header( "Cache-Control: private, must-revalidate, max-age=0" );
1251 $if_none_match = (array_key_exists('HTTP_IF_NONE_MATCH', $_SERVER)) ?
1252 $_SERVER['HTTP_IF_NONE_MATCH'] : null;
1253 if ($if_none_match) {
1254 // If this check fails, ignore the if-modified-since below.
1256 if ($this->_hasEtag($etag, $if_none_match)) {
1257 header('HTTP/1.1 304 Not Modified');
1258 // Better way to do this?
1264 if (!$checked && $lm && array_key_exists('HTTP_IF_MODIFIED_SINCE', $_SERVER)) {
1265 $if_modified_since = $_SERVER['HTTP_IF_MODIFIED_SINCE'];
1266 $ims = strtotime($if_modified_since);
1268 header('HTTP/1.1 304 Not Modified');
1269 // Better way to do this?
1276 * Is this action cacheable?
1278 * If the action returns a last-modified
1280 * @param array $argarray is ignored since it's now passed in in prepare()
1282 * @return boolean is read only action?
1284 function isCacheable()
1290 * Has etag? (private)
1292 * @param string $etag etag http header
1293 * @param string $if_none_match ifNoneMatch http header
1297 function _hasEtag($etag, $if_none_match)
1299 $etags = explode(',', $if_none_match);
1300 return in_array($etag, $etags) || in_array('*', $etags);
1304 * Boolean understands english (yes, no, true, false)
1306 * @param string $key query key we're interested in
1307 * @param string $def default value
1309 * @return boolean interprets yes/no strings as boolean
1311 function boolean($key, $def=false)
1313 $arg = strtolower($this->trimmed($key));
1315 if (is_null($arg)) {
1317 } else if (in_array($arg, array('true', 'yes', '1', 'on'))) {
1319 } else if (in_array($arg, array('false', 'no', '0'))) {
1327 * Integer value of an argument
1329 * @param string $key query key we're interested in
1330 * @param string $defValue optional default value (default null)
1331 * @param string $maxValue optional max value (default null)
1332 * @param string $minValue optional min value (default null)
1334 * @return integer integer value
1336 function int($key, $defValue=null, $maxValue=null, $minValue=null)
1338 $arg = strtolower($this->trimmed($key));
1340 if (is_null($arg) || !is_integer($arg)) {
1344 if (!is_null($maxValue)) {
1345 $arg = min($arg, $maxValue);
1348 if (!is_null($minValue)) {
1349 $arg = max($arg, $minValue);
1358 * @param string $msg error message to display
1359 * @param integer $code http error code, 500 by default
1363 function serverError($msg, $code=500, $format=null)
1365 if ($format === null) {
1366 $format = $this->format;
1369 common_debug("Server error '{$code}' on '{$this->action}': {$msg}", __FILE__);
1371 if (!array_key_exists($code, ServerErrorAction::$status)) {
1375 $status_string = ServerErrorAction::$status[$code];
1379 header("HTTP/1.1 {$code} {$status_string}");
1380 $this->initDocument('xml');
1381 $this->elementStart('hash');
1382 $this->element('error', null, $msg);
1383 $this->element('request', null, $_SERVER['REQUEST_URI']);
1384 $this->elementEnd('hash');
1385 $this->endDocument('xml');
1388 if (!isset($this->callback)) {
1389 header("HTTP/1.1 {$code} {$status_string}");
1391 $this->initDocument('json');
1392 $error_array = array('error' => $msg, 'request' => $_SERVER['REQUEST_URI']);
1393 print(json_encode($error_array));
1394 $this->endDocument('json');
1397 throw new ServerException($msg, $code);
1406 * @param string $msg error message to display
1407 * @param integer $code http error code, 400 by default
1408 * @param string $format error format (json, xml, text) for ApiAction
1411 * @throws ClientException always
1413 function clientError($msg, $code=400, $format=null)
1415 // $format is currently only relevant for an ApiAction anyway
1416 if ($format === null) {
1417 $format = $this->format;
1420 common_debug("User error '{$code}' on '{$this->action}': {$msg}", __FILE__);
1422 if (!array_key_exists($code, ClientErrorAction::$status)) {
1426 $status_string = ClientErrorAction::$status[$code];
1430 header("HTTP/1.1 {$code} {$status_string}");
1431 $this->initDocument('xml');
1432 $this->elementStart('hash');
1433 $this->element('error', null, $msg);
1434 $this->element('request', null, $_SERVER['REQUEST_URI']);
1435 $this->elementEnd('hash');
1436 $this->endDocument('xml');
1439 if (!isset($this->callback)) {
1440 header("HTTP/1.1 {$code} {$status_string}");
1442 $this->initDocument('json');
1443 $error_array = array('error' => $msg, 'request' => $_SERVER['REQUEST_URI']);
1444 $this->text(json_encode($error_array));
1445 $this->endDocument('json');
1448 header("HTTP/1.1 {$code} {$status_string}");
1449 header('Content-Type: text/plain; charset=utf-8');
1453 throw new ClientException($msg, $code);
1459 * If not logged in, take appropriate action (redir or exception)
1461 * @param boolean $redir Redirect to login if not logged in
1463 * @return boolean true if logged in (never returns if not)
1465 public function checkLogin($redir=true)
1467 if (common_logged_in()) {
1472 common_set_returnto($_SERVER['REQUEST_URI']);
1473 common_redirect(common_local_url('login'));
1476 // TRANS: Error message displayed when trying to perform an action that requires a logged in user.
1477 $this->clientError(_('Not logged in.'), 403);
1481 * Returns the current URL
1483 * @return string current URL
1487 list($action, $args) = $this->returnToArgs();
1488 return common_local_url($action, $args);
1492 * Returns arguments sufficient for re-constructing URL
1494 * @return array two elements: action, other args
1496 function returnToArgs()
1498 $action = $this->trimmed('action');
1499 $args = $this->args;
1500 unset($args['action']);
1501 if (common_config('site', 'fancy')) {
1504 if (array_key_exists('submit', $args)) {
1505 unset($args['submit']);
1507 foreach (array_keys($_COOKIE) as $cookie) {
1508 unset($args[$cookie]);
1510 return array($action, $args);
1514 * Generate a menu item
1516 * @param string $url menu URL
1517 * @param string $text menu name
1518 * @param string $title title attribute, null by default
1519 * @param boolean $is_selected current menu item, false by default
1520 * @param string $id element id, null by default
1524 function menuItem($url, $text, $title=null, $is_selected=false, $id=null, $class=null)
1526 // Added @id to li for some control.
1527 // XXX: We might want to move this to htmloutputter.php
1530 if ($class !== null) {
1531 $classes[] = trim($class);
1534 $classes[] = 'current';
1537 if (!empty($classes)) {
1538 $lattrs['class'] = implode(' ', $classes);
1541 if (!is_null($id)) {
1542 $lattrs['id'] = $id;
1545 $this->elementStart('li', $lattrs);
1546 $attrs['href'] = $url;
1548 $attrs['title'] = $title;
1550 $this->element('a', $attrs, $text);
1551 $this->elementEnd('li');
1555 * Generate pagination links
1557 * @param boolean $have_before is there something before?
1558 * @param boolean $have_after is there something after?
1559 * @param integer $page current page
1560 * @param string $action current action
1561 * @param array $args rest of query arguments
1565 // XXX: The messages in this pagination method only tailor to navigating
1566 // notices. In other lists, "Previous"/"Next" type navigation is
1567 // desirable, but not available.
1568 function pagination($have_before, $have_after, $page, $action, $args=null)
1570 // Does a little before-after block for next/prev page
1571 if ($have_before || $have_after) {
1572 $this->elementStart('ul', array('class' => 'nav',
1573 'id' => 'pagination'));
1576 $pargs = array('page' => $page-1);
1577 $this->elementStart('li', array('class' => 'nav_prev'));
1578 $this->element('a', array('href' => common_local_url($action, $args, $pargs),
1580 // TRANS: Pagination message to go to a page displaying information more in the
1581 // TRANS: present than the currently displayed information.
1583 $this->elementEnd('li');
1586 $pargs = array('page' => $page+1);
1587 $this->elementStart('li', array('class' => 'nav_next'));
1588 $this->element('a', array('href' => common_local_url($action, $args, $pargs),
1590 // TRANS: Pagination message to go to a page displaying information more in the
1591 // TRANS: past than the currently displayed information.
1593 $this->elementEnd('li');
1595 if ($have_before || $have_after) {
1596 $this->elementEnd('ul');
1601 * An array of feeds for this action.
1603 * Returns an array of potential feeds for this action.
1605 * @return array Feed object to show in head and links
1613 * Check the session token.
1615 * Checks that the current form has the correct session token,
1616 * and throw an exception if it does not.
1620 // XXX: Finding this type of check with the same message about 50 times.
1621 // Possible to refactor?
1622 function checkSessionToken()
1625 $token = $this->trimmed('token');
1626 if (empty($token) || $token != common_session_token()) {
1627 // TRANS: Client error text when there is a problem with the session token.
1628 $this->clientError(_('There was a problem with your session token.'));
1633 * Check if the current request is a POST
1635 * @return boolean true if POST; otherwise false.
1640 return ($_SERVER['REQUEST_METHOD'] == 'POST');