action.php 53 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712
  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
  352. foreach ($theme->getExternals() as $url) {
  353. $this->cssLink($url, $mainTheme, $media);
  354. }
  355. // If the currently-selected theme has dependencies on other themes,
  356. // we'll need to load their display.css files as well in order.
  357. $baseThemes = $theme->getDeps();
  358. foreach ($baseThemes as $baseTheme) {
  359. $this->cssLink('css/display.css', $baseTheme, $media);
  360. }
  361. $this->cssLink('css/display.css', $mainTheme, $media);
  362. // Additional styles for RTL languages
  363. if (is_rtl(common_language())) {
  364. if (file_exists(Theme::file('css/rtl.css'))) {
  365. $this->cssLink('css/rtl.css', $mainTheme, $media);
  366. }
  367. }
  368. }
  369. /**
  370. * Show javascript headers
  371. *
  372. * @return nothing
  373. */
  374. function showScripts()
  375. {
  376. if (Event::handle('StartShowScripts', array($this))) {
  377. if (Event::handle('StartShowJQueryScripts', array($this))) {
  378. $this->script('extlib/jquery.js');
  379. $this->script('extlib/jquery.form.js');
  380. $this->script('extlib/jquery-ui/jquery-ui.js');
  381. $this->script('extlib/jquery.cookie.js');
  382. Event::handle('EndShowJQueryScripts', array($this));
  383. }
  384. if (Event::handle('StartShowStatusNetScripts', array($this))) {
  385. $this->script('util.js');
  386. $this->script('xbImportNode.js');
  387. // This route isn't available in single-user mode.
  388. // Not sure why, but it causes errors here.
  389. $this->inlineScript('var _peopletagAC = "' .
  390. common_local_url('peopletagautocomplete') . '";');
  391. $this->showScriptMessages();
  392. $this->showScriptVariables();
  393. // Anti-framing code to avoid clickjacking attacks in older browsers.
  394. // This will show a blank page if the page is being framed, which is
  395. // consistent with the behavior of the 'X-Frame-Options: SAMEORIGIN'
  396. // header, which prevents framing in newer browser.
  397. if (common_config('javascript', 'bustframes')) {
  398. $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 = ""; }; }');
  399. }
  400. Event::handle('EndShowStatusNetScripts', array($this));
  401. }
  402. Event::handle('EndShowScripts', array($this));
  403. }
  404. }
  405. /**
  406. * Exports a map of localized text strings to JavaScript code.
  407. *
  408. * Plugins can add to what's exported by hooking the StartScriptMessages or EndScriptMessages
  409. * events and appending to the array. Try to avoid adding strings that won't be used, as
  410. * they'll be added to HTML output.
  411. */
  412. function showScriptMessages()
  413. {
  414. $messages = array();
  415. if (Event::handle('StartScriptMessages', array($this, &$messages))) {
  416. // Common messages needed for timeline views etc...
  417. // TRANS: Localized tooltip for '...' expansion button on overlong remote messages.
  418. $messages['showmore_tooltip'] = _m('TOOLTIP', 'Show more');
  419. $messages['popup_close_button'] = _m('TOOLTIP', 'Close popup');
  420. $messages = array_merge($messages, $this->getScriptMessages());
  421. Event::handle('EndScriptMessages', array($this, &$messages));
  422. }
  423. if (!empty($messages)) {
  424. $this->inlineScript('SN.messages=' . json_encode($messages));
  425. }
  426. return $messages;
  427. }
  428. protected function showScriptVariables()
  429. {
  430. $vars = array();
  431. if (Event::handle('StartScriptVariables', array($this, &$vars))) {
  432. $vars['urlNewNotice'] = common_local_url('newnotice');
  433. $vars['xhrTimeout'] = ini_get('max_execution_time')*1000; // milliseconds
  434. Event::handle('EndScriptVariables', array($this, &$vars));
  435. }
  436. $this->inlineScript('SN.V = ' . json_encode($vars) . ';');
  437. return $vars;
  438. }
  439. /**
  440. * If the action will need localizable text strings, export them here like so:
  441. *
  442. * return array('pool_deepend' => _('Deep end'),
  443. * 'pool_shallow' => _('Shallow end'));
  444. *
  445. * The exported map will be available via SN.msg() to JS code:
  446. *
  447. * $('#pool').html('<div class="deepend"></div><div class="shallow"></div>');
  448. * $('#pool .deepend').text(SN.msg('pool_deepend'));
  449. * $('#pool .shallow').text(SN.msg('pool_shallow'));
  450. *
  451. * Exports a map of localized text strings to JavaScript code.
  452. *
  453. * Plugins can add to what's exported on any action by hooking the StartScriptMessages or
  454. * EndScriptMessages events and appending to the array. Try to avoid adding strings that won't
  455. * be used, as they'll be added to HTML output.
  456. */
  457. function getScriptMessages()
  458. {
  459. return array();
  460. }
  461. /**
  462. * Show OpenSearch headers
  463. *
  464. * @return nothing
  465. */
  466. function showOpenSearch()
  467. {
  468. $this->element('link', array('rel' => 'search',
  469. 'type' => 'application/opensearchdescription+xml',
  470. 'href' => common_local_url('opensearch', array('type' => 'people')),
  471. 'title' => common_config('site', 'name').' People Search'));
  472. $this->element('link', array('rel' => 'search', 'type' => 'application/opensearchdescription+xml',
  473. 'href' => common_local_url('opensearch', array('type' => 'notice')),
  474. 'title' => common_config('site', 'name').' Notice Search'));
  475. }
  476. /**
  477. * Show feed headers
  478. *
  479. * MAY overload
  480. *
  481. * @return nothing
  482. */
  483. function showFeeds()
  484. {
  485. foreach ($this->getFeeds() as $feed) {
  486. $this->element('link', array('rel' => $feed->rel(),
  487. 'href' => $feed->url,
  488. 'type' => $feed->mimeType(),
  489. 'title' => $feed->title));
  490. }
  491. }
  492. /**
  493. * Show description.
  494. *
  495. * SHOULD overload
  496. *
  497. * @return nothing
  498. */
  499. function showDescription()
  500. {
  501. // does nothing by default
  502. }
  503. /**
  504. * Show extra stuff in <head>.
  505. *
  506. * MAY overload
  507. *
  508. * @return nothing
  509. */
  510. function extraHead()
  511. {
  512. // does nothing by default
  513. }
  514. /**
  515. * Show body.
  516. *
  517. * Calls template methods
  518. *
  519. * @return nothing
  520. */
  521. function showBody()
  522. {
  523. $params = array('id' => $this->getActionName());
  524. if ($this->scoped instanceof Profile) {
  525. $params['class'] = 'user_in';
  526. }
  527. $this->elementStart('body', $params);
  528. $this->elementStart('div', array('id' => 'wrap'));
  529. if (Event::handle('StartShowHeader', array($this))) {
  530. $this->showHeader();
  531. $this->flush();
  532. Event::handle('EndShowHeader', array($this));
  533. }
  534. $this->showCore();
  535. $this->flush();
  536. if (Event::handle('StartShowFooter', array($this))) {
  537. $this->showFooter();
  538. $this->flush();
  539. Event::handle('EndShowFooter', array($this));
  540. }
  541. $this->elementEnd('div');
  542. $this->showScripts();
  543. $this->elementEnd('body');
  544. }
  545. /**
  546. * Show header of the page.
  547. *
  548. * Calls template methods
  549. *
  550. * @return nothing
  551. */
  552. function showHeader()
  553. {
  554. $this->elementStart('div', array('id' => 'header'));
  555. $this->showLogo();
  556. $this->showPrimaryNav();
  557. if (Event::handle('StartShowSiteNotice', array($this))) {
  558. $this->showSiteNotice();
  559. Event::handle('EndShowSiteNotice', array($this));
  560. }
  561. $this->elementEnd('div');
  562. }
  563. /**
  564. * Show configured logo.
  565. *
  566. * @return nothing
  567. */
  568. function showLogo()
  569. {
  570. $this->elementStart('address', array('id' => 'site_contact', 'class' => 'h-card'));
  571. if (Event::handle('StartAddressData', array($this))) {
  572. if (common_config('singleuser', 'enabled')) {
  573. $user = User::singleUser();
  574. $url = common_local_url('showstream',
  575. array('nickname' => $user->nickname));
  576. } else if (common_logged_in()) {
  577. $cur = common_current_user();
  578. $url = common_local_url('all', array('nickname' => $cur->nickname));
  579. } else {
  580. $url = common_local_url('public');
  581. }
  582. $this->elementStart('a', array('class' => 'home bookmark',
  583. 'href' => $url));
  584. if (GNUsocial::isHTTPS()) {
  585. $logoUrl = common_config('site', 'ssllogo');
  586. if (empty($logoUrl)) {
  587. // if logo is an uploaded file, try to fall back to HTTPS file URL
  588. $httpUrl = common_config('site', 'logo');
  589. if (!empty($httpUrl)) {
  590. try {
  591. $f = File::getByUrl($httpUrl);
  592. if (!empty($f->filename)) {
  593. // this will handle the HTTPS case
  594. $logoUrl = File::url($f->filename);
  595. }
  596. } catch (NoResultException $e) {
  597. // no match
  598. }
  599. }
  600. }
  601. } else {
  602. $logoUrl = common_config('site', 'logo');
  603. }
  604. if (empty($logoUrl) && file_exists(Theme::file('logo.png'))) {
  605. // This should handle the HTTPS case internally
  606. $logoUrl = Theme::path('logo.png');
  607. }
  608. if (!empty($logoUrl)) {
  609. $this->element('img', array('class' => 'logo u-photo p-name',
  610. 'src' => $logoUrl,
  611. 'alt' => common_config('site', 'name')));
  612. }
  613. $this->elementEnd('a');
  614. Event::handle('EndAddressData', array($this));
  615. }
  616. $this->elementEnd('address');
  617. }
  618. /**
  619. * Show primary navigation.
  620. *
  621. * @return nothing
  622. */
  623. function showPrimaryNav()
  624. {
  625. $this->elementStart('div', array('id' => 'site_nav_global_primary'));
  626. $user = common_current_user();
  627. if (!empty($user) || !common_config('site', 'private')) {
  628. $form = new SearchForm($this);
  629. $form->show();
  630. }
  631. $pn = new PrimaryNav($this);
  632. $pn->show();
  633. $this->elementEnd('div');
  634. }
  635. /**
  636. * Show site notice.
  637. *
  638. * @return nothing
  639. */
  640. function showSiteNotice()
  641. {
  642. // Revist. Should probably do an hAtom pattern here
  643. $text = common_config('site', 'notice');
  644. if ($text) {
  645. $this->elementStart('div', array('id' => 'site_notice',
  646. 'class' => 'system_notice'));
  647. $this->raw($text);
  648. $this->elementEnd('div');
  649. }
  650. }
  651. /**
  652. * Show notice form.
  653. *
  654. * MAY overload if no notice form needed... or direct message box????
  655. *
  656. * @return nothing
  657. */
  658. function showNoticeForm()
  659. {
  660. // TRANS: Tab on the notice form.
  661. $tabs = array('status' => array('title' => _m('TAB','Status'),
  662. 'href' => common_local_url('newnotice')));
  663. $this->elementStart('div', 'input_forms');
  664. $this->element('label', array('for'=>'input_form_nav'), _m('TAB', 'Share your:'));
  665. if (Event::handle('StartShowEntryForms', array(&$tabs))) {
  666. $this->elementStart('ul', array('class' => 'nav',
  667. 'id' => 'input_form_nav'));
  668. foreach ($tabs as $tag => $data) {
  669. $tag = htmlspecialchars($tag);
  670. $attrs = array('id' => 'input_form_nav_'.$tag,
  671. 'class' => 'input_form_nav_tab');
  672. if ($tag == 'status') {
  673. $attrs['class'] .= ' current';
  674. }
  675. $this->elementStart('li', $attrs);
  676. $this->element('a',
  677. array('onclick' => 'return SN.U.switchInputFormTab("'.$tag.'");',
  678. 'href' => $data['href']),
  679. $data['title']);
  680. $this->elementEnd('li');
  681. }
  682. $this->elementEnd('ul');
  683. foreach ($tabs as $tag => $data) {
  684. $attrs = array('class' => 'input_form',
  685. 'id' => 'input_form_'.$tag);
  686. if ($tag == 'status') {
  687. $attrs['class'] .= ' current';
  688. }
  689. $this->elementStart('div', $attrs);
  690. $form = null;
  691. if (Event::handle('StartMakeEntryForm', array($tag, $this, &$form))) {
  692. if ($tag == 'status') {
  693. $options = $this->noticeFormOptions();
  694. $form = new NoticeForm($this, $options);
  695. }
  696. Event::handle('EndMakeEntryForm', array($tag, $this, $form));
  697. }
  698. if (!empty($form)) {
  699. $form->show();
  700. }
  701. $this->elementEnd('div');
  702. }
  703. }
  704. $this->elementEnd('div');
  705. }
  706. function noticeFormOptions()
  707. {
  708. return array();
  709. }
  710. /**
  711. * Show anonymous message.
  712. *
  713. * SHOULD overload
  714. *
  715. * @return nothing
  716. */
  717. function showAnonymousMessage()
  718. {
  719. // needs to be defined by the class
  720. }
  721. /**
  722. * Show core.
  723. *
  724. * Shows local navigation, content block and aside.
  725. *
  726. * @return nothing
  727. */
  728. function showCore()
  729. {
  730. $this->elementStart('div', array('id' => 'core'));
  731. $this->elementStart('div', array('id' => 'aside_primary_wrapper'));
  732. $this->elementStart('div', array('id' => 'content_wrapper'));
  733. $this->elementStart('div', array('id' => 'site_nav_local_views_wrapper'));
  734. if (Event::handle('StartShowLocalNavBlock', array($this))) {
  735. $this->showLocalNavBlock();
  736. $this->flush();
  737. Event::handle('EndShowLocalNavBlock', array($this));
  738. }
  739. if (Event::handle('StartShowContentBlock', array($this))) {
  740. $this->showContentBlock();
  741. $this->flush();
  742. Event::handle('EndShowContentBlock', array($this));
  743. }
  744. if (Event::handle('StartShowAside', array($this))) {
  745. $this->showAside();
  746. $this->flush();
  747. Event::handle('EndShowAside', array($this));
  748. }
  749. $this->elementEnd('div');
  750. $this->elementEnd('div');
  751. $this->elementEnd('div');
  752. $this->elementEnd('div');
  753. }
  754. /**
  755. * Show local navigation block.
  756. *
  757. * @return nothing
  758. */
  759. function showLocalNavBlock()
  760. {
  761. // Need to have this ID for CSS; I'm too lazy to add it to
  762. // all menus
  763. $this->elementStart('div', array('id' => 'site_nav_local_views'));
  764. // Cheat cheat cheat!
  765. $this->showLocalNav();
  766. $this->elementEnd('div');
  767. }
  768. /**
  769. * If there's a logged-in user, show a bit of login context
  770. *
  771. * @return nothing
  772. */
  773. function showProfileBlock()
  774. {
  775. if (common_logged_in()) {
  776. $block = new DefaultProfileBlock($this);
  777. $block->show();
  778. }
  779. }
  780. /**
  781. * Show local navigation.
  782. *
  783. * SHOULD overload
  784. *
  785. * @return nothing
  786. */
  787. function showLocalNav()
  788. {
  789. $nav = new DefaultLocalNav($this);
  790. $nav->show();
  791. }
  792. /**
  793. * Show menu for an object (group, profile)
  794. *
  795. * This block will only show if a subclass has overridden
  796. * the showObjectNav() method.
  797. *
  798. * @return nothing
  799. */
  800. function showObjectNavBlock()
  801. {
  802. $rmethod = new ReflectionMethod($this, 'showObjectNav');
  803. $dclass = $rmethod->getDeclaringClass()->getName();
  804. if ($dclass != 'Action') {
  805. // Need to have this ID for CSS; I'm too lazy to add it to
  806. // all menus
  807. $this->elementStart('div', array('id' => 'site_nav_object',
  808. 'class' => 'section'));
  809. $this->showObjectNav();
  810. $this->elementEnd('div');
  811. }
  812. }
  813. /**
  814. * Show object navigation.
  815. *
  816. * If there are things to do with this object, show it here.
  817. *
  818. * @return nothing
  819. */
  820. function showObjectNav()
  821. {
  822. /* Nothing here. */
  823. }
  824. /**
  825. * Show content block.
  826. *
  827. * @return nothing
  828. */
  829. function showContentBlock()
  830. {
  831. $this->elementStart('div', array('id' => 'content'));
  832. if (common_logged_in()) {
  833. if (Event::handle('StartShowNoticeForm', array($this))) {
  834. $this->showNoticeForm();
  835. Event::handle('EndShowNoticeForm', array($this));
  836. }
  837. }
  838. if (Event::handle('StartShowPageTitle', array($this))) {
  839. $this->showPageTitle();
  840. Event::handle('EndShowPageTitle', array($this));
  841. }
  842. $this->showPageNoticeBlock();
  843. $this->elementStart('div', array('id' => 'content_inner'));
  844. // show the actual content (forms, lists, whatever)
  845. $this->showContent();
  846. $this->elementEnd('div');
  847. $this->elementEnd('div');
  848. }
  849. /**
  850. * Show page title.
  851. *
  852. * @return nothing
  853. */
  854. function showPageTitle()
  855. {
  856. $this->element('h1', null, $this->title());
  857. }
  858. /**
  859. * Show page notice block.
  860. *
  861. * Only show the block if a subclassed action has overrided
  862. * Action::showPageNotice(), or an event handler is registered for
  863. * the StartShowPageNotice event, in which case we assume the
  864. * 'page_notice' definition list is desired. This is to prevent
  865. * empty 'page_notice' definition lists from being output everywhere.
  866. *
  867. * @return nothing
  868. */
  869. function showPageNoticeBlock()
  870. {
  871. $rmethod = new ReflectionMethod($this, 'showPageNotice');
  872. $dclass = $rmethod->getDeclaringClass()->getName();
  873. if ($dclass != 'Action' || Event::hasHandler('StartShowPageNotice')) {
  874. $this->elementStart('div', array('id' => 'page_notice',
  875. 'class' => 'system_notice'));
  876. if (Event::handle('StartShowPageNotice', array($this))) {
  877. $this->showPageNotice();
  878. Event::handle('EndShowPageNotice', array($this));
  879. }
  880. $this->elementEnd('div');
  881. }
  882. }
  883. /**
  884. * Show page notice.
  885. *
  886. * SHOULD overload (unless there's not a notice)
  887. *
  888. * @return nothing
  889. */
  890. function showPageNotice()
  891. {
  892. }
  893. /**
  894. * Show content.
  895. *
  896. * MUST overload (unless there's not a notice)
  897. *
  898. * @return nothing
  899. */
  900. protected function showContent()
  901. {
  902. }
  903. /**
  904. * Show Aside.
  905. *
  906. * @return nothing
  907. */
  908. function showAside()
  909. {
  910. $this->elementStart('div', array('id' => 'aside_primary',
  911. 'class' => 'aside'));
  912. $this->showProfileBlock();
  913. if (Event::handle('StartShowObjectNavBlock', array($this))) {
  914. $this->showObjectNavBlock();
  915. Event::handle('EndShowObjectNavBlock', array($this));
  916. }
  917. if (Event::handle('StartShowSections', array($this))) {
  918. $this->showSections();
  919. Event::handle('EndShowSections', array($this));
  920. }
  921. if (Event::handle('StartShowExportData', array($this))) {
  922. $this->showExportData();
  923. Event::handle('EndShowExportData', array($this));
  924. }
  925. $this->elementEnd('div');
  926. }
  927. /**
  928. * Show export data feeds.
  929. *
  930. * @return void
  931. */
  932. function showExportData()
  933. {
  934. $feeds = $this->getFeeds();
  935. if (!empty($feeds)) {
  936. $fl = new FeedList($this, $feeds);
  937. $fl->show();
  938. }
  939. }
  940. /**
  941. * Show sections.
  942. *
  943. * SHOULD overload
  944. *
  945. * @return nothing
  946. */
  947. function showSections()
  948. {
  949. // for each section, show it
  950. }
  951. /**
  952. * Show footer.
  953. *
  954. * @return nothing
  955. */
  956. function showFooter()
  957. {
  958. $this->elementStart('div', array('id' => 'footer'));
  959. if (Event::handle('StartShowInsideFooter', array($this))) {
  960. $this->showSecondaryNav();
  961. $this->showLicenses();
  962. Event::handle('EndShowInsideFooter', array($this));
  963. }
  964. $this->elementEnd('div');
  965. }
  966. /**
  967. * Show secondary navigation.
  968. *
  969. * @return nothing
  970. */
  971. function showSecondaryNav()
  972. {
  973. $sn = new SecondaryNav($this);
  974. $sn->show();
  975. }
  976. /**
  977. * Show licenses.
  978. *
  979. * @return nothing
  980. */
  981. function showLicenses()
  982. {
  983. $this->showGNUsocialLicense();
  984. $this->showContentLicense();
  985. }
  986. /**
  987. * Show GNU social license.
  988. *
  989. * @return nothing
  990. */
  991. function showGNUsocialLicense()
  992. {
  993. if (common_config('site', 'broughtby')) {
  994. // TRANS: First sentence of the GNU social site license. Used if 'broughtby' is set.
  995. // TRANS: Text between [] is a link description, text between () is the link itself.
  996. // TRANS: Make sure there is no whitespace between "]" and "(".
  997. // TRANS: "%%site.broughtby%%" is the value of the variable site.broughtby
  998. $instr = _('**%%site.name%%** is a social network, courtesy of [%%site.broughtby%%](%%site.broughtbyurl%%).');
  999. } else {
  1000. // TRANS: First sentence of the GNU social site license. Used if 'broughtby' is not set.
  1001. $instr = _('**%%site.name%%** is a social network.');
  1002. }
  1003. $instr .= ' ';
  1004. // TRANS: Second sentence of the GNU social site license. Mentions the GNU social source code license.
  1005. // TRANS: Make sure there is no whitespace between "]" and "(".
  1006. // TRANS: [%1$s](%2$s) is a link description followed by the link itself
  1007. // TRANS: %3$s is the version of GNU social that is being used.
  1008. $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);
  1009. $output = common_markup_to_html($instr);
  1010. $this->raw($output);
  1011. // do it
  1012. }
  1013. /**
  1014. * Show content license.
  1015. *
  1016. * @return nothing
  1017. */
  1018. function showContentLicense()
  1019. {
  1020. if (Event::handle('StartShowContentLicense', array($this))) {
  1021. switch (common_config('license', 'type')) {
  1022. case 'private':
  1023. // TRANS: Content license displayed when license is set to 'private'.
  1024. // TRANS: %1$s is the site name.
  1025. $this->element('p', null, sprintf(_('Content and data of %1$s are private and confidential.'),
  1026. common_config('site', 'name')));
  1027. // fall through
  1028. case 'allrightsreserved':
  1029. if (common_config('license', 'owner')) {
  1030. // TRANS: Content license displayed when license is set to 'allrightsreserved'.
  1031. // TRANS: %1$s is the copyright owner.
  1032. $this->element('p', null, sprintf(_('Content and data copyright by %1$s. All rights reserved.'),
  1033. common_config('license', 'owner')));
  1034. } else {
  1035. // TRANS: Content license displayed when license is set to 'allrightsreserved' and no owner is set.
  1036. $this->element('p', null, _('Content and data copyright by contributors. All rights reserved.'));
  1037. }
  1038. break;
  1039. case 'cc': // fall through
  1040. default:
  1041. $this->elementStart('p');
  1042. $image = common_config('license', 'image');
  1043. $sslimage = common_config('license', 'sslimage');
  1044. if (GNUsocial::isHTTPS()) {
  1045. if (!empty($sslimage)) {
  1046. $url = $sslimage;
  1047. } else if (preg_match('#^http://i.creativecommons.org/#', $image)) {
  1048. // CC support HTTPS on their images
  1049. $url = preg_replace('/^http/', 'https', $image, 1);
  1050. } else {
  1051. // Better to show mixed content than no content
  1052. $url = $image;
  1053. }
  1054. } else {
  1055. $url = $image;
  1056. }
  1057. $this->element('img', array('id' => 'license_cc',
  1058. 'src' => $url,
  1059. 'alt' => common_config('license', 'title'),
  1060. 'width' => '80',
  1061. 'height' => '15'));
  1062. $this->text(' ');
  1063. // TRANS: license message in footer.
  1064. // TRANS: %1$s is the site name, %2$s is a link to the license URL, with a licence name set in configuration.
  1065. $notice = _('All %1$s content and data are available under the %2$s license.');
  1066. $link = sprintf('<a class="license" rel="external license" href="%1$s">%2$s</a>',
  1067. htmlspecialchars(common_config('license', 'url')),
  1068. htmlspecialchars(common_config('license', 'title')));
  1069. $this->raw(@sprintf(htmlspecialchars($notice),
  1070. htmlspecialchars(common_config('site', 'name')),
  1071. $link));
  1072. $this->elementEnd('p');
  1073. break;
  1074. }
  1075. Event::handle('EndShowContentLicense', array($this));
  1076. }
  1077. }
  1078. /**
  1079. * Return last modified, if applicable.
  1080. *
  1081. * MAY override
  1082. *
  1083. * @return string last modified http header
  1084. */
  1085. function lastModified()
  1086. {
  1087. // For comparison with If-Last-Modified
  1088. // If not applicable, return null
  1089. return null;
  1090. }
  1091. /**
  1092. * Return etag, if applicable.
  1093. *
  1094. * MAY override
  1095. *
  1096. * @return string etag http header
  1097. */
  1098. function etag()
  1099. {
  1100. return null;
  1101. }
  1102. /**
  1103. * Return true if read only.
  1104. *
  1105. * MAY override
  1106. *
  1107. * @param array $args other arguments
  1108. *
  1109. * @return boolean is read only action?
  1110. */
  1111. function isReadOnly($args)
  1112. {
  1113. return false;
  1114. }
  1115. /**
  1116. * Returns query argument or default value if not found
  1117. *
  1118. * @param string $key requested argument
  1119. * @param string $def default value to return if $key is not provided
  1120. *
  1121. * @return boolean is read only action?
  1122. */
  1123. function arg($key, $def=null)
  1124. {
  1125. if (array_key_exists($key, $this->args)) {
  1126. return $this->args[$key];
  1127. } else {
  1128. return $def;
  1129. }
  1130. }
  1131. /**
  1132. * Returns trimmed query argument or default value if not found
  1133. *
  1134. * @param string $key requested argument
  1135. * @param string $def default value to return if $key is not provided
  1136. *
  1137. * @return boolean is read only action?
  1138. */
  1139. function trimmed($key, $def=null)
  1140. {
  1141. $arg = $this->arg($key, $def);
  1142. return is_string($arg) ? trim($arg) : $arg;
  1143. }
  1144. /**
  1145. * Handler method
  1146. *
  1147. * @return boolean is read only action?
  1148. */
  1149. protected function handle()
  1150. {
  1151. header('Vary: Accept-Encoding,Cookie');
  1152. $lm = $this->lastModified();
  1153. $etag = $this->etag();
  1154. if ($etag) {
  1155. header('ETag: ' . $etag);
  1156. }
  1157. if ($lm) {
  1158. header('Last-Modified: ' . date(DATE_RFC1123, $lm));
  1159. if ($this->isCacheable()) {
  1160. header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', 0 ) . ' GMT' );
  1161. header( "Cache-Control: private, must-revalidate, max-age=0" );
  1162. header( "Pragma:");
  1163. }
  1164. }
  1165. $checked = false;
  1166. if ($etag) {
  1167. $if_none_match = (array_key_exists('HTTP_IF_NONE_MATCH', $_SERVER)) ?
  1168. $_SERVER['HTTP_IF_NONE_MATCH'] : null;
  1169. if ($if_none_match) {
  1170. // If this check fails, ignore the if-modified-since below.
  1171. $checked = true;
  1172. if ($this->_hasEtag($etag, $if_none_match)) {
  1173. header('HTTP/1.1 304 Not Modified');
  1174. // Better way to do this?
  1175. exit(0);
  1176. }
  1177. }
  1178. }
  1179. if (!$checked && $lm && array_key_exists('HTTP_IF_MODIFIED_SINCE', $_SERVER)) {
  1180. $if_modified_since = $_SERVER['HTTP_IF_MODIFIED_SINCE'];
  1181. $ims = strtotime($if_modified_since);
  1182. if ($lm <= $ims) {
  1183. header('HTTP/1.1 304 Not Modified');
  1184. // Better way to do this?
  1185. exit(0);
  1186. }
  1187. }
  1188. }
  1189. /**
  1190. * Is this action cacheable?
  1191. *
  1192. * If the action returns a last-modified
  1193. *
  1194. * @param array $argarray is ignored since it's now passed in in prepare()
  1195. *
  1196. * @return boolean is read only action?
  1197. */
  1198. function isCacheable()
  1199. {
  1200. return true;
  1201. }
  1202. /**
  1203. * Has etag? (private)
  1204. *
  1205. * @param string $etag etag http header
  1206. * @param string $if_none_match ifNoneMatch http header
  1207. *
  1208. * @return boolean
  1209. */
  1210. function _hasEtag($etag, $if_none_match)
  1211. {
  1212. $etags = explode(',', $if_none_match);
  1213. return in_array($etag, $etags) || in_array('*', $etags);
  1214. }
  1215. /**
  1216. * Boolean understands english (yes, no, true, false)
  1217. *
  1218. * @param string $key query key we're interested in
  1219. * @param string $def default value
  1220. *
  1221. * @return boolean interprets yes/no strings as boolean
  1222. */
  1223. function boolean($key, $def=false)
  1224. {
  1225. $arg = strtolower($this->trimmed($key));
  1226. if (is_null($arg)) {
  1227. return $def;
  1228. } else if (in_array($arg, array('true', 'yes', '1', 'on'))) {
  1229. return true;
  1230. } else if (in_array($arg, array('false', 'no', '0'))) {
  1231. return false;
  1232. } else {
  1233. return $def;
  1234. }
  1235. }
  1236. /**
  1237. * This is a cheap hack to avoid a bug in DB_DataObject
  1238. * where '' is non-type-aware compared to 0, which means it
  1239. * will always be true for values like false and 0 too...
  1240. *
  1241. * Upstream bug is::
  1242. * https://pear.php.net/bugs/bug.php?id=20291
  1243. */
  1244. function booleanintstring($key, $def=false)
  1245. {
  1246. return $this->boolean($key, $def) ? '1' : '0';
  1247. }
  1248. /**
  1249. * Integer value of an argument
  1250. *
  1251. * @param string $key query key we're interested in
  1252. * @param string $defValue optional default value (default null)
  1253. * @param string $maxValue optional max value (default null)
  1254. * @param string $minValue optional min value (default null)
  1255. *
  1256. * @return integer integer value
  1257. */
  1258. function int($key, $defValue=null, $maxValue=null, $minValue=null)
  1259. {
  1260. $arg = intval($this->arg($key));
  1261. if (!is_numeric($this->arg($key)) || $arg != $this->arg($key)) {
  1262. return $defValue;
  1263. }
  1264. if (!is_null($maxValue)) {
  1265. $arg = min($arg, $maxValue);
  1266. }
  1267. if (!is_null($minValue)) {
  1268. $arg = max($arg, $minValue);
  1269. }
  1270. return $arg;
  1271. }
  1272. /**
  1273. * Server error
  1274. *
  1275. * @param string $msg error message to display
  1276. * @param integer $code http error code, 500 by default
  1277. *
  1278. * @return nothing
  1279. */
  1280. function serverError($msg, $code=500, $format=null)
  1281. {
  1282. if ($format === null) {
  1283. $format = $this->format;
  1284. }
  1285. common_debug("Server error '{$code}' on '{$this->action}': {$msg}", __FILE__);
  1286. if (!array_key_exists($code, ServerErrorAction::$status)) {
  1287. $code = 500;
  1288. }
  1289. $status_string = ServerErrorAction::$status[$code];
  1290. switch ($format) {
  1291. case 'xml':
  1292. header("HTTP/1.1 {$code} {$status_string}");
  1293. $this->initDocument('xml');
  1294. $this->elementStart('hash');
  1295. $this->element('error', null, $msg);
  1296. $this->element('request', null, $_SERVER['REQUEST_URI']);
  1297. $this->elementEnd('hash');
  1298. $this->endDocument('xml');
  1299. break;
  1300. case 'json':
  1301. if (!isset($this->callback)) {
  1302. header("HTTP/1.1 {$code} {$status_string}");
  1303. }
  1304. $this->initDocument('json');
  1305. $error_array = array('error' => $msg, 'request' => $_SERVER['REQUEST_URI']);
  1306. print(json_encode($error_array));
  1307. $this->endDocument('json');
  1308. break;
  1309. default:
  1310. common_log(LOG_ERR, 'Handled serverError ('._ve($code).') but cannot output into desired format ('._ve($this->format).'): '._ve($msg));
  1311. $action = new ServerErrorAction($msg, $code);
  1312. $action->execute();
  1313. }
  1314. exit((int)$code);
  1315. }
  1316. /**
  1317. * Client error
  1318. *
  1319. * @param string $msg error message to display
  1320. * @param integer $code http error code, 400 by default
  1321. * @param string $format error format (json, xml, text) for ApiAction
  1322. *
  1323. * @return nothing
  1324. * @throws ClientException always
  1325. */
  1326. function clientError($msg, $code=400, $format=null)
  1327. {
  1328. // $format is currently only relevant for an ApiAction anyway
  1329. if ($format === null) {
  1330. $format = $this->format;
  1331. }
  1332. common_debug("User error '{$code}' on '{$this->action}': {$msg}", __FILE__);
  1333. if (!array_key_exists($code, ClientErrorAction::$status)) {
  1334. $code = 400;
  1335. }
  1336. $status_string = ClientErrorAction::$status[$code];
  1337. switch ($format) {
  1338. case 'xml':
  1339. header("HTTP/1.1 {$code} {$status_string}");
  1340. $this->initDocument('xml');
  1341. $this->elementStart('hash');
  1342. $this->element('error', null, $msg);
  1343. $this->element('request', null, $_SERVER['REQUEST_URI']);
  1344. $this->elementEnd('hash');
  1345. $this->endDocument('xml');
  1346. break;
  1347. case 'json':
  1348. if (!isset($this->callback)) {
  1349. header("HTTP/1.1 {$code} {$status_string}");
  1350. }
  1351. $this->initDocument('json');
  1352. $error_array = array('error' => $msg, 'request' => $_SERVER['REQUEST_URI']);
  1353. print(json_encode($error_array));
  1354. $this->endDocument('json');
  1355. break;
  1356. case 'text':
  1357. header("HTTP/1.1 {$code} {$status_string}");
  1358. header('Content-Type: text/plain; charset=utf-8');
  1359. echo $msg;
  1360. break;
  1361. default:
  1362. common_log(LOG_ERR, 'Handled clientError ('._ve($code).') but cannot output into desired format ('._ve($this->format).'): '._ve($msg));
  1363. $action = new ClientErrorAction($msg, $code);
  1364. $action->execute();
  1365. }
  1366. exit((int)$code);
  1367. }
  1368. /**
  1369. * If not logged in, take appropriate action (redir or exception)
  1370. *
  1371. * @param boolean $redir Redirect to login if not logged in
  1372. *
  1373. * @return boolean true if logged in (never returns if not)
  1374. */
  1375. public function checkLogin($redir=true)
  1376. {
  1377. if (common_logged_in()) {
  1378. return true;
  1379. }
  1380. if ($redir==true) {
  1381. common_set_returnto($_SERVER['REQUEST_URI']);
  1382. common_redirect(common_local_url('login'));
  1383. }
  1384. // TRANS: Error message displayed when trying to perform an action that requires a logged in user.
  1385. $this->clientError(_('Not logged in.'), 403);
  1386. }
  1387. /**
  1388. * Returns the current URL
  1389. *
  1390. * @return string current URL
  1391. */
  1392. function selfUrl()
  1393. {
  1394. list($action, $args) = $this->returnToArgs();
  1395. return common_local_url($action, $args);
  1396. }
  1397. /**
  1398. * Returns arguments sufficient for re-constructing URL
  1399. *
  1400. * @return array two elements: action, other args
  1401. */
  1402. function returnToArgs()
  1403. {
  1404. $action = $this->getActionName();
  1405. $args = $this->args;
  1406. unset($args['action']);
  1407. if (common_config('site', 'fancy')) {
  1408. unset($args['p']);
  1409. }
  1410. if (array_key_exists('submit', $args)) {
  1411. unset($args['submit']);
  1412. }
  1413. foreach (array_keys($_COOKIE) as $cookie) {
  1414. unset($args[$cookie]);
  1415. }
  1416. return array($action, $args);
  1417. }
  1418. /**
  1419. * Generate a menu item
  1420. *
  1421. * @param string $url menu URL
  1422. * @param string $text menu name
  1423. * @param string $title title attribute, null by default
  1424. * @param boolean $is_selected current menu item, false by default
  1425. * @param string $id element id, null by default
  1426. *
  1427. * @return nothing
  1428. */
  1429. function menuItem($url, $text, $title=null, $is_selected=false, $id=null, $class=null)
  1430. {
  1431. // Added @id to li for some control.
  1432. // XXX: We might want to move this to htmloutputter.php
  1433. $lattrs = array();
  1434. $classes = array();
  1435. if ($class !== null) {
  1436. $classes[] = trim($class);
  1437. }
  1438. if ($is_selected) {
  1439. $classes[] = 'current';
  1440. }
  1441. if (!empty($classes)) {
  1442. $lattrs['class'] = implode(' ', $classes);
  1443. }
  1444. if (!is_null($id)) {
  1445. $lattrs['id'] = $id;
  1446. }
  1447. $this->elementStart('li', $lattrs);
  1448. $attrs['href'] = $url;
  1449. if ($title) {
  1450. $attrs['title'] = $title;
  1451. }
  1452. $this->element('a', $attrs, $text);
  1453. $this->elementEnd('li');
  1454. }
  1455. /**
  1456. * Generate pagination links
  1457. *
  1458. * @param boolean $have_before is there something before?
  1459. * @param boolean $have_after is there something after?
  1460. * @param integer $page current page
  1461. * @param string $action current action
  1462. * @param array $args rest of query arguments
  1463. *
  1464. * @return nothing
  1465. */
  1466. // XXX: The messages in this pagination method only tailor to navigating
  1467. // notices. In other lists, "Previous"/"Next" type navigation is
  1468. // desirable, but not available.
  1469. function pagination($have_before, $have_after, $page, $action, $args=null)
  1470. {
  1471. // Does a little before-after block for next/prev page
  1472. if ($have_before || $have_after) {
  1473. $this->elementStart('ul', array('class' => 'nav',
  1474. 'id' => 'pagination'));
  1475. }
  1476. if ($have_before) {
  1477. $pargs = array('page' => $page-1);
  1478. $this->elementStart('li', array('class' => 'nav_prev'));
  1479. $this->element('a', array('href' => common_local_url($action, $args, $pargs),
  1480. 'rel' => 'prev'),
  1481. // TRANS: Pagination message to go to a page displaying information more in the
  1482. // TRANS: present than the currently displayed information.
  1483. _('After'));
  1484. $this->elementEnd('li');
  1485. }
  1486. if ($have_after) {
  1487. $pargs = array('page' => $page+1);
  1488. $this->elementStart('li', array('class' => 'nav_next'));
  1489. $this->element('a', array('href' => common_local_url($action, $args, $pargs),
  1490. 'rel' => 'next'),
  1491. // TRANS: Pagination message to go to a page displaying information more in the
  1492. // TRANS: past than the currently displayed information.
  1493. _('Before'));
  1494. $this->elementEnd('li');
  1495. }
  1496. if ($have_before || $have_after) {
  1497. $this->elementEnd('ul');
  1498. }
  1499. }
  1500. /**
  1501. * An array of feeds for this action.
  1502. *
  1503. * Returns an array of potential feeds for this action.
  1504. *
  1505. * @return array Feed object to show in head and links
  1506. */
  1507. function getFeeds()
  1508. {
  1509. return array();
  1510. }
  1511. /**
  1512. * Check the session token.
  1513. *
  1514. * Checks that the current form has the correct session token,
  1515. * and throw an exception if it does not.
  1516. *
  1517. * @return void
  1518. */
  1519. // XXX: Finding this type of check with the same message about 50 times.
  1520. // Possible to refactor?
  1521. function checkSessionToken()
  1522. {
  1523. // CSRF protection
  1524. $token = $this->trimmed('token');
  1525. if (empty($token) || $token != common_session_token()) {
  1526. // TRANS: Client error text when there is a problem with the session token.
  1527. $this->clientError(_('There was a problem with your session token.'));
  1528. }
  1529. }
  1530. /**
  1531. * Check if the current request is a POST
  1532. *
  1533. * @return boolean true if POST; otherwise false.
  1534. */
  1535. function isPost()
  1536. {
  1537. return ($_SERVER['REQUEST_METHOD'] == 'POST');
  1538. }
  1539. }