template.php 14 KB

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