action.php 52 KB

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