1
0

OC_Template.php 12 KB

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