1
0

template.php 13 KB

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