1
0

template.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363
  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::addStyle('jquery-ui-fixes',null,true);
  97. OC_Util::addStyle('jquery.ocdialog');
  98. OC_Util::addTranslations("core", null, true);
  99. OC_Util::addStyle('search', 'results');
  100. OC_Util::addScript('search', 'search', true);
  101. OC_Util::addScript('search', 'searchprovider');
  102. OC_Util::addScript('merged-template-prepend', null, true);
  103. OC_Util::addScript('jquery-ui-fixes');
  104. OC_Util::addScript('files/fileinfo');
  105. OC_Util::addScript('files/client');
  106. OC_Util::addScript('contactsmenu');
  107. OC_Util::addScript('contactsmenu_templates');
  108. OC_Util::addScript('core', 'dist/main', true);
  109. if (\OC::$server->getRequest()->isUserAgent([\OC\AppFramework\Http\Request::USER_AGENT_IE])) {
  110. // shim for the davclient.js library
  111. \OCP\Util::addScript('files/iedavclient');
  112. }
  113. self::$initTemplateEngineFirstRun = false;
  114. }
  115. }
  116. /**
  117. * find the template with the given name
  118. * @param string $name of the template file (without suffix)
  119. *
  120. * Will select the template file for the selected theme.
  121. * Checking all the possible locations.
  122. * @param string $theme
  123. * @param string $app
  124. * @return string[]
  125. */
  126. protected function findTemplate($theme, $app, $name) {
  127. // Check if it is a app template or not.
  128. if( $app !== '' ) {
  129. $dirs = $this->getAppTemplateDirs($theme, $app, OC::$SERVERROOT, OC_App::getAppPath($app));
  130. } else {
  131. $dirs = $this->getCoreTemplateDirs($theme, OC::$SERVERROOT);
  132. }
  133. $locator = new \OC\Template\TemplateFileLocator( $dirs );
  134. $template = $locator->find($name);
  135. $path = $locator->getPath();
  136. return array($path, $template);
  137. }
  138. /**
  139. * Add a custom element to the header
  140. * @param string $tag tag name of the element
  141. * @param array $attributes array of attributes for the element
  142. * @param string $text the text content for the element. If $text is null then the
  143. * element will be written as empty element. So use "" to get a closing tag.
  144. */
  145. public function addHeader($tag, $attributes, $text=null) {
  146. $this->headers[]= array(
  147. 'tag' => $tag,
  148. 'attributes' => $attributes,
  149. 'text' => $text
  150. );
  151. }
  152. /**
  153. * Process the template
  154. * @return boolean|string
  155. *
  156. * This function process the template. If $this->renderAs is set, it
  157. * will produce a full page.
  158. */
  159. public function fetchPage($additionalParams = null) {
  160. $data = parent::fetchPage($additionalParams);
  161. if( $this->renderAs ) {
  162. $page = new TemplateLayout($this->renderAs, $this->app);
  163. if(is_array($additionalParams)) {
  164. foreach ($additionalParams as $key => $value) {
  165. $page->assign($key, $value);
  166. }
  167. }
  168. // Add custom headers
  169. $headers = '';
  170. foreach(OC_Util::$headers as $header) {
  171. $headers .= '<'.\OCP\Util::sanitizeHTML($header['tag']);
  172. if ( strcasecmp($header['tag'], 'script') === 0 && in_array('src', array_map('strtolower', array_keys($header['attributes']))) ) {
  173. $headers .= ' defer';
  174. }
  175. foreach($header['attributes'] as $name=>$value) {
  176. $headers .= ' '.\OCP\Util::sanitizeHTML($name).'="'.\OCP\Util::sanitizeHTML($value).'"';
  177. }
  178. if ($header['text'] !== null) {
  179. $headers .= '>'.\OCP\Util::sanitizeHTML($header['text']).'</'.\OCP\Util::sanitizeHTML($header['tag']).'>';
  180. } else {
  181. $headers .= '/>';
  182. }
  183. }
  184. $page->assign('headers', $headers);
  185. $page->assign('content', $data);
  186. return $page->fetchPage($additionalParams);
  187. }
  188. return $data;
  189. }
  190. /**
  191. * Include template
  192. *
  193. * @param string $file
  194. * @param array|null $additionalParams
  195. * @return string returns content of included template
  196. *
  197. * Includes another template. use <?php echo $this->inc('template'); ?> to
  198. * do this.
  199. */
  200. public function inc( $file, $additionalParams = null ) {
  201. return $this->load($this->path.$file.'.php', $additionalParams);
  202. }
  203. /**
  204. * Shortcut to print a simple page for users
  205. * @param string $application The application we render the template for
  206. * @param string $name Name of the template
  207. * @param array $parameters Parameters for the template
  208. * @return boolean|null
  209. */
  210. public static function printUserPage( $application, $name, $parameters = array() ) {
  211. $content = new OC_Template( $application, $name, "user" );
  212. foreach( $parameters as $key => $value ) {
  213. $content->assign( $key, $value );
  214. }
  215. print $content->printPage();
  216. }
  217. /**
  218. * Shortcut to print a simple page for admins
  219. * @param string $application The application we render the template for
  220. * @param string $name Name of the template
  221. * @param array $parameters Parameters for the template
  222. * @return bool
  223. */
  224. public static function printAdminPage( $application, $name, $parameters = array() ) {
  225. $content = new OC_Template( $application, $name, "admin" );
  226. foreach( $parameters as $key => $value ) {
  227. $content->assign( $key, $value );
  228. }
  229. return $content->printPage();
  230. }
  231. /**
  232. * Shortcut to print a simple page for guests
  233. * @param string $application The application we render the template for
  234. * @param string $name Name of the template
  235. * @param array|string $parameters Parameters for the template
  236. * @return bool
  237. */
  238. public static function printGuestPage( $application, $name, $parameters = array() ) {
  239. $content = new OC_Template( $application, $name, "guest" );
  240. foreach( $parameters as $key => $value ) {
  241. $content->assign( $key, $value );
  242. }
  243. return $content->printPage();
  244. }
  245. /**
  246. * Print a fatal error page and terminates the script
  247. * @param string $error_msg The error message to show
  248. * @param string $hint An optional hint message - needs to be properly escape
  249. * @param int $statusCode
  250. * @suppress PhanAccessMethodInternal
  251. */
  252. public static function printErrorPage( $error_msg, $hint = '', $statusCode = 500) {
  253. if (\OC::$server->getAppManager()->isEnabledForUser('theming') && !\OC_App::isAppLoaded('theming')) {
  254. \OC_App::loadApp('theming');
  255. }
  256. if ($error_msg === $hint) {
  257. // If the hint is the same as the message there is no need to display it twice.
  258. $hint = '';
  259. }
  260. http_response_code($statusCode);
  261. try {
  262. $content = new \OC_Template( '', 'error', 'error', false );
  263. $errors = array(array('error' => $error_msg, 'hint' => $hint));
  264. $content->assign( 'errors', $errors );
  265. $content->printPage();
  266. } catch (\Exception $e) {
  267. $logger = \OC::$server->getLogger();
  268. $logger->error("$error_msg $hint", ['app' => 'core']);
  269. $logger->logException($e, ['app' => 'core']);
  270. header('Content-Type: text/plain; charset=utf-8');
  271. print("$error_msg $hint");
  272. }
  273. die();
  274. }
  275. /**
  276. * print error page using Exception details
  277. * @param Exception|Throwable $exception
  278. * @param int $statusCode
  279. * @return bool|string
  280. * @suppress PhanAccessMethodInternal
  281. */
  282. public static function printExceptionErrorPage($exception, $statusCode = 503) {
  283. http_response_code($statusCode);
  284. try {
  285. $request = \OC::$server->getRequest();
  286. $content = new \OC_Template('', 'exception', 'error', false);
  287. $content->assign('errorClass', get_class($exception));
  288. $content->assign('errorMsg', $exception->getMessage());
  289. $content->assign('errorCode', $exception->getCode());
  290. $content->assign('file', $exception->getFile());
  291. $content->assign('line', $exception->getLine());
  292. $content->assign('trace', $exception->getTraceAsString());
  293. $content->assign('debugMode', \OC::$server->getSystemConfig()->getValue('debug', false));
  294. $content->assign('remoteAddr', $request->getRemoteAddress());
  295. $content->assign('requestID', $request->getId());
  296. $content->printPage();
  297. } catch (\Exception $e) {
  298. try {
  299. $logger = \OC::$server->getLogger();
  300. $logger->logException($exception, ['app' => 'core']);
  301. $logger->logException($e, ['app' => 'core']);
  302. } catch (Throwable $e) {
  303. // no way to log it properly - but to avoid a white page of death we send some output
  304. header('Content-Type: text/plain; charset=utf-8');
  305. print("Internal Server Error\n\n");
  306. print("The server encountered an internal error and was unable to complete your request.\n");
  307. print("Please contact the server administrator if this error reappears multiple times, please include the technical details below in your report.\n");
  308. print("More details can be found in the server log.\n");
  309. // and then throw it again to log it at least to the web server error log
  310. throw $e;
  311. }
  312. header('Content-Type: text/plain; charset=utf-8');
  313. print("Internal Server Error\n\n");
  314. print("The server encountered an internal error and was unable to complete your request.\n");
  315. print("Please contact the server administrator if this error reappears multiple times, please include the technical details below in your report.\n");
  316. print("More details can be found in the server log.\n");
  317. }
  318. die();
  319. }
  320. }