action.php 55 KB

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