Passed
Push — master ( 645109...008e6d )
by Christoph
12:14 queued 12s
created
lib/private/legacy/OC_Template.php 2 patches
Indentation   +311 added lines, -311 removed lines patch added patch discarded remove patch
@@ -47,315 +47,315 @@
 block discarded – undo
47 47
  */
48 48
 class OC_Template extends \OC\Template\Base {
49 49
 
50
-	/** @var string */
51
-	private $renderAs; // Create a full page?
52
-
53
-	/** @var string */
54
-	private $path; // The path to the template
55
-
56
-	/** @var array */
57
-	private $headers = []; //custom headers
58
-
59
-	/** @var string */
60
-	protected $app; // app id
61
-
62
-	protected static $initTemplateEngineFirstRun = true;
63
-
64
-	/**
65
-	 * Constructor
66
-	 *
67
-	 * @param string $app app providing the template
68
-	 * @param string $name of the template file (without suffix)
69
-	 * @param string $renderAs If $renderAs is set, OC_Template will try to
70
-	 *                         produce a full page in the according layout. For
71
-	 *                         now, $renderAs can be set to "guest", "user" or
72
-	 *                         "admin".
73
-	 * @param bool $registerCall = true
74
-	 */
75
-	public function __construct($app, $name, $renderAs = "", $registerCall = true) {
76
-		// Read the selected theme from the config file
77
-		self::initTemplateEngine($renderAs);
78
-
79
-		$theme = OC_Util::getTheme();
80
-
81
-		$requestToken = (OC::$server->getSession() && $registerCall) ? \OCP\Util::callRegister() : '';
82
-
83
-		$parts = explode('/', $app); // fix translation when app is something like core/lostpassword
84
-		$l10n = \OC::$server->getL10N($parts[0]);
85
-		/** @var \OCP\Defaults $themeDefaults */
86
-		$themeDefaults = \OC::$server->query(\OCP\Defaults::class);
87
-
88
-		list($path, $template) = $this->findTemplate($theme, $app, $name);
89
-
90
-		// Set the private data
91
-		$this->renderAs = $renderAs;
92
-		$this->path = $path;
93
-		$this->app = $app;
94
-
95
-		parent::__construct($template, $requestToken, $l10n, $themeDefaults);
96
-	}
97
-
98
-	/**
99
-	 * @param string $renderAs
100
-	 */
101
-	public static function initTemplateEngine($renderAs) {
102
-		if (self::$initTemplateEngineFirstRun){
103
-
104
-			//apps that started before the template initialization can load their own scripts/styles
105
-			//so to make sure this scripts/styles here are loaded first we use OC_Util::addScript() with $prepend=true
106
-			//meaning the last script/style in this list will be loaded first
107
-			if (\OC::$server->getSystemConfig()->getValue('installed', false) && $renderAs !== 'error' && !\OCP\Util::needUpgrade()) {
108
-				if (\OC::$server->getConfig()->getAppValue('core', 'backgroundjobs_mode', 'ajax') == 'ajax') {
109
-					OC_Util::addScript('backgroundjobs', null, true);
110
-				}
111
-			}
112
-			OC_Util::addStyle('css-variables', null, true);
113
-			OC_Util::addStyle('server', null, true);
114
-			OC_Util::addTranslations('core', null, true);
115
-
116
-			if (\OC::$server->getSystemConfig()->getValue('installed', false)) {
117
-				OC_Util::addStyle('search', 'results');
118
-				OC_Util::addScript('search', 'search', true);
119
-				OC_Util::addScript('search', 'searchprovider');
120
-				OC_Util::addScript('merged-template-prepend', null, true);
121
-				OC_Util::addScript('files/fileinfo');
122
-				OC_Util::addScript('files/client');
123
-			}
124
-			OC_Util::addScript('core', 'dist/main', true);
125
-
126
-			if (\OC::$server->getRequest()->isUserAgent([\OC\AppFramework\Http\Request::USER_AGENT_IE])) {
127
-				// shim for the davclient.js library
128
-				\OCP\Util::addScript('files/iedavclient');
129
-			}
130
-
131
-			self::$initTemplateEngineFirstRun = false;
132
-		}
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
-	}
50
+    /** @var string */
51
+    private $renderAs; // Create a full page?
52
+
53
+    /** @var string */
54
+    private $path; // The path to the template
55
+
56
+    /** @var array */
57
+    private $headers = []; //custom headers
58
+
59
+    /** @var string */
60
+    protected $app; // app id
61
+
62
+    protected static $initTemplateEngineFirstRun = true;
63
+
64
+    /**
65
+     * Constructor
66
+     *
67
+     * @param string $app app providing the template
68
+     * @param string $name of the template file (without suffix)
69
+     * @param string $renderAs If $renderAs is set, OC_Template will try to
70
+     *                         produce a full page in the according layout. For
71
+     *                         now, $renderAs can be set to "guest", "user" or
72
+     *                         "admin".
73
+     * @param bool $registerCall = true
74
+     */
75
+    public function __construct($app, $name, $renderAs = "", $registerCall = true) {
76
+        // Read the selected theme from the config file
77
+        self::initTemplateEngine($renderAs);
78
+
79
+        $theme = OC_Util::getTheme();
80
+
81
+        $requestToken = (OC::$server->getSession() && $registerCall) ? \OCP\Util::callRegister() : '';
82
+
83
+        $parts = explode('/', $app); // fix translation when app is something like core/lostpassword
84
+        $l10n = \OC::$server->getL10N($parts[0]);
85
+        /** @var \OCP\Defaults $themeDefaults */
86
+        $themeDefaults = \OC::$server->query(\OCP\Defaults::class);
87
+
88
+        list($path, $template) = $this->findTemplate($theme, $app, $name);
89
+
90
+        // Set the private data
91
+        $this->renderAs = $renderAs;
92
+        $this->path = $path;
93
+        $this->app = $app;
94
+
95
+        parent::__construct($template, $requestToken, $l10n, $themeDefaults);
96
+    }
97
+
98
+    /**
99
+     * @param string $renderAs
100
+     */
101
+    public static function initTemplateEngine($renderAs) {
102
+        if (self::$initTemplateEngineFirstRun){
103
+
104
+            //apps that started before the template initialization can load their own scripts/styles
105
+            //so to make sure this scripts/styles here are loaded first we use OC_Util::addScript() with $prepend=true
106
+            //meaning the last script/style in this list will be loaded first
107
+            if (\OC::$server->getSystemConfig()->getValue('installed', false) && $renderAs !== 'error' && !\OCP\Util::needUpgrade()) {
108
+                if (\OC::$server->getConfig()->getAppValue('core', 'backgroundjobs_mode', 'ajax') == 'ajax') {
109
+                    OC_Util::addScript('backgroundjobs', null, true);
110
+                }
111
+            }
112
+            OC_Util::addStyle('css-variables', null, true);
113
+            OC_Util::addStyle('server', null, true);
114
+            OC_Util::addTranslations('core', null, true);
115
+
116
+            if (\OC::$server->getSystemConfig()->getValue('installed', false)) {
117
+                OC_Util::addStyle('search', 'results');
118
+                OC_Util::addScript('search', 'search', true);
119
+                OC_Util::addScript('search', 'searchprovider');
120
+                OC_Util::addScript('merged-template-prepend', null, true);
121
+                OC_Util::addScript('files/fileinfo');
122
+                OC_Util::addScript('files/client');
123
+            }
124
+            OC_Util::addScript('core', 'dist/main', true);
125
+
126
+            if (\OC::$server->getRequest()->isUserAgent([\OC\AppFramework\Http\Request::USER_AGENT_IE])) {
127
+                // shim for the davclient.js library
128
+                \OCP\Util::addScript('files/iedavclient');
129
+            }
130
+
131
+            self::$initTemplateEngineFirstRun = false;
132
+        }
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.
Spacing   +11 added lines, -11 removed lines patch added patch discarded remove patch
@@ -99,7 +99,7 @@  discard block
 block discarded – undo
99 99
 	 * @param string $renderAs
100 100
 	 */
101 101
 	public static function initTemplateEngine($renderAs) {
102
-		if (self::$initTemplateEngineFirstRun){
102
+		if (self::$initTemplateEngineFirstRun) {
103 103
 
104 104
 			//apps that started before the template initialization can load their own scripts/styles
105 105
 			//so to make sure this scripts/styles here are loaded first we use OC_Util::addScript() with $prepend=true
@@ -146,7 +146,7 @@  discard block
 block discarded – undo
146 146
 	 */
147 147
 	protected function findTemplate($theme, $app, $name) {
148 148
 		// Check if it is a app template or not.
149
-		if($app !== '') {
149
+		if ($app !== '') {
150 150
 			$dirs = $this->getAppTemplateDirs($theme, $app, OC::$SERVERROOT, OC_App::getAppPath($app));
151 151
 		} else {
152 152
 			$dirs = $this->getCoreTemplateDirs($theme, OC::$SERVERROOT);
@@ -164,8 +164,8 @@  discard block
 block discarded – undo
164 164
 	 * @param string $text the text content for the element. If $text is null then the
165 165
 	 * element will be written as empty element. So use "" to get a closing tag.
166 166
 	 */
167
-	public function addHeader($tag, $attributes, $text=null) {
168
-		$this->headers[]= [
167
+	public function addHeader($tag, $attributes, $text = null) {
168
+		$this->headers[] = [
169 169
 			'tag' => $tag,
170 170
 			'attributes' => $attributes,
171 171
 			'text' => $text
@@ -182,10 +182,10 @@  discard block
 block discarded – undo
182 182
 	public function fetchPage($additionalParams = null) {
183 183
 		$data = parent::fetchPage($additionalParams);
184 184
 
185
-		if($this->renderAs) {
185
+		if ($this->renderAs) {
186 186
 			$page = new TemplateLayout($this->renderAs, $this->app);
187 187
 
188
-			if(is_array($additionalParams)) {
188
+			if (is_array($additionalParams)) {
189 189
 				foreach ($additionalParams as $key => $value) {
190 190
 					$page->assign($key, $value);
191 191
 				}
@@ -193,12 +193,12 @@  discard block
 block discarded – undo
193 193
 
194 194
 			// Add custom headers
195 195
 			$headers = '';
196
-			foreach(OC_Util::$headers as $header) {
196
+			foreach (OC_Util::$headers as $header) {
197 197
 				$headers .= '<'.\OCP\Util::sanitizeHTML($header['tag']);
198 198
 				if (strcasecmp($header['tag'], 'script') === 0 && in_array('src', array_map('strtolower', array_keys($header['attributes'])))) {
199 199
 					$headers .= ' defer';
200 200
 				}
201
-				foreach($header['attributes'] as $name=>$value) {
201
+				foreach ($header['attributes'] as $name=>$value) {
202 202
 					$headers .= ' '.\OCP\Util::sanitizeHTML($name).'="'.\OCP\Util::sanitizeHTML($value).'"';
203 203
 				}
204 204
 				if ($header['text'] !== null) {
@@ -240,7 +240,7 @@  discard block
 block discarded – undo
240 240
 	 */
241 241
 	public static function printUserPage($application, $name, $parameters = []) {
242 242
 		$content = new OC_Template($application, $name, "user");
243
-		foreach($parameters as $key => $value) {
243
+		foreach ($parameters as $key => $value) {
244 244
 			$content->assign($key, $value);
245 245
 		}
246 246
 		print $content->printPage();
@@ -255,7 +255,7 @@  discard block
 block discarded – undo
255 255
 	 */
256 256
 	public static function printAdminPage($application, $name, $parameters = []) {
257 257
 		$content = new OC_Template($application, $name, "admin");
258
-		foreach($parameters as $key => $value) {
258
+		foreach ($parameters as $key => $value) {
259 259
 			$content->assign($key, $value);
260 260
 		}
261 261
 		return $content->printPage();
@@ -270,7 +270,7 @@  discard block
 block discarded – undo
270 270
 	 */
271 271
 	public static function printGuestPage($application, $name, $parameters = []) {
272 272
 		$content = new OC_Template($application, $name, $name === 'error' ? $name : 'guest');
273
-		foreach($parameters as $key => $value) {
273
+		foreach ($parameters as $key => $value) {
274 274
 			$content->assign($key, $value);
275 275
 		}
276 276
 		return $content->printPage();
Please login to merge, or discard this patch.
lib/private/legacy/OC_Util.php 2 patches
Indentation   +1392 added lines, -1392 removed lines patch added patch discarded remove patch
@@ -69,1402 +69,1402 @@
 block discarded – undo
69 69
 use OCP\IUser;
70 70
 
71 71
 class OC_Util {
72
-	public static $scripts = [];
73
-	public static $styles = [];
74
-	public static $headers = [];
75
-	private static $rootMounted = false;
76
-	private static $fsSetup = false;
77
-
78
-	/** @var array Local cache of version.php */
79
-	private static $versionCache = null;
80
-
81
-	protected static function getAppManager() {
82
-		return \OC::$server->getAppManager();
83
-	}
84
-
85
-	private static function initLocalStorageRootFS() {
86
-		// mount local file backend as root
87
-		$configDataDirectory = \OC::$server->getSystemConfig()->getValue("datadirectory", OC::$SERVERROOT . "/data");
88
-		//first set up the local "root" storage
89
-		\OC\Files\Filesystem::initMountManager();
90
-		if (!self::$rootMounted) {
91
-			\OC\Files\Filesystem::mount('\OC\Files\Storage\Local', ['datadir' => $configDataDirectory], '/');
92
-			self::$rootMounted = true;
93
-		}
94
-	}
95
-
96
-	/**
97
-	 * mounting an object storage as the root fs will in essence remove the
98
-	 * necessity of a data folder being present.
99
-	 * TODO make home storage aware of this and use the object storage instead of local disk access
100
-	 *
101
-	 * @param array $config containing 'class' and optional 'arguments'
102
-	 * @suppress PhanDeprecatedFunction
103
-	 */
104
-	private static function initObjectStoreRootFS($config) {
105
-		// check misconfiguration
106
-		if (empty($config['class'])) {
107
-			\OCP\Util::writeLog('files', 'No class given for objectstore', ILogger::ERROR);
108
-		}
109
-		if (!isset($config['arguments'])) {
110
-			$config['arguments'] = [];
111
-		}
112
-
113
-		// instantiate object store implementation
114
-		$name = $config['class'];
115
-		if (strpos($name, 'OCA\\') === 0 && substr_count($name, '\\') >= 2) {
116
-			$segments = explode('\\', $name);
117
-			OC_App::loadApp(strtolower($segments[1]));
118
-		}
119
-		$config['arguments']['objectstore'] = new $config['class']($config['arguments']);
120
-		// mount with plain / root object store implementation
121
-		$config['class'] = '\OC\Files\ObjectStore\ObjectStoreStorage';
122
-
123
-		// mount object storage as root
124
-		\OC\Files\Filesystem::initMountManager();
125
-		if (!self::$rootMounted) {
126
-			\OC\Files\Filesystem::mount($config['class'], $config['arguments'], '/');
127
-			self::$rootMounted = true;
128
-		}
129
-	}
130
-
131
-	/**
132
-	 * mounting an object storage as the root fs will in essence remove the
133
-	 * necessity of a data folder being present.
134
-	 *
135
-	 * @param array $config containing 'class' and optional 'arguments'
136
-	 * @suppress PhanDeprecatedFunction
137
-	 */
138
-	private static function initObjectStoreMultibucketRootFS($config) {
139
-		// check misconfiguration
140
-		if (empty($config['class'])) {
141
-			\OCP\Util::writeLog('files', 'No class given for objectstore', ILogger::ERROR);
142
-		}
143
-		if (!isset($config['arguments'])) {
144
-			$config['arguments'] = [];
145
-		}
146
-
147
-		// instantiate object store implementation
148
-		$name = $config['class'];
149
-		if (strpos($name, 'OCA\\') === 0 && substr_count($name, '\\') >= 2) {
150
-			$segments = explode('\\', $name);
151
-			OC_App::loadApp(strtolower($segments[1]));
152
-		}
153
-
154
-		if (!isset($config['arguments']['bucket'])) {
155
-			$config['arguments']['bucket'] = '';
156
-		}
157
-		// put the root FS always in first bucket for multibucket configuration
158
-		$config['arguments']['bucket'] .= '0';
159
-
160
-		$config['arguments']['objectstore'] = new $config['class']($config['arguments']);
161
-		// mount with plain / root object store implementation
162
-		$config['class'] = '\OC\Files\ObjectStore\ObjectStoreStorage';
163
-
164
-		// mount object storage as root
165
-		\OC\Files\Filesystem::initMountManager();
166
-		if (!self::$rootMounted) {
167
-			\OC\Files\Filesystem::mount($config['class'], $config['arguments'], '/');
168
-			self::$rootMounted = true;
169
-		}
170
-	}
171
-
172
-	/**
173
-	 * Can be set up
174
-	 *
175
-	 * @param string $user
176
-	 * @return boolean
177
-	 * @description configure the initial filesystem based on the configuration
178
-	 * @suppress PhanDeprecatedFunction
179
-	 * @suppress PhanAccessMethodInternal
180
-	 */
181
-	public static function setupFS($user = '') {
182
-		//setting up the filesystem twice can only lead to trouble
183
-		if (self::$fsSetup) {
184
-			return false;
185
-		}
186
-
187
-		\OC::$server->getEventLogger()->start('setup_fs', 'Setup filesystem');
188
-
189
-		// If we are not forced to load a specific user we load the one that is logged in
190
-		if ($user === null) {
191
-			$user = '';
192
-		} else if ($user == "" && \OC::$server->getUserSession()->isLoggedIn()) {
193
-			$user = OC_User::getUser();
194
-		}
195
-
196
-		// load all filesystem apps before, so no setup-hook gets lost
197
-		OC_App::loadApps(['filesystem']);
198
-
199
-		// the filesystem will finish when $user is not empty,
200
-		// mark fs setup here to avoid doing the setup from loading
201
-		// OC_Filesystem
202
-		if ($user != '') {
203
-			self::$fsSetup = true;
204
-		}
205
-
206
-		\OC\Files\Filesystem::initMountManager();
207
-
208
-		$prevLogging = \OC\Files\Filesystem::logWarningWhenAddingStorageWrapper(false);
209
-		\OC\Files\Filesystem::addStorageWrapper('mount_options', function ($mountPoint, \OCP\Files\Storage $storage, \OCP\Files\Mount\IMountPoint $mount) {
210
-			if ($storage->instanceOfStorage('\OC\Files\Storage\Common')) {
211
-				/** @var \OC\Files\Storage\Common $storage */
212
-				$storage->setMountOptions($mount->getOptions());
213
-			}
214
-			return $storage;
215
-		});
216
-
217
-		\OC\Files\Filesystem::addStorageWrapper('enable_sharing', function ($mountPoint, \OCP\Files\Storage\IStorage $storage, \OCP\Files\Mount\IMountPoint $mount) {
218
-			if (!$mount->getOption('enable_sharing', true)) {
219
-				return new \OC\Files\Storage\Wrapper\PermissionsMask([
220
-					'storage' => $storage,
221
-					'mask' => \OCP\Constants::PERMISSION_ALL - \OCP\Constants::PERMISSION_SHARE
222
-				]);
223
-			}
224
-			return $storage;
225
-		});
226
-
227
-		// install storage availability wrapper, before most other wrappers
228
-		\OC\Files\Filesystem::addStorageWrapper('oc_availability', function ($mountPoint, \OCP\Files\Storage\IStorage $storage) {
229
-			if (!$storage->instanceOfStorage('\OCA\Files_Sharing\SharedStorage') && !$storage->isLocal()) {
230
-				return new \OC\Files\Storage\Wrapper\Availability(['storage' => $storage]);
231
-			}
232
-			return $storage;
233
-		});
234
-
235
-		\OC\Files\Filesystem::addStorageWrapper('oc_encoding', function ($mountPoint, \OCP\Files\Storage $storage, \OCP\Files\Mount\IMountPoint $mount) {
236
-			if ($mount->getOption('encoding_compatibility', false) && !$storage->instanceOfStorage('\OCA\Files_Sharing\SharedStorage') && !$storage->isLocal()) {
237
-				return new \OC\Files\Storage\Wrapper\Encoding(['storage' => $storage]);
238
-			}
239
-			return $storage;
240
-		});
241
-
242
-		\OC\Files\Filesystem::addStorageWrapper('oc_quota', function ($mountPoint, $storage) {
243
-			// set up quota for home storages, even for other users
244
-			// which can happen when using sharing
245
-
246
-			/**
247
-			 * @var \OC\Files\Storage\Storage $storage
248
-			 */
249
-			if ($storage->instanceOfStorage('\OC\Files\Storage\Home')
250
-				|| $storage->instanceOfStorage('\OC\Files\ObjectStore\HomeObjectStoreStorage')
251
-			) {
252
-				/** @var \OC\Files\Storage\Home $storage */
253
-				if (is_object($storage->getUser())) {
254
-					$quota = OC_Util::getUserQuota($storage->getUser());
255
-					if ($quota !== \OCP\Files\FileInfo::SPACE_UNLIMITED) {
256
-						return new \OC\Files\Storage\Wrapper\Quota(['storage' => $storage, 'quota' => $quota, 'root' => 'files']);
257
-					}
258
-				}
259
-			}
260
-
261
-			return $storage;
262
-		});
263
-
264
-		\OC\Files\Filesystem::addStorageWrapper('readonly', function ($mountPoint, \OCP\Files\Storage\IStorage $storage, \OCP\Files\Mount\IMountPoint $mount) {
265
-			/*
72
+    public static $scripts = [];
73
+    public static $styles = [];
74
+    public static $headers = [];
75
+    private static $rootMounted = false;
76
+    private static $fsSetup = false;
77
+
78
+    /** @var array Local cache of version.php */
79
+    private static $versionCache = null;
80
+
81
+    protected static function getAppManager() {
82
+        return \OC::$server->getAppManager();
83
+    }
84
+
85
+    private static function initLocalStorageRootFS() {
86
+        // mount local file backend as root
87
+        $configDataDirectory = \OC::$server->getSystemConfig()->getValue("datadirectory", OC::$SERVERROOT . "/data");
88
+        //first set up the local "root" storage
89
+        \OC\Files\Filesystem::initMountManager();
90
+        if (!self::$rootMounted) {
91
+            \OC\Files\Filesystem::mount('\OC\Files\Storage\Local', ['datadir' => $configDataDirectory], '/');
92
+            self::$rootMounted = true;
93
+        }
94
+    }
95
+
96
+    /**
97
+     * mounting an object storage as the root fs will in essence remove the
98
+     * necessity of a data folder being present.
99
+     * TODO make home storage aware of this and use the object storage instead of local disk access
100
+     *
101
+     * @param array $config containing 'class' and optional 'arguments'
102
+     * @suppress PhanDeprecatedFunction
103
+     */
104
+    private static function initObjectStoreRootFS($config) {
105
+        // check misconfiguration
106
+        if (empty($config['class'])) {
107
+            \OCP\Util::writeLog('files', 'No class given for objectstore', ILogger::ERROR);
108
+        }
109
+        if (!isset($config['arguments'])) {
110
+            $config['arguments'] = [];
111
+        }
112
+
113
+        // instantiate object store implementation
114
+        $name = $config['class'];
115
+        if (strpos($name, 'OCA\\') === 0 && substr_count($name, '\\') >= 2) {
116
+            $segments = explode('\\', $name);
117
+            OC_App::loadApp(strtolower($segments[1]));
118
+        }
119
+        $config['arguments']['objectstore'] = new $config['class']($config['arguments']);
120
+        // mount with plain / root object store implementation
121
+        $config['class'] = '\OC\Files\ObjectStore\ObjectStoreStorage';
122
+
123
+        // mount object storage as root
124
+        \OC\Files\Filesystem::initMountManager();
125
+        if (!self::$rootMounted) {
126
+            \OC\Files\Filesystem::mount($config['class'], $config['arguments'], '/');
127
+            self::$rootMounted = true;
128
+        }
129
+    }
130
+
131
+    /**
132
+     * mounting an object storage as the root fs will in essence remove the
133
+     * necessity of a data folder being present.
134
+     *
135
+     * @param array $config containing 'class' and optional 'arguments'
136
+     * @suppress PhanDeprecatedFunction
137
+     */
138
+    private static function initObjectStoreMultibucketRootFS($config) {
139
+        // check misconfiguration
140
+        if (empty($config['class'])) {
141
+            \OCP\Util::writeLog('files', 'No class given for objectstore', ILogger::ERROR);
142
+        }
143
+        if (!isset($config['arguments'])) {
144
+            $config['arguments'] = [];
145
+        }
146
+
147
+        // instantiate object store implementation
148
+        $name = $config['class'];
149
+        if (strpos($name, 'OCA\\') === 0 && substr_count($name, '\\') >= 2) {
150
+            $segments = explode('\\', $name);
151
+            OC_App::loadApp(strtolower($segments[1]));
152
+        }
153
+
154
+        if (!isset($config['arguments']['bucket'])) {
155
+            $config['arguments']['bucket'] = '';
156
+        }
157
+        // put the root FS always in first bucket for multibucket configuration
158
+        $config['arguments']['bucket'] .= '0';
159
+
160
+        $config['arguments']['objectstore'] = new $config['class']($config['arguments']);
161
+        // mount with plain / root object store implementation
162
+        $config['class'] = '\OC\Files\ObjectStore\ObjectStoreStorage';
163
+
164
+        // mount object storage as root
165
+        \OC\Files\Filesystem::initMountManager();
166
+        if (!self::$rootMounted) {
167
+            \OC\Files\Filesystem::mount($config['class'], $config['arguments'], '/');
168
+            self::$rootMounted = true;
169
+        }
170
+    }
171
+
172
+    /**
173
+     * Can be set up
174
+     *
175
+     * @param string $user
176
+     * @return boolean
177
+     * @description configure the initial filesystem based on the configuration
178
+     * @suppress PhanDeprecatedFunction
179
+     * @suppress PhanAccessMethodInternal
180
+     */
181
+    public static function setupFS($user = '') {
182
+        //setting up the filesystem twice can only lead to trouble
183
+        if (self::$fsSetup) {
184
+            return false;
185
+        }
186
+
187
+        \OC::$server->getEventLogger()->start('setup_fs', 'Setup filesystem');
188
+
189
+        // If we are not forced to load a specific user we load the one that is logged in
190
+        if ($user === null) {
191
+            $user = '';
192
+        } else if ($user == "" && \OC::$server->getUserSession()->isLoggedIn()) {
193
+            $user = OC_User::getUser();
194
+        }
195
+
196
+        // load all filesystem apps before, so no setup-hook gets lost
197
+        OC_App::loadApps(['filesystem']);
198
+
199
+        // the filesystem will finish when $user is not empty,
200
+        // mark fs setup here to avoid doing the setup from loading
201
+        // OC_Filesystem
202
+        if ($user != '') {
203
+            self::$fsSetup = true;
204
+        }
205
+
206
+        \OC\Files\Filesystem::initMountManager();
207
+
208
+        $prevLogging = \OC\Files\Filesystem::logWarningWhenAddingStorageWrapper(false);
209
+        \OC\Files\Filesystem::addStorageWrapper('mount_options', function ($mountPoint, \OCP\Files\Storage $storage, \OCP\Files\Mount\IMountPoint $mount) {
210
+            if ($storage->instanceOfStorage('\OC\Files\Storage\Common')) {
211
+                /** @var \OC\Files\Storage\Common $storage */
212
+                $storage->setMountOptions($mount->getOptions());
213
+            }
214
+            return $storage;
215
+        });
216
+
217
+        \OC\Files\Filesystem::addStorageWrapper('enable_sharing', function ($mountPoint, \OCP\Files\Storage\IStorage $storage, \OCP\Files\Mount\IMountPoint $mount) {
218
+            if (!$mount->getOption('enable_sharing', true)) {
219
+                return new \OC\Files\Storage\Wrapper\PermissionsMask([
220
+                    'storage' => $storage,
221
+                    'mask' => \OCP\Constants::PERMISSION_ALL - \OCP\Constants::PERMISSION_SHARE
222
+                ]);
223
+            }
224
+            return $storage;
225
+        });
226
+
227
+        // install storage availability wrapper, before most other wrappers
228
+        \OC\Files\Filesystem::addStorageWrapper('oc_availability', function ($mountPoint, \OCP\Files\Storage\IStorage $storage) {
229
+            if (!$storage->instanceOfStorage('\OCA\Files_Sharing\SharedStorage') && !$storage->isLocal()) {
230
+                return new \OC\Files\Storage\Wrapper\Availability(['storage' => $storage]);
231
+            }
232
+            return $storage;
233
+        });
234
+
235
+        \OC\Files\Filesystem::addStorageWrapper('oc_encoding', function ($mountPoint, \OCP\Files\Storage $storage, \OCP\Files\Mount\IMountPoint $mount) {
236
+            if ($mount->getOption('encoding_compatibility', false) && !$storage->instanceOfStorage('\OCA\Files_Sharing\SharedStorage') && !$storage->isLocal()) {
237
+                return new \OC\Files\Storage\Wrapper\Encoding(['storage' => $storage]);
238
+            }
239
+            return $storage;
240
+        });
241
+
242
+        \OC\Files\Filesystem::addStorageWrapper('oc_quota', function ($mountPoint, $storage) {
243
+            // set up quota for home storages, even for other users
244
+            // which can happen when using sharing
245
+
246
+            /**
247
+             * @var \OC\Files\Storage\Storage $storage
248
+             */
249
+            if ($storage->instanceOfStorage('\OC\Files\Storage\Home')
250
+                || $storage->instanceOfStorage('\OC\Files\ObjectStore\HomeObjectStoreStorage')
251
+            ) {
252
+                /** @var \OC\Files\Storage\Home $storage */
253
+                if (is_object($storage->getUser())) {
254
+                    $quota = OC_Util::getUserQuota($storage->getUser());
255
+                    if ($quota !== \OCP\Files\FileInfo::SPACE_UNLIMITED) {
256
+                        return new \OC\Files\Storage\Wrapper\Quota(['storage' => $storage, 'quota' => $quota, 'root' => 'files']);
257
+                    }
258
+                }
259
+            }
260
+
261
+            return $storage;
262
+        });
263
+
264
+        \OC\Files\Filesystem::addStorageWrapper('readonly', function ($mountPoint, \OCP\Files\Storage\IStorage $storage, \OCP\Files\Mount\IMountPoint $mount) {
265
+            /*
266 266
 			 * Do not allow any operations that modify the storage
267 267
 			 */
268
-			if ($mount->getOption('readonly', false)) {
269
-				return new \OC\Files\Storage\Wrapper\PermissionsMask([
270
-					'storage' => $storage,
271
-					'mask' => \OCP\Constants::PERMISSION_ALL & ~(
272
-						\OCP\Constants::PERMISSION_UPDATE |
273
-						\OCP\Constants::PERMISSION_CREATE |
274
-						\OCP\Constants::PERMISSION_DELETE
275
-					),
276
-				]);
277
-			}
278
-			return $storage;
279
-		});
280
-
281
-		OC_Hook::emit('OC_Filesystem', 'preSetup', ['user' => $user]);
282
-
283
-		\OC\Files\Filesystem::logWarningWhenAddingStorageWrapper($prevLogging);
284
-
285
-		//check if we are using an object storage
286
-		$objectStore = \OC::$server->getSystemConfig()->getValue('objectstore', null);
287
-		$objectStoreMultibucket = \OC::$server->getSystemConfig()->getValue('objectstore_multibucket', null);
288
-
289
-		// use the same order as in ObjectHomeMountProvider
290
-		if (isset($objectStoreMultibucket)) {
291
-			self::initObjectStoreMultibucketRootFS($objectStoreMultibucket);
292
-		} elseif (isset($objectStore)) {
293
-			self::initObjectStoreRootFS($objectStore);
294
-		} else {
295
-			self::initLocalStorageRootFS();
296
-		}
297
-
298
-		if ($user != '' && !\OC::$server->getUserManager()->userExists($user)) {
299
-			\OC::$server->getEventLogger()->end('setup_fs');
300
-			return false;
301
-		}
302
-
303
-		//if we aren't logged in, there is no use to set up the filesystem
304
-		if ($user != "") {
305
-
306
-			$userDir = '/' . $user . '/files';
307
-
308
-			//jail the user into his "home" directory
309
-			\OC\Files\Filesystem::init($user, $userDir);
310
-
311
-			OC_Hook::emit('OC_Filesystem', 'setup', ['user' => $user, 'user_dir' => $userDir]);
312
-		}
313
-		\OC::$server->getEventLogger()->end('setup_fs');
314
-		return true;
315
-	}
316
-
317
-	/**
318
-	 * check if a password is required for each public link
319
-	 *
320
-	 * @return boolean
321
-	 * @suppress PhanDeprecatedFunction
322
-	 */
323
-	public static function isPublicLinkPasswordRequired() {
324
-		$enforcePassword = \OC::$server->getConfig()->getAppValue('core', 'shareapi_enforce_links_password', 'no');
325
-		return $enforcePassword === 'yes';
326
-	}
327
-
328
-	/**
329
-	 * check if sharing is disabled for the current user
330
-	 * @param IConfig $config
331
-	 * @param IGroupManager $groupManager
332
-	 * @param IUser|null $user
333
-	 * @return bool
334
-	 */
335
-	public static function isSharingDisabledForUser(IConfig $config, IGroupManager $groupManager, $user) {
336
-		if ($config->getAppValue('core', 'shareapi_exclude_groups', 'no') === 'yes') {
337
-			$groupsList = $config->getAppValue('core', 'shareapi_exclude_groups_list', '');
338
-			$excludedGroups = json_decode($groupsList);
339
-			if (is_null($excludedGroups)) {
340
-				$excludedGroups = explode(',', $groupsList);
341
-				$newValue = json_encode($excludedGroups);
342
-				$config->setAppValue('core', 'shareapi_exclude_groups_list', $newValue);
343
-			}
344
-			$usersGroups = $groupManager->getUserGroupIds($user);
345
-			if (!empty($usersGroups)) {
346
-				$remainingGroups = array_diff($usersGroups, $excludedGroups);
347
-				// if the user is only in groups which are disabled for sharing then
348
-				// sharing is also disabled for the user
349
-				if (empty($remainingGroups)) {
350
-					return true;
351
-				}
352
-			}
353
-		}
354
-		return false;
355
-	}
356
-
357
-	/**
358
-	 * check if share API enforces a default expire date
359
-	 *
360
-	 * @return boolean
361
-	 * @suppress PhanDeprecatedFunction
362
-	 */
363
-	public static function isDefaultExpireDateEnforced() {
364
-		$isDefaultExpireDateEnabled = \OC::$server->getConfig()->getAppValue('core', 'shareapi_default_expire_date', 'no');
365
-		$enforceDefaultExpireDate = false;
366
-		if ($isDefaultExpireDateEnabled === 'yes') {
367
-			$value = \OC::$server->getConfig()->getAppValue('core', 'shareapi_enforce_expire_date', 'no');
368
-			$enforceDefaultExpireDate = $value === 'yes';
369
-		}
370
-
371
-		return $enforceDefaultExpireDate;
372
-	}
373
-
374
-	/**
375
-	 * Get the quota of a user
376
-	 *
377
-	 * @param IUser|null $user
378
-	 * @return float Quota bytes
379
-	 */
380
-	public static function getUserQuota(?IUser $user) {
381
-		if (is_null($user)) {
382
-			return \OCP\Files\FileInfo::SPACE_UNLIMITED;
383
-		}
384
-		$userQuota = $user->getQuota();
385
-		if($userQuota === 'none') {
386
-			return \OCP\Files\FileInfo::SPACE_UNLIMITED;
387
-		}
388
-		return OC_Helper::computerFileSize($userQuota);
389
-	}
390
-
391
-	/**
392
-	 * copies the skeleton to the users /files
393
-	 *
394
-	 * @param string $userId
395
-	 * @param \OCP\Files\Folder $userDirectory
396
-	 * @throws \OCP\Files\NotFoundException
397
-	 * @throws \OCP\Files\NotPermittedException
398
-	 * @suppress PhanDeprecatedFunction
399
-	 */
400
-	public static function copySkeleton($userId, \OCP\Files\Folder $userDirectory) {
401
-
402
-		$plainSkeletonDirectory = \OC::$server->getConfig()->getSystemValue('skeletondirectory', \OC::$SERVERROOT . '/core/skeleton');
403
-		$userLang = \OC::$server->getL10NFactory()->findLanguage();
404
-		$skeletonDirectory = str_replace('{lang}', $userLang, $plainSkeletonDirectory);
405
-
406
-		if (!file_exists($skeletonDirectory)) {
407
-			$dialectStart = strpos($userLang, '_');
408
-			if ($dialectStart !== false) {
409
-				$skeletonDirectory = str_replace('{lang}', substr($userLang, 0, $dialectStart), $plainSkeletonDirectory);
410
-			}
411
-			if ($dialectStart === false || !file_exists($skeletonDirectory)) {
412
-				$skeletonDirectory = str_replace('{lang}', 'default', $plainSkeletonDirectory);
413
-			}
414
-			if (!file_exists($skeletonDirectory)) {
415
-				$skeletonDirectory = '';
416
-			}
417
-		}
418
-
419
-		$instanceId = \OC::$server->getConfig()->getSystemValue('instanceid', '');
420
-
421
-		if ($instanceId === null) {
422
-			throw new \RuntimeException('no instance id!');
423
-		}
424
-		$appdata = 'appdata_' . $instanceId;
425
-		if ($userId === $appdata) {
426
-			throw new \RuntimeException('username is reserved name: ' . $appdata);
427
-		}
428
-
429
-		if (!empty($skeletonDirectory)) {
430
-			\OCP\Util::writeLog(
431
-				'files_skeleton',
432
-				'copying skeleton for '.$userId.' from '.$skeletonDirectory.' to '.$userDirectory->getFullPath('/'),
433
-				ILogger::DEBUG
434
-			);
435
-			self::copyr($skeletonDirectory, $userDirectory);
436
-			// update the file cache
437
-			$userDirectory->getStorage()->getScanner()->scan('', \OC\Files\Cache\Scanner::SCAN_RECURSIVE);
438
-		}
439
-	}
440
-
441
-	/**
442
-	 * copies a directory recursively by using streams
443
-	 *
444
-	 * @param string $source
445
-	 * @param \OCP\Files\Folder $target
446
-	 * @return void
447
-	 */
448
-	public static function copyr($source, \OCP\Files\Folder $target) {
449
-		$logger = \OC::$server->getLogger();
450
-
451
-		// Verify if folder exists
452
-		$dir = opendir($source);
453
-		if($dir === false) {
454
-			$logger->error(sprintf('Could not opendir "%s"', $source), ['app' => 'core']);
455
-			return;
456
-		}
457
-
458
-		// Copy the files
459
-		while (false !== ($file = readdir($dir))) {
460
-			if (!\OC\Files\Filesystem::isIgnoredDir($file)) {
461
-				if (is_dir($source . '/' . $file)) {
462
-					$child = $target->newFolder($file);
463
-					self::copyr($source . '/' . $file, $child);
464
-				} else {
465
-					$child = $target->newFile($file);
466
-					$sourceStream = fopen($source . '/' . $file, 'r');
467
-					if($sourceStream === false) {
468
-						$logger->error(sprintf('Could not fopen "%s"', $source . '/' . $file), ['app' => 'core']);
469
-						closedir($dir);
470
-						return;
471
-					}
472
-					stream_copy_to_stream($sourceStream, $child->fopen('w'));
473
-				}
474
-			}
475
-		}
476
-		closedir($dir);
477
-	}
478
-
479
-	/**
480
-	 * @return void
481
-	 * @suppress PhanUndeclaredMethod
482
-	 */
483
-	public static function tearDownFS() {
484
-		\OC\Files\Filesystem::tearDown();
485
-		\OC::$server->getRootFolder()->clearCache();
486
-		self::$fsSetup = false;
487
-		self::$rootMounted = false;
488
-	}
489
-
490
-	/**
491
-	 * get the current installed version of ownCloud
492
-	 *
493
-	 * @return array
494
-	 */
495
-	public static function getVersion() {
496
-		OC_Util::loadVersion();
497
-		return self::$versionCache['OC_Version'];
498
-	}
499
-
500
-	/**
501
-	 * get the current installed version string of ownCloud
502
-	 *
503
-	 * @return string
504
-	 */
505
-	public static function getVersionString() {
506
-		OC_Util::loadVersion();
507
-		return self::$versionCache['OC_VersionString'];
508
-	}
509
-
510
-	/**
511
-	 * @deprecated the value is of no use anymore
512
-	 * @return string
513
-	 */
514
-	public static function getEditionString() {
515
-		return '';
516
-	}
517
-
518
-	/**
519
-	 * @description get the update channel of the current installed of ownCloud.
520
-	 * @return string
521
-	 */
522
-	public static function getChannel() {
523
-		OC_Util::loadVersion();
524
-		return \OC::$server->getConfig()->getSystemValue('updater.release.channel', self::$versionCache['OC_Channel']);
525
-	}
526
-
527
-	/**
528
-	 * @description get the build number of the current installed of ownCloud.
529
-	 * @return string
530
-	 */
531
-	public static function getBuild() {
532
-		OC_Util::loadVersion();
533
-		return self::$versionCache['OC_Build'];
534
-	}
535
-
536
-	/**
537
-	 * @description load the version.php into the session as cache
538
-	 * @suppress PhanUndeclaredVariable
539
-	 */
540
-	private static function loadVersion() {
541
-		if (self::$versionCache !== null) {
542
-			return;
543
-		}
544
-
545
-		$timestamp = filemtime(OC::$SERVERROOT . '/version.php');
546
-		require OC::$SERVERROOT . '/version.php';
547
-		/** @var $timestamp int */
548
-		self::$versionCache['OC_Version_Timestamp'] = $timestamp;
549
-		/** @var $OC_Version string */
550
-		self::$versionCache['OC_Version'] = $OC_Version;
551
-		/** @var $OC_VersionString string */
552
-		self::$versionCache['OC_VersionString'] = $OC_VersionString;
553
-		/** @var $OC_Build string */
554
-		self::$versionCache['OC_Build'] = $OC_Build;
555
-
556
-		/** @var $OC_Channel string */
557
-		self::$versionCache['OC_Channel'] = $OC_Channel;
558
-	}
559
-
560
-	/**
561
-	 * generates a path for JS/CSS files. If no application is provided it will create the path for core.
562
-	 *
563
-	 * @param string $application application to get the files from
564
-	 * @param string $directory directory within this application (css, js, vendor, etc)
565
-	 * @param string $file the file inside of the above folder
566
-	 * @return string the path
567
-	 */
568
-	private static function generatePath($application, $directory, $file) {
569
-		if (is_null($file)) {
570
-			$file = $application;
571
-			$application = "";
572
-		}
573
-		if (!empty($application)) {
574
-			return "$application/$directory/$file";
575
-		} else {
576
-			return "$directory/$file";
577
-		}
578
-	}
579
-
580
-	/**
581
-	 * add a javascript file
582
-	 *
583
-	 * @param string $application application id
584
-	 * @param string|null $file filename
585
-	 * @param bool $prepend prepend the Script to the beginning of the list
586
-	 * @return void
587
-	 */
588
-	public static function addScript($application, $file = null, $prepend = false) {
589
-		$path = OC_Util::generatePath($application, 'js', $file);
590
-
591
-		// core js files need separate handling
592
-		if ($application !== 'core' && $file !== null) {
593
-			self::addTranslations($application);
594
-		}
595
-		self::addExternalResource($application, $prepend, $path, "script");
596
-	}
597
-
598
-	/**
599
-	 * add a javascript file from the vendor sub folder
600
-	 *
601
-	 * @param string $application application id
602
-	 * @param string|null $file filename
603
-	 * @param bool $prepend prepend the Script to the beginning of the list
604
-	 * @return void
605
-	 */
606
-	public static function addVendorScript($application, $file = null, $prepend = false) {
607
-		$path = OC_Util::generatePath($application, 'vendor', $file);
608
-		self::addExternalResource($application, $prepend, $path, "script");
609
-	}
610
-
611
-	/**
612
-	 * add a translation JS file
613
-	 *
614
-	 * @param string $application application id
615
-	 * @param string|null $languageCode language code, defaults to the current language
616
-	 * @param bool|null $prepend prepend the Script to the beginning of the list
617
-	 */
618
-	public static function addTranslations($application, $languageCode = null, $prepend = false) {
619
-		if (is_null($languageCode)) {
620
-			$languageCode = \OC::$server->getL10NFactory()->findLanguage($application);
621
-		}
622
-		if (!empty($application)) {
623
-			$path = "$application/l10n/$languageCode";
624
-		} else {
625
-			$path = "l10n/$languageCode";
626
-		}
627
-		self::addExternalResource($application, $prepend, $path, "script");
628
-	}
629
-
630
-	/**
631
-	 * add a css file
632
-	 *
633
-	 * @param string $application application id
634
-	 * @param string|null $file filename
635
-	 * @param bool $prepend prepend the Style to the beginning of the list
636
-	 * @return void
637
-	 */
638
-	public static function addStyle($application, $file = null, $prepend = false) {
639
-		$path = OC_Util::generatePath($application, 'css', $file);
640
-		self::addExternalResource($application, $prepend, $path, "style");
641
-	}
642
-
643
-	/**
644
-	 * add a css file from the vendor sub folder
645
-	 *
646
-	 * @param string $application application id
647
-	 * @param string|null $file filename
648
-	 * @param bool $prepend prepend the Style to the beginning of the list
649
-	 * @return void
650
-	 */
651
-	public static function addVendorStyle($application, $file = null, $prepend = false) {
652
-		$path = OC_Util::generatePath($application, 'vendor', $file);
653
-		self::addExternalResource($application, $prepend, $path, "style");
654
-	}
655
-
656
-	/**
657
-	 * add an external resource css/js file
658
-	 *
659
-	 * @param string $application application id
660
-	 * @param bool $prepend prepend the file to the beginning of the list
661
-	 * @param string $path
662
-	 * @param string $type (script or style)
663
-	 * @return void
664
-	 */
665
-	private static function addExternalResource($application, $prepend, $path, $type = "script") {
666
-
667
-		if ($type === "style") {
668
-			if (!in_array($path, self::$styles)) {
669
-				if ($prepend === true) {
670
-					array_unshift(self::$styles, $path);
671
-				} else {
672
-					self::$styles[] = $path;
673
-				}
674
-			}
675
-		} elseif ($type === "script") {
676
-			if (!in_array($path, self::$scripts)) {
677
-				if ($prepend === true) {
678
-					array_unshift(self::$scripts, $path);
679
-				} else {
680
-					self::$scripts [] = $path;
681
-				}
682
-			}
683
-		}
684
-	}
685
-
686
-	/**
687
-	 * Add a custom element to the header
688
-	 * If $text is null then the element will be written as empty element.
689
-	 * So use "" to get a closing tag.
690
-	 * @param string $tag tag name of the element
691
-	 * @param array $attributes array of attributes for the element
692
-	 * @param string $text the text content for the element
693
-	 * @param bool $prepend prepend the header to the beginning of the list
694
-	 */
695
-	public static function addHeader($tag, $attributes, $text = null, $prepend = false) {
696
-		$header = [
697
-			'tag' => $tag,
698
-			'attributes' => $attributes,
699
-			'text' => $text
700
-		];
701
-		if ($prepend === true) {
702
-			array_unshift(self::$headers, $header);
703
-
704
-		} else {
705
-			self::$headers[] = $header;
706
-		}
707
-	}
708
-
709
-	/**
710
-	 * check if the current server configuration is suitable for ownCloud
711
-	 *
712
-	 * @param \OC\SystemConfig $config
713
-	 * @return array arrays with error messages and hints
714
-	 */
715
-	public static function checkServer(\OC\SystemConfig $config) {
716
-		$l = \OC::$server->getL10N('lib');
717
-		$errors = [];
718
-		$CONFIG_DATADIRECTORY = $config->getValue('datadirectory', OC::$SERVERROOT . '/data');
719
-
720
-		if (!self::needUpgrade($config) && $config->getValue('installed', false)) {
721
-			// this check needs to be done every time
722
-			$errors = self::checkDataDirectoryValidity($CONFIG_DATADIRECTORY);
723
-		}
724
-
725
-		// Assume that if checkServer() succeeded before in this session, then all is fine.
726
-		if (\OC::$server->getSession()->exists('checkServer_succeeded') && \OC::$server->getSession()->get('checkServer_succeeded')) {
727
-			return $errors;
728
-		}
729
-
730
-		$webServerRestart = false;
731
-		$setup = new \OC\Setup(
732
-			$config,
733
-			\OC::$server->getIniWrapper(),
734
-			\OC::$server->getL10N('lib'),
735
-			\OC::$server->query(\OCP\Defaults::class),
736
-			\OC::$server->getLogger(),
737
-			\OC::$server->getSecureRandom(),
738
-			\OC::$server->query(\OC\Installer::class)
739
-		);
740
-
741
-		$urlGenerator = \OC::$server->getURLGenerator();
742
-
743
-		$availableDatabases = $setup->getSupportedDatabases();
744
-		if (empty($availableDatabases)) {
745
-			$errors[] = [
746
-				'error' => $l->t('No database drivers (sqlite, mysql, or postgresql) installed.'),
747
-				'hint' => '' //TODO: sane hint
748
-			];
749
-			$webServerRestart = true;
750
-		}
751
-
752
-		// Check if config folder is writable.
753
-		if(!OC_Helper::isReadOnlyConfigEnabled()) {
754
-			if (!is_writable(OC::$configDir) or !is_readable(OC::$configDir)) {
755
-				$errors[] = [
756
-					'error' => $l->t('Cannot write into "config" directory'),
757
-					'hint' => $l->t('This can usually be fixed by giving the webserver write access to the config directory. See %s',
758
-						[ $urlGenerator->linkToDocs('admin-dir_permissions') ]) . '. '
759
-						. $l->t('Or, if you prefer to keep config.php file read only, set the option "config_is_read_only" to true in it. See %s',
760
-						[ $urlGenerator->linkToDocs('admin-config') ])
761
-				];
762
-			}
763
-		}
764
-
765
-		// Check if there is a writable install folder.
766
-		if ($config->getValue('appstoreenabled', true)) {
767
-			if (OC_App::getInstallPath() === null
768
-				|| !is_writable(OC_App::getInstallPath())
769
-				|| !is_readable(OC_App::getInstallPath())
770
-			) {
771
-				$errors[] = [
772
-					'error' => $l->t('Cannot write into "apps" directory'),
773
-					'hint' => $l->t('This can usually be fixed by giving the webserver write access to the apps directory'
774
-						. ' or disabling the appstore in the config file.')
775
-				];
776
-			}
777
-		}
778
-		// Create root dir.
779
-		if ($config->getValue('installed', false)) {
780
-			if (!is_dir($CONFIG_DATADIRECTORY)) {
781
-				$success = @mkdir($CONFIG_DATADIRECTORY);
782
-				if ($success) {
783
-					$errors = array_merge($errors, self::checkDataDirectoryPermissions($CONFIG_DATADIRECTORY));
784
-				} else {
785
-					$errors[] = [
786
-						'error' => $l->t('Cannot create "data" directory'),
787
-						'hint' => $l->t('This can usually be fixed by giving the webserver write access to the root directory. See %s',
788
-							[$urlGenerator->linkToDocs('admin-dir_permissions')])
789
-					];
790
-				}
791
-			} else if (!is_writable($CONFIG_DATADIRECTORY) or !is_readable($CONFIG_DATADIRECTORY)) {
792
-				// is_writable doesn't work for NFS mounts, so try to write a file and check if it exists.
793
-				$testFile = sprintf('%s/%s.tmp', $CONFIG_DATADIRECTORY, uniqid('data_dir_writability_test_'));
794
-				$handle = fopen($testFile, 'w');
795
-				if (!$handle || fwrite($handle, 'Test write operation') === false) {
796
-					$permissionsHint = $l->t('Permissions can usually be fixed by giving the webserver write access to the root directory. See %s.',
797
-						[$urlGenerator->linkToDocs('admin-dir_permissions')]);
798
-					$errors[] = [
799
-						'error' => 'Your data directory is not writable',
800
-						'hint' => $permissionsHint
801
-					];
802
-				} else {
803
-					fclose($handle);
804
-					unlink($testFile);
805
-				}
806
-			} else {
807
-				$errors = array_merge($errors, self::checkDataDirectoryPermissions($CONFIG_DATADIRECTORY));
808
-			}
809
-		}
810
-
811
-		if (!OC_Util::isSetLocaleWorking()) {
812
-			$errors[] = [
813
-				'error' => $l->t('Setting locale to %s failed',
814
-					['en_US.UTF-8/fr_FR.UTF-8/es_ES.UTF-8/de_DE.UTF-8/ru_RU.UTF-8/'
815
-						. 'pt_BR.UTF-8/it_IT.UTF-8/ja_JP.UTF-8/zh_CN.UTF-8']),
816
-				'hint' => $l->t('Please install one of these locales on your system and restart your webserver.')
817
-			];
818
-		}
819
-
820
-		// Contains the dependencies that should be checked against
821
-		// classes = class_exists
822
-		// functions = function_exists
823
-		// defined = defined
824
-		// ini = ini_get
825
-		// If the dependency is not found the missing module name is shown to the EndUser
826
-		// When adding new checks always verify that they pass on Travis as well
827
-		// for ini settings, see https://github.com/owncloud/administration/blob/master/travis-ci/custom.ini
828
-		$dependencies = [
829
-			'classes' => [
830
-				'ZipArchive' => 'zip',
831
-				'DOMDocument' => 'dom',
832
-				'XMLWriter' => 'XMLWriter',
833
-				'XMLReader' => 'XMLReader',
834
-			],
835
-			'functions' => [
836
-				'xml_parser_create' => 'libxml',
837
-				'mb_strcut' => 'mbstring',
838
-				'ctype_digit' => 'ctype',
839
-				'json_encode' => 'JSON',
840
-				'gd_info' => 'GD',
841
-				'gzencode' => 'zlib',
842
-				'iconv' => 'iconv',
843
-				'simplexml_load_string' => 'SimpleXML',
844
-				'hash' => 'HASH Message Digest Framework',
845
-				'curl_init' => 'cURL',
846
-				'openssl_verify' => 'OpenSSL',
847
-			],
848
-			'defined' => [
849
-				'PDO::ATTR_DRIVER_NAME' => 'PDO'
850
-			],
851
-			'ini' => [
852
-				'default_charset' => 'UTF-8',
853
-			],
854
-		];
855
-		$missingDependencies = [];
856
-		$invalidIniSettings = [];
857
-		$moduleHint = $l->t('Please ask your server administrator to install the module.');
858
-
859
-		$iniWrapper = \OC::$server->getIniWrapper();
860
-		foreach ($dependencies['classes'] as $class => $module) {
861
-			if (!class_exists($class)) {
862
-				$missingDependencies[] = $module;
863
-			}
864
-		}
865
-		foreach ($dependencies['functions'] as $function => $module) {
866
-			if (!function_exists($function)) {
867
-				$missingDependencies[] = $module;
868
-			}
869
-		}
870
-		foreach ($dependencies['defined'] as $defined => $module) {
871
-			if (!defined($defined)) {
872
-				$missingDependencies[] = $module;
873
-			}
874
-		}
875
-		foreach ($dependencies['ini'] as $setting => $expected) {
876
-			if (is_bool($expected)) {
877
-				if ($iniWrapper->getBool($setting) !== $expected) {
878
-					$invalidIniSettings[] = [$setting, $expected];
879
-				}
880
-			}
881
-			if (is_int($expected)) {
882
-				if ($iniWrapper->getNumeric($setting) !== $expected) {
883
-					$invalidIniSettings[] = [$setting, $expected];
884
-				}
885
-			}
886
-			if (is_string($expected)) {
887
-				if (strtolower($iniWrapper->getString($setting)) !== strtolower($expected)) {
888
-					$invalidIniSettings[] = [$setting, $expected];
889
-				}
890
-			}
891
-		}
892
-
893
-		foreach($missingDependencies as $missingDependency) {
894
-			$errors[] = [
895
-				'error' => $l->t('PHP module %s not installed.', [$missingDependency]),
896
-				'hint' => $moduleHint
897
-			];
898
-			$webServerRestart = true;
899
-		}
900
-		foreach($invalidIniSettings as $setting) {
901
-			if(is_bool($setting[1])) {
902
-				$setting[1] = $setting[1] ? 'on' : 'off';
903
-			}
904
-			$errors[] = [
905
-				'error' => $l->t('PHP setting "%s" is not set to "%s".', [$setting[0], var_export($setting[1], true)]),
906
-				'hint' =>  $l->t('Adjusting this setting in php.ini will make Nextcloud run again')
907
-			];
908
-			$webServerRestart = true;
909
-		}
910
-
911
-		/**
912
-		 * The mbstring.func_overload check can only be performed if the mbstring
913
-		 * module is installed as it will return null if the checking setting is
914
-		 * not available and thus a check on the boolean value fails.
915
-		 *
916
-		 * TODO: Should probably be implemented in the above generic dependency
917
-		 *       check somehow in the long-term.
918
-		 */
919
-		if($iniWrapper->getBool('mbstring.func_overload') !== null &&
920
-			$iniWrapper->getBool('mbstring.func_overload') === true) {
921
-			$errors[] = [
922
-				'error' => $l->t('mbstring.func_overload is set to "%s" instead of the expected value "0"', [$iniWrapper->getString('mbstring.func_overload')]),
923
-				'hint' => $l->t('To fix this issue set <code>mbstring.func_overload</code> to <code>0</code> in your php.ini')
924
-			];
925
-		}
926
-
927
-		if(function_exists('xml_parser_create') &&
928
-			LIBXML_LOADED_VERSION < 20700) {
929
-			$version = LIBXML_LOADED_VERSION;
930
-			$major = floor($version/10000);
931
-			$version -= ($major * 10000);
932
-			$minor = floor($version/100);
933
-			$version -= ($minor * 100);
934
-			$patch = $version;
935
-			$errors[] = [
936
-				'error' => $l->t('libxml2 2.7.0 is at least required. Currently %s is installed.', [$major . '.' . $minor . '.' . $patch]),
937
-				'hint' => $l->t('To fix this issue update your libxml2 version and restart your web server.')
938
-			];
939
-		}
940
-
941
-		if (!self::isAnnotationsWorking()) {
942
-			$errors[] = [
943
-				'error' => $l->t('PHP is apparently set up to strip inline doc blocks. This will make several core apps inaccessible.'),
944
-				'hint' => $l->t('This is probably caused by a cache/accelerator such as Zend OPcache or eAccelerator.')
945
-			];
946
-		}
947
-
948
-		if (!\OC::$CLI && $webServerRestart) {
949
-			$errors[] = [
950
-				'error' => $l->t('PHP modules have been installed, but they are still listed as missing?'),
951
-				'hint' => $l->t('Please ask your server administrator to restart the web server.')
952
-			];
953
-		}
954
-
955
-		$errors = array_merge($errors, self::checkDatabaseVersion());
956
-
957
-		// Cache the result of this function
958
-		\OC::$server->getSession()->set('checkServer_succeeded', count($errors) == 0);
959
-
960
-		return $errors;
961
-	}
962
-
963
-	/**
964
-	 * Check the database version
965
-	 *
966
-	 * @return array errors array
967
-	 */
968
-	public static function checkDatabaseVersion() {
969
-		$l = \OC::$server->getL10N('lib');
970
-		$errors = [];
971
-		$dbType = \OC::$server->getSystemConfig()->getValue('dbtype', 'sqlite');
972
-		if ($dbType === 'pgsql') {
973
-			// check PostgreSQL version
974
-			try {
975
-				$result = \OC_DB::executeAudited('SHOW SERVER_VERSION');
976
-				$data = $result->fetchRow();
977
-				if (isset($data['server_version'])) {
978
-					$version = $data['server_version'];
979
-					if (version_compare($version, '9.0.0', '<')) {
980
-						$errors[] = [
981
-							'error' => $l->t('PostgreSQL >= 9 required'),
982
-							'hint' => $l->t('Please upgrade your database version')
983
-						];
984
-					}
985
-				}
986
-			} catch (\Doctrine\DBAL\DBALException $e) {
987
-				$logger = \OC::$server->getLogger();
988
-				$logger->warning('Error occurred while checking PostgreSQL version, assuming >= 9');
989
-				$logger->logException($e);
990
-			}
991
-		}
992
-		return $errors;
993
-	}
994
-
995
-	/**
996
-	 * Check for correct file permissions of data directory
997
-	 *
998
-	 * @param string $dataDirectory
999
-	 * @return array arrays with error messages and hints
1000
-	 */
1001
-	public static function checkDataDirectoryPermissions($dataDirectory) {
1002
-		if(\OC::$server->getConfig()->getSystemValue('check_data_directory_permissions', true) === false) {
1003
-			return  [];
1004
-		}
1005
-		$l = \OC::$server->getL10N('lib');
1006
-		$errors = [];
1007
-		$permissionsModHint = $l->t('Please change the permissions to 0770 so that the directory'
1008
-			. ' cannot be listed by other users.');
1009
-		$perms = substr(decoct(@fileperms($dataDirectory)), -3);
1010
-		if (substr($perms, -1) !== '0') {
1011
-			chmod($dataDirectory, 0770);
1012
-			clearstatcache();
1013
-			$perms = substr(decoct(@fileperms($dataDirectory)), -3);
1014
-			if ($perms[2] !== '0') {
1015
-				$errors[] = [
1016
-					'error' => $l->t('Your data directory is readable by other users'),
1017
-					'hint' => $permissionsModHint
1018
-				];
1019
-			}
1020
-		}
1021
-		return $errors;
1022
-	}
1023
-
1024
-	/**
1025
-	 * Check that the data directory exists and is valid by
1026
-	 * checking the existence of the ".ocdata" file.
1027
-	 *
1028
-	 * @param string $dataDirectory data directory path
1029
-	 * @return array errors found
1030
-	 */
1031
-	public static function checkDataDirectoryValidity($dataDirectory) {
1032
-		$l = \OC::$server->getL10N('lib');
1033
-		$errors = [];
1034
-		if ($dataDirectory[0] !== '/') {
1035
-			$errors[] = [
1036
-				'error' => $l->t('Your data directory must be an absolute path'),
1037
-				'hint' => $l->t('Check the value of "datadirectory" in your configuration')
1038
-			];
1039
-		}
1040
-		if (!file_exists($dataDirectory . '/.ocdata')) {
1041
-			$errors[] = [
1042
-				'error' => $l->t('Your data directory is invalid'),
1043
-				'hint' => $l->t('Ensure there is a file called ".ocdata"' .
1044
-					' in the root of the data directory.')
1045
-			];
1046
-		}
1047
-		return $errors;
1048
-	}
1049
-
1050
-	/**
1051
-	 * Check if the user is logged in, redirects to home if not. With
1052
-	 * redirect URL parameter to the request URI.
1053
-	 *
1054
-	 * @return void
1055
-	 */
1056
-	public static function checkLoggedIn() {
1057
-		// Check if we are a user
1058
-		if (!\OC::$server->getUserSession()->isLoggedIn()) {
1059
-			header('Location: ' . \OC::$server->getURLGenerator()->linkToRoute(
1060
-						'core.login.showLoginForm',
1061
-						[
1062
-							'redirect_url' => \OC::$server->getRequest()->getRequestUri(),
1063
-						]
1064
-					)
1065
-			);
1066
-			exit();
1067
-		}
1068
-		// Redirect to 2FA challenge selection if 2FA challenge was not solved yet
1069
-		if (\OC::$server->getTwoFactorAuthManager()->needsSecondFactor(\OC::$server->getUserSession()->getUser())) {
1070
-			header('Location: ' . \OC::$server->getURLGenerator()->linkToRoute('core.TwoFactorChallenge.selectChallenge'));
1071
-			exit();
1072
-		}
1073
-	}
1074
-
1075
-	/**
1076
-	 * Check if the user is a admin, redirects to home if not
1077
-	 *
1078
-	 * @return void
1079
-	 */
1080
-	public static function checkAdminUser() {
1081
-		OC_Util::checkLoggedIn();
1082
-		if (!OC_User::isAdminUser(OC_User::getUser())) {
1083
-			header('Location: ' . \OCP\Util::linkToAbsolute('', 'index.php'));
1084
-			exit();
1085
-		}
1086
-	}
1087
-
1088
-	/**
1089
-	 * Returns the URL of the default page
1090
-	 * based on the system configuration and
1091
-	 * the apps visible for the current user
1092
-	 *
1093
-	 * @return string URL
1094
-	 * @suppress PhanDeprecatedFunction
1095
-	 */
1096
-	public static function getDefaultPageUrl() {
1097
-		$urlGenerator = \OC::$server->getURLGenerator();
1098
-		// Deny the redirect if the URL contains a @
1099
-		// This prevents unvalidated redirects like ?redirect_url=:[email protected]
1100
-		if (isset($_REQUEST['redirect_url']) && strpos($_REQUEST['redirect_url'], '@') === false) {
1101
-			$location = $urlGenerator->getAbsoluteURL(urldecode($_REQUEST['redirect_url']));
1102
-		} else {
1103
-			$defaultPage = \OC::$server->getConfig()->getAppValue('core', 'defaultpage');
1104
-			if ($defaultPage) {
1105
-				$location = $urlGenerator->getAbsoluteURL($defaultPage);
1106
-			} else {
1107
-				$appId = 'files';
1108
-				$config = \OC::$server->getConfig();
1109
-				$defaultApps = explode(',', $config->getSystemValue('defaultapp', 'files'));
1110
-				// find the first app that is enabled for the current user
1111
-				foreach ($defaultApps as $defaultApp) {
1112
-					$defaultApp = OC_App::cleanAppId(strip_tags($defaultApp));
1113
-					if (static::getAppManager()->isEnabledForUser($defaultApp)) {
1114
-						$appId = $defaultApp;
1115
-						break;
1116
-					}
1117
-				}
1118
-
1119
-				if($config->getSystemValue('htaccess.IgnoreFrontController', false) === true || getenv('front_controller_active') === 'true') {
1120
-					$location = $urlGenerator->getAbsoluteURL('/apps/' . $appId . '/');
1121
-				} else {
1122
-					$location = $urlGenerator->getAbsoluteURL('/index.php/apps/' . $appId . '/');
1123
-				}
1124
-			}
1125
-		}
1126
-		return $location;
1127
-	}
1128
-
1129
-	/**
1130
-	 * Redirect to the user default page
1131
-	 *
1132
-	 * @return void
1133
-	 */
1134
-	public static function redirectToDefaultPage() {
1135
-		$location = self::getDefaultPageUrl();
1136
-		header('Location: ' . $location);
1137
-		exit();
1138
-	}
1139
-
1140
-	/**
1141
-	 * get an id unique for this instance
1142
-	 *
1143
-	 * @return string
1144
-	 */
1145
-	public static function getInstanceId() {
1146
-		$id = \OC::$server->getSystemConfig()->getValue('instanceid', null);
1147
-		if (is_null($id)) {
1148
-			// We need to guarantee at least one letter in instanceid so it can be used as the session_name
1149
-			$id = 'oc' . \OC::$server->getSecureRandom()->generate(10, \OCP\Security\ISecureRandom::CHAR_LOWER.\OCP\Security\ISecureRandom::CHAR_DIGITS);
1150
-			\OC::$server->getSystemConfig()->setValue('instanceid', $id);
1151
-		}
1152
-		return $id;
1153
-	}
1154
-
1155
-	/**
1156
-	 * Public function to sanitize HTML
1157
-	 *
1158
-	 * This function is used to sanitize HTML and should be applied on any
1159
-	 * string or array of strings before displaying it on a web page.
1160
-	 *
1161
-	 * @param string|array $value
1162
-	 * @return string|array an array of sanitized strings or a single sanitized string, depends on the input parameter.
1163
-	 */
1164
-	public static function sanitizeHTML($value) {
1165
-		if (is_array($value)) {
1166
-			$value = array_map(function ($value) {
1167
-				return self::sanitizeHTML($value);
1168
-			}, $value);
1169
-		} else {
1170
-			// Specify encoding for PHP<5.4
1171
-			$value = htmlspecialchars((string)$value, ENT_QUOTES, 'UTF-8');
1172
-		}
1173
-		return $value;
1174
-	}
1175
-
1176
-	/**
1177
-	 * Public function to encode url parameters
1178
-	 *
1179
-	 * This function is used to encode path to file before output.
1180
-	 * Encoding is done according to RFC 3986 with one exception:
1181
-	 * Character '/' is preserved as is.
1182
-	 *
1183
-	 * @param string $component part of URI to encode
1184
-	 * @return string
1185
-	 */
1186
-	public static function encodePath($component) {
1187
-		$encoded = rawurlencode($component);
1188
-		$encoded = str_replace('%2F', '/', $encoded);
1189
-		return $encoded;
1190
-	}
1191
-
1192
-
1193
-	public function createHtaccessTestFile(\OCP\IConfig $config) {
1194
-		// php dev server does not support htaccess
1195
-		if (php_sapi_name() === 'cli-server') {
1196
-			return false;
1197
-		}
1198
-
1199
-		// testdata
1200
-		$fileName = '/htaccesstest.txt';
1201
-		$testContent = 'This is used for testing whether htaccess is properly enabled to disallow access from the outside. This file can be safely removed.';
1202
-
1203
-		// creating a test file
1204
-		$testFile = $config->getSystemValue('datadirectory', OC::$SERVERROOT . '/data') . '/' . $fileName;
1205
-
1206
-		if (file_exists($testFile)) {// already running this test, possible recursive call
1207
-			return false;
1208
-		}
1209
-
1210
-		$fp = @fopen($testFile, 'w');
1211
-		if (!$fp) {
1212
-			throw new OC\HintException('Can\'t create test file to check for working .htaccess file.',
1213
-				'Make sure it is possible for the webserver to write to ' . $testFile);
1214
-		}
1215
-		fwrite($fp, $testContent);
1216
-		fclose($fp);
1217
-
1218
-		return $testContent;
1219
-	}
1220
-
1221
-	/**
1222
-	 * Check if the .htaccess file is working
1223
-	 * @param \OCP\IConfig $config
1224
-	 * @return bool
1225
-	 * @throws Exception
1226
-	 * @throws \OC\HintException If the test file can't get written.
1227
-	 */
1228
-	public function isHtaccessWorking(\OCP\IConfig $config) {
1229
-
1230
-		if (\OC::$CLI || !$config->getSystemValue('check_for_working_htaccess', true)) {
1231
-			return true;
1232
-		}
1233
-
1234
-		$testContent = $this->createHtaccessTestFile($config);
1235
-		if ($testContent === false) {
1236
-			return false;
1237
-		}
1238
-
1239
-		$fileName = '/htaccesstest.txt';
1240
-		$testFile = $config->getSystemValue('datadirectory', OC::$SERVERROOT . '/data') . '/' . $fileName;
1241
-
1242
-		// accessing the file via http
1243
-		$url = \OC::$server->getURLGenerator()->getAbsoluteURL(OC::$WEBROOT . '/data' . $fileName);
1244
-		try {
1245
-			$content = \OC::$server->getHTTPClientService()->newClient()->get($url)->getBody();
1246
-		} catch (\Exception $e) {
1247
-			$content = false;
1248
-		}
1249
-
1250
-		if (strpos($url, 'https:') === 0) {
1251
-			$url = 'http:' . substr($url, 6);
1252
-		} else {
1253
-			$url = 'https:' . substr($url, 5);
1254
-		}
1255
-
1256
-		try {
1257
-			$fallbackContent = \OC::$server->getHTTPClientService()->newClient()->get($url)->getBody();
1258
-		} catch (\Exception $e) {
1259
-			$fallbackContent = false;
1260
-		}
1261
-
1262
-		// cleanup
1263
-		@unlink($testFile);
1264
-
1265
-		/*
268
+            if ($mount->getOption('readonly', false)) {
269
+                return new \OC\Files\Storage\Wrapper\PermissionsMask([
270
+                    'storage' => $storage,
271
+                    'mask' => \OCP\Constants::PERMISSION_ALL & ~(
272
+                        \OCP\Constants::PERMISSION_UPDATE |
273
+                        \OCP\Constants::PERMISSION_CREATE |
274
+                        \OCP\Constants::PERMISSION_DELETE
275
+                    ),
276
+                ]);
277
+            }
278
+            return $storage;
279
+        });
280
+
281
+        OC_Hook::emit('OC_Filesystem', 'preSetup', ['user' => $user]);
282
+
283
+        \OC\Files\Filesystem::logWarningWhenAddingStorageWrapper($prevLogging);
284
+
285
+        //check if we are using an object storage
286
+        $objectStore = \OC::$server->getSystemConfig()->getValue('objectstore', null);
287
+        $objectStoreMultibucket = \OC::$server->getSystemConfig()->getValue('objectstore_multibucket', null);
288
+
289
+        // use the same order as in ObjectHomeMountProvider
290
+        if (isset($objectStoreMultibucket)) {
291
+            self::initObjectStoreMultibucketRootFS($objectStoreMultibucket);
292
+        } elseif (isset($objectStore)) {
293
+            self::initObjectStoreRootFS($objectStore);
294
+        } else {
295
+            self::initLocalStorageRootFS();
296
+        }
297
+
298
+        if ($user != '' && !\OC::$server->getUserManager()->userExists($user)) {
299
+            \OC::$server->getEventLogger()->end('setup_fs');
300
+            return false;
301
+        }
302
+
303
+        //if we aren't logged in, there is no use to set up the filesystem
304
+        if ($user != "") {
305
+
306
+            $userDir = '/' . $user . '/files';
307
+
308
+            //jail the user into his "home" directory
309
+            \OC\Files\Filesystem::init($user, $userDir);
310
+
311
+            OC_Hook::emit('OC_Filesystem', 'setup', ['user' => $user, 'user_dir' => $userDir]);
312
+        }
313
+        \OC::$server->getEventLogger()->end('setup_fs');
314
+        return true;
315
+    }
316
+
317
+    /**
318
+     * check if a password is required for each public link
319
+     *
320
+     * @return boolean
321
+     * @suppress PhanDeprecatedFunction
322
+     */
323
+    public static function isPublicLinkPasswordRequired() {
324
+        $enforcePassword = \OC::$server->getConfig()->getAppValue('core', 'shareapi_enforce_links_password', 'no');
325
+        return $enforcePassword === 'yes';
326
+    }
327
+
328
+    /**
329
+     * check if sharing is disabled for the current user
330
+     * @param IConfig $config
331
+     * @param IGroupManager $groupManager
332
+     * @param IUser|null $user
333
+     * @return bool
334
+     */
335
+    public static function isSharingDisabledForUser(IConfig $config, IGroupManager $groupManager, $user) {
336
+        if ($config->getAppValue('core', 'shareapi_exclude_groups', 'no') === 'yes') {
337
+            $groupsList = $config->getAppValue('core', 'shareapi_exclude_groups_list', '');
338
+            $excludedGroups = json_decode($groupsList);
339
+            if (is_null($excludedGroups)) {
340
+                $excludedGroups = explode(',', $groupsList);
341
+                $newValue = json_encode($excludedGroups);
342
+                $config->setAppValue('core', 'shareapi_exclude_groups_list', $newValue);
343
+            }
344
+            $usersGroups = $groupManager->getUserGroupIds($user);
345
+            if (!empty($usersGroups)) {
346
+                $remainingGroups = array_diff($usersGroups, $excludedGroups);
347
+                // if the user is only in groups which are disabled for sharing then
348
+                // sharing is also disabled for the user
349
+                if (empty($remainingGroups)) {
350
+                    return true;
351
+                }
352
+            }
353
+        }
354
+        return false;
355
+    }
356
+
357
+    /**
358
+     * check if share API enforces a default expire date
359
+     *
360
+     * @return boolean
361
+     * @suppress PhanDeprecatedFunction
362
+     */
363
+    public static function isDefaultExpireDateEnforced() {
364
+        $isDefaultExpireDateEnabled = \OC::$server->getConfig()->getAppValue('core', 'shareapi_default_expire_date', 'no');
365
+        $enforceDefaultExpireDate = false;
366
+        if ($isDefaultExpireDateEnabled === 'yes') {
367
+            $value = \OC::$server->getConfig()->getAppValue('core', 'shareapi_enforce_expire_date', 'no');
368
+            $enforceDefaultExpireDate = $value === 'yes';
369
+        }
370
+
371
+        return $enforceDefaultExpireDate;
372
+    }
373
+
374
+    /**
375
+     * Get the quota of a user
376
+     *
377
+     * @param IUser|null $user
378
+     * @return float Quota bytes
379
+     */
380
+    public static function getUserQuota(?IUser $user) {
381
+        if (is_null($user)) {
382
+            return \OCP\Files\FileInfo::SPACE_UNLIMITED;
383
+        }
384
+        $userQuota = $user->getQuota();
385
+        if($userQuota === 'none') {
386
+            return \OCP\Files\FileInfo::SPACE_UNLIMITED;
387
+        }
388
+        return OC_Helper::computerFileSize($userQuota);
389
+    }
390
+
391
+    /**
392
+     * copies the skeleton to the users /files
393
+     *
394
+     * @param string $userId
395
+     * @param \OCP\Files\Folder $userDirectory
396
+     * @throws \OCP\Files\NotFoundException
397
+     * @throws \OCP\Files\NotPermittedException
398
+     * @suppress PhanDeprecatedFunction
399
+     */
400
+    public static function copySkeleton($userId, \OCP\Files\Folder $userDirectory) {
401
+
402
+        $plainSkeletonDirectory = \OC::$server->getConfig()->getSystemValue('skeletondirectory', \OC::$SERVERROOT . '/core/skeleton');
403
+        $userLang = \OC::$server->getL10NFactory()->findLanguage();
404
+        $skeletonDirectory = str_replace('{lang}', $userLang, $plainSkeletonDirectory);
405
+
406
+        if (!file_exists($skeletonDirectory)) {
407
+            $dialectStart = strpos($userLang, '_');
408
+            if ($dialectStart !== false) {
409
+                $skeletonDirectory = str_replace('{lang}', substr($userLang, 0, $dialectStart), $plainSkeletonDirectory);
410
+            }
411
+            if ($dialectStart === false || !file_exists($skeletonDirectory)) {
412
+                $skeletonDirectory = str_replace('{lang}', 'default', $plainSkeletonDirectory);
413
+            }
414
+            if (!file_exists($skeletonDirectory)) {
415
+                $skeletonDirectory = '';
416
+            }
417
+        }
418
+
419
+        $instanceId = \OC::$server->getConfig()->getSystemValue('instanceid', '');
420
+
421
+        if ($instanceId === null) {
422
+            throw new \RuntimeException('no instance id!');
423
+        }
424
+        $appdata = 'appdata_' . $instanceId;
425
+        if ($userId === $appdata) {
426
+            throw new \RuntimeException('username is reserved name: ' . $appdata);
427
+        }
428
+
429
+        if (!empty($skeletonDirectory)) {
430
+            \OCP\Util::writeLog(
431
+                'files_skeleton',
432
+                'copying skeleton for '.$userId.' from '.$skeletonDirectory.' to '.$userDirectory->getFullPath('/'),
433
+                ILogger::DEBUG
434
+            );
435
+            self::copyr($skeletonDirectory, $userDirectory);
436
+            // update the file cache
437
+            $userDirectory->getStorage()->getScanner()->scan('', \OC\Files\Cache\Scanner::SCAN_RECURSIVE);
438
+        }
439
+    }
440
+
441
+    /**
442
+     * copies a directory recursively by using streams
443
+     *
444
+     * @param string $source
445
+     * @param \OCP\Files\Folder $target
446
+     * @return void
447
+     */
448
+    public static function copyr($source, \OCP\Files\Folder $target) {
449
+        $logger = \OC::$server->getLogger();
450
+
451
+        // Verify if folder exists
452
+        $dir = opendir($source);
453
+        if($dir === false) {
454
+            $logger->error(sprintf('Could not opendir "%s"', $source), ['app' => 'core']);
455
+            return;
456
+        }
457
+
458
+        // Copy the files
459
+        while (false !== ($file = readdir($dir))) {
460
+            if (!\OC\Files\Filesystem::isIgnoredDir($file)) {
461
+                if (is_dir($source . '/' . $file)) {
462
+                    $child = $target->newFolder($file);
463
+                    self::copyr($source . '/' . $file, $child);
464
+                } else {
465
+                    $child = $target->newFile($file);
466
+                    $sourceStream = fopen($source . '/' . $file, 'r');
467
+                    if($sourceStream === false) {
468
+                        $logger->error(sprintf('Could not fopen "%s"', $source . '/' . $file), ['app' => 'core']);
469
+                        closedir($dir);
470
+                        return;
471
+                    }
472
+                    stream_copy_to_stream($sourceStream, $child->fopen('w'));
473
+                }
474
+            }
475
+        }
476
+        closedir($dir);
477
+    }
478
+
479
+    /**
480
+     * @return void
481
+     * @suppress PhanUndeclaredMethod
482
+     */
483
+    public static function tearDownFS() {
484
+        \OC\Files\Filesystem::tearDown();
485
+        \OC::$server->getRootFolder()->clearCache();
486
+        self::$fsSetup = false;
487
+        self::$rootMounted = false;
488
+    }
489
+
490
+    /**
491
+     * get the current installed version of ownCloud
492
+     *
493
+     * @return array
494
+     */
495
+    public static function getVersion() {
496
+        OC_Util::loadVersion();
497
+        return self::$versionCache['OC_Version'];
498
+    }
499
+
500
+    /**
501
+     * get the current installed version string of ownCloud
502
+     *
503
+     * @return string
504
+     */
505
+    public static function getVersionString() {
506
+        OC_Util::loadVersion();
507
+        return self::$versionCache['OC_VersionString'];
508
+    }
509
+
510
+    /**
511
+     * @deprecated the value is of no use anymore
512
+     * @return string
513
+     */
514
+    public static function getEditionString() {
515
+        return '';
516
+    }
517
+
518
+    /**
519
+     * @description get the update channel of the current installed of ownCloud.
520
+     * @return string
521
+     */
522
+    public static function getChannel() {
523
+        OC_Util::loadVersion();
524
+        return \OC::$server->getConfig()->getSystemValue('updater.release.channel', self::$versionCache['OC_Channel']);
525
+    }
526
+
527
+    /**
528
+     * @description get the build number of the current installed of ownCloud.
529
+     * @return string
530
+     */
531
+    public static function getBuild() {
532
+        OC_Util::loadVersion();
533
+        return self::$versionCache['OC_Build'];
534
+    }
535
+
536
+    /**
537
+     * @description load the version.php into the session as cache
538
+     * @suppress PhanUndeclaredVariable
539
+     */
540
+    private static function loadVersion() {
541
+        if (self::$versionCache !== null) {
542
+            return;
543
+        }
544
+
545
+        $timestamp = filemtime(OC::$SERVERROOT . '/version.php');
546
+        require OC::$SERVERROOT . '/version.php';
547
+        /** @var $timestamp int */
548
+        self::$versionCache['OC_Version_Timestamp'] = $timestamp;
549
+        /** @var $OC_Version string */
550
+        self::$versionCache['OC_Version'] = $OC_Version;
551
+        /** @var $OC_VersionString string */
552
+        self::$versionCache['OC_VersionString'] = $OC_VersionString;
553
+        /** @var $OC_Build string */
554
+        self::$versionCache['OC_Build'] = $OC_Build;
555
+
556
+        /** @var $OC_Channel string */
557
+        self::$versionCache['OC_Channel'] = $OC_Channel;
558
+    }
559
+
560
+    /**
561
+     * generates a path for JS/CSS files. If no application is provided it will create the path for core.
562
+     *
563
+     * @param string $application application to get the files from
564
+     * @param string $directory directory within this application (css, js, vendor, etc)
565
+     * @param string $file the file inside of the above folder
566
+     * @return string the path
567
+     */
568
+    private static function generatePath($application, $directory, $file) {
569
+        if (is_null($file)) {
570
+            $file = $application;
571
+            $application = "";
572
+        }
573
+        if (!empty($application)) {
574
+            return "$application/$directory/$file";
575
+        } else {
576
+            return "$directory/$file";
577
+        }
578
+    }
579
+
580
+    /**
581
+     * add a javascript file
582
+     *
583
+     * @param string $application application id
584
+     * @param string|null $file filename
585
+     * @param bool $prepend prepend the Script to the beginning of the list
586
+     * @return void
587
+     */
588
+    public static function addScript($application, $file = null, $prepend = false) {
589
+        $path = OC_Util::generatePath($application, 'js', $file);
590
+
591
+        // core js files need separate handling
592
+        if ($application !== 'core' && $file !== null) {
593
+            self::addTranslations($application);
594
+        }
595
+        self::addExternalResource($application, $prepend, $path, "script");
596
+    }
597
+
598
+    /**
599
+     * add a javascript file from the vendor sub folder
600
+     *
601
+     * @param string $application application id
602
+     * @param string|null $file filename
603
+     * @param bool $prepend prepend the Script to the beginning of the list
604
+     * @return void
605
+     */
606
+    public static function addVendorScript($application, $file = null, $prepend = false) {
607
+        $path = OC_Util::generatePath($application, 'vendor', $file);
608
+        self::addExternalResource($application, $prepend, $path, "script");
609
+    }
610
+
611
+    /**
612
+     * add a translation JS file
613
+     *
614
+     * @param string $application application id
615
+     * @param string|null $languageCode language code, defaults to the current language
616
+     * @param bool|null $prepend prepend the Script to the beginning of the list
617
+     */
618
+    public static function addTranslations($application, $languageCode = null, $prepend = false) {
619
+        if (is_null($languageCode)) {
620
+            $languageCode = \OC::$server->getL10NFactory()->findLanguage($application);
621
+        }
622
+        if (!empty($application)) {
623
+            $path = "$application/l10n/$languageCode";
624
+        } else {
625
+            $path = "l10n/$languageCode";
626
+        }
627
+        self::addExternalResource($application, $prepend, $path, "script");
628
+    }
629
+
630
+    /**
631
+     * add a css file
632
+     *
633
+     * @param string $application application id
634
+     * @param string|null $file filename
635
+     * @param bool $prepend prepend the Style to the beginning of the list
636
+     * @return void
637
+     */
638
+    public static function addStyle($application, $file = null, $prepend = false) {
639
+        $path = OC_Util::generatePath($application, 'css', $file);
640
+        self::addExternalResource($application, $prepend, $path, "style");
641
+    }
642
+
643
+    /**
644
+     * add a css file from the vendor sub folder
645
+     *
646
+     * @param string $application application id
647
+     * @param string|null $file filename
648
+     * @param bool $prepend prepend the Style to the beginning of the list
649
+     * @return void
650
+     */
651
+    public static function addVendorStyle($application, $file = null, $prepend = false) {
652
+        $path = OC_Util::generatePath($application, 'vendor', $file);
653
+        self::addExternalResource($application, $prepend, $path, "style");
654
+    }
655
+
656
+    /**
657
+     * add an external resource css/js file
658
+     *
659
+     * @param string $application application id
660
+     * @param bool $prepend prepend the file to the beginning of the list
661
+     * @param string $path
662
+     * @param string $type (script or style)
663
+     * @return void
664
+     */
665
+    private static function addExternalResource($application, $prepend, $path, $type = "script") {
666
+
667
+        if ($type === "style") {
668
+            if (!in_array($path, self::$styles)) {
669
+                if ($prepend === true) {
670
+                    array_unshift(self::$styles, $path);
671
+                } else {
672
+                    self::$styles[] = $path;
673
+                }
674
+            }
675
+        } elseif ($type === "script") {
676
+            if (!in_array($path, self::$scripts)) {
677
+                if ($prepend === true) {
678
+                    array_unshift(self::$scripts, $path);
679
+                } else {
680
+                    self::$scripts [] = $path;
681
+                }
682
+            }
683
+        }
684
+    }
685
+
686
+    /**
687
+     * Add a custom element to the header
688
+     * If $text is null then the element will be written as empty element.
689
+     * So use "" to get a closing tag.
690
+     * @param string $tag tag name of the element
691
+     * @param array $attributes array of attributes for the element
692
+     * @param string $text the text content for the element
693
+     * @param bool $prepend prepend the header to the beginning of the list
694
+     */
695
+    public static function addHeader($tag, $attributes, $text = null, $prepend = false) {
696
+        $header = [
697
+            'tag' => $tag,
698
+            'attributes' => $attributes,
699
+            'text' => $text
700
+        ];
701
+        if ($prepend === true) {
702
+            array_unshift(self::$headers, $header);
703
+
704
+        } else {
705
+            self::$headers[] = $header;
706
+        }
707
+    }
708
+
709
+    /**
710
+     * check if the current server configuration is suitable for ownCloud
711
+     *
712
+     * @param \OC\SystemConfig $config
713
+     * @return array arrays with error messages and hints
714
+     */
715
+    public static function checkServer(\OC\SystemConfig $config) {
716
+        $l = \OC::$server->getL10N('lib');
717
+        $errors = [];
718
+        $CONFIG_DATADIRECTORY = $config->getValue('datadirectory', OC::$SERVERROOT . '/data');
719
+
720
+        if (!self::needUpgrade($config) && $config->getValue('installed', false)) {
721
+            // this check needs to be done every time
722
+            $errors = self::checkDataDirectoryValidity($CONFIG_DATADIRECTORY);
723
+        }
724
+
725
+        // Assume that if checkServer() succeeded before in this session, then all is fine.
726
+        if (\OC::$server->getSession()->exists('checkServer_succeeded') && \OC::$server->getSession()->get('checkServer_succeeded')) {
727
+            return $errors;
728
+        }
729
+
730
+        $webServerRestart = false;
731
+        $setup = new \OC\Setup(
732
+            $config,
733
+            \OC::$server->getIniWrapper(),
734
+            \OC::$server->getL10N('lib'),
735
+            \OC::$server->query(\OCP\Defaults::class),
736
+            \OC::$server->getLogger(),
737
+            \OC::$server->getSecureRandom(),
738
+            \OC::$server->query(\OC\Installer::class)
739
+        );
740
+
741
+        $urlGenerator = \OC::$server->getURLGenerator();
742
+
743
+        $availableDatabases = $setup->getSupportedDatabases();
744
+        if (empty($availableDatabases)) {
745
+            $errors[] = [
746
+                'error' => $l->t('No database drivers (sqlite, mysql, or postgresql) installed.'),
747
+                'hint' => '' //TODO: sane hint
748
+            ];
749
+            $webServerRestart = true;
750
+        }
751
+
752
+        // Check if config folder is writable.
753
+        if(!OC_Helper::isReadOnlyConfigEnabled()) {
754
+            if (!is_writable(OC::$configDir) or !is_readable(OC::$configDir)) {
755
+                $errors[] = [
756
+                    'error' => $l->t('Cannot write into "config" directory'),
757
+                    'hint' => $l->t('This can usually be fixed by giving the webserver write access to the config directory. See %s',
758
+                        [ $urlGenerator->linkToDocs('admin-dir_permissions') ]) . '. '
759
+                        . $l->t('Or, if you prefer to keep config.php file read only, set the option "config_is_read_only" to true in it. See %s',
760
+                        [ $urlGenerator->linkToDocs('admin-config') ])
761
+                ];
762
+            }
763
+        }
764
+
765
+        // Check if there is a writable install folder.
766
+        if ($config->getValue('appstoreenabled', true)) {
767
+            if (OC_App::getInstallPath() === null
768
+                || !is_writable(OC_App::getInstallPath())
769
+                || !is_readable(OC_App::getInstallPath())
770
+            ) {
771
+                $errors[] = [
772
+                    'error' => $l->t('Cannot write into "apps" directory'),
773
+                    'hint' => $l->t('This can usually be fixed by giving the webserver write access to the apps directory'
774
+                        . ' or disabling the appstore in the config file.')
775
+                ];
776
+            }
777
+        }
778
+        // Create root dir.
779
+        if ($config->getValue('installed', false)) {
780
+            if (!is_dir($CONFIG_DATADIRECTORY)) {
781
+                $success = @mkdir($CONFIG_DATADIRECTORY);
782
+                if ($success) {
783
+                    $errors = array_merge($errors, self::checkDataDirectoryPermissions($CONFIG_DATADIRECTORY));
784
+                } else {
785
+                    $errors[] = [
786
+                        'error' => $l->t('Cannot create "data" directory'),
787
+                        'hint' => $l->t('This can usually be fixed by giving the webserver write access to the root directory. See %s',
788
+                            [$urlGenerator->linkToDocs('admin-dir_permissions')])
789
+                    ];
790
+                }
791
+            } else if (!is_writable($CONFIG_DATADIRECTORY) or !is_readable($CONFIG_DATADIRECTORY)) {
792
+                // is_writable doesn't work for NFS mounts, so try to write a file and check if it exists.
793
+                $testFile = sprintf('%s/%s.tmp', $CONFIG_DATADIRECTORY, uniqid('data_dir_writability_test_'));
794
+                $handle = fopen($testFile, 'w');
795
+                if (!$handle || fwrite($handle, 'Test write operation') === false) {
796
+                    $permissionsHint = $l->t('Permissions can usually be fixed by giving the webserver write access to the root directory. See %s.',
797
+                        [$urlGenerator->linkToDocs('admin-dir_permissions')]);
798
+                    $errors[] = [
799
+                        'error' => 'Your data directory is not writable',
800
+                        'hint' => $permissionsHint
801
+                    ];
802
+                } else {
803
+                    fclose($handle);
804
+                    unlink($testFile);
805
+                }
806
+            } else {
807
+                $errors = array_merge($errors, self::checkDataDirectoryPermissions($CONFIG_DATADIRECTORY));
808
+            }
809
+        }
810
+
811
+        if (!OC_Util::isSetLocaleWorking()) {
812
+            $errors[] = [
813
+                'error' => $l->t('Setting locale to %s failed',
814
+                    ['en_US.UTF-8/fr_FR.UTF-8/es_ES.UTF-8/de_DE.UTF-8/ru_RU.UTF-8/'
815
+                        . 'pt_BR.UTF-8/it_IT.UTF-8/ja_JP.UTF-8/zh_CN.UTF-8']),
816
+                'hint' => $l->t('Please install one of these locales on your system and restart your webserver.')
817
+            ];
818
+        }
819
+
820
+        // Contains the dependencies that should be checked against
821
+        // classes = class_exists
822
+        // functions = function_exists
823
+        // defined = defined
824
+        // ini = ini_get
825
+        // If the dependency is not found the missing module name is shown to the EndUser
826
+        // When adding new checks always verify that they pass on Travis as well
827
+        // for ini settings, see https://github.com/owncloud/administration/blob/master/travis-ci/custom.ini
828
+        $dependencies = [
829
+            'classes' => [
830
+                'ZipArchive' => 'zip',
831
+                'DOMDocument' => 'dom',
832
+                'XMLWriter' => 'XMLWriter',
833
+                'XMLReader' => 'XMLReader',
834
+            ],
835
+            'functions' => [
836
+                'xml_parser_create' => 'libxml',
837
+                'mb_strcut' => 'mbstring',
838
+                'ctype_digit' => 'ctype',
839
+                'json_encode' => 'JSON',
840
+                'gd_info' => 'GD',
841
+                'gzencode' => 'zlib',
842
+                'iconv' => 'iconv',
843
+                'simplexml_load_string' => 'SimpleXML',
844
+                'hash' => 'HASH Message Digest Framework',
845
+                'curl_init' => 'cURL',
846
+                'openssl_verify' => 'OpenSSL',
847
+            ],
848
+            'defined' => [
849
+                'PDO::ATTR_DRIVER_NAME' => 'PDO'
850
+            ],
851
+            'ini' => [
852
+                'default_charset' => 'UTF-8',
853
+            ],
854
+        ];
855
+        $missingDependencies = [];
856
+        $invalidIniSettings = [];
857
+        $moduleHint = $l->t('Please ask your server administrator to install the module.');
858
+
859
+        $iniWrapper = \OC::$server->getIniWrapper();
860
+        foreach ($dependencies['classes'] as $class => $module) {
861
+            if (!class_exists($class)) {
862
+                $missingDependencies[] = $module;
863
+            }
864
+        }
865
+        foreach ($dependencies['functions'] as $function => $module) {
866
+            if (!function_exists($function)) {
867
+                $missingDependencies[] = $module;
868
+            }
869
+        }
870
+        foreach ($dependencies['defined'] as $defined => $module) {
871
+            if (!defined($defined)) {
872
+                $missingDependencies[] = $module;
873
+            }
874
+        }
875
+        foreach ($dependencies['ini'] as $setting => $expected) {
876
+            if (is_bool($expected)) {
877
+                if ($iniWrapper->getBool($setting) !== $expected) {
878
+                    $invalidIniSettings[] = [$setting, $expected];
879
+                }
880
+            }
881
+            if (is_int($expected)) {
882
+                if ($iniWrapper->getNumeric($setting) !== $expected) {
883
+                    $invalidIniSettings[] = [$setting, $expected];
884
+                }
885
+            }
886
+            if (is_string($expected)) {
887
+                if (strtolower($iniWrapper->getString($setting)) !== strtolower($expected)) {
888
+                    $invalidIniSettings[] = [$setting, $expected];
889
+                }
890
+            }
891
+        }
892
+
893
+        foreach($missingDependencies as $missingDependency) {
894
+            $errors[] = [
895
+                'error' => $l->t('PHP module %s not installed.', [$missingDependency]),
896
+                'hint' => $moduleHint
897
+            ];
898
+            $webServerRestart = true;
899
+        }
900
+        foreach($invalidIniSettings as $setting) {
901
+            if(is_bool($setting[1])) {
902
+                $setting[1] = $setting[1] ? 'on' : 'off';
903
+            }
904
+            $errors[] = [
905
+                'error' => $l->t('PHP setting "%s" is not set to "%s".', [$setting[0], var_export($setting[1], true)]),
906
+                'hint' =>  $l->t('Adjusting this setting in php.ini will make Nextcloud run again')
907
+            ];
908
+            $webServerRestart = true;
909
+        }
910
+
911
+        /**
912
+         * The mbstring.func_overload check can only be performed if the mbstring
913
+         * module is installed as it will return null if the checking setting is
914
+         * not available and thus a check on the boolean value fails.
915
+         *
916
+         * TODO: Should probably be implemented in the above generic dependency
917
+         *       check somehow in the long-term.
918
+         */
919
+        if($iniWrapper->getBool('mbstring.func_overload') !== null &&
920
+            $iniWrapper->getBool('mbstring.func_overload') === true) {
921
+            $errors[] = [
922
+                'error' => $l->t('mbstring.func_overload is set to "%s" instead of the expected value "0"', [$iniWrapper->getString('mbstring.func_overload')]),
923
+                'hint' => $l->t('To fix this issue set <code>mbstring.func_overload</code> to <code>0</code> in your php.ini')
924
+            ];
925
+        }
926
+
927
+        if(function_exists('xml_parser_create') &&
928
+            LIBXML_LOADED_VERSION < 20700) {
929
+            $version = LIBXML_LOADED_VERSION;
930
+            $major = floor($version/10000);
931
+            $version -= ($major * 10000);
932
+            $minor = floor($version/100);
933
+            $version -= ($minor * 100);
934
+            $patch = $version;
935
+            $errors[] = [
936
+                'error' => $l->t('libxml2 2.7.0 is at least required. Currently %s is installed.', [$major . '.' . $minor . '.' . $patch]),
937
+                'hint' => $l->t('To fix this issue update your libxml2 version and restart your web server.')
938
+            ];
939
+        }
940
+
941
+        if (!self::isAnnotationsWorking()) {
942
+            $errors[] = [
943
+                'error' => $l->t('PHP is apparently set up to strip inline doc blocks. This will make several core apps inaccessible.'),
944
+                'hint' => $l->t('This is probably caused by a cache/accelerator such as Zend OPcache or eAccelerator.')
945
+            ];
946
+        }
947
+
948
+        if (!\OC::$CLI && $webServerRestart) {
949
+            $errors[] = [
950
+                'error' => $l->t('PHP modules have been installed, but they are still listed as missing?'),
951
+                'hint' => $l->t('Please ask your server administrator to restart the web server.')
952
+            ];
953
+        }
954
+
955
+        $errors = array_merge($errors, self::checkDatabaseVersion());
956
+
957
+        // Cache the result of this function
958
+        \OC::$server->getSession()->set('checkServer_succeeded', count($errors) == 0);
959
+
960
+        return $errors;
961
+    }
962
+
963
+    /**
964
+     * Check the database version
965
+     *
966
+     * @return array errors array
967
+     */
968
+    public static function checkDatabaseVersion() {
969
+        $l = \OC::$server->getL10N('lib');
970
+        $errors = [];
971
+        $dbType = \OC::$server->getSystemConfig()->getValue('dbtype', 'sqlite');
972
+        if ($dbType === 'pgsql') {
973
+            // check PostgreSQL version
974
+            try {
975
+                $result = \OC_DB::executeAudited('SHOW SERVER_VERSION');
976
+                $data = $result->fetchRow();
977
+                if (isset($data['server_version'])) {
978
+                    $version = $data['server_version'];
979
+                    if (version_compare($version, '9.0.0', '<')) {
980
+                        $errors[] = [
981
+                            'error' => $l->t('PostgreSQL >= 9 required'),
982
+                            'hint' => $l->t('Please upgrade your database version')
983
+                        ];
984
+                    }
985
+                }
986
+            } catch (\Doctrine\DBAL\DBALException $e) {
987
+                $logger = \OC::$server->getLogger();
988
+                $logger->warning('Error occurred while checking PostgreSQL version, assuming >= 9');
989
+                $logger->logException($e);
990
+            }
991
+        }
992
+        return $errors;
993
+    }
994
+
995
+    /**
996
+     * Check for correct file permissions of data directory
997
+     *
998
+     * @param string $dataDirectory
999
+     * @return array arrays with error messages and hints
1000
+     */
1001
+    public static function checkDataDirectoryPermissions($dataDirectory) {
1002
+        if(\OC::$server->getConfig()->getSystemValue('check_data_directory_permissions', true) === false) {
1003
+            return  [];
1004
+        }
1005
+        $l = \OC::$server->getL10N('lib');
1006
+        $errors = [];
1007
+        $permissionsModHint = $l->t('Please change the permissions to 0770 so that the directory'
1008
+            . ' cannot be listed by other users.');
1009
+        $perms = substr(decoct(@fileperms($dataDirectory)), -3);
1010
+        if (substr($perms, -1) !== '0') {
1011
+            chmod($dataDirectory, 0770);
1012
+            clearstatcache();
1013
+            $perms = substr(decoct(@fileperms($dataDirectory)), -3);
1014
+            if ($perms[2] !== '0') {
1015
+                $errors[] = [
1016
+                    'error' => $l->t('Your data directory is readable by other users'),
1017
+                    'hint' => $permissionsModHint
1018
+                ];
1019
+            }
1020
+        }
1021
+        return $errors;
1022
+    }
1023
+
1024
+    /**
1025
+     * Check that the data directory exists and is valid by
1026
+     * checking the existence of the ".ocdata" file.
1027
+     *
1028
+     * @param string $dataDirectory data directory path
1029
+     * @return array errors found
1030
+     */
1031
+    public static function checkDataDirectoryValidity($dataDirectory) {
1032
+        $l = \OC::$server->getL10N('lib');
1033
+        $errors = [];
1034
+        if ($dataDirectory[0] !== '/') {
1035
+            $errors[] = [
1036
+                'error' => $l->t('Your data directory must be an absolute path'),
1037
+                'hint' => $l->t('Check the value of "datadirectory" in your configuration')
1038
+            ];
1039
+        }
1040
+        if (!file_exists($dataDirectory . '/.ocdata')) {
1041
+            $errors[] = [
1042
+                'error' => $l->t('Your data directory is invalid'),
1043
+                'hint' => $l->t('Ensure there is a file called ".ocdata"' .
1044
+                    ' in the root of the data directory.')
1045
+            ];
1046
+        }
1047
+        return $errors;
1048
+    }
1049
+
1050
+    /**
1051
+     * Check if the user is logged in, redirects to home if not. With
1052
+     * redirect URL parameter to the request URI.
1053
+     *
1054
+     * @return void
1055
+     */
1056
+    public static function checkLoggedIn() {
1057
+        // Check if we are a user
1058
+        if (!\OC::$server->getUserSession()->isLoggedIn()) {
1059
+            header('Location: ' . \OC::$server->getURLGenerator()->linkToRoute(
1060
+                        'core.login.showLoginForm',
1061
+                        [
1062
+                            'redirect_url' => \OC::$server->getRequest()->getRequestUri(),
1063
+                        ]
1064
+                    )
1065
+            );
1066
+            exit();
1067
+        }
1068
+        // Redirect to 2FA challenge selection if 2FA challenge was not solved yet
1069
+        if (\OC::$server->getTwoFactorAuthManager()->needsSecondFactor(\OC::$server->getUserSession()->getUser())) {
1070
+            header('Location: ' . \OC::$server->getURLGenerator()->linkToRoute('core.TwoFactorChallenge.selectChallenge'));
1071
+            exit();
1072
+        }
1073
+    }
1074
+
1075
+    /**
1076
+     * Check if the user is a admin, redirects to home if not
1077
+     *
1078
+     * @return void
1079
+     */
1080
+    public static function checkAdminUser() {
1081
+        OC_Util::checkLoggedIn();
1082
+        if (!OC_User::isAdminUser(OC_User::getUser())) {
1083
+            header('Location: ' . \OCP\Util::linkToAbsolute('', 'index.php'));
1084
+            exit();
1085
+        }
1086
+    }
1087
+
1088
+    /**
1089
+     * Returns the URL of the default page
1090
+     * based on the system configuration and
1091
+     * the apps visible for the current user
1092
+     *
1093
+     * @return string URL
1094
+     * @suppress PhanDeprecatedFunction
1095
+     */
1096
+    public static function getDefaultPageUrl() {
1097
+        $urlGenerator = \OC::$server->getURLGenerator();
1098
+        // Deny the redirect if the URL contains a @
1099
+        // This prevents unvalidated redirects like ?redirect_url=:[email protected]
1100
+        if (isset($_REQUEST['redirect_url']) && strpos($_REQUEST['redirect_url'], '@') === false) {
1101
+            $location = $urlGenerator->getAbsoluteURL(urldecode($_REQUEST['redirect_url']));
1102
+        } else {
1103
+            $defaultPage = \OC::$server->getConfig()->getAppValue('core', 'defaultpage');
1104
+            if ($defaultPage) {
1105
+                $location = $urlGenerator->getAbsoluteURL($defaultPage);
1106
+            } else {
1107
+                $appId = 'files';
1108
+                $config = \OC::$server->getConfig();
1109
+                $defaultApps = explode(',', $config->getSystemValue('defaultapp', 'files'));
1110
+                // find the first app that is enabled for the current user
1111
+                foreach ($defaultApps as $defaultApp) {
1112
+                    $defaultApp = OC_App::cleanAppId(strip_tags($defaultApp));
1113
+                    if (static::getAppManager()->isEnabledForUser($defaultApp)) {
1114
+                        $appId = $defaultApp;
1115
+                        break;
1116
+                    }
1117
+                }
1118
+
1119
+                if($config->getSystemValue('htaccess.IgnoreFrontController', false) === true || getenv('front_controller_active') === 'true') {
1120
+                    $location = $urlGenerator->getAbsoluteURL('/apps/' . $appId . '/');
1121
+                } else {
1122
+                    $location = $urlGenerator->getAbsoluteURL('/index.php/apps/' . $appId . '/');
1123
+                }
1124
+            }
1125
+        }
1126
+        return $location;
1127
+    }
1128
+
1129
+    /**
1130
+     * Redirect to the user default page
1131
+     *
1132
+     * @return void
1133
+     */
1134
+    public static function redirectToDefaultPage() {
1135
+        $location = self::getDefaultPageUrl();
1136
+        header('Location: ' . $location);
1137
+        exit();
1138
+    }
1139
+
1140
+    /**
1141
+     * get an id unique for this instance
1142
+     *
1143
+     * @return string
1144
+     */
1145
+    public static function getInstanceId() {
1146
+        $id = \OC::$server->getSystemConfig()->getValue('instanceid', null);
1147
+        if (is_null($id)) {
1148
+            // We need to guarantee at least one letter in instanceid so it can be used as the session_name
1149
+            $id = 'oc' . \OC::$server->getSecureRandom()->generate(10, \OCP\Security\ISecureRandom::CHAR_LOWER.\OCP\Security\ISecureRandom::CHAR_DIGITS);
1150
+            \OC::$server->getSystemConfig()->setValue('instanceid', $id);
1151
+        }
1152
+        return $id;
1153
+    }
1154
+
1155
+    /**
1156
+     * Public function to sanitize HTML
1157
+     *
1158
+     * This function is used to sanitize HTML and should be applied on any
1159
+     * string or array of strings before displaying it on a web page.
1160
+     *
1161
+     * @param string|array $value
1162
+     * @return string|array an array of sanitized strings or a single sanitized string, depends on the input parameter.
1163
+     */
1164
+    public static function sanitizeHTML($value) {
1165
+        if (is_array($value)) {
1166
+            $value = array_map(function ($value) {
1167
+                return self::sanitizeHTML($value);
1168
+            }, $value);
1169
+        } else {
1170
+            // Specify encoding for PHP<5.4
1171
+            $value = htmlspecialchars((string)$value, ENT_QUOTES, 'UTF-8');
1172
+        }
1173
+        return $value;
1174
+    }
1175
+
1176
+    /**
1177
+     * Public function to encode url parameters
1178
+     *
1179
+     * This function is used to encode path to file before output.
1180
+     * Encoding is done according to RFC 3986 with one exception:
1181
+     * Character '/' is preserved as is.
1182
+     *
1183
+     * @param string $component part of URI to encode
1184
+     * @return string
1185
+     */
1186
+    public static function encodePath($component) {
1187
+        $encoded = rawurlencode($component);
1188
+        $encoded = str_replace('%2F', '/', $encoded);
1189
+        return $encoded;
1190
+    }
1191
+
1192
+
1193
+    public function createHtaccessTestFile(\OCP\IConfig $config) {
1194
+        // php dev server does not support htaccess
1195
+        if (php_sapi_name() === 'cli-server') {
1196
+            return false;
1197
+        }
1198
+
1199
+        // testdata
1200
+        $fileName = '/htaccesstest.txt';
1201
+        $testContent = 'This is used for testing whether htaccess is properly enabled to disallow access from the outside. This file can be safely removed.';
1202
+
1203
+        // creating a test file
1204
+        $testFile = $config->getSystemValue('datadirectory', OC::$SERVERROOT . '/data') . '/' . $fileName;
1205
+
1206
+        if (file_exists($testFile)) {// already running this test, possible recursive call
1207
+            return false;
1208
+        }
1209
+
1210
+        $fp = @fopen($testFile, 'w');
1211
+        if (!$fp) {
1212
+            throw new OC\HintException('Can\'t create test file to check for working .htaccess file.',
1213
+                'Make sure it is possible for the webserver to write to ' . $testFile);
1214
+        }
1215
+        fwrite($fp, $testContent);
1216
+        fclose($fp);
1217
+
1218
+        return $testContent;
1219
+    }
1220
+
1221
+    /**
1222
+     * Check if the .htaccess file is working
1223
+     * @param \OCP\IConfig $config
1224
+     * @return bool
1225
+     * @throws Exception
1226
+     * @throws \OC\HintException If the test file can't get written.
1227
+     */
1228
+    public function isHtaccessWorking(\OCP\IConfig $config) {
1229
+
1230
+        if (\OC::$CLI || !$config->getSystemValue('check_for_working_htaccess', true)) {
1231
+            return true;
1232
+        }
1233
+
1234
+        $testContent = $this->createHtaccessTestFile($config);
1235
+        if ($testContent === false) {
1236
+            return false;
1237
+        }
1238
+
1239
+        $fileName = '/htaccesstest.txt';
1240
+        $testFile = $config->getSystemValue('datadirectory', OC::$SERVERROOT . '/data') . '/' . $fileName;
1241
+
1242
+        // accessing the file via http
1243
+        $url = \OC::$server->getURLGenerator()->getAbsoluteURL(OC::$WEBROOT . '/data' . $fileName);
1244
+        try {
1245
+            $content = \OC::$server->getHTTPClientService()->newClient()->get($url)->getBody();
1246
+        } catch (\Exception $e) {
1247
+            $content = false;
1248
+        }
1249
+
1250
+        if (strpos($url, 'https:') === 0) {
1251
+            $url = 'http:' . substr($url, 6);
1252
+        } else {
1253
+            $url = 'https:' . substr($url, 5);
1254
+        }
1255
+
1256
+        try {
1257
+            $fallbackContent = \OC::$server->getHTTPClientService()->newClient()->get($url)->getBody();
1258
+        } catch (\Exception $e) {
1259
+            $fallbackContent = false;
1260
+        }
1261
+
1262
+        // cleanup
1263
+        @unlink($testFile);
1264
+
1265
+        /*
1266 1266
 		 * If the content is not equal to test content our .htaccess
1267 1267
 		 * is working as required
1268 1268
 		 */
1269
-		return $content !== $testContent && $fallbackContent !== $testContent;
1270
-	}
1271
-
1272
-	/**
1273
-	 * Check if the setlocal call does not work. This can happen if the right
1274
-	 * local packages are not available on the server.
1275
-	 *
1276
-	 * @return bool
1277
-	 */
1278
-	public static function isSetLocaleWorking() {
1279
-		\Patchwork\Utf8\Bootup::initLocale();
1280
-		if ('' === basename('§')) {
1281
-			return false;
1282
-		}
1283
-		return true;
1284
-	}
1285
-
1286
-	/**
1287
-	 * Check if it's possible to get the inline annotations
1288
-	 *
1289
-	 * @return bool
1290
-	 */
1291
-	public static function isAnnotationsWorking() {
1292
-		$reflection = new \ReflectionMethod(__METHOD__);
1293
-		$docs = $reflection->getDocComment();
1294
-
1295
-		return (is_string($docs) && strlen($docs) > 50);
1296
-	}
1297
-
1298
-	/**
1299
-	 * Check if the PHP module fileinfo is loaded.
1300
-	 *
1301
-	 * @return bool
1302
-	 */
1303
-	public static function fileInfoLoaded() {
1304
-		return function_exists('finfo_open');
1305
-	}
1306
-
1307
-	/**
1308
-	 * clear all levels of output buffering
1309
-	 *
1310
-	 * @return void
1311
-	 */
1312
-	public static function obEnd() {
1313
-		while (ob_get_level()) {
1314
-			ob_end_clean();
1315
-		}
1316
-	}
1317
-
1318
-	/**
1319
-	 * Checks whether the server is running on Mac OS X
1320
-	 *
1321
-	 * @return bool true if running on Mac OS X, false otherwise
1322
-	 */
1323
-	public static function runningOnMac() {
1324
-		return (strtoupper(substr(PHP_OS, 0, 6)) === 'DARWIN');
1325
-	}
1326
-
1327
-	/**
1328
-	 * Handles the case that there may not be a theme, then check if a "default"
1329
-	 * theme exists and take that one
1330
-	 *
1331
-	 * @return string the theme
1332
-	 */
1333
-	public static function getTheme() {
1334
-		$theme = \OC::$server->getSystemConfig()->getValue("theme", '');
1335
-
1336
-		if ($theme === '') {
1337
-			if (is_dir(OC::$SERVERROOT . '/themes/default')) {
1338
-				$theme = 'default';
1339
-			}
1340
-		}
1341
-
1342
-		return $theme;
1343
-	}
1344
-
1345
-	/**
1346
-	 * Normalize a unicode string
1347
-	 *
1348
-	 * @param string $value a not normalized string
1349
-	 * @return bool|string
1350
-	 */
1351
-	public static function normalizeUnicode($value) {
1352
-		if(Normalizer::isNormalized($value)) {
1353
-			return $value;
1354
-		}
1355
-
1356
-		$normalizedValue = Normalizer::normalize($value);
1357
-		if ($normalizedValue === null || $normalizedValue === false) {
1358
-			\OC::$server->getLogger()->warning('normalizing failed for "' . $value . '"', ['app' => 'core']);
1359
-			return $value;
1360
-		}
1361
-
1362
-		return $normalizedValue;
1363
-	}
1364
-
1365
-	/**
1366
-	 * A human readable string is generated based on version and build number
1367
-	 *
1368
-	 * @return string
1369
-	 */
1370
-	public static function getHumanVersion() {
1371
-		$version = OC_Util::getVersionString();
1372
-		$build = OC_Util::getBuild();
1373
-		if (!empty($build) and OC_Util::getChannel() === 'daily') {
1374
-			$version .= ' Build:' . $build;
1375
-		}
1376
-		return $version;
1377
-	}
1378
-
1379
-	/**
1380
-	 * Returns whether the given file name is valid
1381
-	 *
1382
-	 * @param string $file file name to check
1383
-	 * @return bool true if the file name is valid, false otherwise
1384
-	 * @deprecated use \OC\Files\View::verifyPath()
1385
-	 */
1386
-	public static function isValidFileName($file) {
1387
-		$trimmed = trim($file);
1388
-		if ($trimmed === '') {
1389
-			return false;
1390
-		}
1391
-		if (\OC\Files\Filesystem::isIgnoredDir($trimmed)) {
1392
-			return false;
1393
-		}
1394
-
1395
-		// detect part files
1396
-		if (preg_match('/' . \OCP\Files\FileInfo::BLACKLIST_FILES_REGEX . '/', $trimmed) !== 0) {
1397
-			return false;
1398
-		}
1399
-
1400
-		foreach (str_split($trimmed) as $char) {
1401
-			if (strpos(\OCP\Constants::FILENAME_INVALID_CHARS, $char) !== false) {
1402
-				return false;
1403
-			}
1404
-		}
1405
-		return true;
1406
-	}
1407
-
1408
-	/**
1409
-	 * Check whether the instance needs to perform an upgrade,
1410
-	 * either when the core version is higher or any app requires
1411
-	 * an upgrade.
1412
-	 *
1413
-	 * @param \OC\SystemConfig $config
1414
-	 * @return bool whether the core or any app needs an upgrade
1415
-	 * @throws \OC\HintException When the upgrade from the given version is not allowed
1416
-	 */
1417
-	public static function needUpgrade(\OC\SystemConfig $config) {
1418
-		if ($config->getValue('installed', false)) {
1419
-			$installedVersion = $config->getValue('version', '0.0.0');
1420
-			$currentVersion = implode('.', \OCP\Util::getVersion());
1421
-			$versionDiff = version_compare($currentVersion, $installedVersion);
1422
-			if ($versionDiff > 0) {
1423
-				return true;
1424
-			} else if ($config->getValue('debug', false) && $versionDiff < 0) {
1425
-				// downgrade with debug
1426
-				$installedMajor = explode('.', $installedVersion);
1427
-				$installedMajor = $installedMajor[0] . '.' . $installedMajor[1];
1428
-				$currentMajor = explode('.', $currentVersion);
1429
-				$currentMajor = $currentMajor[0] . '.' . $currentMajor[1];
1430
-				if ($installedMajor === $currentMajor) {
1431
-					// Same major, allow downgrade for developers
1432
-					return true;
1433
-				} else {
1434
-					// downgrade attempt, throw exception
1435
-					throw new \OC\HintException('Downgrading is not supported and is likely to cause unpredictable issues (from ' . $installedVersion . ' to ' . $currentVersion . ')');
1436
-				}
1437
-			} else if ($versionDiff < 0) {
1438
-				// downgrade attempt, throw exception
1439
-				throw new \OC\HintException('Downgrading is not supported and is likely to cause unpredictable issues (from ' . $installedVersion . ' to ' . $currentVersion . ')');
1440
-			}
1441
-
1442
-			// also check for upgrades for apps (independently from the user)
1443
-			$apps = \OC_App::getEnabledApps(false, true);
1444
-			$shouldUpgrade = false;
1445
-			foreach ($apps as $app) {
1446
-				if (\OC_App::shouldUpgrade($app)) {
1447
-					$shouldUpgrade = true;
1448
-					break;
1449
-				}
1450
-			}
1451
-			return $shouldUpgrade;
1452
-		} else {
1453
-			return false;
1454
-		}
1455
-	}
1456
-
1457
-	/**
1458
-	 * is this Internet explorer ?
1459
-	 *
1460
-	 * @return boolean
1461
-	 */
1462
-	public static function isIe() {
1463
-		if (!isset($_SERVER['HTTP_USER_AGENT'])) {
1464
-			return false;
1465
-		}
1466
-
1467
-		return preg_match(Request::USER_AGENT_IE, $_SERVER['HTTP_USER_AGENT']) === 1;
1468
-	}
1269
+        return $content !== $testContent && $fallbackContent !== $testContent;
1270
+    }
1271
+
1272
+    /**
1273
+     * Check if the setlocal call does not work. This can happen if the right
1274
+     * local packages are not available on the server.
1275
+     *
1276
+     * @return bool
1277
+     */
1278
+    public static function isSetLocaleWorking() {
1279
+        \Patchwork\Utf8\Bootup::initLocale();
1280
+        if ('' === basename('§')) {
1281
+            return false;
1282
+        }
1283
+        return true;
1284
+    }
1285
+
1286
+    /**
1287
+     * Check if it's possible to get the inline annotations
1288
+     *
1289
+     * @return bool
1290
+     */
1291
+    public static function isAnnotationsWorking() {
1292
+        $reflection = new \ReflectionMethod(__METHOD__);
1293
+        $docs = $reflection->getDocComment();
1294
+
1295
+        return (is_string($docs) && strlen($docs) > 50);
1296
+    }
1297
+
1298
+    /**
1299
+     * Check if the PHP module fileinfo is loaded.
1300
+     *
1301
+     * @return bool
1302
+     */
1303
+    public static function fileInfoLoaded() {
1304
+        return function_exists('finfo_open');
1305
+    }
1306
+
1307
+    /**
1308
+     * clear all levels of output buffering
1309
+     *
1310
+     * @return void
1311
+     */
1312
+    public static function obEnd() {
1313
+        while (ob_get_level()) {
1314
+            ob_end_clean();
1315
+        }
1316
+    }
1317
+
1318
+    /**
1319
+     * Checks whether the server is running on Mac OS X
1320
+     *
1321
+     * @return bool true if running on Mac OS X, false otherwise
1322
+     */
1323
+    public static function runningOnMac() {
1324
+        return (strtoupper(substr(PHP_OS, 0, 6)) === 'DARWIN');
1325
+    }
1326
+
1327
+    /**
1328
+     * Handles the case that there may not be a theme, then check if a "default"
1329
+     * theme exists and take that one
1330
+     *
1331
+     * @return string the theme
1332
+     */
1333
+    public static function getTheme() {
1334
+        $theme = \OC::$server->getSystemConfig()->getValue("theme", '');
1335
+
1336
+        if ($theme === '') {
1337
+            if (is_dir(OC::$SERVERROOT . '/themes/default')) {
1338
+                $theme = 'default';
1339
+            }
1340
+        }
1341
+
1342
+        return $theme;
1343
+    }
1344
+
1345
+    /**
1346
+     * Normalize a unicode string
1347
+     *
1348
+     * @param string $value a not normalized string
1349
+     * @return bool|string
1350
+     */
1351
+    public static function normalizeUnicode($value) {
1352
+        if(Normalizer::isNormalized($value)) {
1353
+            return $value;
1354
+        }
1355
+
1356
+        $normalizedValue = Normalizer::normalize($value);
1357
+        if ($normalizedValue === null || $normalizedValue === false) {
1358
+            \OC::$server->getLogger()->warning('normalizing failed for "' . $value . '"', ['app' => 'core']);
1359
+            return $value;
1360
+        }
1361
+
1362
+        return $normalizedValue;
1363
+    }
1364
+
1365
+    /**
1366
+     * A human readable string is generated based on version and build number
1367
+     *
1368
+     * @return string
1369
+     */
1370
+    public static function getHumanVersion() {
1371
+        $version = OC_Util::getVersionString();
1372
+        $build = OC_Util::getBuild();
1373
+        if (!empty($build) and OC_Util::getChannel() === 'daily') {
1374
+            $version .= ' Build:' . $build;
1375
+        }
1376
+        return $version;
1377
+    }
1378
+
1379
+    /**
1380
+     * Returns whether the given file name is valid
1381
+     *
1382
+     * @param string $file file name to check
1383
+     * @return bool true if the file name is valid, false otherwise
1384
+     * @deprecated use \OC\Files\View::verifyPath()
1385
+     */
1386
+    public static function isValidFileName($file) {
1387
+        $trimmed = trim($file);
1388
+        if ($trimmed === '') {
1389
+            return false;
1390
+        }
1391
+        if (\OC\Files\Filesystem::isIgnoredDir($trimmed)) {
1392
+            return false;
1393
+        }
1394
+
1395
+        // detect part files
1396
+        if (preg_match('/' . \OCP\Files\FileInfo::BLACKLIST_FILES_REGEX . '/', $trimmed) !== 0) {
1397
+            return false;
1398
+        }
1399
+
1400
+        foreach (str_split($trimmed) as $char) {
1401
+            if (strpos(\OCP\Constants::FILENAME_INVALID_CHARS, $char) !== false) {
1402
+                return false;
1403
+            }
1404
+        }
1405
+        return true;
1406
+    }
1407
+
1408
+    /**
1409
+     * Check whether the instance needs to perform an upgrade,
1410
+     * either when the core version is higher or any app requires
1411
+     * an upgrade.
1412
+     *
1413
+     * @param \OC\SystemConfig $config
1414
+     * @return bool whether the core or any app needs an upgrade
1415
+     * @throws \OC\HintException When the upgrade from the given version is not allowed
1416
+     */
1417
+    public static function needUpgrade(\OC\SystemConfig $config) {
1418
+        if ($config->getValue('installed', false)) {
1419
+            $installedVersion = $config->getValue('version', '0.0.0');
1420
+            $currentVersion = implode('.', \OCP\Util::getVersion());
1421
+            $versionDiff = version_compare($currentVersion, $installedVersion);
1422
+            if ($versionDiff > 0) {
1423
+                return true;
1424
+            } else if ($config->getValue('debug', false) && $versionDiff < 0) {
1425
+                // downgrade with debug
1426
+                $installedMajor = explode('.', $installedVersion);
1427
+                $installedMajor = $installedMajor[0] . '.' . $installedMajor[1];
1428
+                $currentMajor = explode('.', $currentVersion);
1429
+                $currentMajor = $currentMajor[0] . '.' . $currentMajor[1];
1430
+                if ($installedMajor === $currentMajor) {
1431
+                    // Same major, allow downgrade for developers
1432
+                    return true;
1433
+                } else {
1434
+                    // downgrade attempt, throw exception
1435
+                    throw new \OC\HintException('Downgrading is not supported and is likely to cause unpredictable issues (from ' . $installedVersion . ' to ' . $currentVersion . ')');
1436
+                }
1437
+            } else if ($versionDiff < 0) {
1438
+                // downgrade attempt, throw exception
1439
+                throw new \OC\HintException('Downgrading is not supported and is likely to cause unpredictable issues (from ' . $installedVersion . ' to ' . $currentVersion . ')');
1440
+            }
1441
+
1442
+            // also check for upgrades for apps (independently from the user)
1443
+            $apps = \OC_App::getEnabledApps(false, true);
1444
+            $shouldUpgrade = false;
1445
+            foreach ($apps as $app) {
1446
+                if (\OC_App::shouldUpgrade($app)) {
1447
+                    $shouldUpgrade = true;
1448
+                    break;
1449
+                }
1450
+            }
1451
+            return $shouldUpgrade;
1452
+        } else {
1453
+            return false;
1454
+        }
1455
+    }
1456
+
1457
+    /**
1458
+     * is this Internet explorer ?
1459
+     *
1460
+     * @return boolean
1461
+     */
1462
+    public static function isIe() {
1463
+        if (!isset($_SERVER['HTTP_USER_AGENT'])) {
1464
+            return false;
1465
+        }
1466
+
1467
+        return preg_match(Request::USER_AGENT_IE, $_SERVER['HTTP_USER_AGENT']) === 1;
1468
+    }
1469 1469
 
1470 1470
 }
Please login to merge, or discard this patch.
Spacing   +60 added lines, -60 removed lines patch added patch discarded remove patch
@@ -84,7 +84,7 @@  discard block
 block discarded – undo
84 84
 
85 85
 	private static function initLocalStorageRootFS() {
86 86
 		// mount local file backend as root
87
-		$configDataDirectory = \OC::$server->getSystemConfig()->getValue("datadirectory", OC::$SERVERROOT . "/data");
87
+		$configDataDirectory = \OC::$server->getSystemConfig()->getValue("datadirectory", OC::$SERVERROOT."/data");
88 88
 		//first set up the local "root" storage
89 89
 		\OC\Files\Filesystem::initMountManager();
90 90
 		if (!self::$rootMounted) {
@@ -206,7 +206,7 @@  discard block
 block discarded – undo
206 206
 		\OC\Files\Filesystem::initMountManager();
207 207
 
208 208
 		$prevLogging = \OC\Files\Filesystem::logWarningWhenAddingStorageWrapper(false);
209
-		\OC\Files\Filesystem::addStorageWrapper('mount_options', function ($mountPoint, \OCP\Files\Storage $storage, \OCP\Files\Mount\IMountPoint $mount) {
209
+		\OC\Files\Filesystem::addStorageWrapper('mount_options', function($mountPoint, \OCP\Files\Storage $storage, \OCP\Files\Mount\IMountPoint $mount) {
210 210
 			if ($storage->instanceOfStorage('\OC\Files\Storage\Common')) {
211 211
 				/** @var \OC\Files\Storage\Common $storage */
212 212
 				$storage->setMountOptions($mount->getOptions());
@@ -214,7 +214,7 @@  discard block
 block discarded – undo
214 214
 			return $storage;
215 215
 		});
216 216
 
217
-		\OC\Files\Filesystem::addStorageWrapper('enable_sharing', function ($mountPoint, \OCP\Files\Storage\IStorage $storage, \OCP\Files\Mount\IMountPoint $mount) {
217
+		\OC\Files\Filesystem::addStorageWrapper('enable_sharing', function($mountPoint, \OCP\Files\Storage\IStorage $storage, \OCP\Files\Mount\IMountPoint $mount) {
218 218
 			if (!$mount->getOption('enable_sharing', true)) {
219 219
 				return new \OC\Files\Storage\Wrapper\PermissionsMask([
220 220
 					'storage' => $storage,
@@ -225,21 +225,21 @@  discard block
 block discarded – undo
225 225
 		});
226 226
 
227 227
 		// install storage availability wrapper, before most other wrappers
228
-		\OC\Files\Filesystem::addStorageWrapper('oc_availability', function ($mountPoint, \OCP\Files\Storage\IStorage $storage) {
228
+		\OC\Files\Filesystem::addStorageWrapper('oc_availability', function($mountPoint, \OCP\Files\Storage\IStorage $storage) {
229 229
 			if (!$storage->instanceOfStorage('\OCA\Files_Sharing\SharedStorage') && !$storage->isLocal()) {
230 230
 				return new \OC\Files\Storage\Wrapper\Availability(['storage' => $storage]);
231 231
 			}
232 232
 			return $storage;
233 233
 		});
234 234
 
235
-		\OC\Files\Filesystem::addStorageWrapper('oc_encoding', function ($mountPoint, \OCP\Files\Storage $storage, \OCP\Files\Mount\IMountPoint $mount) {
235
+		\OC\Files\Filesystem::addStorageWrapper('oc_encoding', function($mountPoint, \OCP\Files\Storage $storage, \OCP\Files\Mount\IMountPoint $mount) {
236 236
 			if ($mount->getOption('encoding_compatibility', false) && !$storage->instanceOfStorage('\OCA\Files_Sharing\SharedStorage') && !$storage->isLocal()) {
237 237
 				return new \OC\Files\Storage\Wrapper\Encoding(['storage' => $storage]);
238 238
 			}
239 239
 			return $storage;
240 240
 		});
241 241
 
242
-		\OC\Files\Filesystem::addStorageWrapper('oc_quota', function ($mountPoint, $storage) {
242
+		\OC\Files\Filesystem::addStorageWrapper('oc_quota', function($mountPoint, $storage) {
243 243
 			// set up quota for home storages, even for other users
244 244
 			// which can happen when using sharing
245 245
 
@@ -261,7 +261,7 @@  discard block
 block discarded – undo
261 261
 			return $storage;
262 262
 		});
263 263
 
264
-		\OC\Files\Filesystem::addStorageWrapper('readonly', function ($mountPoint, \OCP\Files\Storage\IStorage $storage, \OCP\Files\Mount\IMountPoint $mount) {
264
+		\OC\Files\Filesystem::addStorageWrapper('readonly', function($mountPoint, \OCP\Files\Storage\IStorage $storage, \OCP\Files\Mount\IMountPoint $mount) {
265 265
 			/*
266 266
 			 * Do not allow any operations that modify the storage
267 267
 			 */
@@ -303,7 +303,7 @@  discard block
 block discarded – undo
303 303
 		//if we aren't logged in, there is no use to set up the filesystem
304 304
 		if ($user != "") {
305 305
 
306
-			$userDir = '/' . $user . '/files';
306
+			$userDir = '/'.$user.'/files';
307 307
 
308 308
 			//jail the user into his "home" directory
309 309
 			\OC\Files\Filesystem::init($user, $userDir);
@@ -382,7 +382,7 @@  discard block
 block discarded – undo
382 382
 			return \OCP\Files\FileInfo::SPACE_UNLIMITED;
383 383
 		}
384 384
 		$userQuota = $user->getQuota();
385
-		if($userQuota === 'none') {
385
+		if ($userQuota === 'none') {
386 386
 			return \OCP\Files\FileInfo::SPACE_UNLIMITED;
387 387
 		}
388 388
 		return OC_Helper::computerFileSize($userQuota);
@@ -399,7 +399,7 @@  discard block
 block discarded – undo
399 399
 	 */
400 400
 	public static function copySkeleton($userId, \OCP\Files\Folder $userDirectory) {
401 401
 
402
-		$plainSkeletonDirectory = \OC::$server->getConfig()->getSystemValue('skeletondirectory', \OC::$SERVERROOT . '/core/skeleton');
402
+		$plainSkeletonDirectory = \OC::$server->getConfig()->getSystemValue('skeletondirectory', \OC::$SERVERROOT.'/core/skeleton');
403 403
 		$userLang = \OC::$server->getL10NFactory()->findLanguage();
404 404
 		$skeletonDirectory = str_replace('{lang}', $userLang, $plainSkeletonDirectory);
405 405
 
@@ -421,9 +421,9 @@  discard block
 block discarded – undo
421 421
 		if ($instanceId === null) {
422 422
 			throw new \RuntimeException('no instance id!');
423 423
 		}
424
-		$appdata = 'appdata_' . $instanceId;
424
+		$appdata = 'appdata_'.$instanceId;
425 425
 		if ($userId === $appdata) {
426
-			throw new \RuntimeException('username is reserved name: ' . $appdata);
426
+			throw new \RuntimeException('username is reserved name: '.$appdata);
427 427
 		}
428 428
 
429 429
 		if (!empty($skeletonDirectory)) {
@@ -450,7 +450,7 @@  discard block
 block discarded – undo
450 450
 
451 451
 		// Verify if folder exists
452 452
 		$dir = opendir($source);
453
-		if($dir === false) {
453
+		if ($dir === false) {
454 454
 			$logger->error(sprintf('Could not opendir "%s"', $source), ['app' => 'core']);
455 455
 			return;
456 456
 		}
@@ -458,14 +458,14 @@  discard block
 block discarded – undo
458 458
 		// Copy the files
459 459
 		while (false !== ($file = readdir($dir))) {
460 460
 			if (!\OC\Files\Filesystem::isIgnoredDir($file)) {
461
-				if (is_dir($source . '/' . $file)) {
461
+				if (is_dir($source.'/'.$file)) {
462 462
 					$child = $target->newFolder($file);
463
-					self::copyr($source . '/' . $file, $child);
463
+					self::copyr($source.'/'.$file, $child);
464 464
 				} else {
465 465
 					$child = $target->newFile($file);
466
-					$sourceStream = fopen($source . '/' . $file, 'r');
467
-					if($sourceStream === false) {
468
-						$logger->error(sprintf('Could not fopen "%s"', $source . '/' . $file), ['app' => 'core']);
466
+					$sourceStream = fopen($source.'/'.$file, 'r');
467
+					if ($sourceStream === false) {
468
+						$logger->error(sprintf('Could not fopen "%s"', $source.'/'.$file), ['app' => 'core']);
469 469
 						closedir($dir);
470 470
 						return;
471 471
 					}
@@ -542,8 +542,8 @@  discard block
 block discarded – undo
542 542
 			return;
543 543
 		}
544 544
 
545
-		$timestamp = filemtime(OC::$SERVERROOT . '/version.php');
546
-		require OC::$SERVERROOT . '/version.php';
545
+		$timestamp = filemtime(OC::$SERVERROOT.'/version.php');
546
+		require OC::$SERVERROOT.'/version.php';
547 547
 		/** @var $timestamp int */
548 548
 		self::$versionCache['OC_Version_Timestamp'] = $timestamp;
549 549
 		/** @var $OC_Version string */
@@ -715,7 +715,7 @@  discard block
 block discarded – undo
715 715
 	public static function checkServer(\OC\SystemConfig $config) {
716 716
 		$l = \OC::$server->getL10N('lib');
717 717
 		$errors = [];
718
-		$CONFIG_DATADIRECTORY = $config->getValue('datadirectory', OC::$SERVERROOT . '/data');
718
+		$CONFIG_DATADIRECTORY = $config->getValue('datadirectory', OC::$SERVERROOT.'/data');
719 719
 
720 720
 		if (!self::needUpgrade($config) && $config->getValue('installed', false)) {
721 721
 			// this check needs to be done every time
@@ -750,14 +750,14 @@  discard block
 block discarded – undo
750 750
 		}
751 751
 
752 752
 		// Check if config folder is writable.
753
-		if(!OC_Helper::isReadOnlyConfigEnabled()) {
753
+		if (!OC_Helper::isReadOnlyConfigEnabled()) {
754 754
 			if (!is_writable(OC::$configDir) or !is_readable(OC::$configDir)) {
755 755
 				$errors[] = [
756 756
 					'error' => $l->t('Cannot write into "config" directory'),
757 757
 					'hint' => $l->t('This can usually be fixed by giving the webserver write access to the config directory. See %s',
758
-						[ $urlGenerator->linkToDocs('admin-dir_permissions') ]) . '. '
758
+						[$urlGenerator->linkToDocs('admin-dir_permissions')]).'. '
759 759
 						. $l->t('Or, if you prefer to keep config.php file read only, set the option "config_is_read_only" to true in it. See %s',
760
-						[ $urlGenerator->linkToDocs('admin-config') ])
760
+						[$urlGenerator->linkToDocs('admin-config')])
761 761
 				];
762 762
 			}
763 763
 		}
@@ -890,15 +890,15 @@  discard block
 block discarded – undo
890 890
 			}
891 891
 		}
892 892
 
893
-		foreach($missingDependencies as $missingDependency) {
893
+		foreach ($missingDependencies as $missingDependency) {
894 894
 			$errors[] = [
895 895
 				'error' => $l->t('PHP module %s not installed.', [$missingDependency]),
896 896
 				'hint' => $moduleHint
897 897
 			];
898 898
 			$webServerRestart = true;
899 899
 		}
900
-		foreach($invalidIniSettings as $setting) {
901
-			if(is_bool($setting[1])) {
900
+		foreach ($invalidIniSettings as $setting) {
901
+			if (is_bool($setting[1])) {
902 902
 				$setting[1] = $setting[1] ? 'on' : 'off';
903 903
 			}
904 904
 			$errors[] = [
@@ -916,7 +916,7 @@  discard block
 block discarded – undo
916 916
 		 * TODO: Should probably be implemented in the above generic dependency
917 917
 		 *       check somehow in the long-term.
918 918
 		 */
919
-		if($iniWrapper->getBool('mbstring.func_overload') !== null &&
919
+		if ($iniWrapper->getBool('mbstring.func_overload') !== null &&
920 920
 			$iniWrapper->getBool('mbstring.func_overload') === true) {
921 921
 			$errors[] = [
922 922
 				'error' => $l->t('mbstring.func_overload is set to "%s" instead of the expected value "0"', [$iniWrapper->getString('mbstring.func_overload')]),
@@ -924,16 +924,16 @@  discard block
 block discarded – undo
924 924
 			];
925 925
 		}
926 926
 
927
-		if(function_exists('xml_parser_create') &&
927
+		if (function_exists('xml_parser_create') &&
928 928
 			LIBXML_LOADED_VERSION < 20700) {
929 929
 			$version = LIBXML_LOADED_VERSION;
930
-			$major = floor($version/10000);
930
+			$major = floor($version / 10000);
931 931
 			$version -= ($major * 10000);
932
-			$minor = floor($version/100);
932
+			$minor = floor($version / 100);
933 933
 			$version -= ($minor * 100);
934 934
 			$patch = $version;
935 935
 			$errors[] = [
936
-				'error' => $l->t('libxml2 2.7.0 is at least required. Currently %s is installed.', [$major . '.' . $minor . '.' . $patch]),
936
+				'error' => $l->t('libxml2 2.7.0 is at least required. Currently %s is installed.', [$major.'.'.$minor.'.'.$patch]),
937 937
 				'hint' => $l->t('To fix this issue update your libxml2 version and restart your web server.')
938 938
 			];
939 939
 		}
@@ -999,7 +999,7 @@  discard block
 block discarded – undo
999 999
 	 * @return array arrays with error messages and hints
1000 1000
 	 */
1001 1001
 	public static function checkDataDirectoryPermissions($dataDirectory) {
1002
-		if(\OC::$server->getConfig()->getSystemValue('check_data_directory_permissions', true) === false) {
1002
+		if (\OC::$server->getConfig()->getSystemValue('check_data_directory_permissions', true) === false) {
1003 1003
 			return  [];
1004 1004
 		}
1005 1005
 		$l = \OC::$server->getL10N('lib');
@@ -1037,10 +1037,10 @@  discard block
 block discarded – undo
1037 1037
 				'hint' => $l->t('Check the value of "datadirectory" in your configuration')
1038 1038
 			];
1039 1039
 		}
1040
-		if (!file_exists($dataDirectory . '/.ocdata')) {
1040
+		if (!file_exists($dataDirectory.'/.ocdata')) {
1041 1041
 			$errors[] = [
1042 1042
 				'error' => $l->t('Your data directory is invalid'),
1043
-				'hint' => $l->t('Ensure there is a file called ".ocdata"' .
1043
+				'hint' => $l->t('Ensure there is a file called ".ocdata"'.
1044 1044
 					' in the root of the data directory.')
1045 1045
 			];
1046 1046
 		}
@@ -1056,7 +1056,7 @@  discard block
 block discarded – undo
1056 1056
 	public static function checkLoggedIn() {
1057 1057
 		// Check if we are a user
1058 1058
 		if (!\OC::$server->getUserSession()->isLoggedIn()) {
1059
-			header('Location: ' . \OC::$server->getURLGenerator()->linkToRoute(
1059
+			header('Location: '.\OC::$server->getURLGenerator()->linkToRoute(
1060 1060
 						'core.login.showLoginForm',
1061 1061
 						[
1062 1062
 							'redirect_url' => \OC::$server->getRequest()->getRequestUri(),
@@ -1067,7 +1067,7 @@  discard block
 block discarded – undo
1067 1067
 		}
1068 1068
 		// Redirect to 2FA challenge selection if 2FA challenge was not solved yet
1069 1069
 		if (\OC::$server->getTwoFactorAuthManager()->needsSecondFactor(\OC::$server->getUserSession()->getUser())) {
1070
-			header('Location: ' . \OC::$server->getURLGenerator()->linkToRoute('core.TwoFactorChallenge.selectChallenge'));
1070
+			header('Location: '.\OC::$server->getURLGenerator()->linkToRoute('core.TwoFactorChallenge.selectChallenge'));
1071 1071
 			exit();
1072 1072
 		}
1073 1073
 	}
@@ -1080,7 +1080,7 @@  discard block
 block discarded – undo
1080 1080
 	public static function checkAdminUser() {
1081 1081
 		OC_Util::checkLoggedIn();
1082 1082
 		if (!OC_User::isAdminUser(OC_User::getUser())) {
1083
-			header('Location: ' . \OCP\Util::linkToAbsolute('', 'index.php'));
1083
+			header('Location: '.\OCP\Util::linkToAbsolute('', 'index.php'));
1084 1084
 			exit();
1085 1085
 		}
1086 1086
 	}
@@ -1116,10 +1116,10 @@  discard block
 block discarded – undo
1116 1116
 					}
1117 1117
 				}
1118 1118
 
1119
-				if($config->getSystemValue('htaccess.IgnoreFrontController', false) === true || getenv('front_controller_active') === 'true') {
1120
-					$location = $urlGenerator->getAbsoluteURL('/apps/' . $appId . '/');
1119
+				if ($config->getSystemValue('htaccess.IgnoreFrontController', false) === true || getenv('front_controller_active') === 'true') {
1120
+					$location = $urlGenerator->getAbsoluteURL('/apps/'.$appId.'/');
1121 1121
 				} else {
1122
-					$location = $urlGenerator->getAbsoluteURL('/index.php/apps/' . $appId . '/');
1122
+					$location = $urlGenerator->getAbsoluteURL('/index.php/apps/'.$appId.'/');
1123 1123
 				}
1124 1124
 			}
1125 1125
 		}
@@ -1133,7 +1133,7 @@  discard block
 block discarded – undo
1133 1133
 	 */
1134 1134
 	public static function redirectToDefaultPage() {
1135 1135
 		$location = self::getDefaultPageUrl();
1136
-		header('Location: ' . $location);
1136
+		header('Location: '.$location);
1137 1137
 		exit();
1138 1138
 	}
1139 1139
 
@@ -1146,7 +1146,7 @@  discard block
 block discarded – undo
1146 1146
 		$id = \OC::$server->getSystemConfig()->getValue('instanceid', null);
1147 1147
 		if (is_null($id)) {
1148 1148
 			// We need to guarantee at least one letter in instanceid so it can be used as the session_name
1149
-			$id = 'oc' . \OC::$server->getSecureRandom()->generate(10, \OCP\Security\ISecureRandom::CHAR_LOWER.\OCP\Security\ISecureRandom::CHAR_DIGITS);
1149
+			$id = 'oc'.\OC::$server->getSecureRandom()->generate(10, \OCP\Security\ISecureRandom::CHAR_LOWER.\OCP\Security\ISecureRandom::CHAR_DIGITS);
1150 1150
 			\OC::$server->getSystemConfig()->setValue('instanceid', $id);
1151 1151
 		}
1152 1152
 		return $id;
@@ -1163,12 +1163,12 @@  discard block
 block discarded – undo
1163 1163
 	 */
1164 1164
 	public static function sanitizeHTML($value) {
1165 1165
 		if (is_array($value)) {
1166
-			$value = array_map(function ($value) {
1166
+			$value = array_map(function($value) {
1167 1167
 				return self::sanitizeHTML($value);
1168 1168
 			}, $value);
1169 1169
 		} else {
1170 1170
 			// Specify encoding for PHP<5.4
1171
-			$value = htmlspecialchars((string)$value, ENT_QUOTES, 'UTF-8');
1171
+			$value = htmlspecialchars((string) $value, ENT_QUOTES, 'UTF-8');
1172 1172
 		}
1173 1173
 		return $value;
1174 1174
 	}
@@ -1201,7 +1201,7 @@  discard block
 block discarded – undo
1201 1201
 		$testContent = 'This is used for testing whether htaccess is properly enabled to disallow access from the outside. This file can be safely removed.';
1202 1202
 
1203 1203
 		// creating a test file
1204
-		$testFile = $config->getSystemValue('datadirectory', OC::$SERVERROOT . '/data') . '/' . $fileName;
1204
+		$testFile = $config->getSystemValue('datadirectory', OC::$SERVERROOT.'/data').'/'.$fileName;
1205 1205
 
1206 1206
 		if (file_exists($testFile)) {// already running this test, possible recursive call
1207 1207
 			return false;
@@ -1210,7 +1210,7 @@  discard block
 block discarded – undo
1210 1210
 		$fp = @fopen($testFile, 'w');
1211 1211
 		if (!$fp) {
1212 1212
 			throw new OC\HintException('Can\'t create test file to check for working .htaccess file.',
1213
-				'Make sure it is possible for the webserver to write to ' . $testFile);
1213
+				'Make sure it is possible for the webserver to write to '.$testFile);
1214 1214
 		}
1215 1215
 		fwrite($fp, $testContent);
1216 1216
 		fclose($fp);
@@ -1237,10 +1237,10 @@  discard block
 block discarded – undo
1237 1237
 		}
1238 1238
 
1239 1239
 		$fileName = '/htaccesstest.txt';
1240
-		$testFile = $config->getSystemValue('datadirectory', OC::$SERVERROOT . '/data') . '/' . $fileName;
1240
+		$testFile = $config->getSystemValue('datadirectory', OC::$SERVERROOT.'/data').'/'.$fileName;
1241 1241
 
1242 1242
 		// accessing the file via http
1243
-		$url = \OC::$server->getURLGenerator()->getAbsoluteURL(OC::$WEBROOT . '/data' . $fileName);
1243
+		$url = \OC::$server->getURLGenerator()->getAbsoluteURL(OC::$WEBROOT.'/data'.$fileName);
1244 1244
 		try {
1245 1245
 			$content = \OC::$server->getHTTPClientService()->newClient()->get($url)->getBody();
1246 1246
 		} catch (\Exception $e) {
@@ -1248,9 +1248,9 @@  discard block
 block discarded – undo
1248 1248
 		}
1249 1249
 
1250 1250
 		if (strpos($url, 'https:') === 0) {
1251
-			$url = 'http:' . substr($url, 6);
1251
+			$url = 'http:'.substr($url, 6);
1252 1252
 		} else {
1253
-			$url = 'https:' . substr($url, 5);
1253
+			$url = 'https:'.substr($url, 5);
1254 1254
 		}
1255 1255
 
1256 1256
 		try {
@@ -1334,7 +1334,7 @@  discard block
 block discarded – undo
1334 1334
 		$theme = \OC::$server->getSystemConfig()->getValue("theme", '');
1335 1335
 
1336 1336
 		if ($theme === '') {
1337
-			if (is_dir(OC::$SERVERROOT . '/themes/default')) {
1337
+			if (is_dir(OC::$SERVERROOT.'/themes/default')) {
1338 1338
 				$theme = 'default';
1339 1339
 			}
1340 1340
 		}
@@ -1349,13 +1349,13 @@  discard block
 block discarded – undo
1349 1349
 	 * @return bool|string
1350 1350
 	 */
1351 1351
 	public static function normalizeUnicode($value) {
1352
-		if(Normalizer::isNormalized($value)) {
1352
+		if (Normalizer::isNormalized($value)) {
1353 1353
 			return $value;
1354 1354
 		}
1355 1355
 
1356 1356
 		$normalizedValue = Normalizer::normalize($value);
1357 1357
 		if ($normalizedValue === null || $normalizedValue === false) {
1358
-			\OC::$server->getLogger()->warning('normalizing failed for "' . $value . '"', ['app' => 'core']);
1358
+			\OC::$server->getLogger()->warning('normalizing failed for "'.$value.'"', ['app' => 'core']);
1359 1359
 			return $value;
1360 1360
 		}
1361 1361
 
@@ -1371,7 +1371,7 @@  discard block
 block discarded – undo
1371 1371
 		$version = OC_Util::getVersionString();
1372 1372
 		$build = OC_Util::getBuild();
1373 1373
 		if (!empty($build) and OC_Util::getChannel() === 'daily') {
1374
-			$version .= ' Build:' . $build;
1374
+			$version .= ' Build:'.$build;
1375 1375
 		}
1376 1376
 		return $version;
1377 1377
 	}
@@ -1393,7 +1393,7 @@  discard block
 block discarded – undo
1393 1393
 		}
1394 1394
 
1395 1395
 		// detect part files
1396
-		if (preg_match('/' . \OCP\Files\FileInfo::BLACKLIST_FILES_REGEX . '/', $trimmed) !== 0) {
1396
+		if (preg_match('/'.\OCP\Files\FileInfo::BLACKLIST_FILES_REGEX.'/', $trimmed) !== 0) {
1397 1397
 			return false;
1398 1398
 		}
1399 1399
 
@@ -1424,19 +1424,19 @@  discard block
 block discarded – undo
1424 1424
 			} else if ($config->getValue('debug', false) && $versionDiff < 0) {
1425 1425
 				// downgrade with debug
1426 1426
 				$installedMajor = explode('.', $installedVersion);
1427
-				$installedMajor = $installedMajor[0] . '.' . $installedMajor[1];
1427
+				$installedMajor = $installedMajor[0].'.'.$installedMajor[1];
1428 1428
 				$currentMajor = explode('.', $currentVersion);
1429
-				$currentMajor = $currentMajor[0] . '.' . $currentMajor[1];
1429
+				$currentMajor = $currentMajor[0].'.'.$currentMajor[1];
1430 1430
 				if ($installedMajor === $currentMajor) {
1431 1431
 					// Same major, allow downgrade for developers
1432 1432
 					return true;
1433 1433
 				} else {
1434 1434
 					// downgrade attempt, throw exception
1435
-					throw new \OC\HintException('Downgrading is not supported and is likely to cause unpredictable issues (from ' . $installedVersion . ' to ' . $currentVersion . ')');
1435
+					throw new \OC\HintException('Downgrading is not supported and is likely to cause unpredictable issues (from '.$installedVersion.' to '.$currentVersion.')');
1436 1436
 				}
1437 1437
 			} else if ($versionDiff < 0) {
1438 1438
 				// downgrade attempt, throw exception
1439
-				throw new \OC\HintException('Downgrading is not supported and is likely to cause unpredictable issues (from ' . $installedVersion . ' to ' . $currentVersion . ')');
1439
+				throw new \OC\HintException('Downgrading is not supported and is likely to cause unpredictable issues (from '.$installedVersion.' to '.$currentVersion.')');
1440 1440
 			}
1441 1441
 
1442 1442
 			// also check for upgrades for apps (independently from the user)
Please login to merge, or discard this patch.
lib/private/legacy/OC_JSON.php 2 patches
Indentation   +94 added lines, -94 removed lines patch added patch discarded remove patch
@@ -35,106 +35,106 @@
 block discarded – undo
35 35
  */
36 36
 class OC_JSON{
37 37
 
38
-	/**
39
-	 * Check if the app is enabled, send json error msg if not
40
-	 * @param string $app
41
-	 * @deprecated Use the AppFramework instead. It will automatically check if the app is enabled.
42
-	 * @suppress PhanDeprecatedFunction
43
-	 */
44
-	public static function checkAppEnabled($app) {
45
-		if(!\OC::$server->getAppManager()->isEnabledForUser($app)) {
46
-			$l = \OC::$server->getL10N('lib');
47
-			self::error([ 'data' => [ 'message' => $l->t('Application is not enabled'), 'error' => 'application_not_enabled' ]]);
48
-			exit();
49
-		}
50
-	}
38
+    /**
39
+     * Check if the app is enabled, send json error msg if not
40
+     * @param string $app
41
+     * @deprecated Use the AppFramework instead. It will automatically check if the app is enabled.
42
+     * @suppress PhanDeprecatedFunction
43
+     */
44
+    public static function checkAppEnabled($app) {
45
+        if(!\OC::$server->getAppManager()->isEnabledForUser($app)) {
46
+            $l = \OC::$server->getL10N('lib');
47
+            self::error([ 'data' => [ 'message' => $l->t('Application is not enabled'), 'error' => 'application_not_enabled' ]]);
48
+            exit();
49
+        }
50
+    }
51 51
 
52
-	/**
53
-	 * Check if the user is logged in, send json error msg if not
54
-	 * @deprecated Use annotation based ACLs from the AppFramework instead
55
-	 * @suppress PhanDeprecatedFunction
56
-	 */
57
-	public static function checkLoggedIn() {
58
-		$twoFactorAuthManger = \OC::$server->getTwoFactorAuthManager();
59
-		if(!\OC::$server->getUserSession()->isLoggedIn()
60
-			|| $twoFactorAuthManger->needsSecondFactor(\OC::$server->getUserSession()->getUser())) {
61
-			$l = \OC::$server->getL10N('lib');
62
-			http_response_code(\OCP\AppFramework\Http::STATUS_UNAUTHORIZED);
63
-			self::error([ 'data' => [ 'message' => $l->t('Authentication error'), 'error' => 'authentication_error' ]]);
64
-			exit();
65
-		}
66
-	}
52
+    /**
53
+     * Check if the user is logged in, send json error msg if not
54
+     * @deprecated Use annotation based ACLs from the AppFramework instead
55
+     * @suppress PhanDeprecatedFunction
56
+     */
57
+    public static function checkLoggedIn() {
58
+        $twoFactorAuthManger = \OC::$server->getTwoFactorAuthManager();
59
+        if(!\OC::$server->getUserSession()->isLoggedIn()
60
+            || $twoFactorAuthManger->needsSecondFactor(\OC::$server->getUserSession()->getUser())) {
61
+            $l = \OC::$server->getL10N('lib');
62
+            http_response_code(\OCP\AppFramework\Http::STATUS_UNAUTHORIZED);
63
+            self::error([ 'data' => [ 'message' => $l->t('Authentication error'), 'error' => 'authentication_error' ]]);
64
+            exit();
65
+        }
66
+    }
67 67
 
68
-	/**
69
-	 * Check an ajax get/post call if the request token is valid, send json error msg if not.
70
-	 * @deprecated Use annotation based CSRF checks from the AppFramework instead
71
-	 * @suppress PhanDeprecatedFunction
72
-	 */
73
-	public static function callCheck() {
74
-		if(!\OC::$server->getRequest()->passesStrictCookieCheck()) {
75
-			header('Location: '.\OC::$WEBROOT);
76
-			exit();
77
-		}
68
+    /**
69
+     * Check an ajax get/post call if the request token is valid, send json error msg if not.
70
+     * @deprecated Use annotation based CSRF checks from the AppFramework instead
71
+     * @suppress PhanDeprecatedFunction
72
+     */
73
+    public static function callCheck() {
74
+        if(!\OC::$server->getRequest()->passesStrictCookieCheck()) {
75
+            header('Location: '.\OC::$WEBROOT);
76
+            exit();
77
+        }
78 78
 
79
-		if(!\OC::$server->getRequest()->passesCSRFCheck()) {
80
-			$l = \OC::$server->getL10N('lib');
81
-			self::error([ 'data' => [ 'message' => $l->t('Token expired. Please reload page.'), 'error' => 'token_expired' ]]);
82
-			exit();
83
-		}
84
-	}
79
+        if(!\OC::$server->getRequest()->passesCSRFCheck()) {
80
+            $l = \OC::$server->getL10N('lib');
81
+            self::error([ 'data' => [ 'message' => $l->t('Token expired. Please reload page.'), 'error' => 'token_expired' ]]);
82
+            exit();
83
+        }
84
+    }
85 85
 
86
-	/**
87
-	 * Check if the user is a admin, send json error msg if not.
88
-	 * @deprecated Use annotation based ACLs from the AppFramework instead
89
-	 * @suppress PhanDeprecatedFunction
90
-	 */
91
-	public static function checkAdminUser() {
92
-		if(!OC_User::isAdminUser(OC_User::getUser())) {
93
-			$l = \OC::$server->getL10N('lib');
94
-			self::error([ 'data' => [ 'message' => $l->t('Authentication error'), 'error' => 'authentication_error' ]]);
95
-			exit();
96
-		}
97
-	}
86
+    /**
87
+     * Check if the user is a admin, send json error msg if not.
88
+     * @deprecated Use annotation based ACLs from the AppFramework instead
89
+     * @suppress PhanDeprecatedFunction
90
+     */
91
+    public static function checkAdminUser() {
92
+        if(!OC_User::isAdminUser(OC_User::getUser())) {
93
+            $l = \OC::$server->getL10N('lib');
94
+            self::error([ 'data' => [ 'message' => $l->t('Authentication error'), 'error' => 'authentication_error' ]]);
95
+            exit();
96
+        }
97
+    }
98 98
 
99
-	/**
100
-	 * Send json error msg
101
-	 * @deprecated Use a AppFramework JSONResponse instead
102
-	 * @suppress PhanDeprecatedFunction
103
-	 */
104
-	public static function error($data = []) {
105
-		$data['status'] = 'error';
106
-		header('Content-Type: application/json; charset=utf-8');
107
-		echo self::encode($data);
108
-	}
99
+    /**
100
+     * Send json error msg
101
+     * @deprecated Use a AppFramework JSONResponse instead
102
+     * @suppress PhanDeprecatedFunction
103
+     */
104
+    public static function error($data = []) {
105
+        $data['status'] = 'error';
106
+        header('Content-Type: application/json; charset=utf-8');
107
+        echo self::encode($data);
108
+    }
109 109
 
110
-	/**
111
-	 * Send json success msg
112
-	 * @deprecated Use a AppFramework JSONResponse instead
113
-	 * @suppress PhanDeprecatedFunction
114
-	 */
115
-	public static function success($data = []) {
116
-		$data['status'] = 'success';
117
-		header('Content-Type: application/json; charset=utf-8');
118
-		echo self::encode($data);
119
-	}
110
+    /**
111
+     * Send json success msg
112
+     * @deprecated Use a AppFramework JSONResponse instead
113
+     * @suppress PhanDeprecatedFunction
114
+     */
115
+    public static function success($data = []) {
116
+        $data['status'] = 'success';
117
+        header('Content-Type: application/json; charset=utf-8');
118
+        echo self::encode($data);
119
+    }
120 120
 
121
-	/**
122
-	 * Convert OC_L10N_String to string, for use in json encodings
123
-	 */
124
-	protected static function to_string(&$value) {
125
-		if ($value instanceof \OC\L10N\L10NString) {
126
-			$value = (string)$value;
127
-		}
128
-	}
121
+    /**
122
+     * Convert OC_L10N_String to string, for use in json encodings
123
+     */
124
+    protected static function to_string(&$value) {
125
+        if ($value instanceof \OC\L10N\L10NString) {
126
+            $value = (string)$value;
127
+        }
128
+    }
129 129
 
130
-	/**
131
-	 * Encode JSON
132
-	 * @deprecated Use a AppFramework JSONResponse instead
133
-	 */
134
-	public static function encode($data) {
135
-		if (is_array($data)) {
136
-			array_walk_recursive($data, ['OC_JSON', 'to_string']);
137
-		}
138
-		return json_encode($data, JSON_HEX_TAG);
139
-	}
130
+    /**
131
+     * Encode JSON
132
+     * @deprecated Use a AppFramework JSONResponse instead
133
+     */
134
+    public static function encode($data) {
135
+        if (is_array($data)) {
136
+            array_walk_recursive($data, ['OC_JSON', 'to_string']);
137
+        }
138
+        return json_encode($data, JSON_HEX_TAG);
139
+    }
140 140
 }
Please login to merge, or discard this patch.
Spacing   +11 added lines, -11 removed lines patch added patch discarded remove patch
@@ -33,7 +33,7 @@  discard block
 block discarded – undo
33 33
  * Class OC_JSON
34 34
  * @deprecated Use a AppFramework JSONResponse instead
35 35
  */
36
-class OC_JSON{
36
+class OC_JSON {
37 37
 
38 38
 	/**
39 39
 	 * Check if the app is enabled, send json error msg if not
@@ -42,9 +42,9 @@  discard block
 block discarded – undo
42 42
 	 * @suppress PhanDeprecatedFunction
43 43
 	 */
44 44
 	public static function checkAppEnabled($app) {
45
-		if(!\OC::$server->getAppManager()->isEnabledForUser($app)) {
45
+		if (!\OC::$server->getAppManager()->isEnabledForUser($app)) {
46 46
 			$l = \OC::$server->getL10N('lib');
47
-			self::error([ 'data' => [ 'message' => $l->t('Application is not enabled'), 'error' => 'application_not_enabled' ]]);
47
+			self::error(['data' => ['message' => $l->t('Application is not enabled'), 'error' => 'application_not_enabled']]);
48 48
 			exit();
49 49
 		}
50 50
 	}
@@ -56,11 +56,11 @@  discard block
 block discarded – undo
56 56
 	 */
57 57
 	public static function checkLoggedIn() {
58 58
 		$twoFactorAuthManger = \OC::$server->getTwoFactorAuthManager();
59
-		if(!\OC::$server->getUserSession()->isLoggedIn()
59
+		if (!\OC::$server->getUserSession()->isLoggedIn()
60 60
 			|| $twoFactorAuthManger->needsSecondFactor(\OC::$server->getUserSession()->getUser())) {
61 61
 			$l = \OC::$server->getL10N('lib');
62 62
 			http_response_code(\OCP\AppFramework\Http::STATUS_UNAUTHORIZED);
63
-			self::error([ 'data' => [ 'message' => $l->t('Authentication error'), 'error' => 'authentication_error' ]]);
63
+			self::error(['data' => ['message' => $l->t('Authentication error'), 'error' => 'authentication_error']]);
64 64
 			exit();
65 65
 		}
66 66
 	}
@@ -71,14 +71,14 @@  discard block
 block discarded – undo
71 71
 	 * @suppress PhanDeprecatedFunction
72 72
 	 */
73 73
 	public static function callCheck() {
74
-		if(!\OC::$server->getRequest()->passesStrictCookieCheck()) {
74
+		if (!\OC::$server->getRequest()->passesStrictCookieCheck()) {
75 75
 			header('Location: '.\OC::$WEBROOT);
76 76
 			exit();
77 77
 		}
78 78
 
79
-		if(!\OC::$server->getRequest()->passesCSRFCheck()) {
79
+		if (!\OC::$server->getRequest()->passesCSRFCheck()) {
80 80
 			$l = \OC::$server->getL10N('lib');
81
-			self::error([ 'data' => [ 'message' => $l->t('Token expired. Please reload page.'), 'error' => 'token_expired' ]]);
81
+			self::error(['data' => ['message' => $l->t('Token expired. Please reload page.'), 'error' => 'token_expired']]);
82 82
 			exit();
83 83
 		}
84 84
 	}
@@ -89,9 +89,9 @@  discard block
 block discarded – undo
89 89
 	 * @suppress PhanDeprecatedFunction
90 90
 	 */
91 91
 	public static function checkAdminUser() {
92
-		if(!OC_User::isAdminUser(OC_User::getUser())) {
92
+		if (!OC_User::isAdminUser(OC_User::getUser())) {
93 93
 			$l = \OC::$server->getL10N('lib');
94
-			self::error([ 'data' => [ 'message' => $l->t('Authentication error'), 'error' => 'authentication_error' ]]);
94
+			self::error(['data' => ['message' => $l->t('Authentication error'), 'error' => 'authentication_error']]);
95 95
 			exit();
96 96
 		}
97 97
 	}
@@ -123,7 +123,7 @@  discard block
 block discarded – undo
123 123
 	 */
124 124
 	protected static function to_string(&$value) {
125 125
 		if ($value instanceof \OC\L10N\L10NString) {
126
-			$value = (string)$value;
126
+			$value = (string) $value;
127 127
 		}
128 128
 	}
129 129
 
Please login to merge, or discard this patch.
lib/private/legacy/OC_DB.php 2 patches
Indentation   +193 added lines, -193 removed lines patch added patch discarded remove patch
@@ -38,209 +38,209 @@
 block discarded – undo
38 38
  */
39 39
 class OC_DB {
40 40
 
41
-	/**
42
-	 * get MDB2 schema manager
43
-	 *
44
-	 * @return \OC\DB\MDB2SchemaManager
45
-	 */
46
-	private static function getMDB2SchemaManager() {
47
-		return new \OC\DB\MDB2SchemaManager(\OC::$server->getDatabaseConnection());
48
-	}
41
+    /**
42
+     * get MDB2 schema manager
43
+     *
44
+     * @return \OC\DB\MDB2SchemaManager
45
+     */
46
+    private static function getMDB2SchemaManager() {
47
+        return new \OC\DB\MDB2SchemaManager(\OC::$server->getDatabaseConnection());
48
+    }
49 49
 
50
-	/**
51
-	 * Prepare a SQL query
52
-	 * @param string $query Query string
53
-	 * @param int|null $limit
54
-	 * @param int|null $offset
55
-	 * @param bool|null $isManipulation
56
-	 * @throws \OC\DatabaseException
57
-	 * @return OC_DB_StatementWrapper prepared SQL query
58
-	 *
59
-	 * SQL query via Doctrine prepare(), needs to be execute()'d!
60
-	 */
61
-	static public function prepare($query , $limit = null, $offset = null, $isManipulation = null) {
62
-		$connection = \OC::$server->getDatabaseConnection();
50
+    /**
51
+     * Prepare a SQL query
52
+     * @param string $query Query string
53
+     * @param int|null $limit
54
+     * @param int|null $offset
55
+     * @param bool|null $isManipulation
56
+     * @throws \OC\DatabaseException
57
+     * @return OC_DB_StatementWrapper prepared SQL query
58
+     *
59
+     * SQL query via Doctrine prepare(), needs to be execute()'d!
60
+     */
61
+    static public function prepare($query , $limit = null, $offset = null, $isManipulation = null) {
62
+        $connection = \OC::$server->getDatabaseConnection();
63 63
 
64
-		if ($isManipulation === null) {
65
-			//try to guess, so we return the number of rows on manipulations
66
-			$isManipulation = self::isManipulation($query);
67
-		}
64
+        if ($isManipulation === null) {
65
+            //try to guess, so we return the number of rows on manipulations
66
+            $isManipulation = self::isManipulation($query);
67
+        }
68 68
 
69
-		// return the result
70
-		try {
71
-			$result =$connection->prepare($query, $limit, $offset);
72
-		} catch (\Doctrine\DBAL\DBALException $e) {
73
-			throw new \OC\DatabaseException($e->getMessage());
74
-		}
75
-		// differentiate between query and manipulation
76
-		$result = new OC_DB_StatementWrapper($result, $isManipulation);
77
-		return $result;
78
-	}
69
+        // return the result
70
+        try {
71
+            $result =$connection->prepare($query, $limit, $offset);
72
+        } catch (\Doctrine\DBAL\DBALException $e) {
73
+            throw new \OC\DatabaseException($e->getMessage());
74
+        }
75
+        // differentiate between query and manipulation
76
+        $result = new OC_DB_StatementWrapper($result, $isManipulation);
77
+        return $result;
78
+    }
79 79
 
80
-	/**
81
-	 * tries to guess the type of statement based on the first 10 characters
82
-	 * the current check allows some whitespace but does not work with IF EXISTS or other more complex statements
83
-	 *
84
-	 * @param string $sql
85
-	 * @return bool
86
-	 */
87
-	static public function isManipulation($sql) {
88
-		$selectOccurrence = stripos($sql, 'SELECT');
89
-		if ($selectOccurrence !== false && $selectOccurrence < 10) {
90
-			return false;
91
-		}
92
-		$insertOccurrence = stripos($sql, 'INSERT');
93
-		if ($insertOccurrence !== false && $insertOccurrence < 10) {
94
-			return true;
95
-		}
96
-		$updateOccurrence = stripos($sql, 'UPDATE');
97
-		if ($updateOccurrence !== false && $updateOccurrence < 10) {
98
-			return true;
99
-		}
100
-		$deleteOccurrence = stripos($sql, 'DELETE');
101
-		if ($deleteOccurrence !== false && $deleteOccurrence < 10) {
102
-			return true;
103
-		}
104
-		return false;
105
-	}
80
+    /**
81
+     * tries to guess the type of statement based on the first 10 characters
82
+     * the current check allows some whitespace but does not work with IF EXISTS or other more complex statements
83
+     *
84
+     * @param string $sql
85
+     * @return bool
86
+     */
87
+    static public function isManipulation($sql) {
88
+        $selectOccurrence = stripos($sql, 'SELECT');
89
+        if ($selectOccurrence !== false && $selectOccurrence < 10) {
90
+            return false;
91
+        }
92
+        $insertOccurrence = stripos($sql, 'INSERT');
93
+        if ($insertOccurrence !== false && $insertOccurrence < 10) {
94
+            return true;
95
+        }
96
+        $updateOccurrence = stripos($sql, 'UPDATE');
97
+        if ($updateOccurrence !== false && $updateOccurrence < 10) {
98
+            return true;
99
+        }
100
+        $deleteOccurrence = stripos($sql, 'DELETE');
101
+        if ($deleteOccurrence !== false && $deleteOccurrence < 10) {
102
+            return true;
103
+        }
104
+        return false;
105
+    }
106 106
 
107
-	/**
108
-	 * execute a prepared statement, on error write log and throw exception
109
-	 * @param mixed $stmt OC_DB_StatementWrapper,
110
-	 *					  an array with 'sql' and optionally 'limit' and 'offset' keys
111
-	 *					.. or a simple sql query string
112
-	 * @param array $parameters
113
-	 * @return OC_DB_StatementWrapper
114
-	 * @throws \OC\DatabaseException
115
-	 */
116
-	static public function executeAudited($stmt, array $parameters = []) {
117
-		if (is_string($stmt)) {
118
-			// convert to an array with 'sql'
119
-			if (stripos($stmt, 'LIMIT') !== false) { //OFFSET requires LIMIT, so we only need to check for LIMIT
120
-				// TODO try to convert LIMIT OFFSET notation to parameters
121
-				$message = 'LIMIT and OFFSET are forbidden for portability reasons,'
122
-						 . ' pass an array with \'limit\' and \'offset\' instead';
123
-				throw new \OC\DatabaseException($message);
124
-			}
125
-			$stmt = ['sql' => $stmt, 'limit' => null, 'offset' => null];
126
-		}
127
-		if (is_array($stmt)) {
128
-			// convert to prepared statement
129
-			if (! array_key_exists('sql', $stmt)) {
130
-				$message = 'statement array must at least contain key \'sql\'';
131
-				throw new \OC\DatabaseException($message);
132
-			}
133
-			if (! array_key_exists('limit', $stmt)) {
134
-				$stmt['limit'] = null;
135
-			}
136
-			if (! array_key_exists('limit', $stmt)) {
137
-				$stmt['offset'] = null;
138
-			}
139
-			$stmt = self::prepare($stmt['sql'], $stmt['limit'], $stmt['offset']);
140
-		}
141
-		self::raiseExceptionOnError($stmt, 'Could not prepare statement');
142
-		if ($stmt instanceof OC_DB_StatementWrapper) {
143
-			$result = $stmt->execute($parameters);
144
-			self::raiseExceptionOnError($result, 'Could not execute statement');
145
-		} else {
146
-			if (is_object($stmt)) {
147
-				$message = 'Expected a prepared statement or array got ' . get_class($stmt);
148
-			} else {
149
-				$message = 'Expected a prepared statement or array got ' . gettype($stmt);
150
-			}
151
-			throw new \OC\DatabaseException($message);
152
-		}
153
-		return $result;
154
-	}
107
+    /**
108
+     * execute a prepared statement, on error write log and throw exception
109
+     * @param mixed $stmt OC_DB_StatementWrapper,
110
+     *					  an array with 'sql' and optionally 'limit' and 'offset' keys
111
+     *					.. or a simple sql query string
112
+     * @param array $parameters
113
+     * @return OC_DB_StatementWrapper
114
+     * @throws \OC\DatabaseException
115
+     */
116
+    static public function executeAudited($stmt, array $parameters = []) {
117
+        if (is_string($stmt)) {
118
+            // convert to an array with 'sql'
119
+            if (stripos($stmt, 'LIMIT') !== false) { //OFFSET requires LIMIT, so we only need to check for LIMIT
120
+                // TODO try to convert LIMIT OFFSET notation to parameters
121
+                $message = 'LIMIT and OFFSET are forbidden for portability reasons,'
122
+                            . ' pass an array with \'limit\' and \'offset\' instead';
123
+                throw new \OC\DatabaseException($message);
124
+            }
125
+            $stmt = ['sql' => $stmt, 'limit' => null, 'offset' => null];
126
+        }
127
+        if (is_array($stmt)) {
128
+            // convert to prepared statement
129
+            if (! array_key_exists('sql', $stmt)) {
130
+                $message = 'statement array must at least contain key \'sql\'';
131
+                throw new \OC\DatabaseException($message);
132
+            }
133
+            if (! array_key_exists('limit', $stmt)) {
134
+                $stmt['limit'] = null;
135
+            }
136
+            if (! array_key_exists('limit', $stmt)) {
137
+                $stmt['offset'] = null;
138
+            }
139
+            $stmt = self::prepare($stmt['sql'], $stmt['limit'], $stmt['offset']);
140
+        }
141
+        self::raiseExceptionOnError($stmt, 'Could not prepare statement');
142
+        if ($stmt instanceof OC_DB_StatementWrapper) {
143
+            $result = $stmt->execute($parameters);
144
+            self::raiseExceptionOnError($result, 'Could not execute statement');
145
+        } else {
146
+            if (is_object($stmt)) {
147
+                $message = 'Expected a prepared statement or array got ' . get_class($stmt);
148
+            } else {
149
+                $message = 'Expected a prepared statement or array got ' . gettype($stmt);
150
+            }
151
+            throw new \OC\DatabaseException($message);
152
+        }
153
+        return $result;
154
+    }
155 155
 
156
-	/**
157
-	 * saves database schema to xml file
158
-	 * @param string $file name of file
159
-	 * @return bool
160
-	 *
161
-	 * TODO: write more documentation
162
-	 */
163
-	public static function getDbStructure($file) {
164
-		$schemaManager = self::getMDB2SchemaManager();
165
-		return $schemaManager->getDbStructure($file);
166
-	}
156
+    /**
157
+     * saves database schema to xml file
158
+     * @param string $file name of file
159
+     * @return bool
160
+     *
161
+     * TODO: write more documentation
162
+     */
163
+    public static function getDbStructure($file) {
164
+        $schemaManager = self::getMDB2SchemaManager();
165
+        return $schemaManager->getDbStructure($file);
166
+    }
167 167
 
168
-	/**
169
-	 * Creates tables from XML file
170
-	 * @param string $file file to read structure from
171
-	 * @return bool
172
-	 *
173
-	 * TODO: write more documentation
174
-	 */
175
-	public static function createDbFromStructure($file) {
176
-		$schemaManager = self::getMDB2SchemaManager();
177
-		return $schemaManager->createDbFromStructure($file);
178
-	}
168
+    /**
169
+     * Creates tables from XML file
170
+     * @param string $file file to read structure from
171
+     * @return bool
172
+     *
173
+     * TODO: write more documentation
174
+     */
175
+    public static function createDbFromStructure($file) {
176
+        $schemaManager = self::getMDB2SchemaManager();
177
+        return $schemaManager->createDbFromStructure($file);
178
+    }
179 179
 
180
-	/**
181
-	 * update the database schema
182
-	 * @param string $file file to read structure from
183
-	 * @throws Exception
184
-	 * @return string|boolean
185
-	 * @suppress PhanDeprecatedFunction
186
-	 */
187
-	public static function updateDbFromStructure($file) {
188
-		$schemaManager = self::getMDB2SchemaManager();
189
-		try {
190
-			$result = $schemaManager->updateDbFromStructure($file);
191
-		} catch (Exception $e) {
192
-			\OCP\Util::writeLog('core', 'Failed to update database structure ('.$e.')', ILogger::FATAL);
193
-			throw $e;
194
-		}
195
-		return $result;
196
-	}
180
+    /**
181
+     * update the database schema
182
+     * @param string $file file to read structure from
183
+     * @throws Exception
184
+     * @return string|boolean
185
+     * @suppress PhanDeprecatedFunction
186
+     */
187
+    public static function updateDbFromStructure($file) {
188
+        $schemaManager = self::getMDB2SchemaManager();
189
+        try {
190
+            $result = $schemaManager->updateDbFromStructure($file);
191
+        } catch (Exception $e) {
192
+            \OCP\Util::writeLog('core', 'Failed to update database structure ('.$e.')', ILogger::FATAL);
193
+            throw $e;
194
+        }
195
+        return $result;
196
+    }
197 197
 
198
-	/**
199
-	 * remove all tables defined in a database structure xml file
200
-	 * @param string $file the xml file describing the tables
201
-	 */
202
-	public static function removeDBStructure($file) {
203
-		$schemaManager = self::getMDB2SchemaManager();
204
-		$schemaManager->removeDBStructure($file);
205
-	}
198
+    /**
199
+     * remove all tables defined in a database structure xml file
200
+     * @param string $file the xml file describing the tables
201
+     */
202
+    public static function removeDBStructure($file) {
203
+        $schemaManager = self::getMDB2SchemaManager();
204
+        $schemaManager->removeDBStructure($file);
205
+    }
206 206
 
207
-	/**
208
-	 * check if a result is an error and throws an exception, works with \Doctrine\DBAL\DBALException
209
-	 * @param mixed $result
210
-	 * @param string $message
211
-	 * @return void
212
-	 * @throws \OC\DatabaseException
213
-	 */
214
-	public static function raiseExceptionOnError($result, $message = null) {
215
-		if($result === false) {
216
-			if ($message === null) {
217
-				$message = self::getErrorMessage();
218
-			} else {
219
-				$message .= ', Root cause:' . self::getErrorMessage();
220
-			}
221
-			throw new \OC\DatabaseException($message);
222
-		}
223
-	}
207
+    /**
208
+     * check if a result is an error and throws an exception, works with \Doctrine\DBAL\DBALException
209
+     * @param mixed $result
210
+     * @param string $message
211
+     * @return void
212
+     * @throws \OC\DatabaseException
213
+     */
214
+    public static function raiseExceptionOnError($result, $message = null) {
215
+        if($result === false) {
216
+            if ($message === null) {
217
+                $message = self::getErrorMessage();
218
+            } else {
219
+                $message .= ', Root cause:' . self::getErrorMessage();
220
+            }
221
+            throw new \OC\DatabaseException($message);
222
+        }
223
+    }
224 224
 
225
-	/**
226
-	 * returns the error code and message as a string for logging
227
-	 * works with DoctrineException
228
-	 * @return string
229
-	 */
230
-	public static function getErrorMessage() {
231
-		$connection = \OC::$server->getDatabaseConnection();
232
-		return $connection->getError();
233
-	}
225
+    /**
226
+     * returns the error code and message as a string for logging
227
+     * works with DoctrineException
228
+     * @return string
229
+     */
230
+    public static function getErrorMessage() {
231
+        $connection = \OC::$server->getDatabaseConnection();
232
+        return $connection->getError();
233
+    }
234 234
 
235
-	/**
236
-	 * Checks if a table exists in the database - the database prefix will be prepended
237
-	 *
238
-	 * @param string $table
239
-	 * @return bool
240
-	 * @throws \OC\DatabaseException
241
-	 */
242
-	public static function tableExists($table) {
243
-		$connection = \OC::$server->getDatabaseConnection();
244
-		return $connection->tableExists($table);
245
-	}
235
+    /**
236
+     * Checks if a table exists in the database - the database prefix will be prepended
237
+     *
238
+     * @param string $table
239
+     * @return bool
240
+     * @throws \OC\DatabaseException
241
+     */
242
+    public static function tableExists($table) {
243
+        $connection = \OC::$server->getDatabaseConnection();
244
+        return $connection->tableExists($table);
245
+    }
246 246
 }
Please login to merge, or discard this patch.
Spacing   +9 added lines, -9 removed lines patch added patch discarded remove patch
@@ -58,7 +58,7 @@  discard block
 block discarded – undo
58 58
 	 *
59 59
 	 * SQL query via Doctrine prepare(), needs to be execute()'d!
60 60
 	 */
61
-	static public function prepare($query , $limit = null, $offset = null, $isManipulation = null) {
61
+	static public function prepare($query, $limit = null, $offset = null, $isManipulation = null) {
62 62
 		$connection = \OC::$server->getDatabaseConnection();
63 63
 
64 64
 		if ($isManipulation === null) {
@@ -68,7 +68,7 @@  discard block
 block discarded – undo
68 68
 
69 69
 		// return the result
70 70
 		try {
71
-			$result =$connection->prepare($query, $limit, $offset);
71
+			$result = $connection->prepare($query, $limit, $offset);
72 72
 		} catch (\Doctrine\DBAL\DBALException $e) {
73 73
 			throw new \OC\DatabaseException($e->getMessage());
74 74
 		}
@@ -126,14 +126,14 @@  discard block
 block discarded – undo
126 126
 		}
127 127
 		if (is_array($stmt)) {
128 128
 			// convert to prepared statement
129
-			if (! array_key_exists('sql', $stmt)) {
129
+			if (!array_key_exists('sql', $stmt)) {
130 130
 				$message = 'statement array must at least contain key \'sql\'';
131 131
 				throw new \OC\DatabaseException($message);
132 132
 			}
133
-			if (! array_key_exists('limit', $stmt)) {
133
+			if (!array_key_exists('limit', $stmt)) {
134 134
 				$stmt['limit'] = null;
135 135
 			}
136
-			if (! array_key_exists('limit', $stmt)) {
136
+			if (!array_key_exists('limit', $stmt)) {
137 137
 				$stmt['offset'] = null;
138 138
 			}
139 139
 			$stmt = self::prepare($stmt['sql'], $stmt['limit'], $stmt['offset']);
@@ -144,9 +144,9 @@  discard block
 block discarded – undo
144 144
 			self::raiseExceptionOnError($result, 'Could not execute statement');
145 145
 		} else {
146 146
 			if (is_object($stmt)) {
147
-				$message = 'Expected a prepared statement or array got ' . get_class($stmt);
147
+				$message = 'Expected a prepared statement or array got '.get_class($stmt);
148 148
 			} else {
149
-				$message = 'Expected a prepared statement or array got ' . gettype($stmt);
149
+				$message = 'Expected a prepared statement or array got '.gettype($stmt);
150 150
 			}
151 151
 			throw new \OC\DatabaseException($message);
152 152
 		}
@@ -212,11 +212,11 @@  discard block
 block discarded – undo
212 212
 	 * @throws \OC\DatabaseException
213 213
 	 */
214 214
 	public static function raiseExceptionOnError($result, $message = null) {
215
-		if($result === false) {
215
+		if ($result === false) {
216 216
 			if ($message === null) {
217 217
 				$message = self::getErrorMessage();
218 218
 			} else {
219
-				$message .= ', Root cause:' . self::getErrorMessage();
219
+				$message .= ', Root cause:'.self::getErrorMessage();
220 220
 			}
221 221
 			throw new \OC\DatabaseException($message);
222 222
 		}
Please login to merge, or discard this patch.
lib/private/legacy/template/functions.php 2 patches
Indentation   +115 added lines, -115 removed lines patch added patch discarded remove patch
@@ -37,7 +37,7 @@  discard block
 block discarded – undo
37 37
  * @param string $string the string which will be escaped and printed
38 38
  */
39 39
 function p($string) {
40
-	print(\OCP\Util::sanitizeHTML($string));
40
+    print(\OCP\Util::sanitizeHTML($string));
41 41
 }
42 42
 
43 43
 
@@ -47,14 +47,14 @@  discard block
 block discarded – undo
47 47
  * @param string $opts, additional optional options
48 48
  */
49 49
 function emit_css_tag($href, $opts = '') {
50
-	$s='<link rel="stylesheet"';
51
-	if (!empty($href)) {
52
-		$s.=' href="' . $href .'"';
53
-	}
54
-	if (!empty($opts)) {
55
-		$s.=' '.$opts;
56
-	}
57
-	print_unescaped($s.">\n");
50
+    $s='<link rel="stylesheet"';
51
+    if (!empty($href)) {
52
+        $s.=' href="' . $href .'"';
53
+    }
54
+    if (!empty($opts)) {
55
+        $s.=' '.$opts;
56
+    }
57
+    print_unescaped($s.">\n");
58 58
 }
59 59
 
60 60
 /**
@@ -62,12 +62,12 @@  discard block
 block discarded – undo
62 62
  * @param array $obj all the script information from template
63 63
  */
64 64
 function emit_css_loading_tags($obj) {
65
-	foreach($obj['cssfiles'] as $css) {
66
-		emit_css_tag($css);
67
-	}
68
-	foreach($obj['printcssfiles'] as $css) {
69
-		emit_css_tag($css, 'media="print"');
70
-	}
65
+    foreach($obj['cssfiles'] as $css) {
66
+        emit_css_tag($css);
67
+    }
68
+    foreach($obj['printcssfiles'] as $css) {
69
+        emit_css_tag($css, 'media="print"');
70
+    }
71 71
 }
72 72
 
73 73
 /**
@@ -76,20 +76,20 @@  discard block
 block discarded – undo
76 76
  * @param string $script_content the inline script content, ignored when empty
77 77
  */
78 78
 function emit_script_tag($src, $script_content='') {
79
-	$defer_str=' defer';
80
-	$s='<script nonce="' . \OC::$server->getContentSecurityPolicyNonceManager()->getNonce() . '"';
81
-	if (!empty($src)) {
82
-		 // emit script tag for deferred loading from $src
83
-		$s.=$defer_str.' src="' . $src .'">';
84
-	} else if (!empty($script_content)) {
85
-		// emit script tag for inline script from $script_content without defer (see MDN)
86
-		$s.=">\n".$script_content."\n";
87
-	} else {
88
-		// no $src nor $src_content, really useless empty tag
89
-		$s.='>';
90
-	}
91
-	$s.='</script>';
92
-	print_unescaped($s."\n");
79
+    $defer_str=' defer';
80
+    $s='<script nonce="' . \OC::$server->getContentSecurityPolicyNonceManager()->getNonce() . '"';
81
+    if (!empty($src)) {
82
+            // emit script tag for deferred loading from $src
83
+        $s.=$defer_str.' src="' . $src .'">';
84
+    } else if (!empty($script_content)) {
85
+        // emit script tag for inline script from $script_content without defer (see MDN)
86
+        $s.=">\n".$script_content."\n";
87
+    } else {
88
+        // no $src nor $src_content, really useless empty tag
89
+        $s.='>';
90
+    }
91
+    $s.='</script>';
92
+    print_unescaped($s."\n");
93 93
 }
94 94
 
95 95
 /**
@@ -97,12 +97,12 @@  discard block
 block discarded – undo
97 97
  * @param array $obj all the script information from template
98 98
  */
99 99
 function emit_script_loading_tags($obj) {
100
-	foreach($obj['jsfiles'] as $jsfile) {
101
-		emit_script_tag($jsfile, '');
102
-	}
103
-	if (!empty($obj['inline_ocjs'])) {
104
-		emit_script_tag('', $obj['inline_ocjs']);
105
-	}
100
+    foreach($obj['jsfiles'] as $jsfile) {
101
+        emit_script_tag($jsfile, '');
102
+    }
103
+    if (!empty($obj['inline_ocjs'])) {
104
+        emit_script_tag('', $obj['inline_ocjs']);
105
+    }
106 106
 }
107 107
 
108 108
 /**
@@ -111,7 +111,7 @@  discard block
 block discarded – undo
111 111
  * @param string|array $string the string which will be printed as it is
112 112
  */
113 113
 function print_unescaped($string) {
114
-	print($string);
114
+    print($string);
115 115
 }
116 116
 
117 117
 /**
@@ -121,13 +121,13 @@  discard block
 block discarded – undo
121 121
  * if an array is given it will add all scripts
122 122
  */
123 123
 function script($app, $file = null) {
124
-	if(is_array($file)) {
125
-		foreach($file as $f) {
126
-			OC_Util::addScript($app, $f);
127
-		}
128
-	} else {
129
-		OC_Util::addScript($app, $file);
130
-	}
124
+    if(is_array($file)) {
125
+        foreach($file as $f) {
126
+            OC_Util::addScript($app, $f);
127
+        }
128
+    } else {
129
+        OC_Util::addScript($app, $file);
130
+    }
131 131
 }
132 132
 
133 133
 /**
@@ -137,13 +137,13 @@  discard block
 block discarded – undo
137 137
  * if an array is given it will add all scripts
138 138
  */
139 139
 function vendor_script($app, $file = null) {
140
-	if(is_array($file)) {
141
-		foreach($file as $f) {
142
-			OC_Util::addVendorScript($app, $f);
143
-		}
144
-	} else {
145
-		OC_Util::addVendorScript($app, $file);
146
-	}
140
+    if(is_array($file)) {
141
+        foreach($file as $f) {
142
+            OC_Util::addVendorScript($app, $f);
143
+        }
144
+    } else {
145
+        OC_Util::addVendorScript($app, $file);
146
+    }
147 147
 }
148 148
 
149 149
 /**
@@ -153,13 +153,13 @@  discard block
 block discarded – undo
153 153
  * if an array is given it will add all styles
154 154
  */
155 155
 function style($app, $file = null) {
156
-	if(is_array($file)) {
157
-		foreach($file as $f) {
158
-			OC_Util::addStyle($app, $f);
159
-		}
160
-	} else {
161
-		OC_Util::addStyle($app, $file);
162
-	}
156
+    if(is_array($file)) {
157
+        foreach($file as $f) {
158
+            OC_Util::addStyle($app, $f);
159
+        }
160
+    } else {
161
+        OC_Util::addStyle($app, $file);
162
+    }
163 163
 }
164 164
 
165 165
 /**
@@ -169,13 +169,13 @@  discard block
 block discarded – undo
169 169
  * if an array is given it will add all styles
170 170
  */
171 171
 function vendor_style($app, $file = null) {
172
-	if(is_array($file)) {
173
-		foreach($file as $f) {
174
-			OC_Util::addVendorStyle($app, $f);
175
-		}
176
-	} else {
177
-		OC_Util::addVendorStyle($app, $file);
178
-	}
172
+    if(is_array($file)) {
173
+        foreach($file as $f) {
174
+            OC_Util::addVendorStyle($app, $f);
175
+        }
176
+    } else {
177
+        OC_Util::addVendorStyle($app, $file);
178
+    }
179 179
 }
180 180
 
181 181
 /**
@@ -184,7 +184,7 @@  discard block
 block discarded – undo
184 184
  * if an array is given it will add all styles
185 185
  */
186 186
 function translation($app) {
187
-	OC_Util::addTranslations($app);
187
+    OC_Util::addTranslations($app);
188 188
 }
189 189
 
190 190
 /**
@@ -194,15 +194,15 @@  discard block
 block discarded – undo
194 194
  * if an array is given it will add all components
195 195
  */
196 196
 function component($app, $file) {
197
-	if(is_array($file)) {
198
-		foreach($file as $f) {
199
-			$url = link_to($app, 'component/' . $f . '.html');
200
-			OC_Util::addHeader('link', ['rel' => 'import', 'href' => $url]);
201
-		}
202
-	} else {
203
-		$url = link_to($app, 'component/' . $file . '.html');
204
-		OC_Util::addHeader('link', ['rel' => 'import', 'href' => $url]);
205
-	}
197
+    if(is_array($file)) {
198
+        foreach($file as $f) {
199
+            $url = link_to($app, 'component/' . $f . '.html');
200
+            OC_Util::addHeader('link', ['rel' => 'import', 'href' => $url]);
201
+        }
202
+    } else {
203
+        $url = link_to($app, 'component/' . $file . '.html');
204
+        OC_Util::addHeader('link', ['rel' => 'import', 'href' => $url]);
205
+    }
206 206
 }
207 207
 
208 208
 /**
@@ -215,7 +215,7 @@  discard block
 block discarded – undo
215 215
  * For further information have a look at \OCP\IURLGenerator::linkTo
216 216
  */
217 217
 function link_to($app, $file, $args = []) {
218
-	return \OC::$server->getURLGenerator()->linkTo($app, $file, $args);
218
+    return \OC::$server->getURLGenerator()->linkTo($app, $file, $args);
219 219
 }
220 220
 
221 221
 /**
@@ -223,7 +223,7 @@  discard block
 block discarded – undo
223 223
  * @return string url to the online documentation
224 224
  */
225 225
 function link_to_docs($key) {
226
-	return \OC::$server->getURLGenerator()->linkToDocs($key);
226
+    return \OC::$server->getURLGenerator()->linkToDocs($key);
227 227
 }
228 228
 
229 229
 /**
@@ -235,7 +235,7 @@  discard block
 block discarded – undo
235 235
  * For further information have a look at \OCP\IURLGenerator::imagePath
236 236
  */
237 237
 function image_path($app, $image) {
238
-	return \OC::$server->getURLGenerator()->imagePath($app, $image);
238
+    return \OC::$server->getURLGenerator()->imagePath($app, $image);
239 239
 }
240 240
 
241 241
 /**
@@ -244,7 +244,7 @@  discard block
 block discarded – undo
244 244
  * @return string link to the image
245 245
  */
246 246
 function mimetype_icon($mimetype) {
247
-	return \OC::$server->getMimeTypeDetector()->mimeTypeIcon($mimetype);
247
+    return \OC::$server->getMimeTypeDetector()->mimeTypeIcon($mimetype);
248 248
 }
249 249
 
250 250
 /**
@@ -254,7 +254,7 @@  discard block
 block discarded – undo
254 254
  * @return string link to the preview
255 255
  */
256 256
 function preview_icon($path) {
257
-	return \OC::$server->getURLGenerator()->linkToRoute('core.Preview.getPreview', ['x' => 32, 'y' => 32, 'file' => $path]);
257
+    return \OC::$server->getURLGenerator()->linkToRoute('core.Preview.getPreview', ['x' => 32, 'y' => 32, 'file' => $path]);
258 258
 }
259 259
 
260 260
 /**
@@ -263,7 +263,7 @@  discard block
 block discarded – undo
263 263
  * @return string
264 264
  */
265 265
 function publicPreview_icon($path, $token) {
266
-	return \OC::$server->getURLGenerator()->linkToRoute('files_sharing.PublicPreview.getPreview', ['x' => 32, 'y' => 32, 'file' => $path, 'token' => $token]);
266
+    return \OC::$server->getURLGenerator()->linkToRoute('files_sharing.PublicPreview.getPreview', ['x' => 32, 'y' => 32, 'file' => $path, 'token' => $token]);
267 267
 }
268 268
 
269 269
 /**
@@ -274,7 +274,7 @@  discard block
 block discarded – undo
274 274
  * For further information have a look at OC_Helper::humanFileSize
275 275
  */
276 276
 function human_file_size($bytes) {
277
-	return OC_Helper::humanFileSize($bytes);
277
+    return OC_Helper::humanFileSize($bytes);
278 278
 }
279 279
 
280 280
 /**
@@ -283,9 +283,9 @@  discard block
 block discarded – undo
283 283
  * @return int timestamp without time value
284 284
  */
285 285
 function strip_time($timestamp) {
286
-	$date = new \DateTime("@{$timestamp}");
287
-	$date->setTime(0, 0, 0);
288
-	return (int)$date->format('U');
286
+    $date = new \DateTime("@{$timestamp}");
287
+    $date->setTime(0, 0, 0);
288
+    return (int)$date->format('U');
289 289
 }
290 290
 
291 291
 /**
@@ -297,39 +297,39 @@  discard block
 block discarded – undo
297 297
  * @return string timestamp
298 298
  */
299 299
 function relative_modified_date($timestamp, $fromTime = null, $dateOnly = false) {
300
-	/** @var \OC\DateTimeFormatter $formatter */
301
-	$formatter = \OC::$server->query('DateTimeFormatter');
300
+    /** @var \OC\DateTimeFormatter $formatter */
301
+    $formatter = \OC::$server->query('DateTimeFormatter');
302 302
 
303
-	if ($dateOnly){
304
-		return $formatter->formatDateSpan($timestamp, $fromTime);
305
-	}
306
-	return $formatter->formatTimeSpan($timestamp, $fromTime);
303
+    if ($dateOnly){
304
+        return $formatter->formatDateSpan($timestamp, $fromTime);
305
+    }
306
+    return $formatter->formatTimeSpan($timestamp, $fromTime);
307 307
 }
308 308
 
309 309
 function html_select_options($options, $selected, $params=[]) {
310
-	if (!is_array($selected)) {
311
-		$selected=[$selected];
312
-	}
313
-	if (isset($params['combine']) && $params['combine']) {
314
-		$options = array_combine($options, $options);
315
-	}
316
-	$value_name = $label_name = false;
317
-	if (isset($params['value'])) {
318
-		$value_name = $params['value'];
319
-	}
320
-	if (isset($params['label'])) {
321
-		$label_name = $params['label'];
322
-	}
323
-	$html = '';
324
-	foreach($options as $value => $label) {
325
-		if ($value_name && is_array($label)) {
326
-			$value = $label[$value_name];
327
-		}
328
-		if ($label_name && is_array($label)) {
329
-			$label = $label[$label_name];
330
-		}
331
-		$select = in_array($value, $selected) ? ' selected="selected"' : '';
332
-		$html .= '<option value="' . \OCP\Util::sanitizeHTML($value) . '"' . $select . '>' . \OCP\Util::sanitizeHTML($label) . '</option>'."\n";
333
-	}
334
-	return $html;
310
+    if (!is_array($selected)) {
311
+        $selected=[$selected];
312
+    }
313
+    if (isset($params['combine']) && $params['combine']) {
314
+        $options = array_combine($options, $options);
315
+    }
316
+    $value_name = $label_name = false;
317
+    if (isset($params['value'])) {
318
+        $value_name = $params['value'];
319
+    }
320
+    if (isset($params['label'])) {
321
+        $label_name = $params['label'];
322
+    }
323
+    $html = '';
324
+    foreach($options as $value => $label) {
325
+        if ($value_name && is_array($label)) {
326
+            $value = $label[$value_name];
327
+        }
328
+        if ($label_name && is_array($label)) {
329
+            $label = $label[$label_name];
330
+        }
331
+        $select = in_array($value, $selected) ? ' selected="selected"' : '';
332
+        $html .= '<option value="' . \OCP\Util::sanitizeHTML($value) . '"' . $select . '>' . \OCP\Util::sanitizeHTML($label) . '</option>'."\n";
333
+    }
334
+    return $html;
335 335
 }
Please login to merge, or discard this patch.
Spacing   +31 added lines, -31 removed lines patch added patch discarded remove patch
@@ -47,12 +47,12 @@  discard block
 block discarded – undo
47 47
  * @param string $opts, additional optional options
48 48
  */
49 49
 function emit_css_tag($href, $opts = '') {
50
-	$s='<link rel="stylesheet"';
50
+	$s = '<link rel="stylesheet"';
51 51
 	if (!empty($href)) {
52
-		$s.=' href="' . $href .'"';
52
+		$s .= ' href="'.$href.'"';
53 53
 	}
54 54
 	if (!empty($opts)) {
55
-		$s.=' '.$opts;
55
+		$s .= ' '.$opts;
56 56
 	}
57 57
 	print_unescaped($s.">\n");
58 58
 }
@@ -62,10 +62,10 @@  discard block
 block discarded – undo
62 62
  * @param array $obj all the script information from template
63 63
  */
64 64
 function emit_css_loading_tags($obj) {
65
-	foreach($obj['cssfiles'] as $css) {
65
+	foreach ($obj['cssfiles'] as $css) {
66 66
 		emit_css_tag($css);
67 67
 	}
68
-	foreach($obj['printcssfiles'] as $css) {
68
+	foreach ($obj['printcssfiles'] as $css) {
69 69
 		emit_css_tag($css, 'media="print"');
70 70
 	}
71 71
 }
@@ -75,20 +75,20 @@  discard block
 block discarded – undo
75 75
  * @param string $src the source URL, ignored when empty
76 76
  * @param string $script_content the inline script content, ignored when empty
77 77
  */
78
-function emit_script_tag($src, $script_content='') {
79
-	$defer_str=' defer';
80
-	$s='<script nonce="' . \OC::$server->getContentSecurityPolicyNonceManager()->getNonce() . '"';
78
+function emit_script_tag($src, $script_content = '') {
79
+	$defer_str = ' defer';
80
+	$s = '<script nonce="'.\OC::$server->getContentSecurityPolicyNonceManager()->getNonce().'"';
81 81
 	if (!empty($src)) {
82 82
 		 // emit script tag for deferred loading from $src
83
-		$s.=$defer_str.' src="' . $src .'">';
83
+		$s .= $defer_str.' src="'.$src.'">';
84 84
 	} else if (!empty($script_content)) {
85 85
 		// emit script tag for inline script from $script_content without defer (see MDN)
86
-		$s.=">\n".$script_content."\n";
86
+		$s .= ">\n".$script_content."\n";
87 87
 	} else {
88 88
 		// no $src nor $src_content, really useless empty tag
89
-		$s.='>';
89
+		$s .= '>';
90 90
 	}
91
-	$s.='</script>';
91
+	$s .= '</script>';
92 92
 	print_unescaped($s."\n");
93 93
 }
94 94
 
@@ -97,7 +97,7 @@  discard block
 block discarded – undo
97 97
  * @param array $obj all the script information from template
98 98
  */
99 99
 function emit_script_loading_tags($obj) {
100
-	foreach($obj['jsfiles'] as $jsfile) {
100
+	foreach ($obj['jsfiles'] as $jsfile) {
101 101
 		emit_script_tag($jsfile, '');
102 102
 	}
103 103
 	if (!empty($obj['inline_ocjs'])) {
@@ -121,8 +121,8 @@  discard block
 block discarded – undo
121 121
  * if an array is given it will add all scripts
122 122
  */
123 123
 function script($app, $file = null) {
124
-	if(is_array($file)) {
125
-		foreach($file as $f) {
124
+	if (is_array($file)) {
125
+		foreach ($file as $f) {
126 126
 			OC_Util::addScript($app, $f);
127 127
 		}
128 128
 	} else {
@@ -137,8 +137,8 @@  discard block
 block discarded – undo
137 137
  * if an array is given it will add all scripts
138 138
  */
139 139
 function vendor_script($app, $file = null) {
140
-	if(is_array($file)) {
141
-		foreach($file as $f) {
140
+	if (is_array($file)) {
141
+		foreach ($file as $f) {
142 142
 			OC_Util::addVendorScript($app, $f);
143 143
 		}
144 144
 	} else {
@@ -153,8 +153,8 @@  discard block
 block discarded – undo
153 153
  * if an array is given it will add all styles
154 154
  */
155 155
 function style($app, $file = null) {
156
-	if(is_array($file)) {
157
-		foreach($file as $f) {
156
+	if (is_array($file)) {
157
+		foreach ($file as $f) {
158 158
 			OC_Util::addStyle($app, $f);
159 159
 		}
160 160
 	} else {
@@ -169,8 +169,8 @@  discard block
 block discarded – undo
169 169
  * if an array is given it will add all styles
170 170
  */
171 171
 function vendor_style($app, $file = null) {
172
-	if(is_array($file)) {
173
-		foreach($file as $f) {
172
+	if (is_array($file)) {
173
+		foreach ($file as $f) {
174 174
 			OC_Util::addVendorStyle($app, $f);
175 175
 		}
176 176
 	} else {
@@ -194,13 +194,13 @@  discard block
 block discarded – undo
194 194
  * if an array is given it will add all components
195 195
  */
196 196
 function component($app, $file) {
197
-	if(is_array($file)) {
198
-		foreach($file as $f) {
199
-			$url = link_to($app, 'component/' . $f . '.html');
197
+	if (is_array($file)) {
198
+		foreach ($file as $f) {
199
+			$url = link_to($app, 'component/'.$f.'.html');
200 200
 			OC_Util::addHeader('link', ['rel' => 'import', 'href' => $url]);
201 201
 		}
202 202
 	} else {
203
-		$url = link_to($app, 'component/' . $file . '.html');
203
+		$url = link_to($app, 'component/'.$file.'.html');
204 204
 		OC_Util::addHeader('link', ['rel' => 'import', 'href' => $url]);
205 205
 	}
206 206
 }
@@ -285,7 +285,7 @@  discard block
 block discarded – undo
285 285
 function strip_time($timestamp) {
286 286
 	$date = new \DateTime("@{$timestamp}");
287 287
 	$date->setTime(0, 0, 0);
288
-	return (int)$date->format('U');
288
+	return (int) $date->format('U');
289 289
 }
290 290
 
291 291
 /**
@@ -300,15 +300,15 @@  discard block
 block discarded – undo
300 300
 	/** @var \OC\DateTimeFormatter $formatter */
301 301
 	$formatter = \OC::$server->query('DateTimeFormatter');
302 302
 
303
-	if ($dateOnly){
303
+	if ($dateOnly) {
304 304
 		return $formatter->formatDateSpan($timestamp, $fromTime);
305 305
 	}
306 306
 	return $formatter->formatTimeSpan($timestamp, $fromTime);
307 307
 }
308 308
 
309
-function html_select_options($options, $selected, $params=[]) {
309
+function html_select_options($options, $selected, $params = []) {
310 310
 	if (!is_array($selected)) {
311
-		$selected=[$selected];
311
+		$selected = [$selected];
312 312
 	}
313 313
 	if (isset($params['combine']) && $params['combine']) {
314 314
 		$options = array_combine($options, $options);
@@ -321,7 +321,7 @@  discard block
 block discarded – undo
321 321
 		$label_name = $params['label'];
322 322
 	}
323 323
 	$html = '';
324
-	foreach($options as $value => $label) {
324
+	foreach ($options as $value => $label) {
325 325
 		if ($value_name && is_array($label)) {
326 326
 			$value = $label[$value_name];
327 327
 		}
@@ -329,7 +329,7 @@  discard block
 block discarded – undo
329 329
 			$label = $label[$label_name];
330 330
 		}
331 331
 		$select = in_array($value, $selected) ? ' selected="selected"' : '';
332
-		$html .= '<option value="' . \OCP\Util::sanitizeHTML($value) . '"' . $select . '>' . \OCP\Util::sanitizeHTML($label) . '</option>'."\n";
332
+		$html .= '<option value="'.\OCP\Util::sanitizeHTML($value).'"'.$select.'>'.\OCP\Util::sanitizeHTML($label).'</option>'."\n";
333 333
 	}
334 334
 	return $html;
335 335
 }
Please login to merge, or discard this patch.
lib/private/legacy/OC_Response.php 2 patches
Indentation   +73 added lines, -73 removed lines patch added patch discarded remove patch
@@ -28,81 +28,81 @@
 block discarded – undo
28 28
  */
29 29
 
30 30
 class OC_Response {
31
-	/**
32
-	 * Sets the content disposition header (with possible workarounds)
33
-	 * @param string $filename file name
34
-	 * @param string $type disposition type, either 'attachment' or 'inline'
35
-	 */
36
-	static public function setContentDispositionHeader($filename, $type = 'attachment') {
37
-		if (\OC::$server->getRequest()->isUserAgent(
38
-			[
39
-				\OC\AppFramework\Http\Request::USER_AGENT_IE,
40
-				\OC\AppFramework\Http\Request::USER_AGENT_ANDROID_MOBILE_CHROME,
41
-				\OC\AppFramework\Http\Request::USER_AGENT_FREEBOX,
42
-			])) {
43
-			header('Content-Disposition: ' . rawurlencode($type) . '; filename="' . rawurlencode($filename) . '"');
44
-		} else {
45
-			header('Content-Disposition: ' . rawurlencode($type) . '; filename*=UTF-8\'\'' . rawurlencode($filename)
46
-												 . '; filename="' . rawurlencode($filename) . '"');
47
-		}
48
-	}
31
+    /**
32
+     * Sets the content disposition header (with possible workarounds)
33
+     * @param string $filename file name
34
+     * @param string $type disposition type, either 'attachment' or 'inline'
35
+     */
36
+    static public function setContentDispositionHeader($filename, $type = 'attachment') {
37
+        if (\OC::$server->getRequest()->isUserAgent(
38
+            [
39
+                \OC\AppFramework\Http\Request::USER_AGENT_IE,
40
+                \OC\AppFramework\Http\Request::USER_AGENT_ANDROID_MOBILE_CHROME,
41
+                \OC\AppFramework\Http\Request::USER_AGENT_FREEBOX,
42
+            ])) {
43
+            header('Content-Disposition: ' . rawurlencode($type) . '; filename="' . rawurlencode($filename) . '"');
44
+        } else {
45
+            header('Content-Disposition: ' . rawurlencode($type) . '; filename*=UTF-8\'\'' . rawurlencode($filename)
46
+                                                    . '; filename="' . rawurlencode($filename) . '"');
47
+        }
48
+    }
49 49
 
50
-	/**
51
-	 * Sets the content length header (with possible workarounds)
52
-	 * @param string|int|float $length Length to be sent
53
-	 */
54
-	static public function setContentLengthHeader($length) {
55
-		if (PHP_INT_SIZE === 4) {
56
-			if ($length > PHP_INT_MAX && stripos(PHP_SAPI, 'apache') === 0) {
57
-				// Apache PHP SAPI casts Content-Length headers to PHP integers.
58
-				// This enforces a limit of PHP_INT_MAX (2147483647 on 32-bit
59
-				// platforms). So, if the length is greater than PHP_INT_MAX,
60
-				// we just do not send a Content-Length header to prevent
61
-				// bodies from being received incompletely.
62
-				return;
63
-			}
64
-			// Convert signed integer or float to unsigned base-10 string.
65
-			$lfh = new \OC\LargeFileHelper;
66
-			$length = $lfh->formatUnsignedInteger($length);
67
-		}
68
-		header('Content-Length: '.$length);
69
-	}
50
+    /**
51
+     * Sets the content length header (with possible workarounds)
52
+     * @param string|int|float $length Length to be sent
53
+     */
54
+    static public function setContentLengthHeader($length) {
55
+        if (PHP_INT_SIZE === 4) {
56
+            if ($length > PHP_INT_MAX && stripos(PHP_SAPI, 'apache') === 0) {
57
+                // Apache PHP SAPI casts Content-Length headers to PHP integers.
58
+                // This enforces a limit of PHP_INT_MAX (2147483647 on 32-bit
59
+                // platforms). So, if the length is greater than PHP_INT_MAX,
60
+                // we just do not send a Content-Length header to prevent
61
+                // bodies from being received incompletely.
62
+                return;
63
+            }
64
+            // Convert signed integer or float to unsigned base-10 string.
65
+            $lfh = new \OC\LargeFileHelper;
66
+            $length = $lfh->formatUnsignedInteger($length);
67
+        }
68
+        header('Content-Length: '.$length);
69
+    }
70 70
 
71
-	/**
72
-	 * This function adds some security related headers to all requests served via base.php
73
-	 * The implementation of this function has to happen here to ensure that all third-party
74
-	 * components (e.g. SabreDAV) also benefit from this headers.
75
-	 */
76
-	public static function addSecurityHeaders() {
77
-		/**
78
-		 * FIXME: Content Security Policy for legacy ownCloud components. This
79
-		 * can be removed once \OCP\AppFramework\Http\Response from the AppFramework
80
-		 * is used everywhere.
81
-		 * @see \OCP\AppFramework\Http\Response::getHeaders
82
-		 */
83
-		$policy = 'default-src \'self\'; '
84
-			. 'script-src \'self\' \'nonce-'.\OC::$server->getContentSecurityPolicyNonceManager()->getNonce().'\'; '
85
-			. 'style-src \'self\' \'unsafe-inline\'; '
86
-			. 'frame-src *; '
87
-			. 'img-src * data: blob:; '
88
-			. 'font-src \'self\' data:; '
89
-			. 'media-src *; '
90
-			. 'connect-src *; '
91
-			. 'object-src \'none\'; '
92
-			. 'base-uri \'self\'; ';
93
-		header('Content-Security-Policy:' . $policy);
71
+    /**
72
+     * This function adds some security related headers to all requests served via base.php
73
+     * The implementation of this function has to happen here to ensure that all third-party
74
+     * components (e.g. SabreDAV) also benefit from this headers.
75
+     */
76
+    public static function addSecurityHeaders() {
77
+        /**
78
+         * FIXME: Content Security Policy for legacy ownCloud components. This
79
+         * can be removed once \OCP\AppFramework\Http\Response from the AppFramework
80
+         * is used everywhere.
81
+         * @see \OCP\AppFramework\Http\Response::getHeaders
82
+         */
83
+        $policy = 'default-src \'self\'; '
84
+            . 'script-src \'self\' \'nonce-'.\OC::$server->getContentSecurityPolicyNonceManager()->getNonce().'\'; '
85
+            . 'style-src \'self\' \'unsafe-inline\'; '
86
+            . 'frame-src *; '
87
+            . 'img-src * data: blob:; '
88
+            . 'font-src \'self\' data:; '
89
+            . 'media-src *; '
90
+            . 'connect-src *; '
91
+            . 'object-src \'none\'; '
92
+            . 'base-uri \'self\'; ';
93
+        header('Content-Security-Policy:' . $policy);
94 94
 
95
-		// Send fallback headers for installations that don't have the possibility to send
96
-		// custom headers on the webserver side
97
-		if(getenv('modHeadersAvailable') !== 'true') {
98
-			header('Referrer-Policy: no-referrer'); // https://www.w3.org/TR/referrer-policy/
99
-			header('X-Content-Type-Options: nosniff'); // Disable sniffing the content type for IE
100
-			header('X-Download-Options: noopen'); // https://msdn.microsoft.com/en-us/library/jj542450(v=vs.85).aspx
101
-			header('X-Frame-Options: SAMEORIGIN'); // Disallow iFraming from other domains
102
-			header('X-Permitted-Cross-Domain-Policies: none'); // https://www.adobe.com/devnet/adobe-media-server/articles/cross-domain-xml-for-streaming.html
103
-			header('X-Robots-Tag: none'); // https://developers.google.com/webmasters/control-crawl-index/docs/robots_meta_tag
104
-			header('X-XSS-Protection: 1; mode=block'); // Enforce browser based XSS filters
105
-		}
106
-	}
95
+        // Send fallback headers for installations that don't have the possibility to send
96
+        // custom headers on the webserver side
97
+        if(getenv('modHeadersAvailable') !== 'true') {
98
+            header('Referrer-Policy: no-referrer'); // https://www.w3.org/TR/referrer-policy/
99
+            header('X-Content-Type-Options: nosniff'); // Disable sniffing the content type for IE
100
+            header('X-Download-Options: noopen'); // https://msdn.microsoft.com/en-us/library/jj542450(v=vs.85).aspx
101
+            header('X-Frame-Options: SAMEORIGIN'); // Disallow iFraming from other domains
102
+            header('X-Permitted-Cross-Domain-Policies: none'); // https://www.adobe.com/devnet/adobe-media-server/articles/cross-domain-xml-for-streaming.html
103
+            header('X-Robots-Tag: none'); // https://developers.google.com/webmasters/control-crawl-index/docs/robots_meta_tag
104
+            header('X-XSS-Protection: 1; mode=block'); // Enforce browser based XSS filters
105
+        }
106
+    }
107 107
 
108 108
 }
Please login to merge, or discard this patch.
Spacing   +5 added lines, -5 removed lines patch added patch discarded remove patch
@@ -40,10 +40,10 @@  discard block
 block discarded – undo
40 40
 				\OC\AppFramework\Http\Request::USER_AGENT_ANDROID_MOBILE_CHROME,
41 41
 				\OC\AppFramework\Http\Request::USER_AGENT_FREEBOX,
42 42
 			])) {
43
-			header('Content-Disposition: ' . rawurlencode($type) . '; filename="' . rawurlencode($filename) . '"');
43
+			header('Content-Disposition: '.rawurlencode($type).'; filename="'.rawurlencode($filename).'"');
44 44
 		} else {
45
-			header('Content-Disposition: ' . rawurlencode($type) . '; filename*=UTF-8\'\'' . rawurlencode($filename)
46
-												 . '; filename="' . rawurlencode($filename) . '"');
45
+			header('Content-Disposition: '.rawurlencode($type).'; filename*=UTF-8\'\''.rawurlencode($filename)
46
+												 . '; filename="'.rawurlencode($filename).'"');
47 47
 		}
48 48
 	}
49 49
 
@@ -90,11 +90,11 @@  discard block
 block discarded – undo
90 90
 			. 'connect-src *; '
91 91
 			. 'object-src \'none\'; '
92 92
 			. 'base-uri \'self\'; ';
93
-		header('Content-Security-Policy:' . $policy);
93
+		header('Content-Security-Policy:'.$policy);
94 94
 
95 95
 		// Send fallback headers for installations that don't have the possibility to send
96 96
 		// custom headers on the webserver side
97
-		if(getenv('modHeadersAvailable') !== 'true') {
97
+		if (getenv('modHeadersAvailable') !== 'true') {
98 98
 			header('Referrer-Policy: no-referrer'); // https://www.w3.org/TR/referrer-policy/
99 99
 			header('X-Content-Type-Options: nosniff'); // Disable sniffing the content type for IE
100 100
 			header('X-Download-Options: noopen'); // https://msdn.microsoft.com/en-us/library/jj542450(v=vs.85).aspx
Please login to merge, or discard this patch.
lib/private/legacy/OC_Hook.php 2 patches
Indentation   +103 added lines, -103 removed lines patch added patch discarded remove patch
@@ -34,118 +34,118 @@
 block discarded – undo
34 34
  * @deprecated 18.0.0 use events and the \OCP\EventDispatcher\IEventDispatcher service
35 35
  */
36 36
 class OC_Hook {
37
-	public static $thrownExceptions = [];
37
+    public static $thrownExceptions = [];
38 38
 
39
-	static private $registered = [];
39
+    static private $registered = [];
40 40
 
41
-	/**
42
-	 * connects a function to a hook
43
-	 *
44
-	 * @param string $signalClass class name of emitter
45
-	 * @param string $signalName name of signal
46
-	 * @param string|object $slotClass class name of slot
47
-	 * @param string $slotName name of slot
48
-	 * @return bool
49
-	 *
50
-	 * This function makes it very easy to connect to use hooks.
51
-	 *
52
-	 * TODO: write example
53
-	 */
54
-	static public function connect($signalClass, $signalName, $slotClass, $slotName) {
55
-		// If we're trying to connect to an emitting class that isn't
56
-		// yet registered, register it
57
-		if(!array_key_exists($signalClass, self::$registered)) {
58
-			self::$registered[$signalClass] = [];
59
-		}
60
-		// If we're trying to connect to an emitting method that isn't
61
-		// yet registered, register it with the emitting class
62
-		if(!array_key_exists($signalName, self::$registered[$signalClass])) {
63
-			self::$registered[$signalClass][$signalName] = [];
64
-		}
41
+    /**
42
+     * connects a function to a hook
43
+     *
44
+     * @param string $signalClass class name of emitter
45
+     * @param string $signalName name of signal
46
+     * @param string|object $slotClass class name of slot
47
+     * @param string $slotName name of slot
48
+     * @return bool
49
+     *
50
+     * This function makes it very easy to connect to use hooks.
51
+     *
52
+     * TODO: write example
53
+     */
54
+    static public function connect($signalClass, $signalName, $slotClass, $slotName) {
55
+        // If we're trying to connect to an emitting class that isn't
56
+        // yet registered, register it
57
+        if(!array_key_exists($signalClass, self::$registered)) {
58
+            self::$registered[$signalClass] = [];
59
+        }
60
+        // If we're trying to connect to an emitting method that isn't
61
+        // yet registered, register it with the emitting class
62
+        if(!array_key_exists($signalName, self::$registered[$signalClass])) {
63
+            self::$registered[$signalClass][$signalName] = [];
64
+        }
65 65
 
66
-		// don't connect hooks twice
67
-		foreach (self::$registered[$signalClass][$signalName] as $hook) {
68
-			if ($hook['class'] === $slotClass and $hook['name'] === $slotName) {
69
-				return false;
70
-			}
71
-		}
72
-		// Connect the hook handler to the requested emitter
73
-		self::$registered[$signalClass][$signalName][] = [
74
-			"class" => $slotClass,
75
-			"name" => $slotName
76
-		];
66
+        // don't connect hooks twice
67
+        foreach (self::$registered[$signalClass][$signalName] as $hook) {
68
+            if ($hook['class'] === $slotClass and $hook['name'] === $slotName) {
69
+                return false;
70
+            }
71
+        }
72
+        // Connect the hook handler to the requested emitter
73
+        self::$registered[$signalClass][$signalName][] = [
74
+            "class" => $slotClass,
75
+            "name" => $slotName
76
+        ];
77 77
 
78
-		// No chance for failure ;-)
79
-		return true;
80
-	}
78
+        // No chance for failure ;-)
79
+        return true;
80
+    }
81 81
 
82
-	/**
83
-	 * emits a signal
84
-	 *
85
-	 * @param string $signalClass class name of emitter
86
-	 * @param string $signalName name of signal
87
-	 * @param mixed $params default: array() array with additional data
88
-	 * @return bool true if slots exists or false if not
89
-	 * @throws \OC\HintException
90
-	 * @throws \OC\ServerNotAvailableException Emits a signal. To get data from the slot use references!
91
-	 *
92
-	 * TODO: write example
93
-	 */
94
-	static public function emit($signalClass, $signalName, $params = []) {
82
+    /**
83
+     * emits a signal
84
+     *
85
+     * @param string $signalClass class name of emitter
86
+     * @param string $signalName name of signal
87
+     * @param mixed $params default: array() array with additional data
88
+     * @return bool true if slots exists or false if not
89
+     * @throws \OC\HintException
90
+     * @throws \OC\ServerNotAvailableException Emits a signal. To get data from the slot use references!
91
+     *
92
+     * TODO: write example
93
+     */
94
+    static public function emit($signalClass, $signalName, $params = []) {
95 95
 
96
-		// Return false if no hook handlers are listening to this
97
-		// emitting class
98
-		if(!array_key_exists($signalClass, self::$registered)) {
99
-			return false;
100
-		}
96
+        // Return false if no hook handlers are listening to this
97
+        // emitting class
98
+        if(!array_key_exists($signalClass, self::$registered)) {
99
+            return false;
100
+        }
101 101
 
102
-		// Return false if no hook handlers are listening to this
103
-		// emitting method
104
-		if(!array_key_exists($signalName, self::$registered[$signalClass])) {
105
-			return false;
106
-		}
102
+        // Return false if no hook handlers are listening to this
103
+        // emitting method
104
+        if(!array_key_exists($signalName, self::$registered[$signalClass])) {
105
+            return false;
106
+        }
107 107
 
108
-		// Call all slots
109
-		foreach(self::$registered[$signalClass][$signalName] as $i) {
110
-			try {
111
-				call_user_func([ $i["class"], $i["name"] ], $params);
112
-			} catch (Exception $e){
113
-				self::$thrownExceptions[] = $e;
114
-				\OC::$server->getLogger()->logException($e);
115
-				if($e instanceof \OC\HintException) {
116
-					throw $e;
117
-				}
118
-				if($e instanceof \OC\ServerNotAvailableException) {
119
-					throw $e;
120
-				}
121
-			}
122
-		}
108
+        // Call all slots
109
+        foreach(self::$registered[$signalClass][$signalName] as $i) {
110
+            try {
111
+                call_user_func([ $i["class"], $i["name"] ], $params);
112
+            } catch (Exception $e){
113
+                self::$thrownExceptions[] = $e;
114
+                \OC::$server->getLogger()->logException($e);
115
+                if($e instanceof \OC\HintException) {
116
+                    throw $e;
117
+                }
118
+                if($e instanceof \OC\ServerNotAvailableException) {
119
+                    throw $e;
120
+                }
121
+            }
122
+        }
123 123
 
124
-		return true;
125
-	}
124
+        return true;
125
+    }
126 126
 
127
-	/**
128
-	 * clear hooks
129
-	 * @param string $signalClass
130
-	 * @param string $signalName
131
-	 */
132
-	static public function clear($signalClass='', $signalName='') {
133
-		if ($signalClass) {
134
-			if ($signalName) {
135
-				self::$registered[$signalClass][$signalName]=[];
136
-			}else{
137
-				self::$registered[$signalClass]=[];
138
-			}
139
-		}else{
140
-			self::$registered=[];
141
-		}
142
-	}
127
+    /**
128
+     * clear hooks
129
+     * @param string $signalClass
130
+     * @param string $signalName
131
+     */
132
+    static public function clear($signalClass='', $signalName='') {
133
+        if ($signalClass) {
134
+            if ($signalName) {
135
+                self::$registered[$signalClass][$signalName]=[];
136
+            }else{
137
+                self::$registered[$signalClass]=[];
138
+            }
139
+        }else{
140
+            self::$registered=[];
141
+        }
142
+    }
143 143
 
144
-	/**
145
-	 * DO NOT USE!
146
-	 * For unit tests ONLY!
147
-	 */
148
-	static public function getHooks() {
149
-		return self::$registered;
150
-	}
144
+    /**
145
+     * DO NOT USE!
146
+     * For unit tests ONLY!
147
+     */
148
+    static public function getHooks() {
149
+        return self::$registered;
150
+    }
151 151
 }
Please login to merge, or discard this patch.
Spacing   +15 added lines, -15 removed lines patch added patch discarded remove patch
@@ -54,12 +54,12 @@  discard block
 block discarded – undo
54 54
 	static public function connect($signalClass, $signalName, $slotClass, $slotName) {
55 55
 		// If we're trying to connect to an emitting class that isn't
56 56
 		// yet registered, register it
57
-		if(!array_key_exists($signalClass, self::$registered)) {
57
+		if (!array_key_exists($signalClass, self::$registered)) {
58 58
 			self::$registered[$signalClass] = [];
59 59
 		}
60 60
 		// If we're trying to connect to an emitting method that isn't
61 61
 		// yet registered, register it with the emitting class
62
-		if(!array_key_exists($signalName, self::$registered[$signalClass])) {
62
+		if (!array_key_exists($signalName, self::$registered[$signalClass])) {
63 63
 			self::$registered[$signalClass][$signalName] = [];
64 64
 		}
65 65
 
@@ -95,27 +95,27 @@  discard block
 block discarded – undo
95 95
 
96 96
 		// Return false if no hook handlers are listening to this
97 97
 		// emitting class
98
-		if(!array_key_exists($signalClass, self::$registered)) {
98
+		if (!array_key_exists($signalClass, self::$registered)) {
99 99
 			return false;
100 100
 		}
101 101
 
102 102
 		// Return false if no hook handlers are listening to this
103 103
 		// emitting method
104
-		if(!array_key_exists($signalName, self::$registered[$signalClass])) {
104
+		if (!array_key_exists($signalName, self::$registered[$signalClass])) {
105 105
 			return false;
106 106
 		}
107 107
 
108 108
 		// Call all slots
109
-		foreach(self::$registered[$signalClass][$signalName] as $i) {
109
+		foreach (self::$registered[$signalClass][$signalName] as $i) {
110 110
 			try {
111
-				call_user_func([ $i["class"], $i["name"] ], $params);
112
-			} catch (Exception $e){
111
+				call_user_func([$i["class"], $i["name"]], $params);
112
+			} catch (Exception $e) {
113 113
 				self::$thrownExceptions[] = $e;
114 114
 				\OC::$server->getLogger()->logException($e);
115
-				if($e instanceof \OC\HintException) {
115
+				if ($e instanceof \OC\HintException) {
116 116
 					throw $e;
117 117
 				}
118
-				if($e instanceof \OC\ServerNotAvailableException) {
118
+				if ($e instanceof \OC\ServerNotAvailableException) {
119 119
 					throw $e;
120 120
 				}
121 121
 			}
@@ -129,15 +129,15 @@  discard block
 block discarded – undo
129 129
 	 * @param string $signalClass
130 130
 	 * @param string $signalName
131 131
 	 */
132
-	static public function clear($signalClass='', $signalName='') {
132
+	static public function clear($signalClass = '', $signalName = '') {
133 133
 		if ($signalClass) {
134 134
 			if ($signalName) {
135
-				self::$registered[$signalClass][$signalName]=[];
136
-			}else{
137
-				self::$registered[$signalClass]=[];
135
+				self::$registered[$signalClass][$signalName] = [];
136
+			} else {
137
+				self::$registered[$signalClass] = [];
138 138
 			}
139
-		}else{
140
-			self::$registered=[];
139
+		} else {
140
+			self::$registered = [];
141 141
 		}
142 142
 	}
143 143
 
Please login to merge, or discard this patch.
lib/private/Files/View.php 1 patch
Indentation   +2109 added lines, -2109 removed lines patch added patch discarded remove patch
@@ -83,2113 +83,2113 @@
 block discarded – undo
83 83
  * \OC\Files\Storage\Storage object
84 84
  */
85 85
 class View {
86
-	/** @var string */
87
-	private $fakeRoot = '';
88
-
89
-	/**
90
-	 * @var \OCP\Lock\ILockingProvider
91
-	 */
92
-	protected $lockingProvider;
93
-
94
-	private $lockingEnabled;
95
-
96
-	private $updaterEnabled = true;
97
-
98
-	/** @var \OC\User\Manager */
99
-	private $userManager;
100
-
101
-	/** @var \OCP\ILogger */
102
-	private $logger;
103
-
104
-	/**
105
-	 * @param string $root
106
-	 * @throws \Exception If $root contains an invalid path
107
-	 */
108
-	public function __construct($root = '') {
109
-		if (is_null($root)) {
110
-			throw new \InvalidArgumentException('Root can\'t be null');
111
-		}
112
-		if (!Filesystem::isValidPath($root)) {
113
-			throw new \Exception();
114
-		}
115
-
116
-		$this->fakeRoot = $root;
117
-		$this->lockingProvider = \OC::$server->getLockingProvider();
118
-		$this->lockingEnabled = !($this->lockingProvider instanceof \OC\Lock\NoopLockingProvider);
119
-		$this->userManager = \OC::$server->getUserManager();
120
-		$this->logger = \OC::$server->getLogger();
121
-	}
122
-
123
-	public function getAbsolutePath($path = '/') {
124
-		if ($path === null) {
125
-			return null;
126
-		}
127
-		$this->assertPathLength($path);
128
-		if ($path === '') {
129
-			$path = '/';
130
-		}
131
-		if ($path[0] !== '/') {
132
-			$path = '/' . $path;
133
-		}
134
-		return $this->fakeRoot . $path;
135
-	}
136
-
137
-	/**
138
-	 * change the root to a fake root
139
-	 *
140
-	 * @param string $fakeRoot
141
-	 * @return boolean|null
142
-	 */
143
-	public function chroot($fakeRoot) {
144
-		if (!$fakeRoot == '') {
145
-			if ($fakeRoot[0] !== '/') {
146
-				$fakeRoot = '/' . $fakeRoot;
147
-			}
148
-		}
149
-		$this->fakeRoot = $fakeRoot;
150
-	}
151
-
152
-	/**
153
-	 * get the fake root
154
-	 *
155
-	 * @return string
156
-	 */
157
-	public function getRoot() {
158
-		return $this->fakeRoot;
159
-	}
160
-
161
-	/**
162
-	 * get path relative to the root of the view
163
-	 *
164
-	 * @param string $path
165
-	 * @return string
166
-	 */
167
-	public function getRelativePath($path) {
168
-		$this->assertPathLength($path);
169
-		if ($this->fakeRoot == '') {
170
-			return $path;
171
-		}
172
-
173
-		if (rtrim($path, '/') === rtrim($this->fakeRoot, '/')) {
174
-			return '/';
175
-		}
176
-
177
-		// missing slashes can cause wrong matches!
178
-		$root = rtrim($this->fakeRoot, '/') . '/';
179
-
180
-		if (strpos($path, $root) !== 0) {
181
-			return null;
182
-		} else {
183
-			$path = substr($path, strlen($this->fakeRoot));
184
-			if (strlen($path) === 0) {
185
-				return '/';
186
-			} else {
187
-				return $path;
188
-			}
189
-		}
190
-	}
191
-
192
-	/**
193
-	 * get the mountpoint of the storage object for a path
194
-	 * ( note: because a storage is not always mounted inside the fakeroot, the
195
-	 * returned mountpoint is relative to the absolute root of the filesystem
196
-	 * and does not take the chroot into account )
197
-	 *
198
-	 * @param string $path
199
-	 * @return string
200
-	 */
201
-	public function getMountPoint($path) {
202
-		return Filesystem::getMountPoint($this->getAbsolutePath($path));
203
-	}
204
-
205
-	/**
206
-	 * get the mountpoint of the storage object for a path
207
-	 * ( note: because a storage is not always mounted inside the fakeroot, the
208
-	 * returned mountpoint is relative to the absolute root of the filesystem
209
-	 * and does not take the chroot into account )
210
-	 *
211
-	 * @param string $path
212
-	 * @return \OCP\Files\Mount\IMountPoint
213
-	 */
214
-	public function getMount($path) {
215
-		return Filesystem::getMountManager()->find($this->getAbsolutePath($path));
216
-	}
217
-
218
-	/**
219
-	 * resolve a path to a storage and internal path
220
-	 *
221
-	 * @param string $path
222
-	 * @return array an array consisting of the storage and the internal path
223
-	 */
224
-	public function resolvePath($path) {
225
-		$a = $this->getAbsolutePath($path);
226
-		$p = Filesystem::normalizePath($a);
227
-		return Filesystem::resolvePath($p);
228
-	}
229
-
230
-	/**
231
-	 * return the path to a local version of the file
232
-	 * we need this because we can't know if a file is stored local or not from
233
-	 * outside the filestorage and for some purposes a local file is needed
234
-	 *
235
-	 * @param string $path
236
-	 * @return string
237
-	 */
238
-	public function getLocalFile($path) {
239
-		$parent = substr($path, 0, strrpos($path, '/'));
240
-		$path = $this->getAbsolutePath($path);
241
-		list($storage, $internalPath) = Filesystem::resolvePath($path);
242
-		if (Filesystem::isValidPath($parent) and $storage) {
243
-			return $storage->getLocalFile($internalPath);
244
-		} else {
245
-			return null;
246
-		}
247
-	}
248
-
249
-	/**
250
-	 * @param string $path
251
-	 * @return string
252
-	 */
253
-	public function getLocalFolder($path) {
254
-		$parent = substr($path, 0, strrpos($path, '/'));
255
-		$path = $this->getAbsolutePath($path);
256
-		list($storage, $internalPath) = Filesystem::resolvePath($path);
257
-		if (Filesystem::isValidPath($parent) and $storage) {
258
-			return $storage->getLocalFolder($internalPath);
259
-		} else {
260
-			return null;
261
-		}
262
-	}
263
-
264
-	/**
265
-	 * the following functions operate with arguments and return values identical
266
-	 * to those of their PHP built-in equivalents. Mostly they are merely wrappers
267
-	 * for \OC\Files\Storage\Storage via basicOperation().
268
-	 */
269
-	public function mkdir($path) {
270
-		return $this->basicOperation('mkdir', $path, ['create', 'write']);
271
-	}
272
-
273
-	/**
274
-	 * remove mount point
275
-	 *
276
-	 * @param \OC\Files\Mount\MoveableMount $mount
277
-	 * @param string $path relative to data/
278
-	 * @return boolean
279
-	 */
280
-	protected function removeMount($mount, $path) {
281
-		if ($mount instanceof MoveableMount) {
282
-			// cut of /user/files to get the relative path to data/user/files
283
-			$pathParts = explode('/', $path, 4);
284
-			$relPath = '/' . $pathParts[3];
285
-			$this->lockFile($relPath, ILockingProvider::LOCK_SHARED, true);
286
-			\OC_Hook::emit(
287
-				Filesystem::CLASSNAME, "umount",
288
-				[Filesystem::signal_param_path => $relPath]
289
-			);
290
-			$this->changeLock($relPath, ILockingProvider::LOCK_EXCLUSIVE, true);
291
-			$result = $mount->removeMount();
292
-			$this->changeLock($relPath, ILockingProvider::LOCK_SHARED, true);
293
-			if ($result) {
294
-				\OC_Hook::emit(
295
-					Filesystem::CLASSNAME, "post_umount",
296
-					[Filesystem::signal_param_path => $relPath]
297
-				);
298
-			}
299
-			$this->unlockFile($relPath, ILockingProvider::LOCK_SHARED, true);
300
-			return $result;
301
-		} else {
302
-			// do not allow deleting the storage's root / the mount point
303
-			// because for some storages it might delete the whole contents
304
-			// but isn't supposed to work that way
305
-			return false;
306
-		}
307
-	}
308
-
309
-	public function disableCacheUpdate() {
310
-		$this->updaterEnabled = false;
311
-	}
312
-
313
-	public function enableCacheUpdate() {
314
-		$this->updaterEnabled = true;
315
-	}
316
-
317
-	protected function writeUpdate(Storage $storage, $internalPath, $time = null) {
318
-		if ($this->updaterEnabled) {
319
-			if (is_null($time)) {
320
-				$time = time();
321
-			}
322
-			$storage->getUpdater()->update($internalPath, $time);
323
-		}
324
-	}
325
-
326
-	protected function removeUpdate(Storage $storage, $internalPath) {
327
-		if ($this->updaterEnabled) {
328
-			$storage->getUpdater()->remove($internalPath);
329
-		}
330
-	}
331
-
332
-	protected function renameUpdate(Storage $sourceStorage, Storage $targetStorage, $sourceInternalPath, $targetInternalPath) {
333
-		if ($this->updaterEnabled) {
334
-			$targetStorage->getUpdater()->renameFromStorage($sourceStorage, $sourceInternalPath, $targetInternalPath);
335
-		}
336
-	}
337
-
338
-	/**
339
-	 * @param string $path
340
-	 * @return bool|mixed
341
-	 */
342
-	public function rmdir($path) {
343
-		$absolutePath = $this->getAbsolutePath($path);
344
-		$mount = Filesystem::getMountManager()->find($absolutePath);
345
-		if ($mount->getInternalPath($absolutePath) === '') {
346
-			return $this->removeMount($mount, $absolutePath);
347
-		}
348
-		if ($this->is_dir($path)) {
349
-			$result = $this->basicOperation('rmdir', $path, ['delete']);
350
-		} else {
351
-			$result = false;
352
-		}
353
-
354
-		if (!$result && !$this->file_exists($path)) { //clear ghost files from the cache on delete
355
-			$storage = $mount->getStorage();
356
-			$internalPath = $mount->getInternalPath($absolutePath);
357
-			$storage->getUpdater()->remove($internalPath);
358
-		}
359
-		return $result;
360
-	}
361
-
362
-	/**
363
-	 * @param string $path
364
-	 * @return resource
365
-	 */
366
-	public function opendir($path) {
367
-		return $this->basicOperation('opendir', $path, ['read']);
368
-	}
369
-
370
-	/**
371
-	 * @param string $path
372
-	 * @return bool|mixed
373
-	 */
374
-	public function is_dir($path) {
375
-		if ($path == '/') {
376
-			return true;
377
-		}
378
-		return $this->basicOperation('is_dir', $path);
379
-	}
380
-
381
-	/**
382
-	 * @param string $path
383
-	 * @return bool|mixed
384
-	 */
385
-	public function is_file($path) {
386
-		if ($path == '/') {
387
-			return false;
388
-		}
389
-		return $this->basicOperation('is_file', $path);
390
-	}
391
-
392
-	/**
393
-	 * @param string $path
394
-	 * @return mixed
395
-	 */
396
-	public function stat($path) {
397
-		return $this->basicOperation('stat', $path);
398
-	}
399
-
400
-	/**
401
-	 * @param string $path
402
-	 * @return mixed
403
-	 */
404
-	public function filetype($path) {
405
-		return $this->basicOperation('filetype', $path);
406
-	}
407
-
408
-	/**
409
-	 * @param string $path
410
-	 * @return mixed
411
-	 */
412
-	public function filesize($path) {
413
-		return $this->basicOperation('filesize', $path);
414
-	}
415
-
416
-	/**
417
-	 * @param string $path
418
-	 * @return bool|mixed
419
-	 * @throws \OCP\Files\InvalidPathException
420
-	 */
421
-	public function readfile($path) {
422
-		$this->assertPathLength($path);
423
-		@ob_end_clean();
424
-		$handle = $this->fopen($path, 'rb');
425
-		if ($handle) {
426
-			$chunkSize = 8192; // 8 kB chunks
427
-			while (!feof($handle)) {
428
-				echo fread($handle, $chunkSize);
429
-				flush();
430
-			}
431
-			fclose($handle);
432
-			return $this->filesize($path);
433
-		}
434
-		return false;
435
-	}
436
-
437
-	/**
438
-	 * @param string $path
439
-	 * @param int $from
440
-	 * @param int $to
441
-	 * @return bool|mixed
442
-	 * @throws \OCP\Files\InvalidPathException
443
-	 * @throws \OCP\Files\UnseekableException
444
-	 */
445
-	public function readfilePart($path, $from, $to) {
446
-		$this->assertPathLength($path);
447
-		@ob_end_clean();
448
-		$handle = $this->fopen($path, 'rb');
449
-		if ($handle) {
450
-			$chunkSize = 8192; // 8 kB chunks
451
-			$startReading = true;
452
-
453
-			if ($from !== 0 && $from !== '0' && fseek($handle, $from) !== 0) {
454
-				// forward file handle via chunked fread because fseek seem to have failed
455
-
456
-				$end = $from + 1;
457
-				while (!feof($handle) && ftell($handle) < $end) {
458
-					$len = $from - ftell($handle);
459
-					if ($len > $chunkSize) {
460
-						$len = $chunkSize;
461
-					}
462
-					$result = fread($handle, $len);
463
-
464
-					if ($result === false) {
465
-						$startReading = false;
466
-						break;
467
-					}
468
-				}
469
-			}
470
-
471
-			if ($startReading) {
472
-				$end = $to + 1;
473
-				while (!feof($handle) && ftell($handle) < $end) {
474
-					$len = $end - ftell($handle);
475
-					if ($len > $chunkSize) {
476
-						$len = $chunkSize;
477
-					}
478
-					echo fread($handle, $len);
479
-					flush();
480
-				}
481
-				return ftell($handle) - $from;
482
-			}
483
-
484
-			throw new \OCP\Files\UnseekableException('fseek error');
485
-		}
486
-		return false;
487
-	}
488
-
489
-	/**
490
-	 * @param string $path
491
-	 * @return mixed
492
-	 */
493
-	public function isCreatable($path) {
494
-		return $this->basicOperation('isCreatable', $path);
495
-	}
496
-
497
-	/**
498
-	 * @param string $path
499
-	 * @return mixed
500
-	 */
501
-	public function isReadable($path) {
502
-		return $this->basicOperation('isReadable', $path);
503
-	}
504
-
505
-	/**
506
-	 * @param string $path
507
-	 * @return mixed
508
-	 */
509
-	public function isUpdatable($path) {
510
-		return $this->basicOperation('isUpdatable', $path);
511
-	}
512
-
513
-	/**
514
-	 * @param string $path
515
-	 * @return bool|mixed
516
-	 */
517
-	public function isDeletable($path) {
518
-		$absolutePath = $this->getAbsolutePath($path);
519
-		$mount = Filesystem::getMountManager()->find($absolutePath);
520
-		if ($mount->getInternalPath($absolutePath) === '') {
521
-			return $mount instanceof MoveableMount;
522
-		}
523
-		return $this->basicOperation('isDeletable', $path);
524
-	}
525
-
526
-	/**
527
-	 * @param string $path
528
-	 * @return mixed
529
-	 */
530
-	public function isSharable($path) {
531
-		return $this->basicOperation('isSharable', $path);
532
-	}
533
-
534
-	/**
535
-	 * @param string $path
536
-	 * @return bool|mixed
537
-	 */
538
-	public function file_exists($path) {
539
-		if ($path == '/') {
540
-			return true;
541
-		}
542
-		return $this->basicOperation('file_exists', $path);
543
-	}
544
-
545
-	/**
546
-	 * @param string $path
547
-	 * @return mixed
548
-	 */
549
-	public function filemtime($path) {
550
-		return $this->basicOperation('filemtime', $path);
551
-	}
552
-
553
-	/**
554
-	 * @param string $path
555
-	 * @param int|string $mtime
556
-	 * @return bool
557
-	 */
558
-	public function touch($path, $mtime = null) {
559
-		if (!is_null($mtime) and !is_numeric($mtime)) {
560
-			$mtime = strtotime($mtime);
561
-		}
562
-
563
-		$hooks = ['touch'];
564
-
565
-		if (!$this->file_exists($path)) {
566
-			$hooks[] = 'create';
567
-			$hooks[] = 'write';
568
-		}
569
-		try {
570
-			$result = $this->basicOperation('touch', $path, $hooks, $mtime);
571
-		} catch (\Exception $e) {
572
-			$this->logger->logException($e, ['level' => ILogger::INFO, 'message' => 'Error while setting modified time']);
573
-			$result = false;
574
-		}
575
-		if (!$result) {
576
-			// If create file fails because of permissions on external storage like SMB folders,
577
-			// check file exists and return false if not.
578
-			if (!$this->file_exists($path)) {
579
-				return false;
580
-			}
581
-			if (is_null($mtime)) {
582
-				$mtime = time();
583
-			}
584
-			//if native touch fails, we emulate it by changing the mtime in the cache
585
-			$this->putFileInfo($path, ['mtime' => floor($mtime)]);
586
-		}
587
-		return true;
588
-	}
589
-
590
-	/**
591
-	 * @param string $path
592
-	 * @return mixed
593
-	 * @throws LockedException
594
-	 */
595
-	public function file_get_contents($path) {
596
-		return $this->basicOperation('file_get_contents', $path, ['read']);
597
-	}
598
-
599
-	/**
600
-	 * @param bool $exists
601
-	 * @param string $path
602
-	 * @param bool $run
603
-	 */
604
-	protected function emit_file_hooks_pre($exists, $path, &$run) {
605
-		if (!$exists) {
606
-			\OC_Hook::emit(Filesystem::CLASSNAME, Filesystem::signal_create, [
607
-				Filesystem::signal_param_path => $this->getHookPath($path),
608
-				Filesystem::signal_param_run => &$run,
609
-			]);
610
-		} else {
611
-			\OC_Hook::emit(Filesystem::CLASSNAME, Filesystem::signal_update, [
612
-				Filesystem::signal_param_path => $this->getHookPath($path),
613
-				Filesystem::signal_param_run => &$run,
614
-			]);
615
-		}
616
-		\OC_Hook::emit(Filesystem::CLASSNAME, Filesystem::signal_write, [
617
-			Filesystem::signal_param_path => $this->getHookPath($path),
618
-			Filesystem::signal_param_run => &$run,
619
-		]);
620
-	}
621
-
622
-	/**
623
-	 * @param bool $exists
624
-	 * @param string $path
625
-	 */
626
-	protected function emit_file_hooks_post($exists, $path) {
627
-		if (!$exists) {
628
-			\OC_Hook::emit(Filesystem::CLASSNAME, Filesystem::signal_post_create, [
629
-				Filesystem::signal_param_path => $this->getHookPath($path),
630
-			]);
631
-		} else {
632
-			\OC_Hook::emit(Filesystem::CLASSNAME, Filesystem::signal_post_update, [
633
-				Filesystem::signal_param_path => $this->getHookPath($path),
634
-			]);
635
-		}
636
-		\OC_Hook::emit(Filesystem::CLASSNAME, Filesystem::signal_post_write, [
637
-			Filesystem::signal_param_path => $this->getHookPath($path),
638
-		]);
639
-	}
640
-
641
-	/**
642
-	 * @param string $path
643
-	 * @param string|resource $data
644
-	 * @return bool|mixed
645
-	 * @throws LockedException
646
-	 */
647
-	public function file_put_contents($path, $data) {
648
-		if (is_resource($data)) { //not having to deal with streams in file_put_contents makes life easier
649
-			$absolutePath = Filesystem::normalizePath($this->getAbsolutePath($path));
650
-			if (Filesystem::isValidPath($path)
651
-				and !Filesystem::isFileBlacklisted($path)
652
-			) {
653
-				$path = $this->getRelativePath($absolutePath);
654
-
655
-				$this->lockFile($path, ILockingProvider::LOCK_SHARED);
656
-
657
-				$exists = $this->file_exists($path);
658
-				$run = true;
659
-				if ($this->shouldEmitHooks($path)) {
660
-					$this->emit_file_hooks_pre($exists, $path, $run);
661
-				}
662
-				if (!$run) {
663
-					$this->unlockFile($path, ILockingProvider::LOCK_SHARED);
664
-					return false;
665
-				}
666
-
667
-				$this->changeLock($path, ILockingProvider::LOCK_EXCLUSIVE);
668
-
669
-				/** @var \OC\Files\Storage\Storage $storage */
670
-				list($storage, $internalPath) = $this->resolvePath($path);
671
-				$target = $storage->fopen($internalPath, 'w');
672
-				if ($target) {
673
-					list(, $result) = \OC_Helper::streamCopy($data, $target);
674
-					fclose($target);
675
-					fclose($data);
676
-
677
-					$this->writeUpdate($storage, $internalPath);
678
-
679
-					$this->changeLock($path, ILockingProvider::LOCK_SHARED);
680
-
681
-					if ($this->shouldEmitHooks($path) && $result !== false) {
682
-						$this->emit_file_hooks_post($exists, $path);
683
-					}
684
-					$this->unlockFile($path, ILockingProvider::LOCK_SHARED);
685
-					return $result;
686
-				} else {
687
-					$this->unlockFile($path, ILockingProvider::LOCK_EXCLUSIVE);
688
-					return false;
689
-				}
690
-			} else {
691
-				return false;
692
-			}
693
-		} else {
694
-			$hooks = $this->file_exists($path) ? ['update', 'write'] : ['create', 'write'];
695
-			return $this->basicOperation('file_put_contents', $path, $hooks, $data);
696
-		}
697
-	}
698
-
699
-	/**
700
-	 * @param string $path
701
-	 * @return bool|mixed
702
-	 */
703
-	public function unlink($path) {
704
-		if ($path === '' || $path === '/') {
705
-			// do not allow deleting the root
706
-			return false;
707
-		}
708
-		$postFix = (substr($path, -1) === '/') ? '/' : '';
709
-		$absolutePath = Filesystem::normalizePath($this->getAbsolutePath($path));
710
-		$mount = Filesystem::getMountManager()->find($absolutePath . $postFix);
711
-		if ($mount and $mount->getInternalPath($absolutePath) === '') {
712
-			return $this->removeMount($mount, $absolutePath);
713
-		}
714
-		if ($this->is_dir($path)) {
715
-			$result = $this->basicOperation('rmdir', $path, ['delete']);
716
-		} else {
717
-			$result = $this->basicOperation('unlink', $path, ['delete']);
718
-		}
719
-		if (!$result && !$this->file_exists($path)) { //clear ghost files from the cache on delete
720
-			$storage = $mount->getStorage();
721
-			$internalPath = $mount->getInternalPath($absolutePath);
722
-			$storage->getUpdater()->remove($internalPath);
723
-			return true;
724
-		} else {
725
-			return $result;
726
-		}
727
-	}
728
-
729
-	/**
730
-	 * @param string $directory
731
-	 * @return bool|mixed
732
-	 */
733
-	public function deleteAll($directory) {
734
-		return $this->rmdir($directory);
735
-	}
736
-
737
-	/**
738
-	 * Rename/move a file or folder from the source path to target path.
739
-	 *
740
-	 * @param string $path1 source path
741
-	 * @param string $path2 target path
742
-	 *
743
-	 * @return bool|mixed
744
-	 * @throws LockedException
745
-	 */
746
-	public function rename($path1, $path2) {
747
-		$absolutePath1 = Filesystem::normalizePath($this->getAbsolutePath($path1));
748
-		$absolutePath2 = Filesystem::normalizePath($this->getAbsolutePath($path2));
749
-		$result = false;
750
-		if (
751
-			Filesystem::isValidPath($path2)
752
-			and Filesystem::isValidPath($path1)
753
-			and !Filesystem::isFileBlacklisted($path2)
754
-		) {
755
-			$path1 = $this->getRelativePath($absolutePath1);
756
-			$path2 = $this->getRelativePath($absolutePath2);
757
-			$exists = $this->file_exists($path2);
758
-
759
-			if ($path1 == null or $path2 == null) {
760
-				return false;
761
-			}
762
-
763
-			$this->lockFile($path1, ILockingProvider::LOCK_SHARED, true);
764
-			try {
765
-				$this->lockFile($path2, ILockingProvider::LOCK_SHARED, true);
766
-
767
-				$run = true;
768
-				if ($this->shouldEmitHooks($path1) && (Cache\Scanner::isPartialFile($path1) && !Cache\Scanner::isPartialFile($path2))) {
769
-					// if it was a rename from a part file to a regular file it was a write and not a rename operation
770
-					$this->emit_file_hooks_pre($exists, $path2, $run);
771
-				} elseif ($this->shouldEmitHooks($path1)) {
772
-					\OC_Hook::emit(
773
-						Filesystem::CLASSNAME, Filesystem::signal_rename,
774
-						[
775
-							Filesystem::signal_param_oldpath => $this->getHookPath($path1),
776
-							Filesystem::signal_param_newpath => $this->getHookPath($path2),
777
-							Filesystem::signal_param_run => &$run
778
-						]
779
-					);
780
-				}
781
-				if ($run) {
782
-					$this->verifyPath(dirname($path2), basename($path2));
783
-
784
-					$manager = Filesystem::getMountManager();
785
-					$mount1 = $this->getMount($path1);
786
-					$mount2 = $this->getMount($path2);
787
-					$storage1 = $mount1->getStorage();
788
-					$storage2 = $mount2->getStorage();
789
-					$internalPath1 = $mount1->getInternalPath($absolutePath1);
790
-					$internalPath2 = $mount2->getInternalPath($absolutePath2);
791
-
792
-					$this->changeLock($path1, ILockingProvider::LOCK_EXCLUSIVE, true);
793
-					try {
794
-						$this->changeLock($path2, ILockingProvider::LOCK_EXCLUSIVE, true);
795
-
796
-						if ($internalPath1 === '') {
797
-							if ($mount1 instanceof MoveableMount) {
798
-								$sourceParentMount = $this->getMount(dirname($path1));
799
-								if ($sourceParentMount === $mount2 && $this->targetIsNotShared($storage2, $internalPath2)) {
800
-									/**
801
-									 * @var \OC\Files\Mount\MountPoint | \OC\Files\Mount\MoveableMount $mount1
802
-									 */
803
-									$sourceMountPoint = $mount1->getMountPoint();
804
-									$result = $mount1->moveMount($absolutePath2);
805
-									$manager->moveMount($sourceMountPoint, $mount1->getMountPoint());
806
-								} else {
807
-									$result = false;
808
-								}
809
-							} else {
810
-								$result = false;
811
-							}
812
-							// moving a file/folder within the same mount point
813
-						} elseif ($storage1 === $storage2) {
814
-							if ($storage1) {
815
-								$result = $storage1->rename($internalPath1, $internalPath2);
816
-							} else {
817
-								$result = false;
818
-							}
819
-							// moving a file/folder between storages (from $storage1 to $storage2)
820
-						} else {
821
-							$result = $storage2->moveFromStorage($storage1, $internalPath1, $internalPath2);
822
-						}
823
-
824
-						if ((Cache\Scanner::isPartialFile($path1) && !Cache\Scanner::isPartialFile($path2)) && $result !== false) {
825
-							// if it was a rename from a part file to a regular file it was a write and not a rename operation
826
-							$this->writeUpdate($storage2, $internalPath2);
827
-						} else if ($result) {
828
-							if ($internalPath1 !== '') { // don't do a cache update for moved mounts
829
-								$this->renameUpdate($storage1, $storage2, $internalPath1, $internalPath2);
830
-							}
831
-						}
832
-					} catch(\Exception $e) {
833
-						throw $e;
834
-					} finally {
835
-						$this->changeLock($path1, ILockingProvider::LOCK_SHARED, true);
836
-						$this->changeLock($path2, ILockingProvider::LOCK_SHARED, true);
837
-					}
838
-
839
-					if ((Cache\Scanner::isPartialFile($path1) && !Cache\Scanner::isPartialFile($path2)) && $result !== false) {
840
-						if ($this->shouldEmitHooks()) {
841
-							$this->emit_file_hooks_post($exists, $path2);
842
-						}
843
-					} elseif ($result) {
844
-						if ($this->shouldEmitHooks($path1) and $this->shouldEmitHooks($path2)) {
845
-							\OC_Hook::emit(
846
-								Filesystem::CLASSNAME,
847
-								Filesystem::signal_post_rename,
848
-								[
849
-									Filesystem::signal_param_oldpath => $this->getHookPath($path1),
850
-									Filesystem::signal_param_newpath => $this->getHookPath($path2)
851
-								]
852
-							);
853
-						}
854
-					}
855
-				}
856
-			} catch(\Exception $e) {
857
-				throw $e;
858
-			} finally {
859
-				$this->unlockFile($path1, ILockingProvider::LOCK_SHARED, true);
860
-				$this->unlockFile($path2, ILockingProvider::LOCK_SHARED, true);
861
-			}
862
-		}
863
-		return $result;
864
-	}
865
-
866
-	/**
867
-	 * Copy a file/folder from the source path to target path
868
-	 *
869
-	 * @param string $path1 source path
870
-	 * @param string $path2 target path
871
-	 * @param bool $preserveMtime whether to preserve mtime on the copy
872
-	 *
873
-	 * @return bool|mixed
874
-	 */
875
-	public function copy($path1, $path2, $preserveMtime = false) {
876
-		$absolutePath1 = Filesystem::normalizePath($this->getAbsolutePath($path1));
877
-		$absolutePath2 = Filesystem::normalizePath($this->getAbsolutePath($path2));
878
-		$result = false;
879
-		if (
880
-			Filesystem::isValidPath($path2)
881
-			and Filesystem::isValidPath($path1)
882
-			and !Filesystem::isFileBlacklisted($path2)
883
-		) {
884
-			$path1 = $this->getRelativePath($absolutePath1);
885
-			$path2 = $this->getRelativePath($absolutePath2);
886
-
887
-			if ($path1 == null or $path2 == null) {
888
-				return false;
889
-			}
890
-			$run = true;
891
-
892
-			$this->lockFile($path2, ILockingProvider::LOCK_SHARED);
893
-			$this->lockFile($path1, ILockingProvider::LOCK_SHARED);
894
-			$lockTypePath1 = ILockingProvider::LOCK_SHARED;
895
-			$lockTypePath2 = ILockingProvider::LOCK_SHARED;
896
-
897
-			try {
898
-
899
-				$exists = $this->file_exists($path2);
900
-				if ($this->shouldEmitHooks()) {
901
-					\OC_Hook::emit(
902
-						Filesystem::CLASSNAME,
903
-						Filesystem::signal_copy,
904
-						[
905
-							Filesystem::signal_param_oldpath => $this->getHookPath($path1),
906
-							Filesystem::signal_param_newpath => $this->getHookPath($path2),
907
-							Filesystem::signal_param_run => &$run
908
-						]
909
-					);
910
-					$this->emit_file_hooks_pre($exists, $path2, $run);
911
-				}
912
-				if ($run) {
913
-					$mount1 = $this->getMount($path1);
914
-					$mount2 = $this->getMount($path2);
915
-					$storage1 = $mount1->getStorage();
916
-					$internalPath1 = $mount1->getInternalPath($absolutePath1);
917
-					$storage2 = $mount2->getStorage();
918
-					$internalPath2 = $mount2->getInternalPath($absolutePath2);
919
-
920
-					$this->changeLock($path2, ILockingProvider::LOCK_EXCLUSIVE);
921
-					$lockTypePath2 = ILockingProvider::LOCK_EXCLUSIVE;
922
-
923
-					if ($mount1->getMountPoint() == $mount2->getMountPoint()) {
924
-						if ($storage1) {
925
-							$result = $storage1->copy($internalPath1, $internalPath2);
926
-						} else {
927
-							$result = false;
928
-						}
929
-					} else {
930
-						$result = $storage2->copyFromStorage($storage1, $internalPath1, $internalPath2);
931
-					}
932
-
933
-					$this->writeUpdate($storage2, $internalPath2);
934
-
935
-					$this->changeLock($path2, ILockingProvider::LOCK_SHARED);
936
-					$lockTypePath2 = ILockingProvider::LOCK_SHARED;
937
-
938
-					if ($this->shouldEmitHooks() && $result !== false) {
939
-						\OC_Hook::emit(
940
-							Filesystem::CLASSNAME,
941
-							Filesystem::signal_post_copy,
942
-							[
943
-								Filesystem::signal_param_oldpath => $this->getHookPath($path1),
944
-								Filesystem::signal_param_newpath => $this->getHookPath($path2)
945
-							]
946
-						);
947
-						$this->emit_file_hooks_post($exists, $path2);
948
-					}
949
-
950
-				}
951
-			} catch (\Exception $e) {
952
-				$this->unlockFile($path2, $lockTypePath2);
953
-				$this->unlockFile($path1, $lockTypePath1);
954
-				throw $e;
955
-			}
956
-
957
-			$this->unlockFile($path2, $lockTypePath2);
958
-			$this->unlockFile($path1, $lockTypePath1);
959
-
960
-		}
961
-		return $result;
962
-	}
963
-
964
-	/**
965
-	 * @param string $path
966
-	 * @param string $mode 'r' or 'w'
967
-	 * @return resource
968
-	 * @throws LockedException
969
-	 */
970
-	public function fopen($path, $mode) {
971
-		$mode = str_replace('b', '', $mode); // the binary flag is a windows only feature which we do not support
972
-		$hooks = [];
973
-		switch ($mode) {
974
-			case 'r':
975
-				$hooks[] = 'read';
976
-				break;
977
-			case 'r+':
978
-			case 'w+':
979
-			case 'x+':
980
-			case 'a+':
981
-				$hooks[] = 'read';
982
-				$hooks[] = 'write';
983
-				break;
984
-			case 'w':
985
-			case 'x':
986
-			case 'a':
987
-				$hooks[] = 'write';
988
-				break;
989
-			default:
990
-				\OCP\Util::writeLog('core', 'invalid mode (' . $mode . ') for ' . $path, ILogger::ERROR);
991
-		}
992
-
993
-		if ($mode !== 'r' && $mode !== 'w') {
994
-			\OC::$server->getLogger()->info('Trying to open a file with a mode other than "r" or "w" can cause severe performance issues with some backends');
995
-		}
996
-
997
-		return $this->basicOperation('fopen', $path, $hooks, $mode);
998
-	}
999
-
1000
-	/**
1001
-	 * @param string $path
1002
-	 * @return bool|string
1003
-	 * @throws \OCP\Files\InvalidPathException
1004
-	 */
1005
-	public function toTmpFile($path) {
1006
-		$this->assertPathLength($path);
1007
-		if (Filesystem::isValidPath($path)) {
1008
-			$source = $this->fopen($path, 'r');
1009
-			if ($source) {
1010
-				$extension = pathinfo($path, PATHINFO_EXTENSION);
1011
-				$tmpFile = \OC::$server->getTempManager()->getTemporaryFile($extension);
1012
-				file_put_contents($tmpFile, $source);
1013
-				return $tmpFile;
1014
-			} else {
1015
-				return false;
1016
-			}
1017
-		} else {
1018
-			return false;
1019
-		}
1020
-	}
1021
-
1022
-	/**
1023
-	 * @param string $tmpFile
1024
-	 * @param string $path
1025
-	 * @return bool|mixed
1026
-	 * @throws \OCP\Files\InvalidPathException
1027
-	 */
1028
-	public function fromTmpFile($tmpFile, $path) {
1029
-		$this->assertPathLength($path);
1030
-		if (Filesystem::isValidPath($path)) {
1031
-
1032
-			// Get directory that the file is going into
1033
-			$filePath = dirname($path);
1034
-
1035
-			// Create the directories if any
1036
-			if (!$this->file_exists($filePath)) {
1037
-				$result = $this->createParentDirectories($filePath);
1038
-				if ($result === false) {
1039
-					return false;
1040
-				}
1041
-			}
1042
-
1043
-			$source = fopen($tmpFile, 'r');
1044
-			if ($source) {
1045
-				$result = $this->file_put_contents($path, $source);
1046
-				// $this->file_put_contents() might have already closed
1047
-				// the resource, so we check it, before trying to close it
1048
-				// to avoid messages in the error log.
1049
-				if (is_resource($source)) {
1050
-					fclose($source);
1051
-				}
1052
-				unlink($tmpFile);
1053
-				return $result;
1054
-			} else {
1055
-				return false;
1056
-			}
1057
-		} else {
1058
-			return false;
1059
-		}
1060
-	}
1061
-
1062
-
1063
-	/**
1064
-	 * @param string $path
1065
-	 * @return mixed
1066
-	 * @throws \OCP\Files\InvalidPathException
1067
-	 */
1068
-	public function getMimeType($path) {
1069
-		$this->assertPathLength($path);
1070
-		return $this->basicOperation('getMimeType', $path);
1071
-	}
1072
-
1073
-	/**
1074
-	 * @param string $type
1075
-	 * @param string $path
1076
-	 * @param bool $raw
1077
-	 * @return bool|null|string
1078
-	 */
1079
-	public function hash($type, $path, $raw = false) {
1080
-		$postFix = (substr($path, -1) === '/') ? '/' : '';
1081
-		$absolutePath = Filesystem::normalizePath($this->getAbsolutePath($path));
1082
-		if (Filesystem::isValidPath($path)) {
1083
-			$path = $this->getRelativePath($absolutePath);
1084
-			if ($path == null) {
1085
-				return false;
1086
-			}
1087
-			if ($this->shouldEmitHooks($path)) {
1088
-				\OC_Hook::emit(
1089
-					Filesystem::CLASSNAME,
1090
-					Filesystem::signal_read,
1091
-					[Filesystem::signal_param_path => $this->getHookPath($path)]
1092
-				);
1093
-			}
1094
-			list($storage, $internalPath) = Filesystem::resolvePath($absolutePath . $postFix);
1095
-			if ($storage) {
1096
-				return $storage->hash($type, $internalPath, $raw);
1097
-			}
1098
-		}
1099
-		return null;
1100
-	}
1101
-
1102
-	/**
1103
-	 * @param string $path
1104
-	 * @return mixed
1105
-	 * @throws \OCP\Files\InvalidPathException
1106
-	 */
1107
-	public function free_space($path = '/') {
1108
-		$this->assertPathLength($path);
1109
-		$result = $this->basicOperation('free_space', $path);
1110
-		if ($result === null) {
1111
-			throw new InvalidPathException();
1112
-		}
1113
-		return $result;
1114
-	}
1115
-
1116
-	/**
1117
-	 * abstraction layer for basic filesystem functions: wrapper for \OC\Files\Storage\Storage
1118
-	 *
1119
-	 * @param string $operation
1120
-	 * @param string $path
1121
-	 * @param array $hooks (optional)
1122
-	 * @param mixed $extraParam (optional)
1123
-	 * @return mixed
1124
-	 * @throws LockedException
1125
-	 *
1126
-	 * This method takes requests for basic filesystem functions (e.g. reading & writing
1127
-	 * files), processes hooks and proxies, sanitises paths, and finally passes them on to
1128
-	 * \OC\Files\Storage\Storage for delegation to a storage backend for execution
1129
-	 */
1130
-	private function basicOperation($operation, $path, $hooks = [], $extraParam = null) {
1131
-		$postFix = (substr($path, -1) === '/') ? '/' : '';
1132
-		$absolutePath = Filesystem::normalizePath($this->getAbsolutePath($path));
1133
-		if (Filesystem::isValidPath($path)
1134
-			and !Filesystem::isFileBlacklisted($path)
1135
-		) {
1136
-			$path = $this->getRelativePath($absolutePath);
1137
-			if ($path == null) {
1138
-				return false;
1139
-			}
1140
-
1141
-			if (in_array('write', $hooks) || in_array('delete', $hooks) || in_array('read', $hooks)) {
1142
-				// always a shared lock during pre-hooks so the hook can read the file
1143
-				$this->lockFile($path, ILockingProvider::LOCK_SHARED);
1144
-			}
1145
-
1146
-			$run = $this->runHooks($hooks, $path);
1147
-			/** @var \OC\Files\Storage\Storage $storage */
1148
-			list($storage, $internalPath) = Filesystem::resolvePath($absolutePath . $postFix);
1149
-			if ($run and $storage) {
1150
-				if (in_array('write', $hooks) || in_array('delete', $hooks)) {
1151
-					try {
1152
-						$this->changeLock($path, ILockingProvider::LOCK_EXCLUSIVE);
1153
-					} catch (LockedException $e) {
1154
-						// release the shared lock we acquired before quiting
1155
-						$this->unlockFile($path, ILockingProvider::LOCK_SHARED);
1156
-						throw $e;
1157
-					}
1158
-				}
1159
-				try {
1160
-					if (!is_null($extraParam)) {
1161
-						$result = $storage->$operation($internalPath, $extraParam);
1162
-					} else {
1163
-						$result = $storage->$operation($internalPath);
1164
-					}
1165
-				} catch (\Exception $e) {
1166
-					if (in_array('write', $hooks) || in_array('delete', $hooks)) {
1167
-						$this->unlockFile($path, ILockingProvider::LOCK_EXCLUSIVE);
1168
-					} else if (in_array('read', $hooks)) {
1169
-						$this->unlockFile($path, ILockingProvider::LOCK_SHARED);
1170
-					}
1171
-					throw $e;
1172
-				}
1173
-
1174
-				if ($result && in_array('delete', $hooks) and $result) {
1175
-					$this->removeUpdate($storage, $internalPath);
1176
-				}
1177
-				if ($result && in_array('write', $hooks,  true) && $operation !== 'fopen' && $operation !== 'touch') {
1178
-					$this->writeUpdate($storage, $internalPath);
1179
-				}
1180
-				if ($result && in_array('touch', $hooks)) {
1181
-					$this->writeUpdate($storage, $internalPath, $extraParam);
1182
-				}
1183
-
1184
-				if ((in_array('write', $hooks) || in_array('delete', $hooks)) && ($operation !== 'fopen' || $result === false)) {
1185
-					$this->changeLock($path, ILockingProvider::LOCK_SHARED);
1186
-				}
1187
-
1188
-				$unlockLater = false;
1189
-				if ($this->lockingEnabled && $operation === 'fopen' && is_resource($result)) {
1190
-					$unlockLater = true;
1191
-					// make sure our unlocking callback will still be called if connection is aborted
1192
-					ignore_user_abort(true);
1193
-					$result = CallbackWrapper::wrap($result, null, null, function () use ($hooks, $path) {
1194
-						if (in_array('write', $hooks)) {
1195
-							$this->unlockFile($path, ILockingProvider::LOCK_EXCLUSIVE);
1196
-						} else if (in_array('read', $hooks)) {
1197
-							$this->unlockFile($path, ILockingProvider::LOCK_SHARED);
1198
-						}
1199
-					});
1200
-				}
1201
-
1202
-				if ($this->shouldEmitHooks($path) && $result !== false) {
1203
-					if ($operation != 'fopen') { //no post hooks for fopen, the file stream is still open
1204
-						$this->runHooks($hooks, $path, true);
1205
-					}
1206
-				}
1207
-
1208
-				if (!$unlockLater
1209
-					&& (in_array('write', $hooks) || in_array('delete', $hooks) || in_array('read', $hooks))
1210
-				) {
1211
-					$this->unlockFile($path, ILockingProvider::LOCK_SHARED);
1212
-				}
1213
-				return $result;
1214
-			} else {
1215
-				$this->unlockFile($path, ILockingProvider::LOCK_SHARED);
1216
-			}
1217
-		}
1218
-		return null;
1219
-	}
1220
-
1221
-	/**
1222
-	 * get the path relative to the default root for hook usage
1223
-	 *
1224
-	 * @param string $path
1225
-	 * @return string
1226
-	 */
1227
-	private function getHookPath($path) {
1228
-		if (!Filesystem::getView()) {
1229
-			return $path;
1230
-		}
1231
-		return Filesystem::getView()->getRelativePath($this->getAbsolutePath($path));
1232
-	}
1233
-
1234
-	private function shouldEmitHooks($path = '') {
1235
-		if ($path && Cache\Scanner::isPartialFile($path)) {
1236
-			return false;
1237
-		}
1238
-		if (!Filesystem::$loaded) {
1239
-			return false;
1240
-		}
1241
-		$defaultRoot = Filesystem::getRoot();
1242
-		if ($defaultRoot === null) {
1243
-			return false;
1244
-		}
1245
-		if ($this->fakeRoot === $defaultRoot) {
1246
-			return true;
1247
-		}
1248
-		$fullPath = $this->getAbsolutePath($path);
1249
-
1250
-		if ($fullPath === $defaultRoot) {
1251
-			return true;
1252
-		}
1253
-
1254
-		return (strlen($fullPath) > strlen($defaultRoot)) && (substr($fullPath, 0, strlen($defaultRoot) + 1) === $defaultRoot . '/');
1255
-	}
1256
-
1257
-	/**
1258
-	 * @param string[] $hooks
1259
-	 * @param string $path
1260
-	 * @param bool $post
1261
-	 * @return bool
1262
-	 */
1263
-	private function runHooks($hooks, $path, $post = false) {
1264
-		$relativePath = $path;
1265
-		$path = $this->getHookPath($path);
1266
-		$prefix = $post ? 'post_' : '';
1267
-		$run = true;
1268
-		if ($this->shouldEmitHooks($relativePath)) {
1269
-			foreach ($hooks as $hook) {
1270
-				if ($hook != 'read') {
1271
-					\OC_Hook::emit(
1272
-						Filesystem::CLASSNAME,
1273
-						$prefix . $hook,
1274
-						[
1275
-							Filesystem::signal_param_run => &$run,
1276
-							Filesystem::signal_param_path => $path
1277
-						]
1278
-					);
1279
-				} elseif (!$post) {
1280
-					\OC_Hook::emit(
1281
-						Filesystem::CLASSNAME,
1282
-						$prefix . $hook,
1283
-						[
1284
-							Filesystem::signal_param_path => $path
1285
-						]
1286
-					);
1287
-				}
1288
-			}
1289
-		}
1290
-		return $run;
1291
-	}
1292
-
1293
-	/**
1294
-	 * check if a file or folder has been updated since $time
1295
-	 *
1296
-	 * @param string $path
1297
-	 * @param int $time
1298
-	 * @return bool
1299
-	 */
1300
-	public function hasUpdated($path, $time) {
1301
-		return $this->basicOperation('hasUpdated', $path, [], $time);
1302
-	}
1303
-
1304
-	/**
1305
-	 * @param string $ownerId
1306
-	 * @return \OC\User\User
1307
-	 */
1308
-	private function getUserObjectForOwner($ownerId) {
1309
-		$owner = $this->userManager->get($ownerId);
1310
-		if ($owner instanceof IUser) {
1311
-			return $owner;
1312
-		} else {
1313
-			return new User($ownerId, null, \OC::$server->getEventDispatcher());
1314
-		}
1315
-	}
1316
-
1317
-	/**
1318
-	 * Get file info from cache
1319
-	 *
1320
-	 * If the file is not in cached it will be scanned
1321
-	 * If the file has changed on storage the cache will be updated
1322
-	 *
1323
-	 * @param \OC\Files\Storage\Storage $storage
1324
-	 * @param string $internalPath
1325
-	 * @param string $relativePath
1326
-	 * @return ICacheEntry|bool
1327
-	 */
1328
-	private function getCacheEntry($storage, $internalPath, $relativePath) {
1329
-		$cache = $storage->getCache($internalPath);
1330
-		$data = $cache->get($internalPath);
1331
-		$watcher = $storage->getWatcher($internalPath);
1332
-
1333
-		try {
1334
-			// if the file is not in the cache or needs to be updated, trigger the scanner and reload the data
1335
-			if (!$data || $data['size'] === -1) {
1336
-				if (!$storage->file_exists($internalPath)) {
1337
-					return false;
1338
-				}
1339
-				// don't need to get a lock here since the scanner does it's own locking
1340
-				$scanner = $storage->getScanner($internalPath);
1341
-				$scanner->scan($internalPath, Cache\Scanner::SCAN_SHALLOW);
1342
-				$data = $cache->get($internalPath);
1343
-			} else if (!Cache\Scanner::isPartialFile($internalPath) && $watcher->needsUpdate($internalPath, $data)) {
1344
-				$this->lockFile($relativePath, ILockingProvider::LOCK_SHARED);
1345
-				$watcher->update($internalPath, $data);
1346
-				$storage->getPropagator()->propagateChange($internalPath, time());
1347
-				$data = $cache->get($internalPath);
1348
-				$this->unlockFile($relativePath, ILockingProvider::LOCK_SHARED);
1349
-			}
1350
-		} catch (LockedException $e) {
1351
-			// if the file is locked we just use the old cache info
1352
-		}
1353
-
1354
-		return $data;
1355
-	}
1356
-
1357
-	/**
1358
-	 * get the filesystem info
1359
-	 *
1360
-	 * @param string $path
1361
-	 * @param boolean|string $includeMountPoints true to add mountpoint sizes,
1362
-	 * 'ext' to add only ext storage mount point sizes. Defaults to true.
1363
-	 * defaults to true
1364
-	 * @return \OC\Files\FileInfo|false False if file does not exist
1365
-	 */
1366
-	public function getFileInfo($path, $includeMountPoints = true) {
1367
-		$this->assertPathLength($path);
1368
-		if (!Filesystem::isValidPath($path)) {
1369
-			return false;
1370
-		}
1371
-		if (Cache\Scanner::isPartialFile($path)) {
1372
-			return $this->getPartFileInfo($path);
1373
-		}
1374
-		$relativePath = $path;
1375
-		$path = Filesystem::normalizePath($this->fakeRoot . '/' . $path);
1376
-
1377
-		$mount = Filesystem::getMountManager()->find($path);
1378
-		if (!$mount) {
1379
-			\OC::$server->getLogger()->warning('Mountpoint not found for path: ' . $path);
1380
-			return false;
1381
-		}
1382
-		$storage = $mount->getStorage();
1383
-		$internalPath = $mount->getInternalPath($path);
1384
-		if ($storage) {
1385
-			$data = $this->getCacheEntry($storage, $internalPath, $relativePath);
1386
-
1387
-			if (!$data instanceof ICacheEntry) {
1388
-				return false;
1389
-			}
1390
-
1391
-			if ($mount instanceof MoveableMount && $internalPath === '') {
1392
-				$data['permissions'] |= \OCP\Constants::PERMISSION_DELETE;
1393
-			}
1394
-			$ownerId = $storage->getOwner($internalPath);
1395
-			$owner = null;
1396
-			if ($ownerId !== null && $ownerId !== false) {
1397
-				// ownerId might be null if files are accessed with an access token without file system access
1398
-				$owner = $this->getUserObjectForOwner($ownerId);
1399
-			}
1400
-			$info = new FileInfo($path, $storage, $internalPath, $data, $mount, $owner);
1401
-
1402
-			if ($data and isset($data['fileid'])) {
1403
-				if ($includeMountPoints and $data['mimetype'] === 'httpd/unix-directory') {
1404
-					//add the sizes of other mount points to the folder
1405
-					$extOnly = ($includeMountPoints === 'ext');
1406
-					$mounts = Filesystem::getMountManager()->findIn($path);
1407
-					$info->setSubMounts(array_filter($mounts, function (IMountPoint $mount) use ($extOnly) {
1408
-						$subStorage = $mount->getStorage();
1409
-						return !($extOnly && $subStorage instanceof \OCA\Files_Sharing\SharedStorage);
1410
-					}));
1411
-				}
1412
-			}
1413
-
1414
-			return $info;
1415
-		} else {
1416
-			\OC::$server->getLogger()->warning('Storage not valid for mountpoint: ' . $mount->getMountPoint());
1417
-		}
1418
-
1419
-		return false;
1420
-	}
1421
-
1422
-	/**
1423
-	 * get the content of a directory
1424
-	 *
1425
-	 * @param string $directory path under datadirectory
1426
-	 * @param string $mimetype_filter limit returned content to this mimetype or mimepart
1427
-	 * @return FileInfo[]
1428
-	 */
1429
-	public function getDirectoryContent($directory, $mimetype_filter = '') {
1430
-		$this->assertPathLength($directory);
1431
-		if (!Filesystem::isValidPath($directory)) {
1432
-			return [];
1433
-		}
1434
-		$path = $this->getAbsolutePath($directory);
1435
-		$path = Filesystem::normalizePath($path);
1436
-		$mount = $this->getMount($directory);
1437
-		if (!$mount) {
1438
-			return [];
1439
-		}
1440
-		$storage = $mount->getStorage();
1441
-		$internalPath = $mount->getInternalPath($path);
1442
-		if ($storage) {
1443
-			$cache = $storage->getCache($internalPath);
1444
-			$user = \OC_User::getUser();
1445
-
1446
-			$data = $this->getCacheEntry($storage, $internalPath, $directory);
1447
-
1448
-			if (!$data instanceof ICacheEntry || !isset($data['fileid']) || !($data->getPermissions() && Constants::PERMISSION_READ)) {
1449
-				return [];
1450
-			}
1451
-
1452
-			$folderId = $data['fileid'];
1453
-			$contents = $cache->getFolderContentsById($folderId); //TODO: mimetype_filter
1454
-
1455
-			$sharingDisabled = \OCP\Util::isSharingDisabledForUser();
1456
-
1457
-			$fileNames = array_map(function (ICacheEntry $content) {
1458
-				return $content->getName();
1459
-			}, $contents);
1460
-			/**
1461
-			 * @var \OC\Files\FileInfo[] $fileInfos
1462
-			 */
1463
-			$fileInfos = array_map(function (ICacheEntry $content) use ($path, $storage, $mount, $sharingDisabled) {
1464
-				if ($sharingDisabled) {
1465
-					$content['permissions'] = $content['permissions'] & ~\OCP\Constants::PERMISSION_SHARE;
1466
-				}
1467
-				$owner = $this->getUserObjectForOwner($storage->getOwner($content['path']));
1468
-				return new FileInfo($path . '/' . $content['name'], $storage, $content['path'], $content, $mount, $owner);
1469
-			}, $contents);
1470
-			$files = array_combine($fileNames, $fileInfos);
1471
-
1472
-			//add a folder for any mountpoint in this directory and add the sizes of other mountpoints to the folders
1473
-			$mounts = Filesystem::getMountManager()->findIn($path);
1474
-			$dirLength = strlen($path);
1475
-			foreach ($mounts as $mount) {
1476
-				$mountPoint = $mount->getMountPoint();
1477
-				$subStorage = $mount->getStorage();
1478
-				if ($subStorage) {
1479
-					$subCache = $subStorage->getCache('');
1480
-
1481
-					$rootEntry = $subCache->get('');
1482
-					if (!$rootEntry) {
1483
-						$subScanner = $subStorage->getScanner('');
1484
-						try {
1485
-							$subScanner->scanFile('');
1486
-						} catch (\OCP\Files\StorageNotAvailableException $e) {
1487
-							continue;
1488
-						} catch (\OCP\Files\StorageInvalidException $e) {
1489
-							continue;
1490
-						} catch (\Exception $e) {
1491
-							// sometimes when the storage is not available it can be any exception
1492
-							\OC::$server->getLogger()->logException($e, [
1493
-								'message' => 'Exception while scanning storage "' . $subStorage->getId() . '"',
1494
-								'level' => ILogger::ERROR,
1495
-								'app' => 'lib',
1496
-							]);
1497
-							continue;
1498
-						}
1499
-						$rootEntry = $subCache->get('');
1500
-					}
1501
-
1502
-					if ($rootEntry && ($rootEntry->getPermissions() && Constants::PERMISSION_READ)) {
1503
-						$relativePath = trim(substr($mountPoint, $dirLength), '/');
1504
-						if ($pos = strpos($relativePath, '/')) {
1505
-							//mountpoint inside subfolder add size to the correct folder
1506
-							$entryName = substr($relativePath, 0, $pos);
1507
-							foreach ($files as &$entry) {
1508
-								if ($entry->getName() === $entryName) {
1509
-									$entry->addSubEntry($rootEntry, $mountPoint);
1510
-								}
1511
-							}
1512
-						} else { //mountpoint in this folder, add an entry for it
1513
-							$rootEntry['name'] = $relativePath;
1514
-							$rootEntry['type'] = $rootEntry['mimetype'] === 'httpd/unix-directory' ? 'dir' : 'file';
1515
-							$permissions = $rootEntry['permissions'];
1516
-							// do not allow renaming/deleting the mount point if they are not shared files/folders
1517
-							// for shared files/folders we use the permissions given by the owner
1518
-							if ($mount instanceof MoveableMount) {
1519
-								$rootEntry['permissions'] = $permissions | \OCP\Constants::PERMISSION_UPDATE | \OCP\Constants::PERMISSION_DELETE;
1520
-							} else {
1521
-								$rootEntry['permissions'] = $permissions & (\OCP\Constants::PERMISSION_ALL - (\OCP\Constants::PERMISSION_UPDATE | \OCP\Constants::PERMISSION_DELETE));
1522
-							}
1523
-
1524
-							$rootEntry['path'] = substr(Filesystem::normalizePath($path . '/' . $rootEntry['name']), strlen($user) + 2); // full path without /$user/
1525
-
1526
-							// if sharing was disabled for the user we remove the share permissions
1527
-							if (\OCP\Util::isSharingDisabledForUser()) {
1528
-								$rootEntry['permissions'] = $rootEntry['permissions'] & ~\OCP\Constants::PERMISSION_SHARE;
1529
-							}
1530
-
1531
-							$owner = $this->getUserObjectForOwner($subStorage->getOwner(''));
1532
-							$files[$rootEntry->getName()] = new FileInfo($path . '/' . $rootEntry['name'], $subStorage, '', $rootEntry, $mount, $owner);
1533
-						}
1534
-					}
1535
-				}
1536
-			}
1537
-
1538
-			if ($mimetype_filter) {
1539
-				$files = array_filter($files, function (FileInfo $file) use ($mimetype_filter) {
1540
-					if (strpos($mimetype_filter, '/')) {
1541
-						return $file->getMimetype() === $mimetype_filter;
1542
-					} else {
1543
-						return $file->getMimePart() === $mimetype_filter;
1544
-					}
1545
-				});
1546
-			}
1547
-
1548
-			return array_values($files);
1549
-		} else {
1550
-			return [];
1551
-		}
1552
-	}
1553
-
1554
-	/**
1555
-	 * change file metadata
1556
-	 *
1557
-	 * @param string $path
1558
-	 * @param array|\OCP\Files\FileInfo $data
1559
-	 * @return int
1560
-	 *
1561
-	 * returns the fileid of the updated file
1562
-	 */
1563
-	public function putFileInfo($path, $data) {
1564
-		$this->assertPathLength($path);
1565
-		if ($data instanceof FileInfo) {
1566
-			$data = $data->getData();
1567
-		}
1568
-		$path = Filesystem::normalizePath($this->fakeRoot . '/' . $path);
1569
-		/**
1570
-		 * @var \OC\Files\Storage\Storage $storage
1571
-		 * @var string $internalPath
1572
-		 */
1573
-		list($storage, $internalPath) = Filesystem::resolvePath($path);
1574
-		if ($storage) {
1575
-			$cache = $storage->getCache($path);
1576
-
1577
-			if (!$cache->inCache($internalPath)) {
1578
-				$scanner = $storage->getScanner($internalPath);
1579
-				$scanner->scan($internalPath, Cache\Scanner::SCAN_SHALLOW);
1580
-			}
1581
-
1582
-			return $cache->put($internalPath, $data);
1583
-		} else {
1584
-			return -1;
1585
-		}
1586
-	}
1587
-
1588
-	/**
1589
-	 * search for files with the name matching $query
1590
-	 *
1591
-	 * @param string $query
1592
-	 * @return FileInfo[]
1593
-	 */
1594
-	public function search($query) {
1595
-		return $this->searchCommon('search', ['%' . $query . '%']);
1596
-	}
1597
-
1598
-	/**
1599
-	 * search for files with the name matching $query
1600
-	 *
1601
-	 * @param string $query
1602
-	 * @return FileInfo[]
1603
-	 */
1604
-	public function searchRaw($query) {
1605
-		return $this->searchCommon('search', [$query]);
1606
-	}
1607
-
1608
-	/**
1609
-	 * search for files by mimetype
1610
-	 *
1611
-	 * @param string $mimetype
1612
-	 * @return FileInfo[]
1613
-	 */
1614
-	public function searchByMime($mimetype) {
1615
-		return $this->searchCommon('searchByMime', [$mimetype]);
1616
-	}
1617
-
1618
-	/**
1619
-	 * search for files by tag
1620
-	 *
1621
-	 * @param string|int $tag name or tag id
1622
-	 * @param string $userId owner of the tags
1623
-	 * @return FileInfo[]
1624
-	 */
1625
-	public function searchByTag($tag, $userId) {
1626
-		return $this->searchCommon('searchByTag', [$tag, $userId]);
1627
-	}
1628
-
1629
-	/**
1630
-	 * @param string $method cache method
1631
-	 * @param array $args
1632
-	 * @return FileInfo[]
1633
-	 */
1634
-	private function searchCommon($method, $args) {
1635
-		$files = [];
1636
-		$rootLength = strlen($this->fakeRoot);
1637
-
1638
-		$mount = $this->getMount('');
1639
-		$mountPoint = $mount->getMountPoint();
1640
-		$storage = $mount->getStorage();
1641
-		if ($storage) {
1642
-			$cache = $storage->getCache('');
1643
-
1644
-			$results = call_user_func_array([$cache, $method], $args);
1645
-			foreach ($results as $result) {
1646
-				if (substr($mountPoint . $result['path'], 0, $rootLength + 1) === $this->fakeRoot . '/') {
1647
-					$internalPath = $result['path'];
1648
-					$path = $mountPoint . $result['path'];
1649
-					$result['path'] = substr($mountPoint . $result['path'], $rootLength);
1650
-					$owner = \OC::$server->getUserManager()->get($storage->getOwner($internalPath));
1651
-					$files[] = new FileInfo($path, $storage, $internalPath, $result, $mount, $owner);
1652
-				}
1653
-			}
1654
-
1655
-			$mounts = Filesystem::getMountManager()->findIn($this->fakeRoot);
1656
-			foreach ($mounts as $mount) {
1657
-				$mountPoint = $mount->getMountPoint();
1658
-				$storage = $mount->getStorage();
1659
-				if ($storage) {
1660
-					$cache = $storage->getCache('');
1661
-
1662
-					$relativeMountPoint = substr($mountPoint, $rootLength);
1663
-					$results = call_user_func_array([$cache, $method], $args);
1664
-					if ($results) {
1665
-						foreach ($results as $result) {
1666
-							$internalPath = $result['path'];
1667
-							$result['path'] = rtrim($relativeMountPoint . $result['path'], '/');
1668
-							$path = rtrim($mountPoint . $internalPath, '/');
1669
-							$owner = \OC::$server->getUserManager()->get($storage->getOwner($internalPath));
1670
-							$files[] = new FileInfo($path, $storage, $internalPath, $result, $mount, $owner);
1671
-						}
1672
-					}
1673
-				}
1674
-			}
1675
-		}
1676
-		return $files;
1677
-	}
1678
-
1679
-	/**
1680
-	 * Get the owner for a file or folder
1681
-	 *
1682
-	 * @param string $path
1683
-	 * @return string the user id of the owner
1684
-	 * @throws NotFoundException
1685
-	 */
1686
-	public function getOwner($path) {
1687
-		$info = $this->getFileInfo($path);
1688
-		if (!$info) {
1689
-			throw new NotFoundException($path . ' not found while trying to get owner');
1690
-		}
1691
-
1692
-		if ($info->getOwner() === null) {
1693
-			throw new NotFoundException($path . ' has no owner');
1694
-		}
1695
-
1696
-		return $info->getOwner()->getUID();
1697
-	}
1698
-
1699
-	/**
1700
-	 * get the ETag for a file or folder
1701
-	 *
1702
-	 * @param string $path
1703
-	 * @return string
1704
-	 */
1705
-	public function getETag($path) {
1706
-		/**
1707
-		 * @var Storage\Storage $storage
1708
-		 * @var string $internalPath
1709
-		 */
1710
-		list($storage, $internalPath) = $this->resolvePath($path);
1711
-		if ($storage) {
1712
-			return $storage->getETag($internalPath);
1713
-		} else {
1714
-			return null;
1715
-		}
1716
-	}
1717
-
1718
-	/**
1719
-	 * Get the path of a file by id, relative to the view
1720
-	 *
1721
-	 * Note that the resulting path is not guarantied to be unique for the id, multiple paths can point to the same file
1722
-	 *
1723
-	 * @param int $id
1724
-	 * @throws NotFoundException
1725
-	 * @return string
1726
-	 */
1727
-	public function getPath($id) {
1728
-		$id = (int)$id;
1729
-		$manager = Filesystem::getMountManager();
1730
-		$mounts = $manager->findIn($this->fakeRoot);
1731
-		$mounts[] = $manager->find($this->fakeRoot);
1732
-		// reverse the array so we start with the storage this view is in
1733
-		// which is the most likely to contain the file we're looking for
1734
-		$mounts = array_reverse($mounts);
1735
-
1736
-		// put non shared mounts in front of the shared mount
1737
-		// this prevent unneeded recursion into shares
1738
-		usort($mounts, function (IMountPoint $a, IMountPoint $b) {
1739
-			return $a instanceof SharedMount && (!$b instanceof SharedMount) ? 1 : -1;
1740
-		});
1741
-
1742
-		foreach ($mounts as $mount) {
1743
-			/**
1744
-			 * @var \OC\Files\Mount\MountPoint $mount
1745
-			 */
1746
-			if ($mount->getStorage()) {
1747
-				$cache = $mount->getStorage()->getCache();
1748
-				$internalPath = $cache->getPathById($id);
1749
-				if (is_string($internalPath)) {
1750
-					$fullPath = $mount->getMountPoint() . $internalPath;
1751
-					if (!is_null($path = $this->getRelativePath($fullPath))) {
1752
-						return $path;
1753
-					}
1754
-				}
1755
-			}
1756
-		}
1757
-		throw new NotFoundException(sprintf('File with id "%s" has not been found.', $id));
1758
-	}
1759
-
1760
-	/**
1761
-	 * @param string $path
1762
-	 * @throws InvalidPathException
1763
-	 */
1764
-	private function assertPathLength($path) {
1765
-		$maxLen = min(PHP_MAXPATHLEN, 4000);
1766
-		// Check for the string length - performed using isset() instead of strlen()
1767
-		// because isset() is about 5x-40x faster.
1768
-		if (isset($path[$maxLen])) {
1769
-			$pathLen = strlen($path);
1770
-			throw new \OCP\Files\InvalidPathException("Path length($pathLen) exceeds max path length($maxLen): $path");
1771
-		}
1772
-	}
1773
-
1774
-	/**
1775
-	 * check if it is allowed to move a mount point to a given target.
1776
-	 * It is not allowed to move a mount point into a different mount point or
1777
-	 * into an already shared folder
1778
-	 *
1779
-	 * @param IStorage $targetStorage
1780
-	 * @param string $targetInternalPath
1781
-	 * @return boolean
1782
-	 */
1783
-	private function targetIsNotShared(IStorage $targetStorage, string $targetInternalPath) {
1784
-
1785
-		// note: cannot use the view because the target is already locked
1786
-		$fileId = (int)$targetStorage->getCache()->getId($targetInternalPath);
1787
-		if ($fileId === -1) {
1788
-			// target might not exist, need to check parent instead
1789
-			$fileId = (int)$targetStorage->getCache()->getId(dirname($targetInternalPath));
1790
-		}
1791
-
1792
-		// check if any of the parents were shared by the current owner (include collections)
1793
-		$shares = \OCP\Share::getItemShared(
1794
-			'folder',
1795
-			$fileId,
1796
-			\OCP\Share::FORMAT_NONE,
1797
-			null,
1798
-			true
1799
-		);
1800
-
1801
-		if (count($shares) > 0) {
1802
-			\OCP\Util::writeLog('files',
1803
-				'It is not allowed to move one mount point into a shared folder',
1804
-				ILogger::DEBUG);
1805
-			return false;
1806
-		}
1807
-
1808
-		return true;
1809
-	}
1810
-
1811
-	/**
1812
-	 * Get a fileinfo object for files that are ignored in the cache (part files)
1813
-	 *
1814
-	 * @param string $path
1815
-	 * @return \OCP\Files\FileInfo
1816
-	 */
1817
-	private function getPartFileInfo($path) {
1818
-		$mount = $this->getMount($path);
1819
-		$storage = $mount->getStorage();
1820
-		$internalPath = $mount->getInternalPath($this->getAbsolutePath($path));
1821
-		$owner = \OC::$server->getUserManager()->get($storage->getOwner($internalPath));
1822
-		return new FileInfo(
1823
-			$this->getAbsolutePath($path),
1824
-			$storage,
1825
-			$internalPath,
1826
-			[
1827
-				'fileid' => null,
1828
-				'mimetype' => $storage->getMimeType($internalPath),
1829
-				'name' => basename($path),
1830
-				'etag' => null,
1831
-				'size' => $storage->filesize($internalPath),
1832
-				'mtime' => $storage->filemtime($internalPath),
1833
-				'encrypted' => false,
1834
-				'permissions' => \OCP\Constants::PERMISSION_ALL
1835
-			],
1836
-			$mount,
1837
-			$owner
1838
-		);
1839
-	}
1840
-
1841
-	/**
1842
-	 * @param string $path
1843
-	 * @param string $fileName
1844
-	 * @throws InvalidPathException
1845
-	 */
1846
-	public function verifyPath($path, $fileName) {
1847
-		try {
1848
-			/** @type \OCP\Files\Storage $storage */
1849
-			list($storage, $internalPath) = $this->resolvePath($path);
1850
-			$storage->verifyPath($internalPath, $fileName);
1851
-		} catch (ReservedWordException $ex) {
1852
-			$l = \OC::$server->getL10N('lib');
1853
-			throw new InvalidPathException($l->t('File name is a reserved word'));
1854
-		} catch (InvalidCharacterInPathException $ex) {
1855
-			$l = \OC::$server->getL10N('lib');
1856
-			throw new InvalidPathException($l->t('File name contains at least one invalid character'));
1857
-		} catch (FileNameTooLongException $ex) {
1858
-			$l = \OC::$server->getL10N('lib');
1859
-			throw new InvalidPathException($l->t('File name is too long'));
1860
-		} catch (InvalidDirectoryException $ex) {
1861
-			$l = \OC::$server->getL10N('lib');
1862
-			throw new InvalidPathException($l->t('Dot files are not allowed'));
1863
-		} catch (EmptyFileNameException $ex) {
1864
-			$l = \OC::$server->getL10N('lib');
1865
-			throw new InvalidPathException($l->t('Empty filename is not allowed'));
1866
-		}
1867
-	}
1868
-
1869
-	/**
1870
-	 * get all parent folders of $path
1871
-	 *
1872
-	 * @param string $path
1873
-	 * @return string[]
1874
-	 */
1875
-	private function getParents($path) {
1876
-		$path = trim($path, '/');
1877
-		if (!$path) {
1878
-			return [];
1879
-		}
1880
-
1881
-		$parts = explode('/', $path);
1882
-
1883
-		// remove the single file
1884
-		array_pop($parts);
1885
-		$result = ['/'];
1886
-		$resultPath = '';
1887
-		foreach ($parts as $part) {
1888
-			if ($part) {
1889
-				$resultPath .= '/' . $part;
1890
-				$result[] = $resultPath;
1891
-			}
1892
-		}
1893
-		return $result;
1894
-	}
1895
-
1896
-	/**
1897
-	 * Returns the mount point for which to lock
1898
-	 *
1899
-	 * @param string $absolutePath absolute path
1900
-	 * @param bool $useParentMount true to return parent mount instead of whatever
1901
-	 * is mounted directly on the given path, false otherwise
1902
-	 * @return \OC\Files\Mount\MountPoint mount point for which to apply locks
1903
-	 */
1904
-	private function getMountForLock($absolutePath, $useParentMount = false) {
1905
-		$results = [];
1906
-		$mount = Filesystem::getMountManager()->find($absolutePath);
1907
-		if (!$mount) {
1908
-			return $results;
1909
-		}
1910
-
1911
-		if ($useParentMount) {
1912
-			// find out if something is mounted directly on the path
1913
-			$internalPath = $mount->getInternalPath($absolutePath);
1914
-			if ($internalPath === '') {
1915
-				// resolve the parent mount instead
1916
-				$mount = Filesystem::getMountManager()->find(dirname($absolutePath));
1917
-			}
1918
-		}
1919
-
1920
-		return $mount;
1921
-	}
1922
-
1923
-	/**
1924
-	 * Lock the given path
1925
-	 *
1926
-	 * @param string $path the path of the file to lock, relative to the view
1927
-	 * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
1928
-	 * @param bool $lockMountPoint true to lock the mount point, false to lock the attached mount/storage
1929
-	 *
1930
-	 * @return bool False if the path is excluded from locking, true otherwise
1931
-	 * @throws LockedException if the path is already locked
1932
-	 */
1933
-	private function lockPath($path, $type, $lockMountPoint = false) {
1934
-		$absolutePath = $this->getAbsolutePath($path);
1935
-		$absolutePath = Filesystem::normalizePath($absolutePath);
1936
-		if (!$this->shouldLockFile($absolutePath)) {
1937
-			return false;
1938
-		}
1939
-
1940
-		$mount = $this->getMountForLock($absolutePath, $lockMountPoint);
1941
-		if ($mount) {
1942
-			try {
1943
-				$storage = $mount->getStorage();
1944
-				if ($storage && $storage->instanceOfStorage('\OCP\Files\Storage\ILockingStorage')) {
1945
-					$storage->acquireLock(
1946
-						$mount->getInternalPath($absolutePath),
1947
-						$type,
1948
-						$this->lockingProvider
1949
-					);
1950
-				}
1951
-			} catch (LockedException $e) {
1952
-				// rethrow with the a human-readable path
1953
-				throw new LockedException(
1954
-					$this->getPathRelativeToFiles($absolutePath),
1955
-					$e,
1956
-					$e->getExistingLock()
1957
-				);
1958
-			}
1959
-		}
1960
-
1961
-		return true;
1962
-	}
1963
-
1964
-	/**
1965
-	 * Change the lock type
1966
-	 *
1967
-	 * @param string $path the path of the file to lock, relative to the view
1968
-	 * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
1969
-	 * @param bool $lockMountPoint true to lock the mount point, false to lock the attached mount/storage
1970
-	 *
1971
-	 * @return bool False if the path is excluded from locking, true otherwise
1972
-	 * @throws LockedException if the path is already locked
1973
-	 */
1974
-	public function changeLock($path, $type, $lockMountPoint = false) {
1975
-		$path = Filesystem::normalizePath($path);
1976
-		$absolutePath = $this->getAbsolutePath($path);
1977
-		$absolutePath = Filesystem::normalizePath($absolutePath);
1978
-		if (!$this->shouldLockFile($absolutePath)) {
1979
-			return false;
1980
-		}
1981
-
1982
-		$mount = $this->getMountForLock($absolutePath, $lockMountPoint);
1983
-		if ($mount) {
1984
-			try {
1985
-				$storage = $mount->getStorage();
1986
-				if ($storage && $storage->instanceOfStorage('\OCP\Files\Storage\ILockingStorage')) {
1987
-					$storage->changeLock(
1988
-						$mount->getInternalPath($absolutePath),
1989
-						$type,
1990
-						$this->lockingProvider
1991
-					);
1992
-				}
1993
-			} catch (LockedException $e) {
1994
-				try {
1995
-					// rethrow with the a human-readable path
1996
-					throw new LockedException(
1997
-						$this->getPathRelativeToFiles($absolutePath),
1998
-						$e,
1999
-						$e->getExistingLock()
2000
-					);
2001
-				} catch (\InvalidArgumentException $ex) {
2002
-					throw new LockedException(
2003
-						$absolutePath,
2004
-						$ex,
2005
-						$e->getExistingLock()
2006
-					);
2007
-				}
2008
-			}
2009
-		}
2010
-
2011
-		return true;
2012
-	}
2013
-
2014
-	/**
2015
-	 * Unlock the given path
2016
-	 *
2017
-	 * @param string $path the path of the file to unlock, relative to the view
2018
-	 * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
2019
-	 * @param bool $lockMountPoint true to lock the mount point, false to lock the attached mount/storage
2020
-	 *
2021
-	 * @return bool False if the path is excluded from locking, true otherwise
2022
-	 * @throws LockedException
2023
-	 */
2024
-	private function unlockPath($path, $type, $lockMountPoint = false) {
2025
-		$absolutePath = $this->getAbsolutePath($path);
2026
-		$absolutePath = Filesystem::normalizePath($absolutePath);
2027
-		if (!$this->shouldLockFile($absolutePath)) {
2028
-			return false;
2029
-		}
2030
-
2031
-		$mount = $this->getMountForLock($absolutePath, $lockMountPoint);
2032
-		if ($mount) {
2033
-			$storage = $mount->getStorage();
2034
-			if ($storage && $storage->instanceOfStorage('\OCP\Files\Storage\ILockingStorage')) {
2035
-				$storage->releaseLock(
2036
-					$mount->getInternalPath($absolutePath),
2037
-					$type,
2038
-					$this->lockingProvider
2039
-				);
2040
-			}
2041
-		}
2042
-
2043
-		return true;
2044
-	}
2045
-
2046
-	/**
2047
-	 * Lock a path and all its parents up to the root of the view
2048
-	 *
2049
-	 * @param string $path the path of the file to lock relative to the view
2050
-	 * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
2051
-	 * @param bool $lockMountPoint true to lock the mount point, false to lock the attached mount/storage
2052
-	 *
2053
-	 * @return bool False if the path is excluded from locking, true otherwise
2054
-	 * @throws LockedException
2055
-	 */
2056
-	public function lockFile($path, $type, $lockMountPoint = false) {
2057
-		$absolutePath = $this->getAbsolutePath($path);
2058
-		$absolutePath = Filesystem::normalizePath($absolutePath);
2059
-		if (!$this->shouldLockFile($absolutePath)) {
2060
-			return false;
2061
-		}
2062
-
2063
-		$this->lockPath($path, $type, $lockMountPoint);
2064
-
2065
-		$parents = $this->getParents($path);
2066
-		foreach ($parents as $parent) {
2067
-			$this->lockPath($parent, ILockingProvider::LOCK_SHARED);
2068
-		}
2069
-
2070
-		return true;
2071
-	}
2072
-
2073
-	/**
2074
-	 * Unlock a path and all its parents up to the root of the view
2075
-	 *
2076
-	 * @param string $path the path of the file to lock relative to the view
2077
-	 * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
2078
-	 * @param bool $lockMountPoint true to lock the mount point, false to lock the attached mount/storage
2079
-	 *
2080
-	 * @return bool False if the path is excluded from locking, true otherwise
2081
-	 * @throws LockedException
2082
-	 */
2083
-	public function unlockFile($path, $type, $lockMountPoint = false) {
2084
-		$absolutePath = $this->getAbsolutePath($path);
2085
-		$absolutePath = Filesystem::normalizePath($absolutePath);
2086
-		if (!$this->shouldLockFile($absolutePath)) {
2087
-			return false;
2088
-		}
2089
-
2090
-		$this->unlockPath($path, $type, $lockMountPoint);
2091
-
2092
-		$parents = $this->getParents($path);
2093
-		foreach ($parents as $parent) {
2094
-			$this->unlockPath($parent, ILockingProvider::LOCK_SHARED);
2095
-		}
2096
-
2097
-		return true;
2098
-	}
2099
-
2100
-	/**
2101
-	 * Only lock files in data/user/files/
2102
-	 *
2103
-	 * @param string $path Absolute path to the file/folder we try to (un)lock
2104
-	 * @return bool
2105
-	 */
2106
-	protected function shouldLockFile($path) {
2107
-		$path = Filesystem::normalizePath($path);
2108
-
2109
-		$pathSegments = explode('/', $path);
2110
-		if (isset($pathSegments[2])) {
2111
-			// E.g.: /username/files/path-to-file
2112
-			return ($pathSegments[2] === 'files') && (count($pathSegments) > 3);
2113
-		}
2114
-
2115
-		return strpos($path, '/appdata_') !== 0;
2116
-	}
2117
-
2118
-	/**
2119
-	 * Shortens the given absolute path to be relative to
2120
-	 * "$user/files".
2121
-	 *
2122
-	 * @param string $absolutePath absolute path which is under "files"
2123
-	 *
2124
-	 * @return string path relative to "files" with trimmed slashes or null
2125
-	 * if the path was NOT relative to files
2126
-	 *
2127
-	 * @throws \InvalidArgumentException if the given path was not under "files"
2128
-	 * @since 8.1.0
2129
-	 */
2130
-	public function getPathRelativeToFiles($absolutePath) {
2131
-		$path = Filesystem::normalizePath($absolutePath);
2132
-		$parts = explode('/', trim($path, '/'), 3);
2133
-		// "$user", "files", "path/to/dir"
2134
-		if (!isset($parts[1]) || $parts[1] !== 'files') {
2135
-			$this->logger->error(
2136
-				'$absolutePath must be relative to "files", value is "%s"',
2137
-				[
2138
-					$absolutePath
2139
-				]
2140
-			);
2141
-			throw new \InvalidArgumentException('$absolutePath must be relative to "files"');
2142
-		}
2143
-		if (isset($parts[2])) {
2144
-			return $parts[2];
2145
-		}
2146
-		return '';
2147
-	}
2148
-
2149
-	/**
2150
-	 * @param string $filename
2151
-	 * @return array
2152
-	 * @throws \OC\User\NoUserException
2153
-	 * @throws NotFoundException
2154
-	 */
2155
-	public function getUidAndFilename($filename) {
2156
-		$info = $this->getFileInfo($filename);
2157
-		if (!$info instanceof \OCP\Files\FileInfo) {
2158
-			throw new NotFoundException($this->getAbsolutePath($filename) . ' not found');
2159
-		}
2160
-		$uid = $info->getOwner()->getUID();
2161
-		if ($uid != \OCP\User::getUser()) {
2162
-			Filesystem::initMountPoints($uid);
2163
-			$ownerView = new View('/' . $uid . '/files');
2164
-			try {
2165
-				$filename = $ownerView->getPath($info['fileid']);
2166
-			} catch (NotFoundException $e) {
2167
-				throw new NotFoundException('File with id ' . $info['fileid'] . ' not found for user ' . $uid);
2168
-			}
2169
-		}
2170
-		return [$uid, $filename];
2171
-	}
2172
-
2173
-	/**
2174
-	 * Creates parent non-existing folders
2175
-	 *
2176
-	 * @param string $filePath
2177
-	 * @return bool
2178
-	 */
2179
-	private function createParentDirectories($filePath) {
2180
-		$directoryParts = explode('/', $filePath);
2181
-		$directoryParts = array_filter($directoryParts);
2182
-		foreach ($directoryParts as $key => $part) {
2183
-			$currentPathElements = array_slice($directoryParts, 0, $key);
2184
-			$currentPath = '/' . implode('/', $currentPathElements);
2185
-			if ($this->is_file($currentPath)) {
2186
-				return false;
2187
-			}
2188
-			if (!$this->file_exists($currentPath)) {
2189
-				$this->mkdir($currentPath);
2190
-			}
2191
-		}
2192
-
2193
-		return true;
2194
-	}
86
+    /** @var string */
87
+    private $fakeRoot = '';
88
+
89
+    /**
90
+     * @var \OCP\Lock\ILockingProvider
91
+     */
92
+    protected $lockingProvider;
93
+
94
+    private $lockingEnabled;
95
+
96
+    private $updaterEnabled = true;
97
+
98
+    /** @var \OC\User\Manager */
99
+    private $userManager;
100
+
101
+    /** @var \OCP\ILogger */
102
+    private $logger;
103
+
104
+    /**
105
+     * @param string $root
106
+     * @throws \Exception If $root contains an invalid path
107
+     */
108
+    public function __construct($root = '') {
109
+        if (is_null($root)) {
110
+            throw new \InvalidArgumentException('Root can\'t be null');
111
+        }
112
+        if (!Filesystem::isValidPath($root)) {
113
+            throw new \Exception();
114
+        }
115
+
116
+        $this->fakeRoot = $root;
117
+        $this->lockingProvider = \OC::$server->getLockingProvider();
118
+        $this->lockingEnabled = !($this->lockingProvider instanceof \OC\Lock\NoopLockingProvider);
119
+        $this->userManager = \OC::$server->getUserManager();
120
+        $this->logger = \OC::$server->getLogger();
121
+    }
122
+
123
+    public function getAbsolutePath($path = '/') {
124
+        if ($path === null) {
125
+            return null;
126
+        }
127
+        $this->assertPathLength($path);
128
+        if ($path === '') {
129
+            $path = '/';
130
+        }
131
+        if ($path[0] !== '/') {
132
+            $path = '/' . $path;
133
+        }
134
+        return $this->fakeRoot . $path;
135
+    }
136
+
137
+    /**
138
+     * change the root to a fake root
139
+     *
140
+     * @param string $fakeRoot
141
+     * @return boolean|null
142
+     */
143
+    public function chroot($fakeRoot) {
144
+        if (!$fakeRoot == '') {
145
+            if ($fakeRoot[0] !== '/') {
146
+                $fakeRoot = '/' . $fakeRoot;
147
+            }
148
+        }
149
+        $this->fakeRoot = $fakeRoot;
150
+    }
151
+
152
+    /**
153
+     * get the fake root
154
+     *
155
+     * @return string
156
+     */
157
+    public function getRoot() {
158
+        return $this->fakeRoot;
159
+    }
160
+
161
+    /**
162
+     * get path relative to the root of the view
163
+     *
164
+     * @param string $path
165
+     * @return string
166
+     */
167
+    public function getRelativePath($path) {
168
+        $this->assertPathLength($path);
169
+        if ($this->fakeRoot == '') {
170
+            return $path;
171
+        }
172
+
173
+        if (rtrim($path, '/') === rtrim($this->fakeRoot, '/')) {
174
+            return '/';
175
+        }
176
+
177
+        // missing slashes can cause wrong matches!
178
+        $root = rtrim($this->fakeRoot, '/') . '/';
179
+
180
+        if (strpos($path, $root) !== 0) {
181
+            return null;
182
+        } else {
183
+            $path = substr($path, strlen($this->fakeRoot));
184
+            if (strlen($path) === 0) {
185
+                return '/';
186
+            } else {
187
+                return $path;
188
+            }
189
+        }
190
+    }
191
+
192
+    /**
193
+     * get the mountpoint of the storage object for a path
194
+     * ( note: because a storage is not always mounted inside the fakeroot, the
195
+     * returned mountpoint is relative to the absolute root of the filesystem
196
+     * and does not take the chroot into account )
197
+     *
198
+     * @param string $path
199
+     * @return string
200
+     */
201
+    public function getMountPoint($path) {
202
+        return Filesystem::getMountPoint($this->getAbsolutePath($path));
203
+    }
204
+
205
+    /**
206
+     * get the mountpoint of the storage object for a path
207
+     * ( note: because a storage is not always mounted inside the fakeroot, the
208
+     * returned mountpoint is relative to the absolute root of the filesystem
209
+     * and does not take the chroot into account )
210
+     *
211
+     * @param string $path
212
+     * @return \OCP\Files\Mount\IMountPoint
213
+     */
214
+    public function getMount($path) {
215
+        return Filesystem::getMountManager()->find($this->getAbsolutePath($path));
216
+    }
217
+
218
+    /**
219
+     * resolve a path to a storage and internal path
220
+     *
221
+     * @param string $path
222
+     * @return array an array consisting of the storage and the internal path
223
+     */
224
+    public function resolvePath($path) {
225
+        $a = $this->getAbsolutePath($path);
226
+        $p = Filesystem::normalizePath($a);
227
+        return Filesystem::resolvePath($p);
228
+    }
229
+
230
+    /**
231
+     * return the path to a local version of the file
232
+     * we need this because we can't know if a file is stored local or not from
233
+     * outside the filestorage and for some purposes a local file is needed
234
+     *
235
+     * @param string $path
236
+     * @return string
237
+     */
238
+    public function getLocalFile($path) {
239
+        $parent = substr($path, 0, strrpos($path, '/'));
240
+        $path = $this->getAbsolutePath($path);
241
+        list($storage, $internalPath) = Filesystem::resolvePath($path);
242
+        if (Filesystem::isValidPath($parent) and $storage) {
243
+            return $storage->getLocalFile($internalPath);
244
+        } else {
245
+            return null;
246
+        }
247
+    }
248
+
249
+    /**
250
+     * @param string $path
251
+     * @return string
252
+     */
253
+    public function getLocalFolder($path) {
254
+        $parent = substr($path, 0, strrpos($path, '/'));
255
+        $path = $this->getAbsolutePath($path);
256
+        list($storage, $internalPath) = Filesystem::resolvePath($path);
257
+        if (Filesystem::isValidPath($parent) and $storage) {
258
+            return $storage->getLocalFolder($internalPath);
259
+        } else {
260
+            return null;
261
+        }
262
+    }
263
+
264
+    /**
265
+     * the following functions operate with arguments and return values identical
266
+     * to those of their PHP built-in equivalents. Mostly they are merely wrappers
267
+     * for \OC\Files\Storage\Storage via basicOperation().
268
+     */
269
+    public function mkdir($path) {
270
+        return $this->basicOperation('mkdir', $path, ['create', 'write']);
271
+    }
272
+
273
+    /**
274
+     * remove mount point
275
+     *
276
+     * @param \OC\Files\Mount\MoveableMount $mount
277
+     * @param string $path relative to data/
278
+     * @return boolean
279
+     */
280
+    protected function removeMount($mount, $path) {
281
+        if ($mount instanceof MoveableMount) {
282
+            // cut of /user/files to get the relative path to data/user/files
283
+            $pathParts = explode('/', $path, 4);
284
+            $relPath = '/' . $pathParts[3];
285
+            $this->lockFile($relPath, ILockingProvider::LOCK_SHARED, true);
286
+            \OC_Hook::emit(
287
+                Filesystem::CLASSNAME, "umount",
288
+                [Filesystem::signal_param_path => $relPath]
289
+            );
290
+            $this->changeLock($relPath, ILockingProvider::LOCK_EXCLUSIVE, true);
291
+            $result = $mount->removeMount();
292
+            $this->changeLock($relPath, ILockingProvider::LOCK_SHARED, true);
293
+            if ($result) {
294
+                \OC_Hook::emit(
295
+                    Filesystem::CLASSNAME, "post_umount",
296
+                    [Filesystem::signal_param_path => $relPath]
297
+                );
298
+            }
299
+            $this->unlockFile($relPath, ILockingProvider::LOCK_SHARED, true);
300
+            return $result;
301
+        } else {
302
+            // do not allow deleting the storage's root / the mount point
303
+            // because for some storages it might delete the whole contents
304
+            // but isn't supposed to work that way
305
+            return false;
306
+        }
307
+    }
308
+
309
+    public function disableCacheUpdate() {
310
+        $this->updaterEnabled = false;
311
+    }
312
+
313
+    public function enableCacheUpdate() {
314
+        $this->updaterEnabled = true;
315
+    }
316
+
317
+    protected function writeUpdate(Storage $storage, $internalPath, $time = null) {
318
+        if ($this->updaterEnabled) {
319
+            if (is_null($time)) {
320
+                $time = time();
321
+            }
322
+            $storage->getUpdater()->update($internalPath, $time);
323
+        }
324
+    }
325
+
326
+    protected function removeUpdate(Storage $storage, $internalPath) {
327
+        if ($this->updaterEnabled) {
328
+            $storage->getUpdater()->remove($internalPath);
329
+        }
330
+    }
331
+
332
+    protected function renameUpdate(Storage $sourceStorage, Storage $targetStorage, $sourceInternalPath, $targetInternalPath) {
333
+        if ($this->updaterEnabled) {
334
+            $targetStorage->getUpdater()->renameFromStorage($sourceStorage, $sourceInternalPath, $targetInternalPath);
335
+        }
336
+    }
337
+
338
+    /**
339
+     * @param string $path
340
+     * @return bool|mixed
341
+     */
342
+    public function rmdir($path) {
343
+        $absolutePath = $this->getAbsolutePath($path);
344
+        $mount = Filesystem::getMountManager()->find($absolutePath);
345
+        if ($mount->getInternalPath($absolutePath) === '') {
346
+            return $this->removeMount($mount, $absolutePath);
347
+        }
348
+        if ($this->is_dir($path)) {
349
+            $result = $this->basicOperation('rmdir', $path, ['delete']);
350
+        } else {
351
+            $result = false;
352
+        }
353
+
354
+        if (!$result && !$this->file_exists($path)) { //clear ghost files from the cache on delete
355
+            $storage = $mount->getStorage();
356
+            $internalPath = $mount->getInternalPath($absolutePath);
357
+            $storage->getUpdater()->remove($internalPath);
358
+        }
359
+        return $result;
360
+    }
361
+
362
+    /**
363
+     * @param string $path
364
+     * @return resource
365
+     */
366
+    public function opendir($path) {
367
+        return $this->basicOperation('opendir', $path, ['read']);
368
+    }
369
+
370
+    /**
371
+     * @param string $path
372
+     * @return bool|mixed
373
+     */
374
+    public function is_dir($path) {
375
+        if ($path == '/') {
376
+            return true;
377
+        }
378
+        return $this->basicOperation('is_dir', $path);
379
+    }
380
+
381
+    /**
382
+     * @param string $path
383
+     * @return bool|mixed
384
+     */
385
+    public function is_file($path) {
386
+        if ($path == '/') {
387
+            return false;
388
+        }
389
+        return $this->basicOperation('is_file', $path);
390
+    }
391
+
392
+    /**
393
+     * @param string $path
394
+     * @return mixed
395
+     */
396
+    public function stat($path) {
397
+        return $this->basicOperation('stat', $path);
398
+    }
399
+
400
+    /**
401
+     * @param string $path
402
+     * @return mixed
403
+     */
404
+    public function filetype($path) {
405
+        return $this->basicOperation('filetype', $path);
406
+    }
407
+
408
+    /**
409
+     * @param string $path
410
+     * @return mixed
411
+     */
412
+    public function filesize($path) {
413
+        return $this->basicOperation('filesize', $path);
414
+    }
415
+
416
+    /**
417
+     * @param string $path
418
+     * @return bool|mixed
419
+     * @throws \OCP\Files\InvalidPathException
420
+     */
421
+    public function readfile($path) {
422
+        $this->assertPathLength($path);
423
+        @ob_end_clean();
424
+        $handle = $this->fopen($path, 'rb');
425
+        if ($handle) {
426
+            $chunkSize = 8192; // 8 kB chunks
427
+            while (!feof($handle)) {
428
+                echo fread($handle, $chunkSize);
429
+                flush();
430
+            }
431
+            fclose($handle);
432
+            return $this->filesize($path);
433
+        }
434
+        return false;
435
+    }
436
+
437
+    /**
438
+     * @param string $path
439
+     * @param int $from
440
+     * @param int $to
441
+     * @return bool|mixed
442
+     * @throws \OCP\Files\InvalidPathException
443
+     * @throws \OCP\Files\UnseekableException
444
+     */
445
+    public function readfilePart($path, $from, $to) {
446
+        $this->assertPathLength($path);
447
+        @ob_end_clean();
448
+        $handle = $this->fopen($path, 'rb');
449
+        if ($handle) {
450
+            $chunkSize = 8192; // 8 kB chunks
451
+            $startReading = true;
452
+
453
+            if ($from !== 0 && $from !== '0' && fseek($handle, $from) !== 0) {
454
+                // forward file handle via chunked fread because fseek seem to have failed
455
+
456
+                $end = $from + 1;
457
+                while (!feof($handle) && ftell($handle) < $end) {
458
+                    $len = $from - ftell($handle);
459
+                    if ($len > $chunkSize) {
460
+                        $len = $chunkSize;
461
+                    }
462
+                    $result = fread($handle, $len);
463
+
464
+                    if ($result === false) {
465
+                        $startReading = false;
466
+                        break;
467
+                    }
468
+                }
469
+            }
470
+
471
+            if ($startReading) {
472
+                $end = $to + 1;
473
+                while (!feof($handle) && ftell($handle) < $end) {
474
+                    $len = $end - ftell($handle);
475
+                    if ($len > $chunkSize) {
476
+                        $len = $chunkSize;
477
+                    }
478
+                    echo fread($handle, $len);
479
+                    flush();
480
+                }
481
+                return ftell($handle) - $from;
482
+            }
483
+
484
+            throw new \OCP\Files\UnseekableException('fseek error');
485
+        }
486
+        return false;
487
+    }
488
+
489
+    /**
490
+     * @param string $path
491
+     * @return mixed
492
+     */
493
+    public function isCreatable($path) {
494
+        return $this->basicOperation('isCreatable', $path);
495
+    }
496
+
497
+    /**
498
+     * @param string $path
499
+     * @return mixed
500
+     */
501
+    public function isReadable($path) {
502
+        return $this->basicOperation('isReadable', $path);
503
+    }
504
+
505
+    /**
506
+     * @param string $path
507
+     * @return mixed
508
+     */
509
+    public function isUpdatable($path) {
510
+        return $this->basicOperation('isUpdatable', $path);
511
+    }
512
+
513
+    /**
514
+     * @param string $path
515
+     * @return bool|mixed
516
+     */
517
+    public function isDeletable($path) {
518
+        $absolutePath = $this->getAbsolutePath($path);
519
+        $mount = Filesystem::getMountManager()->find($absolutePath);
520
+        if ($mount->getInternalPath($absolutePath) === '') {
521
+            return $mount instanceof MoveableMount;
522
+        }
523
+        return $this->basicOperation('isDeletable', $path);
524
+    }
525
+
526
+    /**
527
+     * @param string $path
528
+     * @return mixed
529
+     */
530
+    public function isSharable($path) {
531
+        return $this->basicOperation('isSharable', $path);
532
+    }
533
+
534
+    /**
535
+     * @param string $path
536
+     * @return bool|mixed
537
+     */
538
+    public function file_exists($path) {
539
+        if ($path == '/') {
540
+            return true;
541
+        }
542
+        return $this->basicOperation('file_exists', $path);
543
+    }
544
+
545
+    /**
546
+     * @param string $path
547
+     * @return mixed
548
+     */
549
+    public function filemtime($path) {
550
+        return $this->basicOperation('filemtime', $path);
551
+    }
552
+
553
+    /**
554
+     * @param string $path
555
+     * @param int|string $mtime
556
+     * @return bool
557
+     */
558
+    public function touch($path, $mtime = null) {
559
+        if (!is_null($mtime) and !is_numeric($mtime)) {
560
+            $mtime = strtotime($mtime);
561
+        }
562
+
563
+        $hooks = ['touch'];
564
+
565
+        if (!$this->file_exists($path)) {
566
+            $hooks[] = 'create';
567
+            $hooks[] = 'write';
568
+        }
569
+        try {
570
+            $result = $this->basicOperation('touch', $path, $hooks, $mtime);
571
+        } catch (\Exception $e) {
572
+            $this->logger->logException($e, ['level' => ILogger::INFO, 'message' => 'Error while setting modified time']);
573
+            $result = false;
574
+        }
575
+        if (!$result) {
576
+            // If create file fails because of permissions on external storage like SMB folders,
577
+            // check file exists and return false if not.
578
+            if (!$this->file_exists($path)) {
579
+                return false;
580
+            }
581
+            if (is_null($mtime)) {
582
+                $mtime = time();
583
+            }
584
+            //if native touch fails, we emulate it by changing the mtime in the cache
585
+            $this->putFileInfo($path, ['mtime' => floor($mtime)]);
586
+        }
587
+        return true;
588
+    }
589
+
590
+    /**
591
+     * @param string $path
592
+     * @return mixed
593
+     * @throws LockedException
594
+     */
595
+    public function file_get_contents($path) {
596
+        return $this->basicOperation('file_get_contents', $path, ['read']);
597
+    }
598
+
599
+    /**
600
+     * @param bool $exists
601
+     * @param string $path
602
+     * @param bool $run
603
+     */
604
+    protected function emit_file_hooks_pre($exists, $path, &$run) {
605
+        if (!$exists) {
606
+            \OC_Hook::emit(Filesystem::CLASSNAME, Filesystem::signal_create, [
607
+                Filesystem::signal_param_path => $this->getHookPath($path),
608
+                Filesystem::signal_param_run => &$run,
609
+            ]);
610
+        } else {
611
+            \OC_Hook::emit(Filesystem::CLASSNAME, Filesystem::signal_update, [
612
+                Filesystem::signal_param_path => $this->getHookPath($path),
613
+                Filesystem::signal_param_run => &$run,
614
+            ]);
615
+        }
616
+        \OC_Hook::emit(Filesystem::CLASSNAME, Filesystem::signal_write, [
617
+            Filesystem::signal_param_path => $this->getHookPath($path),
618
+            Filesystem::signal_param_run => &$run,
619
+        ]);
620
+    }
621
+
622
+    /**
623
+     * @param bool $exists
624
+     * @param string $path
625
+     */
626
+    protected function emit_file_hooks_post($exists, $path) {
627
+        if (!$exists) {
628
+            \OC_Hook::emit(Filesystem::CLASSNAME, Filesystem::signal_post_create, [
629
+                Filesystem::signal_param_path => $this->getHookPath($path),
630
+            ]);
631
+        } else {
632
+            \OC_Hook::emit(Filesystem::CLASSNAME, Filesystem::signal_post_update, [
633
+                Filesystem::signal_param_path => $this->getHookPath($path),
634
+            ]);
635
+        }
636
+        \OC_Hook::emit(Filesystem::CLASSNAME, Filesystem::signal_post_write, [
637
+            Filesystem::signal_param_path => $this->getHookPath($path),
638
+        ]);
639
+    }
640
+
641
+    /**
642
+     * @param string $path
643
+     * @param string|resource $data
644
+     * @return bool|mixed
645
+     * @throws LockedException
646
+     */
647
+    public function file_put_contents($path, $data) {
648
+        if (is_resource($data)) { //not having to deal with streams in file_put_contents makes life easier
649
+            $absolutePath = Filesystem::normalizePath($this->getAbsolutePath($path));
650
+            if (Filesystem::isValidPath($path)
651
+                and !Filesystem::isFileBlacklisted($path)
652
+            ) {
653
+                $path = $this->getRelativePath($absolutePath);
654
+
655
+                $this->lockFile($path, ILockingProvider::LOCK_SHARED);
656
+
657
+                $exists = $this->file_exists($path);
658
+                $run = true;
659
+                if ($this->shouldEmitHooks($path)) {
660
+                    $this->emit_file_hooks_pre($exists, $path, $run);
661
+                }
662
+                if (!$run) {
663
+                    $this->unlockFile($path, ILockingProvider::LOCK_SHARED);
664
+                    return false;
665
+                }
666
+
667
+                $this->changeLock($path, ILockingProvider::LOCK_EXCLUSIVE);
668
+
669
+                /** @var \OC\Files\Storage\Storage $storage */
670
+                list($storage, $internalPath) = $this->resolvePath($path);
671
+                $target = $storage->fopen($internalPath, 'w');
672
+                if ($target) {
673
+                    list(, $result) = \OC_Helper::streamCopy($data, $target);
674
+                    fclose($target);
675
+                    fclose($data);
676
+
677
+                    $this->writeUpdate($storage, $internalPath);
678
+
679
+                    $this->changeLock($path, ILockingProvider::LOCK_SHARED);
680
+
681
+                    if ($this->shouldEmitHooks($path) && $result !== false) {
682
+                        $this->emit_file_hooks_post($exists, $path);
683
+                    }
684
+                    $this->unlockFile($path, ILockingProvider::LOCK_SHARED);
685
+                    return $result;
686
+                } else {
687
+                    $this->unlockFile($path, ILockingProvider::LOCK_EXCLUSIVE);
688
+                    return false;
689
+                }
690
+            } else {
691
+                return false;
692
+            }
693
+        } else {
694
+            $hooks = $this->file_exists($path) ? ['update', 'write'] : ['create', 'write'];
695
+            return $this->basicOperation('file_put_contents', $path, $hooks, $data);
696
+        }
697
+    }
698
+
699
+    /**
700
+     * @param string $path
701
+     * @return bool|mixed
702
+     */
703
+    public function unlink($path) {
704
+        if ($path === '' || $path === '/') {
705
+            // do not allow deleting the root
706
+            return false;
707
+        }
708
+        $postFix = (substr($path, -1) === '/') ? '/' : '';
709
+        $absolutePath = Filesystem::normalizePath($this->getAbsolutePath($path));
710
+        $mount = Filesystem::getMountManager()->find($absolutePath . $postFix);
711
+        if ($mount and $mount->getInternalPath($absolutePath) === '') {
712
+            return $this->removeMount($mount, $absolutePath);
713
+        }
714
+        if ($this->is_dir($path)) {
715
+            $result = $this->basicOperation('rmdir', $path, ['delete']);
716
+        } else {
717
+            $result = $this->basicOperation('unlink', $path, ['delete']);
718
+        }
719
+        if (!$result && !$this->file_exists($path)) { //clear ghost files from the cache on delete
720
+            $storage = $mount->getStorage();
721
+            $internalPath = $mount->getInternalPath($absolutePath);
722
+            $storage->getUpdater()->remove($internalPath);
723
+            return true;
724
+        } else {
725
+            return $result;
726
+        }
727
+    }
728
+
729
+    /**
730
+     * @param string $directory
731
+     * @return bool|mixed
732
+     */
733
+    public function deleteAll($directory) {
734
+        return $this->rmdir($directory);
735
+    }
736
+
737
+    /**
738
+     * Rename/move a file or folder from the source path to target path.
739
+     *
740
+     * @param string $path1 source path
741
+     * @param string $path2 target path
742
+     *
743
+     * @return bool|mixed
744
+     * @throws LockedException
745
+     */
746
+    public function rename($path1, $path2) {
747
+        $absolutePath1 = Filesystem::normalizePath($this->getAbsolutePath($path1));
748
+        $absolutePath2 = Filesystem::normalizePath($this->getAbsolutePath($path2));
749
+        $result = false;
750
+        if (
751
+            Filesystem::isValidPath($path2)
752
+            and Filesystem::isValidPath($path1)
753
+            and !Filesystem::isFileBlacklisted($path2)
754
+        ) {
755
+            $path1 = $this->getRelativePath($absolutePath1);
756
+            $path2 = $this->getRelativePath($absolutePath2);
757
+            $exists = $this->file_exists($path2);
758
+
759
+            if ($path1 == null or $path2 == null) {
760
+                return false;
761
+            }
762
+
763
+            $this->lockFile($path1, ILockingProvider::LOCK_SHARED, true);
764
+            try {
765
+                $this->lockFile($path2, ILockingProvider::LOCK_SHARED, true);
766
+
767
+                $run = true;
768
+                if ($this->shouldEmitHooks($path1) && (Cache\Scanner::isPartialFile($path1) && !Cache\Scanner::isPartialFile($path2))) {
769
+                    // if it was a rename from a part file to a regular file it was a write and not a rename operation
770
+                    $this->emit_file_hooks_pre($exists, $path2, $run);
771
+                } elseif ($this->shouldEmitHooks($path1)) {
772
+                    \OC_Hook::emit(
773
+                        Filesystem::CLASSNAME, Filesystem::signal_rename,
774
+                        [
775
+                            Filesystem::signal_param_oldpath => $this->getHookPath($path1),
776
+                            Filesystem::signal_param_newpath => $this->getHookPath($path2),
777
+                            Filesystem::signal_param_run => &$run
778
+                        ]
779
+                    );
780
+                }
781
+                if ($run) {
782
+                    $this->verifyPath(dirname($path2), basename($path2));
783
+
784
+                    $manager = Filesystem::getMountManager();
785
+                    $mount1 = $this->getMount($path1);
786
+                    $mount2 = $this->getMount($path2);
787
+                    $storage1 = $mount1->getStorage();
788
+                    $storage2 = $mount2->getStorage();
789
+                    $internalPath1 = $mount1->getInternalPath($absolutePath1);
790
+                    $internalPath2 = $mount2->getInternalPath($absolutePath2);
791
+
792
+                    $this->changeLock($path1, ILockingProvider::LOCK_EXCLUSIVE, true);
793
+                    try {
794
+                        $this->changeLock($path2, ILockingProvider::LOCK_EXCLUSIVE, true);
795
+
796
+                        if ($internalPath1 === '') {
797
+                            if ($mount1 instanceof MoveableMount) {
798
+                                $sourceParentMount = $this->getMount(dirname($path1));
799
+                                if ($sourceParentMount === $mount2 && $this->targetIsNotShared($storage2, $internalPath2)) {
800
+                                    /**
801
+                                     * @var \OC\Files\Mount\MountPoint | \OC\Files\Mount\MoveableMount $mount1
802
+                                     */
803
+                                    $sourceMountPoint = $mount1->getMountPoint();
804
+                                    $result = $mount1->moveMount($absolutePath2);
805
+                                    $manager->moveMount($sourceMountPoint, $mount1->getMountPoint());
806
+                                } else {
807
+                                    $result = false;
808
+                                }
809
+                            } else {
810
+                                $result = false;
811
+                            }
812
+                            // moving a file/folder within the same mount point
813
+                        } elseif ($storage1 === $storage2) {
814
+                            if ($storage1) {
815
+                                $result = $storage1->rename($internalPath1, $internalPath2);
816
+                            } else {
817
+                                $result = false;
818
+                            }
819
+                            // moving a file/folder between storages (from $storage1 to $storage2)
820
+                        } else {
821
+                            $result = $storage2->moveFromStorage($storage1, $internalPath1, $internalPath2);
822
+                        }
823
+
824
+                        if ((Cache\Scanner::isPartialFile($path1) && !Cache\Scanner::isPartialFile($path2)) && $result !== false) {
825
+                            // if it was a rename from a part file to a regular file it was a write and not a rename operation
826
+                            $this->writeUpdate($storage2, $internalPath2);
827
+                        } else if ($result) {
828
+                            if ($internalPath1 !== '') { // don't do a cache update for moved mounts
829
+                                $this->renameUpdate($storage1, $storage2, $internalPath1, $internalPath2);
830
+                            }
831
+                        }
832
+                    } catch(\Exception $e) {
833
+                        throw $e;
834
+                    } finally {
835
+                        $this->changeLock($path1, ILockingProvider::LOCK_SHARED, true);
836
+                        $this->changeLock($path2, ILockingProvider::LOCK_SHARED, true);
837
+                    }
838
+
839
+                    if ((Cache\Scanner::isPartialFile($path1) && !Cache\Scanner::isPartialFile($path2)) && $result !== false) {
840
+                        if ($this->shouldEmitHooks()) {
841
+                            $this->emit_file_hooks_post($exists, $path2);
842
+                        }
843
+                    } elseif ($result) {
844
+                        if ($this->shouldEmitHooks($path1) and $this->shouldEmitHooks($path2)) {
845
+                            \OC_Hook::emit(
846
+                                Filesystem::CLASSNAME,
847
+                                Filesystem::signal_post_rename,
848
+                                [
849
+                                    Filesystem::signal_param_oldpath => $this->getHookPath($path1),
850
+                                    Filesystem::signal_param_newpath => $this->getHookPath($path2)
851
+                                ]
852
+                            );
853
+                        }
854
+                    }
855
+                }
856
+            } catch(\Exception $e) {
857
+                throw $e;
858
+            } finally {
859
+                $this->unlockFile($path1, ILockingProvider::LOCK_SHARED, true);
860
+                $this->unlockFile($path2, ILockingProvider::LOCK_SHARED, true);
861
+            }
862
+        }
863
+        return $result;
864
+    }
865
+
866
+    /**
867
+     * Copy a file/folder from the source path to target path
868
+     *
869
+     * @param string $path1 source path
870
+     * @param string $path2 target path
871
+     * @param bool $preserveMtime whether to preserve mtime on the copy
872
+     *
873
+     * @return bool|mixed
874
+     */
875
+    public function copy($path1, $path2, $preserveMtime = false) {
876
+        $absolutePath1 = Filesystem::normalizePath($this->getAbsolutePath($path1));
877
+        $absolutePath2 = Filesystem::normalizePath($this->getAbsolutePath($path2));
878
+        $result = false;
879
+        if (
880
+            Filesystem::isValidPath($path2)
881
+            and Filesystem::isValidPath($path1)
882
+            and !Filesystem::isFileBlacklisted($path2)
883
+        ) {
884
+            $path1 = $this->getRelativePath($absolutePath1);
885
+            $path2 = $this->getRelativePath($absolutePath2);
886
+
887
+            if ($path1 == null or $path2 == null) {
888
+                return false;
889
+            }
890
+            $run = true;
891
+
892
+            $this->lockFile($path2, ILockingProvider::LOCK_SHARED);
893
+            $this->lockFile($path1, ILockingProvider::LOCK_SHARED);
894
+            $lockTypePath1 = ILockingProvider::LOCK_SHARED;
895
+            $lockTypePath2 = ILockingProvider::LOCK_SHARED;
896
+
897
+            try {
898
+
899
+                $exists = $this->file_exists($path2);
900
+                if ($this->shouldEmitHooks()) {
901
+                    \OC_Hook::emit(
902
+                        Filesystem::CLASSNAME,
903
+                        Filesystem::signal_copy,
904
+                        [
905
+                            Filesystem::signal_param_oldpath => $this->getHookPath($path1),
906
+                            Filesystem::signal_param_newpath => $this->getHookPath($path2),
907
+                            Filesystem::signal_param_run => &$run
908
+                        ]
909
+                    );
910
+                    $this->emit_file_hooks_pre($exists, $path2, $run);
911
+                }
912
+                if ($run) {
913
+                    $mount1 = $this->getMount($path1);
914
+                    $mount2 = $this->getMount($path2);
915
+                    $storage1 = $mount1->getStorage();
916
+                    $internalPath1 = $mount1->getInternalPath($absolutePath1);
917
+                    $storage2 = $mount2->getStorage();
918
+                    $internalPath2 = $mount2->getInternalPath($absolutePath2);
919
+
920
+                    $this->changeLock($path2, ILockingProvider::LOCK_EXCLUSIVE);
921
+                    $lockTypePath2 = ILockingProvider::LOCK_EXCLUSIVE;
922
+
923
+                    if ($mount1->getMountPoint() == $mount2->getMountPoint()) {
924
+                        if ($storage1) {
925
+                            $result = $storage1->copy($internalPath1, $internalPath2);
926
+                        } else {
927
+                            $result = false;
928
+                        }
929
+                    } else {
930
+                        $result = $storage2->copyFromStorage($storage1, $internalPath1, $internalPath2);
931
+                    }
932
+
933
+                    $this->writeUpdate($storage2, $internalPath2);
934
+
935
+                    $this->changeLock($path2, ILockingProvider::LOCK_SHARED);
936
+                    $lockTypePath2 = ILockingProvider::LOCK_SHARED;
937
+
938
+                    if ($this->shouldEmitHooks() && $result !== false) {
939
+                        \OC_Hook::emit(
940
+                            Filesystem::CLASSNAME,
941
+                            Filesystem::signal_post_copy,
942
+                            [
943
+                                Filesystem::signal_param_oldpath => $this->getHookPath($path1),
944
+                                Filesystem::signal_param_newpath => $this->getHookPath($path2)
945
+                            ]
946
+                        );
947
+                        $this->emit_file_hooks_post($exists, $path2);
948
+                    }
949
+
950
+                }
951
+            } catch (\Exception $e) {
952
+                $this->unlockFile($path2, $lockTypePath2);
953
+                $this->unlockFile($path1, $lockTypePath1);
954
+                throw $e;
955
+            }
956
+
957
+            $this->unlockFile($path2, $lockTypePath2);
958
+            $this->unlockFile($path1, $lockTypePath1);
959
+
960
+        }
961
+        return $result;
962
+    }
963
+
964
+    /**
965
+     * @param string $path
966
+     * @param string $mode 'r' or 'w'
967
+     * @return resource
968
+     * @throws LockedException
969
+     */
970
+    public function fopen($path, $mode) {
971
+        $mode = str_replace('b', '', $mode); // the binary flag is a windows only feature which we do not support
972
+        $hooks = [];
973
+        switch ($mode) {
974
+            case 'r':
975
+                $hooks[] = 'read';
976
+                break;
977
+            case 'r+':
978
+            case 'w+':
979
+            case 'x+':
980
+            case 'a+':
981
+                $hooks[] = 'read';
982
+                $hooks[] = 'write';
983
+                break;
984
+            case 'w':
985
+            case 'x':
986
+            case 'a':
987
+                $hooks[] = 'write';
988
+                break;
989
+            default:
990
+                \OCP\Util::writeLog('core', 'invalid mode (' . $mode . ') for ' . $path, ILogger::ERROR);
991
+        }
992
+
993
+        if ($mode !== 'r' && $mode !== 'w') {
994
+            \OC::$server->getLogger()->info('Trying to open a file with a mode other than "r" or "w" can cause severe performance issues with some backends');
995
+        }
996
+
997
+        return $this->basicOperation('fopen', $path, $hooks, $mode);
998
+    }
999
+
1000
+    /**
1001
+     * @param string $path
1002
+     * @return bool|string
1003
+     * @throws \OCP\Files\InvalidPathException
1004
+     */
1005
+    public function toTmpFile($path) {
1006
+        $this->assertPathLength($path);
1007
+        if (Filesystem::isValidPath($path)) {
1008
+            $source = $this->fopen($path, 'r');
1009
+            if ($source) {
1010
+                $extension = pathinfo($path, PATHINFO_EXTENSION);
1011
+                $tmpFile = \OC::$server->getTempManager()->getTemporaryFile($extension);
1012
+                file_put_contents($tmpFile, $source);
1013
+                return $tmpFile;
1014
+            } else {
1015
+                return false;
1016
+            }
1017
+        } else {
1018
+            return false;
1019
+        }
1020
+    }
1021
+
1022
+    /**
1023
+     * @param string $tmpFile
1024
+     * @param string $path
1025
+     * @return bool|mixed
1026
+     * @throws \OCP\Files\InvalidPathException
1027
+     */
1028
+    public function fromTmpFile($tmpFile, $path) {
1029
+        $this->assertPathLength($path);
1030
+        if (Filesystem::isValidPath($path)) {
1031
+
1032
+            // Get directory that the file is going into
1033
+            $filePath = dirname($path);
1034
+
1035
+            // Create the directories if any
1036
+            if (!$this->file_exists($filePath)) {
1037
+                $result = $this->createParentDirectories($filePath);
1038
+                if ($result === false) {
1039
+                    return false;
1040
+                }
1041
+            }
1042
+
1043
+            $source = fopen($tmpFile, 'r');
1044
+            if ($source) {
1045
+                $result = $this->file_put_contents($path, $source);
1046
+                // $this->file_put_contents() might have already closed
1047
+                // the resource, so we check it, before trying to close it
1048
+                // to avoid messages in the error log.
1049
+                if (is_resource($source)) {
1050
+                    fclose($source);
1051
+                }
1052
+                unlink($tmpFile);
1053
+                return $result;
1054
+            } else {
1055
+                return false;
1056
+            }
1057
+        } else {
1058
+            return false;
1059
+        }
1060
+    }
1061
+
1062
+
1063
+    /**
1064
+     * @param string $path
1065
+     * @return mixed
1066
+     * @throws \OCP\Files\InvalidPathException
1067
+     */
1068
+    public function getMimeType($path) {
1069
+        $this->assertPathLength($path);
1070
+        return $this->basicOperation('getMimeType', $path);
1071
+    }
1072
+
1073
+    /**
1074
+     * @param string $type
1075
+     * @param string $path
1076
+     * @param bool $raw
1077
+     * @return bool|null|string
1078
+     */
1079
+    public function hash($type, $path, $raw = false) {
1080
+        $postFix = (substr($path, -1) === '/') ? '/' : '';
1081
+        $absolutePath = Filesystem::normalizePath($this->getAbsolutePath($path));
1082
+        if (Filesystem::isValidPath($path)) {
1083
+            $path = $this->getRelativePath($absolutePath);
1084
+            if ($path == null) {
1085
+                return false;
1086
+            }
1087
+            if ($this->shouldEmitHooks($path)) {
1088
+                \OC_Hook::emit(
1089
+                    Filesystem::CLASSNAME,
1090
+                    Filesystem::signal_read,
1091
+                    [Filesystem::signal_param_path => $this->getHookPath($path)]
1092
+                );
1093
+            }
1094
+            list($storage, $internalPath) = Filesystem::resolvePath($absolutePath . $postFix);
1095
+            if ($storage) {
1096
+                return $storage->hash($type, $internalPath, $raw);
1097
+            }
1098
+        }
1099
+        return null;
1100
+    }
1101
+
1102
+    /**
1103
+     * @param string $path
1104
+     * @return mixed
1105
+     * @throws \OCP\Files\InvalidPathException
1106
+     */
1107
+    public function free_space($path = '/') {
1108
+        $this->assertPathLength($path);
1109
+        $result = $this->basicOperation('free_space', $path);
1110
+        if ($result === null) {
1111
+            throw new InvalidPathException();
1112
+        }
1113
+        return $result;
1114
+    }
1115
+
1116
+    /**
1117
+     * abstraction layer for basic filesystem functions: wrapper for \OC\Files\Storage\Storage
1118
+     *
1119
+     * @param string $operation
1120
+     * @param string $path
1121
+     * @param array $hooks (optional)
1122
+     * @param mixed $extraParam (optional)
1123
+     * @return mixed
1124
+     * @throws LockedException
1125
+     *
1126
+     * This method takes requests for basic filesystem functions (e.g. reading & writing
1127
+     * files), processes hooks and proxies, sanitises paths, and finally passes them on to
1128
+     * \OC\Files\Storage\Storage for delegation to a storage backend for execution
1129
+     */
1130
+    private function basicOperation($operation, $path, $hooks = [], $extraParam = null) {
1131
+        $postFix = (substr($path, -1) === '/') ? '/' : '';
1132
+        $absolutePath = Filesystem::normalizePath($this->getAbsolutePath($path));
1133
+        if (Filesystem::isValidPath($path)
1134
+            and !Filesystem::isFileBlacklisted($path)
1135
+        ) {
1136
+            $path = $this->getRelativePath($absolutePath);
1137
+            if ($path == null) {
1138
+                return false;
1139
+            }
1140
+
1141
+            if (in_array('write', $hooks) || in_array('delete', $hooks) || in_array('read', $hooks)) {
1142
+                // always a shared lock during pre-hooks so the hook can read the file
1143
+                $this->lockFile($path, ILockingProvider::LOCK_SHARED);
1144
+            }
1145
+
1146
+            $run = $this->runHooks($hooks, $path);
1147
+            /** @var \OC\Files\Storage\Storage $storage */
1148
+            list($storage, $internalPath) = Filesystem::resolvePath($absolutePath . $postFix);
1149
+            if ($run and $storage) {
1150
+                if (in_array('write', $hooks) || in_array('delete', $hooks)) {
1151
+                    try {
1152
+                        $this->changeLock($path, ILockingProvider::LOCK_EXCLUSIVE);
1153
+                    } catch (LockedException $e) {
1154
+                        // release the shared lock we acquired before quiting
1155
+                        $this->unlockFile($path, ILockingProvider::LOCK_SHARED);
1156
+                        throw $e;
1157
+                    }
1158
+                }
1159
+                try {
1160
+                    if (!is_null($extraParam)) {
1161
+                        $result = $storage->$operation($internalPath, $extraParam);
1162
+                    } else {
1163
+                        $result = $storage->$operation($internalPath);
1164
+                    }
1165
+                } catch (\Exception $e) {
1166
+                    if (in_array('write', $hooks) || in_array('delete', $hooks)) {
1167
+                        $this->unlockFile($path, ILockingProvider::LOCK_EXCLUSIVE);
1168
+                    } else if (in_array('read', $hooks)) {
1169
+                        $this->unlockFile($path, ILockingProvider::LOCK_SHARED);
1170
+                    }
1171
+                    throw $e;
1172
+                }
1173
+
1174
+                if ($result && in_array('delete', $hooks) and $result) {
1175
+                    $this->removeUpdate($storage, $internalPath);
1176
+                }
1177
+                if ($result && in_array('write', $hooks,  true) && $operation !== 'fopen' && $operation !== 'touch') {
1178
+                    $this->writeUpdate($storage, $internalPath);
1179
+                }
1180
+                if ($result && in_array('touch', $hooks)) {
1181
+                    $this->writeUpdate($storage, $internalPath, $extraParam);
1182
+                }
1183
+
1184
+                if ((in_array('write', $hooks) || in_array('delete', $hooks)) && ($operation !== 'fopen' || $result === false)) {
1185
+                    $this->changeLock($path, ILockingProvider::LOCK_SHARED);
1186
+                }
1187
+
1188
+                $unlockLater = false;
1189
+                if ($this->lockingEnabled && $operation === 'fopen' && is_resource($result)) {
1190
+                    $unlockLater = true;
1191
+                    // make sure our unlocking callback will still be called if connection is aborted
1192
+                    ignore_user_abort(true);
1193
+                    $result = CallbackWrapper::wrap($result, null, null, function () use ($hooks, $path) {
1194
+                        if (in_array('write', $hooks)) {
1195
+                            $this->unlockFile($path, ILockingProvider::LOCK_EXCLUSIVE);
1196
+                        } else if (in_array('read', $hooks)) {
1197
+                            $this->unlockFile($path, ILockingProvider::LOCK_SHARED);
1198
+                        }
1199
+                    });
1200
+                }
1201
+
1202
+                if ($this->shouldEmitHooks($path) && $result !== false) {
1203
+                    if ($operation != 'fopen') { //no post hooks for fopen, the file stream is still open
1204
+                        $this->runHooks($hooks, $path, true);
1205
+                    }
1206
+                }
1207
+
1208
+                if (!$unlockLater
1209
+                    && (in_array('write', $hooks) || in_array('delete', $hooks) || in_array('read', $hooks))
1210
+                ) {
1211
+                    $this->unlockFile($path, ILockingProvider::LOCK_SHARED);
1212
+                }
1213
+                return $result;
1214
+            } else {
1215
+                $this->unlockFile($path, ILockingProvider::LOCK_SHARED);
1216
+            }
1217
+        }
1218
+        return null;
1219
+    }
1220
+
1221
+    /**
1222
+     * get the path relative to the default root for hook usage
1223
+     *
1224
+     * @param string $path
1225
+     * @return string
1226
+     */
1227
+    private function getHookPath($path) {
1228
+        if (!Filesystem::getView()) {
1229
+            return $path;
1230
+        }
1231
+        return Filesystem::getView()->getRelativePath($this->getAbsolutePath($path));
1232
+    }
1233
+
1234
+    private function shouldEmitHooks($path = '') {
1235
+        if ($path && Cache\Scanner::isPartialFile($path)) {
1236
+            return false;
1237
+        }
1238
+        if (!Filesystem::$loaded) {
1239
+            return false;
1240
+        }
1241
+        $defaultRoot = Filesystem::getRoot();
1242
+        if ($defaultRoot === null) {
1243
+            return false;
1244
+        }
1245
+        if ($this->fakeRoot === $defaultRoot) {
1246
+            return true;
1247
+        }
1248
+        $fullPath = $this->getAbsolutePath($path);
1249
+
1250
+        if ($fullPath === $defaultRoot) {
1251
+            return true;
1252
+        }
1253
+
1254
+        return (strlen($fullPath) > strlen($defaultRoot)) && (substr($fullPath, 0, strlen($defaultRoot) + 1) === $defaultRoot . '/');
1255
+    }
1256
+
1257
+    /**
1258
+     * @param string[] $hooks
1259
+     * @param string $path
1260
+     * @param bool $post
1261
+     * @return bool
1262
+     */
1263
+    private function runHooks($hooks, $path, $post = false) {
1264
+        $relativePath = $path;
1265
+        $path = $this->getHookPath($path);
1266
+        $prefix = $post ? 'post_' : '';
1267
+        $run = true;
1268
+        if ($this->shouldEmitHooks($relativePath)) {
1269
+            foreach ($hooks as $hook) {
1270
+                if ($hook != 'read') {
1271
+                    \OC_Hook::emit(
1272
+                        Filesystem::CLASSNAME,
1273
+                        $prefix . $hook,
1274
+                        [
1275
+                            Filesystem::signal_param_run => &$run,
1276
+                            Filesystem::signal_param_path => $path
1277
+                        ]
1278
+                    );
1279
+                } elseif (!$post) {
1280
+                    \OC_Hook::emit(
1281
+                        Filesystem::CLASSNAME,
1282
+                        $prefix . $hook,
1283
+                        [
1284
+                            Filesystem::signal_param_path => $path
1285
+                        ]
1286
+                    );
1287
+                }
1288
+            }
1289
+        }
1290
+        return $run;
1291
+    }
1292
+
1293
+    /**
1294
+     * check if a file or folder has been updated since $time
1295
+     *
1296
+     * @param string $path
1297
+     * @param int $time
1298
+     * @return bool
1299
+     */
1300
+    public function hasUpdated($path, $time) {
1301
+        return $this->basicOperation('hasUpdated', $path, [], $time);
1302
+    }
1303
+
1304
+    /**
1305
+     * @param string $ownerId
1306
+     * @return \OC\User\User
1307
+     */
1308
+    private function getUserObjectForOwner($ownerId) {
1309
+        $owner = $this->userManager->get($ownerId);
1310
+        if ($owner instanceof IUser) {
1311
+            return $owner;
1312
+        } else {
1313
+            return new User($ownerId, null, \OC::$server->getEventDispatcher());
1314
+        }
1315
+    }
1316
+
1317
+    /**
1318
+     * Get file info from cache
1319
+     *
1320
+     * If the file is not in cached it will be scanned
1321
+     * If the file has changed on storage the cache will be updated
1322
+     *
1323
+     * @param \OC\Files\Storage\Storage $storage
1324
+     * @param string $internalPath
1325
+     * @param string $relativePath
1326
+     * @return ICacheEntry|bool
1327
+     */
1328
+    private function getCacheEntry($storage, $internalPath, $relativePath) {
1329
+        $cache = $storage->getCache($internalPath);
1330
+        $data = $cache->get($internalPath);
1331
+        $watcher = $storage->getWatcher($internalPath);
1332
+
1333
+        try {
1334
+            // if the file is not in the cache or needs to be updated, trigger the scanner and reload the data
1335
+            if (!$data || $data['size'] === -1) {
1336
+                if (!$storage->file_exists($internalPath)) {
1337
+                    return false;
1338
+                }
1339
+                // don't need to get a lock here since the scanner does it's own locking
1340
+                $scanner = $storage->getScanner($internalPath);
1341
+                $scanner->scan($internalPath, Cache\Scanner::SCAN_SHALLOW);
1342
+                $data = $cache->get($internalPath);
1343
+            } else if (!Cache\Scanner::isPartialFile($internalPath) && $watcher->needsUpdate($internalPath, $data)) {
1344
+                $this->lockFile($relativePath, ILockingProvider::LOCK_SHARED);
1345
+                $watcher->update($internalPath, $data);
1346
+                $storage->getPropagator()->propagateChange($internalPath, time());
1347
+                $data = $cache->get($internalPath);
1348
+                $this->unlockFile($relativePath, ILockingProvider::LOCK_SHARED);
1349
+            }
1350
+        } catch (LockedException $e) {
1351
+            // if the file is locked we just use the old cache info
1352
+        }
1353
+
1354
+        return $data;
1355
+    }
1356
+
1357
+    /**
1358
+     * get the filesystem info
1359
+     *
1360
+     * @param string $path
1361
+     * @param boolean|string $includeMountPoints true to add mountpoint sizes,
1362
+     * 'ext' to add only ext storage mount point sizes. Defaults to true.
1363
+     * defaults to true
1364
+     * @return \OC\Files\FileInfo|false False if file does not exist
1365
+     */
1366
+    public function getFileInfo($path, $includeMountPoints = true) {
1367
+        $this->assertPathLength($path);
1368
+        if (!Filesystem::isValidPath($path)) {
1369
+            return false;
1370
+        }
1371
+        if (Cache\Scanner::isPartialFile($path)) {
1372
+            return $this->getPartFileInfo($path);
1373
+        }
1374
+        $relativePath = $path;
1375
+        $path = Filesystem::normalizePath($this->fakeRoot . '/' . $path);
1376
+
1377
+        $mount = Filesystem::getMountManager()->find($path);
1378
+        if (!$mount) {
1379
+            \OC::$server->getLogger()->warning('Mountpoint not found for path: ' . $path);
1380
+            return false;
1381
+        }
1382
+        $storage = $mount->getStorage();
1383
+        $internalPath = $mount->getInternalPath($path);
1384
+        if ($storage) {
1385
+            $data = $this->getCacheEntry($storage, $internalPath, $relativePath);
1386
+
1387
+            if (!$data instanceof ICacheEntry) {
1388
+                return false;
1389
+            }
1390
+
1391
+            if ($mount instanceof MoveableMount && $internalPath === '') {
1392
+                $data['permissions'] |= \OCP\Constants::PERMISSION_DELETE;
1393
+            }
1394
+            $ownerId = $storage->getOwner($internalPath);
1395
+            $owner = null;
1396
+            if ($ownerId !== null && $ownerId !== false) {
1397
+                // ownerId might be null if files are accessed with an access token without file system access
1398
+                $owner = $this->getUserObjectForOwner($ownerId);
1399
+            }
1400
+            $info = new FileInfo($path, $storage, $internalPath, $data, $mount, $owner);
1401
+
1402
+            if ($data and isset($data['fileid'])) {
1403
+                if ($includeMountPoints and $data['mimetype'] === 'httpd/unix-directory') {
1404
+                    //add the sizes of other mount points to the folder
1405
+                    $extOnly = ($includeMountPoints === 'ext');
1406
+                    $mounts = Filesystem::getMountManager()->findIn($path);
1407
+                    $info->setSubMounts(array_filter($mounts, function (IMountPoint $mount) use ($extOnly) {
1408
+                        $subStorage = $mount->getStorage();
1409
+                        return !($extOnly && $subStorage instanceof \OCA\Files_Sharing\SharedStorage);
1410
+                    }));
1411
+                }
1412
+            }
1413
+
1414
+            return $info;
1415
+        } else {
1416
+            \OC::$server->getLogger()->warning('Storage not valid for mountpoint: ' . $mount->getMountPoint());
1417
+        }
1418
+
1419
+        return false;
1420
+    }
1421
+
1422
+    /**
1423
+     * get the content of a directory
1424
+     *
1425
+     * @param string $directory path under datadirectory
1426
+     * @param string $mimetype_filter limit returned content to this mimetype or mimepart
1427
+     * @return FileInfo[]
1428
+     */
1429
+    public function getDirectoryContent($directory, $mimetype_filter = '') {
1430
+        $this->assertPathLength($directory);
1431
+        if (!Filesystem::isValidPath($directory)) {
1432
+            return [];
1433
+        }
1434
+        $path = $this->getAbsolutePath($directory);
1435
+        $path = Filesystem::normalizePath($path);
1436
+        $mount = $this->getMount($directory);
1437
+        if (!$mount) {
1438
+            return [];
1439
+        }
1440
+        $storage = $mount->getStorage();
1441
+        $internalPath = $mount->getInternalPath($path);
1442
+        if ($storage) {
1443
+            $cache = $storage->getCache($internalPath);
1444
+            $user = \OC_User::getUser();
1445
+
1446
+            $data = $this->getCacheEntry($storage, $internalPath, $directory);
1447
+
1448
+            if (!$data instanceof ICacheEntry || !isset($data['fileid']) || !($data->getPermissions() && Constants::PERMISSION_READ)) {
1449
+                return [];
1450
+            }
1451
+
1452
+            $folderId = $data['fileid'];
1453
+            $contents = $cache->getFolderContentsById($folderId); //TODO: mimetype_filter
1454
+
1455
+            $sharingDisabled = \OCP\Util::isSharingDisabledForUser();
1456
+
1457
+            $fileNames = array_map(function (ICacheEntry $content) {
1458
+                return $content->getName();
1459
+            }, $contents);
1460
+            /**
1461
+             * @var \OC\Files\FileInfo[] $fileInfos
1462
+             */
1463
+            $fileInfos = array_map(function (ICacheEntry $content) use ($path, $storage, $mount, $sharingDisabled) {
1464
+                if ($sharingDisabled) {
1465
+                    $content['permissions'] = $content['permissions'] & ~\OCP\Constants::PERMISSION_SHARE;
1466
+                }
1467
+                $owner = $this->getUserObjectForOwner($storage->getOwner($content['path']));
1468
+                return new FileInfo($path . '/' . $content['name'], $storage, $content['path'], $content, $mount, $owner);
1469
+            }, $contents);
1470
+            $files = array_combine($fileNames, $fileInfos);
1471
+
1472
+            //add a folder for any mountpoint in this directory and add the sizes of other mountpoints to the folders
1473
+            $mounts = Filesystem::getMountManager()->findIn($path);
1474
+            $dirLength = strlen($path);
1475
+            foreach ($mounts as $mount) {
1476
+                $mountPoint = $mount->getMountPoint();
1477
+                $subStorage = $mount->getStorage();
1478
+                if ($subStorage) {
1479
+                    $subCache = $subStorage->getCache('');
1480
+
1481
+                    $rootEntry = $subCache->get('');
1482
+                    if (!$rootEntry) {
1483
+                        $subScanner = $subStorage->getScanner('');
1484
+                        try {
1485
+                            $subScanner->scanFile('');
1486
+                        } catch (\OCP\Files\StorageNotAvailableException $e) {
1487
+                            continue;
1488
+                        } catch (\OCP\Files\StorageInvalidException $e) {
1489
+                            continue;
1490
+                        } catch (\Exception $e) {
1491
+                            // sometimes when the storage is not available it can be any exception
1492
+                            \OC::$server->getLogger()->logException($e, [
1493
+                                'message' => 'Exception while scanning storage "' . $subStorage->getId() . '"',
1494
+                                'level' => ILogger::ERROR,
1495
+                                'app' => 'lib',
1496
+                            ]);
1497
+                            continue;
1498
+                        }
1499
+                        $rootEntry = $subCache->get('');
1500
+                    }
1501
+
1502
+                    if ($rootEntry && ($rootEntry->getPermissions() && Constants::PERMISSION_READ)) {
1503
+                        $relativePath = trim(substr($mountPoint, $dirLength), '/');
1504
+                        if ($pos = strpos($relativePath, '/')) {
1505
+                            //mountpoint inside subfolder add size to the correct folder
1506
+                            $entryName = substr($relativePath, 0, $pos);
1507
+                            foreach ($files as &$entry) {
1508
+                                if ($entry->getName() === $entryName) {
1509
+                                    $entry->addSubEntry($rootEntry, $mountPoint);
1510
+                                }
1511
+                            }
1512
+                        } else { //mountpoint in this folder, add an entry for it
1513
+                            $rootEntry['name'] = $relativePath;
1514
+                            $rootEntry['type'] = $rootEntry['mimetype'] === 'httpd/unix-directory' ? 'dir' : 'file';
1515
+                            $permissions = $rootEntry['permissions'];
1516
+                            // do not allow renaming/deleting the mount point if they are not shared files/folders
1517
+                            // for shared files/folders we use the permissions given by the owner
1518
+                            if ($mount instanceof MoveableMount) {
1519
+                                $rootEntry['permissions'] = $permissions | \OCP\Constants::PERMISSION_UPDATE | \OCP\Constants::PERMISSION_DELETE;
1520
+                            } else {
1521
+                                $rootEntry['permissions'] = $permissions & (\OCP\Constants::PERMISSION_ALL - (\OCP\Constants::PERMISSION_UPDATE | \OCP\Constants::PERMISSION_DELETE));
1522
+                            }
1523
+
1524
+                            $rootEntry['path'] = substr(Filesystem::normalizePath($path . '/' . $rootEntry['name']), strlen($user) + 2); // full path without /$user/
1525
+
1526
+                            // if sharing was disabled for the user we remove the share permissions
1527
+                            if (\OCP\Util::isSharingDisabledForUser()) {
1528
+                                $rootEntry['permissions'] = $rootEntry['permissions'] & ~\OCP\Constants::PERMISSION_SHARE;
1529
+                            }
1530
+
1531
+                            $owner = $this->getUserObjectForOwner($subStorage->getOwner(''));
1532
+                            $files[$rootEntry->getName()] = new FileInfo($path . '/' . $rootEntry['name'], $subStorage, '', $rootEntry, $mount, $owner);
1533
+                        }
1534
+                    }
1535
+                }
1536
+            }
1537
+
1538
+            if ($mimetype_filter) {
1539
+                $files = array_filter($files, function (FileInfo $file) use ($mimetype_filter) {
1540
+                    if (strpos($mimetype_filter, '/')) {
1541
+                        return $file->getMimetype() === $mimetype_filter;
1542
+                    } else {
1543
+                        return $file->getMimePart() === $mimetype_filter;
1544
+                    }
1545
+                });
1546
+            }
1547
+
1548
+            return array_values($files);
1549
+        } else {
1550
+            return [];
1551
+        }
1552
+    }
1553
+
1554
+    /**
1555
+     * change file metadata
1556
+     *
1557
+     * @param string $path
1558
+     * @param array|\OCP\Files\FileInfo $data
1559
+     * @return int
1560
+     *
1561
+     * returns the fileid of the updated file
1562
+     */
1563
+    public function putFileInfo($path, $data) {
1564
+        $this->assertPathLength($path);
1565
+        if ($data instanceof FileInfo) {
1566
+            $data = $data->getData();
1567
+        }
1568
+        $path = Filesystem::normalizePath($this->fakeRoot . '/' . $path);
1569
+        /**
1570
+         * @var \OC\Files\Storage\Storage $storage
1571
+         * @var string $internalPath
1572
+         */
1573
+        list($storage, $internalPath) = Filesystem::resolvePath($path);
1574
+        if ($storage) {
1575
+            $cache = $storage->getCache($path);
1576
+
1577
+            if (!$cache->inCache($internalPath)) {
1578
+                $scanner = $storage->getScanner($internalPath);
1579
+                $scanner->scan($internalPath, Cache\Scanner::SCAN_SHALLOW);
1580
+            }
1581
+
1582
+            return $cache->put($internalPath, $data);
1583
+        } else {
1584
+            return -1;
1585
+        }
1586
+    }
1587
+
1588
+    /**
1589
+     * search for files with the name matching $query
1590
+     *
1591
+     * @param string $query
1592
+     * @return FileInfo[]
1593
+     */
1594
+    public function search($query) {
1595
+        return $this->searchCommon('search', ['%' . $query . '%']);
1596
+    }
1597
+
1598
+    /**
1599
+     * search for files with the name matching $query
1600
+     *
1601
+     * @param string $query
1602
+     * @return FileInfo[]
1603
+     */
1604
+    public function searchRaw($query) {
1605
+        return $this->searchCommon('search', [$query]);
1606
+    }
1607
+
1608
+    /**
1609
+     * search for files by mimetype
1610
+     *
1611
+     * @param string $mimetype
1612
+     * @return FileInfo[]
1613
+     */
1614
+    public function searchByMime($mimetype) {
1615
+        return $this->searchCommon('searchByMime', [$mimetype]);
1616
+    }
1617
+
1618
+    /**
1619
+     * search for files by tag
1620
+     *
1621
+     * @param string|int $tag name or tag id
1622
+     * @param string $userId owner of the tags
1623
+     * @return FileInfo[]
1624
+     */
1625
+    public function searchByTag($tag, $userId) {
1626
+        return $this->searchCommon('searchByTag', [$tag, $userId]);
1627
+    }
1628
+
1629
+    /**
1630
+     * @param string $method cache method
1631
+     * @param array $args
1632
+     * @return FileInfo[]
1633
+     */
1634
+    private function searchCommon($method, $args) {
1635
+        $files = [];
1636
+        $rootLength = strlen($this->fakeRoot);
1637
+
1638
+        $mount = $this->getMount('');
1639
+        $mountPoint = $mount->getMountPoint();
1640
+        $storage = $mount->getStorage();
1641
+        if ($storage) {
1642
+            $cache = $storage->getCache('');
1643
+
1644
+            $results = call_user_func_array([$cache, $method], $args);
1645
+            foreach ($results as $result) {
1646
+                if (substr($mountPoint . $result['path'], 0, $rootLength + 1) === $this->fakeRoot . '/') {
1647
+                    $internalPath = $result['path'];
1648
+                    $path = $mountPoint . $result['path'];
1649
+                    $result['path'] = substr($mountPoint . $result['path'], $rootLength);
1650
+                    $owner = \OC::$server->getUserManager()->get($storage->getOwner($internalPath));
1651
+                    $files[] = new FileInfo($path, $storage, $internalPath, $result, $mount, $owner);
1652
+                }
1653
+            }
1654
+
1655
+            $mounts = Filesystem::getMountManager()->findIn($this->fakeRoot);
1656
+            foreach ($mounts as $mount) {
1657
+                $mountPoint = $mount->getMountPoint();
1658
+                $storage = $mount->getStorage();
1659
+                if ($storage) {
1660
+                    $cache = $storage->getCache('');
1661
+
1662
+                    $relativeMountPoint = substr($mountPoint, $rootLength);
1663
+                    $results = call_user_func_array([$cache, $method], $args);
1664
+                    if ($results) {
1665
+                        foreach ($results as $result) {
1666
+                            $internalPath = $result['path'];
1667
+                            $result['path'] = rtrim($relativeMountPoint . $result['path'], '/');
1668
+                            $path = rtrim($mountPoint . $internalPath, '/');
1669
+                            $owner = \OC::$server->getUserManager()->get($storage->getOwner($internalPath));
1670
+                            $files[] = new FileInfo($path, $storage, $internalPath, $result, $mount, $owner);
1671
+                        }
1672
+                    }
1673
+                }
1674
+            }
1675
+        }
1676
+        return $files;
1677
+    }
1678
+
1679
+    /**
1680
+     * Get the owner for a file or folder
1681
+     *
1682
+     * @param string $path
1683
+     * @return string the user id of the owner
1684
+     * @throws NotFoundException
1685
+     */
1686
+    public function getOwner($path) {
1687
+        $info = $this->getFileInfo($path);
1688
+        if (!$info) {
1689
+            throw new NotFoundException($path . ' not found while trying to get owner');
1690
+        }
1691
+
1692
+        if ($info->getOwner() === null) {
1693
+            throw new NotFoundException($path . ' has no owner');
1694
+        }
1695
+
1696
+        return $info->getOwner()->getUID();
1697
+    }
1698
+
1699
+    /**
1700
+     * get the ETag for a file or folder
1701
+     *
1702
+     * @param string $path
1703
+     * @return string
1704
+     */
1705
+    public function getETag($path) {
1706
+        /**
1707
+         * @var Storage\Storage $storage
1708
+         * @var string $internalPath
1709
+         */
1710
+        list($storage, $internalPath) = $this->resolvePath($path);
1711
+        if ($storage) {
1712
+            return $storage->getETag($internalPath);
1713
+        } else {
1714
+            return null;
1715
+        }
1716
+    }
1717
+
1718
+    /**
1719
+     * Get the path of a file by id, relative to the view
1720
+     *
1721
+     * Note that the resulting path is not guarantied to be unique for the id, multiple paths can point to the same file
1722
+     *
1723
+     * @param int $id
1724
+     * @throws NotFoundException
1725
+     * @return string
1726
+     */
1727
+    public function getPath($id) {
1728
+        $id = (int)$id;
1729
+        $manager = Filesystem::getMountManager();
1730
+        $mounts = $manager->findIn($this->fakeRoot);
1731
+        $mounts[] = $manager->find($this->fakeRoot);
1732
+        // reverse the array so we start with the storage this view is in
1733
+        // which is the most likely to contain the file we're looking for
1734
+        $mounts = array_reverse($mounts);
1735
+
1736
+        // put non shared mounts in front of the shared mount
1737
+        // this prevent unneeded recursion into shares
1738
+        usort($mounts, function (IMountPoint $a, IMountPoint $b) {
1739
+            return $a instanceof SharedMount && (!$b instanceof SharedMount) ? 1 : -1;
1740
+        });
1741
+
1742
+        foreach ($mounts as $mount) {
1743
+            /**
1744
+             * @var \OC\Files\Mount\MountPoint $mount
1745
+             */
1746
+            if ($mount->getStorage()) {
1747
+                $cache = $mount->getStorage()->getCache();
1748
+                $internalPath = $cache->getPathById($id);
1749
+                if (is_string($internalPath)) {
1750
+                    $fullPath = $mount->getMountPoint() . $internalPath;
1751
+                    if (!is_null($path = $this->getRelativePath($fullPath))) {
1752
+                        return $path;
1753
+                    }
1754
+                }
1755
+            }
1756
+        }
1757
+        throw new NotFoundException(sprintf('File with id "%s" has not been found.', $id));
1758
+    }
1759
+
1760
+    /**
1761
+     * @param string $path
1762
+     * @throws InvalidPathException
1763
+     */
1764
+    private function assertPathLength($path) {
1765
+        $maxLen = min(PHP_MAXPATHLEN, 4000);
1766
+        // Check for the string length - performed using isset() instead of strlen()
1767
+        // because isset() is about 5x-40x faster.
1768
+        if (isset($path[$maxLen])) {
1769
+            $pathLen = strlen($path);
1770
+            throw new \OCP\Files\InvalidPathException("Path length($pathLen) exceeds max path length($maxLen): $path");
1771
+        }
1772
+    }
1773
+
1774
+    /**
1775
+     * check if it is allowed to move a mount point to a given target.
1776
+     * It is not allowed to move a mount point into a different mount point or
1777
+     * into an already shared folder
1778
+     *
1779
+     * @param IStorage $targetStorage
1780
+     * @param string $targetInternalPath
1781
+     * @return boolean
1782
+     */
1783
+    private function targetIsNotShared(IStorage $targetStorage, string $targetInternalPath) {
1784
+
1785
+        // note: cannot use the view because the target is already locked
1786
+        $fileId = (int)$targetStorage->getCache()->getId($targetInternalPath);
1787
+        if ($fileId === -1) {
1788
+            // target might not exist, need to check parent instead
1789
+            $fileId = (int)$targetStorage->getCache()->getId(dirname($targetInternalPath));
1790
+        }
1791
+
1792
+        // check if any of the parents were shared by the current owner (include collections)
1793
+        $shares = \OCP\Share::getItemShared(
1794
+            'folder',
1795
+            $fileId,
1796
+            \OCP\Share::FORMAT_NONE,
1797
+            null,
1798
+            true
1799
+        );
1800
+
1801
+        if (count($shares) > 0) {
1802
+            \OCP\Util::writeLog('files',
1803
+                'It is not allowed to move one mount point into a shared folder',
1804
+                ILogger::DEBUG);
1805
+            return false;
1806
+        }
1807
+
1808
+        return true;
1809
+    }
1810
+
1811
+    /**
1812
+     * Get a fileinfo object for files that are ignored in the cache (part files)
1813
+     *
1814
+     * @param string $path
1815
+     * @return \OCP\Files\FileInfo
1816
+     */
1817
+    private function getPartFileInfo($path) {
1818
+        $mount = $this->getMount($path);
1819
+        $storage = $mount->getStorage();
1820
+        $internalPath = $mount->getInternalPath($this->getAbsolutePath($path));
1821
+        $owner = \OC::$server->getUserManager()->get($storage->getOwner($internalPath));
1822
+        return new FileInfo(
1823
+            $this->getAbsolutePath($path),
1824
+            $storage,
1825
+            $internalPath,
1826
+            [
1827
+                'fileid' => null,
1828
+                'mimetype' => $storage->getMimeType($internalPath),
1829
+                'name' => basename($path),
1830
+                'etag' => null,
1831
+                'size' => $storage->filesize($internalPath),
1832
+                'mtime' => $storage->filemtime($internalPath),
1833
+                'encrypted' => false,
1834
+                'permissions' => \OCP\Constants::PERMISSION_ALL
1835
+            ],
1836
+            $mount,
1837
+            $owner
1838
+        );
1839
+    }
1840
+
1841
+    /**
1842
+     * @param string $path
1843
+     * @param string $fileName
1844
+     * @throws InvalidPathException
1845
+     */
1846
+    public function verifyPath($path, $fileName) {
1847
+        try {
1848
+            /** @type \OCP\Files\Storage $storage */
1849
+            list($storage, $internalPath) = $this->resolvePath($path);
1850
+            $storage->verifyPath($internalPath, $fileName);
1851
+        } catch (ReservedWordException $ex) {
1852
+            $l = \OC::$server->getL10N('lib');
1853
+            throw new InvalidPathException($l->t('File name is a reserved word'));
1854
+        } catch (InvalidCharacterInPathException $ex) {
1855
+            $l = \OC::$server->getL10N('lib');
1856
+            throw new InvalidPathException($l->t('File name contains at least one invalid character'));
1857
+        } catch (FileNameTooLongException $ex) {
1858
+            $l = \OC::$server->getL10N('lib');
1859
+            throw new InvalidPathException($l->t('File name is too long'));
1860
+        } catch (InvalidDirectoryException $ex) {
1861
+            $l = \OC::$server->getL10N('lib');
1862
+            throw new InvalidPathException($l->t('Dot files are not allowed'));
1863
+        } catch (EmptyFileNameException $ex) {
1864
+            $l = \OC::$server->getL10N('lib');
1865
+            throw new InvalidPathException($l->t('Empty filename is not allowed'));
1866
+        }
1867
+    }
1868
+
1869
+    /**
1870
+     * get all parent folders of $path
1871
+     *
1872
+     * @param string $path
1873
+     * @return string[]
1874
+     */
1875
+    private function getParents($path) {
1876
+        $path = trim($path, '/');
1877
+        if (!$path) {
1878
+            return [];
1879
+        }
1880
+
1881
+        $parts = explode('/', $path);
1882
+
1883
+        // remove the single file
1884
+        array_pop($parts);
1885
+        $result = ['/'];
1886
+        $resultPath = '';
1887
+        foreach ($parts as $part) {
1888
+            if ($part) {
1889
+                $resultPath .= '/' . $part;
1890
+                $result[] = $resultPath;
1891
+            }
1892
+        }
1893
+        return $result;
1894
+    }
1895
+
1896
+    /**
1897
+     * Returns the mount point for which to lock
1898
+     *
1899
+     * @param string $absolutePath absolute path
1900
+     * @param bool $useParentMount true to return parent mount instead of whatever
1901
+     * is mounted directly on the given path, false otherwise
1902
+     * @return \OC\Files\Mount\MountPoint mount point for which to apply locks
1903
+     */
1904
+    private function getMountForLock($absolutePath, $useParentMount = false) {
1905
+        $results = [];
1906
+        $mount = Filesystem::getMountManager()->find($absolutePath);
1907
+        if (!$mount) {
1908
+            return $results;
1909
+        }
1910
+
1911
+        if ($useParentMount) {
1912
+            // find out if something is mounted directly on the path
1913
+            $internalPath = $mount->getInternalPath($absolutePath);
1914
+            if ($internalPath === '') {
1915
+                // resolve the parent mount instead
1916
+                $mount = Filesystem::getMountManager()->find(dirname($absolutePath));
1917
+            }
1918
+        }
1919
+
1920
+        return $mount;
1921
+    }
1922
+
1923
+    /**
1924
+     * Lock the given path
1925
+     *
1926
+     * @param string $path the path of the file to lock, relative to the view
1927
+     * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
1928
+     * @param bool $lockMountPoint true to lock the mount point, false to lock the attached mount/storage
1929
+     *
1930
+     * @return bool False if the path is excluded from locking, true otherwise
1931
+     * @throws LockedException if the path is already locked
1932
+     */
1933
+    private function lockPath($path, $type, $lockMountPoint = false) {
1934
+        $absolutePath = $this->getAbsolutePath($path);
1935
+        $absolutePath = Filesystem::normalizePath($absolutePath);
1936
+        if (!$this->shouldLockFile($absolutePath)) {
1937
+            return false;
1938
+        }
1939
+
1940
+        $mount = $this->getMountForLock($absolutePath, $lockMountPoint);
1941
+        if ($mount) {
1942
+            try {
1943
+                $storage = $mount->getStorage();
1944
+                if ($storage && $storage->instanceOfStorage('\OCP\Files\Storage\ILockingStorage')) {
1945
+                    $storage->acquireLock(
1946
+                        $mount->getInternalPath($absolutePath),
1947
+                        $type,
1948
+                        $this->lockingProvider
1949
+                    );
1950
+                }
1951
+            } catch (LockedException $e) {
1952
+                // rethrow with the a human-readable path
1953
+                throw new LockedException(
1954
+                    $this->getPathRelativeToFiles($absolutePath),
1955
+                    $e,
1956
+                    $e->getExistingLock()
1957
+                );
1958
+            }
1959
+        }
1960
+
1961
+        return true;
1962
+    }
1963
+
1964
+    /**
1965
+     * Change the lock type
1966
+     *
1967
+     * @param string $path the path of the file to lock, relative to the view
1968
+     * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
1969
+     * @param bool $lockMountPoint true to lock the mount point, false to lock the attached mount/storage
1970
+     *
1971
+     * @return bool False if the path is excluded from locking, true otherwise
1972
+     * @throws LockedException if the path is already locked
1973
+     */
1974
+    public function changeLock($path, $type, $lockMountPoint = false) {
1975
+        $path = Filesystem::normalizePath($path);
1976
+        $absolutePath = $this->getAbsolutePath($path);
1977
+        $absolutePath = Filesystem::normalizePath($absolutePath);
1978
+        if (!$this->shouldLockFile($absolutePath)) {
1979
+            return false;
1980
+        }
1981
+
1982
+        $mount = $this->getMountForLock($absolutePath, $lockMountPoint);
1983
+        if ($mount) {
1984
+            try {
1985
+                $storage = $mount->getStorage();
1986
+                if ($storage && $storage->instanceOfStorage('\OCP\Files\Storage\ILockingStorage')) {
1987
+                    $storage->changeLock(
1988
+                        $mount->getInternalPath($absolutePath),
1989
+                        $type,
1990
+                        $this->lockingProvider
1991
+                    );
1992
+                }
1993
+            } catch (LockedException $e) {
1994
+                try {
1995
+                    // rethrow with the a human-readable path
1996
+                    throw new LockedException(
1997
+                        $this->getPathRelativeToFiles($absolutePath),
1998
+                        $e,
1999
+                        $e->getExistingLock()
2000
+                    );
2001
+                } catch (\InvalidArgumentException $ex) {
2002
+                    throw new LockedException(
2003
+                        $absolutePath,
2004
+                        $ex,
2005
+                        $e->getExistingLock()
2006
+                    );
2007
+                }
2008
+            }
2009
+        }
2010
+
2011
+        return true;
2012
+    }
2013
+
2014
+    /**
2015
+     * Unlock the given path
2016
+     *
2017
+     * @param string $path the path of the file to unlock, relative to the view
2018
+     * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
2019
+     * @param bool $lockMountPoint true to lock the mount point, false to lock the attached mount/storage
2020
+     *
2021
+     * @return bool False if the path is excluded from locking, true otherwise
2022
+     * @throws LockedException
2023
+     */
2024
+    private function unlockPath($path, $type, $lockMountPoint = false) {
2025
+        $absolutePath = $this->getAbsolutePath($path);
2026
+        $absolutePath = Filesystem::normalizePath($absolutePath);
2027
+        if (!$this->shouldLockFile($absolutePath)) {
2028
+            return false;
2029
+        }
2030
+
2031
+        $mount = $this->getMountForLock($absolutePath, $lockMountPoint);
2032
+        if ($mount) {
2033
+            $storage = $mount->getStorage();
2034
+            if ($storage && $storage->instanceOfStorage('\OCP\Files\Storage\ILockingStorage')) {
2035
+                $storage->releaseLock(
2036
+                    $mount->getInternalPath($absolutePath),
2037
+                    $type,
2038
+                    $this->lockingProvider
2039
+                );
2040
+            }
2041
+        }
2042
+
2043
+        return true;
2044
+    }
2045
+
2046
+    /**
2047
+     * Lock a path and all its parents up to the root of the view
2048
+     *
2049
+     * @param string $path the path of the file to lock relative to the view
2050
+     * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
2051
+     * @param bool $lockMountPoint true to lock the mount point, false to lock the attached mount/storage
2052
+     *
2053
+     * @return bool False if the path is excluded from locking, true otherwise
2054
+     * @throws LockedException
2055
+     */
2056
+    public function lockFile($path, $type, $lockMountPoint = false) {
2057
+        $absolutePath = $this->getAbsolutePath($path);
2058
+        $absolutePath = Filesystem::normalizePath($absolutePath);
2059
+        if (!$this->shouldLockFile($absolutePath)) {
2060
+            return false;
2061
+        }
2062
+
2063
+        $this->lockPath($path, $type, $lockMountPoint);
2064
+
2065
+        $parents = $this->getParents($path);
2066
+        foreach ($parents as $parent) {
2067
+            $this->lockPath($parent, ILockingProvider::LOCK_SHARED);
2068
+        }
2069
+
2070
+        return true;
2071
+    }
2072
+
2073
+    /**
2074
+     * Unlock a path and all its parents up to the root of the view
2075
+     *
2076
+     * @param string $path the path of the file to lock relative to the view
2077
+     * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
2078
+     * @param bool $lockMountPoint true to lock the mount point, false to lock the attached mount/storage
2079
+     *
2080
+     * @return bool False if the path is excluded from locking, true otherwise
2081
+     * @throws LockedException
2082
+     */
2083
+    public function unlockFile($path, $type, $lockMountPoint = false) {
2084
+        $absolutePath = $this->getAbsolutePath($path);
2085
+        $absolutePath = Filesystem::normalizePath($absolutePath);
2086
+        if (!$this->shouldLockFile($absolutePath)) {
2087
+            return false;
2088
+        }
2089
+
2090
+        $this->unlockPath($path, $type, $lockMountPoint);
2091
+
2092
+        $parents = $this->getParents($path);
2093
+        foreach ($parents as $parent) {
2094
+            $this->unlockPath($parent, ILockingProvider::LOCK_SHARED);
2095
+        }
2096
+
2097
+        return true;
2098
+    }
2099
+
2100
+    /**
2101
+     * Only lock files in data/user/files/
2102
+     *
2103
+     * @param string $path Absolute path to the file/folder we try to (un)lock
2104
+     * @return bool
2105
+     */
2106
+    protected function shouldLockFile($path) {
2107
+        $path = Filesystem::normalizePath($path);
2108
+
2109
+        $pathSegments = explode('/', $path);
2110
+        if (isset($pathSegments[2])) {
2111
+            // E.g.: /username/files/path-to-file
2112
+            return ($pathSegments[2] === 'files') && (count($pathSegments) > 3);
2113
+        }
2114
+
2115
+        return strpos($path, '/appdata_') !== 0;
2116
+    }
2117
+
2118
+    /**
2119
+     * Shortens the given absolute path to be relative to
2120
+     * "$user/files".
2121
+     *
2122
+     * @param string $absolutePath absolute path which is under "files"
2123
+     *
2124
+     * @return string path relative to "files" with trimmed slashes or null
2125
+     * if the path was NOT relative to files
2126
+     *
2127
+     * @throws \InvalidArgumentException if the given path was not under "files"
2128
+     * @since 8.1.0
2129
+     */
2130
+    public function getPathRelativeToFiles($absolutePath) {
2131
+        $path = Filesystem::normalizePath($absolutePath);
2132
+        $parts = explode('/', trim($path, '/'), 3);
2133
+        // "$user", "files", "path/to/dir"
2134
+        if (!isset($parts[1]) || $parts[1] !== 'files') {
2135
+            $this->logger->error(
2136
+                '$absolutePath must be relative to "files", value is "%s"',
2137
+                [
2138
+                    $absolutePath
2139
+                ]
2140
+            );
2141
+            throw new \InvalidArgumentException('$absolutePath must be relative to "files"');
2142
+        }
2143
+        if (isset($parts[2])) {
2144
+            return $parts[2];
2145
+        }
2146
+        return '';
2147
+    }
2148
+
2149
+    /**
2150
+     * @param string $filename
2151
+     * @return array
2152
+     * @throws \OC\User\NoUserException
2153
+     * @throws NotFoundException
2154
+     */
2155
+    public function getUidAndFilename($filename) {
2156
+        $info = $this->getFileInfo($filename);
2157
+        if (!$info instanceof \OCP\Files\FileInfo) {
2158
+            throw new NotFoundException($this->getAbsolutePath($filename) . ' not found');
2159
+        }
2160
+        $uid = $info->getOwner()->getUID();
2161
+        if ($uid != \OCP\User::getUser()) {
2162
+            Filesystem::initMountPoints($uid);
2163
+            $ownerView = new View('/' . $uid . '/files');
2164
+            try {
2165
+                $filename = $ownerView->getPath($info['fileid']);
2166
+            } catch (NotFoundException $e) {
2167
+                throw new NotFoundException('File with id ' . $info['fileid'] . ' not found for user ' . $uid);
2168
+            }
2169
+        }
2170
+        return [$uid, $filename];
2171
+    }
2172
+
2173
+    /**
2174
+     * Creates parent non-existing folders
2175
+     *
2176
+     * @param string $filePath
2177
+     * @return bool
2178
+     */
2179
+    private function createParentDirectories($filePath) {
2180
+        $directoryParts = explode('/', $filePath);
2181
+        $directoryParts = array_filter($directoryParts);
2182
+        foreach ($directoryParts as $key => $part) {
2183
+            $currentPathElements = array_slice($directoryParts, 0, $key);
2184
+            $currentPath = '/' . implode('/', $currentPathElements);
2185
+            if ($this->is_file($currentPath)) {
2186
+                return false;
2187
+            }
2188
+            if (!$this->file_exists($currentPath)) {
2189
+                $this->mkdir($currentPath);
2190
+            }
2191
+        }
2192
+
2193
+        return true;
2194
+    }
2195 2195
 }
Please login to merge, or discard this patch.
lib/private/User/Backend.php 2 patches
Indentation   +120 added lines, -120 removed lines patch added patch discarded remove patch
@@ -31,136 +31,136 @@
 block discarded – undo
31 31
  * capabilities.
32 32
  */
33 33
 abstract class Backend implements UserInterface {
34
-	/**
35
-	 * error code for functions not provided by the user backend
36
-	 */
37
-	const NOT_IMPLEMENTED = -501;
34
+    /**
35
+     * error code for functions not provided by the user backend
36
+     */
37
+    const NOT_IMPLEMENTED = -501;
38 38
 
39
-	/**
40
-	 * actions that user backends can define
41
-	 */
42
-	const CREATE_USER		= 1;			// 1 << 0
43
-	const SET_PASSWORD		= 16;			// 1 << 4
44
-	const CHECK_PASSWORD	= 256;			// 1 << 8
45
-	const GET_HOME			= 4096;			// 1 << 12
46
-	const GET_DISPLAYNAME	= 65536;		// 1 << 16
47
-	const SET_DISPLAYNAME	= 1048576;		// 1 << 20
48
-	const PROVIDE_AVATAR	= 16777216;		// 1 << 24
49
-	const COUNT_USERS		= 268435456;	// 1 << 28
39
+    /**
40
+     * actions that user backends can define
41
+     */
42
+    const CREATE_USER		= 1;			// 1 << 0
43
+    const SET_PASSWORD		= 16;			// 1 << 4
44
+    const CHECK_PASSWORD	= 256;			// 1 << 8
45
+    const GET_HOME			= 4096;			// 1 << 12
46
+    const GET_DISPLAYNAME	= 65536;		// 1 << 16
47
+    const SET_DISPLAYNAME	= 1048576;		// 1 << 20
48
+    const PROVIDE_AVATAR	= 16777216;		// 1 << 24
49
+    const COUNT_USERS		= 268435456;	// 1 << 28
50 50
 
51
-	protected $possibleActions = [
52
-		self::CREATE_USER => 'createUser',
53
-		self::SET_PASSWORD => 'setPassword',
54
-		self::CHECK_PASSWORD => 'checkPassword',
55
-		self::GET_HOME => 'getHome',
56
-		self::GET_DISPLAYNAME => 'getDisplayName',
57
-		self::SET_DISPLAYNAME => 'setDisplayName',
58
-		self::PROVIDE_AVATAR => 'canChangeAvatar',
59
-		self::COUNT_USERS => 'countUsers',
60
-	];
51
+    protected $possibleActions = [
52
+        self::CREATE_USER => 'createUser',
53
+        self::SET_PASSWORD => 'setPassword',
54
+        self::CHECK_PASSWORD => 'checkPassword',
55
+        self::GET_HOME => 'getHome',
56
+        self::GET_DISPLAYNAME => 'getDisplayName',
57
+        self::SET_DISPLAYNAME => 'setDisplayName',
58
+        self::PROVIDE_AVATAR => 'canChangeAvatar',
59
+        self::COUNT_USERS => 'countUsers',
60
+    ];
61 61
 
62
-	/**
63
-	 * Get all supported actions
64
-	 * @return int bitwise-or'ed actions
65
-	 *
66
-	 * Returns the supported actions as int to be
67
-	 * compared with self::CREATE_USER etc.
68
-	 */
69
-	public function getSupportedActions() {
70
-		$actions = 0;
71
-		foreach($this->possibleActions as $action => $methodName) {
72
-			if(method_exists($this, $methodName)) {
73
-				$actions |= $action;
74
-			}
75
-		}
62
+    /**
63
+     * Get all supported actions
64
+     * @return int bitwise-or'ed actions
65
+     *
66
+     * Returns the supported actions as int to be
67
+     * compared with self::CREATE_USER etc.
68
+     */
69
+    public function getSupportedActions() {
70
+        $actions = 0;
71
+        foreach($this->possibleActions as $action => $methodName) {
72
+            if(method_exists($this, $methodName)) {
73
+                $actions |= $action;
74
+            }
75
+        }
76 76
 
77
-		return $actions;
78
-	}
77
+        return $actions;
78
+    }
79 79
 
80
-	/**
81
-	 * Check if backend implements actions
82
-	 * @param int $actions bitwise-or'ed actions
83
-	 * @return boolean
84
-	 *
85
-	 * Returns the supported actions as int to be
86
-	 * compared with self::CREATE_USER etc.
87
-	 */
88
-	public function implementsActions($actions) {
89
-		return (bool)($this->getSupportedActions() & $actions);
90
-	}
80
+    /**
81
+     * Check if backend implements actions
82
+     * @param int $actions bitwise-or'ed actions
83
+     * @return boolean
84
+     *
85
+     * Returns the supported actions as int to be
86
+     * compared with self::CREATE_USER etc.
87
+     */
88
+    public function implementsActions($actions) {
89
+        return (bool)($this->getSupportedActions() & $actions);
90
+    }
91 91
 
92
-	/**
93
-	 * delete a user
94
-	 * @param string $uid The username of the user to delete
95
-	 * @return bool
96
-	 *
97
-	 * Deletes a user
98
-	 */
99
-	public function deleteUser($uid) {
100
-		return false;
101
-	}
92
+    /**
93
+     * delete a user
94
+     * @param string $uid The username of the user to delete
95
+     * @return bool
96
+     *
97
+     * Deletes a user
98
+     */
99
+    public function deleteUser($uid) {
100
+        return false;
101
+    }
102 102
 
103
-	/**
104
-	 * Get a list of all users
105
-	 *
106
-	 * @param string $search
107
-	 * @param null|int $limit
108
-	 * @param null|int $offset
109
-	 * @return string[] an array of all uids
110
-	 */
111
-	public function getUsers($search = '', $limit = null, $offset = null) {
112
-		return [];
113
-	}
103
+    /**
104
+     * Get a list of all users
105
+     *
106
+     * @param string $search
107
+     * @param null|int $limit
108
+     * @param null|int $offset
109
+     * @return string[] an array of all uids
110
+     */
111
+    public function getUsers($search = '', $limit = null, $offset = null) {
112
+        return [];
113
+    }
114 114
 
115
-	/**
116
-	 * check if a user exists
117
-	 * @param string $uid the username
118
-	 * @return boolean
119
-	 */
120
-	public function userExists($uid) {
121
-		return false;
122
-	}
115
+    /**
116
+     * check if a user exists
117
+     * @param string $uid the username
118
+     * @return boolean
119
+     */
120
+    public function userExists($uid) {
121
+        return false;
122
+    }
123 123
 
124
-	/**
125
-	 * get the user's home directory
126
-	 * @param string $uid the username
127
-	 * @return boolean
128
-	 */
129
-	public function getHome($uid) {
130
-		return false;
131
-	}
124
+    /**
125
+     * get the user's home directory
126
+     * @param string $uid the username
127
+     * @return boolean
128
+     */
129
+    public function getHome($uid) {
130
+        return false;
131
+    }
132 132
 
133
-	/**
134
-	 * get display name of the user
135
-	 * @param string $uid user ID of the user
136
-	 * @return string display name
137
-	 */
138
-	public function getDisplayName($uid) {
139
-		return $uid;
140
-	}
133
+    /**
134
+     * get display name of the user
135
+     * @param string $uid user ID of the user
136
+     * @return string display name
137
+     */
138
+    public function getDisplayName($uid) {
139
+        return $uid;
140
+    }
141 141
 
142
-	/**
143
-	 * Get a list of all display names and user ids.
144
-	 *
145
-	 * @param string $search
146
-	 * @param string|null $limit
147
-	 * @param string|null $offset
148
-	 * @return array an array of all displayNames (value) and the corresponding uids (key)
149
-	 */
150
-	public function getDisplayNames($search = '', $limit = null, $offset = null) {
151
-		$displayNames = [];
152
-		$users = $this->getUsers($search, $limit, $offset);
153
-		foreach ($users as $user) {
154
-			$displayNames[$user] = $user;
155
-		}
156
-		return $displayNames;
157
-	}
142
+    /**
143
+     * Get a list of all display names and user ids.
144
+     *
145
+     * @param string $search
146
+     * @param string|null $limit
147
+     * @param string|null $offset
148
+     * @return array an array of all displayNames (value) and the corresponding uids (key)
149
+     */
150
+    public function getDisplayNames($search = '', $limit = null, $offset = null) {
151
+        $displayNames = [];
152
+        $users = $this->getUsers($search, $limit, $offset);
153
+        foreach ($users as $user) {
154
+            $displayNames[$user] = $user;
155
+        }
156
+        return $displayNames;
157
+    }
158 158
 
159
-	/**
160
-	 * Check if a user list is available or not
161
-	 * @return boolean if users can be listed or not
162
-	 */
163
-	public function hasUserListings() {
164
-		return false;
165
-	}
159
+    /**
160
+     * Check if a user list is available or not
161
+     * @return boolean if users can be listed or not
162
+     */
163
+    public function hasUserListings() {
164
+        return false;
165
+    }
166 166
 }
Please login to merge, or discard this patch.
Spacing   +11 added lines, -11 removed lines patch added patch discarded remove patch
@@ -39,14 +39,14 @@  discard block
 block discarded – undo
39 39
 	/**
40 40
 	 * actions that user backends can define
41 41
 	 */
42
-	const CREATE_USER		= 1;			// 1 << 0
43
-	const SET_PASSWORD		= 16;			// 1 << 4
44
-	const CHECK_PASSWORD	= 256;			// 1 << 8
45
-	const GET_HOME			= 4096;			// 1 << 12
46
-	const GET_DISPLAYNAME	= 65536;		// 1 << 16
47
-	const SET_DISPLAYNAME	= 1048576;		// 1 << 20
48
-	const PROVIDE_AVATAR	= 16777216;		// 1 << 24
49
-	const COUNT_USERS		= 268435456;	// 1 << 28
42
+	const CREATE_USER = 1; // 1 << 0
43
+	const SET_PASSWORD = 16; // 1 << 4
44
+	const CHECK_PASSWORD = 256; // 1 << 8
45
+	const GET_HOME = 4096; // 1 << 12
46
+	const GET_DISPLAYNAME	= 65536; // 1 << 16
47
+	const SET_DISPLAYNAME	= 1048576; // 1 << 20
48
+	const PROVIDE_AVATAR = 16777216; // 1 << 24
49
+	const COUNT_USERS = 268435456; // 1 << 28
50 50
 
51 51
 	protected $possibleActions = [
52 52
 		self::CREATE_USER => 'createUser',
@@ -68,8 +68,8 @@  discard block
 block discarded – undo
68 68
 	 */
69 69
 	public function getSupportedActions() {
70 70
 		$actions = 0;
71
-		foreach($this->possibleActions as $action => $methodName) {
72
-			if(method_exists($this, $methodName)) {
71
+		foreach ($this->possibleActions as $action => $methodName) {
72
+			if (method_exists($this, $methodName)) {
73 73
 				$actions |= $action;
74 74
 			}
75 75
 		}
@@ -86,7 +86,7 @@  discard block
 block discarded – undo
86 86
 	 * compared with self::CREATE_USER etc.
87 87
 	 */
88 88
 	public function implementsActions($actions) {
89
-		return (bool)($this->getSupportedActions() & $actions);
89
+		return (bool) ($this->getSupportedActions() & $actions);
90 90
 	}
91 91
 
92 92
 	/**
Please login to merge, or discard this patch.