action.php 52 KB

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