action.php 55 KB

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