template.php 14 KB

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