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 if (Event::handle('StartActionExecute', array($this, &$args))) {
122 $prepared = $this->prepare($args);
124 $this->handle($args);
126 common_debug('Prepare failed for Action.');
132 Event::handle('EndActionExecute', array($this));
136 * For initializing members of the class.
138 * @param array $argarray misc. arguments
140 * @return boolean true
142 protected function prepare(array $args=array())
144 if ($this->needPost && !$this->isPost()) {
145 // TRANS: Client error. POST is a HTTP command. It should not be translated.
146 $this->clientError(_('This method requires a POST.'), 405);
149 // needPost, of course, overrides canPost if true
150 if (!$this->canPost) {
151 $this->canPost = $this->needPost;
154 $this->args = common_copy_args($args);
156 // This could be set with get_called_action and then
157 // chop off 'Action' from the class name. In lower case.
158 $this->action = strtolower($this->trimmed('action'));
160 if ($this->ajax || $this->boolean('ajax')) {
161 // check with StatusNet::isAjax()
162 StatusNet::setAjax(true);
165 if ($this->needLogin) {
166 $this->checkLogin(); // if not logged in, this redirs/excepts
169 $this->updateScopedProfile();
174 public function updateScopedProfile()
176 $this->scoped = Profile::current();
177 return $this->scoped;
180 public function getScoped()
182 return ($this->scoped instanceof Profile) ? $this->scoped : null;
185 // Must be run _after_ prepare
186 public function getActionName()
188 return $this->action;
191 public function isAction(array $names)
193 foreach ($names as $class) {
194 // PHP is case insensitive, and we have stuff like ApiUpperCaseAction,
195 // but we at least make a point out of wanting to do stuff case-sensitive.
196 $class = ucfirst($class) . 'Action';
197 if ($this instanceof $class) {
205 * Show page, a template method.
211 if (StatusNet::isAjax()) {
215 if (Event::handle('StartShowHTML', array($this))) {
218 Event::handle('EndShowHTML', array($this));
220 if (Event::handle('StartShowHead', array($this))) {
223 Event::handle('EndShowHead', array($this));
225 if (Event::handle('StartShowBody', array($this))) {
227 Event::handle('EndShowBody', array($this));
229 if (Event::handle('StartEndHTML', array($this))) {
231 Event::handle('EndEndHTML', array($this));
235 public function showAjax()
237 $this->startHTML('text/xml;charset=utf-8');
238 $this->elementStart('head');
239 // TRANS: Title for conversation page.
240 $this->element('title', null, $this->title());
241 $this->elementEnd('head');
242 $this->elementStart('body');
243 if ($this->getError()) {
244 $this->element('p', array('id'=>'error'), $this->getError());
246 $this->showContent();
248 $this->elementEnd('body');
256 if (isset($_startTime)) {
257 $endTime = microtime(true);
258 $diff = round(($endTime - $_startTime) * 1000);
259 $this->raw("<!-- ${diff}ms -->");
262 return parent::endHTML();
266 * Show head, a template method.
272 // XXX: attributes (profile?)
273 $this->elementStart('head');
274 if (Event::handle('StartShowHeadElements', array($this))) {
275 if (Event::handle('StartShowHeadTitle', array($this))) {
277 Event::handle('EndShowHeadTitle', array($this));
279 $this->showShortcutIcon();
280 $this->showStylesheets();
281 $this->showOpenSearch();
283 $this->showDescription();
285 Event::handle('EndShowHeadElements', array($this));
287 $this->elementEnd('head');
291 * Show title, a template method.
297 $this->element('title', null,
298 // TRANS: Page title. %1$s is the title, %2$s is the site name.
299 sprintf(_('%1$s - %2$s'),
301 common_config('site', 'name')));
305 * Returns the page title
309 * @return string page title
314 // TRANS: Page title for a page without a title set.
315 return _('Untitled page');
319 * Show themed shortcut icon
323 function showShortcutIcon()
325 if (is_readable(INSTALLDIR . '/theme/' . common_config('site', 'theme') . '/favicon.ico')) {
326 $this->element('link', array('rel' => 'shortcut icon',
327 'href' => Theme::path('favicon.ico')));
329 // favicon.ico should be HTTPS if the rest of the page is
330 $this->element('link', array('rel' => 'shortcut icon',
331 'href' => common_path('favicon.ico', StatusNet::isHTTPS())));
334 if (common_config('site', 'mobile')) {
335 if (is_readable(INSTALLDIR . '/theme/' . common_config('site', 'theme') . '/apple-touch-icon.png')) {
336 $this->element('link', array('rel' => 'apple-touch-icon',
337 'href' => Theme::path('apple-touch-icon.png')));
339 $this->element('link', array('rel' => 'apple-touch-icon',
340 'href' => common_path('apple-touch-icon.png')));
350 function showStylesheets()
352 if (Event::handle('StartShowStyles', array($this))) {
354 // Use old name for StatusNet for compatibility on events
356 if (Event::handle('StartShowStylesheets', array($this))) {
357 $this->primaryCssLink(null, 'screen, projection, tv, print');
358 Event::handle('EndShowStylesheets', array($this));
361 $this->cssLink('js/extlib/jquery-ui/css/smoothness/jquery-ui.css');
363 if (Event::handle('StartShowUAStyles', array($this))) {
364 Event::handle('EndShowUAStyles', array($this));
367 Event::handle('EndShowStyles', array($this));
369 if (common_config('custom_css', 'enabled')) {
370 $css = common_config('custom_css', 'css');
371 if (Event::handle('StartShowCustomCss', array($this, &$css))) {
372 if (trim($css) != '') {
375 Event::handle('EndShowCustomCss', array($this));
381 function primaryCssLink($mainTheme=null, $media=null)
383 $theme = new Theme($mainTheme);
385 // Some themes may have external stylesheets, such as using the
386 // Google Font APIs to load webfonts.
387 foreach ($theme->getExternals() as $url) {
388 $this->cssLink($url, $mainTheme, $media);
391 // If the currently-selected theme has dependencies on other themes,
392 // we'll need to load their display.css files as well in order.
393 $baseThemes = $theme->getDeps();
394 foreach ($baseThemes as $baseTheme) {
395 $this->cssLink('css/display.css', $baseTheme, $media);
397 $this->cssLink('css/display.css', $mainTheme, $media);
399 // Additional styles for RTL languages
400 if (is_rtl(common_language())) {
401 if (file_exists(Theme::file('css/rtl.css'))) {
402 $this->cssLink('css/rtl.css', $mainTheme, $media);
408 * Show javascript headers
412 function showScripts()
414 if (Event::handle('StartShowScripts', array($this))) {
415 if (Event::handle('StartShowJQueryScripts', array($this))) {
416 $this->script('extlib/jquery.js');
417 $this->script('extlib/jquery.form.js');
418 $this->script('extlib/jquery-ui/jquery-ui.js');
419 $this->script('extlib/jquery.cookie.js');
420 $this->inlineScript('if (typeof window.JSON !== "object") { $.getScript("'.common_path('js/extlib/json2.js', StatusNet::isHTTPS()).'"); }');
421 $this->script('extlib/jquery.infieldlabel.js');
423 Event::handle('EndShowJQueryScripts', array($this));
425 if (Event::handle('StartShowStatusNetScripts', array($this))) {
426 $this->script('util.js');
427 $this->script('xbImportNode.js');
428 $this->script('geometa.js');
430 // This route isn't available in single-user mode.
431 // Not sure why, but it causes errors here.
432 $this->inlineScript('var _peopletagAC = "' .
433 common_local_url('peopletagautocomplete') . '";');
434 $this->showScriptMessages();
435 // Anti-framing code to avoid clickjacking attacks in older browsers.
436 // This will show a blank page if the page is being framed, which is
437 // consistent with the behavior of the 'X-Frame-Options: SAMEORIGIN'
438 // header, which prevents framing in newer browser.
439 if (common_config('javascript', 'bustframes')) {
440 $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 = ""; }; }');
442 Event::handle('EndShowStatusNetScripts', array($this));
444 Event::handle('EndShowScripts', array($this));
449 * Exports a map of localized text strings to JavaScript code.
451 * Plugins can add to what's exported by hooking the StartScriptMessages or EndScriptMessages
452 * events and appending to the array. Try to avoid adding strings that won't be used, as
453 * they'll be added to HTML output.
455 function showScriptMessages()
459 if (Event::handle('StartScriptMessages', array($this, &$messages))) {
460 // Common messages needed for timeline views etc...
462 // TRANS: Localized tooltip for '...' expansion button on overlong remote messages.
463 $messages['showmore_tooltip'] = _m('TOOLTIP', 'Show more');
465 // TRANS: Inline reply form submit button: submits a reply comment.
466 $messages['reply_submit'] = _m('BUTTON', 'Reply');
468 // TRANS: Placeholder text for inline reply form. Clicking in this box will turn it into a mini notice form.
469 $messages['reply_placeholder'] = _m('Write a reply...');
471 $messages = array_merge($messages, $this->getScriptMessages());
473 Event::handle('EndScriptMessages', array($this, &$messages));
476 if (!empty($messages)) {
477 $this->inlineScript('SN.messages=' . json_encode($messages));
484 * If the action will need localizable text strings, export them here like so:
486 * return array('pool_deepend' => _('Deep end'),
487 * 'pool_shallow' => _('Shallow end'));
489 * The exported map will be available via SN.msg() to JS code:
491 * $('#pool').html('<div class="deepend"></div><div class="shallow"></div>');
492 * $('#pool .deepend').text(SN.msg('pool_deepend'));
493 * $('#pool .shallow').text(SN.msg('pool_shallow'));
495 * Exports a map of localized text strings to JavaScript code.
497 * Plugins can add to what's exported on any action by hooking the StartScriptMessages or
498 * EndScriptMessages events and appending to the array. Try to avoid adding strings that won't
499 * be used, as they'll be added to HTML output.
501 function getScriptMessages()
507 * Show OpenSearch headers
511 function showOpenSearch()
513 $this->element('link', array('rel' => 'search',
514 'type' => 'application/opensearchdescription+xml',
515 'href' => common_local_url('opensearch', array('type' => 'people')),
516 'title' => common_config('site', 'name').' People Search'));
517 $this->element('link', array('rel' => 'search', 'type' => 'application/opensearchdescription+xml',
518 'href' => common_local_url('opensearch', array('type' => 'notice')),
519 'title' => common_config('site', 'name').' Notice Search'));
531 $feeds = $this->getFeeds();
534 foreach ($feeds as $feed) {
535 $this->element('link', array('rel' => $feed->rel(),
536 'href' => $feed->url,
537 'type' => $feed->mimeType(),
538 'title' => $feed->title));
550 function showDescription()
552 // does nothing by default
556 * Show extra stuff in <head>.
564 // does nothing by default
570 * Calls template methods
576 $params = array('id' => $this->getActionName());
577 if ($this->scoped instanceof Profile) {
578 $params['class'] = 'user_in';
580 $this->elementStart('body', $params);
581 $this->elementStart('div', array('id' => 'wrap'));
582 if (Event::handle('StartShowHeader', array($this))) {
585 Event::handle('EndShowHeader', array($this));
589 if (Event::handle('StartShowFooter', array($this))) {
592 Event::handle('EndShowFooter', array($this));
594 $this->elementEnd('div');
595 $this->showScripts();
596 $this->elementEnd('body');
600 * Show header of the page.
602 * Calls template methods
606 function showHeader()
608 $this->elementStart('div', array('id' => 'header'));
610 $this->showPrimaryNav();
611 if (Event::handle('StartShowSiteNotice', array($this))) {
612 $this->showSiteNotice();
614 Event::handle('EndShowSiteNotice', array($this));
617 $this->elementEnd('div');
621 * Show configured logo.
627 $this->elementStart('address', array('id' => 'site_contact', 'class' => 'h-card'));
628 if (Event::handle('StartAddressData', array($this))) {
629 if (common_config('singleuser', 'enabled')) {
630 $user = User::singleUser();
631 $url = common_local_url('showstream',
632 array('nickname' => $user->nickname));
633 } else if (common_logged_in()) {
634 $cur = common_current_user();
635 $url = common_local_url('all', array('nickname' => $cur->nickname));
637 $url = common_local_url('public');
640 $this->elementStart('a', array('class' => 'home bookmark',
643 if (StatusNet::isHTTPS()) {
644 $logoUrl = common_config('site', 'ssllogo');
645 if (empty($logoUrl)) {
646 // if logo is an uploaded file, try to fall back to HTTPS file URL
647 $httpUrl = common_config('site', 'logo');
648 if (!empty($httpUrl)) {
649 $f = File::getKV('url', $httpUrl);
650 if (!empty($f) && !empty($f->filename)) {
651 // this will handle the HTTPS case
652 $logoUrl = File::url($f->filename);
657 $logoUrl = common_config('site', 'logo');
660 if (empty($logoUrl) && file_exists(Theme::file('logo.png'))) {
661 // This should handle the HTTPS case internally
662 $logoUrl = Theme::path('logo.png');
665 if (!empty($logoUrl)) {
666 $this->element('img', array('class' => 'logo u-photo p-name',
668 'alt' => common_config('site', 'name')));
671 $this->elementEnd('a');
673 Event::handle('EndAddressData', array($this));
675 $this->elementEnd('address');
679 * Show primary navigation.
683 function showPrimaryNav()
685 $this->elementStart('div', array('id' => 'site_nav_global_primary'));
687 $user = common_current_user();
689 if (!empty($user) || !common_config('site', 'private')) {
690 $form = new SearchForm($this);
694 $pn = new PrimaryNav($this);
696 $this->elementEnd('div');
704 function showSiteNotice()
706 // Revist. Should probably do an hAtom pattern here
707 $text = common_config('site', 'notice');
709 $this->elementStart('div', array('id' => 'site_notice',
710 'class' => 'system_notice'));
712 $this->elementEnd('div');
719 * MAY overload if no notice form needed... or direct message box????
723 function showNoticeForm()
725 // TRANS: Tab on the notice form.
726 $tabs = array('status' => array('title' => _m('TAB','Status'),
727 'href' => common_local_url('newnotice')));
729 $this->elementStart('div', 'input_forms');
731 $this->element('label', array('for'=>'input_form_nav'), _m('TAB', 'Share your:'));
733 if (Event::handle('StartShowEntryForms', array(&$tabs))) {
734 $this->elementStart('ul', array('class' => 'nav',
735 'id' => 'input_form_nav'));
737 foreach ($tabs as $tag => $data) {
738 $tag = htmlspecialchars($tag);
739 $attrs = array('id' => 'input_form_nav_'.$tag,
740 'class' => 'input_form_nav_tab');
742 if ($tag == 'status') {
743 $attrs['class'] .= ' current';
745 $this->elementStart('li', $attrs);
748 array('onclick' => 'return SN.U.switchInputFormTab("'.$tag.'");',
749 'href' => $data['href']),
751 $this->elementEnd('li');
754 $this->elementEnd('ul');
756 foreach ($tabs as $tag => $data) {
757 $attrs = array('class' => 'input_form',
758 'id' => 'input_form_'.$tag);
759 if ($tag == 'status') {
760 $attrs['class'] .= ' current';
763 $this->elementStart('div', $attrs);
767 if (Event::handle('StartMakeEntryForm', array($tag, $this, &$form))) {
768 if ($tag == 'status') {
769 $options = $this->noticeFormOptions();
770 $form = new NoticeForm($this, $options);
772 Event::handle('EndMakeEntryForm', array($tag, $this, $form));
779 $this->elementEnd('div');
783 $this->elementEnd('div');
786 function noticeFormOptions()
792 * Show anonymous message.
798 function showAnonymousMessage()
800 // needs to be defined by the class
806 * Shows local navigation, content block and aside.
812 $this->elementStart('div', array('id' => 'core'));
813 $this->elementStart('div', array('id' => 'aside_primary_wrapper'));
814 $this->elementStart('div', array('id' => 'content_wrapper'));
815 $this->elementStart('div', array('id' => 'site_nav_local_views_wrapper'));
816 if (Event::handle('StartShowLocalNavBlock', array($this))) {
817 $this->showLocalNavBlock();
819 Event::handle('EndShowLocalNavBlock', array($this));
821 if (Event::handle('StartShowContentBlock', array($this))) {
822 $this->showContentBlock();
824 Event::handle('EndShowContentBlock', array($this));
826 if (Event::handle('StartShowAside', array($this))) {
829 Event::handle('EndShowAside', array($this));
831 $this->elementEnd('div');
832 $this->elementEnd('div');
833 $this->elementEnd('div');
834 $this->elementEnd('div');
838 * Show local navigation block.
842 function showLocalNavBlock()
844 // Need to have this ID for CSS; I'm too lazy to add it to
846 $this->elementStart('div', array('id' => 'site_nav_local_views'));
847 // Cheat cheat cheat!
848 $this->showLocalNav();
849 $this->elementEnd('div');
853 * If there's a logged-in user, show a bit of login context
857 function showProfileBlock()
859 if (common_logged_in()) {
860 $block = new DefaultProfileBlock($this);
866 * Show local navigation.
872 function showLocalNav()
874 $nav = new DefaultLocalNav($this);
879 * Show menu for an object (group, profile)
881 * This block will only show if a subclass has overridden
882 * the showObjectNav() method.
886 function showObjectNavBlock()
888 $rmethod = new ReflectionMethod($this, 'showObjectNav');
889 $dclass = $rmethod->getDeclaringClass()->getName();
891 if ($dclass != 'Action') {
892 // Need to have this ID for CSS; I'm too lazy to add it to
894 $this->elementStart('div', array('id' => 'site_nav_object',
895 'class' => 'section'));
896 $this->showObjectNav();
897 $this->elementEnd('div');
902 * Show object navigation.
904 * If there are things to do with this object, show it here.
908 function showObjectNav()
914 * Show content block.
918 function showContentBlock()
920 $this->elementStart('div', array('id' => 'content'));
921 if (common_logged_in()) {
922 if (Event::handle('StartShowNoticeForm', array($this))) {
923 $this->showNoticeForm();
924 Event::handle('EndShowNoticeForm', array($this));
927 if (Event::handle('StartShowPageTitle', array($this))) {
928 $this->showPageTitle();
929 Event::handle('EndShowPageTitle', array($this));
931 $this->showPageNoticeBlock();
932 $this->elementStart('div', array('id' => 'content_inner'));
933 // show the actual content (forms, lists, whatever)
934 $this->showContent();
935 $this->elementEnd('div');
936 $this->elementEnd('div');
944 function showPageTitle()
946 $this->element('h1', null, $this->title());
950 * Show page notice block.
952 * Only show the block if a subclassed action has overrided
953 * Action::showPageNotice(), or an event handler is registered for
954 * the StartShowPageNotice event, in which case we assume the
955 * 'page_notice' definition list is desired. This is to prevent
956 * empty 'page_notice' definition lists from being output everywhere.
960 function showPageNoticeBlock()
962 $rmethod = new ReflectionMethod($this, 'showPageNotice');
963 $dclass = $rmethod->getDeclaringClass()->getName();
965 if ($dclass != 'Action' || Event::hasHandler('StartShowPageNotice')) {
967 $this->elementStart('div', array('id' => 'page_notice',
968 'class' => 'system_notice'));
969 if (Event::handle('StartShowPageNotice', array($this))) {
970 $this->showPageNotice();
971 Event::handle('EndShowPageNotice', array($this));
973 $this->elementEnd('div');
980 * SHOULD overload (unless there's not a notice)
984 function showPageNotice()
991 * MUST overload (unless there's not a notice)
995 protected function showContent()
1004 function showAside()
1006 $this->elementStart('div', array('id' => 'aside_primary',
1007 'class' => 'aside'));
1008 $this->showProfileBlock();
1009 if (Event::handle('StartShowObjectNavBlock', array($this))) {
1010 $this->showObjectNavBlock();
1011 Event::handle('EndShowObjectNavBlock', array($this));
1013 if (Event::handle('StartShowSections', array($this))) {
1014 $this->showSections();
1015 Event::handle('EndShowSections', array($this));
1017 if (Event::handle('StartShowExportData', array($this))) {
1018 $this->showExportData();
1019 Event::handle('EndShowExportData', array($this));
1021 $this->elementEnd('div');
1025 * Show export data feeds.
1029 function showExportData()
1031 $feeds = $this->getFeeds();
1033 $fl = new FeedList($this);
1045 function showSections()
1047 // for each section, show it
1055 function showFooter()
1057 $this->elementStart('div', array('id' => 'footer'));
1058 if (Event::handle('StartShowInsideFooter', array($this))) {
1059 $this->showSecondaryNav();
1060 $this->showLicenses();
1061 Event::handle('EndShowInsideFooter', array($this));
1063 $this->elementEnd('div');
1067 * Show secondary navigation.
1071 function showSecondaryNav()
1073 $sn = new SecondaryNav($this);
1082 function showLicenses()
1084 $this->showGNUsocialLicense();
1085 $this->showContentLicense();
1089 * Show GNU social license.
1093 function showGNUsocialLicense()
1095 if (common_config('site', 'broughtby')) {
1096 // TRANS: First sentence of the GNU social site license. Used if 'broughtby' is set.
1097 // TRANS: Text between [] is a link description, text between () is the link itself.
1098 // TRANS: Make sure there is no whitespace between "]" and "(".
1099 // TRANS: "%%site.broughtby%%" is the value of the variable site.broughtby
1100 $instr = _('**%%site.name%%** is a social network, courtesy of [%%site.broughtby%%](%%site.broughtbyurl%%).');
1102 // TRANS: First sentence of the GNU social site license. Used if 'broughtby' is not set.
1103 $instr = _('**%%site.name%%** is a social network.');
1106 // TRANS: Second sentence of the GNU social site license. Mentions the GNU social source code license.
1107 // TRANS: Make sure there is no whitespace between "]" and "(".
1108 // TRANS: [%1$s](%2$s) is a link description followed by the link itself
1109 // TRANS: %3$s is the version of GNU social that is being used.
1110 $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);
1111 $output = common_markup_to_html($instr);
1112 $this->raw($output);
1117 * Show content license.
1121 function showContentLicense()
1123 if (Event::handle('StartShowContentLicense', array($this))) {
1124 switch (common_config('license', 'type')) {
1126 // TRANS: Content license displayed when license is set to 'private'.
1127 // TRANS: %1$s is the site name.
1128 $this->element('p', null, sprintf(_('Content and data of %1$s are private and confidential.'),
1129 common_config('site', 'name')));
1131 case 'allrightsreserved':
1132 if (common_config('license', 'owner')) {
1133 // TRANS: Content license displayed when license is set to 'allrightsreserved'.
1134 // TRANS: %1$s is the copyright owner.
1135 $this->element('p', null, sprintf(_('Content and data copyright by %1$s. All rights reserved.'),
1136 common_config('license', 'owner')));
1138 // TRANS: Content license displayed when license is set to 'allrightsreserved' and no owner is set.
1139 $this->element('p', null, _('Content and data copyright by contributors. All rights reserved.'));
1142 case 'cc': // fall through
1144 $this->elementStart('p');
1146 $image = common_config('license', 'image');
1147 $sslimage = common_config('license', 'sslimage');
1149 if (StatusNet::isHTTPS()) {
1150 if (!empty($sslimage)) {
1152 } else if (preg_match('#^http://i.creativecommons.org/#', $image)) {
1153 // CC support HTTPS on their images
1154 $url = preg_replace('/^http/', 'https', $image);
1156 // Better to show mixed content than no content
1163 $this->element('img', array('id' => 'license_cc',
1165 'alt' => common_config('license', 'title'),
1169 // TRANS: license message in footer.
1170 // TRANS: %1$s is the site name, %2$s is a link to the license URL, with a licence name set in configuration.
1171 $notice = _('All %1$s content and data are available under the %2$s license.');
1172 $link = sprintf('<a class="license" rel="external license" href="%1$s">%2$s</a>',
1173 htmlspecialchars(common_config('license', 'url')),
1174 htmlspecialchars(common_config('license', 'title')));
1175 $this->raw(@sprintf(htmlspecialchars($notice),
1176 htmlspecialchars(common_config('site', 'name')),
1178 $this->elementEnd('p');
1182 Event::handle('EndShowContentLicense', array($this));
1187 * Return last modified, if applicable.
1191 * @return string last modified http header
1193 function lastModified()
1195 // For comparison with If-Last-Modified
1196 // If not applicable, return null
1201 * Return etag, if applicable.
1205 * @return string etag http header
1213 * Return true if read only.
1217 * @param array $args other arguments
1219 * @return boolean is read only action?
1221 function isReadOnly($args)
1227 * Returns query argument or default value if not found
1229 * @param string $key requested argument
1230 * @param string $def default value to return if $key is not provided
1232 * @return boolean is read only action?
1234 function arg($key, $def=null)
1236 if (array_key_exists($key, $this->args)) {
1237 return $this->args[$key];
1244 * Returns trimmed query argument or default value if not found
1246 * @param string $key requested argument
1247 * @param string $def default value to return if $key is not provided
1249 * @return boolean is read only action?
1251 function trimmed($key, $def=null)
1253 $arg = $this->arg($key, $def);
1254 return is_string($arg) ? trim($arg) : $arg;
1260 * @return boolean is read only action?
1262 protected function handle()
1264 header('Vary: Accept-Encoding,Cookie');
1266 $lm = $this->lastModified();
1267 $etag = $this->etag();
1270 header('ETag: ' . $etag);
1274 header('Last-Modified: ' . date(DATE_RFC1123, $lm));
1275 if ($this->isCacheable()) {
1276 header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', 0 ) . ' GMT' );
1277 header( "Cache-Control: private, must-revalidate, max-age=0" );
1284 $if_none_match = (array_key_exists('HTTP_IF_NONE_MATCH', $_SERVER)) ?
1285 $_SERVER['HTTP_IF_NONE_MATCH'] : null;
1286 if ($if_none_match) {
1287 // If this check fails, ignore the if-modified-since below.
1289 if ($this->_hasEtag($etag, $if_none_match)) {
1290 header('HTTP/1.1 304 Not Modified');
1291 // Better way to do this?
1297 if (!$checked && $lm && array_key_exists('HTTP_IF_MODIFIED_SINCE', $_SERVER)) {
1298 $if_modified_since = $_SERVER['HTTP_IF_MODIFIED_SINCE'];
1299 $ims = strtotime($if_modified_since);
1301 header('HTTP/1.1 304 Not Modified');
1302 // Better way to do this?
1309 * Is this action cacheable?
1311 * If the action returns a last-modified
1313 * @param array $argarray is ignored since it's now passed in in prepare()
1315 * @return boolean is read only action?
1317 function isCacheable()
1323 * Has etag? (private)
1325 * @param string $etag etag http header
1326 * @param string $if_none_match ifNoneMatch http header
1330 function _hasEtag($etag, $if_none_match)
1332 $etags = explode(',', $if_none_match);
1333 return in_array($etag, $etags) || in_array('*', $etags);
1337 * Boolean understands english (yes, no, true, false)
1339 * @param string $key query key we're interested in
1340 * @param string $def default value
1342 * @return boolean interprets yes/no strings as boolean
1344 function boolean($key, $def=false)
1346 $arg = strtolower($this->trimmed($key));
1348 if (is_null($arg)) {
1350 } else if (in_array($arg, array('true', 'yes', '1', 'on'))) {
1352 } else if (in_array($arg, array('false', 'no', '0'))) {
1360 * Integer value of an argument
1362 * @param string $key query key we're interested in
1363 * @param string $defValue optional default value (default null)
1364 * @param string $maxValue optional max value (default null)
1365 * @param string $minValue optional min value (default null)
1367 * @return integer integer value
1369 function int($key, $defValue=null, $maxValue=null, $minValue=null)
1371 $arg = intval($this->arg($key));
1373 if (!is_numeric($this->arg($key)) || $arg != $this->arg($key)) {
1377 if (!is_null($maxValue)) {
1378 $arg = min($arg, $maxValue);
1381 if (!is_null($minValue)) {
1382 $arg = max($arg, $minValue);
1391 * @param string $msg error message to display
1392 * @param integer $code http error code, 500 by default
1396 function serverError($msg, $code=500, $format=null)
1398 if ($format === null) {
1399 $format = $this->format;
1402 common_debug("Server error '{$code}' on '{$this->action}': {$msg}", __FILE__);
1404 if (!array_key_exists($code, ServerErrorAction::$status)) {
1408 $status_string = ServerErrorAction::$status[$code];
1412 header("HTTP/1.1 {$code} {$status_string}");
1413 $this->initDocument('xml');
1414 $this->elementStart('hash');
1415 $this->element('error', null, $msg);
1416 $this->element('request', null, $_SERVER['REQUEST_URI']);
1417 $this->elementEnd('hash');
1418 $this->endDocument('xml');
1421 if (!isset($this->callback)) {
1422 header("HTTP/1.1 {$code} {$status_string}");
1424 $this->initDocument('json');
1425 $error_array = array('error' => $msg, 'request' => $_SERVER['REQUEST_URI']);
1426 print(json_encode($error_array));
1427 $this->endDocument('json');
1430 throw new ServerException($msg, $code);
1439 * @param string $msg error message to display
1440 * @param integer $code http error code, 400 by default
1441 * @param string $format error format (json, xml, text) for ApiAction
1444 * @throws ClientException always
1446 function clientError($msg, $code=400, $format=null)
1448 // $format is currently only relevant for an ApiAction anyway
1449 if ($format === null) {
1450 $format = $this->format;
1453 common_debug("User error '{$code}' on '{$this->action}': {$msg}", __FILE__);
1455 if (!array_key_exists($code, ClientErrorAction::$status)) {
1459 $status_string = ClientErrorAction::$status[$code];
1463 header("HTTP/1.1 {$code} {$status_string}");
1464 $this->initDocument('xml');
1465 $this->elementStart('hash');
1466 $this->element('error', null, $msg);
1467 $this->element('request', null, $_SERVER['REQUEST_URI']);
1468 $this->elementEnd('hash');
1469 $this->endDocument('xml');
1472 if (!isset($this->callback)) {
1473 header("HTTP/1.1 {$code} {$status_string}");
1475 $this->initDocument('json');
1476 $error_array = array('error' => $msg, 'request' => $_SERVER['REQUEST_URI']);
1477 $this->text(json_encode($error_array));
1478 $this->endDocument('json');
1481 header("HTTP/1.1 {$code} {$status_string}");
1482 header('Content-Type: text/plain; charset=utf-8');
1486 throw new ClientException($msg, $code);
1492 * If not logged in, take appropriate action (redir or exception)
1494 * @param boolean $redir Redirect to login if not logged in
1496 * @return boolean true if logged in (never returns if not)
1498 public function checkLogin($redir=true)
1500 if (common_logged_in()) {
1505 common_set_returnto($_SERVER['REQUEST_URI']);
1506 common_redirect(common_local_url('login'));
1509 // TRANS: Error message displayed when trying to perform an action that requires a logged in user.
1510 $this->clientError(_('Not logged in.'), 403);
1514 * Returns the current URL
1516 * @return string current URL
1520 list($action, $args) = $this->returnToArgs();
1521 return common_local_url($action, $args);
1525 * Returns arguments sufficient for re-constructing URL
1527 * @return array two elements: action, other args
1529 function returnToArgs()
1531 $action = $this->getActionName();
1532 $args = $this->args;
1533 unset($args['action']);
1534 if (common_config('site', 'fancy')) {
1537 if (array_key_exists('submit', $args)) {
1538 unset($args['submit']);
1540 foreach (array_keys($_COOKIE) as $cookie) {
1541 unset($args[$cookie]);
1543 return array($action, $args);
1547 * Generate a menu item
1549 * @param string $url menu URL
1550 * @param string $text menu name
1551 * @param string $title title attribute, null by default
1552 * @param boolean $is_selected current menu item, false by default
1553 * @param string $id element id, null by default
1557 function menuItem($url, $text, $title=null, $is_selected=false, $id=null, $class=null)
1559 // Added @id to li for some control.
1560 // XXX: We might want to move this to htmloutputter.php
1563 if ($class !== null) {
1564 $classes[] = trim($class);
1567 $classes[] = 'current';
1570 if (!empty($classes)) {
1571 $lattrs['class'] = implode(' ', $classes);
1574 if (!is_null($id)) {
1575 $lattrs['id'] = $id;
1578 $this->elementStart('li', $lattrs);
1579 $attrs['href'] = $url;
1581 $attrs['title'] = $title;
1583 $this->element('a', $attrs, $text);
1584 $this->elementEnd('li');
1588 * Generate pagination links
1590 * @param boolean $have_before is there something before?
1591 * @param boolean $have_after is there something after?
1592 * @param integer $page current page
1593 * @param string $action current action
1594 * @param array $args rest of query arguments
1598 // XXX: The messages in this pagination method only tailor to navigating
1599 // notices. In other lists, "Previous"/"Next" type navigation is
1600 // desirable, but not available.
1601 function pagination($have_before, $have_after, $page, $action, $args=null)
1603 // Does a little before-after block for next/prev page
1604 if ($have_before || $have_after) {
1605 $this->elementStart('ul', array('class' => 'nav',
1606 'id' => 'pagination'));
1609 $pargs = array('page' => $page-1);
1610 $this->elementStart('li', array('class' => 'nav_prev'));
1611 $this->element('a', array('href' => common_local_url($action, $args, $pargs),
1613 // TRANS: Pagination message to go to a page displaying information more in the
1614 // TRANS: present than the currently displayed information.
1616 $this->elementEnd('li');
1619 $pargs = array('page' => $page+1);
1620 $this->elementStart('li', array('class' => 'nav_next'));
1621 $this->element('a', array('href' => common_local_url($action, $args, $pargs),
1623 // TRANS: Pagination message to go to a page displaying information more in the
1624 // TRANS: past than the currently displayed information.
1626 $this->elementEnd('li');
1628 if ($have_before || $have_after) {
1629 $this->elementEnd('ul');
1634 * An array of feeds for this action.
1636 * Returns an array of potential feeds for this action.
1638 * @return array Feed object to show in head and links
1646 * Check the session token.
1648 * Checks that the current form has the correct session token,
1649 * and throw an exception if it does not.
1653 // XXX: Finding this type of check with the same message about 50 times.
1654 // Possible to refactor?
1655 function checkSessionToken()
1658 $token = $this->trimmed('token');
1659 if (empty($token) || $token != common_session_token()) {
1660 // TRANS: Client error text when there is a problem with the session token.
1661 $this->clientError(_('There was a problem with your session token.'));
1666 * Check if the current request is a POST
1668 * @return boolean true if POST; otherwise false.
1673 return ($_SERVER['REQUEST_METHOD'] == 'POST');