OC_Template.php 10 KB

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