template.php 13 KB

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