OC_Template.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352
  1. <?php
  2. /**
  3. * @copyright Copyright (c) 2016, ownCloud, Inc.
  4. *
  5. * @author Bart Visscher <bartv@thisnet.nl>
  6. * @author Brice Maron <brice@bmaron.net>
  7. * @author Christoph Wurst <christoph@winzerhof-wurst.at>
  8. * @author Frank Karlitschek <frank@karlitschek.de>
  9. * @author Individual IT Services <info@individual-it.net>
  10. * @author Jakob Sack <mail@jakobsack.de>
  11. * @author Jan-Christoph Borchardt <hey@jancborchardt.net>
  12. * @author Joas Schilling <coding@schilljs.com>
  13. * @author John Molakvoæ <skjnldsv@protonmail.com>
  14. * @author Jörn Friedrich Dreyer <jfd@butonic.de>
  15. * @author Julius Härtl <jus@bitgrid.net>
  16. * @author Lukas Reschke <lukas@statuscode.ch>
  17. * @author Marin Treselj <marin@pixelipo.com>
  18. * @author Michael Letzgus <www@chronos.michael-letzgus.de>
  19. * @author Morris Jobke <hey@morrisjobke.de>
  20. * @author Robin Appelman <robin@icewind.nl>
  21. * @author Roeland Jago Douma <roeland@famdouma.nl>
  22. * @author Thomas Müller <thomas.mueller@tmit.eu>
  23. * @author Vincent Petry <vincent@nextcloud.com>
  24. * @author Richard Steinmetz <richard@steinmetz.cloud>
  25. *
  26. * @license AGPL-3.0
  27. *
  28. * This code is free software: you can redistribute it and/or modify
  29. * it under the terms of the GNU Affero General Public License, version 3,
  30. * as published by the Free Software Foundation.
  31. *
  32. * This program is distributed in the hope that it will be useful,
  33. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  34. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  35. * GNU Affero General Public License for more details.
  36. *
  37. * You should have received a copy of the GNU Affero General Public License, version 3,
  38. * along with this program. If not, see <http://www.gnu.org/licenses/>
  39. *
  40. */
  41. use OC\TemplateLayout;
  42. use OCP\AppFramework\Http\Events\BeforeTemplateRenderedEvent;
  43. use OCP\AppFramework\Http\TemplateResponse;
  44. use OCP\EventDispatcher\IEventDispatcher;
  45. require_once __DIR__.'/template/functions.php';
  46. /**
  47. * This class provides the templates for ownCloud.
  48. */
  49. class OC_Template extends \OC\Template\Base {
  50. /** @var string */
  51. private $renderAs; // Create a full page?
  52. /** @var string */
  53. private $path; // The path to the template
  54. /** @var array */
  55. private $headers = []; //custom headers
  56. /** @var string */
  57. protected $app; // app id
  58. /**
  59. * Constructor
  60. *
  61. * @param string $app app providing the template
  62. * @param string $name of the template file (without suffix)
  63. * @param string $renderAs If $renderAs is set, OC_Template will try to
  64. * produce a full page in the according layout. For
  65. * now, $renderAs can be set to "guest", "user" or
  66. * "admin".
  67. * @param bool $registerCall = true
  68. */
  69. public function __construct($app, $name, $renderAs = TemplateResponse::RENDER_AS_BLANK, $registerCall = true) {
  70. $theme = OC_Util::getTheme();
  71. $requestToken = (OC::$server->getSession() && $registerCall) ? \OCP\Util::callRegister() : '';
  72. $parts = explode('/', $app); // fix translation when app is something like core/lostpassword
  73. $l10n = \OC::$server->getL10N($parts[0]);
  74. /** @var \OCP\Defaults $themeDefaults */
  75. $themeDefaults = \OCP\Server::get(\OCP\Defaults::class);
  76. [$path, $template] = $this->findTemplate($theme, $app, $name);
  77. // Set the private data
  78. $this->renderAs = $renderAs;
  79. $this->path = $path;
  80. $this->app = $app;
  81. parent::__construct($template, $requestToken, $l10n, $themeDefaults);
  82. }
  83. /**
  84. * find the template with the given name
  85. * @param string $name of the template file (without suffix)
  86. *
  87. * Will select the template file for the selected theme.
  88. * Checking all the possible locations.
  89. * @param string $theme
  90. * @param string $app
  91. * @return string[]
  92. */
  93. protected function findTemplate($theme, $app, $name) {
  94. // Check if it is a app template or not.
  95. if ($app !== '') {
  96. $dirs = $this->getAppTemplateDirs($theme, $app, OC::$SERVERROOT, OC_App::getAppPath($app));
  97. } else {
  98. $dirs = $this->getCoreTemplateDirs($theme, OC::$SERVERROOT);
  99. }
  100. $locator = new \OC\Template\TemplateFileLocator($dirs);
  101. $template = $locator->find($name);
  102. $path = $locator->getPath();
  103. return [$path, $template];
  104. }
  105. /**
  106. * Add a custom element to the header
  107. * @param string $tag tag name of the element
  108. * @param array $attributes array of attributes for the element
  109. * @param string $text the text content for the element. If $text is null then the
  110. * element will be written as empty element. So use "" to get a closing tag.
  111. */
  112. public function addHeader($tag, $attributes, $text = null) {
  113. $this->headers[] = [
  114. 'tag' => $tag,
  115. 'attributes' => $attributes,
  116. 'text' => $text
  117. ];
  118. }
  119. /**
  120. * Process the template
  121. * @return string
  122. *
  123. * This function process the template. If $this->renderAs is set, it
  124. * will produce a full page.
  125. */
  126. public function fetchPage($additionalParams = null) {
  127. $data = parent::fetchPage($additionalParams);
  128. if ($this->renderAs) {
  129. $page = new TemplateLayout($this->renderAs, $this->app);
  130. if (is_array($additionalParams)) {
  131. foreach ($additionalParams as $key => $value) {
  132. $page->assign($key, $value);
  133. }
  134. }
  135. // Add custom headers
  136. $headers = '';
  137. foreach (OC_Util::$headers as $header) {
  138. $headers .= '<'.\OCP\Util::sanitizeHTML($header['tag']);
  139. if (strcasecmp($header['tag'], 'script') === 0 && in_array('src', array_map('strtolower', array_keys($header['attributes'])))) {
  140. $headers .= ' defer';
  141. }
  142. foreach ($header['attributes'] as $name => $value) {
  143. $headers .= ' '.\OCP\Util::sanitizeHTML($name).'="'.\OCP\Util::sanitizeHTML($value).'"';
  144. }
  145. if ($header['text'] !== null) {
  146. $headers .= '>'.\OCP\Util::sanitizeHTML($header['text']).'</'.\OCP\Util::sanitizeHTML($header['tag']).'>';
  147. } else {
  148. $headers .= '/>';
  149. }
  150. }
  151. $page->assign('headers', $headers);
  152. $page->assign('content', $data);
  153. return $page->fetchPage($additionalParams);
  154. }
  155. return $data;
  156. }
  157. /**
  158. * Include template
  159. *
  160. * @param string $file
  161. * @param array|null $additionalParams
  162. * @return string returns content of included template
  163. *
  164. * Includes another template. use <?php echo $this->inc('template'); ?> to
  165. * do this.
  166. */
  167. public function inc($file, $additionalParams = null) {
  168. return $this->load($this->path.$file.'.php', $additionalParams);
  169. }
  170. /**
  171. * Shortcut to print a simple page for users
  172. * @param string $application The application we render the template for
  173. * @param string $name Name of the template
  174. * @param array $parameters Parameters for the template
  175. * @return boolean|null
  176. */
  177. public static function printUserPage($application, $name, $parameters = []) {
  178. $content = new OC_Template($application, $name, "user");
  179. foreach ($parameters as $key => $value) {
  180. $content->assign($key, $value);
  181. }
  182. print $content->printPage();
  183. }
  184. /**
  185. * Shortcut to print a simple page for admins
  186. * @param string $application The application we render the template for
  187. * @param string $name Name of the template
  188. * @param array $parameters Parameters for the template
  189. * @return bool
  190. */
  191. public static function printAdminPage($application, $name, $parameters = []) {
  192. $content = new OC_Template($application, $name, "admin");
  193. foreach ($parameters as $key => $value) {
  194. $content->assign($key, $value);
  195. }
  196. return $content->printPage();
  197. }
  198. /**
  199. * Shortcut to print a simple page for guests
  200. * @param string $application The application we render the template for
  201. * @param string $name Name of the template
  202. * @param array|string $parameters Parameters for the template
  203. * @return bool
  204. */
  205. public static function printGuestPage($application, $name, $parameters = []) {
  206. $content = new OC_Template($application, $name, $name === 'error' ? $name : 'guest');
  207. foreach ($parameters as $key => $value) {
  208. $content->assign($key, $value);
  209. }
  210. return $content->printPage();
  211. }
  212. /**
  213. * Print a fatal error page and terminates the script
  214. * @param string $error_msg The error message to show
  215. * @param string $hint An optional hint message - needs to be properly escape
  216. * @param int $statusCode
  217. * @suppress PhanAccessMethodInternal
  218. */
  219. public static function printErrorPage($error_msg, $hint = '', $statusCode = 500) {
  220. if (\OC::$server->getAppManager()->isEnabledForUser('theming') && !\OC_App::isAppLoaded('theming')) {
  221. \OC_App::loadApp('theming');
  222. }
  223. if ($error_msg === $hint) {
  224. // If the hint is the same as the message there is no need to display it twice.
  225. $hint = '';
  226. }
  227. $errors = [['error' => $error_msg, 'hint' => $hint]];
  228. http_response_code($statusCode);
  229. try {
  230. // Try rendering themed html error page
  231. $response = new TemplateResponse(
  232. '',
  233. 'error',
  234. ['errors' => $errors],
  235. TemplateResponse::RENDER_AS_ERROR,
  236. $statusCode,
  237. );
  238. $event = new BeforeTemplateRenderedEvent(false, $response);
  239. \OC::$server->get(IEventDispatcher::class)->dispatchTyped($event);
  240. print($response->render());
  241. } catch (\Throwable $e1) {
  242. $logger = \OC::$server->getLogger();
  243. $logger->logException($e1, [
  244. 'app' => 'core',
  245. 'message' => 'Rendering themed error page failed. Falling back to unthemed error page.'
  246. ]);
  247. try {
  248. // Try rendering unthemed html error page
  249. $content = new \OC_Template('', 'error', 'error', false);
  250. $content->assign('errors', $errors);
  251. $content->printPage();
  252. } catch (\Exception $e2) {
  253. // If nothing else works, fall back to plain text error page
  254. $logger->error("$error_msg $hint", ['app' => 'core']);
  255. $logger->logException($e2, [
  256. 'app' => 'core',
  257. 'message' => 'Rendering unthemed error page failed. Falling back to plain text error page.'
  258. ]);
  259. header('Content-Type: text/plain; charset=utf-8');
  260. print("$error_msg $hint");
  261. }
  262. }
  263. die();
  264. }
  265. /**
  266. * print error page using Exception details
  267. * @param Exception|Throwable $exception
  268. * @param int $statusCode
  269. * @return bool|string
  270. * @suppress PhanAccessMethodInternal
  271. */
  272. public static function printExceptionErrorPage($exception, $statusCode = 503) {
  273. $debug = false;
  274. http_response_code($statusCode);
  275. try {
  276. $debug = \OC::$server->getSystemConfig()->getValue('debug', false);
  277. $request = \OC::$server->getRequest();
  278. $content = new \OC_Template('', 'exception', 'error', false);
  279. $content->assign('errorClass', get_class($exception));
  280. $content->assign('errorMsg', $exception->getMessage());
  281. $content->assign('errorCode', $exception->getCode());
  282. $content->assign('file', $exception->getFile());
  283. $content->assign('line', $exception->getLine());
  284. $content->assign('exception', $exception);
  285. $content->assign('debugMode', $debug);
  286. $content->assign('remoteAddr', $request->getRemoteAddress());
  287. $content->assign('requestID', $request->getId());
  288. $content->printPage();
  289. } catch (\Exception $e) {
  290. try {
  291. $logger = \OC::$server->getLogger();
  292. $logger->logException($exception, ['app' => 'core']);
  293. $logger->logException($e, ['app' => 'core']);
  294. } catch (Throwable $e) {
  295. // no way to log it properly - but to avoid a white page of death we send some output
  296. self::printPlainErrorPage($e, $debug);
  297. // and then throw it again to log it at least to the web server error log
  298. throw $e;
  299. }
  300. self::printPlainErrorPage($e, $debug);
  301. }
  302. die();
  303. }
  304. private static function printPlainErrorPage(\Throwable $exception, bool $debug = false) {
  305. header('Content-Type: text/plain; charset=utf-8');
  306. print("Internal Server Error\n\n");
  307. print("The server encountered an internal error and was unable to complete your request.\n");
  308. print("Please contact the server administrator if this error reappears multiple times, please include the technical details below in your report.\n");
  309. print("More details can be found in the server log.\n");
  310. if ($debug) {
  311. print("\n");
  312. print($exception->getMessage() . ' ' . $exception->getFile() . ' at ' . $exception->getLine() . "\n");
  313. print($exception->getTraceAsString());
  314. }
  315. }
  316. }