OC_Template.php 11 KB

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