Completed
Pull Request — master (#5888)
by Maxence
16:07
created
lib/public/Util.php 3 patches
Doc Comments   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -544,7 +544,7 @@
 block discarded – undo
544 544
 	 * @param array $input The array to work on
545 545
 	 * @param int $case Either MB_CASE_UPPER or MB_CASE_LOWER (default)
546 546
 	 * @param string $encoding The encoding parameter is the character encoding. Defaults to UTF-8
547
-	 * @return array
547
+	 * @return string
548 548
 	 * @since 4.5.0
549 549
 	 */
550 550
 	public static function mb_array_change_key_case($input, $case = MB_CASE_LOWER, $encoding = 'UTF-8') {
Please login to merge, or discard this patch.
Indentation   +649 added lines, -649 removed lines patch added patch discarded remove patch
@@ -57,655 +57,655 @@
 block discarded – undo
57 57
  * @since 4.0.0
58 58
  */
59 59
 class Util {
60
-	// consts for Logging
61
-	const DEBUG=0;
62
-	const INFO=1;
63
-	const WARN=2;
64
-	const ERROR=3;
65
-	const FATAL=4;
66
-
67
-	/** \OCP\Share\IManager */
68
-	private static $shareManager;
69
-
70
-	/**
71
-	 * get the current installed version of ownCloud
72
-	 * @return array
73
-	 * @since 4.0.0
74
-	 */
75
-	public static function getVersion() {
76
-		return \OC_Util::getVersion();
77
-	}
60
+    // consts for Logging
61
+    const DEBUG=0;
62
+    const INFO=1;
63
+    const WARN=2;
64
+    const ERROR=3;
65
+    const FATAL=4;
66
+
67
+    /** \OCP\Share\IManager */
68
+    private static $shareManager;
69
+
70
+    /**
71
+     * get the current installed version of ownCloud
72
+     * @return array
73
+     * @since 4.0.0
74
+     */
75
+    public static function getVersion() {
76
+        return \OC_Util::getVersion();
77
+    }
78 78
 	
79
-	/**
80
-	 * Set current update channel
81
-	 * @param string $channel
82
-	 * @since 8.1.0
83
-	 */
84
-	public static function setChannel($channel) {
85
-		\OC::$server->getConfig()->setSystemValue('updater.release.channel', $channel);
86
-	}
79
+    /**
80
+     * Set current update channel
81
+     * @param string $channel
82
+     * @since 8.1.0
83
+     */
84
+    public static function setChannel($channel) {
85
+        \OC::$server->getConfig()->setSystemValue('updater.release.channel', $channel);
86
+    }
87 87
 	
88
-	/**
89
-	 * Get current update channel
90
-	 * @return string
91
-	 * @since 8.1.0
92
-	 */
93
-	public static function getChannel() {
94
-		return \OC_Util::getChannel();
95
-	}
96
-
97
-	/**
98
-	 * send an email
99
-	 * @param string $toaddress
100
-	 * @param string $toname
101
-	 * @param string $subject
102
-	 * @param string $mailtext
103
-	 * @param string $fromaddress
104
-	 * @param string $fromname
105
-	 * @param int $html
106
-	 * @param string $altbody
107
-	 * @param string $ccaddress
108
-	 * @param string $ccname
109
-	 * @param string $bcc
110
-	 * @deprecated 8.1.0 Use \OCP\Mail\IMailer instead
111
-	 * @since 4.0.0
112
-	 */
113
-	public static function sendMail($toaddress, $toname, $subject, $mailtext, $fromaddress, $fromname,
114
-		$html = 0, $altbody = '', $ccaddress = '', $ccname = '', $bcc = '') {
115
-		$mailer = \OC::$server->getMailer();
116
-		$message = $mailer->createMessage();
117
-		$message->setTo([$toaddress => $toname]);
118
-		$message->setSubject($subject);
119
-		$message->setPlainBody($mailtext);
120
-		$message->setFrom([$fromaddress => $fromname]);
121
-		if($html === 1) {
122
-			$message->setHtmlBody($altbody);
123
-		}
124
-
125
-		if($altbody === '') {
126
-			$message->setHtmlBody($mailtext);
127
-			$message->setPlainBody('');
128
-		} else {
129
-			$message->setHtmlBody($mailtext);
130
-			$message->setPlainBody($altbody);
131
-		}
132
-
133
-		if(!empty($ccaddress)) {
134
-			if(!empty($ccname)) {
135
-				$message->setCc([$ccaddress => $ccname]);
136
-			} else {
137
-				$message->setCc([$ccaddress]);
138
-			}
139
-		}
140
-		if(!empty($bcc)) {
141
-			$message->setBcc([$bcc]);
142
-		}
143
-
144
-		$mailer->send($message);
145
-	}
146
-
147
-	/**
148
-	 * write a message in the log
149
-	 * @param string $app
150
-	 * @param string $message
151
-	 * @param int $level
152
-	 * @since 4.0.0
153
-	 * @deprecated 13.0.0 use log of \OCP\ILogger
154
-	 */
155
-	public static function writeLog( $app, $message, $level ) {
156
-		$context = ['app' => $app];
157
-		\OC::$server->getLogger()->log($level, $message, $context);
158
-	}
159
-
160
-	/**
161
-	 * write exception into the log
162
-	 * @param string $app app name
163
-	 * @param \Exception $ex exception to log
164
-	 * @param int $level log level, defaults to \OCP\Util::FATAL
165
-	 * @since ....0.0 - parameter $level was added in 7.0.0
166
-	 * @deprecated 8.2.0 use logException of \OCP\ILogger
167
-	 */
168
-	public static function logException( $app, \Exception $ex, $level = \OCP\Util::FATAL ) {
169
-		\OC::$server->getLogger()->logException($ex, ['app' => $app]);
170
-	}
171
-
172
-	/**
173
-	 * check if sharing is disabled for the current user
174
-	 *
175
-	 * @return boolean
176
-	 * @since 7.0.0
177
-	 * @deprecated 9.1.0 Use \OC::$server->getShareManager()->sharingDisabledForUser
178
-	 */
179
-	public static function isSharingDisabledForUser() {
180
-		if (self::$shareManager === null) {
181
-			self::$shareManager = \OC::$server->getShareManager();
182
-		}
183
-
184
-		$user = \OC::$server->getUserSession()->getUser();
185
-		if ($user !== null) {
186
-			$user = $user->getUID();
187
-		}
188
-
189
-		return self::$shareManager->sharingDisabledForUser($user);
190
-	}
191
-
192
-	/**
193
-	 * get l10n object
194
-	 * @param string $application
195
-	 * @param string|null $language
196
-	 * @return \OCP\IL10N
197
-	 * @since 6.0.0 - parameter $language was added in 8.0.0
198
-	 */
199
-	public static function getL10N($application, $language = null) {
200
-		return \OC::$server->getL10N($application, $language);
201
-	}
202
-
203
-	/**
204
-	 * add a css file
205
-	 * @param string $application
206
-	 * @param string $file
207
-	 * @since 4.0.0
208
-	 */
209
-	public static function addStyle( $application, $file = null ) {
210
-		\OC_Util::addStyle( $application, $file );
211
-	}
212
-
213
-	/**
214
-	 * add a javascript file
215
-	 * @param string $application
216
-	 * @param string $file
217
-	 * @since 4.0.0
218
-	 */
219
-	public static function addScript( $application, $file = null ) {
220
-		\OC_Util::addScript( $application, $file );
221
-	}
222
-
223
-	/**
224
-	 * Add a translation JS file
225
-	 * @param string $application application id
226
-	 * @param string $languageCode language code, defaults to the current locale
227
-	 * @since 8.0.0
228
-	 */
229
-	public static function addTranslations($application, $languageCode = null) {
230
-		\OC_Util::addTranslations($application, $languageCode);
231
-	}
232
-
233
-	/**
234
-	 * Add a custom element to the header
235
-	 * If $text is null then the element will be written as empty element.
236
-	 * So use "" to get a closing tag.
237
-	 * @param string $tag tag name of the element
238
-	 * @param array $attributes array of attributes for the element
239
-	 * @param string $text the text content for the element
240
-	 * @since 4.0.0
241
-	 */
242
-	public static function addHeader($tag, $attributes, $text=null) {
243
-		\OC_Util::addHeader($tag, $attributes, $text);
244
-	}
245
-
246
-	/**
247
-	 * formats a timestamp in the "right" way
248
-	 * @param int $timestamp $timestamp
249
-	 * @param bool $dateOnly option to omit time from the result
250
-	 * @param DateTimeZone|string $timeZone where the given timestamp shall be converted to
251
-	 * @return string timestamp
252
-	 *
253
-	 * @deprecated 8.0.0 Use \OC::$server->query('DateTimeFormatter') instead
254
-	 * @since 4.0.0
255
-	 */
256
-	public static function formatDate($timestamp, $dateOnly=false, $timeZone = null) {
257
-		return \OC_Util::formatDate($timestamp, $dateOnly, $timeZone);
258
-	}
259
-
260
-	/**
261
-	 * check if some encrypted files are stored
262
-	 * @return bool
263
-	 *
264
-	 * @deprecated 8.1.0 No longer required
265
-	 * @since 6.0.0
266
-	 */
267
-	public static function encryptedFiles() {
268
-		return false;
269
-	}
270
-
271
-	/**
272
-	 * Creates an absolute url to the given app and file.
273
-	 * @param string $app app
274
-	 * @param string $file file
275
-	 * @param array $args array with param=>value, will be appended to the returned url
276
-	 * 	The value of $args will be urlencoded
277
-	 * @return string the url
278
-	 * @since 4.0.0 - parameter $args was added in 4.5.0
279
-	 */
280
-	public static function linkToAbsolute( $app, $file, $args = array() ) {
281
-		$urlGenerator = \OC::$server->getURLGenerator();
282
-		return $urlGenerator->getAbsoluteURL(
283
-			$urlGenerator->linkTo($app, $file, $args)
284
-		);
285
-	}
286
-
287
-	/**
288
-	 * Creates an absolute url for remote use.
289
-	 * @param string $service id
290
-	 * @return string the url
291
-	 * @since 4.0.0
292
-	 */
293
-	public static function linkToRemote( $service ) {
294
-		$urlGenerator = \OC::$server->getURLGenerator();
295
-		$remoteBase = $urlGenerator->linkTo('', 'remote.php') . '/' . $service;
296
-		return $urlGenerator->getAbsoluteURL(
297
-			$remoteBase . (($service[strlen($service) - 1] != '/') ? '/' : '')
298
-		);
299
-	}
300
-
301
-	/**
302
-	 * Creates an absolute url for public use
303
-	 * @param string $service id
304
-	 * @return string the url
305
-	 * @since 4.5.0
306
-	 */
307
-	public static function linkToPublic($service) {
308
-		return \OC_Helper::linkToPublic($service);
309
-	}
310
-
311
-	/**
312
-	 * Creates an url using a defined route
313
-	 * @param string $route
314
-	 * @param array $parameters
315
-	 * @internal param array $args with param=>value, will be appended to the returned url
316
-	 * @return string the url
317
-	 * @deprecated 8.1.0 Use \OC::$server->getURLGenerator()->linkToRoute($route, $parameters)
318
-	 * @since 5.0.0
319
-	 */
320
-	public static function linkToRoute( $route, $parameters = array() ) {
321
-		return \OC::$server->getURLGenerator()->linkToRoute($route, $parameters);
322
-	}
323
-
324
-	/**
325
-	 * Creates an url to the given app and file
326
-	 * @param string $app app
327
-	 * @param string $file file
328
-	 * @param array $args array with param=>value, will be appended to the returned url
329
-	 * 	The value of $args will be urlencoded
330
-	 * @return string the url
331
-	 * @deprecated 8.1.0 Use \OC::$server->getURLGenerator()->linkTo($app, $file, $args)
332
-	 * @since 4.0.0 - parameter $args was added in 4.5.0
333
-	 */
334
-	public static function linkTo( $app, $file, $args = array() ) {
335
-		return \OC::$server->getURLGenerator()->linkTo($app, $file, $args);
336
-	}
337
-
338
-	/**
339
-	 * Returns the server host, even if the website uses one or more reverse proxy
340
-	 * @return string the server host
341
-	 * @deprecated 8.1.0 Use \OCP\IRequest::getServerHost
342
-	 * @since 4.0.0
343
-	 */
344
-	public static function getServerHost() {
345
-		return \OC::$server->getRequest()->getServerHost();
346
-	}
347
-
348
-	/**
349
-	 * Returns the server host name without an eventual port number
350
-	 * @return string the server hostname
351
-	 * @since 5.0.0
352
-	 */
353
-	public static function getServerHostName() {
354
-		$host_name = self::getServerHost();
355
-		// strip away port number (if existing)
356
-		$colon_pos = strpos($host_name, ':');
357
-		if ($colon_pos != FALSE) {
358
-			$host_name = substr($host_name, 0, $colon_pos);
359
-		}
360
-		return $host_name;
361
-	}
362
-
363
-	/**
364
-	 * Returns the default email address
365
-	 * @param string $user_part the user part of the address
366
-	 * @return string the default email address
367
-	 *
368
-	 * Assembles a default email address (using the server hostname
369
-	 * and the given user part, and returns it
370
-	 * Example: when given lostpassword-noreply as $user_part param,
371
-	 *     and is currently accessed via http(s)://example.com/,
372
-	 *     it would return '[email protected]'
373
-	 *
374
-	 * If the configuration value 'mail_from_address' is set in
375
-	 * config.php, this value will override the $user_part that
376
-	 * is passed to this function
377
-	 * @since 5.0.0
378
-	 */
379
-	public static function getDefaultEmailAddress($user_part) {
380
-		$config = \OC::$server->getConfig();
381
-		$user_part = $config->getSystemValue('mail_from_address', $user_part);
382
-		$host_name = self::getServerHostName();
383
-		$host_name = $config->getSystemValue('mail_domain', $host_name);
384
-		$defaultEmailAddress = $user_part.'@'.$host_name;
385
-
386
-		$mailer = \OC::$server->getMailer();
387
-		if ($mailer->validateMailAddress($defaultEmailAddress)) {
388
-			return $defaultEmailAddress;
389
-		}
390
-
391
-		// in case we cannot build a valid email address from the hostname let's fallback to 'localhost.localdomain'
392
-		return $user_part.'@localhost.localdomain';
393
-	}
394
-
395
-	/**
396
-	 * Returns the server protocol. It respects reverse proxy servers and load balancers
397
-	 * @return string the server protocol
398
-	 * @deprecated 8.1.0 Use \OCP\IRequest::getServerProtocol
399
-	 * @since 4.5.0
400
-	 */
401
-	public static function getServerProtocol() {
402
-		return \OC::$server->getRequest()->getServerProtocol();
403
-	}
404
-
405
-	/**
406
-	 * Returns the request uri, even if the website uses one or more reverse proxies
407
-	 * @return string the request uri
408
-	 * @deprecated 8.1.0 Use \OCP\IRequest::getRequestUri
409
-	 * @since 5.0.0
410
-	 */
411
-	public static function getRequestUri() {
412
-		return \OC::$server->getRequest()->getRequestUri();
413
-	}
414
-
415
-	/**
416
-	 * Returns the script name, even if the website uses one or more reverse proxies
417
-	 * @return string the script name
418
-	 * @deprecated 8.1.0 Use \OCP\IRequest::getScriptName
419
-	 * @since 5.0.0
420
-	 */
421
-	public static function getScriptName() {
422
-		return \OC::$server->getRequest()->getScriptName();
423
-	}
424
-
425
-	/**
426
-	 * Creates path to an image
427
-	 * @param string $app app
428
-	 * @param string $image image name
429
-	 * @return string the url
430
-	 * @deprecated 8.1.0 Use \OC::$server->getURLGenerator()->imagePath($app, $image)
431
-	 * @since 4.0.0
432
-	 */
433
-	public static function imagePath( $app, $image ) {
434
-		return \OC::$server->getURLGenerator()->imagePath($app, $image);
435
-	}
436
-
437
-	/**
438
-	 * Make a human file size (2048 to 2 kB)
439
-	 * @param int $bytes file size in bytes
440
-	 * @return string a human readable file size
441
-	 * @since 4.0.0
442
-	 */
443
-	public static function humanFileSize($bytes) {
444
-		return \OC_Helper::humanFileSize($bytes);
445
-	}
446
-
447
-	/**
448
-	 * Make a computer file size (2 kB to 2048)
449
-	 * @param string $str file size in a fancy format
450
-	 * @return int a file size in bytes
451
-	 *
452
-	 * Inspired by: http://www.php.net/manual/en/function.filesize.php#92418
453
-	 * @since 4.0.0
454
-	 */
455
-	public static function computerFileSize($str) {
456
-		return \OC_Helper::computerFileSize($str);
457
-	}
458
-
459
-	/**
460
-	 * connects a function to a hook
461
-	 *
462
-	 * @param string $signalClass class name of emitter
463
-	 * @param string $signalName name of signal
464
-	 * @param string|object $slotClass class name of slot
465
-	 * @param string $slotName name of slot
466
-	 * @return bool
467
-	 *
468
-	 * This function makes it very easy to connect to use hooks.
469
-	 *
470
-	 * TODO: write example
471
-	 * @since 4.0.0
472
-	 */
473
-	static public function connectHook($signalClass, $signalName, $slotClass, $slotName) {
474
-		return \OC_Hook::connect($signalClass, $signalName, $slotClass, $slotName);
475
-	}
476
-
477
-	/**
478
-	 * Emits a signal. To get data from the slot use references!
479
-	 * @param string $signalclass class name of emitter
480
-	 * @param string $signalname name of signal
481
-	 * @param array $params default: array() array with additional data
482
-	 * @return bool true if slots exists or false if not
483
-	 *
484
-	 * TODO: write example
485
-	 * @since 4.0.0
486
-	 */
487
-	static public function emitHook($signalclass, $signalname, $params = array()) {
488
-		return \OC_Hook::emit($signalclass, $signalname, $params);
489
-	}
490
-
491
-	/**
492
-	 * Cached encrypted CSRF token. Some static unit-tests of ownCloud compare
493
-	 * multiple OC_Template elements which invoke `callRegister`. If the value
494
-	 * would not be cached these unit-tests would fail.
495
-	 * @var string
496
-	 */
497
-	private static $token = '';
498
-
499
-	/**
500
-	 * Register an get/post call. This is important to prevent CSRF attacks
501
-	 * @since 4.5.0
502
-	 */
503
-	public static function callRegister() {
504
-		if(self::$token === '') {
505
-			self::$token = \OC::$server->getCsrfTokenManager()->getToken()->getEncryptedValue();
506
-		}
507
-		return self::$token;
508
-	}
509
-
510
-	/**
511
-	 * Check an ajax get/post call if the request token is valid. exit if not.
512
-	 * @since 4.5.0
513
-	 * @deprecated 9.0.0 Use annotations based on the app framework.
514
-	 */
515
-	public static function callCheck() {
516
-		if(!\OC::$server->getRequest()->passesStrictCookieCheck()) {
517
-			header('Location: '.\OC::$WEBROOT);
518
-			exit();
519
-		}
520
-
521
-		if (!\OC::$server->getRequest()->passesCSRFCheck()) {
522
-			exit();
523
-		}
524
-	}
525
-
526
-	/**
527
-	 * Used to sanitize HTML
528
-	 *
529
-	 * This function is used to sanitize HTML and should be applied on any
530
-	 * string or array of strings before displaying it on a web page.
531
-	 *
532
-	 * @param string|array $value
533
-	 * @return string|array an array of sanitized strings or a single sanitized string, depends on the input parameter.
534
-	 * @since 4.5.0
535
-	 */
536
-	public static function sanitizeHTML($value) {
537
-		return \OC_Util::sanitizeHTML($value);
538
-	}
539
-
540
-	/**
541
-	 * Public function to encode url parameters
542
-	 *
543
-	 * This function is used to encode path to file before output.
544
-	 * Encoding is done according to RFC 3986 with one exception:
545
-	 * Character '/' is preserved as is.
546
-	 *
547
-	 * @param string $component part of URI to encode
548
-	 * @return string
549
-	 * @since 6.0.0
550
-	 */
551
-	public static function encodePath($component) {
552
-		return \OC_Util::encodePath($component);
553
-	}
554
-
555
-	/**
556
-	 * Returns an array with all keys from input lowercased or uppercased. Numbered indices are left as is.
557
-	 *
558
-	 * @param array $input The array to work on
559
-	 * @param int $case Either MB_CASE_UPPER or MB_CASE_LOWER (default)
560
-	 * @param string $encoding The encoding parameter is the character encoding. Defaults to UTF-8
561
-	 * @return array
562
-	 * @since 4.5.0
563
-	 */
564
-	public static function mb_array_change_key_case($input, $case = MB_CASE_LOWER, $encoding = 'UTF-8') {
565
-		return \OC_Helper::mb_array_change_key_case($input, $case, $encoding);
566
-	}
567
-
568
-	/**
569
-	 * replaces a copy of string delimited by the start and (optionally) length parameters with the string given in replacement.
570
-	 *
571
-	 * @param string $string The input string. Opposite to the PHP build-in function does not accept an array.
572
-	 * @param string $replacement The replacement string.
573
-	 * @param int $start If start is positive, the replacing will begin at the start'th offset into string. If start is negative, the replacing will begin at the start'th character from the end of string.
574
-	 * @param int $length Length of the part to be replaced
575
-	 * @param string $encoding The encoding parameter is the character encoding. Defaults to UTF-8
576
-	 * @return string
577
-	 * @since 4.5.0
578
-	 * @deprecated 8.2.0 Use substr_replace() instead.
579
-	 */
580
-	public static function mb_substr_replace($string, $replacement, $start, $length = null, $encoding = 'UTF-8') {
581
-		return substr_replace($string, $replacement, $start, $length);
582
-	}
583
-
584
-	/**
585
-	 * Replace all occurrences of the search string with the replacement string
586
-	 *
587
-	 * @param string $search The value being searched for, otherwise known as the needle. String.
588
-	 * @param string $replace The replacement string.
589
-	 * @param string $subject The string or array being searched and replaced on, otherwise known as the haystack.
590
-	 * @param string $encoding The encoding parameter is the character encoding. Defaults to UTF-8
591
-	 * @param int $count If passed, this will be set to the number of replacements performed.
592
-	 * @return string
593
-	 * @since 4.5.0
594
-	 * @deprecated 8.2.0 Use str_replace() instead.
595
-	 */
596
-	public static function mb_str_replace($search, $replace, $subject, $encoding = 'UTF-8', &$count = null) {
597
-		return str_replace($search, $replace, $subject, $count);
598
-	}
599
-
600
-	/**
601
-	 * performs a search in a nested array
602
-	 *
603
-	 * @param array $haystack the array to be searched
604
-	 * @param string $needle the search string
605
-	 * @param int $index optional, only search this key name
606
-	 * @return mixed the key of the matching field, otherwise false
607
-	 * @since 4.5.0
608
-	 */
609
-	public static function recursiveArraySearch($haystack, $needle, $index = null) {
610
-		return \OC_Helper::recursiveArraySearch($haystack, $needle, $index);
611
-	}
612
-
613
-	/**
614
-	 * calculates the maximum upload size respecting system settings, free space and user quota
615
-	 *
616
-	 * @param string $dir the current folder where the user currently operates
617
-	 * @param int $free the number of bytes free on the storage holding $dir, if not set this will be received from the storage directly
618
-	 * @return int number of bytes representing
619
-	 * @since 5.0.0
620
-	 */
621
-	public static function maxUploadFilesize($dir, $free = null) {
622
-		return \OC_Helper::maxUploadFilesize($dir, $free);
623
-	}
624
-
625
-	/**
626
-	 * Calculate free space left within user quota
627
-	 * @param string $dir the current folder where the user currently operates
628
-	 * @return int number of bytes representing
629
-	 * @since 7.0.0
630
-	 */
631
-	public static function freeSpace($dir) {
632
-		return \OC_Helper::freeSpace($dir);
633
-	}
634
-
635
-	/**
636
-	 * Calculate PHP upload limit
637
-	 *
638
-	 * @return int number of bytes representing
639
-	 * @since 7.0.0
640
-	 */
641
-	public static function uploadLimit() {
642
-		return \OC_Helper::uploadLimit();
643
-	}
644
-
645
-	/**
646
-	 * Returns whether the given file name is valid
647
-	 * @param string $file file name to check
648
-	 * @return bool true if the file name is valid, false otherwise
649
-	 * @deprecated 8.1.0 use \OC\Files\View::verifyPath()
650
-	 * @since 7.0.0
651
-	 */
652
-	public static function isValidFileName($file) {
653
-		return \OC_Util::isValidFileName($file);
654
-	}
655
-
656
-	/**
657
-	 * Generates a cryptographic secure pseudo-random string
658
-	 * @param int $length of the random string
659
-	 * @return string
660
-	 * @deprecated 8.0.0 Use \OC::$server->getSecureRandom()->getMediumStrengthGenerator()->generate($length); instead
661
-	 * @since 7.0.0
662
-	 */
663
-	public static function generateRandomBytes($length = 30) {
664
-		return \OC::$server->getSecureRandom()->generate($length, \OCP\Security\ISecureRandom::CHAR_LOWER.\OCP\Security\ISecureRandom::CHAR_DIGITS);
665
-	}
666
-
667
-	/**
668
-	 * Compare two strings to provide a natural sort
669
-	 * @param string $a first string to compare
670
-	 * @param string $b second string to compare
671
-	 * @return -1 if $b comes before $a, 1 if $a comes before $b
672
-	 * or 0 if the strings are identical
673
-	 * @since 7.0.0
674
-	 */
675
-	public static function naturalSortCompare($a, $b) {
676
-		return \OC\NaturalSort::getInstance()->compare($a, $b);
677
-	}
678
-
679
-	/**
680
-	 * check if a password is required for each public link
681
-	 * @return boolean
682
-	 * @since 7.0.0
683
-	 */
684
-	public static function isPublicLinkPasswordRequired() {
685
-		return \OC_Util::isPublicLinkPasswordRequired();
686
-	}
687
-
688
-	/**
689
-	 * check if share API enforces a default expire date
690
-	 * @return boolean
691
-	 * @since 8.0.0
692
-	 */
693
-	public static function isDefaultExpireDateEnforced() {
694
-		return \OC_Util::isDefaultExpireDateEnforced();
695
-	}
696
-
697
-	protected static $needUpgradeCache = null;
698
-
699
-	/**
700
-	 * Checks whether the current version needs upgrade.
701
-	 *
702
-	 * @return bool true if upgrade is needed, false otherwise
703
-	 * @since 7.0.0
704
-	 */
705
-	public static function needUpgrade() {
706
-		if (!isset(self::$needUpgradeCache)) {
707
-			self::$needUpgradeCache=\OC_Util::needUpgrade(\OC::$server->getSystemConfig());
708
-		}		
709
-		return self::$needUpgradeCache;
710
-	}
88
+    /**
89
+     * Get current update channel
90
+     * @return string
91
+     * @since 8.1.0
92
+     */
93
+    public static function getChannel() {
94
+        return \OC_Util::getChannel();
95
+    }
96
+
97
+    /**
98
+     * send an email
99
+     * @param string $toaddress
100
+     * @param string $toname
101
+     * @param string $subject
102
+     * @param string $mailtext
103
+     * @param string $fromaddress
104
+     * @param string $fromname
105
+     * @param int $html
106
+     * @param string $altbody
107
+     * @param string $ccaddress
108
+     * @param string $ccname
109
+     * @param string $bcc
110
+     * @deprecated 8.1.0 Use \OCP\Mail\IMailer instead
111
+     * @since 4.0.0
112
+     */
113
+    public static function sendMail($toaddress, $toname, $subject, $mailtext, $fromaddress, $fromname,
114
+        $html = 0, $altbody = '', $ccaddress = '', $ccname = '', $bcc = '') {
115
+        $mailer = \OC::$server->getMailer();
116
+        $message = $mailer->createMessage();
117
+        $message->setTo([$toaddress => $toname]);
118
+        $message->setSubject($subject);
119
+        $message->setPlainBody($mailtext);
120
+        $message->setFrom([$fromaddress => $fromname]);
121
+        if($html === 1) {
122
+            $message->setHtmlBody($altbody);
123
+        }
124
+
125
+        if($altbody === '') {
126
+            $message->setHtmlBody($mailtext);
127
+            $message->setPlainBody('');
128
+        } else {
129
+            $message->setHtmlBody($mailtext);
130
+            $message->setPlainBody($altbody);
131
+        }
132
+
133
+        if(!empty($ccaddress)) {
134
+            if(!empty($ccname)) {
135
+                $message->setCc([$ccaddress => $ccname]);
136
+            } else {
137
+                $message->setCc([$ccaddress]);
138
+            }
139
+        }
140
+        if(!empty($bcc)) {
141
+            $message->setBcc([$bcc]);
142
+        }
143
+
144
+        $mailer->send($message);
145
+    }
146
+
147
+    /**
148
+     * write a message in the log
149
+     * @param string $app
150
+     * @param string $message
151
+     * @param int $level
152
+     * @since 4.0.0
153
+     * @deprecated 13.0.0 use log of \OCP\ILogger
154
+     */
155
+    public static function writeLog( $app, $message, $level ) {
156
+        $context = ['app' => $app];
157
+        \OC::$server->getLogger()->log($level, $message, $context);
158
+    }
159
+
160
+    /**
161
+     * write exception into the log
162
+     * @param string $app app name
163
+     * @param \Exception $ex exception to log
164
+     * @param int $level log level, defaults to \OCP\Util::FATAL
165
+     * @since ....0.0 - parameter $level was added in 7.0.0
166
+     * @deprecated 8.2.0 use logException of \OCP\ILogger
167
+     */
168
+    public static function logException( $app, \Exception $ex, $level = \OCP\Util::FATAL ) {
169
+        \OC::$server->getLogger()->logException($ex, ['app' => $app]);
170
+    }
171
+
172
+    /**
173
+     * check if sharing is disabled for the current user
174
+     *
175
+     * @return boolean
176
+     * @since 7.0.0
177
+     * @deprecated 9.1.0 Use \OC::$server->getShareManager()->sharingDisabledForUser
178
+     */
179
+    public static function isSharingDisabledForUser() {
180
+        if (self::$shareManager === null) {
181
+            self::$shareManager = \OC::$server->getShareManager();
182
+        }
183
+
184
+        $user = \OC::$server->getUserSession()->getUser();
185
+        if ($user !== null) {
186
+            $user = $user->getUID();
187
+        }
188
+
189
+        return self::$shareManager->sharingDisabledForUser($user);
190
+    }
191
+
192
+    /**
193
+     * get l10n object
194
+     * @param string $application
195
+     * @param string|null $language
196
+     * @return \OCP\IL10N
197
+     * @since 6.0.0 - parameter $language was added in 8.0.0
198
+     */
199
+    public static function getL10N($application, $language = null) {
200
+        return \OC::$server->getL10N($application, $language);
201
+    }
202
+
203
+    /**
204
+     * add a css file
205
+     * @param string $application
206
+     * @param string $file
207
+     * @since 4.0.0
208
+     */
209
+    public static function addStyle( $application, $file = null ) {
210
+        \OC_Util::addStyle( $application, $file );
211
+    }
212
+
213
+    /**
214
+     * add a javascript file
215
+     * @param string $application
216
+     * @param string $file
217
+     * @since 4.0.0
218
+     */
219
+    public static function addScript( $application, $file = null ) {
220
+        \OC_Util::addScript( $application, $file );
221
+    }
222
+
223
+    /**
224
+     * Add a translation JS file
225
+     * @param string $application application id
226
+     * @param string $languageCode language code, defaults to the current locale
227
+     * @since 8.0.0
228
+     */
229
+    public static function addTranslations($application, $languageCode = null) {
230
+        \OC_Util::addTranslations($application, $languageCode);
231
+    }
232
+
233
+    /**
234
+     * Add a custom element to the header
235
+     * If $text is null then the element will be written as empty element.
236
+     * So use "" to get a closing tag.
237
+     * @param string $tag tag name of the element
238
+     * @param array $attributes array of attributes for the element
239
+     * @param string $text the text content for the element
240
+     * @since 4.0.0
241
+     */
242
+    public static function addHeader($tag, $attributes, $text=null) {
243
+        \OC_Util::addHeader($tag, $attributes, $text);
244
+    }
245
+
246
+    /**
247
+     * formats a timestamp in the "right" way
248
+     * @param int $timestamp $timestamp
249
+     * @param bool $dateOnly option to omit time from the result
250
+     * @param DateTimeZone|string $timeZone where the given timestamp shall be converted to
251
+     * @return string timestamp
252
+     *
253
+     * @deprecated 8.0.0 Use \OC::$server->query('DateTimeFormatter') instead
254
+     * @since 4.0.0
255
+     */
256
+    public static function formatDate($timestamp, $dateOnly=false, $timeZone = null) {
257
+        return \OC_Util::formatDate($timestamp, $dateOnly, $timeZone);
258
+    }
259
+
260
+    /**
261
+     * check if some encrypted files are stored
262
+     * @return bool
263
+     *
264
+     * @deprecated 8.1.0 No longer required
265
+     * @since 6.0.0
266
+     */
267
+    public static function encryptedFiles() {
268
+        return false;
269
+    }
270
+
271
+    /**
272
+     * Creates an absolute url to the given app and file.
273
+     * @param string $app app
274
+     * @param string $file file
275
+     * @param array $args array with param=>value, will be appended to the returned url
276
+     * 	The value of $args will be urlencoded
277
+     * @return string the url
278
+     * @since 4.0.0 - parameter $args was added in 4.5.0
279
+     */
280
+    public static function linkToAbsolute( $app, $file, $args = array() ) {
281
+        $urlGenerator = \OC::$server->getURLGenerator();
282
+        return $urlGenerator->getAbsoluteURL(
283
+            $urlGenerator->linkTo($app, $file, $args)
284
+        );
285
+    }
286
+
287
+    /**
288
+     * Creates an absolute url for remote use.
289
+     * @param string $service id
290
+     * @return string the url
291
+     * @since 4.0.0
292
+     */
293
+    public static function linkToRemote( $service ) {
294
+        $urlGenerator = \OC::$server->getURLGenerator();
295
+        $remoteBase = $urlGenerator->linkTo('', 'remote.php') . '/' . $service;
296
+        return $urlGenerator->getAbsoluteURL(
297
+            $remoteBase . (($service[strlen($service) - 1] != '/') ? '/' : '')
298
+        );
299
+    }
300
+
301
+    /**
302
+     * Creates an absolute url for public use
303
+     * @param string $service id
304
+     * @return string the url
305
+     * @since 4.5.0
306
+     */
307
+    public static function linkToPublic($service) {
308
+        return \OC_Helper::linkToPublic($service);
309
+    }
310
+
311
+    /**
312
+     * Creates an url using a defined route
313
+     * @param string $route
314
+     * @param array $parameters
315
+     * @internal param array $args with param=>value, will be appended to the returned url
316
+     * @return string the url
317
+     * @deprecated 8.1.0 Use \OC::$server->getURLGenerator()->linkToRoute($route, $parameters)
318
+     * @since 5.0.0
319
+     */
320
+    public static function linkToRoute( $route, $parameters = array() ) {
321
+        return \OC::$server->getURLGenerator()->linkToRoute($route, $parameters);
322
+    }
323
+
324
+    /**
325
+     * Creates an url to the given app and file
326
+     * @param string $app app
327
+     * @param string $file file
328
+     * @param array $args array with param=>value, will be appended to the returned url
329
+     * 	The value of $args will be urlencoded
330
+     * @return string the url
331
+     * @deprecated 8.1.0 Use \OC::$server->getURLGenerator()->linkTo($app, $file, $args)
332
+     * @since 4.0.0 - parameter $args was added in 4.5.0
333
+     */
334
+    public static function linkTo( $app, $file, $args = array() ) {
335
+        return \OC::$server->getURLGenerator()->linkTo($app, $file, $args);
336
+    }
337
+
338
+    /**
339
+     * Returns the server host, even if the website uses one or more reverse proxy
340
+     * @return string the server host
341
+     * @deprecated 8.1.0 Use \OCP\IRequest::getServerHost
342
+     * @since 4.0.0
343
+     */
344
+    public static function getServerHost() {
345
+        return \OC::$server->getRequest()->getServerHost();
346
+    }
347
+
348
+    /**
349
+     * Returns the server host name without an eventual port number
350
+     * @return string the server hostname
351
+     * @since 5.0.0
352
+     */
353
+    public static function getServerHostName() {
354
+        $host_name = self::getServerHost();
355
+        // strip away port number (if existing)
356
+        $colon_pos = strpos($host_name, ':');
357
+        if ($colon_pos != FALSE) {
358
+            $host_name = substr($host_name, 0, $colon_pos);
359
+        }
360
+        return $host_name;
361
+    }
362
+
363
+    /**
364
+     * Returns the default email address
365
+     * @param string $user_part the user part of the address
366
+     * @return string the default email address
367
+     *
368
+     * Assembles a default email address (using the server hostname
369
+     * and the given user part, and returns it
370
+     * Example: when given lostpassword-noreply as $user_part param,
371
+     *     and is currently accessed via http(s)://example.com/,
372
+     *     it would return '[email protected]'
373
+     *
374
+     * If the configuration value 'mail_from_address' is set in
375
+     * config.php, this value will override the $user_part that
376
+     * is passed to this function
377
+     * @since 5.0.0
378
+     */
379
+    public static function getDefaultEmailAddress($user_part) {
380
+        $config = \OC::$server->getConfig();
381
+        $user_part = $config->getSystemValue('mail_from_address', $user_part);
382
+        $host_name = self::getServerHostName();
383
+        $host_name = $config->getSystemValue('mail_domain', $host_name);
384
+        $defaultEmailAddress = $user_part.'@'.$host_name;
385
+
386
+        $mailer = \OC::$server->getMailer();
387
+        if ($mailer->validateMailAddress($defaultEmailAddress)) {
388
+            return $defaultEmailAddress;
389
+        }
390
+
391
+        // in case we cannot build a valid email address from the hostname let's fallback to 'localhost.localdomain'
392
+        return $user_part.'@localhost.localdomain';
393
+    }
394
+
395
+    /**
396
+     * Returns the server protocol. It respects reverse proxy servers and load balancers
397
+     * @return string the server protocol
398
+     * @deprecated 8.1.0 Use \OCP\IRequest::getServerProtocol
399
+     * @since 4.5.0
400
+     */
401
+    public static function getServerProtocol() {
402
+        return \OC::$server->getRequest()->getServerProtocol();
403
+    }
404
+
405
+    /**
406
+     * Returns the request uri, even if the website uses one or more reverse proxies
407
+     * @return string the request uri
408
+     * @deprecated 8.1.0 Use \OCP\IRequest::getRequestUri
409
+     * @since 5.0.0
410
+     */
411
+    public static function getRequestUri() {
412
+        return \OC::$server->getRequest()->getRequestUri();
413
+    }
414
+
415
+    /**
416
+     * Returns the script name, even if the website uses one or more reverse proxies
417
+     * @return string the script name
418
+     * @deprecated 8.1.0 Use \OCP\IRequest::getScriptName
419
+     * @since 5.0.0
420
+     */
421
+    public static function getScriptName() {
422
+        return \OC::$server->getRequest()->getScriptName();
423
+    }
424
+
425
+    /**
426
+     * Creates path to an image
427
+     * @param string $app app
428
+     * @param string $image image name
429
+     * @return string the url
430
+     * @deprecated 8.1.0 Use \OC::$server->getURLGenerator()->imagePath($app, $image)
431
+     * @since 4.0.0
432
+     */
433
+    public static function imagePath( $app, $image ) {
434
+        return \OC::$server->getURLGenerator()->imagePath($app, $image);
435
+    }
436
+
437
+    /**
438
+     * Make a human file size (2048 to 2 kB)
439
+     * @param int $bytes file size in bytes
440
+     * @return string a human readable file size
441
+     * @since 4.0.0
442
+     */
443
+    public static function humanFileSize($bytes) {
444
+        return \OC_Helper::humanFileSize($bytes);
445
+    }
446
+
447
+    /**
448
+     * Make a computer file size (2 kB to 2048)
449
+     * @param string $str file size in a fancy format
450
+     * @return int a file size in bytes
451
+     *
452
+     * Inspired by: http://www.php.net/manual/en/function.filesize.php#92418
453
+     * @since 4.0.0
454
+     */
455
+    public static function computerFileSize($str) {
456
+        return \OC_Helper::computerFileSize($str);
457
+    }
458
+
459
+    /**
460
+     * connects a function to a hook
461
+     *
462
+     * @param string $signalClass class name of emitter
463
+     * @param string $signalName name of signal
464
+     * @param string|object $slotClass class name of slot
465
+     * @param string $slotName name of slot
466
+     * @return bool
467
+     *
468
+     * This function makes it very easy to connect to use hooks.
469
+     *
470
+     * TODO: write example
471
+     * @since 4.0.0
472
+     */
473
+    static public function connectHook($signalClass, $signalName, $slotClass, $slotName) {
474
+        return \OC_Hook::connect($signalClass, $signalName, $slotClass, $slotName);
475
+    }
476
+
477
+    /**
478
+     * Emits a signal. To get data from the slot use references!
479
+     * @param string $signalclass class name of emitter
480
+     * @param string $signalname name of signal
481
+     * @param array $params default: array() array with additional data
482
+     * @return bool true if slots exists or false if not
483
+     *
484
+     * TODO: write example
485
+     * @since 4.0.0
486
+     */
487
+    static public function emitHook($signalclass, $signalname, $params = array()) {
488
+        return \OC_Hook::emit($signalclass, $signalname, $params);
489
+    }
490
+
491
+    /**
492
+     * Cached encrypted CSRF token. Some static unit-tests of ownCloud compare
493
+     * multiple OC_Template elements which invoke `callRegister`. If the value
494
+     * would not be cached these unit-tests would fail.
495
+     * @var string
496
+     */
497
+    private static $token = '';
498
+
499
+    /**
500
+     * Register an get/post call. This is important to prevent CSRF attacks
501
+     * @since 4.5.0
502
+     */
503
+    public static function callRegister() {
504
+        if(self::$token === '') {
505
+            self::$token = \OC::$server->getCsrfTokenManager()->getToken()->getEncryptedValue();
506
+        }
507
+        return self::$token;
508
+    }
509
+
510
+    /**
511
+     * Check an ajax get/post call if the request token is valid. exit if not.
512
+     * @since 4.5.0
513
+     * @deprecated 9.0.0 Use annotations based on the app framework.
514
+     */
515
+    public static function callCheck() {
516
+        if(!\OC::$server->getRequest()->passesStrictCookieCheck()) {
517
+            header('Location: '.\OC::$WEBROOT);
518
+            exit();
519
+        }
520
+
521
+        if (!\OC::$server->getRequest()->passesCSRFCheck()) {
522
+            exit();
523
+        }
524
+    }
525
+
526
+    /**
527
+     * Used to sanitize HTML
528
+     *
529
+     * This function is used to sanitize HTML and should be applied on any
530
+     * string or array of strings before displaying it on a web page.
531
+     *
532
+     * @param string|array $value
533
+     * @return string|array an array of sanitized strings or a single sanitized string, depends on the input parameter.
534
+     * @since 4.5.0
535
+     */
536
+    public static function sanitizeHTML($value) {
537
+        return \OC_Util::sanitizeHTML($value);
538
+    }
539
+
540
+    /**
541
+     * Public function to encode url parameters
542
+     *
543
+     * This function is used to encode path to file before output.
544
+     * Encoding is done according to RFC 3986 with one exception:
545
+     * Character '/' is preserved as is.
546
+     *
547
+     * @param string $component part of URI to encode
548
+     * @return string
549
+     * @since 6.0.0
550
+     */
551
+    public static function encodePath($component) {
552
+        return \OC_Util::encodePath($component);
553
+    }
554
+
555
+    /**
556
+     * Returns an array with all keys from input lowercased or uppercased. Numbered indices are left as is.
557
+     *
558
+     * @param array $input The array to work on
559
+     * @param int $case Either MB_CASE_UPPER or MB_CASE_LOWER (default)
560
+     * @param string $encoding The encoding parameter is the character encoding. Defaults to UTF-8
561
+     * @return array
562
+     * @since 4.5.0
563
+     */
564
+    public static function mb_array_change_key_case($input, $case = MB_CASE_LOWER, $encoding = 'UTF-8') {
565
+        return \OC_Helper::mb_array_change_key_case($input, $case, $encoding);
566
+    }
567
+
568
+    /**
569
+     * replaces a copy of string delimited by the start and (optionally) length parameters with the string given in replacement.
570
+     *
571
+     * @param string $string The input string. Opposite to the PHP build-in function does not accept an array.
572
+     * @param string $replacement The replacement string.
573
+     * @param int $start If start is positive, the replacing will begin at the start'th offset into string. If start is negative, the replacing will begin at the start'th character from the end of string.
574
+     * @param int $length Length of the part to be replaced
575
+     * @param string $encoding The encoding parameter is the character encoding. Defaults to UTF-8
576
+     * @return string
577
+     * @since 4.5.0
578
+     * @deprecated 8.2.0 Use substr_replace() instead.
579
+     */
580
+    public static function mb_substr_replace($string, $replacement, $start, $length = null, $encoding = 'UTF-8') {
581
+        return substr_replace($string, $replacement, $start, $length);
582
+    }
583
+
584
+    /**
585
+     * Replace all occurrences of the search string with the replacement string
586
+     *
587
+     * @param string $search The value being searched for, otherwise known as the needle. String.
588
+     * @param string $replace The replacement string.
589
+     * @param string $subject The string or array being searched and replaced on, otherwise known as the haystack.
590
+     * @param string $encoding The encoding parameter is the character encoding. Defaults to UTF-8
591
+     * @param int $count If passed, this will be set to the number of replacements performed.
592
+     * @return string
593
+     * @since 4.5.0
594
+     * @deprecated 8.2.0 Use str_replace() instead.
595
+     */
596
+    public static function mb_str_replace($search, $replace, $subject, $encoding = 'UTF-8', &$count = null) {
597
+        return str_replace($search, $replace, $subject, $count);
598
+    }
599
+
600
+    /**
601
+     * performs a search in a nested array
602
+     *
603
+     * @param array $haystack the array to be searched
604
+     * @param string $needle the search string
605
+     * @param int $index optional, only search this key name
606
+     * @return mixed the key of the matching field, otherwise false
607
+     * @since 4.5.0
608
+     */
609
+    public static function recursiveArraySearch($haystack, $needle, $index = null) {
610
+        return \OC_Helper::recursiveArraySearch($haystack, $needle, $index);
611
+    }
612
+
613
+    /**
614
+     * calculates the maximum upload size respecting system settings, free space and user quota
615
+     *
616
+     * @param string $dir the current folder where the user currently operates
617
+     * @param int $free the number of bytes free on the storage holding $dir, if not set this will be received from the storage directly
618
+     * @return int number of bytes representing
619
+     * @since 5.0.0
620
+     */
621
+    public static function maxUploadFilesize($dir, $free = null) {
622
+        return \OC_Helper::maxUploadFilesize($dir, $free);
623
+    }
624
+
625
+    /**
626
+     * Calculate free space left within user quota
627
+     * @param string $dir the current folder where the user currently operates
628
+     * @return int number of bytes representing
629
+     * @since 7.0.0
630
+     */
631
+    public static function freeSpace($dir) {
632
+        return \OC_Helper::freeSpace($dir);
633
+    }
634
+
635
+    /**
636
+     * Calculate PHP upload limit
637
+     *
638
+     * @return int number of bytes representing
639
+     * @since 7.0.0
640
+     */
641
+    public static function uploadLimit() {
642
+        return \OC_Helper::uploadLimit();
643
+    }
644
+
645
+    /**
646
+     * Returns whether the given file name is valid
647
+     * @param string $file file name to check
648
+     * @return bool true if the file name is valid, false otherwise
649
+     * @deprecated 8.1.0 use \OC\Files\View::verifyPath()
650
+     * @since 7.0.0
651
+     */
652
+    public static function isValidFileName($file) {
653
+        return \OC_Util::isValidFileName($file);
654
+    }
655
+
656
+    /**
657
+     * Generates a cryptographic secure pseudo-random string
658
+     * @param int $length of the random string
659
+     * @return string
660
+     * @deprecated 8.0.0 Use \OC::$server->getSecureRandom()->getMediumStrengthGenerator()->generate($length); instead
661
+     * @since 7.0.0
662
+     */
663
+    public static function generateRandomBytes($length = 30) {
664
+        return \OC::$server->getSecureRandom()->generate($length, \OCP\Security\ISecureRandom::CHAR_LOWER.\OCP\Security\ISecureRandom::CHAR_DIGITS);
665
+    }
666
+
667
+    /**
668
+     * Compare two strings to provide a natural sort
669
+     * @param string $a first string to compare
670
+     * @param string $b second string to compare
671
+     * @return -1 if $b comes before $a, 1 if $a comes before $b
672
+     * or 0 if the strings are identical
673
+     * @since 7.0.0
674
+     */
675
+    public static function naturalSortCompare($a, $b) {
676
+        return \OC\NaturalSort::getInstance()->compare($a, $b);
677
+    }
678
+
679
+    /**
680
+     * check if a password is required for each public link
681
+     * @return boolean
682
+     * @since 7.0.0
683
+     */
684
+    public static function isPublicLinkPasswordRequired() {
685
+        return \OC_Util::isPublicLinkPasswordRequired();
686
+    }
687
+
688
+    /**
689
+     * check if share API enforces a default expire date
690
+     * @return boolean
691
+     * @since 8.0.0
692
+     */
693
+    public static function isDefaultExpireDateEnforced() {
694
+        return \OC_Util::isDefaultExpireDateEnforced();
695
+    }
696
+
697
+    protected static $needUpgradeCache = null;
698
+
699
+    /**
700
+     * Checks whether the current version needs upgrade.
701
+     *
702
+     * @return bool true if upgrade is needed, false otherwise
703
+     * @since 7.0.0
704
+     */
705
+    public static function needUpgrade() {
706
+        if (!isset(self::$needUpgradeCache)) {
707
+            self::$needUpgradeCache=\OC_Util::needUpgrade(\OC::$server->getSystemConfig());
708
+        }		
709
+        return self::$needUpgradeCache;
710
+    }
711 711
 }
Please login to merge, or discard this patch.
Spacing   +28 added lines, -28 removed lines patch added patch discarded remove patch
@@ -58,11 +58,11 @@  discard block
 block discarded – undo
58 58
  */
59 59
 class Util {
60 60
 	// consts for Logging
61
-	const DEBUG=0;
62
-	const INFO=1;
63
-	const WARN=2;
64
-	const ERROR=3;
65
-	const FATAL=4;
61
+	const DEBUG = 0;
62
+	const INFO = 1;
63
+	const WARN = 2;
64
+	const ERROR = 3;
65
+	const FATAL = 4;
66 66
 
67 67
 	/** \OCP\Share\IManager */
68 68
 	private static $shareManager;
@@ -118,11 +118,11 @@  discard block
 block discarded – undo
118 118
 		$message->setSubject($subject);
119 119
 		$message->setPlainBody($mailtext);
120 120
 		$message->setFrom([$fromaddress => $fromname]);
121
-		if($html === 1) {
121
+		if ($html === 1) {
122 122
 			$message->setHtmlBody($altbody);
123 123
 		}
124 124
 
125
-		if($altbody === '') {
125
+		if ($altbody === '') {
126 126
 			$message->setHtmlBody($mailtext);
127 127
 			$message->setPlainBody('');
128 128
 		} else {
@@ -130,14 +130,14 @@  discard block
 block discarded – undo
130 130
 			$message->setPlainBody($altbody);
131 131
 		}
132 132
 
133
-		if(!empty($ccaddress)) {
134
-			if(!empty($ccname)) {
133
+		if (!empty($ccaddress)) {
134
+			if (!empty($ccname)) {
135 135
 				$message->setCc([$ccaddress => $ccname]);
136 136
 			} else {
137 137
 				$message->setCc([$ccaddress]);
138 138
 			}
139 139
 		}
140
-		if(!empty($bcc)) {
140
+		if (!empty($bcc)) {
141 141
 			$message->setBcc([$bcc]);
142 142
 		}
143 143
 
@@ -152,7 +152,7 @@  discard block
 block discarded – undo
152 152
 	 * @since 4.0.0
153 153
 	 * @deprecated 13.0.0 use log of \OCP\ILogger
154 154
 	 */
155
-	public static function writeLog( $app, $message, $level ) {
155
+	public static function writeLog($app, $message, $level) {
156 156
 		$context = ['app' => $app];
157 157
 		\OC::$server->getLogger()->log($level, $message, $context);
158 158
 	}
@@ -165,7 +165,7 @@  discard block
 block discarded – undo
165 165
 	 * @since ....0.0 - parameter $level was added in 7.0.0
166 166
 	 * @deprecated 8.2.0 use logException of \OCP\ILogger
167 167
 	 */
168
-	public static function logException( $app, \Exception $ex, $level = \OCP\Util::FATAL ) {
168
+	public static function logException($app, \Exception $ex, $level = \OCP\Util::FATAL) {
169 169
 		\OC::$server->getLogger()->logException($ex, ['app' => $app]);
170 170
 	}
171 171
 
@@ -206,8 +206,8 @@  discard block
 block discarded – undo
206 206
 	 * @param string $file
207 207
 	 * @since 4.0.0
208 208
 	 */
209
-	public static function addStyle( $application, $file = null ) {
210
-		\OC_Util::addStyle( $application, $file );
209
+	public static function addStyle($application, $file = null) {
210
+		\OC_Util::addStyle($application, $file);
211 211
 	}
212 212
 
213 213
 	/**
@@ -216,8 +216,8 @@  discard block
 block discarded – undo
216 216
 	 * @param string $file
217 217
 	 * @since 4.0.0
218 218
 	 */
219
-	public static function addScript( $application, $file = null ) {
220
-		\OC_Util::addScript( $application, $file );
219
+	public static function addScript($application, $file = null) {
220
+		\OC_Util::addScript($application, $file);
221 221
 	}
222 222
 
223 223
 	/**
@@ -239,7 +239,7 @@  discard block
 block discarded – undo
239 239
 	 * @param string $text the text content for the element
240 240
 	 * @since 4.0.0
241 241
 	 */
242
-	public static function addHeader($tag, $attributes, $text=null) {
242
+	public static function addHeader($tag, $attributes, $text = null) {
243 243
 		\OC_Util::addHeader($tag, $attributes, $text);
244 244
 	}
245 245
 
@@ -253,7 +253,7 @@  discard block
 block discarded – undo
253 253
 	 * @deprecated 8.0.0 Use \OC::$server->query('DateTimeFormatter') instead
254 254
 	 * @since 4.0.0
255 255
 	 */
256
-	public static function formatDate($timestamp, $dateOnly=false, $timeZone = null) {
256
+	public static function formatDate($timestamp, $dateOnly = false, $timeZone = null) {
257 257
 		return \OC_Util::formatDate($timestamp, $dateOnly, $timeZone);
258 258
 	}
259 259
 
@@ -277,7 +277,7 @@  discard block
 block discarded – undo
277 277
 	 * @return string the url
278 278
 	 * @since 4.0.0 - parameter $args was added in 4.5.0
279 279
 	 */
280
-	public static function linkToAbsolute( $app, $file, $args = array() ) {
280
+	public static function linkToAbsolute($app, $file, $args = array()) {
281 281
 		$urlGenerator = \OC::$server->getURLGenerator();
282 282
 		return $urlGenerator->getAbsoluteURL(
283 283
 			$urlGenerator->linkTo($app, $file, $args)
@@ -290,11 +290,11 @@  discard block
 block discarded – undo
290 290
 	 * @return string the url
291 291
 	 * @since 4.0.0
292 292
 	 */
293
-	public static function linkToRemote( $service ) {
293
+	public static function linkToRemote($service) {
294 294
 		$urlGenerator = \OC::$server->getURLGenerator();
295
-		$remoteBase = $urlGenerator->linkTo('', 'remote.php') . '/' . $service;
295
+		$remoteBase = $urlGenerator->linkTo('', 'remote.php').'/'.$service;
296 296
 		return $urlGenerator->getAbsoluteURL(
297
-			$remoteBase . (($service[strlen($service) - 1] != '/') ? '/' : '')
297
+			$remoteBase.(($service[strlen($service) - 1] != '/') ? '/' : '')
298 298
 		);
299 299
 	}
300 300
 
@@ -317,7 +317,7 @@  discard block
 block discarded – undo
317 317
 	 * @deprecated 8.1.0 Use \OC::$server->getURLGenerator()->linkToRoute($route, $parameters)
318 318
 	 * @since 5.0.0
319 319
 	 */
320
-	public static function linkToRoute( $route, $parameters = array() ) {
320
+	public static function linkToRoute($route, $parameters = array()) {
321 321
 		return \OC::$server->getURLGenerator()->linkToRoute($route, $parameters);
322 322
 	}
323 323
 
@@ -331,7 +331,7 @@  discard block
 block discarded – undo
331 331
 	 * @deprecated 8.1.0 Use \OC::$server->getURLGenerator()->linkTo($app, $file, $args)
332 332
 	 * @since 4.0.0 - parameter $args was added in 4.5.0
333 333
 	 */
334
-	public static function linkTo( $app, $file, $args = array() ) {
334
+	public static function linkTo($app, $file, $args = array()) {
335 335
 		return \OC::$server->getURLGenerator()->linkTo($app, $file, $args);
336 336
 	}
337 337
 
@@ -430,7 +430,7 @@  discard block
 block discarded – undo
430 430
 	 * @deprecated 8.1.0 Use \OC::$server->getURLGenerator()->imagePath($app, $image)
431 431
 	 * @since 4.0.0
432 432
 	 */
433
-	public static function imagePath( $app, $image ) {
433
+	public static function imagePath($app, $image) {
434 434
 		return \OC::$server->getURLGenerator()->imagePath($app, $image);
435 435
 	}
436 436
 
@@ -501,7 +501,7 @@  discard block
 block discarded – undo
501 501
 	 * @since 4.5.0
502 502
 	 */
503 503
 	public static function callRegister() {
504
-		if(self::$token === '') {
504
+		if (self::$token === '') {
505 505
 			self::$token = \OC::$server->getCsrfTokenManager()->getToken()->getEncryptedValue();
506 506
 		}
507 507
 		return self::$token;
@@ -513,7 +513,7 @@  discard block
 block discarded – undo
513 513
 	 * @deprecated 9.0.0 Use annotations based on the app framework.
514 514
 	 */
515 515
 	public static function callCheck() {
516
-		if(!\OC::$server->getRequest()->passesStrictCookieCheck()) {
516
+		if (!\OC::$server->getRequest()->passesStrictCookieCheck()) {
517 517
 			header('Location: '.\OC::$WEBROOT);
518 518
 			exit();
519 519
 		}
@@ -704,7 +704,7 @@  discard block
 block discarded – undo
704 704
 	 */
705 705
 	public static function needUpgrade() {
706 706
 		if (!isset(self::$needUpgradeCache)) {
707
-			self::$needUpgradeCache=\OC_Util::needUpgrade(\OC::$server->getSystemConfig());
707
+			self::$needUpgradeCache = \OC_Util::needUpgrade(\OC::$server->getSystemConfig());
708 708
 		}		
709 709
 		return self::$needUpgradeCache;
710 710
 	}
Please login to merge, or discard this patch.
lib/private/Files/View.php 3 patches
Doc Comments   +4 added lines, -4 removed lines patch added patch discarded remove patch
@@ -200,7 +200,7 @@  discard block
 block discarded – undo
200 200
 	 * and does not take the chroot into account )
201 201
 	 *
202 202
 	 * @param string $path
203
-	 * @return \OCP\Files\Mount\IMountPoint
203
+	 * @return Mount\MountPoint|null
204 204
 	 */
205 205
 	public function getMount($path) {
206 206
 		return Filesystem::getMountManager()->find($this->getAbsolutePath($path));
@@ -963,7 +963,7 @@  discard block
 block discarded – undo
963 963
 
964 964
 	/**
965 965
 	 * @param string $path
966
-	 * @return bool|string
966
+	 * @return string|false
967 967
 	 * @throws \OCP\Files\InvalidPathException
968 968
 	 */
969 969
 	public function toTmpFile($path) {
@@ -1078,7 +1078,7 @@  discard block
 block discarded – undo
1078 1078
 	 * @param string $path
1079 1079
 	 * @param array $hooks (optional)
1080 1080
 	 * @param mixed $extraParam (optional)
1081
-	 * @return mixed
1081
+	 * @return string
1082 1082
 	 * @throws \Exception
1083 1083
 	 *
1084 1084
 	 * This method takes requests for basic filesystem functions (e.g. reading & writing
@@ -2086,7 +2086,7 @@  discard block
 block discarded – undo
2086 2086
 
2087 2087
 	/**
2088 2088
 	 * @param string $filename
2089
-	 * @return array
2089
+	 * @return string[]
2090 2090
 	 * @throws \OC\User\NoUserException
2091 2091
 	 * @throws NotFoundException
2092 2092
 	 */
Please login to merge, or discard this patch.
Spacing   +39 added lines, -39 removed lines patch added patch discarded remove patch
@@ -125,9 +125,9 @@  discard block
 block discarded – undo
125 125
 			$path = '/';
126 126
 		}
127 127
 		if ($path[0] !== '/') {
128
-			$path = '/' . $path;
128
+			$path = '/'.$path;
129 129
 		}
130
-		return $this->fakeRoot . $path;
130
+		return $this->fakeRoot.$path;
131 131
 	}
132 132
 
133 133
 	/**
@@ -139,7 +139,7 @@  discard block
 block discarded – undo
139 139
 	public function chroot($fakeRoot) {
140 140
 		if (!$fakeRoot == '') {
141 141
 			if ($fakeRoot[0] !== '/') {
142
-				$fakeRoot = '/' . $fakeRoot;
142
+				$fakeRoot = '/'.$fakeRoot;
143 143
 			}
144 144
 		}
145 145
 		$this->fakeRoot = $fakeRoot;
@@ -171,7 +171,7 @@  discard block
 block discarded – undo
171 171
 		}
172 172
 
173 173
 		// missing slashes can cause wrong matches!
174
-		$root = rtrim($this->fakeRoot, '/') . '/';
174
+		$root = rtrim($this->fakeRoot, '/').'/';
175 175
 
176 176
 		if (strpos($path, $root) !== 0) {
177 177
 			return null;
@@ -277,7 +277,7 @@  discard block
 block discarded – undo
277 277
 		if ($mount instanceof MoveableMount) {
278 278
 			// cut of /user/files to get the relative path to data/user/files
279 279
 			$pathParts = explode('/', $path, 4);
280
-			$relPath = '/' . $pathParts[3];
280
+			$relPath = '/'.$pathParts[3];
281 281
 			$this->lockFile($relPath, ILockingProvider::LOCK_SHARED, true);
282 282
 			\OC_Hook::emit(
283 283
 				Filesystem::CLASSNAME, "umount",
@@ -688,7 +688,7 @@  discard block
 block discarded – undo
688 688
 		}
689 689
 		$postFix = (substr($path, -1, 1) === '/') ? '/' : '';
690 690
 		$absolutePath = Filesystem::normalizePath($this->getAbsolutePath($path));
691
-		$mount = Filesystem::getMountManager()->find($absolutePath . $postFix);
691
+		$mount = Filesystem::getMountManager()->find($absolutePath.$postFix);
692 692
 		if ($mount and $mount->getInternalPath($absolutePath) === '') {
693 693
 			return $this->removeMount($mount, $absolutePath);
694 694
 		}
@@ -954,7 +954,7 @@  discard block
 block discarded – undo
954 954
 				$hooks[] = 'write';
955 955
 				break;
956 956
 			default:
957
-				\OCP\Util::writeLog('core', 'invalid mode (' . $mode . ') for ' . $path, \OCP\Util::ERROR);
957
+				\OCP\Util::writeLog('core', 'invalid mode ('.$mode.') for '.$path, \OCP\Util::ERROR);
958 958
 		}
959 959
 
960 960
 		if ($mode !== 'r' && $mode !== 'w') {
@@ -1058,7 +1058,7 @@  discard block
 block discarded – undo
1058 1058
 					array(Filesystem::signal_param_path => $this->getHookPath($path))
1059 1059
 				);
1060 1060
 			}
1061
-			list($storage, $internalPath) = Filesystem::resolvePath($absolutePath . $postFix);
1061
+			list($storage, $internalPath) = Filesystem::resolvePath($absolutePath.$postFix);
1062 1062
 			if ($storage) {
1063 1063
 				$result = $storage->hash($type, $internalPath, $raw);
1064 1064
 				return $result;
@@ -1109,7 +1109,7 @@  discard block
 block discarded – undo
1109 1109
 
1110 1110
 			$run = $this->runHooks($hooks, $path);
1111 1111
 			/** @var \OC\Files\Storage\Storage $storage */
1112
-			list($storage, $internalPath) = Filesystem::resolvePath($absolutePath . $postFix);
1112
+			list($storage, $internalPath) = Filesystem::resolvePath($absolutePath.$postFix);
1113 1113
 			if ($run and $storage) {
1114 1114
 				if (in_array('write', $hooks) || in_array('delete', $hooks)) {
1115 1115
 					$this->changeLock($path, ILockingProvider::LOCK_EXCLUSIVE);
@@ -1148,7 +1148,7 @@  discard block
 block discarded – undo
1148 1148
 					$unlockLater = true;
1149 1149
 					// make sure our unlocking callback will still be called if connection is aborted
1150 1150
 					ignore_user_abort(true);
1151
-					$result = CallbackWrapper::wrap($result, null, null, function () use ($hooks, $path) {
1151
+					$result = CallbackWrapper::wrap($result, null, null, function() use ($hooks, $path) {
1152 1152
 						if (in_array('write', $hooks)) {
1153 1153
 							$this->unlockFile($path, ILockingProvider::LOCK_EXCLUSIVE);
1154 1154
 						} else if (in_array('read', $hooks)) {
@@ -1209,7 +1209,7 @@  discard block
 block discarded – undo
1209 1209
 			return true;
1210 1210
 		}
1211 1211
 
1212
-		return (strlen($fullPath) > strlen($defaultRoot)) && (substr($fullPath, 0, strlen($defaultRoot) + 1) === $defaultRoot . '/');
1212
+		return (strlen($fullPath) > strlen($defaultRoot)) && (substr($fullPath, 0, strlen($defaultRoot) + 1) === $defaultRoot.'/');
1213 1213
 	}
1214 1214
 
1215 1215
 	/**
@@ -1228,7 +1228,7 @@  discard block
 block discarded – undo
1228 1228
 				if ($hook != 'read') {
1229 1229
 					\OC_Hook::emit(
1230 1230
 						Filesystem::CLASSNAME,
1231
-						$prefix . $hook,
1231
+						$prefix.$hook,
1232 1232
 						array(
1233 1233
 							Filesystem::signal_param_run => &$run,
1234 1234
 							Filesystem::signal_param_path => $path
@@ -1237,7 +1237,7 @@  discard block
 block discarded – undo
1237 1237
 				} elseif (!$post) {
1238 1238
 					\OC_Hook::emit(
1239 1239
 						Filesystem::CLASSNAME,
1240
-						$prefix . $hook,
1240
+						$prefix.$hook,
1241 1241
 						array(
1242 1242
 							Filesystem::signal_param_path => $path
1243 1243
 						)
@@ -1332,7 +1332,7 @@  discard block
 block discarded – undo
1332 1332
 			return $this->getPartFileInfo($path);
1333 1333
 		}
1334 1334
 		$relativePath = $path;
1335
-		$path = Filesystem::normalizePath($this->fakeRoot . '/' . $path);
1335
+		$path = Filesystem::normalizePath($this->fakeRoot.'/'.$path);
1336 1336
 
1337 1337
 		$mount = Filesystem::getMountManager()->find($path);
1338 1338
 		$storage = $mount->getStorage();
@@ -1356,7 +1356,7 @@  discard block
 block discarded – undo
1356 1356
 					//add the sizes of other mount points to the folder
1357 1357
 					$extOnly = ($includeMountPoints === 'ext');
1358 1358
 					$mounts = Filesystem::getMountManager()->findIn($path);
1359
-					$info->setSubMounts(array_filter($mounts, function (IMountPoint $mount) use ($extOnly) {
1359
+					$info->setSubMounts(array_filter($mounts, function(IMountPoint $mount) use ($extOnly) {
1360 1360
 						$subStorage = $mount->getStorage();
1361 1361
 						return !($extOnly && $subStorage instanceof \OCA\Files_Sharing\SharedStorage);
1362 1362
 					}));
@@ -1403,12 +1403,12 @@  discard block
 block discarded – undo
1403 1403
 			/**
1404 1404
 			 * @var \OC\Files\FileInfo[] $files
1405 1405
 			 */
1406
-			$files = array_map(function (ICacheEntry $content) use ($path, $storage, $mount, $sharingDisabled) {
1406
+			$files = array_map(function(ICacheEntry $content) use ($path, $storage, $mount, $sharingDisabled) {
1407 1407
 				if ($sharingDisabled) {
1408 1408
 					$content['permissions'] = $content['permissions'] & ~\OCP\Constants::PERMISSION_SHARE;
1409 1409
 				}
1410 1410
 				$owner = $this->getUserObjectForOwner($storage->getOwner($content['path']));
1411
-				return new FileInfo($path . '/' . $content['name'], $storage, $content['path'], $content, $mount, $owner);
1411
+				return new FileInfo($path.'/'.$content['name'], $storage, $content['path'], $content, $mount, $owner);
1412 1412
 			}, $contents);
1413 1413
 
1414 1414
 			//add a folder for any mountpoint in this directory and add the sizes of other mountpoints to the folders
@@ -1433,8 +1433,8 @@  discard block
 block discarded – undo
1433 1433
 							// sometimes when the storage is not available it can be any exception
1434 1434
 							\OCP\Util::writeLog(
1435 1435
 								'core',
1436
-								'Exception while scanning storage "' . $subStorage->getId() . '": ' .
1437
-								get_class($e) . ': ' . $e->getMessage(),
1436
+								'Exception while scanning storage "'.$subStorage->getId().'": '.
1437
+								get_class($e).': '.$e->getMessage(),
1438 1438
 								\OCP\Util::ERROR
1439 1439
 							);
1440 1440
 							continue;
@@ -1471,7 +1471,7 @@  discard block
 block discarded – undo
1471 1471
 									break;
1472 1472
 								}
1473 1473
 							}
1474
-							$rootEntry['path'] = substr(Filesystem::normalizePath($path . '/' . $rootEntry['name']), strlen($user) + 2); // full path without /$user/
1474
+							$rootEntry['path'] = substr(Filesystem::normalizePath($path.'/'.$rootEntry['name']), strlen($user) + 2); // full path without /$user/
1475 1475
 
1476 1476
 							// if sharing was disabled for the user we remove the share permissions
1477 1477
 							if (\OCP\Util::isSharingDisabledForUser()) {
@@ -1479,14 +1479,14 @@  discard block
 block discarded – undo
1479 1479
 							}
1480 1480
 
1481 1481
 							$owner = $this->getUserObjectForOwner($subStorage->getOwner(''));
1482
-							$files[] = new FileInfo($path . '/' . $rootEntry['name'], $subStorage, '', $rootEntry, $mount, $owner);
1482
+							$files[] = new FileInfo($path.'/'.$rootEntry['name'], $subStorage, '', $rootEntry, $mount, $owner);
1483 1483
 						}
1484 1484
 					}
1485 1485
 				}
1486 1486
 			}
1487 1487
 
1488 1488
 			if ($mimetype_filter) {
1489
-				$files = array_filter($files, function (FileInfo $file) use ($mimetype_filter) {
1489
+				$files = array_filter($files, function(FileInfo $file) use ($mimetype_filter) {
1490 1490
 					if (strpos($mimetype_filter, '/')) {
1491 1491
 						return $file->getMimetype() === $mimetype_filter;
1492 1492
 					} else {
@@ -1515,7 +1515,7 @@  discard block
 block discarded – undo
1515 1515
 		if ($data instanceof FileInfo) {
1516 1516
 			$data = $data->getData();
1517 1517
 		}
1518
-		$path = Filesystem::normalizePath($this->fakeRoot . '/' . $path);
1518
+		$path = Filesystem::normalizePath($this->fakeRoot.'/'.$path);
1519 1519
 		/**
1520 1520
 		 * @var \OC\Files\Storage\Storage $storage
1521 1521
 		 * @var string $internalPath
@@ -1542,7 +1542,7 @@  discard block
 block discarded – undo
1542 1542
 	 * @return FileInfo[]
1543 1543
 	 */
1544 1544
 	public function search($query) {
1545
-		return $this->searchCommon('search', array('%' . $query . '%'));
1545
+		return $this->searchCommon('search', array('%'.$query.'%'));
1546 1546
 	}
1547 1547
 
1548 1548
 	/**
@@ -1593,10 +1593,10 @@  discard block
 block discarded – undo
1593 1593
 
1594 1594
 			$results = call_user_func_array(array($cache, $method), $args);
1595 1595
 			foreach ($results as $result) {
1596
-				if (substr($mountPoint . $result['path'], 0, $rootLength + 1) === $this->fakeRoot . '/') {
1596
+				if (substr($mountPoint.$result['path'], 0, $rootLength + 1) === $this->fakeRoot.'/') {
1597 1597
 					$internalPath = $result['path'];
1598
-					$path = $mountPoint . $result['path'];
1599
-					$result['path'] = substr($mountPoint . $result['path'], $rootLength);
1598
+					$path = $mountPoint.$result['path'];
1599
+					$result['path'] = substr($mountPoint.$result['path'], $rootLength);
1600 1600
 					$owner = \OC::$server->getUserManager()->get($storage->getOwner($internalPath));
1601 1601
 					$files[] = new FileInfo($path, $storage, $internalPath, $result, $mount, $owner);
1602 1602
 				}
@@ -1614,8 +1614,8 @@  discard block
 block discarded – undo
1614 1614
 					if ($results) {
1615 1615
 						foreach ($results as $result) {
1616 1616
 							$internalPath = $result['path'];
1617
-							$result['path'] = rtrim($relativeMountPoint . $result['path'], '/');
1618
-							$path = rtrim($mountPoint . $internalPath, '/');
1617
+							$result['path'] = rtrim($relativeMountPoint.$result['path'], '/');
1618
+							$path = rtrim($mountPoint.$internalPath, '/');
1619 1619
 							$owner = \OC::$server->getUserManager()->get($storage->getOwner($internalPath));
1620 1620
 							$files[] = new FileInfo($path, $storage, $internalPath, $result, $mount, $owner);
1621 1621
 						}
@@ -1636,7 +1636,7 @@  discard block
 block discarded – undo
1636 1636
 	public function getOwner($path) {
1637 1637
 		$info = $this->getFileInfo($path);
1638 1638
 		if (!$info) {
1639
-			throw new NotFoundException($path . ' not found while trying to get owner');
1639
+			throw new NotFoundException($path.' not found while trying to get owner');
1640 1640
 		}
1641 1641
 		return $info->getOwner()->getUID();
1642 1642
 	}
@@ -1670,7 +1670,7 @@  discard block
 block discarded – undo
1670 1670
 	 * @return string
1671 1671
 	 */
1672 1672
 	public function getPath($id) {
1673
-		$id = (int)$id;
1673
+		$id = (int) $id;
1674 1674
 		$manager = Filesystem::getMountManager();
1675 1675
 		$mounts = $manager->findIn($this->fakeRoot);
1676 1676
 		$mounts[] = $manager->find($this->fakeRoot);
@@ -1685,7 +1685,7 @@  discard block
 block discarded – undo
1685 1685
 				$cache = $mount->getStorage()->getCache();
1686 1686
 				$internalPath = $cache->getPathById($id);
1687 1687
 				if (is_string($internalPath)) {
1688
-					$fullPath = $mount->getMountPoint() . $internalPath;
1688
+					$fullPath = $mount->getMountPoint().$internalPath;
1689 1689
 					if (!is_null($path = $this->getRelativePath($fullPath))) {
1690 1690
 						return $path;
1691 1691
 					}
@@ -1728,10 +1728,10 @@  discard block
 block discarded – undo
1728 1728
 		}
1729 1729
 
1730 1730
 		// note: cannot use the view because the target is already locked
1731
-		$fileId = (int)$targetStorage->getCache()->getId($targetInternalPath);
1731
+		$fileId = (int) $targetStorage->getCache()->getId($targetInternalPath);
1732 1732
 		if ($fileId === -1) {
1733 1733
 			// target might not exist, need to check parent instead
1734
-			$fileId = (int)$targetStorage->getCache()->getId(dirname($targetInternalPath));
1734
+			$fileId = (int) $targetStorage->getCache()->getId(dirname($targetInternalPath));
1735 1735
 		}
1736 1736
 
1737 1737
 		// check if any of the parents were shared by the current owner (include collections)
@@ -1831,7 +1831,7 @@  discard block
 block discarded – undo
1831 1831
 		$resultPath = '';
1832 1832
 		foreach ($parts as $part) {
1833 1833
 			if ($part) {
1834
-				$resultPath .= '/' . $part;
1834
+				$resultPath .= '/'.$part;
1835 1835
 				$result[] = $resultPath;
1836 1836
 			}
1837 1837
 		}
@@ -2081,16 +2081,16 @@  discard block
 block discarded – undo
2081 2081
 	public function getUidAndFilename($filename) {
2082 2082
 		$info = $this->getFileInfo($filename);
2083 2083
 		if (!$info instanceof \OCP\Files\FileInfo) {
2084
-			throw new NotFoundException($this->getAbsolutePath($filename) . ' not found');
2084
+			throw new NotFoundException($this->getAbsolutePath($filename).' not found');
2085 2085
 		}
2086 2086
 		$uid = $info->getOwner()->getUID();
2087 2087
 		if ($uid != \OCP\User::getUser()) {
2088 2088
 			Filesystem::initMountPoints($uid);
2089
-			$ownerView = new View('/' . $uid . '/files');
2089
+			$ownerView = new View('/'.$uid.'/files');
2090 2090
 			try {
2091 2091
 				$filename = $ownerView->getPath($info['fileid']);
2092 2092
 			} catch (NotFoundException $e) {
2093
-				throw new NotFoundException('File with id ' . $info['fileid'] . ' not found for user ' . $uid);
2093
+				throw new NotFoundException('File with id '.$info['fileid'].' not found for user '.$uid);
2094 2094
 			}
2095 2095
 		}
2096 2096
 		return [$uid, $filename];
@@ -2107,7 +2107,7 @@  discard block
 block discarded – undo
2107 2107
 		$directoryParts = array_filter($directoryParts);
2108 2108
 		foreach ($directoryParts as $key => $part) {
2109 2109
 			$currentPathElements = array_slice($directoryParts, 0, $key);
2110
-			$currentPath = '/' . implode('/', $currentPathElements);
2110
+			$currentPath = '/'.implode('/', $currentPathElements);
2111 2111
 			if ($this->is_file($currentPath)) {
2112 2112
 				return false;
2113 2113
 			}
Please login to merge, or discard this patch.
Indentation   +2048 added lines, -2048 removed lines patch added patch discarded remove patch
@@ -82,2052 +82,2052 @@
 block discarded – undo
82 82
  * \OC\Files\Storage\Storage object
83 83
  */
84 84
 class View {
85
-	/** @var string */
86
-	private $fakeRoot = '';
87
-
88
-	/**
89
-	 * @var \OCP\Lock\ILockingProvider
90
-	 */
91
-	protected $lockingProvider;
92
-
93
-	private $lockingEnabled;
94
-
95
-	private $updaterEnabled = true;
96
-
97
-	/** @var \OC\User\Manager */
98
-	private $userManager;
99
-
100
-	/** @var \OCP\ILogger */
101
-	private $logger;
102
-
103
-	/**
104
-	 * @param string $root
105
-	 * @throws \Exception If $root contains an invalid path
106
-	 */
107
-	public function __construct($root = '') {
108
-		if (is_null($root)) {
109
-			throw new \InvalidArgumentException('Root can\'t be null');
110
-		}
111
-		if (!Filesystem::isValidPath($root)) {
112
-			throw new \Exception();
113
-		}
114
-
115
-		$this->fakeRoot = $root;
116
-		$this->lockingProvider = \OC::$server->getLockingProvider();
117
-		$this->lockingEnabled = !($this->lockingProvider instanceof \OC\Lock\NoopLockingProvider);
118
-		$this->userManager = \OC::$server->getUserManager();
119
-		$this->logger = \OC::$server->getLogger();
120
-	}
121
-
122
-	public function getAbsolutePath($path = '/') {
123
-		if ($path === null) {
124
-			return null;
125
-		}
126
-		$this->assertPathLength($path);
127
-		if ($path === '') {
128
-			$path = '/';
129
-		}
130
-		if ($path[0] !== '/') {
131
-			$path = '/' . $path;
132
-		}
133
-		return $this->fakeRoot . $path;
134
-	}
135
-
136
-	/**
137
-	 * change the root to a fake root
138
-	 *
139
-	 * @param string $fakeRoot
140
-	 * @return boolean|null
141
-	 */
142
-	public function chroot($fakeRoot) {
143
-		if (!$fakeRoot == '') {
144
-			if ($fakeRoot[0] !== '/') {
145
-				$fakeRoot = '/' . $fakeRoot;
146
-			}
147
-		}
148
-		$this->fakeRoot = $fakeRoot;
149
-	}
150
-
151
-	/**
152
-	 * get the fake root
153
-	 *
154
-	 * @return string
155
-	 */
156
-	public function getRoot() {
157
-		return $this->fakeRoot;
158
-	}
159
-
160
-	/**
161
-	 * get path relative to the root of the view
162
-	 *
163
-	 * @param string $path
164
-	 * @return string
165
-	 */
166
-	public function getRelativePath($path) {
167
-		$this->assertPathLength($path);
168
-		if ($this->fakeRoot == '') {
169
-			return $path;
170
-		}
171
-
172
-		if (rtrim($path, '/') === rtrim($this->fakeRoot, '/')) {
173
-			return '/';
174
-		}
175
-
176
-		// missing slashes can cause wrong matches!
177
-		$root = rtrim($this->fakeRoot, '/') . '/';
178
-
179
-		if (strpos($path, $root) !== 0) {
180
-			return null;
181
-		} else {
182
-			$path = substr($path, strlen($this->fakeRoot));
183
-			if (strlen($path) === 0) {
184
-				return '/';
185
-			} else {
186
-				return $path;
187
-			}
188
-		}
189
-	}
190
-
191
-	/**
192
-	 * get the mountpoint of the storage object for a path
193
-	 * ( note: because a storage is not always mounted inside the fakeroot, the
194
-	 * returned mountpoint is relative to the absolute root of the filesystem
195
-	 * and does not take the chroot into account )
196
-	 *
197
-	 * @param string $path
198
-	 * @return string
199
-	 */
200
-	public function getMountPoint($path) {
201
-		return Filesystem::getMountPoint($this->getAbsolutePath($path));
202
-	}
203
-
204
-	/**
205
-	 * get the mountpoint of the storage object for a path
206
-	 * ( note: because a storage is not always mounted inside the fakeroot, the
207
-	 * returned mountpoint is relative to the absolute root of the filesystem
208
-	 * and does not take the chroot into account )
209
-	 *
210
-	 * @param string $path
211
-	 * @return \OCP\Files\Mount\IMountPoint
212
-	 */
213
-	public function getMount($path) {
214
-		return Filesystem::getMountManager()->find($this->getAbsolutePath($path));
215
-	}
216
-
217
-	/**
218
-	 * resolve a path to a storage and internal path
219
-	 *
220
-	 * @param string $path
221
-	 * @return array an array consisting of the storage and the internal path
222
-	 */
223
-	public function resolvePath($path) {
224
-		$a = $this->getAbsolutePath($path);
225
-		$p = Filesystem::normalizePath($a);
226
-		return Filesystem::resolvePath($p);
227
-	}
228
-
229
-	/**
230
-	 * return the path to a local version of the file
231
-	 * we need this because we can't know if a file is stored local or not from
232
-	 * outside the filestorage and for some purposes a local file is needed
233
-	 *
234
-	 * @param string $path
235
-	 * @return string
236
-	 */
237
-	public function getLocalFile($path) {
238
-		$parent = substr($path, 0, strrpos($path, '/'));
239
-		$path = $this->getAbsolutePath($path);
240
-		list($storage, $internalPath) = Filesystem::resolvePath($path);
241
-		if (Filesystem::isValidPath($parent) and $storage) {
242
-			return $storage->getLocalFile($internalPath);
243
-		} else {
244
-			return null;
245
-		}
246
-	}
247
-
248
-	/**
249
-	 * @param string $path
250
-	 * @return string
251
-	 */
252
-	public function getLocalFolder($path) {
253
-		$parent = substr($path, 0, strrpos($path, '/'));
254
-		$path = $this->getAbsolutePath($path);
255
-		list($storage, $internalPath) = Filesystem::resolvePath($path);
256
-		if (Filesystem::isValidPath($parent) and $storage) {
257
-			return $storage->getLocalFolder($internalPath);
258
-		} else {
259
-			return null;
260
-		}
261
-	}
262
-
263
-	/**
264
-	 * the following functions operate with arguments and return values identical
265
-	 * to those of their PHP built-in equivalents. Mostly they are merely wrappers
266
-	 * for \OC\Files\Storage\Storage via basicOperation().
267
-	 */
268
-	public function mkdir($path) {
269
-		return $this->basicOperation('mkdir', $path, array('create', 'write'));
270
-	}
271
-
272
-	/**
273
-	 * remove mount point
274
-	 *
275
-	 * @param \OC\Files\Mount\MoveableMount $mount
276
-	 * @param string $path relative to data/
277
-	 * @return boolean
278
-	 */
279
-	protected function removeMount($mount, $path) {
280
-		if ($mount instanceof MoveableMount) {
281
-			// cut of /user/files to get the relative path to data/user/files
282
-			$pathParts = explode('/', $path, 4);
283
-			$relPath = '/' . $pathParts[3];
284
-			$this->lockFile($relPath, ILockingProvider::LOCK_SHARED, true);
285
-			\OC_Hook::emit(
286
-				Filesystem::CLASSNAME, "umount",
287
-				array(Filesystem::signal_param_path => $relPath)
288
-			);
289
-			$this->changeLock($relPath, ILockingProvider::LOCK_EXCLUSIVE, true);
290
-			$result = $mount->removeMount();
291
-			$this->changeLock($relPath, ILockingProvider::LOCK_SHARED, true);
292
-			if ($result) {
293
-				\OC_Hook::emit(
294
-					Filesystem::CLASSNAME, "post_umount",
295
-					array(Filesystem::signal_param_path => $relPath)
296
-				);
297
-			}
298
-			$this->unlockFile($relPath, ILockingProvider::LOCK_SHARED, true);
299
-			return $result;
300
-		} else {
301
-			// do not allow deleting the storage's root / the mount point
302
-			// because for some storages it might delete the whole contents
303
-			// but isn't supposed to work that way
304
-			return false;
305
-		}
306
-	}
307
-
308
-	public function disableCacheUpdate() {
309
-		$this->updaterEnabled = false;
310
-	}
311
-
312
-	public function enableCacheUpdate() {
313
-		$this->updaterEnabled = true;
314
-	}
315
-
316
-	protected function writeUpdate(Storage $storage, $internalPath, $time = null) {
317
-		if ($this->updaterEnabled) {
318
-			if (is_null($time)) {
319
-				$time = time();
320
-			}
321
-			$storage->getUpdater()->update($internalPath, $time);
322
-		}
323
-	}
324
-
325
-	protected function removeUpdate(Storage $storage, $internalPath) {
326
-		if ($this->updaterEnabled) {
327
-			$storage->getUpdater()->remove($internalPath);
328
-		}
329
-	}
330
-
331
-	protected function renameUpdate(Storage $sourceStorage, Storage $targetStorage, $sourceInternalPath, $targetInternalPath) {
332
-		if ($this->updaterEnabled) {
333
-			$targetStorage->getUpdater()->renameFromStorage($sourceStorage, $sourceInternalPath, $targetInternalPath);
334
-		}
335
-	}
336
-
337
-	/**
338
-	 * @param string $path
339
-	 * @return bool|mixed
340
-	 */
341
-	public function rmdir($path) {
342
-		$absolutePath = $this->getAbsolutePath($path);
343
-		$mount = Filesystem::getMountManager()->find($absolutePath);
344
-		if ($mount->getInternalPath($absolutePath) === '') {
345
-			return $this->removeMount($mount, $absolutePath);
346
-		}
347
-		if ($this->is_dir($path)) {
348
-			$result = $this->basicOperation('rmdir', $path, array('delete'));
349
-		} else {
350
-			$result = false;
351
-		}
352
-
353
-		if (!$result && !$this->file_exists($path)) { //clear ghost files from the cache on delete
354
-			$storage = $mount->getStorage();
355
-			$internalPath = $mount->getInternalPath($absolutePath);
356
-			$storage->getUpdater()->remove($internalPath);
357
-		}
358
-		return $result;
359
-	}
360
-
361
-	/**
362
-	 * @param string $path
363
-	 * @return resource
364
-	 */
365
-	public function opendir($path) {
366
-		return $this->basicOperation('opendir', $path, array('read'));
367
-	}
368
-
369
-	/**
370
-	 * @param string $path
371
-	 * @return bool|mixed
372
-	 */
373
-	public function is_dir($path) {
374
-		if ($path == '/') {
375
-			return true;
376
-		}
377
-		return $this->basicOperation('is_dir', $path);
378
-	}
379
-
380
-	/**
381
-	 * @param string $path
382
-	 * @return bool|mixed
383
-	 */
384
-	public function is_file($path) {
385
-		if ($path == '/') {
386
-			return false;
387
-		}
388
-		return $this->basicOperation('is_file', $path);
389
-	}
390
-
391
-	/**
392
-	 * @param string $path
393
-	 * @return mixed
394
-	 */
395
-	public function stat($path) {
396
-		return $this->basicOperation('stat', $path);
397
-	}
398
-
399
-	/**
400
-	 * @param string $path
401
-	 * @return mixed
402
-	 */
403
-	public function filetype($path) {
404
-		return $this->basicOperation('filetype', $path);
405
-	}
406
-
407
-	/**
408
-	 * @param string $path
409
-	 * @return mixed
410
-	 */
411
-	public function filesize($path) {
412
-		return $this->basicOperation('filesize', $path);
413
-	}
414
-
415
-	/**
416
-	 * @param string $path
417
-	 * @return bool|mixed
418
-	 * @throws \OCP\Files\InvalidPathException
419
-	 */
420
-	public function readfile($path) {
421
-		$this->assertPathLength($path);
422
-		@ob_end_clean();
423
-		$handle = $this->fopen($path, 'rb');
424
-		if ($handle) {
425
-			$chunkSize = 8192; // 8 kB chunks
426
-			while (!feof($handle)) {
427
-				echo fread($handle, $chunkSize);
428
-				flush();
429
-			}
430
-			fclose($handle);
431
-			$size = $this->filesize($path);
432
-			return $size;
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
-			if (fseek($handle, $from) === 0) {
451
-				$chunkSize = 8192; // 8 kB chunks
452
-				$end = $to + 1;
453
-				while (!feof($handle) && ftell($handle) < $end) {
454
-					$len = $end - ftell($handle);
455
-					if ($len > $chunkSize) {
456
-						$len = $chunkSize;
457
-					}
458
-					echo fread($handle, $len);
459
-					flush();
460
-				}
461
-				$size = ftell($handle) - $from;
462
-				return $size;
463
-			}
464
-
465
-			throw new \OCP\Files\UnseekableException('fseek error');
466
-		}
467
-		return false;
468
-	}
469
-
470
-	/**
471
-	 * @param string $path
472
-	 * @return mixed
473
-	 */
474
-	public function isCreatable($path) {
475
-		return $this->basicOperation('isCreatable', $path);
476
-	}
477
-
478
-	/**
479
-	 * @param string $path
480
-	 * @return mixed
481
-	 */
482
-	public function isReadable($path) {
483
-		return $this->basicOperation('isReadable', $path);
484
-	}
485
-
486
-	/**
487
-	 * @param string $path
488
-	 * @return mixed
489
-	 */
490
-	public function isUpdatable($path) {
491
-		return $this->basicOperation('isUpdatable', $path);
492
-	}
493
-
494
-	/**
495
-	 * @param string $path
496
-	 * @return bool|mixed
497
-	 */
498
-	public function isDeletable($path) {
499
-		$absolutePath = $this->getAbsolutePath($path);
500
-		$mount = Filesystem::getMountManager()->find($absolutePath);
501
-		if ($mount->getInternalPath($absolutePath) === '') {
502
-			return $mount instanceof MoveableMount;
503
-		}
504
-		return $this->basicOperation('isDeletable', $path);
505
-	}
506
-
507
-	/**
508
-	 * @param string $path
509
-	 * @return mixed
510
-	 */
511
-	public function isSharable($path) {
512
-		return $this->basicOperation('isSharable', $path);
513
-	}
514
-
515
-	/**
516
-	 * @param string $path
517
-	 * @return bool|mixed
518
-	 */
519
-	public function file_exists($path) {
520
-		if ($path == '/') {
521
-			return true;
522
-		}
523
-		return $this->basicOperation('file_exists', $path);
524
-	}
525
-
526
-	/**
527
-	 * @param string $path
528
-	 * @return mixed
529
-	 */
530
-	public function filemtime($path) {
531
-		return $this->basicOperation('filemtime', $path);
532
-	}
533
-
534
-	/**
535
-	 * @param string $path
536
-	 * @param int|string $mtime
537
-	 * @return bool
538
-	 */
539
-	public function touch($path, $mtime = null) {
540
-		if (!is_null($mtime) and !is_numeric($mtime)) {
541
-			$mtime = strtotime($mtime);
542
-		}
543
-
544
-		$hooks = array('touch');
545
-
546
-		if (!$this->file_exists($path)) {
547
-			$hooks[] = 'create';
548
-			$hooks[] = 'write';
549
-		}
550
-		$result = $this->basicOperation('touch', $path, $hooks, $mtime);
551
-		if (!$result) {
552
-			// If create file fails because of permissions on external storage like SMB folders,
553
-			// check file exists and return false if not.
554
-			if (!$this->file_exists($path)) {
555
-				return false;
556
-			}
557
-			if (is_null($mtime)) {
558
-				$mtime = time();
559
-			}
560
-			//if native touch fails, we emulate it by changing the mtime in the cache
561
-			$this->putFileInfo($path, array('mtime' => floor($mtime)));
562
-		}
563
-		return true;
564
-	}
565
-
566
-	/**
567
-	 * @param string $path
568
-	 * @return mixed
569
-	 */
570
-	public function file_get_contents($path) {
571
-		return $this->basicOperation('file_get_contents', $path, array('read'));
572
-	}
573
-
574
-	/**
575
-	 * @param bool $exists
576
-	 * @param string $path
577
-	 * @param bool $run
578
-	 */
579
-	protected function emit_file_hooks_pre($exists, $path, &$run) {
580
-		if (!$exists) {
581
-			\OC_Hook::emit(Filesystem::CLASSNAME, Filesystem::signal_create, array(
582
-				Filesystem::signal_param_path => $this->getHookPath($path),
583
-				Filesystem::signal_param_run => &$run,
584
-			));
585
-		} else {
586
-			\OC_Hook::emit(Filesystem::CLASSNAME, Filesystem::signal_update, array(
587
-				Filesystem::signal_param_path => $this->getHookPath($path),
588
-				Filesystem::signal_param_run => &$run,
589
-			));
590
-		}
591
-		\OC_Hook::emit(Filesystem::CLASSNAME, Filesystem::signal_write, array(
592
-			Filesystem::signal_param_path => $this->getHookPath($path),
593
-			Filesystem::signal_param_run => &$run,
594
-		));
595
-	}
596
-
597
-	/**
598
-	 * @param bool $exists
599
-	 * @param string $path
600
-	 */
601
-	protected function emit_file_hooks_post($exists, $path) {
602
-		if (!$exists) {
603
-			\OC_Hook::emit(Filesystem::CLASSNAME, Filesystem::signal_post_create, array(
604
-				Filesystem::signal_param_path => $this->getHookPath($path),
605
-			));
606
-		} else {
607
-			\OC_Hook::emit(Filesystem::CLASSNAME, Filesystem::signal_post_update, array(
608
-				Filesystem::signal_param_path => $this->getHookPath($path),
609
-			));
610
-		}
611
-		\OC_Hook::emit(Filesystem::CLASSNAME, Filesystem::signal_post_write, array(
612
-			Filesystem::signal_param_path => $this->getHookPath($path),
613
-		));
614
-	}
615
-
616
-	/**
617
-	 * @param string $path
618
-	 * @param mixed $data
619
-	 * @return bool|mixed
620
-	 * @throws \Exception
621
-	 */
622
-	public function file_put_contents($path, $data) {
623
-		if (is_resource($data)) { //not having to deal with streams in file_put_contents makes life easier
624
-			$absolutePath = Filesystem::normalizePath($this->getAbsolutePath($path));
625
-			if (Filesystem::isValidPath($path)
626
-				and !Filesystem::isFileBlacklisted($path)
627
-			) {
628
-				$path = $this->getRelativePath($absolutePath);
629
-
630
-				$this->lockFile($path, ILockingProvider::LOCK_SHARED);
631
-
632
-				$exists = $this->file_exists($path);
633
-				$run = true;
634
-				if ($this->shouldEmitHooks($path)) {
635
-					$this->emit_file_hooks_pre($exists, $path, $run);
636
-				}
637
-				if (!$run) {
638
-					$this->unlockFile($path, ILockingProvider::LOCK_SHARED);
639
-					return false;
640
-				}
641
-
642
-				$this->changeLock($path, ILockingProvider::LOCK_EXCLUSIVE);
643
-
644
-				/** @var \OC\Files\Storage\Storage $storage */
645
-				list($storage, $internalPath) = $this->resolvePath($path);
646
-				$target = $storage->fopen($internalPath, 'w');
647
-				if ($target) {
648
-					list (, $result) = \OC_Helper::streamCopy($data, $target);
649
-					fclose($target);
650
-					fclose($data);
651
-
652
-					$this->writeUpdate($storage, $internalPath);
653
-
654
-					$this->changeLock($path, ILockingProvider::LOCK_SHARED);
655
-
656
-					if ($this->shouldEmitHooks($path) && $result !== false) {
657
-						$this->emit_file_hooks_post($exists, $path);
658
-					}
659
-					$this->unlockFile($path, ILockingProvider::LOCK_SHARED);
660
-					return $result;
661
-				} else {
662
-					$this->unlockFile($path, ILockingProvider::LOCK_EXCLUSIVE);
663
-					return false;
664
-				}
665
-			} else {
666
-				return false;
667
-			}
668
-		} else {
669
-			$hooks = ($this->file_exists($path)) ? array('update', 'write') : array('create', 'write');
670
-			return $this->basicOperation('file_put_contents', $path, $hooks, $data);
671
-		}
672
-	}
673
-
674
-	/**
675
-	 * @param string $path
676
-	 * @return bool|mixed
677
-	 */
678
-	public function unlink($path) {
679
-		if ($path === '' || $path === '/') {
680
-			// do not allow deleting the root
681
-			return false;
682
-		}
683
-		$postFix = (substr($path, -1, 1) === '/') ? '/' : '';
684
-		$absolutePath = Filesystem::normalizePath($this->getAbsolutePath($path));
685
-		$mount = Filesystem::getMountManager()->find($absolutePath . $postFix);
686
-		if ($mount and $mount->getInternalPath($absolutePath) === '') {
687
-			return $this->removeMount($mount, $absolutePath);
688
-		}
689
-		if ($this->is_dir($path)) {
690
-			$result = $this->basicOperation('rmdir', $path, ['delete']);
691
-		} else {
692
-			$result = $this->basicOperation('unlink', $path, ['delete']);
693
-		}
694
-		if (!$result && !$this->file_exists($path)) { //clear ghost files from the cache on delete
695
-			$storage = $mount->getStorage();
696
-			$internalPath = $mount->getInternalPath($absolutePath);
697
-			$storage->getUpdater()->remove($internalPath);
698
-			return true;
699
-		} else {
700
-			return $result;
701
-		}
702
-	}
703
-
704
-	/**
705
-	 * @param string $directory
706
-	 * @return bool|mixed
707
-	 */
708
-	public function deleteAll($directory) {
709
-		return $this->rmdir($directory);
710
-	}
711
-
712
-	/**
713
-	 * Rename/move a file or folder from the source path to target path.
714
-	 *
715
-	 * @param string $path1 source path
716
-	 * @param string $path2 target path
717
-	 *
718
-	 * @return bool|mixed
719
-	 */
720
-	public function rename($path1, $path2) {
721
-		$absolutePath1 = Filesystem::normalizePath($this->getAbsolutePath($path1));
722
-		$absolutePath2 = Filesystem::normalizePath($this->getAbsolutePath($path2));
723
-		$result = false;
724
-		if (
725
-			Filesystem::isValidPath($path2)
726
-			and Filesystem::isValidPath($path1)
727
-			and !Filesystem::isFileBlacklisted($path2)
728
-		) {
729
-			$path1 = $this->getRelativePath($absolutePath1);
730
-			$path2 = $this->getRelativePath($absolutePath2);
731
-			$exists = $this->file_exists($path2);
732
-
733
-			if ($path1 == null or $path2 == null) {
734
-				return false;
735
-			}
736
-
737
-			$this->lockFile($path1, ILockingProvider::LOCK_SHARED, true);
738
-			try {
739
-				$this->lockFile($path2, ILockingProvider::LOCK_SHARED, true);
740
-			} catch (LockedException $e) {
741
-				$this->unlockFile($path1, ILockingProvider::LOCK_SHARED);
742
-				throw $e;
743
-			}
744
-
745
-			$run = true;
746
-			if ($this->shouldEmitHooks($path1) && (Cache\Scanner::isPartialFile($path1) && !Cache\Scanner::isPartialFile($path2))) {
747
-				// if it was a rename from a part file to a regular file it was a write and not a rename operation
748
-				$this->emit_file_hooks_pre($exists, $path2, $run);
749
-			} elseif ($this->shouldEmitHooks($path1)) {
750
-				\OC_Hook::emit(
751
-					Filesystem::CLASSNAME, Filesystem::signal_rename,
752
-					array(
753
-						Filesystem::signal_param_oldpath => $this->getHookPath($path1),
754
-						Filesystem::signal_param_newpath => $this->getHookPath($path2),
755
-						Filesystem::signal_param_run => &$run
756
-					)
757
-				);
758
-			}
759
-			if ($run) {
760
-				$this->verifyPath(dirname($path2), basename($path2));
761
-
762
-				$manager = Filesystem::getMountManager();
763
-				$mount1 = $this->getMount($path1);
764
-				$mount2 = $this->getMount($path2);
765
-				$storage1 = $mount1->getStorage();
766
-				$storage2 = $mount2->getStorage();
767
-				$internalPath1 = $mount1->getInternalPath($absolutePath1);
768
-				$internalPath2 = $mount2->getInternalPath($absolutePath2);
769
-
770
-				$this->changeLock($path1, ILockingProvider::LOCK_EXCLUSIVE, true);
771
-				$this->changeLock($path2, ILockingProvider::LOCK_EXCLUSIVE, true);
772
-
773
-				if ($internalPath1 === '') {
774
-					if ($mount1 instanceof MoveableMount) {
775
-						if ($this->isTargetAllowed($absolutePath2)) {
776
-							/**
777
-							 * @var \OC\Files\Mount\MountPoint | \OC\Files\Mount\MoveableMount $mount1
778
-							 */
779
-							$sourceMountPoint = $mount1->getMountPoint();
780
-							$result = $mount1->moveMount($absolutePath2);
781
-							$manager->moveMount($sourceMountPoint, $mount1->getMountPoint());
782
-						} else {
783
-							$result = false;
784
-						}
785
-					} else {
786
-						$result = false;
787
-					}
788
-					// moving a file/folder within the same mount point
789
-				} elseif ($storage1 === $storage2) {
790
-					if ($storage1) {
791
-						$result = $storage1->rename($internalPath1, $internalPath2);
792
-					} else {
793
-						$result = false;
794
-					}
795
-					// moving a file/folder between storages (from $storage1 to $storage2)
796
-				} else {
797
-					$result = $storage2->moveFromStorage($storage1, $internalPath1, $internalPath2);
798
-				}
799
-
800
-				if ((Cache\Scanner::isPartialFile($path1) && !Cache\Scanner::isPartialFile($path2)) && $result !== false) {
801
-					// if it was a rename from a part file to a regular file it was a write and not a rename operation
802
-
803
-					$this->writeUpdate($storage2, $internalPath2);
804
-				} else if ($result) {
805
-					if ($internalPath1 !== '') { // don't do a cache update for moved mounts
806
-						$this->renameUpdate($storage1, $storage2, $internalPath1, $internalPath2);
807
-					}
808
-				}
809
-
810
-				$this->changeLock($path1, ILockingProvider::LOCK_SHARED, true);
811
-				$this->changeLock($path2, ILockingProvider::LOCK_SHARED, true);
812
-
813
-				if ((Cache\Scanner::isPartialFile($path1) && !Cache\Scanner::isPartialFile($path2)) && $result !== false) {
814
-					if ($this->shouldEmitHooks()) {
815
-						$this->emit_file_hooks_post($exists, $path2);
816
-					}
817
-				} elseif ($result) {
818
-					if ($this->shouldEmitHooks($path1) and $this->shouldEmitHooks($path2)) {
819
-						\OC_Hook::emit(
820
-							Filesystem::CLASSNAME,
821
-							Filesystem::signal_post_rename,
822
-							array(
823
-								Filesystem::signal_param_oldpath => $this->getHookPath($path1),
824
-								Filesystem::signal_param_newpath => $this->getHookPath($path2)
825
-							)
826
-						);
827
-					}
828
-				}
829
-			}
830
-			$this->unlockFile($path1, ILockingProvider::LOCK_SHARED, true);
831
-			$this->unlockFile($path2, ILockingProvider::LOCK_SHARED, true);
832
-		}
833
-		return $result;
834
-	}
835
-
836
-	/**
837
-	 * Copy a file/folder from the source path to target path
838
-	 *
839
-	 * @param string $path1 source path
840
-	 * @param string $path2 target path
841
-	 * @param bool $preserveMtime whether to preserve mtime on the copy
842
-	 *
843
-	 * @return bool|mixed
844
-	 */
845
-	public function copy($path1, $path2, $preserveMtime = false) {
846
-		$absolutePath1 = Filesystem::normalizePath($this->getAbsolutePath($path1));
847
-		$absolutePath2 = Filesystem::normalizePath($this->getAbsolutePath($path2));
848
-		$result = false;
849
-		if (
850
-			Filesystem::isValidPath($path2)
851
-			and Filesystem::isValidPath($path1)
852
-			and !Filesystem::isFileBlacklisted($path2)
853
-		) {
854
-			$path1 = $this->getRelativePath($absolutePath1);
855
-			$path2 = $this->getRelativePath($absolutePath2);
856
-
857
-			if ($path1 == null or $path2 == null) {
858
-				return false;
859
-			}
860
-			$run = true;
861
-
862
-			$this->lockFile($path2, ILockingProvider::LOCK_SHARED);
863
-			$this->lockFile($path1, ILockingProvider::LOCK_SHARED);
864
-			$lockTypePath1 = ILockingProvider::LOCK_SHARED;
865
-			$lockTypePath2 = ILockingProvider::LOCK_SHARED;
866
-
867
-			try {
868
-
869
-				$exists = $this->file_exists($path2);
870
-				if ($this->shouldEmitHooks()) {
871
-					\OC_Hook::emit(
872
-						Filesystem::CLASSNAME,
873
-						Filesystem::signal_copy,
874
-						array(
875
-							Filesystem::signal_param_oldpath => $this->getHookPath($path1),
876
-							Filesystem::signal_param_newpath => $this->getHookPath($path2),
877
-							Filesystem::signal_param_run => &$run
878
-						)
879
-					);
880
-					$this->emit_file_hooks_pre($exists, $path2, $run);
881
-				}
882
-				if ($run) {
883
-					$mount1 = $this->getMount($path1);
884
-					$mount2 = $this->getMount($path2);
885
-					$storage1 = $mount1->getStorage();
886
-					$internalPath1 = $mount1->getInternalPath($absolutePath1);
887
-					$storage2 = $mount2->getStorage();
888
-					$internalPath2 = $mount2->getInternalPath($absolutePath2);
889
-
890
-					$this->changeLock($path2, ILockingProvider::LOCK_EXCLUSIVE);
891
-					$lockTypePath2 = ILockingProvider::LOCK_EXCLUSIVE;
892
-
893
-					if ($mount1->getMountPoint() == $mount2->getMountPoint()) {
894
-						if ($storage1) {
895
-							$result = $storage1->copy($internalPath1, $internalPath2);
896
-						} else {
897
-							$result = false;
898
-						}
899
-					} else {
900
-						$result = $storage2->copyFromStorage($storage1, $internalPath1, $internalPath2);
901
-					}
902
-
903
-					$this->writeUpdate($storage2, $internalPath2);
904
-
905
-					$this->changeLock($path2, ILockingProvider::LOCK_SHARED);
906
-					$lockTypePath2 = ILockingProvider::LOCK_SHARED;
907
-
908
-					if ($this->shouldEmitHooks() && $result !== false) {
909
-						\OC_Hook::emit(
910
-							Filesystem::CLASSNAME,
911
-							Filesystem::signal_post_copy,
912
-							array(
913
-								Filesystem::signal_param_oldpath => $this->getHookPath($path1),
914
-								Filesystem::signal_param_newpath => $this->getHookPath($path2)
915
-							)
916
-						);
917
-						$this->emit_file_hooks_post($exists, $path2);
918
-					}
919
-
920
-				}
921
-			} catch (\Exception $e) {
922
-				$this->unlockFile($path2, $lockTypePath2);
923
-				$this->unlockFile($path1, $lockTypePath1);
924
-				throw $e;
925
-			}
926
-
927
-			$this->unlockFile($path2, $lockTypePath2);
928
-			$this->unlockFile($path1, $lockTypePath1);
929
-
930
-		}
931
-		return $result;
932
-	}
933
-
934
-	/**
935
-	 * @param string $path
936
-	 * @param string $mode 'r' or 'w'
937
-	 * @return resource
938
-	 */
939
-	public function fopen($path, $mode) {
940
-		$mode = str_replace('b', '', $mode); // the binary flag is a windows only feature which we do not support
941
-		$hooks = array();
942
-		switch ($mode) {
943
-			case 'r':
944
-				$hooks[] = 'read';
945
-				break;
946
-			case 'r+':
947
-			case 'w+':
948
-			case 'x+':
949
-			case 'a+':
950
-				$hooks[] = 'read';
951
-				$hooks[] = 'write';
952
-				break;
953
-			case 'w':
954
-			case 'x':
955
-			case 'a':
956
-				$hooks[] = 'write';
957
-				break;
958
-			default:
959
-				\OCP\Util::writeLog('core', 'invalid mode (' . $mode . ') for ' . $path, \OCP\Util::ERROR);
960
-		}
961
-
962
-		if ($mode !== 'r' && $mode !== 'w') {
963
-			\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');
964
-		}
965
-
966
-		return $this->basicOperation('fopen', $path, $hooks, $mode);
967
-	}
968
-
969
-	/**
970
-	 * @param string $path
971
-	 * @return bool|string
972
-	 * @throws \OCP\Files\InvalidPathException
973
-	 */
974
-	public function toTmpFile($path) {
975
-		$this->assertPathLength($path);
976
-		if (Filesystem::isValidPath($path)) {
977
-			$source = $this->fopen($path, 'r');
978
-			if ($source) {
979
-				$extension = pathinfo($path, PATHINFO_EXTENSION);
980
-				$tmpFile = \OC::$server->getTempManager()->getTemporaryFile($extension);
981
-				file_put_contents($tmpFile, $source);
982
-				return $tmpFile;
983
-			} else {
984
-				return false;
985
-			}
986
-		} else {
987
-			return false;
988
-		}
989
-	}
990
-
991
-	/**
992
-	 * @param string $tmpFile
993
-	 * @param string $path
994
-	 * @return bool|mixed
995
-	 * @throws \OCP\Files\InvalidPathException
996
-	 */
997
-	public function fromTmpFile($tmpFile, $path) {
998
-		$this->assertPathLength($path);
999
-		if (Filesystem::isValidPath($path)) {
1000
-
1001
-			// Get directory that the file is going into
1002
-			$filePath = dirname($path);
1003
-
1004
-			// Create the directories if any
1005
-			if (!$this->file_exists($filePath)) {
1006
-				$result = $this->createParentDirectories($filePath);
1007
-				if ($result === false) {
1008
-					return false;
1009
-				}
1010
-			}
1011
-
1012
-			$source = fopen($tmpFile, 'r');
1013
-			if ($source) {
1014
-				$result = $this->file_put_contents($path, $source);
1015
-				// $this->file_put_contents() might have already closed
1016
-				// the resource, so we check it, before trying to close it
1017
-				// to avoid messages in the error log.
1018
-				if (is_resource($source)) {
1019
-					fclose($source);
1020
-				}
1021
-				unlink($tmpFile);
1022
-				return $result;
1023
-			} else {
1024
-				return false;
1025
-			}
1026
-		} else {
1027
-			return false;
1028
-		}
1029
-	}
1030
-
1031
-
1032
-	/**
1033
-	 * @param string $path
1034
-	 * @return mixed
1035
-	 * @throws \OCP\Files\InvalidPathException
1036
-	 */
1037
-	public function getMimeType($path) {
1038
-		$this->assertPathLength($path);
1039
-		return $this->basicOperation('getMimeType', $path);
1040
-	}
1041
-
1042
-	/**
1043
-	 * @param string $type
1044
-	 * @param string $path
1045
-	 * @param bool $raw
1046
-	 * @return bool|null|string
1047
-	 */
1048
-	public function hash($type, $path, $raw = false) {
1049
-		$postFix = (substr($path, -1, 1) === '/') ? '/' : '';
1050
-		$absolutePath = Filesystem::normalizePath($this->getAbsolutePath($path));
1051
-		if (Filesystem::isValidPath($path)) {
1052
-			$path = $this->getRelativePath($absolutePath);
1053
-			if ($path == null) {
1054
-				return false;
1055
-			}
1056
-			if ($this->shouldEmitHooks($path)) {
1057
-				\OC_Hook::emit(
1058
-					Filesystem::CLASSNAME,
1059
-					Filesystem::signal_read,
1060
-					array(Filesystem::signal_param_path => $this->getHookPath($path))
1061
-				);
1062
-			}
1063
-			list($storage, $internalPath) = Filesystem::resolvePath($absolutePath . $postFix);
1064
-			if ($storage) {
1065
-				$result = $storage->hash($type, $internalPath, $raw);
1066
-				return $result;
1067
-			}
1068
-		}
1069
-		return null;
1070
-	}
1071
-
1072
-	/**
1073
-	 * @param string $path
1074
-	 * @return mixed
1075
-	 * @throws \OCP\Files\InvalidPathException
1076
-	 */
1077
-	public function free_space($path = '/') {
1078
-		$this->assertPathLength($path);
1079
-		$result = $this->basicOperation('free_space', $path);
1080
-		if ($result === null) {
1081
-			throw new InvalidPathException();
1082
-		}
1083
-		return $result;
1084
-	}
1085
-
1086
-	/**
1087
-	 * abstraction layer for basic filesystem functions: wrapper for \OC\Files\Storage\Storage
1088
-	 *
1089
-	 * @param string $operation
1090
-	 * @param string $path
1091
-	 * @param array $hooks (optional)
1092
-	 * @param mixed $extraParam (optional)
1093
-	 * @return mixed
1094
-	 * @throws \Exception
1095
-	 *
1096
-	 * This method takes requests for basic filesystem functions (e.g. reading & writing
1097
-	 * files), processes hooks and proxies, sanitises paths, and finally passes them on to
1098
-	 * \OC\Files\Storage\Storage for delegation to a storage backend for execution
1099
-	 */
1100
-	private function basicOperation($operation, $path, $hooks = [], $extraParam = null) {
1101
-		$postFix = (substr($path, -1, 1) === '/') ? '/' : '';
1102
-		$absolutePath = Filesystem::normalizePath($this->getAbsolutePath($path));
1103
-		if (Filesystem::isValidPath($path)
1104
-			and !Filesystem::isFileBlacklisted($path)
1105
-		) {
1106
-			$path = $this->getRelativePath($absolutePath);
1107
-			if ($path == null) {
1108
-				return false;
1109
-			}
1110
-
1111
-			if (in_array('write', $hooks) || in_array('delete', $hooks) || in_array('read', $hooks)) {
1112
-				// always a shared lock during pre-hooks so the hook can read the file
1113
-				$this->lockFile($path, ILockingProvider::LOCK_SHARED);
1114
-			}
1115
-
1116
-			$run = $this->runHooks($hooks, $path);
1117
-			/** @var \OC\Files\Storage\Storage $storage */
1118
-			list($storage, $internalPath) = Filesystem::resolvePath($absolutePath . $postFix);
1119
-			if ($run and $storage) {
1120
-				if (in_array('write', $hooks) || in_array('delete', $hooks)) {
1121
-					$this->changeLock($path, ILockingProvider::LOCK_EXCLUSIVE);
1122
-				}
1123
-				try {
1124
-					if (!is_null($extraParam)) {
1125
-						$result = $storage->$operation($internalPath, $extraParam);
1126
-					} else {
1127
-						$result = $storage->$operation($internalPath);
1128
-					}
1129
-				} catch (\Exception $e) {
1130
-					if (in_array('write', $hooks) || in_array('delete', $hooks)) {
1131
-						$this->unlockFile($path, ILockingProvider::LOCK_EXCLUSIVE);
1132
-					} else if (in_array('read', $hooks)) {
1133
-						$this->unlockFile($path, ILockingProvider::LOCK_SHARED);
1134
-					}
1135
-					throw $e;
1136
-				}
1137
-
1138
-				if ($result && in_array('delete', $hooks) and $result) {
1139
-					$this->removeUpdate($storage, $internalPath);
1140
-				}
1141
-				if ($result && in_array('write', $hooks) and $operation !== 'fopen') {
1142
-					$this->writeUpdate($storage, $internalPath);
1143
-				}
1144
-				if ($result && in_array('touch', $hooks)) {
1145
-					$this->writeUpdate($storage, $internalPath, $extraParam);
1146
-				}
1147
-
1148
-				if ((in_array('write', $hooks) || in_array('delete', $hooks)) && ($operation !== 'fopen' || $result === false)) {
1149
-					$this->changeLock($path, ILockingProvider::LOCK_SHARED);
1150
-				}
1151
-
1152
-				$unlockLater = false;
1153
-				if ($this->lockingEnabled && $operation === 'fopen' && is_resource($result)) {
1154
-					$unlockLater = true;
1155
-					// make sure our unlocking callback will still be called if connection is aborted
1156
-					ignore_user_abort(true);
1157
-					$result = CallbackWrapper::wrap($result, null, null, function () use ($hooks, $path) {
1158
-						if (in_array('write', $hooks)) {
1159
-							$this->unlockFile($path, ILockingProvider::LOCK_EXCLUSIVE);
1160
-						} else if (in_array('read', $hooks)) {
1161
-							$this->unlockFile($path, ILockingProvider::LOCK_SHARED);
1162
-						}
1163
-					});
1164
-				}
1165
-
1166
-				if ($this->shouldEmitHooks($path) && $result !== false) {
1167
-					if ($operation != 'fopen') { //no post hooks for fopen, the file stream is still open
1168
-						$this->runHooks($hooks, $path, true);
1169
-					}
1170
-				}
1171
-
1172
-				if (!$unlockLater
1173
-					&& (in_array('write', $hooks) || in_array('delete', $hooks) || in_array('read', $hooks))
1174
-				) {
1175
-					$this->unlockFile($path, ILockingProvider::LOCK_SHARED);
1176
-				}
1177
-				return $result;
1178
-			} else {
1179
-				$this->unlockFile($path, ILockingProvider::LOCK_SHARED);
1180
-			}
1181
-		}
1182
-		return null;
1183
-	}
1184
-
1185
-	/**
1186
-	 * get the path relative to the default root for hook usage
1187
-	 *
1188
-	 * @param string $path
1189
-	 * @return string
1190
-	 */
1191
-	private function getHookPath($path) {
1192
-		if (!Filesystem::getView()) {
1193
-			return $path;
1194
-		}
1195
-		return Filesystem::getView()->getRelativePath($this->getAbsolutePath($path));
1196
-	}
1197
-
1198
-	private function shouldEmitHooks($path = '') {
1199
-		if ($path && Cache\Scanner::isPartialFile($path)) {
1200
-			return false;
1201
-		}
1202
-		if (!Filesystem::$loaded) {
1203
-			return false;
1204
-		}
1205
-		$defaultRoot = Filesystem::getRoot();
1206
-		if ($defaultRoot === null) {
1207
-			return false;
1208
-		}
1209
-		if ($this->fakeRoot === $defaultRoot) {
1210
-			return true;
1211
-		}
1212
-		$fullPath = $this->getAbsolutePath($path);
1213
-
1214
-		if ($fullPath === $defaultRoot) {
1215
-			return true;
1216
-		}
1217
-
1218
-		return (strlen($fullPath) > strlen($defaultRoot)) && (substr($fullPath, 0, strlen($defaultRoot) + 1) === $defaultRoot . '/');
1219
-	}
1220
-
1221
-	/**
1222
-	 * @param string[] $hooks
1223
-	 * @param string $path
1224
-	 * @param bool $post
1225
-	 * @return bool
1226
-	 */
1227
-	private function runHooks($hooks, $path, $post = false) {
1228
-		$relativePath = $path;
1229
-		$path = $this->getHookPath($path);
1230
-		$prefix = ($post) ? 'post_' : '';
1231
-		$run = true;
1232
-		if ($this->shouldEmitHooks($relativePath)) {
1233
-			foreach ($hooks as $hook) {
1234
-				if ($hook != 'read') {
1235
-					\OC_Hook::emit(
1236
-						Filesystem::CLASSNAME,
1237
-						$prefix . $hook,
1238
-						array(
1239
-							Filesystem::signal_param_run => &$run,
1240
-							Filesystem::signal_param_path => $path
1241
-						)
1242
-					);
1243
-				} elseif (!$post) {
1244
-					\OC_Hook::emit(
1245
-						Filesystem::CLASSNAME,
1246
-						$prefix . $hook,
1247
-						array(
1248
-							Filesystem::signal_param_path => $path
1249
-						)
1250
-					);
1251
-				}
1252
-			}
1253
-		}
1254
-		return $run;
1255
-	}
1256
-
1257
-	/**
1258
-	 * check if a file or folder has been updated since $time
1259
-	 *
1260
-	 * @param string $path
1261
-	 * @param int $time
1262
-	 * @return bool
1263
-	 */
1264
-	public function hasUpdated($path, $time) {
1265
-		return $this->basicOperation('hasUpdated', $path, array(), $time);
1266
-	}
1267
-
1268
-	/**
1269
-	 * @param string $ownerId
1270
-	 * @return \OC\User\User
1271
-	 */
1272
-	private function getUserObjectForOwner($ownerId) {
1273
-		$owner = $this->userManager->get($ownerId);
1274
-		if ($owner instanceof IUser) {
1275
-			return $owner;
1276
-		} else {
1277
-			return new User($ownerId, null);
1278
-		}
1279
-	}
1280
-
1281
-	/**
1282
-	 * Get file info from cache
1283
-	 *
1284
-	 * If the file is not in cached it will be scanned
1285
-	 * If the file has changed on storage the cache will be updated
1286
-	 *
1287
-	 * @param \OC\Files\Storage\Storage $storage
1288
-	 * @param string $internalPath
1289
-	 * @param string $relativePath
1290
-	 * @return ICacheEntry|bool
1291
-	 */
1292
-	private function getCacheEntry($storage, $internalPath, $relativePath) {
1293
-		$cache = $storage->getCache($internalPath);
1294
-		$data = $cache->get($internalPath);
1295
-		$watcher = $storage->getWatcher($internalPath);
1296
-
1297
-		try {
1298
-			// if the file is not in the cache or needs to be updated, trigger the scanner and reload the data
1299
-			if (!$data || $data['size'] === -1) {
1300
-				$this->lockFile($relativePath, ILockingProvider::LOCK_SHARED);
1301
-				if (!$storage->file_exists($internalPath)) {
1302
-					$this->unlockFile($relativePath, ILockingProvider::LOCK_SHARED);
1303
-					return false;
1304
-				}
1305
-				$scanner = $storage->getScanner($internalPath);
1306
-				$scanner->scan($internalPath, Cache\Scanner::SCAN_SHALLOW);
1307
-				$data = $cache->get($internalPath);
1308
-				$this->unlockFile($relativePath, ILockingProvider::LOCK_SHARED);
1309
-			} else if (!Cache\Scanner::isPartialFile($internalPath) && $watcher->needsUpdate($internalPath, $data)) {
1310
-				$this->lockFile($relativePath, ILockingProvider::LOCK_SHARED);
1311
-				$watcher->update($internalPath, $data);
1312
-				$storage->getPropagator()->propagateChange($internalPath, time());
1313
-				$data = $cache->get($internalPath);
1314
-				$this->unlockFile($relativePath, ILockingProvider::LOCK_SHARED);
1315
-			}
1316
-		} catch (LockedException $e) {
1317
-			// if the file is locked we just use the old cache info
1318
-		}
1319
-
1320
-		return $data;
1321
-	}
1322
-
1323
-	/**
1324
-	 * get the filesystem info
1325
-	 *
1326
-	 * @param string $path
1327
-	 * @param boolean|string $includeMountPoints true to add mountpoint sizes,
1328
-	 * 'ext' to add only ext storage mount point sizes. Defaults to true.
1329
-	 * defaults to true
1330
-	 * @return \OC\Files\FileInfo|false False if file does not exist
1331
-	 */
1332
-	public function getFileInfo($path, $includeMountPoints = true) {
1333
-		$this->assertPathLength($path);
1334
-		if (!Filesystem::isValidPath($path)) {
1335
-			return false;
1336
-		}
1337
-		if (Cache\Scanner::isPartialFile($path)) {
1338
-			return $this->getPartFileInfo($path);
1339
-		}
1340
-		$relativePath = $path;
1341
-		$path = Filesystem::normalizePath($this->fakeRoot . '/' . $path);
1342
-
1343
-		$mount = Filesystem::getMountManager()->find($path);
1344
-		$storage = $mount->getStorage();
1345
-		$internalPath = $mount->getInternalPath($path);
1346
-		if ($storage) {
1347
-			$data = $this->getCacheEntry($storage, $internalPath, $relativePath);
1348
-
1349
-			if (!$data instanceof ICacheEntry) {
1350
-				return false;
1351
-			}
1352
-
1353
-			if ($mount instanceof MoveableMount && $internalPath === '') {
1354
-				$data['permissions'] |= \OCP\Constants::PERMISSION_DELETE;
1355
-			}
1356
-
1357
-			$owner = $this->getUserObjectForOwner($storage->getOwner($internalPath));
1358
-			$info = new FileInfo($path, $storage, $internalPath, $data, $mount, $owner);
1359
-
1360
-			if ($data and isset($data['fileid'])) {
1361
-				if ($includeMountPoints and $data['mimetype'] === 'httpd/unix-directory') {
1362
-					//add the sizes of other mount points to the folder
1363
-					$extOnly = ($includeMountPoints === 'ext');
1364
-					$mounts = Filesystem::getMountManager()->findIn($path);
1365
-					$info->setSubMounts(array_filter($mounts, function (IMountPoint $mount) use ($extOnly) {
1366
-						$subStorage = $mount->getStorage();
1367
-						return !($extOnly && $subStorage instanceof \OCA\Files_Sharing\SharedStorage);
1368
-					}));
1369
-				}
1370
-			}
1371
-
1372
-			return $info;
1373
-		}
1374
-
1375
-		return false;
1376
-	}
1377
-
1378
-	/**
1379
-	 * get the content of a directory
1380
-	 *
1381
-	 * @param string $directory path under datadirectory
1382
-	 * @param string $mimetype_filter limit returned content to this mimetype or mimepart
1383
-	 * @return FileInfo[]
1384
-	 */
1385
-	public function getDirectoryContent($directory, $mimetype_filter = '') {
1386
-		$this->assertPathLength($directory);
1387
-		if (!Filesystem::isValidPath($directory)) {
1388
-			return [];
1389
-		}
1390
-		$path = $this->getAbsolutePath($directory);
1391
-		$path = Filesystem::normalizePath($path);
1392
-		$mount = $this->getMount($directory);
1393
-		$storage = $mount->getStorage();
1394
-		$internalPath = $mount->getInternalPath($path);
1395
-		if ($storage) {
1396
-			$cache = $storage->getCache($internalPath);
1397
-			$user = \OC_User::getUser();
1398
-
1399
-			$data = $this->getCacheEntry($storage, $internalPath, $directory);
1400
-
1401
-			if (!$data instanceof ICacheEntry || !isset($data['fileid']) || !($data->getPermissions() && Constants::PERMISSION_READ)) {
1402
-				return [];
1403
-			}
1404
-
1405
-			$folderId = $data['fileid'];
1406
-			$contents = $cache->getFolderContentsById($folderId); //TODO: mimetype_filter
1407
-
1408
-			$sharingDisabled = \OCP\Util::isSharingDisabledForUser();
1409
-			/**
1410
-			 * @var \OC\Files\FileInfo[] $files
1411
-			 */
1412
-			$files = array_map(function (ICacheEntry $content) use ($path, $storage, $mount, $sharingDisabled) {
1413
-				if ($sharingDisabled) {
1414
-					$content['permissions'] = $content['permissions'] & ~\OCP\Constants::PERMISSION_SHARE;
1415
-				}
1416
-				$owner = $this->getUserObjectForOwner($storage->getOwner($content['path']));
1417
-				return new FileInfo($path . '/' . $content['name'], $storage, $content['path'], $content, $mount, $owner);
1418
-			}, $contents);
1419
-
1420
-			//add a folder for any mountpoint in this directory and add the sizes of other mountpoints to the folders
1421
-			$mounts = Filesystem::getMountManager()->findIn($path);
1422
-			$dirLength = strlen($path);
1423
-			foreach ($mounts as $mount) {
1424
-				$mountPoint = $mount->getMountPoint();
1425
-				$subStorage = $mount->getStorage();
1426
-				if ($subStorage) {
1427
-					$subCache = $subStorage->getCache('');
1428
-
1429
-					$rootEntry = $subCache->get('');
1430
-					if (!$rootEntry) {
1431
-						$subScanner = $subStorage->getScanner('');
1432
-						try {
1433
-							$subScanner->scanFile('');
1434
-						} catch (\OCP\Files\StorageNotAvailableException $e) {
1435
-							continue;
1436
-						} catch (\OCP\Files\StorageInvalidException $e) {
1437
-							continue;
1438
-						} catch (\Exception $e) {
1439
-							// sometimes when the storage is not available it can be any exception
1440
-							\OCP\Util::writeLog(
1441
-								'core',
1442
-								'Exception while scanning storage "' . $subStorage->getId() . '": ' .
1443
-								get_class($e) . ': ' . $e->getMessage(),
1444
-								\OCP\Util::ERROR
1445
-							);
1446
-							continue;
1447
-						}
1448
-						$rootEntry = $subCache->get('');
1449
-					}
1450
-
1451
-					if ($rootEntry && ($rootEntry->getPermissions() && Constants::PERMISSION_READ)) {
1452
-						$relativePath = trim(substr($mountPoint, $dirLength), '/');
1453
-						if ($pos = strpos($relativePath, '/')) {
1454
-							//mountpoint inside subfolder add size to the correct folder
1455
-							$entryName = substr($relativePath, 0, $pos);
1456
-							foreach ($files as &$entry) {
1457
-								if ($entry->getName() === $entryName) {
1458
-									$entry->addSubEntry($rootEntry, $mountPoint);
1459
-								}
1460
-							}
1461
-						} else { //mountpoint in this folder, add an entry for it
1462
-							$rootEntry['name'] = $relativePath;
1463
-							$rootEntry['type'] = $rootEntry['mimetype'] === 'httpd/unix-directory' ? 'dir' : 'file';
1464
-							$permissions = $rootEntry['permissions'];
1465
-							// do not allow renaming/deleting the mount point if they are not shared files/folders
1466
-							// for shared files/folders we use the permissions given by the owner
1467
-							if ($mount instanceof MoveableMount) {
1468
-								$rootEntry['permissions'] = $permissions | \OCP\Constants::PERMISSION_UPDATE | \OCP\Constants::PERMISSION_DELETE;
1469
-							} else {
1470
-								$rootEntry['permissions'] = $permissions & (\OCP\Constants::PERMISSION_ALL - (\OCP\Constants::PERMISSION_UPDATE | \OCP\Constants::PERMISSION_DELETE));
1471
-							}
1472
-
1473
-							//remove any existing entry with the same name
1474
-							foreach ($files as $i => $file) {
1475
-								if ($file['name'] === $rootEntry['name']) {
1476
-									unset($files[$i]);
1477
-									break;
1478
-								}
1479
-							}
1480
-							$rootEntry['path'] = substr(Filesystem::normalizePath($path . '/' . $rootEntry['name']), strlen($user) + 2); // full path without /$user/
1481
-
1482
-							// if sharing was disabled for the user we remove the share permissions
1483
-							if (\OCP\Util::isSharingDisabledForUser()) {
1484
-								$rootEntry['permissions'] = $rootEntry['permissions'] & ~\OCP\Constants::PERMISSION_SHARE;
1485
-							}
1486
-
1487
-							$owner = $this->getUserObjectForOwner($subStorage->getOwner(''));
1488
-							$files[] = new FileInfo($path . '/' . $rootEntry['name'], $subStorage, '', $rootEntry, $mount, $owner);
1489
-						}
1490
-					}
1491
-				}
1492
-			}
1493
-
1494
-			if ($mimetype_filter) {
1495
-				$files = array_filter($files, function (FileInfo $file) use ($mimetype_filter) {
1496
-					if (strpos($mimetype_filter, '/')) {
1497
-						return $file->getMimetype() === $mimetype_filter;
1498
-					} else {
1499
-						return $file->getMimePart() === $mimetype_filter;
1500
-					}
1501
-				});
1502
-			}
1503
-
1504
-			return $files;
1505
-		} else {
1506
-			return [];
1507
-		}
1508
-	}
1509
-
1510
-	/**
1511
-	 * change file metadata
1512
-	 *
1513
-	 * @param string $path
1514
-	 * @param array|\OCP\Files\FileInfo $data
1515
-	 * @return int
1516
-	 *
1517
-	 * returns the fileid of the updated file
1518
-	 */
1519
-	public function putFileInfo($path, $data) {
1520
-		$this->assertPathLength($path);
1521
-		if ($data instanceof FileInfo) {
1522
-			$data = $data->getData();
1523
-		}
1524
-		$path = Filesystem::normalizePath($this->fakeRoot . '/' . $path);
1525
-		/**
1526
-		 * @var \OC\Files\Storage\Storage $storage
1527
-		 * @var string $internalPath
1528
-		 */
1529
-		list($storage, $internalPath) = Filesystem::resolvePath($path);
1530
-		if ($storage) {
1531
-			$cache = $storage->getCache($path);
1532
-
1533
-			if (!$cache->inCache($internalPath)) {
1534
-				$scanner = $storage->getScanner($internalPath);
1535
-				$scanner->scan($internalPath, Cache\Scanner::SCAN_SHALLOW);
1536
-			}
1537
-
1538
-			return $cache->put($internalPath, $data);
1539
-		} else {
1540
-			return -1;
1541
-		}
1542
-	}
1543
-
1544
-	/**
1545
-	 * search for files with the name matching $query
1546
-	 *
1547
-	 * @param string $query
1548
-	 * @return FileInfo[]
1549
-	 */
1550
-	public function search($query) {
1551
-		return $this->searchCommon('search', array('%' . $query . '%'));
1552
-	}
1553
-
1554
-	/**
1555
-	 * search for files with the name matching $query
1556
-	 *
1557
-	 * @param string $query
1558
-	 * @return FileInfo[]
1559
-	 */
1560
-	public function searchRaw($query) {
1561
-		return $this->searchCommon('search', array($query));
1562
-	}
1563
-
1564
-	/**
1565
-	 * search for files by mimetype
1566
-	 *
1567
-	 * @param string $mimetype
1568
-	 * @return FileInfo[]
1569
-	 */
1570
-	public function searchByMime($mimetype) {
1571
-		return $this->searchCommon('searchByMime', array($mimetype));
1572
-	}
1573
-
1574
-	/**
1575
-	 * search for files by tag
1576
-	 *
1577
-	 * @param string|int $tag name or tag id
1578
-	 * @param string $userId owner of the tags
1579
-	 * @return FileInfo[]
1580
-	 */
1581
-	public function searchByTag($tag, $userId) {
1582
-		return $this->searchCommon('searchByTag', array($tag, $userId));
1583
-	}
1584
-
1585
-	/**
1586
-	 * @param string $method cache method
1587
-	 * @param array $args
1588
-	 * @return FileInfo[]
1589
-	 */
1590
-	private function searchCommon($method, $args) {
1591
-		$files = array();
1592
-		$rootLength = strlen($this->fakeRoot);
1593
-
1594
-		$mount = $this->getMount('');
1595
-		$mountPoint = $mount->getMountPoint();
1596
-		$storage = $mount->getStorage();
1597
-		if ($storage) {
1598
-			$cache = $storage->getCache('');
1599
-
1600
-			$results = call_user_func_array(array($cache, $method), $args);
1601
-			foreach ($results as $result) {
1602
-				if (substr($mountPoint . $result['path'], 0, $rootLength + 1) === $this->fakeRoot . '/') {
1603
-					$internalPath = $result['path'];
1604
-					$path = $mountPoint . $result['path'];
1605
-					$result['path'] = substr($mountPoint . $result['path'], $rootLength);
1606
-					$owner = \OC::$server->getUserManager()->get($storage->getOwner($internalPath));
1607
-					$files[] = new FileInfo($path, $storage, $internalPath, $result, $mount, $owner);
1608
-				}
1609
-			}
1610
-
1611
-			$mounts = Filesystem::getMountManager()->findIn($this->fakeRoot);
1612
-			foreach ($mounts as $mount) {
1613
-				$mountPoint = $mount->getMountPoint();
1614
-				$storage = $mount->getStorage();
1615
-				if ($storage) {
1616
-					$cache = $storage->getCache('');
1617
-
1618
-					$relativeMountPoint = substr($mountPoint, $rootLength);
1619
-					$results = call_user_func_array(array($cache, $method), $args);
1620
-					if ($results) {
1621
-						foreach ($results as $result) {
1622
-							$internalPath = $result['path'];
1623
-							$result['path'] = rtrim($relativeMountPoint . $result['path'], '/');
1624
-							$path = rtrim($mountPoint . $internalPath, '/');
1625
-							$owner = \OC::$server->getUserManager()->get($storage->getOwner($internalPath));
1626
-							$files[] = new FileInfo($path, $storage, $internalPath, $result, $mount, $owner);
1627
-						}
1628
-					}
1629
-				}
1630
-			}
1631
-		}
1632
-		return $files;
1633
-	}
1634
-
1635
-	/**
1636
-	 * Get the owner for a file or folder
1637
-	 *
1638
-	 * @param string $path
1639
-	 * @return string the user id of the owner
1640
-	 * @throws NotFoundException
1641
-	 */
1642
-	public function getOwner($path) {
1643
-		$info = $this->getFileInfo($path);
1644
-		if (!$info) {
1645
-			throw new NotFoundException($path . ' not found while trying to get owner');
1646
-		}
1647
-		return $info->getOwner()->getUID();
1648
-	}
1649
-
1650
-	/**
1651
-	 * get the ETag for a file or folder
1652
-	 *
1653
-	 * @param string $path
1654
-	 * @return string
1655
-	 */
1656
-	public function getETag($path) {
1657
-		/**
1658
-		 * @var Storage\Storage $storage
1659
-		 * @var string $internalPath
1660
-		 */
1661
-		list($storage, $internalPath) = $this->resolvePath($path);
1662
-		if ($storage) {
1663
-			return $storage->getETag($internalPath);
1664
-		} else {
1665
-			return null;
1666
-		}
1667
-	}
1668
-
1669
-	/**
1670
-	 * Get the path of a file by id, relative to the view
1671
-	 *
1672
-	 * Note that the resulting path is not guarantied to be unique for the id, multiple paths can point to the same file
1673
-	 *
1674
-	 * @param int $id
1675
-	 * @throws NotFoundException
1676
-	 * @return string
1677
-	 */
1678
-	public function getPath($id) {
1679
-		$id = (int)$id;
1680
-		$manager = Filesystem::getMountManager();
1681
-		$mounts = $manager->findIn($this->fakeRoot);
1682
-		$mounts[] = $manager->find($this->fakeRoot);
1683
-		// reverse the array so we start with the storage this view is in
1684
-		// which is the most likely to contain the file we're looking for
1685
-		$mounts = array_reverse($mounts);
1686
-		foreach ($mounts as $mount) {
1687
-			/**
1688
-			 * @var \OC\Files\Mount\MountPoint $mount
1689
-			 */
1690
-			if ($mount->getStorage()) {
1691
-				$cache = $mount->getStorage()->getCache();
1692
-				$internalPath = $cache->getPathById($id);
1693
-				if (is_string($internalPath)) {
1694
-					$fullPath = $mount->getMountPoint() . $internalPath;
1695
-					if (!is_null($path = $this->getRelativePath($fullPath))) {
1696
-						return $path;
1697
-					}
1698
-				}
1699
-			}
1700
-		}
1701
-		throw new NotFoundException(sprintf('File with id "%s" has not been found.', $id));
1702
-	}
1703
-
1704
-	/**
1705
-	 * @param string $path
1706
-	 * @throws InvalidPathException
1707
-	 */
1708
-	private function assertPathLength($path) {
1709
-		$maxLen = min(PHP_MAXPATHLEN, 4000);
1710
-		// Check for the string length - performed using isset() instead of strlen()
1711
-		// because isset() is about 5x-40x faster.
1712
-		if (isset($path[$maxLen])) {
1713
-			$pathLen = strlen($path);
1714
-			throw new \OCP\Files\InvalidPathException("Path length($pathLen) exceeds max path length($maxLen): $path");
1715
-		}
1716
-	}
1717
-
1718
-	/**
1719
-	 * check if it is allowed to move a mount point to a given target.
1720
-	 * It is not allowed to move a mount point into a different mount point or
1721
-	 * into an already shared folder
1722
-	 *
1723
-	 * @param string $target path
1724
-	 * @return boolean
1725
-	 */
1726
-	private function isTargetAllowed($target) {
1727
-
1728
-		list($targetStorage, $targetInternalPath) = \OC\Files\Filesystem::resolvePath($target);
1729
-		if (!$targetStorage->instanceOfStorage('\OCP\Files\IHomeStorage')) {
1730
-			\OCP\Util::writeLog('files',
1731
-				'It is not allowed to move one mount point into another one',
1732
-				\OCP\Util::DEBUG);
1733
-			return false;
1734
-		}
1735
-
1736
-		// note: cannot use the view because the target is already locked
1737
-		$fileId = (int)$targetStorage->getCache()->getId($targetInternalPath);
1738
-		if ($fileId === -1) {
1739
-			// target might not exist, need to check parent instead
1740
-			$fileId = (int)$targetStorage->getCache()->getId(dirname($targetInternalPath));
1741
-		}
1742
-
1743
-		// check if any of the parents were shared by the current owner (include collections)
1744
-		$shares = \OCP\Share::getItemShared(
1745
-			'folder',
1746
-			$fileId,
1747
-			\OCP\Share::FORMAT_NONE,
1748
-			null,
1749
-			true
1750
-		);
1751
-
1752
-		if (count($shares) > 0) {
1753
-			\OCP\Util::writeLog('files',
1754
-				'It is not allowed to move one mount point into a shared folder',
1755
-				\OCP\Util::DEBUG);
1756
-			return false;
1757
-		}
1758
-
1759
-		return true;
1760
-	}
1761
-
1762
-	/**
1763
-	 * Get a fileinfo object for files that are ignored in the cache (part files)
1764
-	 *
1765
-	 * @param string $path
1766
-	 * @return \OCP\Files\FileInfo
1767
-	 */
1768
-	private function getPartFileInfo($path) {
1769
-		$mount = $this->getMount($path);
1770
-		$storage = $mount->getStorage();
1771
-		$internalPath = $mount->getInternalPath($this->getAbsolutePath($path));
1772
-		$owner = \OC::$server->getUserManager()->get($storage->getOwner($internalPath));
1773
-		return new FileInfo(
1774
-			$this->getAbsolutePath($path),
1775
-			$storage,
1776
-			$internalPath,
1777
-			[
1778
-				'fileid' => null,
1779
-				'mimetype' => $storage->getMimeType($internalPath),
1780
-				'name' => basename($path),
1781
-				'etag' => null,
1782
-				'size' => $storage->filesize($internalPath),
1783
-				'mtime' => $storage->filemtime($internalPath),
1784
-				'encrypted' => false,
1785
-				'permissions' => \OCP\Constants::PERMISSION_ALL
1786
-			],
1787
-			$mount,
1788
-			$owner
1789
-		);
1790
-	}
1791
-
1792
-	/**
1793
-	 * @param string $path
1794
-	 * @param string $fileName
1795
-	 * @throws InvalidPathException
1796
-	 */
1797
-	public function verifyPath($path, $fileName) {
1798
-		try {
1799
-			/** @type \OCP\Files\Storage $storage */
1800
-			list($storage, $internalPath) = $this->resolvePath($path);
1801
-			$storage->verifyPath($internalPath, $fileName);
1802
-		} catch (ReservedWordException $ex) {
1803
-			$l = \OC::$server->getL10N('lib');
1804
-			throw new InvalidPathException($l->t('File name is a reserved word'));
1805
-		} catch (InvalidCharacterInPathException $ex) {
1806
-			$l = \OC::$server->getL10N('lib');
1807
-			throw new InvalidPathException($l->t('File name contains at least one invalid character'));
1808
-		} catch (FileNameTooLongException $ex) {
1809
-			$l = \OC::$server->getL10N('lib');
1810
-			throw new InvalidPathException($l->t('File name is too long'));
1811
-		} catch (InvalidDirectoryException $ex) {
1812
-			$l = \OC::$server->getL10N('lib');
1813
-			throw new InvalidPathException($l->t('Dot files are not allowed'));
1814
-		} catch (EmptyFileNameException $ex) {
1815
-			$l = \OC::$server->getL10N('lib');
1816
-			throw new InvalidPathException($l->t('Empty filename is not allowed'));
1817
-		}
1818
-	}
1819
-
1820
-	/**
1821
-	 * get all parent folders of $path
1822
-	 *
1823
-	 * @param string $path
1824
-	 * @return string[]
1825
-	 */
1826
-	private function getParents($path) {
1827
-		$path = trim($path, '/');
1828
-		if (!$path) {
1829
-			return [];
1830
-		}
1831
-
1832
-		$parts = explode('/', $path);
1833
-
1834
-		// remove the single file
1835
-		array_pop($parts);
1836
-		$result = array('/');
1837
-		$resultPath = '';
1838
-		foreach ($parts as $part) {
1839
-			if ($part) {
1840
-				$resultPath .= '/' . $part;
1841
-				$result[] = $resultPath;
1842
-			}
1843
-		}
1844
-		return $result;
1845
-	}
1846
-
1847
-	/**
1848
-	 * Returns the mount point for which to lock
1849
-	 *
1850
-	 * @param string $absolutePath absolute path
1851
-	 * @param bool $useParentMount true to return parent mount instead of whatever
1852
-	 * is mounted directly on the given path, false otherwise
1853
-	 * @return \OC\Files\Mount\MountPoint mount point for which to apply locks
1854
-	 */
1855
-	private function getMountForLock($absolutePath, $useParentMount = false) {
1856
-		$results = [];
1857
-		$mount = Filesystem::getMountManager()->find($absolutePath);
1858
-		if (!$mount) {
1859
-			return $results;
1860
-		}
1861
-
1862
-		if ($useParentMount) {
1863
-			// find out if something is mounted directly on the path
1864
-			$internalPath = $mount->getInternalPath($absolutePath);
1865
-			if ($internalPath === '') {
1866
-				// resolve the parent mount instead
1867
-				$mount = Filesystem::getMountManager()->find(dirname($absolutePath));
1868
-			}
1869
-		}
1870
-
1871
-		return $mount;
1872
-	}
1873
-
1874
-	/**
1875
-	 * Lock the given path
1876
-	 *
1877
-	 * @param string $path the path of the file to lock, relative to the view
1878
-	 * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
1879
-	 * @param bool $lockMountPoint true to lock the mount point, false to lock the attached mount/storage
1880
-	 *
1881
-	 * @return bool False if the path is excluded from locking, true otherwise
1882
-	 * @throws \OCP\Lock\LockedException if the path is already locked
1883
-	 */
1884
-	private function lockPath($path, $type, $lockMountPoint = false) {
1885
-		$absolutePath = $this->getAbsolutePath($path);
1886
-		$absolutePath = Filesystem::normalizePath($absolutePath);
1887
-		if (!$this->shouldLockFile($absolutePath)) {
1888
-			return false;
1889
-		}
1890
-
1891
-		$mount = $this->getMountForLock($absolutePath, $lockMountPoint);
1892
-		if ($mount) {
1893
-			try {
1894
-				$storage = $mount->getStorage();
1895
-				if ($storage->instanceOfStorage('\OCP\Files\Storage\ILockingStorage')) {
1896
-					$storage->acquireLock(
1897
-						$mount->getInternalPath($absolutePath),
1898
-						$type,
1899
-						$this->lockingProvider
1900
-					);
1901
-				}
1902
-			} catch (\OCP\Lock\LockedException $e) {
1903
-				// rethrow with the a human-readable path
1904
-				throw new \OCP\Lock\LockedException(
1905
-					$this->getPathRelativeToFiles($absolutePath),
1906
-					$e
1907
-				);
1908
-			}
1909
-		}
1910
-
1911
-		return true;
1912
-	}
1913
-
1914
-	/**
1915
-	 * Change the lock type
1916
-	 *
1917
-	 * @param string $path the path of the file to lock, relative to the view
1918
-	 * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
1919
-	 * @param bool $lockMountPoint true to lock the mount point, false to lock the attached mount/storage
1920
-	 *
1921
-	 * @return bool False if the path is excluded from locking, true otherwise
1922
-	 * @throws \OCP\Lock\LockedException if the path is already locked
1923
-	 */
1924
-	public function changeLock($path, $type, $lockMountPoint = false) {
1925
-		$path = Filesystem::normalizePath($path);
1926
-		$absolutePath = $this->getAbsolutePath($path);
1927
-		$absolutePath = Filesystem::normalizePath($absolutePath);
1928
-		if (!$this->shouldLockFile($absolutePath)) {
1929
-			return false;
1930
-		}
1931
-
1932
-		$mount = $this->getMountForLock($absolutePath, $lockMountPoint);
1933
-		if ($mount) {
1934
-			try {
1935
-				$storage = $mount->getStorage();
1936
-				if ($storage->instanceOfStorage('\OCP\Files\Storage\ILockingStorage')) {
1937
-					$storage->changeLock(
1938
-						$mount->getInternalPath($absolutePath),
1939
-						$type,
1940
-						$this->lockingProvider
1941
-					);
1942
-				}
1943
-			} catch (\OCP\Lock\LockedException $e) {
1944
-				// rethrow with the a human-readable path
1945
-				throw new \OCP\Lock\LockedException(
1946
-					$this->getPathRelativeToFiles($absolutePath),
1947
-					$e
1948
-				);
1949
-			}
1950
-		}
1951
-
1952
-		return true;
1953
-	}
1954
-
1955
-	/**
1956
-	 * Unlock the given path
1957
-	 *
1958
-	 * @param string $path the path of the file to unlock, relative to the view
1959
-	 * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
1960
-	 * @param bool $lockMountPoint true to lock the mount point, false to lock the attached mount/storage
1961
-	 *
1962
-	 * @return bool False if the path is excluded from locking, true otherwise
1963
-	 */
1964
-	private function unlockPath($path, $type, $lockMountPoint = false) {
1965
-		$absolutePath = $this->getAbsolutePath($path);
1966
-		$absolutePath = Filesystem::normalizePath($absolutePath);
1967
-		if (!$this->shouldLockFile($absolutePath)) {
1968
-			return false;
1969
-		}
1970
-
1971
-		$mount = $this->getMountForLock($absolutePath, $lockMountPoint);
1972
-		if ($mount) {
1973
-			$storage = $mount->getStorage();
1974
-			if ($storage && $storage->instanceOfStorage('\OCP\Files\Storage\ILockingStorage')) {
1975
-				$storage->releaseLock(
1976
-					$mount->getInternalPath($absolutePath),
1977
-					$type,
1978
-					$this->lockingProvider
1979
-				);
1980
-			}
1981
-		}
1982
-
1983
-		return true;
1984
-	}
1985
-
1986
-	/**
1987
-	 * Lock a path and all its parents up to the root of the view
1988
-	 *
1989
-	 * @param string $path the path of the file to lock relative to the view
1990
-	 * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
1991
-	 * @param bool $lockMountPoint true to lock the mount point, false to lock the attached mount/storage
1992
-	 *
1993
-	 * @return bool False if the path is excluded from locking, true otherwise
1994
-	 */
1995
-	public function lockFile($path, $type, $lockMountPoint = false) {
1996
-		$absolutePath = $this->getAbsolutePath($path);
1997
-		$absolutePath = Filesystem::normalizePath($absolutePath);
1998
-		if (!$this->shouldLockFile($absolutePath)) {
1999
-			return false;
2000
-		}
2001
-
2002
-		$this->lockPath($path, $type, $lockMountPoint);
2003
-
2004
-		$parents = $this->getParents($path);
2005
-		foreach ($parents as $parent) {
2006
-			$this->lockPath($parent, ILockingProvider::LOCK_SHARED);
2007
-		}
2008
-
2009
-		return true;
2010
-	}
2011
-
2012
-	/**
2013
-	 * Unlock a path and all its parents up to the root of the view
2014
-	 *
2015
-	 * @param string $path the path of the file to lock relative to the view
2016
-	 * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
2017
-	 * @param bool $lockMountPoint true to lock the mount point, false to lock the attached mount/storage
2018
-	 *
2019
-	 * @return bool False if the path is excluded from locking, true otherwise
2020
-	 */
2021
-	public function unlockFile($path, $type, $lockMountPoint = false) {
2022
-		$absolutePath = $this->getAbsolutePath($path);
2023
-		$absolutePath = Filesystem::normalizePath($absolutePath);
2024
-		if (!$this->shouldLockFile($absolutePath)) {
2025
-			return false;
2026
-		}
2027
-
2028
-		$this->unlockPath($path, $type, $lockMountPoint);
2029
-
2030
-		$parents = $this->getParents($path);
2031
-		foreach ($parents as $parent) {
2032
-			$this->unlockPath($parent, ILockingProvider::LOCK_SHARED);
2033
-		}
2034
-
2035
-		return true;
2036
-	}
2037
-
2038
-	/**
2039
-	 * Only lock files in data/user/files/
2040
-	 *
2041
-	 * @param string $path Absolute path to the file/folder we try to (un)lock
2042
-	 * @return bool
2043
-	 */
2044
-	protected function shouldLockFile($path) {
2045
-		$path = Filesystem::normalizePath($path);
2046
-
2047
-		$pathSegments = explode('/', $path);
2048
-		if (isset($pathSegments[2])) {
2049
-			// E.g.: /username/files/path-to-file
2050
-			return ($pathSegments[2] === 'files') && (count($pathSegments) > 3);
2051
-		}
2052
-
2053
-		return true;
2054
-	}
2055
-
2056
-	/**
2057
-	 * Shortens the given absolute path to be relative to
2058
-	 * "$user/files".
2059
-	 *
2060
-	 * @param string $absolutePath absolute path which is under "files"
2061
-	 *
2062
-	 * @return string path relative to "files" with trimmed slashes or null
2063
-	 * if the path was NOT relative to files
2064
-	 *
2065
-	 * @throws \InvalidArgumentException if the given path was not under "files"
2066
-	 * @since 8.1.0
2067
-	 */
2068
-	public function getPathRelativeToFiles($absolutePath) {
2069
-		$path = Filesystem::normalizePath($absolutePath);
2070
-		$parts = explode('/', trim($path, '/'), 3);
2071
-		// "$user", "files", "path/to/dir"
2072
-		if (!isset($parts[1]) || $parts[1] !== 'files') {
2073
-			$this->logger->error(
2074
-				'$absolutePath must be relative to "files", value is "%s"',
2075
-				[
2076
-					$absolutePath
2077
-				]
2078
-			);
2079
-			throw new \InvalidArgumentException('$absolutePath must be relative to "files"');
2080
-		}
2081
-		if (isset($parts[2])) {
2082
-			return $parts[2];
2083
-		}
2084
-		return '';
2085
-	}
2086
-
2087
-	/**
2088
-	 * @param string $filename
2089
-	 * @return array
2090
-	 * @throws \OC\User\NoUserException
2091
-	 * @throws NotFoundException
2092
-	 */
2093
-	public function getUidAndFilename($filename) {
2094
-		$info = $this->getFileInfo($filename);
2095
-		if (!$info instanceof \OCP\Files\FileInfo) {
2096
-			throw new NotFoundException($this->getAbsolutePath($filename) . ' not found');
2097
-		}
2098
-		$uid = $info->getOwner()->getUID();
2099
-		if ($uid != \OCP\User::getUser()) {
2100
-			Filesystem::initMountPoints($uid);
2101
-			$ownerView = new View('/' . $uid . '/files');
2102
-			try {
2103
-				$filename = $ownerView->getPath($info['fileid']);
2104
-			} catch (NotFoundException $e) {
2105
-				throw new NotFoundException('File with id ' . $info['fileid'] . ' not found for user ' . $uid);
2106
-			}
2107
-		}
2108
-		return [$uid, $filename];
2109
-	}
2110
-
2111
-	/**
2112
-	 * Creates parent non-existing folders
2113
-	 *
2114
-	 * @param string $filePath
2115
-	 * @return bool
2116
-	 */
2117
-	private function createParentDirectories($filePath) {
2118
-		$directoryParts = explode('/', $filePath);
2119
-		$directoryParts = array_filter($directoryParts);
2120
-		foreach ($directoryParts as $key => $part) {
2121
-			$currentPathElements = array_slice($directoryParts, 0, $key);
2122
-			$currentPath = '/' . implode('/', $currentPathElements);
2123
-			if ($this->is_file($currentPath)) {
2124
-				return false;
2125
-			}
2126
-			if (!$this->file_exists($currentPath)) {
2127
-				$this->mkdir($currentPath);
2128
-			}
2129
-		}
2130
-
2131
-		return true;
2132
-	}
85
+    /** @var string */
86
+    private $fakeRoot = '';
87
+
88
+    /**
89
+     * @var \OCP\Lock\ILockingProvider
90
+     */
91
+    protected $lockingProvider;
92
+
93
+    private $lockingEnabled;
94
+
95
+    private $updaterEnabled = true;
96
+
97
+    /** @var \OC\User\Manager */
98
+    private $userManager;
99
+
100
+    /** @var \OCP\ILogger */
101
+    private $logger;
102
+
103
+    /**
104
+     * @param string $root
105
+     * @throws \Exception If $root contains an invalid path
106
+     */
107
+    public function __construct($root = '') {
108
+        if (is_null($root)) {
109
+            throw new \InvalidArgumentException('Root can\'t be null');
110
+        }
111
+        if (!Filesystem::isValidPath($root)) {
112
+            throw new \Exception();
113
+        }
114
+
115
+        $this->fakeRoot = $root;
116
+        $this->lockingProvider = \OC::$server->getLockingProvider();
117
+        $this->lockingEnabled = !($this->lockingProvider instanceof \OC\Lock\NoopLockingProvider);
118
+        $this->userManager = \OC::$server->getUserManager();
119
+        $this->logger = \OC::$server->getLogger();
120
+    }
121
+
122
+    public function getAbsolutePath($path = '/') {
123
+        if ($path === null) {
124
+            return null;
125
+        }
126
+        $this->assertPathLength($path);
127
+        if ($path === '') {
128
+            $path = '/';
129
+        }
130
+        if ($path[0] !== '/') {
131
+            $path = '/' . $path;
132
+        }
133
+        return $this->fakeRoot . $path;
134
+    }
135
+
136
+    /**
137
+     * change the root to a fake root
138
+     *
139
+     * @param string $fakeRoot
140
+     * @return boolean|null
141
+     */
142
+    public function chroot($fakeRoot) {
143
+        if (!$fakeRoot == '') {
144
+            if ($fakeRoot[0] !== '/') {
145
+                $fakeRoot = '/' . $fakeRoot;
146
+            }
147
+        }
148
+        $this->fakeRoot = $fakeRoot;
149
+    }
150
+
151
+    /**
152
+     * get the fake root
153
+     *
154
+     * @return string
155
+     */
156
+    public function getRoot() {
157
+        return $this->fakeRoot;
158
+    }
159
+
160
+    /**
161
+     * get path relative to the root of the view
162
+     *
163
+     * @param string $path
164
+     * @return string
165
+     */
166
+    public function getRelativePath($path) {
167
+        $this->assertPathLength($path);
168
+        if ($this->fakeRoot == '') {
169
+            return $path;
170
+        }
171
+
172
+        if (rtrim($path, '/') === rtrim($this->fakeRoot, '/')) {
173
+            return '/';
174
+        }
175
+
176
+        // missing slashes can cause wrong matches!
177
+        $root = rtrim($this->fakeRoot, '/') . '/';
178
+
179
+        if (strpos($path, $root) !== 0) {
180
+            return null;
181
+        } else {
182
+            $path = substr($path, strlen($this->fakeRoot));
183
+            if (strlen($path) === 0) {
184
+                return '/';
185
+            } else {
186
+                return $path;
187
+            }
188
+        }
189
+    }
190
+
191
+    /**
192
+     * get the mountpoint of the storage object for a path
193
+     * ( note: because a storage is not always mounted inside the fakeroot, the
194
+     * returned mountpoint is relative to the absolute root of the filesystem
195
+     * and does not take the chroot into account )
196
+     *
197
+     * @param string $path
198
+     * @return string
199
+     */
200
+    public function getMountPoint($path) {
201
+        return Filesystem::getMountPoint($this->getAbsolutePath($path));
202
+    }
203
+
204
+    /**
205
+     * get the mountpoint of the storage object for a path
206
+     * ( note: because a storage is not always mounted inside the fakeroot, the
207
+     * returned mountpoint is relative to the absolute root of the filesystem
208
+     * and does not take the chroot into account )
209
+     *
210
+     * @param string $path
211
+     * @return \OCP\Files\Mount\IMountPoint
212
+     */
213
+    public function getMount($path) {
214
+        return Filesystem::getMountManager()->find($this->getAbsolutePath($path));
215
+    }
216
+
217
+    /**
218
+     * resolve a path to a storage and internal path
219
+     *
220
+     * @param string $path
221
+     * @return array an array consisting of the storage and the internal path
222
+     */
223
+    public function resolvePath($path) {
224
+        $a = $this->getAbsolutePath($path);
225
+        $p = Filesystem::normalizePath($a);
226
+        return Filesystem::resolvePath($p);
227
+    }
228
+
229
+    /**
230
+     * return the path to a local version of the file
231
+     * we need this because we can't know if a file is stored local or not from
232
+     * outside the filestorage and for some purposes a local file is needed
233
+     *
234
+     * @param string $path
235
+     * @return string
236
+     */
237
+    public function getLocalFile($path) {
238
+        $parent = substr($path, 0, strrpos($path, '/'));
239
+        $path = $this->getAbsolutePath($path);
240
+        list($storage, $internalPath) = Filesystem::resolvePath($path);
241
+        if (Filesystem::isValidPath($parent) and $storage) {
242
+            return $storage->getLocalFile($internalPath);
243
+        } else {
244
+            return null;
245
+        }
246
+    }
247
+
248
+    /**
249
+     * @param string $path
250
+     * @return string
251
+     */
252
+    public function getLocalFolder($path) {
253
+        $parent = substr($path, 0, strrpos($path, '/'));
254
+        $path = $this->getAbsolutePath($path);
255
+        list($storage, $internalPath) = Filesystem::resolvePath($path);
256
+        if (Filesystem::isValidPath($parent) and $storage) {
257
+            return $storage->getLocalFolder($internalPath);
258
+        } else {
259
+            return null;
260
+        }
261
+    }
262
+
263
+    /**
264
+     * the following functions operate with arguments and return values identical
265
+     * to those of their PHP built-in equivalents. Mostly they are merely wrappers
266
+     * for \OC\Files\Storage\Storage via basicOperation().
267
+     */
268
+    public function mkdir($path) {
269
+        return $this->basicOperation('mkdir', $path, array('create', 'write'));
270
+    }
271
+
272
+    /**
273
+     * remove mount point
274
+     *
275
+     * @param \OC\Files\Mount\MoveableMount $mount
276
+     * @param string $path relative to data/
277
+     * @return boolean
278
+     */
279
+    protected function removeMount($mount, $path) {
280
+        if ($mount instanceof MoveableMount) {
281
+            // cut of /user/files to get the relative path to data/user/files
282
+            $pathParts = explode('/', $path, 4);
283
+            $relPath = '/' . $pathParts[3];
284
+            $this->lockFile($relPath, ILockingProvider::LOCK_SHARED, true);
285
+            \OC_Hook::emit(
286
+                Filesystem::CLASSNAME, "umount",
287
+                array(Filesystem::signal_param_path => $relPath)
288
+            );
289
+            $this->changeLock($relPath, ILockingProvider::LOCK_EXCLUSIVE, true);
290
+            $result = $mount->removeMount();
291
+            $this->changeLock($relPath, ILockingProvider::LOCK_SHARED, true);
292
+            if ($result) {
293
+                \OC_Hook::emit(
294
+                    Filesystem::CLASSNAME, "post_umount",
295
+                    array(Filesystem::signal_param_path => $relPath)
296
+                );
297
+            }
298
+            $this->unlockFile($relPath, ILockingProvider::LOCK_SHARED, true);
299
+            return $result;
300
+        } else {
301
+            // do not allow deleting the storage's root / the mount point
302
+            // because for some storages it might delete the whole contents
303
+            // but isn't supposed to work that way
304
+            return false;
305
+        }
306
+    }
307
+
308
+    public function disableCacheUpdate() {
309
+        $this->updaterEnabled = false;
310
+    }
311
+
312
+    public function enableCacheUpdate() {
313
+        $this->updaterEnabled = true;
314
+    }
315
+
316
+    protected function writeUpdate(Storage $storage, $internalPath, $time = null) {
317
+        if ($this->updaterEnabled) {
318
+            if (is_null($time)) {
319
+                $time = time();
320
+            }
321
+            $storage->getUpdater()->update($internalPath, $time);
322
+        }
323
+    }
324
+
325
+    protected function removeUpdate(Storage $storage, $internalPath) {
326
+        if ($this->updaterEnabled) {
327
+            $storage->getUpdater()->remove($internalPath);
328
+        }
329
+    }
330
+
331
+    protected function renameUpdate(Storage $sourceStorage, Storage $targetStorage, $sourceInternalPath, $targetInternalPath) {
332
+        if ($this->updaterEnabled) {
333
+            $targetStorage->getUpdater()->renameFromStorage($sourceStorage, $sourceInternalPath, $targetInternalPath);
334
+        }
335
+    }
336
+
337
+    /**
338
+     * @param string $path
339
+     * @return bool|mixed
340
+     */
341
+    public function rmdir($path) {
342
+        $absolutePath = $this->getAbsolutePath($path);
343
+        $mount = Filesystem::getMountManager()->find($absolutePath);
344
+        if ($mount->getInternalPath($absolutePath) === '') {
345
+            return $this->removeMount($mount, $absolutePath);
346
+        }
347
+        if ($this->is_dir($path)) {
348
+            $result = $this->basicOperation('rmdir', $path, array('delete'));
349
+        } else {
350
+            $result = false;
351
+        }
352
+
353
+        if (!$result && !$this->file_exists($path)) { //clear ghost files from the cache on delete
354
+            $storage = $mount->getStorage();
355
+            $internalPath = $mount->getInternalPath($absolutePath);
356
+            $storage->getUpdater()->remove($internalPath);
357
+        }
358
+        return $result;
359
+    }
360
+
361
+    /**
362
+     * @param string $path
363
+     * @return resource
364
+     */
365
+    public function opendir($path) {
366
+        return $this->basicOperation('opendir', $path, array('read'));
367
+    }
368
+
369
+    /**
370
+     * @param string $path
371
+     * @return bool|mixed
372
+     */
373
+    public function is_dir($path) {
374
+        if ($path == '/') {
375
+            return true;
376
+        }
377
+        return $this->basicOperation('is_dir', $path);
378
+    }
379
+
380
+    /**
381
+     * @param string $path
382
+     * @return bool|mixed
383
+     */
384
+    public function is_file($path) {
385
+        if ($path == '/') {
386
+            return false;
387
+        }
388
+        return $this->basicOperation('is_file', $path);
389
+    }
390
+
391
+    /**
392
+     * @param string $path
393
+     * @return mixed
394
+     */
395
+    public function stat($path) {
396
+        return $this->basicOperation('stat', $path);
397
+    }
398
+
399
+    /**
400
+     * @param string $path
401
+     * @return mixed
402
+     */
403
+    public function filetype($path) {
404
+        return $this->basicOperation('filetype', $path);
405
+    }
406
+
407
+    /**
408
+     * @param string $path
409
+     * @return mixed
410
+     */
411
+    public function filesize($path) {
412
+        return $this->basicOperation('filesize', $path);
413
+    }
414
+
415
+    /**
416
+     * @param string $path
417
+     * @return bool|mixed
418
+     * @throws \OCP\Files\InvalidPathException
419
+     */
420
+    public function readfile($path) {
421
+        $this->assertPathLength($path);
422
+        @ob_end_clean();
423
+        $handle = $this->fopen($path, 'rb');
424
+        if ($handle) {
425
+            $chunkSize = 8192; // 8 kB chunks
426
+            while (!feof($handle)) {
427
+                echo fread($handle, $chunkSize);
428
+                flush();
429
+            }
430
+            fclose($handle);
431
+            $size = $this->filesize($path);
432
+            return $size;
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
+            if (fseek($handle, $from) === 0) {
451
+                $chunkSize = 8192; // 8 kB chunks
452
+                $end = $to + 1;
453
+                while (!feof($handle) && ftell($handle) < $end) {
454
+                    $len = $end - ftell($handle);
455
+                    if ($len > $chunkSize) {
456
+                        $len = $chunkSize;
457
+                    }
458
+                    echo fread($handle, $len);
459
+                    flush();
460
+                }
461
+                $size = ftell($handle) - $from;
462
+                return $size;
463
+            }
464
+
465
+            throw new \OCP\Files\UnseekableException('fseek error');
466
+        }
467
+        return false;
468
+    }
469
+
470
+    /**
471
+     * @param string $path
472
+     * @return mixed
473
+     */
474
+    public function isCreatable($path) {
475
+        return $this->basicOperation('isCreatable', $path);
476
+    }
477
+
478
+    /**
479
+     * @param string $path
480
+     * @return mixed
481
+     */
482
+    public function isReadable($path) {
483
+        return $this->basicOperation('isReadable', $path);
484
+    }
485
+
486
+    /**
487
+     * @param string $path
488
+     * @return mixed
489
+     */
490
+    public function isUpdatable($path) {
491
+        return $this->basicOperation('isUpdatable', $path);
492
+    }
493
+
494
+    /**
495
+     * @param string $path
496
+     * @return bool|mixed
497
+     */
498
+    public function isDeletable($path) {
499
+        $absolutePath = $this->getAbsolutePath($path);
500
+        $mount = Filesystem::getMountManager()->find($absolutePath);
501
+        if ($mount->getInternalPath($absolutePath) === '') {
502
+            return $mount instanceof MoveableMount;
503
+        }
504
+        return $this->basicOperation('isDeletable', $path);
505
+    }
506
+
507
+    /**
508
+     * @param string $path
509
+     * @return mixed
510
+     */
511
+    public function isSharable($path) {
512
+        return $this->basicOperation('isSharable', $path);
513
+    }
514
+
515
+    /**
516
+     * @param string $path
517
+     * @return bool|mixed
518
+     */
519
+    public function file_exists($path) {
520
+        if ($path == '/') {
521
+            return true;
522
+        }
523
+        return $this->basicOperation('file_exists', $path);
524
+    }
525
+
526
+    /**
527
+     * @param string $path
528
+     * @return mixed
529
+     */
530
+    public function filemtime($path) {
531
+        return $this->basicOperation('filemtime', $path);
532
+    }
533
+
534
+    /**
535
+     * @param string $path
536
+     * @param int|string $mtime
537
+     * @return bool
538
+     */
539
+    public function touch($path, $mtime = null) {
540
+        if (!is_null($mtime) and !is_numeric($mtime)) {
541
+            $mtime = strtotime($mtime);
542
+        }
543
+
544
+        $hooks = array('touch');
545
+
546
+        if (!$this->file_exists($path)) {
547
+            $hooks[] = 'create';
548
+            $hooks[] = 'write';
549
+        }
550
+        $result = $this->basicOperation('touch', $path, $hooks, $mtime);
551
+        if (!$result) {
552
+            // If create file fails because of permissions on external storage like SMB folders,
553
+            // check file exists and return false if not.
554
+            if (!$this->file_exists($path)) {
555
+                return false;
556
+            }
557
+            if (is_null($mtime)) {
558
+                $mtime = time();
559
+            }
560
+            //if native touch fails, we emulate it by changing the mtime in the cache
561
+            $this->putFileInfo($path, array('mtime' => floor($mtime)));
562
+        }
563
+        return true;
564
+    }
565
+
566
+    /**
567
+     * @param string $path
568
+     * @return mixed
569
+     */
570
+    public function file_get_contents($path) {
571
+        return $this->basicOperation('file_get_contents', $path, array('read'));
572
+    }
573
+
574
+    /**
575
+     * @param bool $exists
576
+     * @param string $path
577
+     * @param bool $run
578
+     */
579
+    protected function emit_file_hooks_pre($exists, $path, &$run) {
580
+        if (!$exists) {
581
+            \OC_Hook::emit(Filesystem::CLASSNAME, Filesystem::signal_create, array(
582
+                Filesystem::signal_param_path => $this->getHookPath($path),
583
+                Filesystem::signal_param_run => &$run,
584
+            ));
585
+        } else {
586
+            \OC_Hook::emit(Filesystem::CLASSNAME, Filesystem::signal_update, array(
587
+                Filesystem::signal_param_path => $this->getHookPath($path),
588
+                Filesystem::signal_param_run => &$run,
589
+            ));
590
+        }
591
+        \OC_Hook::emit(Filesystem::CLASSNAME, Filesystem::signal_write, array(
592
+            Filesystem::signal_param_path => $this->getHookPath($path),
593
+            Filesystem::signal_param_run => &$run,
594
+        ));
595
+    }
596
+
597
+    /**
598
+     * @param bool $exists
599
+     * @param string $path
600
+     */
601
+    protected function emit_file_hooks_post($exists, $path) {
602
+        if (!$exists) {
603
+            \OC_Hook::emit(Filesystem::CLASSNAME, Filesystem::signal_post_create, array(
604
+                Filesystem::signal_param_path => $this->getHookPath($path),
605
+            ));
606
+        } else {
607
+            \OC_Hook::emit(Filesystem::CLASSNAME, Filesystem::signal_post_update, array(
608
+                Filesystem::signal_param_path => $this->getHookPath($path),
609
+            ));
610
+        }
611
+        \OC_Hook::emit(Filesystem::CLASSNAME, Filesystem::signal_post_write, array(
612
+            Filesystem::signal_param_path => $this->getHookPath($path),
613
+        ));
614
+    }
615
+
616
+    /**
617
+     * @param string $path
618
+     * @param mixed $data
619
+     * @return bool|mixed
620
+     * @throws \Exception
621
+     */
622
+    public function file_put_contents($path, $data) {
623
+        if (is_resource($data)) { //not having to deal with streams in file_put_contents makes life easier
624
+            $absolutePath = Filesystem::normalizePath($this->getAbsolutePath($path));
625
+            if (Filesystem::isValidPath($path)
626
+                and !Filesystem::isFileBlacklisted($path)
627
+            ) {
628
+                $path = $this->getRelativePath($absolutePath);
629
+
630
+                $this->lockFile($path, ILockingProvider::LOCK_SHARED);
631
+
632
+                $exists = $this->file_exists($path);
633
+                $run = true;
634
+                if ($this->shouldEmitHooks($path)) {
635
+                    $this->emit_file_hooks_pre($exists, $path, $run);
636
+                }
637
+                if (!$run) {
638
+                    $this->unlockFile($path, ILockingProvider::LOCK_SHARED);
639
+                    return false;
640
+                }
641
+
642
+                $this->changeLock($path, ILockingProvider::LOCK_EXCLUSIVE);
643
+
644
+                /** @var \OC\Files\Storage\Storage $storage */
645
+                list($storage, $internalPath) = $this->resolvePath($path);
646
+                $target = $storage->fopen($internalPath, 'w');
647
+                if ($target) {
648
+                    list (, $result) = \OC_Helper::streamCopy($data, $target);
649
+                    fclose($target);
650
+                    fclose($data);
651
+
652
+                    $this->writeUpdate($storage, $internalPath);
653
+
654
+                    $this->changeLock($path, ILockingProvider::LOCK_SHARED);
655
+
656
+                    if ($this->shouldEmitHooks($path) && $result !== false) {
657
+                        $this->emit_file_hooks_post($exists, $path);
658
+                    }
659
+                    $this->unlockFile($path, ILockingProvider::LOCK_SHARED);
660
+                    return $result;
661
+                } else {
662
+                    $this->unlockFile($path, ILockingProvider::LOCK_EXCLUSIVE);
663
+                    return false;
664
+                }
665
+            } else {
666
+                return false;
667
+            }
668
+        } else {
669
+            $hooks = ($this->file_exists($path)) ? array('update', 'write') : array('create', 'write');
670
+            return $this->basicOperation('file_put_contents', $path, $hooks, $data);
671
+        }
672
+    }
673
+
674
+    /**
675
+     * @param string $path
676
+     * @return bool|mixed
677
+     */
678
+    public function unlink($path) {
679
+        if ($path === '' || $path === '/') {
680
+            // do not allow deleting the root
681
+            return false;
682
+        }
683
+        $postFix = (substr($path, -1, 1) === '/') ? '/' : '';
684
+        $absolutePath = Filesystem::normalizePath($this->getAbsolutePath($path));
685
+        $mount = Filesystem::getMountManager()->find($absolutePath . $postFix);
686
+        if ($mount and $mount->getInternalPath($absolutePath) === '') {
687
+            return $this->removeMount($mount, $absolutePath);
688
+        }
689
+        if ($this->is_dir($path)) {
690
+            $result = $this->basicOperation('rmdir', $path, ['delete']);
691
+        } else {
692
+            $result = $this->basicOperation('unlink', $path, ['delete']);
693
+        }
694
+        if (!$result && !$this->file_exists($path)) { //clear ghost files from the cache on delete
695
+            $storage = $mount->getStorage();
696
+            $internalPath = $mount->getInternalPath($absolutePath);
697
+            $storage->getUpdater()->remove($internalPath);
698
+            return true;
699
+        } else {
700
+            return $result;
701
+        }
702
+    }
703
+
704
+    /**
705
+     * @param string $directory
706
+     * @return bool|mixed
707
+     */
708
+    public function deleteAll($directory) {
709
+        return $this->rmdir($directory);
710
+    }
711
+
712
+    /**
713
+     * Rename/move a file or folder from the source path to target path.
714
+     *
715
+     * @param string $path1 source path
716
+     * @param string $path2 target path
717
+     *
718
+     * @return bool|mixed
719
+     */
720
+    public function rename($path1, $path2) {
721
+        $absolutePath1 = Filesystem::normalizePath($this->getAbsolutePath($path1));
722
+        $absolutePath2 = Filesystem::normalizePath($this->getAbsolutePath($path2));
723
+        $result = false;
724
+        if (
725
+            Filesystem::isValidPath($path2)
726
+            and Filesystem::isValidPath($path1)
727
+            and !Filesystem::isFileBlacklisted($path2)
728
+        ) {
729
+            $path1 = $this->getRelativePath($absolutePath1);
730
+            $path2 = $this->getRelativePath($absolutePath2);
731
+            $exists = $this->file_exists($path2);
732
+
733
+            if ($path1 == null or $path2 == null) {
734
+                return false;
735
+            }
736
+
737
+            $this->lockFile($path1, ILockingProvider::LOCK_SHARED, true);
738
+            try {
739
+                $this->lockFile($path2, ILockingProvider::LOCK_SHARED, true);
740
+            } catch (LockedException $e) {
741
+                $this->unlockFile($path1, ILockingProvider::LOCK_SHARED);
742
+                throw $e;
743
+            }
744
+
745
+            $run = true;
746
+            if ($this->shouldEmitHooks($path1) && (Cache\Scanner::isPartialFile($path1) && !Cache\Scanner::isPartialFile($path2))) {
747
+                // if it was a rename from a part file to a regular file it was a write and not a rename operation
748
+                $this->emit_file_hooks_pre($exists, $path2, $run);
749
+            } elseif ($this->shouldEmitHooks($path1)) {
750
+                \OC_Hook::emit(
751
+                    Filesystem::CLASSNAME, Filesystem::signal_rename,
752
+                    array(
753
+                        Filesystem::signal_param_oldpath => $this->getHookPath($path1),
754
+                        Filesystem::signal_param_newpath => $this->getHookPath($path2),
755
+                        Filesystem::signal_param_run => &$run
756
+                    )
757
+                );
758
+            }
759
+            if ($run) {
760
+                $this->verifyPath(dirname($path2), basename($path2));
761
+
762
+                $manager = Filesystem::getMountManager();
763
+                $mount1 = $this->getMount($path1);
764
+                $mount2 = $this->getMount($path2);
765
+                $storage1 = $mount1->getStorage();
766
+                $storage2 = $mount2->getStorage();
767
+                $internalPath1 = $mount1->getInternalPath($absolutePath1);
768
+                $internalPath2 = $mount2->getInternalPath($absolutePath2);
769
+
770
+                $this->changeLock($path1, ILockingProvider::LOCK_EXCLUSIVE, true);
771
+                $this->changeLock($path2, ILockingProvider::LOCK_EXCLUSIVE, true);
772
+
773
+                if ($internalPath1 === '') {
774
+                    if ($mount1 instanceof MoveableMount) {
775
+                        if ($this->isTargetAllowed($absolutePath2)) {
776
+                            /**
777
+                             * @var \OC\Files\Mount\MountPoint | \OC\Files\Mount\MoveableMount $mount1
778
+                             */
779
+                            $sourceMountPoint = $mount1->getMountPoint();
780
+                            $result = $mount1->moveMount($absolutePath2);
781
+                            $manager->moveMount($sourceMountPoint, $mount1->getMountPoint());
782
+                        } else {
783
+                            $result = false;
784
+                        }
785
+                    } else {
786
+                        $result = false;
787
+                    }
788
+                    // moving a file/folder within the same mount point
789
+                } elseif ($storage1 === $storage2) {
790
+                    if ($storage1) {
791
+                        $result = $storage1->rename($internalPath1, $internalPath2);
792
+                    } else {
793
+                        $result = false;
794
+                    }
795
+                    // moving a file/folder between storages (from $storage1 to $storage2)
796
+                } else {
797
+                    $result = $storage2->moveFromStorage($storage1, $internalPath1, $internalPath2);
798
+                }
799
+
800
+                if ((Cache\Scanner::isPartialFile($path1) && !Cache\Scanner::isPartialFile($path2)) && $result !== false) {
801
+                    // if it was a rename from a part file to a regular file it was a write and not a rename operation
802
+
803
+                    $this->writeUpdate($storage2, $internalPath2);
804
+                } else if ($result) {
805
+                    if ($internalPath1 !== '') { // don't do a cache update for moved mounts
806
+                        $this->renameUpdate($storage1, $storage2, $internalPath1, $internalPath2);
807
+                    }
808
+                }
809
+
810
+                $this->changeLock($path1, ILockingProvider::LOCK_SHARED, true);
811
+                $this->changeLock($path2, ILockingProvider::LOCK_SHARED, true);
812
+
813
+                if ((Cache\Scanner::isPartialFile($path1) && !Cache\Scanner::isPartialFile($path2)) && $result !== false) {
814
+                    if ($this->shouldEmitHooks()) {
815
+                        $this->emit_file_hooks_post($exists, $path2);
816
+                    }
817
+                } elseif ($result) {
818
+                    if ($this->shouldEmitHooks($path1) and $this->shouldEmitHooks($path2)) {
819
+                        \OC_Hook::emit(
820
+                            Filesystem::CLASSNAME,
821
+                            Filesystem::signal_post_rename,
822
+                            array(
823
+                                Filesystem::signal_param_oldpath => $this->getHookPath($path1),
824
+                                Filesystem::signal_param_newpath => $this->getHookPath($path2)
825
+                            )
826
+                        );
827
+                    }
828
+                }
829
+            }
830
+            $this->unlockFile($path1, ILockingProvider::LOCK_SHARED, true);
831
+            $this->unlockFile($path2, ILockingProvider::LOCK_SHARED, true);
832
+        }
833
+        return $result;
834
+    }
835
+
836
+    /**
837
+     * Copy a file/folder from the source path to target path
838
+     *
839
+     * @param string $path1 source path
840
+     * @param string $path2 target path
841
+     * @param bool $preserveMtime whether to preserve mtime on the copy
842
+     *
843
+     * @return bool|mixed
844
+     */
845
+    public function copy($path1, $path2, $preserveMtime = false) {
846
+        $absolutePath1 = Filesystem::normalizePath($this->getAbsolutePath($path1));
847
+        $absolutePath2 = Filesystem::normalizePath($this->getAbsolutePath($path2));
848
+        $result = false;
849
+        if (
850
+            Filesystem::isValidPath($path2)
851
+            and Filesystem::isValidPath($path1)
852
+            and !Filesystem::isFileBlacklisted($path2)
853
+        ) {
854
+            $path1 = $this->getRelativePath($absolutePath1);
855
+            $path2 = $this->getRelativePath($absolutePath2);
856
+
857
+            if ($path1 == null or $path2 == null) {
858
+                return false;
859
+            }
860
+            $run = true;
861
+
862
+            $this->lockFile($path2, ILockingProvider::LOCK_SHARED);
863
+            $this->lockFile($path1, ILockingProvider::LOCK_SHARED);
864
+            $lockTypePath1 = ILockingProvider::LOCK_SHARED;
865
+            $lockTypePath2 = ILockingProvider::LOCK_SHARED;
866
+
867
+            try {
868
+
869
+                $exists = $this->file_exists($path2);
870
+                if ($this->shouldEmitHooks()) {
871
+                    \OC_Hook::emit(
872
+                        Filesystem::CLASSNAME,
873
+                        Filesystem::signal_copy,
874
+                        array(
875
+                            Filesystem::signal_param_oldpath => $this->getHookPath($path1),
876
+                            Filesystem::signal_param_newpath => $this->getHookPath($path2),
877
+                            Filesystem::signal_param_run => &$run
878
+                        )
879
+                    );
880
+                    $this->emit_file_hooks_pre($exists, $path2, $run);
881
+                }
882
+                if ($run) {
883
+                    $mount1 = $this->getMount($path1);
884
+                    $mount2 = $this->getMount($path2);
885
+                    $storage1 = $mount1->getStorage();
886
+                    $internalPath1 = $mount1->getInternalPath($absolutePath1);
887
+                    $storage2 = $mount2->getStorage();
888
+                    $internalPath2 = $mount2->getInternalPath($absolutePath2);
889
+
890
+                    $this->changeLock($path2, ILockingProvider::LOCK_EXCLUSIVE);
891
+                    $lockTypePath2 = ILockingProvider::LOCK_EXCLUSIVE;
892
+
893
+                    if ($mount1->getMountPoint() == $mount2->getMountPoint()) {
894
+                        if ($storage1) {
895
+                            $result = $storage1->copy($internalPath1, $internalPath2);
896
+                        } else {
897
+                            $result = false;
898
+                        }
899
+                    } else {
900
+                        $result = $storage2->copyFromStorage($storage1, $internalPath1, $internalPath2);
901
+                    }
902
+
903
+                    $this->writeUpdate($storage2, $internalPath2);
904
+
905
+                    $this->changeLock($path2, ILockingProvider::LOCK_SHARED);
906
+                    $lockTypePath2 = ILockingProvider::LOCK_SHARED;
907
+
908
+                    if ($this->shouldEmitHooks() && $result !== false) {
909
+                        \OC_Hook::emit(
910
+                            Filesystem::CLASSNAME,
911
+                            Filesystem::signal_post_copy,
912
+                            array(
913
+                                Filesystem::signal_param_oldpath => $this->getHookPath($path1),
914
+                                Filesystem::signal_param_newpath => $this->getHookPath($path2)
915
+                            )
916
+                        );
917
+                        $this->emit_file_hooks_post($exists, $path2);
918
+                    }
919
+
920
+                }
921
+            } catch (\Exception $e) {
922
+                $this->unlockFile($path2, $lockTypePath2);
923
+                $this->unlockFile($path1, $lockTypePath1);
924
+                throw $e;
925
+            }
926
+
927
+            $this->unlockFile($path2, $lockTypePath2);
928
+            $this->unlockFile($path1, $lockTypePath1);
929
+
930
+        }
931
+        return $result;
932
+    }
933
+
934
+    /**
935
+     * @param string $path
936
+     * @param string $mode 'r' or 'w'
937
+     * @return resource
938
+     */
939
+    public function fopen($path, $mode) {
940
+        $mode = str_replace('b', '', $mode); // the binary flag is a windows only feature which we do not support
941
+        $hooks = array();
942
+        switch ($mode) {
943
+            case 'r':
944
+                $hooks[] = 'read';
945
+                break;
946
+            case 'r+':
947
+            case 'w+':
948
+            case 'x+':
949
+            case 'a+':
950
+                $hooks[] = 'read';
951
+                $hooks[] = 'write';
952
+                break;
953
+            case 'w':
954
+            case 'x':
955
+            case 'a':
956
+                $hooks[] = 'write';
957
+                break;
958
+            default:
959
+                \OCP\Util::writeLog('core', 'invalid mode (' . $mode . ') for ' . $path, \OCP\Util::ERROR);
960
+        }
961
+
962
+        if ($mode !== 'r' && $mode !== 'w') {
963
+            \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');
964
+        }
965
+
966
+        return $this->basicOperation('fopen', $path, $hooks, $mode);
967
+    }
968
+
969
+    /**
970
+     * @param string $path
971
+     * @return bool|string
972
+     * @throws \OCP\Files\InvalidPathException
973
+     */
974
+    public function toTmpFile($path) {
975
+        $this->assertPathLength($path);
976
+        if (Filesystem::isValidPath($path)) {
977
+            $source = $this->fopen($path, 'r');
978
+            if ($source) {
979
+                $extension = pathinfo($path, PATHINFO_EXTENSION);
980
+                $tmpFile = \OC::$server->getTempManager()->getTemporaryFile($extension);
981
+                file_put_contents($tmpFile, $source);
982
+                return $tmpFile;
983
+            } else {
984
+                return false;
985
+            }
986
+        } else {
987
+            return false;
988
+        }
989
+    }
990
+
991
+    /**
992
+     * @param string $tmpFile
993
+     * @param string $path
994
+     * @return bool|mixed
995
+     * @throws \OCP\Files\InvalidPathException
996
+     */
997
+    public function fromTmpFile($tmpFile, $path) {
998
+        $this->assertPathLength($path);
999
+        if (Filesystem::isValidPath($path)) {
1000
+
1001
+            // Get directory that the file is going into
1002
+            $filePath = dirname($path);
1003
+
1004
+            // Create the directories if any
1005
+            if (!$this->file_exists($filePath)) {
1006
+                $result = $this->createParentDirectories($filePath);
1007
+                if ($result === false) {
1008
+                    return false;
1009
+                }
1010
+            }
1011
+
1012
+            $source = fopen($tmpFile, 'r');
1013
+            if ($source) {
1014
+                $result = $this->file_put_contents($path, $source);
1015
+                // $this->file_put_contents() might have already closed
1016
+                // the resource, so we check it, before trying to close it
1017
+                // to avoid messages in the error log.
1018
+                if (is_resource($source)) {
1019
+                    fclose($source);
1020
+                }
1021
+                unlink($tmpFile);
1022
+                return $result;
1023
+            } else {
1024
+                return false;
1025
+            }
1026
+        } else {
1027
+            return false;
1028
+        }
1029
+    }
1030
+
1031
+
1032
+    /**
1033
+     * @param string $path
1034
+     * @return mixed
1035
+     * @throws \OCP\Files\InvalidPathException
1036
+     */
1037
+    public function getMimeType($path) {
1038
+        $this->assertPathLength($path);
1039
+        return $this->basicOperation('getMimeType', $path);
1040
+    }
1041
+
1042
+    /**
1043
+     * @param string $type
1044
+     * @param string $path
1045
+     * @param bool $raw
1046
+     * @return bool|null|string
1047
+     */
1048
+    public function hash($type, $path, $raw = false) {
1049
+        $postFix = (substr($path, -1, 1) === '/') ? '/' : '';
1050
+        $absolutePath = Filesystem::normalizePath($this->getAbsolutePath($path));
1051
+        if (Filesystem::isValidPath($path)) {
1052
+            $path = $this->getRelativePath($absolutePath);
1053
+            if ($path == null) {
1054
+                return false;
1055
+            }
1056
+            if ($this->shouldEmitHooks($path)) {
1057
+                \OC_Hook::emit(
1058
+                    Filesystem::CLASSNAME,
1059
+                    Filesystem::signal_read,
1060
+                    array(Filesystem::signal_param_path => $this->getHookPath($path))
1061
+                );
1062
+            }
1063
+            list($storage, $internalPath) = Filesystem::resolvePath($absolutePath . $postFix);
1064
+            if ($storage) {
1065
+                $result = $storage->hash($type, $internalPath, $raw);
1066
+                return $result;
1067
+            }
1068
+        }
1069
+        return null;
1070
+    }
1071
+
1072
+    /**
1073
+     * @param string $path
1074
+     * @return mixed
1075
+     * @throws \OCP\Files\InvalidPathException
1076
+     */
1077
+    public function free_space($path = '/') {
1078
+        $this->assertPathLength($path);
1079
+        $result = $this->basicOperation('free_space', $path);
1080
+        if ($result === null) {
1081
+            throw new InvalidPathException();
1082
+        }
1083
+        return $result;
1084
+    }
1085
+
1086
+    /**
1087
+     * abstraction layer for basic filesystem functions: wrapper for \OC\Files\Storage\Storage
1088
+     *
1089
+     * @param string $operation
1090
+     * @param string $path
1091
+     * @param array $hooks (optional)
1092
+     * @param mixed $extraParam (optional)
1093
+     * @return mixed
1094
+     * @throws \Exception
1095
+     *
1096
+     * This method takes requests for basic filesystem functions (e.g. reading & writing
1097
+     * files), processes hooks and proxies, sanitises paths, and finally passes them on to
1098
+     * \OC\Files\Storage\Storage for delegation to a storage backend for execution
1099
+     */
1100
+    private function basicOperation($operation, $path, $hooks = [], $extraParam = null) {
1101
+        $postFix = (substr($path, -1, 1) === '/') ? '/' : '';
1102
+        $absolutePath = Filesystem::normalizePath($this->getAbsolutePath($path));
1103
+        if (Filesystem::isValidPath($path)
1104
+            and !Filesystem::isFileBlacklisted($path)
1105
+        ) {
1106
+            $path = $this->getRelativePath($absolutePath);
1107
+            if ($path == null) {
1108
+                return false;
1109
+            }
1110
+
1111
+            if (in_array('write', $hooks) || in_array('delete', $hooks) || in_array('read', $hooks)) {
1112
+                // always a shared lock during pre-hooks so the hook can read the file
1113
+                $this->lockFile($path, ILockingProvider::LOCK_SHARED);
1114
+            }
1115
+
1116
+            $run = $this->runHooks($hooks, $path);
1117
+            /** @var \OC\Files\Storage\Storage $storage */
1118
+            list($storage, $internalPath) = Filesystem::resolvePath($absolutePath . $postFix);
1119
+            if ($run and $storage) {
1120
+                if (in_array('write', $hooks) || in_array('delete', $hooks)) {
1121
+                    $this->changeLock($path, ILockingProvider::LOCK_EXCLUSIVE);
1122
+                }
1123
+                try {
1124
+                    if (!is_null($extraParam)) {
1125
+                        $result = $storage->$operation($internalPath, $extraParam);
1126
+                    } else {
1127
+                        $result = $storage->$operation($internalPath);
1128
+                    }
1129
+                } catch (\Exception $e) {
1130
+                    if (in_array('write', $hooks) || in_array('delete', $hooks)) {
1131
+                        $this->unlockFile($path, ILockingProvider::LOCK_EXCLUSIVE);
1132
+                    } else if (in_array('read', $hooks)) {
1133
+                        $this->unlockFile($path, ILockingProvider::LOCK_SHARED);
1134
+                    }
1135
+                    throw $e;
1136
+                }
1137
+
1138
+                if ($result && in_array('delete', $hooks) and $result) {
1139
+                    $this->removeUpdate($storage, $internalPath);
1140
+                }
1141
+                if ($result && in_array('write', $hooks) and $operation !== 'fopen') {
1142
+                    $this->writeUpdate($storage, $internalPath);
1143
+                }
1144
+                if ($result && in_array('touch', $hooks)) {
1145
+                    $this->writeUpdate($storage, $internalPath, $extraParam);
1146
+                }
1147
+
1148
+                if ((in_array('write', $hooks) || in_array('delete', $hooks)) && ($operation !== 'fopen' || $result === false)) {
1149
+                    $this->changeLock($path, ILockingProvider::LOCK_SHARED);
1150
+                }
1151
+
1152
+                $unlockLater = false;
1153
+                if ($this->lockingEnabled && $operation === 'fopen' && is_resource($result)) {
1154
+                    $unlockLater = true;
1155
+                    // make sure our unlocking callback will still be called if connection is aborted
1156
+                    ignore_user_abort(true);
1157
+                    $result = CallbackWrapper::wrap($result, null, null, function () use ($hooks, $path) {
1158
+                        if (in_array('write', $hooks)) {
1159
+                            $this->unlockFile($path, ILockingProvider::LOCK_EXCLUSIVE);
1160
+                        } else if (in_array('read', $hooks)) {
1161
+                            $this->unlockFile($path, ILockingProvider::LOCK_SHARED);
1162
+                        }
1163
+                    });
1164
+                }
1165
+
1166
+                if ($this->shouldEmitHooks($path) && $result !== false) {
1167
+                    if ($operation != 'fopen') { //no post hooks for fopen, the file stream is still open
1168
+                        $this->runHooks($hooks, $path, true);
1169
+                    }
1170
+                }
1171
+
1172
+                if (!$unlockLater
1173
+                    && (in_array('write', $hooks) || in_array('delete', $hooks) || in_array('read', $hooks))
1174
+                ) {
1175
+                    $this->unlockFile($path, ILockingProvider::LOCK_SHARED);
1176
+                }
1177
+                return $result;
1178
+            } else {
1179
+                $this->unlockFile($path, ILockingProvider::LOCK_SHARED);
1180
+            }
1181
+        }
1182
+        return null;
1183
+    }
1184
+
1185
+    /**
1186
+     * get the path relative to the default root for hook usage
1187
+     *
1188
+     * @param string $path
1189
+     * @return string
1190
+     */
1191
+    private function getHookPath($path) {
1192
+        if (!Filesystem::getView()) {
1193
+            return $path;
1194
+        }
1195
+        return Filesystem::getView()->getRelativePath($this->getAbsolutePath($path));
1196
+    }
1197
+
1198
+    private function shouldEmitHooks($path = '') {
1199
+        if ($path && Cache\Scanner::isPartialFile($path)) {
1200
+            return false;
1201
+        }
1202
+        if (!Filesystem::$loaded) {
1203
+            return false;
1204
+        }
1205
+        $defaultRoot = Filesystem::getRoot();
1206
+        if ($defaultRoot === null) {
1207
+            return false;
1208
+        }
1209
+        if ($this->fakeRoot === $defaultRoot) {
1210
+            return true;
1211
+        }
1212
+        $fullPath = $this->getAbsolutePath($path);
1213
+
1214
+        if ($fullPath === $defaultRoot) {
1215
+            return true;
1216
+        }
1217
+
1218
+        return (strlen($fullPath) > strlen($defaultRoot)) && (substr($fullPath, 0, strlen($defaultRoot) + 1) === $defaultRoot . '/');
1219
+    }
1220
+
1221
+    /**
1222
+     * @param string[] $hooks
1223
+     * @param string $path
1224
+     * @param bool $post
1225
+     * @return bool
1226
+     */
1227
+    private function runHooks($hooks, $path, $post = false) {
1228
+        $relativePath = $path;
1229
+        $path = $this->getHookPath($path);
1230
+        $prefix = ($post) ? 'post_' : '';
1231
+        $run = true;
1232
+        if ($this->shouldEmitHooks($relativePath)) {
1233
+            foreach ($hooks as $hook) {
1234
+                if ($hook != 'read') {
1235
+                    \OC_Hook::emit(
1236
+                        Filesystem::CLASSNAME,
1237
+                        $prefix . $hook,
1238
+                        array(
1239
+                            Filesystem::signal_param_run => &$run,
1240
+                            Filesystem::signal_param_path => $path
1241
+                        )
1242
+                    );
1243
+                } elseif (!$post) {
1244
+                    \OC_Hook::emit(
1245
+                        Filesystem::CLASSNAME,
1246
+                        $prefix . $hook,
1247
+                        array(
1248
+                            Filesystem::signal_param_path => $path
1249
+                        )
1250
+                    );
1251
+                }
1252
+            }
1253
+        }
1254
+        return $run;
1255
+    }
1256
+
1257
+    /**
1258
+     * check if a file or folder has been updated since $time
1259
+     *
1260
+     * @param string $path
1261
+     * @param int $time
1262
+     * @return bool
1263
+     */
1264
+    public function hasUpdated($path, $time) {
1265
+        return $this->basicOperation('hasUpdated', $path, array(), $time);
1266
+    }
1267
+
1268
+    /**
1269
+     * @param string $ownerId
1270
+     * @return \OC\User\User
1271
+     */
1272
+    private function getUserObjectForOwner($ownerId) {
1273
+        $owner = $this->userManager->get($ownerId);
1274
+        if ($owner instanceof IUser) {
1275
+            return $owner;
1276
+        } else {
1277
+            return new User($ownerId, null);
1278
+        }
1279
+    }
1280
+
1281
+    /**
1282
+     * Get file info from cache
1283
+     *
1284
+     * If the file is not in cached it will be scanned
1285
+     * If the file has changed on storage the cache will be updated
1286
+     *
1287
+     * @param \OC\Files\Storage\Storage $storage
1288
+     * @param string $internalPath
1289
+     * @param string $relativePath
1290
+     * @return ICacheEntry|bool
1291
+     */
1292
+    private function getCacheEntry($storage, $internalPath, $relativePath) {
1293
+        $cache = $storage->getCache($internalPath);
1294
+        $data = $cache->get($internalPath);
1295
+        $watcher = $storage->getWatcher($internalPath);
1296
+
1297
+        try {
1298
+            // if the file is not in the cache or needs to be updated, trigger the scanner and reload the data
1299
+            if (!$data || $data['size'] === -1) {
1300
+                $this->lockFile($relativePath, ILockingProvider::LOCK_SHARED);
1301
+                if (!$storage->file_exists($internalPath)) {
1302
+                    $this->unlockFile($relativePath, ILockingProvider::LOCK_SHARED);
1303
+                    return false;
1304
+                }
1305
+                $scanner = $storage->getScanner($internalPath);
1306
+                $scanner->scan($internalPath, Cache\Scanner::SCAN_SHALLOW);
1307
+                $data = $cache->get($internalPath);
1308
+                $this->unlockFile($relativePath, ILockingProvider::LOCK_SHARED);
1309
+            } else if (!Cache\Scanner::isPartialFile($internalPath) && $watcher->needsUpdate($internalPath, $data)) {
1310
+                $this->lockFile($relativePath, ILockingProvider::LOCK_SHARED);
1311
+                $watcher->update($internalPath, $data);
1312
+                $storage->getPropagator()->propagateChange($internalPath, time());
1313
+                $data = $cache->get($internalPath);
1314
+                $this->unlockFile($relativePath, ILockingProvider::LOCK_SHARED);
1315
+            }
1316
+        } catch (LockedException $e) {
1317
+            // if the file is locked we just use the old cache info
1318
+        }
1319
+
1320
+        return $data;
1321
+    }
1322
+
1323
+    /**
1324
+     * get the filesystem info
1325
+     *
1326
+     * @param string $path
1327
+     * @param boolean|string $includeMountPoints true to add mountpoint sizes,
1328
+     * 'ext' to add only ext storage mount point sizes. Defaults to true.
1329
+     * defaults to true
1330
+     * @return \OC\Files\FileInfo|false False if file does not exist
1331
+     */
1332
+    public function getFileInfo($path, $includeMountPoints = true) {
1333
+        $this->assertPathLength($path);
1334
+        if (!Filesystem::isValidPath($path)) {
1335
+            return false;
1336
+        }
1337
+        if (Cache\Scanner::isPartialFile($path)) {
1338
+            return $this->getPartFileInfo($path);
1339
+        }
1340
+        $relativePath = $path;
1341
+        $path = Filesystem::normalizePath($this->fakeRoot . '/' . $path);
1342
+
1343
+        $mount = Filesystem::getMountManager()->find($path);
1344
+        $storage = $mount->getStorage();
1345
+        $internalPath = $mount->getInternalPath($path);
1346
+        if ($storage) {
1347
+            $data = $this->getCacheEntry($storage, $internalPath, $relativePath);
1348
+
1349
+            if (!$data instanceof ICacheEntry) {
1350
+                return false;
1351
+            }
1352
+
1353
+            if ($mount instanceof MoveableMount && $internalPath === '') {
1354
+                $data['permissions'] |= \OCP\Constants::PERMISSION_DELETE;
1355
+            }
1356
+
1357
+            $owner = $this->getUserObjectForOwner($storage->getOwner($internalPath));
1358
+            $info = new FileInfo($path, $storage, $internalPath, $data, $mount, $owner);
1359
+
1360
+            if ($data and isset($data['fileid'])) {
1361
+                if ($includeMountPoints and $data['mimetype'] === 'httpd/unix-directory') {
1362
+                    //add the sizes of other mount points to the folder
1363
+                    $extOnly = ($includeMountPoints === 'ext');
1364
+                    $mounts = Filesystem::getMountManager()->findIn($path);
1365
+                    $info->setSubMounts(array_filter($mounts, function (IMountPoint $mount) use ($extOnly) {
1366
+                        $subStorage = $mount->getStorage();
1367
+                        return !($extOnly && $subStorage instanceof \OCA\Files_Sharing\SharedStorage);
1368
+                    }));
1369
+                }
1370
+            }
1371
+
1372
+            return $info;
1373
+        }
1374
+
1375
+        return false;
1376
+    }
1377
+
1378
+    /**
1379
+     * get the content of a directory
1380
+     *
1381
+     * @param string $directory path under datadirectory
1382
+     * @param string $mimetype_filter limit returned content to this mimetype or mimepart
1383
+     * @return FileInfo[]
1384
+     */
1385
+    public function getDirectoryContent($directory, $mimetype_filter = '') {
1386
+        $this->assertPathLength($directory);
1387
+        if (!Filesystem::isValidPath($directory)) {
1388
+            return [];
1389
+        }
1390
+        $path = $this->getAbsolutePath($directory);
1391
+        $path = Filesystem::normalizePath($path);
1392
+        $mount = $this->getMount($directory);
1393
+        $storage = $mount->getStorage();
1394
+        $internalPath = $mount->getInternalPath($path);
1395
+        if ($storage) {
1396
+            $cache = $storage->getCache($internalPath);
1397
+            $user = \OC_User::getUser();
1398
+
1399
+            $data = $this->getCacheEntry($storage, $internalPath, $directory);
1400
+
1401
+            if (!$data instanceof ICacheEntry || !isset($data['fileid']) || !($data->getPermissions() && Constants::PERMISSION_READ)) {
1402
+                return [];
1403
+            }
1404
+
1405
+            $folderId = $data['fileid'];
1406
+            $contents = $cache->getFolderContentsById($folderId); //TODO: mimetype_filter
1407
+
1408
+            $sharingDisabled = \OCP\Util::isSharingDisabledForUser();
1409
+            /**
1410
+             * @var \OC\Files\FileInfo[] $files
1411
+             */
1412
+            $files = array_map(function (ICacheEntry $content) use ($path, $storage, $mount, $sharingDisabled) {
1413
+                if ($sharingDisabled) {
1414
+                    $content['permissions'] = $content['permissions'] & ~\OCP\Constants::PERMISSION_SHARE;
1415
+                }
1416
+                $owner = $this->getUserObjectForOwner($storage->getOwner($content['path']));
1417
+                return new FileInfo($path . '/' . $content['name'], $storage, $content['path'], $content, $mount, $owner);
1418
+            }, $contents);
1419
+
1420
+            //add a folder for any mountpoint in this directory and add the sizes of other mountpoints to the folders
1421
+            $mounts = Filesystem::getMountManager()->findIn($path);
1422
+            $dirLength = strlen($path);
1423
+            foreach ($mounts as $mount) {
1424
+                $mountPoint = $mount->getMountPoint();
1425
+                $subStorage = $mount->getStorage();
1426
+                if ($subStorage) {
1427
+                    $subCache = $subStorage->getCache('');
1428
+
1429
+                    $rootEntry = $subCache->get('');
1430
+                    if (!$rootEntry) {
1431
+                        $subScanner = $subStorage->getScanner('');
1432
+                        try {
1433
+                            $subScanner->scanFile('');
1434
+                        } catch (\OCP\Files\StorageNotAvailableException $e) {
1435
+                            continue;
1436
+                        } catch (\OCP\Files\StorageInvalidException $e) {
1437
+                            continue;
1438
+                        } catch (\Exception $e) {
1439
+                            // sometimes when the storage is not available it can be any exception
1440
+                            \OCP\Util::writeLog(
1441
+                                'core',
1442
+                                'Exception while scanning storage "' . $subStorage->getId() . '": ' .
1443
+                                get_class($e) . ': ' . $e->getMessage(),
1444
+                                \OCP\Util::ERROR
1445
+                            );
1446
+                            continue;
1447
+                        }
1448
+                        $rootEntry = $subCache->get('');
1449
+                    }
1450
+
1451
+                    if ($rootEntry && ($rootEntry->getPermissions() && Constants::PERMISSION_READ)) {
1452
+                        $relativePath = trim(substr($mountPoint, $dirLength), '/');
1453
+                        if ($pos = strpos($relativePath, '/')) {
1454
+                            //mountpoint inside subfolder add size to the correct folder
1455
+                            $entryName = substr($relativePath, 0, $pos);
1456
+                            foreach ($files as &$entry) {
1457
+                                if ($entry->getName() === $entryName) {
1458
+                                    $entry->addSubEntry($rootEntry, $mountPoint);
1459
+                                }
1460
+                            }
1461
+                        } else { //mountpoint in this folder, add an entry for it
1462
+                            $rootEntry['name'] = $relativePath;
1463
+                            $rootEntry['type'] = $rootEntry['mimetype'] === 'httpd/unix-directory' ? 'dir' : 'file';
1464
+                            $permissions = $rootEntry['permissions'];
1465
+                            // do not allow renaming/deleting the mount point if they are not shared files/folders
1466
+                            // for shared files/folders we use the permissions given by the owner
1467
+                            if ($mount instanceof MoveableMount) {
1468
+                                $rootEntry['permissions'] = $permissions | \OCP\Constants::PERMISSION_UPDATE | \OCP\Constants::PERMISSION_DELETE;
1469
+                            } else {
1470
+                                $rootEntry['permissions'] = $permissions & (\OCP\Constants::PERMISSION_ALL - (\OCP\Constants::PERMISSION_UPDATE | \OCP\Constants::PERMISSION_DELETE));
1471
+                            }
1472
+
1473
+                            //remove any existing entry with the same name
1474
+                            foreach ($files as $i => $file) {
1475
+                                if ($file['name'] === $rootEntry['name']) {
1476
+                                    unset($files[$i]);
1477
+                                    break;
1478
+                                }
1479
+                            }
1480
+                            $rootEntry['path'] = substr(Filesystem::normalizePath($path . '/' . $rootEntry['name']), strlen($user) + 2); // full path without /$user/
1481
+
1482
+                            // if sharing was disabled for the user we remove the share permissions
1483
+                            if (\OCP\Util::isSharingDisabledForUser()) {
1484
+                                $rootEntry['permissions'] = $rootEntry['permissions'] & ~\OCP\Constants::PERMISSION_SHARE;
1485
+                            }
1486
+
1487
+                            $owner = $this->getUserObjectForOwner($subStorage->getOwner(''));
1488
+                            $files[] = new FileInfo($path . '/' . $rootEntry['name'], $subStorage, '', $rootEntry, $mount, $owner);
1489
+                        }
1490
+                    }
1491
+                }
1492
+            }
1493
+
1494
+            if ($mimetype_filter) {
1495
+                $files = array_filter($files, function (FileInfo $file) use ($mimetype_filter) {
1496
+                    if (strpos($mimetype_filter, '/')) {
1497
+                        return $file->getMimetype() === $mimetype_filter;
1498
+                    } else {
1499
+                        return $file->getMimePart() === $mimetype_filter;
1500
+                    }
1501
+                });
1502
+            }
1503
+
1504
+            return $files;
1505
+        } else {
1506
+            return [];
1507
+        }
1508
+    }
1509
+
1510
+    /**
1511
+     * change file metadata
1512
+     *
1513
+     * @param string $path
1514
+     * @param array|\OCP\Files\FileInfo $data
1515
+     * @return int
1516
+     *
1517
+     * returns the fileid of the updated file
1518
+     */
1519
+    public function putFileInfo($path, $data) {
1520
+        $this->assertPathLength($path);
1521
+        if ($data instanceof FileInfo) {
1522
+            $data = $data->getData();
1523
+        }
1524
+        $path = Filesystem::normalizePath($this->fakeRoot . '/' . $path);
1525
+        /**
1526
+         * @var \OC\Files\Storage\Storage $storage
1527
+         * @var string $internalPath
1528
+         */
1529
+        list($storage, $internalPath) = Filesystem::resolvePath($path);
1530
+        if ($storage) {
1531
+            $cache = $storage->getCache($path);
1532
+
1533
+            if (!$cache->inCache($internalPath)) {
1534
+                $scanner = $storage->getScanner($internalPath);
1535
+                $scanner->scan($internalPath, Cache\Scanner::SCAN_SHALLOW);
1536
+            }
1537
+
1538
+            return $cache->put($internalPath, $data);
1539
+        } else {
1540
+            return -1;
1541
+        }
1542
+    }
1543
+
1544
+    /**
1545
+     * search for files with the name matching $query
1546
+     *
1547
+     * @param string $query
1548
+     * @return FileInfo[]
1549
+     */
1550
+    public function search($query) {
1551
+        return $this->searchCommon('search', array('%' . $query . '%'));
1552
+    }
1553
+
1554
+    /**
1555
+     * search for files with the name matching $query
1556
+     *
1557
+     * @param string $query
1558
+     * @return FileInfo[]
1559
+     */
1560
+    public function searchRaw($query) {
1561
+        return $this->searchCommon('search', array($query));
1562
+    }
1563
+
1564
+    /**
1565
+     * search for files by mimetype
1566
+     *
1567
+     * @param string $mimetype
1568
+     * @return FileInfo[]
1569
+     */
1570
+    public function searchByMime($mimetype) {
1571
+        return $this->searchCommon('searchByMime', array($mimetype));
1572
+    }
1573
+
1574
+    /**
1575
+     * search for files by tag
1576
+     *
1577
+     * @param string|int $tag name or tag id
1578
+     * @param string $userId owner of the tags
1579
+     * @return FileInfo[]
1580
+     */
1581
+    public function searchByTag($tag, $userId) {
1582
+        return $this->searchCommon('searchByTag', array($tag, $userId));
1583
+    }
1584
+
1585
+    /**
1586
+     * @param string $method cache method
1587
+     * @param array $args
1588
+     * @return FileInfo[]
1589
+     */
1590
+    private function searchCommon($method, $args) {
1591
+        $files = array();
1592
+        $rootLength = strlen($this->fakeRoot);
1593
+
1594
+        $mount = $this->getMount('');
1595
+        $mountPoint = $mount->getMountPoint();
1596
+        $storage = $mount->getStorage();
1597
+        if ($storage) {
1598
+            $cache = $storage->getCache('');
1599
+
1600
+            $results = call_user_func_array(array($cache, $method), $args);
1601
+            foreach ($results as $result) {
1602
+                if (substr($mountPoint . $result['path'], 0, $rootLength + 1) === $this->fakeRoot . '/') {
1603
+                    $internalPath = $result['path'];
1604
+                    $path = $mountPoint . $result['path'];
1605
+                    $result['path'] = substr($mountPoint . $result['path'], $rootLength);
1606
+                    $owner = \OC::$server->getUserManager()->get($storage->getOwner($internalPath));
1607
+                    $files[] = new FileInfo($path, $storage, $internalPath, $result, $mount, $owner);
1608
+                }
1609
+            }
1610
+
1611
+            $mounts = Filesystem::getMountManager()->findIn($this->fakeRoot);
1612
+            foreach ($mounts as $mount) {
1613
+                $mountPoint = $mount->getMountPoint();
1614
+                $storage = $mount->getStorage();
1615
+                if ($storage) {
1616
+                    $cache = $storage->getCache('');
1617
+
1618
+                    $relativeMountPoint = substr($mountPoint, $rootLength);
1619
+                    $results = call_user_func_array(array($cache, $method), $args);
1620
+                    if ($results) {
1621
+                        foreach ($results as $result) {
1622
+                            $internalPath = $result['path'];
1623
+                            $result['path'] = rtrim($relativeMountPoint . $result['path'], '/');
1624
+                            $path = rtrim($mountPoint . $internalPath, '/');
1625
+                            $owner = \OC::$server->getUserManager()->get($storage->getOwner($internalPath));
1626
+                            $files[] = new FileInfo($path, $storage, $internalPath, $result, $mount, $owner);
1627
+                        }
1628
+                    }
1629
+                }
1630
+            }
1631
+        }
1632
+        return $files;
1633
+    }
1634
+
1635
+    /**
1636
+     * Get the owner for a file or folder
1637
+     *
1638
+     * @param string $path
1639
+     * @return string the user id of the owner
1640
+     * @throws NotFoundException
1641
+     */
1642
+    public function getOwner($path) {
1643
+        $info = $this->getFileInfo($path);
1644
+        if (!$info) {
1645
+            throw new NotFoundException($path . ' not found while trying to get owner');
1646
+        }
1647
+        return $info->getOwner()->getUID();
1648
+    }
1649
+
1650
+    /**
1651
+     * get the ETag for a file or folder
1652
+     *
1653
+     * @param string $path
1654
+     * @return string
1655
+     */
1656
+    public function getETag($path) {
1657
+        /**
1658
+         * @var Storage\Storage $storage
1659
+         * @var string $internalPath
1660
+         */
1661
+        list($storage, $internalPath) = $this->resolvePath($path);
1662
+        if ($storage) {
1663
+            return $storage->getETag($internalPath);
1664
+        } else {
1665
+            return null;
1666
+        }
1667
+    }
1668
+
1669
+    /**
1670
+     * Get the path of a file by id, relative to the view
1671
+     *
1672
+     * Note that the resulting path is not guarantied to be unique for the id, multiple paths can point to the same file
1673
+     *
1674
+     * @param int $id
1675
+     * @throws NotFoundException
1676
+     * @return string
1677
+     */
1678
+    public function getPath($id) {
1679
+        $id = (int)$id;
1680
+        $manager = Filesystem::getMountManager();
1681
+        $mounts = $manager->findIn($this->fakeRoot);
1682
+        $mounts[] = $manager->find($this->fakeRoot);
1683
+        // reverse the array so we start with the storage this view is in
1684
+        // which is the most likely to contain the file we're looking for
1685
+        $mounts = array_reverse($mounts);
1686
+        foreach ($mounts as $mount) {
1687
+            /**
1688
+             * @var \OC\Files\Mount\MountPoint $mount
1689
+             */
1690
+            if ($mount->getStorage()) {
1691
+                $cache = $mount->getStorage()->getCache();
1692
+                $internalPath = $cache->getPathById($id);
1693
+                if (is_string($internalPath)) {
1694
+                    $fullPath = $mount->getMountPoint() . $internalPath;
1695
+                    if (!is_null($path = $this->getRelativePath($fullPath))) {
1696
+                        return $path;
1697
+                    }
1698
+                }
1699
+            }
1700
+        }
1701
+        throw new NotFoundException(sprintf('File with id "%s" has not been found.', $id));
1702
+    }
1703
+
1704
+    /**
1705
+     * @param string $path
1706
+     * @throws InvalidPathException
1707
+     */
1708
+    private function assertPathLength($path) {
1709
+        $maxLen = min(PHP_MAXPATHLEN, 4000);
1710
+        // Check for the string length - performed using isset() instead of strlen()
1711
+        // because isset() is about 5x-40x faster.
1712
+        if (isset($path[$maxLen])) {
1713
+            $pathLen = strlen($path);
1714
+            throw new \OCP\Files\InvalidPathException("Path length($pathLen) exceeds max path length($maxLen): $path");
1715
+        }
1716
+    }
1717
+
1718
+    /**
1719
+     * check if it is allowed to move a mount point to a given target.
1720
+     * It is not allowed to move a mount point into a different mount point or
1721
+     * into an already shared folder
1722
+     *
1723
+     * @param string $target path
1724
+     * @return boolean
1725
+     */
1726
+    private function isTargetAllowed($target) {
1727
+
1728
+        list($targetStorage, $targetInternalPath) = \OC\Files\Filesystem::resolvePath($target);
1729
+        if (!$targetStorage->instanceOfStorage('\OCP\Files\IHomeStorage')) {
1730
+            \OCP\Util::writeLog('files',
1731
+                'It is not allowed to move one mount point into another one',
1732
+                \OCP\Util::DEBUG);
1733
+            return false;
1734
+        }
1735
+
1736
+        // note: cannot use the view because the target is already locked
1737
+        $fileId = (int)$targetStorage->getCache()->getId($targetInternalPath);
1738
+        if ($fileId === -1) {
1739
+            // target might not exist, need to check parent instead
1740
+            $fileId = (int)$targetStorage->getCache()->getId(dirname($targetInternalPath));
1741
+        }
1742
+
1743
+        // check if any of the parents were shared by the current owner (include collections)
1744
+        $shares = \OCP\Share::getItemShared(
1745
+            'folder',
1746
+            $fileId,
1747
+            \OCP\Share::FORMAT_NONE,
1748
+            null,
1749
+            true
1750
+        );
1751
+
1752
+        if (count($shares) > 0) {
1753
+            \OCP\Util::writeLog('files',
1754
+                'It is not allowed to move one mount point into a shared folder',
1755
+                \OCP\Util::DEBUG);
1756
+            return false;
1757
+        }
1758
+
1759
+        return true;
1760
+    }
1761
+
1762
+    /**
1763
+     * Get a fileinfo object for files that are ignored in the cache (part files)
1764
+     *
1765
+     * @param string $path
1766
+     * @return \OCP\Files\FileInfo
1767
+     */
1768
+    private function getPartFileInfo($path) {
1769
+        $mount = $this->getMount($path);
1770
+        $storage = $mount->getStorage();
1771
+        $internalPath = $mount->getInternalPath($this->getAbsolutePath($path));
1772
+        $owner = \OC::$server->getUserManager()->get($storage->getOwner($internalPath));
1773
+        return new FileInfo(
1774
+            $this->getAbsolutePath($path),
1775
+            $storage,
1776
+            $internalPath,
1777
+            [
1778
+                'fileid' => null,
1779
+                'mimetype' => $storage->getMimeType($internalPath),
1780
+                'name' => basename($path),
1781
+                'etag' => null,
1782
+                'size' => $storage->filesize($internalPath),
1783
+                'mtime' => $storage->filemtime($internalPath),
1784
+                'encrypted' => false,
1785
+                'permissions' => \OCP\Constants::PERMISSION_ALL
1786
+            ],
1787
+            $mount,
1788
+            $owner
1789
+        );
1790
+    }
1791
+
1792
+    /**
1793
+     * @param string $path
1794
+     * @param string $fileName
1795
+     * @throws InvalidPathException
1796
+     */
1797
+    public function verifyPath($path, $fileName) {
1798
+        try {
1799
+            /** @type \OCP\Files\Storage $storage */
1800
+            list($storage, $internalPath) = $this->resolvePath($path);
1801
+            $storage->verifyPath($internalPath, $fileName);
1802
+        } catch (ReservedWordException $ex) {
1803
+            $l = \OC::$server->getL10N('lib');
1804
+            throw new InvalidPathException($l->t('File name is a reserved word'));
1805
+        } catch (InvalidCharacterInPathException $ex) {
1806
+            $l = \OC::$server->getL10N('lib');
1807
+            throw new InvalidPathException($l->t('File name contains at least one invalid character'));
1808
+        } catch (FileNameTooLongException $ex) {
1809
+            $l = \OC::$server->getL10N('lib');
1810
+            throw new InvalidPathException($l->t('File name is too long'));
1811
+        } catch (InvalidDirectoryException $ex) {
1812
+            $l = \OC::$server->getL10N('lib');
1813
+            throw new InvalidPathException($l->t('Dot files are not allowed'));
1814
+        } catch (EmptyFileNameException $ex) {
1815
+            $l = \OC::$server->getL10N('lib');
1816
+            throw new InvalidPathException($l->t('Empty filename is not allowed'));
1817
+        }
1818
+    }
1819
+
1820
+    /**
1821
+     * get all parent folders of $path
1822
+     *
1823
+     * @param string $path
1824
+     * @return string[]
1825
+     */
1826
+    private function getParents($path) {
1827
+        $path = trim($path, '/');
1828
+        if (!$path) {
1829
+            return [];
1830
+        }
1831
+
1832
+        $parts = explode('/', $path);
1833
+
1834
+        // remove the single file
1835
+        array_pop($parts);
1836
+        $result = array('/');
1837
+        $resultPath = '';
1838
+        foreach ($parts as $part) {
1839
+            if ($part) {
1840
+                $resultPath .= '/' . $part;
1841
+                $result[] = $resultPath;
1842
+            }
1843
+        }
1844
+        return $result;
1845
+    }
1846
+
1847
+    /**
1848
+     * Returns the mount point for which to lock
1849
+     *
1850
+     * @param string $absolutePath absolute path
1851
+     * @param bool $useParentMount true to return parent mount instead of whatever
1852
+     * is mounted directly on the given path, false otherwise
1853
+     * @return \OC\Files\Mount\MountPoint mount point for which to apply locks
1854
+     */
1855
+    private function getMountForLock($absolutePath, $useParentMount = false) {
1856
+        $results = [];
1857
+        $mount = Filesystem::getMountManager()->find($absolutePath);
1858
+        if (!$mount) {
1859
+            return $results;
1860
+        }
1861
+
1862
+        if ($useParentMount) {
1863
+            // find out if something is mounted directly on the path
1864
+            $internalPath = $mount->getInternalPath($absolutePath);
1865
+            if ($internalPath === '') {
1866
+                // resolve the parent mount instead
1867
+                $mount = Filesystem::getMountManager()->find(dirname($absolutePath));
1868
+            }
1869
+        }
1870
+
1871
+        return $mount;
1872
+    }
1873
+
1874
+    /**
1875
+     * Lock the given path
1876
+     *
1877
+     * @param string $path the path of the file to lock, relative to the view
1878
+     * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
1879
+     * @param bool $lockMountPoint true to lock the mount point, false to lock the attached mount/storage
1880
+     *
1881
+     * @return bool False if the path is excluded from locking, true otherwise
1882
+     * @throws \OCP\Lock\LockedException if the path is already locked
1883
+     */
1884
+    private function lockPath($path, $type, $lockMountPoint = false) {
1885
+        $absolutePath = $this->getAbsolutePath($path);
1886
+        $absolutePath = Filesystem::normalizePath($absolutePath);
1887
+        if (!$this->shouldLockFile($absolutePath)) {
1888
+            return false;
1889
+        }
1890
+
1891
+        $mount = $this->getMountForLock($absolutePath, $lockMountPoint);
1892
+        if ($mount) {
1893
+            try {
1894
+                $storage = $mount->getStorage();
1895
+                if ($storage->instanceOfStorage('\OCP\Files\Storage\ILockingStorage')) {
1896
+                    $storage->acquireLock(
1897
+                        $mount->getInternalPath($absolutePath),
1898
+                        $type,
1899
+                        $this->lockingProvider
1900
+                    );
1901
+                }
1902
+            } catch (\OCP\Lock\LockedException $e) {
1903
+                // rethrow with the a human-readable path
1904
+                throw new \OCP\Lock\LockedException(
1905
+                    $this->getPathRelativeToFiles($absolutePath),
1906
+                    $e
1907
+                );
1908
+            }
1909
+        }
1910
+
1911
+        return true;
1912
+    }
1913
+
1914
+    /**
1915
+     * Change the lock type
1916
+     *
1917
+     * @param string $path the path of the file to lock, relative to the view
1918
+     * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
1919
+     * @param bool $lockMountPoint true to lock the mount point, false to lock the attached mount/storage
1920
+     *
1921
+     * @return bool False if the path is excluded from locking, true otherwise
1922
+     * @throws \OCP\Lock\LockedException if the path is already locked
1923
+     */
1924
+    public function changeLock($path, $type, $lockMountPoint = false) {
1925
+        $path = Filesystem::normalizePath($path);
1926
+        $absolutePath = $this->getAbsolutePath($path);
1927
+        $absolutePath = Filesystem::normalizePath($absolutePath);
1928
+        if (!$this->shouldLockFile($absolutePath)) {
1929
+            return false;
1930
+        }
1931
+
1932
+        $mount = $this->getMountForLock($absolutePath, $lockMountPoint);
1933
+        if ($mount) {
1934
+            try {
1935
+                $storage = $mount->getStorage();
1936
+                if ($storage->instanceOfStorage('\OCP\Files\Storage\ILockingStorage')) {
1937
+                    $storage->changeLock(
1938
+                        $mount->getInternalPath($absolutePath),
1939
+                        $type,
1940
+                        $this->lockingProvider
1941
+                    );
1942
+                }
1943
+            } catch (\OCP\Lock\LockedException $e) {
1944
+                // rethrow with the a human-readable path
1945
+                throw new \OCP\Lock\LockedException(
1946
+                    $this->getPathRelativeToFiles($absolutePath),
1947
+                    $e
1948
+                );
1949
+            }
1950
+        }
1951
+
1952
+        return true;
1953
+    }
1954
+
1955
+    /**
1956
+     * Unlock the given path
1957
+     *
1958
+     * @param string $path the path of the file to unlock, relative to the view
1959
+     * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
1960
+     * @param bool $lockMountPoint true to lock the mount point, false to lock the attached mount/storage
1961
+     *
1962
+     * @return bool False if the path is excluded from locking, true otherwise
1963
+     */
1964
+    private function unlockPath($path, $type, $lockMountPoint = false) {
1965
+        $absolutePath = $this->getAbsolutePath($path);
1966
+        $absolutePath = Filesystem::normalizePath($absolutePath);
1967
+        if (!$this->shouldLockFile($absolutePath)) {
1968
+            return false;
1969
+        }
1970
+
1971
+        $mount = $this->getMountForLock($absolutePath, $lockMountPoint);
1972
+        if ($mount) {
1973
+            $storage = $mount->getStorage();
1974
+            if ($storage && $storage->instanceOfStorage('\OCP\Files\Storage\ILockingStorage')) {
1975
+                $storage->releaseLock(
1976
+                    $mount->getInternalPath($absolutePath),
1977
+                    $type,
1978
+                    $this->lockingProvider
1979
+                );
1980
+            }
1981
+        }
1982
+
1983
+        return true;
1984
+    }
1985
+
1986
+    /**
1987
+     * Lock a path and all its parents up to the root of the view
1988
+     *
1989
+     * @param string $path the path of the file to lock relative to the view
1990
+     * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
1991
+     * @param bool $lockMountPoint true to lock the mount point, false to lock the attached mount/storage
1992
+     *
1993
+     * @return bool False if the path is excluded from locking, true otherwise
1994
+     */
1995
+    public function lockFile($path, $type, $lockMountPoint = false) {
1996
+        $absolutePath = $this->getAbsolutePath($path);
1997
+        $absolutePath = Filesystem::normalizePath($absolutePath);
1998
+        if (!$this->shouldLockFile($absolutePath)) {
1999
+            return false;
2000
+        }
2001
+
2002
+        $this->lockPath($path, $type, $lockMountPoint);
2003
+
2004
+        $parents = $this->getParents($path);
2005
+        foreach ($parents as $parent) {
2006
+            $this->lockPath($parent, ILockingProvider::LOCK_SHARED);
2007
+        }
2008
+
2009
+        return true;
2010
+    }
2011
+
2012
+    /**
2013
+     * Unlock a path and all its parents up to the root of the view
2014
+     *
2015
+     * @param string $path the path of the file to lock relative to the view
2016
+     * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
2017
+     * @param bool $lockMountPoint true to lock the mount point, false to lock the attached mount/storage
2018
+     *
2019
+     * @return bool False if the path is excluded from locking, true otherwise
2020
+     */
2021
+    public function unlockFile($path, $type, $lockMountPoint = false) {
2022
+        $absolutePath = $this->getAbsolutePath($path);
2023
+        $absolutePath = Filesystem::normalizePath($absolutePath);
2024
+        if (!$this->shouldLockFile($absolutePath)) {
2025
+            return false;
2026
+        }
2027
+
2028
+        $this->unlockPath($path, $type, $lockMountPoint);
2029
+
2030
+        $parents = $this->getParents($path);
2031
+        foreach ($parents as $parent) {
2032
+            $this->unlockPath($parent, ILockingProvider::LOCK_SHARED);
2033
+        }
2034
+
2035
+        return true;
2036
+    }
2037
+
2038
+    /**
2039
+     * Only lock files in data/user/files/
2040
+     *
2041
+     * @param string $path Absolute path to the file/folder we try to (un)lock
2042
+     * @return bool
2043
+     */
2044
+    protected function shouldLockFile($path) {
2045
+        $path = Filesystem::normalizePath($path);
2046
+
2047
+        $pathSegments = explode('/', $path);
2048
+        if (isset($pathSegments[2])) {
2049
+            // E.g.: /username/files/path-to-file
2050
+            return ($pathSegments[2] === 'files') && (count($pathSegments) > 3);
2051
+        }
2052
+
2053
+        return true;
2054
+    }
2055
+
2056
+    /**
2057
+     * Shortens the given absolute path to be relative to
2058
+     * "$user/files".
2059
+     *
2060
+     * @param string $absolutePath absolute path which is under "files"
2061
+     *
2062
+     * @return string path relative to "files" with trimmed slashes or null
2063
+     * if the path was NOT relative to files
2064
+     *
2065
+     * @throws \InvalidArgumentException if the given path was not under "files"
2066
+     * @since 8.1.0
2067
+     */
2068
+    public function getPathRelativeToFiles($absolutePath) {
2069
+        $path = Filesystem::normalizePath($absolutePath);
2070
+        $parts = explode('/', trim($path, '/'), 3);
2071
+        // "$user", "files", "path/to/dir"
2072
+        if (!isset($parts[1]) || $parts[1] !== 'files') {
2073
+            $this->logger->error(
2074
+                '$absolutePath must be relative to "files", value is "%s"',
2075
+                [
2076
+                    $absolutePath
2077
+                ]
2078
+            );
2079
+            throw new \InvalidArgumentException('$absolutePath must be relative to "files"');
2080
+        }
2081
+        if (isset($parts[2])) {
2082
+            return $parts[2];
2083
+        }
2084
+        return '';
2085
+    }
2086
+
2087
+    /**
2088
+     * @param string $filename
2089
+     * @return array
2090
+     * @throws \OC\User\NoUserException
2091
+     * @throws NotFoundException
2092
+     */
2093
+    public function getUidAndFilename($filename) {
2094
+        $info = $this->getFileInfo($filename);
2095
+        if (!$info instanceof \OCP\Files\FileInfo) {
2096
+            throw new NotFoundException($this->getAbsolutePath($filename) . ' not found');
2097
+        }
2098
+        $uid = $info->getOwner()->getUID();
2099
+        if ($uid != \OCP\User::getUser()) {
2100
+            Filesystem::initMountPoints($uid);
2101
+            $ownerView = new View('/' . $uid . '/files');
2102
+            try {
2103
+                $filename = $ownerView->getPath($info['fileid']);
2104
+            } catch (NotFoundException $e) {
2105
+                throw new NotFoundException('File with id ' . $info['fileid'] . ' not found for user ' . $uid);
2106
+            }
2107
+        }
2108
+        return [$uid, $filename];
2109
+    }
2110
+
2111
+    /**
2112
+     * Creates parent non-existing folders
2113
+     *
2114
+     * @param string $filePath
2115
+     * @return bool
2116
+     */
2117
+    private function createParentDirectories($filePath) {
2118
+        $directoryParts = explode('/', $filePath);
2119
+        $directoryParts = array_filter($directoryParts);
2120
+        foreach ($directoryParts as $key => $part) {
2121
+            $currentPathElements = array_slice($directoryParts, 0, $key);
2122
+            $currentPath = '/' . implode('/', $currentPathElements);
2123
+            if ($this->is_file($currentPath)) {
2124
+                return false;
2125
+            }
2126
+            if (!$this->file_exists($currentPath)) {
2127
+                $this->mkdir($currentPath);
2128
+            }
2129
+        }
2130
+
2131
+        return true;
2132
+    }
2133 2133
 }
Please login to merge, or discard this patch.
apps/files_sharing/lib/Helper.php 3 patches
Doc Comments   +1 added lines patch added patch discarded remove patch
@@ -303,6 +303,7 @@
 block discarded – undo
303 303
 	 * get default share folder
304 304
 	 *
305 305
 	 * @param \OC\Files\View
306
+	 * @param View $view
306 307
 	 * @return string
307 308
 	 */
308 309
 	public static function getShareFolder($view = null) {
Please login to merge, or discard this patch.
Indentation   +237 added lines, -237 removed lines patch added patch discarded remove patch
@@ -36,242 +36,242 @@
 block discarded – undo
36 36
 
37 37
 class Helper {
38 38
 
39
-	public static function registerHooks() {
40
-		\OCP\Util::connectHook('OC_Filesystem', 'post_rename', '\OCA\Files_Sharing\Updater', 'renameHook');
41
-		\OCP\Util::connectHook('OC_Filesystem', 'post_delete', '\OCA\Files_Sharing\Hooks', 'unshareChildren');
42
-
43
-		\OCP\Util::connectHook('OC_User', 'post_deleteUser', '\OCA\Files_Sharing\Hooks', 'deleteUser');
44
-	}
45
-
46
-	/**
47
-	 * Sets up the filesystem and user for public sharing
48
-	 * @param string $token string share token
49
-	 * @param string $relativePath optional path relative to the share
50
-	 * @param string $password optional password
51
-	 * @return array
52
-	 */
53
-	public static function setupFromToken($token, $relativePath = null, $password = null) {
54
-		\OC_User::setIncognitoMode(true);
55
-
56
-		$shareManager = \OC::$server->getShareManager();
57
-
58
-		try {
59
-			$share = $shareManager->getShareByToken($token);
60
-		} catch (ShareNotFound $e) {
61
-			\OC_Response::setStatus(404);
62
-			\OCP\Util::writeLog('core-preview', 'Passed token parameter is not valid', \OCP\Util::DEBUG);
63
-			exit;
64
-		}
65
-
66
-		\OCP\JSON::checkUserExists($share->getShareOwner());
67
-		\OC_Util::tearDownFS();
68
-		\OC_Util::setupFS($share->getShareOwner());
69
-
70
-
71
-		try {
72
-			$path = Filesystem::getPath($share->getNodeId());
73
-		} catch (NotFoundException $e) {
74
-			\OCP\Util::writeLog('share', 'could not resolve linkItem', \OCP\Util::DEBUG);
75
-			\OC_Response::setStatus(404);
76
-			\OCP\JSON::error(array('success' => false));
77
-			exit();
78
-		}
79
-
80
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK && $share->getPassword() !== null) {
81
-			if (!self::authenticate($share, $password)) {
82
-				\OC_Response::setStatus(403);
83
-				\OCP\JSON::error(array('success' => false));
84
-				exit();
85
-			}
86
-		}
87
-
88
-		$basePath = $path;
89
-
90
-		if ($relativePath !== null && Filesystem::isReadable($basePath . $relativePath)) {
91
-			$path .= Filesystem::normalizePath($relativePath);
92
-		}
93
-
94
-		return array(
95
-			'share' => $share,
96
-			'basePath' => $basePath,
97
-			'realPath' => $path
98
-		);
99
-	}
100
-
101
-	/**
102
-	 * Authenticate link item with the given password
103
-	 * or with the session if no password was given.
104
-	 * @param \OCP\Share\IShare $share
105
-	 * @param string $password optional password
106
-	 *
107
-	 * @return boolean true if authorized, false otherwise
108
-	 */
109
-	public static function authenticate($share, $password = null) {
110
-		$shareManager = \OC::$server->getShareManager();
111
-
112
-		if ($password !== null) {
113
-			if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
114
-				if ($shareManager->checkPassword($share, $password)) {
115
-					\OC::$server->getSession()->set('public_link_authenticated', (string)$share->getId());
116
-					return true;
117
-				}
118
-			}
119
-		} else {
120
-			// not authenticated ?
121
-			if (\OC::$server->getSession()->exists('public_link_authenticated')
122
-				&& \OC::$server->getSession()->get('public_link_authenticated') !== (string)$share->getId()) {
123
-				return true;
124
-			}
125
-		}
126
-		return false;
127
-	}
128
-
129
-	public static function getSharesFromItem($target) {
130
-		$result = array();
131
-		$owner = Filesystem::getOwner($target);
132
-		Filesystem::initMountPoints($owner);
133
-		$info = Filesystem::getFileInfo($target);
134
-		$ownerView = new View('/'.$owner.'/files');
135
-		if ( $owner != User::getUser() ) {
136
-			$path = $ownerView->getPath($info['fileid']);
137
-		} else {
138
-			$path = $target;
139
-		}
140
-
141
-
142
-		$ids = array();
143
-		while ($path !== dirname($path)) {
144
-			$info = $ownerView->getFileInfo($path);
145
-			if ($info instanceof \OC\Files\FileInfo) {
146
-				$ids[] = $info['fileid'];
147
-			} else {
148
-				\OCP\Util::writeLog('sharing', 'No fileinfo available for: ' . $path, \OCP\Util::WARN);
149
-			}
150
-			$path = dirname($path);
151
-		}
152
-
153
-		if (!empty($ids)) {
154
-
155
-			$idList = array_chunk($ids, 99, true);
156
-
157
-			foreach ($idList as $subList) {
158
-				$statement = "SELECT `share_with`, `share_type`, `file_target` FROM `*PREFIX*share` WHERE `file_source` IN (" . implode(',', $subList) . ") AND `share_type` IN (0, 1, 2)";
159
-				$query = \OCP\DB::prepare($statement);
160
-				$r = $query->execute();
161
-				$result = array_merge($result, $r->fetchAll());
162
-			}
163
-		}
164
-
165
-		return $result;
166
-	}
167
-
168
-	/**
169
-	 * get the UID of the owner of the file and the path to the file relative to
170
-	 * owners files folder
171
-	 *
172
-	 * @param $filename
173
-	 * @return array
174
-	 * @throws \OC\User\NoUserException
175
-	 */
176
-	public static function getUidAndFilename($filename) {
177
-		$uid = Filesystem::getOwner($filename);
178
-		$userManager = \OC::$server->getUserManager();
179
-		// if the user with the UID doesn't exists, e.g. because the UID points
180
-		// to a remote user with a federated cloud ID we use the current logged-in
181
-		// user. We need a valid local user to create the share
182
-		if (!$userManager->userExists($uid)) {
183
-			$uid = User::getUser();
184
-		}
185
-		Filesystem::initMountPoints($uid);
186
-		if ( $uid != User::getUser() ) {
187
-			$info = Filesystem::getFileInfo($filename);
188
-			$ownerView = new View('/'.$uid.'/files');
189
-			try {
190
-				$filename = $ownerView->getPath($info['fileid']);
191
-			} catch (NotFoundException $e) {
192
-				$filename = null;
193
-			}
194
-		}
195
-		return [$uid, $filename];
196
-	}
197
-
198
-	/**
199
-	 * Format a path to be relative to the /user/files/ directory
200
-	 * @param string $path the absolute path
201
-	 * @return string e.g. turns '/admin/files/test.txt' into 'test.txt'
202
-	 */
203
-	public static function stripUserFilesPath($path) {
204
-		$trimmed = ltrim($path, '/');
205
-		$split = explode('/', $trimmed);
206
-
207
-		// it is not a file relative to data/user/files
208
-		if (count($split) < 3 || $split[1] !== 'files') {
209
-			return false;
210
-		}
211
-
212
-		$sliced = array_slice($split, 2);
213
-		$relPath = implode('/', $sliced);
214
-
215
-		return $relPath;
216
-	}
217
-
218
-	/**
219
-	 * check if file name already exists and generate unique target
220
-	 *
221
-	 * @param string $path
222
-	 * @param array $excludeList
223
-	 * @param View $view
224
-	 * @return string $path
225
-	 */
226
-	public static function generateUniqueTarget($path, $excludeList, $view) {
227
-		$pathinfo = pathinfo($path);
228
-		$ext = (isset($pathinfo['extension'])) ? '.'.$pathinfo['extension'] : '';
229
-		$name = $pathinfo['filename'];
230
-		$dir = $pathinfo['dirname'];
231
-		$i = 2;
232
-		while ($view->file_exists($path) || in_array($path, $excludeList)) {
233
-			$path = Filesystem::normalizePath($dir . '/' . $name . ' ('.$i.')' . $ext);
234
-			$i++;
235
-		}
236
-
237
-		return $path;
238
-	}
239
-
240
-	/**
241
-	 * get default share folder
242
-	 *
243
-	 * @param \OC\Files\View
244
-	 * @return string
245
-	 */
246
-	public static function getShareFolder($view = null) {
247
-		if ($view === null) {
248
-			$view = Filesystem::getView();
249
-		}
250
-		$shareFolder = \OC::$server->getConfig()->getSystemValue('share_folder', '/');
251
-		$shareFolder = Filesystem::normalizePath($shareFolder);
252
-
253
-		if (!$view->file_exists($shareFolder)) {
254
-			$dir = '';
255
-			$subdirs = explode('/', $shareFolder);
256
-			foreach ($subdirs as $subdir) {
257
-				$dir = $dir . '/' . $subdir;
258
-				if (!$view->is_dir($dir)) {
259
-					$view->mkdir($dir);
260
-				}
261
-			}
262
-		}
263
-
264
-		return $shareFolder;
265
-
266
-	}
267
-
268
-	/**
269
-	 * set default share folder
270
-	 *
271
-	 * @param string $shareFolder
272
-	 */
273
-	public static function setShareFolder($shareFolder) {
274
-		\OC::$server->getConfig()->setSystemValue('share_folder', $shareFolder);
275
-	}
39
+    public static function registerHooks() {
40
+        \OCP\Util::connectHook('OC_Filesystem', 'post_rename', '\OCA\Files_Sharing\Updater', 'renameHook');
41
+        \OCP\Util::connectHook('OC_Filesystem', 'post_delete', '\OCA\Files_Sharing\Hooks', 'unshareChildren');
42
+
43
+        \OCP\Util::connectHook('OC_User', 'post_deleteUser', '\OCA\Files_Sharing\Hooks', 'deleteUser');
44
+    }
45
+
46
+    /**
47
+     * Sets up the filesystem and user for public sharing
48
+     * @param string $token string share token
49
+     * @param string $relativePath optional path relative to the share
50
+     * @param string $password optional password
51
+     * @return array
52
+     */
53
+    public static function setupFromToken($token, $relativePath = null, $password = null) {
54
+        \OC_User::setIncognitoMode(true);
55
+
56
+        $shareManager = \OC::$server->getShareManager();
57
+
58
+        try {
59
+            $share = $shareManager->getShareByToken($token);
60
+        } catch (ShareNotFound $e) {
61
+            \OC_Response::setStatus(404);
62
+            \OCP\Util::writeLog('core-preview', 'Passed token parameter is not valid', \OCP\Util::DEBUG);
63
+            exit;
64
+        }
65
+
66
+        \OCP\JSON::checkUserExists($share->getShareOwner());
67
+        \OC_Util::tearDownFS();
68
+        \OC_Util::setupFS($share->getShareOwner());
69
+
70
+
71
+        try {
72
+            $path = Filesystem::getPath($share->getNodeId());
73
+        } catch (NotFoundException $e) {
74
+            \OCP\Util::writeLog('share', 'could not resolve linkItem', \OCP\Util::DEBUG);
75
+            \OC_Response::setStatus(404);
76
+            \OCP\JSON::error(array('success' => false));
77
+            exit();
78
+        }
79
+
80
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK && $share->getPassword() !== null) {
81
+            if (!self::authenticate($share, $password)) {
82
+                \OC_Response::setStatus(403);
83
+                \OCP\JSON::error(array('success' => false));
84
+                exit();
85
+            }
86
+        }
87
+
88
+        $basePath = $path;
89
+
90
+        if ($relativePath !== null && Filesystem::isReadable($basePath . $relativePath)) {
91
+            $path .= Filesystem::normalizePath($relativePath);
92
+        }
93
+
94
+        return array(
95
+            'share' => $share,
96
+            'basePath' => $basePath,
97
+            'realPath' => $path
98
+        );
99
+    }
100
+
101
+    /**
102
+     * Authenticate link item with the given password
103
+     * or with the session if no password was given.
104
+     * @param \OCP\Share\IShare $share
105
+     * @param string $password optional password
106
+     *
107
+     * @return boolean true if authorized, false otherwise
108
+     */
109
+    public static function authenticate($share, $password = null) {
110
+        $shareManager = \OC::$server->getShareManager();
111
+
112
+        if ($password !== null) {
113
+            if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
114
+                if ($shareManager->checkPassword($share, $password)) {
115
+                    \OC::$server->getSession()->set('public_link_authenticated', (string)$share->getId());
116
+                    return true;
117
+                }
118
+            }
119
+        } else {
120
+            // not authenticated ?
121
+            if (\OC::$server->getSession()->exists('public_link_authenticated')
122
+                && \OC::$server->getSession()->get('public_link_authenticated') !== (string)$share->getId()) {
123
+                return true;
124
+            }
125
+        }
126
+        return false;
127
+    }
128
+
129
+    public static function getSharesFromItem($target) {
130
+        $result = array();
131
+        $owner = Filesystem::getOwner($target);
132
+        Filesystem::initMountPoints($owner);
133
+        $info = Filesystem::getFileInfo($target);
134
+        $ownerView = new View('/'.$owner.'/files');
135
+        if ( $owner != User::getUser() ) {
136
+            $path = $ownerView->getPath($info['fileid']);
137
+        } else {
138
+            $path = $target;
139
+        }
140
+
141
+
142
+        $ids = array();
143
+        while ($path !== dirname($path)) {
144
+            $info = $ownerView->getFileInfo($path);
145
+            if ($info instanceof \OC\Files\FileInfo) {
146
+                $ids[] = $info['fileid'];
147
+            } else {
148
+                \OCP\Util::writeLog('sharing', 'No fileinfo available for: ' . $path, \OCP\Util::WARN);
149
+            }
150
+            $path = dirname($path);
151
+        }
152
+
153
+        if (!empty($ids)) {
154
+
155
+            $idList = array_chunk($ids, 99, true);
156
+
157
+            foreach ($idList as $subList) {
158
+                $statement = "SELECT `share_with`, `share_type`, `file_target` FROM `*PREFIX*share` WHERE `file_source` IN (" . implode(',', $subList) . ") AND `share_type` IN (0, 1, 2)";
159
+                $query = \OCP\DB::prepare($statement);
160
+                $r = $query->execute();
161
+                $result = array_merge($result, $r->fetchAll());
162
+            }
163
+        }
164
+
165
+        return $result;
166
+    }
167
+
168
+    /**
169
+     * get the UID of the owner of the file and the path to the file relative to
170
+     * owners files folder
171
+     *
172
+     * @param $filename
173
+     * @return array
174
+     * @throws \OC\User\NoUserException
175
+     */
176
+    public static function getUidAndFilename($filename) {
177
+        $uid = Filesystem::getOwner($filename);
178
+        $userManager = \OC::$server->getUserManager();
179
+        // if the user with the UID doesn't exists, e.g. because the UID points
180
+        // to a remote user with a federated cloud ID we use the current logged-in
181
+        // user. We need a valid local user to create the share
182
+        if (!$userManager->userExists($uid)) {
183
+            $uid = User::getUser();
184
+        }
185
+        Filesystem::initMountPoints($uid);
186
+        if ( $uid != User::getUser() ) {
187
+            $info = Filesystem::getFileInfo($filename);
188
+            $ownerView = new View('/'.$uid.'/files');
189
+            try {
190
+                $filename = $ownerView->getPath($info['fileid']);
191
+            } catch (NotFoundException $e) {
192
+                $filename = null;
193
+            }
194
+        }
195
+        return [$uid, $filename];
196
+    }
197
+
198
+    /**
199
+     * Format a path to be relative to the /user/files/ directory
200
+     * @param string $path the absolute path
201
+     * @return string e.g. turns '/admin/files/test.txt' into 'test.txt'
202
+     */
203
+    public static function stripUserFilesPath($path) {
204
+        $trimmed = ltrim($path, '/');
205
+        $split = explode('/', $trimmed);
206
+
207
+        // it is not a file relative to data/user/files
208
+        if (count($split) < 3 || $split[1] !== 'files') {
209
+            return false;
210
+        }
211
+
212
+        $sliced = array_slice($split, 2);
213
+        $relPath = implode('/', $sliced);
214
+
215
+        return $relPath;
216
+    }
217
+
218
+    /**
219
+     * check if file name already exists and generate unique target
220
+     *
221
+     * @param string $path
222
+     * @param array $excludeList
223
+     * @param View $view
224
+     * @return string $path
225
+     */
226
+    public static function generateUniqueTarget($path, $excludeList, $view) {
227
+        $pathinfo = pathinfo($path);
228
+        $ext = (isset($pathinfo['extension'])) ? '.'.$pathinfo['extension'] : '';
229
+        $name = $pathinfo['filename'];
230
+        $dir = $pathinfo['dirname'];
231
+        $i = 2;
232
+        while ($view->file_exists($path) || in_array($path, $excludeList)) {
233
+            $path = Filesystem::normalizePath($dir . '/' . $name . ' ('.$i.')' . $ext);
234
+            $i++;
235
+        }
236
+
237
+        return $path;
238
+    }
239
+
240
+    /**
241
+     * get default share folder
242
+     *
243
+     * @param \OC\Files\View
244
+     * @return string
245
+     */
246
+    public static function getShareFolder($view = null) {
247
+        if ($view === null) {
248
+            $view = Filesystem::getView();
249
+        }
250
+        $shareFolder = \OC::$server->getConfig()->getSystemValue('share_folder', '/');
251
+        $shareFolder = Filesystem::normalizePath($shareFolder);
252
+
253
+        if (!$view->file_exists($shareFolder)) {
254
+            $dir = '';
255
+            $subdirs = explode('/', $shareFolder);
256
+            foreach ($subdirs as $subdir) {
257
+                $dir = $dir . '/' . $subdir;
258
+                if (!$view->is_dir($dir)) {
259
+                    $view->mkdir($dir);
260
+                }
261
+            }
262
+        }
263
+
264
+        return $shareFolder;
265
+
266
+    }
267
+
268
+    /**
269
+     * set default share folder
270
+     *
271
+     * @param string $shareFolder
272
+     */
273
+    public static function setShareFolder($shareFolder) {
274
+        \OC::$server->getConfig()->setSystemValue('share_folder', $shareFolder);
275
+    }
276 276
 
277 277
 }
Please login to merge, or discard this patch.
Spacing   +9 added lines, -9 removed lines patch added patch discarded remove patch
@@ -87,7 +87,7 @@  discard block
 block discarded – undo
87 87
 
88 88
 		$basePath = $path;
89 89
 
90
-		if ($relativePath !== null && Filesystem::isReadable($basePath . $relativePath)) {
90
+		if ($relativePath !== null && Filesystem::isReadable($basePath.$relativePath)) {
91 91
 			$path .= Filesystem::normalizePath($relativePath);
92 92
 		}
93 93
 
@@ -112,14 +112,14 @@  discard block
 block discarded – undo
112 112
 		if ($password !== null) {
113 113
 			if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
114 114
 				if ($shareManager->checkPassword($share, $password)) {
115
-					\OC::$server->getSession()->set('public_link_authenticated', (string)$share->getId());
115
+					\OC::$server->getSession()->set('public_link_authenticated', (string) $share->getId());
116 116
 					return true;
117 117
 				}
118 118
 			}
119 119
 		} else {
120 120
 			// not authenticated ?
121 121
 			if (\OC::$server->getSession()->exists('public_link_authenticated')
122
-				&& \OC::$server->getSession()->get('public_link_authenticated') !== (string)$share->getId()) {
122
+				&& \OC::$server->getSession()->get('public_link_authenticated') !== (string) $share->getId()) {
123 123
 				return true;
124 124
 			}
125 125
 		}
@@ -132,7 +132,7 @@  discard block
 block discarded – undo
132 132
 		Filesystem::initMountPoints($owner);
133 133
 		$info = Filesystem::getFileInfo($target);
134 134
 		$ownerView = new View('/'.$owner.'/files');
135
-		if ( $owner != User::getUser() ) {
135
+		if ($owner != User::getUser()) {
136 136
 			$path = $ownerView->getPath($info['fileid']);
137 137
 		} else {
138 138
 			$path = $target;
@@ -145,7 +145,7 @@  discard block
 block discarded – undo
145 145
 			if ($info instanceof \OC\Files\FileInfo) {
146 146
 				$ids[] = $info['fileid'];
147 147
 			} else {
148
-				\OCP\Util::writeLog('sharing', 'No fileinfo available for: ' . $path, \OCP\Util::WARN);
148
+				\OCP\Util::writeLog('sharing', 'No fileinfo available for: '.$path, \OCP\Util::WARN);
149 149
 			}
150 150
 			$path = dirname($path);
151 151
 		}
@@ -155,7 +155,7 @@  discard block
 block discarded – undo
155 155
 			$idList = array_chunk($ids, 99, true);
156 156
 
157 157
 			foreach ($idList as $subList) {
158
-				$statement = "SELECT `share_with`, `share_type`, `file_target` FROM `*PREFIX*share` WHERE `file_source` IN (" . implode(',', $subList) . ") AND `share_type` IN (0, 1, 2)";
158
+				$statement = "SELECT `share_with`, `share_type`, `file_target` FROM `*PREFIX*share` WHERE `file_source` IN (".implode(',', $subList).") AND `share_type` IN (0, 1, 2)";
159 159
 				$query = \OCP\DB::prepare($statement);
160 160
 				$r = $query->execute();
161 161
 				$result = array_merge($result, $r->fetchAll());
@@ -183,7 +183,7 @@  discard block
 block discarded – undo
183 183
 			$uid = User::getUser();
184 184
 		}
185 185
 		Filesystem::initMountPoints($uid);
186
-		if ( $uid != User::getUser() ) {
186
+		if ($uid != User::getUser()) {
187 187
 			$info = Filesystem::getFileInfo($filename);
188 188
 			$ownerView = new View('/'.$uid.'/files');
189 189
 			try {
@@ -230,7 +230,7 @@  discard block
 block discarded – undo
230 230
 		$dir = $pathinfo['dirname'];
231 231
 		$i = 2;
232 232
 		while ($view->file_exists($path) || in_array($path, $excludeList)) {
233
-			$path = Filesystem::normalizePath($dir . '/' . $name . ' ('.$i.')' . $ext);
233
+			$path = Filesystem::normalizePath($dir.'/'.$name.' ('.$i.')'.$ext);
234 234
 			$i++;
235 235
 		}
236 236
 
@@ -254,7 +254,7 @@  discard block
 block discarded – undo
254 254
 			$dir = '';
255 255
 			$subdirs = explode('/', $shareFolder);
256 256
 			foreach ($subdirs as $subdir) {
257
-				$dir = $dir . '/' . $subdir;
257
+				$dir = $dir.'/'.$subdir;
258 258
 				if (!$view->is_dir($dir)) {
259 259
 					$view->mkdir($dir);
260 260
 				}
Please login to merge, or discard this patch.
apps/dav/lib/SystemTag/SystemTagsObjectMappingCollection.php 3 patches
Doc Comments   +3 added lines patch added patch discarded remove patch
@@ -89,6 +89,9 @@
 block discarded – undo
89 89
 		$this->user = $user;
90 90
 	}
91 91
 
92
+	/**
93
+	 * @param string $tagId
94
+	 */
92 95
 	function createFile($tagId, $data = null) {
93 96
 		try {
94 97
 			$tags = $this->tagManager->getTagsByIds([$tagId]);
Please login to merge, or discard this patch.
Indentation   +165 added lines, -165 removed lines patch added patch discarded remove patch
@@ -39,169 +39,169 @@
 block discarded – undo
39 39
  */
40 40
 class SystemTagsObjectMappingCollection implements ICollection {
41 41
 
42
-	/**
43
-	 * @var string
44
-	 */
45
-	private $objectId;
46
-
47
-	/**
48
-	 * @var string
49
-	 */
50
-	private $objectType;
51
-
52
-	/**
53
-	 * @var ISystemTagManager
54
-	 */
55
-	private $tagManager;
56
-
57
-	/**
58
-	 * @var ISystemTagObjectMapper
59
-	 */
60
-	private $tagMapper;
61
-
62
-	/**
63
-	 * User
64
-	 *
65
-	 * @var IUser
66
-	 */
67
-	private $user;
68
-
69
-
70
-	/**
71
-	 * Constructor
72
-	 *
73
-	 * @param string $objectId object id
74
-	 * @param string $objectType object type
75
-	 * @param IUser $user user
76
-	 * @param ISystemTagManager $tagManager tag manager
77
-	 * @param ISystemTagObjectMapper $tagMapper tag mapper
78
-	 */
79
-	public function __construct(
80
-		$objectId,
81
-		$objectType,
82
-		IUser $user,
83
-		ISystemTagManager $tagManager,
84
-		ISystemTagObjectMapper $tagMapper
85
-	) {
86
-		$this->tagManager = $tagManager;
87
-		$this->tagMapper = $tagMapper;
88
-		$this->objectId = $objectId;
89
-		$this->objectType = $objectType;
90
-		$this->user = $user;
91
-	}
92
-
93
-	function createFile($tagId, $data = null) {
94
-		try {
95
-			$tags = $this->tagManager->getTagsByIds([$tagId]);
96
-			$tag = current($tags);
97
-			if (!$this->tagManager->canUserSeeTag($tag, $this->user)) {
98
-				throw new PreconditionFailed('Tag with id ' . $tagId . ' does not exist, cannot assign');
99
-			}
100
-			if (!$this->tagManager->canUserAssignTag($tag, $this->user)) {
101
-				throw new Forbidden('No permission to assign tag ' . $tagId);
102
-			}
103
-
104
-			$this->tagMapper->assignTags($this->objectId, $this->objectType, $tagId);
105
-		} catch (TagNotFoundException $e) {
106
-			throw new PreconditionFailed('Tag with id ' . $tagId . ' does not exist, cannot assign');
107
-		}
108
-	}
109
-
110
-	function createDirectory($name) {
111
-		throw new Forbidden('Permission denied to create collections');
112
-	}
113
-
114
-	function getChild($tagId) {
115
-		try {
116
-			if ($this->tagMapper->haveTag([$this->objectId], $this->objectType, $tagId, true)) {
117
-				$tag = $this->tagManager->getTagsByIds([$tagId]);
118
-				$tag = current($tag);
119
-				if ($this->tagManager->canUserSeeTag($tag, $this->user)) {
120
-					return $this->makeNode($tag);
121
-				}
122
-			}
123
-			throw new NotFound('Tag with id ' . $tagId . ' not present for object ' . $this->objectId);
124
-		} catch (\InvalidArgumentException $e) {
125
-			throw new BadRequest('Invalid tag id', 0, $e);
126
-		} catch (TagNotFoundException $e) {
127
-			throw new NotFound('Tag with id ' . $tagId . ' not found', 0, $e);
128
-		}
129
-	}
130
-
131
-	function getChildren() {
132
-		$tagIds = current($this->tagMapper->getTagIdsForObjects([$this->objectId], $this->objectType));
133
-		if (empty($tagIds)) {
134
-			return [];
135
-		}
136
-		$tags = $this->tagManager->getTagsByIds($tagIds);
137
-
138
-		// filter out non-visible tags
139
-		$tags = array_filter($tags, function($tag) {
140
-			return $this->tagManager->canUserSeeTag($tag, $this->user);
141
-		});
142
-
143
-		return array_values(array_map(function($tag) {
144
-			return $this->makeNode($tag);
145
-		}, $tags));
146
-	}
147
-
148
-	function childExists($tagId) {
149
-		try {
150
-			$result = ($this->tagMapper->haveTag([$this->objectId], $this->objectType, $tagId, true));
151
-
152
-			if ($result) {
153
-				$tags = $this->tagManager->getTagsByIds([$tagId]);
154
-				$tag = current($tags);
155
-				if (!$this->tagManager->canUserSeeTag($tag, $this->user)) {
156
-					return false;
157
-				}
158
-			}
159
-
160
-			return $result;
161
-		} catch (\InvalidArgumentException $e) {
162
-			throw new BadRequest('Invalid tag id', 0, $e);
163
-		} catch (TagNotFoundException $e) {
164
-			return false;
165
-		}
166
-	}
167
-
168
-	function delete() {
169
-		throw new Forbidden('Permission denied to delete this collection');
170
-	}
171
-
172
-	function getName() {
173
-		return $this->objectId;
174
-	}
175
-
176
-	function setName($name) {
177
-		throw new Forbidden('Permission denied to rename this collection');
178
-	}
179
-
180
-	/**
181
-	 * Returns the last modification time, as a unix timestamp
182
-	 *
183
-	 * @return int
184
-	 */
185
-	function getLastModified() {
186
-		return null;
187
-	}
188
-
189
-	/**
190
-	 * Create a sabre node for the mapping of the 
191
-	 * given system tag to the collection's object
192
-	 *
193
-	 * @param ISystemTag $tag
194
-	 *
195
-	 * @return SystemTagMappingNode
196
-	 */
197
-	private function makeNode(ISystemTag $tag) {
198
-		return new SystemTagMappingNode(
199
-			$tag,
200
-			$this->objectId,
201
-			$this->objectType,
202
-			$this->user,
203
-			$this->tagManager,
204
-			$this->tagMapper
205
-		);
206
-	}
42
+    /**
43
+     * @var string
44
+     */
45
+    private $objectId;
46
+
47
+    /**
48
+     * @var string
49
+     */
50
+    private $objectType;
51
+
52
+    /**
53
+     * @var ISystemTagManager
54
+     */
55
+    private $tagManager;
56
+
57
+    /**
58
+     * @var ISystemTagObjectMapper
59
+     */
60
+    private $tagMapper;
61
+
62
+    /**
63
+     * User
64
+     *
65
+     * @var IUser
66
+     */
67
+    private $user;
68
+
69
+
70
+    /**
71
+     * Constructor
72
+     *
73
+     * @param string $objectId object id
74
+     * @param string $objectType object type
75
+     * @param IUser $user user
76
+     * @param ISystemTagManager $tagManager tag manager
77
+     * @param ISystemTagObjectMapper $tagMapper tag mapper
78
+     */
79
+    public function __construct(
80
+        $objectId,
81
+        $objectType,
82
+        IUser $user,
83
+        ISystemTagManager $tagManager,
84
+        ISystemTagObjectMapper $tagMapper
85
+    ) {
86
+        $this->tagManager = $tagManager;
87
+        $this->tagMapper = $tagMapper;
88
+        $this->objectId = $objectId;
89
+        $this->objectType = $objectType;
90
+        $this->user = $user;
91
+    }
92
+
93
+    function createFile($tagId, $data = null) {
94
+        try {
95
+            $tags = $this->tagManager->getTagsByIds([$tagId]);
96
+            $tag = current($tags);
97
+            if (!$this->tagManager->canUserSeeTag($tag, $this->user)) {
98
+                throw new PreconditionFailed('Tag with id ' . $tagId . ' does not exist, cannot assign');
99
+            }
100
+            if (!$this->tagManager->canUserAssignTag($tag, $this->user)) {
101
+                throw new Forbidden('No permission to assign tag ' . $tagId);
102
+            }
103
+
104
+            $this->tagMapper->assignTags($this->objectId, $this->objectType, $tagId);
105
+        } catch (TagNotFoundException $e) {
106
+            throw new PreconditionFailed('Tag with id ' . $tagId . ' does not exist, cannot assign');
107
+        }
108
+    }
109
+
110
+    function createDirectory($name) {
111
+        throw new Forbidden('Permission denied to create collections');
112
+    }
113
+
114
+    function getChild($tagId) {
115
+        try {
116
+            if ($this->tagMapper->haveTag([$this->objectId], $this->objectType, $tagId, true)) {
117
+                $tag = $this->tagManager->getTagsByIds([$tagId]);
118
+                $tag = current($tag);
119
+                if ($this->tagManager->canUserSeeTag($tag, $this->user)) {
120
+                    return $this->makeNode($tag);
121
+                }
122
+            }
123
+            throw new NotFound('Tag with id ' . $tagId . ' not present for object ' . $this->objectId);
124
+        } catch (\InvalidArgumentException $e) {
125
+            throw new BadRequest('Invalid tag id', 0, $e);
126
+        } catch (TagNotFoundException $e) {
127
+            throw new NotFound('Tag with id ' . $tagId . ' not found', 0, $e);
128
+        }
129
+    }
130
+
131
+    function getChildren() {
132
+        $tagIds = current($this->tagMapper->getTagIdsForObjects([$this->objectId], $this->objectType));
133
+        if (empty($tagIds)) {
134
+            return [];
135
+        }
136
+        $tags = $this->tagManager->getTagsByIds($tagIds);
137
+
138
+        // filter out non-visible tags
139
+        $tags = array_filter($tags, function($tag) {
140
+            return $this->tagManager->canUserSeeTag($tag, $this->user);
141
+        });
142
+
143
+        return array_values(array_map(function($tag) {
144
+            return $this->makeNode($tag);
145
+        }, $tags));
146
+    }
147
+
148
+    function childExists($tagId) {
149
+        try {
150
+            $result = ($this->tagMapper->haveTag([$this->objectId], $this->objectType, $tagId, true));
151
+
152
+            if ($result) {
153
+                $tags = $this->tagManager->getTagsByIds([$tagId]);
154
+                $tag = current($tags);
155
+                if (!$this->tagManager->canUserSeeTag($tag, $this->user)) {
156
+                    return false;
157
+                }
158
+            }
159
+
160
+            return $result;
161
+        } catch (\InvalidArgumentException $e) {
162
+            throw new BadRequest('Invalid tag id', 0, $e);
163
+        } catch (TagNotFoundException $e) {
164
+            return false;
165
+        }
166
+    }
167
+
168
+    function delete() {
169
+        throw new Forbidden('Permission denied to delete this collection');
170
+    }
171
+
172
+    function getName() {
173
+        return $this->objectId;
174
+    }
175
+
176
+    function setName($name) {
177
+        throw new Forbidden('Permission denied to rename this collection');
178
+    }
179
+
180
+    /**
181
+     * Returns the last modification time, as a unix timestamp
182
+     *
183
+     * @return int
184
+     */
185
+    function getLastModified() {
186
+        return null;
187
+    }
188
+
189
+    /**
190
+     * Create a sabre node for the mapping of the 
191
+     * given system tag to the collection's object
192
+     *
193
+     * @param ISystemTag $tag
194
+     *
195
+     * @return SystemTagMappingNode
196
+     */
197
+    private function makeNode(ISystemTag $tag) {
198
+        return new SystemTagMappingNode(
199
+            $tag,
200
+            $this->objectId,
201
+            $this->objectType,
202
+            $this->user,
203
+            $this->tagManager,
204
+            $this->tagMapper
205
+        );
206
+    }
207 207
 }
Please login to merge, or discard this patch.
Spacing   +5 added lines, -5 removed lines patch added patch discarded remove patch
@@ -95,15 +95,15 @@  discard block
 block discarded – undo
95 95
 			$tags = $this->tagManager->getTagsByIds([$tagId]);
96 96
 			$tag = current($tags);
97 97
 			if (!$this->tagManager->canUserSeeTag($tag, $this->user)) {
98
-				throw new PreconditionFailed('Tag with id ' . $tagId . ' does not exist, cannot assign');
98
+				throw new PreconditionFailed('Tag with id '.$tagId.' does not exist, cannot assign');
99 99
 			}
100 100
 			if (!$this->tagManager->canUserAssignTag($tag, $this->user)) {
101
-				throw new Forbidden('No permission to assign tag ' . $tagId);
101
+				throw new Forbidden('No permission to assign tag '.$tagId);
102 102
 			}
103 103
 
104 104
 			$this->tagMapper->assignTags($this->objectId, $this->objectType, $tagId);
105 105
 		} catch (TagNotFoundException $e) {
106
-			throw new PreconditionFailed('Tag with id ' . $tagId . ' does not exist, cannot assign');
106
+			throw new PreconditionFailed('Tag with id '.$tagId.' does not exist, cannot assign');
107 107
 		}
108 108
 	}
109 109
 
@@ -120,11 +120,11 @@  discard block
 block discarded – undo
120 120
 					return $this->makeNode($tag);
121 121
 				}
122 122
 			}
123
-			throw new NotFound('Tag with id ' . $tagId . ' not present for object ' . $this->objectId);
123
+			throw new NotFound('Tag with id '.$tagId.' not present for object '.$this->objectId);
124 124
 		} catch (\InvalidArgumentException $e) {
125 125
 			throw new BadRequest('Invalid tag id', 0, $e);
126 126
 		} catch (TagNotFoundException $e) {
127
-			throw new NotFound('Tag with id ' . $tagId . ' not found', 0, $e);
127
+			throw new NotFound('Tag with id '.$tagId.' not found', 0, $e);
128 128
 		}
129 129
 	}
130 130
 
Please login to merge, or discard this patch.
lib/private/DB/Migrator.php 3 patches
Doc Comments   +8 added lines patch added patch discarded remove patch
@@ -273,6 +273,10 @@  discard block
 block discarded – undo
273 273
 		return '/^' . preg_quote($this->config->getSystemValue('dbtableprefix', 'oc_')) . '/';
274 274
 	}
275 275
 
276
+	/**
277
+	 * @param integer $step
278
+	 * @param integer $max
279
+	 */
276 280
 	protected function emit($sql, $step, $max) {
277 281
 		if ($this->noEmit) {
278 282
 			return;
@@ -283,6 +287,10 @@  discard block
 block discarded – undo
283 287
 		$this->dispatcher->dispatch('\OC\DB\Migrator::executeSql', new GenericEvent($sql, [$step+1, $max]));
284 288
 	}
285 289
 
290
+	/**
291
+	 * @param integer $step
292
+	 * @param integer $max
293
+	 */
286 294
 	private function emitCheckStep($tableName, $step, $max) {
287 295
 		if(is_null($this->dispatcher)) {
288 296
 			return;
Please login to merge, or discard this patch.
Spacing   +11 added lines, -11 removed lines patch added patch discarded remove patch
@@ -137,7 +137,7 @@  discard block
 block discarded – undo
137 137
 	 * @return string
138 138
 	 */
139 139
 	protected function generateTemporaryTableName($name) {
140
-		return $this->config->getSystemValue('dbtableprefix', 'oc_') . $name . '_' . $this->random->generate(13, ISecureRandom::CHAR_LOWER . ISecureRandom::CHAR_DIGITS);
140
+		return $this->config->getSystemValue('dbtableprefix', 'oc_').$name.'_'.$this->random->generate(13, ISecureRandom::CHAR_LOWER.ISecureRandom::CHAR_DIGITS);
141 141
 	}
142 142
 
143 143
 	/**
@@ -188,7 +188,7 @@  discard block
 block discarded – undo
188 188
 				$indexName = $index->getName();
189 189
 			} else {
190 190
 				// avoid conflicts in index names
191
-				$indexName = $this->config->getSystemValue('dbtableprefix', 'oc_') . $this->random->generate(13, ISecureRandom::CHAR_LOWER);
191
+				$indexName = $this->config->getSystemValue('dbtableprefix', 'oc_').$this->random->generate(13, ISecureRandom::CHAR_LOWER);
192 192
 			}
193 193
 			$newIndexes[] = new Index($indexName, $index->getColumns(), $index->isUnique(), $index->isPrimary());
194 194
 		}
@@ -268,15 +268,15 @@  discard block
 block discarded – undo
268 268
 		$quotedSource = $this->connection->quoteIdentifier($sourceName);
269 269
 		$quotedTarget = $this->connection->quoteIdentifier($targetName);
270 270
 
271
-		$this->connection->exec('CREATE TABLE ' . $quotedTarget . ' (LIKE ' . $quotedSource . ')');
272
-		$this->connection->exec('INSERT INTO ' . $quotedTarget . ' SELECT * FROM ' . $quotedSource);
271
+		$this->connection->exec('CREATE TABLE '.$quotedTarget.' (LIKE '.$quotedSource.')');
272
+		$this->connection->exec('INSERT INTO '.$quotedTarget.' SELECT * FROM '.$quotedSource);
273 273
 	}
274 274
 
275 275
 	/**
276 276
 	 * @param string $name
277 277
 	 */
278 278
 	protected function dropTable($name) {
279
-		$this->connection->exec('DROP TABLE ' . $this->connection->quoteIdentifier($name));
279
+		$this->connection->exec('DROP TABLE '.$this->connection->quoteIdentifier($name));
280 280
 	}
281 281
 
282 282
 	/**
@@ -284,30 +284,30 @@  discard block
 block discarded – undo
284 284
 	 * @return string
285 285
 	 */
286 286
 	protected function convertStatementToScript($statement) {
287
-		$script = $statement . ';';
287
+		$script = $statement.';';
288 288
 		$script .= PHP_EOL;
289 289
 		$script .= PHP_EOL;
290 290
 		return $script;
291 291
 	}
292 292
 
293 293
 	protected function getFilterExpression() {
294
-		return '/^' . preg_quote($this->config->getSystemValue('dbtableprefix', 'oc_')) . '/';
294
+		return '/^'.preg_quote($this->config->getSystemValue('dbtableprefix', 'oc_')).'/';
295 295
 	}
296 296
 
297 297
 	protected function emit($sql, $step, $max) {
298 298
 		if ($this->noEmit) {
299 299
 			return;
300 300
 		}
301
-		if(is_null($this->dispatcher)) {
301
+		if (is_null($this->dispatcher)) {
302 302
 			return;
303 303
 		}
304
-		$this->dispatcher->dispatch('\OC\DB\Migrator::executeSql', new GenericEvent($sql, [$step+1, $max]));
304
+		$this->dispatcher->dispatch('\OC\DB\Migrator::executeSql', new GenericEvent($sql, [$step + 1, $max]));
305 305
 	}
306 306
 
307 307
 	private function emitCheckStep($tableName, $step, $max) {
308
-		if(is_null($this->dispatcher)) {
308
+		if (is_null($this->dispatcher)) {
309 309
 			return;
310 310
 		}
311
-		$this->dispatcher->dispatch('\OC\DB\Migrator::checkTable', new GenericEvent($tableName, [$step+1, $max]));
311
+		$this->dispatcher->dispatch('\OC\DB\Migrator::checkTable', new GenericEvent($tableName, [$step + 1, $max]));
312 312
 	}
313 313
 }
Please login to merge, or discard this patch.
Indentation   +268 added lines, -268 removed lines patch added patch discarded remove patch
@@ -43,272 +43,272 @@
 block discarded – undo
43 43
 
44 44
 class Migrator {
45 45
 
46
-	/** @var \Doctrine\DBAL\Connection */
47
-	protected $connection;
48
-
49
-	/** @var ISecureRandom */
50
-	private $random;
51
-
52
-	/** @var IConfig */
53
-	protected $config;
54
-
55
-	/** @var EventDispatcher  */
56
-	private $dispatcher;
57
-
58
-	/** @var bool */
59
-	private $noEmit = false;
60
-
61
-	/**
62
-	 * @param \Doctrine\DBAL\Connection|Connection $connection
63
-	 * @param ISecureRandom $random
64
-	 * @param IConfig $config
65
-	 * @param EventDispatcher $dispatcher
66
-	 */
67
-	public function __construct(\Doctrine\DBAL\Connection $connection,
68
-								ISecureRandom $random,
69
-								IConfig $config,
70
-								EventDispatcher $dispatcher = null) {
71
-		$this->connection = $connection;
72
-		$this->random = $random;
73
-		$this->config = $config;
74
-		$this->dispatcher = $dispatcher;
75
-	}
76
-
77
-	/**
78
-	 * @param \Doctrine\DBAL\Schema\Schema $targetSchema
79
-	 */
80
-	public function migrate(Schema $targetSchema) {
81
-		$this->noEmit = true;
82
-		$this->applySchema($targetSchema);
83
-	}
84
-
85
-	/**
86
-	 * @param \Doctrine\DBAL\Schema\Schema $targetSchema
87
-	 * @return string
88
-	 */
89
-	public function generateChangeScript(Schema $targetSchema) {
90
-		$schemaDiff = $this->getDiff($targetSchema, $this->connection);
91
-
92
-		$script = '';
93
-		$sqls = $schemaDiff->toSql($this->connection->getDatabasePlatform());
94
-		foreach ($sqls as $sql) {
95
-			$script .= $this->convertStatementToScript($sql);
96
-		}
97
-
98
-		return $script;
99
-	}
100
-
101
-	/**
102
-	 * @param Schema $targetSchema
103
-	 * @throws \OC\DB\MigrationException
104
-	 */
105
-	public function checkMigrate(Schema $targetSchema) {
106
-		$this->noEmit = true;
107
-		/**@var \Doctrine\DBAL\Schema\Table[] $tables */
108
-		$tables = $targetSchema->getTables();
109
-		$filterExpression = $this->getFilterExpression();
110
-		$this->connection->getConfiguration()->
111
-			setFilterSchemaAssetsExpression($filterExpression);
112
-		$existingTables = $this->connection->getSchemaManager()->listTableNames();
113
-
114
-		$step = 0;
115
-		foreach ($tables as $table) {
116
-			if (strpos($table->getName(), '.')) {
117
-				list(, $tableName) = explode('.', $table->getName());
118
-			} else {
119
-				$tableName = $table->getName();
120
-			}
121
-			$this->emitCheckStep($tableName, $step++, count($tables));
122
-			// don't need to check for new tables
123
-			if (array_search($tableName, $existingTables) !== false) {
124
-				$this->checkTableMigrate($table);
125
-			}
126
-		}
127
-	}
128
-
129
-	/**
130
-	 * Create a unique name for the temporary table
131
-	 *
132
-	 * @param string $name
133
-	 * @return string
134
-	 */
135
-	protected function generateTemporaryTableName($name) {
136
-		return $this->config->getSystemValue('dbtableprefix', 'oc_') . $name . '_' . $this->random->generate(13, ISecureRandom::CHAR_LOWER . ISecureRandom::CHAR_DIGITS);
137
-	}
138
-
139
-	/**
140
-	 * Check the migration of a table on a copy so we can detect errors before messing with the real table
141
-	 *
142
-	 * @param \Doctrine\DBAL\Schema\Table $table
143
-	 * @throws \OC\DB\MigrationException
144
-	 */
145
-	protected function checkTableMigrate(Table $table) {
146
-		$name = $table->getName();
147
-		$tmpName = $this->generateTemporaryTableName($name);
148
-
149
-		$this->copyTable($name, $tmpName);
150
-
151
-		//create the migration schema for the temporary table
152
-		$tmpTable = $this->renameTableSchema($table, $tmpName);
153
-		$schemaConfig = new SchemaConfig();
154
-		$schemaConfig->setName($this->connection->getDatabase());
155
-		$schema = new Schema(array($tmpTable), array(), $schemaConfig);
156
-
157
-		try {
158
-			$this->applySchema($schema);
159
-			$this->dropTable($tmpName);
160
-		} catch (DBALException $e) {
161
-			// pgsql needs to commit it's failed transaction before doing anything else
162
-			if ($this->connection->isTransactionActive()) {
163
-				$this->connection->commit();
164
-			}
165
-			$this->dropTable($tmpName);
166
-			throw new MigrationException($table->getName(), $e->getMessage());
167
-		}
168
-	}
169
-
170
-	/**
171
-	 * @param \Doctrine\DBAL\Schema\Table $table
172
-	 * @param string $newName
173
-	 * @return \Doctrine\DBAL\Schema\Table
174
-	 */
175
-	protected function renameTableSchema(Table $table, $newName) {
176
-		/**
177
-		 * @var \Doctrine\DBAL\Schema\Index[] $indexes
178
-		 */
179
-		$indexes = $table->getIndexes();
180
-		$newIndexes = array();
181
-		foreach ($indexes as $index) {
182
-			if ($index->isPrimary()) {
183
-				// do not rename primary key
184
-				$indexName = $index->getName();
185
-			} else {
186
-				// avoid conflicts in index names
187
-				$indexName = $this->config->getSystemValue('dbtableprefix', 'oc_') . $this->random->generate(13, ISecureRandom::CHAR_LOWER);
188
-			}
189
-			$newIndexes[] = new Index($indexName, $index->getColumns(), $index->isUnique(), $index->isPrimary());
190
-		}
191
-
192
-		// foreign keys are not supported so we just set it to an empty array
193
-		return new Table($newName, $table->getColumns(), $newIndexes, array(), 0, $table->getOptions());
194
-	}
195
-
196
-	public function createSchema() {
197
-		$filterExpression = $this->getFilterExpression();
198
-		$this->connection->getConfiguration()->setFilterSchemaAssetsExpression($filterExpression);
199
-		return $this->connection->getSchemaManager()->createSchema();
200
-	}
201
-
202
-	/**
203
-	 * @param Schema $targetSchema
204
-	 * @param \Doctrine\DBAL\Connection $connection
205
-	 * @return \Doctrine\DBAL\Schema\SchemaDiff
206
-	 * @throws DBALException
207
-	 */
208
-	protected function getDiff(Schema $targetSchema, \Doctrine\DBAL\Connection $connection) {
209
-		// adjust varchar columns with a length higher then getVarcharMaxLength to clob
210
-		foreach ($targetSchema->getTables() as $table) {
211
-			foreach ($table->getColumns() as $column) {
212
-				if ($column->getType() instanceof StringType) {
213
-					if ($column->getLength() > $connection->getDatabasePlatform()->getVarcharMaxLength()) {
214
-						$column->setType(Type::getType('text'));
215
-						$column->setLength(null);
216
-					}
217
-				}
218
-			}
219
-		}
220
-
221
-		$filterExpression = $this->getFilterExpression();
222
-		$this->connection->getConfiguration()->setFilterSchemaAssetsExpression($filterExpression);
223
-		$sourceSchema = $connection->getSchemaManager()->createSchema();
224
-
225
-		// remove tables we don't know about
226
-		/** @var $table \Doctrine\DBAL\Schema\Table */
227
-		foreach ($sourceSchema->getTables() as $table) {
228
-			if (!$targetSchema->hasTable($table->getName())) {
229
-				$sourceSchema->dropTable($table->getName());
230
-			}
231
-		}
232
-		// remove sequences we don't know about
233
-		foreach ($sourceSchema->getSequences() as $table) {
234
-			if (!$targetSchema->hasSequence($table->getName())) {
235
-				$sourceSchema->dropSequence($table->getName());
236
-			}
237
-		}
238
-
239
-		$comparator = new Comparator();
240
-		return $comparator->compare($sourceSchema, $targetSchema);
241
-	}
242
-
243
-	/**
244
-	 * @param \Doctrine\DBAL\Schema\Schema $targetSchema
245
-	 * @param \Doctrine\DBAL\Connection $connection
246
-	 */
247
-	protected function applySchema(Schema $targetSchema, \Doctrine\DBAL\Connection $connection = null) {
248
-		if (is_null($connection)) {
249
-			$connection = $this->connection;
250
-		}
251
-
252
-		$schemaDiff = $this->getDiff($targetSchema, $connection);
253
-
254
-		$connection->beginTransaction();
255
-		$sqls = $schemaDiff->toSql($connection->getDatabasePlatform());
256
-		$step = 0;
257
-		foreach ($sqls as $sql) {
258
-			$this->emit($sql, $step++, count($sqls));
259
-			$connection->query($sql);
260
-		}
261
-		$connection->commit();
262
-	}
263
-
264
-	/**
265
-	 * @param string $sourceName
266
-	 * @param string $targetName
267
-	 */
268
-	protected function copyTable($sourceName, $targetName) {
269
-		$quotedSource = $this->connection->quoteIdentifier($sourceName);
270
-		$quotedTarget = $this->connection->quoteIdentifier($targetName);
271
-
272
-		$this->connection->exec('CREATE TABLE ' . $quotedTarget . ' (LIKE ' . $quotedSource . ')');
273
-		$this->connection->exec('INSERT INTO ' . $quotedTarget . ' SELECT * FROM ' . $quotedSource);
274
-	}
275
-
276
-	/**
277
-	 * @param string $name
278
-	 */
279
-	protected function dropTable($name) {
280
-		$this->connection->exec('DROP TABLE ' . $this->connection->quoteIdentifier($name));
281
-	}
282
-
283
-	/**
284
-	 * @param $statement
285
-	 * @return string
286
-	 */
287
-	protected function convertStatementToScript($statement) {
288
-		$script = $statement . ';';
289
-		$script .= PHP_EOL;
290
-		$script .= PHP_EOL;
291
-		return $script;
292
-	}
293
-
294
-	protected function getFilterExpression() {
295
-		return '/^' . preg_quote($this->config->getSystemValue('dbtableprefix', 'oc_')) . '/';
296
-	}
297
-
298
-	protected function emit($sql, $step, $max) {
299
-		if ($this->noEmit) {
300
-			return;
301
-		}
302
-		if(is_null($this->dispatcher)) {
303
-			return;
304
-		}
305
-		$this->dispatcher->dispatch('\OC\DB\Migrator::executeSql', new GenericEvent($sql, [$step+1, $max]));
306
-	}
307
-
308
-	private function emitCheckStep($tableName, $step, $max) {
309
-		if(is_null($this->dispatcher)) {
310
-			return;
311
-		}
312
-		$this->dispatcher->dispatch('\OC\DB\Migrator::checkTable', new GenericEvent($tableName, [$step+1, $max]));
313
-	}
46
+    /** @var \Doctrine\DBAL\Connection */
47
+    protected $connection;
48
+
49
+    /** @var ISecureRandom */
50
+    private $random;
51
+
52
+    /** @var IConfig */
53
+    protected $config;
54
+
55
+    /** @var EventDispatcher  */
56
+    private $dispatcher;
57
+
58
+    /** @var bool */
59
+    private $noEmit = false;
60
+
61
+    /**
62
+     * @param \Doctrine\DBAL\Connection|Connection $connection
63
+     * @param ISecureRandom $random
64
+     * @param IConfig $config
65
+     * @param EventDispatcher $dispatcher
66
+     */
67
+    public function __construct(\Doctrine\DBAL\Connection $connection,
68
+                                ISecureRandom $random,
69
+                                IConfig $config,
70
+                                EventDispatcher $dispatcher = null) {
71
+        $this->connection = $connection;
72
+        $this->random = $random;
73
+        $this->config = $config;
74
+        $this->dispatcher = $dispatcher;
75
+    }
76
+
77
+    /**
78
+     * @param \Doctrine\DBAL\Schema\Schema $targetSchema
79
+     */
80
+    public function migrate(Schema $targetSchema) {
81
+        $this->noEmit = true;
82
+        $this->applySchema($targetSchema);
83
+    }
84
+
85
+    /**
86
+     * @param \Doctrine\DBAL\Schema\Schema $targetSchema
87
+     * @return string
88
+     */
89
+    public function generateChangeScript(Schema $targetSchema) {
90
+        $schemaDiff = $this->getDiff($targetSchema, $this->connection);
91
+
92
+        $script = '';
93
+        $sqls = $schemaDiff->toSql($this->connection->getDatabasePlatform());
94
+        foreach ($sqls as $sql) {
95
+            $script .= $this->convertStatementToScript($sql);
96
+        }
97
+
98
+        return $script;
99
+    }
100
+
101
+    /**
102
+     * @param Schema $targetSchema
103
+     * @throws \OC\DB\MigrationException
104
+     */
105
+    public function checkMigrate(Schema $targetSchema) {
106
+        $this->noEmit = true;
107
+        /**@var \Doctrine\DBAL\Schema\Table[] $tables */
108
+        $tables = $targetSchema->getTables();
109
+        $filterExpression = $this->getFilterExpression();
110
+        $this->connection->getConfiguration()->
111
+            setFilterSchemaAssetsExpression($filterExpression);
112
+        $existingTables = $this->connection->getSchemaManager()->listTableNames();
113
+
114
+        $step = 0;
115
+        foreach ($tables as $table) {
116
+            if (strpos($table->getName(), '.')) {
117
+                list(, $tableName) = explode('.', $table->getName());
118
+            } else {
119
+                $tableName = $table->getName();
120
+            }
121
+            $this->emitCheckStep($tableName, $step++, count($tables));
122
+            // don't need to check for new tables
123
+            if (array_search($tableName, $existingTables) !== false) {
124
+                $this->checkTableMigrate($table);
125
+            }
126
+        }
127
+    }
128
+
129
+    /**
130
+     * Create a unique name for the temporary table
131
+     *
132
+     * @param string $name
133
+     * @return string
134
+     */
135
+    protected function generateTemporaryTableName($name) {
136
+        return $this->config->getSystemValue('dbtableprefix', 'oc_') . $name . '_' . $this->random->generate(13, ISecureRandom::CHAR_LOWER . ISecureRandom::CHAR_DIGITS);
137
+    }
138
+
139
+    /**
140
+     * Check the migration of a table on a copy so we can detect errors before messing with the real table
141
+     *
142
+     * @param \Doctrine\DBAL\Schema\Table $table
143
+     * @throws \OC\DB\MigrationException
144
+     */
145
+    protected function checkTableMigrate(Table $table) {
146
+        $name = $table->getName();
147
+        $tmpName = $this->generateTemporaryTableName($name);
148
+
149
+        $this->copyTable($name, $tmpName);
150
+
151
+        //create the migration schema for the temporary table
152
+        $tmpTable = $this->renameTableSchema($table, $tmpName);
153
+        $schemaConfig = new SchemaConfig();
154
+        $schemaConfig->setName($this->connection->getDatabase());
155
+        $schema = new Schema(array($tmpTable), array(), $schemaConfig);
156
+
157
+        try {
158
+            $this->applySchema($schema);
159
+            $this->dropTable($tmpName);
160
+        } catch (DBALException $e) {
161
+            // pgsql needs to commit it's failed transaction before doing anything else
162
+            if ($this->connection->isTransactionActive()) {
163
+                $this->connection->commit();
164
+            }
165
+            $this->dropTable($tmpName);
166
+            throw new MigrationException($table->getName(), $e->getMessage());
167
+        }
168
+    }
169
+
170
+    /**
171
+     * @param \Doctrine\DBAL\Schema\Table $table
172
+     * @param string $newName
173
+     * @return \Doctrine\DBAL\Schema\Table
174
+     */
175
+    protected function renameTableSchema(Table $table, $newName) {
176
+        /**
177
+         * @var \Doctrine\DBAL\Schema\Index[] $indexes
178
+         */
179
+        $indexes = $table->getIndexes();
180
+        $newIndexes = array();
181
+        foreach ($indexes as $index) {
182
+            if ($index->isPrimary()) {
183
+                // do not rename primary key
184
+                $indexName = $index->getName();
185
+            } else {
186
+                // avoid conflicts in index names
187
+                $indexName = $this->config->getSystemValue('dbtableprefix', 'oc_') . $this->random->generate(13, ISecureRandom::CHAR_LOWER);
188
+            }
189
+            $newIndexes[] = new Index($indexName, $index->getColumns(), $index->isUnique(), $index->isPrimary());
190
+        }
191
+
192
+        // foreign keys are not supported so we just set it to an empty array
193
+        return new Table($newName, $table->getColumns(), $newIndexes, array(), 0, $table->getOptions());
194
+    }
195
+
196
+    public function createSchema() {
197
+        $filterExpression = $this->getFilterExpression();
198
+        $this->connection->getConfiguration()->setFilterSchemaAssetsExpression($filterExpression);
199
+        return $this->connection->getSchemaManager()->createSchema();
200
+    }
201
+
202
+    /**
203
+     * @param Schema $targetSchema
204
+     * @param \Doctrine\DBAL\Connection $connection
205
+     * @return \Doctrine\DBAL\Schema\SchemaDiff
206
+     * @throws DBALException
207
+     */
208
+    protected function getDiff(Schema $targetSchema, \Doctrine\DBAL\Connection $connection) {
209
+        // adjust varchar columns with a length higher then getVarcharMaxLength to clob
210
+        foreach ($targetSchema->getTables() as $table) {
211
+            foreach ($table->getColumns() as $column) {
212
+                if ($column->getType() instanceof StringType) {
213
+                    if ($column->getLength() > $connection->getDatabasePlatform()->getVarcharMaxLength()) {
214
+                        $column->setType(Type::getType('text'));
215
+                        $column->setLength(null);
216
+                    }
217
+                }
218
+            }
219
+        }
220
+
221
+        $filterExpression = $this->getFilterExpression();
222
+        $this->connection->getConfiguration()->setFilterSchemaAssetsExpression($filterExpression);
223
+        $sourceSchema = $connection->getSchemaManager()->createSchema();
224
+
225
+        // remove tables we don't know about
226
+        /** @var $table \Doctrine\DBAL\Schema\Table */
227
+        foreach ($sourceSchema->getTables() as $table) {
228
+            if (!$targetSchema->hasTable($table->getName())) {
229
+                $sourceSchema->dropTable($table->getName());
230
+            }
231
+        }
232
+        // remove sequences we don't know about
233
+        foreach ($sourceSchema->getSequences() as $table) {
234
+            if (!$targetSchema->hasSequence($table->getName())) {
235
+                $sourceSchema->dropSequence($table->getName());
236
+            }
237
+        }
238
+
239
+        $comparator = new Comparator();
240
+        return $comparator->compare($sourceSchema, $targetSchema);
241
+    }
242
+
243
+    /**
244
+     * @param \Doctrine\DBAL\Schema\Schema $targetSchema
245
+     * @param \Doctrine\DBAL\Connection $connection
246
+     */
247
+    protected function applySchema(Schema $targetSchema, \Doctrine\DBAL\Connection $connection = null) {
248
+        if (is_null($connection)) {
249
+            $connection = $this->connection;
250
+        }
251
+
252
+        $schemaDiff = $this->getDiff($targetSchema, $connection);
253
+
254
+        $connection->beginTransaction();
255
+        $sqls = $schemaDiff->toSql($connection->getDatabasePlatform());
256
+        $step = 0;
257
+        foreach ($sqls as $sql) {
258
+            $this->emit($sql, $step++, count($sqls));
259
+            $connection->query($sql);
260
+        }
261
+        $connection->commit();
262
+    }
263
+
264
+    /**
265
+     * @param string $sourceName
266
+     * @param string $targetName
267
+     */
268
+    protected function copyTable($sourceName, $targetName) {
269
+        $quotedSource = $this->connection->quoteIdentifier($sourceName);
270
+        $quotedTarget = $this->connection->quoteIdentifier($targetName);
271
+
272
+        $this->connection->exec('CREATE TABLE ' . $quotedTarget . ' (LIKE ' . $quotedSource . ')');
273
+        $this->connection->exec('INSERT INTO ' . $quotedTarget . ' SELECT * FROM ' . $quotedSource);
274
+    }
275
+
276
+    /**
277
+     * @param string $name
278
+     */
279
+    protected function dropTable($name) {
280
+        $this->connection->exec('DROP TABLE ' . $this->connection->quoteIdentifier($name));
281
+    }
282
+
283
+    /**
284
+     * @param $statement
285
+     * @return string
286
+     */
287
+    protected function convertStatementToScript($statement) {
288
+        $script = $statement . ';';
289
+        $script .= PHP_EOL;
290
+        $script .= PHP_EOL;
291
+        return $script;
292
+    }
293
+
294
+    protected function getFilterExpression() {
295
+        return '/^' . preg_quote($this->config->getSystemValue('dbtableprefix', 'oc_')) . '/';
296
+    }
297
+
298
+    protected function emit($sql, $step, $max) {
299
+        if ($this->noEmit) {
300
+            return;
301
+        }
302
+        if(is_null($this->dispatcher)) {
303
+            return;
304
+        }
305
+        $this->dispatcher->dispatch('\OC\DB\Migrator::executeSql', new GenericEvent($sql, [$step+1, $max]));
306
+    }
307
+
308
+    private function emitCheckStep($tableName, $step, $max) {
309
+        if(is_null($this->dispatcher)) {
310
+            return;
311
+        }
312
+        $this->dispatcher->dispatch('\OC\DB\Migrator::checkTable', new GenericEvent($tableName, [$step+1, $max]));
313
+    }
314 314
 }
Please login to merge, or discard this patch.
settings/Controller/CheckSetupController.php 3 patches
Doc Comments   +2 added lines, -1 removed lines patch added patch discarded remove patch
@@ -103,6 +103,7 @@  discard block
 block discarded – undo
103 103
 
104 104
 	/**
105 105
 	* Chceks if the ownCloud server can connect to a specific URL using both HTTPS and HTTP
106
+	* @param string $sitename
106 107
 	* @return bool
107 108
 	*/
108 109
 	private function isSiteReachable($sitename) {
@@ -285,7 +286,7 @@  discard block
 block discarded – undo
285 286
 
286 287
 	/**
287 288
 	 * @NoCSRFRequired
288
-	 * @return DataResponse
289
+	 * @return DataDisplayResponse
289 290
 	 */
290 291
 	public function getFailedIntegrityCheckFiles() {
291 292
 		if(!$this->checker->isCodeCheckEnforced()) {
Please login to merge, or discard this patch.
Spacing   +26 added lines, -26 removed lines patch added patch discarded remove patch
@@ -104,7 +104,7 @@  discard block
 block discarded – undo
104 104
 						'www.google.com',
105 105
 						'www.github.com'];
106 106
 
107
-		foreach($siteArray as $site) {
107
+		foreach ($siteArray as $site) {
108 108
 			if ($this->isSiteReachable($site)) {
109 109
 				return true;
110 110
 			}
@@ -117,8 +117,8 @@  discard block
 block discarded – undo
117 117
 	* @return bool
118 118
 	*/
119 119
 	private function isSiteReachable($sitename) {
120
-		$httpSiteName = 'http://' . $sitename . '/';
121
-		$httpsSiteName = 'https://' . $sitename . '/';
120
+		$httpSiteName = 'http://'.$sitename.'/';
121
+		$httpsSiteName = 'https://'.$sitename.'/';
122 122
 
123 123
 		try {
124 124
 			$client = $this->clientService->newClient();
@@ -145,9 +145,9 @@  discard block
 block discarded – undo
145 145
 	 * @return bool
146 146
 	 */
147 147
 	private function isUrandomAvailable() {
148
-		if(@file_exists('/dev/urandom')) {
148
+		if (@file_exists('/dev/urandom')) {
149 149
 			$file = fopen('/dev/urandom', 'rb');
150
-			if($file) {
150
+			if ($file) {
151 151
 				fclose($file);
152 152
 				return true;
153 153
 			}
@@ -178,40 +178,40 @@  discard block
 block discarded – undo
178 178
 		// Don't run check when:
179 179
 		// 1. Server has `has_internet_connection` set to false
180 180
 		// 2. AppStore AND S2S is disabled
181
-		if(!$this->config->getSystemValue('has_internet_connection', true)) {
181
+		if (!$this->config->getSystemValue('has_internet_connection', true)) {
182 182
 			return '';
183 183
 		}
184
-		if(!$this->config->getSystemValue('appstoreenabled', true)
184
+		if (!$this->config->getSystemValue('appstoreenabled', true)
185 185
 			&& $this->config->getAppValue('files_sharing', 'outgoing_server2server_share_enabled', 'yes') === 'no'
186 186
 			&& $this->config->getAppValue('files_sharing', 'incoming_server2server_share_enabled', 'yes') === 'no') {
187 187
 			return '';
188 188
 		}
189 189
 
190 190
 		$versionString = $this->getCurlVersion();
191
-		if(isset($versionString['ssl_version'])) {
191
+		if (isset($versionString['ssl_version'])) {
192 192
 			$versionString = $versionString['ssl_version'];
193 193
 		} else {
194 194
 			return '';
195 195
 		}
196 196
 
197
-		$features = (string)$this->l10n->t('installing and updating apps via the app store or Federated Cloud Sharing');
198
-		if(!$this->config->getSystemValue('appstoreenabled', true)) {
199
-			$features = (string)$this->l10n->t('Federated Cloud Sharing');
197
+		$features = (string) $this->l10n->t('installing and updating apps via the app store or Federated Cloud Sharing');
198
+		if (!$this->config->getSystemValue('appstoreenabled', true)) {
199
+			$features = (string) $this->l10n->t('Federated Cloud Sharing');
200 200
 		}
201 201
 
202 202
 		// Check if at least OpenSSL after 1.01d or 1.0.2b
203
-		if(strpos($versionString, 'OpenSSL/') === 0) {
203
+		if (strpos($versionString, 'OpenSSL/') === 0) {
204 204
 			$majorVersion = substr($versionString, 8, 5);
205 205
 			$patchRelease = substr($versionString, 13, 6);
206 206
 
207
-			if(($majorVersion === '1.0.1' && ord($patchRelease) < ord('d')) ||
207
+			if (($majorVersion === '1.0.1' && ord($patchRelease) < ord('d')) ||
208 208
 				($majorVersion === '1.0.2' && ord($patchRelease) < ord('b'))) {
209 209
 				return (string) $this->l10n->t('cURL is using an outdated %s version (%s). Please update your operating system or features such as %s will not work reliably.', ['OpenSSL', $versionString, $features]);
210 210
 			}
211 211
 		}
212 212
 
213 213
 		// Check if NSS and perform heuristic check
214
-		if(strpos($versionString, 'NSS/') === 0) {
214
+		if (strpos($versionString, 'NSS/') === 0) {
215 215
 			try {
216 216
 				$firstClient = $this->clientService->newClient();
217 217
 				$firstClient->get('https://www.owncloud.org/');
@@ -219,7 +219,7 @@  discard block
 block discarded – undo
219 219
 				$secondClient = $this->clientService->newClient();
220 220
 				$secondClient->get('https://owncloud.org/');
221 221
 			} catch (ClientException $e) {
222
-				if($e->getResponse()->getStatusCode() === 400) {
222
+				if ($e->getResponse()->getStatusCode() === 400) {
223 223
 					return (string) $this->l10n->t('cURL is using an outdated %s version (%s). Please update your operating system or features such as %s will not work reliably.', ['NSS', $versionString, $features]);
224 224
 				}
225 225
 			}
@@ -300,13 +300,13 @@  discard block
 block discarded – undo
300 300
 	 * @return DataResponse
301 301
 	 */
302 302
 	public function getFailedIntegrityCheckFiles() {
303
-		if(!$this->checker->isCodeCheckEnforced()) {
303
+		if (!$this->checker->isCodeCheckEnforced()) {
304 304
 			return new DataDisplayResponse('Integrity checker has been disabled. Integrity cannot be verified.');
305 305
 		}
306 306
 
307 307
 		$completeResults = $this->checker->getResults();
308 308
 
309
-		if(!empty($completeResults)) {
309
+		if (!empty($completeResults)) {
310 310
 			$formattedTextResponse = 'Technical information
311 311
 =====================
312 312
 The following list covers which files have failed the integrity check. Please read
@@ -316,12 +316,12 @@  discard block
 block discarded – undo
316 316
 Results
317 317
 =======
318 318
 ';
319
-			foreach($completeResults as $context => $contextResult) {
319
+			foreach ($completeResults as $context => $contextResult) {
320 320
 				$formattedTextResponse .= "- $context\n";
321 321
 
322
-				foreach($contextResult as $category => $result) {
322
+				foreach ($contextResult as $category => $result) {
323 323
 					$formattedTextResponse .= "\t- $category\n";
324
-					if($category !== 'EXCEPTION') {
324
+					if ($category !== 'EXCEPTION') {
325 325
 						foreach ($result as $key => $results) {
326 326
 							$formattedTextResponse .= "\t\t- $key\n";
327 327
 						}
@@ -364,27 +364,27 @@  discard block
 block discarded – undo
364 364
 
365 365
 		$isOpcacheProperlySetUp = true;
366 366
 
367
-		if(!$iniWrapper->getBool('opcache.enable')) {
367
+		if (!$iniWrapper->getBool('opcache.enable')) {
368 368
 			$isOpcacheProperlySetUp = false;
369 369
 		}
370 370
 
371
-		if(!$iniWrapper->getBool('opcache.save_comments')) {
371
+		if (!$iniWrapper->getBool('opcache.save_comments')) {
372 372
 			$isOpcacheProperlySetUp = false;
373 373
 		}
374 374
 
375
-		if(!$iniWrapper->getBool('opcache.enable_cli')) {
375
+		if (!$iniWrapper->getBool('opcache.enable_cli')) {
376 376
 			$isOpcacheProperlySetUp = false;
377 377
 		}
378 378
 
379
-		if($iniWrapper->getNumeric('opcache.max_accelerated_files') < 10000) {
379
+		if ($iniWrapper->getNumeric('opcache.max_accelerated_files') < 10000) {
380 380
 			$isOpcacheProperlySetUp = false;
381 381
 		}
382 382
 
383
-		if($iniWrapper->getNumeric('opcache.memory_consumption') < 128) {
383
+		if ($iniWrapper->getNumeric('opcache.memory_consumption') < 128) {
384 384
 			$isOpcacheProperlySetUp = false;
385 385
 		}
386 386
 
387
-		if($iniWrapper->getNumeric('opcache.interned_strings_buffer') < 8) {
387
+		if ($iniWrapper->getNumeric('opcache.interned_strings_buffer') < 8) {
388 388
 			$isOpcacheProperlySetUp = false;
389 389
 		}
390 390
 
Please login to merge, or discard this patch.
Indentation   +372 added lines, -372 removed lines patch added patch discarded remove patch
@@ -46,282 +46,282 @@  discard block
 block discarded – undo
46 46
  * @package OC\Settings\Controller
47 47
  */
48 48
 class CheckSetupController extends Controller {
49
-	/** @var IConfig */
50
-	private $config;
51
-	/** @var IClientService */
52
-	private $clientService;
53
-	/** @var \OC_Util */
54
-	private $util;
55
-	/** @var IURLGenerator */
56
-	private $urlGenerator;
57
-	/** @var IL10N */
58
-	private $l10n;
59
-	/** @var Checker */
60
-	private $checker;
61
-	/** @var ILogger */
62
-	private $logger;
63
-
64
-	/**
65
-	 * @param string $AppName
66
-	 * @param IRequest $request
67
-	 * @param IConfig $config
68
-	 * @param IClientService $clientService
69
-	 * @param IURLGenerator $urlGenerator
70
-	 * @param \OC_Util $util
71
-	 * @param IL10N $l10n
72
-	 * @param Checker $checker
73
-	 * @param ILogger $logger
74
-	 */
75
-	public function __construct($AppName,
76
-								IRequest $request,
77
-								IConfig $config,
78
-								IClientService $clientService,
79
-								IURLGenerator $urlGenerator,
80
-								\OC_Util $util,
81
-								IL10N $l10n,
82
-								Checker $checker,
83
-								ILogger $logger) {
84
-		parent::__construct($AppName, $request);
85
-		$this->config = $config;
86
-		$this->clientService = $clientService;
87
-		$this->util = $util;
88
-		$this->urlGenerator = $urlGenerator;
89
-		$this->l10n = $l10n;
90
-		$this->checker = $checker;
91
-		$this->logger = $logger;
92
-	}
93
-
94
-	/**
95
-	 * Checks if the ownCloud server can connect to the internet using HTTPS and HTTP
96
-	 * @return bool
97
-	 */
98
-	private function isInternetConnectionWorking() {
99
-		if ($this->config->getSystemValue('has_internet_connection', true) === false) {
100
-			return false;
101
-		}
102
-
103
-		$siteArray = ['www.nextcloud.com',
104
-						'www.google.com',
105
-						'www.github.com'];
106
-
107
-		foreach($siteArray as $site) {
108
-			if ($this->isSiteReachable($site)) {
109
-				return true;
110
-			}
111
-		}
112
-		return false;
113
-	}
114
-
115
-	/**
116
-	* Chceks if the ownCloud server can connect to a specific URL using both HTTPS and HTTP
117
-	* @return bool
118
-	*/
119
-	private function isSiteReachable($sitename) {
120
-		$httpSiteName = 'http://' . $sitename . '/';
121
-		$httpsSiteName = 'https://' . $sitename . '/';
122
-
123
-		try {
124
-			$client = $this->clientService->newClient();
125
-			$client->get($httpSiteName);
126
-			$client->get($httpsSiteName);
127
-		} catch (\Exception $e) {
128
-			$this->logger->logException($e, ['app' => 'internet_connection_check']);
129
-			return false;
130
-		}
131
-		return true;
132
-	}
133
-
134
-	/**
135
-	 * Checks whether a local memcache is installed or not
136
-	 * @return bool
137
-	 */
138
-	private function isMemcacheConfigured() {
139
-		return $this->config->getSystemValue('memcache.local', null) !== null;
140
-	}
141
-
142
-	/**
143
-	 * Whether /dev/urandom is available to the PHP controller
144
-	 *
145
-	 * @return bool
146
-	 */
147
-	private function isUrandomAvailable() {
148
-		if(@file_exists('/dev/urandom')) {
149
-			$file = fopen('/dev/urandom', 'rb');
150
-			if($file) {
151
-				fclose($file);
152
-				return true;
153
-			}
154
-		}
155
-
156
-		return false;
157
-	}
158
-
159
-	/**
160
-	 * Public for the sake of unit-testing
161
-	 *
162
-	 * @return array
163
-	 */
164
-	protected function getCurlVersion() {
165
-		return curl_version();
166
-	}
167
-
168
-	/**
169
-	 * Check if the used  SSL lib is outdated. Older OpenSSL and NSS versions do
170
-	 * have multiple bugs which likely lead to problems in combination with
171
-	 * functionality required by ownCloud such as SNI.
172
-	 *
173
-	 * @link https://github.com/owncloud/core/issues/17446#issuecomment-122877546
174
-	 * @link https://bugzilla.redhat.com/show_bug.cgi?id=1241172
175
-	 * @return string
176
-	 */
177
-	private function isUsedTlsLibOutdated() {
178
-		// Don't run check when:
179
-		// 1. Server has `has_internet_connection` set to false
180
-		// 2. AppStore AND S2S is disabled
181
-		if(!$this->config->getSystemValue('has_internet_connection', true)) {
182
-			return '';
183
-		}
184
-		if(!$this->config->getSystemValue('appstoreenabled', true)
185
-			&& $this->config->getAppValue('files_sharing', 'outgoing_server2server_share_enabled', 'yes') === 'no'
186
-			&& $this->config->getAppValue('files_sharing', 'incoming_server2server_share_enabled', 'yes') === 'no') {
187
-			return '';
188
-		}
189
-
190
-		$versionString = $this->getCurlVersion();
191
-		if(isset($versionString['ssl_version'])) {
192
-			$versionString = $versionString['ssl_version'];
193
-		} else {
194
-			return '';
195
-		}
196
-
197
-		$features = (string)$this->l10n->t('installing and updating apps via the app store or Federated Cloud Sharing');
198
-		if(!$this->config->getSystemValue('appstoreenabled', true)) {
199
-			$features = (string)$this->l10n->t('Federated Cloud Sharing');
200
-		}
201
-
202
-		// Check if at least OpenSSL after 1.01d or 1.0.2b
203
-		if(strpos($versionString, 'OpenSSL/') === 0) {
204
-			$majorVersion = substr($versionString, 8, 5);
205
-			$patchRelease = substr($versionString, 13, 6);
206
-
207
-			if(($majorVersion === '1.0.1' && ord($patchRelease) < ord('d')) ||
208
-				($majorVersion === '1.0.2' && ord($patchRelease) < ord('b'))) {
209
-				return (string) $this->l10n->t('cURL is using an outdated %s version (%s). Please update your operating system or features such as %s will not work reliably.', ['OpenSSL', $versionString, $features]);
210
-			}
211
-		}
212
-
213
-		// Check if NSS and perform heuristic check
214
-		if(strpos($versionString, 'NSS/') === 0) {
215
-			try {
216
-				$firstClient = $this->clientService->newClient();
217
-				$firstClient->get('https://www.owncloud.org/');
218
-
219
-				$secondClient = $this->clientService->newClient();
220
-				$secondClient->get('https://owncloud.org/');
221
-			} catch (ClientException $e) {
222
-				if($e->getResponse()->getStatusCode() === 400) {
223
-					return (string) $this->l10n->t('cURL is using an outdated %s version (%s). Please update your operating system or features such as %s will not work reliably.', ['NSS', $versionString, $features]);
224
-				}
225
-			}
226
-		}
227
-
228
-		return '';
229
-	}
230
-
231
-	/**
232
-	 * Whether the version is outdated
233
-	 *
234
-	 * @return bool
235
-	 */
236
-	protected function isPhpOutdated() {
237
-		if (version_compare(PHP_VERSION, '5.5.0') === -1) {
238
-			return true;
239
-		}
240
-
241
-		return false;
242
-	}
243
-
244
-	/**
245
-	 * Whether the php version is still supported (at time of release)
246
-	 * according to: https://secure.php.net/supported-versions.php
247
-	 *
248
-	 * @return array
249
-	 */
250
-	private function isPhpSupported() {
251
-		return ['eol' => $this->isPhpOutdated(), 'version' => PHP_VERSION];
252
-	}
253
-
254
-	/**
255
-	 * Check if the reverse proxy configuration is working as expected
256
-	 *
257
-	 * @return bool
258
-	 */
259
-	private function forwardedForHeadersWorking() {
260
-		$trustedProxies = $this->config->getSystemValue('trusted_proxies', []);
261
-		$remoteAddress = $this->request->getRemoteAddress();
262
-
263
-		if (is_array($trustedProxies) && in_array($remoteAddress, $trustedProxies)) {
264
-			return false;
265
-		}
266
-
267
-		// either not enabled or working correctly
268
-		return true;
269
-	}
270
-
271
-	/**
272
-	 * Checks if the correct memcache module for PHP is installed. Only
273
-	 * fails if memcached is configured and the working module is not installed.
274
-	 *
275
-	 * @return bool
276
-	 */
277
-	private function isCorrectMemcachedPHPModuleInstalled() {
278
-		if ($this->config->getSystemValue('memcache.distributed', null) !== '\OC\Memcache\Memcached') {
279
-			return true;
280
-		}
281
-
282
-		// there are two different memcached modules for PHP
283
-		// we only support memcached and not memcache
284
-		// https://code.google.com/p/memcached/wiki/PHPClientComparison
285
-		return !(!extension_loaded('memcached') && extension_loaded('memcache'));
286
-	}
287
-
288
-	/**
289
-	 * Checks if set_time_limit is not disabled.
290
-	 *
291
-	 * @return bool
292
-	 */
293
-	private function isSettimelimitAvailable() {
294
-		if (function_exists('set_time_limit')
295
-			&& strpos(@ini_get('disable_functions'), 'set_time_limit') === false) {
296
-			return true;
297
-		}
298
-
299
-		return false;
300
-	}
301
-
302
-	/**
303
-	 * @return RedirectResponse
304
-	 */
305
-	public function rescanFailedIntegrityCheck() {
306
-		$this->checker->runInstanceVerification();
307
-		return new RedirectResponse(
308
-			$this->urlGenerator->linkToRoute('settings.AdminSettings.index')
309
-		);
310
-	}
311
-
312
-	/**
313
-	 * @NoCSRFRequired
314
-	 * @return DataResponse
315
-	 */
316
-	public function getFailedIntegrityCheckFiles() {
317
-		if(!$this->checker->isCodeCheckEnforced()) {
318
-			return new DataDisplayResponse('Integrity checker has been disabled. Integrity cannot be verified.');
319
-		}
320
-
321
-		$completeResults = $this->checker->getResults();
322
-
323
-		if(!empty($completeResults)) {
324
-			$formattedTextResponse = 'Technical information
49
+    /** @var IConfig */
50
+    private $config;
51
+    /** @var IClientService */
52
+    private $clientService;
53
+    /** @var \OC_Util */
54
+    private $util;
55
+    /** @var IURLGenerator */
56
+    private $urlGenerator;
57
+    /** @var IL10N */
58
+    private $l10n;
59
+    /** @var Checker */
60
+    private $checker;
61
+    /** @var ILogger */
62
+    private $logger;
63
+
64
+    /**
65
+     * @param string $AppName
66
+     * @param IRequest $request
67
+     * @param IConfig $config
68
+     * @param IClientService $clientService
69
+     * @param IURLGenerator $urlGenerator
70
+     * @param \OC_Util $util
71
+     * @param IL10N $l10n
72
+     * @param Checker $checker
73
+     * @param ILogger $logger
74
+     */
75
+    public function __construct($AppName,
76
+                                IRequest $request,
77
+                                IConfig $config,
78
+                                IClientService $clientService,
79
+                                IURLGenerator $urlGenerator,
80
+                                \OC_Util $util,
81
+                                IL10N $l10n,
82
+                                Checker $checker,
83
+                                ILogger $logger) {
84
+        parent::__construct($AppName, $request);
85
+        $this->config = $config;
86
+        $this->clientService = $clientService;
87
+        $this->util = $util;
88
+        $this->urlGenerator = $urlGenerator;
89
+        $this->l10n = $l10n;
90
+        $this->checker = $checker;
91
+        $this->logger = $logger;
92
+    }
93
+
94
+    /**
95
+     * Checks if the ownCloud server can connect to the internet using HTTPS and HTTP
96
+     * @return bool
97
+     */
98
+    private function isInternetConnectionWorking() {
99
+        if ($this->config->getSystemValue('has_internet_connection', true) === false) {
100
+            return false;
101
+        }
102
+
103
+        $siteArray = ['www.nextcloud.com',
104
+                        'www.google.com',
105
+                        'www.github.com'];
106
+
107
+        foreach($siteArray as $site) {
108
+            if ($this->isSiteReachable($site)) {
109
+                return true;
110
+            }
111
+        }
112
+        return false;
113
+    }
114
+
115
+    /**
116
+     * Chceks if the ownCloud server can connect to a specific URL using both HTTPS and HTTP
117
+     * @return bool
118
+     */
119
+    private function isSiteReachable($sitename) {
120
+        $httpSiteName = 'http://' . $sitename . '/';
121
+        $httpsSiteName = 'https://' . $sitename . '/';
122
+
123
+        try {
124
+            $client = $this->clientService->newClient();
125
+            $client->get($httpSiteName);
126
+            $client->get($httpsSiteName);
127
+        } catch (\Exception $e) {
128
+            $this->logger->logException($e, ['app' => 'internet_connection_check']);
129
+            return false;
130
+        }
131
+        return true;
132
+    }
133
+
134
+    /**
135
+     * Checks whether a local memcache is installed or not
136
+     * @return bool
137
+     */
138
+    private function isMemcacheConfigured() {
139
+        return $this->config->getSystemValue('memcache.local', null) !== null;
140
+    }
141
+
142
+    /**
143
+     * Whether /dev/urandom is available to the PHP controller
144
+     *
145
+     * @return bool
146
+     */
147
+    private function isUrandomAvailable() {
148
+        if(@file_exists('/dev/urandom')) {
149
+            $file = fopen('/dev/urandom', 'rb');
150
+            if($file) {
151
+                fclose($file);
152
+                return true;
153
+            }
154
+        }
155
+
156
+        return false;
157
+    }
158
+
159
+    /**
160
+     * Public for the sake of unit-testing
161
+     *
162
+     * @return array
163
+     */
164
+    protected function getCurlVersion() {
165
+        return curl_version();
166
+    }
167
+
168
+    /**
169
+     * Check if the used  SSL lib is outdated. Older OpenSSL and NSS versions do
170
+     * have multiple bugs which likely lead to problems in combination with
171
+     * functionality required by ownCloud such as SNI.
172
+     *
173
+     * @link https://github.com/owncloud/core/issues/17446#issuecomment-122877546
174
+     * @link https://bugzilla.redhat.com/show_bug.cgi?id=1241172
175
+     * @return string
176
+     */
177
+    private function isUsedTlsLibOutdated() {
178
+        // Don't run check when:
179
+        // 1. Server has `has_internet_connection` set to false
180
+        // 2. AppStore AND S2S is disabled
181
+        if(!$this->config->getSystemValue('has_internet_connection', true)) {
182
+            return '';
183
+        }
184
+        if(!$this->config->getSystemValue('appstoreenabled', true)
185
+            && $this->config->getAppValue('files_sharing', 'outgoing_server2server_share_enabled', 'yes') === 'no'
186
+            && $this->config->getAppValue('files_sharing', 'incoming_server2server_share_enabled', 'yes') === 'no') {
187
+            return '';
188
+        }
189
+
190
+        $versionString = $this->getCurlVersion();
191
+        if(isset($versionString['ssl_version'])) {
192
+            $versionString = $versionString['ssl_version'];
193
+        } else {
194
+            return '';
195
+        }
196
+
197
+        $features = (string)$this->l10n->t('installing and updating apps via the app store or Federated Cloud Sharing');
198
+        if(!$this->config->getSystemValue('appstoreenabled', true)) {
199
+            $features = (string)$this->l10n->t('Federated Cloud Sharing');
200
+        }
201
+
202
+        // Check if at least OpenSSL after 1.01d or 1.0.2b
203
+        if(strpos($versionString, 'OpenSSL/') === 0) {
204
+            $majorVersion = substr($versionString, 8, 5);
205
+            $patchRelease = substr($versionString, 13, 6);
206
+
207
+            if(($majorVersion === '1.0.1' && ord($patchRelease) < ord('d')) ||
208
+                ($majorVersion === '1.0.2' && ord($patchRelease) < ord('b'))) {
209
+                return (string) $this->l10n->t('cURL is using an outdated %s version (%s). Please update your operating system or features such as %s will not work reliably.', ['OpenSSL', $versionString, $features]);
210
+            }
211
+        }
212
+
213
+        // Check if NSS and perform heuristic check
214
+        if(strpos($versionString, 'NSS/') === 0) {
215
+            try {
216
+                $firstClient = $this->clientService->newClient();
217
+                $firstClient->get('https://www.owncloud.org/');
218
+
219
+                $secondClient = $this->clientService->newClient();
220
+                $secondClient->get('https://owncloud.org/');
221
+            } catch (ClientException $e) {
222
+                if($e->getResponse()->getStatusCode() === 400) {
223
+                    return (string) $this->l10n->t('cURL is using an outdated %s version (%s). Please update your operating system or features such as %s will not work reliably.', ['NSS', $versionString, $features]);
224
+                }
225
+            }
226
+        }
227
+
228
+        return '';
229
+    }
230
+
231
+    /**
232
+     * Whether the version is outdated
233
+     *
234
+     * @return bool
235
+     */
236
+    protected function isPhpOutdated() {
237
+        if (version_compare(PHP_VERSION, '5.5.0') === -1) {
238
+            return true;
239
+        }
240
+
241
+        return false;
242
+    }
243
+
244
+    /**
245
+     * Whether the php version is still supported (at time of release)
246
+     * according to: https://secure.php.net/supported-versions.php
247
+     *
248
+     * @return array
249
+     */
250
+    private function isPhpSupported() {
251
+        return ['eol' => $this->isPhpOutdated(), 'version' => PHP_VERSION];
252
+    }
253
+
254
+    /**
255
+     * Check if the reverse proxy configuration is working as expected
256
+     *
257
+     * @return bool
258
+     */
259
+    private function forwardedForHeadersWorking() {
260
+        $trustedProxies = $this->config->getSystemValue('trusted_proxies', []);
261
+        $remoteAddress = $this->request->getRemoteAddress();
262
+
263
+        if (is_array($trustedProxies) && in_array($remoteAddress, $trustedProxies)) {
264
+            return false;
265
+        }
266
+
267
+        // either not enabled or working correctly
268
+        return true;
269
+    }
270
+
271
+    /**
272
+     * Checks if the correct memcache module for PHP is installed. Only
273
+     * fails if memcached is configured and the working module is not installed.
274
+     *
275
+     * @return bool
276
+     */
277
+    private function isCorrectMemcachedPHPModuleInstalled() {
278
+        if ($this->config->getSystemValue('memcache.distributed', null) !== '\OC\Memcache\Memcached') {
279
+            return true;
280
+        }
281
+
282
+        // there are two different memcached modules for PHP
283
+        // we only support memcached and not memcache
284
+        // https://code.google.com/p/memcached/wiki/PHPClientComparison
285
+        return !(!extension_loaded('memcached') && extension_loaded('memcache'));
286
+    }
287
+
288
+    /**
289
+     * Checks if set_time_limit is not disabled.
290
+     *
291
+     * @return bool
292
+     */
293
+    private function isSettimelimitAvailable() {
294
+        if (function_exists('set_time_limit')
295
+            && strpos(@ini_get('disable_functions'), 'set_time_limit') === false) {
296
+            return true;
297
+        }
298
+
299
+        return false;
300
+    }
301
+
302
+    /**
303
+     * @return RedirectResponse
304
+     */
305
+    public function rescanFailedIntegrityCheck() {
306
+        $this->checker->runInstanceVerification();
307
+        return new RedirectResponse(
308
+            $this->urlGenerator->linkToRoute('settings.AdminSettings.index')
309
+        );
310
+    }
311
+
312
+    /**
313
+     * @NoCSRFRequired
314
+     * @return DataResponse
315
+     */
316
+    public function getFailedIntegrityCheckFiles() {
317
+        if(!$this->checker->isCodeCheckEnforced()) {
318
+            return new DataDisplayResponse('Integrity checker has been disabled. Integrity cannot be verified.');
319
+        }
320
+
321
+        $completeResults = $this->checker->getResults();
322
+
323
+        if(!empty($completeResults)) {
324
+            $formattedTextResponse = 'Technical information
325 325
 =====================
326 326
 The following list covers which files have failed the integrity check. Please read
327 327
 the previous linked documentation to learn more about the errors and how to fix
@@ -330,103 +330,103 @@  discard block
 block discarded – undo
330 330
 Results
331 331
 =======
332 332
 ';
333
-			foreach($completeResults as $context => $contextResult) {
334
-				$formattedTextResponse .= "- $context\n";
335
-
336
-				foreach($contextResult as $category => $result) {
337
-					$formattedTextResponse .= "\t- $category\n";
338
-					if($category !== 'EXCEPTION') {
339
-						foreach ($result as $key => $results) {
340
-							$formattedTextResponse .= "\t\t- $key\n";
341
-						}
342
-					} else {
343
-						foreach ($result as $key => $results) {
344
-							$formattedTextResponse .= "\t\t- $results\n";
345
-						}
346
-					}
347
-
348
-				}
349
-			}
350
-
351
-			$formattedTextResponse .= '
333
+            foreach($completeResults as $context => $contextResult) {
334
+                $formattedTextResponse .= "- $context\n";
335
+
336
+                foreach($contextResult as $category => $result) {
337
+                    $formattedTextResponse .= "\t- $category\n";
338
+                    if($category !== 'EXCEPTION') {
339
+                        foreach ($result as $key => $results) {
340
+                            $formattedTextResponse .= "\t\t- $key\n";
341
+                        }
342
+                    } else {
343
+                        foreach ($result as $key => $results) {
344
+                            $formattedTextResponse .= "\t\t- $results\n";
345
+                        }
346
+                    }
347
+
348
+                }
349
+            }
350
+
351
+            $formattedTextResponse .= '
352 352
 Raw output
353 353
 ==========
354 354
 ';
355
-			$formattedTextResponse .= print_r($completeResults, true);
356
-		} else {
357
-			$formattedTextResponse = 'No errors have been found.';
358
-		}
359
-
360
-
361
-		$response = new DataDisplayResponse(
362
-			$formattedTextResponse,
363
-			Http::STATUS_OK,
364
-			[
365
-				'Content-Type' => 'text/plain',
366
-			]
367
-		);
368
-
369
-		return $response;
370
-	}
371
-
372
-	/**
373
-	 * Checks whether a PHP opcache is properly set up
374
-	 * @return bool
375
-	 */
376
-	protected function isOpcacheProperlySetup() {
377
-		$iniWrapper = new IniGetWrapper();
378
-
379
-		$isOpcacheProperlySetUp = true;
380
-
381
-		if(!$iniWrapper->getBool('opcache.enable')) {
382
-			$isOpcacheProperlySetUp = false;
383
-		}
384
-
385
-		if(!$iniWrapper->getBool('opcache.save_comments')) {
386
-			$isOpcacheProperlySetUp = false;
387
-		}
388
-
389
-		if(!$iniWrapper->getBool('opcache.enable_cli')) {
390
-			$isOpcacheProperlySetUp = false;
391
-		}
392
-
393
-		if($iniWrapper->getNumeric('opcache.max_accelerated_files') < 10000) {
394
-			$isOpcacheProperlySetUp = false;
395
-		}
396
-
397
-		if($iniWrapper->getNumeric('opcache.memory_consumption') < 128) {
398
-			$isOpcacheProperlySetUp = false;
399
-		}
400
-
401
-		if($iniWrapper->getNumeric('opcache.interned_strings_buffer') < 8) {
402
-			$isOpcacheProperlySetUp = false;
403
-		}
404
-
405
-		return $isOpcacheProperlySetUp;
406
-	}
407
-
408
-	/**
409
-	 * @return DataResponse
410
-	 */
411
-	public function check() {
412
-		return new DataResponse(
413
-			[
414
-				'serverHasInternetConnection' => $this->isInternetConnectionWorking(),
415
-				'isMemcacheConfigured' => $this->isMemcacheConfigured(),
416
-				'memcacheDocs' => $this->urlGenerator->linkToDocs('admin-performance'),
417
-				'isUrandomAvailable' => $this->isUrandomAvailable(),
418
-				'securityDocs' => $this->urlGenerator->linkToDocs('admin-security'),
419
-				'isUsedTlsLibOutdated' => $this->isUsedTlsLibOutdated(),
420
-				'phpSupported' => $this->isPhpSupported(),
421
-				'forwardedForHeadersWorking' => $this->forwardedForHeadersWorking(),
422
-				'reverseProxyDocs' => $this->urlGenerator->linkToDocs('admin-reverse-proxy'),
423
-				'isCorrectMemcachedPHPModuleInstalled' => $this->isCorrectMemcachedPHPModuleInstalled(),
424
-				'hasPassedCodeIntegrityCheck' => $this->checker->hasPassedCheck(),
425
-				'codeIntegrityCheckerDocumentation' => $this->urlGenerator->linkToDocs('admin-code-integrity'),
426
-				'isOpcacheProperlySetup' => $this->isOpcacheProperlySetup(),
427
-				'phpOpcacheDocumentation' => $this->urlGenerator->linkToDocs('admin-php-opcache'),
428
-				'isSettimelimitAvailable' => $this->isSettimelimitAvailable(),
429
-			]
430
-		);
431
-	}
355
+            $formattedTextResponse .= print_r($completeResults, true);
356
+        } else {
357
+            $formattedTextResponse = 'No errors have been found.';
358
+        }
359
+
360
+
361
+        $response = new DataDisplayResponse(
362
+            $formattedTextResponse,
363
+            Http::STATUS_OK,
364
+            [
365
+                'Content-Type' => 'text/plain',
366
+            ]
367
+        );
368
+
369
+        return $response;
370
+    }
371
+
372
+    /**
373
+     * Checks whether a PHP opcache is properly set up
374
+     * @return bool
375
+     */
376
+    protected function isOpcacheProperlySetup() {
377
+        $iniWrapper = new IniGetWrapper();
378
+
379
+        $isOpcacheProperlySetUp = true;
380
+
381
+        if(!$iniWrapper->getBool('opcache.enable')) {
382
+            $isOpcacheProperlySetUp = false;
383
+        }
384
+
385
+        if(!$iniWrapper->getBool('opcache.save_comments')) {
386
+            $isOpcacheProperlySetUp = false;
387
+        }
388
+
389
+        if(!$iniWrapper->getBool('opcache.enable_cli')) {
390
+            $isOpcacheProperlySetUp = false;
391
+        }
392
+
393
+        if($iniWrapper->getNumeric('opcache.max_accelerated_files') < 10000) {
394
+            $isOpcacheProperlySetUp = false;
395
+        }
396
+
397
+        if($iniWrapper->getNumeric('opcache.memory_consumption') < 128) {
398
+            $isOpcacheProperlySetUp = false;
399
+        }
400
+
401
+        if($iniWrapper->getNumeric('opcache.interned_strings_buffer') < 8) {
402
+            $isOpcacheProperlySetUp = false;
403
+        }
404
+
405
+        return $isOpcacheProperlySetUp;
406
+    }
407
+
408
+    /**
409
+     * @return DataResponse
410
+     */
411
+    public function check() {
412
+        return new DataResponse(
413
+            [
414
+                'serverHasInternetConnection' => $this->isInternetConnectionWorking(),
415
+                'isMemcacheConfigured' => $this->isMemcacheConfigured(),
416
+                'memcacheDocs' => $this->urlGenerator->linkToDocs('admin-performance'),
417
+                'isUrandomAvailable' => $this->isUrandomAvailable(),
418
+                'securityDocs' => $this->urlGenerator->linkToDocs('admin-security'),
419
+                'isUsedTlsLibOutdated' => $this->isUsedTlsLibOutdated(),
420
+                'phpSupported' => $this->isPhpSupported(),
421
+                'forwardedForHeadersWorking' => $this->forwardedForHeadersWorking(),
422
+                'reverseProxyDocs' => $this->urlGenerator->linkToDocs('admin-reverse-proxy'),
423
+                'isCorrectMemcachedPHPModuleInstalled' => $this->isCorrectMemcachedPHPModuleInstalled(),
424
+                'hasPassedCodeIntegrityCheck' => $this->checker->hasPassedCheck(),
425
+                'codeIntegrityCheckerDocumentation' => $this->urlGenerator->linkToDocs('admin-code-integrity'),
426
+                'isOpcacheProperlySetup' => $this->isOpcacheProperlySetup(),
427
+                'phpOpcacheDocumentation' => $this->urlGenerator->linkToDocs('admin-php-opcache'),
428
+                'isSettimelimitAvailable' => $this->isSettimelimitAvailable(),
429
+            ]
430
+        );
431
+    }
432 432
 }
Please login to merge, or discard this patch.
apps/user_ldap/lib/Wizard.php 3 patches
Doc Comments   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -1104,7 +1104,7 @@
 block discarded – undo
1104 1104
 	}
1105 1105
 
1106 1106
 	/**
1107
-	 * @param array $reqs
1107
+	 * @param string[] $reqs
1108 1108
 	 * @return bool
1109 1109
 	 */
1110 1110
 	private function checkRequirements($reqs) {
Please login to merge, or discard this patch.
Spacing   +151 added lines, -151 removed lines patch added patch discarded remove patch
@@ -68,7 +68,7 @@  discard block
 block discarded – undo
68 68
 	public function __construct(Configuration $configuration, ILDAPWrapper $ldap, Access $access) {
69 69
 		parent::__construct($ldap);
70 70
 		$this->configuration = $configuration;
71
-		if(is_null(Wizard::$l)) {
71
+		if (is_null(Wizard::$l)) {
72 72
 			Wizard::$l = \OC::$server->getL10N('user_ldap');
73 73
 		}
74 74
 		$this->access = $access;
@@ -76,7 +76,7 @@  discard block
 block discarded – undo
76 76
 	}
77 77
 
78 78
 	public function  __destruct() {
79
-		if($this->result->hasChanges()) {
79
+		if ($this->result->hasChanges()) {
80 80
 			$this->configuration->saveConfiguration();
81 81
 		}
82 82
 	}
@@ -91,18 +91,18 @@  discard block
 block discarded – undo
91 91
 	 */
92 92
 	public function countEntries($filter, $type) {
93 93
 		$reqs = array('ldapHost', 'ldapPort', 'ldapBase');
94
-		if($type === 'users') {
94
+		if ($type === 'users') {
95 95
 			$reqs[] = 'ldapUserFilter';
96 96
 		}
97
-		if(!$this->checkRequirements($reqs)) {
97
+		if (!$this->checkRequirements($reqs)) {
98 98
 			throw new \Exception('Requirements not met', 400);
99 99
 		}
100 100
 
101 101
 		$attr = array('dn'); // default
102 102
 		$limit = 1001;
103
-		if($type === 'groups') {
104
-			$result =  $this->access->countGroups($filter, $attr, $limit);
105
-		} else if($type === 'users') {
103
+		if ($type === 'groups') {
104
+			$result = $this->access->countGroups($filter, $attr, $limit);
105
+		} else if ($type === 'users') {
106 106
 			$result = $this->access->countUsers($filter, $attr, $limit);
107 107
 		} else if ($type === 'objects') {
108 108
 			$result = $this->access->countObjects($limit);
@@ -122,7 +122,7 @@  discard block
 block discarded – undo
122 122
 	 */
123 123
 	private function formatCountResult($count) {
124 124
 		$formatted = ($count !== false) ? $count : 0;
125
-		if($formatted > 1000) {
125
+		if ($formatted > 1000) {
126 126
 			$formatted = '> 1000';
127 127
 		}
128 128
 		return $formatted;
@@ -131,7 +131,7 @@  discard block
 block discarded – undo
131 131
 	public function countGroups() {
132 132
 		$filter = $this->configuration->ldapGroupFilter;
133 133
 
134
-		if(empty($filter)) {
134
+		if (empty($filter)) {
135 135
 			$output = self::$l->n('%s group found', '%s groups found', 0, array(0));
136 136
 			$this->result->addChange('ldap_group_count', $output);
137 137
 			return $this->result;
@@ -141,7 +141,7 @@  discard block
 block discarded – undo
141 141
 			$groupsTotal = $this->formatCountResult($this->countEntries($filter, 'groups'));
142 142
 		} catch (\Exception $e) {
143 143
 			//400 can be ignored, 500 is forwarded
144
-			if($e->getCode() === 500) {
144
+			if ($e->getCode() === 500) {
145 145
 				throw $e;
146 146
 			}
147 147
 			return false;
@@ -173,7 +173,7 @@  discard block
 block discarded – undo
173 173
 	public function countInBaseDN() {
174 174
 		// we don't need to provide a filter in this case
175 175
 		$total = $this->countEntries(null, 'objects');
176
-		if($total === false) {
176
+		if ($total === false) {
177 177
 			throw new \Exception('invalid results received');
178 178
 		}
179 179
 		$this->result->addChange('ldap_test_base', $total);
@@ -187,7 +187,7 @@  discard block
 block discarded – undo
187 187
 	 * @return int|bool
188 188
 	 */
189 189
 	public function countUsersWithAttribute($attr, $existsCheck = false) {
190
-		if(!$this->checkRequirements(array('ldapHost',
190
+		if (!$this->checkRequirements(array('ldapHost',
191 191
 										   'ldapPort',
192 192
 										   'ldapBase',
193 193
 										   'ldapUserFilter',
@@ -197,7 +197,7 @@  discard block
 block discarded – undo
197 197
 
198 198
 		$filter = $this->access->combineFilterWithAnd(array(
199 199
 			$this->configuration->ldapUserFilter,
200
-			$attr . '=*'
200
+			$attr.'=*'
201 201
 		));
202 202
 
203 203
 		$limit = ($existsCheck === false) ? null : 1;
@@ -212,7 +212,7 @@  discard block
 block discarded – undo
212 212
 	 * @throws \Exception
213 213
 	 */
214 214
 	public function detectUserDisplayNameAttribute() {
215
-		if(!$this->checkRequirements(array('ldapHost',
215
+		if (!$this->checkRequirements(array('ldapHost',
216 216
 										'ldapPort',
217 217
 										'ldapBase',
218 218
 										'ldapUserFilter',
@@ -225,7 +225,7 @@  discard block
 block discarded – undo
225 225
 			// most likely not the default value with upper case N,
226 226
 			// verify it still produces a result
227 227
 			$count = intval($this->countUsersWithAttribute($attr, true));
228
-			if($count > 0) {
228
+			if ($count > 0) {
229 229
 				//no change, but we sent it back to make sure the user interface
230 230
 				//is still correct, even if the ajax call was cancelled meanwhile
231 231
 				$this->result->addChange('ldap_display_name', $attr);
@@ -238,7 +238,7 @@  discard block
 block discarded – undo
238 238
 		foreach ($displayNameAttrs as $attr) {
239 239
 			$count = intval($this->countUsersWithAttribute($attr, true));
240 240
 
241
-			if($count > 0) {
241
+			if ($count > 0) {
242 242
 				$this->applyFind('ldap_display_name', $attr);
243 243
 				return $this->result;
244 244
 			}
@@ -254,7 +254,7 @@  discard block
 block discarded – undo
254 254
 	 * @return WizardResult|bool
255 255
 	 */
256 256
 	public function detectEmailAttribute() {
257
-		if(!$this->checkRequirements(array('ldapHost',
257
+		if (!$this->checkRequirements(array('ldapHost',
258 258
 										   'ldapPort',
259 259
 										   'ldapBase',
260 260
 										   'ldapUserFilter',
@@ -265,7 +265,7 @@  discard block
 block discarded – undo
265 265
 		$attr = $this->configuration->ldapEmailAttribute;
266 266
 		if ($attr !== '') {
267 267
 			$count = intval($this->countUsersWithAttribute($attr, true));
268
-			if($count > 0) {
268
+			if ($count > 0) {
269 269
 				return false;
270 270
 			}
271 271
 			$writeLog = true;
@@ -276,19 +276,19 @@  discard block
 block discarded – undo
276 276
 		$emailAttributes = array('mail', 'mailPrimaryAddress');
277 277
 		$winner = '';
278 278
 		$maxUsers = 0;
279
-		foreach($emailAttributes as $attr) {
279
+		foreach ($emailAttributes as $attr) {
280 280
 			$count = $this->countUsersWithAttribute($attr);
281
-			if($count > $maxUsers) {
281
+			if ($count > $maxUsers) {
282 282
 				$maxUsers = $count;
283 283
 				$winner = $attr;
284 284
 			}
285 285
 		}
286 286
 
287
-		if($winner !== '') {
287
+		if ($winner !== '') {
288 288
 			$this->applyFind('ldap_email_attr', $winner);
289
-			if($writeLog) {
290
-				\OCP\Util::writeLog('user_ldap', 'The mail attribute has ' .
291
-					'automatically been reset, because the original value ' .
289
+			if ($writeLog) {
290
+				\OCP\Util::writeLog('user_ldap', 'The mail attribute has '.
291
+					'automatically been reset, because the original value '.
292 292
 					'did not return any results.', \OCP\Util::INFO);
293 293
 			}
294 294
 		}
@@ -301,7 +301,7 @@  discard block
 block discarded – undo
301 301
 	 * @throws \Exception
302 302
 	 */
303 303
 	public function determineAttributes() {
304
-		if(!$this->checkRequirements(array('ldapHost',
304
+		if (!$this->checkRequirements(array('ldapHost',
305 305
 										   'ldapPort',
306 306
 										   'ldapBase',
307 307
 										   'ldapUserFilter',
@@ -317,7 +317,7 @@  discard block
 block discarded – undo
317 317
 		$this->result->addOptions('ldap_loginfilter_attributes', $attributes);
318 318
 
319 319
 		$selected = $this->configuration->ldapLoginFilterAttributes;
320
-		if(is_array($selected) && !empty($selected)) {
320
+		if (is_array($selected) && !empty($selected)) {
321 321
 			$this->result->addChange('ldap_loginfilter_attributes', $selected);
322 322
 		}
323 323
 
@@ -330,7 +330,7 @@  discard block
 block discarded – undo
330 330
 	 * @throws \Exception
331 331
 	 */
332 332
 	private function getUserAttributes() {
333
-		if(!$this->checkRequirements(array('ldapHost',
333
+		if (!$this->checkRequirements(array('ldapHost',
334 334
 										   'ldapPort',
335 335
 										   'ldapBase',
336 336
 										   'ldapUserFilter',
@@ -338,20 +338,20 @@  discard block
 block discarded – undo
338 338
 			return  false;
339 339
 		}
340 340
 		$cr = $this->getConnection();
341
-		if(!$cr) {
341
+		if (!$cr) {
342 342
 			throw new \Exception('Could not connect to LDAP');
343 343
 		}
344 344
 
345 345
 		$base = $this->configuration->ldapBase[0];
346 346
 		$filter = $this->configuration->ldapUserFilter;
347 347
 		$rr = $this->ldap->search($cr, $base, $filter, array(), 1, 1);
348
-		if(!$this->ldap->isResource($rr)) {
348
+		if (!$this->ldap->isResource($rr)) {
349 349
 			return false;
350 350
 		}
351 351
 		$er = $this->ldap->firstEntry($cr, $rr);
352 352
 		$attributes = $this->ldap->getAttributes($cr, $er);
353 353
 		$pureAttributes = array();
354
-		for($i = 0; $i < $attributes['count']; $i++) {
354
+		for ($i = 0; $i < $attributes['count']; $i++) {
355 355
 			$pureAttributes[] = $attributes[$i];
356 356
 		}
357 357
 
@@ -386,23 +386,23 @@  discard block
 block discarded – undo
386 386
 	 * @throws \Exception
387 387
 	 */
388 388
 	private function determineGroups($dbKey, $confKey, $testMemberOf = true) {
389
-		if(!$this->checkRequirements(array('ldapHost',
389
+		if (!$this->checkRequirements(array('ldapHost',
390 390
 										   'ldapPort',
391 391
 										   'ldapBase',
392 392
 										   ))) {
393 393
 			return  false;
394 394
 		}
395 395
 		$cr = $this->getConnection();
396
-		if(!$cr) {
396
+		if (!$cr) {
397 397
 			throw new \Exception('Could not connect to LDAP');
398 398
 		}
399 399
 
400 400
 		$this->fetchGroups($dbKey, $confKey);
401 401
 
402
-		if($testMemberOf) {
402
+		if ($testMemberOf) {
403 403
 			$this->configuration->hasMemberOfFilterSupport = $this->testMemberOf();
404 404
 			$this->result->markChange();
405
-			if(!$this->configuration->hasMemberOfFilterSupport) {
405
+			if (!$this->configuration->hasMemberOfFilterSupport) {
406 406
 				throw new \Exception('memberOf is not supported by the server');
407 407
 			}
408 408
 		}
@@ -422,7 +422,7 @@  discard block
 block discarded – undo
422 422
 		$obclasses = array('posixGroup', 'group', 'zimbraDistributionList', 'groupOfNames');
423 423
 
424 424
 		$filterParts = array();
425
-		foreach($obclasses as $obclass) {
425
+		foreach ($obclasses as $obclass) {
426 426
 			$filterParts[] = 'objectclass='.$obclass;
427 427
 		}
428 428
 		//we filter for everything
@@ -439,8 +439,8 @@  discard block
 block discarded – undo
439 439
 			// we need to request dn additionally here, otherwise memberOf
440 440
 			// detection will fail later
441 441
 			$result = $this->access->searchGroups($filter, array('cn', 'dn'), $limit, $offset);
442
-			foreach($result as $item) {
443
-				if(!isset($item['cn']) && !is_array($item['cn']) && !isset($item['cn'][0])) {
442
+			foreach ($result as $item) {
443
+				if (!isset($item['cn']) && !is_array($item['cn']) && !isset($item['cn'][0])) {
444 444
 					// just in case - no issue known
445 445
 					continue;
446 446
 				}
@@ -450,7 +450,7 @@  discard block
 block discarded – undo
450 450
 			$offset += $limit;
451 451
 		} while ($this->access->hasMoreResults());
452 452
 
453
-		if(count($groupNames) > 0) {
453
+		if (count($groupNames) > 0) {
454 454
 			natsort($groupNames);
455 455
 			$this->result->addOptions($dbKey, array_values($groupNames));
456 456
 		} else {
@@ -458,7 +458,7 @@  discard block
 block discarded – undo
458 458
 		}
459 459
 
460 460
 		$setFeatures = $this->configuration->$confKey;
461
-		if(is_array($setFeatures) && !empty($setFeatures)) {
461
+		if (is_array($setFeatures) && !empty($setFeatures)) {
462 462
 			//something is already configured? pre-select it.
463 463
 			$this->result->addChange($dbKey, $setFeatures);
464 464
 		}
@@ -466,14 +466,14 @@  discard block
 block discarded – undo
466 466
 	}
467 467
 
468 468
 	public function determineGroupMemberAssoc() {
469
-		if(!$this->checkRequirements(array('ldapHost',
469
+		if (!$this->checkRequirements(array('ldapHost',
470 470
 										   'ldapPort',
471 471
 										   'ldapGroupFilter',
472 472
 										   ))) {
473 473
 			return  false;
474 474
 		}
475 475
 		$attribute = $this->detectGroupMemberAssoc();
476
-		if($attribute === false) {
476
+		if ($attribute === false) {
477 477
 			return false;
478 478
 		}
479 479
 		$this->configuration->setConfiguration(array('ldapGroupMemberAssocAttr' => $attribute));
@@ -488,14 +488,14 @@  discard block
 block discarded – undo
488 488
 	 * @throws \Exception
489 489
 	 */
490 490
 	public function determineGroupObjectClasses() {
491
-		if(!$this->checkRequirements(array('ldapHost',
491
+		if (!$this->checkRequirements(array('ldapHost',
492 492
 										   'ldapPort',
493 493
 										   'ldapBase',
494 494
 										   ))) {
495 495
 			return  false;
496 496
 		}
497 497
 		$cr = $this->getConnection();
498
-		if(!$cr) {
498
+		if (!$cr) {
499 499
 			throw new \Exception('Could not connect to LDAP');
500 500
 		}
501 501
 
@@ -515,14 +515,14 @@  discard block
 block discarded – undo
515 515
 	 * @throws \Exception
516 516
 	 */
517 517
 	public function determineUserObjectClasses() {
518
-		if(!$this->checkRequirements(array('ldapHost',
518
+		if (!$this->checkRequirements(array('ldapHost',
519 519
 										   'ldapPort',
520 520
 										   'ldapBase',
521 521
 										   ))) {
522 522
 			return  false;
523 523
 		}
524 524
 		$cr = $this->getConnection();
525
-		if(!$cr) {
525
+		if (!$cr) {
526 526
 			throw new \Exception('Could not connect to LDAP');
527 527
 		}
528 528
 
@@ -545,7 +545,7 @@  discard block
 block discarded – undo
545 545
 	 * @throws \Exception
546 546
 	 */
547 547
 	public function getGroupFilter() {
548
-		if(!$this->checkRequirements(array('ldapHost',
548
+		if (!$this->checkRequirements(array('ldapHost',
549 549
 										   'ldapPort',
550 550
 										   'ldapBase',
551 551
 										   ))) {
@@ -569,7 +569,7 @@  discard block
 block discarded – undo
569 569
 	 * @throws \Exception
570 570
 	 */
571 571
 	public function getUserListFilter() {
572
-		if(!$this->checkRequirements(array('ldapHost',
572
+		if (!$this->checkRequirements(array('ldapHost',
573 573
 										   'ldapPort',
574 574
 										   'ldapBase',
575 575
 										   ))) {
@@ -582,7 +582,7 @@  discard block
 block discarded – undo
582 582
 			$this->applyFind('ldap_display_name', $d['ldap_display_name']);
583 583
 		}
584 584
 		$filter = $this->composeLdapFilter(self::LFILTER_USER_LIST);
585
-		if(!$filter) {
585
+		if (!$filter) {
586 586
 			throw new \Exception('Cannot create filter');
587 587
 		}
588 588
 
@@ -595,7 +595,7 @@  discard block
 block discarded – undo
595 595
 	 * @throws \Exception
596 596
 	 */
597 597
 	public function getUserLoginFilter() {
598
-		if(!$this->checkRequirements(array('ldapHost',
598
+		if (!$this->checkRequirements(array('ldapHost',
599 599
 										   'ldapPort',
600 600
 										   'ldapBase',
601 601
 										   'ldapUserFilter',
@@ -604,7 +604,7 @@  discard block
 block discarded – undo
604 604
 		}
605 605
 
606 606
 		$filter = $this->composeLdapFilter(self::LFILTER_LOGIN);
607
-		if(!$filter) {
607
+		if (!$filter) {
608 608
 			throw new \Exception('Cannot create filter');
609 609
 		}
610 610
 
@@ -618,7 +618,7 @@  discard block
 block discarded – undo
618 618
 	 * @throws \Exception
619 619
 	 */
620 620
 	public function testLoginName($loginName) {
621
-		if(!$this->checkRequirements(array('ldapHost',
621
+		if (!$this->checkRequirements(array('ldapHost',
622 622
 			'ldapPort',
623 623
 			'ldapBase',
624 624
 			'ldapLoginFilter',
@@ -627,17 +627,17 @@  discard block
 block discarded – undo
627 627
 		}
628 628
 
629 629
 		$cr = $this->access->connection->getConnectionResource();
630
-		if(!$this->ldap->isResource($cr)) {
630
+		if (!$this->ldap->isResource($cr)) {
631 631
 			throw new \Exception('connection error');
632 632
 		}
633 633
 
634
-		if(mb_strpos($this->access->connection->ldapLoginFilter, '%uid', 0, 'UTF-8')
634
+		if (mb_strpos($this->access->connection->ldapLoginFilter, '%uid', 0, 'UTF-8')
635 635
 			=== false) {
636 636
 			throw new \Exception('missing placeholder');
637 637
 		}
638 638
 
639 639
 		$users = $this->access->countUsersByLoginName($loginName);
640
-		if($this->ldap->errno($cr) !== 0) {
640
+		if ($this->ldap->errno($cr) !== 0) {
641 641
 			throw new \Exception($this->ldap->error($cr));
642 642
 		}
643 643
 		$filter = str_replace('%uid', $loginName, $this->access->connection->ldapLoginFilter);
@@ -652,22 +652,22 @@  discard block
 block discarded – undo
652 652
 	 * @throws \Exception
653 653
 	 */
654 654
 	public function guessPortAndTLS() {
655
-		if(!$this->checkRequirements(array('ldapHost',
655
+		if (!$this->checkRequirements(array('ldapHost',
656 656
 										   ))) {
657 657
 			return false;
658 658
 		}
659 659
 		$this->checkHost();
660 660
 		$portSettings = $this->getPortSettingsToTry();
661 661
 
662
-		if(!is_array($portSettings)) {
662
+		if (!is_array($portSettings)) {
663 663
 			throw new \Exception(print_r($portSettings, true));
664 664
 		}
665 665
 
666 666
 		//proceed from the best configuration and return on first success
667
-		foreach($portSettings as $setting) {
667
+		foreach ($portSettings as $setting) {
668 668
 			$p = $setting['port'];
669 669
 			$t = $setting['tls'];
670
-			\OCP\Util::writeLog('user_ldap', 'Wiz: trying port '. $p . ', TLS '. $t, \OCP\Util::DEBUG);
670
+			\OCP\Util::writeLog('user_ldap', 'Wiz: trying port '.$p.', TLS '.$t, \OCP\Util::DEBUG);
671 671
 			//connectAndBind may throw Exception, it needs to be catched by the
672 672
 			//callee of this method
673 673
 
@@ -677,7 +677,7 @@  discard block
 block discarded – undo
677 677
 				// any reply other than -1 (= cannot connect) is already okay,
678 678
 				// because then we found the server
679 679
 				// unavailable startTLS returns -11
680
-				if($e->getCode() > 0) {
680
+				if ($e->getCode() > 0) {
681 681
 					$settingsFound = true;
682 682
 				} else {
683 683
 					throw $e;
@@ -690,7 +690,7 @@  discard block
 block discarded – undo
690 690
 					'ldapTLS' => intval($t)
691 691
 				);
692 692
 				$this->configuration->setConfiguration($config);
693
-				\OCP\Util::writeLog('user_ldap', 'Wiz: detected Port ' . $p, \OCP\Util::DEBUG);
693
+				\OCP\Util::writeLog('user_ldap', 'Wiz: detected Port '.$p, \OCP\Util::DEBUG);
694 694
 				$this->result->addChange('ldap_port', $p);
695 695
 				return $this->result;
696 696
 			}
@@ -705,7 +705,7 @@  discard block
 block discarded – undo
705 705
 	 * @return WizardResult|false WizardResult on success, false otherwise
706 706
 	 */
707 707
 	public function guessBaseDN() {
708
-		if(!$this->checkRequirements(array('ldapHost',
708
+		if (!$this->checkRequirements(array('ldapHost',
709 709
 										   'ldapPort',
710 710
 										   ))) {
711 711
 			return false;
@@ -714,9 +714,9 @@  discard block
 block discarded – undo
714 714
 		//check whether a DN is given in the agent name (99.9% of all cases)
715 715
 		$base = null;
716 716
 		$i = stripos($this->configuration->ldapAgentName, 'dc=');
717
-		if($i !== false) {
717
+		if ($i !== false) {
718 718
 			$base = substr($this->configuration->ldapAgentName, $i);
719
-			if($this->testBaseDN($base)) {
719
+			if ($this->testBaseDN($base)) {
720 720
 				$this->applyFind('ldap_base', $base);
721 721
 				return $this->result;
722 722
 			}
@@ -727,13 +727,13 @@  discard block
 block discarded – undo
727 727
 		//a base DN
728 728
 		$helper = new Helper(\OC::$server->getConfig());
729 729
 		$domain = $helper->getDomainFromURL($this->configuration->ldapHost);
730
-		if(!$domain) {
730
+		if (!$domain) {
731 731
 			return false;
732 732
 		}
733 733
 
734 734
 		$dparts = explode('.', $domain);
735
-		while(count($dparts) > 0) {
736
-			$base2 = 'dc=' . implode(',dc=', $dparts);
735
+		while (count($dparts) > 0) {
736
+			$base2 = 'dc='.implode(',dc=', $dparts);
737 737
 			if ($base !== $base2 && $this->testBaseDN($base2)) {
738 738
 				$this->applyFind('ldap_base', $base2);
739 739
 				return $this->result;
@@ -766,7 +766,7 @@  discard block
 block discarded – undo
766 766
 		$hostInfo = parse_url($host);
767 767
 
768 768
 		//removes Port from Host
769
-		if(is_array($hostInfo) && isset($hostInfo['port'])) {
769
+		if (is_array($hostInfo) && isset($hostInfo['port'])) {
770 770
 			$port = $hostInfo['port'];
771 771
 			$host = str_replace(':'.$port, '', $host);
772 772
 			$this->applyFind('ldap_host', $host);
@@ -783,30 +783,30 @@  discard block
 block discarded – undo
783 783
 	private function detectGroupMemberAssoc() {
784 784
 		$possibleAttrs = array('uniqueMember', 'memberUid', 'member', 'gidNumber');
785 785
 		$filter = $this->configuration->ldapGroupFilter;
786
-		if(empty($filter)) {
786
+		if (empty($filter)) {
787 787
 			return false;
788 788
 		}
789 789
 		$cr = $this->getConnection();
790
-		if(!$cr) {
790
+		if (!$cr) {
791 791
 			throw new \Exception('Could not connect to LDAP');
792 792
 		}
793 793
 		$base = $this->configuration->ldapBase[0];
794 794
 		$rr = $this->ldap->search($cr, $base, $filter, $possibleAttrs, 0, 1000);
795
-		if(!$this->ldap->isResource($rr)) {
795
+		if (!$this->ldap->isResource($rr)) {
796 796
 			return false;
797 797
 		}
798 798
 		$er = $this->ldap->firstEntry($cr, $rr);
799
-		while(is_resource($er)) {
799
+		while (is_resource($er)) {
800 800
 			$this->ldap->getDN($cr, $er);
801 801
 			$attrs = $this->ldap->getAttributes($cr, $er);
802 802
 			$result = array();
803 803
 			$possibleAttrsCount = count($possibleAttrs);
804
-			for($i = 0; $i < $possibleAttrsCount; $i++) {
805
-				if(isset($attrs[$possibleAttrs[$i]])) {
804
+			for ($i = 0; $i < $possibleAttrsCount; $i++) {
805
+				if (isset($attrs[$possibleAttrs[$i]])) {
806 806
 					$result[$possibleAttrs[$i]] = $attrs[$possibleAttrs[$i]]['count'];
807 807
 				}
808 808
 			}
809
-			if(!empty($result)) {
809
+			if (!empty($result)) {
810 810
 				natsort($result);
811 811
 				return key($result);
812 812
 			}
@@ -825,14 +825,14 @@  discard block
 block discarded – undo
825 825
 	 */
826 826
 	private function testBaseDN($base) {
827 827
 		$cr = $this->getConnection();
828
-		if(!$cr) {
828
+		if (!$cr) {
829 829
 			throw new \Exception('Could not connect to LDAP');
830 830
 		}
831 831
 
832 832
 		//base is there, let's validate it. If we search for anything, we should
833 833
 		//get a result set > 0 on a proper base
834 834
 		$rr = $this->ldap->search($cr, $base, 'objectClass=*', array('dn'), 0, 1);
835
-		if(!$this->ldap->isResource($rr)) {
835
+		if (!$this->ldap->isResource($rr)) {
836 836
 			$errorNo  = $this->ldap->errno($cr);
837 837
 			$errorMsg = $this->ldap->error($cr);
838 838
 			\OCP\Util::writeLog('user_ldap', 'Wiz: Could not search base '.$base.
@@ -854,11 +854,11 @@  discard block
 block discarded – undo
854 854
 	 */
855 855
 	private function testMemberOf() {
856 856
 		$cr = $this->getConnection();
857
-		if(!$cr) {
857
+		if (!$cr) {
858 858
 			throw new \Exception('Could not connect to LDAP');
859 859
 		}
860 860
 		$result = $this->access->countUsers('memberOf=*', array('memberOf'), 1);
861
-		if(is_int($result) &&  $result > 0) {
861
+		if (is_int($result) && $result > 0) {
862 862
 			return true;
863 863
 		}
864 864
 		return false;
@@ -879,27 +879,27 @@  discard block
 block discarded – undo
879 879
 			case self::LFILTER_USER_LIST:
880 880
 				$objcs = $this->configuration->ldapUserFilterObjectclass;
881 881
 				//glue objectclasses
882
-				if(is_array($objcs) && count($objcs) > 0) {
882
+				if (is_array($objcs) && count($objcs) > 0) {
883 883
 					$filter .= '(|';
884
-					foreach($objcs as $objc) {
885
-						$filter .= '(objectclass=' . $objc . ')';
884
+					foreach ($objcs as $objc) {
885
+						$filter .= '(objectclass='.$objc.')';
886 886
 					}
887 887
 					$filter .= ')';
888 888
 					$parts++;
889 889
 				}
890 890
 				//glue group memberships
891
-				if($this->configuration->hasMemberOfFilterSupport) {
891
+				if ($this->configuration->hasMemberOfFilterSupport) {
892 892
 					$cns = $this->configuration->ldapUserFilterGroups;
893
-					if(is_array($cns) && count($cns) > 0) {
893
+					if (is_array($cns) && count($cns) > 0) {
894 894
 						$filter .= '(|';
895 895
 						$cr = $this->getConnection();
896
-						if(!$cr) {
896
+						if (!$cr) {
897 897
 							throw new \Exception('Could not connect to LDAP');
898 898
 						}
899 899
 						$base = $this->configuration->ldapBase[0];
900
-						foreach($cns as $cn) {
901
-							$rr = $this->ldap->search($cr, $base, 'cn=' . $cn, array('dn', 'primaryGroupToken'));
902
-							if(!$this->ldap->isResource($rr)) {
900
+						foreach ($cns as $cn) {
901
+							$rr = $this->ldap->search($cr, $base, 'cn='.$cn, array('dn', 'primaryGroupToken'));
902
+							if (!$this->ldap->isResource($rr)) {
903 903
 								continue;
904 904
 							}
905 905
 							$er = $this->ldap->firstEntry($cr, $rr);
@@ -908,11 +908,11 @@  discard block
 block discarded – undo
908 908
 							if ($dn == false || $dn === '') {
909 909
 								continue;
910 910
 							}
911
-							$filterPart = '(memberof=' . $dn . ')';
912
-							if(isset($attrs['primaryGroupToken'])) {
911
+							$filterPart = '(memberof='.$dn.')';
912
+							if (isset($attrs['primaryGroupToken'])) {
913 913
 								$pgt = $attrs['primaryGroupToken'][0];
914
-								$primaryFilterPart = '(primaryGroupID=' . $pgt .')';
915
-								$filterPart = '(|' . $filterPart . $primaryFilterPart . ')';
914
+								$primaryFilterPart = '(primaryGroupID='.$pgt.')';
915
+								$filterPart = '(|'.$filterPart.$primaryFilterPart.')';
916 916
 							}
917 917
 							$filter .= $filterPart;
918 918
 						}
@@ -921,8 +921,8 @@  discard block
 block discarded – undo
921 921
 					$parts++;
922 922
 				}
923 923
 				//wrap parts in AND condition
924
-				if($parts > 1) {
925
-					$filter = '(&' . $filter . ')';
924
+				if ($parts > 1) {
925
+					$filter = '(&'.$filter.')';
926 926
 				}
927 927
 				if ($filter === '') {
928 928
 					$filter = '(objectclass=*)';
@@ -932,27 +932,27 @@  discard block
 block discarded – undo
932 932
 			case self::LFILTER_GROUP_LIST:
933 933
 				$objcs = $this->configuration->ldapGroupFilterObjectclass;
934 934
 				//glue objectclasses
935
-				if(is_array($objcs) && count($objcs) > 0) {
935
+				if (is_array($objcs) && count($objcs) > 0) {
936 936
 					$filter .= '(|';
937
-					foreach($objcs as $objc) {
938
-						$filter .= '(objectclass=' . $objc . ')';
937
+					foreach ($objcs as $objc) {
938
+						$filter .= '(objectclass='.$objc.')';
939 939
 					}
940 940
 					$filter .= ')';
941 941
 					$parts++;
942 942
 				}
943 943
 				//glue group memberships
944 944
 				$cns = $this->configuration->ldapGroupFilterGroups;
945
-				if(is_array($cns) && count($cns) > 0) {
945
+				if (is_array($cns) && count($cns) > 0) {
946 946
 					$filter .= '(|';
947
-					foreach($cns as $cn) {
948
-						$filter .= '(cn=' . $cn . ')';
947
+					foreach ($cns as $cn) {
948
+						$filter .= '(cn='.$cn.')';
949 949
 					}
950 950
 					$filter .= ')';
951 951
 				}
952 952
 				$parts++;
953 953
 				//wrap parts in AND condition
954
-				if($parts > 1) {
955
-					$filter = '(&' . $filter . ')';
954
+				if ($parts > 1) {
955
+					$filter = '(&'.$filter.')';
956 956
 				}
957 957
 				break;
958 958
 
@@ -964,47 +964,47 @@  discard block
 block discarded – undo
964 964
 				$userAttributes = array_change_key_case(array_flip($userAttributes));
965 965
 				$parts = 0;
966 966
 
967
-				if($this->configuration->ldapLoginFilterUsername === '1') {
967
+				if ($this->configuration->ldapLoginFilterUsername === '1') {
968 968
 					$attr = '';
969
-					if(isset($userAttributes['uid'])) {
969
+					if (isset($userAttributes['uid'])) {
970 970
 						$attr = 'uid';
971
-					} else if(isset($userAttributes['samaccountname'])) {
971
+					} else if (isset($userAttributes['samaccountname'])) {
972 972
 						$attr = 'samaccountname';
973
-					} else if(isset($userAttributes['cn'])) {
973
+					} else if (isset($userAttributes['cn'])) {
974 974
 						//fallback
975 975
 						$attr = 'cn';
976 976
 					}
977 977
 					if ($attr !== '') {
978
-						$filterUsername = '(' . $attr . $loginpart . ')';
978
+						$filterUsername = '('.$attr.$loginpart.')';
979 979
 						$parts++;
980 980
 					}
981 981
 				}
982 982
 
983 983
 				$filterEmail = '';
984
-				if($this->configuration->ldapLoginFilterEmail === '1') {
984
+				if ($this->configuration->ldapLoginFilterEmail === '1') {
985 985
 					$filterEmail = '(|(mailPrimaryAddress=%uid)(mail=%uid))';
986 986
 					$parts++;
987 987
 				}
988 988
 
989 989
 				$filterAttributes = '';
990 990
 				$attrsToFilter = $this->configuration->ldapLoginFilterAttributes;
991
-				if(is_array($attrsToFilter) && count($attrsToFilter) > 0) {
991
+				if (is_array($attrsToFilter) && count($attrsToFilter) > 0) {
992 992
 					$filterAttributes = '(|';
993
-					foreach($attrsToFilter as $attribute) {
994
-						$filterAttributes .= '(' . $attribute . $loginpart . ')';
993
+					foreach ($attrsToFilter as $attribute) {
994
+						$filterAttributes .= '('.$attribute.$loginpart.')';
995 995
 					}
996 996
 					$filterAttributes .= ')';
997 997
 					$parts++;
998 998
 				}
999 999
 
1000 1000
 				$filterLogin = '';
1001
-				if($parts > 1) {
1001
+				if ($parts > 1) {
1002 1002
 					$filterLogin = '(|';
1003 1003
 				}
1004 1004
 				$filterLogin .= $filterUsername;
1005 1005
 				$filterLogin .= $filterEmail;
1006 1006
 				$filterLogin .= $filterAttributes;
1007
-				if($parts > 1) {
1007
+				if ($parts > 1) {
1008 1008
 					$filterLogin .= ')';
1009 1009
 				}
1010 1010
 
@@ -1026,7 +1026,7 @@  discard block
 block discarded – undo
1026 1026
 	 * @throws \Exception
1027 1027
 	 */
1028 1028
 	private function connectAndBind($port = 389, $tls = false, $ncc = false) {
1029
-		if($ncc) {
1029
+		if ($ncc) {
1030 1030
 			//No certificate check
1031 1031
 			//FIXME: undo afterwards
1032 1032
 			putenv('LDAPTLS_REQCERT=never');
@@ -1036,12 +1036,12 @@  discard block
 block discarded – undo
1036 1036
 		\OCP\Util::writeLog('user_ldap', 'Wiz: Checking Host Info ', \OCP\Util::DEBUG);
1037 1037
 		$host = $this->configuration->ldapHost;
1038 1038
 		$hostInfo = parse_url($host);
1039
-		if(!$hostInfo) {
1039
+		if (!$hostInfo) {
1040 1040
 			throw new \Exception(self::$l->t('Invalid Host'));
1041 1041
 		}
1042 1042
 		\OCP\Util::writeLog('user_ldap', 'Wiz: Attempting to connect ', \OCP\Util::DEBUG);
1043 1043
 		$cr = $this->ldap->connect($host, $port);
1044
-		if(!is_resource($cr)) {
1044
+		if (!is_resource($cr)) {
1045 1045
 			throw new \Exception(self::$l->t('Invalid Host'));
1046 1046
 		}
1047 1047
 
@@ -1052,9 +1052,9 @@  discard block
 block discarded – undo
1052 1052
 		$this->ldap->setOption($cr, LDAP_OPT_NETWORK_TIMEOUT, self::LDAP_NW_TIMEOUT);
1053 1053
 
1054 1054
 		try {
1055
-			if($tls) {
1055
+			if ($tls) {
1056 1056
 				$isTlsWorking = @$this->ldap->startTls($cr);
1057
-				if(!$isTlsWorking) {
1057
+				if (!$isTlsWorking) {
1058 1058
 					return false;
1059 1059
 				}
1060 1060
 			}
@@ -1068,20 +1068,20 @@  discard block
 block discarded – undo
1068 1068
 			$errNo = $this->ldap->errno($cr);
1069 1069
 			$error = ldap_error($cr);
1070 1070
 			$this->ldap->unbind($cr);
1071
-		} catch(ServerNotAvailableException $e) {
1071
+		} catch (ServerNotAvailableException $e) {
1072 1072
 			return false;
1073 1073
 		}
1074 1074
 
1075
-		if($login === true) {
1075
+		if ($login === true) {
1076 1076
 			$this->ldap->unbind($cr);
1077
-			if($ncc) {
1077
+			if ($ncc) {
1078 1078
 				throw new \Exception('Certificate cannot be validated.');
1079 1079
 			}
1080
-			\OCP\Util::writeLog('user_ldap', 'Wiz: Bind successful to Port '. $port . ' TLS ' . intval($tls), \OCP\Util::DEBUG);
1080
+			\OCP\Util::writeLog('user_ldap', 'Wiz: Bind successful to Port '.$port.' TLS '.intval($tls), \OCP\Util::DEBUG);
1081 1081
 			return true;
1082 1082
 		}
1083 1083
 
1084
-		if($errNo === -1 || ($errNo === 2 && $ncc)) {
1084
+		if ($errNo === -1 || ($errNo === 2 && $ncc)) {
1085 1085
 			//host, port or TLS wrong
1086 1086
 			return false;
1087 1087
 		} else if ($errNo === 2) {
@@ -1111,9 +1111,9 @@  discard block
 block discarded – undo
1111 1111
 	 */
1112 1112
 	private function checkRequirements($reqs) {
1113 1113
 		$this->checkAgentRequirements();
1114
-		foreach($reqs as $option) {
1114
+		foreach ($reqs as $option) {
1115 1115
 			$value = $this->configuration->$option;
1116
-			if(empty($value)) {
1116
+			if (empty($value)) {
1117 1117
 				return false;
1118 1118
 			}
1119 1119
 		}
@@ -1135,33 +1135,33 @@  discard block
 block discarded – undo
1135 1135
 		$dnRead = array();
1136 1136
 		$foundItems = array();
1137 1137
 		$maxEntries = 0;
1138
-		if(!is_array($this->configuration->ldapBase)
1138
+		if (!is_array($this->configuration->ldapBase)
1139 1139
 		   || !isset($this->configuration->ldapBase[0])) {
1140 1140
 			return false;
1141 1141
 		}
1142 1142
 		$base = $this->configuration->ldapBase[0];
1143 1143
 		$cr = $this->getConnection();
1144
-		if(!$this->ldap->isResource($cr)) {
1144
+		if (!$this->ldap->isResource($cr)) {
1145 1145
 			return false;
1146 1146
 		}
1147 1147
 		$lastFilter = null;
1148
-		if(isset($filters[count($filters)-1])) {
1149
-			$lastFilter = $filters[count($filters)-1];
1148
+		if (isset($filters[count($filters) - 1])) {
1149
+			$lastFilter = $filters[count($filters) - 1];
1150 1150
 		}
1151
-		foreach($filters as $filter) {
1152
-			if($lastFilter === $filter && count($foundItems) > 0) {
1151
+		foreach ($filters as $filter) {
1152
+			if ($lastFilter === $filter && count($foundItems) > 0) {
1153 1153
 				//skip when the filter is a wildcard and results were found
1154 1154
 				continue;
1155 1155
 			}
1156 1156
 			// 20k limit for performance and reason
1157 1157
 			$rr = $this->ldap->search($cr, $base, $filter, array($attr), 0, 20000);
1158
-			if(!$this->ldap->isResource($rr)) {
1158
+			if (!$this->ldap->isResource($rr)) {
1159 1159
 				continue;
1160 1160
 			}
1161 1161
 			$entries = $this->ldap->countEntries($cr, $rr);
1162 1162
 			$getEntryFunc = 'firstEntry';
1163
-			if(($entries !== false) && ($entries > 0)) {
1164
-				if(!is_null($maxF) && $entries > $maxEntries) {
1163
+			if (($entries !== false) && ($entries > 0)) {
1164
+				if (!is_null($maxF) && $entries > $maxEntries) {
1165 1165
 					$maxEntries = $entries;
1166 1166
 					$maxF = $filter;
1167 1167
 				}
@@ -1169,13 +1169,13 @@  discard block
 block discarded – undo
1169 1169
 				do {
1170 1170
 					$entry = $this->ldap->$getEntryFunc($cr, $rr);
1171 1171
 					$getEntryFunc = 'nextEntry';
1172
-					if(!$this->ldap->isResource($entry)) {
1172
+					if (!$this->ldap->isResource($entry)) {
1173 1173
 						continue 2;
1174 1174
 					}
1175 1175
 					$rr = $entry; //will be expected by nextEntry next round
1176 1176
 					$attributes = $this->ldap->getAttributes($cr, $entry);
1177 1177
 					$dn = $this->ldap->getDN($cr, $entry);
1178
-					if($dn === false || in_array($dn, $dnRead)) {
1178
+					if ($dn === false || in_array($dn, $dnRead)) {
1179 1179
 						continue;
1180 1180
 					}
1181 1181
 					$newItems = array();
@@ -1186,7 +1186,7 @@  discard block
 block discarded – undo
1186 1186
 					$foundItems = array_merge($foundItems, $newItems);
1187 1187
 					$this->resultCache[$dn][$attr] = $newItems;
1188 1188
 					$dnRead[] = $dn;
1189
-				} while(($state === self::LRESULT_PROCESSED_SKIP
1189
+				} while (($state === self::LRESULT_PROCESSED_SKIP
1190 1190
 						|| $this->ldap->isResource($entry))
1191 1191
 						&& ($dnReadLimit === 0 || $dnReadCount < $dnReadLimit));
1192 1192
 			}
@@ -1209,11 +1209,11 @@  discard block
 block discarded – undo
1209 1209
 	 */
1210 1210
 	private function determineFeature($objectclasses, $attr, $dbkey, $confkey, $po = false) {
1211 1211
 		$cr = $this->getConnection();
1212
-		if(!$cr) {
1212
+		if (!$cr) {
1213 1213
 			throw new \Exception('Could not connect to LDAP');
1214 1214
 		}
1215 1215
 		$p = 'objectclass=';
1216
-		foreach($objectclasses as $key => $value) {
1216
+		foreach ($objectclasses as $key => $value) {
1217 1217
 			$objectclasses[$key] = $p.$value;
1218 1218
 		}
1219 1219
 		$maxEntryObjC = '';
@@ -1225,7 +1225,7 @@  discard block
 block discarded – undo
1225 1225
 		$availableFeatures =
1226 1226
 			$this->cumulativeSearchOnAttribute($objectclasses, $attr,
1227 1227
 											   $dig, $maxEntryObjC);
1228
-		if(is_array($availableFeatures)
1228
+		if (is_array($availableFeatures)
1229 1229
 		   && count($availableFeatures) > 0) {
1230 1230
 			natcasesort($availableFeatures);
1231 1231
 			//natcasesort keeps indices, but we must get rid of them for proper
@@ -1236,7 +1236,7 @@  discard block
 block discarded – undo
1236 1236
 		}
1237 1237
 
1238 1238
 		$setFeatures = $this->configuration->$confkey;
1239
-		if(is_array($setFeatures) && !empty($setFeatures)) {
1239
+		if (is_array($setFeatures) && !empty($setFeatures)) {
1240 1240
 			//something is already configured? pre-select it.
1241 1241
 			$this->result->addChange($dbkey, $setFeatures);
1242 1242
 		} else if ($po && $maxEntryObjC !== '') {
@@ -1258,7 +1258,7 @@  discard block
 block discarded – undo
1258 1258
 	 * LRESULT_PROCESSED_INVALID or LRESULT_PROCESSED_SKIP
1259 1259
 	 */
1260 1260
 	private function getAttributeValuesFromEntry($result, $attribute, &$known) {
1261
-		if(!is_array($result)
1261
+		if (!is_array($result)
1262 1262
 		   || !isset($result['count'])
1263 1263
 		   || !$result['count'] > 0) {
1264 1264
 			return self::LRESULT_PROCESSED_INVALID;
@@ -1267,12 +1267,12 @@  discard block
 block discarded – undo
1267 1267
 		// strtolower on all keys for proper comparison
1268 1268
 		$result = \OCP\Util::mb_array_change_key_case($result);
1269 1269
 		$attribute = strtolower($attribute);
1270
-		if(isset($result[$attribute])) {
1271
-			foreach($result[$attribute] as $key => $val) {
1272
-				if($key === 'count') {
1270
+		if (isset($result[$attribute])) {
1271
+			foreach ($result[$attribute] as $key => $val) {
1272
+				if ($key === 'count') {
1273 1273
 					continue;
1274 1274
 				}
1275
-				if(!in_array($val, $known)) {
1275
+				if (!in_array($val, $known)) {
1276 1276
 					$known[] = $val;
1277 1277
 				}
1278 1278
 			}
@@ -1286,7 +1286,7 @@  discard block
 block discarded – undo
1286 1286
 	 * @return bool|mixed
1287 1287
 	 */
1288 1288
 	private function getConnection() {
1289
-		if(!is_null($this->cr)) {
1289
+		if (!is_null($this->cr)) {
1290 1290
 			return $this->cr;
1291 1291
 		}
1292 1292
 
@@ -1298,14 +1298,14 @@  discard block
 block discarded – undo
1298 1298
 		$this->ldap->setOption($cr, LDAP_OPT_PROTOCOL_VERSION, 3);
1299 1299
 		$this->ldap->setOption($cr, LDAP_OPT_REFERRALS, 0);
1300 1300
 		$this->ldap->setOption($cr, LDAP_OPT_NETWORK_TIMEOUT, self::LDAP_NW_TIMEOUT);
1301
-		if($this->configuration->ldapTLS === 1) {
1301
+		if ($this->configuration->ldapTLS === 1) {
1302 1302
 			$this->ldap->startTls($cr);
1303 1303
 		}
1304 1304
 
1305 1305
 		$lo = @$this->ldap->bind($cr,
1306 1306
 								 $this->configuration->ldapAgentName,
1307 1307
 								 $this->configuration->ldapAgentPassword);
1308
-		if($lo === true) {
1308
+		if ($lo === true) {
1309 1309
 			$this->$cr = $cr;
1310 1310
 			return $cr;
1311 1311
 		}
@@ -1340,14 +1340,14 @@  discard block
 block discarded – undo
1340 1340
 		$portSettings = array();
1341 1341
 
1342 1342
 		//In case the port is already provided, we will check this first
1343
-		if($port > 0) {
1343
+		if ($port > 0) {
1344 1344
 			$hostInfo = parse_url($host);
1345
-			if(!(is_array($hostInfo)
1345
+			if (!(is_array($hostInfo)
1346 1346
 				&& isset($hostInfo['scheme'])
1347 1347
 				&& stripos($hostInfo['scheme'], 'ldaps') !== false)) {
1348 1348
 				$portSettings[] = array('port' => $port, 'tls' => true);
1349 1349
 			}
1350
-			$portSettings[] =array('port' => $port, 'tls' => false);
1350
+			$portSettings[] = array('port' => $port, 'tls' => false);
1351 1351
 		}
1352 1352
 
1353 1353
 		//default ports
Please login to merge, or discard this patch.
Indentation   +1318 added lines, -1318 removed lines patch added patch discarded remove patch
@@ -38,1324 +38,1324 @@
 block discarded – undo
38 38
 use OC\ServerNotAvailableException;
39 39
 
40 40
 class Wizard extends LDAPUtility {
41
-	/** @var \OCP\IL10N */
42
-	static protected $l;
43
-	protected $access;
44
-	protected $cr;
45
-	protected $configuration;
46
-	protected $result;
47
-	protected $resultCache = array();
48
-
49
-	const LRESULT_PROCESSED_OK = 2;
50
-	const LRESULT_PROCESSED_INVALID = 3;
51
-	const LRESULT_PROCESSED_SKIP = 4;
52
-
53
-	const LFILTER_LOGIN      = 2;
54
-	const LFILTER_USER_LIST  = 3;
55
-	const LFILTER_GROUP_LIST = 4;
56
-
57
-	const LFILTER_MODE_ASSISTED = 2;
58
-	const LFILTER_MODE_RAW = 1;
59
-
60
-	const LDAP_NW_TIMEOUT = 4;
61
-
62
-	/**
63
-	 * Constructor
64
-	 * @param Configuration $configuration an instance of Configuration
65
-	 * @param ILDAPWrapper $ldap an instance of ILDAPWrapper
66
-	 * @param Access $access
67
-	 */
68
-	public function __construct(Configuration $configuration, ILDAPWrapper $ldap, Access $access) {
69
-		parent::__construct($ldap);
70
-		$this->configuration = $configuration;
71
-		if(is_null(Wizard::$l)) {
72
-			Wizard::$l = \OC::$server->getL10N('user_ldap');
73
-		}
74
-		$this->access = $access;
75
-		$this->result = new WizardResult();
76
-	}
77
-
78
-	public function  __destruct() {
79
-		if($this->result->hasChanges()) {
80
-			$this->configuration->saveConfiguration();
81
-		}
82
-	}
83
-
84
-	/**
85
-	 * counts entries in the LDAP directory
86
-	 *
87
-	 * @param string $filter the LDAP search filter
88
-	 * @param string $type a string being either 'users' or 'groups';
89
-	 * @return bool|int
90
-	 * @throws \Exception
91
-	 */
92
-	public function countEntries($filter, $type) {
93
-		$reqs = array('ldapHost', 'ldapPort', 'ldapBase');
94
-		if($type === 'users') {
95
-			$reqs[] = 'ldapUserFilter';
96
-		}
97
-		if(!$this->checkRequirements($reqs)) {
98
-			throw new \Exception('Requirements not met', 400);
99
-		}
100
-
101
-		$attr = array('dn'); // default
102
-		$limit = 1001;
103
-		if($type === 'groups') {
104
-			$result =  $this->access->countGroups($filter, $attr, $limit);
105
-		} else if($type === 'users') {
106
-			$result = $this->access->countUsers($filter, $attr, $limit);
107
-		} else if ($type === 'objects') {
108
-			$result = $this->access->countObjects($limit);
109
-		} else {
110
-			throw new \Exception('Internal error: Invalid object type', 500);
111
-		}
112
-
113
-		return $result;
114
-	}
115
-
116
-	/**
117
-	 * formats the return value of a count operation to the string to be
118
-	 * inserted.
119
-	 *
120
-	 * @param bool|int $count
121
-	 * @return int|string
122
-	 */
123
-	private function formatCountResult($count) {
124
-		$formatted = ($count !== false) ? $count : 0;
125
-		if($formatted > 1000) {
126
-			$formatted = '> 1000';
127
-		}
128
-		return $formatted;
129
-	}
130
-
131
-	public function countGroups() {
132
-		$filter = $this->configuration->ldapGroupFilter;
133
-
134
-		if(empty($filter)) {
135
-			$output = self::$l->n('%s group found', '%s groups found', 0, array(0));
136
-			$this->result->addChange('ldap_group_count', $output);
137
-			return $this->result;
138
-		}
139
-
140
-		try {
141
-			$groupsTotal = $this->formatCountResult($this->countEntries($filter, 'groups'));
142
-		} catch (\Exception $e) {
143
-			//400 can be ignored, 500 is forwarded
144
-			if($e->getCode() === 500) {
145
-				throw $e;
146
-			}
147
-			return false;
148
-		}
149
-		$output = self::$l->n('%s group found', '%s groups found', $groupsTotal, array($groupsTotal));
150
-		$this->result->addChange('ldap_group_count', $output);
151
-		return $this->result;
152
-	}
153
-
154
-	/**
155
-	 * @return WizardResult
156
-	 * @throws \Exception
157
-	 */
158
-	public function countUsers() {
159
-		$filter = $this->access->getFilterForUserCount();
160
-
161
-		$usersTotal = $this->formatCountResult($this->countEntries($filter, 'users'));
162
-		$output = self::$l->n('%s user found', '%s users found', $usersTotal, array($usersTotal));
163
-		$this->result->addChange('ldap_user_count', $output);
164
-		return $this->result;
165
-	}
166
-
167
-	/**
168
-	 * counts any objects in the currently set base dn
169
-	 *
170
-	 * @return WizardResult
171
-	 * @throws \Exception
172
-	 */
173
-	public function countInBaseDN() {
174
-		// we don't need to provide a filter in this case
175
-		$total = $this->countEntries(null, 'objects');
176
-		if($total === false) {
177
-			throw new \Exception('invalid results received');
178
-		}
179
-		$this->result->addChange('ldap_test_base', $total);
180
-		return $this->result;
181
-	}
182
-
183
-	/**
184
-	 * counts users with a specified attribute
185
-	 * @param string $attr
186
-	 * @param bool $existsCheck
187
-	 * @return int|bool
188
-	 */
189
-	public function countUsersWithAttribute($attr, $existsCheck = false) {
190
-		if(!$this->checkRequirements(array('ldapHost',
191
-										   'ldapPort',
192
-										   'ldapBase',
193
-										   'ldapUserFilter',
194
-										   ))) {
195
-			return  false;
196
-		}
197
-
198
-		$filter = $this->access->combineFilterWithAnd(array(
199
-			$this->configuration->ldapUserFilter,
200
-			$attr . '=*'
201
-		));
202
-
203
-		$limit = ($existsCheck === false) ? null : 1;
204
-
205
-		return $this->access->countUsers($filter, array('dn'), $limit);
206
-	}
207
-
208
-	/**
209
-	 * detects the display name attribute. If a setting is already present that
210
-	 * returns at least one hit, the detection will be canceled.
211
-	 * @return WizardResult|bool
212
-	 * @throws \Exception
213
-	 */
214
-	public function detectUserDisplayNameAttribute() {
215
-		if(!$this->checkRequirements(array('ldapHost',
216
-										'ldapPort',
217
-										'ldapBase',
218
-										'ldapUserFilter',
219
-										))) {
220
-			return  false;
221
-		}
222
-
223
-		$attr = $this->configuration->ldapUserDisplayName;
224
-		if ($attr !== '' && $attr !== 'displayName') {
225
-			// most likely not the default value with upper case N,
226
-			// verify it still produces a result
227
-			$count = intval($this->countUsersWithAttribute($attr, true));
228
-			if($count > 0) {
229
-				//no change, but we sent it back to make sure the user interface
230
-				//is still correct, even if the ajax call was cancelled meanwhile
231
-				$this->result->addChange('ldap_display_name', $attr);
232
-				return $this->result;
233
-			}
234
-		}
235
-
236
-		// first attribute that has at least one result wins
237
-		$displayNameAttrs = array('displayname', 'cn');
238
-		foreach ($displayNameAttrs as $attr) {
239
-			$count = intval($this->countUsersWithAttribute($attr, true));
240
-
241
-			if($count > 0) {
242
-				$this->applyFind('ldap_display_name', $attr);
243
-				return $this->result;
244
-			}
245
-		};
246
-
247
-		throw new \Exception(self::$l->t('Could not detect user display name attribute. Please specify it yourself in advanced LDAP settings.'));
248
-	}
249
-
250
-	/**
251
-	 * detects the most often used email attribute for users applying to the
252
-	 * user list filter. If a setting is already present that returns at least
253
-	 * one hit, the detection will be canceled.
254
-	 * @return WizardResult|bool
255
-	 */
256
-	public function detectEmailAttribute() {
257
-		if(!$this->checkRequirements(array('ldapHost',
258
-										   'ldapPort',
259
-										   'ldapBase',
260
-										   'ldapUserFilter',
261
-										   ))) {
262
-			return  false;
263
-		}
264
-
265
-		$attr = $this->configuration->ldapEmailAttribute;
266
-		if ($attr !== '') {
267
-			$count = intval($this->countUsersWithAttribute($attr, true));
268
-			if($count > 0) {
269
-				return false;
270
-			}
271
-			$writeLog = true;
272
-		} else {
273
-			$writeLog = false;
274
-		}
275
-
276
-		$emailAttributes = array('mail', 'mailPrimaryAddress');
277
-		$winner = '';
278
-		$maxUsers = 0;
279
-		foreach($emailAttributes as $attr) {
280
-			$count = $this->countUsersWithAttribute($attr);
281
-			if($count > $maxUsers) {
282
-				$maxUsers = $count;
283
-				$winner = $attr;
284
-			}
285
-		}
286
-
287
-		if($winner !== '') {
288
-			$this->applyFind('ldap_email_attr', $winner);
289
-			if($writeLog) {
290
-				\OCP\Util::writeLog('user_ldap', 'The mail attribute has ' .
291
-					'automatically been reset, because the original value ' .
292
-					'did not return any results.', \OCP\Util::INFO);
293
-			}
294
-		}
295
-
296
-		return $this->result;
297
-	}
298
-
299
-	/**
300
-	 * @return WizardResult
301
-	 * @throws \Exception
302
-	 */
303
-	public function determineAttributes() {
304
-		if(!$this->checkRequirements(array('ldapHost',
305
-										   'ldapPort',
306
-										   'ldapBase',
307
-										   'ldapUserFilter',
308
-										   ))) {
309
-			return  false;
310
-		}
311
-
312
-		$attributes = $this->getUserAttributes();
313
-
314
-		natcasesort($attributes);
315
-		$attributes = array_values($attributes);
316
-
317
-		$this->result->addOptions('ldap_loginfilter_attributes', $attributes);
318
-
319
-		$selected = $this->configuration->ldapLoginFilterAttributes;
320
-		if(is_array($selected) && !empty($selected)) {
321
-			$this->result->addChange('ldap_loginfilter_attributes', $selected);
322
-		}
323
-
324
-		return $this->result;
325
-	}
326
-
327
-	/**
328
-	 * detects the available LDAP attributes
329
-	 * @return array|false The instance's WizardResult instance
330
-	 * @throws \Exception
331
-	 */
332
-	private function getUserAttributes() {
333
-		if(!$this->checkRequirements(array('ldapHost',
334
-										   'ldapPort',
335
-										   'ldapBase',
336
-										   'ldapUserFilter',
337
-										   ))) {
338
-			return  false;
339
-		}
340
-		$cr = $this->getConnection();
341
-		if(!$cr) {
342
-			throw new \Exception('Could not connect to LDAP');
343
-		}
344
-
345
-		$base = $this->configuration->ldapBase[0];
346
-		$filter = $this->configuration->ldapUserFilter;
347
-		$rr = $this->ldap->search($cr, $base, $filter, array(), 1, 1);
348
-		if(!$this->ldap->isResource($rr)) {
349
-			return false;
350
-		}
351
-		$er = $this->ldap->firstEntry($cr, $rr);
352
-		$attributes = $this->ldap->getAttributes($cr, $er);
353
-		$pureAttributes = array();
354
-		for($i = 0; $i < $attributes['count']; $i++) {
355
-			$pureAttributes[] = $attributes[$i];
356
-		}
357
-
358
-		return $pureAttributes;
359
-	}
360
-
361
-	/**
362
-	 * detects the available LDAP groups
363
-	 * @return WizardResult|false the instance's WizardResult instance
364
-	 */
365
-	public function determineGroupsForGroups() {
366
-		return $this->determineGroups('ldap_groupfilter_groups',
367
-									  'ldapGroupFilterGroups',
368
-									  false);
369
-	}
370
-
371
-	/**
372
-	 * detects the available LDAP groups
373
-	 * @return WizardResult|false the instance's WizardResult instance
374
-	 */
375
-	public function determineGroupsForUsers() {
376
-		return $this->determineGroups('ldap_userfilter_groups',
377
-									  'ldapUserFilterGroups');
378
-	}
379
-
380
-	/**
381
-	 * detects the available LDAP groups
382
-	 * @param string $dbKey
383
-	 * @param string $confKey
384
-	 * @param bool $testMemberOf
385
-	 * @return WizardResult|false the instance's WizardResult instance
386
-	 * @throws \Exception
387
-	 */
388
-	private function determineGroups($dbKey, $confKey, $testMemberOf = true) {
389
-		if(!$this->checkRequirements(array('ldapHost',
390
-										   'ldapPort',
391
-										   'ldapBase',
392
-										   ))) {
393
-			return  false;
394
-		}
395
-		$cr = $this->getConnection();
396
-		if(!$cr) {
397
-			throw new \Exception('Could not connect to LDAP');
398
-		}
399
-
400
-		$this->fetchGroups($dbKey, $confKey);
401
-
402
-		if($testMemberOf) {
403
-			$this->configuration->hasMemberOfFilterSupport = $this->testMemberOf();
404
-			$this->result->markChange();
405
-			if(!$this->configuration->hasMemberOfFilterSupport) {
406
-				throw new \Exception('memberOf is not supported by the server');
407
-			}
408
-		}
409
-
410
-		return $this->result;
411
-	}
412
-
413
-	/**
414
-	 * fetches all groups from LDAP and adds them to the result object
415
-	 *
416
-	 * @param string $dbKey
417
-	 * @param string $confKey
418
-	 * @return array $groupEntries
419
-	 * @throws \Exception
420
-	 */
421
-	public function fetchGroups($dbKey, $confKey) {
422
-		$obclasses = array('posixGroup', 'group', 'zimbraDistributionList', 'groupOfNames');
423
-
424
-		$filterParts = array();
425
-		foreach($obclasses as $obclass) {
426
-			$filterParts[] = 'objectclass='.$obclass;
427
-		}
428
-		//we filter for everything
429
-		//- that looks like a group and
430
-		//- has the group display name set
431
-		$filter = $this->access->combineFilterWithOr($filterParts);
432
-		$filter = $this->access->combineFilterWithAnd(array($filter, 'cn=*'));
433
-
434
-		$groupNames = array();
435
-		$groupEntries = array();
436
-		$limit = 400;
437
-		$offset = 0;
438
-		do {
439
-			// we need to request dn additionally here, otherwise memberOf
440
-			// detection will fail later
441
-			$result = $this->access->searchGroups($filter, array('cn', 'dn'), $limit, $offset);
442
-			foreach($result as $item) {
443
-				if(!isset($item['cn']) && !is_array($item['cn']) && !isset($item['cn'][0])) {
444
-					// just in case - no issue known
445
-					continue;
446
-				}
447
-				$groupNames[] = $item['cn'][0];
448
-				$groupEntries[] = $item;
449
-			}
450
-			$offset += $limit;
451
-		} while ($this->access->hasMoreResults());
452
-
453
-		if(count($groupNames) > 0) {
454
-			natsort($groupNames);
455
-			$this->result->addOptions($dbKey, array_values($groupNames));
456
-		} else {
457
-			throw new \Exception(self::$l->t('Could not find the desired feature'));
458
-		}
459
-
460
-		$setFeatures = $this->configuration->$confKey;
461
-		if(is_array($setFeatures) && !empty($setFeatures)) {
462
-			//something is already configured? pre-select it.
463
-			$this->result->addChange($dbKey, $setFeatures);
464
-		}
465
-		return $groupEntries;
466
-	}
467
-
468
-	public function determineGroupMemberAssoc() {
469
-		if(!$this->checkRequirements(array('ldapHost',
470
-										   'ldapPort',
471
-										   'ldapGroupFilter',
472
-										   ))) {
473
-			return  false;
474
-		}
475
-		$attribute = $this->detectGroupMemberAssoc();
476
-		if($attribute === false) {
477
-			return false;
478
-		}
479
-		$this->configuration->setConfiguration(array('ldapGroupMemberAssocAttr' => $attribute));
480
-		$this->result->addChange('ldap_group_member_assoc_attribute', $attribute);
481
-
482
-		return $this->result;
483
-	}
484
-
485
-	/**
486
-	 * Detects the available object classes
487
-	 * @return WizardResult|false the instance's WizardResult instance
488
-	 * @throws \Exception
489
-	 */
490
-	public function determineGroupObjectClasses() {
491
-		if(!$this->checkRequirements(array('ldapHost',
492
-										   'ldapPort',
493
-										   'ldapBase',
494
-										   ))) {
495
-			return  false;
496
-		}
497
-		$cr = $this->getConnection();
498
-		if(!$cr) {
499
-			throw new \Exception('Could not connect to LDAP');
500
-		}
501
-
502
-		$obclasses = array('groupOfNames', 'groupOfUniqueNames', 'group', 'posixGroup', '*');
503
-		$this->determineFeature($obclasses,
504
-								'objectclass',
505
-								'ldap_groupfilter_objectclass',
506
-								'ldapGroupFilterObjectclass',
507
-								false);
508
-
509
-		return $this->result;
510
-	}
511
-
512
-	/**
513
-	 * detects the available object classes
514
-	 * @return WizardResult
515
-	 * @throws \Exception
516
-	 */
517
-	public function determineUserObjectClasses() {
518
-		if(!$this->checkRequirements(array('ldapHost',
519
-										   'ldapPort',
520
-										   'ldapBase',
521
-										   ))) {
522
-			return  false;
523
-		}
524
-		$cr = $this->getConnection();
525
-		if(!$cr) {
526
-			throw new \Exception('Could not connect to LDAP');
527
-		}
528
-
529
-		$obclasses = array('inetOrgPerson', 'person', 'organizationalPerson',
530
-						   'user', 'posixAccount', '*');
531
-		$filter = $this->configuration->ldapUserFilter;
532
-		//if filter is empty, it is probably the first time the wizard is called
533
-		//then, apply suggestions.
534
-		$this->determineFeature($obclasses,
535
-								'objectclass',
536
-								'ldap_userfilter_objectclass',
537
-								'ldapUserFilterObjectclass',
538
-								empty($filter));
539
-
540
-		return $this->result;
541
-	}
542
-
543
-	/**
544
-	 * @return WizardResult|false
545
-	 * @throws \Exception
546
-	 */
547
-	public function getGroupFilter() {
548
-		if(!$this->checkRequirements(array('ldapHost',
549
-										   'ldapPort',
550
-										   'ldapBase',
551
-										   ))) {
552
-			return false;
553
-		}
554
-		//make sure the use display name is set
555
-		$displayName = $this->configuration->ldapGroupDisplayName;
556
-		if ($displayName === '') {
557
-			$d = $this->configuration->getDefaults();
558
-			$this->applyFind('ldap_group_display_name',
559
-							 $d['ldap_group_display_name']);
560
-		}
561
-		$filter = $this->composeLdapFilter(self::LFILTER_GROUP_LIST);
562
-
563
-		$this->applyFind('ldap_group_filter', $filter);
564
-		return $this->result;
565
-	}
566
-
567
-	/**
568
-	 * @return WizardResult|false
569
-	 * @throws \Exception
570
-	 */
571
-	public function getUserListFilter() {
572
-		if(!$this->checkRequirements(array('ldapHost',
573
-										   'ldapPort',
574
-										   'ldapBase',
575
-										   ))) {
576
-			return false;
577
-		}
578
-		//make sure the use display name is set
579
-		$displayName = $this->configuration->ldapUserDisplayName;
580
-		if ($displayName === '') {
581
-			$d = $this->configuration->getDefaults();
582
-			$this->applyFind('ldap_display_name', $d['ldap_display_name']);
583
-		}
584
-		$filter = $this->composeLdapFilter(self::LFILTER_USER_LIST);
585
-		if(!$filter) {
586
-			throw new \Exception('Cannot create filter');
587
-		}
588
-
589
-		$this->applyFind('ldap_userlist_filter', $filter);
590
-		return $this->result;
591
-	}
592
-
593
-	/**
594
-	 * @return bool|WizardResult
595
-	 * @throws \Exception
596
-	 */
597
-	public function getUserLoginFilter() {
598
-		if(!$this->checkRequirements(array('ldapHost',
599
-										   'ldapPort',
600
-										   'ldapBase',
601
-										   'ldapUserFilter',
602
-										   ))) {
603
-			return false;
604
-		}
605
-
606
-		$filter = $this->composeLdapFilter(self::LFILTER_LOGIN);
607
-		if(!$filter) {
608
-			throw new \Exception('Cannot create filter');
609
-		}
610
-
611
-		$this->applyFind('ldap_login_filter', $filter);
612
-		return $this->result;
613
-	}
614
-
615
-	/**
616
-	 * @return bool|WizardResult
617
-	 * @param string $loginName
618
-	 * @throws \Exception
619
-	 */
620
-	public function testLoginName($loginName) {
621
-		if(!$this->checkRequirements(array('ldapHost',
622
-			'ldapPort',
623
-			'ldapBase',
624
-			'ldapLoginFilter',
625
-		))) {
626
-			return false;
627
-		}
628
-
629
-		$cr = $this->access->connection->getConnectionResource();
630
-		if(!$this->ldap->isResource($cr)) {
631
-			throw new \Exception('connection error');
632
-		}
633
-
634
-		if(mb_strpos($this->access->connection->ldapLoginFilter, '%uid', 0, 'UTF-8')
635
-			=== false) {
636
-			throw new \Exception('missing placeholder');
637
-		}
638
-
639
-		$users = $this->access->countUsersByLoginName($loginName);
640
-		if($this->ldap->errno($cr) !== 0) {
641
-			throw new \Exception($this->ldap->error($cr));
642
-		}
643
-		$filter = str_replace('%uid', $loginName, $this->access->connection->ldapLoginFilter);
644
-		$this->result->addChange('ldap_test_loginname', $users);
645
-		$this->result->addChange('ldap_test_effective_filter', $filter);
646
-		return $this->result;
647
-	}
648
-
649
-	/**
650
-	 * Tries to determine the port, requires given Host, User DN and Password
651
-	 * @return WizardResult|false WizardResult on success, false otherwise
652
-	 * @throws \Exception
653
-	 */
654
-	public function guessPortAndTLS() {
655
-		if(!$this->checkRequirements(array('ldapHost',
656
-										   ))) {
657
-			return false;
658
-		}
659
-		$this->checkHost();
660
-		$portSettings = $this->getPortSettingsToTry();
661
-
662
-		if(!is_array($portSettings)) {
663
-			throw new \Exception(print_r($portSettings, true));
664
-		}
665
-
666
-		//proceed from the best configuration and return on first success
667
-		foreach($portSettings as $setting) {
668
-			$p = $setting['port'];
669
-			$t = $setting['tls'];
670
-			\OCP\Util::writeLog('user_ldap', 'Wiz: trying port '. $p . ', TLS '. $t, \OCP\Util::DEBUG);
671
-			//connectAndBind may throw Exception, it needs to be catched by the
672
-			//callee of this method
673
-
674
-			try {
675
-				$settingsFound = $this->connectAndBind($p, $t);
676
-			} catch (\Exception $e) {
677
-				// any reply other than -1 (= cannot connect) is already okay,
678
-				// because then we found the server
679
-				// unavailable startTLS returns -11
680
-				if($e->getCode() > 0) {
681
-					$settingsFound = true;
682
-				} else {
683
-					throw $e;
684
-				}
685
-			}
686
-
687
-			if ($settingsFound === true) {
688
-				$config = array(
689
-					'ldapPort' => $p,
690
-					'ldapTLS' => intval($t)
691
-				);
692
-				$this->configuration->setConfiguration($config);
693
-				\OCP\Util::writeLog('user_ldap', 'Wiz: detected Port ' . $p, \OCP\Util::DEBUG);
694
-				$this->result->addChange('ldap_port', $p);
695
-				return $this->result;
696
-			}
697
-		}
698
-
699
-		//custom port, undetected (we do not brute force)
700
-		return false;
701
-	}
702
-
703
-	/**
704
-	 * tries to determine a base dn from User DN or LDAP Host
705
-	 * @return WizardResult|false WizardResult on success, false otherwise
706
-	 */
707
-	public function guessBaseDN() {
708
-		if(!$this->checkRequirements(array('ldapHost',
709
-										   'ldapPort',
710
-										   ))) {
711
-			return false;
712
-		}
713
-
714
-		//check whether a DN is given in the agent name (99.9% of all cases)
715
-		$base = null;
716
-		$i = stripos($this->configuration->ldapAgentName, 'dc=');
717
-		if($i !== false) {
718
-			$base = substr($this->configuration->ldapAgentName, $i);
719
-			if($this->testBaseDN($base)) {
720
-				$this->applyFind('ldap_base', $base);
721
-				return $this->result;
722
-			}
723
-		}
724
-
725
-		//this did not help :(
726
-		//Let's see whether we can parse the Host URL and convert the domain to
727
-		//a base DN
728
-		$helper = new Helper(\OC::$server->getConfig());
729
-		$domain = $helper->getDomainFromURL($this->configuration->ldapHost);
730
-		if(!$domain) {
731
-			return false;
732
-		}
733
-
734
-		$dparts = explode('.', $domain);
735
-		while(count($dparts) > 0) {
736
-			$base2 = 'dc=' . implode(',dc=', $dparts);
737
-			if ($base !== $base2 && $this->testBaseDN($base2)) {
738
-				$this->applyFind('ldap_base', $base2);
739
-				return $this->result;
740
-			}
741
-			array_shift($dparts);
742
-		}
743
-
744
-		return false;
745
-	}
746
-
747
-	/**
748
-	 * sets the found value for the configuration key in the WizardResult
749
-	 * as well as in the Configuration instance
750
-	 * @param string $key the configuration key
751
-	 * @param string $value the (detected) value
752
-	 *
753
-	 */
754
-	private function applyFind($key, $value) {
755
-		$this->result->addChange($key, $value);
756
-		$this->configuration->setConfiguration(array($key => $value));
757
-	}
758
-
759
-	/**
760
-	 * Checks, whether a port was entered in the Host configuration
761
-	 * field. In this case the port will be stripped off, but also stored as
762
-	 * setting.
763
-	 */
764
-	private function checkHost() {
765
-		$host = $this->configuration->ldapHost;
766
-		$hostInfo = parse_url($host);
767
-
768
-		//removes Port from Host
769
-		if(is_array($hostInfo) && isset($hostInfo['port'])) {
770
-			$port = $hostInfo['port'];
771
-			$host = str_replace(':'.$port, '', $host);
772
-			$this->applyFind('ldap_host', $host);
773
-			$this->applyFind('ldap_port', $port);
774
-		}
775
-	}
776
-
777
-	/**
778
-	 * tries to detect the group member association attribute which is
779
-	 * one of 'uniqueMember', 'memberUid', 'member', 'gidNumber'
780
-	 * @return string|false, string with the attribute name, false on error
781
-	 * @throws \Exception
782
-	 */
783
-	private function detectGroupMemberAssoc() {
784
-		$possibleAttrs = array('uniqueMember', 'memberUid', 'member', 'gidNumber');
785
-		$filter = $this->configuration->ldapGroupFilter;
786
-		if(empty($filter)) {
787
-			return false;
788
-		}
789
-		$cr = $this->getConnection();
790
-		if(!$cr) {
791
-			throw new \Exception('Could not connect to LDAP');
792
-		}
793
-		$base = $this->configuration->ldapBase[0];
794
-		$rr = $this->ldap->search($cr, $base, $filter, $possibleAttrs, 0, 1000);
795
-		if(!$this->ldap->isResource($rr)) {
796
-			return false;
797
-		}
798
-		$er = $this->ldap->firstEntry($cr, $rr);
799
-		while(is_resource($er)) {
800
-			$this->ldap->getDN($cr, $er);
801
-			$attrs = $this->ldap->getAttributes($cr, $er);
802
-			$result = array();
803
-			$possibleAttrsCount = count($possibleAttrs);
804
-			for($i = 0; $i < $possibleAttrsCount; $i++) {
805
-				if(isset($attrs[$possibleAttrs[$i]])) {
806
-					$result[$possibleAttrs[$i]] = $attrs[$possibleAttrs[$i]]['count'];
807
-				}
808
-			}
809
-			if(!empty($result)) {
810
-				natsort($result);
811
-				return key($result);
812
-			}
813
-
814
-			$er = $this->ldap->nextEntry($cr, $er);
815
-		}
816
-
817
-		return false;
818
-	}
819
-
820
-	/**
821
-	 * Checks whether for a given BaseDN results will be returned
822
-	 * @param string $base the BaseDN to test
823
-	 * @return bool true on success, false otherwise
824
-	 * @throws \Exception
825
-	 */
826
-	private function testBaseDN($base) {
827
-		$cr = $this->getConnection();
828
-		if(!$cr) {
829
-			throw new \Exception('Could not connect to LDAP');
830
-		}
831
-
832
-		//base is there, let's validate it. If we search for anything, we should
833
-		//get a result set > 0 on a proper base
834
-		$rr = $this->ldap->search($cr, $base, 'objectClass=*', array('dn'), 0, 1);
835
-		if(!$this->ldap->isResource($rr)) {
836
-			$errorNo  = $this->ldap->errno($cr);
837
-			$errorMsg = $this->ldap->error($cr);
838
-			\OCP\Util::writeLog('user_ldap', 'Wiz: Could not search base '.$base.
839
-							' Error '.$errorNo.': '.$errorMsg, \OCP\Util::INFO);
840
-			return false;
841
-		}
842
-		$entries = $this->ldap->countEntries($cr, $rr);
843
-		return ($entries !== false) && ($entries > 0);
844
-	}
845
-
846
-	/**
847
-	 * Checks whether the server supports memberOf in LDAP Filter.
848
-	 * Note: at least in OpenLDAP, availability of memberOf is dependent on
849
-	 * a configured objectClass. I.e. not necessarily for all available groups
850
-	 * memberOf does work.
851
-	 *
852
-	 * @return bool true if it does, false otherwise
853
-	 * @throws \Exception
854
-	 */
855
-	private function testMemberOf() {
856
-		$cr = $this->getConnection();
857
-		if(!$cr) {
858
-			throw new \Exception('Could not connect to LDAP');
859
-		}
860
-		$result = $this->access->countUsers('memberOf=*', array('memberOf'), 1);
861
-		if(is_int($result) &&  $result > 0) {
862
-			return true;
863
-		}
864
-		return false;
865
-	}
866
-
867
-	/**
868
-	 * creates an LDAP Filter from given configuration
869
-	 * @param integer $filterType int, for which use case the filter shall be created
870
-	 * can be any of self::LFILTER_USER_LIST, self::LFILTER_LOGIN or
871
-	 * self::LFILTER_GROUP_LIST
872
-	 * @return string|false string with the filter on success, false otherwise
873
-	 * @throws \Exception
874
-	 */
875
-	private function composeLdapFilter($filterType) {
876
-		$filter = '';
877
-		$parts = 0;
878
-		switch ($filterType) {
879
-			case self::LFILTER_USER_LIST:
880
-				$objcs = $this->configuration->ldapUserFilterObjectclass;
881
-				//glue objectclasses
882
-				if(is_array($objcs) && count($objcs) > 0) {
883
-					$filter .= '(|';
884
-					foreach($objcs as $objc) {
885
-						$filter .= '(objectclass=' . $objc . ')';
886
-					}
887
-					$filter .= ')';
888
-					$parts++;
889
-				}
890
-				//glue group memberships
891
-				if($this->configuration->hasMemberOfFilterSupport) {
892
-					$cns = $this->configuration->ldapUserFilterGroups;
893
-					if(is_array($cns) && count($cns) > 0) {
894
-						$filter .= '(|';
895
-						$cr = $this->getConnection();
896
-						if(!$cr) {
897
-							throw new \Exception('Could not connect to LDAP');
898
-						}
899
-						$base = $this->configuration->ldapBase[0];
900
-						foreach($cns as $cn) {
901
-							$rr = $this->ldap->search($cr, $base, 'cn=' . $cn, array('dn', 'primaryGroupToken'));
902
-							if(!$this->ldap->isResource($rr)) {
903
-								continue;
904
-							}
905
-							$er = $this->ldap->firstEntry($cr, $rr);
906
-							$attrs = $this->ldap->getAttributes($cr, $er);
907
-							$dn = $this->ldap->getDN($cr, $er);
908
-							if ($dn == false || $dn === '') {
909
-								continue;
910
-							}
911
-							$filterPart = '(memberof=' . $dn . ')';
912
-							if(isset($attrs['primaryGroupToken'])) {
913
-								$pgt = $attrs['primaryGroupToken'][0];
914
-								$primaryFilterPart = '(primaryGroupID=' . $pgt .')';
915
-								$filterPart = '(|' . $filterPart . $primaryFilterPart . ')';
916
-							}
917
-							$filter .= $filterPart;
918
-						}
919
-						$filter .= ')';
920
-					}
921
-					$parts++;
922
-				}
923
-				//wrap parts in AND condition
924
-				if($parts > 1) {
925
-					$filter = '(&' . $filter . ')';
926
-				}
927
-				if ($filter === '') {
928
-					$filter = '(objectclass=*)';
929
-				}
930
-				break;
931
-
932
-			case self::LFILTER_GROUP_LIST:
933
-				$objcs = $this->configuration->ldapGroupFilterObjectclass;
934
-				//glue objectclasses
935
-				if(is_array($objcs) && count($objcs) > 0) {
936
-					$filter .= '(|';
937
-					foreach($objcs as $objc) {
938
-						$filter .= '(objectclass=' . $objc . ')';
939
-					}
940
-					$filter .= ')';
941
-					$parts++;
942
-				}
943
-				//glue group memberships
944
-				$cns = $this->configuration->ldapGroupFilterGroups;
945
-				if(is_array($cns) && count($cns) > 0) {
946
-					$filter .= '(|';
947
-					foreach($cns as $cn) {
948
-						$filter .= '(cn=' . $cn . ')';
949
-					}
950
-					$filter .= ')';
951
-				}
952
-				$parts++;
953
-				//wrap parts in AND condition
954
-				if($parts > 1) {
955
-					$filter = '(&' . $filter . ')';
956
-				}
957
-				break;
958
-
959
-			case self::LFILTER_LOGIN:
960
-				$ulf = $this->configuration->ldapUserFilter;
961
-				$loginpart = '=%uid';
962
-				$filterUsername = '';
963
-				$userAttributes = $this->getUserAttributes();
964
-				$userAttributes = array_change_key_case(array_flip($userAttributes));
965
-				$parts = 0;
966
-
967
-				if($this->configuration->ldapLoginFilterUsername === '1') {
968
-					$attr = '';
969
-					if(isset($userAttributes['uid'])) {
970
-						$attr = 'uid';
971
-					} else if(isset($userAttributes['samaccountname'])) {
972
-						$attr = 'samaccountname';
973
-					} else if(isset($userAttributes['cn'])) {
974
-						//fallback
975
-						$attr = 'cn';
976
-					}
977
-					if ($attr !== '') {
978
-						$filterUsername = '(' . $attr . $loginpart . ')';
979
-						$parts++;
980
-					}
981
-				}
982
-
983
-				$filterEmail = '';
984
-				if($this->configuration->ldapLoginFilterEmail === '1') {
985
-					$filterEmail = '(|(mailPrimaryAddress=%uid)(mail=%uid))';
986
-					$parts++;
987
-				}
988
-
989
-				$filterAttributes = '';
990
-				$attrsToFilter = $this->configuration->ldapLoginFilterAttributes;
991
-				if(is_array($attrsToFilter) && count($attrsToFilter) > 0) {
992
-					$filterAttributes = '(|';
993
-					foreach($attrsToFilter as $attribute) {
994
-						$filterAttributes .= '(' . $attribute . $loginpart . ')';
995
-					}
996
-					$filterAttributes .= ')';
997
-					$parts++;
998
-				}
999
-
1000
-				$filterLogin = '';
1001
-				if($parts > 1) {
1002
-					$filterLogin = '(|';
1003
-				}
1004
-				$filterLogin .= $filterUsername;
1005
-				$filterLogin .= $filterEmail;
1006
-				$filterLogin .= $filterAttributes;
1007
-				if($parts > 1) {
1008
-					$filterLogin .= ')';
1009
-				}
1010
-
1011
-				$filter = '(&'.$ulf.$filterLogin.')';
1012
-				break;
1013
-		}
1014
-
1015
-		\OCP\Util::writeLog('user_ldap', 'Wiz: Final filter '.$filter, \OCP\Util::DEBUG);
1016
-
1017
-		return $filter;
1018
-	}
1019
-
1020
-	/**
1021
-	 * Connects and Binds to an LDAP Server
1022
-	 * @param int $port the port to connect with
1023
-	 * @param bool $tls whether startTLS is to be used
1024
-	 * @param bool $ncc
1025
-	 * @return bool
1026
-	 * @throws \Exception
1027
-	 */
1028
-	private function connectAndBind($port = 389, $tls = false, $ncc = false) {
1029
-		if($ncc) {
1030
-			//No certificate check
1031
-			//FIXME: undo afterwards
1032
-			putenv('LDAPTLS_REQCERT=never');
1033
-		}
1034
-
1035
-		//connect, does not really trigger any server communication
1036
-		\OCP\Util::writeLog('user_ldap', 'Wiz: Checking Host Info ', \OCP\Util::DEBUG);
1037
-		$host = $this->configuration->ldapHost;
1038
-		$hostInfo = parse_url($host);
1039
-		if(!$hostInfo) {
1040
-			throw new \Exception(self::$l->t('Invalid Host'));
1041
-		}
1042
-		\OCP\Util::writeLog('user_ldap', 'Wiz: Attempting to connect ', \OCP\Util::DEBUG);
1043
-		$cr = $this->ldap->connect($host, $port);
1044
-		if(!is_resource($cr)) {
1045
-			throw new \Exception(self::$l->t('Invalid Host'));
1046
-		}
1047
-
1048
-		\OCP\Util::writeLog('user_ldap', 'Wiz: Setting LDAP Options ', \OCP\Util::DEBUG);
1049
-		//set LDAP options
1050
-		$this->ldap->setOption($cr, LDAP_OPT_PROTOCOL_VERSION, 3);
1051
-		$this->ldap->setOption($cr, LDAP_OPT_REFERRALS, 0);
1052
-		$this->ldap->setOption($cr, LDAP_OPT_NETWORK_TIMEOUT, self::LDAP_NW_TIMEOUT);
1053
-
1054
-		try {
1055
-			if($tls) {
1056
-				$isTlsWorking = @$this->ldap->startTls($cr);
1057
-				if(!$isTlsWorking) {
1058
-					return false;
1059
-				}
1060
-			}
1061
-
1062
-			\OCP\Util::writeLog('user_ldap', 'Wiz: Attemping to Bind ', \OCP\Util::DEBUG);
1063
-			//interesting part: do the bind!
1064
-			$login = $this->ldap->bind($cr,
1065
-				$this->configuration->ldapAgentName,
1066
-				$this->configuration->ldapAgentPassword
1067
-			);
1068
-			$errNo = $this->ldap->errno($cr);
1069
-			$error = ldap_error($cr);
1070
-			$this->ldap->unbind($cr);
1071
-		} catch(ServerNotAvailableException $e) {
1072
-			return false;
1073
-		}
1074
-
1075
-		if($login === true) {
1076
-			$this->ldap->unbind($cr);
1077
-			if($ncc) {
1078
-				throw new \Exception('Certificate cannot be validated.');
1079
-			}
1080
-			\OCP\Util::writeLog('user_ldap', 'Wiz: Bind successful to Port '. $port . ' TLS ' . intval($tls), \OCP\Util::DEBUG);
1081
-			return true;
1082
-		}
1083
-
1084
-		if($errNo === -1 || ($errNo === 2 && $ncc)) {
1085
-			//host, port or TLS wrong
1086
-			return false;
1087
-		} else if ($errNo === 2) {
1088
-			return $this->connectAndBind($port, $tls, true);
1089
-		}
1090
-		throw new \Exception($error, $errNo);
1091
-	}
1092
-
1093
-	/**
1094
-	 * checks whether a valid combination of agent and password has been
1095
-	 * provided (either two values or nothing for anonymous connect)
1096
-	 * @return bool, true if everything is fine, false otherwise
1097
-	 */
1098
-	private function checkAgentRequirements() {
1099
-		$agent = $this->configuration->ldapAgentName;
1100
-		$pwd = $this->configuration->ldapAgentPassword;
1101
-
1102
-		return
1103
-			($agent !== '' && $pwd !== '')
1104
-			||  ($agent === '' && $pwd === '')
1105
-		;
1106
-	}
1107
-
1108
-	/**
1109
-	 * @param array $reqs
1110
-	 * @return bool
1111
-	 */
1112
-	private function checkRequirements($reqs) {
1113
-		$this->checkAgentRequirements();
1114
-		foreach($reqs as $option) {
1115
-			$value = $this->configuration->$option;
1116
-			if(empty($value)) {
1117
-				return false;
1118
-			}
1119
-		}
1120
-		return true;
1121
-	}
1122
-
1123
-	/**
1124
-	 * does a cumulativeSearch on LDAP to get different values of a
1125
-	 * specified attribute
1126
-	 * @param string[] $filters array, the filters that shall be used in the search
1127
-	 * @param string $attr the attribute of which a list of values shall be returned
1128
-	 * @param int $dnReadLimit the amount of how many DNs should be analyzed.
1129
-	 * The lower, the faster
1130
-	 * @param string $maxF string. if not null, this variable will have the filter that
1131
-	 * yields most result entries
1132
-	 * @return array|false an array with the values on success, false otherwise
1133
-	 */
1134
-	public function cumulativeSearchOnAttribute($filters, $attr, $dnReadLimit = 3, &$maxF = null) {
1135
-		$dnRead = array();
1136
-		$foundItems = array();
1137
-		$maxEntries = 0;
1138
-		if(!is_array($this->configuration->ldapBase)
1139
-		   || !isset($this->configuration->ldapBase[0])) {
1140
-			return false;
1141
-		}
1142
-		$base = $this->configuration->ldapBase[0];
1143
-		$cr = $this->getConnection();
1144
-		if(!$this->ldap->isResource($cr)) {
1145
-			return false;
1146
-		}
1147
-		$lastFilter = null;
1148
-		if(isset($filters[count($filters)-1])) {
1149
-			$lastFilter = $filters[count($filters)-1];
1150
-		}
1151
-		foreach($filters as $filter) {
1152
-			if($lastFilter === $filter && count($foundItems) > 0) {
1153
-				//skip when the filter is a wildcard and results were found
1154
-				continue;
1155
-			}
1156
-			// 20k limit for performance and reason
1157
-			$rr = $this->ldap->search($cr, $base, $filter, array($attr), 0, 20000);
1158
-			if(!$this->ldap->isResource($rr)) {
1159
-				continue;
1160
-			}
1161
-			$entries = $this->ldap->countEntries($cr, $rr);
1162
-			$getEntryFunc = 'firstEntry';
1163
-			if(($entries !== false) && ($entries > 0)) {
1164
-				if(!is_null($maxF) && $entries > $maxEntries) {
1165
-					$maxEntries = $entries;
1166
-					$maxF = $filter;
1167
-				}
1168
-				$dnReadCount = 0;
1169
-				do {
1170
-					$entry = $this->ldap->$getEntryFunc($cr, $rr);
1171
-					$getEntryFunc = 'nextEntry';
1172
-					if(!$this->ldap->isResource($entry)) {
1173
-						continue 2;
1174
-					}
1175
-					$rr = $entry; //will be expected by nextEntry next round
1176
-					$attributes = $this->ldap->getAttributes($cr, $entry);
1177
-					$dn = $this->ldap->getDN($cr, $entry);
1178
-					if($dn === false || in_array($dn, $dnRead)) {
1179
-						continue;
1180
-					}
1181
-					$newItems = array();
1182
-					$state = $this->getAttributeValuesFromEntry($attributes,
1183
-																$attr,
1184
-																$newItems);
1185
-					$dnReadCount++;
1186
-					$foundItems = array_merge($foundItems, $newItems);
1187
-					$this->resultCache[$dn][$attr] = $newItems;
1188
-					$dnRead[] = $dn;
1189
-				} while(($state === self::LRESULT_PROCESSED_SKIP
1190
-						|| $this->ldap->isResource($entry))
1191
-						&& ($dnReadLimit === 0 || $dnReadCount < $dnReadLimit));
1192
-			}
1193
-		}
1194
-
1195
-		return array_unique($foundItems);
1196
-	}
1197
-
1198
-	/**
1199
-	 * determines if and which $attr are available on the LDAP server
1200
-	 * @param string[] $objectclasses the objectclasses to use as search filter
1201
-	 * @param string $attr the attribute to look for
1202
-	 * @param string $dbkey the dbkey of the setting the feature is connected to
1203
-	 * @param string $confkey the confkey counterpart for the $dbkey as used in the
1204
-	 * Configuration class
1205
-	 * @param bool $po whether the objectClass with most result entries
1206
-	 * shall be pre-selected via the result
1207
-	 * @return array|false list of found items.
1208
-	 * @throws \Exception
1209
-	 */
1210
-	private function determineFeature($objectclasses, $attr, $dbkey, $confkey, $po = false) {
1211
-		$cr = $this->getConnection();
1212
-		if(!$cr) {
1213
-			throw new \Exception('Could not connect to LDAP');
1214
-		}
1215
-		$p = 'objectclass=';
1216
-		foreach($objectclasses as $key => $value) {
1217
-			$objectclasses[$key] = $p.$value;
1218
-		}
1219
-		$maxEntryObjC = '';
1220
-
1221
-		//how deep to dig?
1222
-		//When looking for objectclasses, testing few entries is sufficient,
1223
-		$dig = 3;
1224
-
1225
-		$availableFeatures =
1226
-			$this->cumulativeSearchOnAttribute($objectclasses, $attr,
1227
-											   $dig, $maxEntryObjC);
1228
-		if(is_array($availableFeatures)
1229
-		   && count($availableFeatures) > 0) {
1230
-			natcasesort($availableFeatures);
1231
-			//natcasesort keeps indices, but we must get rid of them for proper
1232
-			//sorting in the web UI. Therefore: array_values
1233
-			$this->result->addOptions($dbkey, array_values($availableFeatures));
1234
-		} else {
1235
-			throw new \Exception(self::$l->t('Could not find the desired feature'));
1236
-		}
1237
-
1238
-		$setFeatures = $this->configuration->$confkey;
1239
-		if(is_array($setFeatures) && !empty($setFeatures)) {
1240
-			//something is already configured? pre-select it.
1241
-			$this->result->addChange($dbkey, $setFeatures);
1242
-		} else if ($po && $maxEntryObjC !== '') {
1243
-			//pre-select objectclass with most result entries
1244
-			$maxEntryObjC = str_replace($p, '', $maxEntryObjC);
1245
-			$this->applyFind($dbkey, $maxEntryObjC);
1246
-			$this->result->addChange($dbkey, $maxEntryObjC);
1247
-		}
1248
-
1249
-		return $availableFeatures;
1250
-	}
1251
-
1252
-	/**
1253
-	 * appends a list of values fr
1254
-	 * @param resource $result the return value from ldap_get_attributes
1255
-	 * @param string $attribute the attribute values to look for
1256
-	 * @param array &$known new values will be appended here
1257
-	 * @return int, state on of the class constants LRESULT_PROCESSED_OK,
1258
-	 * LRESULT_PROCESSED_INVALID or LRESULT_PROCESSED_SKIP
1259
-	 */
1260
-	private function getAttributeValuesFromEntry($result, $attribute, &$known) {
1261
-		if(!is_array($result)
1262
-		   || !isset($result['count'])
1263
-		   || !$result['count'] > 0) {
1264
-			return self::LRESULT_PROCESSED_INVALID;
1265
-		}
1266
-
1267
-		// strtolower on all keys for proper comparison
1268
-		$result = \OCP\Util::mb_array_change_key_case($result);
1269
-		$attribute = strtolower($attribute);
1270
-		if(isset($result[$attribute])) {
1271
-			foreach($result[$attribute] as $key => $val) {
1272
-				if($key === 'count') {
1273
-					continue;
1274
-				}
1275
-				if(!in_array($val, $known)) {
1276
-					$known[] = $val;
1277
-				}
1278
-			}
1279
-			return self::LRESULT_PROCESSED_OK;
1280
-		} else {
1281
-			return self::LRESULT_PROCESSED_SKIP;
1282
-		}
1283
-	}
1284
-
1285
-	/**
1286
-	 * @return bool|mixed
1287
-	 */
1288
-	private function getConnection() {
1289
-		if(!is_null($this->cr)) {
1290
-			return $this->cr;
1291
-		}
1292
-
1293
-		$cr = $this->ldap->connect(
1294
-			$this->configuration->ldapHost,
1295
-			$this->configuration->ldapPort
1296
-		);
1297
-
1298
-		$this->ldap->setOption($cr, LDAP_OPT_PROTOCOL_VERSION, 3);
1299
-		$this->ldap->setOption($cr, LDAP_OPT_REFERRALS, 0);
1300
-		$this->ldap->setOption($cr, LDAP_OPT_NETWORK_TIMEOUT, self::LDAP_NW_TIMEOUT);
1301
-		if($this->configuration->ldapTLS === 1) {
1302
-			$this->ldap->startTls($cr);
1303
-		}
1304
-
1305
-		$lo = @$this->ldap->bind($cr,
1306
-								 $this->configuration->ldapAgentName,
1307
-								 $this->configuration->ldapAgentPassword);
1308
-		if($lo === true) {
1309
-			$this->$cr = $cr;
1310
-			return $cr;
1311
-		}
1312
-
1313
-		return false;
1314
-	}
1315
-
1316
-	/**
1317
-	 * @return array
1318
-	 */
1319
-	private function getDefaultLdapPortSettings() {
1320
-		static $settings = array(
1321
-								array('port' => 7636, 'tls' => false),
1322
-								array('port' =>  636, 'tls' => false),
1323
-								array('port' => 7389, 'tls' => true),
1324
-								array('port' =>  389, 'tls' => true),
1325
-								array('port' => 7389, 'tls' => false),
1326
-								array('port' =>  389, 'tls' => false),
1327
-						  );
1328
-		return $settings;
1329
-	}
1330
-
1331
-	/**
1332
-	 * @return array
1333
-	 */
1334
-	private function getPortSettingsToTry() {
1335
-		//389 ← LDAP / Unencrypted or StartTLS
1336
-		//636 ← LDAPS / SSL
1337
-		//7xxx ← UCS. need to be checked first, because both ports may be open
1338
-		$host = $this->configuration->ldapHost;
1339
-		$port = intval($this->configuration->ldapPort);
1340
-		$portSettings = array();
1341
-
1342
-		//In case the port is already provided, we will check this first
1343
-		if($port > 0) {
1344
-			$hostInfo = parse_url($host);
1345
-			if(!(is_array($hostInfo)
1346
-				&& isset($hostInfo['scheme'])
1347
-				&& stripos($hostInfo['scheme'], 'ldaps') !== false)) {
1348
-				$portSettings[] = array('port' => $port, 'tls' => true);
1349
-			}
1350
-			$portSettings[] =array('port' => $port, 'tls' => false);
1351
-		}
1352
-
1353
-		//default ports
1354
-		$portSettings = array_merge($portSettings,
1355
-		                            $this->getDefaultLdapPortSettings());
1356
-
1357
-		return $portSettings;
1358
-	}
41
+    /** @var \OCP\IL10N */
42
+    static protected $l;
43
+    protected $access;
44
+    protected $cr;
45
+    protected $configuration;
46
+    protected $result;
47
+    protected $resultCache = array();
48
+
49
+    const LRESULT_PROCESSED_OK = 2;
50
+    const LRESULT_PROCESSED_INVALID = 3;
51
+    const LRESULT_PROCESSED_SKIP = 4;
52
+
53
+    const LFILTER_LOGIN      = 2;
54
+    const LFILTER_USER_LIST  = 3;
55
+    const LFILTER_GROUP_LIST = 4;
56
+
57
+    const LFILTER_MODE_ASSISTED = 2;
58
+    const LFILTER_MODE_RAW = 1;
59
+
60
+    const LDAP_NW_TIMEOUT = 4;
61
+
62
+    /**
63
+     * Constructor
64
+     * @param Configuration $configuration an instance of Configuration
65
+     * @param ILDAPWrapper $ldap an instance of ILDAPWrapper
66
+     * @param Access $access
67
+     */
68
+    public function __construct(Configuration $configuration, ILDAPWrapper $ldap, Access $access) {
69
+        parent::__construct($ldap);
70
+        $this->configuration = $configuration;
71
+        if(is_null(Wizard::$l)) {
72
+            Wizard::$l = \OC::$server->getL10N('user_ldap');
73
+        }
74
+        $this->access = $access;
75
+        $this->result = new WizardResult();
76
+    }
77
+
78
+    public function  __destruct() {
79
+        if($this->result->hasChanges()) {
80
+            $this->configuration->saveConfiguration();
81
+        }
82
+    }
83
+
84
+    /**
85
+     * counts entries in the LDAP directory
86
+     *
87
+     * @param string $filter the LDAP search filter
88
+     * @param string $type a string being either 'users' or 'groups';
89
+     * @return bool|int
90
+     * @throws \Exception
91
+     */
92
+    public function countEntries($filter, $type) {
93
+        $reqs = array('ldapHost', 'ldapPort', 'ldapBase');
94
+        if($type === 'users') {
95
+            $reqs[] = 'ldapUserFilter';
96
+        }
97
+        if(!$this->checkRequirements($reqs)) {
98
+            throw new \Exception('Requirements not met', 400);
99
+        }
100
+
101
+        $attr = array('dn'); // default
102
+        $limit = 1001;
103
+        if($type === 'groups') {
104
+            $result =  $this->access->countGroups($filter, $attr, $limit);
105
+        } else if($type === 'users') {
106
+            $result = $this->access->countUsers($filter, $attr, $limit);
107
+        } else if ($type === 'objects') {
108
+            $result = $this->access->countObjects($limit);
109
+        } else {
110
+            throw new \Exception('Internal error: Invalid object type', 500);
111
+        }
112
+
113
+        return $result;
114
+    }
115
+
116
+    /**
117
+     * formats the return value of a count operation to the string to be
118
+     * inserted.
119
+     *
120
+     * @param bool|int $count
121
+     * @return int|string
122
+     */
123
+    private function formatCountResult($count) {
124
+        $formatted = ($count !== false) ? $count : 0;
125
+        if($formatted > 1000) {
126
+            $formatted = '> 1000';
127
+        }
128
+        return $formatted;
129
+    }
130
+
131
+    public function countGroups() {
132
+        $filter = $this->configuration->ldapGroupFilter;
133
+
134
+        if(empty($filter)) {
135
+            $output = self::$l->n('%s group found', '%s groups found', 0, array(0));
136
+            $this->result->addChange('ldap_group_count', $output);
137
+            return $this->result;
138
+        }
139
+
140
+        try {
141
+            $groupsTotal = $this->formatCountResult($this->countEntries($filter, 'groups'));
142
+        } catch (\Exception $e) {
143
+            //400 can be ignored, 500 is forwarded
144
+            if($e->getCode() === 500) {
145
+                throw $e;
146
+            }
147
+            return false;
148
+        }
149
+        $output = self::$l->n('%s group found', '%s groups found', $groupsTotal, array($groupsTotal));
150
+        $this->result->addChange('ldap_group_count', $output);
151
+        return $this->result;
152
+    }
153
+
154
+    /**
155
+     * @return WizardResult
156
+     * @throws \Exception
157
+     */
158
+    public function countUsers() {
159
+        $filter = $this->access->getFilterForUserCount();
160
+
161
+        $usersTotal = $this->formatCountResult($this->countEntries($filter, 'users'));
162
+        $output = self::$l->n('%s user found', '%s users found', $usersTotal, array($usersTotal));
163
+        $this->result->addChange('ldap_user_count', $output);
164
+        return $this->result;
165
+    }
166
+
167
+    /**
168
+     * counts any objects in the currently set base dn
169
+     *
170
+     * @return WizardResult
171
+     * @throws \Exception
172
+     */
173
+    public function countInBaseDN() {
174
+        // we don't need to provide a filter in this case
175
+        $total = $this->countEntries(null, 'objects');
176
+        if($total === false) {
177
+            throw new \Exception('invalid results received');
178
+        }
179
+        $this->result->addChange('ldap_test_base', $total);
180
+        return $this->result;
181
+    }
182
+
183
+    /**
184
+     * counts users with a specified attribute
185
+     * @param string $attr
186
+     * @param bool $existsCheck
187
+     * @return int|bool
188
+     */
189
+    public function countUsersWithAttribute($attr, $existsCheck = false) {
190
+        if(!$this->checkRequirements(array('ldapHost',
191
+                                            'ldapPort',
192
+                                            'ldapBase',
193
+                                            'ldapUserFilter',
194
+                                            ))) {
195
+            return  false;
196
+        }
197
+
198
+        $filter = $this->access->combineFilterWithAnd(array(
199
+            $this->configuration->ldapUserFilter,
200
+            $attr . '=*'
201
+        ));
202
+
203
+        $limit = ($existsCheck === false) ? null : 1;
204
+
205
+        return $this->access->countUsers($filter, array('dn'), $limit);
206
+    }
207
+
208
+    /**
209
+     * detects the display name attribute. If a setting is already present that
210
+     * returns at least one hit, the detection will be canceled.
211
+     * @return WizardResult|bool
212
+     * @throws \Exception
213
+     */
214
+    public function detectUserDisplayNameAttribute() {
215
+        if(!$this->checkRequirements(array('ldapHost',
216
+                                        'ldapPort',
217
+                                        'ldapBase',
218
+                                        'ldapUserFilter',
219
+                                        ))) {
220
+            return  false;
221
+        }
222
+
223
+        $attr = $this->configuration->ldapUserDisplayName;
224
+        if ($attr !== '' && $attr !== 'displayName') {
225
+            // most likely not the default value with upper case N,
226
+            // verify it still produces a result
227
+            $count = intval($this->countUsersWithAttribute($attr, true));
228
+            if($count > 0) {
229
+                //no change, but we sent it back to make sure the user interface
230
+                //is still correct, even if the ajax call was cancelled meanwhile
231
+                $this->result->addChange('ldap_display_name', $attr);
232
+                return $this->result;
233
+            }
234
+        }
235
+
236
+        // first attribute that has at least one result wins
237
+        $displayNameAttrs = array('displayname', 'cn');
238
+        foreach ($displayNameAttrs as $attr) {
239
+            $count = intval($this->countUsersWithAttribute($attr, true));
240
+
241
+            if($count > 0) {
242
+                $this->applyFind('ldap_display_name', $attr);
243
+                return $this->result;
244
+            }
245
+        };
246
+
247
+        throw new \Exception(self::$l->t('Could not detect user display name attribute. Please specify it yourself in advanced LDAP settings.'));
248
+    }
249
+
250
+    /**
251
+     * detects the most often used email attribute for users applying to the
252
+     * user list filter. If a setting is already present that returns at least
253
+     * one hit, the detection will be canceled.
254
+     * @return WizardResult|bool
255
+     */
256
+    public function detectEmailAttribute() {
257
+        if(!$this->checkRequirements(array('ldapHost',
258
+                                            'ldapPort',
259
+                                            'ldapBase',
260
+                                            'ldapUserFilter',
261
+                                            ))) {
262
+            return  false;
263
+        }
264
+
265
+        $attr = $this->configuration->ldapEmailAttribute;
266
+        if ($attr !== '') {
267
+            $count = intval($this->countUsersWithAttribute($attr, true));
268
+            if($count > 0) {
269
+                return false;
270
+            }
271
+            $writeLog = true;
272
+        } else {
273
+            $writeLog = false;
274
+        }
275
+
276
+        $emailAttributes = array('mail', 'mailPrimaryAddress');
277
+        $winner = '';
278
+        $maxUsers = 0;
279
+        foreach($emailAttributes as $attr) {
280
+            $count = $this->countUsersWithAttribute($attr);
281
+            if($count > $maxUsers) {
282
+                $maxUsers = $count;
283
+                $winner = $attr;
284
+            }
285
+        }
286
+
287
+        if($winner !== '') {
288
+            $this->applyFind('ldap_email_attr', $winner);
289
+            if($writeLog) {
290
+                \OCP\Util::writeLog('user_ldap', 'The mail attribute has ' .
291
+                    'automatically been reset, because the original value ' .
292
+                    'did not return any results.', \OCP\Util::INFO);
293
+            }
294
+        }
295
+
296
+        return $this->result;
297
+    }
298
+
299
+    /**
300
+     * @return WizardResult
301
+     * @throws \Exception
302
+     */
303
+    public function determineAttributes() {
304
+        if(!$this->checkRequirements(array('ldapHost',
305
+                                            'ldapPort',
306
+                                            'ldapBase',
307
+                                            'ldapUserFilter',
308
+                                            ))) {
309
+            return  false;
310
+        }
311
+
312
+        $attributes = $this->getUserAttributes();
313
+
314
+        natcasesort($attributes);
315
+        $attributes = array_values($attributes);
316
+
317
+        $this->result->addOptions('ldap_loginfilter_attributes', $attributes);
318
+
319
+        $selected = $this->configuration->ldapLoginFilterAttributes;
320
+        if(is_array($selected) && !empty($selected)) {
321
+            $this->result->addChange('ldap_loginfilter_attributes', $selected);
322
+        }
323
+
324
+        return $this->result;
325
+    }
326
+
327
+    /**
328
+     * detects the available LDAP attributes
329
+     * @return array|false The instance's WizardResult instance
330
+     * @throws \Exception
331
+     */
332
+    private function getUserAttributes() {
333
+        if(!$this->checkRequirements(array('ldapHost',
334
+                                            'ldapPort',
335
+                                            'ldapBase',
336
+                                            'ldapUserFilter',
337
+                                            ))) {
338
+            return  false;
339
+        }
340
+        $cr = $this->getConnection();
341
+        if(!$cr) {
342
+            throw new \Exception('Could not connect to LDAP');
343
+        }
344
+
345
+        $base = $this->configuration->ldapBase[0];
346
+        $filter = $this->configuration->ldapUserFilter;
347
+        $rr = $this->ldap->search($cr, $base, $filter, array(), 1, 1);
348
+        if(!$this->ldap->isResource($rr)) {
349
+            return false;
350
+        }
351
+        $er = $this->ldap->firstEntry($cr, $rr);
352
+        $attributes = $this->ldap->getAttributes($cr, $er);
353
+        $pureAttributes = array();
354
+        for($i = 0; $i < $attributes['count']; $i++) {
355
+            $pureAttributes[] = $attributes[$i];
356
+        }
357
+
358
+        return $pureAttributes;
359
+    }
360
+
361
+    /**
362
+     * detects the available LDAP groups
363
+     * @return WizardResult|false the instance's WizardResult instance
364
+     */
365
+    public function determineGroupsForGroups() {
366
+        return $this->determineGroups('ldap_groupfilter_groups',
367
+                                        'ldapGroupFilterGroups',
368
+                                        false);
369
+    }
370
+
371
+    /**
372
+     * detects the available LDAP groups
373
+     * @return WizardResult|false the instance's WizardResult instance
374
+     */
375
+    public function determineGroupsForUsers() {
376
+        return $this->determineGroups('ldap_userfilter_groups',
377
+                                        'ldapUserFilterGroups');
378
+    }
379
+
380
+    /**
381
+     * detects the available LDAP groups
382
+     * @param string $dbKey
383
+     * @param string $confKey
384
+     * @param bool $testMemberOf
385
+     * @return WizardResult|false the instance's WizardResult instance
386
+     * @throws \Exception
387
+     */
388
+    private function determineGroups($dbKey, $confKey, $testMemberOf = true) {
389
+        if(!$this->checkRequirements(array('ldapHost',
390
+                                            'ldapPort',
391
+                                            'ldapBase',
392
+                                            ))) {
393
+            return  false;
394
+        }
395
+        $cr = $this->getConnection();
396
+        if(!$cr) {
397
+            throw new \Exception('Could not connect to LDAP');
398
+        }
399
+
400
+        $this->fetchGroups($dbKey, $confKey);
401
+
402
+        if($testMemberOf) {
403
+            $this->configuration->hasMemberOfFilterSupport = $this->testMemberOf();
404
+            $this->result->markChange();
405
+            if(!$this->configuration->hasMemberOfFilterSupport) {
406
+                throw new \Exception('memberOf is not supported by the server');
407
+            }
408
+        }
409
+
410
+        return $this->result;
411
+    }
412
+
413
+    /**
414
+     * fetches all groups from LDAP and adds them to the result object
415
+     *
416
+     * @param string $dbKey
417
+     * @param string $confKey
418
+     * @return array $groupEntries
419
+     * @throws \Exception
420
+     */
421
+    public function fetchGroups($dbKey, $confKey) {
422
+        $obclasses = array('posixGroup', 'group', 'zimbraDistributionList', 'groupOfNames');
423
+
424
+        $filterParts = array();
425
+        foreach($obclasses as $obclass) {
426
+            $filterParts[] = 'objectclass='.$obclass;
427
+        }
428
+        //we filter for everything
429
+        //- that looks like a group and
430
+        //- has the group display name set
431
+        $filter = $this->access->combineFilterWithOr($filterParts);
432
+        $filter = $this->access->combineFilterWithAnd(array($filter, 'cn=*'));
433
+
434
+        $groupNames = array();
435
+        $groupEntries = array();
436
+        $limit = 400;
437
+        $offset = 0;
438
+        do {
439
+            // we need to request dn additionally here, otherwise memberOf
440
+            // detection will fail later
441
+            $result = $this->access->searchGroups($filter, array('cn', 'dn'), $limit, $offset);
442
+            foreach($result as $item) {
443
+                if(!isset($item['cn']) && !is_array($item['cn']) && !isset($item['cn'][0])) {
444
+                    // just in case - no issue known
445
+                    continue;
446
+                }
447
+                $groupNames[] = $item['cn'][0];
448
+                $groupEntries[] = $item;
449
+            }
450
+            $offset += $limit;
451
+        } while ($this->access->hasMoreResults());
452
+
453
+        if(count($groupNames) > 0) {
454
+            natsort($groupNames);
455
+            $this->result->addOptions($dbKey, array_values($groupNames));
456
+        } else {
457
+            throw new \Exception(self::$l->t('Could not find the desired feature'));
458
+        }
459
+
460
+        $setFeatures = $this->configuration->$confKey;
461
+        if(is_array($setFeatures) && !empty($setFeatures)) {
462
+            //something is already configured? pre-select it.
463
+            $this->result->addChange($dbKey, $setFeatures);
464
+        }
465
+        return $groupEntries;
466
+    }
467
+
468
+    public function determineGroupMemberAssoc() {
469
+        if(!$this->checkRequirements(array('ldapHost',
470
+                                            'ldapPort',
471
+                                            'ldapGroupFilter',
472
+                                            ))) {
473
+            return  false;
474
+        }
475
+        $attribute = $this->detectGroupMemberAssoc();
476
+        if($attribute === false) {
477
+            return false;
478
+        }
479
+        $this->configuration->setConfiguration(array('ldapGroupMemberAssocAttr' => $attribute));
480
+        $this->result->addChange('ldap_group_member_assoc_attribute', $attribute);
481
+
482
+        return $this->result;
483
+    }
484
+
485
+    /**
486
+     * Detects the available object classes
487
+     * @return WizardResult|false the instance's WizardResult instance
488
+     * @throws \Exception
489
+     */
490
+    public function determineGroupObjectClasses() {
491
+        if(!$this->checkRequirements(array('ldapHost',
492
+                                            'ldapPort',
493
+                                            'ldapBase',
494
+                                            ))) {
495
+            return  false;
496
+        }
497
+        $cr = $this->getConnection();
498
+        if(!$cr) {
499
+            throw new \Exception('Could not connect to LDAP');
500
+        }
501
+
502
+        $obclasses = array('groupOfNames', 'groupOfUniqueNames', 'group', 'posixGroup', '*');
503
+        $this->determineFeature($obclasses,
504
+                                'objectclass',
505
+                                'ldap_groupfilter_objectclass',
506
+                                'ldapGroupFilterObjectclass',
507
+                                false);
508
+
509
+        return $this->result;
510
+    }
511
+
512
+    /**
513
+     * detects the available object classes
514
+     * @return WizardResult
515
+     * @throws \Exception
516
+     */
517
+    public function determineUserObjectClasses() {
518
+        if(!$this->checkRequirements(array('ldapHost',
519
+                                            'ldapPort',
520
+                                            'ldapBase',
521
+                                            ))) {
522
+            return  false;
523
+        }
524
+        $cr = $this->getConnection();
525
+        if(!$cr) {
526
+            throw new \Exception('Could not connect to LDAP');
527
+        }
528
+
529
+        $obclasses = array('inetOrgPerson', 'person', 'organizationalPerson',
530
+                            'user', 'posixAccount', '*');
531
+        $filter = $this->configuration->ldapUserFilter;
532
+        //if filter is empty, it is probably the first time the wizard is called
533
+        //then, apply suggestions.
534
+        $this->determineFeature($obclasses,
535
+                                'objectclass',
536
+                                'ldap_userfilter_objectclass',
537
+                                'ldapUserFilterObjectclass',
538
+                                empty($filter));
539
+
540
+        return $this->result;
541
+    }
542
+
543
+    /**
544
+     * @return WizardResult|false
545
+     * @throws \Exception
546
+     */
547
+    public function getGroupFilter() {
548
+        if(!$this->checkRequirements(array('ldapHost',
549
+                                            'ldapPort',
550
+                                            'ldapBase',
551
+                                            ))) {
552
+            return false;
553
+        }
554
+        //make sure the use display name is set
555
+        $displayName = $this->configuration->ldapGroupDisplayName;
556
+        if ($displayName === '') {
557
+            $d = $this->configuration->getDefaults();
558
+            $this->applyFind('ldap_group_display_name',
559
+                                $d['ldap_group_display_name']);
560
+        }
561
+        $filter = $this->composeLdapFilter(self::LFILTER_GROUP_LIST);
562
+
563
+        $this->applyFind('ldap_group_filter', $filter);
564
+        return $this->result;
565
+    }
566
+
567
+    /**
568
+     * @return WizardResult|false
569
+     * @throws \Exception
570
+     */
571
+    public function getUserListFilter() {
572
+        if(!$this->checkRequirements(array('ldapHost',
573
+                                            'ldapPort',
574
+                                            'ldapBase',
575
+                                            ))) {
576
+            return false;
577
+        }
578
+        //make sure the use display name is set
579
+        $displayName = $this->configuration->ldapUserDisplayName;
580
+        if ($displayName === '') {
581
+            $d = $this->configuration->getDefaults();
582
+            $this->applyFind('ldap_display_name', $d['ldap_display_name']);
583
+        }
584
+        $filter = $this->composeLdapFilter(self::LFILTER_USER_LIST);
585
+        if(!$filter) {
586
+            throw new \Exception('Cannot create filter');
587
+        }
588
+
589
+        $this->applyFind('ldap_userlist_filter', $filter);
590
+        return $this->result;
591
+    }
592
+
593
+    /**
594
+     * @return bool|WizardResult
595
+     * @throws \Exception
596
+     */
597
+    public function getUserLoginFilter() {
598
+        if(!$this->checkRequirements(array('ldapHost',
599
+                                            'ldapPort',
600
+                                            'ldapBase',
601
+                                            'ldapUserFilter',
602
+                                            ))) {
603
+            return false;
604
+        }
605
+
606
+        $filter = $this->composeLdapFilter(self::LFILTER_LOGIN);
607
+        if(!$filter) {
608
+            throw new \Exception('Cannot create filter');
609
+        }
610
+
611
+        $this->applyFind('ldap_login_filter', $filter);
612
+        return $this->result;
613
+    }
614
+
615
+    /**
616
+     * @return bool|WizardResult
617
+     * @param string $loginName
618
+     * @throws \Exception
619
+     */
620
+    public function testLoginName($loginName) {
621
+        if(!$this->checkRequirements(array('ldapHost',
622
+            'ldapPort',
623
+            'ldapBase',
624
+            'ldapLoginFilter',
625
+        ))) {
626
+            return false;
627
+        }
628
+
629
+        $cr = $this->access->connection->getConnectionResource();
630
+        if(!$this->ldap->isResource($cr)) {
631
+            throw new \Exception('connection error');
632
+        }
633
+
634
+        if(mb_strpos($this->access->connection->ldapLoginFilter, '%uid', 0, 'UTF-8')
635
+            === false) {
636
+            throw new \Exception('missing placeholder');
637
+        }
638
+
639
+        $users = $this->access->countUsersByLoginName($loginName);
640
+        if($this->ldap->errno($cr) !== 0) {
641
+            throw new \Exception($this->ldap->error($cr));
642
+        }
643
+        $filter = str_replace('%uid', $loginName, $this->access->connection->ldapLoginFilter);
644
+        $this->result->addChange('ldap_test_loginname', $users);
645
+        $this->result->addChange('ldap_test_effective_filter', $filter);
646
+        return $this->result;
647
+    }
648
+
649
+    /**
650
+     * Tries to determine the port, requires given Host, User DN and Password
651
+     * @return WizardResult|false WizardResult on success, false otherwise
652
+     * @throws \Exception
653
+     */
654
+    public function guessPortAndTLS() {
655
+        if(!$this->checkRequirements(array('ldapHost',
656
+                                            ))) {
657
+            return false;
658
+        }
659
+        $this->checkHost();
660
+        $portSettings = $this->getPortSettingsToTry();
661
+
662
+        if(!is_array($portSettings)) {
663
+            throw new \Exception(print_r($portSettings, true));
664
+        }
665
+
666
+        //proceed from the best configuration and return on first success
667
+        foreach($portSettings as $setting) {
668
+            $p = $setting['port'];
669
+            $t = $setting['tls'];
670
+            \OCP\Util::writeLog('user_ldap', 'Wiz: trying port '. $p . ', TLS '. $t, \OCP\Util::DEBUG);
671
+            //connectAndBind may throw Exception, it needs to be catched by the
672
+            //callee of this method
673
+
674
+            try {
675
+                $settingsFound = $this->connectAndBind($p, $t);
676
+            } catch (\Exception $e) {
677
+                // any reply other than -1 (= cannot connect) is already okay,
678
+                // because then we found the server
679
+                // unavailable startTLS returns -11
680
+                if($e->getCode() > 0) {
681
+                    $settingsFound = true;
682
+                } else {
683
+                    throw $e;
684
+                }
685
+            }
686
+
687
+            if ($settingsFound === true) {
688
+                $config = array(
689
+                    'ldapPort' => $p,
690
+                    'ldapTLS' => intval($t)
691
+                );
692
+                $this->configuration->setConfiguration($config);
693
+                \OCP\Util::writeLog('user_ldap', 'Wiz: detected Port ' . $p, \OCP\Util::DEBUG);
694
+                $this->result->addChange('ldap_port', $p);
695
+                return $this->result;
696
+            }
697
+        }
698
+
699
+        //custom port, undetected (we do not brute force)
700
+        return false;
701
+    }
702
+
703
+    /**
704
+     * tries to determine a base dn from User DN or LDAP Host
705
+     * @return WizardResult|false WizardResult on success, false otherwise
706
+     */
707
+    public function guessBaseDN() {
708
+        if(!$this->checkRequirements(array('ldapHost',
709
+                                            'ldapPort',
710
+                                            ))) {
711
+            return false;
712
+        }
713
+
714
+        //check whether a DN is given in the agent name (99.9% of all cases)
715
+        $base = null;
716
+        $i = stripos($this->configuration->ldapAgentName, 'dc=');
717
+        if($i !== false) {
718
+            $base = substr($this->configuration->ldapAgentName, $i);
719
+            if($this->testBaseDN($base)) {
720
+                $this->applyFind('ldap_base', $base);
721
+                return $this->result;
722
+            }
723
+        }
724
+
725
+        //this did not help :(
726
+        //Let's see whether we can parse the Host URL and convert the domain to
727
+        //a base DN
728
+        $helper = new Helper(\OC::$server->getConfig());
729
+        $domain = $helper->getDomainFromURL($this->configuration->ldapHost);
730
+        if(!$domain) {
731
+            return false;
732
+        }
733
+
734
+        $dparts = explode('.', $domain);
735
+        while(count($dparts) > 0) {
736
+            $base2 = 'dc=' . implode(',dc=', $dparts);
737
+            if ($base !== $base2 && $this->testBaseDN($base2)) {
738
+                $this->applyFind('ldap_base', $base2);
739
+                return $this->result;
740
+            }
741
+            array_shift($dparts);
742
+        }
743
+
744
+        return false;
745
+    }
746
+
747
+    /**
748
+     * sets the found value for the configuration key in the WizardResult
749
+     * as well as in the Configuration instance
750
+     * @param string $key the configuration key
751
+     * @param string $value the (detected) value
752
+     *
753
+     */
754
+    private function applyFind($key, $value) {
755
+        $this->result->addChange($key, $value);
756
+        $this->configuration->setConfiguration(array($key => $value));
757
+    }
758
+
759
+    /**
760
+     * Checks, whether a port was entered in the Host configuration
761
+     * field. In this case the port will be stripped off, but also stored as
762
+     * setting.
763
+     */
764
+    private function checkHost() {
765
+        $host = $this->configuration->ldapHost;
766
+        $hostInfo = parse_url($host);
767
+
768
+        //removes Port from Host
769
+        if(is_array($hostInfo) && isset($hostInfo['port'])) {
770
+            $port = $hostInfo['port'];
771
+            $host = str_replace(':'.$port, '', $host);
772
+            $this->applyFind('ldap_host', $host);
773
+            $this->applyFind('ldap_port', $port);
774
+        }
775
+    }
776
+
777
+    /**
778
+     * tries to detect the group member association attribute which is
779
+     * one of 'uniqueMember', 'memberUid', 'member', 'gidNumber'
780
+     * @return string|false, string with the attribute name, false on error
781
+     * @throws \Exception
782
+     */
783
+    private function detectGroupMemberAssoc() {
784
+        $possibleAttrs = array('uniqueMember', 'memberUid', 'member', 'gidNumber');
785
+        $filter = $this->configuration->ldapGroupFilter;
786
+        if(empty($filter)) {
787
+            return false;
788
+        }
789
+        $cr = $this->getConnection();
790
+        if(!$cr) {
791
+            throw new \Exception('Could not connect to LDAP');
792
+        }
793
+        $base = $this->configuration->ldapBase[0];
794
+        $rr = $this->ldap->search($cr, $base, $filter, $possibleAttrs, 0, 1000);
795
+        if(!$this->ldap->isResource($rr)) {
796
+            return false;
797
+        }
798
+        $er = $this->ldap->firstEntry($cr, $rr);
799
+        while(is_resource($er)) {
800
+            $this->ldap->getDN($cr, $er);
801
+            $attrs = $this->ldap->getAttributes($cr, $er);
802
+            $result = array();
803
+            $possibleAttrsCount = count($possibleAttrs);
804
+            for($i = 0; $i < $possibleAttrsCount; $i++) {
805
+                if(isset($attrs[$possibleAttrs[$i]])) {
806
+                    $result[$possibleAttrs[$i]] = $attrs[$possibleAttrs[$i]]['count'];
807
+                }
808
+            }
809
+            if(!empty($result)) {
810
+                natsort($result);
811
+                return key($result);
812
+            }
813
+
814
+            $er = $this->ldap->nextEntry($cr, $er);
815
+        }
816
+
817
+        return false;
818
+    }
819
+
820
+    /**
821
+     * Checks whether for a given BaseDN results will be returned
822
+     * @param string $base the BaseDN to test
823
+     * @return bool true on success, false otherwise
824
+     * @throws \Exception
825
+     */
826
+    private function testBaseDN($base) {
827
+        $cr = $this->getConnection();
828
+        if(!$cr) {
829
+            throw new \Exception('Could not connect to LDAP');
830
+        }
831
+
832
+        //base is there, let's validate it. If we search for anything, we should
833
+        //get a result set > 0 on a proper base
834
+        $rr = $this->ldap->search($cr, $base, 'objectClass=*', array('dn'), 0, 1);
835
+        if(!$this->ldap->isResource($rr)) {
836
+            $errorNo  = $this->ldap->errno($cr);
837
+            $errorMsg = $this->ldap->error($cr);
838
+            \OCP\Util::writeLog('user_ldap', 'Wiz: Could not search base '.$base.
839
+                            ' Error '.$errorNo.': '.$errorMsg, \OCP\Util::INFO);
840
+            return false;
841
+        }
842
+        $entries = $this->ldap->countEntries($cr, $rr);
843
+        return ($entries !== false) && ($entries > 0);
844
+    }
845
+
846
+    /**
847
+     * Checks whether the server supports memberOf in LDAP Filter.
848
+     * Note: at least in OpenLDAP, availability of memberOf is dependent on
849
+     * a configured objectClass. I.e. not necessarily for all available groups
850
+     * memberOf does work.
851
+     *
852
+     * @return bool true if it does, false otherwise
853
+     * @throws \Exception
854
+     */
855
+    private function testMemberOf() {
856
+        $cr = $this->getConnection();
857
+        if(!$cr) {
858
+            throw new \Exception('Could not connect to LDAP');
859
+        }
860
+        $result = $this->access->countUsers('memberOf=*', array('memberOf'), 1);
861
+        if(is_int($result) &&  $result > 0) {
862
+            return true;
863
+        }
864
+        return false;
865
+    }
866
+
867
+    /**
868
+     * creates an LDAP Filter from given configuration
869
+     * @param integer $filterType int, for which use case the filter shall be created
870
+     * can be any of self::LFILTER_USER_LIST, self::LFILTER_LOGIN or
871
+     * self::LFILTER_GROUP_LIST
872
+     * @return string|false string with the filter on success, false otherwise
873
+     * @throws \Exception
874
+     */
875
+    private function composeLdapFilter($filterType) {
876
+        $filter = '';
877
+        $parts = 0;
878
+        switch ($filterType) {
879
+            case self::LFILTER_USER_LIST:
880
+                $objcs = $this->configuration->ldapUserFilterObjectclass;
881
+                //glue objectclasses
882
+                if(is_array($objcs) && count($objcs) > 0) {
883
+                    $filter .= '(|';
884
+                    foreach($objcs as $objc) {
885
+                        $filter .= '(objectclass=' . $objc . ')';
886
+                    }
887
+                    $filter .= ')';
888
+                    $parts++;
889
+                }
890
+                //glue group memberships
891
+                if($this->configuration->hasMemberOfFilterSupport) {
892
+                    $cns = $this->configuration->ldapUserFilterGroups;
893
+                    if(is_array($cns) && count($cns) > 0) {
894
+                        $filter .= '(|';
895
+                        $cr = $this->getConnection();
896
+                        if(!$cr) {
897
+                            throw new \Exception('Could not connect to LDAP');
898
+                        }
899
+                        $base = $this->configuration->ldapBase[0];
900
+                        foreach($cns as $cn) {
901
+                            $rr = $this->ldap->search($cr, $base, 'cn=' . $cn, array('dn', 'primaryGroupToken'));
902
+                            if(!$this->ldap->isResource($rr)) {
903
+                                continue;
904
+                            }
905
+                            $er = $this->ldap->firstEntry($cr, $rr);
906
+                            $attrs = $this->ldap->getAttributes($cr, $er);
907
+                            $dn = $this->ldap->getDN($cr, $er);
908
+                            if ($dn == false || $dn === '') {
909
+                                continue;
910
+                            }
911
+                            $filterPart = '(memberof=' . $dn . ')';
912
+                            if(isset($attrs['primaryGroupToken'])) {
913
+                                $pgt = $attrs['primaryGroupToken'][0];
914
+                                $primaryFilterPart = '(primaryGroupID=' . $pgt .')';
915
+                                $filterPart = '(|' . $filterPart . $primaryFilterPart . ')';
916
+                            }
917
+                            $filter .= $filterPart;
918
+                        }
919
+                        $filter .= ')';
920
+                    }
921
+                    $parts++;
922
+                }
923
+                //wrap parts in AND condition
924
+                if($parts > 1) {
925
+                    $filter = '(&' . $filter . ')';
926
+                }
927
+                if ($filter === '') {
928
+                    $filter = '(objectclass=*)';
929
+                }
930
+                break;
931
+
932
+            case self::LFILTER_GROUP_LIST:
933
+                $objcs = $this->configuration->ldapGroupFilterObjectclass;
934
+                //glue objectclasses
935
+                if(is_array($objcs) && count($objcs) > 0) {
936
+                    $filter .= '(|';
937
+                    foreach($objcs as $objc) {
938
+                        $filter .= '(objectclass=' . $objc . ')';
939
+                    }
940
+                    $filter .= ')';
941
+                    $parts++;
942
+                }
943
+                //glue group memberships
944
+                $cns = $this->configuration->ldapGroupFilterGroups;
945
+                if(is_array($cns) && count($cns) > 0) {
946
+                    $filter .= '(|';
947
+                    foreach($cns as $cn) {
948
+                        $filter .= '(cn=' . $cn . ')';
949
+                    }
950
+                    $filter .= ')';
951
+                }
952
+                $parts++;
953
+                //wrap parts in AND condition
954
+                if($parts > 1) {
955
+                    $filter = '(&' . $filter . ')';
956
+                }
957
+                break;
958
+
959
+            case self::LFILTER_LOGIN:
960
+                $ulf = $this->configuration->ldapUserFilter;
961
+                $loginpart = '=%uid';
962
+                $filterUsername = '';
963
+                $userAttributes = $this->getUserAttributes();
964
+                $userAttributes = array_change_key_case(array_flip($userAttributes));
965
+                $parts = 0;
966
+
967
+                if($this->configuration->ldapLoginFilterUsername === '1') {
968
+                    $attr = '';
969
+                    if(isset($userAttributes['uid'])) {
970
+                        $attr = 'uid';
971
+                    } else if(isset($userAttributes['samaccountname'])) {
972
+                        $attr = 'samaccountname';
973
+                    } else if(isset($userAttributes['cn'])) {
974
+                        //fallback
975
+                        $attr = 'cn';
976
+                    }
977
+                    if ($attr !== '') {
978
+                        $filterUsername = '(' . $attr . $loginpart . ')';
979
+                        $parts++;
980
+                    }
981
+                }
982
+
983
+                $filterEmail = '';
984
+                if($this->configuration->ldapLoginFilterEmail === '1') {
985
+                    $filterEmail = '(|(mailPrimaryAddress=%uid)(mail=%uid))';
986
+                    $parts++;
987
+                }
988
+
989
+                $filterAttributes = '';
990
+                $attrsToFilter = $this->configuration->ldapLoginFilterAttributes;
991
+                if(is_array($attrsToFilter) && count($attrsToFilter) > 0) {
992
+                    $filterAttributes = '(|';
993
+                    foreach($attrsToFilter as $attribute) {
994
+                        $filterAttributes .= '(' . $attribute . $loginpart . ')';
995
+                    }
996
+                    $filterAttributes .= ')';
997
+                    $parts++;
998
+                }
999
+
1000
+                $filterLogin = '';
1001
+                if($parts > 1) {
1002
+                    $filterLogin = '(|';
1003
+                }
1004
+                $filterLogin .= $filterUsername;
1005
+                $filterLogin .= $filterEmail;
1006
+                $filterLogin .= $filterAttributes;
1007
+                if($parts > 1) {
1008
+                    $filterLogin .= ')';
1009
+                }
1010
+
1011
+                $filter = '(&'.$ulf.$filterLogin.')';
1012
+                break;
1013
+        }
1014
+
1015
+        \OCP\Util::writeLog('user_ldap', 'Wiz: Final filter '.$filter, \OCP\Util::DEBUG);
1016
+
1017
+        return $filter;
1018
+    }
1019
+
1020
+    /**
1021
+     * Connects and Binds to an LDAP Server
1022
+     * @param int $port the port to connect with
1023
+     * @param bool $tls whether startTLS is to be used
1024
+     * @param bool $ncc
1025
+     * @return bool
1026
+     * @throws \Exception
1027
+     */
1028
+    private function connectAndBind($port = 389, $tls = false, $ncc = false) {
1029
+        if($ncc) {
1030
+            //No certificate check
1031
+            //FIXME: undo afterwards
1032
+            putenv('LDAPTLS_REQCERT=never');
1033
+        }
1034
+
1035
+        //connect, does not really trigger any server communication
1036
+        \OCP\Util::writeLog('user_ldap', 'Wiz: Checking Host Info ', \OCP\Util::DEBUG);
1037
+        $host = $this->configuration->ldapHost;
1038
+        $hostInfo = parse_url($host);
1039
+        if(!$hostInfo) {
1040
+            throw new \Exception(self::$l->t('Invalid Host'));
1041
+        }
1042
+        \OCP\Util::writeLog('user_ldap', 'Wiz: Attempting to connect ', \OCP\Util::DEBUG);
1043
+        $cr = $this->ldap->connect($host, $port);
1044
+        if(!is_resource($cr)) {
1045
+            throw new \Exception(self::$l->t('Invalid Host'));
1046
+        }
1047
+
1048
+        \OCP\Util::writeLog('user_ldap', 'Wiz: Setting LDAP Options ', \OCP\Util::DEBUG);
1049
+        //set LDAP options
1050
+        $this->ldap->setOption($cr, LDAP_OPT_PROTOCOL_VERSION, 3);
1051
+        $this->ldap->setOption($cr, LDAP_OPT_REFERRALS, 0);
1052
+        $this->ldap->setOption($cr, LDAP_OPT_NETWORK_TIMEOUT, self::LDAP_NW_TIMEOUT);
1053
+
1054
+        try {
1055
+            if($tls) {
1056
+                $isTlsWorking = @$this->ldap->startTls($cr);
1057
+                if(!$isTlsWorking) {
1058
+                    return false;
1059
+                }
1060
+            }
1061
+
1062
+            \OCP\Util::writeLog('user_ldap', 'Wiz: Attemping to Bind ', \OCP\Util::DEBUG);
1063
+            //interesting part: do the bind!
1064
+            $login = $this->ldap->bind($cr,
1065
+                $this->configuration->ldapAgentName,
1066
+                $this->configuration->ldapAgentPassword
1067
+            );
1068
+            $errNo = $this->ldap->errno($cr);
1069
+            $error = ldap_error($cr);
1070
+            $this->ldap->unbind($cr);
1071
+        } catch(ServerNotAvailableException $e) {
1072
+            return false;
1073
+        }
1074
+
1075
+        if($login === true) {
1076
+            $this->ldap->unbind($cr);
1077
+            if($ncc) {
1078
+                throw new \Exception('Certificate cannot be validated.');
1079
+            }
1080
+            \OCP\Util::writeLog('user_ldap', 'Wiz: Bind successful to Port '. $port . ' TLS ' . intval($tls), \OCP\Util::DEBUG);
1081
+            return true;
1082
+        }
1083
+
1084
+        if($errNo === -1 || ($errNo === 2 && $ncc)) {
1085
+            //host, port or TLS wrong
1086
+            return false;
1087
+        } else if ($errNo === 2) {
1088
+            return $this->connectAndBind($port, $tls, true);
1089
+        }
1090
+        throw new \Exception($error, $errNo);
1091
+    }
1092
+
1093
+    /**
1094
+     * checks whether a valid combination of agent and password has been
1095
+     * provided (either two values or nothing for anonymous connect)
1096
+     * @return bool, true if everything is fine, false otherwise
1097
+     */
1098
+    private function checkAgentRequirements() {
1099
+        $agent = $this->configuration->ldapAgentName;
1100
+        $pwd = $this->configuration->ldapAgentPassword;
1101
+
1102
+        return
1103
+            ($agent !== '' && $pwd !== '')
1104
+            ||  ($agent === '' && $pwd === '')
1105
+        ;
1106
+    }
1107
+
1108
+    /**
1109
+     * @param array $reqs
1110
+     * @return bool
1111
+     */
1112
+    private function checkRequirements($reqs) {
1113
+        $this->checkAgentRequirements();
1114
+        foreach($reqs as $option) {
1115
+            $value = $this->configuration->$option;
1116
+            if(empty($value)) {
1117
+                return false;
1118
+            }
1119
+        }
1120
+        return true;
1121
+    }
1122
+
1123
+    /**
1124
+     * does a cumulativeSearch on LDAP to get different values of a
1125
+     * specified attribute
1126
+     * @param string[] $filters array, the filters that shall be used in the search
1127
+     * @param string $attr the attribute of which a list of values shall be returned
1128
+     * @param int $dnReadLimit the amount of how many DNs should be analyzed.
1129
+     * The lower, the faster
1130
+     * @param string $maxF string. if not null, this variable will have the filter that
1131
+     * yields most result entries
1132
+     * @return array|false an array with the values on success, false otherwise
1133
+     */
1134
+    public function cumulativeSearchOnAttribute($filters, $attr, $dnReadLimit = 3, &$maxF = null) {
1135
+        $dnRead = array();
1136
+        $foundItems = array();
1137
+        $maxEntries = 0;
1138
+        if(!is_array($this->configuration->ldapBase)
1139
+           || !isset($this->configuration->ldapBase[0])) {
1140
+            return false;
1141
+        }
1142
+        $base = $this->configuration->ldapBase[0];
1143
+        $cr = $this->getConnection();
1144
+        if(!$this->ldap->isResource($cr)) {
1145
+            return false;
1146
+        }
1147
+        $lastFilter = null;
1148
+        if(isset($filters[count($filters)-1])) {
1149
+            $lastFilter = $filters[count($filters)-1];
1150
+        }
1151
+        foreach($filters as $filter) {
1152
+            if($lastFilter === $filter && count($foundItems) > 0) {
1153
+                //skip when the filter is a wildcard and results were found
1154
+                continue;
1155
+            }
1156
+            // 20k limit for performance and reason
1157
+            $rr = $this->ldap->search($cr, $base, $filter, array($attr), 0, 20000);
1158
+            if(!$this->ldap->isResource($rr)) {
1159
+                continue;
1160
+            }
1161
+            $entries = $this->ldap->countEntries($cr, $rr);
1162
+            $getEntryFunc = 'firstEntry';
1163
+            if(($entries !== false) && ($entries > 0)) {
1164
+                if(!is_null($maxF) && $entries > $maxEntries) {
1165
+                    $maxEntries = $entries;
1166
+                    $maxF = $filter;
1167
+                }
1168
+                $dnReadCount = 0;
1169
+                do {
1170
+                    $entry = $this->ldap->$getEntryFunc($cr, $rr);
1171
+                    $getEntryFunc = 'nextEntry';
1172
+                    if(!$this->ldap->isResource($entry)) {
1173
+                        continue 2;
1174
+                    }
1175
+                    $rr = $entry; //will be expected by nextEntry next round
1176
+                    $attributes = $this->ldap->getAttributes($cr, $entry);
1177
+                    $dn = $this->ldap->getDN($cr, $entry);
1178
+                    if($dn === false || in_array($dn, $dnRead)) {
1179
+                        continue;
1180
+                    }
1181
+                    $newItems = array();
1182
+                    $state = $this->getAttributeValuesFromEntry($attributes,
1183
+                                                                $attr,
1184
+                                                                $newItems);
1185
+                    $dnReadCount++;
1186
+                    $foundItems = array_merge($foundItems, $newItems);
1187
+                    $this->resultCache[$dn][$attr] = $newItems;
1188
+                    $dnRead[] = $dn;
1189
+                } while(($state === self::LRESULT_PROCESSED_SKIP
1190
+                        || $this->ldap->isResource($entry))
1191
+                        && ($dnReadLimit === 0 || $dnReadCount < $dnReadLimit));
1192
+            }
1193
+        }
1194
+
1195
+        return array_unique($foundItems);
1196
+    }
1197
+
1198
+    /**
1199
+     * determines if and which $attr are available on the LDAP server
1200
+     * @param string[] $objectclasses the objectclasses to use as search filter
1201
+     * @param string $attr the attribute to look for
1202
+     * @param string $dbkey the dbkey of the setting the feature is connected to
1203
+     * @param string $confkey the confkey counterpart for the $dbkey as used in the
1204
+     * Configuration class
1205
+     * @param bool $po whether the objectClass with most result entries
1206
+     * shall be pre-selected via the result
1207
+     * @return array|false list of found items.
1208
+     * @throws \Exception
1209
+     */
1210
+    private function determineFeature($objectclasses, $attr, $dbkey, $confkey, $po = false) {
1211
+        $cr = $this->getConnection();
1212
+        if(!$cr) {
1213
+            throw new \Exception('Could not connect to LDAP');
1214
+        }
1215
+        $p = 'objectclass=';
1216
+        foreach($objectclasses as $key => $value) {
1217
+            $objectclasses[$key] = $p.$value;
1218
+        }
1219
+        $maxEntryObjC = '';
1220
+
1221
+        //how deep to dig?
1222
+        //When looking for objectclasses, testing few entries is sufficient,
1223
+        $dig = 3;
1224
+
1225
+        $availableFeatures =
1226
+            $this->cumulativeSearchOnAttribute($objectclasses, $attr,
1227
+                                                $dig, $maxEntryObjC);
1228
+        if(is_array($availableFeatures)
1229
+           && count($availableFeatures) > 0) {
1230
+            natcasesort($availableFeatures);
1231
+            //natcasesort keeps indices, but we must get rid of them for proper
1232
+            //sorting in the web UI. Therefore: array_values
1233
+            $this->result->addOptions($dbkey, array_values($availableFeatures));
1234
+        } else {
1235
+            throw new \Exception(self::$l->t('Could not find the desired feature'));
1236
+        }
1237
+
1238
+        $setFeatures = $this->configuration->$confkey;
1239
+        if(is_array($setFeatures) && !empty($setFeatures)) {
1240
+            //something is already configured? pre-select it.
1241
+            $this->result->addChange($dbkey, $setFeatures);
1242
+        } else if ($po && $maxEntryObjC !== '') {
1243
+            //pre-select objectclass with most result entries
1244
+            $maxEntryObjC = str_replace($p, '', $maxEntryObjC);
1245
+            $this->applyFind($dbkey, $maxEntryObjC);
1246
+            $this->result->addChange($dbkey, $maxEntryObjC);
1247
+        }
1248
+
1249
+        return $availableFeatures;
1250
+    }
1251
+
1252
+    /**
1253
+     * appends a list of values fr
1254
+     * @param resource $result the return value from ldap_get_attributes
1255
+     * @param string $attribute the attribute values to look for
1256
+     * @param array &$known new values will be appended here
1257
+     * @return int, state on of the class constants LRESULT_PROCESSED_OK,
1258
+     * LRESULT_PROCESSED_INVALID or LRESULT_PROCESSED_SKIP
1259
+     */
1260
+    private function getAttributeValuesFromEntry($result, $attribute, &$known) {
1261
+        if(!is_array($result)
1262
+           || !isset($result['count'])
1263
+           || !$result['count'] > 0) {
1264
+            return self::LRESULT_PROCESSED_INVALID;
1265
+        }
1266
+
1267
+        // strtolower on all keys for proper comparison
1268
+        $result = \OCP\Util::mb_array_change_key_case($result);
1269
+        $attribute = strtolower($attribute);
1270
+        if(isset($result[$attribute])) {
1271
+            foreach($result[$attribute] as $key => $val) {
1272
+                if($key === 'count') {
1273
+                    continue;
1274
+                }
1275
+                if(!in_array($val, $known)) {
1276
+                    $known[] = $val;
1277
+                }
1278
+            }
1279
+            return self::LRESULT_PROCESSED_OK;
1280
+        } else {
1281
+            return self::LRESULT_PROCESSED_SKIP;
1282
+        }
1283
+    }
1284
+
1285
+    /**
1286
+     * @return bool|mixed
1287
+     */
1288
+    private function getConnection() {
1289
+        if(!is_null($this->cr)) {
1290
+            return $this->cr;
1291
+        }
1292
+
1293
+        $cr = $this->ldap->connect(
1294
+            $this->configuration->ldapHost,
1295
+            $this->configuration->ldapPort
1296
+        );
1297
+
1298
+        $this->ldap->setOption($cr, LDAP_OPT_PROTOCOL_VERSION, 3);
1299
+        $this->ldap->setOption($cr, LDAP_OPT_REFERRALS, 0);
1300
+        $this->ldap->setOption($cr, LDAP_OPT_NETWORK_TIMEOUT, self::LDAP_NW_TIMEOUT);
1301
+        if($this->configuration->ldapTLS === 1) {
1302
+            $this->ldap->startTls($cr);
1303
+        }
1304
+
1305
+        $lo = @$this->ldap->bind($cr,
1306
+                                    $this->configuration->ldapAgentName,
1307
+                                    $this->configuration->ldapAgentPassword);
1308
+        if($lo === true) {
1309
+            $this->$cr = $cr;
1310
+            return $cr;
1311
+        }
1312
+
1313
+        return false;
1314
+    }
1315
+
1316
+    /**
1317
+     * @return array
1318
+     */
1319
+    private function getDefaultLdapPortSettings() {
1320
+        static $settings = array(
1321
+                                array('port' => 7636, 'tls' => false),
1322
+                                array('port' =>  636, 'tls' => false),
1323
+                                array('port' => 7389, 'tls' => true),
1324
+                                array('port' =>  389, 'tls' => true),
1325
+                                array('port' => 7389, 'tls' => false),
1326
+                                array('port' =>  389, 'tls' => false),
1327
+                            );
1328
+        return $settings;
1329
+    }
1330
+
1331
+    /**
1332
+     * @return array
1333
+     */
1334
+    private function getPortSettingsToTry() {
1335
+        //389 ← LDAP / Unencrypted or StartTLS
1336
+        //636 ← LDAPS / SSL
1337
+        //7xxx ← UCS. need to be checked first, because both ports may be open
1338
+        $host = $this->configuration->ldapHost;
1339
+        $port = intval($this->configuration->ldapPort);
1340
+        $portSettings = array();
1341
+
1342
+        //In case the port is already provided, we will check this first
1343
+        if($port > 0) {
1344
+            $hostInfo = parse_url($host);
1345
+            if(!(is_array($hostInfo)
1346
+                && isset($hostInfo['scheme'])
1347
+                && stripos($hostInfo['scheme'], 'ldaps') !== false)) {
1348
+                $portSettings[] = array('port' => $port, 'tls' => true);
1349
+            }
1350
+            $portSettings[] =array('port' => $port, 'tls' => false);
1351
+        }
1352
+
1353
+        //default ports
1354
+        $portSettings = array_merge($portSettings,
1355
+                                    $this->getDefaultLdapPortSettings());
1356
+
1357
+        return $portSettings;
1358
+    }
1359 1359
 
1360 1360
 
1361 1361
 }
Please login to merge, or discard this patch.
lib/private/legacy/db.php 3 patches
Doc Comments   -1 removed lines patch added patch discarded remove patch
@@ -151,7 +151,6 @@
 block discarded – undo
151 151
 	/**
152 152
 	 * saves database schema to xml file
153 153
 	 * @param string $file name of file
154
-	 * @param int $mode
155 154
 	 * @return bool
156 155
 	 *
157 156
 	 * TODO: write more documentation
Please login to merge, or discard this patch.
Indentation   +194 added lines, -194 removed lines patch added patch discarded remove patch
@@ -33,210 +33,210 @@
 block discarded – undo
33 33
  */
34 34
 class OC_DB {
35 35
 
36
-	/**
37
-	 * get MDB2 schema manager
38
-	 *
39
-	 * @return \OC\DB\MDB2SchemaManager
40
-	 */
41
-	private static function getMDB2SchemaManager() {
42
-		return new \OC\DB\MDB2SchemaManager(\OC::$server->getDatabaseConnection());
43
-	}
36
+    /**
37
+     * get MDB2 schema manager
38
+     *
39
+     * @return \OC\DB\MDB2SchemaManager
40
+     */
41
+    private static function getMDB2SchemaManager() {
42
+        return new \OC\DB\MDB2SchemaManager(\OC::$server->getDatabaseConnection());
43
+    }
44 44
 
45
-	/**
46
-	 * Prepare a SQL query
47
-	 * @param string $query Query string
48
-	 * @param int $limit
49
-	 * @param int $offset
50
-	 * @param bool $isManipulation
51
-	 * @throws \OC\DatabaseException
52
-	 * @return OC_DB_StatementWrapper prepared SQL query
53
-	 *
54
-	 * SQL query via Doctrine prepare(), needs to be execute()'d!
55
-	 */
56
-	static public function prepare( $query , $limit = null, $offset = null, $isManipulation = null) {
57
-		$connection = \OC::$server->getDatabaseConnection();
45
+    /**
46
+     * Prepare a SQL query
47
+     * @param string $query Query string
48
+     * @param int $limit
49
+     * @param int $offset
50
+     * @param bool $isManipulation
51
+     * @throws \OC\DatabaseException
52
+     * @return OC_DB_StatementWrapper prepared SQL query
53
+     *
54
+     * SQL query via Doctrine prepare(), needs to be execute()'d!
55
+     */
56
+    static public function prepare( $query , $limit = null, $offset = null, $isManipulation = null) {
57
+        $connection = \OC::$server->getDatabaseConnection();
58 58
 
59
-		if ($isManipulation === null) {
60
-			//try to guess, so we return the number of rows on manipulations
61
-			$isManipulation = self::isManipulation($query);
62
-		}
59
+        if ($isManipulation === null) {
60
+            //try to guess, so we return the number of rows on manipulations
61
+            $isManipulation = self::isManipulation($query);
62
+        }
63 63
 
64
-		// return the result
65
-		try {
66
-			$result =$connection->prepare($query, $limit, $offset);
67
-		} catch (\Doctrine\DBAL\DBALException $e) {
68
-			throw new \OC\DatabaseException($e->getMessage());
69
-		}
70
-		// differentiate between query and manipulation
71
-		$result = new OC_DB_StatementWrapper($result, $isManipulation);
72
-		return $result;
73
-	}
64
+        // return the result
65
+        try {
66
+            $result =$connection->prepare($query, $limit, $offset);
67
+        } catch (\Doctrine\DBAL\DBALException $e) {
68
+            throw new \OC\DatabaseException($e->getMessage());
69
+        }
70
+        // differentiate between query and manipulation
71
+        $result = new OC_DB_StatementWrapper($result, $isManipulation);
72
+        return $result;
73
+    }
74 74
 
75
-	/**
76
-	 * tries to guess the type of statement based on the first 10 characters
77
-	 * the current check allows some whitespace but does not work with IF EXISTS or other more complex statements
78
-	 *
79
-	 * @param string $sql
80
-	 * @return bool
81
-	 */
82
-	static public function isManipulation( $sql ) {
83
-		$selectOccurrence = stripos($sql, 'SELECT');
84
-		if ($selectOccurrence !== false && $selectOccurrence < 10) {
85
-			return false;
86
-		}
87
-		$insertOccurrence = stripos($sql, 'INSERT');
88
-		if ($insertOccurrence !== false && $insertOccurrence < 10) {
89
-			return true;
90
-		}
91
-		$updateOccurrence = stripos($sql, 'UPDATE');
92
-		if ($updateOccurrence !== false && $updateOccurrence < 10) {
93
-			return true;
94
-		}
95
-		$deleteOccurrence = stripos($sql, 'DELETE');
96
-		if ($deleteOccurrence !== false && $deleteOccurrence < 10) {
97
-			return true;
98
-		}
99
-		return false;
100
-	}
75
+    /**
76
+     * tries to guess the type of statement based on the first 10 characters
77
+     * the current check allows some whitespace but does not work with IF EXISTS or other more complex statements
78
+     *
79
+     * @param string $sql
80
+     * @return bool
81
+     */
82
+    static public function isManipulation( $sql ) {
83
+        $selectOccurrence = stripos($sql, 'SELECT');
84
+        if ($selectOccurrence !== false && $selectOccurrence < 10) {
85
+            return false;
86
+        }
87
+        $insertOccurrence = stripos($sql, 'INSERT');
88
+        if ($insertOccurrence !== false && $insertOccurrence < 10) {
89
+            return true;
90
+        }
91
+        $updateOccurrence = stripos($sql, 'UPDATE');
92
+        if ($updateOccurrence !== false && $updateOccurrence < 10) {
93
+            return true;
94
+        }
95
+        $deleteOccurrence = stripos($sql, 'DELETE');
96
+        if ($deleteOccurrence !== false && $deleteOccurrence < 10) {
97
+            return true;
98
+        }
99
+        return false;
100
+    }
101 101
 
102
-	/**
103
-	 * execute a prepared statement, on error write log and throw exception
104
-	 * @param mixed $stmt OC_DB_StatementWrapper,
105
-	 *					  an array with 'sql' and optionally 'limit' and 'offset' keys
106
-	 *					.. or a simple sql query string
107
-	 * @param array $parameters
108
-	 * @return OC_DB_StatementWrapper
109
-	 * @throws \OC\DatabaseException
110
-	 */
111
-	static public function executeAudited( $stmt, array $parameters = null) {
112
-		if (is_string($stmt)) {
113
-			// convert to an array with 'sql'
114
-			if (stripos($stmt, 'LIMIT') !== false) { //OFFSET requires LIMIT, so we only need to check for LIMIT
115
-				// TODO try to convert LIMIT OFFSET notation to parameters
116
-				$message = 'LIMIT and OFFSET are forbidden for portability reasons,'
117
-						 . ' pass an array with \'limit\' and \'offset\' instead';
118
-				throw new \OC\DatabaseException($message);
119
-			}
120
-			$stmt = array('sql' => $stmt, 'limit' => null, 'offset' => null);
121
-		}
122
-		if (is_array($stmt)) {
123
-			// convert to prepared statement
124
-			if ( ! array_key_exists('sql', $stmt) ) {
125
-				$message = 'statement array must at least contain key \'sql\'';
126
-				throw new \OC\DatabaseException($message);
127
-			}
128
-			if ( ! array_key_exists('limit', $stmt) ) {
129
-				$stmt['limit'] = null;
130
-			}
131
-			if ( ! array_key_exists('limit', $stmt) ) {
132
-				$stmt['offset'] = null;
133
-			}
134
-			$stmt = self::prepare($stmt['sql'], $stmt['limit'], $stmt['offset']);
135
-		}
136
-		self::raiseExceptionOnError($stmt, 'Could not prepare statement');
137
-		if ($stmt instanceof OC_DB_StatementWrapper) {
138
-			$result = $stmt->execute($parameters);
139
-			self::raiseExceptionOnError($result, 'Could not execute statement');
140
-		} else {
141
-			if (is_object($stmt)) {
142
-				$message = 'Expected a prepared statement or array got ' . get_class($stmt);
143
-			} else {
144
-				$message = 'Expected a prepared statement or array got ' . gettype($stmt);
145
-			}
146
-			throw new \OC\DatabaseException($message);
147
-		}
148
-		return $result;
149
-	}
102
+    /**
103
+     * execute a prepared statement, on error write log and throw exception
104
+     * @param mixed $stmt OC_DB_StatementWrapper,
105
+     *					  an array with 'sql' and optionally 'limit' and 'offset' keys
106
+     *					.. or a simple sql query string
107
+     * @param array $parameters
108
+     * @return OC_DB_StatementWrapper
109
+     * @throws \OC\DatabaseException
110
+     */
111
+    static public function executeAudited( $stmt, array $parameters = null) {
112
+        if (is_string($stmt)) {
113
+            // convert to an array with 'sql'
114
+            if (stripos($stmt, 'LIMIT') !== false) { //OFFSET requires LIMIT, so we only need to check for LIMIT
115
+                // TODO try to convert LIMIT OFFSET notation to parameters
116
+                $message = 'LIMIT and OFFSET are forbidden for portability reasons,'
117
+                            . ' pass an array with \'limit\' and \'offset\' instead';
118
+                throw new \OC\DatabaseException($message);
119
+            }
120
+            $stmt = array('sql' => $stmt, 'limit' => null, 'offset' => null);
121
+        }
122
+        if (is_array($stmt)) {
123
+            // convert to prepared statement
124
+            if ( ! array_key_exists('sql', $stmt) ) {
125
+                $message = 'statement array must at least contain key \'sql\'';
126
+                throw new \OC\DatabaseException($message);
127
+            }
128
+            if ( ! array_key_exists('limit', $stmt) ) {
129
+                $stmt['limit'] = null;
130
+            }
131
+            if ( ! array_key_exists('limit', $stmt) ) {
132
+                $stmt['offset'] = null;
133
+            }
134
+            $stmt = self::prepare($stmt['sql'], $stmt['limit'], $stmt['offset']);
135
+        }
136
+        self::raiseExceptionOnError($stmt, 'Could not prepare statement');
137
+        if ($stmt instanceof OC_DB_StatementWrapper) {
138
+            $result = $stmt->execute($parameters);
139
+            self::raiseExceptionOnError($result, 'Could not execute statement');
140
+        } else {
141
+            if (is_object($stmt)) {
142
+                $message = 'Expected a prepared statement or array got ' . get_class($stmt);
143
+            } else {
144
+                $message = 'Expected a prepared statement or array got ' . gettype($stmt);
145
+            }
146
+            throw new \OC\DatabaseException($message);
147
+        }
148
+        return $result;
149
+    }
150 150
 
151
-	/**
152
-	 * saves database schema to xml file
153
-	 * @param string $file name of file
154
-	 * @param int $mode
155
-	 * @return bool
156
-	 *
157
-	 * TODO: write more documentation
158
-	 */
159
-	public static function getDbStructure($file) {
160
-		$schemaManager = self::getMDB2SchemaManager();
161
-		return $schemaManager->getDbStructure($file);
162
-	}
151
+    /**
152
+     * saves database schema to xml file
153
+     * @param string $file name of file
154
+     * @param int $mode
155
+     * @return bool
156
+     *
157
+     * TODO: write more documentation
158
+     */
159
+    public static function getDbStructure($file) {
160
+        $schemaManager = self::getMDB2SchemaManager();
161
+        return $schemaManager->getDbStructure($file);
162
+    }
163 163
 
164
-	/**
165
-	 * Creates tables from XML file
166
-	 * @param string $file file to read structure from
167
-	 * @return bool
168
-	 *
169
-	 * TODO: write more documentation
170
-	 */
171
-	public static function createDbFromStructure( $file ) {
172
-		$schemaManager = self::getMDB2SchemaManager();
173
-		$result = $schemaManager->createDbFromStructure($file);
174
-		return $result;
175
-	}
164
+    /**
165
+     * Creates tables from XML file
166
+     * @param string $file file to read structure from
167
+     * @return bool
168
+     *
169
+     * TODO: write more documentation
170
+     */
171
+    public static function createDbFromStructure( $file ) {
172
+        $schemaManager = self::getMDB2SchemaManager();
173
+        $result = $schemaManager->createDbFromStructure($file);
174
+        return $result;
175
+    }
176 176
 
177
-	/**
178
-	 * update the database schema
179
-	 * @param string $file file to read structure from
180
-	 * @throws Exception
181
-	 * @return string|boolean
182
-	 */
183
-	public static function updateDbFromStructure($file) {
184
-		$schemaManager = self::getMDB2SchemaManager();
185
-		try {
186
-			$result = $schemaManager->updateDbFromStructure($file);
187
-		} catch (Exception $e) {
188
-			\OCP\Util::writeLog('core', 'Failed to update database structure ('.$e.')', \OCP\Util::FATAL);
189
-			throw $e;
190
-		}
191
-		return $result;
192
-	}
177
+    /**
178
+     * update the database schema
179
+     * @param string $file file to read structure from
180
+     * @throws Exception
181
+     * @return string|boolean
182
+     */
183
+    public static function updateDbFromStructure($file) {
184
+        $schemaManager = self::getMDB2SchemaManager();
185
+        try {
186
+            $result = $schemaManager->updateDbFromStructure($file);
187
+        } catch (Exception $e) {
188
+            \OCP\Util::writeLog('core', 'Failed to update database structure ('.$e.')', \OCP\Util::FATAL);
189
+            throw $e;
190
+        }
191
+        return $result;
192
+    }
193 193
 
194
-	/**
195
-	 * remove all tables defined in a database structure xml file
196
-	 * @param string $file the xml file describing the tables
197
-	 */
198
-	public static function removeDBStructure($file) {
199
-		$schemaManager = self::getMDB2SchemaManager();
200
-		$schemaManager->removeDBStructure($file);
201
-	}
194
+    /**
195
+     * remove all tables defined in a database structure xml file
196
+     * @param string $file the xml file describing the tables
197
+     */
198
+    public static function removeDBStructure($file) {
199
+        $schemaManager = self::getMDB2SchemaManager();
200
+        $schemaManager->removeDBStructure($file);
201
+    }
202 202
 
203
-	/**
204
-	 * check if a result is an error and throws an exception, works with \Doctrine\DBAL\DBALException
205
-	 * @param mixed $result
206
-	 * @param string $message
207
-	 * @return void
208
-	 * @throws \OC\DatabaseException
209
-	 */
210
-	public static function raiseExceptionOnError($result, $message = null) {
211
-		if($result === false) {
212
-			if ($message === null) {
213
-				$message = self::getErrorMessage();
214
-			} else {
215
-				$message .= ', Root cause:' . self::getErrorMessage();
216
-			}
217
-			throw new \OC\DatabaseException($message);
218
-		}
219
-	}
203
+    /**
204
+     * check if a result is an error and throws an exception, works with \Doctrine\DBAL\DBALException
205
+     * @param mixed $result
206
+     * @param string $message
207
+     * @return void
208
+     * @throws \OC\DatabaseException
209
+     */
210
+    public static function raiseExceptionOnError($result, $message = null) {
211
+        if($result === false) {
212
+            if ($message === null) {
213
+                $message = self::getErrorMessage();
214
+            } else {
215
+                $message .= ', Root cause:' . self::getErrorMessage();
216
+            }
217
+            throw new \OC\DatabaseException($message);
218
+        }
219
+    }
220 220
 
221
-	/**
222
-	 * returns the error code and message as a string for logging
223
-	 * works with DoctrineException
224
-	 * @return string
225
-	 */
226
-	public static function getErrorMessage() {
227
-		$connection = \OC::$server->getDatabaseConnection();
228
-		return $connection->getError();
229
-	}
221
+    /**
222
+     * returns the error code and message as a string for logging
223
+     * works with DoctrineException
224
+     * @return string
225
+     */
226
+    public static function getErrorMessage() {
227
+        $connection = \OC::$server->getDatabaseConnection();
228
+        return $connection->getError();
229
+    }
230 230
 
231
-	/**
232
-	 * Checks if a table exists in the database - the database prefix will be prepended
233
-	 *
234
-	 * @param string $table
235
-	 * @return bool
236
-	 * @throws \OC\DatabaseException
237
-	 */
238
-	public static function tableExists($table) {
239
-		$connection = \OC::$server->getDatabaseConnection();
240
-		return $connection->tableExists($table);
241
-	}
231
+    /**
232
+     * Checks if a table exists in the database - the database prefix will be prepended
233
+     *
234
+     * @param string $table
235
+     * @return bool
236
+     * @throws \OC\DatabaseException
237
+     */
238
+    public static function tableExists($table) {
239
+        $connection = \OC::$server->getDatabaseConnection();
240
+        return $connection->tableExists($table);
241
+    }
242 242
 }
Please login to merge, or discard this patch.
Spacing   +12 added lines, -12 removed lines patch added patch discarded remove patch
@@ -53,7 +53,7 @@  discard block
 block discarded – undo
53 53
 	 *
54 54
 	 * SQL query via Doctrine prepare(), needs to be execute()'d!
55 55
 	 */
56
-	static public function prepare( $query , $limit = null, $offset = null, $isManipulation = null) {
56
+	static public function prepare($query, $limit = null, $offset = null, $isManipulation = null) {
57 57
 		$connection = \OC::$server->getDatabaseConnection();
58 58
 
59 59
 		if ($isManipulation === null) {
@@ -63,7 +63,7 @@  discard block
 block discarded – undo
63 63
 
64 64
 		// return the result
65 65
 		try {
66
-			$result =$connection->prepare($query, $limit, $offset);
66
+			$result = $connection->prepare($query, $limit, $offset);
67 67
 		} catch (\Doctrine\DBAL\DBALException $e) {
68 68
 			throw new \OC\DatabaseException($e->getMessage());
69 69
 		}
@@ -79,7 +79,7 @@  discard block
 block discarded – undo
79 79
 	 * @param string $sql
80 80
 	 * @return bool
81 81
 	 */
82
-	static public function isManipulation( $sql ) {
82
+	static public function isManipulation($sql) {
83 83
 		$selectOccurrence = stripos($sql, 'SELECT');
84 84
 		if ($selectOccurrence !== false && $selectOccurrence < 10) {
85 85
 			return false;
@@ -108,7 +108,7 @@  discard block
 block discarded – undo
108 108
 	 * @return OC_DB_StatementWrapper
109 109
 	 * @throws \OC\DatabaseException
110 110
 	 */
111
-	static public function executeAudited( $stmt, array $parameters = null) {
111
+	static public function executeAudited($stmt, array $parameters = null) {
112 112
 		if (is_string($stmt)) {
113 113
 			// convert to an array with 'sql'
114 114
 			if (stripos($stmt, 'LIMIT') !== false) { //OFFSET requires LIMIT, so we only need to check for LIMIT
@@ -121,14 +121,14 @@  discard block
 block discarded – undo
121 121
 		}
122 122
 		if (is_array($stmt)) {
123 123
 			// convert to prepared statement
124
-			if ( ! array_key_exists('sql', $stmt) ) {
124
+			if (!array_key_exists('sql', $stmt)) {
125 125
 				$message = 'statement array must at least contain key \'sql\'';
126 126
 				throw new \OC\DatabaseException($message);
127 127
 			}
128
-			if ( ! array_key_exists('limit', $stmt) ) {
128
+			if (!array_key_exists('limit', $stmt)) {
129 129
 				$stmt['limit'] = null;
130 130
 			}
131
-			if ( ! array_key_exists('limit', $stmt) ) {
131
+			if (!array_key_exists('limit', $stmt)) {
132 132
 				$stmt['offset'] = null;
133 133
 			}
134 134
 			$stmt = self::prepare($stmt['sql'], $stmt['limit'], $stmt['offset']);
@@ -139,9 +139,9 @@  discard block
 block discarded – undo
139 139
 			self::raiseExceptionOnError($result, 'Could not execute statement');
140 140
 		} else {
141 141
 			if (is_object($stmt)) {
142
-				$message = 'Expected a prepared statement or array got ' . get_class($stmt);
142
+				$message = 'Expected a prepared statement or array got '.get_class($stmt);
143 143
 			} else {
144
-				$message = 'Expected a prepared statement or array got ' . gettype($stmt);
144
+				$message = 'Expected a prepared statement or array got '.gettype($stmt);
145 145
 			}
146 146
 			throw new \OC\DatabaseException($message);
147 147
 		}
@@ -168,7 +168,7 @@  discard block
 block discarded – undo
168 168
 	 *
169 169
 	 * TODO: write more documentation
170 170
 	 */
171
-	public static function createDbFromStructure( $file ) {
171
+	public static function createDbFromStructure($file) {
172 172
 		$schemaManager = self::getMDB2SchemaManager();
173 173
 		$result = $schemaManager->createDbFromStructure($file);
174 174
 		return $result;
@@ -208,11 +208,11 @@  discard block
 block discarded – undo
208 208
 	 * @throws \OC\DatabaseException
209 209
 	 */
210 210
 	public static function raiseExceptionOnError($result, $message = null) {
211
-		if($result === false) {
211
+		if ($result === false) {
212 212
 			if ($message === null) {
213 213
 				$message = self::getErrorMessage();
214 214
 			} else {
215
-				$message .= ', Root cause:' . self::getErrorMessage();
215
+				$message .= ', Root cause:'.self::getErrorMessage();
216 216
 			}
217 217
 			throw new \OC\DatabaseException($message);
218 218
 		}
Please login to merge, or discard this patch.
apps/files_sharing/lib/SharedMount.php 3 patches
Doc Comments   +2 added lines, -2 removed lines patch added patch discarded remove patch
@@ -110,7 +110,7 @@  discard block
 block discarded – undo
110 110
 	 *
111 111
 	 * @param string $newPath
112 112
 	 * @param \OCP\Share\IShare $share
113
-	 * @return bool
113
+	 * @return boolean|null
114 114
 	 */
115 115
 	private function updateFileTarget($newPath, &$share) {
116 116
 		$share->setTarget($newPath);
@@ -126,7 +126,7 @@  discard block
 block discarded – undo
126 126
 	 * @param string $path
127 127
 	 * @param View $view
128 128
 	 * @param SharedMount[] $mountpoints
129
-	 * @return mixed
129
+	 * @return string
130 130
 	 */
131 131
 	private function generateUniqueTarget($path, $view, array $mountpoints) {
132 132
 		$pathinfo = pathinfo($path);
Please login to merge, or discard this patch.
Spacing   +11 added lines, -11 removed lines patch added patch discarded remove patch
@@ -65,14 +65,14 @@  discard block
 block discarded – undo
65 65
 	 */
66 66
 	public function __construct($storage, array $mountpoints, $arguments = null, $loader = null) {
67 67
 		$this->user = $arguments['user'];
68
-		$this->recipientView = new View('/' . $this->user . '/files');
68
+		$this->recipientView = new View('/'.$this->user.'/files');
69 69
 
70 70
 		$this->superShare = $arguments['superShare'];
71 71
 		$this->groupedShares = $arguments['groupedShares'];
72 72
 
73 73
 		$newMountPoint = $this->verifyMountPoint($this->superShare, $mountpoints);
74
-		$absMountPoint = '/' . $this->user . '/files' . $newMountPoint;
75
-		$arguments['ownerView'] = new View('/' . $this->superShare->getShareOwner() . '/files');
74
+		$absMountPoint = '/'.$this->user.'/files'.$newMountPoint;
75
+		$arguments['ownerView'] = new View('/'.$this->superShare->getShareOwner().'/files');
76 76
 		parent::__construct($storage, $absMountPoint, $arguments, $loader);
77 77
 	}
78 78
 
@@ -93,7 +93,7 @@  discard block
 block discarded – undo
93 93
 		}
94 94
 
95 95
 		$newMountPoint = $this->generateUniqueTarget(
96
-			\OC\Files\Filesystem::normalizePath($parent . '/' . $mountPoint),
96
+			\OC\Files\Filesystem::normalizePath($parent.'/'.$mountPoint),
97 97
 			$this->recipientView,
98 98
 			$mountpoints
99 99
 		);
@@ -130,12 +130,12 @@  discard block
 block discarded – undo
130 130
 	 */
131 131
 	private function generateUniqueTarget($path, $view, array $mountpoints) {
132 132
 		$pathinfo = pathinfo($path);
133
-		$ext = (isset($pathinfo['extension'])) ? '.' . $pathinfo['extension'] : '';
133
+		$ext = (isset($pathinfo['extension'])) ? '.'.$pathinfo['extension'] : '';
134 134
 		$name = $pathinfo['filename'];
135 135
 		$dir = $pathinfo['dirname'];
136 136
 
137 137
 		// Helper function to find existing mount points
138
-		$mountpointExists = function ($path) use ($mountpoints) {
138
+		$mountpointExists = function($path) use ($mountpoints) {
139 139
 			foreach ($mountpoints as $mountpoint) {
140 140
 				if ($mountpoint->getShare()->getTarget() === $path) {
141 141
 					return true;
@@ -146,7 +146,7 @@  discard block
 block discarded – undo
146 146
 
147 147
 		$i = 2;
148 148
 		while ($view->file_exists($path) || $mountpointExists($path)) {
149
-			$path = Filesystem::normalizePath($dir . '/' . $name . ' (' . $i . ')' . $ext);
149
+			$path = Filesystem::normalizePath($dir.'/'.$name.' ('.$i.')'.$ext);
150 150
 			$i++;
151 151
 		}
152 152
 
@@ -167,7 +167,7 @@  discard block
 block discarded – undo
167 167
 		// it is not a file relative to data/user/files
168 168
 		if (count($split) < 3 || $split[1] !== 'files') {
169 169
 			\OCP\Util::writeLog('file sharing',
170
-				'Can not strip userid and "files/" from path: ' . $path,
170
+				'Can not strip userid and "files/" from path: '.$path,
171 171
 				\OCP\Util::ERROR);
172 172
 			throw new \OCA\Files_Sharing\Exceptions\BrokenPath('Path does not start with /user/files', 10);
173 173
 		}
@@ -176,7 +176,7 @@  discard block
 block discarded – undo
176 176
 		$sliced = array_slice($split, 2);
177 177
 		$relPath = implode('/', $sliced);
178 178
 
179
-		return '/' . $relPath;
179
+		return '/'.$relPath;
180 180
 	}
181 181
 
182 182
 	/**
@@ -198,7 +198,7 @@  discard block
 block discarded – undo
198 198
 			$this->storage->setMountPoint($relTargetPath);
199 199
 		} catch (\Exception $e) {
200 200
 			\OCP\Util::writeLog('file sharing',
201
-				'Could not rename mount point for shared folder "' . $this->getMountPoint() . '" to "' . $target . '"',
201
+				'Could not rename mount point for shared folder "'.$this->getMountPoint().'" to "'.$target.'"',
202 202
 				\OCP\Util::ERROR);
203 203
 		}
204 204
 
@@ -253,7 +253,7 @@  discard block
 block discarded – undo
253 253
 			$row = $result->fetch();
254 254
 			$result->closeCursor();
255 255
 			if ($row) {
256
-				return (int)$row['storage'];
256
+				return (int) $row['storage'];
257 257
 			}
258 258
 			return -1;
259 259
 		}
Please login to merge, or discard this patch.
Indentation   +226 added lines, -226 removed lines patch added patch discarded remove patch
@@ -36,230 +36,230 @@
 block discarded – undo
36 36
  * Shared mount points can be moved by the user
37 37
  */
38 38
 class SharedMount extends MountPoint implements MoveableMount {
39
-	/**
40
-	 * @var \OCA\Files_Sharing\SharedStorage $storage
41
-	 */
42
-	protected $storage = null;
43
-
44
-	/**
45
-	 * @var \OC\Files\View
46
-	 */
47
-	private $recipientView;
48
-
49
-	/**
50
-	 * @var string
51
-	 */
52
-	private $user;
53
-
54
-	/** @var \OCP\Share\IShare */
55
-	private $superShare;
56
-
57
-	/** @var \OCP\Share\IShare[] */
58
-	private $groupedShares;
59
-
60
-	/**
61
-	 * @param string $storage
62
-	 * @param SharedMount[] $mountpoints
63
-	 * @param array|null $arguments
64
-	 * @param \OCP\Files\Storage\IStorageFactory $loader
65
-	 */
66
-	public function __construct($storage, array $mountpoints, $arguments = null, $loader = null) {
67
-		$this->user = $arguments['user'];
68
-		$this->recipientView = new View('/' . $this->user . '/files');
69
-
70
-		$this->superShare = $arguments['superShare'];
71
-		$this->groupedShares = $arguments['groupedShares'];
72
-
73
-		$newMountPoint = $this->verifyMountPoint($this->superShare, $mountpoints);
74
-		$absMountPoint = '/' . $this->user . '/files' . $newMountPoint;
75
-		$arguments['ownerView'] = new View('/' . $this->superShare->getShareOwner() . '/files');
76
-		parent::__construct($storage, $absMountPoint, $arguments, $loader);
77
-	}
78
-
79
-	/**
80
-	 * check if the parent folder exists otherwise move the mount point up
81
-	 *
82
-	 * @param \OCP\Share\IShare $share
83
-	 * @param SharedMount[] $mountpoints
84
-	 * @return string
85
-	 */
86
-	private function verifyMountPoint(\OCP\Share\IShare $share, array $mountpoints) {
87
-
88
-		$mountPoint = basename($share->getTarget());
89
-		$parent = dirname($share->getTarget());
90
-
91
-		if (!$this->recipientView->is_dir($parent)) {
92
-			$parent = Helper::getShareFolder($this->recipientView);
93
-		}
94
-
95
-		$newMountPoint = $this->generateUniqueTarget(
96
-			\OC\Files\Filesystem::normalizePath($parent . '/' . $mountPoint),
97
-			$this->recipientView,
98
-			$mountpoints
99
-		);
100
-
101
-		if ($newMountPoint !== $share->getTarget()) {
102
-			$this->updateFileTarget($newMountPoint, $share);
103
-		}
104
-
105
-		return $newMountPoint;
106
-	}
107
-
108
-	/**
109
-	 * update fileTarget in the database if the mount point changed
110
-	 *
111
-	 * @param string $newPath
112
-	 * @param \OCP\Share\IShare $share
113
-	 * @return bool
114
-	 */
115
-	private function updateFileTarget($newPath, &$share) {
116
-		$share->setTarget($newPath);
117
-
118
-		foreach ($this->groupedShares as $tmpShare) {
119
-			$tmpShare->setTarget($newPath);
120
-			\OC::$server->getShareManager()->moveShare($tmpShare, $this->user);
121
-		}
122
-	}
123
-
124
-
125
-	/**
126
-	 * @param string $path
127
-	 * @param View $view
128
-	 * @param SharedMount[] $mountpoints
129
-	 * @return mixed
130
-	 */
131
-	private function generateUniqueTarget($path, $view, array $mountpoints) {
132
-		$pathinfo = pathinfo($path);
133
-		$ext = (isset($pathinfo['extension'])) ? '.' . $pathinfo['extension'] : '';
134
-		$name = $pathinfo['filename'];
135
-		$dir = $pathinfo['dirname'];
136
-
137
-		// Helper function to find existing mount points
138
-		$mountpointExists = function ($path) use ($mountpoints) {
139
-			foreach ($mountpoints as $mountpoint) {
140
-				if ($mountpoint->getShare()->getTarget() === $path) {
141
-					return true;
142
-				}
143
-			}
144
-			return false;
145
-		};
146
-
147
-		$i = 2;
148
-		while ($view->file_exists($path) || $mountpointExists($path)) {
149
-			$path = Filesystem::normalizePath($dir . '/' . $name . ' (' . $i . ')' . $ext);
150
-			$i++;
151
-		}
152
-
153
-		return $path;
154
-	}
155
-
156
-	/**
157
-	 * Format a path to be relative to the /user/files/ directory
158
-	 *
159
-	 * @param string $path the absolute path
160
-	 * @return string e.g. turns '/admin/files/test.txt' into '/test.txt'
161
-	 * @throws \OCA\Files_Sharing\Exceptions\BrokenPath
162
-	 */
163
-	protected function stripUserFilesPath($path) {
164
-		$trimmed = ltrim($path, '/');
165
-		$split = explode('/', $trimmed);
166
-
167
-		// it is not a file relative to data/user/files
168
-		if (count($split) < 3 || $split[1] !== 'files') {
169
-			\OCP\Util::writeLog('file sharing',
170
-				'Can not strip userid and "files/" from path: ' . $path,
171
-				\OCP\Util::ERROR);
172
-			throw new \OCA\Files_Sharing\Exceptions\BrokenPath('Path does not start with /user/files', 10);
173
-		}
174
-
175
-		// skip 'user' and 'files'
176
-		$sliced = array_slice($split, 2);
177
-		$relPath = implode('/', $sliced);
178
-
179
-		return '/' . $relPath;
180
-	}
181
-
182
-	/**
183
-	 * Move the mount point to $target
184
-	 *
185
-	 * @param string $target the target mount point
186
-	 * @return bool
187
-	 */
188
-	public function moveMount($target) {
189
-
190
-		$relTargetPath = $this->stripUserFilesPath($target);
191
-		$share = $this->storage->getShare();
192
-
193
-		$result = true;
194
-
195
-		try {
196
-			$this->updateFileTarget($relTargetPath, $share);
197
-			$this->setMountPoint($target);
198
-			$this->storage->setMountPoint($relTargetPath);
199
-		} catch (\Exception $e) {
200
-			\OCP\Util::writeLog('file sharing',
201
-				'Could not rename mount point for shared folder "' . $this->getMountPoint() . '" to "' . $target . '"',
202
-				\OCP\Util::ERROR);
203
-		}
204
-
205
-		return $result;
206
-	}
207
-
208
-	/**
209
-	 * Remove the mount points
210
-	 *
211
-	 * @return bool
212
-	 */
213
-	public function removeMount() {
214
-		$mountManager = \OC\Files\Filesystem::getMountManager();
215
-		/** @var $storage \OCA\Files_Sharing\SharedStorage */
216
-		$storage = $this->getStorage();
217
-		$result = $storage->unshareStorage();
218
-		$mountManager->removeMount($this->mountPoint);
219
-
220
-		return $result;
221
-	}
222
-
223
-	/**
224
-	 * @return \OCP\Share\IShare
225
-	 */
226
-	public function getShare() {
227
-		return $this->superShare;
228
-	}
229
-
230
-	/**
231
-	 * Get the file id of the root of the storage
232
-	 *
233
-	 * @return int
234
-	 */
235
-	public function getStorageRootId() {
236
-		return $this->getShare()->getNodeId();
237
-	}
238
-
239
-	/**
240
-	 * @return int
241
-	 */
242
-	public function getNumericStorageId() {
243
-		if (!is_null($this->getShare()->getNodeCacheEntry())) {
244
-			return $this->getShare()->getNodeCacheEntry()->getStorageId();
245
-		} else {
246
-			$builder = \OC::$server->getDatabaseConnection()->getQueryBuilder();
247
-
248
-			$query = $builder->select('storage')
249
-				->from('filecache')
250
-				->where($builder->expr()->eq('fileid', $builder->createNamedParameter($this->getStorageRootId())));
251
-
252
-			$result = $query->execute();
253
-			$row = $result->fetch();
254
-			$result->closeCursor();
255
-			if ($row) {
256
-				return (int)$row['storage'];
257
-			}
258
-			return -1;
259
-		}
260
-	}
261
-
262
-	public function getMountType() {
263
-		return 'shared';
264
-	}
39
+    /**
40
+     * @var \OCA\Files_Sharing\SharedStorage $storage
41
+     */
42
+    protected $storage = null;
43
+
44
+    /**
45
+     * @var \OC\Files\View
46
+     */
47
+    private $recipientView;
48
+
49
+    /**
50
+     * @var string
51
+     */
52
+    private $user;
53
+
54
+    /** @var \OCP\Share\IShare */
55
+    private $superShare;
56
+
57
+    /** @var \OCP\Share\IShare[] */
58
+    private $groupedShares;
59
+
60
+    /**
61
+     * @param string $storage
62
+     * @param SharedMount[] $mountpoints
63
+     * @param array|null $arguments
64
+     * @param \OCP\Files\Storage\IStorageFactory $loader
65
+     */
66
+    public function __construct($storage, array $mountpoints, $arguments = null, $loader = null) {
67
+        $this->user = $arguments['user'];
68
+        $this->recipientView = new View('/' . $this->user . '/files');
69
+
70
+        $this->superShare = $arguments['superShare'];
71
+        $this->groupedShares = $arguments['groupedShares'];
72
+
73
+        $newMountPoint = $this->verifyMountPoint($this->superShare, $mountpoints);
74
+        $absMountPoint = '/' . $this->user . '/files' . $newMountPoint;
75
+        $arguments['ownerView'] = new View('/' . $this->superShare->getShareOwner() . '/files');
76
+        parent::__construct($storage, $absMountPoint, $arguments, $loader);
77
+    }
78
+
79
+    /**
80
+     * check if the parent folder exists otherwise move the mount point up
81
+     *
82
+     * @param \OCP\Share\IShare $share
83
+     * @param SharedMount[] $mountpoints
84
+     * @return string
85
+     */
86
+    private function verifyMountPoint(\OCP\Share\IShare $share, array $mountpoints) {
87
+
88
+        $mountPoint = basename($share->getTarget());
89
+        $parent = dirname($share->getTarget());
90
+
91
+        if (!$this->recipientView->is_dir($parent)) {
92
+            $parent = Helper::getShareFolder($this->recipientView);
93
+        }
94
+
95
+        $newMountPoint = $this->generateUniqueTarget(
96
+            \OC\Files\Filesystem::normalizePath($parent . '/' . $mountPoint),
97
+            $this->recipientView,
98
+            $mountpoints
99
+        );
100
+
101
+        if ($newMountPoint !== $share->getTarget()) {
102
+            $this->updateFileTarget($newMountPoint, $share);
103
+        }
104
+
105
+        return $newMountPoint;
106
+    }
107
+
108
+    /**
109
+     * update fileTarget in the database if the mount point changed
110
+     *
111
+     * @param string $newPath
112
+     * @param \OCP\Share\IShare $share
113
+     * @return bool
114
+     */
115
+    private function updateFileTarget($newPath, &$share) {
116
+        $share->setTarget($newPath);
117
+
118
+        foreach ($this->groupedShares as $tmpShare) {
119
+            $tmpShare->setTarget($newPath);
120
+            \OC::$server->getShareManager()->moveShare($tmpShare, $this->user);
121
+        }
122
+    }
123
+
124
+
125
+    /**
126
+     * @param string $path
127
+     * @param View $view
128
+     * @param SharedMount[] $mountpoints
129
+     * @return mixed
130
+     */
131
+    private function generateUniqueTarget($path, $view, array $mountpoints) {
132
+        $pathinfo = pathinfo($path);
133
+        $ext = (isset($pathinfo['extension'])) ? '.' . $pathinfo['extension'] : '';
134
+        $name = $pathinfo['filename'];
135
+        $dir = $pathinfo['dirname'];
136
+
137
+        // Helper function to find existing mount points
138
+        $mountpointExists = function ($path) use ($mountpoints) {
139
+            foreach ($mountpoints as $mountpoint) {
140
+                if ($mountpoint->getShare()->getTarget() === $path) {
141
+                    return true;
142
+                }
143
+            }
144
+            return false;
145
+        };
146
+
147
+        $i = 2;
148
+        while ($view->file_exists($path) || $mountpointExists($path)) {
149
+            $path = Filesystem::normalizePath($dir . '/' . $name . ' (' . $i . ')' . $ext);
150
+            $i++;
151
+        }
152
+
153
+        return $path;
154
+    }
155
+
156
+    /**
157
+     * Format a path to be relative to the /user/files/ directory
158
+     *
159
+     * @param string $path the absolute path
160
+     * @return string e.g. turns '/admin/files/test.txt' into '/test.txt'
161
+     * @throws \OCA\Files_Sharing\Exceptions\BrokenPath
162
+     */
163
+    protected function stripUserFilesPath($path) {
164
+        $trimmed = ltrim($path, '/');
165
+        $split = explode('/', $trimmed);
166
+
167
+        // it is not a file relative to data/user/files
168
+        if (count($split) < 3 || $split[1] !== 'files') {
169
+            \OCP\Util::writeLog('file sharing',
170
+                'Can not strip userid and "files/" from path: ' . $path,
171
+                \OCP\Util::ERROR);
172
+            throw new \OCA\Files_Sharing\Exceptions\BrokenPath('Path does not start with /user/files', 10);
173
+        }
174
+
175
+        // skip 'user' and 'files'
176
+        $sliced = array_slice($split, 2);
177
+        $relPath = implode('/', $sliced);
178
+
179
+        return '/' . $relPath;
180
+    }
181
+
182
+    /**
183
+     * Move the mount point to $target
184
+     *
185
+     * @param string $target the target mount point
186
+     * @return bool
187
+     */
188
+    public function moveMount($target) {
189
+
190
+        $relTargetPath = $this->stripUserFilesPath($target);
191
+        $share = $this->storage->getShare();
192
+
193
+        $result = true;
194
+
195
+        try {
196
+            $this->updateFileTarget($relTargetPath, $share);
197
+            $this->setMountPoint($target);
198
+            $this->storage->setMountPoint($relTargetPath);
199
+        } catch (\Exception $e) {
200
+            \OCP\Util::writeLog('file sharing',
201
+                'Could not rename mount point for shared folder "' . $this->getMountPoint() . '" to "' . $target . '"',
202
+                \OCP\Util::ERROR);
203
+        }
204
+
205
+        return $result;
206
+    }
207
+
208
+    /**
209
+     * Remove the mount points
210
+     *
211
+     * @return bool
212
+     */
213
+    public function removeMount() {
214
+        $mountManager = \OC\Files\Filesystem::getMountManager();
215
+        /** @var $storage \OCA\Files_Sharing\SharedStorage */
216
+        $storage = $this->getStorage();
217
+        $result = $storage->unshareStorage();
218
+        $mountManager->removeMount($this->mountPoint);
219
+
220
+        return $result;
221
+    }
222
+
223
+    /**
224
+     * @return \OCP\Share\IShare
225
+     */
226
+    public function getShare() {
227
+        return $this->superShare;
228
+    }
229
+
230
+    /**
231
+     * Get the file id of the root of the storage
232
+     *
233
+     * @return int
234
+     */
235
+    public function getStorageRootId() {
236
+        return $this->getShare()->getNodeId();
237
+    }
238
+
239
+    /**
240
+     * @return int
241
+     */
242
+    public function getNumericStorageId() {
243
+        if (!is_null($this->getShare()->getNodeCacheEntry())) {
244
+            return $this->getShare()->getNodeCacheEntry()->getStorageId();
245
+        } else {
246
+            $builder = \OC::$server->getDatabaseConnection()->getQueryBuilder();
247
+
248
+            $query = $builder->select('storage')
249
+                ->from('filecache')
250
+                ->where($builder->expr()->eq('fileid', $builder->createNamedParameter($this->getStorageRootId())));
251
+
252
+            $result = $query->execute();
253
+            $row = $result->fetch();
254
+            $result->closeCursor();
255
+            if ($row) {
256
+                return (int)$row['storage'];
257
+            }
258
+            return -1;
259
+        }
260
+    }
261
+
262
+    public function getMountType() {
263
+        return 'shared';
264
+    }
265 265
 }
Please login to merge, or discard this patch.