template.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358
  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@owncloud.com>
  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@users.noreply.github.com>
  14. * @author Jörn Friedrich Dreyer <jfd@butonic.de>
  15. * @author Lukas Reschke <lukas@statuscode.ch>
  16. * @author Marin Treselj <marin@pixelipo.com>
  17. * @author Michael Letzgus <www@chronos.michael-letzgus.de>
  18. * @author Morris Jobke <hey@morrisjobke.de>
  19. * @author Robin Appelman <robin@icewind.nl>
  20. * @author Roeland Jago Douma <roeland@famdouma.nl>
  21. * @author Thomas Müller <thomas.mueller@tmit.eu>
  22. * @author Vincent Petry <pvince81@owncloud.com>
  23. *
  24. * @license AGPL-3.0
  25. *
  26. * This code is free software: you can redistribute it and/or modify
  27. * it under the terms of the GNU Affero General Public License, version 3,
  28. * as published by the Free Software Foundation.
  29. *
  30. * This program is distributed in the hope that it will be useful,
  31. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  32. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  33. * GNU Affero General Public License for more details.
  34. *
  35. * You should have received a copy of the GNU Affero General Public License, version 3,
  36. * along with this program. If not, see <http://www.gnu.org/licenses/>
  37. *
  38. */
  39. use OC\TemplateLayout;
  40. require_once __DIR__.'/template/functions.php';
  41. /**
  42. * This class provides the templates for ownCloud.
  43. */
  44. class OC_Template extends \OC\Template\Base {
  45. /** @var string */
  46. private $renderAs; // Create a full page?
  47. /** @var string */
  48. private $path; // The path to the template
  49. /** @var array */
  50. private $headers = array(); //custom headers
  51. /** @var string */
  52. protected $app; // app id
  53. protected static $initTemplateEngineFirstRun = true;
  54. /**
  55. * Constructor
  56. *
  57. * @param string $app app providing the template
  58. * @param string $name of the template file (without suffix)
  59. * @param string $renderAs If $renderAs is set, OC_Template will try to
  60. * produce a full page in the according layout. For
  61. * now, $renderAs can be set to "guest", "user" or
  62. * "admin".
  63. * @param bool $registerCall = true
  64. */
  65. public function __construct( $app, $name, $renderAs = "", $registerCall = true ) {
  66. // Read the selected theme from the config file
  67. self::initTemplateEngine($renderAs);
  68. $theme = OC_Util::getTheme();
  69. $requestToken = (OC::$server->getSession() && $registerCall) ? \OCP\Util::callRegister() : '';
  70. $parts = explode('/', $app); // fix translation when app is something like core/lostpassword
  71. $l10n = \OC::$server->getL10N($parts[0]);
  72. /** @var \OCP\Defaults $themeDefaults */
  73. $themeDefaults = \OC::$server->query(\OCP\Defaults::class);
  74. list($path, $template) = $this->findTemplate($theme, $app, $name);
  75. // Set the private data
  76. $this->renderAs = $renderAs;
  77. $this->path = $path;
  78. $this->app = $app;
  79. parent::__construct($template, $requestToken, $l10n, $themeDefaults);
  80. }
  81. /**
  82. * @param string $renderAs
  83. */
  84. public static function initTemplateEngine($renderAs) {
  85. if (self::$initTemplateEngineFirstRun){
  86. //apps that started before the template initialization can load their own scripts/styles
  87. //so to make sure this scripts/styles here are loaded first we use OC_Util::addScript() with $prepend=true
  88. //meaning the last script/style in this list will be loaded first
  89. if (\OC::$server->getSystemConfig()->getValue ('installed', false) && $renderAs !== 'error' && !\OCP\Util::needUpgrade()) {
  90. if (\OC::$server->getConfig ()->getAppValue ( 'core', 'backgroundjobs_mode', 'ajax' ) == 'ajax') {
  91. OC_Util::addScript ( 'backgroundjobs', null, true );
  92. }
  93. }
  94. OC_Util::addStyle('css-variables', null, true);
  95. OC_Util::addStyle('server', null, true);
  96. OC_Util::addTranslations("core", null, true);
  97. OC_Util::addStyle('search', 'results');
  98. OC_Util::addScript('search', 'search', true);
  99. OC_Util::addScript('search', 'searchprovider');
  100. OC_Util::addScript('merged-template-prepend', null, true);
  101. OC_Util::addScript('files/fileinfo');
  102. OC_Util::addScript('files/client');
  103. OC_Util::addScript('core', 'dist/main', true);
  104. if (\OC::$server->getRequest()->isUserAgent([\OC\AppFramework\Http\Request::USER_AGENT_IE])) {
  105. // shim for the davclient.js library
  106. \OCP\Util::addScript('files/iedavclient');
  107. }
  108. self::$initTemplateEngineFirstRun = false;
  109. }
  110. }
  111. /**
  112. * find the template with the given name
  113. * @param string $name of the template file (without suffix)
  114. *
  115. * Will select the template file for the selected theme.
  116. * Checking all the possible locations.
  117. * @param string $theme
  118. * @param string $app
  119. * @return string[]
  120. */
  121. protected function findTemplate($theme, $app, $name) {
  122. // Check if it is a app template or not.
  123. if( $app !== '' ) {
  124. $dirs = $this->getAppTemplateDirs($theme, $app, OC::$SERVERROOT, OC_App::getAppPath($app));
  125. } else {
  126. $dirs = $this->getCoreTemplateDirs($theme, OC::$SERVERROOT);
  127. }
  128. $locator = new \OC\Template\TemplateFileLocator( $dirs );
  129. $template = $locator->find($name);
  130. $path = $locator->getPath();
  131. return array($path, $template);
  132. }
  133. /**
  134. * Add a custom element to the header
  135. * @param string $tag tag name of the element
  136. * @param array $attributes array of attributes for the element
  137. * @param string $text the text content for the element. If $text is null then the
  138. * element will be written as empty element. So use "" to get a closing tag.
  139. */
  140. public function addHeader($tag, $attributes, $text=null) {
  141. $this->headers[]= array(
  142. 'tag' => $tag,
  143. 'attributes' => $attributes,
  144. 'text' => $text
  145. );
  146. }
  147. /**
  148. * Process the template
  149. * @return boolean|string
  150. *
  151. * This function process the template. If $this->renderAs is set, it
  152. * will produce a full page.
  153. */
  154. public function fetchPage($additionalParams = null) {
  155. $data = parent::fetchPage($additionalParams);
  156. if( $this->renderAs ) {
  157. $page = new TemplateLayout($this->renderAs, $this->app);
  158. if(is_array($additionalParams)) {
  159. foreach ($additionalParams as $key => $value) {
  160. $page->assign($key, $value);
  161. }
  162. }
  163. // Add custom headers
  164. $headers = '';
  165. foreach(OC_Util::$headers as $header) {
  166. $headers .= '<'.\OCP\Util::sanitizeHTML($header['tag']);
  167. if ( strcasecmp($header['tag'], 'script') === 0 && in_array('src', array_map('strtolower', array_keys($header['attributes']))) ) {
  168. $headers .= ' defer';
  169. }
  170. foreach($header['attributes'] as $name=>$value) {
  171. $headers .= ' '.\OCP\Util::sanitizeHTML($name).'="'.\OCP\Util::sanitizeHTML($value).'"';
  172. }
  173. if ($header['text'] !== null) {
  174. $headers .= '>'.\OCP\Util::sanitizeHTML($header['text']).'</'.\OCP\Util::sanitizeHTML($header['tag']).'>';
  175. } else {
  176. $headers .= '/>';
  177. }
  178. }
  179. $page->assign('headers', $headers);
  180. $page->assign('content', $data);
  181. return $page->fetchPage($additionalParams);
  182. }
  183. return $data;
  184. }
  185. /**
  186. * Include template
  187. *
  188. * @param string $file
  189. * @param array|null $additionalParams
  190. * @return string returns content of included template
  191. *
  192. * Includes another template. use <?php echo $this->inc('template'); ?> to
  193. * do this.
  194. */
  195. public function inc( $file, $additionalParams = null ) {
  196. return $this->load($this->path.$file.'.php', $additionalParams);
  197. }
  198. /**
  199. * Shortcut to print a simple page for users
  200. * @param string $application The application we render the template for
  201. * @param string $name Name of the template
  202. * @param array $parameters Parameters for the template
  203. * @return boolean|null
  204. */
  205. public static function printUserPage( $application, $name, $parameters = array() ) {
  206. $content = new OC_Template( $application, $name, "user" );
  207. foreach( $parameters as $key => $value ) {
  208. $content->assign( $key, $value );
  209. }
  210. print $content->printPage();
  211. }
  212. /**
  213. * Shortcut to print a simple page for admins
  214. * @param string $application The application we render the template for
  215. * @param string $name Name of the template
  216. * @param array $parameters Parameters for the template
  217. * @return bool
  218. */
  219. public static function printAdminPage( $application, $name, $parameters = array() ) {
  220. $content = new OC_Template( $application, $name, "admin" );
  221. foreach( $parameters as $key => $value ) {
  222. $content->assign( $key, $value );
  223. }
  224. return $content->printPage();
  225. }
  226. /**
  227. * Shortcut to print a simple page for guests
  228. * @param string $application The application we render the template for
  229. * @param string $name Name of the template
  230. * @param array|string $parameters Parameters for the template
  231. * @return bool
  232. */
  233. public static function printGuestPage( $application, $name, $parameters = array() ) {
  234. $content = new OC_Template( $application, $name, "guest" );
  235. foreach( $parameters as $key => $value ) {
  236. $content->assign( $key, $value );
  237. }
  238. return $content->printPage();
  239. }
  240. /**
  241. * Print a fatal error page and terminates the script
  242. * @param string $error_msg The error message to show
  243. * @param string $hint An optional hint message - needs to be properly escape
  244. * @param int $statusCode
  245. * @suppress PhanAccessMethodInternal
  246. */
  247. public static function printErrorPage( $error_msg, $hint = '', $statusCode = 500) {
  248. if (\OC::$server->getAppManager()->isEnabledForUser('theming') && !\OC_App::isAppLoaded('theming')) {
  249. \OC_App::loadApp('theming');
  250. }
  251. if ($error_msg === $hint) {
  252. // If the hint is the same as the message there is no need to display it twice.
  253. $hint = '';
  254. }
  255. http_response_code($statusCode);
  256. try {
  257. $content = new \OC_Template( '', 'error', 'error', false );
  258. $errors = array(array('error' => $error_msg, 'hint' => $hint));
  259. $content->assign( 'errors', $errors );
  260. $content->printPage();
  261. } catch (\Exception $e) {
  262. $logger = \OC::$server->getLogger();
  263. $logger->error("$error_msg $hint", ['app' => 'core']);
  264. $logger->logException($e, ['app' => 'core']);
  265. header('Content-Type: text/plain; charset=utf-8');
  266. print("$error_msg $hint");
  267. }
  268. die();
  269. }
  270. /**
  271. * print error page using Exception details
  272. * @param Exception|Throwable $exception
  273. * @param int $statusCode
  274. * @return bool|string
  275. * @suppress PhanAccessMethodInternal
  276. */
  277. public static function printExceptionErrorPage($exception, $statusCode = 503) {
  278. http_response_code($statusCode);
  279. try {
  280. $request = \OC::$server->getRequest();
  281. $content = new \OC_Template('', 'exception', 'error', false);
  282. $content->assign('errorClass', get_class($exception));
  283. $content->assign('errorMsg', $exception->getMessage());
  284. $content->assign('errorCode', $exception->getCode());
  285. $content->assign('file', $exception->getFile());
  286. $content->assign('line', $exception->getLine());
  287. $content->assign('trace', $exception->getTraceAsString());
  288. $content->assign('debugMode', \OC::$server->getSystemConfig()->getValue('debug', false));
  289. $content->assign('remoteAddr', $request->getRemoteAddress());
  290. $content->assign('requestID', $request->getId());
  291. $content->printPage();
  292. } catch (\Exception $e) {
  293. try {
  294. $logger = \OC::$server->getLogger();
  295. $logger->logException($exception, ['app' => 'core']);
  296. $logger->logException($e, ['app' => 'core']);
  297. } catch (Throwable $e) {
  298. // no way to log it properly - but to avoid a white page of death we send some output
  299. header('Content-Type: text/plain; charset=utf-8');
  300. print("Internal Server Error\n\n");
  301. print("The server encountered an internal error and was unable to complete your request.\n");
  302. print("Please contact the server administrator if this error reappears multiple times, please include the technical details below in your report.\n");
  303. print("More details can be found in the server log.\n");
  304. // and then throw it again to log it at least to the web server error log
  305. throw $e;
  306. }
  307. header('Content-Type: text/plain; charset=utf-8');
  308. print("Internal Server Error\n\n");
  309. print("The server encountered an internal error and was unable to complete your request.\n");
  310. print("Please contact the server administrator if this error reappears multiple times, please include the technical details below in your report.\n");
  311. print("More details can be found in the server log.\n");
  312. }
  313. die();
  314. }
  315. }