Passed
Push — master ( dfcb49...cae849 )
by Joas
11:45 queued 11s
created
lib/public/AppFramework/Http/TemplateResponse.php 2 patches
Indentation   +165 added lines, -165 removed lines patch added patch discarded remove patch
@@ -38,169 +38,169 @@
 block discarded – undo
38 38
  * @since 6.0.0
39 39
  */
40 40
 class TemplateResponse extends Response {
41
-	/**
42
-	 * @since 20.0.0
43
-	 */
44
-	public const RENDER_AS_GUEST = 'guest';
45
-	/**
46
-	 * @since 20.0.0
47
-	 */
48
-	public const RENDER_AS_BLANK = '';
49
-	/**
50
-	 * @since 20.0.0
51
-	 */
52
-	public const RENDER_AS_USER = 'user';
53
-	/**
54
-	 * @since 20.0.0
55
-	 */
56
-	public const RENDER_AS_ERROR = 'error';
57
-	/**
58
-	 * @since 20.0.0
59
-	 */
60
-	public const RENDER_AS_PUBLIC = 'public';
61
-
62
-	/**
63
-	 * @deprecated 20.0.0 use OCP\AppFramework\Http\Events\BeforeTemplateRenderedEvent
64
-	 */
65
-	public const EVENT_LOAD_ADDITIONAL_SCRIPTS = self::class . '::loadAdditionalScripts';
66
-	/**
67
-	 * @deprecated 20.0.0 use OCP\AppFramework\Http\Events\BeforeTemplateRenderedEvent
68
-	 */
69
-	public const EVENT_LOAD_ADDITIONAL_SCRIPTS_LOGGEDIN = self::class . '::loadAdditionalScriptsLoggedIn';
70
-
71
-	/**
72
-	 * name of the template
73
-	 * @var string
74
-	 */
75
-	protected $templateName;
76
-
77
-	/**
78
-	 * parameters
79
-	 * @var array
80
-	 */
81
-	protected $params;
82
-
83
-	/**
84
-	 * rendering type (admin, user, blank)
85
-	 * @var string
86
-	 */
87
-	protected $renderAs;
88
-
89
-	/**
90
-	 * app name
91
-	 * @var string
92
-	 */
93
-	protected $appName;
94
-
95
-	/**
96
-	 * constructor of TemplateResponse
97
-	 * @param string $appName the name of the app to load the template from
98
-	 * @param string $templateName the name of the template
99
-	 * @param array $params an array of parameters which should be passed to the
100
-	 * template
101
-	 * @param string $renderAs how the page should be rendered, defaults to user
102
-	 * @since 6.0.0 - parameters $params and $renderAs were added in 7.0.0
103
-	 */
104
-	public function __construct($appName, $templateName, array $params=[],
105
-								$renderAs = self::RENDER_AS_USER) {
106
-		parent::__construct();
107
-
108
-		$this->templateName = $templateName;
109
-		$this->appName = $appName;
110
-		$this->params = $params;
111
-		$this->renderAs = $renderAs;
112
-
113
-		$this->setContentSecurityPolicy(new ContentSecurityPolicy());
114
-		$this->setFeaturePolicy(new FeaturePolicy());
115
-	}
116
-
117
-
118
-	/**
119
-	 * Sets template parameters
120
-	 * @param array $params an array with key => value structure which sets template
121
-	 *                      variables
122
-	 * @return TemplateResponse Reference to this object
123
-	 * @since 6.0.0 - return value was added in 7.0.0
124
-	 */
125
-	public function setParams(array $params) {
126
-		$this->params = $params;
127
-
128
-		return $this;
129
-	}
130
-
131
-
132
-	/**
133
-	 * Used for accessing the set parameters
134
-	 * @return array the params
135
-	 * @since 6.0.0
136
-	 */
137
-	public function getParams() {
138
-		return $this->params;
139
-	}
140
-
141
-
142
-	/**
143
-	 * Used for accessing the name of the set template
144
-	 * @return string the name of the used template
145
-	 * @since 6.0.0
146
-	 */
147
-	public function getTemplateName() {
148
-		return $this->templateName;
149
-	}
150
-
151
-
152
-	/**
153
-	 * Sets the template page
154
-	 * @param string $renderAs admin, user or blank. Admin also prints the admin
155
-	 *                         settings header and footer, user renders the normal
156
-	 *                         normal page including footer and header and blank
157
-	 *                         just renders the plain template
158
-	 * @return TemplateResponse Reference to this object
159
-	 * @since 6.0.0 - return value was added in 7.0.0
160
-	 */
161
-	public function renderAs($renderAs) {
162
-		$this->renderAs = $renderAs;
163
-
164
-		return $this;
165
-	}
166
-
167
-
168
-	/**
169
-	 * Returns the set renderAs
170
-	 * @return string the renderAs value
171
-	 * @since 6.0.0
172
-	 */
173
-	public function getRenderAs() {
174
-		return $this->renderAs;
175
-	}
176
-
177
-
178
-	/**
179
-	 * Returns the rendered html
180
-	 * @return string the rendered html
181
-	 * @since 6.0.0
182
-	 */
183
-	public function render() {
184
-		$renderAs = self::RENDER_AS_USER;
185
-		if ($this->renderAs === 'blank') {
186
-			// Legacy fallback as \OCP\Template needs an empty string instead of 'blank' for an unwrapped response
187
-			$renderAs = self::RENDER_AS_BLANK;
188
-		} elseif (in_array($this->renderAs, [
189
-			self::RENDER_AS_GUEST,
190
-			self::RENDER_AS_BLANK,
191
-			self::RENDER_AS_ERROR,
192
-			self::RENDER_AS_PUBLIC,
193
-			self::RENDER_AS_USER], true)) {
194
-			$renderAs = $this->renderAs;
195
-		}
196
-
197
-		\OCP\Util::addHeader('meta', ['name' => 'robots', 'content' => 'noindex, nofollow']);
198
-		$template = new \OCP\Template($this->appName, $this->templateName, $renderAs);
199
-
200
-		foreach ($this->params as $key => $value) {
201
-			$template->assign($key, $value);
202
-		}
203
-
204
-		return $template->fetchPage($this->params);
205
-	}
41
+    /**
42
+     * @since 20.0.0
43
+     */
44
+    public const RENDER_AS_GUEST = 'guest';
45
+    /**
46
+     * @since 20.0.0
47
+     */
48
+    public const RENDER_AS_BLANK = '';
49
+    /**
50
+     * @since 20.0.0
51
+     */
52
+    public const RENDER_AS_USER = 'user';
53
+    /**
54
+     * @since 20.0.0
55
+     */
56
+    public const RENDER_AS_ERROR = 'error';
57
+    /**
58
+     * @since 20.0.0
59
+     */
60
+    public const RENDER_AS_PUBLIC = 'public';
61
+
62
+    /**
63
+     * @deprecated 20.0.0 use OCP\AppFramework\Http\Events\BeforeTemplateRenderedEvent
64
+     */
65
+    public const EVENT_LOAD_ADDITIONAL_SCRIPTS = self::class . '::loadAdditionalScripts';
66
+    /**
67
+     * @deprecated 20.0.0 use OCP\AppFramework\Http\Events\BeforeTemplateRenderedEvent
68
+     */
69
+    public const EVENT_LOAD_ADDITIONAL_SCRIPTS_LOGGEDIN = self::class . '::loadAdditionalScriptsLoggedIn';
70
+
71
+    /**
72
+     * name of the template
73
+     * @var string
74
+     */
75
+    protected $templateName;
76
+
77
+    /**
78
+     * parameters
79
+     * @var array
80
+     */
81
+    protected $params;
82
+
83
+    /**
84
+     * rendering type (admin, user, blank)
85
+     * @var string
86
+     */
87
+    protected $renderAs;
88
+
89
+    /**
90
+     * app name
91
+     * @var string
92
+     */
93
+    protected $appName;
94
+
95
+    /**
96
+     * constructor of TemplateResponse
97
+     * @param string $appName the name of the app to load the template from
98
+     * @param string $templateName the name of the template
99
+     * @param array $params an array of parameters which should be passed to the
100
+     * template
101
+     * @param string $renderAs how the page should be rendered, defaults to user
102
+     * @since 6.0.0 - parameters $params and $renderAs were added in 7.0.0
103
+     */
104
+    public function __construct($appName, $templateName, array $params=[],
105
+                                $renderAs = self::RENDER_AS_USER) {
106
+        parent::__construct();
107
+
108
+        $this->templateName = $templateName;
109
+        $this->appName = $appName;
110
+        $this->params = $params;
111
+        $this->renderAs = $renderAs;
112
+
113
+        $this->setContentSecurityPolicy(new ContentSecurityPolicy());
114
+        $this->setFeaturePolicy(new FeaturePolicy());
115
+    }
116
+
117
+
118
+    /**
119
+     * Sets template parameters
120
+     * @param array $params an array with key => value structure which sets template
121
+     *                      variables
122
+     * @return TemplateResponse Reference to this object
123
+     * @since 6.0.0 - return value was added in 7.0.0
124
+     */
125
+    public function setParams(array $params) {
126
+        $this->params = $params;
127
+
128
+        return $this;
129
+    }
130
+
131
+
132
+    /**
133
+     * Used for accessing the set parameters
134
+     * @return array the params
135
+     * @since 6.0.0
136
+     */
137
+    public function getParams() {
138
+        return $this->params;
139
+    }
140
+
141
+
142
+    /**
143
+     * Used for accessing the name of the set template
144
+     * @return string the name of the used template
145
+     * @since 6.0.0
146
+     */
147
+    public function getTemplateName() {
148
+        return $this->templateName;
149
+    }
150
+
151
+
152
+    /**
153
+     * Sets the template page
154
+     * @param string $renderAs admin, user or blank. Admin also prints the admin
155
+     *                         settings header and footer, user renders the normal
156
+     *                         normal page including footer and header and blank
157
+     *                         just renders the plain template
158
+     * @return TemplateResponse Reference to this object
159
+     * @since 6.0.0 - return value was added in 7.0.0
160
+     */
161
+    public function renderAs($renderAs) {
162
+        $this->renderAs = $renderAs;
163
+
164
+        return $this;
165
+    }
166
+
167
+
168
+    /**
169
+     * Returns the set renderAs
170
+     * @return string the renderAs value
171
+     * @since 6.0.0
172
+     */
173
+    public function getRenderAs() {
174
+        return $this->renderAs;
175
+    }
176
+
177
+
178
+    /**
179
+     * Returns the rendered html
180
+     * @return string the rendered html
181
+     * @since 6.0.0
182
+     */
183
+    public function render() {
184
+        $renderAs = self::RENDER_AS_USER;
185
+        if ($this->renderAs === 'blank') {
186
+            // Legacy fallback as \OCP\Template needs an empty string instead of 'blank' for an unwrapped response
187
+            $renderAs = self::RENDER_AS_BLANK;
188
+        } elseif (in_array($this->renderAs, [
189
+            self::RENDER_AS_GUEST,
190
+            self::RENDER_AS_BLANK,
191
+            self::RENDER_AS_ERROR,
192
+            self::RENDER_AS_PUBLIC,
193
+            self::RENDER_AS_USER], true)) {
194
+            $renderAs = $this->renderAs;
195
+        }
196
+
197
+        \OCP\Util::addHeader('meta', ['name' => 'robots', 'content' => 'noindex, nofollow']);
198
+        $template = new \OCP\Template($this->appName, $this->templateName, $renderAs);
199
+
200
+        foreach ($this->params as $key => $value) {
201
+            $template->assign($key, $value);
202
+        }
203
+
204
+        return $template->fetchPage($this->params);
205
+    }
206 206
 }
