template.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440
  1. <?php
  2. /**
  3. * @author Adam Williamson <awilliam@redhat.com>
  4. * @author Bart Visscher <bartv@thisnet.nl>
  5. * @author Björn Schießle <bjoern@schiessle.org>
  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 <nickvergessen@owncloud.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 <icewind@owncloud.com>
  18. * @author Roeland Jago Douma <rullzer@owncloud.com>
  19. * @author Thomas Müller <thomas.mueller@tmit.eu>
  20. * @author Vincent Petry <pvince81@owncloud.com>
  21. *
  22. * @copyright Copyright (c) 2016, ownCloud, Inc.
  23. * @license AGPL-3.0
  24. *
  25. * This code is free software: you can redistribute it and/or modify
  26. * it under the terms of the GNU Affero General Public License, version 3,
  27. * as published by the Free Software Foundation.
  28. *
  29. * This program is distributed in the hope that it will be useful,
  30. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  31. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  32. * GNU Affero General Public License for more details.
  33. *
  34. * You should have received a copy of the GNU Affero General Public License, version 3,
  35. * along with this program. If not, see <http://www.gnu.org/licenses/>
  36. *
  37. */
  38. use OC\TemplateLayout;
  39. require_once __DIR__.'/template/functions.php';
  40. /**
  41. * This class provides the templates for ownCloud.
  42. */
  43. class OC_Template extends \OC\Template\Base {
  44. /** @var string */
  45. private $renderAs; // Create a full page?
  46. /** @var string */
  47. private $path; // The path to the template
  48. /** @var array */
  49. private $headers = array(); //custom headers
  50. /** @var string */
  51. protected $app; // app id
  52. protected static $initTemplateEngineFirstRun = true;
  53. /**
  54. * Constructor
  55. *
  56. * @param string $app app providing the template
  57. * @param string $name of the template file (without suffix)
  58. * @param string $renderAs If $renderAs is set, OC_Template will try to
  59. * produce a full page in the according layout. For
  60. * now, $renderAs can be set to "guest", "user" or
  61. * "admin".
  62. * @param bool $registerCall = true
  63. */
  64. public function __construct( $app, $name, $renderAs = "", $registerCall = true ) {
  65. // Read the selected theme from the config file
  66. self::initTemplateEngine($renderAs);
  67. $theme = OC_Util::getTheme();
  68. $requestToken = (OC::$server->getSession() && $registerCall) ? \OCP\Util::callRegister() : '';
  69. $parts = explode('/', $app); // fix translation when app is something like core/lostpassword
  70. $l10n = \OC::$server->getL10N($parts[0]);
  71. $themeDefaults = new OC_Defaults();
  72. list($path, $template) = $this->findTemplate($theme, $app, $name);
  73. // Set the private data
  74. $this->renderAs = $renderAs;
  75. $this->path = $path;
  76. $this->app = $app;
  77. parent::__construct($template, $requestToken, $l10n, $themeDefaults);
  78. }
  79. /**
  80. * @param string $renderAs
  81. */
  82. public static function initTemplateEngine($renderAs) {
  83. if (self::$initTemplateEngineFirstRun){
  84. //apps that started before the template initialization can load their own scripts/styles
  85. //so to make sure this scripts/styles here are loaded first we use OC_Util::addScript() with $prepend=true
  86. //meaning the last script/style in this list will be loaded first
  87. if (\OC::$server->getSystemConfig()->getValue ('installed', false) && $renderAs !== 'error' && !\OCP\Util::needUpgrade()) {
  88. if (\OC::$server->getConfig ()->getAppValue ( 'core', 'backgroundjobs_mode', 'ajax' ) == 'ajax') {
  89. OC_Util::addScript ( 'backgroundjobs', null, true );
  90. }
  91. }
  92. OC_Util::addStyle("tooltip",null,true);
  93. OC_Util::addStyle('jquery-ui-fixes',null,true);
  94. OC_Util::addVendorStyle('jquery-ui/themes/base/jquery-ui',null,true);
  95. OC_Util::addStyle("mobile",null,true);
  96. OC_Util::addStyle("multiselect",null,true);
  97. OC_Util::addStyle("fixes",null,true);
  98. OC_Util::addStyle("global",null,true);
  99. OC_Util::addStyle("apps",null,true);
  100. OC_Util::addStyle("fonts",null,true);
  101. OC_Util::addStyle("icons",null,true);
  102. OC_Util::addStyle("header",null,true);
  103. OC_Util::addStyle("inputs",null,true);
  104. OC_Util::addStyle("styles",null,true);
  105. // avatars
  106. if (\OC::$server->getSystemConfig()->getValue('enable_avatars', true) === true) {
  107. \OC_Util::addScript('jquery.avatar', null, true);
  108. \OC_Util::addScript('placeholder', null, true);
  109. }
  110. OC_Util::addScript('oc-backbone', null, true);
  111. OC_Util::addVendorScript('core', 'backbone/backbone', true);
  112. OC_Util::addVendorScript('snapjs/dist/latest/snap', null, true);
  113. OC_Util::addScript('mimetypelist', null, true);
  114. OC_Util::addScript('mimetype', null, true);
  115. OC_Util::addScript("apps", null, true);
  116. OC_Util::addScript("oc-requesttoken", null, true);
  117. OC_Util::addScript('search', 'search', true);
  118. OC_Util::addScript("config", null, true);
  119. OC_Util::addScript("eventsource", null, true);
  120. OC_Util::addScript("octemplate", null, true);
  121. OC_Util::addTranslations("core", null, true);
  122. OC_Util::addScript("l10n", null, true);
  123. OC_Util::addScript("js", null, true);
  124. OC_Util::addScript("oc-dialogs", null, true);
  125. OC_Util::addScript("jquery.ocdialog", null, true);
  126. OC_Util::addStyle("jquery.ocdialog");
  127. OC_Util::addScript("compatibility", null, true);
  128. OC_Util::addScript("placeholders", null, true);
  129. OC_Util::addScript('files/fileinfo');
  130. OC_Util::addScript('files/client');
  131. // Add the stuff we need always
  132. // following logic will import all vendor libraries that are
  133. // specified in core/js/core.json
  134. $fileContent = file_get_contents(OC::$SERVERROOT . '/core/js/core.json');
  135. if($fileContent !== false) {
  136. $coreDependencies = json_decode($fileContent, true);
  137. foreach(array_reverse($coreDependencies['vendor']) as $vendorLibrary) {
  138. // remove trailing ".js" as addVendorScript will append it
  139. OC_Util::addVendorScript(
  140. substr($vendorLibrary, 0, strlen($vendorLibrary) - 3),null,true);
  141. }
  142. } else {
  143. throw new \Exception('Cannot read core/js/core.json');
  144. }
  145. if (\OC::$server->getRequest()->isUserAgent([\OC\AppFramework\Http\Request::USER_AGENT_IE])) {
  146. // polyfill for btoa/atob for IE friends
  147. OC_Util::addVendorScript('base64/base64');
  148. // shim for the davclient.js library
  149. \OCP\Util::addScript('files/iedavclient');
  150. }
  151. self::$initTemplateEngineFirstRun = false;
  152. }
  153. }
  154. /**
  155. * find the template with the given name
  156. * @param string $name of the template file (without suffix)
  157. *
  158. * Will select the template file for the selected theme.
  159. * Checking all the possible locations.
  160. * @param string $theme
  161. * @param string $app
  162. * @return string[]
  163. */
  164. protected function findTemplate($theme, $app, $name) {
  165. // Check if it is a app template or not.
  166. if( $app !== '' ) {
  167. $dirs = $this->getAppTemplateDirs($theme, $app, OC::$SERVERROOT, OC_App::getAppPath($app));
  168. } else {
  169. $dirs = $this->getCoreTemplateDirs($theme, OC::$SERVERROOT);
  170. }
  171. $locator = new \OC\Template\TemplateFileLocator( $dirs );
  172. $template = $locator->find($name);
  173. $path = $locator->getPath();
  174. return array($path, $template);
  175. }
  176. /**
  177. * Add a custom element to the header
  178. * @param string $tag tag name of the element
  179. * @param array $attributes array of attributes for the element
  180. * @param string $text the text content for the element. If $text is null then the
  181. * element will be written as empty element. So use "" to get a closing tag.
  182. */
  183. public function addHeader($tag, $attributes, $text=null) {
  184. $this->headers[]= array(
  185. 'tag' => $tag,
  186. 'attributes' => $attributes,
  187. 'text' => $text
  188. );
  189. }
  190. /**
  191. * Process the template
  192. * @return boolean|string
  193. *
  194. * This function process the template. If $this->renderAs is set, it
  195. * will produce a full page.
  196. */
  197. public function fetchPage($additionalParams = null) {
  198. $data = parent::fetchPage($additionalParams);
  199. if( $this->renderAs ) {
  200. $page = new TemplateLayout($this->renderAs, $this->app);
  201. // Add custom headers
  202. $headers = '';
  203. foreach(OC_Util::$headers as $header) {
  204. $headers .= '<'.\OCP\Util::sanitizeHTML($header['tag']);
  205. foreach($header['attributes'] as $name=>$value) {
  206. $headers .= ' '.\OCP\Util::sanitizeHTML($name).'="'.\OCP\Util::sanitizeHTML($value).'"';
  207. }
  208. if ($header['text'] !== null) {
  209. $headers .= '>'.\OCP\Util::sanitizeHTML($header['text']).'</'.\OCP\Util::sanitizeHTML($header['tag']).'>';
  210. } else {
  211. $headers .= '/>';
  212. }
  213. }
  214. $page->assign('headers', $headers);
  215. $page->assign('content', $data);
  216. return $page->fetchPage();
  217. }
  218. return $data;
  219. }
  220. /**
  221. * Include template
  222. *
  223. * @param string $file
  224. * @param array|null $additionalParams
  225. * @return string returns content of included template
  226. *
  227. * Includes another template. use <?php echo $this->inc('template'); ?> to
  228. * do this.
  229. */
  230. public function inc( $file, $additionalParams = null ) {
  231. return $this->load($this->path.$file.'.php', $additionalParams);
  232. }
  233. /**
  234. * Shortcut to print a simple page for users
  235. * @param string $application The application we render the template for
  236. * @param string $name Name of the template
  237. * @param array $parameters Parameters for the template
  238. * @return boolean|null
  239. */
  240. public static function printUserPage( $application, $name, $parameters = array() ) {
  241. $content = new OC_Template( $application, $name, "user" );
  242. foreach( $parameters as $key => $value ) {
  243. $content->assign( $key, $value );
  244. }
  245. print $content->printPage();
  246. }
  247. /**
  248. * Shortcut to print a simple page for admins
  249. * @param string $application The application we render the template for
  250. * @param string $name Name of the template
  251. * @param array $parameters Parameters for the template
  252. * @return bool
  253. */
  254. public static function printAdminPage( $application, $name, $parameters = array() ) {
  255. $content = new OC_Template( $application, $name, "admin" );
  256. foreach( $parameters as $key => $value ) {
  257. $content->assign( $key, $value );
  258. }
  259. return $content->printPage();
  260. }
  261. /**
  262. * Shortcut to print a simple page for guests
  263. * @param string $application The application we render the template for
  264. * @param string $name Name of the template
  265. * @param array|string $parameters Parameters for the template
  266. * @return bool
  267. */
  268. public static function printGuestPage( $application, $name, $parameters = array() ) {
  269. $content = new OC_Template( $application, $name, "guest" );
  270. foreach( $parameters as $key => $value ) {
  271. $content->assign( $key, $value );
  272. }
  273. return $content->printPage();
  274. }
  275. /**
  276. * Print a fatal error page and terminates the script
  277. * @param string $error_msg The error message to show
  278. * @param string $hint An optional hint message - needs to be properly escaped
  279. */
  280. public static function printErrorPage( $error_msg, $hint = '' ) {
  281. if ($error_msg === $hint) {
  282. // If the hint is the same as the message there is no need to display it twice.
  283. $hint = '';
  284. }
  285. try {
  286. $content = new \OC_Template( '', 'error', 'error', false );
  287. $errors = array(array('error' => $error_msg, 'hint' => $hint));
  288. $content->assign( 'errors', $errors );
  289. $content->printPage();
  290. } catch (\Exception $e) {
  291. $logger = \OC::$server->getLogger();
  292. $logger->error("$error_msg $hint", ['app' => 'core']);
  293. $logger->logException($e, ['app' => 'core']);
  294. header(self::getHttpProtocol() . ' 500 Internal Server Error');
  295. header('Content-Type: text/plain; charset=utf-8');
  296. print("$error_msg $hint");
  297. }
  298. die();
  299. }
  300. /**
  301. * print error page using Exception details
  302. * @param Exception | Throwable $exception
  303. */
  304. public static function printExceptionErrorPage($exception, $fetchPage = false) {
  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. if ($fetchPage) {
  318. return $content->fetchPage();
  319. }
  320. $content->printPage();
  321. } catch (\Exception $e) {
  322. $logger = \OC::$server->getLogger();
  323. $logger->logException($exception, ['app' => 'core']);
  324. $logger->logException($e, ['app' => 'core']);
  325. header(self::getHttpProtocol() . ' 500 Internal Server Error');
  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. }
  332. die();
  333. }
  334. /**
  335. * This is only here to reduce the dependencies in case of an exception to
  336. * still be able to print a plain error message.
  337. *
  338. * Returns the used HTTP protocol.
  339. *
  340. * @return string HTTP protocol. HTTP/2, HTTP/1.1 or HTTP/1.0.
  341. * @internal Don't use this - use AppFramework\Http\Request->getHttpProtocol instead
  342. */
  343. protected static function getHttpProtocol() {
  344. $claimedProtocol = strtoupper($_SERVER['SERVER_PROTOCOL']);
  345. $validProtocols = [
  346. 'HTTP/1.0',
  347. 'HTTP/1.1',
  348. 'HTTP/2',
  349. ];
  350. if(in_array($claimedProtocol, $validProtocols, true)) {
  351. return $claimedProtocol;
  352. }
  353. return 'HTTP/1.1';
  354. }
  355. /**
  356. * @return bool
  357. */
  358. public static function isAssetPipelineEnabled() {
  359. try {
  360. if (\OCP\Util::needUpgrade()) {
  361. // Don't use the compiled asset when we need to do an update
  362. return false;
  363. }
  364. } catch (\Exception $e) {
  365. // Catch any exception, because this code is also called when displaying
  366. // an exception error page.
  367. return false;
  368. }
  369. // asset management enabled?
  370. $config = \OC::$server->getConfig();
  371. $useAssetPipeline = $config->getSystemValue('asset-pipeline.enabled', false);
  372. if (!$useAssetPipeline) {
  373. return false;
  374. }
  375. // assets folder exists?
  376. $assetDir = $config->getSystemValue('assetdirectory', \OC::$SERVERROOT) . '/assets';
  377. if (!is_dir($assetDir)) {
  378. if (!mkdir($assetDir)) {
  379. \OCP\Util::writeLog('assets',
  380. "Folder <$assetDir> does not exist and/or could not be generated.", \OCP\Util::ERROR);
  381. return false;
  382. }
  383. }
  384. // assets folder can be accessed?
  385. if (!touch($assetDir."/.oc")) {
  386. \OCP\Util::writeLog('assets',
  387. "Folder <$assetDir> could not be accessed.", \OCP\Util::ERROR);
  388. return false;
  389. }
  390. return $useAssetPipeline;
  391. }
  392. }