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 public function updateScopedProfile()
174 $this->scoped = Profile::current();
175 return $this->scoped;
178 public function getScoped()
180 return ($this->scoped instanceof Profile) ? $this->scoped : null;
183 // Must be run _after_ prepare
184 public function getActionName()
186 return $this->action;
189 public function isAction(array $names)
191 foreach ($names as $class) {
192 // PHP is case insensitive, and we have stuff like ApiUpperCaseAction,
193 // but we at least make a point out of wanting to do stuff case-sensitive.
194 $class = ucfirst($class) . 'Action';
195 if ($this instanceof $class) {
203 * Show page, a template method.
209 if (StatusNet::isAjax()) {
213 if (Event::handle('StartShowHTML', array($this))) {
216 Event::handle('EndShowHTML', array($this));
218 if (Event::handle('StartShowHead', array($this))) {
221 Event::handle('EndShowHead', array($this));
223 if (Event::handle('StartShowBody', array($this))) {
225 Event::handle('EndShowBody', array($this));
227 if (Event::handle('StartEndHTML', array($this))) {
229 Event::handle('EndEndHTML', array($this));
233 public function showAjax()
235 $this->startHTML('text/xml;charset=utf-8');
236 $this->elementStart('head');
237 // TRANS: Title for conversation page.
238 $this->element('title', null, $this->title());
239 $this->elementEnd('head');
240 $this->elementStart('body');
241 if ($this->getError()) {
242 $this->element('p', array('id'=>'error'), $this->getError());
244 $this->showContent();
246 $this->elementEnd('body');
254 if (isset($_startTime)) {
255 $endTime = microtime(true);
256 $diff = round(($endTime - $_startTime) * 1000);
257 $this->raw("<!-- ${diff}ms -->");
260 return parent::endHTML();
264 * Show head, a template method.
270 // XXX: attributes (profile?)
271 $this->elementStart('head');
272 if (Event::handle('StartShowHeadElements', array($this))) {
273 if (Event::handle('StartShowHeadTitle', array($this))) {
275 Event::handle('EndShowHeadTitle', array($this));
277 $this->showShortcutIcon();
278 $this->showStylesheets();
279 $this->showOpenSearch();
281 $this->showDescription();
283 Event::handle('EndShowHeadElements', array($this));
285 $this->elementEnd('head');
289 * Show title, a template method.
295 $this->element('title', null,
296 // TRANS: Page title. %1$s is the title, %2$s is the site name.
297 sprintf(_('%1$s - %2$s'),
299 common_config('site', 'name')));
303 * Returns the page title
307 * @return string page title
312 // TRANS: Page title for a page without a title set.
313 return _('Untitled page');
317 * Show themed shortcut icon
321 function showShortcutIcon()
323 if (is_readable(INSTALLDIR . '/theme/' . common_config('site', 'theme') . '/favicon.ico')) {
324 $this->element('link', array('rel' => 'shortcut icon',
325 'href' => Theme::path('favicon.ico')));
327 // favicon.ico should be HTTPS if the rest of the page is
328 $this->element('link', array('rel' => 'shortcut icon',
329 'href' => common_path('favicon.ico', StatusNet::isHTTPS())));
332 if (common_config('site', 'mobile')) {
333 if (is_readable(INSTALLDIR . '/theme/' . common_config('site', 'theme') . '/apple-touch-icon.png')) {
334 $this->element('link', array('rel' => 'apple-touch-icon',
335 'href' => Theme::path('apple-touch-icon.png')));
337 $this->element('link', array('rel' => 'apple-touch-icon',
338 'href' => common_path('apple-touch-icon.png')));
348 function showStylesheets()
350 if (Event::handle('StartShowStyles', array($this))) {
352 // Use old name for StatusNet for compatibility on events
354 if (Event::handle('StartShowStylesheets', array($this))) {
355 $this->primaryCssLink(null, 'screen, projection, tv, print');
356 Event::handle('EndShowStylesheets', array($this));
359 $this->cssLink('js/extlib/jquery-ui/css/smoothness/jquery-ui.css');
361 if (Event::handle('StartShowUAStyles', array($this))) {
362 Event::handle('EndShowUAStyles', array($this));
365 Event::handle('EndShowStyles', array($this));
367 if (common_config('custom_css', 'enabled')) {
368 $css = common_config('custom_css', 'css');
369 if (Event::handle('StartShowCustomCss', array($this, &$css))) {
370 if (trim($css) != '') {
373 Event::handle('EndShowCustomCss', array($this));
379 function primaryCssLink($mainTheme=null, $media=null)
381 $theme = new Theme($mainTheme);
383 // Some themes may have external stylesheets, such as using the
384 // Google Font APIs to load webfonts.
385 foreach ($theme->getExternals() as $url) {
386 $this->cssLink($url, $mainTheme, $media);
389 // If the currently-selected theme has dependencies on other themes,
390 // we'll need to load their display.css files as well in order.
391 $baseThemes = $theme->getDeps();
392 foreach ($baseThemes as $baseTheme) {
393 $this->cssLink('css/display.css', $baseTheme, $media);
395 $this->cssLink('css/display.css', $mainTheme, $media);
397 // Additional styles for RTL languages
398 if (is_rtl(common_language())) {
399 if (file_exists(Theme::file('css/rtl.css'))) {
400 $this->cssLink('css/rtl.css', $mainTheme, $media);
406 * Show javascript headers
410 function showScripts()
412 if (Event::handle('StartShowScripts', array($this))) {
413 if (Event::handle('StartShowJQueryScripts', array($this))) {
414 $this->script('extlib/jquery.js');
415 $this->script('extlib/jquery.form.js');
416 $this->script('extlib/jquery-ui/jquery-ui.js');
417 $this->script('extlib/jquery.cookie.js');
418 $this->inlineScript('if (typeof window.JSON !== "object") { $.getScript("'.common_path('js/extlib/json2.js', StatusNet::isHTTPS()).'"); }');
419 $this->script('extlib/jquery.infieldlabel.js');
421 Event::handle('EndShowJQueryScripts', array($this));
423 if (Event::handle('StartShowStatusNetScripts', array($this))) {
424 $this->script('util.js');
425 $this->script('xbImportNode.js');
426 $this->script('geometa.js');
428 // This route isn't available in single-user mode.
429 // Not sure why, but it causes errors here.
430 $this->inlineScript('var _peopletagAC = "' .
431 common_local_url('peopletagautocomplete') . '";');
432 $this->showScriptMessages();
433 // Anti-framing code to avoid clickjacking attacks in older browsers.
434 // This will show a blank page if the page is being framed, which is
435 // consistent with the behavior of the 'X-Frame-Options: SAMEORIGIN'
436 // header, which prevents framing in newer browser.
437 if (common_config('javascript', 'bustframes')) {
438 $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 = ""; }; }');
440 Event::handle('EndShowStatusNetScripts', array($this));
442 Event::handle('EndShowScripts', array($this));
447 * Exports a map of localized text strings to JavaScript code.
449 * Plugins can add to what's exported by hooking the StartScriptMessages or EndScriptMessages
450 * events and appending to the array. Try to avoid adding strings that won't be used, as
451 * they'll be added to HTML output.
453 function showScriptMessages()
457 if (Event::handle('StartScriptMessages', array($this, &$messages))) {
458 // Common messages needed for timeline views etc...
460 // TRANS: Localized tooltip for '...' expansion button on overlong remote messages.
461 $messages['showmore_tooltip'] = _m('TOOLTIP', 'Show more');
463 // TRANS: Inline reply form submit button: submits a reply comment.
464 $messages['reply_submit'] = _m('BUTTON', 'Reply');
466 // TRANS: Placeholder text for inline reply form. Clicking in this box will turn it into a mini notice form.
467 $messages['reply_placeholder'] = _m('Write a reply...');
469 $messages = array_merge($messages, $this->getScriptMessages());
471 Event::handle('EndScriptMessages', array($this, &$messages));
474 if (!empty($messages)) {
475 $this->inlineScript('SN.messages=' . json_encode($messages));
482 * If the action will need localizable text strings, export them here like so:
484 * return array('pool_deepend' => _('Deep end'),
485 * 'pool_shallow' => _('Shallow end'));
487 * The exported map will be available via SN.msg() to JS code:
489 * $('#pool').html('<div class="deepend"></div><div class="shallow"></div>');
490 * $('#pool .deepend').text(SN.msg('pool_deepend'));
491 * $('#pool .shallow').text(SN.msg('pool_shallow'));
493 * Exports a map of localized text strings to JavaScript code.
495 * Plugins can add to what's exported on any action by hooking the StartScriptMessages or
496 * EndScriptMessages events and appending to the array. Try to avoid adding strings that won't
497 * be used, as they'll be added to HTML output.
499 function getScriptMessages()
505 * Show OpenSearch headers
509 function showOpenSearch()
511 $this->element('link', array('rel' => 'search',
512 'type' => 'application/opensearchdescription+xml',
513 'href' => common_local_url('opensearch', array('type' => 'people')),
514 'title' => common_config('site', 'name').' People Search'));
515 $this->element('link', array('rel' => 'search', 'type' => 'application/opensearchdescription+xml',
516 'href' => common_local_url('opensearch', array('type' => 'notice')),
517 'title' => common_config('site', 'name').' Notice Search'));
529 $feeds = $this->getFeeds();
532 foreach ($feeds as $feed) {
533 $this->element('link', array('rel' => $feed->rel(),
534 'href' => $feed->url,
535 'type' => $feed->mimeType(),
536 'title' => $feed->title));
548 function showDescription()
550 // does nothing by default
554 * Show extra stuff in <head>.
562 // does nothing by default
568 * Calls template methods
574 $params = array('id' => $this->getActionName());
575 if ($this->scoped instanceof Profile) {
576 $params['class'] = 'user_in';
578 $this->elementStart('body', $params);
579 $this->elementStart('div', array('id' => 'wrap'));
580 if (Event::handle('StartShowHeader', array($this))) {
583 Event::handle('EndShowHeader', array($this));
587 if (Event::handle('StartShowFooter', array($this))) {
590 Event::handle('EndShowFooter', array($this));
592 $this->elementEnd('div');
593 $this->showScripts();
594 $this->elementEnd('body');
598 * Show header of the page.
600 * Calls template methods
604 function showHeader()
606 $this->elementStart('div', array('id' => 'header'));
608 $this->showPrimaryNav();
609 if (Event::handle('StartShowSiteNotice', array($this))) {
610 $this->showSiteNotice();
612 Event::handle('EndShowSiteNotice', array($this));
615 $this->elementEnd('div');
619 * Show configured logo.
625 $this->elementStart('address', array('id' => 'site_contact', 'class' => 'h-card'));
626 if (Event::handle('StartAddressData', array($this))) {
627 if (common_config('singleuser', 'enabled')) {
628 $user = User::singleUser();
629 $url = common_local_url('showstream',
630 array('nickname' => $user->nickname));
631 } else if (common_logged_in()) {
632 $cur = common_current_user();
633 $url = common_local_url('all', array('nickname' => $cur->nickname));
635 $url = common_local_url('public');
638 $this->elementStart('a', array('class' => 'home bookmark',
641 if (StatusNet::isHTTPS()) {
642 $logoUrl = common_config('site', 'ssllogo');
643 if (empty($logoUrl)) {
644 // if logo is an uploaded file, try to fall back to HTTPS file URL
645 $httpUrl = common_config('site', 'logo');
646 if (!empty($httpUrl)) {
647 $f = File::getKV('url', $httpUrl);
648 if (!empty($f) && !empty($f->filename)) {
649 // this will handle the HTTPS case
650 $logoUrl = File::url($f->filename);
655 $logoUrl = common_config('site', 'logo');
658 if (empty($logoUrl) && file_exists(Theme::file('logo.png'))) {
659 // This should handle the HTTPS case internally
660 $logoUrl = Theme::path('logo.png');
663 if (!empty($logoUrl)) {
664 $this->element('img', array('class' => 'logo u-photo p-name',
666 'alt' => common_config('site', 'name')));
669 $this->elementEnd('a');
671 Event::handle('EndAddressData', array($this));
673 $this->elementEnd('address');
677 * Show primary navigation.
681 function showPrimaryNav()
683 $this->elementStart('div', array('id' => 'site_nav_global_primary'));
685 $user = common_current_user();
687 if (!empty($user) || !common_config('site', 'private')) {
688 $form = new SearchForm($this);
692 $pn = new PrimaryNav($this);
694 $this->elementEnd('div');
702 function showSiteNotice()
704 // Revist. Should probably do an hAtom pattern here
705 $text = common_config('site', 'notice');
707 $this->elementStart('div', array('id' => 'site_notice',
708 'class' => 'system_notice'));
710 $this->elementEnd('div');
717 * MAY overload if no notice form needed... or direct message box????
721 function showNoticeForm()
723 // TRANS: Tab on the notice form.
724 $tabs = array('status' => array('title' => _m('TAB','Status'),
725 'href' => common_local_url('newnotice')));
727 $this->elementStart('div', 'input_forms');
729 if (Event::handle('StartShowEntryForms', array(&$tabs))) {
730 $this->elementStart('ul', array('class' => 'nav',
731 'id' => 'input_form_nav'));
733 foreach ($tabs as $tag => $data) {
734 $tag = htmlspecialchars($tag);
735 $attrs = array('id' => 'input_form_nav_'.$tag,
736 'class' => 'input_form_nav_tab');
738 if ($tag == 'status') {
739 // We're actually showing the placeholder form,
740 // but we special-case the 'Status' tab as if
741 // it were a small version of it.
742 $attrs['class'] .= ' current';
744 $this->elementStart('li', $attrs);
747 array('onclick' => 'return SN.U.switchInputFormTab("'.$tag.'");',
748 'href' => $data['href']),
750 $this->elementEnd('li');
753 $this->elementEnd('ul');
755 $attrs = array('class' => 'input_form current',
756 'id' => 'input_form_placeholder');
757 $this->elementStart('div', $attrs);
758 $form = new NoticePlaceholderForm($this);
760 $this->elementEnd('div');
762 foreach ($tabs as $tag => $data) {
763 $attrs = array('class' => 'input_form',
764 'id' => 'input_form_'.$tag);
766 $this->elementStart('div', $attrs);
770 if (Event::handle('StartMakeEntryForm', array($tag, $this, &$form))) {
771 if ($tag == 'status') {
772 $options = $this->noticeFormOptions();
773 $form = new NoticeForm($this, $options);
775 Event::handle('EndMakeEntryForm', array($tag, $this, $form));
782 $this->elementEnd('div');
786 $this->elementEnd('div');
789 function noticeFormOptions()
795 * Show anonymous message.
801 function showAnonymousMessage()
803 // needs to be defined by the class
809 * Shows local navigation, content block and aside.
815 $this->elementStart('div', array('id' => 'core'));
816 $this->elementStart('div', array('id' => 'aside_primary_wrapper'));
817 $this->elementStart('div', array('id' => 'content_wrapper'));
818 $this->elementStart('div', array('id' => 'site_nav_local_views_wrapper'));
819 if (Event::handle('StartShowLocalNavBlock', array($this))) {
820 $this->showLocalNavBlock();
822 Event::handle('EndShowLocalNavBlock', array($this));
824 if (Event::handle('StartShowContentBlock', array($this))) {
825 $this->showContentBlock();
827 Event::handle('EndShowContentBlock', array($this));
829 if (Event::handle('StartShowAside', array($this))) {
832 Event::handle('EndShowAside', array($this));
834 $this->elementEnd('div');
835 $this->elementEnd('div');
836 $this->elementEnd('div');
837 $this->elementEnd('div');
841 * Show local navigation block.
845 function showLocalNavBlock()
847 // Need to have this ID for CSS; I'm too lazy to add it to
849 $this->elementStart('div', array('id' => 'site_nav_local_views'));
850 // Cheat cheat cheat!
851 $this->showLocalNav();
852 $this->elementEnd('div');
856 * If there's a logged-in user, show a bit of login context
860 function showProfileBlock()
862 if (common_logged_in()) {
863 $block = new DefaultProfileBlock($this);
869 * Show local navigation.
875 function showLocalNav()
877 $nav = new DefaultLocalNav($this);
882 * Show menu for an object (group, profile)
884 * This block will only show if a subclass has overridden
885 * the showObjectNav() method.
889 function showObjectNavBlock()
891 $rmethod = new ReflectionMethod($this, 'showObjectNav');
892 $dclass = $rmethod->getDeclaringClass()->getName();
894 if ($dclass != 'Action') {
895 // Need to have this ID for CSS; I'm too lazy to add it to
897 $this->elementStart('div', array('id' => 'site_nav_object',
898 'class' => 'section'));
899 $this->showObjectNav();
900 $this->elementEnd('div');
905 * Show object navigation.
907 * If there are things to do with this object, show it here.
911 function showObjectNav()
917 * Show content block.
921 function showContentBlock()
923 $this->elementStart('div', array('id' => 'content'));
924 if (common_logged_in()) {
925 if (Event::handle('StartShowNoticeForm', array($this))) {
926 $this->showNoticeForm();
927 Event::handle('EndShowNoticeForm', array($this));
930 if (Event::handle('StartShowPageTitle', array($this))) {
931 $this->showPageTitle();
932 Event::handle('EndShowPageTitle', array($this));
934 $this->showPageNoticeBlock();
935 $this->elementStart('div', array('id' => 'content_inner'));
936 // show the actual content (forms, lists, whatever)
937 $this->showContent();
938 $this->elementEnd('div');
939 $this->elementEnd('div');
947 function showPageTitle()
949 $this->element('h1', null, $this->title());
953 * Show page notice block.
955 * Only show the block if a subclassed action has overrided
956 * Action::showPageNotice(), or an event handler is registered for
957 * the StartShowPageNotice event, in which case we assume the
958 * 'page_notice' definition list is desired. This is to prevent
959 * empty 'page_notice' definition lists from being output everywhere.
963 function showPageNoticeBlock()
965 $rmethod = new ReflectionMethod($this, 'showPageNotice');
966 $dclass = $rmethod->getDeclaringClass()->getName();
968 if ($dclass != 'Action' || Event::hasHandler('StartShowPageNotice')) {
970 $this->elementStart('div', array('id' => 'page_notice',
971 'class' => 'system_notice'));
972 if (Event::handle('StartShowPageNotice', array($this))) {
973 $this->showPageNotice();
974 Event::handle('EndShowPageNotice', array($this));
976 $this->elementEnd('div');
983 * SHOULD overload (unless there's not a notice)
987 function showPageNotice()
994 * MUST overload (unless there's not a notice)
998 protected function showContent()
1007 function showAside()
1009 $this->elementStart('div', array('id' => 'aside_primary',
1010 'class' => 'aside'));
1011 $this->showProfileBlock();
1012 if (Event::handle('StartShowObjectNavBlock', array($this))) {
1013 $this->showObjectNavBlock();
1014 Event::handle('EndShowObjectNavBlock', array($this));
1016 if (Event::handle('StartShowSections', array($this))) {
1017 $this->showSections();
1018 Event::handle('EndShowSections', array($this));
1020 if (Event::handle('StartShowExportData', array($this))) {
1021 $this->showExportData();
1022 Event::handle('EndShowExportData', array($this));
1024 $this->elementEnd('div');
1028 * Show export data feeds.
1032 function showExportData()
1034 $feeds = $this->getFeeds();
1036 $fl = new FeedList($this);
1048 function showSections()
1050 // for each section, show it
1058 function showFooter()
1060 $this->elementStart('div', array('id' => 'footer'));
1061 if (Event::handle('StartShowInsideFooter', array($this))) {
1062 $this->showSecondaryNav();
1063 $this->showLicenses();
1064 Event::handle('EndShowInsideFooter', array($this));
1066 $this->elementEnd('div');
1070 * Show secondary navigation.
1074 function showSecondaryNav()
1076 $sn = new SecondaryNav($this);
1085 function showLicenses()
1087 $this->showGNUsocialLicense();
1088 $this->showContentLicense();
1092 * Show GNU social license.
1096 function showGNUsocialLicense()
1098 if (common_config('site', 'broughtby')) {
1099 // TRANS: First sentence of the GNU social site license. Used if 'broughtby' is set.
1100 // TRANS: Text between [] is a link description, text between () is the link itself.
1101 // TRANS: Make sure there is no whitespace between "]" and "(".
1102 // TRANS: "%%site.broughtby%%" is the value of the variable site.broughtby
1103 $instr = _('**%%site.name%%** is a social network, courtesy of [%%site.broughtby%%](%%site.broughtbyurl%%).');
1105 // TRANS: First sentence of the GNU social site license. Used if 'broughtby' is not set.
1106 $instr = _('**%%site.name%%** is a social network.');
1109 // TRANS: Second sentence of the GNU social site license. Mentions the GNU social source code license.
1110 // TRANS: Make sure there is no whitespace between "]" and "(".
1111 // TRANS: [%1$s](%2$s) is a link description followed by the link itself
1112 // TRANS: %3$s is the version of GNU social that is being used.
1113 $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);
1114 $output = common_markup_to_html($instr);
1115 $this->raw($output);
1120 * Show content license.
1124 function showContentLicense()
1126 if (Event::handle('StartShowContentLicense', array($this))) {
1127 switch (common_config('license', 'type')) {
1129 // TRANS: Content license displayed when license is set to 'private'.
1130 // TRANS: %1$s is the site name.
1131 $this->element('p', null, sprintf(_('Content and data of %1$s are private and confidential.'),
1132 common_config('site', 'name')));
1134 case 'allrightsreserved':
1135 if (common_config('license', 'owner')) {
1136 // TRANS: Content license displayed when license is set to 'allrightsreserved'.
1137 // TRANS: %1$s is the copyright owner.
1138 $this->element('p', null, sprintf(_('Content and data copyright by %1$s. All rights reserved.'),
1139 common_config('license', 'owner')));
1141 // TRANS: Content license displayed when license is set to 'allrightsreserved' and no owner is set.
1142 $this->element('p', null, _('Content and data copyright by contributors. All rights reserved.'));
1145 case 'cc': // fall through
1147 $this->elementStart('p');
1149 $image = common_config('license', 'image');
1150 $sslimage = common_config('license', 'sslimage');
1152 if (StatusNet::isHTTPS()) {
1153 if (!empty($sslimage)) {
1155 } else if (preg_match('#^http://i.creativecommons.org/#', $image)) {
1156 // CC support HTTPS on their images
1157 $url = preg_replace('/^http/', 'https', $image);
1159 // Better to show mixed content than no content
1166 $this->element('img', array('id' => 'license_cc',
1168 'alt' => common_config('license', 'title'),
1172 // TRANS: license message in footer.
1173 // TRANS: %1$s is the site name, %2$s is a link to the license URL, with a licence name set in configuration.
1174 $notice = _('All %1$s content and data are available under the %2$s license.');
1175 $link = "<a class=\"license\" rel=\"external license\" href=\"" .
1176 htmlspecialchars(common_config('license', 'url')) .
1178 htmlspecialchars(common_config('license', 'title')) .
1180 $this->raw(sprintf(htmlspecialchars($notice),
1181 htmlspecialchars(common_config('site', 'name')),
1183 $this->elementEnd('p');
1187 Event::handle('EndShowContentLicense', array($this));
1192 * Return last modified, if applicable.
1196 * @return string last modified http header
1198 function lastModified()
1200 // For comparison with If-Last-Modified
1201 // If not applicable, return null
1206 * Return etag, if applicable.
1210 * @return string etag http header
1218 * Return true if read only.
1222 * @param array $args other arguments
1224 * @return boolean is read only action?
1226 function isReadOnly($args)
1232 * Returns query argument or default value if not found
1234 * @param string $key requested argument
1235 * @param string $def default value to return if $key is not provided
1237 * @return boolean is read only action?
1239 function arg($key, $def=null)
1241 if (array_key_exists($key, $this->args)) {
1242 return $this->args[$key];
1249 * Returns trimmed query argument or default value if not found
1251 * @param string $key requested argument
1252 * @param string $def default value to return if $key is not provided
1254 * @return boolean is read only action?
1256 function trimmed($key, $def=null)
1258 $arg = $this->arg($key, $def);
1259 return is_string($arg) ? trim($arg) : $arg;
1265 * @return boolean is read only action?
1267 protected function handle()
1269 header('Vary: Accept-Encoding,Cookie');
1271 $lm = $this->lastModified();
1272 $etag = $this->etag();
1275 header('ETag: ' . $etag);
1279 header('Last-Modified: ' . date(DATE_RFC1123, $lm));
1280 if ($this->isCacheable()) {
1281 header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', 0 ) . ' GMT' );
1282 header( "Cache-Control: private, must-revalidate, max-age=0" );
1289 $if_none_match = (array_key_exists('HTTP_IF_NONE_MATCH', $_SERVER)) ?
1290 $_SERVER['HTTP_IF_NONE_MATCH'] : null;
1291 if ($if_none_match) {
1292 // If this check fails, ignore the if-modified-since below.
1294 if ($this->_hasEtag($etag, $if_none_match)) {
1295 header('HTTP/1.1 304 Not Modified');
1296 // Better way to do this?
1302 if (!$checked && $lm && array_key_exists('HTTP_IF_MODIFIED_SINCE', $_SERVER)) {
1303 $if_modified_since = $_SERVER['HTTP_IF_MODIFIED_SINCE'];
1304 $ims = strtotime($if_modified_since);
1306 header('HTTP/1.1 304 Not Modified');
1307 // Better way to do this?
1314 * Is this action cacheable?
1316 * If the action returns a last-modified
1318 * @param array $argarray is ignored since it's now passed in in prepare()
1320 * @return boolean is read only action?
1322 function isCacheable()
1328 * Has etag? (private)
1330 * @param string $etag etag http header
1331 * @param string $if_none_match ifNoneMatch http header
1335 function _hasEtag($etag, $if_none_match)
1337 $etags = explode(',', $if_none_match);
1338 return in_array($etag, $etags) || in_array('*', $etags);
1342 * Boolean understands english (yes, no, true, false)
1344 * @param string $key query key we're interested in
1345 * @param string $def default value
1347 * @return boolean interprets yes/no strings as boolean
1349 function boolean($key, $def=false)
1351 $arg = strtolower($this->trimmed($key));
1353 if (is_null($arg)) {
1355 } else if (in_array($arg, array('true', 'yes', '1', 'on'))) {
1357 } else if (in_array($arg, array('false', 'no', '0'))) {
1365 * Integer value of an argument
1367 * @param string $key query key we're interested in
1368 * @param string $defValue optional default value (default null)
1369 * @param string $maxValue optional max value (default null)
1370 * @param string $minValue optional min value (default null)
1372 * @return integer integer value
1374 function int($key, $defValue=null, $maxValue=null, $minValue=null)
1376 $arg = intval($this->arg($key));
1378 if (!is_numeric($this->arg($key)) || $arg != $this->arg($key)) {
1382 if (!is_null($maxValue)) {
1383 $arg = min($arg, $maxValue);
1386 if (!is_null($minValue)) {
1387 $arg = max($arg, $minValue);
1396 * @param string $msg error message to display
1397 * @param integer $code http error code, 500 by default
1401 function serverError($msg, $code=500, $format=null)
1403 if ($format === null) {
1404 $format = $this->format;
1407 common_debug("Server error '{$code}' on '{$this->action}': {$msg}", __FILE__);
1409 if (!array_key_exists($code, ServerErrorAction::$status)) {
1413 $status_string = ServerErrorAction::$status[$code];
1417 header("HTTP/1.1 {$code} {$status_string}");
1418 $this->initDocument('xml');
1419 $this->elementStart('hash');
1420 $this->element('error', null, $msg);
1421 $this->element('request', null, $_SERVER['REQUEST_URI']);
1422 $this->elementEnd('hash');
1423 $this->endDocument('xml');
1426 if (!isset($this->callback)) {
1427 header("HTTP/1.1 {$code} {$status_string}");
1429 $this->initDocument('json');
1430 $error_array = array('error' => $msg, 'request' => $_SERVER['REQUEST_URI']);
1431 print(json_encode($error_array));
1432 $this->endDocument('json');
1435 throw new ServerException($msg, $code);
1444 * @param string $msg error message to display
1445 * @param integer $code http error code, 400 by default
1446 * @param string $format error format (json, xml, text) for ApiAction
1449 * @throws ClientException always
1451 function clientError($msg, $code=400, $format=null)
1453 // $format is currently only relevant for an ApiAction anyway
1454 if ($format === null) {
1455 $format = $this->format;
1458 common_debug("User error '{$code}' on '{$this->action}': {$msg}", __FILE__);
1460 if (!array_key_exists($code, ClientErrorAction::$status)) {
1464 $status_string = ClientErrorAction::$status[$code];
1468 header("HTTP/1.1 {$code} {$status_string}");
1469 $this->initDocument('xml');
1470 $this->elementStart('hash');
1471 $this->element('error', null, $msg);
1472 $this->element('request', null, $_SERVER['REQUEST_URI']);
1473 $this->elementEnd('hash');
1474 $this->endDocument('xml');
1477 if (!isset($this->callback)) {
1478 header("HTTP/1.1 {$code} {$status_string}");
1480 $this->initDocument('json');
1481 $error_array = array('error' => $msg, 'request' => $_SERVER['REQUEST_URI']);
1482 $this->text(json_encode($error_array));
1483 $this->endDocument('json');
1486 header("HTTP/1.1 {$code} {$status_string}");
1487 header('Content-Type: text/plain; charset=utf-8');
1491 throw new ClientException($msg, $code);
1497 * If not logged in, take appropriate action (redir or exception)
1499 * @param boolean $redir Redirect to login if not logged in
1501 * @return boolean true if logged in (never returns if not)
1503 public function checkLogin($redir=true)
1505 if (common_logged_in()) {
1510 common_set_returnto($_SERVER['REQUEST_URI']);
1511 common_redirect(common_local_url('login'));
1514 // TRANS: Error message displayed when trying to perform an action that requires a logged in user.
1515 $this->clientError(_('Not logged in.'), 403);
1519 * Returns the current URL
1521 * @return string current URL
1525 list($action, $args) = $this->returnToArgs();
1526 return common_local_url($action, $args);
1530 * Returns arguments sufficient for re-constructing URL
1532 * @return array two elements: action, other args
1534 function returnToArgs()
1536 $action = $this->getActionName();
1537 $args = $this->args;
1538 unset($args['action']);
1539 if (common_config('site', 'fancy')) {
1542 if (array_key_exists('submit', $args)) {
1543 unset($args['submit']);
1545 foreach (array_keys($_COOKIE) as $cookie) {
1546 unset($args[$cookie]);
1548 return array($action, $args);
1552 * Generate a menu item
1554 * @param string $url menu URL
1555 * @param string $text menu name
1556 * @param string $title title attribute, null by default
1557 * @param boolean $is_selected current menu item, false by default
1558 * @param string $id element id, null by default
1562 function menuItem($url, $text, $title=null, $is_selected=false, $id=null, $class=null)
1564 // Added @id to li for some control.
1565 // XXX: We might want to move this to htmloutputter.php
1568 if ($class !== null) {
1569 $classes[] = trim($class);
1572 $classes[] = 'current';
1575 if (!empty($classes)) {
1576 $lattrs['class'] = implode(' ', $classes);
1579 if (!is_null($id)) {
1580 $lattrs['id'] = $id;
1583 $this->elementStart('li', $lattrs);
1584 $attrs['href'] = $url;
1586 $attrs['title'] = $title;
1588 $this->element('a', $attrs, $text);
1589 $this->elementEnd('li');
1593 * Generate pagination links
1595 * @param boolean $have_before is there something before?
1596 * @param boolean $have_after is there something after?
1597 * @param integer $page current page
1598 * @param string $action current action
1599 * @param array $args rest of query arguments
1603 // XXX: The messages in this pagination method only tailor to navigating
1604 // notices. In other lists, "Previous"/"Next" type navigation is
1605 // desirable, but not available.
1606 function pagination($have_before, $have_after, $page, $action, $args=null)
1608 // Does a little before-after block for next/prev page
1609 if ($have_before || $have_after) {
1610 $this->elementStart('ul', array('class' => 'nav',
1611 'id' => 'pagination'));
1614 $pargs = array('page' => $page-1);
1615 $this->elementStart('li', array('class' => 'nav_prev'));
1616 $this->element('a', array('href' => common_local_url($action, $args, $pargs),
1618 // TRANS: Pagination message to go to a page displaying information more in the
1619 // TRANS: present than the currently displayed information.
1621 $this->elementEnd('li');
1624 $pargs = array('page' => $page+1);
1625 $this->elementStart('li', array('class' => 'nav_next'));
1626 $this->element('a', array('href' => common_local_url($action, $args, $pargs),
1628 // TRANS: Pagination message to go to a page displaying information more in the
1629 // TRANS: past than the currently displayed information.
1631 $this->elementEnd('li');
1633 if ($have_before || $have_after) {
1634 $this->elementEnd('ul');
1639 * An array of feeds for this action.
1641 * Returns an array of potential feeds for this action.
1643 * @return array Feed object to show in head and links
1651 * Check the session token.
1653 * Checks that the current form has the correct session token,
1654 * and throw an exception if it does not.
1658 // XXX: Finding this type of check with the same message about 50 times.
1659 // Possible to refactor?
1660 function checkSessionToken()
1663 $token = $this->trimmed('token');
1664 if (empty($token) || $token != common_session_token()) {
1665 // TRANS: Client error text when there is a problem with the session token.
1666 $this->clientError(_('There was a problem with your session token.'));
1671 * Check if the current request is a POST
1673 * @return boolean true if POST; otherwise false.
1678 return ($_SERVER['REQUEST_METHOD'] == 'POST');