action.php 55 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856
  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. $count = $this->trimmed('count');
  1630. if ($count) {
  1631. $pargs['count'] = $count;
  1632. }
  1633. // Does a little before-after block for next/prev page
  1634. if ($have_before || $have_after) {
  1635. $this->elementStart('ul', ['class' => 'nav',
  1636. 'id' => 'pagination',]);
  1637. }
  1638. if ($have_before) {
  1639. $pargs['page'] = $page - 1;
  1640. $this->elementStart('li', ['class' => 'nav_prev']);
  1641. $this->element(
  1642. 'a',
  1643. ['href' => common_local_url($action, $args, $pargs),
  1644. 'rel' => 'prev',],
  1645. // TRANS: Pagination message to go to a page displaying information more in the
  1646. // TRANS: present than the currently displayed information.
  1647. _('After')
  1648. );
  1649. $this->elementEnd('li');
  1650. }
  1651. if ($have_after) {
  1652. $pargs['page'] = $page + 1;
  1653. $this->elementStart('li', ['class' => 'nav_next']);
  1654. $this->element(
  1655. 'a',
  1656. ['href' => common_local_url($action, $args, $pargs),
  1657. 'rel' => 'next',],
  1658. // TRANS: Pagination message to go to a page displaying information more in the
  1659. // TRANS: past than the currently displayed information.
  1660. _('Before')
  1661. );
  1662. $this->elementEnd('li');
  1663. }
  1664. if ($have_before || $have_after) {
  1665. $this->elementEnd('ul');
  1666. }
  1667. }
  1668. /**
  1669. * Check the session token.
  1670. *
  1671. * Checks that the current form has the correct session token,
  1672. * and throw an exception if it does not.
  1673. *
  1674. * @return void
  1675. * @throws ServerException
  1676. * @throws ClientException
  1677. */
  1678. public function checkSessionToken(): void
  1679. {
  1680. // CSRF protection
  1681. $token = $this->trimmed('token');
  1682. if (empty($token) || $token != common_session_token()) {
  1683. // TRANS: Client error text when there is a problem with the session token.
  1684. $this->clientError(_m('There was a problem with your session token.'));
  1685. }
  1686. }
  1687. }