OC_Template.php 11 KB

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