template.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432
  1. <?php
  2. /**
  3. * @copyright Copyright (c) 2016, ownCloud, Inc.
  4. *
  5. * @author Adam Williamson <awilliam@redhat.com>
  6. * @author Bart Visscher <bartv@thisnet.nl>
  7. * @author Bjoern Schiessle <bjoern@schiessle.org>
  8. * @author Brice Maron <brice@bmaron.net>
  9. * @author Frank Karlitschek <frank@karlitschek.de>
  10. * @author Hendrik Leppelsack <hendrik@leppelsack.de>
  11. * @author Individual IT Services <info@individual-it.net>
  12. * @author Jakob Sack <mail@jakobsack.de>
  13. * @author Joas Schilling <coding@schilljs.com>
  14. * @author Jörn Friedrich Dreyer <jfd@butonic.de>
  15. * @author Lukas Reschke <lukas@statuscode.ch>
  16. * @author Morris Jobke <hey@morrisjobke.de>
  17. * @author Raghu Nayyar <hey@raghunayyar.com>
  18. * @author Robin Appelman <robin@icewind.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. require_once __DIR__.'/template/functions.php';
  38. /**
  39. * This class provides the templates for ownCloud.
  40. */
  41. class OC_Template extends \OC\Template\Base {
  42. /** @var string */
  43. private $renderAs; // Create a full page?
  44. /** @var string */
  45. private $path; // The path to the template
  46. /** @var array */
  47. private $headers = array(); //custom headers
  48. /** @var string */
  49. protected $app; // app id
  50. protected static $initTemplateEngineFirstRun = true;
  51. /**
  52. * Constructor
  53. *
  54. * @param string $app app providing the template
  55. * @param string $name of the template file (without suffix)
  56. * @param string $renderAs If $renderAs is set, OC_Template will try to
  57. * produce a full page in the according layout. For
  58. * now, $renderAs can be set to "guest", "user" or
  59. * "admin".
  60. * @param bool $registerCall = true
  61. */
  62. public function __construct( $app, $name, $renderAs = "", $registerCall = true ) {
  63. // Read the selected theme from the config file
  64. self::initTemplateEngine($renderAs);
  65. $theme = OC_Util::getTheme();
  66. $requestToken = (OC::$server->getSession() && $registerCall) ? \OCP\Util::callRegister() : '';
  67. $parts = explode('/', $app); // fix translation when app is something like core/lostpassword
  68. $l10n = \OC::$server->getL10N($parts[0]);
  69. $themeDefaults = \OC::$server->getThemingDefaults();
  70. list($path, $template) = $this->findTemplate($theme, $app, $name);
  71. // Set the private data
  72. $this->renderAs = $renderAs;
  73. $this->path = $path;
  74. $this->app = $app;
  75. parent::__construct($template, $requestToken, $l10n, $themeDefaults);
  76. }
  77. /**
  78. * @param string $renderAs
  79. */
  80. public static function initTemplateEngine($renderAs) {
  81. if (self::$initTemplateEngineFirstRun){
  82. //apps that started before the template initialization can load their own scripts/styles
  83. //so to make sure this scripts/styles here are loaded first we use OC_Util::addScript() with $prepend=true
  84. //meaning the last script/style in this list will be loaded first
  85. if (\OC::$server->getSystemConfig()->getValue ('installed', false) && $renderAs !== 'error' && !\OCP\Util::needUpgrade()) {
  86. if (\OC::$server->getConfig ()->getAppValue ( 'core', 'backgroundjobs_mode', 'ajax' ) == 'ajax') {
  87. OC_Util::addScript ( 'backgroundjobs', null, true );
  88. }
  89. }
  90. OC_Util::addStyle("tooltip",null,true);
  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("multiselect",null,true);
  94. OC_Util::addStyle("fixes",null,true);
  95. OC_Util::addStyle("global",null,true);
  96. OC_Util::addStyle("apps",null,true);
  97. OC_Util::addStyle("fonts",null,true);
  98. OC_Util::addStyle("icons",null,true);
  99. OC_Util::addStyle("mobile",null,true);
  100. OC_Util::addStyle("header",null,true);
  101. OC_Util::addStyle("inputs",null,true);
  102. OC_Util::addStyle("styles",null,true);
  103. // avatars
  104. if (\OC::$server->getSystemConfig()->getValue('enable_avatars', true) === true) {
  105. \OC_Util::addScript('jquery.avatar', null, true);
  106. \OC_Util::addScript('placeholder', null, true);
  107. }
  108. OC_Util::addScript('oc-backbone', null, true);
  109. OC_Util::addVendorScript('core', 'backbone/backbone', true);
  110. OC_Util::addVendorScript('snapjs/dist/latest/snap', null, true);
  111. OC_Util::addScript('mimetypelist', null, true);
  112. OC_Util::addScript('mimetype', null, true);
  113. OC_Util::addScript("apps", null, true);
  114. OC_Util::addScript("oc-requesttoken", null, true);
  115. OC_Util::addScript('search', 'search', true);
  116. OC_Util::addScript("config", null, true);
  117. OC_Util::addScript("eventsource", null, true);
  118. OC_Util::addScript("octemplate", null, true);
  119. OC_Util::addTranslations("core", null, true);
  120. OC_Util::addScript("l10n", null, true);
  121. OC_Util::addScript("js", null, true);
  122. OC_Util::addScript("oc-dialogs", null, true);
  123. OC_Util::addScript("jquery.ocdialog", null, true);
  124. OC_Util::addStyle("jquery.ocdialog");
  125. OC_Util::addScript("compatibility", null, true);
  126. OC_Util::addScript("placeholders", null, true);
  127. OC_Util::addScript('files/fileinfo');
  128. OC_Util::addScript('files/client');
  129. // Add the stuff we need always
  130. // following logic will import all vendor libraries that are
  131. // specified in core/js/core.json
  132. $fileContent = file_get_contents(OC::$SERVERROOT . '/core/js/core.json');
  133. if($fileContent !== false) {
  134. $coreDependencies = json_decode($fileContent, true);
  135. foreach(array_reverse($coreDependencies['vendor']) as $vendorLibrary) {
  136. // remove trailing ".js" as addVendorScript will append it
  137. OC_Util::addVendorScript(
  138. substr($vendorLibrary, 0, strlen($vendorLibrary) - 3),null,true);
  139. }
  140. } else {
  141. throw new \Exception('Cannot read core/js/core.json');
  142. }
  143. if (\OC::$server->getRequest()->isUserAgent([\OC\AppFramework\Http\Request::USER_AGENT_IE])) {
  144. // polyfill for btoa/atob for IE friends
  145. OC_Util::addVendorScript('base64/base64');
  146. // shim for the davclient.js library
  147. \OCP\Util::addScript('files/iedavclient');
  148. }
  149. self::$initTemplateEngineFirstRun = false;
  150. }
  151. }
  152. /**
  153. * find the template with the given name
  154. * @param string $name of the template file (without suffix)
  155. *
  156. * Will select the template file for the selected theme.
  157. * Checking all the possible locations.
  158. * @param string $theme
  159. * @param string $app
  160. * @return string[]
  161. */
  162. protected function findTemplate($theme, $app, $name) {
  163. // Check if it is a app template or not.
  164. if( $app !== '' ) {
  165. $dirs = $this->getAppTemplateDirs($theme, $app, OC::$SERVERROOT, OC_App::getAppPath($app));
  166. } else {
  167. $dirs = $this->getCoreTemplateDirs($theme, OC::$SERVERROOT);
  168. }
  169. $locator = new \OC\Template\TemplateFileLocator( $dirs );
  170. $template = $locator->find($name);
  171. $path = $locator->getPath();
  172. return array($path, $template);
  173. }
  174. /**
  175. * Add a custom element to the header
  176. * @param string $tag tag name of the element
  177. * @param array $attributes array of attributes for the element
  178. * @param string $text the text content for the element. If $text is null then the
  179. * element will be written as empty element. So use "" to get a closing tag.
  180. */
  181. public function addHeader($tag, $attributes, $text=null) {
  182. $this->headers[]= array(
  183. 'tag' => $tag,
  184. 'attributes' => $attributes,
  185. 'text' => $text
  186. );
  187. }
  188. /**
  189. * Process the template
  190. * @return boolean|string
  191. *
  192. * This function process the template. If $this->renderAs is set, it
  193. * will produce a full page.
  194. */
  195. public function fetchPage() {
  196. $data = parent::fetchPage();
  197. if( $this->renderAs ) {
  198. $page = new \OC\TemplateLayout($this->renderAs, $this->app);
  199. // Add custom headers
  200. $headers = '';
  201. foreach(OC_Util::$headers as $header) {
  202. $headers .= '<'.\OCP\Util::sanitizeHTML($header['tag']);
  203. foreach($header['attributes'] as $name=>$value) {
  204. $headers .= ' '.\OCP\Util::sanitizeHTML($name).'="'.\OCP\Util::sanitizeHTML($value).'"';
  205. }
  206. if ($header['text'] !== null) {
  207. $headers .= '>'.\OCP\Util::sanitizeHTML($header['text']).'</'.\OCP\Util::sanitizeHTML($header['tag']).'>';
  208. } else {
  209. $headers .= '/>';
  210. }
  211. }
  212. $page->assign('headers', $headers);
  213. $page->assign('content', $data);
  214. return $page->fetchPage();
  215. }
  216. return $data;
  217. }
  218. /**
  219. * Include template
  220. *
  221. * @param string $file
  222. * @param array|null $additionalParams
  223. * @return string returns content of included template
  224. *
  225. * Includes another template. use <?php echo $this->inc('template'); ?> to
  226. * do this.
  227. */
  228. public function inc( $file, $additionalParams = null ) {
  229. return $this->load($this->path.$file.'.php', $additionalParams);
  230. }
  231. /**
  232. * Shortcut to print a simple page for users
  233. * @param string $application The application we render the template for
  234. * @param string $name Name of the template
  235. * @param array $parameters Parameters for the template
  236. * @return boolean|null
  237. */
  238. public static function printUserPage( $application, $name, $parameters = array() ) {
  239. $content = new OC_Template( $application, $name, "user" );
  240. foreach( $parameters as $key => $value ) {
  241. $content->assign( $key, $value );
  242. }
  243. print $content->printPage();
  244. }
  245. /**
  246. * Shortcut to print a simple page for admins
  247. * @param string $application The application we render the template for
  248. * @param string $name Name of the template
  249. * @param array $parameters Parameters for the template
  250. * @return bool
  251. */
  252. public static function printAdminPage( $application, $name, $parameters = array() ) {
  253. $content = new OC_Template( $application, $name, "admin" );
  254. foreach( $parameters as $key => $value ) {
  255. $content->assign( $key, $value );
  256. }
  257. return $content->printPage();
  258. }
  259. /**
  260. * Shortcut to print a simple page for guests
  261. * @param string $application The application we render the template for
  262. * @param string $name Name of the template
  263. * @param array|string $parameters Parameters for the template
  264. * @return bool
  265. */
  266. public static function printGuestPage( $application, $name, $parameters = array() ) {
  267. $content = new OC_Template( $application, $name, "guest" );
  268. foreach( $parameters as $key => $value ) {
  269. $content->assign( $key, $value );
  270. }
  271. return $content->printPage();
  272. }
  273. /**
  274. * Print a fatal error page and terminates the script
  275. * @param string $error_msg The error message to show
  276. * @param string $hint An optional hint message - needs to be properly escaped
  277. */
  278. public static function printErrorPage( $error_msg, $hint = '' ) {
  279. try {
  280. $content = new \OC_Template( '', 'error', 'error', false );
  281. $errors = array(array('error' => $error_msg, 'hint' => $hint));
  282. $content->assign( 'errors', $errors );
  283. $content->printPage();
  284. } catch (\Exception $e) {
  285. $logger = \OC::$server->getLogger();
  286. $logger->error("$error_msg $hint", ['app' => 'core']);
  287. $logger->logException($e, ['app' => 'core']);
  288. header(self::getHttpProtocol() . ' 500 Internal Server Error');
  289. header('Content-Type: text/plain; charset=utf-8');
  290. print("$error_msg $hint");
  291. }
  292. die();
  293. }
  294. /**
  295. * print error page using Exception details
  296. * @param Exception $exception
  297. */
  298. public static function printExceptionErrorPage($exception, $fetchPage = false) {
  299. try {
  300. $request = \OC::$server->getRequest();
  301. $content = new \OC_Template('', 'exception', 'error', false);
  302. $content->assign('errorClass', get_class($exception));
  303. $content->assign('errorMsg', $exception->getMessage());
  304. $content->assign('errorCode', $exception->getCode());
  305. $content->assign('file', $exception->getFile());
  306. $content->assign('line', $exception->getLine());
  307. $content->assign('trace', $exception->getTraceAsString());
  308. $content->assign('debugMode', \OC::$server->getSystemConfig()->getValue('debug', false));
  309. $content->assign('remoteAddr', $request->getRemoteAddress());
  310. $content->assign('requestID', $request->getId());
  311. if ($fetchPage) {
  312. return $content->fetchPage();
  313. }
  314. $content->printPage();
  315. } catch (\Exception $e) {
  316. $logger = \OC::$server->getLogger();
  317. $logger->logException($exception, ['app' => 'core']);
  318. $logger->logException($e, ['app' => 'core']);
  319. header(self::getHttpProtocol() . ' 500 Internal Server Error');
  320. header('Content-Type: text/plain; charset=utf-8');
  321. print("Internal Server Error\n\n");
  322. print("The server encountered an internal error and was unable to complete your request.\n");
  323. print("Please contact the server administrator if this error reappears multiple times, please include the technical details below in your report.\n");
  324. print("More details can be found in the server log.\n");
  325. }
  326. die();
  327. }
  328. /**
  329. * This is only here to reduce the dependencies in case of an exception to
  330. * still be able to print a plain error message.
  331. *
  332. * Returns the used HTTP protocol.
  333. *
  334. * @return string HTTP protocol. HTTP/2, HTTP/1.1 or HTTP/1.0.
  335. * @internal Don't use this - use AppFramework\Http\Request->getHttpProtocol instead
  336. */
  337. protected static function getHttpProtocol() {
  338. $claimedProtocol = strtoupper($_SERVER['SERVER_PROTOCOL']);
  339. $validProtocols = [
  340. 'HTTP/1.0',
  341. 'HTTP/1.1',
  342. 'HTTP/2',
  343. ];
  344. if(in_array($claimedProtocol, $validProtocols, true)) {
  345. return $claimedProtocol;
  346. }
  347. return 'HTTP/1.1';
  348. }
  349. /**
  350. * @return bool
  351. */
  352. public static function isAssetPipelineEnabled() {
  353. try {
  354. if (\OCP\Util::needUpgrade()) {
  355. // Don't use the compiled asset when we need to do an update
  356. return false;
  357. }
  358. } catch (\Exception $e) {
  359. // Catch any exception, because this code is also called when displaying
  360. // an exception error page.
  361. return false;
  362. }
  363. // asset management enabled?
  364. $config = \OC::$server->getConfig();
  365. $useAssetPipeline = $config->getSystemValue('asset-pipeline.enabled', false);
  366. if (!$useAssetPipeline) {
  367. return false;
  368. }
  369. // assets folder exists?
  370. $assetDir = $config->getSystemValue('assetdirectory', \OC::$SERVERROOT) . '/assets';
  371. if (!is_dir($assetDir)) {
  372. if (!mkdir($assetDir)) {
  373. \OCP\Util::writeLog('assets',
  374. "Folder <$assetDir> does not exist and/or could not be generated.", \OCP\Util::ERROR);
  375. return false;
  376. }
  377. }
  378. // assets folder can be accessed?
  379. if (!touch($assetDir."/.oc")) {
  380. \OCP\Util::writeLog('assets',
  381. "Folder <$assetDir> could not be accessed.", \OCP\Util::ERROR);
  382. return false;
  383. }
  384. return $useAssetPipeline;
  385. }
  386. }