OC_Template.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328
  1. <?php
  2. /**
  3. * SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors
  4. * SPDX-FileCopyrightText: 2016 ownCloud, Inc.
  5. * SPDX-License-Identifier: AGPL-3.0-only
  6. */
  7. use OC\TemplateLayout;
  8. use OCP\AppFramework\Http\Events\BeforeTemplateRenderedEvent;
  9. use OCP\AppFramework\Http\TemplateResponse;
  10. use OCP\EventDispatcher\IEventDispatcher;
  11. require_once __DIR__.'/template/functions.php';
  12. /**
  13. * This class provides the templates for ownCloud.
  14. */
  15. class OC_Template extends \OC\Template\Base {
  16. /** @var string */
  17. private $renderAs; // Create a full page?
  18. /** @var string */
  19. private $path; // The path to the template
  20. /** @var array */
  21. private $headers = []; //custom headers
  22. /** @var string */
  23. protected $app; // app id
  24. /**
  25. * Constructor
  26. *
  27. * @param string $app app providing the template
  28. * @param string $name of the template file (without suffix)
  29. * @param string $renderAs If $renderAs is set, OC_Template will try to
  30. * produce a full page in the according layout. For
  31. * now, $renderAs can be set to "guest", "user" or
  32. * "admin".
  33. * @param bool $registerCall = true
  34. */
  35. public function __construct($app, $name, $renderAs = TemplateResponse::RENDER_AS_BLANK, $registerCall = true) {
  36. $theme = OC_Util::getTheme();
  37. $requestToken = (OC::$server->getSession() && $registerCall) ? \OCP\Util::callRegister() : '';
  38. $cspNonce = \OCP\Server::get(\OC\Security\CSP\ContentSecurityPolicyNonceManager::class)->getNonce();
  39. $parts = explode('/', $app); // fix translation when app is something like core/lostpassword
  40. $l10n = \OC::$server->getL10N($parts[0]);
  41. /** @var \OCP\Defaults $themeDefaults */
  42. $themeDefaults = \OCP\Server::get(\OCP\Defaults::class);
  43. [$path, $template] = $this->findTemplate($theme, $app, $name);
  44. // Set the private data
  45. $this->renderAs = $renderAs;
  46. $this->path = $path;
  47. $this->app = $app;
  48. parent::__construct(
  49. $template,
  50. $requestToken,
  51. $l10n,
  52. $themeDefaults,
  53. $cspNonce,
  54. );
  55. }
  56. /**
  57. * find the template with the given name
  58. * @param string $name of the template file (without suffix)
  59. *
  60. * Will select the template file for the selected theme.
  61. * Checking all the possible locations.
  62. * @param string $theme
  63. * @param string $app
  64. * @return string[]
  65. */
  66. protected function findTemplate($theme, $app, $name) {
  67. // Check if it is a app template or not.
  68. if ($app !== '') {
  69. $dirs = $this->getAppTemplateDirs($theme, $app, OC::$SERVERROOT, OC_App::getAppPath($app));
  70. } else {
  71. $dirs = $this->getCoreTemplateDirs($theme, OC::$SERVERROOT);
  72. }
  73. $locator = new \OC\Template\TemplateFileLocator($dirs);
  74. $template = $locator->find($name);
  75. $path = $locator->getPath();
  76. return [$path, $template];
  77. }
  78. /**
  79. * Add a custom element to the header
  80. * @param string $tag tag name of the element
  81. * @param array $attributes array of attributes for the element
  82. * @param string $text the text content for the element. If $text is null then the
  83. * element will be written as empty element. So use "" to get a closing tag.
  84. */
  85. public function addHeader($tag, $attributes, $text = null) {
  86. $this->headers[] = [
  87. 'tag' => $tag,
  88. 'attributes' => $attributes,
  89. 'text' => $text
  90. ];
  91. }
  92. /**
  93. * Process the template
  94. * @return string
  95. *
  96. * This function process the template. If $this->renderAs is set, it
  97. * will produce a full page.
  98. */
  99. public function fetchPage($additionalParams = null) {
  100. $data = parent::fetchPage($additionalParams);
  101. if ($this->renderAs) {
  102. $page = new TemplateLayout($this->renderAs, $this->app);
  103. if (is_array($additionalParams)) {
  104. foreach ($additionalParams as $key => $value) {
  105. $page->assign($key, $value);
  106. }
  107. }
  108. // Add custom headers
  109. $headers = '';
  110. foreach (OC_Util::$headers as $header) {
  111. $headers .= '<'.\OCP\Util::sanitizeHTML($header['tag']);
  112. if (strcasecmp($header['tag'], 'script') === 0 && in_array('src', array_map('strtolower', array_keys($header['attributes'])))) {
  113. $headers .= ' defer';
  114. }
  115. foreach ($header['attributes'] as $name => $value) {
  116. $headers .= ' '.\OCP\Util::sanitizeHTML($name).'="'.\OCP\Util::sanitizeHTML($value).'"';
  117. }
  118. if ($header['text'] !== null) {
  119. $headers .= '>'.\OCP\Util::sanitizeHTML($header['text']).'</'.\OCP\Util::sanitizeHTML($header['tag']).'>';
  120. } else {
  121. $headers .= '/>';
  122. }
  123. }
  124. $page->assign('headers', $headers);
  125. $page->assign('content', $data);
  126. return $page->fetchPage($additionalParams);
  127. }
  128. return $data;
  129. }
  130. /**
  131. * Include template
  132. *
  133. * @param string $file
  134. * @param array|null $additionalParams
  135. * @return string returns content of included template
  136. *
  137. * Includes another template. use <?php echo $this->inc('template'); ?> to
  138. * do this.
  139. */
  140. public function inc($file, $additionalParams = null) {
  141. return $this->load($this->path.$file.'.php', $additionalParams);
  142. }
  143. /**
  144. * Shortcut to print a simple page for users
  145. * @param string $application The application we render the template for
  146. * @param string $name Name of the template
  147. * @param array $parameters Parameters for the template
  148. * @return boolean|null
  149. */
  150. public static function printUserPage($application, $name, $parameters = []) {
  151. $content = new OC_Template($application, $name, 'user');
  152. foreach ($parameters as $key => $value) {
  153. $content->assign($key, $value);
  154. }
  155. print $content->printPage();
  156. }
  157. /**
  158. * Shortcut to print a simple page for admins
  159. * @param string $application The application we render the template for
  160. * @param string $name Name of the template
  161. * @param array $parameters Parameters for the template
  162. * @return bool
  163. */
  164. public static function printAdminPage($application, $name, $parameters = []) {
  165. $content = new OC_Template($application, $name, 'admin');
  166. foreach ($parameters as $key => $value) {
  167. $content->assign($key, $value);
  168. }
  169. return $content->printPage();
  170. }
  171. /**
  172. * Shortcut to print a simple page for guests
  173. * @param string $application The application we render the template for
  174. * @param string $name Name of the template
  175. * @param array|string $parameters Parameters for the template
  176. * @return bool
  177. */
  178. public static function printGuestPage($application, $name, $parameters = []) {
  179. $content = new OC_Template($application, $name, $name === 'error' ? $name : 'guest');
  180. foreach ($parameters as $key => $value) {
  181. $content->assign($key, $value);
  182. }
  183. return $content->printPage();
  184. }
  185. /**
  186. * Print a fatal error page and terminates the script
  187. * @param string $error_msg The error message to show
  188. * @param string $hint An optional hint message - needs to be properly escape
  189. * @param int $statusCode
  190. * @suppress PhanAccessMethodInternal
  191. */
  192. public static function printErrorPage($error_msg, $hint = '', $statusCode = 500) {
  193. if (\OC::$server->getAppManager()->isEnabledForUser('theming') && !\OC_App::isAppLoaded('theming')) {
  194. \OC_App::loadApp('theming');
  195. }
  196. if ($error_msg === $hint) {
  197. // If the hint is the same as the message there is no need to display it twice.
  198. $hint = '';
  199. }
  200. $errors = [['error' => $error_msg, 'hint' => $hint]];
  201. http_response_code($statusCode);
  202. try {
  203. // Try rendering themed html error page
  204. $response = new TemplateResponse(
  205. '',
  206. 'error',
  207. ['errors' => $errors],
  208. TemplateResponse::RENDER_AS_ERROR,
  209. $statusCode,
  210. );
  211. $event = new BeforeTemplateRenderedEvent(false, $response);
  212. \OC::$server->get(IEventDispatcher::class)->dispatchTyped($event);
  213. print($response->render());
  214. } catch (\Throwable $e1) {
  215. $logger = \OC::$server->getLogger();
  216. $logger->logException($e1, [
  217. 'app' => 'core',
  218. 'message' => 'Rendering themed error page failed. Falling back to unthemed error page.'
  219. ]);
  220. try {
  221. // Try rendering unthemed html error page
  222. $content = new \OC_Template('', 'error', 'error', false);
  223. $content->assign('errors', $errors);
  224. $content->printPage();
  225. } catch (\Exception $e2) {
  226. // If nothing else works, fall back to plain text error page
  227. $logger->error("$error_msg $hint", ['app' => 'core']);
  228. $logger->logException($e2, [
  229. 'app' => 'core',
  230. 'message' => 'Rendering unthemed error page failed. Falling back to plain text error page.'
  231. ]);
  232. header('Content-Type: text/plain; charset=utf-8');
  233. print("$error_msg $hint");
  234. }
  235. }
  236. die();
  237. }
  238. /**
  239. * print error page using Exception details
  240. * @param Exception|Throwable $exception
  241. * @param int $statusCode
  242. * @return bool|string
  243. * @suppress PhanAccessMethodInternal
  244. */
  245. public static function printExceptionErrorPage($exception, $statusCode = 503) {
  246. $debug = false;
  247. http_response_code($statusCode);
  248. try {
  249. $debug = \OC::$server->getSystemConfig()->getValue('debug', false);
  250. $serverLogsDocumentation = \OC::$server->getSystemConfig()->getValue('documentation_url.server_logs', '');
  251. $request = \OC::$server->getRequest();
  252. $content = new \OC_Template('', 'exception', 'error', false);
  253. $content->assign('errorClass', get_class($exception));
  254. $content->assign('errorMsg', $exception->getMessage());
  255. $content->assign('errorCode', $exception->getCode());
  256. $content->assign('file', $exception->getFile());
  257. $content->assign('line', $exception->getLine());
  258. $content->assign('exception', $exception);
  259. $content->assign('debugMode', $debug);
  260. $content->assign('serverLogsDocumentation', $serverLogsDocumentation);
  261. $content->assign('remoteAddr', $request->getRemoteAddress());
  262. $content->assign('requestID', $request->getId());
  263. $content->printPage();
  264. } catch (\Exception $e) {
  265. try {
  266. $logger = \OC::$server->getLogger();
  267. $logger->logException($exception, ['app' => 'core']);
  268. $logger->logException($e, ['app' => 'core']);
  269. } catch (Throwable $e) {
  270. // no way to log it properly - but to avoid a white page of death we send some output
  271. self::printPlainErrorPage($e, $debug);
  272. // and then throw it again to log it at least to the web server error log
  273. throw $e;
  274. }
  275. self::printPlainErrorPage($e, $debug);
  276. }
  277. die();
  278. }
  279. private static function printPlainErrorPage(\Throwable $exception, bool $debug = false) {
  280. header('Content-Type: text/plain; charset=utf-8');
  281. print("Internal Server Error\n\n");
  282. print("The server encountered an internal error and was unable to complete your request.\n");
  283. print("Please contact the server administrator if this error reappears multiple times, please include the technical details below in your report.\n");
  284. print("More details can be found in the server log.\n");
  285. if ($debug) {
  286. print("\n");
  287. print($exception->getMessage() . ' ' . $exception->getFile() . ' at ' . $exception->getLine() . "\n");
  288. print($exception->getTraceAsString());
  289. }
  290. }
  291. }