Please login to merge, or discard this patch.
Spacing   +3 added lines, -3 removed lines patch added patch discarded remove patch
@@ -62,11 +62,11 @@  discard block
 block discarded – undo
62 62
 	/**
63 63
 	 * @deprecated 20.0.0 use OCP\AppFramework\Http\Events\BeforeTemplateRenderedEvent
64 64
 	 */
65
-	public const EVENT_LOAD_ADDITIONAL_SCRIPTS = self::class . '::loadAdditionalScripts';
65
+	public const EVENT_LOAD_ADDITIONAL_SCRIPTS = self::class.'::loadAdditionalScripts';
66 66
 	/**
67 67
 	 * @deprecated 20.0.0 use OCP\AppFramework\Http\Events\BeforeTemplateRenderedEvent
68 68
 	 */
69
-	public const EVENT_LOAD_ADDITIONAL_SCRIPTS_LOGGEDIN = self::class . '::loadAdditionalScriptsLoggedIn';
69
+	public const EVENT_LOAD_ADDITIONAL_SCRIPTS_LOGGEDIN = self::class.'::loadAdditionalScriptsLoggedIn';
70 70
 
71 71
 	/**
72 72
 	 * name of the template
@@ -101,7 +101,7 @@  discard block
 block discarded – undo
101 101
 	 * @param string $renderAs how the page should be rendered, defaults to user
102 102
 	 * @since 6.0.0 - parameters $params and $renderAs were added in 7.0.0
103 103
 	 */
