action.php 54 KB

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