action.php 53 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708
  1. <?php
  2. /**
  3. * StatusNet, the distributed open-source microblogging tool
  4. *
  5. * Base class for all actions (~views)
  6. *
  7. * PHP version 5
  8. *
  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.
  13. *
  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.
  18. *
  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/>.
  21. *
  22. * @category Action
  23. * @package StatusNet
  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/
  29. */
  30. if (!defined('GNUSOCIAL')) { exit(1); }
  31. /**
  32. * Base class for all actions
  33. *
  34. * This is the base class for all actions in the package. An action is
  35. * more or less a "view" in an MVC framework.
  36. *
  37. * Actions are responsible for extracting and validating parameters; using
  38. * model classes to read and write to the database; and doing ouput.
  39. *
  40. * @category Output
  41. * @package StatusNet
  42. * @author Evan Prodromou <evan@status.net>
  43. * @author Sarven Capadisli <csarven@status.net>
  44. * @license http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
  45. * @link http://status.net/
  46. *
  47. * @see HTMLOutputter
  48. */
  49. class Action extends HTMLOutputter // lawsuit
  50. {
  51. // This should be protected/private in the future
  52. public $args = array();
  53. // Action properties, set per-class
  54. protected $action = false;
  55. protected $ajax = false;
  56. protected $menus = true;
  57. protected $needLogin = false;
  58. protected $needPost = false; // implies canPost if true
  59. protected $canPost = false; // can this action handle POST method?
  60. // The currently scoped profile (normally Profile::current; from $this->auth_user for API)
  61. protected $scoped = null;
  62. // Related to front-end user representation
  63. protected $format = null;
  64. protected $error = null;
  65. protected $msg = null;
  66. /**
  67. * Constructor
  68. *
  69. * Just wraps the HTMLOutputter constructor.
  70. *
  71. * @param string $output URI to output to, default = stdout
  72. * @param boolean $indent Whether to indent output, default true
  73. *
  74. * @see XMLOutputter::__construct
  75. * @see HTMLOutputter::__construct
  76. */
  77. function __construct($output='php://output', $indent=null)
  78. {
  79. parent::__construct($output, $indent);
  80. }
  81. function getError()
  82. {
  83. return $this->error;
  84. }
  85. function getInfo()
  86. {
  87. return $this->msg;
  88. }
  89. public function handleError($e)
  90. {
  91. if ($e instanceof ClientException) {
  92. $this->clientError($e->getMessage(), $e->getCode());
  93. } elseif ($e instanceof ServerException) {
  94. $this->serverError($e->getMessage(), $e->getCode());
  95. } else {
  96. // If it wasn't specified more closely which kind of exception it was
  97. $this->serverError($e->getMessage(), 500);
  98. }
  99. }
  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. set_exception_handler(array($action, 'handleError'));
  104. $action->execute($args);
  105. return $action;
  106. }
  107. public function execute(array $args=array()) {
  108. // checkMirror stuff
  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);
  114. $mirror = $arr[$k];
  115. } else {
  116. $mirror = common_config('db', 'mirror');
  117. }
  118. // everyone else uses the mirror
  119. common_config_set('db', 'database', $mirror);
  120. }
  121. if (Event::handle('StartActionExecute', array($this, &$args))) {
  122. $prepared = $this->prepare($args);
  123. if ($prepared) {
  124. $this->handle($args);
  125. } else {
  126. common_debug('Prepare failed for Action.');
  127. }
  128. $this->flush();
  129. Event::handle('EndActionExecute', array($this));
  130. }
  131. }
  132. /**
  133. * For initializing members of the class.
  134. *
  135. * @param array $argarray misc. arguments
  136. *
  137. * @return boolean true
  138. */
  139. protected function prepare(array $args=array())
  140. {
  141. if ($this->needPost && !$this->isPost()) {
  142. // TRANS: Client error. POST is a HTTP command. It should not be translated.
  143. $this->clientError(_('This method requires a POST.'), 405);
  144. }
  145. // needPost, of course, overrides canPost if true
  146. if (!$this->canPost) {
  147. $this->canPost = $this->needPost;
  148. }
  149. $this->args = common_copy_args($args);
  150. // This could be set with get_called_action and then
  151. // chop off 'Action' from the class name. In lower case.
  152. $this->action = strtolower($this->trimmed('action'));
  153. if ($this->ajax || $this->boolean('ajax')) {
  154. // check with GNUsocial::isAjax()
  155. GNUsocial::setAjax(true);
  156. }
  157. if ($this->needLogin) {
  158. $this->checkLogin(); // if not logged in, this redirs/excepts
  159. }
  160. $this->updateScopedProfile();
  161. return true;
  162. }
  163. public function updateScopedProfile()
  164. {
  165. $this->scoped = Profile::current();
  166. return $this->scoped;
  167. }
  168. public function getScoped()
  169. {
  170. return ($this->scoped instanceof Profile) ? $this->scoped : null;
  171. }
  172. // Must be run _after_ prepare
  173. public function getActionName()
  174. {
  175. return $this->action;
  176. }
  177. public function isAction(array $names)
  178. {
  179. foreach ($names as $class) {
  180. // PHP is case insensitive, and we have stuff like ApiUpperCaseAction,
  181. // but we at least make a point out of wanting to do stuff case-sensitive.
  182. $class = ucfirst($class) . 'Action';
  183. if ($this instanceof $class) {
  184. return true;
  185. }
  186. }
  187. return false;
  188. }
  189. /**
  190. * Show page, a template method.
  191. *
  192. * @return nothing
  193. */
  194. public function showPage()
  195. {
  196. if (GNUsocial::isAjax()) {
  197. self::showAjax();
  198. return;
  199. }
  200. if (Event::handle('StartShowHTML', array($this))) {
  201. $this->startHTML();
  202. $this->flush();
  203. Event::handle('EndShowHTML', array($this));
  204. }
  205. if (Event::handle('StartShowHead', array($this))) {
  206. $this->showHead();
  207. $this->flush();
  208. Event::handle('EndShowHead', array($this));
  209. }
  210. if (Event::handle('StartShowBody', array($this))) {
  211. $this->showBody();
  212. Event::handle('EndShowBody', array($this));
  213. }
  214. if (Event::handle('StartEndHTML', array($this))) {
  215. $this->endHTML();
  216. Event::handle('EndEndHTML', array($this));
  217. }
  218. }
  219. public function showAjax()
  220. {
  221. $this->startHTML('text/xml;charset=utf-8');
  222. $this->elementStart('head');
  223. // TRANS: Title for conversation page.
  224. $this->element('title', null, $this->title());
  225. $this->elementEnd('head');
  226. $this->elementStart('body');
  227. if ($this->getError()) {
  228. $this->element('p', array('id'=>'error'), $this->getError());
  229. } else {
  230. $this->showContent();
  231. }
  232. $this->elementEnd('body');
  233. $this->endHTML();
  234. }
  235. function endHTML()
  236. {
  237. global $_startTime;
  238. if (isset($_startTime)) {
  239. $endTime = microtime(true);
  240. $diff = round(($endTime - $_startTime) * 1000);
  241. $this->raw("<!-- ${diff}ms -->");
  242. }
  243. return parent::endHTML();
  244. }
  245. /**
  246. * Show head, a template method.
  247. *
  248. * @return nothing
  249. */
  250. function showHead()
  251. {
  252. // XXX: attributes (profile?)
  253. $this->elementStart('head');
  254. if (Event::handle('StartShowHeadElements', array($this))) {
  255. if (Event::handle('StartShowHeadTitle', array($this))) {
  256. $this->showTitle();
  257. Event::handle('EndShowHeadTitle', array($this));
  258. }
  259. $this->showShortcutIcon();
  260. $this->showStylesheets();
  261. $this->showOpenSearch();
  262. $this->showFeeds();
  263. $this->showDescription();
  264. $this->extraHead();
  265. Event::handle('EndShowHeadElements', array($this));
  266. }
  267. $this->elementEnd('head');
  268. }
  269. /**
  270. * Show title, a template method.
  271. *
  272. * @return nothing
  273. */
  274. function showTitle()
  275. {
  276. $this->element('title', null,
  277. // TRANS: Page title. %1$s is the title, %2$s is the site name.
  278. sprintf(_('%1$s - %2$s'),
  279. $this->title(),
  280. common_config('site', 'name')));
  281. }
  282. /**
  283. * Returns the page title
  284. *
  285. * SHOULD overload
  286. *
  287. * @return string page title
  288. */
  289. function title()
  290. {
  291. // TRANS: Page title for a page without a title set.
  292. return _('Untitled page');
  293. }
  294. /**
  295. * Show themed shortcut icon
  296. *
  297. * @return nothing
  298. */
  299. function showShortcutIcon()
  300. {
  301. if (is_readable(INSTALLDIR . '/theme/' . common_config('site', 'theme') . '/favicon.ico')) {
  302. $this->element('link', array('rel' => 'shortcut icon',
  303. 'href' => Theme::path('favicon.ico')));
  304. } else {
  305. // favicon.ico should be HTTPS if the rest of the page is
  306. $this->element('link', array('rel' => 'shortcut icon',
  307. 'href' => common_path('favicon.ico', GNUsocial::isHTTPS())));
  308. }
  309. if (common_config('site', 'mobile')) {
  310. if (is_readable(INSTALLDIR . '/theme/' . common_config('site', 'theme') . '/apple-touch-icon.png')) {
  311. $this->element('link', array('rel' => 'apple-touch-icon',
  312. 'href' => Theme::path('apple-touch-icon.png')));
  313. } else {
  314. $this->element('link', array('rel' => 'apple-touch-icon',
  315. 'href' => common_path('apple-touch-icon.png')));
  316. }
  317. }
  318. }
  319. /**
  320. * Show stylesheets
  321. *
  322. * @return nothing
  323. */
  324. function showStylesheets()
  325. {
  326. if (Event::handle('StartShowStyles', array($this))) {
  327. // Use old name for StatusNet for compatibility on events
  328. if (Event::handle('StartShowStylesheets', array($this))) {
  329. $this->primaryCssLink(null, 'screen, projection, tv, print');
  330. Event::handle('EndShowStylesheets', array($this));
  331. }
  332. $this->cssLink('js/extlib/jquery-ui/css/smoothness/jquery-ui.css');
  333. if (Event::handle('StartShowUAStyles', array($this))) {
  334. Event::handle('EndShowUAStyles', array($this));
  335. }
  336. Event::handle('EndShowStyles', array($this));
  337. if (common_config('custom_css', 'enabled')) {
  338. $css = common_config('custom_css', 'css');
  339. if (Event::handle('StartShowCustomCss', array($this, &$css))) {
  340. if (trim($css) != '') {
  341. $this->style($css);
  342. }
  343. Event::handle('EndShowCustomCss', array($this));
  344. }
  345. }
  346. }
  347. }
  348. function primaryCssLink($mainTheme=null, $media=null)
  349. {
  350. $theme = new Theme($mainTheme);
  351. // Some themes may have external stylesheets, such as using the
  352. // Google Font APIs to load webfonts.
  353. foreach ($theme->getExternals() as $url) {
  354. $this->cssLink($url, $mainTheme, $media);
  355. }
  356. // If the currently-selected theme has dependencies on other themes,
  357. // we'll need to load their display.css files as well in order.
  358. $baseThemes = $theme->getDeps();
  359. foreach ($baseThemes as $baseTheme) {
  360. $this->cssLink('css/display.css', $baseTheme, $media);
  361. }
  362. $this->cssLink('css/display.css', $mainTheme, $media);
  363. // Additional styles for RTL languages
  364. if (is_rtl(common_language())) {
  365. if (file_exists(Theme::file('css/rtl.css'))) {
  366. $this->cssLink('css/rtl.css', $mainTheme, $media);
  367. }
  368. }
  369. }
  370. /**
  371. * Show javascript headers
  372. *
  373. * @return nothing
  374. */
  375. function showScripts()
  376. {
  377. if (Event::handle('StartShowScripts', array($this))) {
  378. if (Event::handle('StartShowJQueryScripts', array($this))) {
  379. $this->script('extlib/jquery.js');
  380. $this->script('extlib/jquery.form.js');
  381. $this->script('extlib/jquery-ui/jquery-ui.js');
  382. $this->script('extlib/jquery.cookie.js');
  383. Event::handle('EndShowJQueryScripts', array($this));
  384. }
  385. if (Event::handle('StartShowStatusNetScripts', array($this))) {
  386. $this->script('util.js');
  387. $this->script('xbImportNode.js');
  388. $this->script('geometa.js');
  389. // This route isn't available in single-user mode.
  390. // Not sure why, but it causes errors here.
  391. $this->inlineScript('var _peopletagAC = "' .
  392. common_local_url('peopletagautocomplete') . '";');
  393. $this->showScriptMessages();
  394. $this->showScriptVariables();
  395. // Anti-framing code to avoid clickjacking attacks in older browsers.
  396. // This will show a blank page if the page is being framed, which is
  397. // consistent with the behavior of the 'X-Frame-Options: SAMEORIGIN'
  398. // header, which prevents framing in newer browser.
  399. if (common_config('javascript', 'bustframes')) {
  400. $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 = ""; }; }');
  401. }
  402. Event::handle('EndShowStatusNetScripts', array($this));
  403. }
  404. Event::handle('EndShowScripts', array($this));
  405. }
  406. }
  407. /**
  408. * Exports a map of localized text strings to JavaScript code.
  409. *
  410. * Plugins can add to what's exported by hooking the StartScriptMessages or EndScriptMessages
  411. * events and appending to the array. Try to avoid adding strings that won't be used, as
  412. * they'll be added to HTML output.
  413. */
  414. function showScriptMessages()
  415. {
  416. $messages = array();
  417. if (Event::handle('StartScriptMessages', array($this, &$messages))) {
  418. // Common messages needed for timeline views etc...
  419. // TRANS: Localized tooltip for '...' expansion button on overlong remote messages.
  420. $messages['showmore_tooltip'] = _m('TOOLTIP', 'Show more');
  421. $messages['popup_close_button'] = _m('TOOLTIP', 'Close popup');
  422. $messages = array_merge($messages, $this->getScriptMessages());
  423. Event::handle('EndScriptMessages', array($this, &$messages));
  424. }
  425. if (!empty($messages)) {
  426. $this->inlineScript('SN.messages=' . json_encode($messages));
  427. }
  428. return $messages;
  429. }
  430. protected function showScriptVariables()
  431. {
  432. $vars = array();
  433. if (Event::handle('StartScriptVariables', array($this, &$vars))) {
  434. $vars['urlNewNotice'] = common_local_url('newnotice');
  435. }
  436. if (!empty($vars)) {
  437. $this->inlineScript('SN.V = ' . json_encode($vars));
  438. }
  439. return $vars;
  440. }
  441. /**
  442. * If the action will need localizable text strings, export them here like so:
  443. *
  444. * return array('pool_deepend' => _('Deep end'),
  445. * 'pool_shallow' => _('Shallow end'));
  446. *
  447. * The exported map will be available via SN.msg() to JS code:
  448. *
  449. * $('#pool').html('<div class="deepend"></div><div class="shallow"></div>');
  450. * $('#pool .deepend').text(SN.msg('pool_deepend'));
  451. * $('#pool .shallow').text(SN.msg('pool_shallow'));
  452. *
  453. * Exports a map of localized text strings to JavaScript code.
  454. *
  455. * Plugins can add to what's exported on any action by hooking the StartScriptMessages or
  456. * EndScriptMessages events and appending to the array. Try to avoid adding strings that won't
  457. * be used, as they'll be added to HTML output.
  458. */
  459. function getScriptMessages()
  460. {
  461. return array();
  462. }
  463. /**
  464. * Show OpenSearch headers
  465. *
  466. * @return nothing
  467. */
  468. function showOpenSearch()
  469. {
  470. $this->element('link', array('rel' => 'search',
  471. 'type' => 'application/opensearchdescription+xml',
  472. 'href' => common_local_url('opensearch', array('type' => 'people')),
  473. 'title' => common_config('site', 'name').' People Search'));
  474. $this->element('link', array('rel' => 'search', 'type' => 'application/opensearchdescription+xml',
  475. 'href' => common_local_url('opensearch', array('type' => 'notice')),
  476. 'title' => common_config('site', 'name').' Notice Search'));
  477. }
  478. /**
  479. * Show feed headers
  480. *
  481. * MAY overload
  482. *
  483. * @return nothing
  484. */
  485. function showFeeds()
  486. {
  487. foreach ($this->getFeeds() as $feed) {
  488. $this->element('link', array('rel' => $feed->rel(),
  489. 'href' => $feed->url,
  490. 'type' => $feed->mimeType(),
  491. 'title' => $feed->title));
  492. }
  493. }
  494. /**
  495. * Show description.
  496. *
  497. * SHOULD overload
  498. *
  499. * @return nothing
  500. */
  501. function showDescription()
  502. {
  503. // does nothing by default
  504. }
  505. /**
  506. * Show extra stuff in <head>.
  507. *
  508. * MAY overload
  509. *
  510. * @return nothing
  511. */
  512. function extraHead()
  513. {
  514. // does nothing by default
  515. }
  516. /**
  517. * Show body.
  518. *
  519. * Calls template methods
  520. *
  521. * @return nothing
  522. */
  523. function showBody()
  524. {
  525. $params = array('id' => $this->getActionName());
  526. if ($this->scoped instanceof Profile) {
  527. $params['class'] = 'user_in';
  528. }
  529. $this->elementStart('body', $params);
  530. $this->elementStart('div', array('id' => 'wrap'));
  531. if (Event::handle('StartShowHeader', array($this))) {
  532. $this->showHeader();
  533. $this->flush();
  534. Event::handle('EndShowHeader', array($this));
  535. }
  536. $this->showCore();
  537. $this->flush();
  538. if (Event::handle('StartShowFooter', array($this))) {
  539. $this->showFooter();
  540. $this->flush();
  541. Event::handle('EndShowFooter', array($this));
  542. }
  543. $this->elementEnd('div');
  544. $this->showScripts();
  545. $this->elementEnd('body');
  546. }
  547. /**
  548. * Show header of the page.
  549. *
  550. * Calls template methods
  551. *
  552. * @return nothing
  553. */
  554. function showHeader()
  555. {
  556. $this->elementStart('div', array('id' => 'header'));
  557. $this->showLogo();
  558. $this->showPrimaryNav();
  559. if (Event::handle('StartShowSiteNotice', array($this))) {
  560. $this->showSiteNotice();
  561. Event::handle('EndShowSiteNotice', array($this));
  562. }
  563. $this->elementEnd('div');
  564. }
  565. /**
  566. * Show configured logo.
  567. *
  568. * @return nothing
  569. */
  570. function showLogo()
  571. {
  572. $this->elementStart('address', array('id' => 'site_contact', 'class' => 'h-card'));
  573. if (Event::handle('StartAddressData', array($this))) {
  574. if (common_config('singleuser', 'enabled')) {
  575. $user = User::singleUser();
  576. $url = common_local_url('showstream',
  577. array('nickname' => $user->nickname));
  578. } else if (common_logged_in()) {
  579. $cur = common_current_user();
  580. $url = common_local_url('all', array('nickname' => $cur->nickname));
  581. } else {
  582. $url = common_local_url('public');
  583. }
  584. $this->elementStart('a', array('class' => 'home bookmark',
  585. 'href' => $url));
  586. if (GNUsocial::isHTTPS()) {
  587. $logoUrl = common_config('site', 'ssllogo');
  588. if (empty($logoUrl)) {
  589. // if logo is an uploaded file, try to fall back to HTTPS file URL
  590. $httpUrl = common_config('site', 'logo');
  591. if (!empty($httpUrl)) {
  592. $f = File::getKV('url', $httpUrl);
  593. if (!empty($f) && !empty($f->filename)) {
  594. // this will handle the HTTPS case
  595. $logoUrl = File::url($f->filename);
  596. }
  597. }
  598. }
  599. } else {
  600. $logoUrl = common_config('site', 'logo');
  601. }
  602. if (empty($logoUrl) && file_exists(Theme::file('logo.png'))) {
  603. // This should handle the HTTPS case internally
  604. $logoUrl = Theme::path('logo.png');
  605. }
  606. if (!empty($logoUrl)) {
  607. $this->element('img', array('class' => 'logo u-photo p-name',
  608. 'src' => $logoUrl,
  609. 'alt' => common_config('site', 'name')));
  610. }
  611. $this->elementEnd('a');
  612. Event::handle('EndAddressData', array($this));
  613. }
  614. $this->elementEnd('address');
  615. }
  616. /**
  617. * Show primary navigation.
  618. *
  619. * @return nothing
  620. */
  621. function showPrimaryNav()
  622. {
  623. $this->elementStart('div', array('id' => 'site_nav_global_primary'));
  624. $user = common_current_user();
  625. if (!empty($user) || !common_config('site', 'private')) {
  626. $form = new SearchForm($this);
  627. $form->show();
  628. }
  629. $pn = new PrimaryNav($this);
  630. $pn->show();
  631. $this->elementEnd('div');
  632. }
  633. /**
  634. * Show site notice.
  635. *
  636. * @return nothing
  637. */
  638. function showSiteNotice()
  639. {
  640. // Revist. Should probably do an hAtom pattern here
  641. $text = common_config('site', 'notice');
  642. if ($text) {
  643. $this->elementStart('div', array('id' => 'site_notice',
  644. 'class' => 'system_notice'));
  645. $this->raw($text);
  646. $this->elementEnd('div');
  647. }
  648. }
  649. /**
  650. * Show notice form.
  651. *
  652. * MAY overload if no notice form needed... or direct message box????
  653. *
  654. * @return nothing
  655. */
  656. function showNoticeForm()
  657. {
  658. // TRANS: Tab on the notice form.
  659. $tabs = array('status' => array('title' => _m('TAB','Status'),
  660. 'href' => common_local_url('newnotice')));
  661. $this->elementStart('div', 'input_forms');
  662. $this->element('label', array('for'=>'input_form_nav'), _m('TAB', 'Share your:'));
  663. if (Event::handle('StartShowEntryForms', array(&$tabs))) {
  664. $this->elementStart('ul', array('class' => 'nav',
  665. 'id' => 'input_form_nav'));
  666. foreach ($tabs as $tag => $data) {
  667. $tag = htmlspecialchars($tag);
  668. $attrs = array('id' => 'input_form_nav_'.$tag,
  669. 'class' => 'input_form_nav_tab');
  670. if ($tag == 'status') {
  671. $attrs['class'] .= ' current';
  672. }
  673. $this->elementStart('li', $attrs);
  674. $this->element('a',
  675. array('onclick' => 'return SN.U.switchInputFormTab("'.$tag.'");',
  676. 'href' => $data['href']),
  677. $data['title']);
  678. $this->elementEnd('li');
  679. }
  680. $this->elementEnd('ul');
  681. foreach ($tabs as $tag => $data) {
  682. $attrs = array('class' => 'input_form',
  683. 'id' => 'input_form_'.$tag);
  684. if ($tag == 'status') {
  685. $attrs['class'] .= ' current';
  686. }
  687. $this->elementStart('div', $attrs);
  688. $form = null;
  689. if (Event::handle('StartMakeEntryForm', array($tag, $this, &$form))) {
  690. if ($tag == 'status') {
  691. $options = $this->noticeFormOptions();
  692. $form = new NoticeForm($this, $options);
  693. }
  694. Event::handle('EndMakeEntryForm', array($tag, $this, $form));
  695. }
  696. if (!empty($form)) {
  697. $form->show();
  698. }
  699. $this->elementEnd('div');
  700. }
  701. }
  702. $this->elementEnd('div');
  703. }
  704. function noticeFormOptions()
  705. {
  706. return array();
  707. }
  708. /**
  709. * Show anonymous message.
  710. *
  711. * SHOULD overload
  712. *
  713. * @return nothing
  714. */
  715. function showAnonymousMessage()
  716. {
  717. // needs to be defined by the class
  718. }
  719. /**
  720. * Show core.
  721. *
  722. * Shows local navigation, content block and aside.
  723. *
  724. * @return nothing
  725. */
  726. function showCore()
  727. {
  728. $this->elementStart('div', array('id' => 'core'));
  729. $this->elementStart('div', array('id' => 'aside_primary_wrapper'));
  730. $this->elementStart('div', array('id' => 'content_wrapper'));
  731. $this->elementStart('div', array('id' => 'site_nav_local_views_wrapper'));
  732. if (Event::handle('StartShowLocalNavBlock', array($this))) {
  733. $this->showLocalNavBlock();
  734. $this->flush();
  735. Event::handle('EndShowLocalNavBlock', array($this));
  736. }
  737. if (Event::handle('StartShowContentBlock', array($this))) {
  738. $this->showContentBlock();
  739. $this->flush();
  740. Event::handle('EndShowContentBlock', array($this));
  741. }
  742. if (Event::handle('StartShowAside', array($this))) {
  743. $this->showAside();
  744. $this->flush();
  745. Event::handle('EndShowAside', array($this));
  746. }
  747. $this->elementEnd('div');
  748. $this->elementEnd('div');
  749. $this->elementEnd('div');
  750. $this->elementEnd('div');
  751. }
  752. /**
  753. * Show local navigation block.
  754. *
  755. * @return nothing
  756. */
  757. function showLocalNavBlock()
  758. {
  759. // Need to have this ID for CSS; I'm too lazy to add it to
  760. // all menus
  761. $this->elementStart('div', array('id' => 'site_nav_local_views'));
  762. // Cheat cheat cheat!
  763. $this->showLocalNav();
  764. $this->elementEnd('div');
  765. }
  766. /**
  767. * If there's a logged-in user, show a bit of login context
  768. *
  769. * @return nothing
  770. */
  771. function showProfileBlock()
  772. {
  773. if (common_logged_in()) {
  774. $block = new DefaultProfileBlock($this);
  775. $block->show();
  776. }
  777. }
  778. /**
  779. * Show local navigation.
  780. *
  781. * SHOULD overload
  782. *
  783. * @return nothing
  784. */
  785. function showLocalNav()
  786. {
  787. $nav = new DefaultLocalNav($this);
  788. $nav->show();
  789. }
  790. /**
  791. * Show menu for an object (group, profile)
  792. *
  793. * This block will only show if a subclass has overridden
  794. * the showObjectNav() method.
  795. *
  796. * @return nothing
  797. */
  798. function showObjectNavBlock()
  799. {
  800. $rmethod = new ReflectionMethod($this, 'showObjectNav');
  801. $dclass = $rmethod->getDeclaringClass()->getName();
  802. if ($dclass != 'Action') {
  803. // Need to have this ID for CSS; I'm too lazy to add it to
  804. // all menus
  805. $this->elementStart('div', array('id' => 'site_nav_object',
  806. 'class' => 'section'));
  807. $this->showObjectNav();
  808. $this->elementEnd('div');
  809. }
  810. }
  811. /**
  812. * Show object navigation.
  813. *
  814. * If there are things to do with this object, show it here.
  815. *
  816. * @return nothing
  817. */
  818. function showObjectNav()
  819. {
  820. /* Nothing here. */
  821. }
  822. /**
  823. * Show content block.
  824. *
  825. * @return nothing
  826. */
  827. function showContentBlock()
  828. {
  829. $this->elementStart('div', array('id' => 'content'));
  830. if (common_logged_in()) {
  831. if (Event::handle('StartShowNoticeForm', array($this))) {
  832. $this->showNoticeForm();
  833. Event::handle('EndShowNoticeForm', array($this));
  834. }
  835. }
  836. if (Event::handle('StartShowPageTitle', array($this))) {
  837. $this->showPageTitle();
  838. Event::handle('EndShowPageTitle', array($this));
  839. }
  840. $this->showPageNoticeBlock();
  841. $this->elementStart('div', array('id' => 'content_inner'));
  842. // show the actual content (forms, lists, whatever)
  843. $this->showContent();
  844. $this->elementEnd('div');
  845. $this->elementEnd('div');
  846. }
  847. /**
  848. * Show page title.
  849. *
  850. * @return nothing
  851. */
  852. function showPageTitle()
  853. {
  854. $this->element('h1', null, $this->title());
  855. }
  856. /**
  857. * Show page notice block.
  858. *
  859. * Only show the block if a subclassed action has overrided
  860. * Action::showPageNotice(), or an event handler is registered for
  861. * the StartShowPageNotice event, in which case we assume the
  862. * 'page_notice' definition list is desired. This is to prevent
  863. * empty 'page_notice' definition lists from being output everywhere.
  864. *
  865. * @return nothing
  866. */
  867. function showPageNoticeBlock()
  868. {
  869. $rmethod = new ReflectionMethod($this, 'showPageNotice');
  870. $dclass = $rmethod->getDeclaringClass()->getName();
  871. if ($dclass != 'Action' || Event::hasHandler('StartShowPageNotice')) {
  872. $this->elementStart('div', array('id' => 'page_notice',
  873. 'class' => 'system_notice'));
  874. if (Event::handle('StartShowPageNotice', array($this))) {
  875. $this->showPageNotice();
  876. Event::handle('EndShowPageNotice', array($this));
  877. }
  878. $this->elementEnd('div');
  879. }
  880. }
  881. /**
  882. * Show page notice.
  883. *
  884. * SHOULD overload (unless there's not a notice)
  885. *
  886. * @return nothing
  887. */
  888. function showPageNotice()
  889. {
  890. }
  891. /**
  892. * Show content.
  893. *
  894. * MUST overload (unless there's not a notice)
  895. *
  896. * @return nothing
  897. */
  898. protected function showContent()
  899. {
  900. }
  901. /**
  902. * Show Aside.
  903. *
  904. * @return nothing
  905. */
  906. function showAside()
  907. {
  908. $this->elementStart('div', array('id' => 'aside_primary',
  909. 'class' => 'aside'));
  910. $this->showProfileBlock();
  911. if (Event::handle('StartShowObjectNavBlock', array($this))) {
  912. $this->showObjectNavBlock();
  913. Event::handle('EndShowObjectNavBlock', array($this));
  914. }
  915. if (Event::handle('StartShowSections', array($this))) {
  916. $this->showSections();
  917. Event::handle('EndShowSections', array($this));
  918. }
  919. if (Event::handle('StartShowExportData', array($this))) {
  920. $this->showExportData();
  921. Event::handle('EndShowExportData', array($this));
  922. }
  923. $this->elementEnd('div');
  924. }
  925. /**
  926. * Show export data feeds.
  927. *
  928. * @return void
  929. */
  930. function showExportData()
  931. {
  932. $feeds = $this->getFeeds();
  933. if (!empty($feeds)) {
  934. $fl = new FeedList($this, $feeds);
  935. $fl->show();
  936. }
  937. }
  938. /**
  939. * Show sections.
  940. *
  941. * SHOULD overload
  942. *
  943. * @return nothing
  944. */
  945. function showSections()
  946. {
  947. // for each section, show it
  948. }
  949. /**
  950. * Show footer.
  951. *
  952. * @return nothing
  953. */
  954. function showFooter()
  955. {
  956. $this->elementStart('div', array('id' => 'footer'));
  957. if (Event::handle('StartShowInsideFooter', array($this))) {
  958. $this->showSecondaryNav();
  959. $this->showLicenses();
  960. Event::handle('EndShowInsideFooter', array($this));
  961. }
  962. $this->elementEnd('div');
  963. }
  964. /**
  965. * Show secondary navigation.
  966. *
  967. * @return nothing
  968. */
  969. function showSecondaryNav()
  970. {
  971. $sn = new SecondaryNav($this);
  972. $sn->show();
  973. }
  974. /**
  975. * Show licenses.
  976. *
  977. * @return nothing
  978. */
  979. function showLicenses()
  980. {
  981. $this->showGNUsocialLicense();
  982. $this->showContentLicense();
  983. }
  984. /**
  985. * Show GNU social license.
  986. *
  987. * @return nothing
  988. */
  989. function showGNUsocialLicense()
  990. {
  991. if (common_config('site', 'broughtby')) {
  992. // TRANS: First sentence of the GNU social site license. Used if 'broughtby' is set.
  993. // TRANS: Text between [] is a link description, text between () is the link itself.
  994. // TRANS: Make sure there is no whitespace between "]" and "(".
  995. // TRANS: "%%site.broughtby%%" is the value of the variable site.broughtby
  996. $instr = _('**%%site.name%%** is a social network, courtesy of [%%site.broughtby%%](%%site.broughtbyurl%%).');
  997. } else {
  998. // TRANS: First sentence of the GNU social site license. Used if 'broughtby' is not set.
  999. $instr = _('**%%site.name%%** is a social network.');
  1000. }
  1001. $instr .= ' ';
  1002. // TRANS: Second sentence of the GNU social site license. Mentions the GNU social source code license.
  1003. // TRANS: Make sure there is no whitespace between "]" and "(".
  1004. // TRANS: [%1$s](%2$s) is a link description followed by the link itself
  1005. // TRANS: %3$s is the version of GNU social that is being used.
  1006. $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);
  1007. $output = common_markup_to_html($instr);
  1008. $this->raw($output);
  1009. // do it
  1010. }
  1011. /**
  1012. * Show content license.
  1013. *
  1014. * @return nothing
  1015. */
  1016. function showContentLicense()
  1017. {
  1018. if (Event::handle('StartShowContentLicense', array($this))) {
  1019. switch (common_config('license', 'type')) {
  1020. case 'private':
  1021. // TRANS: Content license displayed when license is set to 'private'.
  1022. // TRANS: %1$s is the site name.
  1023. $this->element('p', null, sprintf(_('Content and data of %1$s are private and confidential.'),
  1024. common_config('site', 'name')));
  1025. // fall through
  1026. case 'allrightsreserved':
  1027. if (common_config('license', 'owner')) {
  1028. // TRANS: Content license displayed when license is set to 'allrightsreserved'.
  1029. // TRANS: %1$s is the copyright owner.
  1030. $this->element('p', null, sprintf(_('Content and data copyright by %1$s. All rights reserved.'),
  1031. common_config('license', 'owner')));
  1032. } else {
  1033. // TRANS: Content license displayed when license is set to 'allrightsreserved' and no owner is set.
  1034. $this->element('p', null, _('Content and data copyright by contributors. All rights reserved.'));
  1035. }
  1036. break;
  1037. case 'cc': // fall through
  1038. default:
  1039. $this->elementStart('p');
  1040. $image = common_config('license', 'image');
  1041. $sslimage = common_config('license', 'sslimage');
  1042. if (GNUsocial::isHTTPS()) {
  1043. if (!empty($sslimage)) {
  1044. $url = $sslimage;
  1045. } else if (preg_match('#^http://i.creativecommons.org/#', $image)) {
  1046. // CC support HTTPS on their images
  1047. $url = preg_replace('/^http/', 'https', $image, 1);
  1048. } else {
  1049. // Better to show mixed content than no content
  1050. $url = $image;
  1051. }
  1052. } else {
  1053. $url = $image;
  1054. }
  1055. $this->element('img', array('id' => 'license_cc',
  1056. 'src' => $url,
  1057. 'alt' => common_config('license', 'title'),
  1058. 'width' => '80',
  1059. 'height' => '15'));
  1060. $this->text(' ');
  1061. // TRANS: license message in footer.
  1062. // TRANS: %1$s is the site name, %2$s is a link to the license URL, with a licence name set in configuration.
  1063. $notice = _('All %1$s content and data are available under the %2$s license.');
  1064. $link = sprintf('<a class="license" rel="external license" href="%1$s">%2$s</a>',
  1065. htmlspecialchars(common_config('license', 'url')),
  1066. htmlspecialchars(common_config('license', 'title')));
  1067. $this->raw(@sprintf(htmlspecialchars($notice),
  1068. htmlspecialchars(common_config('site', 'name')),
  1069. $link));
  1070. $this->elementEnd('p');
  1071. break;
  1072. }
  1073. Event::handle('EndShowContentLicense', array($this));
  1074. }
  1075. }
  1076. /**
  1077. * Return last modified, if applicable.
  1078. *
  1079. * MAY override
  1080. *
  1081. * @return string last modified http header
  1082. */
  1083. function lastModified()
  1084. {
  1085. // For comparison with If-Last-Modified
  1086. // If not applicable, return null
  1087. return null;
  1088. }
  1089. /**
  1090. * Return etag, if applicable.
  1091. *
  1092. * MAY override
  1093. *
  1094. * @return string etag http header
  1095. */
  1096. function etag()
  1097. {
  1098. return null;
  1099. }
  1100. /**
  1101. * Return true if read only.
  1102. *
  1103. * MAY override
  1104. *
  1105. * @param array $args other arguments
  1106. *
  1107. * @return boolean is read only action?
  1108. */
  1109. function isReadOnly($args)
  1110. {
  1111. return false;
  1112. }
  1113. /**
  1114. * Returns query argument or default value if not found
  1115. *
  1116. * @param string $key requested argument
  1117. * @param string $def default value to return if $key is not provided
  1118. *
  1119. * @return boolean is read only action?
  1120. */
  1121. function arg($key, $def=null)
  1122. {
  1123. if (array_key_exists($key, $this->args)) {
  1124. return $this->args[$key];
  1125. } else {
  1126. return $def;
  1127. }
  1128. }
  1129. /**
  1130. * Returns trimmed query argument or default value if not found
  1131. *
  1132. * @param string $key requested argument
  1133. * @param string $def default value to return if $key is not provided
  1134. *
  1135. * @return boolean is read only action?
  1136. */
  1137. function trimmed($key, $def=null)
  1138. {
  1139. $arg = $this->arg($key, $def);
  1140. return is_string($arg) ? trim($arg) : $arg;
  1141. }
  1142. /**
  1143. * Handler method
  1144. *
  1145. * @return boolean is read only action?
  1146. */
  1147. protected function handle()
  1148. {
  1149. header('Vary: Accept-Encoding,Cookie');
  1150. $lm = $this->lastModified();
  1151. $etag = $this->etag();
  1152. if ($etag) {
  1153. header('ETag: ' . $etag);
  1154. }
  1155. if ($lm) {
  1156. header('Last-Modified: ' . date(DATE_RFC1123, $lm));
  1157. if ($this->isCacheable()) {
  1158. header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', 0 ) . ' GMT' );
  1159. header( "Cache-Control: private, must-revalidate, max-age=0" );
  1160. header( "Pragma:");
  1161. }
  1162. }
  1163. $checked = false;
  1164. if ($etag) {
  1165. $if_none_match = (array_key_exists('HTTP_IF_NONE_MATCH', $_SERVER)) ?
  1166. $_SERVER['HTTP_IF_NONE_MATCH'] : null;
  1167. if ($if_none_match) {
  1168. // If this check fails, ignore the if-modified-since below.
  1169. $checked = true;
  1170. if ($this->_hasEtag($etag, $if_none_match)) {
  1171. header('HTTP/1.1 304 Not Modified');
  1172. // Better way to do this?
  1173. exit(0);
  1174. }
  1175. }
  1176. }
  1177. if (!$checked && $lm && array_key_exists('HTTP_IF_MODIFIED_SINCE', $_SERVER)) {
  1178. $if_modified_since = $_SERVER['HTTP_IF_MODIFIED_SINCE'];
  1179. $ims = strtotime($if_modified_since);
  1180. if ($lm <= $ims) {
  1181. header('HTTP/1.1 304 Not Modified');
  1182. // Better way to do this?
  1183. exit(0);
  1184. }
  1185. }
  1186. }
  1187. /**
  1188. * Is this action cacheable?
  1189. *
  1190. * If the action returns a last-modified
  1191. *
  1192. * @param array $argarray is ignored since it's now passed in in prepare()
  1193. *
  1194. * @return boolean is read only action?
  1195. */
  1196. function isCacheable()
  1197. {
  1198. return true;
  1199. }
  1200. /**
  1201. * Has etag? (private)
  1202. *
  1203. * @param string $etag etag http header
  1204. * @param string $if_none_match ifNoneMatch http header
  1205. *
  1206. * @return boolean
  1207. */
  1208. function _hasEtag($etag, $if_none_match)
  1209. {
  1210. $etags = explode(',', $if_none_match);
  1211. return in_array($etag, $etags) || in_array('*', $etags);
  1212. }
  1213. /**
  1214. * Boolean understands english (yes, no, true, false)
  1215. *
  1216. * @param string $key query key we're interested in
  1217. * @param string $def default value
  1218. *
  1219. * @return boolean interprets yes/no strings as boolean
  1220. */
  1221. function boolean($key, $def=false)
  1222. {
  1223. $arg = strtolower($this->trimmed($key));
  1224. if (is_null($arg)) {
  1225. return $def;
  1226. } else if (in_array($arg, array('true', 'yes', '1', 'on'))) {
  1227. return true;
  1228. } else if (in_array($arg, array('false', 'no', '0'))) {
  1229. return false;
  1230. } else {
  1231. return $def;
  1232. }
  1233. }
  1234. /**
  1235. * This is a cheap hack to avoid a bug in DB_DataObject
  1236. * where '' is non-type-aware compared to 0, which means it
  1237. * will always be true for values like false and 0 too...
  1238. *
  1239. * Upstream bug is::
  1240. * https://pear.php.net/bugs/bug.php?id=20291
  1241. */
  1242. function booleanintstring($key, $def=false)
  1243. {
  1244. return $this->boolean($key, $def) ? '1' : '0';
  1245. }
  1246. /**
  1247. * Integer value of an argument
  1248. *
  1249. * @param string $key query key we're interested in
  1250. * @param string $defValue optional default value (default null)
  1251. * @param string $maxValue optional max value (default null)
  1252. * @param string $minValue optional min value (default null)
  1253. *
  1254. * @return integer integer value
  1255. */
  1256. function int($key, $defValue=null, $maxValue=null, $minValue=null)
  1257. {
  1258. $arg = intval($this->arg($key));
  1259. if (!is_numeric($this->arg($key)) || $arg != $this->arg($key)) {
  1260. return $defValue;
  1261. }
  1262. if (!is_null($maxValue)) {
  1263. $arg = min($arg, $maxValue);
  1264. }
  1265. if (!is_null($minValue)) {
  1266. $arg = max($arg, $minValue);
  1267. }
  1268. return $arg;
  1269. }
  1270. /**
  1271. * Server error
  1272. *
  1273. * @param string $msg error message to display
  1274. * @param integer $code http error code, 500 by default
  1275. *
  1276. * @return nothing
  1277. */
  1278. function serverError($msg, $code=500, $format=null)
  1279. {
  1280. if ($format === null) {
  1281. $format = $this->format;
  1282. }
  1283. common_debug("Server error '{$code}' on '{$this->action}': {$msg}", __FILE__);
  1284. if (!array_key_exists($code, ServerErrorAction::$status)) {
  1285. $code = 500;
  1286. }
  1287. $status_string = ServerErrorAction::$status[$code];
  1288. switch ($format) {
  1289. case 'xml':
  1290. header("HTTP/1.1 {$code} {$status_string}");
  1291. $this->initDocument('xml');
  1292. $this->elementStart('hash');
  1293. $this->element('error', null, $msg);
  1294. $this->element('request', null, $_SERVER['REQUEST_URI']);
  1295. $this->elementEnd('hash');
  1296. $this->endDocument('xml');
  1297. break;
  1298. case 'json':
  1299. if (!isset($this->callback)) {
  1300. header("HTTP/1.1 {$code} {$status_string}");
  1301. }
  1302. $this->initDocument('json');
  1303. $error_array = array('error' => $msg, 'request' => $_SERVER['REQUEST_URI']);
  1304. print(json_encode($error_array));
  1305. $this->endDocument('json');
  1306. break;
  1307. default:
  1308. common_log(LOG_ERR, 'Handled serverError ('._ve($code).') but cannot output into desired format ('._ve($this->format).'): '._ve($msg));
  1309. $action = new ServerErrorAction($msg, $code);
  1310. $action->execute();
  1311. }
  1312. exit((int)$code);
  1313. }
  1314. /**
  1315. * Client error
  1316. *
  1317. * @param string $msg error message to display
  1318. * @param integer $code http error code, 400 by default
  1319. * @param string $format error format (json, xml, text) for ApiAction
  1320. *
  1321. * @return nothing
  1322. * @throws ClientException always
  1323. */
  1324. function clientError($msg, $code=400, $format=null)
  1325. {
  1326. // $format is currently only relevant for an ApiAction anyway
  1327. if ($format === null) {
  1328. $format = $this->format;
  1329. }
  1330. common_debug("User error '{$code}' on '{$this->action}': {$msg}", __FILE__);
  1331. if (!array_key_exists($code, ClientErrorAction::$status)) {
  1332. $code = 400;
  1333. }
  1334. $status_string = ClientErrorAction::$status[$code];
  1335. switch ($format) {
  1336. case 'xml':
  1337. header("HTTP/1.1 {$code} {$status_string}");
  1338. $this->initDocument('xml');
  1339. $this->elementStart('hash');
  1340. $this->element('error', null, $msg);
  1341. $this->element('request', null, $_SERVER['REQUEST_URI']);
  1342. $this->elementEnd('hash');
  1343. $this->endDocument('xml');
  1344. break;
  1345. case 'json':
  1346. if (!isset($this->callback)) {
  1347. header("HTTP/1.1 {$code} {$status_string}");
  1348. }
  1349. $this->initDocument('json');
  1350. $error_array = array('error' => $msg, 'request' => $_SERVER['REQUEST_URI']);
  1351. print(json_encode($error_array));
  1352. $this->endDocument('json');
  1353. break;
  1354. case 'text':
  1355. header("HTTP/1.1 {$code} {$status_string}");
  1356. header('Content-Type: text/plain; charset=utf-8');
  1357. echo $msg;
  1358. break;
  1359. default:
  1360. common_log(LOG_ERR, 'Handled clientError ('._ve($code).') but cannot output into desired format ('._ve($this->format).'): '._ve($msg));
  1361. $action = new ClientErrorAction($msg, $code);
  1362. $action->execute();
  1363. }
  1364. exit((int)$code);
  1365. }
  1366. /**
  1367. * If not logged in, take appropriate action (redir or exception)
  1368. *
  1369. * @param boolean $redir Redirect to login if not logged in
  1370. *
  1371. * @return boolean true if logged in (never returns if not)
  1372. */
  1373. public function checkLogin($redir=true)
  1374. {
  1375. if (common_logged_in()) {
  1376. return true;
  1377. }
  1378. if ($redir==true) {
  1379. common_set_returnto($_SERVER['REQUEST_URI']);
  1380. common_redirect(common_local_url('login'));
  1381. }
  1382. // TRANS: Error message displayed when trying to perform an action that requires a logged in user.
  1383. $this->clientError(_('Not logged in.'), 403);
  1384. }
  1385. /**
  1386. * Returns the current URL
  1387. *
  1388. * @return string current URL
  1389. */
  1390. function selfUrl()
  1391. {
  1392. list($action, $args) = $this->returnToArgs();
  1393. return common_local_url($action, $args);
  1394. }
  1395. /**
  1396. * Returns arguments sufficient for re-constructing URL
  1397. *
  1398. * @return array two elements: action, other args
  1399. */
  1400. function returnToArgs()
  1401. {
  1402. $action = $this->getActionName();
  1403. $args = $this->args;
  1404. unset($args['action']);
  1405. if (common_config('site', 'fancy')) {
  1406. unset($args['p']);
  1407. }
  1408. if (array_key_exists('submit', $args)) {
  1409. unset($args['submit']);
  1410. }
  1411. foreach (array_keys($_COOKIE) as $cookie) {
  1412. unset($args[$cookie]);
  1413. }
  1414. return array($action, $args);
  1415. }
  1416. /**
  1417. * Generate a menu item
  1418. *
  1419. * @param string $url menu URL
  1420. * @param string $text menu name
  1421. * @param string $title title attribute, null by default
  1422. * @param boolean $is_selected current menu item, false by default
  1423. * @param string $id element id, null by default
  1424. *
  1425. * @return nothing
  1426. */
  1427. function menuItem($url, $text, $title=null, $is_selected=false, $id=null, $class=null)
  1428. {
  1429. // Added @id to li for some control.
  1430. // XXX: We might want to move this to htmloutputter.php
  1431. $lattrs = array();
  1432. $classes = array();
  1433. if ($class !== null) {
  1434. $classes[] = trim($class);
  1435. }
  1436. if ($is_selected) {
  1437. $classes[] = 'current';
  1438. }
  1439. if (!empty($classes)) {
  1440. $lattrs['class'] = implode(' ', $classes);
  1441. }
  1442. if (!is_null($id)) {
  1443. $lattrs['id'] = $id;
  1444. }
  1445. $this->elementStart('li', $lattrs);
  1446. $attrs['href'] = $url;
  1447. if ($title) {
  1448. $attrs['title'] = $title;
  1449. }
  1450. $this->element('a', $attrs, $text);
  1451. $this->elementEnd('li');
  1452. }
  1453. /**
  1454. * Generate pagination links
  1455. *
  1456. * @param boolean $have_before is there something before?
  1457. * @param boolean $have_after is there something after?
  1458. * @param integer $page current page
  1459. * @param string $action current action
  1460. * @param array $args rest of query arguments
  1461. *
  1462. * @return nothing
  1463. */
  1464. // XXX: The messages in this pagination method only tailor to navigating
  1465. // notices. In other lists, "Previous"/"Next" type navigation is
  1466. // desirable, but not available.
  1467. function pagination($have_before, $have_after, $page, $action, $args=null)
  1468. {
  1469. // Does a little before-after block for next/prev page
  1470. if ($have_before || $have_after) {
  1471. $this->elementStart('ul', array('class' => 'nav',
  1472. 'id' => 'pagination'));
  1473. }
  1474. if ($have_before) {
  1475. $pargs = array('page' => $page-1);
  1476. $this->elementStart('li', array('class' => 'nav_prev'));
  1477. $this->element('a', array('href' => common_local_url($action, $args, $pargs),
  1478. 'rel' => 'prev'),
  1479. // TRANS: Pagination message to go to a page displaying information more in the
  1480. // TRANS: present than the currently displayed information.
  1481. _('After'));
  1482. $this->elementEnd('li');
  1483. }
  1484. if ($have_after) {
  1485. $pargs = array('page' => $page+1);
  1486. $this->elementStart('li', array('class' => 'nav_next'));
  1487. $this->element('a', array('href' => common_local_url($action, $args, $pargs),
  1488. 'rel' => 'next'),
  1489. // TRANS: Pagination message to go to a page displaying information more in the
  1490. // TRANS: past than the currently displayed information.
  1491. _('Before'));
  1492. $this->elementEnd('li');
  1493. }
  1494. if ($have_before || $have_after) {
  1495. $this->elementEnd('ul');
  1496. }
  1497. }
  1498. /**
  1499. * An array of feeds for this action.
  1500. *
  1501. * Returns an array of potential feeds for this action.
  1502. *
  1503. * @return array Feed object to show in head and links
  1504. */
  1505. function getFeeds()
  1506. {
  1507. return array();
  1508. }
  1509. /**
  1510. * Check the session token.
  1511. *
  1512. * Checks that the current form has the correct session token,
  1513. * and throw an exception if it does not.
  1514. *
  1515. * @return void
  1516. */
  1517. // XXX: Finding this type of check with the same message about 50 times.
  1518. // Possible to refactor?
  1519. function checkSessionToken()
  1520. {
  1521. // CSRF protection
  1522. $token = $this->trimmed('token');
  1523. if (empty($token) || $token != common_session_token()) {
  1524. // TRANS: Client error text when there is a problem with the session token.
  1525. $this->clientError(_('There was a problem with your session token.'));
  1526. }
  1527. }
  1528. /**
  1529. * Check if the current request is a POST
  1530. *
  1531. * @return boolean true if POST; otherwise false.
  1532. */
  1533. function isPost()
  1534. {
  1535. return ($_SERVER['REQUEST_METHOD'] == 'POST');
  1536. }
  1537. }