104
-	public function __construct($appName, $templateName, array $params=[],
104
+	public function __construct($appName, $templateName, array $params = [],
105 105
 								$renderAs = self::RENDER_AS_USER) {
106 106
 		parent::__construct();
107 107
 
Please login to merge, or discard this patch.
lib/private/legacy/OC_Template.php 1 patch
Indentation   +310 added lines, -310 removed lines patch added patch discarded remove patch
@@ -48,314 +48,314 @@
 block discarded – undo
48 48
  */
49 49
 class OC_Template extends \OC\Template\Base {
50 50
 
51
-	/** @var string */
52
-	private $renderAs; // Create a full page?
53
-
54
-	/** @var string */
55
-	private $path; // The path to the template
56
-
57
-	/** @var array */
58
-	private $headers = []; //custom headers
59
-
60
-	/** @var string */
61
-	protected $app; // app id
62
-
63
-	protected static $initTemplateEngineFirstRun = true;
64
-
65
-	/**
66
-	 * Constructor
67
-	 *
68
-	 * @param string $app app providing the template
69
-	 * @param string $name of the template file (without suffix)
70
-	 * @param string $renderAs If $renderAs is set, OC_Template will try to
71
-	 *                         produce a full page in the according layout. For
72
-	 *                         now, $renderAs can be set to "guest", "user" or
73
-	 *                         "admin".
74
-	 * @param bool $registerCall = true
75
-	 */
76
-	public function __construct($app, $name, $renderAs = TemplateResponse::RENDER_AS_BLANK, $registerCall = true) {
77
-		// Read the selected theme from the config file
78
-		self::initTemplateEngine($renderAs);
79
-
80
-		$theme = OC_Util::getTheme();
81
-
82
-		$requestToken = (OC::$server->getSession() && $registerCall) ? \OCP\Util::callRegister() : '';
83
-
84
-		$parts = explode('/', $app); // fix translation when app is something like core/lostpassword
85
-		$l10n = \OC::$server->getL10N($parts[0]);
86
-		/** @var \OCP\Defaults $themeDefaults */
87
-		$themeDefaults = \OC::$server->query(\OCP\Defaults::class);
88
-
89
-		list($path, $template) = $this->findTemplate($theme, $app, $name);
90
-
91
-		// Set the private data
92
-		$this->renderAs = $renderAs;
93
-		$this->path = $path;
94
-		$this->app = $app;
95
-
96
-		parent::__construct($template, $requestToken, $l10n, $themeDefaults);
97
-	}
98
-
99
-	/**
100
-	 * @param string $renderAs
101
-	 */
102
-	public static function initTemplateEngine($renderAs) {
103
-		if (self::$initTemplateEngineFirstRun) {
104
-
105
-			//apps that started before the template initialization can load their own scripts/styles
106
-			//so to make sure this scripts/styles here are loaded first we use OC_Util::addScript() with $prepend=true
107
-			//meaning the last script/style in this list will be loaded first
108
-			if (\OC::$server->getSystemConfig()->getValue('installed', false) && $renderAs !== TemplateResponse::RENDER_AS_ERROR && !\OCP\Util::needUpgrade()) {
109
-				if (\OC::$server->getConfig()->getAppValue('core', 'backgroundjobs_mode', 'ajax') == 'ajax') {
110
-					OC_Util::addScript('backgroundjobs', null, true);
111
-				}
112
-			}
113
-			OC_Util::addStyle('css-variables', null, true);
114
-			OC_Util::addStyle('server', null, true);
115
-			OC_Util::addTranslations('core', null, true);
116
-
117
-			if (\OC::$server->getSystemConfig()->getValue('installed', false)) {
118
-				OC_Util::addStyle('search', 'results');
119
-				OC_Util::addScript('search', 'search', true);
120
-				OC_Util::addScript('search', 'searchprovider');
121
-				OC_Util::addScript('merged-template-prepend', null, true);
122
-				OC_Util::addScript('dist/files_client', null, true);
123
-				OC_Util::addScript('dist/files_fileinfo', null, true);
124
-			}
125
-			OC_Util::addScript('core', 'dist/main', true);
126
-
127
-			if (\OC::$server->getRequest()->isUserAgent([\OC\AppFramework\Http\Request::USER_AGENT_IE])) {
128
-				// shim for the davclient.js library
129
-				\OCP\Util::addScript('dist/files_iedavclient');
130
-			}
131
-
132
-			self::$initTemplateEngineFirstRun = false;
133
-		}
134
-	}
135
-
136
-
137
-	/**
138
-	 * find the template with the given name
139
-	 * @param string $name of the template file (without suffix)
140
-	 *
141
-	 * Will select the template file for the selected theme.
142
-	 * Checking all the possible locations.
143
-	 * @param string $theme
144
-	 * @param string $app
145
-	 * @return string[]
146
-	 */
147
-	protected function findTemplate($theme, $app, $name) {
148
-		// Check if it is a app template or not.
149
-		if ($app !== '') {
150
-			$dirs = $this->getAppTemplateDirs($theme, $app, OC::$SERVERROOT, OC_App::getAppPath($app));
151
-		} else {
152
-			$dirs = $this->getCoreTemplateDirs($theme, OC::$SERVERROOT);
153
-		}
154
-		$locator = new \OC\Template\TemplateFileLocator($dirs);
155
-		$template = $locator->find($name);
156
-		$path = $locator->getPath();
157
-		return [$path, $template];
158
-	}
159
-
160
-	/**
161
-	 * Add a custom element to the header
162
-	 * @param string $tag tag name of the element
163
-	 * @param array $attributes array of attributes for the element
164
-	 * @param string $text the text content for the element. If $text is null then the
165
-	 * element will be written as empty element. So use "" to get a closing tag.
166
-	 */
167
-	public function addHeader($tag, $attributes, $text=null) {
168
-		$this->headers[]= [
169
-			'tag' => $tag,
170
-			'attributes' => $attributes,
171
-			'text' => $text
172
-		];
173
-	}
174
-
175
-	/**
176
-	 * Process the template
177
-	 * @return boolean|string
178
-	 *
179
-	 * This function process the template. If $this->renderAs is set, it
180
-	 * will produce a full page.
181
-	 */
182
-	public function fetchPage($additionalParams = null) {
183
-		$data = parent::fetchPage($additionalParams);
184
-
185
-		if ($this->renderAs) {
186
-			$page = new TemplateLayout($this->renderAs, $this->app);
187
-
188
-			if (is_array($additionalParams)) {
189
-				foreach ($additionalParams as $key => $value) {
190
-					$page->assign($key, $value);
191
-				}
192
-			}
193
-
194
-			// Add custom headers
195
-			$headers = '';
196
-			foreach (OC_Util::$headers as $header) {
197
-				$headers .= '<'.\OCP\Util::sanitizeHTML($header['tag']);
198
-				if (strcasecmp($header['tag'], 'script') === 0 && in_array('src', array_map('strtolower', array_keys($header['attributes'])))) {
199
-					$headers .= ' defer';
200
-				}
201
-				foreach ($header['attributes'] as $name=>$value) {
202
-					$headers .= ' '.\OCP\Util::sanitizeHTML($name).'="'.\OCP\Util::sanitizeHTML($value).'"';
203
-				}
204
-				if ($header['text'] !== null) {
205
-					$headers .= '>'.\OCP\Util::sanitizeHTML($header['text']).'</'.\OCP\Util::sanitizeHTML($header['tag']).'>';
206
-				} else {
207
-					$headers .= '/>';
208
-				}
209
-			}
210
-
211
-			$page->assign('headers', $headers);
212
-
213
-			$page->assign('content', $data);
214
-			return $page->fetchPage($additionalParams);
215
-		}
216
-
217
-		return $data;
218
-	}
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
-	/**
235
-	 * Shortcut to print a simple page for users
236
-	 * @param string $application The application we render the template for
237
-	 * @param string $name Name of the template
238
-	 * @param array $parameters Parameters for the template
239
-	 * @return boolean|null
240
-	 */
241
-	public static function printUserPage($application, $name, $parameters = []) {
242
-		$content = new OC_Template($application, $name, "user");
243
-		foreach ($parameters as $key => $value) {
244
-			$content->assign($key, $value);
245
-		}
246
-		print $content->printPage();
247
-	}
248
-
249
-	/**
250
-	 * Shortcut to print a simple page for admins
251
-	 * @param string $application The application we render the template for
252
-	 * @param string $name Name of the template
253
-	 * @param array $parameters Parameters for the template
254
-	 * @return bool
255
-	 */
256
-	public static function printAdminPage($application, $name, $parameters = []) {
257
-		$content = new OC_Template($application, $name, "admin");
258
-		foreach ($parameters as $key => $value) {
259
-			$content->assign($key, $value);
260
-		}
261
-		return $content->printPage();
262
-	}
263
-
264
-	/**
265
-	 * Shortcut to print a simple page for guests
266
-	 * @param string $application The application we render the template for
267
-	 * @param string $name Name of the template
268
-	 * @param array|string $parameters Parameters for the template
269
-	 * @return bool
270
-	 */
271
-	public static function printGuestPage($application, $name, $parameters = []) {
272
-		$content = new OC_Template($application, $name, $name === 'error' ? $name : 'guest');
273
-		foreach ($parameters as $key => $value) {
274
-			$content->assign($key, $value);
275
-		}
276
-		return $content->printPage();
277
-	}
278
-
279
-	/**
280
-	 * Print a fatal error page and terminates the script
281
-	 * @param string $error_msg The error message to show
282
-	 * @param string $hint An optional hint message - needs to be properly escape
283
-	 * @param int $statusCode
284
-	 * @suppress PhanAccessMethodInternal
285
-	 */
286
-	public static function printErrorPage($error_msg, $hint = '', $statusCode = 500) {
287
-		if (\OC::$server->getAppManager()->isEnabledForUser('theming') && !\OC_App::isAppLoaded('theming')) {
288
-			\OC_App::loadApp('theming');
289
-		}
290
-
291
-
292
-		if ($error_msg === $hint) {
293
-			// If the hint is the same as the message there is no need to display it twice.
294
-			$hint = '';
295
-		}
296
-
297
-		http_response_code($statusCode);
298
-		try {
299
-			$content = new \OC_Template('', 'error', 'error', false);
300
-			$errors = [['error' => $error_msg, 'hint' => $hint]];
301
-			$content->assign('errors', $errors);
302
-			$content->printPage();
303
-		} catch (\Exception $e) {
304
-			$logger = \OC::$server->getLogger();
305
-			$logger->error("$error_msg $hint", ['app' => 'core']);
306
-			$logger->logException($e, ['app' => 'core']);
307
-
308
-			header('Content-Type: text/plain; charset=utf-8');
309
-			print("$error_msg $hint");
310
-		}
311
-		die();
312
-	}
313
-
314
-	/**
315
-	 * print error page using Exception details
316
-	 * @param Exception|Throwable $exception
317
-	 * @param int $statusCode
318
-	 * @return bool|string
319
-	 * @suppress PhanAccessMethodInternal
320
-	 */
321
-	public static function printExceptionErrorPage($exception, $statusCode = 503) {
322
-		http_response_code($statusCode);
323
-		try {
324
-			$request = \OC::$server->getRequest();
325
-			$content = new \OC_Template('', 'exception', 'error', false);
326
-			$content->assign('errorClass', get_class($exception));
327
-			$content->assign('errorMsg', $exception->getMessage());
328
-			$content->assign('errorCode', $exception->getCode());
329
-			$content->assign('file', $exception->getFile());
330
-			$content->assign('line', $exception->getLine());
331
-			$content->assign('trace', $exception->getTraceAsString());
332
-			$content->assign('debugMode', \OC::$server->getSystemConfig()->getValue('debug', false));
333
-			$content->assign('remoteAddr', $request->getRemoteAddress());
334
-			$content->assign('requestID', $request->getId());
335
-			$content->printPage();
336
-		} catch (\Exception $e) {
337
-			try {
338
-				$logger = \OC::$server->getLogger();
339
-				$logger->logException($exception, ['app' => 'core']);
340
-				$logger->logException($e, ['app' => 'core']);
341
-			} catch (Throwable $e) {
342
-				// no way to log it properly - but to avoid a white page of death we send some output
343
-				header('Content-Type: text/plain; charset=utf-8');
344
-				print("Internal Server Error\n\n");
345
-				print("The server encountered an internal error and was unable to complete your request.\n");
346
-				print("Please contact the server administrator if this error reappears multiple times, please include the technical details below in your report.\n");
347
-				print("More details can be found in the server log.\n");
348
-
349
-				// and then throw it again to log it at least to the web server error log
350
-				throw $e;
351
-			}
352
-
353
-			header('Content-Type: text/plain; charset=utf-8');
354
-			print("Internal Server Error\n\n");
355
-			print("The server encountered an internal error and was unable to complete your request.\n");
356
-			print("Please contact the server administrator if this error reappears multiple times, please include the technical details below in your report.\n");
357
-			print("More details can be found in the server log.\n");
358
-		}
359
-		die();
360
-	}
51
+    /** @var string */
52
+    private $renderAs; // Create a full page?
53
+
54
+    /** @var string */
55
+    private $path; // The path to the template
56
+
57
+    /** @var array */
58
+    private $headers = []; //custom headers
59
+
60
+    /** @var string */
61
+    protected $app; // app id
62
+
63
+    protected static $initTemplateEngineFirstRun = true;
64
+
65
+    /**
66
+     * Constructor
67
+     *
68
+     * @param string $app app providing the template
69
+     * @param string $name of the template file (without suffix)
70
+     * @param string $renderAs If $renderAs is set, OC_Template will try to
71
+     *                         produce a full page in the according layout. For
72
+     *                         now, $renderAs can be set to "guest", "user" or
73
+     *                         "admin".
74
+     * @param bool $registerCall = true
75
+     */
76
+    public function __construct($app, $name, $renderAs = TemplateResponse::RENDER_AS_BLANK, $registerCall = true) {
77
+        // Read the selected theme from the config file
78
+        self::initTemplateEngine($renderAs);
79
+
80
+        $theme = OC_Util::getTheme();
81
+
82
+        $requestToken = (OC::$server->getSession() && $registerCall) ? \OCP\Util::callRegister() : '';
83
+
84
+        $parts = explode('/', $app); // fix translation when app is something like core/lostpassword
85
+        $l10n = \OC::$server->getL10N($parts[0]);
86
+        /** @var \OCP\Defaults $themeDefaults */
87
+        $themeDefaults = \OC::$server->query(\OCP\Defaults::class);
88
+
89
+        list($path, $template) = $this->findTemplate($theme, $app, $name);
90
+
91
+        // Set the private data
92
+        $this->renderAs = $renderAs;
93
+        $this->path = $path;
94
+        $this->app = $app;
95
+
96
+        parent::__construct($template, $requestToken, $l10n, $themeDefaults);
97
+    }
98
+
99
+    /**
100
+     * @param string $renderAs
101
+     */
102
+    public static function initTemplateEngine($renderAs) {
103
+        if (self::$initTemplateEngineFirstRun) {
104
+
105
+            //apps that started before the template initialization can load their own scripts/styles
106
+            //so to make sure this scripts/styles here are loaded first we use OC_Util::addScript() with $prepend=true
107
+            //meaning the last script/style in this list will be loaded first
108
+            if (\OC::$server->getSystemConfig()->getValue('installed', false) && $renderAs !== TemplateResponse::RENDER_AS_ERROR && !\OCP\Util::needUpgrade()) {
109
+                if (\OC::$server->getConfig()->getAppValue('core', 'backgroundjobs_mode', 'ajax') == 'ajax') {
110
+                    OC_Util::addScript('backgroundjobs', null, true);
111
+                }
112
+            }
113
+            OC_Util::addStyle('css-variables', null, true);
114
+            OC_Util::addStyle('server', null, true);
115
+            OC_Util::addTranslations('core', null, true);
116
+
117
+            if (\OC::$server->getSystemConfig()->getValue('installed', false)) {
118
+                OC_Util::addStyle('search', 'results');
119
+                OC_Util::addScript('search', 'search', true);
120
+                OC_Util::addScript('search', 'searchprovider');
121
+                OC_Util::addScript('merged-template-prepend', null, true);
122
+                OC_Util::addScript('dist/files_client', null, true);
123
+                OC_Util::addScript('dist/files_fileinfo', null, true);
124
+            }
125
+            OC_Util::addScript('core', 'dist/main', true);
126
+
127
+            if (\OC::$server->getRequest()->isUserAgent([\OC\AppFramework\Http\Request::USER_AGENT_IE])) {
128
+                // shim for the davclient.js library
129
+                \OCP\Util::addScript('dist/files_iedavclient');
130
+            }
131
+
132
+            self::$initTemplateEngineFirstRun = false;
133
+        }
134
+    }
135
+
136
+
137
+    /**
138
+     * find the template with the given name
139
+     * @param string $name of the template file (without suffix)
140
+     *
141
+     * Will select the template file for the selected theme.
142
+     * Checking all the possible locations.
143
+     * @param string $theme
144
+     * @param string $app
145
+     * @return string[]
146
+     */
147
+    protected function findTemplate($theme, $app, $name) {
148
+        // Check if it is a app template or not.
149
+        if ($app !== '') {
150
+            $dirs = $this->getAppTemplateDirs($theme, $app, OC::$SERVERROOT, OC_App::getAppPath($app));
151
+        } else {
152
+            $dirs = $this->getCoreTemplateDirs($theme, OC::$SERVERROOT);
153
+        }
154
+        $locator = new \OC\Template\TemplateFileLocator($dirs);
155
+        $template = $locator->find($name);
156
+        $path = $locator->getPath();
157
+        return [$path, $template];
158
+    }
159
+
160
+    /**
161
+     * Add a custom element to the header
162
+     * @param string $tag tag name of the element
163
+     * @param array $attributes array of attributes for the element
164
+     * @param string $text the text content for the element. If $text is null then the
165
+     * element will be written as empty element. So use "" to get a closing tag.
166
+     */
167
+    public function addHeader($tag, $attributes, $text=null) {
168
+        $this->headers[]= [
169
+            'tag' => $tag,
170
+            'attributes' => $attributes,
171
+            'text' => $text
172
+        ];
173
+    }
174
+
175
+    /**
176
+     * Process the template
177
+     * @return boolean|string
178
+     *
179
+     * This function process the template. If $this->renderAs is set, it
180
+     * will produce a full page.
181
+     */
182
+    public function fetchPage($additionalParams = null) {
183
+        $data = parent::fetchPage($additionalParams);
184
+
185
+        if ($this->renderAs) {
186
+            $page = new TemplateLayout($this->renderAs, $this->app);
187
+
188
+            if (is_array($additionalParams)) {
189
+                foreach ($additionalParams as $key => $value) {
190
+                    $page->assign($key, $value);
191
+                }
192
+            }
193
+
194
+            // Add custom headers
195
+            $headers = '';
196
+            foreach (OC_Util::$headers as $header) {
197
+                $headers .= '<'.\OCP\Util::sanitizeHTML($header['tag']);
198
+                if (strcasecmp($header['tag'], 'script') === 0 && in_array('src', array_map('strtolower', array_keys($header['attributes'])))) {
199
+                    $headers .= ' defer';
200
+                }
201
+                foreach ($header['attributes'] as $name=>$value) {
202
+                    $headers .= ' '.\OCP\Util::sanitizeHTML($name).'="'.\OCP\Util::sanitizeHTML($value).'"';
203
+                }
204
+                if ($header['text'] !== null) {
205
+                    $headers .= '>'.\OCP\Util::sanitizeHTML($header['text']).'</'.\OCP\Util::sanitizeHTML($header['tag']).'>';
206
+                } else {
207
+                    $headers .= '/>';
208
+                }
209
+            }
210
+
211
+            $page->assign('headers', $headers);
212
+
213
+            $page->assign('content', $data);
214
+            return $page->fetchPage($additionalParams);
215
+        }
216
+
217
+        return $data;
218
+    }
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
+    /**
235
+     * Shortcut to print a simple page for users
236
+     * @param string $application The application we render the template for
237
+     * @param string $name Name of the template
238
+     * @param array $parameters Parameters for the template
239
+     * @return boolean|null
240
+     */
241
+    public static function printUserPage($application, $name, $parameters = []) {
242
+        $content = new OC_Template($application, $name, "user");
243
+        foreach ($parameters as $key => $value) {
244
+            $content->assign($key, $value);
245
+        }
246
+        print $content->printPage();
247
+    }
248
+
249
+    /**
250
+     * Shortcut to print a simple page for admins
251
+     * @param string $application The application we render the template for
252
+     * @param string $name Name of the template
253
+     * @param array $parameters Parameters for the template
254
+     * @return bool
255
+     */
256
+    public static function printAdminPage($application, $name, $parameters = []) {
257
+        $content = new OC_Template($application, $name, "admin");
258
+        foreach ($parameters as $key => $value) {
259
+            $content->assign($key, $value);
260
+        }
261
+        return $content->printPage();
262
+    }
263
+
264
+    /**
265
+     * Shortcut to print a simple page for guests
266
+     * @param string $application The application we render the template for
267
+     * @param string $name Name of the template
268
+     * @param array|string $parameters Parameters for the template
269
+     * @return bool
270
+     */
271
+    public static function printGuestPage($application, $name, $parameters = []) {
272
+        $content = new OC_Template($application, $name, $name === 'error' ? $name : 'guest');
273
+        foreach ($parameters as $key => $value) {
274
+            $content->assign($key, $value);
275
+        }
276
+        return $content->printPage();
277
+    }
278
+
279
+    /**
280
+     * Print a fatal error page and terminates the script
281
+     * @param string $error_msg The error message to show
282
+     * @param string $hint An optional hint message - needs to be properly escape
283
+     * @param int $statusCode
284
+     * @suppress PhanAccessMethodInternal
285
+     */
286
+    public static function printErrorPage($error_msg, $hint = '', $statusCode = 500) {
287
+        if (\OC::$server->getAppManager()->isEnabledForUser('theming') && !\OC_App::isAppLoaded('theming')) {
288
+            \OC_App::loadApp('theming');
289
+        }
290
+
291
+
292
+        if ($error_msg === $hint) {
293
+            // If the hint is the same as the message there is no need to display it twice.
294
+            $hint = '';
295
+        }
296
+
297
+        http_response_code($statusCode);
298
+        try {
299
+            $content = new \OC_Template('', 'error', 'error', false);
300
+            $errors = [['error' => $error_msg, 'hint' => $hint]];
301
+            $content->assign('errors', $errors);
302
+            $content->printPage();
303
+        } catch (\Exception $e) {
304
+            $logger = \OC::$server->getLogger();
305
+            $logger->error("$error_msg $hint", ['app' => 'core']);
306
+            $logger->logException($e, ['app' => 'core']);
307
+
308
+            header('Content-Type: text/plain; charset=utf-8');
309
+            print("$error_msg $hint");
310
+        }
311
+        die();
312
+    }
313
+
314
+    /**
315
+     * print error page using Exception details
316
+     * @param Exception|Throwable $exception
317
+     * @param int $statusCode
318
+     * @return bool|string
319
+     * @suppress PhanAccessMethodInternal
320
+     */
321
+    public static function printExceptionErrorPage($exception, $statusCode = 503) {
322
+        http_response_code($statusCode);
323
+        try {
324
+            $request = \OC::$server->getRequest();
325
+            $content = new \OC_Template('', 'exception', 'error', false);
326
+            $content->assign('errorClass', get_class($exception));
327
+            $content->assign('errorMsg', $exception->getMessage());
328
+            $content->assign('errorCode', $exception->getCode());
329
+            $content->assign('file', $exception->getFile());
330
+            $content->assign('line', $exception->getLine());
331
+            $content->assign('trace', $exception->getTraceAsString());
332
+            $content->assign('debugMode', \OC::$server->getSystemConfig()->getValue('debug', false));
333
+            $content->assign('remoteAddr', $request->getRemoteAddress());
334
+            $content->assign('requestID', $request->getId());
335
+            $content->printPage();
336
+        } catch (\Exception $e) {
337
+            try {
338
+                $logger = \OC::$server->getLogger();
339
+                $logger->logException($exception, ['app' => 'core']);
340
+                $logger->logException($e, ['app' => 'core']);
341
+            } catch (Throwable $e) {
342
+                // no way to log it properly - but to avoid a white page of death we send some output
343
+                header('Content-Type: text/plain; charset=utf-8');
344
+                print("Internal Server Error\n\n");
345
+                print("The server encountered an internal error and was unable to complete your request.\n");
346
+                print("Please contact the server administrator if this error reappears multiple times, please include the technical details below in your report.\n");
347
+                print("More details can be found in the server log.\n");
348
+
349
+                // and then throw it again to log it at least to the web server error log
350
+                throw $e;
351
+            }
352
+
353
+            header('Content-Type: text/plain; charset=utf-8');
354
+            print("Internal Server Error\n\n");
355
+            print("The server encountered an internal error and was unable to complete your request.\n");
356
+            print("Please contact the server administrator if this error reappears multiple times, please include the technical details below in your report.\n");
357
+            print("More details can be found in the server log.\n");
358
+        }
359
+        die();
360
+    }
361 361
 }
Please login to merge, or discard this patch.
lib/private/TemplateLayout.php 2 patches
Indentation   +306 added lines, -306 removed lines patch added patch discarded remove patch
@@ -54,310 +54,310 @@
 block discarded – undo
54 54
 use OCP\Support\Subscription\IRegistry;
55 55
 
56 56
 class TemplateLayout extends \OC_Template {
57
-	private static $versionHash = '';
58
-
59
-	/**
60
-	 * @var \OCP\IConfig
61
-	 */
62
-	private $config;
63
-
64
-	/**
65
-	 * @param string $renderAs
66
-	 * @param string $appId application id
67
-	 */
68
-	public function __construct($renderAs, $appId = '') {
69
-
70
-		// yes - should be injected ....
71
-		$this->config = \OC::$server->getConfig();
72
-
73
-		if (\OCP\Util::isIE()) {
74
-			\OC_Util::addStyle('ie');
75
-		}
76
-
77
-		// Decide which page we show
78
-		if ($renderAs === TemplateResponse::RENDER_AS_USER) {
79
-			parent::__construct('core', 'layout.user');
80
-			if (in_array(\OC_App::getCurrentApp(), ['settings','admin', 'help']) !== false) {
81
-				$this->assign('bodyid', 'body-settings');
82
-			} else {
83
-				$this->assign('bodyid', 'body-user');
84
-			}
85
-
86
-			// Add navigation entry
87
-			$this->assign('application', '');
88
-			$this->assign('appid', $appId);
89
-			$navigation = \OC::$server->getNavigationManager()->getAll();
90
-			$this->assign('navigation', $navigation);
91
-			$settingsNavigation = \OC::$server->getNavigationManager()->getAll('settings');
92
-			$this->assign('settingsnavigation', $settingsNavigation);
93
-			foreach ($navigation as $entry) {
94
-				if ($entry['active']) {
95
-					$this->assign('application', $entry['name']);
96
-					break;
97
-				}
98
-			}
99
-
100
-			foreach ($settingsNavigation as $entry) {
101
-				if ($entry['active']) {
102
-					$this->assign('application', $entry['name']);
103
-					break;
104
-				}
105
-			}
106
-			$userDisplayName = \OC_User::getDisplayName();
107
-			$this->assign('user_displayname', $userDisplayName);
108
-			$this->assign('user_uid', \OC_User::getUser());
109
-
110
-			if (\OC_User::getUser() === false) {
111
-				$this->assign('userAvatarSet', false);
112
-			} else {
113
-				$this->assign('userAvatarSet', \OC::$server->getAvatarManager()->getAvatar(\OC_User::getUser())->exists());
114
-				$this->assign('userAvatarVersion', $this->config->getUserValue(\OC_User::getUser(), 'avatar', 'version', 0));
115
-			}
116
-
117
-			// check if app menu icons should be inverted
118
-			try {
119
-				/** @var \OCA\Theming\Util $util */
120
-				$util = \OC::$server->query(\OCA\Theming\Util::class);
121
-				$this->assign('themingInvertMenu', $util->invertTextColor(\OC::$server->getThemingDefaults()->getColorPrimary()));
122
-			} catch (\OCP\AppFramework\QueryException $e) {
123
-				$this->assign('themingInvertMenu', false);
124
-			} catch (\OCP\AutoloadNotAllowedException $e) {
125
-				$this->assign('themingInvertMenu', false);
126
-			}
127
-		} elseif ($renderAs === TemplateResponse::RENDER_AS_ERROR) {
128
-			parent::__construct('core', 'layout.guest', '', false);
129
-			$this->assign('bodyid', 'body-login');
130
-			$this->assign('user_displayname', '');
131
-			$this->assign('user_uid', '');
132
-		} elseif ($renderAs === TemplateResponse::RENDER_AS_GUEST) {
133
-			parent::__construct('core', 'layout.guest');
134
-			\OC_Util::addStyle('guest');
135
-			$this->assign('bodyid', 'body-login');
136
-
137
-			$userDisplayName = \OC_User::getDisplayName();
138
-			$this->assign('user_displayname', $userDisplayName);
139
-			$this->assign('user_uid', \OC_User::getUser());
140
-		} elseif ($renderAs === TemplateResponse::RENDER_AS_PUBLIC) {
141
-			parent::__construct('core', 'layout.public');
142
-			$this->assign('appid', $appId);
143
-			$this->assign('bodyid', 'body-public');
144
-
145
-			/** @var IRegistry $subscription */
146
-			$subscription = \OC::$server->query(IRegistry::class);
147
-			$showSimpleSignup = $this->config->getSystemValueBool('simpleSignUpLink.shown', true);
148
-			if ($showSimpleSignup && $subscription->delegateHasValidSubscription()) {
149
-				$showSimpleSignup = false;
150
-			}
151
-			$this->assign('showSimpleSignUpLink', $showSimpleSignup);
152
-		} else {
153
-			parent::__construct('core', 'layout.base');
154
-		}
155
-		// Send the language and the locale to our layouts
156
-		$lang = \OC::$server->getL10NFactory()->findLanguage();
157
-		$locale = \OC::$server->getL10NFactory()->findLocale($lang);
158
-
159
-		$lang = str_replace('_', '-', $lang);
160
-		$this->assign('language', $lang);
161
-		$this->assign('locale', $locale);
162
-
163
-		if (\OC::$server->getSystemConfig()->getValue('installed', false)) {
164
-			if (empty(self::$versionHash)) {
165
-				$v = \OC_App::getAppVersions();
166
-				$v['core'] = implode('.', \OCP\Util::getVersion());
167
-				self::$versionHash = substr(md5(implode(',', $v)), 0, 8);
168
-			}
169
-		} else {
170
-			self::$versionHash = md5('not installed');
171
-		}
172
-
173
-		// Add the js files
174
-		$jsFiles = self::findJavascriptFiles(\OC_Util::$scripts);
175
-		$this->assign('jsfiles', []);
176
-		if ($this->config->getSystemValue('installed', false) && $renderAs != TemplateResponse::RENDER_AS_ERROR) {
177
-			if (\OC::$server->getContentSecurityPolicyNonceManager()->browserSupportsCspV3()) {
178
-				$jsConfigHelper = new JSConfigHelper(
179
-					\OC::$server->getL10N('lib'),
180
-					\OC::$server->query(Defaults::class),
181
-					\OC::$server->getAppManager(),
182
-					\OC::$server->getSession(),
183
-					\OC::$server->getUserSession()->getUser(),
184
-					$this->config,
185
-					\OC::$server->getGroupManager(),
186
-					\OC::$server->getIniWrapper(),
187
-					\OC::$server->getURLGenerator(),
188
-					\OC::$server->getCapabilitiesManager(),
189
-					\OC::$server->query(IInitialStateService::class)
190
-				);
191
-				$this->assign('inline_ocjs', $jsConfigHelper->getConfig());
192
-			} else {
193
-				$this->append('jsfiles', \OC::$server->getURLGenerator()->linkToRoute('core.OCJS.getConfig', ['v' => self::$versionHash]));
194
-			}
195
-		}
196
-		foreach ($jsFiles as $info) {
197
-			$web = $info[1];
198
-			$file = $info[2];
199
-			$this->append('jsfiles', $web.'/'.$file . $this->getVersionHashSuffix());
200
-		}
201
-
202
-		try {
203
-			$pathInfo = \OC::$server->getRequest()->getPathInfo();
204
-		} catch (\Exception $e) {
205
-			$pathInfo = '';
206
-		}
207
-
208
-		// Do not initialise scss appdata until we have a fully installed instance
209
-		// Do not load scss for update, errors, installation or login page
210
-		if (\OC::$server->getSystemConfig()->getValue('installed', false)
211
-			&& !\OCP\Util::needUpgrade()
212
-			&& $pathInfo !== ''
213
-			&& !preg_match('/^\/login/', $pathInfo)
214
-			&& $renderAs !== TemplateResponse::RENDER_AS_ERROR
215
-		) {
216
-			$cssFiles = self::findStylesheetFiles(\OC_Util::$styles);
217
-		} else {
218
-			// If we ignore the scss compiler,
219
-			// we need to load the guest css fallback
220
-			\OC_Util::addStyle('guest');
221
-			$cssFiles = self::findStylesheetFiles(\OC_Util::$styles, false);
222
-		}
223
-
224
-		$this->assign('cssfiles', []);
225
-		$this->assign('printcssfiles', []);
226
-		$this->assign('versionHash', self::$versionHash);
227
-		foreach ($cssFiles as $info) {
228
-			$web = $info[1];
229
-			$file = $info[2];
230
-
231
-			if (substr($file, -strlen('print.css')) === 'print.css') {
232
-				$this->append('printcssfiles', $web.'/'.$file . $this->getVersionHashSuffix());
233
-			} else {
234
-				$suffix = $this->getVersionHashSuffix($web, $file);
235
-
236
-				if (strpos($file, '?v=') == false) {
237
-					$this->append('cssfiles', $web.'/'.$file . $suffix);
238
-				} else {
239
-					$this->append('cssfiles', $web.'/'.$file . '-' . substr($suffix, 3));
240
-				}
241
-			}
242
-		}
243
-
244
-		/** @var InitialStateService $initialState */
245
-		$initialState = \OC::$server->query(InitialStateService::class);
246
-		$this->assign('initialStates', $initialState->getInitialStates());
247
-	}
248
-
249
-	/**
250
-	 * @param string $path
251
-	 * @param string $file
252
-	 * @return string
253
-	 */
254
-	protected function getVersionHashSuffix($path = false, $file = false) {
255
-		if ($this->config->getSystemValue('debug', false)) {
256
-			// allows chrome workspace mapping in debug mode
257
-			return "";
258
-		}
259
-		$themingSuffix = '';
260
-		$v = [];
261
-
262
-		if ($this->config->getSystemValue('installed', false)) {
263
-			if (\OC::$server->getAppManager()->isInstalled('theming')) {
264
-				$themingSuffix = '-' . $this->config->getAppValue('theming', 'cachebuster', '0');
265
-			}
266
-			$v = \OC_App::getAppVersions();
267
-		}
268
-
269
-		// Try the webroot path for a match
270
-		if ($path !== false && $path !== '') {
271
-			$appName = $this->getAppNamefromPath($path);
272
-			if (array_key_exists($appName, $v)) {
273
-				$appVersion = $v[$appName];
274
-				return '?v=' . substr(md5($appVersion), 0, 8) . $themingSuffix;
275
-			}
276
-		}
277
-		// fallback to the file path instead
278
-		if ($file !== false && $file !== '') {
279
-			$appName = $this->getAppNamefromPath($file);
280
-			if (array_key_exists($appName, $v)) {
281
-				$appVersion = $v[$appName];
282
-				return '?v=' . substr(md5($appVersion), 0, 8) . $themingSuffix;
283
-			}
284
-		}
285
-
286
-		return '?v=' . self::$versionHash . $themingSuffix;
287
-	}
288
-
289
-	/**
290
-	 * @param array $styles
291
-	 * @return array
292
-	 */
293
-	public static function findStylesheetFiles($styles, $compileScss = true) {
294
-		// Read the selected theme from the config file
295
-		$theme = \OC_Util::getTheme();
296
-
297
-		if ($compileScss) {
298
-			$SCSSCacher = \OC::$server->query(SCSSCacher::class);
299
-		} else {
300
-			$SCSSCacher = null;
301
-		}
302
-
303
-		$locator = new \OC\Template\CSSResourceLocator(
304
-			\OC::$server->getLogger(),
305
-			$theme,
306
-			[ \OC::$SERVERROOT => \OC::$WEBROOT ],
307
-			[ \OC::$SERVERROOT => \OC::$WEBROOT ],
308
-			$SCSSCacher
309
-		);
310
-		$locator->find($styles);
311
-		return $locator->getResources();
312
-	}
313
-
314
-	/**
315
-	 * @param string $path
316
-	 * @return string|boolean
317
-	 */
318
-	public function getAppNamefromPath($path) {
319
-		if ($path !== '' && is_string($path)) {
320
-			$pathParts = explode('/', $path);
321
-			if ($pathParts[0] === 'css') {
322
-				// This is a scss request
323
-				return $pathParts[1];
324
-			}
325
-			return end($pathParts);
326
-		}
327
-		return false;
328
-	}
329
-
330
-	/**
331
-	 * @param array $scripts
332
-	 * @return array
333
-	 */
334
-	public static function findJavascriptFiles($scripts) {
335
-		// Read the selected theme from the config file
336
-		$theme = \OC_Util::getTheme();
337
-
338
-		$locator = new \OC\Template\JSResourceLocator(
339
-			\OC::$server->getLogger(),
340
-			$theme,
341
-			[ \OC::$SERVERROOT => \OC::$WEBROOT ],
342
-			[ \OC::$SERVERROOT => \OC::$WEBROOT ],
343
-			\OC::$server->query(JSCombiner::class)
344
-			);
345
-		$locator->find($scripts);
346
-		return $locator->getResources();
347
-	}
348
-
349
-	/**
350
-	 * Converts the absolute file path to a relative path from \OC::$SERVERROOT
351
-	 * @param string $filePath Absolute path
352
-	 * @return string Relative path
353
-	 * @throws \Exception If $filePath is not under \OC::$SERVERROOT
354
-	 */
355
-	public static function convertToRelativePath($filePath) {
356
-		$relativePath = explode(\OC::$SERVERROOT, $filePath);
357
-		if (count($relativePath) !== 2) {
358
-			throw new \Exception('$filePath is not under the \OC::$SERVERROOT');
359
-		}
360
-
361
-		return $relativePath[1];
362
-	}
57
+    private static $versionHash = '';
58
+
59
+    /**
60
+     * @var \OCP\IConfig
61
+     */
62
+    private $config;
63
+
64
+    /**
65
+     * @param string $renderAs
66
+     * @param string $appId application id
67
+     */
68
+    public function __construct($renderAs, $appId = '') {
69
+
70
+        // yes - should be injected ....
71
+        $this->config = \OC::$server->getConfig();
72
+
73
+        if (\OCP\Util::isIE()) {
74
+            \OC_Util::addStyle('ie');
75
+        }
76
+
77
+        // Decide which page we show
78
+        if ($renderAs === TemplateResponse::RENDER_AS_USER) {
79
+            parent::__construct('core', 'layout.user');
80
+            if (in_array(\OC_App::getCurrentApp(), ['settings','admin', 'help']) !== false) {
81
+                $this->assign('bodyid', 'body-settings');
82
+            } else {
83
+                $this->assign('bodyid', 'body-user');
84
+            }
85
+
86
+            // Add navigation entry
87
+            $this->assign('application', '');
88
+            $this->assign('appid', $appId);
89
+            $navigation = \OC::$server->getNavigationManager()->getAll();
90
+            $this->assign('navigation', $navigation);
91
+            $settingsNavigation = \OC::$server->getNavigationManager()->getAll('settings');
92
+            $this->assign('settingsnavigation', $settingsNavigation);
93
+            foreach ($navigation as $entry) {
94
+                if ($entry['active']) {
95
+                    $this->assign('application', $entry['name']);
96
+                    break;
97
+                }
98
+            }
99
+
100
+            foreach ($settingsNavigation as $entry) {
101
+                if ($entry['active']) {
102
+                    $this->assign('application', $entry['name']);
103
+                    break;
104
+                }
105
+            }
106
+            $userDisplayName = \OC_User::getDisplayName();
107
+            $this->assign('user_displayname', $userDisplayName);
108
+            $this->assign('user_uid', \OC_User::getUser());
109
+
110
+            if (\OC_User::getUser() === false) {
111
+                $this->assign('userAvatarSet', false);
112
+            } else {
113
+                $this->assign('userAvatarSet', \OC::$server->getAvatarManager()->getAvatar(\OC_User::getUser())->exists());
114
+                $this->assign('userAvatarVersion', $this->config->getUserValue(\OC_User::getUser(), 'avatar', 'version', 0));
115
+            }
116
+
117
+            // check if app menu icons should be inverted
118
+            try {
119
+                /** @var \OCA\Theming\Util $util */
120
+                $util = \OC::$server->query(\OCA\Theming\Util::class);
121
+                $this->assign('themingInvertMenu', $util->invertTextColor(\OC::$server->getThemingDefaults()->getColorPrimary()));
122
+            } catch (\OCP\AppFramework\QueryException $e) {
123
+                $this->assign('themingInvertMenu', false);
124
+            } catch (\OCP\AutoloadNotAllowedException $e) {
125
+                $this->assign('themingInvertMenu', false);
126
+            }
127
+        } elseif ($renderAs === TemplateResponse::RENDER_AS_ERROR) {
128
+            parent::__construct('core', 'layout.guest', '', false);
129
+            $this->assign('bodyid', 'body-login');
130
+            $this->assign('user_displayname', '');
131
+            $this->assign('user_uid', '');
132
+        } elseif ($renderAs === TemplateResponse::RENDER_AS_GUEST) {
133
+            parent::__construct('core', 'layout.guest');
134
+            \OC_Util::addStyle('guest');
135
+            $this->assign('bodyid', 'body-login');
136
+
137
+            $userDisplayName = \OC_User::getDisplayName();
138
+            $this->assign('user_displayname', $userDisplayName);
139
+            $this->assign('user_uid', \OC_User::getUser());
140
+        } elseif ($renderAs === TemplateResponse::RENDER_AS_PUBLIC) {
141
+            parent::__construct('core', 'layout.public');
142
+            $this->assign('appid', $appId);
143
+            $this->assign('bodyid', 'body-public');
144
+
145
+            /** @var IRegistry $subscription */
146
+            $subscription = \OC::$server->query(IRegistry::class);
147
+            $showSimpleSignup = $this->config->getSystemValueBool('simpleSignUpLink.shown', true);
148
+            if ($showSimpleSignup && $subscription->delegateHasValidSubscription()) {
149
+                $showSimpleSignup = false;
150
+            }
151
+            $this->assign('showSimpleSignUpLink', $showSimpleSignup);
152
+        } else {
153
+            parent::__construct('core', 'layout.base');
154
+        }
155
+        // Send the language and the locale to our layouts
156
+        $lang = \OC::$server->getL10NFactory()->findLanguage();
157
+        $locale = \OC::$server->getL10NFactory()->findLocale($lang);
158
+
159
+        $lang = str_replace('_', '-', $lang);
160
+        $this->assign('language', $lang);
161
+        $this->assign('locale', $locale);
162
+
163
+        if (\OC::$server->getSystemConfig()->getValue('installed', false)) {
164
+            if (empty(self::$versionHash)) {
165
+                $v = \OC_App::getAppVersions();
166
+                $v['core'] = implode('.', \OCP\Util::getVersion());
167
+                self::$versionHash = substr(md5(implode(',', $v)), 0, 8);
168
+            }
169
+        } else {
170
+            self::$versionHash = md5('not installed');
171
+        }
172
+
173
+        // Add the js files
174
+        $jsFiles = self::findJavascriptFiles(\OC_Util::$scripts);
175
+        $this->assign('jsfiles', []);
176
+        if ($this->config->getSystemValue('installed', false) && $renderAs != TemplateResponse::RENDER_AS_ERROR) {
177
+            if (\OC::$server->getContentSecurityPolicyNonceManager()->browserSupportsCspV3()) {
178
+                $jsConfigHelper = new JSConfigHelper(
179
+                    \OC::$server->getL10N('lib'),
180
+                    \OC::$server->query(Defaults::class),
181
+                    \OC::$server->getAppManager(),
182
+                    \OC::$server->getSession(),
183
+                    \OC::$server->getUserSession()->getUser(),
184
+                    $this->config,
185
+                    \OC::$server->getGroupManager(),
186
+                    \OC::$server->getIniWrapper(),
187
+                    \OC::$server->getURLGenerator(),
188
+                    \OC::$server->getCapabilitiesManager(),
189
+                    \OC::$server->query(IInitialStateService::class)
190
+                );
191
+                $this->assign('inline_ocjs', $jsConfigHelper->getConfig());
192
+            } else {
193
+                $this->append('jsfiles', \OC::$server->getURLGenerator()->linkToRoute('core.OCJS.getConfig', ['v' => self::$versionHash]));
194
+            }
195
+        }
196
+        foreach ($jsFiles as $info) {
197
+            $web = $info[1];
198
+            $file = $info[2];
199
+            $this->append('jsfiles', $web.'/'.$file . $this->getVersionHashSuffix());
200
+        }
201
+
202
+        try {
203
+            $pathInfo = \OC::$server->getRequest()->getPathInfo();
204
+        } catch (\Exception $e) {
205
+            $pathInfo = '';
206
+        }
207
+
208
+        // Do not initialise scss appdata until we have a fully installed instance
209
+        // Do not load scss for update, errors, installation or login page
210
+        if (\OC::$server->getSystemConfig()->getValue('installed', false)
211
+            && !\OCP\Util::needUpgrade()
212
+            && $pathInfo !== ''
213
+            && !preg_match('/^\/login/', $pathInfo)
214
+            && $renderAs !== TemplateResponse::RENDER_AS_ERROR
215
+        ) {
216
+            $cssFiles = self::findStylesheetFiles(\OC_Util::$styles);
217
+        } else {
218
+            // If we ignore the scss compiler,
219
+            // we need to load the guest css fallback
220
+            \OC_Util::addStyle('guest');
221
+            $cssFiles = self::findStylesheetFiles(\OC_Util::$styles, false);
222
+        }
223
+
224
+        $this->assign('cssfiles', []);
225
+        $this->assign('printcssfiles', []);
226
+        $this->assign('versionHash', self::$versionHash);
227
+        foreach ($cssFiles as $info) {
228
+            $web = $info[1];
229
+            $file = $info[2];
230
+
231
+            if (substr($file, -strlen('print.css')) === 'print.css') {
232
+                $this->append('printcssfiles', $web.'/'.$file . $this->getVersionHashSuffix());
233
+            } else {
234
+                $suffix = $this->getVersionHashSuffix($web, $file);
235
+
236
+                if (strpos($file, '?v=') == false) {
237
+                    $this->append('cssfiles', $web.'/'.$file . $suffix);
238
+                } else {
239
+                    $this->append('cssfiles', $web.'/'.$file . '-' . substr($suffix, 3));
240
+                }
241
+            }
242
+        }
243
+
244
+        /** @var InitialStateService $initialState */
245
+        $initialState = \OC::$server->query(InitialStateService::class);
246
+        $this->assign('initialStates', $initialState->getInitialStates());
247
+    }
248
+
249
+    /**
250
+     * @param string $path
251
+     * @param string $file
252
+     * @return string
253
+     */
254
+    protected function getVersionHashSuffix($path = false, $file = false) {
255
+        if ($this->config->getSystemValue('debug', false)) {
256
+            // allows chrome workspace mapping in debug mode
257
+            return "";
258
+        }
259
+        $themingSuffix = '';
260
+        $v = [];
261
+
262
+        if ($this->config->getSystemValue('installed', false)) {
263
+            if (\OC::$server->getAppManager()->isInstalled('theming')) {
264
+                $themingSuffix = '-' . $this->config->getAppValue('theming', 'cachebuster', '0');
265
+            }
266
+            $v = \OC_App::getAppVersions();
267
+        }
268
+
269
+        // Try the webroot path for a match
270
+        if ($path !== false && $path !== '') {
271
+            $appName = $this->getAppNamefromPath($path);
272
+            if (array_key_exists($appName, $v)) {
273
+                $appVersion = $v[$appName];
274
+                return '?v=' . substr(md5($appVersion), 0, 8) . $themingSuffix;
275
+            }
276
+        }
277
+        // fallback to the file path instead
278
+        if ($file !== false && $file !== '') {
279
+            $appName = $this->getAppNamefromPath($file);
280
+            if (array_key_exists($appName, $v)) {
281
+                $appVersion = $v[$appName];
282
+                return '?v=' . substr(md5($appVersion), 0, 8) . $themingSuffix;
283
+            }
284
+        }
285
+
286
+        return '?v=' . self::$versionHash . $themingSuffix;
287
+    }
288
+
289
+    /**
290
+     * @param array $styles
291
+     * @return array
292
+     */
293
+    public static function findStylesheetFiles($styles, $compileScss = true) {
294
+        // Read the selected theme from the config file
295
+        $theme = \OC_Util::getTheme();
296
+
297
+        if ($compileScss) {
298
+            $SCSSCacher = \OC::$server->query(SCSSCacher::class);
299
+        } else {
300
+            $SCSSCacher = null;
301
+        }
302
+
303
+        $locator = new \OC\Template\CSSResourceLocator(
304
+            \OC::$server->getLogger(),
305
+            $theme,
306
+            [ \OC::$SERVERROOT => \OC::$WEBROOT ],
307
+            [ \OC::$SERVERROOT => \OC::$WEBROOT ],
308
+            $SCSSCacher
309
+        );
310
+        $locator->find($styles);
311
+        return $locator->getResources();
312
+    }
313
+
314
+    /**
315
+     * @param string $path
316
+     * @return string|boolean
317
+     */
318
+    public function getAppNamefromPath($path) {
319
+        if ($path !== '' && is_string($path)) {
320
+            $pathParts = explode('/', $path);
321
+            if ($pathParts[0] === 'css') {
322
+                // This is a scss request
323
+                return $pathParts[1];
324
+            }
325
+            return end($pathParts);
326
+        }
327
+        return false;
328
+    }
329
+
330
+    /**
331
+     * @param array $scripts
332
+     * @return array
333
+     */
334
+    public static function findJavascriptFiles($scripts) {
335
+        // Read the selected theme from the config file
336
+        $theme = \OC_Util::getTheme();
337
+
338
+        $locator = new \OC\Template\JSResourceLocator(
339
+            \OC::$server->getLogger(),
340
+            $theme,
341
+            [ \OC::$SERVERROOT => \OC::$WEBROOT ],
342
+            [ \OC::$SERVERROOT => \OC::$WEBROOT ],
343
+            \OC::$server->query(JSCombiner::class)
344
+            );
345
+        $locator->find($scripts);
346
+        return $locator->getResources();
347
+    }
348
+
349
+    /**
350
+     * Converts the absolute file path to a relative path from \OC::$SERVERROOT
351
+     * @param string $filePath Absolute path
352
+     * @return string Relative path
353
+     * @throws \Exception If $filePath is not under \OC::$SERVERROOT
354
+     */
355
+    public static function convertToRelativePath($filePath) {
356
+        $relativePath = explode(\OC::$SERVERROOT, $filePath);
357
+        if (count($relativePath) !== 2) {
358
+            throw new \Exception('$filePath is not under the \OC::$SERVERROOT');
359
+        }
360
+
361
+        return $relativePath[1];
362
+    }
363 363
 }
Please login to merge, or discard this patch.
Spacing   +13 added lines, -13 removed lines patch added patch discarded remove patch
@@ -77,7 +77,7 @@  discard block
 block discarded – undo
77 77
 		// Decide which page we show
78 78
 		if ($renderAs === TemplateResponse::RENDER_AS_USER) {
79 79
 			parent::__construct('core', 'layout.user');
80
-			if (in_array(\OC_App::getCurrentApp(), ['settings','admin', 'help']) !== false) {
80
+			if (in_array(\OC_App::getCurrentApp(), ['settings', 'admin', 'help']) !== false) {
81 81
 				$this->assign('bodyid', 'body-settings');
82 82
 			} else {
83 83
 				$this->assign('bodyid', 'body-user');
@@ -196,7 +196,7 @@  discard block
 block discarded – undo
196 196
 		foreach ($jsFiles as $info) {
197 197
 			$web = $info[1];
198 198
 			$file = $info[2];
199
-			$this->append('jsfiles', $web.'/'.$file . $this->getVersionHashSuffix());
199
+			$this->append('jsfiles', $web.'/'.$file.$this->getVersionHashSuffix());
200 200
 		}
201 201
 
202 202
 		try {
@@ -229,14 +229,14 @@  discard block
 block discarded – undo
229 229
 			$file = $info[2];
230 230
 
231 231
 			if (substr($file, -strlen('print.css')) === 'print.css') {
232
-				$this->append('printcssfiles', $web.'/'.$file . $this->getVersionHashSuffix());
232
+				$this->append('printcssfiles', $web.'/'.$file.$this->getVersionHashSuffix());
233 233
 			} else {
234 234
 				$suffix = $this->getVersionHashSuffix($web, $file);
235 235
 
236 236
 				if (strpos($file, '?v=') == false) {
237
-					$this->append('cssfiles', $web.'/'.$file . $suffix);
237
+					$this->append('cssfiles', $web.'/'.$file.$suffix);
238 238
 				} else {
239
-					$this->append('cssfiles', $web.'/'.$file . '-' . substr($suffix, 3));
239
+					$this->append('cssfiles', $web.'/'.$file.'-'.substr($suffix, 3));
240 240
 				}
241 241
 			}
242 242
 		}
@@ -261,7 +261,7 @@  discard block
 block discarded – undo
261 261
 
262 262
 		if ($this->config->getSystemValue('installed', false)) {
263 263
 			if (\OC::$server->getAppManager()->isInstalled('theming')) {
264
-				$themingSuffix = '-' . $this->config->getAppValue('theming', 'cachebuster', '0');
264
+				$themingSuffix = '-'.$this->config->getAppValue('theming', 'cachebuster', '0');
265 265
 			}
266 266
 			$v = \OC_App::getAppVersions();
267 267
 		}
@@ -271,7 +271,7 @@  discard block
 block discarded – undo
271 271
 			$appName = $this->getAppNamefromPath($path);
272 272
 			if (array_key_exists($appName, $v)) {
273 273
 				$appVersion = $v[$appName];
274
-				return '?v=' . substr(md5($appVersion), 0, 8) . $themingSuffix;
274
+				return '?v='.substr(md5($appVersion), 0, 8).$themingSuffix;
275 275
 			}
276 276
 		}
277 277
 		// fallback to the file path instead
@@ -279,11 +279,11 @@  discard block
 block discarded – undo
279 279
 			$appName = $this->getAppNamefromPath($file);
280 280
 			if (array_key_exists($appName, $v)) {
281 281
 				$appVersion = $v[$appName];
282
-				return '?v=' . substr(md5($appVersion), 0, 8) . $themingSuffix;
282
+				return '?v='.substr(md5($appVersion), 0, 8).$themingSuffix;
283 283
 			}
284 284
 		}
285 285
 
286
-		return '?v=' . self::$versionHash . $themingSuffix;
286
+		return '?v='.self::$versionHash.$themingSuffix;
287 287
 	}
288 288
 
289 289
 	/**
@@ -303,8 +303,8 @@  discard block
 block discarded – undo
303 303
 		$locator = new \OC\Template\CSSResourceLocator(
304 304
 			\OC::$server->getLogger(),
305 305
 			$theme,
306
-			[ \OC::$SERVERROOT => \OC::$WEBROOT ],
307
-			[ \OC::$SERVERROOT => \OC::$WEBROOT ],
306
+			[\OC::$SERVERROOT => \OC::$WEBROOT],
307
+			[\OC::$SERVERROOT => \OC::$WEBROOT],
308 308
 			$SCSSCacher
309 309
 		);
310 310
 		$locator->find($styles);
@@ -338,8 +338,8 @@  discard block
 block discarded – undo
338 338
 		$locator = new \OC\Template\JSResourceLocator(
339 339
 			\OC::$server->getLogger(),
340 340
 			$theme,
341
-			[ \OC::$SERVERROOT => \OC::$WEBROOT ],
342
-			[ \OC::$SERVERROOT => \OC::$WEBROOT ],
341
+			[\OC::$SERVERROOT => \OC::$WEBROOT],
342
+			[\OC::$SERVERROOT => \OC::$WEBROOT],
343 343
 			\OC::$server->query(JSCombiner::class)
344 344
 			);
345 345
 		$locator->find($scripts);
Please login to merge, or discard this patch.