You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

358 lines
12 KiB

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