Completed
Pull Request — master (#3385)
by Christoph
18:07
created
lib/private/legacy/template.php 2 patches
Indentation   +353 added lines, -353 removed lines patch added patch discarded remove patch
@@ -44,357 +44,357 @@
 block discarded – undo
44 44
  */
45 45
 class OC_Template extends \OC\Template\Base {
46 46
 
47
-	/** @var string */
48
-	private $renderAs; // Create a full page?
49
-
50
-	/** @var string */
51
-	private $path; // The path to the template
52
-
53
-	/** @var array */
54
-	private $headers = array(); //custom headers
55
-
56
-	/** @var string */
57
-	protected $app; // app id
58
-
59
-	protected static $initTemplateEngineFirstRun = true;
60
-
61
-	/**
62
-	 * Constructor
63
-	 *
64
-	 * @param string $app app providing the template
65
-	 * @param string $name of the template file (without suffix)
66
-	 * @param string $renderAs If $renderAs is set, OC_Template will try to
67
-	 *                         produce a full page in the according layout. For
68
-	 *                         now, $renderAs can be set to "guest", "user" or
69
-	 *                         "admin".
70
-	 * @param bool $registerCall = true
71
-	 */
72
-	public function __construct( $app, $name, $renderAs = "", $registerCall = true ) {
73
-		// Read the selected theme from the config file
74
-		self::initTemplateEngine($renderAs);
75
-
76
-		$theme = OC_Util::getTheme();
77
-
78
-		$requestToken = (OC::$server->getSession() && $registerCall) ? \OCP\Util::callRegister() : '';
79
-
80
-		$parts = explode('/', $app); // fix translation when app is something like core/lostpassword
81
-		$l10n = \OC::$server->getL10N($parts[0]);
82
-		$themeDefaults = \OC::$server->getThemingDefaults();
83
-
84
-		list($path, $template) = $this->findTemplate($theme, $app, $name);
85
-
86
-		// Set the private data
87
-		$this->renderAs = $renderAs;
88
-		$this->path = $path;
89
-		$this->app = $app;
90
-
91
-		parent::__construct($template, $requestToken, $l10n, $themeDefaults);
92
-	}
93
-
94
-	/**
95
-	 * @param string $renderAs
96
-	 */
97
-	public static function initTemplateEngine($renderAs) {
98
-		if (self::$initTemplateEngineFirstRun){
99
-
100
-			//apps that started before the template initialization can load their own scripts/styles
101
-			//so to make sure this scripts/styles here are loaded first we use OC_Util::addScript() with $prepend=true
102
-			//meaning the last script/style in this list will be loaded first
103
-			if (\OC::$server->getSystemConfig()->getValue ('installed', false) && $renderAs !== 'error' && !\OCP\Util::needUpgrade()) {
104
-				if (\OC::$server->getConfig ()->getAppValue ( 'core', 'backgroundjobs_mode', 'ajax' ) == 'ajax') {
105
-					OC_Util::addScript ( 'backgroundjobs', null, true );
106
-				}
107
-			}
108
-
109
-			OC_Util::addStyle("tooltip",null,true);
110
-			OC_Util::addStyle('jquery-ui-fixes',null,true);
111
-			OC_Util::addVendorStyle('jquery-ui/themes/base/jquery-ui',null,true);
112
-			OC_Util::addStyle("mobile",null,true);
113
-			OC_Util::addStyle("multiselect",null,true);
114
-			OC_Util::addStyle("fixes",null,true);
115
-			OC_Util::addStyle("global",null,true);
116
-			OC_Util::addStyle("apps",null,true);
117
-			OC_Util::addStyle("fonts",null,true);
118
-			OC_Util::addStyle("icons",null,true);
119
-			OC_Util::addStyle("actions",null,true);
120
-			OC_Util::addStyle("header",null,true);
121
-			OC_Util::addStyle("inputs");
122
-			OC_Util::addStyle("styles",null,true);
123
-
124
-			// avatars
125
-			\OC_Util::addScript('jquery.avatar', null, true);
126
-			\OC_Util::addScript('placeholder', null, true);
127
-
128
-			OC_Util::addVendorScript('select2/select2');
129
-			OC_Util::addVendorStyle('select2/select2', null, true);
130
-			OC_Util::addScript('select2-toggleselect');
131
-
132
-			OC_Util::addScript('oc-backbone', null, true);
133
-			OC_Util::addVendorScript('core', 'backbone/backbone', true);
134
-			OC_Util::addVendorScript('snapjs/dist/latest/snap', null, true);
135
-			OC_Util::addScript('mimetypelist', null, true);
136
-			OC_Util::addScript('mimetype', null, true);
137
-			OC_Util::addScript("apps", null, true);
138
-			OC_Util::addScript("oc-requesttoken", null, true);
139
-			OC_Util::addScript('search', 'search', true);
140
-			OC_Util::addScript("config", null, true);
141
-			OC_Util::addScript("public/appconfig", null, true);
142
-			OC_Util::addScript("eventsource", null, true);
143
-			OC_Util::addScript("octemplate", null, true);
144
-			OC_Util::addTranslations("core", null, true);
145
-			OC_Util::addScript("l10n", null, true);
146
-			OC_Util::addScript("js", null, true);
147
-			OC_Util::addScript("oc-dialogs", null, true);
148
-			OC_Util::addScript("jquery.ocdialog", null, true);
149
-			OC_Util::addScript("jquery-ui-fixes");
150
-			OC_Util::addStyle("jquery.ocdialog");
151
-			OC_Util::addScript('files/fileinfo');
152
-			OC_Util::addScript('files/client');
153
-
154
-			// Add the stuff we need always
155
-			// following logic will import all vendor libraries that are
156
-			// specified in core/js/core.json
157
-			$fileContent = file_get_contents(OC::$SERVERROOT . '/core/js/core.json');
158
-			if($fileContent !== false) {
159
-				$coreDependencies = json_decode($fileContent, true);
160
-				foreach(array_reverse($coreDependencies['vendor']) as $vendorLibrary) {
161
-					// remove trailing ".js" as addVendorScript will append it
162
-					OC_Util::addVendorScript(
163
-							substr($vendorLibrary, 0, strlen($vendorLibrary) - 3),null,true);
164
-				}
165
-			} else {
166
-				throw new \Exception('Cannot read core/js/core.json');
167
-			}
168
-
169
-			if (\OC::$server->getRequest()->isUserAgent([\OC\AppFramework\Http\Request::USER_AGENT_IE])) {
170
-				// polyfill for btoa/atob for IE friends
171
-				OC_Util::addVendorScript('base64/base64');
172
-				// shim for the davclient.js library
173
-				\OCP\Util::addScript('files/iedavclient');
174
-			}
175
-
176
-			self::$initTemplateEngineFirstRun = false;
177
-		}
178
-
179
-	}
180
-
181
-
182
-	/**
183
-	 * find the template with the given name
184
-	 * @param string $name of the template file (without suffix)
185
-	 *
186
-	 * Will select the template file for the selected theme.
187
-	 * Checking all the possible locations.
188
-	 * @param string $theme
189
-	 * @param string $app
190
-	 * @return string[]
191
-	 */
192
-	protected function findTemplate($theme, $app, $name) {
193
-		// Check if it is a app template or not.
194
-		if( $app !== '' ) {
195
-			$dirs = $this->getAppTemplateDirs($theme, $app, OC::$SERVERROOT, OC_App::getAppPath($app));
196
-		} else {
197
-			$dirs = $this->getCoreTemplateDirs($theme, OC::$SERVERROOT);
198
-		}
199
-		$locator = new \OC\Template\TemplateFileLocator( $dirs );
200
-		$template = $locator->find($name);
201
-		$path = $locator->getPath();
202
-		return array($path, $template);
203
-	}
204
-
205
-	/**
206
-	 * Add a custom element to the header
207
-	 * @param string $tag tag name of the element
208
-	 * @param array $attributes array of attributes for the element
209
-	 * @param string $text the text content for the element. If $text is null then the
210
-	 * element will be written as empty element. So use "" to get a closing tag.
211
-	 */
212
-	public function addHeader($tag, $attributes, $text=null) {
213
-		$this->headers[]= array(
214
-			'tag' => $tag,
215
-			'attributes' => $attributes,
216
-			'text' => $text
217
-		);
218
-	}
219
-
220
-	/**
221
-	 * Process the template
222
-	 * @return boolean|string
223
-	 *
224
-	 * This function process the template. If $this->renderAs is set, it
225
-	 * will produce a full page.
226
-	 */
227
-	public function fetchPage($additionalParams = null) {
228
-		$data = parent::fetchPage($additionalParams);
229
-
230
-		if( $this->renderAs ) {
231
-			$page = new TemplateLayout($this->renderAs, $this->app);
232
-
233
-			// Add custom headers
234
-			$headers = '';
235
-			foreach(OC_Util::$headers as $header) {
236
-				$headers .= '<'.\OCP\Util::sanitizeHTML($header['tag']);
237
-				foreach($header['attributes'] as $name=>$value) {
238
-					$headers .= ' '.\OCP\Util::sanitizeHTML($name).'="'.\OCP\Util::sanitizeHTML($value).'"';
239
-				}
240
-				if ($header['text'] !== null) {
241
-					$headers .= '>'.\OCP\Util::sanitizeHTML($header['text']).'</'.\OCP\Util::sanitizeHTML($header['tag']).'>';
242
-				} else {
243
-					$headers .= '/>';
244
-				}
245
-			}
246
-
247
-			$page->assign('headers', $headers);
248
-
249
-			$page->assign('content', $data);
250
-			return $page->fetchPage();
251
-		}
252
-
253
-		return $data;
254
-	}
255
-
256
-	/**
257
-	 * Include template
258
-	 *
259
-	 * @param string $file
260
-	 * @param array|null $additionalParams
261
-	 * @return string returns content of included template
262
-	 *
263
-	 * Includes another template. use <?php echo $this->inc('template'); ?> to
264
-	 * do this.
265
-	 */
266
-	public function inc( $file, $additionalParams = null ) {
267
-		return $this->load($this->path.$file.'.php', $additionalParams);
268
-	}
269
-
270
-	/**
271
-	 * Shortcut to print a simple page for users
272
-	 * @param string $application The application we render the template for
273
-	 * @param string $name Name of the template
274
-	 * @param array $parameters Parameters for the template
275
-	 * @return boolean|null
276
-	 */
277
-	public static function printUserPage( $application, $name, $parameters = array() ) {
278
-		$content = new OC_Template( $application, $name, "user" );
279
-		foreach( $parameters as $key => $value ) {
280
-			$content->assign( $key, $value );
281
-		}
282
-		print $content->printPage();
283
-	}
284
-
285
-	/**
286
-	 * Shortcut to print a simple page for admins
287
-	 * @param string $application The application we render the template for
288
-	 * @param string $name Name of the template
289
-	 * @param array $parameters Parameters for the template
290
-	 * @return bool
291
-	 */
292
-	public static function printAdminPage( $application, $name, $parameters = array() ) {
293
-		$content = new OC_Template( $application, $name, "admin" );
294
-		foreach( $parameters as $key => $value ) {
295
-			$content->assign( $key, $value );
296
-		}
297
-		return $content->printPage();
298
-	}
299
-
300
-	/**
301
-	 * Shortcut to print a simple page for guests
302
-	 * @param string $application The application we render the template for
303
-	 * @param string $name Name of the template
304
-	 * @param array|string $parameters Parameters for the template
305
-	 * @return bool
306
-	 */
307
-	public static function printGuestPage( $application, $name, $parameters = array() ) {
308
-		$content = new OC_Template( $application, $name, "guest" );
309
-		foreach( $parameters as $key => $value ) {
310
-			$content->assign( $key, $value );
311
-		}
312
-		return $content->printPage();
313
-	}
314
-
315
-	/**
316
-		* Print a fatal error page and terminates the script
317
-		* @param string $error_msg The error message to show
318
-		* @param string $hint An optional hint message - needs to be properly escaped
319
-		*/
320
-	public static function printErrorPage( $error_msg, $hint = '' ) {
321
-		if ($error_msg === $hint) {
322
-			// If the hint is the same as the message there is no need to display it twice.
323
-			$hint = '';
324
-		}
325
-
326
-		try {
327
-			$content = new \OC_Template( '', 'error', 'error', false );
328
-			$errors = array(array('error' => $error_msg, 'hint' => $hint));
329
-			$content->assign( 'errors', $errors );
330
-			$content->printPage();
331
-		} catch (\Exception $e) {
332
-			$logger = \OC::$server->getLogger();
333
-			$logger->error("$error_msg $hint", ['app' => 'core']);
334
-			$logger->logException($e, ['app' => 'core']);
335
-
336
-			header(self::getHttpProtocol() . ' 500 Internal Server Error');
337
-			header('Content-Type: text/plain; charset=utf-8');
338
-			print("$error_msg $hint");
339
-		}
340
-		die();
341
-	}
342
-
343
-	/**
344
-	 * print error page using Exception details
345
-	 * @param Exception | Throwable $exception
346
-	 */
347
-	public static function printExceptionErrorPage($exception, $fetchPage = false) {
348
-		try {
349
-			$request = \OC::$server->getRequest();
350
-			$content = new \OC_Template('', 'exception', 'error', false);
351
-			$content->assign('errorClass', get_class($exception));
352
-			$content->assign('errorMsg', $exception->getMessage());
353
-			$content->assign('errorCode', $exception->getCode());
354
-			$content->assign('file', $exception->getFile());
355
-			$content->assign('line', $exception->getLine());
356
-			$content->assign('trace', $exception->getTraceAsString());
357
-			$content->assign('debugMode', \OC::$server->getSystemConfig()->getValue('debug', false));
358
-			$content->assign('remoteAddr', $request->getRemoteAddress());
359
-			$content->assign('requestID', $request->getId());
360
-			if ($fetchPage) {
361
-				return $content->fetchPage();
362
-			}
363
-			$content->printPage();
364
-		} catch (\Exception $e) {
365
-			$logger = \OC::$server->getLogger();
366
-			$logger->logException($exception, ['app' => 'core']);
367
-			$logger->logException($e, ['app' => 'core']);
368
-
369
-			header(self::getHttpProtocol() . ' 500 Internal Server Error');
370
-			header('Content-Type: text/plain; charset=utf-8');
371
-			print("Internal Server Error\n\n");
372
-			print("The server encountered an internal error and was unable to complete your request.\n");
373
-			print("Please contact the server administrator if this error reappears multiple times, please include the technical details below in your report.\n");
374
-			print("More details can be found in the server log.\n");
375
-		}
376
-		die();
377
-	}
378
-
379
-	/**
380
-	 * This is only here to reduce the dependencies in case of an exception to
381
-	 * still be able to print a plain error message.
382
-	 *
383
-	 * Returns the used HTTP protocol.
384
-	 *
385
-	 * @return string HTTP protocol. HTTP/2, HTTP/1.1 or HTTP/1.0.
386
-	 * @internal Don't use this - use AppFramework\Http\Request->getHttpProtocol instead
387
-	 */
388
-	protected static function getHttpProtocol() {
389
-		$claimedProtocol = strtoupper($_SERVER['SERVER_PROTOCOL']);
390
-		$validProtocols = [
391
-			'HTTP/1.0',
392
-			'HTTP/1.1',
393
-			'HTTP/2',
394
-		];
395
-		if(in_array($claimedProtocol, $validProtocols, true)) {
396
-			return $claimedProtocol;
397
-		}
398
-		return 'HTTP/1.1';
399
-	}
47
+    /** @var string */
48
+    private $renderAs; // Create a full page?
49
+
50
+    /** @var string */
51
+    private $path; // The path to the template
52
+
53
+    /** @var array */
54
+    private $headers = array(); //custom headers
55
+
56
+    /** @var string */
57
+    protected $app; // app id
58
+
59
+    protected static $initTemplateEngineFirstRun = true;
60
+
61
+    /**
62
+     * Constructor
63
+     *
64
+     * @param string $app app providing the template
65
+     * @param string $name of the template file (without suffix)
66
+     * @param string $renderAs If $renderAs is set, OC_Template will try to
67
+     *                         produce a full page in the according layout. For
68
+     *                         now, $renderAs can be set to "guest", "user" or
69
+     *                         "admin".
70
+     * @param bool $registerCall = true
71
+     */
72
+    public function __construct( $app, $name, $renderAs = "", $registerCall = true ) {
73
+        // Read the selected theme from the config file
74
+        self::initTemplateEngine($renderAs);
75
+
76
+        $theme = OC_Util::getTheme();
77
+
78
+        $requestToken = (OC::$server->getSession() && $registerCall) ? \OCP\Util::callRegister() : '';
79
+
80
+        $parts = explode('/', $app); // fix translation when app is something like core/lostpassword
81
+        $l10n = \OC::$server->getL10N($parts[0]);
82
+        $themeDefaults = \OC::$server->getThemingDefaults();
83
+
84
+        list($path, $template) = $this->findTemplate($theme, $app, $name);
85
+
86
+        // Set the private data
87
+        $this->renderAs = $renderAs;
88
+        $this->path = $path;
89
+        $this->app = $app;
90
+
91
+        parent::__construct($template, $requestToken, $l10n, $themeDefaults);
92
+    }
93
+
94
+    /**
95
+     * @param string $renderAs
96
+     */
97
+    public static function initTemplateEngine($renderAs) {
98
+        if (self::$initTemplateEngineFirstRun){
99
+
100
+            //apps that started before the template initialization can load their own scripts/styles
101
+            //so to make sure this scripts/styles here are loaded first we use OC_Util::addScript() with $prepend=true
102
+            //meaning the last script/style in this list will be loaded first
103
+            if (\OC::$server->getSystemConfig()->getValue ('installed', false) && $renderAs !== 'error' && !\OCP\Util::needUpgrade()) {
104
+                if (\OC::$server->getConfig ()->getAppValue ( 'core', 'backgroundjobs_mode', 'ajax' ) == 'ajax') {
105
+                    OC_Util::addScript ( 'backgroundjobs', null, true );
106
+                }
107
+            }
108
+
109
+            OC_Util::addStyle("tooltip",null,true);
110
+            OC_Util::addStyle('jquery-ui-fixes',null,true);
111
+            OC_Util::addVendorStyle('jquery-ui/themes/base/jquery-ui',null,true);
112
+            OC_Util::addStyle("mobile",null,true);
113
+            OC_Util::addStyle("multiselect",null,true);
114
+            OC_Util::addStyle("fixes",null,true);
115
+            OC_Util::addStyle("global",null,true);
116
+            OC_Util::addStyle("apps",null,true);
117
+            OC_Util::addStyle("fonts",null,true);
118
+            OC_Util::addStyle("icons",null,true);
119
+            OC_Util::addStyle("actions",null,true);
120
+            OC_Util::addStyle("header",null,true);
121
+            OC_Util::addStyle("inputs");
122
+            OC_Util::addStyle("styles",null,true);
123
+
124
+            // avatars
125
+            \OC_Util::addScript('jquery.avatar', null, true);
126
+            \OC_Util::addScript('placeholder', null, true);
127
+
128
+            OC_Util::addVendorScript('select2/select2');
129
+            OC_Util::addVendorStyle('select2/select2', null, true);
130
+            OC_Util::addScript('select2-toggleselect');
131
+
132
+            OC_Util::addScript('oc-backbone', null, true);
133
+            OC_Util::addVendorScript('core', 'backbone/backbone', true);
134
+            OC_Util::addVendorScript('snapjs/dist/latest/snap', null, true);
135
+            OC_Util::addScript('mimetypelist', null, true);
136
+            OC_Util::addScript('mimetype', null, true);
137
+            OC_Util::addScript("apps", null, true);
138
+            OC_Util::addScript("oc-requesttoken", null, true);
139
+            OC_Util::addScript('search', 'search', true);
140
+            OC_Util::addScript("config", null, true);
141
+            OC_Util::addScript("public/appconfig", null, true);
142
+            OC_Util::addScript("eventsource", null, true);
143
+            OC_Util::addScript("octemplate", null, true);
144
+            OC_Util::addTranslations("core", null, true);
145
+            OC_Util::addScript("l10n", null, true);
146
+            OC_Util::addScript("js", null, true);
147
+            OC_Util::addScript("oc-dialogs", null, true);
148
+            OC_Util::addScript("jquery.ocdialog", null, true);
149
+            OC_Util::addScript("jquery-ui-fixes");
150
+            OC_Util::addStyle("jquery.ocdialog");
151
+            OC_Util::addScript('files/fileinfo');
152
+            OC_Util::addScript('files/client');
153
+
154
+            // Add the stuff we need always
155
+            // following logic will import all vendor libraries that are
156
+            // specified in core/js/core.json
157
+            $fileContent = file_get_contents(OC::$SERVERROOT . '/core/js/core.json');
158
+            if($fileContent !== false) {
159
+                $coreDependencies = json_decode($fileContent, true);
160
+                foreach(array_reverse($coreDependencies['vendor']) as $vendorLibrary) {
161
+                    // remove trailing ".js" as addVendorScript will append it
162
+                    OC_Util::addVendorScript(
163
+                            substr($vendorLibrary, 0, strlen($vendorLibrary) - 3),null,true);
164
+                }
165
+            } else {
166
+                throw new \Exception('Cannot read core/js/core.json');
167
+            }
168
+
169
+            if (\OC::$server->getRequest()->isUserAgent([\OC\AppFramework\Http\Request::USER_AGENT_IE])) {
170
+                // polyfill for btoa/atob for IE friends
171
+                OC_Util::addVendorScript('base64/base64');
172
+                // shim for the davclient.js library
173
+                \OCP\Util::addScript('files/iedavclient');
174
+            }
175
+
176
+            self::$initTemplateEngineFirstRun = false;
177
+        }
178
+
179
+    }
180
+
181
+
182
+    /**
183
+     * find the template with the given name
184
+     * @param string $name of the template file (without suffix)
185
+     *
186
+     * Will select the template file for the selected theme.
187
+     * Checking all the possible locations.
188
+     * @param string $theme
189
+     * @param string $app
190
+     * @return string[]
191
+     */
192
+    protected function findTemplate($theme, $app, $name) {
193
+        // Check if it is a app template or not.
194
+        if( $app !== '' ) {
195
+            $dirs = $this->getAppTemplateDirs($theme, $app, OC::$SERVERROOT, OC_App::getAppPath($app));
196
+        } else {
197
+            $dirs = $this->getCoreTemplateDirs($theme, OC::$SERVERROOT);
198
+        }
199
+        $locator = new \OC\Template\TemplateFileLocator( $dirs );
200
+        $template = $locator->find($name);
201
+        $path = $locator->getPath();
202
+        return array($path, $template);
203
+    }
204
+
205
+    /**
206
+     * Add a custom element to the header
207
+     * @param string $tag tag name of the element
208
+     * @param array $attributes array of attributes for the element
209
+     * @param string $text the text content for the element. If $text is null then the
210
+     * element will be written as empty element. So use "" to get a closing tag.
211
+     */
212
+    public function addHeader($tag, $attributes, $text=null) {
213
+        $this->headers[]= array(
214
+            'tag' => $tag,
215
+            'attributes' => $attributes,
216
+            'text' => $text
217
+        );
218
+    }
219
+
220
+    /**
221
+     * Process the template
222
+     * @return boolean|string
223
+     *
224
+     * This function process the template. If $this->renderAs is set, it
225
+     * will produce a full page.
226
+     */
227
+    public function fetchPage($additionalParams = null) {
228
+        $data = parent::fetchPage($additionalParams);
229
+
230
+        if( $this->renderAs ) {
231
+            $page = new TemplateLayout($this->renderAs, $this->app);
232
+
233
+            // Add custom headers
234
+            $headers = '';
235
+            foreach(OC_Util::$headers as $header) {
236
+                $headers .= '<'.\OCP\Util::sanitizeHTML($header['tag']);
237
+                foreach($header['attributes'] as $name=>$value) {
238
+                    $headers .= ' '.\OCP\Util::sanitizeHTML($name).'="'.\OCP\Util::sanitizeHTML($value).'"';
239
+                }
240
+                if ($header['text'] !== null) {
241
+                    $headers .= '>'.\OCP\Util::sanitizeHTML($header['text']).'</'.\OCP\Util::sanitizeHTML($header['tag']).'>';
242
+                } else {
243
+                    $headers .= '/>';
244
+                }
245
+            }
246
+
247
+            $page->assign('headers', $headers);
248
+
249
+            $page->assign('content', $data);
250
+            return $page->fetchPage();
251
+        }
252
+
253
+        return $data;
254
+    }
255
+
256
+    /**
257
+     * Include template
258
+     *
259
+     * @param string $file
260
+     * @param array|null $additionalParams
261
+     * @return string returns content of included template
262
+     *
263
+     * Includes another template. use <?php echo $this->inc('template'); ?> to
264
+     * do this.
265
+     */
266
+    public function inc( $file, $additionalParams = null ) {
267
+        return $this->load($this->path.$file.'.php', $additionalParams);
268
+    }
269
+
270
+    /**
271
+     * Shortcut to print a simple page for users
272
+     * @param string $application The application we render the template for
273
+     * @param string $name Name of the template
274
+     * @param array $parameters Parameters for the template
275
+     * @return boolean|null
276
+     */
277
+    public static function printUserPage( $application, $name, $parameters = array() ) {
278
+        $content = new OC_Template( $application, $name, "user" );
279
+        foreach( $parameters as $key => $value ) {
280
+            $content->assign( $key, $value );
281
+        }
282
+        print $content->printPage();
283
+    }
284
+
285
+    /**
286
+     * Shortcut to print a simple page for admins
287
+     * @param string $application The application we render the template for
288
+     * @param string $name Name of the template
289
+     * @param array $parameters Parameters for the template
290
+     * @return bool
291
+     */
292
+    public static function printAdminPage( $application, $name, $parameters = array() ) {
293
+        $content = new OC_Template( $application, $name, "admin" );
294
+        foreach( $parameters as $key => $value ) {
295
+            $content->assign( $key, $value );
296
+        }
297
+        return $content->printPage();
298
+    }
299
+
300
+    /**
301
+     * Shortcut to print a simple page for guests
302
+     * @param string $application The application we render the template for
303
+     * @param string $name Name of the template
304
+     * @param array|string $parameters Parameters for the template
305
+     * @return bool
306
+     */
307
+    public static function printGuestPage( $application, $name, $parameters = array() ) {
308
+        $content = new OC_Template( $application, $name, "guest" );
309
+        foreach( $parameters as $key => $value ) {
310
+            $content->assign( $key, $value );
311
+        }
312
+        return $content->printPage();
313
+    }
314
+
315
+    /**
316
+     * Print a fatal error page and terminates the script
317
+     * @param string $error_msg The error message to show
318
+     * @param string $hint An optional hint message - needs to be properly escaped
319
+     */
320
+    public static function printErrorPage( $error_msg, $hint = '' ) {
321
+        if ($error_msg === $hint) {
322
+            // If the hint is the same as the message there is no need to display it twice.
323
+            $hint = '';
324
+        }
325
+
326
+        try {
327
+            $content = new \OC_Template( '', 'error', 'error', false );
328
+            $errors = array(array('error' => $error_msg, 'hint' => $hint));
329
+            $content->assign( 'errors', $errors );
330
+            $content->printPage();
331
+        } catch (\Exception $e) {
332
+            $logger = \OC::$server->getLogger();
333
+            $logger->error("$error_msg $hint", ['app' => 'core']);
334
+            $logger->logException($e, ['app' => 'core']);
335
+
336
+            header(self::getHttpProtocol() . ' 500 Internal Server Error');
337
+            header('Content-Type: text/plain; charset=utf-8');
338
+            print("$error_msg $hint");
339
+        }
340
+        die();
341
+    }
342
+
343
+    /**
344
+     * print error page using Exception details
345
+     * @param Exception | Throwable $exception
346
+     */
347
+    public static function printExceptionErrorPage($exception, $fetchPage = false) {
348
+        try {
349
+            $request = \OC::$server->getRequest();
350
+            $content = new \OC_Template('', 'exception', 'error', false);
351
+            $content->assign('errorClass', get_class($exception));
352
+            $content->assign('errorMsg', $exception->getMessage());
353
+            $content->assign('errorCode', $exception->getCode());
354
+            $content->assign('file', $exception->getFile());
355
+            $content->assign('line', $exception->getLine());
356
+            $content->assign('trace', $exception->getTraceAsString());
357
+            $content->assign('debugMode', \OC::$server->getSystemConfig()->getValue('debug', false));
358
+            $content->assign('remoteAddr', $request->getRemoteAddress());
359
+            $content->assign('requestID', $request->getId());
360
+            if ($fetchPage) {
361
+                return $content->fetchPage();
362
+            }
363
+            $content->printPage();
364
+        } catch (\Exception $e) {
365
+            $logger = \OC::$server->getLogger();
366
+            $logger->logException($exception, ['app' => 'core']);
367
+            $logger->logException($e, ['app' => 'core']);
368
+
369
+            header(self::getHttpProtocol() . ' 500 Internal Server Error');
370
+            header('Content-Type: text/plain; charset=utf-8');
371
+            print("Internal Server Error\n\n");
372
+            print("The server encountered an internal error and was unable to complete your request.\n");
373
+            print("Please contact the server administrator if this error reappears multiple times, please include the technical details below in your report.\n");
374
+            print("More details can be found in the server log.\n");
375
+        }
376
+        die();
377
+    }
378
+
379
+    /**
380
+     * This is only here to reduce the dependencies in case of an exception to
381
+     * still be able to print a plain error message.
382
+     *
383
+     * Returns the used HTTP protocol.
384
+     *
385
+     * @return string HTTP protocol. HTTP/2, HTTP/1.1 or HTTP/1.0.
386
+     * @internal Don't use this - use AppFramework\Http\Request->getHttpProtocol instead
387
+     */
388
+    protected static function getHttpProtocol() {
389
+        $claimedProtocol = strtoupper($_SERVER['SERVER_PROTOCOL']);
390
+        $validProtocols = [
391
+            'HTTP/1.0',
392
+            'HTTP/1.1',
393
+            'HTTP/2',
394
+        ];
395
+        if(in_array($claimedProtocol, $validProtocols, true)) {
396
+            return $claimedProtocol;
397
+        }
398
+        return 'HTTP/1.1';
399
+    }
400 400
 }
Please login to merge, or discard this patch.
Spacing   +48 added lines, -48 removed lines patch added patch discarded remove patch
@@ -69,7 +69,7 @@  discard block
 block discarded – undo
69 69
 	 *                         "admin".
70 70
 	 * @param bool $registerCall = true
71 71
 	 */
72
-	public function __construct( $app, $name, $renderAs = "", $registerCall = true ) {
72
+	public function __construct($app, $name, $renderAs = "", $registerCall = true) {
73 73
 		// Read the selected theme from the config file
74 74
 		self::initTemplateEngine($renderAs);
75 75
 
@@ -95,31 +95,31 @@  discard block
 block discarded – undo
95 95
 	 * @param string $renderAs
96 96
 	 */
97 97
 	public static function initTemplateEngine($renderAs) {
98
-		if (self::$initTemplateEngineFirstRun){
98
+		if (self::$initTemplateEngineFirstRun) {
99 99
 
100 100
 			//apps that started before the template initialization can load their own scripts/styles
101 101
 			//so to make sure this scripts/styles here are loaded first we use OC_Util::addScript() with $prepend=true
102 102
 			//meaning the last script/style in this list will be loaded first
103
-			if (\OC::$server->getSystemConfig()->getValue ('installed', false) && $renderAs !== 'error' && !\OCP\Util::needUpgrade()) {
104
-				if (\OC::$server->getConfig ()->getAppValue ( 'core', 'backgroundjobs_mode', 'ajax' ) == 'ajax') {
105
-					OC_Util::addScript ( 'backgroundjobs', null, true );
103
+			if (\OC::$server->getSystemConfig()->getValue('installed', false) && $renderAs !== 'error' && !\OCP\Util::needUpgrade()) {
104
+				if (\OC::$server->getConfig()->getAppValue('core', 'backgroundjobs_mode', 'ajax') == 'ajax') {
105
+					OC_Util::addScript('backgroundjobs', null, true);
106 106
 				}
107 107
 			}
108 108
 
109
-			OC_Util::addStyle("tooltip",null,true);
110
-			OC_Util::addStyle('jquery-ui-fixes',null,true);
111
-			OC_Util::addVendorStyle('jquery-ui/themes/base/jquery-ui',null,true);
112
-			OC_Util::addStyle("mobile",null,true);
113
-			OC_Util::addStyle("multiselect",null,true);
114
-			OC_Util::addStyle("fixes",null,true);
115
-			OC_Util::addStyle("global",null,true);
116
-			OC_Util::addStyle("apps",null,true);
117
-			OC_Util::addStyle("fonts",null,true);
118
-			OC_Util::addStyle("icons",null,true);
119
-			OC_Util::addStyle("actions",null,true);
120
-			OC_Util::addStyle("header",null,true);
109
+			OC_Util::addStyle("tooltip", null, true);
110
+			OC_Util::addStyle('jquery-ui-fixes', null, true);
111
+			OC_Util::addVendorStyle('jquery-ui/themes/base/jquery-ui', null, true);
112
+			OC_Util::addStyle("mobile", null, true);
113
+			OC_Util::addStyle("multiselect", null, true);
114
+			OC_Util::addStyle("fixes", null, true);
115
+			OC_Util::addStyle("global", null, true);
116
+			OC_Util::addStyle("apps", null, true);
117
+			OC_Util::addStyle("fonts", null, true);
118
+			OC_Util::addStyle("icons", null, true);
119
+			OC_Util::addStyle("actions", null, true);
120
+			OC_Util::addStyle("header", null, true);
121 121
 			OC_Util::addStyle("inputs");
122
-			OC_Util::addStyle("styles",null,true);
122
+			OC_Util::addStyle("styles", null, true);
123 123
 
124 124
 			// avatars
125 125
 			\OC_Util::addScript('jquery.avatar', null, true);
@@ -154,13 +154,13 @@  discard block
 block discarded – undo
154 154
 			// Add the stuff we need always
155 155
 			// following logic will import all vendor libraries that are
156 156
 			// specified in core/js/core.json
157
-			$fileContent = file_get_contents(OC::$SERVERROOT . '/core/js/core.json');
158
-			if($fileContent !== false) {
157
+			$fileContent = file_get_contents(OC::$SERVERROOT.'/core/js/core.json');
158
+			if ($fileContent !== false) {
159 159
 				$coreDependencies = json_decode($fileContent, true);
160
-				foreach(array_reverse($coreDependencies['vendor']) as $vendorLibrary) {
160
+				foreach (array_reverse($coreDependencies['vendor']) as $vendorLibrary) {
161 161
 					// remove trailing ".js" as addVendorScript will append it
162 162
 					OC_Util::addVendorScript(
163
-							substr($vendorLibrary, 0, strlen($vendorLibrary) - 3),null,true);
163
+							substr($vendorLibrary, 0, strlen($vendorLibrary) - 3), null, true);
164 164
 				}
165 165
 			} else {
166 166
 				throw new \Exception('Cannot read core/js/core.json');
@@ -191,12 +191,12 @@  discard block
 block discarded – undo
191 191
 	 */
192 192
 	protected function findTemplate($theme, $app, $name) {
193 193
 		// Check if it is a app template or not.
194
-		if( $app !== '' ) {
194
+		if ($app !== '') {
195 195
 			$dirs = $this->getAppTemplateDirs($theme, $app, OC::$SERVERROOT, OC_App::getAppPath($app));
196 196
 		} else {
197 197
 			$dirs = $this->getCoreTemplateDirs($theme, OC::$SERVERROOT);
198 198
 		}
199
-		$locator = new \OC\Template\TemplateFileLocator( $dirs );
199
+		$locator = new \OC\Template\TemplateFileLocator($dirs);
200 200
 		$template = $locator->find($name);
201 201
 		$path = $locator->getPath();
202 202
 		return array($path, $template);
@@ -209,8 +209,8 @@  discard block
 block discarded – undo
209 209
 	 * @param string $text the text content for the element. If $text is null then the
210 210
 	 * element will be written as empty element. So use "" to get a closing tag.
211 211
 	 */
212
-	public function addHeader($tag, $attributes, $text=null) {
213
-		$this->headers[]= array(
212
+	public function addHeader($tag, $attributes, $text = null) {
213
+		$this->headers[] = array(
214 214
 			'tag' => $tag,
215 215
 			'attributes' => $attributes,
216 216
 			'text' => $text
@@ -227,14 +227,14 @@  discard block
 block discarded – undo
227 227
 	public function fetchPage($additionalParams = null) {
228 228
 		$data = parent::fetchPage($additionalParams);
229 229
 
230
-		if( $this->renderAs ) {
230
+		if ($this->renderAs) {
231 231
 			$page = new TemplateLayout($this->renderAs, $this->app);
232 232
 
233 233
 			// Add custom headers
234 234
 			$headers = '';
235
-			foreach(OC_Util::$headers as $header) {
235
+			foreach (OC_Util::$headers as $header) {
236 236
 				$headers .= '<'.\OCP\Util::sanitizeHTML($header['tag']);
237
-				foreach($header['attributes'] as $name=>$value) {
237
+				foreach ($header['attributes'] as $name=>$value) {
238 238
 					$headers .= ' '.\OCP\Util::sanitizeHTML($name).'="'.\OCP\Util::sanitizeHTML($value).'"';
239 239
 				}
240 240
 				if ($header['text'] !== null) {
@@ -263,7 +263,7 @@  discard block
 block discarded – undo
263 263
 	 * Includes another template. use <?php echo $this->inc('template'); ?> to
264 264
 	 * do this.
265 265
 	 */
266
-	public function inc( $file, $additionalParams = null ) {
266
+	public function inc($file, $additionalParams = null) {
267 267
 		return $this->load($this->path.$file.'.php', $additionalParams);
268 268
 	}
269 269
 
@@ -274,10 +274,10 @@  discard block
 block discarded – undo
274 274
 	 * @param array $parameters Parameters for the template
275 275
 	 * @return boolean|null
276 276
 	 */
277
-	public static function printUserPage( $application, $name, $parameters = array() ) {
278
-		$content = new OC_Template( $application, $name, "user" );
279
-		foreach( $parameters as $key => $value ) {
280
-			$content->assign( $key, $value );
277
+	public static function printUserPage($application, $name, $parameters = array()) {
278
+		$content = new OC_Template($application, $name, "user");
279
+		foreach ($parameters as $key => $value) {
280
+			$content->assign($key, $value);
281 281
 		}
282 282
 		print $content->printPage();
283 283
 	}
@@ -289,10 +289,10 @@  discard block
 block discarded – undo
289 289
 	 * @param array $parameters Parameters for the template
290 290
 	 * @return bool
291 291
 	 */
292
-	public static function printAdminPage( $application, $name, $parameters = array() ) {
293
-		$content = new OC_Template( $application, $name, "admin" );
294
-		foreach( $parameters as $key => $value ) {
295
-			$content->assign( $key, $value );
292
+	public static function printAdminPage($application, $name, $parameters = array()) {
293
+		$content = new OC_Template($application, $name, "admin");
294
+		foreach ($parameters as $key => $value) {
295
+			$content->assign($key, $value);
296 296
 		}
297 297
 		return $content->printPage();
298 298
 	}
@@ -304,10 +304,10 @@  discard block
 block discarded – undo
304 304
 	 * @param array|string $parameters Parameters for the template
305 305
 	 * @return bool
306 306
 	 */
307
-	public static function printGuestPage( $application, $name, $parameters = array() ) {
308
-		$content = new OC_Template( $application, $name, "guest" );
309
-		foreach( $parameters as $key => $value ) {
310
-			$content->assign( $key, $value );
307
+	public static function printGuestPage($application, $name, $parameters = array()) {
308
+		$content = new OC_Template($application, $name, "guest");
309
+		foreach ($parameters as $key => $value) {
310
+			$content->assign($key, $value);
311 311
 		}
312 312
 		return $content->printPage();
313 313
 	}
@@ -317,23 +317,23 @@  discard block
 block discarded – undo
317 317
 		* @param string $error_msg The error message to show
318 318
 		* @param string $hint An optional hint message - needs to be properly escaped
319 319
 		*/
320
-	public static function printErrorPage( $error_msg, $hint = '' ) {
320
+	public static function printErrorPage($error_msg, $hint = '') {
321 321
 		if ($error_msg === $hint) {
322 322
 			// If the hint is the same as the message there is no need to display it twice.
323 323
 			$hint = '';
324 324
 		}
325 325
 
326 326
 		try {
327
-			$content = new \OC_Template( '', 'error', 'error', false );
327
+			$content = new \OC_Template('', 'error', 'error', false);
328 328
 			$errors = array(array('error' => $error_msg, 'hint' => $hint));
329
-			$content->assign( 'errors', $errors );
329
+			$content->assign('errors', $errors);
330 330
 			$content->printPage();
331 331
 		} catch (\Exception $e) {
332 332
 			$logger = \OC::$server->getLogger();
333 333
 			$logger->error("$error_msg $hint", ['app' => 'core']);
334 334
 			$logger->logException($e, ['app' => 'core']);
335 335
 
336
-			header(self::getHttpProtocol() . ' 500 Internal Server Error');
336
+			header(self::getHttpProtocol().' 500 Internal Server Error');
337 337
 			header('Content-Type: text/plain; charset=utf-8');
338 338
 			print("$error_msg $hint");
339 339
 		}
@@ -366,7 +366,7 @@  discard block
 block discarded – undo
366 366
 			$logger->logException($exception, ['app' => 'core']);
367 367
 			$logger->logException($e, ['app' => 'core']);
368 368
 
369
-			header(self::getHttpProtocol() . ' 500 Internal Server Error');
369
+			header(self::getHttpProtocol().' 500 Internal Server Error');
370 370
 			header('Content-Type: text/plain; charset=utf-8');
371 371
 			print("Internal Server Error\n\n");
372 372
 			print("The server encountered an internal error and was unable to complete your request.\n");
@@ -392,7 +392,7 @@  discard block
 block discarded – undo
392 392
 			'HTTP/1.1',
393 393
 			'HTTP/2',
394 394
 		];
395
-		if(in_array($claimedProtocol, $validProtocols, true)) {
395
+		if (in_array($claimedProtocol, $validProtocols, true)) {
396 396
 			return $claimedProtocol;
397 397
 		}
398 398
 		return 'HTTP/1.1';
Please login to merge, or discard this patch.