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.

template.php 13KB

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