Completed
Push — master ( 4ad272...f18db1 )
by Morris
14:44
created
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.
Indentation   +1314 added lines, -1314 removed lines patch added patch discarded remove patch
@@ -42,1320 +42,1320 @@
 block discarded – undo
42 42
 use OCP\ILogger;
43 43
 
44 44
 class Wizard extends LDAPUtility {
45
-	/** @var \OCP\IL10N */
46
-	static protected $l;
47
-	protected $access;
48
-	protected $cr;
49
-	protected $configuration;
50
-	protected $result;
51
-	protected $resultCache = array();
52
-
53
-	const LRESULT_PROCESSED_OK = 2;
54
-	const LRESULT_PROCESSED_INVALID = 3;
55
-	const LRESULT_PROCESSED_SKIP = 4;
56
-
57
-	const LFILTER_LOGIN      = 2;
58
-	const LFILTER_USER_LIST  = 3;
59
-	const LFILTER_GROUP_LIST = 4;
60
-
61
-	const LFILTER_MODE_ASSISTED = 2;
62
-	const LFILTER_MODE_RAW = 1;
63
-
64
-	const LDAP_NW_TIMEOUT = 4;
65
-
66
-	/**
67
-	 * Constructor
68
-	 * @param Configuration $configuration an instance of Configuration
69
-	 * @param ILDAPWrapper $ldap an instance of ILDAPWrapper
70
-	 * @param Access $access
71
-	 */
72
-	public function __construct(Configuration $configuration, ILDAPWrapper $ldap, Access $access) {
73
-		parent::__construct($ldap);
74
-		$this->configuration = $configuration;
75
-		if(is_null(Wizard::$l)) {
76
-			Wizard::$l = \OC::$server->getL10N('user_ldap');
77
-		}
78
-		$this->access = $access;
79
-		$this->result = new WizardResult();
80
-	}
81
-
82
-	public function  __destruct() {
83
-		if($this->result->hasChanges()) {
84
-			$this->configuration->saveConfiguration();
85
-		}
86
-	}
87
-
88
-	/**
89
-	 * counts entries in the LDAP directory
90
-	 *
91
-	 * @param string $filter the LDAP search filter
92
-	 * @param string $type a string being either 'users' or 'groups';
93
-	 * @return int
94
-	 * @throws \Exception
95
-	 */
96
-	public function countEntries(string $filter, string $type): int {
97
-		$reqs = ['ldapHost', 'ldapPort', 'ldapBase'];
98
-		if($type === 'users') {
99
-			$reqs[] = 'ldapUserFilter';
100
-		}
101
-		if(!$this->checkRequirements($reqs)) {
102
-			throw new \Exception('Requirements not met', 400);
103
-		}
104
-
105
-		$attr = ['dn']; // default
106
-		$limit = 1001;
107
-		if($type === 'groups') {
108
-			$result =  $this->access->countGroups($filter, $attr, $limit);
109
-		} else if($type === 'users') {
110
-			$result = $this->access->countUsers($filter, $attr, $limit);
111
-		} else if ($type === 'objects') {
112
-			$result = $this->access->countObjects($limit);
113
-		} else {
114
-			throw new \Exception('Internal error: Invalid object type', 500);
115
-		}
116
-
117
-		return (int)$result;
118
-	}
119
-
120
-	/**
121
-	 * formats the return value of a count operation to the string to be
122
-	 * inserted.
123
-	 *
124
-	 * @param int $count
125
-	 * @return string
126
-	 */
127
-	private function formatCountResult(int $count): string {
128
-		if($count > 1000) {
129
-			return '> 1000';
130
-		}
131
-		return (string)$count;
132
-	}
133
-
134
-	public function countGroups() {
135
-		$filter = $this->configuration->ldapGroupFilter;
136
-
137
-		if(empty($filter)) {
138
-			$output = self::$l->n('%s group found', '%s groups found', 0, array(0));
139
-			$this->result->addChange('ldap_group_count', $output);
140
-			return $this->result;
141
-		}
142
-
143
-		try {
144
-			$groupsTotal = $this->countEntries($filter, 'groups');
145
-		} catch (\Exception $e) {
146
-			//400 can be ignored, 500 is forwarded
147
-			if($e->getCode() === 500) {
148
-				throw $e;
149
-			}
150
-			return false;
151
-		}
152
-		$output = self::$l->n(
153
-			'%s group found',
154
-			'%s groups found',
155
-			$groupsTotal,
156
-			[$this->formatCountResult($groupsTotal)]
157
-		);
158
-		$this->result->addChange('ldap_group_count', $output);
159
-		return $this->result;
160
-	}
161
-
162
-	/**
163
-	 * @return WizardResult
164
-	 * @throws \Exception
165
-	 */
166
-	public function countUsers() {
167
-		$filter = $this->access->getFilterForUserCount();
168
-
169
-		$usersTotal = $this->countEntries($filter, 'users');
170
-		$output = self::$l->n(
171
-			'%s user found',
172
-			'%s users found',
173
-			$usersTotal,
174
-			[$this->formatCountResult($usersTotal)]
175
-		);
176
-		$this->result->addChange('ldap_user_count', $output);
177
-		return $this->result;
178
-	}
179
-
180
-	/**
181
-	 * counts any objects in the currently set base dn
182
-	 *
183
-	 * @return WizardResult
184
-	 * @throws \Exception
185
-	 */
186
-	public function countInBaseDN() {
187
-		// we don't need to provide a filter in this case
188
-		$total = $this->countEntries('', 'objects');
189
-		if($total === false) {
190
-			throw new \Exception('invalid results received');
191
-		}
192
-		$this->result->addChange('ldap_test_base', $total);
193
-		return $this->result;
194
-	}
195
-
196
-	/**
197
-	 * counts users with a specified attribute
198
-	 * @param string $attr
199
-	 * @param bool $existsCheck
200
-	 * @return int|bool
201
-	 */
202
-	public function countUsersWithAttribute($attr, $existsCheck = false) {
203
-		if(!$this->checkRequirements(array('ldapHost',
204
-										   'ldapPort',
205
-										   'ldapBase',
206
-										   'ldapUserFilter',
207
-										   ))) {
208
-			return  false;
209
-		}
210
-
211
-		$filter = $this->access->combineFilterWithAnd(array(
212
-			$this->configuration->ldapUserFilter,
213
-			$attr . '=*'
214
-		));
215
-
216
-		$limit = ($existsCheck === false) ? null : 1;
217
-
218
-		return $this->access->countUsers($filter, array('dn'), $limit);
219
-	}
220
-
221
-	/**
222
-	 * detects the display name attribute. If a setting is already present that
223
-	 * returns at least one hit, the detection will be canceled.
224
-	 * @return WizardResult|bool
225
-	 * @throws \Exception
226
-	 */
227
-	public function detectUserDisplayNameAttribute() {
228
-		if(!$this->checkRequirements(array('ldapHost',
229
-										'ldapPort',
230
-										'ldapBase',
231
-										'ldapUserFilter',
232
-										))) {
233
-			return  false;
234
-		}
235
-
236
-		$attr = $this->configuration->ldapUserDisplayName;
237
-		if ($attr !== '' && $attr !== 'displayName') {
238
-			// most likely not the default value with upper case N,
239
-			// verify it still produces a result
240
-			$count = (int)$this->countUsersWithAttribute($attr, true);
241
-			if($count > 0) {
242
-				//no change, but we sent it back to make sure the user interface
243
-				//is still correct, even if the ajax call was cancelled meanwhile
244
-				$this->result->addChange('ldap_display_name', $attr);
245
-				return $this->result;
246
-			}
247
-		}
248
-
249
-		// first attribute that has at least one result wins
250
-		$displayNameAttrs = array('displayname', 'cn');
251
-		foreach ($displayNameAttrs as $attr) {
252
-			$count = (int)$this->countUsersWithAttribute($attr, true);
253
-
254
-			if($count > 0) {
255
-				$this->applyFind('ldap_display_name', $attr);
256
-				return $this->result;
257
-			}
258
-		}
259
-
260
-		throw new \Exception(self::$l->t('Could not detect user display name attribute. Please specify it yourself in advanced LDAP settings.'));
261
-	}
262
-
263
-	/**
264
-	 * detects the most often used email attribute for users applying to the
265
-	 * user list filter. If a setting is already present that returns at least
266
-	 * one hit, the detection will be canceled.
267
-	 * @return WizardResult|bool
268
-	 */
269
-	public function detectEmailAttribute() {
270
-		if(!$this->checkRequirements(array('ldapHost',
271
-										   'ldapPort',
272
-										   'ldapBase',
273
-										   'ldapUserFilter',
274
-										   ))) {
275
-			return  false;
276
-		}
277
-
278
-		$attr = $this->configuration->ldapEmailAttribute;
279
-		if ($attr !== '') {
280
-			$count = (int)$this->countUsersWithAttribute($attr, true);
281
-			if($count > 0) {
282
-				return false;
283
-			}
284
-			$writeLog = true;
285
-		} else {
286
-			$writeLog = false;
287
-		}
288
-
289
-		$emailAttributes = array('mail', 'mailPrimaryAddress');
290
-		$winner = '';
291
-		$maxUsers = 0;
292
-		foreach($emailAttributes as $attr) {
293
-			$count = $this->countUsersWithAttribute($attr);
294
-			if($count > $maxUsers) {
295
-				$maxUsers = $count;
296
-				$winner = $attr;
297
-			}
298
-		}
299
-
300
-		if($winner !== '') {
301
-			$this->applyFind('ldap_email_attr', $winner);
302
-			if($writeLog) {
303
-				\OCP\Util::writeLog('user_ldap', 'The mail attribute has ' .
304
-					'automatically been reset, because the original value ' .
305
-					'did not return any results.', ILogger::INFO);
306
-			}
307
-		}
308
-
309
-		return $this->result;
310
-	}
311
-
312
-	/**
313
-	 * @return WizardResult
314
-	 * @throws \Exception
315
-	 */
316
-	public function determineAttributes() {
317
-		if(!$this->checkRequirements(array('ldapHost',
318
-										   'ldapPort',
319
-										   'ldapBase',
320
-										   'ldapUserFilter',
321
-										   ))) {
322
-			return  false;
323
-		}
324
-
325
-		$attributes = $this->getUserAttributes();
326
-
327
-		natcasesort($attributes);
328
-		$attributes = array_values($attributes);
329
-
330
-		$this->result->addOptions('ldap_loginfilter_attributes', $attributes);
331
-
332
-		$selected = $this->configuration->ldapLoginFilterAttributes;
333
-		if(is_array($selected) && !empty($selected)) {
334
-			$this->result->addChange('ldap_loginfilter_attributes', $selected);
335
-		}
336
-
337
-		return $this->result;
338
-	}
339
-
340
-	/**
341
-	 * detects the available LDAP attributes
342
-	 * @return array|false The instance's WizardResult instance
343
-	 * @throws \Exception
344
-	 */
345
-	private function getUserAttributes() {
346
-		if(!$this->checkRequirements(array('ldapHost',
347
-										   'ldapPort',
348
-										   'ldapBase',
349
-										   'ldapUserFilter',
350
-										   ))) {
351
-			return  false;
352
-		}
353
-		$cr = $this->getConnection();
354
-		if(!$cr) {
355
-			throw new \Exception('Could not connect to LDAP');
356
-		}
357
-
358
-		$base = $this->configuration->ldapBase[0];
359
-		$filter = $this->configuration->ldapUserFilter;
360
-		$rr = $this->ldap->search($cr, $base, $filter, array(), 1, 1);
361
-		if(!$this->ldap->isResource($rr)) {
362
-			return false;
363
-		}
364
-		$er = $this->ldap->firstEntry($cr, $rr);
365
-		$attributes = $this->ldap->getAttributes($cr, $er);
366
-		$pureAttributes = array();
367
-		for($i = 0; $i < $attributes['count']; $i++) {
368
-			$pureAttributes[] = $attributes[$i];
369
-		}
370
-
371
-		return $pureAttributes;
372
-	}
373
-
374
-	/**
375
-	 * detects the available LDAP groups
376
-	 * @return WizardResult|false the instance's WizardResult instance
377
-	 */
378
-	public function determineGroupsForGroups() {
379
-		return $this->determineGroups('ldap_groupfilter_groups',
380
-									  'ldapGroupFilterGroups',
381
-									  false);
382
-	}
383
-
384
-	/**
385
-	 * detects the available LDAP groups
386
-	 * @return WizardResult|false the instance's WizardResult instance
387
-	 */
388
-	public function determineGroupsForUsers() {
389
-		return $this->determineGroups('ldap_userfilter_groups',
390
-									  'ldapUserFilterGroups');
391
-	}
392
-
393
-	/**
394
-	 * detects the available LDAP groups
395
-	 * @param string $dbKey
396
-	 * @param string $confKey
397
-	 * @param bool $testMemberOf
398
-	 * @return WizardResult|false the instance's WizardResult instance
399
-	 * @throws \Exception
400
-	 */
401
-	private function determineGroups($dbKey, $confKey, $testMemberOf = true) {
402
-		if(!$this->checkRequirements(array('ldapHost',
403
-										   'ldapPort',
404
-										   'ldapBase',
405
-										   ))) {
406
-			return  false;
407
-		}
408
-		$cr = $this->getConnection();
409
-		if(!$cr) {
410
-			throw new \Exception('Could not connect to LDAP');
411
-		}
412
-
413
-		$this->fetchGroups($dbKey, $confKey);
414
-
415
-		if($testMemberOf) {
416
-			$this->configuration->hasMemberOfFilterSupport = $this->testMemberOf();
417
-			$this->result->markChange();
418
-			if(!$this->configuration->hasMemberOfFilterSupport) {
419
-				throw new \Exception('memberOf is not supported by the server');
420
-			}
421
-		}
422
-
423
-		return $this->result;
424
-	}
425
-
426
-	/**
427
-	 * fetches all groups from LDAP and adds them to the result object
428
-	 *
429
-	 * @param string $dbKey
430
-	 * @param string $confKey
431
-	 * @return array $groupEntries
432
-	 * @throws \Exception
433
-	 */
434
-	public function fetchGroups($dbKey, $confKey) {
435
-		$obclasses = array('posixGroup', 'group', 'zimbraDistributionList', 'groupOfNames', 'groupOfUniqueNames');
436
-
437
-		$filterParts = array();
438
-		foreach($obclasses as $obclass) {
439
-			$filterParts[] = 'objectclass='.$obclass;
440
-		}
441
-		//we filter for everything
442
-		//- that looks like a group and
443
-		//- has the group display name set
444
-		$filter = $this->access->combineFilterWithOr($filterParts);
445
-		$filter = $this->access->combineFilterWithAnd(array($filter, 'cn=*'));
446
-
447
-		$groupNames = array();
448
-		$groupEntries = array();
449
-		$limit = 400;
450
-		$offset = 0;
451
-		do {
452
-			// we need to request dn additionally here, otherwise memberOf
453
-			// detection will fail later
454
-			$result = $this->access->searchGroups($filter, array('cn', 'dn'), $limit, $offset);
455
-			foreach($result as $item) {
456
-				if(!isset($item['cn']) && !is_array($item['cn']) && !isset($item['cn'][0])) {
457
-					// just in case - no issue known
458
-					continue;
459
-				}
460
-				$groupNames[] = $item['cn'][0];
461
-				$groupEntries[] = $item;
462
-			}
463
-			$offset += $limit;
464
-		} while ($this->access->hasMoreResults());
465
-
466
-		if(count($groupNames) > 0) {
467
-			natsort($groupNames);
468
-			$this->result->addOptions($dbKey, array_values($groupNames));
469
-		} else {
470
-			throw new \Exception(self::$l->t('Could not find the desired feature'));
471
-		}
472
-
473
-		$setFeatures = $this->configuration->$confKey;
474
-		if(is_array($setFeatures) && !empty($setFeatures)) {
475
-			//something is already configured? pre-select it.
476
-			$this->result->addChange($dbKey, $setFeatures);
477
-		}
478
-		return $groupEntries;
479
-	}
480
-
481
-	public function determineGroupMemberAssoc() {
482
-		if(!$this->checkRequirements(array('ldapHost',
483
-										   'ldapPort',
484
-										   'ldapGroupFilter',
485
-										   ))) {
486
-			return  false;
487
-		}
488
-		$attribute = $this->detectGroupMemberAssoc();
489
-		if($attribute === false) {
490
-			return false;
491
-		}
492
-		$this->configuration->setConfiguration(array('ldapGroupMemberAssocAttr' => $attribute));
493
-		$this->result->addChange('ldap_group_member_assoc_attribute', $attribute);
494
-
495
-		return $this->result;
496
-	}
497
-
498
-	/**
499
-	 * Detects the available object classes
500
-	 * @return WizardResult|false the instance's WizardResult instance
501
-	 * @throws \Exception
502
-	 */
503
-	public function determineGroupObjectClasses() {
504
-		if(!$this->checkRequirements(array('ldapHost',
505
-										   'ldapPort',
506
-										   'ldapBase',
507
-										   ))) {
508
-			return  false;
509
-		}
510
-		$cr = $this->getConnection();
511
-		if(!$cr) {
512
-			throw new \Exception('Could not connect to LDAP');
513
-		}
514
-
515
-		$obclasses = array('groupOfNames', 'groupOfUniqueNames', 'group', 'posixGroup', '*');
516
-		$this->determineFeature($obclasses,
517
-								'objectclass',
518
-								'ldap_groupfilter_objectclass',
519
-								'ldapGroupFilterObjectclass',
520
-								false);
521
-
522
-		return $this->result;
523
-	}
524
-
525
-	/**
526
-	 * detects the available object classes
527
-	 * @return WizardResult
528
-	 * @throws \Exception
529
-	 */
530
-	public function determineUserObjectClasses() {
531
-		if(!$this->checkRequirements(array('ldapHost',
532
-										   'ldapPort',
533
-										   'ldapBase',
534
-										   ))) {
535
-			return  false;
536
-		}
537
-		$cr = $this->getConnection();
538
-		if(!$cr) {
539
-			throw new \Exception('Could not connect to LDAP');
540
-		}
541
-
542
-		$obclasses = array('inetOrgPerson', 'person', 'organizationalPerson',
543
-						   'user', 'posixAccount', '*');
544
-		$filter = $this->configuration->ldapUserFilter;
545
-		//if filter is empty, it is probably the first time the wizard is called
546
-		//then, apply suggestions.
547
-		$this->determineFeature($obclasses,
548
-								'objectclass',
549
-								'ldap_userfilter_objectclass',
550
-								'ldapUserFilterObjectclass',
551
-								empty($filter));
552
-
553
-		return $this->result;
554
-	}
555
-
556
-	/**
557
-	 * @return WizardResult|false
558
-	 * @throws \Exception
559
-	 */
560
-	public function getGroupFilter() {
561
-		if(!$this->checkRequirements(array('ldapHost',
562
-										   'ldapPort',
563
-										   'ldapBase',
564
-										   ))) {
565
-			return false;
566
-		}
567
-		//make sure the use display name is set
568
-		$displayName = $this->configuration->ldapGroupDisplayName;
569
-		if ($displayName === '') {
570
-			$d = $this->configuration->getDefaults();
571
-			$this->applyFind('ldap_group_display_name',
572
-							 $d['ldap_group_display_name']);
573
-		}
574
-		$filter = $this->composeLdapFilter(self::LFILTER_GROUP_LIST);
575
-
576
-		$this->applyFind('ldap_group_filter', $filter);
577
-		return $this->result;
578
-	}
579
-
580
-	/**
581
-	 * @return WizardResult|false
582
-	 * @throws \Exception
583
-	 */
584
-	public function getUserListFilter() {
585
-		if(!$this->checkRequirements(array('ldapHost',
586
-										   'ldapPort',
587
-										   'ldapBase',
588
-										   ))) {
589
-			return false;
590
-		}
591
-		//make sure the use display name is set
592
-		$displayName = $this->configuration->ldapUserDisplayName;
593
-		if ($displayName === '') {
594
-			$d = $this->configuration->getDefaults();
595
-			$this->applyFind('ldap_display_name', $d['ldap_display_name']);
596
-		}
597
-		$filter = $this->composeLdapFilter(self::LFILTER_USER_LIST);
598
-		if(!$filter) {
599
-			throw new \Exception('Cannot create filter');
600
-		}
601
-
602
-		$this->applyFind('ldap_userlist_filter', $filter);
603
-		return $this->result;
604
-	}
605
-
606
-	/**
607
-	 * @return bool|WizardResult
608
-	 * @throws \Exception
609
-	 */
610
-	public function getUserLoginFilter() {
611
-		if(!$this->checkRequirements(array('ldapHost',
612
-										   'ldapPort',
613
-										   'ldapBase',
614
-										   'ldapUserFilter',
615
-										   ))) {
616
-			return false;
617
-		}
618
-
619
-		$filter = $this->composeLdapFilter(self::LFILTER_LOGIN);
620
-		if(!$filter) {
621
-			throw new \Exception('Cannot create filter');
622
-		}
623
-
624
-		$this->applyFind('ldap_login_filter', $filter);
625
-		return $this->result;
626
-	}
627
-
628
-	/**
629
-	 * @return bool|WizardResult
630
-	 * @param string $loginName
631
-	 * @throws \Exception
632
-	 */
633
-	public function testLoginName($loginName) {
634
-		if(!$this->checkRequirements(array('ldapHost',
635
-			'ldapPort',
636
-			'ldapBase',
637
-			'ldapLoginFilter',
638
-		))) {
639
-			return false;
640
-		}
641
-
642
-		$cr = $this->access->connection->getConnectionResource();
643
-		if(!$this->ldap->isResource($cr)) {
644
-			throw new \Exception('connection error');
645
-		}
646
-
647
-		if(mb_strpos($this->access->connection->ldapLoginFilter, '%uid', 0, 'UTF-8')
648
-			=== false) {
649
-			throw new \Exception('missing placeholder');
650
-		}
651
-
652
-		$users = $this->access->countUsersByLoginName($loginName);
653
-		if($this->ldap->errno($cr) !== 0) {
654
-			throw new \Exception($this->ldap->error($cr));
655
-		}
656
-		$filter = str_replace('%uid', $loginName, $this->access->connection->ldapLoginFilter);
657
-		$this->result->addChange('ldap_test_loginname', $users);
658
-		$this->result->addChange('ldap_test_effective_filter', $filter);
659
-		return $this->result;
660
-	}
661
-
662
-	/**
663
-	 * Tries to determine the port, requires given Host, User DN and Password
664
-	 * @return WizardResult|false WizardResult on success, false otherwise
665
-	 * @throws \Exception
666
-	 */
667
-	public function guessPortAndTLS() {
668
-		if(!$this->checkRequirements(array('ldapHost',
669
-										   ))) {
670
-			return false;
671
-		}
672
-		$this->checkHost();
673
-		$portSettings = $this->getPortSettingsToTry();
674
-
675
-		if(!is_array($portSettings)) {
676
-			throw new \Exception(print_r($portSettings, true));
677
-		}
678
-
679
-		//proceed from the best configuration and return on first success
680
-		foreach($portSettings as $setting) {
681
-			$p = $setting['port'];
682
-			$t = $setting['tls'];
683
-			\OCP\Util::writeLog('user_ldap', 'Wiz: trying port '. $p . ', TLS '. $t, ILogger::DEBUG);
684
-			//connectAndBind may throw Exception, it needs to be catched by the
685
-			//callee of this method
686
-
687
-			try {
688
-				$settingsFound = $this->connectAndBind($p, $t);
689
-			} catch (\Exception $e) {
690
-				// any reply other than -1 (= cannot connect) is already okay,
691
-				// because then we found the server
692
-				// unavailable startTLS returns -11
693
-				if($e->getCode() > 0) {
694
-					$settingsFound = true;
695
-				} else {
696
-					throw $e;
697
-				}
698
-			}
699
-
700
-			if ($settingsFound === true) {
701
-				$config = array(
702
-					'ldapPort' => $p,
703
-					'ldapTLS' => (int)$t
704
-				);
705
-				$this->configuration->setConfiguration($config);
706
-				\OCP\Util::writeLog('user_ldap', 'Wiz: detected Port ' . $p, ILogger::DEBUG);
707
-				$this->result->addChange('ldap_port', $p);
708
-				return $this->result;
709
-			}
710
-		}
711
-
712
-		//custom port, undetected (we do not brute force)
713
-		return false;
714
-	}
715
-
716
-	/**
717
-	 * tries to determine a base dn from User DN or LDAP Host
718
-	 * @return WizardResult|false WizardResult on success, false otherwise
719
-	 */
720
-	public function guessBaseDN() {
721
-		if(!$this->checkRequirements(array('ldapHost',
722
-										   'ldapPort',
723
-										   ))) {
724
-			return false;
725
-		}
726
-
727
-		//check whether a DN is given in the agent name (99.9% of all cases)
728
-		$base = null;
729
-		$i = stripos($this->configuration->ldapAgentName, 'dc=');
730
-		if($i !== false) {
731
-			$base = substr($this->configuration->ldapAgentName, $i);
732
-			if($this->testBaseDN($base)) {
733
-				$this->applyFind('ldap_base', $base);
734
-				return $this->result;
735
-			}
736
-		}
737
-
738
-		//this did not help :(
739
-		//Let's see whether we can parse the Host URL and convert the domain to
740
-		//a base DN
741
-		$helper = new Helper(\OC::$server->getConfig());
742
-		$domain = $helper->getDomainFromURL($this->configuration->ldapHost);
743
-		if(!$domain) {
744
-			return false;
745
-		}
746
-
747
-		$dparts = explode('.', $domain);
748
-		while(count($dparts) > 0) {
749
-			$base2 = 'dc=' . implode(',dc=', $dparts);
750
-			if ($base !== $base2 && $this->testBaseDN($base2)) {
751
-				$this->applyFind('ldap_base', $base2);
752
-				return $this->result;
753
-			}
754
-			array_shift($dparts);
755
-		}
756
-
757
-		return false;
758
-	}
759
-
760
-	/**
761
-	 * sets the found value for the configuration key in the WizardResult
762
-	 * as well as in the Configuration instance
763
-	 * @param string $key the configuration key
764
-	 * @param string $value the (detected) value
765
-	 *
766
-	 */
767
-	private function applyFind($key, $value) {
768
-		$this->result->addChange($key, $value);
769
-		$this->configuration->setConfiguration(array($key => $value));
770
-	}
771
-
772
-	/**
773
-	 * Checks, whether a port was entered in the Host configuration
774
-	 * field. In this case the port will be stripped off, but also stored as
775
-	 * setting.
776
-	 */
777
-	private function checkHost() {
778
-		$host = $this->configuration->ldapHost;
779
-		$hostInfo = parse_url($host);
780
-
781
-		//removes Port from Host
782
-		if(is_array($hostInfo) && isset($hostInfo['port'])) {
783
-			$port = $hostInfo['port'];
784
-			$host = str_replace(':'.$port, '', $host);
785
-			$this->applyFind('ldap_host', $host);
786
-			$this->applyFind('ldap_port', $port);
787
-		}
788
-	}
789
-
790
-	/**
791
-	 * tries to detect the group member association attribute which is
792
-	 * one of 'uniqueMember', 'memberUid', 'member', 'gidNumber'
793
-	 * @return string|false, string with the attribute name, false on error
794
-	 * @throws \Exception
795
-	 */
796
-	private function detectGroupMemberAssoc() {
797
-		$possibleAttrs = array('uniqueMember', 'memberUid', 'member', 'gidNumber');
798
-		$filter = $this->configuration->ldapGroupFilter;
799
-		if(empty($filter)) {
800
-			return false;
801
-		}
802
-		$cr = $this->getConnection();
803
-		if(!$cr) {
804
-			throw new \Exception('Could not connect to LDAP');
805
-		}
806
-		$base = $this->configuration->ldapBase[0];
807
-		$rr = $this->ldap->search($cr, $base, $filter, $possibleAttrs, 0, 1000);
808
-		if(!$this->ldap->isResource($rr)) {
809
-			return false;
810
-		}
811
-		$er = $this->ldap->firstEntry($cr, $rr);
812
-		while(is_resource($er)) {
813
-			$this->ldap->getDN($cr, $er);
814
-			$attrs = $this->ldap->getAttributes($cr, $er);
815
-			$result = array();
816
-			$possibleAttrsCount = count($possibleAttrs);
817
-			for($i = 0; $i < $possibleAttrsCount; $i++) {
818
-				if(isset($attrs[$possibleAttrs[$i]])) {
819
-					$result[$possibleAttrs[$i]] = $attrs[$possibleAttrs[$i]]['count'];
820
-				}
821
-			}
822
-			if(!empty($result)) {
823
-				natsort($result);
824
-				return key($result);
825
-			}
826
-
827
-			$er = $this->ldap->nextEntry($cr, $er);
828
-		}
829
-
830
-		return false;
831
-	}
832
-
833
-	/**
834
-	 * Checks whether for a given BaseDN results will be returned
835
-	 * @param string $base the BaseDN to test
836
-	 * @return bool true on success, false otherwise
837
-	 * @throws \Exception
838
-	 */
839
-	private function testBaseDN($base) {
840
-		$cr = $this->getConnection();
841
-		if(!$cr) {
842
-			throw new \Exception('Could not connect to LDAP');
843
-		}
844
-
845
-		//base is there, let's validate it. If we search for anything, we should
846
-		//get a result set > 0 on a proper base
847
-		$rr = $this->ldap->search($cr, $base, 'objectClass=*', array('dn'), 0, 1);
848
-		if(!$this->ldap->isResource($rr)) {
849
-			$errorNo  = $this->ldap->errno($cr);
850
-			$errorMsg = $this->ldap->error($cr);
851
-			\OCP\Util::writeLog('user_ldap', 'Wiz: Could not search base '.$base.
852
-							' Error '.$errorNo.': '.$errorMsg, ILogger::INFO);
853
-			return false;
854
-		}
855
-		$entries = $this->ldap->countEntries($cr, $rr);
856
-		return ($entries !== false) && ($entries > 0);
857
-	}
858
-
859
-	/**
860
-	 * Checks whether the server supports memberOf in LDAP Filter.
861
-	 * Note: at least in OpenLDAP, availability of memberOf is dependent on
862
-	 * a configured objectClass. I.e. not necessarily for all available groups
863
-	 * memberOf does work.
864
-	 *
865
-	 * @return bool true if it does, false otherwise
866
-	 * @throws \Exception
867
-	 */
868
-	private function testMemberOf() {
869
-		$cr = $this->getConnection();
870
-		if(!$cr) {
871
-			throw new \Exception('Could not connect to LDAP');
872
-		}
873
-		$result = $this->access->countUsers('memberOf=*', array('memberOf'), 1);
874
-		if(is_int($result) &&  $result > 0) {
875
-			return true;
876
-		}
877
-		return false;
878
-	}
879
-
880
-	/**
881
-	 * creates an LDAP Filter from given configuration
882
-	 * @param integer $filterType int, for which use case the filter shall be created
883
-	 * can be any of self::LFILTER_USER_LIST, self::LFILTER_LOGIN or
884
-	 * self::LFILTER_GROUP_LIST
885
-	 * @return string|false string with the filter on success, false otherwise
886
-	 * @throws \Exception
887
-	 */
888
-	private function composeLdapFilter($filterType) {
889
-		$filter = '';
890
-		$parts = 0;
891
-		switch ($filterType) {
892
-			case self::LFILTER_USER_LIST:
893
-				$objcs = $this->configuration->ldapUserFilterObjectclass;
894
-				//glue objectclasses
895
-				if(is_array($objcs) && count($objcs) > 0) {
896
-					$filter .= '(|';
897
-					foreach($objcs as $objc) {
898
-						$filter .= '(objectclass=' . $objc . ')';
899
-					}
900
-					$filter .= ')';
901
-					$parts++;
902
-				}
903
-				//glue group memberships
904
-				if($this->configuration->hasMemberOfFilterSupport) {
905
-					$cns = $this->configuration->ldapUserFilterGroups;
906
-					if(is_array($cns) && count($cns) > 0) {
907
-						$filter .= '(|';
908
-						$cr = $this->getConnection();
909
-						if(!$cr) {
910
-							throw new \Exception('Could not connect to LDAP');
911
-						}
912
-						$base = $this->configuration->ldapBase[0];
913
-						foreach($cns as $cn) {
914
-							$rr = $this->ldap->search($cr, $base, 'cn=' . $cn, array('dn', 'primaryGroupToken'));
915
-							if(!$this->ldap->isResource($rr)) {
916
-								continue;
917
-							}
918
-							$er = $this->ldap->firstEntry($cr, $rr);
919
-							$attrs = $this->ldap->getAttributes($cr, $er);
920
-							$dn = $this->ldap->getDN($cr, $er);
921
-							if ($dn === false || $dn === '') {
922
-								continue;
923
-							}
924
-							$filterPart = '(memberof=' . $dn . ')';
925
-							if(isset($attrs['primaryGroupToken'])) {
926
-								$pgt = $attrs['primaryGroupToken'][0];
927
-								$primaryFilterPart = '(primaryGroupID=' . $pgt .')';
928
-								$filterPart = '(|' . $filterPart . $primaryFilterPart . ')';
929
-							}
930
-							$filter .= $filterPart;
931
-						}
932
-						$filter .= ')';
933
-					}
934
-					$parts++;
935
-				}
936
-				//wrap parts in AND condition
937
-				if($parts > 1) {
938
-					$filter = '(&' . $filter . ')';
939
-				}
940
-				if ($filter === '') {
941
-					$filter = '(objectclass=*)';
942
-				}
943
-				break;
944
-
945
-			case self::LFILTER_GROUP_LIST:
946
-				$objcs = $this->configuration->ldapGroupFilterObjectclass;
947
-				//glue objectclasses
948
-				if(is_array($objcs) && count($objcs) > 0) {
949
-					$filter .= '(|';
950
-					foreach($objcs as $objc) {
951
-						$filter .= '(objectclass=' . $objc . ')';
952
-					}
953
-					$filter .= ')';
954
-					$parts++;
955
-				}
956
-				//glue group memberships
957
-				$cns = $this->configuration->ldapGroupFilterGroups;
958
-				if(is_array($cns) && count($cns) > 0) {
959
-					$filter .= '(|';
960
-					foreach($cns as $cn) {
961
-						$filter .= '(cn=' . $cn . ')';
962
-					}
963
-					$filter .= ')';
964
-				}
965
-				$parts++;
966
-				//wrap parts in AND condition
967
-				if($parts > 1) {
968
-					$filter = '(&' . $filter . ')';
969
-				}
970
-				break;
971
-
972
-			case self::LFILTER_LOGIN:
973
-				$ulf = $this->configuration->ldapUserFilter;
974
-				$loginpart = '=%uid';
975
-				$filterUsername = '';
976
-				$userAttributes = $this->getUserAttributes();
977
-				$userAttributes = array_change_key_case(array_flip($userAttributes));
978
-				$parts = 0;
979
-
980
-				if($this->configuration->ldapLoginFilterUsername === '1') {
981
-					$attr = '';
982
-					if(isset($userAttributes['uid'])) {
983
-						$attr = 'uid';
984
-					} else if(isset($userAttributes['samaccountname'])) {
985
-						$attr = 'samaccountname';
986
-					} else if(isset($userAttributes['cn'])) {
987
-						//fallback
988
-						$attr = 'cn';
989
-					}
990
-					if ($attr !== '') {
991
-						$filterUsername = '(' . $attr . $loginpart . ')';
992
-						$parts++;
993
-					}
994
-				}
995
-
996
-				$filterEmail = '';
997
-				if($this->configuration->ldapLoginFilterEmail === '1') {
998
-					$filterEmail = '(|(mailPrimaryAddress=%uid)(mail=%uid))';
999
-					$parts++;
1000
-				}
1001
-
1002
-				$filterAttributes = '';
1003
-				$attrsToFilter = $this->configuration->ldapLoginFilterAttributes;
1004
-				if(is_array($attrsToFilter) && count($attrsToFilter) > 0) {
1005
-					$filterAttributes = '(|';
1006
-					foreach($attrsToFilter as $attribute) {
1007
-						$filterAttributes .= '(' . $attribute . $loginpart . ')';
1008
-					}
1009
-					$filterAttributes .= ')';
1010
-					$parts++;
1011
-				}
1012
-
1013
-				$filterLogin = '';
1014
-				if($parts > 1) {
1015
-					$filterLogin = '(|';
1016
-				}
1017
-				$filterLogin .= $filterUsername;
1018
-				$filterLogin .= $filterEmail;
1019
-				$filterLogin .= $filterAttributes;
1020
-				if($parts > 1) {
1021
-					$filterLogin .= ')';
1022
-				}
1023
-
1024
-				$filter = '(&'.$ulf.$filterLogin.')';
1025
-				break;
1026
-		}
1027
-
1028
-		\OCP\Util::writeLog('user_ldap', 'Wiz: Final filter '.$filter, ILogger::DEBUG);
1029
-
1030
-		return $filter;
1031
-	}
1032
-
1033
-	/**
1034
-	 * Connects and Binds to an LDAP Server
1035
-	 *
1036
-	 * @param int $port the port to connect with
1037
-	 * @param bool $tls whether startTLS is to be used
1038
-	 * @return bool
1039
-	 * @throws \Exception
1040
-	 */
1041
-	private function connectAndBind($port, $tls) {
1042
-		//connect, does not really trigger any server communication
1043
-		$host = $this->configuration->ldapHost;
1044
-		$hostInfo = parse_url($host);
1045
-		if(!$hostInfo) {
1046
-			throw new \Exception(self::$l->t('Invalid Host'));
1047
-		}
1048
-		\OCP\Util::writeLog('user_ldap', 'Wiz: Attempting to connect ', ILogger::DEBUG);
1049
-		$cr = $this->ldap->connect($host, $port);
1050
-		if(!is_resource($cr)) {
1051
-			throw new \Exception(self::$l->t('Invalid Host'));
1052
-		}
1053
-
1054
-		//set LDAP options
1055
-		$this->ldap->setOption($cr, LDAP_OPT_PROTOCOL_VERSION, 3);
1056
-		$this->ldap->setOption($cr, LDAP_OPT_REFERRALS, 0);
1057
-		$this->ldap->setOption($cr, LDAP_OPT_NETWORK_TIMEOUT, self::LDAP_NW_TIMEOUT);
1058
-
1059
-		try {
1060
-			if($tls) {
1061
-				$isTlsWorking = @$this->ldap->startTls($cr);
1062
-				if(!$isTlsWorking) {
1063
-					return false;
1064
-				}
1065
-			}
1066
-
1067
-			\OCP\Util::writeLog('user_ldap', 'Wiz: Attemping to Bind ', ILogger::DEBUG);
1068
-			//interesting part: do the bind!
1069
-			$login = $this->ldap->bind($cr,
1070
-				$this->configuration->ldapAgentName,
1071
-				$this->configuration->ldapAgentPassword
1072
-			);
1073
-			$errNo = $this->ldap->errno($cr);
1074
-			$error = ldap_error($cr);
1075
-			$this->ldap->unbind($cr);
1076
-		} catch(ServerNotAvailableException $e) {
1077
-			return false;
1078
-		}
1079
-
1080
-		if($login === true) {
1081
-			$this->ldap->unbind($cr);
1082
-			\OCP\Util::writeLog('user_ldap', 'Wiz: Bind successful to Port '. $port . ' TLS ' . (int)$tls, ILogger::DEBUG);
1083
-			return true;
1084
-		}
1085
-
1086
-		if($errNo === -1) {
1087
-			//host, port or TLS wrong
1088
-			return false;
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 = (int)$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
-	}
45
+    /** @var \OCP\IL10N */
46
+    static protected $l;
47
+    protected $access;
48
+    protected $cr;
49
+    protected $configuration;
50
+    protected $result;
51
+    protected $resultCache = array();
52
+
53
+    const LRESULT_PROCESSED_OK = 2;
54
+    const LRESULT_PROCESSED_INVALID = 3;
55
+    const LRESULT_PROCESSED_SKIP = 4;
56
+
57
+    const LFILTER_LOGIN      = 2;
58
+    const LFILTER_USER_LIST  = 3;
59
+    const LFILTER_GROUP_LIST = 4;
60
+
61
+    const LFILTER_MODE_ASSISTED = 2;
62
+    const LFILTER_MODE_RAW = 1;
63
+
64
+    const LDAP_NW_TIMEOUT = 4;
65
+
66
+    /**
67
+     * Constructor
68
+     * @param Configuration $configuration an instance of Configuration
69
+     * @param ILDAPWrapper $ldap an instance of ILDAPWrapper
70
+     * @param Access $access
71
+     */
72
+    public function __construct(Configuration $configuration, ILDAPWrapper $ldap, Access $access) {
73
+        parent::__construct($ldap);
74
+        $this->configuration = $configuration;
75
+        if(is_null(Wizard::$l)) {
76
+            Wizard::$l = \OC::$server->getL10N('user_ldap');
77
+        }
78
+        $this->access = $access;
79
+        $this->result = new WizardResult();
80
+    }
81
+
82
+    public function  __destruct() {
83
+        if($this->result->hasChanges()) {
84
+            $this->configuration->saveConfiguration();
85
+        }
86
+    }
87
+
88
+    /**
89
+     * counts entries in the LDAP directory
90
+     *
91
+     * @param string $filter the LDAP search filter
92
+     * @param string $type a string being either 'users' or 'groups';
93
+     * @return int
94
+     * @throws \Exception
95
+     */
96
+    public function countEntries(string $filter, string $type): int {
97
+        $reqs = ['ldapHost', 'ldapPort', 'ldapBase'];
98
+        if($type === 'users') {
99
+            $reqs[] = 'ldapUserFilter';
100
+        }
101
+        if(!$this->checkRequirements($reqs)) {
102
+            throw new \Exception('Requirements not met', 400);
103
+        }
104
+
105
+        $attr = ['dn']; // default
106
+        $limit = 1001;
107
+        if($type === 'groups') {
108
+            $result =  $this->access->countGroups($filter, $attr, $limit);
109
+        } else if($type === 'users') {
110
+            $result = $this->access->countUsers($filter, $attr, $limit);
111
+        } else if ($type === 'objects') {
112
+            $result = $this->access->countObjects($limit);
113
+        } else {
114
+            throw new \Exception('Internal error: Invalid object type', 500);
115
+        }
116
+
117
+        return (int)$result;
118
+    }
119
+
120
+    /**
121
+     * formats the return value of a count operation to the string to be
122
+     * inserted.
123
+     *
124
+     * @param int $count
125
+     * @return string
126
+     */
127
+    private function formatCountResult(int $count): string {
128
+        if($count > 1000) {
129
+            return '> 1000';
130
+        }
131
+        return (string)$count;
132
+    }
133
+
134
+    public function countGroups() {
135
+        $filter = $this->configuration->ldapGroupFilter;
136
+
137
+        if(empty($filter)) {
138
+            $output = self::$l->n('%s group found', '%s groups found', 0, array(0));
139
+            $this->result->addChange('ldap_group_count', $output);
140
+            return $this->result;
141
+        }
142
+
143
+        try {
144
+            $groupsTotal = $this->countEntries($filter, 'groups');
145
+        } catch (\Exception $e) {
146
+            //400 can be ignored, 500 is forwarded
147
+            if($e->getCode() === 500) {
148
+                throw $e;
149
+            }
150
+            return false;
151
+        }
152
+        $output = self::$l->n(
153
+            '%s group found',
154
+            '%s groups found',
155
+            $groupsTotal,
156
+            [$this->formatCountResult($groupsTotal)]
157
+        );
158
+        $this->result->addChange('ldap_group_count', $output);
159
+        return $this->result;
160
+    }
161
+
162
+    /**
163
+     * @return WizardResult
164
+     * @throws \Exception
165
+     */
166
+    public function countUsers() {
167
+        $filter = $this->access->getFilterForUserCount();
168
+
169
+        $usersTotal = $this->countEntries($filter, 'users');
170
+        $output = self::$l->n(
171
+            '%s user found',
172
+            '%s users found',
173
+            $usersTotal,
174
+            [$this->formatCountResult($usersTotal)]
175
+        );
176
+        $this->result->addChange('ldap_user_count', $output);
177
+        return $this->result;
178
+    }
179
+
180
+    /**
181
+     * counts any objects in the currently set base dn
182
+     *
183
+     * @return WizardResult
184
+     * @throws \Exception
185
+     */
186
+    public function countInBaseDN() {
187
+        // we don't need to provide a filter in this case
188
+        $total = $this->countEntries('', 'objects');
189
+        if($total === false) {
190
+            throw new \Exception('invalid results received');
191
+        }
192
+        $this->result->addChange('ldap_test_base', $total);
193
+        return $this->result;
194
+    }
195
+
196
+    /**
197
+     * counts users with a specified attribute
198
+     * @param string $attr
199
+     * @param bool $existsCheck
200
+     * @return int|bool
201
+     */
202
+    public function countUsersWithAttribute($attr, $existsCheck = false) {
203
+        if(!$this->checkRequirements(array('ldapHost',
204
+                                            'ldapPort',
205
+                                            'ldapBase',
206
+                                            'ldapUserFilter',
207
+                                            ))) {
208
+            return  false;
209
+        }
210
+
211
+        $filter = $this->access->combineFilterWithAnd(array(
212
+            $this->configuration->ldapUserFilter,
213
+            $attr . '=*'
214
+        ));
215
+
216
+        $limit = ($existsCheck === false) ? null : 1;
217
+
218
+        return $this->access->countUsers($filter, array('dn'), $limit);
219
+    }
220
+
221
+    /**
222
+     * detects the display name attribute. If a setting is already present that
223
+     * returns at least one hit, the detection will be canceled.
224
+     * @return WizardResult|bool
225
+     * @throws \Exception
226
+     */
227
+    public function detectUserDisplayNameAttribute() {
228
+        if(!$this->checkRequirements(array('ldapHost',
229
+                                        'ldapPort',
230
+                                        'ldapBase',
231
+                                        'ldapUserFilter',
232
+                                        ))) {
233
+            return  false;
234
+        }
235
+
236
+        $attr = $this->configuration->ldapUserDisplayName;
237
+        if ($attr !== '' && $attr !== 'displayName') {
238
+            // most likely not the default value with upper case N,
239
+            // verify it still produces a result
240
+            $count = (int)$this->countUsersWithAttribute($attr, true);
241
+            if($count > 0) {
242
+                //no change, but we sent it back to make sure the user interface
243
+                //is still correct, even if the ajax call was cancelled meanwhile
244
+                $this->result->addChange('ldap_display_name', $attr);
245
+                return $this->result;
246
+            }
247
+        }
248
+
249
+        // first attribute that has at least one result wins
250
+        $displayNameAttrs = array('displayname', 'cn');
251
+        foreach ($displayNameAttrs as $attr) {
252
+            $count = (int)$this->countUsersWithAttribute($attr, true);
253
+
254
+            if($count > 0) {
255
+                $this->applyFind('ldap_display_name', $attr);
256
+                return $this->result;
257
+            }
258
+        }
259
+
260
+        throw new \Exception(self::$l->t('Could not detect user display name attribute. Please specify it yourself in advanced LDAP settings.'));
261
+    }
262
+
263
+    /**
264
+     * detects the most often used email attribute for users applying to the
265
+     * user list filter. If a setting is already present that returns at least
266
+     * one hit, the detection will be canceled.
267
+     * @return WizardResult|bool
268
+     */
269
+    public function detectEmailAttribute() {
270
+        if(!$this->checkRequirements(array('ldapHost',
271
+                                            'ldapPort',
272
+                                            'ldapBase',
273
+                                            'ldapUserFilter',
274
+                                            ))) {
275
+            return  false;
276
+        }
277
+
278
+        $attr = $this->configuration->ldapEmailAttribute;
279
+        if ($attr !== '') {
280
+            $count = (int)$this->countUsersWithAttribute($attr, true);
281
+            if($count > 0) {
282
+                return false;
283
+            }
284
+            $writeLog = true;
285
+        } else {
286
+            $writeLog = false;
287
+        }
288
+
289
+        $emailAttributes = array('mail', 'mailPrimaryAddress');
290
+        $winner = '';
291
+        $maxUsers = 0;
292
+        foreach($emailAttributes as $attr) {
293
+            $count = $this->countUsersWithAttribute($attr);
294
+            if($count > $maxUsers) {
295
+                $maxUsers = $count;
296
+                $winner = $attr;
297
+            }
298
+        }
299
+
300
+        if($winner !== '') {
301
+            $this->applyFind('ldap_email_attr', $winner);
302
+            if($writeLog) {
303
+                \OCP\Util::writeLog('user_ldap', 'The mail attribute has ' .
304
+                    'automatically been reset, because the original value ' .
305
+                    'did not return any results.', ILogger::INFO);
306
+            }
307
+        }
308
+
309
+        return $this->result;
310
+    }
311
+
312
+    /**
313
+     * @return WizardResult
314
+     * @throws \Exception
315
+     */
316
+    public function determineAttributes() {
317
+        if(!$this->checkRequirements(array('ldapHost',
318
+                                            'ldapPort',
319
+                                            'ldapBase',
320
+                                            'ldapUserFilter',
321
+                                            ))) {
322
+            return  false;
323
+        }
324
+
325
+        $attributes = $this->getUserAttributes();
326
+
327
+        natcasesort($attributes);
328
+        $attributes = array_values($attributes);
329
+
330
+        $this->result->addOptions('ldap_loginfilter_attributes', $attributes);
331
+
332
+        $selected = $this->configuration->ldapLoginFilterAttributes;
333
+        if(is_array($selected) && !empty($selected)) {
334
+            $this->result->addChange('ldap_loginfilter_attributes', $selected);
335
+        }
336
+
337
+        return $this->result;
338
+    }
339
+
340
+    /**
341
+     * detects the available LDAP attributes
342
+     * @return array|false The instance's WizardResult instance
343
+     * @throws \Exception
344
+     */
345
+    private function getUserAttributes() {
346
+        if(!$this->checkRequirements(array('ldapHost',
347
+                                            'ldapPort',
348
+                                            'ldapBase',
349
+                                            'ldapUserFilter',
350
+                                            ))) {
351
+            return  false;
352
+        }
353
+        $cr = $this->getConnection();
354
+        if(!$cr) {
355
+            throw new \Exception('Could not connect to LDAP');
356
+        }
357
+
358
+        $base = $this->configuration->ldapBase[0];
359
+        $filter = $this->configuration->ldapUserFilter;
360
+        $rr = $this->ldap->search($cr, $base, $filter, array(), 1, 1);
361
+        if(!$this->ldap->isResource($rr)) {
362
+            return false;
363
+        }
364
+        $er = $this->ldap->firstEntry($cr, $rr);
365
+        $attributes = $this->ldap->getAttributes($cr, $er);
366
+        $pureAttributes = array();
367
+        for($i = 0; $i < $attributes['count']; $i++) {
368
+            $pureAttributes[] = $attributes[$i];
369
+        }
370
+
371
+        return $pureAttributes;
372
+    }
373
+
374
+    /**
375
+     * detects the available LDAP groups
376
+     * @return WizardResult|false the instance's WizardResult instance
377
+     */
378
+    public function determineGroupsForGroups() {
379
+        return $this->determineGroups('ldap_groupfilter_groups',
380
+                                        'ldapGroupFilterGroups',
381
+                                        false);
382
+    }
383
+
384
+    /**
385
+     * detects the available LDAP groups
386
+     * @return WizardResult|false the instance's WizardResult instance
387
+     */
388
+    public function determineGroupsForUsers() {
389
+        return $this->determineGroups('ldap_userfilter_groups',
390
+                                        'ldapUserFilterGroups');
391
+    }
392
+
393
+    /**
394
+     * detects the available LDAP groups
395
+     * @param string $dbKey
396
+     * @param string $confKey
397
+     * @param bool $testMemberOf
398
+     * @return WizardResult|false the instance's WizardResult instance
399
+     * @throws \Exception
400
+     */
401
+    private function determineGroups($dbKey, $confKey, $testMemberOf = true) {
402
+        if(!$this->checkRequirements(array('ldapHost',
403
+                                            'ldapPort',
404
+                                            'ldapBase',
405
+                                            ))) {
406
+            return  false;
407
+        }
408
+        $cr = $this->getConnection();
409
+        if(!$cr) {
410
+            throw new \Exception('Could not connect to LDAP');
411
+        }
412
+
413
+        $this->fetchGroups($dbKey, $confKey);
414
+
415
+        if($testMemberOf) {
416
+            $this->configuration->hasMemberOfFilterSupport = $this->testMemberOf();
417
+            $this->result->markChange();
418
+            if(!$this->configuration->hasMemberOfFilterSupport) {
419
+                throw new \Exception('memberOf is not supported by the server');
420
+            }
421
+        }
422
+
423
+        return $this->result;
424
+    }
425
+
426
+    /**
427
+     * fetches all groups from LDAP and adds them to the result object
428
+     *
429
+     * @param string $dbKey
430
+     * @param string $confKey
431
+     * @return array $groupEntries
432
+     * @throws \Exception
433
+     */
434
+    public function fetchGroups($dbKey, $confKey) {
435
+        $obclasses = array('posixGroup', 'group', 'zimbraDistributionList', 'groupOfNames', 'groupOfUniqueNames');
436
+
437
+        $filterParts = array();
438
+        foreach($obclasses as $obclass) {
439
+            $filterParts[] = 'objectclass='.$obclass;
440
+        }
441
+        //we filter for everything
442
+        //- that looks like a group and
443
+        //- has the group display name set
444
+        $filter = $this->access->combineFilterWithOr($filterParts);
445
+        $filter = $this->access->combineFilterWithAnd(array($filter, 'cn=*'));
446
+
447
+        $groupNames = array();
448
+        $groupEntries = array();
449
+        $limit = 400;
450
+        $offset = 0;
451
+        do {
452
+            // we need to request dn additionally here, otherwise memberOf
453
+            // detection will fail later
454
+            $result = $this->access->searchGroups($filter, array('cn', 'dn'), $limit, $offset);
455
+            foreach($result as $item) {
456
+                if(!isset($item['cn']) && !is_array($item['cn']) && !isset($item['cn'][0])) {
457
+                    // just in case - no issue known
458
+                    continue;
459
+                }
460
+                $groupNames[] = $item['cn'][0];
461
+                $groupEntries[] = $item;
462
+            }
463
+            $offset += $limit;
464
+        } while ($this->access->hasMoreResults());
465
+
466
+        if(count($groupNames) > 0) {
467
+            natsort($groupNames);
468
+            $this->result->addOptions($dbKey, array_values($groupNames));
469
+        } else {
470
+            throw new \Exception(self::$l->t('Could not find the desired feature'));
471
+        }
472
+
473
+        $setFeatures = $this->configuration->$confKey;
474
+        if(is_array($setFeatures) && !empty($setFeatures)) {
475
+            //something is already configured? pre-select it.
476
+            $this->result->addChange($dbKey, $setFeatures);
477
+        }
478
+        return $groupEntries;
479
+    }
480
+
481
+    public function determineGroupMemberAssoc() {
482
+        if(!$this->checkRequirements(array('ldapHost',
483
+                                            'ldapPort',
484
+                                            'ldapGroupFilter',
485
+                                            ))) {
486
+            return  false;
487
+        }
488
+        $attribute = $this->detectGroupMemberAssoc();
489
+        if($attribute === false) {
490
+            return false;
491
+        }
492
+        $this->configuration->setConfiguration(array('ldapGroupMemberAssocAttr' => $attribute));
493
+        $this->result->addChange('ldap_group_member_assoc_attribute', $attribute);
494
+
495
+        return $this->result;
496
+    }
497
+
498
+    /**
499
+     * Detects the available object classes
500
+     * @return WizardResult|false the instance's WizardResult instance
501
+     * @throws \Exception
502
+     */
503
+    public function determineGroupObjectClasses() {
504
+        if(!$this->checkRequirements(array('ldapHost',
505
+                                            'ldapPort',
506
+                                            'ldapBase',
507
+                                            ))) {
508
+            return  false;
509
+        }
510
+        $cr = $this->getConnection();
511
+        if(!$cr) {
512
+            throw new \Exception('Could not connect to LDAP');
513
+        }
514
+
515
+        $obclasses = array('groupOfNames', 'groupOfUniqueNames', 'group', 'posixGroup', '*');
516
+        $this->determineFeature($obclasses,
517
+                                'objectclass',
518
+                                'ldap_groupfilter_objectclass',
519
+                                'ldapGroupFilterObjectclass',
520
+                                false);
521
+
522
+        return $this->result;
523
+    }
524
+
525
+    /**
526
+     * detects the available object classes
527
+     * @return WizardResult
528
+     * @throws \Exception
529
+     */
530
+    public function determineUserObjectClasses() {
531
+        if(!$this->checkRequirements(array('ldapHost',
532
+                                            'ldapPort',
533
+                                            'ldapBase',
534
+                                            ))) {
535
+            return  false;
536
+        }
537
+        $cr = $this->getConnection();
538
+        if(!$cr) {
539
+            throw new \Exception('Could not connect to LDAP');
540
+        }
541
+
542
+        $obclasses = array('inetOrgPerson', 'person', 'organizationalPerson',
543
+                            'user', 'posixAccount', '*');
544
+        $filter = $this->configuration->ldapUserFilter;
545
+        //if filter is empty, it is probably the first time the wizard is called
546
+        //then, apply suggestions.
547
+        $this->determineFeature($obclasses,
548
+                                'objectclass',
549
+                                'ldap_userfilter_objectclass',
550
+                                'ldapUserFilterObjectclass',
551
+                                empty($filter));
552
+
553
+        return $this->result;
554
+    }
555
+
556
+    /**
557
+     * @return WizardResult|false
558
+     * @throws \Exception
559
+     */
560
+    public function getGroupFilter() {
561
+        if(!$this->checkRequirements(array('ldapHost',
562
+                                            'ldapPort',
563
+                                            'ldapBase',
564
+                                            ))) {
565
+            return false;
566
+        }
567
+        //make sure the use display name is set
568
+        $displayName = $this->configuration->ldapGroupDisplayName;
569
+        if ($displayName === '') {
570
+            $d = $this->configuration->getDefaults();
571
+            $this->applyFind('ldap_group_display_name',
572
+                                $d['ldap_group_display_name']);
573
+        }
574
+        $filter = $this->composeLdapFilter(self::LFILTER_GROUP_LIST);
575
+
576
+        $this->applyFind('ldap_group_filter', $filter);
577
+        return $this->result;
578
+    }
579
+
580
+    /**
581
+     * @return WizardResult|false
582
+     * @throws \Exception
583
+     */
584
+    public function getUserListFilter() {
585
+        if(!$this->checkRequirements(array('ldapHost',
586
+                                            'ldapPort',
587
+                                            'ldapBase',
588
+                                            ))) {
589
+            return false;
590
+        }
591
+        //make sure the use display name is set
592
+        $displayName = $this->configuration->ldapUserDisplayName;
593
+        if ($displayName === '') {
594
+            $d = $this->configuration->getDefaults();
595
+            $this->applyFind('ldap_display_name', $d['ldap_display_name']);
596
+        }
597
+        $filter = $this->composeLdapFilter(self::LFILTER_USER_LIST);
598
+        if(!$filter) {
599
+            throw new \Exception('Cannot create filter');
600
+        }
601
+
602
+        $this->applyFind('ldap_userlist_filter', $filter);
603
+        return $this->result;
604
+    }
605
+
606
+    /**
607
+     * @return bool|WizardResult
608
+     * @throws \Exception
609
+     */
610
+    public function getUserLoginFilter() {
611
+        if(!$this->checkRequirements(array('ldapHost',
612
+                                            'ldapPort',
613
+                                            'ldapBase',
614
+                                            'ldapUserFilter',
615
+                                            ))) {
616
+            return false;
617
+        }
618
+
619
+        $filter = $this->composeLdapFilter(self::LFILTER_LOGIN);
620
+        if(!$filter) {
621
+            throw new \Exception('Cannot create filter');
622
+        }
623
+
624
+        $this->applyFind('ldap_login_filter', $filter);
625
+        return $this->result;
626
+    }
627
+
628
+    /**
629
+     * @return bool|WizardResult
630
+     * @param string $loginName
631
+     * @throws \Exception
632
+     */
633
+    public function testLoginName($loginName) {
634
+        if(!$this->checkRequirements(array('ldapHost',
635
+            'ldapPort',
636
+            'ldapBase',
637
+            'ldapLoginFilter',
638
+        ))) {
639
+            return false;
640
+        }
641
+
642
+        $cr = $this->access->connection->getConnectionResource();
643
+        if(!$this->ldap->isResource($cr)) {
644
+            throw new \Exception('connection error');
645
+        }
646
+
647
+        if(mb_strpos($this->access->connection->ldapLoginFilter, '%uid', 0, 'UTF-8')
648
+            === false) {
649
+            throw new \Exception('missing placeholder');
650
+        }
651
+
652
+        $users = $this->access->countUsersByLoginName($loginName);
653
+        if($this->ldap->errno($cr) !== 0) {
654
+            throw new \Exception($this->ldap->error($cr));
655
+        }
656
+        $filter = str_replace('%uid', $loginName, $this->access->connection->ldapLoginFilter);
657
+        $this->result->addChange('ldap_test_loginname', $users);
658
+        $this->result->addChange('ldap_test_effective_filter', $filter);
659
+        return $this->result;
660
+    }
661
+
662
+    /**
663
+     * Tries to determine the port, requires given Host, User DN and Password
664
+     * @return WizardResult|false WizardResult on success, false otherwise
665
+     * @throws \Exception
666
+     */
667
+    public function guessPortAndTLS() {
668
+        if(!$this->checkRequirements(array('ldapHost',
669
+                                            ))) {
670
+            return false;
671
+        }
672
+        $this->checkHost();
673
+        $portSettings = $this->getPortSettingsToTry();
674
+
675
+        if(!is_array($portSettings)) {
676
+            throw new \Exception(print_r($portSettings, true));
677
+        }
678
+
679
+        //proceed from the best configuration and return on first success
680
+        foreach($portSettings as $setting) {
681
+            $p = $setting['port'];
682
+            $t = $setting['tls'];
683
+            \OCP\Util::writeLog('user_ldap', 'Wiz: trying port '. $p . ', TLS '. $t, ILogger::DEBUG);
684
+            //connectAndBind may throw Exception, it needs to be catched by the
685
+            //callee of this method
686
+
687
+            try {
688
+                $settingsFound = $this->connectAndBind($p, $t);
689
+            } catch (\Exception $e) {
690
+                // any reply other than -1 (= cannot connect) is already okay,
691
+                // because then we found the server
692
+                // unavailable startTLS returns -11
693
+                if($e->getCode() > 0) {
694
+                    $settingsFound = true;
695
+                } else {
696
+                    throw $e;
697
+                }
698
+            }
699
+
700
+            if ($settingsFound === true) {
701
+                $config = array(
702
+                    'ldapPort' => $p,
703
+                    'ldapTLS' => (int)$t
704
+                );
705
+                $this->configuration->setConfiguration($config);
706
+                \OCP\Util::writeLog('user_ldap', 'Wiz: detected Port ' . $p, ILogger::DEBUG);
707
+                $this->result->addChange('ldap_port', $p);
708
+                return $this->result;
709
+            }
710
+        }
711
+
712
+        //custom port, undetected (we do not brute force)
713
+        return false;
714
+    }
715
+
716
+    /**
717
+     * tries to determine a base dn from User DN or LDAP Host
718
+     * @return WizardResult|false WizardResult on success, false otherwise
719
+     */
720
+    public function guessBaseDN() {
721
+        if(!$this->checkRequirements(array('ldapHost',
722
+                                            'ldapPort',
723
+                                            ))) {
724
+            return false;
725
+        }
726
+
727
+        //check whether a DN is given in the agent name (99.9% of all cases)
728
+        $base = null;
729
+        $i = stripos($this->configuration->ldapAgentName, 'dc=');
730
+        if($i !== false) {
731
+            $base = substr($this->configuration->ldapAgentName, $i);
732
+            if($this->testBaseDN($base)) {
733
+                $this->applyFind('ldap_base', $base);
734
+                return $this->result;
735
+            }
736
+        }
737
+
738
+        //this did not help :(
739
+        //Let's see whether we can parse the Host URL and convert the domain to
740
+        //a base DN
741
+        $helper = new Helper(\OC::$server->getConfig());
742
+        $domain = $helper->getDomainFromURL($this->configuration->ldapHost);
743
+        if(!$domain) {
744
+            return false;
745
+        }
746
+
747
+        $dparts = explode('.', $domain);
748
+        while(count($dparts) > 0) {
749
+            $base2 = 'dc=' . implode(',dc=', $dparts);
750
+            if ($base !== $base2 && $this->testBaseDN($base2)) {
751
+                $this->applyFind('ldap_base', $base2);
752
+                return $this->result;
753
+            }
754
+            array_shift($dparts);
755
+        }
756
+
757
+        return false;
758
+    }
759
+
760
+    /**
761
+     * sets the found value for the configuration key in the WizardResult
762
+     * as well as in the Configuration instance
763
+     * @param string $key the configuration key
764
+     * @param string $value the (detected) value
765
+     *
766
+     */
767
+    private function applyFind($key, $value) {
768
+        $this->result->addChange($key, $value);
769
+        $this->configuration->setConfiguration(array($key => $value));
770
+    }
771
+
772
+    /**
773
+     * Checks, whether a port was entered in the Host configuration
774
+     * field. In this case the port will be stripped off, but also stored as
775
+     * setting.
776
+     */
777
+    private function checkHost() {
778
+        $host = $this->configuration->ldapHost;
779
+        $hostInfo = parse_url($host);
780
+
781
+        //removes Port from Host
782
+        if(is_array($hostInfo) && isset($hostInfo['port'])) {
783
+            $port = $hostInfo['port'];
784
+            $host = str_replace(':'.$port, '', $host);
785
+            $this->applyFind('ldap_host', $host);
786
+            $this->applyFind('ldap_port', $port);
787
+        }
788
+    }
789
+
790
+    /**
791
+     * tries to detect the group member association attribute which is
792
+     * one of 'uniqueMember', 'memberUid', 'member', 'gidNumber'
793
+     * @return string|false, string with the attribute name, false on error
794
+     * @throws \Exception
795
+     */
796
+    private function detectGroupMemberAssoc() {
797
+        $possibleAttrs = array('uniqueMember', 'memberUid', 'member', 'gidNumber');
798
+        $filter = $this->configuration->ldapGroupFilter;
799
+        if(empty($filter)) {
800
+            return false;
801
+        }
802
+        $cr = $this->getConnection();
803
+        if(!$cr) {
804
+            throw new \Exception('Could not connect to LDAP');
805
+        }
806
+        $base = $this->configuration->ldapBase[0];
807
+        $rr = $this->ldap->search($cr, $base, $filter, $possibleAttrs, 0, 1000);
808
+        if(!$this->ldap->isResource($rr)) {
809
+            return false;
810
+        }
811
+        $er = $this->ldap->firstEntry($cr, $rr);
812
+        while(is_resource($er)) {
813
+            $this->ldap->getDN($cr, $er);
814
+            $attrs = $this->ldap->getAttributes($cr, $er);
815
+            $result = array();
816
+            $possibleAttrsCount = count($possibleAttrs);
817
+            for($i = 0; $i < $possibleAttrsCount; $i++) {
818
+                if(isset($attrs[$possibleAttrs[$i]])) {
819
+                    $result[$possibleAttrs[$i]] = $attrs[$possibleAttrs[$i]]['count'];
820
+                }
821
+            }
822
+            if(!empty($result)) {
823
+                natsort($result);
824
+                return key($result);
825
+            }
826
+
827
+            $er = $this->ldap->nextEntry($cr, $er);
828
+        }
829
+
830
+        return false;
831
+    }
832
+
833
+    /**
834
+     * Checks whether for a given BaseDN results will be returned
835
+     * @param string $base the BaseDN to test
836
+     * @return bool true on success, false otherwise
837
+     * @throws \Exception
838
+     */
839
+    private function testBaseDN($base) {
840
+        $cr = $this->getConnection();
841
+        if(!$cr) {
842
+            throw new \Exception('Could not connect to LDAP');
843
+        }
844
+
845
+        //base is there, let's validate it. If we search for anything, we should
846
+        //get a result set > 0 on a proper base
847
+        $rr = $this->ldap->search($cr, $base, 'objectClass=*', array('dn'), 0, 1);
848
+        if(!$this->ldap->isResource($rr)) {
849
+            $errorNo  = $this->ldap->errno($cr);
850
+            $errorMsg = $this->ldap->error($cr);
851
+            \OCP\Util::writeLog('user_ldap', 'Wiz: Could not search base '.$base.
852
+                            ' Error '.$errorNo.': '.$errorMsg, ILogger::INFO);
853
+            return false;
854
+        }
855
+        $entries = $this->ldap->countEntries($cr, $rr);
856
+        return ($entries !== false) && ($entries > 0);
857
+    }
858
+
859
+    /**
860
+     * Checks whether the server supports memberOf in LDAP Filter.
861
+     * Note: at least in OpenLDAP, availability of memberOf is dependent on
862
+     * a configured objectClass. I.e. not necessarily for all available groups
863
+     * memberOf does work.
864
+     *
865
+     * @return bool true if it does, false otherwise
866
+     * @throws \Exception
867
+     */
868
+    private function testMemberOf() {
869
+        $cr = $this->getConnection();
870
+        if(!$cr) {
871
+            throw new \Exception('Could not connect to LDAP');
872
+        }
873
+        $result = $this->access->countUsers('memberOf=*', array('memberOf'), 1);
874
+        if(is_int($result) &&  $result > 0) {
875
+            return true;
876
+        }
877
+        return false;
878
+    }
879
+
880
+    /**
881
+     * creates an LDAP Filter from given configuration
882
+     * @param integer $filterType int, for which use case the filter shall be created
883
+     * can be any of self::LFILTER_USER_LIST, self::LFILTER_LOGIN or
884
+     * self::LFILTER_GROUP_LIST
885
+     * @return string|false string with the filter on success, false otherwise
886
+     * @throws \Exception
887
+     */
888
+    private function composeLdapFilter($filterType) {
889
+        $filter = '';
890
+        $parts = 0;
891
+        switch ($filterType) {
892
+            case self::LFILTER_USER_LIST:
893
+                $objcs = $this->configuration->ldapUserFilterObjectclass;
894
+                //glue objectclasses
895
+                if(is_array($objcs) && count($objcs) > 0) {
896
+                    $filter .= '(|';
897
+                    foreach($objcs as $objc) {
898
+                        $filter .= '(objectclass=' . $objc . ')';
899
+                    }
900
+                    $filter .= ')';
901
+                    $parts++;
902
+                }
903
+                //glue group memberships
904
+                if($this->configuration->hasMemberOfFilterSupport) {
905
+                    $cns = $this->configuration->ldapUserFilterGroups;
906
+                    if(is_array($cns) && count($cns) > 0) {
907
+                        $filter .= '(|';
908
+                        $cr = $this->getConnection();
909
+                        if(!$cr) {
910
+                            throw new \Exception('Could not connect to LDAP');
911
+                        }
912
+                        $base = $this->configuration->ldapBase[0];
913
+                        foreach($cns as $cn) {
914
+                            $rr = $this->ldap->search($cr, $base, 'cn=' . $cn, array('dn', 'primaryGroupToken'));
915
+                            if(!$this->ldap->isResource($rr)) {
916
+                                continue;
917
+                            }
918
+                            $er = $this->ldap->firstEntry($cr, $rr);
919
+                            $attrs = $this->ldap->getAttributes($cr, $er);
920
+                            $dn = $this->ldap->getDN($cr, $er);
921
+                            if ($dn === false || $dn === '') {
922
+                                continue;
923
+                            }
924
+                            $filterPart = '(memberof=' . $dn . ')';
925
+                            if(isset($attrs['primaryGroupToken'])) {
926
+                                $pgt = $attrs['primaryGroupToken'][0];
927
+                                $primaryFilterPart = '(primaryGroupID=' . $pgt .')';
928
+                                $filterPart = '(|' . $filterPart . $primaryFilterPart . ')';
929
+                            }
930
+                            $filter .= $filterPart;
931
+                        }
932
+                        $filter .= ')';
933
+                    }
934
+                    $parts++;
935
+                }
936
+                //wrap parts in AND condition
937
+                if($parts > 1) {
938
+                    $filter = '(&' . $filter . ')';
939
+                }
940
+                if ($filter === '') {
941
+                    $filter = '(objectclass=*)';
942
+                }
943
+                break;
944
+
945
+            case self::LFILTER_GROUP_LIST:
946
+                $objcs = $this->configuration->ldapGroupFilterObjectclass;
947
+                //glue objectclasses
948
+                if(is_array($objcs) && count($objcs) > 0) {
949
+                    $filter .= '(|';
950
+                    foreach($objcs as $objc) {
951
+                        $filter .= '(objectclass=' . $objc . ')';
952
+                    }
953
+                    $filter .= ')';
954
+                    $parts++;
955
+                }
956
+                //glue group memberships
957
+                $cns = $this->configuration->ldapGroupFilterGroups;
958
+                if(is_array($cns) && count($cns) > 0) {
959
+                    $filter .= '(|';
960
+                    foreach($cns as $cn) {
961
+                        $filter .= '(cn=' . $cn . ')';
962
+                    }
963
+                    $filter .= ')';
964
+                }
965
+                $parts++;
966
+                //wrap parts in AND condition
967
+                if($parts > 1) {
968
+                    $filter = '(&' . $filter . ')';
969
+                }
970
+                break;
971
+
972
+            case self::LFILTER_LOGIN:
973
+                $ulf = $this->configuration->ldapUserFilter;
974
+                $loginpart = '=%uid';
975
+                $filterUsername = '';
976
+                $userAttributes = $this->getUserAttributes();
977
+                $userAttributes = array_change_key_case(array_flip($userAttributes));
978
+                $parts = 0;
979
+
980
+                if($this->configuration->ldapLoginFilterUsername === '1') {
981
+                    $attr = '';
982
+                    if(isset($userAttributes['uid'])) {
983
+                        $attr = 'uid';
984
+                    } else if(isset($userAttributes['samaccountname'])) {
985
+                        $attr = 'samaccountname';
986
+                    } else if(isset($userAttributes['cn'])) {
987
+                        //fallback
988
+                        $attr = 'cn';
989
+                    }
990
+                    if ($attr !== '') {
991
+                        $filterUsername = '(' . $attr . $loginpart . ')';
992
+                        $parts++;
993
+                    }
994
+                }
995
+
996
+                $filterEmail = '';
997
+                if($this->configuration->ldapLoginFilterEmail === '1') {
998
+                    $filterEmail = '(|(mailPrimaryAddress=%uid)(mail=%uid))';
999
+                    $parts++;
1000
+                }
1001
+
1002
+                $filterAttributes = '';
1003
+                $attrsToFilter = $this->configuration->ldapLoginFilterAttributes;
1004
+                if(is_array($attrsToFilter) && count($attrsToFilter) > 0) {
1005
+                    $filterAttributes = '(|';
1006
+                    foreach($attrsToFilter as $attribute) {
1007
+                        $filterAttributes .= '(' . $attribute . $loginpart . ')';
1008
+                    }
1009
+                    $filterAttributes .= ')';
1010
+                    $parts++;
1011
+                }
1012
+
1013
+                $filterLogin = '';
1014
+                if($parts > 1) {
1015
+                    $filterLogin = '(|';
1016
+                }
1017
+                $filterLogin .= $filterUsername;
1018
+                $filterLogin .= $filterEmail;
1019
+                $filterLogin .= $filterAttributes;
1020
+                if($parts > 1) {
1021
+                    $filterLogin .= ')';
1022
+                }
1023
+
1024
+                $filter = '(&'.$ulf.$filterLogin.')';
1025
+                break;
1026
+        }
1027
+
1028
+        \OCP\Util::writeLog('user_ldap', 'Wiz: Final filter '.$filter, ILogger::DEBUG);
1029
+
1030
+        return $filter;
1031
+    }
1032
+
1033
+    /**
1034
+     * Connects and Binds to an LDAP Server
1035
+     *
1036
+     * @param int $port the port to connect with
1037
+     * @param bool $tls whether startTLS is to be used
1038
+     * @return bool
1039
+     * @throws \Exception
1040
+     */
1041
+    private function connectAndBind($port, $tls) {
1042
+        //connect, does not really trigger any server communication
1043
+        $host = $this->configuration->ldapHost;
1044
+        $hostInfo = parse_url($host);
1045
+        if(!$hostInfo) {
1046
+            throw new \Exception(self::$l->t('Invalid Host'));
1047
+        }
1048
+        \OCP\Util::writeLog('user_ldap', 'Wiz: Attempting to connect ', ILogger::DEBUG);
1049
+        $cr = $this->ldap->connect($host, $port);
1050
+        if(!is_resource($cr)) {
1051
+            throw new \Exception(self::$l->t('Invalid Host'));
1052
+        }
1053
+
1054
+        //set LDAP options
1055
+        $this->ldap->setOption($cr, LDAP_OPT_PROTOCOL_VERSION, 3);
1056
+        $this->ldap->setOption($cr, LDAP_OPT_REFERRALS, 0);
1057
+        $this->ldap->setOption($cr, LDAP_OPT_NETWORK_TIMEOUT, self::LDAP_NW_TIMEOUT);
1058
+
1059
+        try {
1060
+            if($tls) {
1061
+                $isTlsWorking = @$this->ldap->startTls($cr);
1062
+                if(!$isTlsWorking) {
1063
+                    return false;
1064
+                }
1065
+            }
1066
+
1067
+            \OCP\Util::writeLog('user_ldap', 'Wiz: Attemping to Bind ', ILogger::DEBUG);
1068
+            //interesting part: do the bind!
1069
+            $login = $this->ldap->bind($cr,
1070
+                $this->configuration->ldapAgentName,
1071
+                $this->configuration->ldapAgentPassword
1072
+            );
1073
+            $errNo = $this->ldap->errno($cr);
1074
+            $error = ldap_error($cr);
1075
+            $this->ldap->unbind($cr);
1076
+        } catch(ServerNotAvailableException $e) {
1077
+            return false;
1078
+        }
1079
+
1080
+        if($login === true) {
1081
+            $this->ldap->unbind($cr);
1082
+            \OCP\Util::writeLog('user_ldap', 'Wiz: Bind successful to Port '. $port . ' TLS ' . (int)$tls, ILogger::DEBUG);
1083
+            return true;
1084
+        }
1085
+
1086
+        if($errNo === -1) {
1087
+            //host, port or TLS wrong
1088
+            return false;
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 = (int)$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.
Spacing   +156 added lines, -156 removed lines patch added patch discarded remove patch
@@ -72,7 +72,7 @@  discard block
 block discarded – undo
72 72
 	public function __construct(Configuration $configuration, ILDAPWrapper $ldap, Access $access) {
73 73
 		parent::__construct($ldap);
74 74
 		$this->configuration = $configuration;
75
-		if(is_null(Wizard::$l)) {
75
+		if (is_null(Wizard::$l)) {
76 76
 			Wizard::$l = \OC::$server->getL10N('user_ldap');
77 77
 		}
78 78
 		$this->access = $access;
@@ -80,7 +80,7 @@  discard block
 block discarded – undo
80 80
 	}
81 81
 
82 82
 	public function  __destruct() {
83
-		if($this->result->hasChanges()) {
83
+		if ($this->result->hasChanges()) {
84 84
 			$this->configuration->saveConfiguration();
85 85
 		}
86 86
 	}
@@ -95,18 +95,18 @@  discard block
 block discarded – undo
95 95
 	 */
96 96
 	public function countEntries(string $filter, string $type): int {
97 97
 		$reqs = ['ldapHost', 'ldapPort', 'ldapBase'];
98
-		if($type === 'users') {
98
+		if ($type === 'users') {
99 99
 			$reqs[] = 'ldapUserFilter';
100 100
 		}
101
-		if(!$this->checkRequirements($reqs)) {
101
+		if (!$this->checkRequirements($reqs)) {
102 102
 			throw new \Exception('Requirements not met', 400);
103 103
 		}
104 104
 
105 105
 		$attr = ['dn']; // default
106 106
 		$limit = 1001;
107
-		if($type === 'groups') {
108
-			$result =  $this->access->countGroups($filter, $attr, $limit);
109
-		} else if($type === 'users') {
107
+		if ($type === 'groups') {
108
+			$result = $this->access->countGroups($filter, $attr, $limit);
109
+		} else if ($type === 'users') {
110 110
 			$result = $this->access->countUsers($filter, $attr, $limit);
111 111
 		} else if ($type === 'objects') {
112 112
 			$result = $this->access->countObjects($limit);
@@ -114,7 +114,7 @@  discard block
 block discarded – undo
114 114
 			throw new \Exception('Internal error: Invalid object type', 500);
115 115
 		}
116 116
 
117
-		return (int)$result;
117
+		return (int) $result;
118 118
 	}
119 119
 
120 120
 	/**
@@ -125,16 +125,16 @@  discard block
 block discarded – undo
125 125
 	 * @return string
126 126
 	 */
127 127
 	private function formatCountResult(int $count): string {
128
-		if($count > 1000) {
128
+		if ($count > 1000) {
129 129
 			return '> 1000';
130 130
 		}
131
-		return (string)$count;
131
+		return (string) $count;
132 132
 	}
133 133
 
134 134
 	public function countGroups() {
135 135
 		$filter = $this->configuration->ldapGroupFilter;
136 136
 
137
-		if(empty($filter)) {
137
+		if (empty($filter)) {
138 138
 			$output = self::$l->n('%s group found', '%s groups found', 0, array(0));
139 139
 			$this->result->addChange('ldap_group_count', $output);
140 140
 			return $this->result;
@@ -144,7 +144,7 @@  discard block
 block discarded – undo
144 144
 			$groupsTotal = $this->countEntries($filter, 'groups');
145 145
 		} catch (\Exception $e) {
146 146
 			//400 can be ignored, 500 is forwarded
147
-			if($e->getCode() === 500) {
147
+			if ($e->getCode() === 500) {
148 148
 				throw $e;
149 149
 			}
150 150
 			return false;
@@ -186,7 +186,7 @@  discard block
 block discarded – undo
186 186
 	public function countInBaseDN() {
187 187
 		// we don't need to provide a filter in this case
188 188
 		$total = $this->countEntries('', 'objects');
189
-		if($total === false) {
189
+		if ($total === false) {
190 190
 			throw new \Exception('invalid results received');
191 191
 		}
192 192
 		$this->result->addChange('ldap_test_base', $total);
@@ -200,7 +200,7 @@  discard block
 block discarded – undo
200 200
 	 * @return int|bool
201 201
 	 */
202 202
 	public function countUsersWithAttribute($attr, $existsCheck = false) {
203
-		if(!$this->checkRequirements(array('ldapHost',
203
+		if (!$this->checkRequirements(array('ldapHost',
204 204
 										   'ldapPort',
205 205
 										   'ldapBase',
206 206
 										   'ldapUserFilter',
@@ -210,7 +210,7 @@  discard block
 block discarded – undo
210 210
 
211 211
 		$filter = $this->access->combineFilterWithAnd(array(
212 212
 			$this->configuration->ldapUserFilter,
213
-			$attr . '=*'
213
+			$attr.'=*'
214 214
 		));
215 215
 
216 216
 		$limit = ($existsCheck === false) ? null : 1;
@@ -225,7 +225,7 @@  discard block
 block discarded – undo
225 225
 	 * @throws \Exception
226 226
 	 */
227 227
 	public function detectUserDisplayNameAttribute() {
228
-		if(!$this->checkRequirements(array('ldapHost',
228
+		if (!$this->checkRequirements(array('ldapHost',
229 229
 										'ldapPort',
230 230
 										'ldapBase',
231 231
 										'ldapUserFilter',
@@ -237,8 +237,8 @@  discard block
 block discarded – undo
237 237
 		if ($attr !== '' && $attr !== 'displayName') {
238 238
 			// most likely not the default value with upper case N,
239 239
 			// verify it still produces a result
240
-			$count = (int)$this->countUsersWithAttribute($attr, true);
241
-			if($count > 0) {
240
+			$count = (int) $this->countUsersWithAttribute($attr, true);
241
+			if ($count > 0) {
242 242
 				//no change, but we sent it back to make sure the user interface
243 243
 				//is still correct, even if the ajax call was cancelled meanwhile
244 244
 				$this->result->addChange('ldap_display_name', $attr);
@@ -249,9 +249,9 @@  discard block
 block discarded – undo
249 249
 		// first attribute that has at least one result wins
250 250
 		$displayNameAttrs = array('displayname', 'cn');
251 251
 		foreach ($displayNameAttrs as $attr) {
252
-			$count = (int)$this->countUsersWithAttribute($attr, true);
252
+			$count = (int) $this->countUsersWithAttribute($attr, true);
253 253
 
254
-			if($count > 0) {
254
+			if ($count > 0) {
255 255
 				$this->applyFind('ldap_display_name', $attr);
256 256
 				return $this->result;
257 257
 			}
@@ -267,7 +267,7 @@  discard block
 block discarded – undo
267 267
 	 * @return WizardResult|bool
268 268
 	 */
269 269
 	public function detectEmailAttribute() {
270
-		if(!$this->checkRequirements(array('ldapHost',
270
+		if (!$this->checkRequirements(array('ldapHost',
271 271
 										   'ldapPort',
272 272
 										   'ldapBase',
273 273
 										   'ldapUserFilter',
@@ -277,8 +277,8 @@  discard block
 block discarded – undo
277 277
 
278 278
 		$attr = $this->configuration->ldapEmailAttribute;
279 279
 		if ($attr !== '') {
280
-			$count = (int)$this->countUsersWithAttribute($attr, true);
281
-			if($count > 0) {
280
+			$count = (int) $this->countUsersWithAttribute($attr, true);
281
+			if ($count > 0) {
282 282
 				return false;
283 283
 			}
284 284
 			$writeLog = true;
@@ -289,19 +289,19 @@  discard block
 block discarded – undo
289 289
 		$emailAttributes = array('mail', 'mailPrimaryAddress');
290 290
 		$winner = '';
291 291
 		$maxUsers = 0;
292
-		foreach($emailAttributes as $attr) {
292
+		foreach ($emailAttributes as $attr) {
293 293
 			$count = $this->countUsersWithAttribute($attr);
294
-			if($count > $maxUsers) {
294
+			if ($count > $maxUsers) {
295 295
 				$maxUsers = $count;
296 296
 				$winner = $attr;
297 297
 			}
298 298
 		}
299 299
 
300
-		if($winner !== '') {
300
+		if ($winner !== '') {
301 301
 			$this->applyFind('ldap_email_attr', $winner);
302
-			if($writeLog) {
303
-				\OCP\Util::writeLog('user_ldap', 'The mail attribute has ' .
304
-					'automatically been reset, because the original value ' .
302
+			if ($writeLog) {
303
+				\OCP\Util::writeLog('user_ldap', 'The mail attribute has '.
304
+					'automatically been reset, because the original value '.
305 305
 					'did not return any results.', ILogger::INFO);
306 306
 			}
307 307
 		}
@@ -314,7 +314,7 @@  discard block
 block discarded – undo
314 314
 	 * @throws \Exception
315 315
 	 */
316 316
 	public function determineAttributes() {
317
-		if(!$this->checkRequirements(array('ldapHost',
317
+		if (!$this->checkRequirements(array('ldapHost',
318 318
 										   'ldapPort',
319 319
 										   'ldapBase',
320 320
 										   'ldapUserFilter',
@@ -330,7 +330,7 @@  discard block
 block discarded – undo
330 330
 		$this->result->addOptions('ldap_loginfilter_attributes', $attributes);
331 331
 
332 332
 		$selected = $this->configuration->ldapLoginFilterAttributes;
333
-		if(is_array($selected) && !empty($selected)) {
333
+		if (is_array($selected) && !empty($selected)) {
334 334
 			$this->result->addChange('ldap_loginfilter_attributes', $selected);
335 335
 		}
336 336
 
@@ -343,7 +343,7 @@  discard block
 block discarded – undo
343 343
 	 * @throws \Exception
344 344
 	 */
345 345
 	private function getUserAttributes() {
346
-		if(!$this->checkRequirements(array('ldapHost',
346
+		if (!$this->checkRequirements(array('ldapHost',
347 347
 										   'ldapPort',
348 348
 										   'ldapBase',
349 349
 										   'ldapUserFilter',
@@ -351,20 +351,20 @@  discard block
 block discarded – undo
351 351
 			return  false;
352 352
 		}
353 353
 		$cr = $this->getConnection();
354
-		if(!$cr) {
354
+		if (!$cr) {
355 355
 			throw new \Exception('Could not connect to LDAP');
356 356
 		}
357 357
 
358 358
 		$base = $this->configuration->ldapBase[0];
359 359
 		$filter = $this->configuration->ldapUserFilter;
360 360
 		$rr = $this->ldap->search($cr, $base, $filter, array(), 1, 1);
361
-		if(!$this->ldap->isResource($rr)) {
361
+		if (!$this->ldap->isResource($rr)) {
362 362
 			return false;
363 363
 		}
364 364
 		$er = $this->ldap->firstEntry($cr, $rr);
365 365
 		$attributes = $this->ldap->getAttributes($cr, $er);
366 366
 		$pureAttributes = array();
367
-		for($i = 0; $i < $attributes['count']; $i++) {
367
+		for ($i = 0; $i < $attributes['count']; $i++) {
368 368
 			$pureAttributes[] = $attributes[$i];
369 369
 		}
370 370
 
@@ -399,23 +399,23 @@  discard block
 block discarded – undo
399 399
 	 * @throws \Exception
400 400
 	 */
401 401
 	private function determineGroups($dbKey, $confKey, $testMemberOf = true) {
402
-		if(!$this->checkRequirements(array('ldapHost',
402
+		if (!$this->checkRequirements(array('ldapHost',
403 403
 										   'ldapPort',
404 404
 										   'ldapBase',
405 405
 										   ))) {
406 406
 			return  false;
407 407
 		}
408 408
 		$cr = $this->getConnection();
409
-		if(!$cr) {
409
+		if (!$cr) {
410 410
 			throw new \Exception('Could not connect to LDAP');
411 411
 		}
412 412
 
413 413
 		$this->fetchGroups($dbKey, $confKey);
414 414
 
415
-		if($testMemberOf) {
415
+		if ($testMemberOf) {
416 416
 			$this->configuration->hasMemberOfFilterSupport = $this->testMemberOf();
417 417
 			$this->result->markChange();
418
-			if(!$this->configuration->hasMemberOfFilterSupport) {
418
+			if (!$this->configuration->hasMemberOfFilterSupport) {
419 419
 				throw new \Exception('memberOf is not supported by the server');
420 420
 			}
421 421
 		}
@@ -435,7 +435,7 @@  discard block
 block discarded – undo
435 435
 		$obclasses = array('posixGroup', 'group', 'zimbraDistributionList', 'groupOfNames', 'groupOfUniqueNames');
436 436
 
437 437
 		$filterParts = array();
438
-		foreach($obclasses as $obclass) {
438
+		foreach ($obclasses as $obclass) {
439 439
 			$filterParts[] = 'objectclass='.$obclass;
440 440
 		}
441 441
 		//we filter for everything
@@ -452,8 +452,8 @@  discard block
 block discarded – undo
452 452
 			// we need to request dn additionally here, otherwise memberOf
453 453
 			// detection will fail later
454 454
 			$result = $this->access->searchGroups($filter, array('cn', 'dn'), $limit, $offset);
455
-			foreach($result as $item) {
456
-				if(!isset($item['cn']) && !is_array($item['cn']) && !isset($item['cn'][0])) {
455
+			foreach ($result as $item) {
456
+				if (!isset($item['cn']) && !is_array($item['cn']) && !isset($item['cn'][0])) {
457 457
 					// just in case - no issue known
458 458
 					continue;
459 459
 				}
@@ -463,7 +463,7 @@  discard block
 block discarded – undo
463 463
 			$offset += $limit;
464 464
 		} while ($this->access->hasMoreResults());
465 465
 
466
-		if(count($groupNames) > 0) {
466
+		if (count($groupNames) > 0) {
467 467
 			natsort($groupNames);
468 468
 			$this->result->addOptions($dbKey, array_values($groupNames));
469 469
 		} else {
@@ -471,7 +471,7 @@  discard block
 block discarded – undo
471 471
 		}
472 472
 
473 473
 		$setFeatures = $this->configuration->$confKey;
474
-		if(is_array($setFeatures) && !empty($setFeatures)) {
474
+		if (is_array($setFeatures) && !empty($setFeatures)) {
475 475
 			//something is already configured? pre-select it.
476 476
 			$this->result->addChange($dbKey, $setFeatures);
477 477
 		}
@@ -479,14 +479,14 @@  discard block
 block discarded – undo
479 479
 	}
480 480
 
481 481
 	public function determineGroupMemberAssoc() {
482
-		if(!$this->checkRequirements(array('ldapHost',
482
+		if (!$this->checkRequirements(array('ldapHost',
483 483
 										   'ldapPort',
484 484
 										   'ldapGroupFilter',
485 485
 										   ))) {
486 486
 			return  false;
487 487
 		}
488 488
 		$attribute = $this->detectGroupMemberAssoc();
489
-		if($attribute === false) {
489
+		if ($attribute === false) {
490 490
 			return false;
491 491
 		}
492 492
 		$this->configuration->setConfiguration(array('ldapGroupMemberAssocAttr' => $attribute));
@@ -501,14 +501,14 @@  discard block
 block discarded – undo
501 501
 	 * @throws \Exception
502 502
 	 */
503 503
 	public function determineGroupObjectClasses() {
504
-		if(!$this->checkRequirements(array('ldapHost',
504
+		if (!$this->checkRequirements(array('ldapHost',
505 505
 										   'ldapPort',
506 506
 										   'ldapBase',
507 507
 										   ))) {
508 508
 			return  false;
509 509
 		}
510 510
 		$cr = $this->getConnection();
511
-		if(!$cr) {
511
+		if (!$cr) {
512 512
 			throw new \Exception('Could not connect to LDAP');
513 513
 		}
514 514
 
@@ -528,14 +528,14 @@  discard block
 block discarded – undo
528 528
 	 * @throws \Exception
529 529
 	 */
530 530
 	public function determineUserObjectClasses() {
531
-		if(!$this->checkRequirements(array('ldapHost',
531
+		if (!$this->checkRequirements(array('ldapHost',
532 532
 										   'ldapPort',
533 533
 										   'ldapBase',
534 534
 										   ))) {
535 535
 			return  false;
536 536
 		}
537 537
 		$cr = $this->getConnection();
538
-		if(!$cr) {
538
+		if (!$cr) {
539 539
 			throw new \Exception('Could not connect to LDAP');
540 540
 		}
541 541
 
@@ -558,7 +558,7 @@  discard block
 block discarded – undo
558 558
 	 * @throws \Exception
559 559
 	 */
560 560
 	public function getGroupFilter() {
561
-		if(!$this->checkRequirements(array('ldapHost',
561
+		if (!$this->checkRequirements(array('ldapHost',
562 562
 										   'ldapPort',
563 563
 										   'ldapBase',
564 564
 										   ))) {
@@ -582,7 +582,7 @@  discard block
 block discarded – undo
582 582
 	 * @throws \Exception
583 583
 	 */
584 584
 	public function getUserListFilter() {
585
-		if(!$this->checkRequirements(array('ldapHost',
585
+		if (!$this->checkRequirements(array('ldapHost',
586 586
 										   'ldapPort',
587 587
 										   'ldapBase',
588 588
 										   ))) {
@@ -595,7 +595,7 @@  discard block
 block discarded – undo
595 595
 			$this->applyFind('ldap_display_name', $d['ldap_display_name']);
596 596
 		}
597 597
 		$filter = $this->composeLdapFilter(self::LFILTER_USER_LIST);
598
-		if(!$filter) {
598
+		if (!$filter) {
599 599
 			throw new \Exception('Cannot create filter');
600 600
 		}
601 601
 
@@ -608,7 +608,7 @@  discard block
 block discarded – undo
608 608
 	 * @throws \Exception
609 609
 	 */
610 610
 	public function getUserLoginFilter() {
611
-		if(!$this->checkRequirements(array('ldapHost',
611
+		if (!$this->checkRequirements(array('ldapHost',
612 612
 										   'ldapPort',
613 613
 										   'ldapBase',
614 614
 										   'ldapUserFilter',
@@ -617,7 +617,7 @@  discard block
 block discarded – undo
617 617
 		}
618 618
 
619 619
 		$filter = $this->composeLdapFilter(self::LFILTER_LOGIN);
620
-		if(!$filter) {
620
+		if (!$filter) {
621 621
 			throw new \Exception('Cannot create filter');
622 622
 		}
623 623
 
@@ -631,7 +631,7 @@  discard block
 block discarded – undo
631 631
 	 * @throws \Exception
632 632
 	 */
633 633
 	public function testLoginName($loginName) {
634
-		if(!$this->checkRequirements(array('ldapHost',
634
+		if (!$this->checkRequirements(array('ldapHost',
635 635
 			'ldapPort',
636 636
 			'ldapBase',
637 637
 			'ldapLoginFilter',
@@ -640,17 +640,17 @@  discard block
 block discarded – undo
640 640
 		}
641 641
 
642 642
 		$cr = $this->access->connection->getConnectionResource();
643
-		if(!$this->ldap->isResource($cr)) {
643
+		if (!$this->ldap->isResource($cr)) {
644 644
 			throw new \Exception('connection error');
645 645
 		}
646 646
 
647
-		if(mb_strpos($this->access->connection->ldapLoginFilter, '%uid', 0, 'UTF-8')
647
+		if (mb_strpos($this->access->connection->ldapLoginFilter, '%uid', 0, 'UTF-8')
648 648
 			=== false) {
649 649
 			throw new \Exception('missing placeholder');
650 650
 		}
651 651
 
652 652
 		$users = $this->access->countUsersByLoginName($loginName);
653
-		if($this->ldap->errno($cr) !== 0) {
653
+		if ($this->ldap->errno($cr) !== 0) {
654 654
 			throw new \Exception($this->ldap->error($cr));
655 655
 		}
656 656
 		$filter = str_replace('%uid', $loginName, $this->access->connection->ldapLoginFilter);
@@ -665,22 +665,22 @@  discard block
 block discarded – undo
665 665
 	 * @throws \Exception
666 666
 	 */
667 667
 	public function guessPortAndTLS() {
668
-		if(!$this->checkRequirements(array('ldapHost',
668
+		if (!$this->checkRequirements(array('ldapHost',
669 669
 										   ))) {
670 670
 			return false;
671 671
 		}
672 672
 		$this->checkHost();
673 673
 		$portSettings = $this->getPortSettingsToTry();
674 674
 
675
-		if(!is_array($portSettings)) {
675
+		if (!is_array($portSettings)) {
676 676
 			throw new \Exception(print_r($portSettings, true));
677 677
 		}
678 678
 
679 679
 		//proceed from the best configuration and return on first success
680
-		foreach($portSettings as $setting) {
680
+		foreach ($portSettings as $setting) {
681 681
 			$p = $setting['port'];
682 682
 			$t = $setting['tls'];
683
-			\OCP\Util::writeLog('user_ldap', 'Wiz: trying port '. $p . ', TLS '. $t, ILogger::DEBUG);
683
+			\OCP\Util::writeLog('user_ldap', 'Wiz: trying port '.$p.', TLS '.$t, ILogger::DEBUG);
684 684
 			//connectAndBind may throw Exception, it needs to be catched by the
685 685
 			//callee of this method
686 686
 
@@ -690,7 +690,7 @@  discard block
 block discarded – undo
690 690
 				// any reply other than -1 (= cannot connect) is already okay,
691 691
 				// because then we found the server
692 692
 				// unavailable startTLS returns -11
693
-				if($e->getCode() > 0) {
693
+				if ($e->getCode() > 0) {
694 694
 					$settingsFound = true;
695 695
 				} else {
696 696
 					throw $e;
@@ -700,10 +700,10 @@  discard block
 block discarded – undo
700 700
 			if ($settingsFound === true) {
701 701
 				$config = array(
702 702
 					'ldapPort' => $p,
703
-					'ldapTLS' => (int)$t
703
+					'ldapTLS' => (int) $t
704 704
 				);
705 705
 				$this->configuration->setConfiguration($config);
706
-				\OCP\Util::writeLog('user_ldap', 'Wiz: detected Port ' . $p, ILogger::DEBUG);
706
+				\OCP\Util::writeLog('user_ldap', 'Wiz: detected Port '.$p, ILogger::DEBUG);
707 707
 				$this->result->addChange('ldap_port', $p);
708 708
 				return $this->result;
709 709
 			}
@@ -718,7 +718,7 @@  discard block
 block discarded – undo
718 718
 	 * @return WizardResult|false WizardResult on success, false otherwise
719 719
 	 */
720 720
 	public function guessBaseDN() {
721
-		if(!$this->checkRequirements(array('ldapHost',
721
+		if (!$this->checkRequirements(array('ldapHost',
722 722
 										   'ldapPort',
723 723
 										   ))) {
724 724
 			return false;
@@ -727,9 +727,9 @@  discard block
 block discarded – undo
727 727
 		//check whether a DN is given in the agent name (99.9% of all cases)
728 728
 		$base = null;
729 729
 		$i = stripos($this->configuration->ldapAgentName, 'dc=');
730
-		if($i !== false) {
730
+		if ($i !== false) {
731 731
 			$base = substr($this->configuration->ldapAgentName, $i);
732
-			if($this->testBaseDN($base)) {
732
+			if ($this->testBaseDN($base)) {
733 733
 				$this->applyFind('ldap_base', $base);
734 734
 				return $this->result;
735 735
 			}
@@ -740,13 +740,13 @@  discard block
 block discarded – undo
740 740
 		//a base DN
741 741
 		$helper = new Helper(\OC::$server->getConfig());
742 742
 		$domain = $helper->getDomainFromURL($this->configuration->ldapHost);
743
-		if(!$domain) {
743
+		if (!$domain) {
744 744
 			return false;
745 745
 		}
746 746
 
747 747
 		$dparts = explode('.', $domain);
748
-		while(count($dparts) > 0) {
749
-			$base2 = 'dc=' . implode(',dc=', $dparts);
748
+		while (count($dparts) > 0) {
749
+			$base2 = 'dc='.implode(',dc=', $dparts);
750 750
 			if ($base !== $base2 && $this->testBaseDN($base2)) {
751 751
 				$this->applyFind('ldap_base', $base2);
752 752
 				return $this->result;
@@ -779,7 +779,7 @@  discard block
 block discarded – undo
779 779
 		$hostInfo = parse_url($host);
780 780
 
781 781
 		//removes Port from Host
782
-		if(is_array($hostInfo) && isset($hostInfo['port'])) {
782
+		if (is_array($hostInfo) && isset($hostInfo['port'])) {
783 783
 			$port = $hostInfo['port'];
784 784
 			$host = str_replace(':'.$port, '', $host);
785 785
 			$this->applyFind('ldap_host', $host);
@@ -796,30 +796,30 @@  discard block
 block discarded – undo
796 796
 	private function detectGroupMemberAssoc() {
797 797
 		$possibleAttrs = array('uniqueMember', 'memberUid', 'member', 'gidNumber');
798 798
 		$filter = $this->configuration->ldapGroupFilter;
799
-		if(empty($filter)) {
799
+		if (empty($filter)) {
800 800
 			return false;
801 801
 		}
802 802
 		$cr = $this->getConnection();
803
-		if(!$cr) {
803
+		if (!$cr) {
804 804
 			throw new \Exception('Could not connect to LDAP');
805 805
 		}
806 806
 		$base = $this->configuration->ldapBase[0];
807 807
 		$rr = $this->ldap->search($cr, $base, $filter, $possibleAttrs, 0, 1000);
808
-		if(!$this->ldap->isResource($rr)) {
808
+		if (!$this->ldap->isResource($rr)) {
809 809
 			return false;
810 810
 		}
811 811
 		$er = $this->ldap->firstEntry($cr, $rr);
812
-		while(is_resource($er)) {
812
+		while (is_resource($er)) {
813 813
 			$this->ldap->getDN($cr, $er);
814 814
 			$attrs = $this->ldap->getAttributes($cr, $er);
815 815
 			$result = array();
816 816
 			$possibleAttrsCount = count($possibleAttrs);
817
-			for($i = 0; $i < $possibleAttrsCount; $i++) {
818
-				if(isset($attrs[$possibleAttrs[$i]])) {
817
+			for ($i = 0; $i < $possibleAttrsCount; $i++) {
818
+				if (isset($attrs[$possibleAttrs[$i]])) {
819 819
 					$result[$possibleAttrs[$i]] = $attrs[$possibleAttrs[$i]]['count'];
820 820
 				}
821 821
 			}
822
-			if(!empty($result)) {
822
+			if (!empty($result)) {
823 823
 				natsort($result);
824 824
 				return key($result);
825 825
 			}
@@ -838,14 +838,14 @@  discard block
 block discarded – undo
838 838
 	 */
839 839
 	private function testBaseDN($base) {
840 840
 		$cr = $this->getConnection();
841
-		if(!$cr) {
841
+		if (!$cr) {
842 842
 			throw new \Exception('Could not connect to LDAP');
843 843
 		}
844 844
 
845 845
 		//base is there, let's validate it. If we search for anything, we should
846 846
 		//get a result set > 0 on a proper base
847 847
 		$rr = $this->ldap->search($cr, $base, 'objectClass=*', array('dn'), 0, 1);
848
-		if(!$this->ldap->isResource($rr)) {
848
+		if (!$this->ldap->isResource($rr)) {
849 849
 			$errorNo  = $this->ldap->errno($cr);
850 850
 			$errorMsg = $this->ldap->error($cr);
851 851
 			\OCP\Util::writeLog('user_ldap', 'Wiz: Could not search base '.$base.
@@ -867,11 +867,11 @@  discard block
 block discarded – undo
867 867
 	 */
868 868
 	private function testMemberOf() {
869 869
 		$cr = $this->getConnection();
870
-		if(!$cr) {
870
+		if (!$cr) {
871 871
 			throw new \Exception('Could not connect to LDAP');
872 872
 		}
873 873
 		$result = $this->access->countUsers('memberOf=*', array('memberOf'), 1);
874
-		if(is_int($result) &&  $result > 0) {
874
+		if (is_int($result) && $result > 0) {
875 875
 			return true;
876 876
 		}
877 877
 		return false;
@@ -892,27 +892,27 @@  discard block
 block discarded – undo
892 892
 			case self::LFILTER_USER_LIST:
893 893
 				$objcs = $this->configuration->ldapUserFilterObjectclass;
894 894
 				//glue objectclasses
895
-				if(is_array($objcs) && count($objcs) > 0) {
895
+				if (is_array($objcs) && count($objcs) > 0) {
896 896
 					$filter .= '(|';
897
-					foreach($objcs as $objc) {
898
-						$filter .= '(objectclass=' . $objc . ')';
897
+					foreach ($objcs as $objc) {
898
+						$filter .= '(objectclass='.$objc.')';
899 899
 					}
900 900
 					$filter .= ')';
901 901
 					$parts++;
902 902
 				}
903 903
 				//glue group memberships
904
-				if($this->configuration->hasMemberOfFilterSupport) {
904
+				if ($this->configuration->hasMemberOfFilterSupport) {
905 905
 					$cns = $this->configuration->ldapUserFilterGroups;
906
-					if(is_array($cns) && count($cns) > 0) {
906
+					if (is_array($cns) && count($cns) > 0) {
907 907
 						$filter .= '(|';
908 908
 						$cr = $this->getConnection();
909
-						if(!$cr) {
909
+						if (!$cr) {
910 910
 							throw new \Exception('Could not connect to LDAP');
911 911
 						}
912 912
 						$base = $this->configuration->ldapBase[0];
913
-						foreach($cns as $cn) {
914
-							$rr = $this->ldap->search($cr, $base, 'cn=' . $cn, array('dn', 'primaryGroupToken'));
915
-							if(!$this->ldap->isResource($rr)) {
913
+						foreach ($cns as $cn) {
914
+							$rr = $this->ldap->search($cr, $base, 'cn='.$cn, array('dn', 'primaryGroupToken'));
915
+							if (!$this->ldap->isResource($rr)) {
916 916
 								continue;
917 917
 							}
918 918
 							$er = $this->ldap->firstEntry($cr, $rr);
@@ -921,11 +921,11 @@  discard block
 block discarded – undo
921 921
 							if ($dn === false || $dn === '') {
922 922
 								continue;
923 923
 							}
924
-							$filterPart = '(memberof=' . $dn . ')';
925
-							if(isset($attrs['primaryGroupToken'])) {
924
+							$filterPart = '(memberof='.$dn.')';
925
+							if (isset($attrs['primaryGroupToken'])) {
926 926
 								$pgt = $attrs['primaryGroupToken'][0];
927
-								$primaryFilterPart = '(primaryGroupID=' . $pgt .')';
928
-								$filterPart = '(|' . $filterPart . $primaryFilterPart . ')';
927
+								$primaryFilterPart = '(primaryGroupID='.$pgt.')';
928
+								$filterPart = '(|'.$filterPart.$primaryFilterPart.')';
929 929
 							}
930 930
 							$filter .= $filterPart;
931 931
 						}
@@ -934,8 +934,8 @@  discard block
 block discarded – undo
934 934
 					$parts++;
935 935
 				}
936 936
 				//wrap parts in AND condition
937
-				if($parts > 1) {
938
-					$filter = '(&' . $filter . ')';
937
+				if ($parts > 1) {
938
+					$filter = '(&'.$filter.')';
939 939
 				}
940 940
 				if ($filter === '') {
941 941
 					$filter = '(objectclass=*)';
@@ -945,27 +945,27 @@  discard block
 block discarded – undo
945 945
 			case self::LFILTER_GROUP_LIST:
946 946
 				$objcs = $this->configuration->ldapGroupFilterObjectclass;
947 947
 				//glue objectclasses
948
-				if(is_array($objcs) && count($objcs) > 0) {
948
+				if (is_array($objcs) && count($objcs) > 0) {
949 949
 					$filter .= '(|';
950
-					foreach($objcs as $objc) {
951
-						$filter .= '(objectclass=' . $objc . ')';
950
+					foreach ($objcs as $objc) {
951
+						$filter .= '(objectclass='.$objc.')';
952 952
 					}
953 953
 					$filter .= ')';
954 954
 					$parts++;
955 955
 				}
956 956
 				//glue group memberships
957 957
 				$cns = $this->configuration->ldapGroupFilterGroups;
958
-				if(is_array($cns) && count($cns) > 0) {
958
+				if (is_array($cns) && count($cns) > 0) {
959 959
 					$filter .= '(|';
960
-					foreach($cns as $cn) {
961
-						$filter .= '(cn=' . $cn . ')';
960
+					foreach ($cns as $cn) {
961
+						$filter .= '(cn='.$cn.')';
962 962
 					}
963 963
 					$filter .= ')';
964 964
 				}
965 965
 				$parts++;
966 966
 				//wrap parts in AND condition
967
-				if($parts > 1) {
968
-					$filter = '(&' . $filter . ')';
967
+				if ($parts > 1) {
968
+					$filter = '(&'.$filter.')';
969 969
 				}
970 970
 				break;
971 971
 
@@ -977,47 +977,47 @@  discard block
 block discarded – undo
977 977
 				$userAttributes = array_change_key_case(array_flip($userAttributes));
978 978
 				$parts = 0;
979 979
 
980
-				if($this->configuration->ldapLoginFilterUsername === '1') {
980
+				if ($this->configuration->ldapLoginFilterUsername === '1') {
981 981
 					$attr = '';
982
-					if(isset($userAttributes['uid'])) {
982
+					if (isset($userAttributes['uid'])) {
983 983
 						$attr = 'uid';
984
-					} else if(isset($userAttributes['samaccountname'])) {
984
+					} else if (isset($userAttributes['samaccountname'])) {
985 985
 						$attr = 'samaccountname';
986
-					} else if(isset($userAttributes['cn'])) {
986
+					} else if (isset($userAttributes['cn'])) {
987 987
 						//fallback
988 988
 						$attr = 'cn';
989 989
 					}
990 990
 					if ($attr !== '') {
991
-						$filterUsername = '(' . $attr . $loginpart . ')';
991
+						$filterUsername = '('.$attr.$loginpart.')';
992 992
 						$parts++;
993 993
 					}
994 994
 				}
995 995
 
996 996
 				$filterEmail = '';
997
-				if($this->configuration->ldapLoginFilterEmail === '1') {
997
+				if ($this->configuration->ldapLoginFilterEmail === '1') {
998 998
 					$filterEmail = '(|(mailPrimaryAddress=%uid)(mail=%uid))';
999 999
 					$parts++;
1000 1000
 				}
1001 1001
 
1002 1002
 				$filterAttributes = '';
1003 1003
 				$attrsToFilter = $this->configuration->ldapLoginFilterAttributes;
1004
-				if(is_array($attrsToFilter) && count($attrsToFilter) > 0) {
1004
+				if (is_array($attrsToFilter) && count($attrsToFilter) > 0) {
1005 1005
 					$filterAttributes = '(|';
1006
-					foreach($attrsToFilter as $attribute) {
1007
-						$filterAttributes .= '(' . $attribute . $loginpart . ')';
1006
+					foreach ($attrsToFilter as $attribute) {
1007
+						$filterAttributes .= '('.$attribute.$loginpart.')';
1008 1008
 					}
1009 1009
 					$filterAttributes .= ')';
1010 1010
 					$parts++;
1011 1011
 				}
1012 1012
 
1013 1013
 				$filterLogin = '';
1014
-				if($parts > 1) {
1014
+				if ($parts > 1) {
1015 1015
 					$filterLogin = '(|';
1016 1016
 				}
1017 1017
 				$filterLogin .= $filterUsername;
1018 1018
 				$filterLogin .= $filterEmail;
1019 1019
 				$filterLogin .= $filterAttributes;
1020
-				if($parts > 1) {
1020
+				if ($parts > 1) {
1021 1021
 					$filterLogin .= ')';
1022 1022
 				}
1023 1023
 
@@ -1042,12 +1042,12 @@  discard block
 block discarded – undo
1042 1042
 		//connect, does not really trigger any server communication
1043 1043
 		$host = $this->configuration->ldapHost;
1044 1044
 		$hostInfo = parse_url($host);
1045
-		if(!$hostInfo) {
1045
+		if (!$hostInfo) {
1046 1046
 			throw new \Exception(self::$l->t('Invalid Host'));
1047 1047
 		}
1048 1048
 		\OCP\Util::writeLog('user_ldap', 'Wiz: Attempting to connect ', ILogger::DEBUG);
1049 1049
 		$cr = $this->ldap->connect($host, $port);
1050
-		if(!is_resource($cr)) {
1050
+		if (!is_resource($cr)) {
1051 1051
 			throw new \Exception(self::$l->t('Invalid Host'));
1052 1052
 		}
1053 1053
 
@@ -1057,9 +1057,9 @@  discard block
 block discarded – undo
1057 1057
 		$this->ldap->setOption($cr, LDAP_OPT_NETWORK_TIMEOUT, self::LDAP_NW_TIMEOUT);
1058 1058
 
1059 1059
 		try {
1060
-			if($tls) {
1060
+			if ($tls) {
1061 1061
 				$isTlsWorking = @$this->ldap->startTls($cr);
1062
-				if(!$isTlsWorking) {
1062
+				if (!$isTlsWorking) {
1063 1063
 					return false;
1064 1064
 				}
1065 1065
 			}
@@ -1073,17 +1073,17 @@  discard block
 block discarded – undo
1073 1073
 			$errNo = $this->ldap->errno($cr);
1074 1074
 			$error = ldap_error($cr);
1075 1075
 			$this->ldap->unbind($cr);
1076
-		} catch(ServerNotAvailableException $e) {
1076
+		} catch (ServerNotAvailableException $e) {
1077 1077
 			return false;
1078 1078
 		}
1079 1079
 
1080
-		if($login === true) {
1080
+		if ($login === true) {
1081 1081
 			$this->ldap->unbind($cr);
1082
-			\OCP\Util::writeLog('user_ldap', 'Wiz: Bind successful to Port '. $port . ' TLS ' . (int)$tls, ILogger::DEBUG);
1082
+			\OCP\Util::writeLog('user_ldap', 'Wiz: Bind successful to Port '.$port.' TLS '.(int) $tls, ILogger::DEBUG);
1083 1083
 			return true;
1084 1084
 		}
1085 1085
 
1086
-		if($errNo === -1) {
1086
+		if ($errNo === -1) {
1087 1087
 			//host, port or TLS wrong
1088 1088
 			return false;
1089 1089
 		}
@@ -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
 		}
@@ -1336,18 +1336,18 @@  discard block
 block discarded – undo
1336 1336
 		//636 ← LDAPS / SSL
1337 1337
 		//7xxx ← UCS. need to be checked first, because both ports may be open
1338 1338
 		$host = $this->configuration->ldapHost;
1339
-		$port = (int)$this->configuration->ldapPort;
1339
+		$port = (int) $this->configuration->ldapPort;
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.
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.
Indentation   +220 added lines, -220 removed lines patch added patch discarded remove patch
@@ -39,224 +39,224 @@
 block discarded – undo
39 39
  * Shared mount points can be moved by the user
40 40
  */
41 41
 class SharedMount extends MountPoint implements MoveableMount {
42
-	/**
43
-	 * @var \OCA\Files_Sharing\SharedStorage $storage
44
-	 */
45
-	protected $storage = null;
46
-
47
-	/**
48
-	 * @var \OC\Files\View
49
-	 */
50
-	private $recipientView;
51
-
52
-	/**
53
-	 * @var string
54
-	 */
55
-	private $user;
56
-
57
-	/** @var \OCP\Share\IShare */
58
-	private $superShare;
59
-
60
-	/** @var \OCP\Share\IShare[] */
61
-	private $groupedShares;
62
-
63
-	/**
64
-	 * @param string $storage
65
-	 * @param SharedMount[] $mountpoints
66
-	 * @param array $arguments
67
-	 * @param IStorageFactory $loader
68
-	 * @param View $recipientView
69
-	 */
70
-	public function __construct($storage, array $mountpoints, $arguments, IStorageFactory $loader, View $recipientView, CappedMemoryCache $folderExistCache) {
71
-		$this->user = $arguments['user'];
72
-		$this->recipientView = $recipientView;
73
-
74
-		$this->superShare = $arguments['superShare'];
75
-		$this->groupedShares = $arguments['groupedShares'];
76
-
77
-		$newMountPoint = $this->verifyMountPoint($this->superShare, $mountpoints, $folderExistCache);
78
-		$absMountPoint = '/' . $this->user . '/files' . $newMountPoint;
79
-		parent::__construct($storage, $absMountPoint, $arguments, $loader);
80
-	}
81
-
82
-	/**
83
-	 * check if the parent folder exists otherwise move the mount point up
84
-	 *
85
-	 * @param \OCP\Share\IShare $share
86
-	 * @param SharedMount[] $mountpoints
87
-	 * @return string
88
-	 */
89
-	private function verifyMountPoint(\OCP\Share\IShare $share, array $mountpoints, CappedMemoryCache $folderExistCache) {
90
-
91
-		$mountPoint = basename($share->getTarget());
92
-		$parent = dirname($share->getTarget());
93
-
94
-		if ($folderExistCache->hasKey($parent)) {
95
-			$parentExists = $folderExistCache->get($parent);
96
-		} else {
97
-			$parentExists = $this->recipientView->is_dir($parent);
98
-			$folderExistCache->set($parent, $parentExists);
99
-		}
100
-		if (!$parentExists) {
101
-			$parent = Helper::getShareFolder($this->recipientView);
102
-		}
103
-
104
-		$newMountPoint = $this->generateUniqueTarget(
105
-			\OC\Files\Filesystem::normalizePath($parent . '/' . $mountPoint),
106
-			$this->recipientView,
107
-			$mountpoints
108
-		);
109
-
110
-		if ($newMountPoint !== $share->getTarget()) {
111
-			$this->updateFileTarget($newMountPoint, $share);
112
-		}
113
-
114
-		return $newMountPoint;
115
-	}
116
-
117
-	/**
118
-	 * update fileTarget in the database if the mount point changed
119
-	 *
120
-	 * @param string $newPath
121
-	 * @param \OCP\Share\IShare $share
122
-	 * @return bool
123
-	 */
124
-	private function updateFileTarget($newPath, &$share) {
125
-		$share->setTarget($newPath);
126
-
127
-		foreach ($this->groupedShares as $tmpShare) {
128
-			$tmpShare->setTarget($newPath);
129
-			\OC::$server->getShareManager()->moveShare($tmpShare, $this->user);
130
-		}
131
-	}
132
-
133
-
134
-	/**
135
-	 * @param string $path
136
-	 * @param View $view
137
-	 * @param SharedMount[] $mountpoints
138
-	 * @return mixed
139
-	 */
140
-	private function generateUniqueTarget($path, $view, array $mountpoints) {
141
-		$pathinfo = pathinfo($path);
142
-		$ext = isset($pathinfo['extension']) ? '.' . $pathinfo['extension'] : '';
143
-		$name = $pathinfo['filename'];
144
-		$dir = $pathinfo['dirname'];
145
-
146
-		$i = 2;
147
-		$absolutePath = $this->recipientView->getAbsolutePath($path) . '/';
148
-		while ($view->file_exists($path) || isset($mountpoints[$absolutePath])) {
149
-			$path = Filesystem::normalizePath($dir . '/' . $name . ' (' . $i . ')' . $ext);
150
-			$absolutePath = $this->recipientView->getAbsolutePath($path) . '/';
151
-			$i++;
152
-		}
153
-
154
-		return $path;
155
-	}
156
-
157
-	/**
158
-	 * Format a path to be relative to the /user/files/ directory
159
-	 *
160
-	 * @param string $path the absolute path
161
-	 * @return string e.g. turns '/admin/files/test.txt' into '/test.txt'
162
-	 * @throws \OCA\Files_Sharing\Exceptions\BrokenPath
163
-	 */
164
-	protected function stripUserFilesPath($path) {
165
-		$trimmed = ltrim($path, '/');
166
-		$split = explode('/', $trimmed);
167
-
168
-		// it is not a file relative to data/user/files
169
-		if (count($split) < 3 || $split[1] !== 'files') {
170
-			\OC::$server->getLogger()->error('Can not strip userid and "files/" from path: ' . $path, ['app' => 'files_sharing']);
171
-			throw new \OCA\Files_Sharing\Exceptions\BrokenPath('Path does not start with /user/files', 10);
172
-		}
173
-
174
-		// skip 'user' and 'files'
175
-		$sliced = array_slice($split, 2);
176
-		$relPath = implode('/', $sliced);
177
-
178
-		return '/' . $relPath;
179
-	}
180
-
181
-	/**
182
-	 * Move the mount point to $target
183
-	 *
184
-	 * @param string $target the target mount point
185
-	 * @return bool
186
-	 */
187
-	public function moveMount($target) {
188
-
189
-		$relTargetPath = $this->stripUserFilesPath($target);
190
-		$share = $this->storage->getShare();
191
-
192
-		$result = true;
193
-
194
-		try {
195
-			$this->updateFileTarget($relTargetPath, $share);
196
-			$this->setMountPoint($target);
197
-			$this->storage->setMountPoint($relTargetPath);
198
-		} catch (\Exception $e) {
199
-			\OC::$server->getLogger()->logException($e, ['app' => 'files_sharing', 'message' => 'Could not rename mount point for shared folder "' . $this->getMountPoint() . '" to "' . $target . '"']);
200
-		}
201
-
202
-		return $result;
203
-	}
204
-
205
-	/**
206
-	 * Remove the mount points
207
-	 *
208
-	 * @return bool
209
-	 */
210
-	public function removeMount() {
211
-		$mountManager = \OC\Files\Filesystem::getMountManager();
212
-		/** @var $storage \OCA\Files_Sharing\SharedStorage */
213
-		$storage = $this->getStorage();
214
-		$result = $storage->unshareStorage();
215
-		$mountManager->removeMount($this->mountPoint);
216
-
217
-		return $result;
218
-	}
219
-
220
-	/**
221
-	 * @return \OCP\Share\IShare
222
-	 */
223
-	public function getShare() {
224
-		return $this->superShare;
225
-	}
226
-
227
-	/**
228
-	 * Get the file id of the root of the storage
229
-	 *
230
-	 * @return int
231
-	 */
232
-	public function getStorageRootId() {
233
-		return $this->getShare()->getNodeId();
234
-	}
235
-
236
-	/**
237
-	 * @return int
238
-	 */
239
-	public function getNumericStorageId() {
240
-		if (!is_null($this->getShare()->getNodeCacheEntry())) {
241
-			return $this->getShare()->getNodeCacheEntry()->getStorageId();
242
-		} else {
243
-			$builder = \OC::$server->getDatabaseConnection()->getQueryBuilder();
244
-
245
-			$query = $builder->select('storage')
246
-				->from('filecache')
247
-				->where($builder->expr()->eq('fileid', $builder->createNamedParameter($this->getStorageRootId())));
248
-
249
-			$result = $query->execute();
250
-			$row = $result->fetch();
251
-			$result->closeCursor();
252
-			if ($row) {
253
-				return (int)$row['storage'];
254
-			}
255
-			return -1;
256
-		}
257
-	}
258
-
259
-	public function getMountType() {
260
-		return 'shared';
261
-	}
42
+    /**
43
+     * @var \OCA\Files_Sharing\SharedStorage $storage
44
+     */
45
+    protected $storage = null;
46
+
47
+    /**
48
+     * @var \OC\Files\View
49
+     */
50
+    private $recipientView;
51
+
52
+    /**
53
+     * @var string
54
+     */
55
+    private $user;
56
+
57
+    /** @var \OCP\Share\IShare */
58
+    private $superShare;
59
+
60
+    /** @var \OCP\Share\IShare[] */
61
+    private $groupedShares;
62
+
63
+    /**
64
+     * @param string $storage
65
+     * @param SharedMount[] $mountpoints
66
+     * @param array $arguments
67
+     * @param IStorageFactory $loader
68
+     * @param View $recipientView
69
+     */
70
+    public function __construct($storage, array $mountpoints, $arguments, IStorageFactory $loader, View $recipientView, CappedMemoryCache $folderExistCache) {
71
+        $this->user = $arguments['user'];
72
+        $this->recipientView = $recipientView;
73
+
74
+        $this->superShare = $arguments['superShare'];
75
+        $this->groupedShares = $arguments['groupedShares'];
76
+
77
+        $newMountPoint = $this->verifyMountPoint($this->superShare, $mountpoints, $folderExistCache);
78
+        $absMountPoint = '/' . $this->user . '/files' . $newMountPoint;
79
+        parent::__construct($storage, $absMountPoint, $arguments, $loader);
80
+    }
81
+
82
+    /**
83
+     * check if the parent folder exists otherwise move the mount point up
84
+     *
85
+     * @param \OCP\Share\IShare $share
86
+     * @param SharedMount[] $mountpoints
87
+     * @return string
88
+     */
89
+    private function verifyMountPoint(\OCP\Share\IShare $share, array $mountpoints, CappedMemoryCache $folderExistCache) {
90
+
91
+        $mountPoint = basename($share->getTarget());
92
+        $parent = dirname($share->getTarget());
93
+
94
+        if ($folderExistCache->hasKey($parent)) {
95
+            $parentExists = $folderExistCache->get($parent);
96
+        } else {
97
+            $parentExists = $this->recipientView->is_dir($parent);
98
+            $folderExistCache->set($parent, $parentExists);
99
+        }
100
+        if (!$parentExists) {
101
+            $parent = Helper::getShareFolder($this->recipientView);
102
+        }
103
+
104
+        $newMountPoint = $this->generateUniqueTarget(
105
+            \OC\Files\Filesystem::normalizePath($parent . '/' . $mountPoint),
106
+            $this->recipientView,
107
+            $mountpoints
108
+        );
109
+
110
+        if ($newMountPoint !== $share->getTarget()) {
111
+            $this->updateFileTarget($newMountPoint, $share);
112
+        }
113
+
114
+        return $newMountPoint;
115
+    }
116
+
117
+    /**
118
+     * update fileTarget in the database if the mount point changed
119
+     *
120
+     * @param string $newPath
121
+     * @param \OCP\Share\IShare $share
122
+     * @return bool
123
+     */
124
+    private function updateFileTarget($newPath, &$share) {
125
+        $share->setTarget($newPath);
126
+
127
+        foreach ($this->groupedShares as $tmpShare) {
128
+            $tmpShare->setTarget($newPath);
129
+            \OC::$server->getShareManager()->moveShare($tmpShare, $this->user);
130
+        }
131
+    }
132
+
133
+
134
+    /**
135
+     * @param string $path
136
+     * @param View $view
137
+     * @param SharedMount[] $mountpoints
138
+     * @return mixed
139
+     */
140
+    private function generateUniqueTarget($path, $view, array $mountpoints) {
141
+        $pathinfo = pathinfo($path);
142
+        $ext = isset($pathinfo['extension']) ? '.' . $pathinfo['extension'] : '';
143
+        $name = $pathinfo['filename'];
144
+        $dir = $pathinfo['dirname'];
145
+
146
+        $i = 2;
147
+        $absolutePath = $this->recipientView->getAbsolutePath($path) . '/';
148
+        while ($view->file_exists($path) || isset($mountpoints[$absolutePath])) {
149
+            $path = Filesystem::normalizePath($dir . '/' . $name . ' (' . $i . ')' . $ext);
150
+            $absolutePath = $this->recipientView->getAbsolutePath($path) . '/';
151
+            $i++;
152
+        }
153
+
154
+        return $path;
155
+    }
156
+
157
+    /**
158
+     * Format a path to be relative to the /user/files/ directory
159
+     *
160
+     * @param string $path the absolute path
161
+     * @return string e.g. turns '/admin/files/test.txt' into '/test.txt'
162
+     * @throws \OCA\Files_Sharing\Exceptions\BrokenPath
163
+     */
164
+    protected function stripUserFilesPath($path) {
165
+        $trimmed = ltrim($path, '/');
166
+        $split = explode('/', $trimmed);
167
+
168
+        // it is not a file relative to data/user/files
169
+        if (count($split) < 3 || $split[1] !== 'files') {
170
+            \OC::$server->getLogger()->error('Can not strip userid and "files/" from path: ' . $path, ['app' => 'files_sharing']);
171
+            throw new \OCA\Files_Sharing\Exceptions\BrokenPath('Path does not start with /user/files', 10);
172
+        }
173
+
174
+        // skip 'user' and 'files'
175
+        $sliced = array_slice($split, 2);
176
+        $relPath = implode('/', $sliced);
177
+
178
+        return '/' . $relPath;
179
+    }
180
+
181
+    /**
182
+     * Move the mount point to $target
183
+     *
184
+     * @param string $target the target mount point
185
+     * @return bool
186
+     */
187
+    public function moveMount($target) {
188
+
189
+        $relTargetPath = $this->stripUserFilesPath($target);
190
+        $share = $this->storage->getShare();
191
+
192
+        $result = true;
193
+
194
+        try {
195
+            $this->updateFileTarget($relTargetPath, $share);
196
+            $this->setMountPoint($target);
197
+            $this->storage->setMountPoint($relTargetPath);
198
+        } catch (\Exception $e) {
199
+            \OC::$server->getLogger()->logException($e, ['app' => 'files_sharing', 'message' => 'Could not rename mount point for shared folder "' . $this->getMountPoint() . '" to "' . $target . '"']);
200
+        }
201
+
202
+        return $result;
203
+    }
204
+
205
+    /**
206
+     * Remove the mount points
207
+     *
208
+     * @return bool
209
+     */
210
+    public function removeMount() {
211
+        $mountManager = \OC\Files\Filesystem::getMountManager();
212
+        /** @var $storage \OCA\Files_Sharing\SharedStorage */
213
+        $storage = $this->getStorage();
214
+        $result = $storage->unshareStorage();
215
+        $mountManager->removeMount($this->mountPoint);
216
+
217
+        return $result;
218
+    }
219
+
220
+    /**
221
+     * @return \OCP\Share\IShare
222
+     */
223
+    public function getShare() {
224
+        return $this->superShare;
225
+    }
226
+
227
+    /**
228
+     * Get the file id of the root of the storage
229
+     *
230
+     * @return int
231
+     */
232
+    public function getStorageRootId() {
233
+        return $this->getShare()->getNodeId();
234
+    }
235
+
236
+    /**
237
+     * @return int
238
+     */
239
+    public function getNumericStorageId() {
240
+        if (!is_null($this->getShare()->getNodeCacheEntry())) {
241
+            return $this->getShare()->getNodeCacheEntry()->getStorageId();
242
+        } else {
243
+            $builder = \OC::$server->getDatabaseConnection()->getQueryBuilder();
244
+
245
+            $query = $builder->select('storage')
246
+                ->from('filecache')
247
+                ->where($builder->expr()->eq('fileid', $builder->createNamedParameter($this->getStorageRootId())));
248
+
249
+            $result = $query->execute();
250
+            $row = $result->fetch();
251
+            $result->closeCursor();
252
+            if ($row) {
253
+                return (int)$row['storage'];
254
+            }
255
+            return -1;
256
+        }
257
+    }
258
+
259
+    public function getMountType() {
260
+        return 'shared';
261
+    }
262 262
 }
Please login to merge, or discard this patch.
Spacing   +10 added lines, -10 removed lines patch added patch discarded remove patch
@@ -75,7 +75,7 @@  discard block
 block discarded – undo
75 75
 		$this->groupedShares = $arguments['groupedShares'];
76 76
 
77 77
 		$newMountPoint = $this->verifyMountPoint($this->superShare, $mountpoints, $folderExistCache);
78
-		$absMountPoint = '/' . $this->user . '/files' . $newMountPoint;
78
+		$absMountPoint = '/'.$this->user.'/files'.$newMountPoint;
79 79
 		parent::__construct($storage, $absMountPoint, $arguments, $loader);
80 80
 	}
81 81
 
@@ -102,7 +102,7 @@  discard block
 block discarded – undo
102 102
 		}
103 103
 
104 104
 		$newMountPoint = $this->generateUniqueTarget(
105
-			\OC\Files\Filesystem::normalizePath($parent . '/' . $mountPoint),
105
+			\OC\Files\Filesystem::normalizePath($parent.'/'.$mountPoint),
106 106
 			$this->recipientView,
107 107
 			$mountpoints
108 108
 		);
@@ -139,15 +139,15 @@  discard block
 block discarded – undo
139 139
 	 */
140 140
 	private function generateUniqueTarget($path, $view, array $mountpoints) {
141 141
 		$pathinfo = pathinfo($path);
142
-		$ext = isset($pathinfo['extension']) ? '.' . $pathinfo['extension'] : '';
142
+		$ext = isset($pathinfo['extension']) ? '.'.$pathinfo['extension'] : '';
143 143
 		$name = $pathinfo['filename'];
144 144
 		$dir = $pathinfo['dirname'];
145 145
 
146 146
 		$i = 2;
147
-		$absolutePath = $this->recipientView->getAbsolutePath($path) . '/';
147
+		$absolutePath = $this->recipientView->getAbsolutePath($path).'/';
148 148
 		while ($view->file_exists($path) || isset($mountpoints[$absolutePath])) {
149
-			$path = Filesystem::normalizePath($dir . '/' . $name . ' (' . $i . ')' . $ext);
150
-			$absolutePath = $this->recipientView->getAbsolutePath($path) . '/';
149
+			$path = Filesystem::normalizePath($dir.'/'.$name.' ('.$i.')'.$ext);
150
+			$absolutePath = $this->recipientView->getAbsolutePath($path).'/';
151 151
 			$i++;
152 152
 		}
153 153
 
@@ -167,7 +167,7 @@  discard block
 block discarded – undo
167 167
 
168 168
 		// it is not a file relative to data/user/files
169 169
 		if (count($split) < 3 || $split[1] !== 'files') {
170
-			\OC::$server->getLogger()->error('Can not strip userid and "files/" from path: ' . $path, ['app' => 'files_sharing']);
170
+			\OC::$server->getLogger()->error('Can not strip userid and "files/" from path: '.$path, ['app' => 'files_sharing']);
171 171
 			throw new \OCA\Files_Sharing\Exceptions\BrokenPath('Path does not start with /user/files', 10);
172 172
 		}
173 173
 
@@ -175,7 +175,7 @@  discard block
 block discarded – undo
175 175
 		$sliced = array_slice($split, 2);
176 176
 		$relPath = implode('/', $sliced);
177 177
 
178
-		return '/' . $relPath;
178
+		return '/'.$relPath;
179 179
 	}
180 180
 
181 181
 	/**
@@ -196,7 +196,7 @@  discard block
 block discarded – undo
196 196
 			$this->setMountPoint($target);
197 197
 			$this->storage->setMountPoint($relTargetPath);
198 198
 		} catch (\Exception $e) {
199
-			\OC::$server->getLogger()->logException($e, ['app' => 'files_sharing', 'message' => 'Could not rename mount point for shared folder "' . $this->getMountPoint() . '" to "' . $target . '"']);
199
+			\OC::$server->getLogger()->logException($e, ['app' => 'files_sharing', 'message' => 'Could not rename mount point for shared folder "'.$this->getMountPoint().'" to "'.$target.'"']);
200 200
 		}
201 201
 
202 202
 		return $result;
@@ -250,7 +250,7 @@  discard block
 block discarded – undo
250 250
 			$row = $result->fetch();
251 251
 			$result->closeCursor();
252 252
 			if ($row) {
253
-				return (int)$row['storage'];
253
+				return (int) $row['storage'];
254 254
 			}
255 255
 			return -1;
256 256
 		}
Please login to merge, or discard this patch.
lib/private/Cache/File.php 3 patches
Doc Comments   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -95,7 +95,7 @@
 block discarded – undo
95 95
 	 * @param string $key
96 96
 	 * @param mixed $value
97 97
 	 * @param int $ttl
98
-	 * @return bool|mixed
98
+	 * @return boolean
99 99
 	 * @throws \OC\ForbiddenException
100 100
 	 */
101 101
 	public function set($key, $value, $ttl = 0) {
Please login to merge, or discard this patch.
Spacing   +11 added lines, -11 removed lines patch added patch discarded remove patch
@@ -53,10 +53,10 @@  discard block
 block discarded – undo
53 53
 			$rootView = new View();
54 54
 			$user = \OC::$server->getUserSession()->getUser();
55 55
 			Filesystem::initMountPoints($user->getUID());
56
-			if (!$rootView->file_exists('/' . $user->getUID() . '/cache')) {
57
-				$rootView->mkdir('/' . $user->getUID() . '/cache');
56
+			if (!$rootView->file_exists('/'.$user->getUID().'/cache')) {
57
+				$rootView->mkdir('/'.$user->getUID().'/cache');
58 58
 			}
59
-			$this->storage = new View('/' . $user->getUID() . '/cache');
59
+			$this->storage = new View('/'.$user->getUID().'/cache');
60 60
 			return $this->storage;
61 61
 		} else {
62 62
 			\OCP\Util::writeLog('core', 'Can\'t get cache storage, user not logged in', ILogger::ERROR);
@@ -106,12 +106,12 @@  discard block
 block discarded – undo
106 106
 		// unique id to avoid chunk collision, just in case
107 107
 		$uniqueId = \OC::$server->getSecureRandom()->generate(
108 108
 			16,
109
-			ISecureRandom::CHAR_DIGITS . ISecureRandom::CHAR_LOWER . ISecureRandom::CHAR_UPPER
109
+			ISecureRandom::CHAR_DIGITS.ISecureRandom::CHAR_LOWER.ISecureRandom::CHAR_UPPER
110 110
 		);
111 111
 
112 112
 		// use part file to prevent hasKey() to find the key
113 113
 		// while it is being written
114
-		$keyPart = $key . '.' . $uniqueId . '.part';
114
+		$keyPart = $key.'.'.$uniqueId.'.part';
115 115
 		if ($storage and $storage->file_put_contents($keyPart, $value)) {
116 116
 			if ($ttl === 0) {
117 117
 				$ttl = 86400; // 60*60*24
@@ -160,7 +160,7 @@  discard block
 block discarded – undo
160 160
 			if (is_resource($dh)) {
161 161
 				while (($file = readdir($dh)) !== false) {
162 162
 					if ($file != '.' and $file != '..' and ($prefix === '' || strpos($file, $prefix) === 0)) {
163
-						$storage->unlink('/' . $file);
163
+						$storage->unlink('/'.$file);
164 164
 					}
165 165
 				}
166 166
 			}
@@ -185,17 +185,17 @@  discard block
 block discarded – undo
185 185
 			while (($file = readdir($dh)) !== false) {
186 186
 				if ($file != '.' and $file != '..') {
187 187
 					try {
188
-						$mtime = $storage->filemtime('/' . $file);
188
+						$mtime = $storage->filemtime('/'.$file);
189 189
 						if ($mtime < $now) {
190
-							$storage->unlink('/' . $file);
190
+							$storage->unlink('/'.$file);
191 191
 						}
192 192
 					} catch (\OCP\Lock\LockedException $e) {
193 193
 						// ignore locked chunks
194
-						\OC::$server->getLogger()->debug('Could not cleanup locked chunk "' . $file . '"', array('app' => 'core'));
194
+						\OC::$server->getLogger()->debug('Could not cleanup locked chunk "'.$file.'"', array('app' => 'core'));
195 195
 					} catch (\OCP\Files\ForbiddenException $e) {
196
-						\OC::$server->getLogger()->debug('Could not cleanup forbidden chunk "' . $file . '"', array('app' => 'core'));
196
+						\OC::$server->getLogger()->debug('Could not cleanup forbidden chunk "'.$file.'"', array('app' => 'core'));
197 197
 					} catch (\OCP\Files\LockNotAcquiredException $e) {
198
-						\OC::$server->getLogger()->debug('Could not cleanup locked chunk "' . $file . '"', array('app' => 'core'));
198
+						\OC::$server->getLogger()->debug('Could not cleanup locked chunk "'.$file.'"', array('app' => 'core'));
199 199
 					}
200 200
 				}
201 201
 			}
Please login to merge, or discard this patch.
Indentation   +157 added lines, -157 removed lines patch added patch discarded remove patch
@@ -35,170 +35,170 @@
 block discarded – undo
35 35
 
36 36
 class File implements ICache {
37 37
 
38
-	/** @var View */
39
-	protected $storage;
38
+    /** @var View */
39
+    protected $storage;
40 40
 
41
-	/**
42
-	 * Returns the cache storage for the logged in user
43
-	 *
44
-	 * @return \OC\Files\View cache storage
45
-	 * @throws \OC\ForbiddenException
46
-	 * @throws \OC\User\NoUserException
47
-	 */
48
-	protected function getStorage() {
49
-		if (isset($this->storage)) {
50
-			return $this->storage;
51
-		}
52
-		if (\OC::$server->getUserSession()->isLoggedIn()) {
53
-			$rootView = new View();
54
-			$user = \OC::$server->getUserSession()->getUser();
55
-			Filesystem::initMountPoints($user->getUID());
56
-			if (!$rootView->file_exists('/' . $user->getUID() . '/cache')) {
57
-				$rootView->mkdir('/' . $user->getUID() . '/cache');
58
-			}
59
-			$this->storage = new View('/' . $user->getUID() . '/cache');
60
-			return $this->storage;
61
-		} else {
62
-			\OCP\Util::writeLog('core', 'Can\'t get cache storage, user not logged in', ILogger::ERROR);
63
-			throw new \OC\ForbiddenException('Can\t get cache storage, user not logged in');
64
-		}
65
-	}
41
+    /**
42
+     * Returns the cache storage for the logged in user
43
+     *
44
+     * @return \OC\Files\View cache storage
45
+     * @throws \OC\ForbiddenException
46
+     * @throws \OC\User\NoUserException
47
+     */
48
+    protected function getStorage() {
49
+        if (isset($this->storage)) {
50
+            return $this->storage;
51
+        }
52
+        if (\OC::$server->getUserSession()->isLoggedIn()) {
53
+            $rootView = new View();
54
+            $user = \OC::$server->getUserSession()->getUser();
55
+            Filesystem::initMountPoints($user->getUID());
56
+            if (!$rootView->file_exists('/' . $user->getUID() . '/cache')) {
57
+                $rootView->mkdir('/' . $user->getUID() . '/cache');
58
+            }
59
+            $this->storage = new View('/' . $user->getUID() . '/cache');
60
+            return $this->storage;
61
+        } else {
62
+            \OCP\Util::writeLog('core', 'Can\'t get cache storage, user not logged in', ILogger::ERROR);
63
+            throw new \OC\ForbiddenException('Can\t get cache storage, user not logged in');
64
+        }
65
+    }
66 66
 
67
-	/**
68
-	 * @param string $key
69
-	 * @return mixed|null
70
-	 * @throws \OC\ForbiddenException
71
-	 */
72
-	public function get($key) {
73
-		$result = null;
74
-		if ($this->hasKey($key)) {
75
-			$storage = $this->getStorage();
76
-			$result = $storage->file_get_contents($key);
77
-		}
78
-		return $result;
79
-	}
67
+    /**
68
+     * @param string $key
69
+     * @return mixed|null
70
+     * @throws \OC\ForbiddenException
71
+     */
72
+    public function get($key) {
73
+        $result = null;
74
+        if ($this->hasKey($key)) {
75
+            $storage = $this->getStorage();
76
+            $result = $storage->file_get_contents($key);
77
+        }
78
+        return $result;
79
+    }
80 80
 
81
-	/**
82
-	 * Returns the size of the stored/cached data
83
-	 *
84
-	 * @param string $key
85
-	 * @return int
86
-	 */
87
-	public function size($key) {
88
-		$result = 0;
89
-		if ($this->hasKey($key)) {
90
-			$storage = $this->getStorage();
91
-			$result = $storage->filesize($key);
92
-		}
93
-		return $result;
94
-	}
81
+    /**
82
+     * Returns the size of the stored/cached data
83
+     *
84
+     * @param string $key
85
+     * @return int
86
+     */
87
+    public function size($key) {
88
+        $result = 0;
89
+        if ($this->hasKey($key)) {
90
+            $storage = $this->getStorage();
91
+            $result = $storage->filesize($key);
92
+        }
93
+        return $result;
94
+    }
95 95
 
96
-	/**
97
-	 * @param string $key
98
-	 * @param mixed $value
99
-	 * @param int $ttl
100
-	 * @return bool|mixed
101
-	 * @throws \OC\ForbiddenException
102
-	 */
103
-	public function set($key, $value, $ttl = 0) {
104
-		$storage = $this->getStorage();
105
-		$result = false;
106
-		// unique id to avoid chunk collision, just in case
107
-		$uniqueId = \OC::$server->getSecureRandom()->generate(
108
-			16,
109
-			ISecureRandom::CHAR_DIGITS . ISecureRandom::CHAR_LOWER . ISecureRandom::CHAR_UPPER
110
-		);
96
+    /**
97
+     * @param string $key
98
+     * @param mixed $value
99
+     * @param int $ttl
100
+     * @return bool|mixed
101
+     * @throws \OC\ForbiddenException
102
+     */
103
+    public function set($key, $value, $ttl = 0) {
104
+        $storage = $this->getStorage();
105
+        $result = false;
106
+        // unique id to avoid chunk collision, just in case
107
+        $uniqueId = \OC::$server->getSecureRandom()->generate(
108
+            16,
109
+            ISecureRandom::CHAR_DIGITS . ISecureRandom::CHAR_LOWER . ISecureRandom::CHAR_UPPER
110
+        );
111 111
 
112
-		// use part file to prevent hasKey() to find the key
113
-		// while it is being written
114
-		$keyPart = $key . '.' . $uniqueId . '.part';
115
-		if ($storage and $storage->file_put_contents($keyPart, $value)) {
116
-			if ($ttl === 0) {
117
-				$ttl = 86400; // 60*60*24
118
-			}
119
-			$result = $storage->touch($keyPart, time() + $ttl);
120
-			$result &= $storage->rename($keyPart, $key);
121
-		}
122
-		return $result;
123
-	}
112
+        // use part file to prevent hasKey() to find the key
113
+        // while it is being written
114
+        $keyPart = $key . '.' . $uniqueId . '.part';
115
+        if ($storage and $storage->file_put_contents($keyPart, $value)) {
116
+            if ($ttl === 0) {
117
+                $ttl = 86400; // 60*60*24
118
+            }
119
+            $result = $storage->touch($keyPart, time() + $ttl);
120
+            $result &= $storage->rename($keyPart, $key);
121
+        }
122
+        return $result;
123
+    }
124 124
 
125
-	/**
126
-	 * @param string $key
127
-	 * @return bool
128
-	 * @throws \OC\ForbiddenException
129
-	 */
130
-	public function hasKey($key) {
131
-		$storage = $this->getStorage();
132
-		if ($storage && $storage->is_file($key) && $storage->isReadable($key)) {
133
-			return true;
134
-		}
135
-		return false;
136
-	}
125
+    /**
126
+     * @param string $key
127
+     * @return bool
128
+     * @throws \OC\ForbiddenException
129
+     */
130
+    public function hasKey($key) {
131
+        $storage = $this->getStorage();
132
+        if ($storage && $storage->is_file($key) && $storage->isReadable($key)) {
133
+            return true;
134
+        }
135
+        return false;
136
+    }
137 137
 
138
-	/**
139
-	 * @param string $key
140
-	 * @return bool|mixed
141
-	 * @throws \OC\ForbiddenException
142
-	 */
143
-	public function remove($key) {
144
-		$storage = $this->getStorage();
145
-		if (!$storage) {
146
-			return false;
147
-		}
148
-		return $storage->unlink($key);
149
-	}
138
+    /**
139
+     * @param string $key
140
+     * @return bool|mixed
141
+     * @throws \OC\ForbiddenException
142
+     */
143
+    public function remove($key) {
144
+        $storage = $this->getStorage();
145
+        if (!$storage) {
146
+            return false;
147
+        }
148
+        return $storage->unlink($key);
149
+    }
150 150
 
151
-	/**
152
-	 * @param string $prefix
153
-	 * @return bool
154
-	 * @throws \OC\ForbiddenException
155
-	 */
156
-	public function clear($prefix = '') {
157
-		$storage = $this->getStorage();
158
-		if ($storage and $storage->is_dir('/')) {
159
-			$dh = $storage->opendir('/');
160
-			if (is_resource($dh)) {
161
-				while (($file = readdir($dh)) !== false) {
162
-					if ($file != '.' and $file != '..' and ($prefix === '' || strpos($file, $prefix) === 0)) {
163
-						$storage->unlink('/' . $file);
164
-					}
165
-				}
166
-			}
167
-		}
168
-		return true;
169
-	}
151
+    /**
152
+     * @param string $prefix
153
+     * @return bool
154
+     * @throws \OC\ForbiddenException
155
+     */
156
+    public function clear($prefix = '') {
157
+        $storage = $this->getStorage();
158
+        if ($storage and $storage->is_dir('/')) {
159
+            $dh = $storage->opendir('/');
160
+            if (is_resource($dh)) {
161
+                while (($file = readdir($dh)) !== false) {
162
+                    if ($file != '.' and $file != '..' and ($prefix === '' || strpos($file, $prefix) === 0)) {
163
+                        $storage->unlink('/' . $file);
164
+                    }
165
+                }
166
+            }
167
+        }
168
+        return true;
169
+    }
170 170
 
171
-	/**
172
-	 * Runs GC
173
-	 * @throws \OC\ForbiddenException
174
-	 */
175
-	public function gc() {
176
-		$storage = $this->getStorage();
177
-		if ($storage) {
178
-			// extra hour safety, in case of stray part chunks that take longer to write,
179
-			// because touch() is only called after the chunk was finished
180
-			$now = time() - 3600;
181
-			$dh = $storage->opendir('/');
182
-			if (!is_resource($dh)) {
183
-				return null;
184
-			}
185
-			while (($file = readdir($dh)) !== false) {
186
-				if ($file != '.' and $file != '..') {
187
-					try {
188
-						$mtime = $storage->filemtime('/' . $file);
189
-						if ($mtime < $now) {
190
-							$storage->unlink('/' . $file);
191
-						}
192
-					} catch (\OCP\Lock\LockedException $e) {
193
-						// ignore locked chunks
194
-						\OC::$server->getLogger()->debug('Could not cleanup locked chunk "' . $file . '"', array('app' => 'core'));
195
-					} catch (\OCP\Files\ForbiddenException $e) {
196
-						\OC::$server->getLogger()->debug('Could not cleanup forbidden chunk "' . $file . '"', array('app' => 'core'));
197
-					} catch (\OCP\Files\LockNotAcquiredException $e) {
198
-						\OC::$server->getLogger()->debug('Could not cleanup locked chunk "' . $file . '"', array('app' => 'core'));
199
-					}
200
-				}
201
-			}
202
-		}
203
-	}
171
+    /**
172
+     * Runs GC
173
+     * @throws \OC\ForbiddenException
174
+     */
175
+    public function gc() {
176
+        $storage = $this->getStorage();
177
+        if ($storage) {
178
+            // extra hour safety, in case of stray part chunks that take longer to write,
179
+            // because touch() is only called after the chunk was finished
180
+            $now = time() - 3600;
181
+            $dh = $storage->opendir('/');
182
+            if (!is_resource($dh)) {
183
+                return null;
184
+            }
185
+            while (($file = readdir($dh)) !== false) {
186
+                if ($file != '.' and $file != '..') {
187
+                    try {
188
+                        $mtime = $storage->filemtime('/' . $file);
189
+                        if ($mtime < $now) {
190
+                            $storage->unlink('/' . $file);
191
+                        }
192
+                    } catch (\OCP\Lock\LockedException $e) {
193
+                        // ignore locked chunks
194
+                        \OC::$server->getLogger()->debug('Could not cleanup locked chunk "' . $file . '"', array('app' => 'core'));
195
+                    } catch (\OCP\Files\ForbiddenException $e) {
196
+                        \OC::$server->getLogger()->debug('Could not cleanup forbidden chunk "' . $file . '"', array('app' => 'core'));
197
+                    } catch (\OCP\Files\LockNotAcquiredException $e) {
198
+                        \OC::$server->getLogger()->debug('Could not cleanup locked chunk "' . $file . '"', array('app' => 'core'));
199
+                    }
200
+                }
201
+            }
202
+        }
203
+    }
204 204
 }
Please login to merge, or discard this patch.
core/Controller/LostController.php 3 patches
Doc Comments   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -132,7 +132,7 @@
 block discarded – undo
132 132
 	}
133 133
 
134 134
 	/**
135
-	 * @param $message
135
+	 * @param string $message
136 136
 	 * @param array $additional
137 137
 	 * @return array
138 138
 	 */
Please login to merge, or discard this patch.
Indentation   +329 added lines, -329 removed lines patch added patch discarded remove patch
@@ -58,333 +58,333 @@
 block discarded – undo
58 58
  */
59 59
 class LostController extends Controller {
60 60
 
61
-	/** @var IURLGenerator */
62
-	protected $urlGenerator;
63
-	/** @var IUserManager */
64
-	protected $userManager;
65
-	/** @var Defaults */
66
-	protected $defaults;
67
-	/** @var IL10N */
68
-	protected $l10n;
69
-	/** @var string */
70
-	protected $from;
71
-	/** @var IManager */
72
-	protected $encryptionManager;
73
-	/** @var IConfig */
74
-	protected $config;
75
-	/** @var ISecureRandom */
76
-	protected $secureRandom;
77
-	/** @var IMailer */
78
-	protected $mailer;
79
-	/** @var ITimeFactory */
80
-	protected $timeFactory;
81
-	/** @var ICrypto */
82
-	protected $crypto;
83
-
84
-	/**
85
-	 * @param string $appName
86
-	 * @param IRequest $request
87
-	 * @param IURLGenerator $urlGenerator
88
-	 * @param IUserManager $userManager
89
-	 * @param Defaults $defaults
90
-	 * @param IL10N $l10n
91
-	 * @param IConfig $config
92
-	 * @param ISecureRandom $secureRandom
93
-	 * @param string $defaultMailAddress
94
-	 * @param IManager $encryptionManager
95
-	 * @param IMailer $mailer
96
-	 * @param ITimeFactory $timeFactory
97
-	 * @param ICrypto $crypto
98
-	 */
99
-	public function __construct($appName,
100
-								IRequest $request,
101
-								IURLGenerator $urlGenerator,
102
-								IUserManager $userManager,
103
-								Defaults $defaults,
104
-								IL10N $l10n,
105
-								IConfig $config,
106
-								ISecureRandom $secureRandom,
107
-								$defaultMailAddress,
108
-								IManager $encryptionManager,
109
-								IMailer $mailer,
110
-								ITimeFactory $timeFactory,
111
-								ICrypto $crypto) {
112
-		parent::__construct($appName, $request);
113
-		$this->urlGenerator = $urlGenerator;
114
-		$this->userManager = $userManager;
115
-		$this->defaults = $defaults;
116
-		$this->l10n = $l10n;
117
-		$this->secureRandom = $secureRandom;
118
-		$this->from = $defaultMailAddress;
119
-		$this->encryptionManager = $encryptionManager;
120
-		$this->config = $config;
121
-		$this->mailer = $mailer;
122
-		$this->timeFactory = $timeFactory;
123
-		$this->crypto = $crypto;
124
-	}
125
-
126
-	/**
127
-	 * Someone wants to reset their password:
128
-	 *
129
-	 * @PublicPage
130
-	 * @NoCSRFRequired
131
-	 *
132
-	 * @param string $token
133
-	 * @param string $userId
134
-	 * @return TemplateResponse
135
-	 */
136
-	public function resetform($token, $userId) {
137
-		if ($this->config->getSystemValue('lost_password_link', '') !== '') {
138
-			return new TemplateResponse('core', 'error', [
139
-					'errors' => [['error' => $this->l10n->t('Password reset is disabled')]]
140
-				],
141
-				'guest'
142
-			);
143
-		}
144
-
145
-		try {
146
-			$this->checkPasswordResetToken($token, $userId);
147
-		} catch (\Exception $e) {
148
-			return new TemplateResponse(
149
-				'core', 'error', [
150
-					"errors" => array(array("error" => $e->getMessage()))
151
-				],
152
-				'guest'
153
-			);
154
-		}
155
-
156
-		return new TemplateResponse(
157
-			'core',
158
-			'lostpassword/resetpassword',
159
-			array(
160
-				'link' => $this->urlGenerator->linkToRouteAbsolute('core.lost.setPassword', array('userId' => $userId, 'token' => $token)),
161
-			),
162
-			'guest'
163
-		);
164
-	}
165
-
166
-	/**
167
-	 * @param string $token
168
-	 * @param string $userId
169
-	 * @throws \Exception
170
-	 */
171
-	protected function checkPasswordResetToken($token, $userId) {
172
-		$user = $this->userManager->get($userId);
173
-		if($user === null || !$user->isEnabled()) {
174
-			throw new \Exception($this->l10n->t('Couldn\'t reset password because the token is invalid'));
175
-		}
176
-
177
-		try {
178
-			$encryptedToken = $this->config->getUserValue($userId, 'core', 'lostpassword', null);
179
-			$mailAddress = !is_null($user->getEMailAddress()) ? $user->getEMailAddress() : '';
180
-			$decryptedToken = $this->crypto->decrypt($encryptedToken, $mailAddress.$this->config->getSystemValue('secret'));
181
-		} catch (\Exception $e) {
182
-			throw new \Exception($this->l10n->t('Couldn\'t reset password because the token is invalid'));
183
-		}
184
-
185
-		$splittedToken = explode(':', $decryptedToken);
186
-		if(count($splittedToken) !== 2) {
187
-			throw new \Exception($this->l10n->t('Couldn\'t reset password because the token is invalid'));
188
-		}
189
-
190
-		if ($splittedToken[0] < ($this->timeFactory->getTime() - 60*60*24*7) ||
191
-			$user->getLastLogin() > $splittedToken[0]) {
192
-			throw new \Exception($this->l10n->t('Couldn\'t reset password because the token is expired'));
193
-		}
194
-
195
-		if (!hash_equals($splittedToken[1], $token)) {
196
-			throw new \Exception($this->l10n->t('Couldn\'t reset password because the token is invalid'));
197
-		}
198
-	}
199
-
200
-	/**
201
-	 * @param $message
202
-	 * @param array $additional
203
-	 * @return array
204
-	 */
205
-	private function error($message, array $additional=array()) {
206
-		return array_merge(array('status' => 'error', 'msg' => $message), $additional);
207
-	}
208
-
209
-	/**
210
-	 * @param array $data
211
-	 * @return array
212
-	 */
213
-	private function success($data = []) {
214
-		return array_merge($data, ['status'=>'success']);
215
-	}
216
-
217
-	/**
218
-	 * @PublicPage
219
-	 * @BruteForceProtection(action=passwordResetEmail)
220
-	 * @AnonRateThrottle(limit=10, period=300)
221
-	 *
222
-	 * @param string $user
223
-	 * @return JSONResponse
224
-	 */
225
-	public function email($user){
226
-		if ($this->config->getSystemValue('lost_password_link', '') !== '') {
227
-			return new JSONResponse($this->error($this->l10n->t('Password reset is disabled')));
228
-		}
229
-
230
-		\OCP\Util::emitHook(
231
-			'\OCA\Files_Sharing\API\Server2Server',
232
-			'preLoginNameUsedAsUserName',
233
-			['uid' => &$user]
234
-		);
235
-
236
-		// FIXME: use HTTP error codes
237
-		try {
238
-			$this->sendEmail($user);
239
-		} catch (\Exception $e){
240
-			$response = new JSONResponse($this->error($e->getMessage()));
241
-			$response->throttle();
242
-			return $response;
243
-		}
244
-
245
-		$response = new JSONResponse($this->success());
246
-		$response->throttle();
247
-		return $response;
248
-	}
249
-
250
-	/**
251
-	 * @PublicPage
252
-	 * @param string $token
253
-	 * @param string $userId
254
-	 * @param string $password
255
-	 * @param boolean $proceed
256
-	 * @return array
257
-	 */
258
-	public function setPassword($token, $userId, $password, $proceed) {
259
-		if ($this->config->getSystemValue('lost_password_link', '') !== '') {
260
-			return $this->error($this->l10n->t('Password reset is disabled'));
261
-		}
262
-
263
-		if ($this->encryptionManager->isEnabled() && !$proceed) {
264
-			$encryptionModules = $this->encryptionManager->getEncryptionModules();
265
-			foreach ($encryptionModules as $module) {
266
-				/** @var IEncryptionModule $instance */
267
-				$instance = call_user_func($module['callback']);
268
-				// this way we can find out whether per-user keys are used or a system wide encryption key
269
-				if ($instance->needDetailedAccessList()) {
270
-					return $this->error('', array('encryption' => true));
271
-				}
272
-			}
273
-		}
274
-
275
-		try {
276
-			$this->checkPasswordResetToken($token, $userId);
277
-			$user = $this->userManager->get($userId);
278
-
279
-			\OC_Hook::emit('\OC\Core\LostPassword\Controller\LostController', 'pre_passwordReset', array('uid' => $userId, 'password' => $password));
280
-
281
-			if (!$user->setPassword($password)) {
282
-				throw new \Exception();
283
-			}
284
-
285
-			\OC_Hook::emit('\OC\Core\LostPassword\Controller\LostController', 'post_passwordReset', array('uid' => $userId, 'password' => $password));
286
-
287
-			$this->config->deleteUserValue($userId, 'core', 'lostpassword');
288
-			@\OC::$server->getUserSession()->unsetMagicInCookie();
289
-		} catch (HintException $e){
290
-			return $this->error($e->getHint());
291
-		} catch (\Exception $e){
292
-			return $this->error($e->getMessage());
293
-		}
294
-
295
-		return $this->success(['user' => $userId]);
296
-	}
297
-
298
-	/**
299
-	 * @param string $input
300
-	 * @throws \Exception
301
-	 */
302
-	protected function sendEmail($input) {
303
-		$user = $this->findUserByIdOrMail($input);
304
-		$email = $user->getEMailAddress();
305
-
306
-		if (empty($email)) {
307
-			throw new \Exception(
308
-				$this->l10n->t('Could not send reset email because there is no email address for this username. Please contact your administrator.')
309
-			);
310
-		}
311
-
312
-		// Generate the token. It is stored encrypted in the database with the
313
-		// secret being the users' email address appended with the system secret.
314
-		// This makes the token automatically invalidate once the user changes
315
-		// their email address.
316
-		$token = $this->secureRandom->generate(
317
-			21,
318
-			ISecureRandom::CHAR_DIGITS.
319
-			ISecureRandom::CHAR_LOWER.
320
-			ISecureRandom::CHAR_UPPER
321
-		);
322
-		$tokenValue = $this->timeFactory->getTime() .':'. $token;
323
-		$encryptedValue = $this->crypto->encrypt($tokenValue, $email . $this->config->getSystemValue('secret'));
324
-		$this->config->setUserValue($user->getUID(), 'core', 'lostpassword', $encryptedValue);
325
-
326
-		$link = $this->urlGenerator->linkToRouteAbsolute('core.lost.resetform', array('userId' => $user->getUID(), 'token' => $token));
327
-
328
-		$emailTemplate = $this->mailer->createEMailTemplate('core.ResetPassword', [
329
-			'link' => $link,
330
-		]);
331
-
332
-		$emailTemplate->setSubject($this->l10n->t('%s password reset', [$this->defaults->getName()]));
333
-		$emailTemplate->addHeader();
334
-		$emailTemplate->addHeading($this->l10n->t('Password reset'));
335
-
336
-		$emailTemplate->addBodyText(
337
-			htmlspecialchars($this->l10n->t('Click the following button to reset your password. If you have not requested the password reset, then ignore this email.')),
338
-			$this->l10n->t('Click the following link to reset your password. If you have not requested the password reset, then ignore this email.')
339
-		);
340
-
341
-		$emailTemplate->addBodyButton(
342
-			htmlspecialchars($this->l10n->t('Reset your password')),
343
-			$link,
344
-			false
345
-		);
346
-		$emailTemplate->addFooter();
347
-
348
-		try {
349
-			$message = $this->mailer->createMessage();
350
-			$message->setTo([$email => $user->getUID()]);
351
-			$message->setFrom([$this->from => $this->defaults->getName()]);
352
-			$message->useTemplate($emailTemplate);
353
-			$this->mailer->send($message);
354
-		} catch (\Exception $e) {
355
-			throw new \Exception($this->l10n->t(
356
-				'Couldn\'t send reset email. Please contact your administrator.'
357
-			));
358
-		}
359
-	}
360
-
361
-	/**
362
-	 * @param string $input
363
-	 * @return IUser
364
-	 * @throws \InvalidArgumentException
365
-	 */
366
-	protected function findUserByIdOrMail($input) {
367
-		$userNotFound = new \InvalidArgumentException(
368
-			$this->l10n->t('Couldn\'t send reset email. Please make sure your username is correct.')
369
-		);
370
-
371
-		$user = $this->userManager->get($input);
372
-		if ($user instanceof IUser) {
373
-			if (!$user->isEnabled()) {
374
-				throw $userNotFound;
375
-			}
376
-
377
-			return $user;
378
-		}
379
-
380
-		$users = \array_filter($this->userManager->getByEmail($input), function (IUser $user) {
381
-			return $user->isEnabled();
382
-		});
383
-
384
-		if (\count($users) === 1) {
385
-			return $users[0];
386
-		}
387
-
388
-		throw $userNotFound;
389
-	}
61
+    /** @var IURLGenerator */
62
+    protected $urlGenerator;
63
+    /** @var IUserManager */
64
+    protected $userManager;
65
+    /** @var Defaults */
66
+    protected $defaults;
67
+    /** @var IL10N */
68
+    protected $l10n;
69
+    /** @var string */
70
+    protected $from;
71
+    /** @var IManager */
72
+    protected $encryptionManager;
73
+    /** @var IConfig */
74
+    protected $config;
75
+    /** @var ISecureRandom */
76
+    protected $secureRandom;
77
+    /** @var IMailer */
78
+    protected $mailer;
79
+    /** @var ITimeFactory */
80
+    protected $timeFactory;
81
+    /** @var ICrypto */
82
+    protected $crypto;
83
+
84
+    /**
85
+     * @param string $appName
86
+     * @param IRequest $request
87
+     * @param IURLGenerator $urlGenerator
88
+     * @param IUserManager $userManager
89
+     * @param Defaults $defaults
90
+     * @param IL10N $l10n
91
+     * @param IConfig $config
92
+     * @param ISecureRandom $secureRandom
93
+     * @param string $defaultMailAddress
94
+     * @param IManager $encryptionManager
95
+     * @param IMailer $mailer
96
+     * @param ITimeFactory $timeFactory
97
+     * @param ICrypto $crypto
98
+     */
99
+    public function __construct($appName,
100
+                                IRequest $request,
101
+                                IURLGenerator $urlGenerator,
102
+                                IUserManager $userManager,
103
+                                Defaults $defaults,
104
+                                IL10N $l10n,
105
+                                IConfig $config,
106
+                                ISecureRandom $secureRandom,
107
+                                $defaultMailAddress,
108
+                                IManager $encryptionManager,
109
+                                IMailer $mailer,
110
+                                ITimeFactory $timeFactory,
111
+                                ICrypto $crypto) {
112
+        parent::__construct($appName, $request);
113
+        $this->urlGenerator = $urlGenerator;
114
+        $this->userManager = $userManager;
115
+        $this->defaults = $defaults;
116
+        $this->l10n = $l10n;
117
+        $this->secureRandom = $secureRandom;
118
+        $this->from = $defaultMailAddress;
119
+        $this->encryptionManager = $encryptionManager;
120
+        $this->config = $config;
121
+        $this->mailer = $mailer;
122
+        $this->timeFactory = $timeFactory;
123
+        $this->crypto = $crypto;
124
+    }
125
+
126
+    /**
127
+     * Someone wants to reset their password:
128
+     *
129
+     * @PublicPage
130
+     * @NoCSRFRequired
131
+     *
132
+     * @param string $token
133
+     * @param string $userId
134
+     * @return TemplateResponse
135
+     */
136
+    public function resetform($token, $userId) {
137
+        if ($this->config->getSystemValue('lost_password_link', '') !== '') {
138
+            return new TemplateResponse('core', 'error', [
139
+                    'errors' => [['error' => $this->l10n->t('Password reset is disabled')]]
140
+                ],
141
+                'guest'
142
+            );
143
+        }
144
+
145
+        try {
146
+            $this->checkPasswordResetToken($token, $userId);
147
+        } catch (\Exception $e) {
148
+            return new TemplateResponse(
149
+                'core', 'error', [
150
+                    "errors" => array(array("error" => $e->getMessage()))
151
+                ],
152
+                'guest'
153
+            );
154
+        }
155
+
156
+        return new TemplateResponse(
157
+            'core',
158
+            'lostpassword/resetpassword',
159
+            array(
160
+                'link' => $this->urlGenerator->linkToRouteAbsolute('core.lost.setPassword', array('userId' => $userId, 'token' => $token)),
161
+            ),
162
+            'guest'
163
+        );
164
+    }
165
+
166
+    /**
167
+     * @param string $token
168
+     * @param string $userId
169
+     * @throws \Exception
170
+     */
171
+    protected function checkPasswordResetToken($token, $userId) {
172
+        $user = $this->userManager->get($userId);
173
+        if($user === null || !$user->isEnabled()) {
174
+            throw new \Exception($this->l10n->t('Couldn\'t reset password because the token is invalid'));
175
+        }
176
+
177
+        try {
178
+            $encryptedToken = $this->config->getUserValue($userId, 'core', 'lostpassword', null);
179
+            $mailAddress = !is_null($user->getEMailAddress()) ? $user->getEMailAddress() : '';
180
+            $decryptedToken = $this->crypto->decrypt($encryptedToken, $mailAddress.$this->config->getSystemValue('secret'));
181
+        } catch (\Exception $e) {
182
+            throw new \Exception($this->l10n->t('Couldn\'t reset password because the token is invalid'));
183
+        }
184
+
185
+        $splittedToken = explode(':', $decryptedToken);
186
+        if(count($splittedToken) !== 2) {
187
+            throw new \Exception($this->l10n->t('Couldn\'t reset password because the token is invalid'));
188
+        }
189
+
190
+        if ($splittedToken[0] < ($this->timeFactory->getTime() - 60*60*24*7) ||
191
+            $user->getLastLogin() > $splittedToken[0]) {
192
+            throw new \Exception($this->l10n->t('Couldn\'t reset password because the token is expired'));
193
+        }
194
+
195
+        if (!hash_equals($splittedToken[1], $token)) {
196
+            throw new \Exception($this->l10n->t('Couldn\'t reset password because the token is invalid'));
197
+        }
198
+    }
199
+
200
+    /**
201
+     * @param $message
202
+     * @param array $additional
203
+     * @return array
204
+     */
205
+    private function error($message, array $additional=array()) {
206
+        return array_merge(array('status' => 'error', 'msg' => $message), $additional);
207
+    }
208
+
209
+    /**
210
+     * @param array $data
211
+     * @return array
212
+     */
213
+    private function success($data = []) {
214
+        return array_merge($data, ['status'=>'success']);
215
+    }
216
+
217
+    /**
218
+     * @PublicPage
219
+     * @BruteForceProtection(action=passwordResetEmail)
220
+     * @AnonRateThrottle(limit=10, period=300)
221
+     *
222
+     * @param string $user
223
+     * @return JSONResponse
224
+     */
225
+    public function email($user){
226
+        if ($this->config->getSystemValue('lost_password_link', '') !== '') {
227
+            return new JSONResponse($this->error($this->l10n->t('Password reset is disabled')));
228
+        }
229
+
230
+        \OCP\Util::emitHook(
231
+            '\OCA\Files_Sharing\API\Server2Server',
232
+            'preLoginNameUsedAsUserName',
233
+            ['uid' => &$user]
234
+        );
235
+
236
+        // FIXME: use HTTP error codes
237
+        try {
238
+            $this->sendEmail($user);
239
+        } catch (\Exception $e){
240
+            $response = new JSONResponse($this->error($e->getMessage()));
241
+            $response->throttle();
242
+            return $response;
243
+        }
244
+
245
+        $response = new JSONResponse($this->success());
246
+        $response->throttle();
247
+        return $response;
248
+    }
249
+
250
+    /**
251
+     * @PublicPage
252
+     * @param string $token
253
+     * @param string $userId
254
+     * @param string $password
255
+     * @param boolean $proceed
256
+     * @return array
257
+     */
258
+    public function setPassword($token, $userId, $password, $proceed) {
259
+        if ($this->config->getSystemValue('lost_password_link', '') !== '') {
260
+            return $this->error($this->l10n->t('Password reset is disabled'));
261
+        }
262
+
263
+        if ($this->encryptionManager->isEnabled() && !$proceed) {
264
+            $encryptionModules = $this->encryptionManager->getEncryptionModules();
265
+            foreach ($encryptionModules as $module) {
266
+                /** @var IEncryptionModule $instance */
267
+                $instance = call_user_func($module['callback']);
268
+                // this way we can find out whether per-user keys are used or a system wide encryption key
269
+                if ($instance->needDetailedAccessList()) {
270
+                    return $this->error('', array('encryption' => true));
271
+                }
272
+            }
273
+        }
274
+
275
+        try {
276
+            $this->checkPasswordResetToken($token, $userId);
277
+            $user = $this->userManager->get($userId);
278
+
279
+            \OC_Hook::emit('\OC\Core\LostPassword\Controller\LostController', 'pre_passwordReset', array('uid' => $userId, 'password' => $password));
280
+
281
+            if (!$user->setPassword($password)) {
282
+                throw new \Exception();
283
+            }
284
+
285
+            \OC_Hook::emit('\OC\Core\LostPassword\Controller\LostController', 'post_passwordReset', array('uid' => $userId, 'password' => $password));
286
+
287
+            $this->config->deleteUserValue($userId, 'core', 'lostpassword');
288
+            @\OC::$server->getUserSession()->unsetMagicInCookie();
289
+        } catch (HintException $e){
290
+            return $this->error($e->getHint());
291
+        } catch (\Exception $e){
292
+            return $this->error($e->getMessage());
293
+        }
294
+
295
+        return $this->success(['user' => $userId]);
296
+    }
297
+
298
+    /**
299
+     * @param string $input
300
+     * @throws \Exception
301
+     */
302
+    protected function sendEmail($input) {
303
+        $user = $this->findUserByIdOrMail($input);
304
+        $email = $user->getEMailAddress();
305
+
306
+        if (empty($email)) {
307
+            throw new \Exception(
308
+                $this->l10n->t('Could not send reset email because there is no email address for this username. Please contact your administrator.')
309
+            );
310
+        }
311
+
312
+        // Generate the token. It is stored encrypted in the database with the
313
+        // secret being the users' email address appended with the system secret.
314
+        // This makes the token automatically invalidate once the user changes
315
+        // their email address.
316
+        $token = $this->secureRandom->generate(
317
+            21,
318
+            ISecureRandom::CHAR_DIGITS.
319
+            ISecureRandom::CHAR_LOWER.
320
+            ISecureRandom::CHAR_UPPER
321
+        );
322
+        $tokenValue = $this->timeFactory->getTime() .':'. $token;
323
+        $encryptedValue = $this->crypto->encrypt($tokenValue, $email . $this->config->getSystemValue('secret'));
324
+        $this->config->setUserValue($user->getUID(), 'core', 'lostpassword', $encryptedValue);
325
+
326
+        $link = $this->urlGenerator->linkToRouteAbsolute('core.lost.resetform', array('userId' => $user->getUID(), 'token' => $token));
327
+
328
+        $emailTemplate = $this->mailer->createEMailTemplate('core.ResetPassword', [
329
+            'link' => $link,
330
+        ]);
331
+
332
+        $emailTemplate->setSubject($this->l10n->t('%s password reset', [$this->defaults->getName()]));
333
+        $emailTemplate->addHeader();
334
+        $emailTemplate->addHeading($this->l10n->t('Password reset'));
335
+
336
+        $emailTemplate->addBodyText(
337
+            htmlspecialchars($this->l10n->t('Click the following button to reset your password. If you have not requested the password reset, then ignore this email.')),
338
+            $this->l10n->t('Click the following link to reset your password. If you have not requested the password reset, then ignore this email.')
339
+        );
340
+
341
+        $emailTemplate->addBodyButton(
342
+            htmlspecialchars($this->l10n->t('Reset your password')),
343
+            $link,
344
+            false
345
+        );
346
+        $emailTemplate->addFooter();
347
+
348
+        try {
349
+            $message = $this->mailer->createMessage();
350
+            $message->setTo([$email => $user->getUID()]);
351
+            $message->setFrom([$this->from => $this->defaults->getName()]);
352
+            $message->useTemplate($emailTemplate);
353
+            $this->mailer->send($message);
354
+        } catch (\Exception $e) {
355
+            throw new \Exception($this->l10n->t(
356
+                'Couldn\'t send reset email. Please contact your administrator.'
357
+            ));
358
+        }
359
+    }
360
+
361
+    /**
362
+     * @param string $input
363
+     * @return IUser
364
+     * @throws \InvalidArgumentException
365
+     */
366
+    protected function findUserByIdOrMail($input) {
367
+        $userNotFound = new \InvalidArgumentException(
368
+            $this->l10n->t('Couldn\'t send reset email. Please make sure your username is correct.')
369
+        );
370
+
371
+        $user = $this->userManager->get($input);
372
+        if ($user instanceof IUser) {
373
+            if (!$user->isEnabled()) {
374
+                throw $userNotFound;
375
+            }
376
+
377
+            return $user;
378
+        }
379
+
380
+        $users = \array_filter($this->userManager->getByEmail($input), function (IUser $user) {
381
+            return $user->isEnabled();
382
+        });
383
+
384
+        if (\count($users) === 1) {
385
+            return $users[0];
386
+        }
387
+
388
+        throw $userNotFound;
389
+    }
390 390
 }
Please login to merge, or discard this patch.
Spacing   +11 added lines, -11 removed lines patch added patch discarded remove patch
@@ -170,7 +170,7 @@  discard block
 block discarded – undo
170 170
 	 */
171 171
 	protected function checkPasswordResetToken($token, $userId) {
172 172
 		$user = $this->userManager->get($userId);
173
-		if($user === null || !$user->isEnabled()) {
173
+		if ($user === null || !$user->isEnabled()) {
174 174
 			throw new \Exception($this->l10n->t('Couldn\'t reset password because the token is invalid'));
175 175
 		}
176 176
 
@@ -183,11 +183,11 @@  discard block
 block discarded – undo
183 183
 		}
184 184
 
185 185
 		$splittedToken = explode(':', $decryptedToken);
186
-		if(count($splittedToken) !== 2) {
186
+		if (count($splittedToken) !== 2) {
187 187
 			throw new \Exception($this->l10n->t('Couldn\'t reset password because the token is invalid'));
188 188
 		}
189 189
 
190
-		if ($splittedToken[0] < ($this->timeFactory->getTime() - 60*60*24*7) ||
190
+		if ($splittedToken[0] < ($this->timeFactory->getTime() - 60 * 60 * 24 * 7) ||
191 191
 			$user->getLastLogin() > $splittedToken[0]) {
192 192
 			throw new \Exception($this->l10n->t('Couldn\'t reset password because the token is expired'));
193 193
 		}
@@ -202,7 +202,7 @@  discard block
 block discarded – undo
202 202
 	 * @param array $additional
203 203
 	 * @return array
204 204
 	 */
205
-	private function error($message, array $additional=array()) {
205
+	private function error($message, array $additional = array()) {
206 206
 		return array_merge(array('status' => 'error', 'msg' => $message), $additional);
207 207
 	}
208 208
 
@@ -222,7 +222,7 @@  discard block
 block discarded – undo
222 222
 	 * @param string $user
223 223
 	 * @return JSONResponse
224 224
 	 */
225
-	public function email($user){
225
+	public function email($user) {
226 226
 		if ($this->config->getSystemValue('lost_password_link', '') !== '') {
227 227
 			return new JSONResponse($this->error($this->l10n->t('Password reset is disabled')));
228 228
 		}
@@ -236,7 +236,7 @@  discard block
 block discarded – undo
236 236
 		// FIXME: use HTTP error codes
237 237
 		try {
238 238
 			$this->sendEmail($user);
239
-		} catch (\Exception $e){
239
+		} catch (\Exception $e) {
240 240
 			$response = new JSONResponse($this->error($e->getMessage()));
241 241
 			$response->throttle();
242 242
 			return $response;
@@ -286,9 +286,9 @@  discard block
 block discarded – undo
286 286
 
287 287
 			$this->config->deleteUserValue($userId, 'core', 'lostpassword');
288 288
 			@\OC::$server->getUserSession()->unsetMagicInCookie();
289
-		} catch (HintException $e){
289
+		} catch (HintException $e) {
290 290
 			return $this->error($e->getHint());
291
-		} catch (\Exception $e){
291
+		} catch (\Exception $e) {
292 292
 			return $this->error($e->getMessage());
293 293
 		}
294 294
 
@@ -319,8 +319,8 @@  discard block
 block discarded – undo
319 319
 			ISecureRandom::CHAR_LOWER.
320 320
 			ISecureRandom::CHAR_UPPER
321 321
 		);
322
-		$tokenValue = $this->timeFactory->getTime() .':'. $token;
323
-		$encryptedValue = $this->crypto->encrypt($tokenValue, $email . $this->config->getSystemValue('secret'));
322
+		$tokenValue = $this->timeFactory->getTime().':'.$token;
323
+		$encryptedValue = $this->crypto->encrypt($tokenValue, $email.$this->config->getSystemValue('secret'));
324 324
 		$this->config->setUserValue($user->getUID(), 'core', 'lostpassword', $encryptedValue);
325 325
 
326 326
 		$link = $this->urlGenerator->linkToRouteAbsolute('core.lost.resetform', array('userId' => $user->getUID(), 'token' => $token));
@@ -377,7 +377,7 @@  discard block
 block discarded – undo
377 377
 			return $user;
378 378
 		}
379 379
 
380
-		$users = \array_filter($this->userManager->getByEmail($input), function (IUser $user) {
380
+		$users = \array_filter($this->userManager->getByEmail($input), function(IUser $user) {
381 381
 			return $user->isEnabled();
382 382
 		});
383 383
 
Please login to merge, or discard this patch.
lib/private/AppFramework/OCS/BaseResponse.php 3 patches
Doc Comments   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -24,7 +24,7 @@
 block discarded – undo
24 24
 	/**
25 25
 	 * BaseResponse constructor.
26 26
 	 *
27
-	 * @param DataResponse|null $dataResponse
27
+	 * @param DataResponse $dataResponse
28 28
 	 * @param string $format
29 29
 	 * @param string|null $statusMessage
30 30
 	 * @param int|null $itemsCount
Please login to merge, or discard this patch.
Spacing   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -26,7 +26,7 @@
 block discarded – undo
26 26
 use OCP\AppFramework\Http\EmptyContentSecurityPolicy;
27 27
 use OCP\AppFramework\Http\Response;
28 28
 
29
-abstract class BaseResponse extends Response   {
29
+abstract class BaseResponse extends Response {
30 30
 	/** @var array */
31 31
 	protected $data;
32 32
 
Please login to merge, or discard this patch.
Indentation   +117 added lines, -117 removed lines patch added patch discarded remove patch
@@ -28,121 +28,121 @@
 block discarded – undo
28 28
 use OCP\AppFramework\Http\Response;
29 29
 
30 30
 abstract class BaseResponse extends Response   {
31
-	/** @var array */
32
-	protected $data;
33
-
34
-	/** @var string */
35
-	protected $format;
36
-
37
-	/** @var string */
38
-	protected $statusMessage;
39
-
40
-	/** @var int */
41
-	protected $itemsCount;
42
-
43
-	/** @var int */
44
-	protected $itemsPerPage;
45
-
46
-	/**
47
-	 * BaseResponse constructor.
48
-	 *
49
-	 * @param DataResponse|null $dataResponse
50
-	 * @param string $format
51
-	 * @param string|null $statusMessage
52
-	 * @param int|null $itemsCount
53
-	 * @param int|null $itemsPerPage
54
-	 */
55
-	public function __construct(DataResponse $dataResponse,
56
-								$format = 'xml',
57
-								$statusMessage = null,
58
-								$itemsCount = null,
59
-								$itemsPerPage = null) {
60
-		$this->format = $format;
61
-		$this->statusMessage = $statusMessage;
62
-		$this->itemsCount = $itemsCount;
63
-		$this->itemsPerPage = $itemsPerPage;
64
-
65
-		$this->data = $dataResponse->getData();
66
-
67
-		$this->setHeaders($dataResponse->getHeaders());
68
-		$this->setStatus($dataResponse->getStatus());
69
-		$this->setETag($dataResponse->getETag());
70
-		$this->setLastModified($dataResponse->getLastModified());
71
-		$this->setCookies($dataResponse->getCookies());
72
-		$this->setContentSecurityPolicy(new EmptyContentSecurityPolicy());
73
-
74
-		if ($format === 'json') {
75
-			$this->addHeader(
76
-				'Content-Type', 'application/json; charset=utf-8'
77
-			);
78
-		} else {
79
-			$this->addHeader(
80
-				'Content-Type', 'application/xml; charset=utf-8'
81
-			);
82
-		}
83
-	}
84
-
85
-	/**
86
-	 * @param string[] $meta
87
-	 * @return string
88
-	 */
89
-	protected function renderResult(array $meta): string {
90
-		$status = $this->getStatus();
91
-		if ($status === Http::STATUS_NO_CONTENT ||
92
-			$status === Http::STATUS_NOT_MODIFIED ||
93
-			($status >= 100 && $status <= 199)) {
94
-			// Those status codes are not supposed to have a body:
95
-			// https://stackoverflow.com/q/8628725
96
-			return '';
97
-		}
98
-
99
-		$response = [
100
-			'ocs' => [
101
-				'meta' => $meta,
102
-				'data' => $this->data,
103
-			],
104
-		];
105
-
106
-		if ($this->format === 'json') {
107
-			return json_encode($response, JSON_HEX_TAG);
108
-		}
109
-
110
-		$writer = new \XMLWriter();
111
-		$writer->openMemory();
112
-		$writer->setIndent(true);
113
-		$writer->startDocument();
114
-		$this->toXML($response, $writer);
115
-		$writer->endDocument();
116
-		return $writer->outputMemory(true);
117
-
118
-	}
119
-
120
-	/**
121
-	 * @param array $array
122
-	 * @param \XMLWriter $writer
123
-	 */
124
-	protected function toXML(array $array, \XMLWriter $writer) {
125
-		foreach ($array as $k => $v) {
126
-			if ($k[0] === '@') {
127
-				$writer->writeAttribute(substr($k, 1), $v);
128
-				continue;
129
-			}
130
-
131
-			if (\is_numeric($k)) {
132
-				$k = 'element';
133
-			}
134
-
135
-			if (\is_array($v)) {
136
-				$writer->startElement($k);
137
-				$this->toXML($v, $writer);
138
-				$writer->endElement();
139
-			} else {
140
-				$writer->writeElement($k, $v);
141
-			}
142
-		}
143
-	}
144
-
145
-	public function getOCSStatus() {
146
-		return parent::getStatus();
147
-	}
31
+    /** @var array */
32
+    protected $data;
33
+
34
+    /** @var string */
35
+    protected $format;
36
+
37
+    /** @var string */
38
+    protected $statusMessage;
39
+
40
+    /** @var int */
41
+    protected $itemsCount;
42
+
43
+    /** @var int */
44
+    protected $itemsPerPage;
45
+
46
+    /**
47
+     * BaseResponse constructor.
48
+     *
49
+     * @param DataResponse|null $dataResponse
50
+     * @param string $format
51
+     * @param string|null $statusMessage
52
+     * @param int|null $itemsCount
53
+     * @param int|null $itemsPerPage
54
+     */
55
+    public function __construct(DataResponse $dataResponse,
56
+                                $format = 'xml',
57
+                                $statusMessage = null,
58
+                                $itemsCount = null,
59
+                                $itemsPerPage = null) {
60
+        $this->format = $format;
61
+        $this->statusMessage = $statusMessage;
62
+        $this->itemsCount = $itemsCount;
63
+        $this->itemsPerPage = $itemsPerPage;
64
+
65
+        $this->data = $dataResponse->getData();
66
+
67
+        $this->setHeaders($dataResponse->getHeaders());
68
+        $this->setStatus($dataResponse->getStatus());
69
+        $this->setETag($dataResponse->getETag());
70
+        $this->setLastModified($dataResponse->getLastModified());
71
+        $this->setCookies($dataResponse->getCookies());
72
+        $this->setContentSecurityPolicy(new EmptyContentSecurityPolicy());
73
+
74
+        if ($format === 'json') {
75
+            $this->addHeader(
76
+                'Content-Type', 'application/json; charset=utf-8'
77
+            );
78
+        } else {
79
+            $this->addHeader(
80
+                'Content-Type', 'application/xml; charset=utf-8'
81
+            );
82
+        }
83
+    }
84
+
85
+    /**
86
+     * @param string[] $meta
87
+     * @return string
88
+     */
89
+    protected function renderResult(array $meta): string {
90
+        $status = $this->getStatus();
91
+        if ($status === Http::STATUS_NO_CONTENT ||
92
+            $status === Http::STATUS_NOT_MODIFIED ||
93
+            ($status >= 100 && $status <= 199)) {
94
+            // Those status codes are not supposed to have a body:
95
+            // https://stackoverflow.com/q/8628725
96
+            return '';
97
+        }
98
+
99
+        $response = [
100
+            'ocs' => [
101
+                'meta' => $meta,
102
+                'data' => $this->data,
103
+            ],
104
+        ];
105
+
106
+        if ($this->format === 'json') {
107
+            return json_encode($response, JSON_HEX_TAG);
108
+        }
109
+
110
+        $writer = new \XMLWriter();
111
+        $writer->openMemory();
112
+        $writer->setIndent(true);
113
+        $writer->startDocument();
114
+        $this->toXML($response, $writer);
115
+        $writer->endDocument();
116
+        return $writer->outputMemory(true);
117
+
118
+    }
119
+
120
+    /**
121
+     * @param array $array
122
+     * @param \XMLWriter $writer
123
+     */
124
+    protected function toXML(array $array, \XMLWriter $writer) {
125
+        foreach ($array as $k => $v) {
126
+            if ($k[0] === '@') {
127
+                $writer->writeAttribute(substr($k, 1), $v);
128
+                continue;
129
+            }
130
+
131
+            if (\is_numeric($k)) {
132
+                $k = 'element';
133
+            }
134
+
135
+            if (\is_array($v)) {
136
+                $writer->startElement($k);
137
+                $this->toXML($v, $writer);
138
+                $writer->endElement();
139
+            } else {
140
+                $writer->writeElement($k, $v);
141
+            }
142
+        }
143
+    }
144
+
145
+    public function getOCSStatus() {
146
+        return parent::getStatus();
147
+    }
148 148
 }
Please login to merge, or discard this patch.
lib/private/Server.php 4 patches
Doc Comments   +2 added lines, -1 removed lines patch added patch discarded remove patch
@@ -1143,7 +1143,7 @@  discard block
 block discarded – undo
1143 1143
 	 * Get the certificate manager for the user
1144 1144
 	 *
1145 1145
 	 * @param string $userId (optional) if not specified the current loggedin user is used, use null to get the system certificate manager
1146
-	 * @return \OCP\ICertificateManager | null if $uid is null and no user is logged in
1146
+	 * @return null|CertificateManager | null if $uid is null and no user is logged in
1147 1147
 	 */
1148 1148
 	public function getCertificateManager($userId = '') {
1149 1149
 		if ($userId === '') {
@@ -1464,6 +1464,7 @@  discard block
 block discarded – undo
1464 1464
 	}
1465 1465
 
1466 1466
 	/**
1467
+	 * @param string $app
1467 1468
 	 * @return \OCP\Files\IAppData
1468 1469
 	 */
1469 1470
 	public function getAppDataDir($app) {
Please login to merge, or discard this patch.
Spacing   +115 added lines, -115 removed lines patch added patch discarded remove patch
@@ -174,7 +174,7 @@  discard block
 block discarded – undo
174 174
 		// To find out if we are running from CLI or not
175 175
 		$this->registerParameter('isCLI', \OC::$CLI);
176 176
 
177
-		$this->registerService(\OCP\IServerContainer::class, function (IServerContainer $c) {
177
+		$this->registerService(\OCP\IServerContainer::class, function(IServerContainer $c) {
178 178
 			return $c;
179 179
 		});
180 180
 
@@ -193,7 +193,7 @@  discard block
 block discarded – undo
193 193
 		$this->registerAlias(IActionFactory::class, ActionFactory::class);
194 194
 
195 195
 
196
-		$this->registerService(\OCP\IPreview::class, function (Server $c) {
196
+		$this->registerService(\OCP\IPreview::class, function(Server $c) {
197 197
 			return new PreviewManager(
198 198
 				$c->getConfig(),
199 199
 				$c->getRootFolder(),
@@ -204,13 +204,13 @@  discard block
 block discarded – undo
204 204
 		});
205 205
 		$this->registerAlias('PreviewManager', \OCP\IPreview::class);
206 206
 
207
-		$this->registerService(\OC\Preview\Watcher::class, function (Server $c) {
207
+		$this->registerService(\OC\Preview\Watcher::class, function(Server $c) {
208 208
 			return new \OC\Preview\Watcher(
209 209
 				$c->getAppDataDir('preview')
210 210
 			);
211 211
 		});
212 212
 
213
-		$this->registerService('EncryptionManager', function (Server $c) {
213
+		$this->registerService('EncryptionManager', function(Server $c) {
214 214
 			$view = new View();
215 215
 			$util = new Encryption\Util(
216 216
 				$view,
@@ -228,7 +228,7 @@  discard block
 block discarded – undo
228 228
 			);
229 229
 		});
230 230
 
231
-		$this->registerService('EncryptionFileHelper', function (Server $c) {
231
+		$this->registerService('EncryptionFileHelper', function(Server $c) {
232 232
 			$util = new Encryption\Util(
233 233
 				new View(),
234 234
 				$c->getUserManager(),
@@ -242,7 +242,7 @@  discard block
 block discarded – undo
242 242
 			);
243 243
 		});
244 244
 
245
-		$this->registerService('EncryptionKeyStorage', function (Server $c) {
245
+		$this->registerService('EncryptionKeyStorage', function(Server $c) {
246 246
 			$view = new View();
247 247
 			$util = new Encryption\Util(
248 248
 				$view,
@@ -253,30 +253,30 @@  discard block
 block discarded – undo
253 253
 
254 254
 			return new Encryption\Keys\Storage($view, $util);
255 255
 		});
256
-		$this->registerService('TagMapper', function (Server $c) {
256
+		$this->registerService('TagMapper', function(Server $c) {
257 257
 			return new TagMapper($c->getDatabaseConnection());
258 258
 		});
259 259
 
260
-		$this->registerService(\OCP\ITagManager::class, function (Server $c) {
260
+		$this->registerService(\OCP\ITagManager::class, function(Server $c) {
261 261
 			$tagMapper = $c->query('TagMapper');
262 262
 			return new TagManager($tagMapper, $c->getUserSession());
263 263
 		});
264 264
 		$this->registerAlias('TagManager', \OCP\ITagManager::class);
265 265
 
266
-		$this->registerService('SystemTagManagerFactory', function (Server $c) {
266
+		$this->registerService('SystemTagManagerFactory', function(Server $c) {
267 267
 			$config = $c->getConfig();
268 268
 			$factoryClass = $config->getSystemValue('systemtags.managerFactory', SystemTagManagerFactory::class);
269 269
 			return new $factoryClass($this);
270 270
 		});
271
-		$this->registerService(\OCP\SystemTag\ISystemTagManager::class, function (Server $c) {
271
+		$this->registerService(\OCP\SystemTag\ISystemTagManager::class, function(Server $c) {
272 272
 			return $c->query('SystemTagManagerFactory')->getManager();
273 273
 		});
274 274
 		$this->registerAlias('SystemTagManager', \OCP\SystemTag\ISystemTagManager::class);
275 275
 
276
-		$this->registerService(\OCP\SystemTag\ISystemTagObjectMapper::class, function (Server $c) {
276
+		$this->registerService(\OCP\SystemTag\ISystemTagObjectMapper::class, function(Server $c) {
277 277
 			return $c->query('SystemTagManagerFactory')->getObjectMapper();
278 278
 		});
279
-		$this->registerService('RootFolder', function (Server $c) {
279
+		$this->registerService('RootFolder', function(Server $c) {
280 280
 			$manager = \OC\Files\Filesystem::getMountManager(null);
281 281
 			$view = new View();
282 282
 			$root = new Root(
@@ -297,38 +297,38 @@  discard block
 block discarded – undo
297 297
 		});
298 298
 		$this->registerAlias('SystemTagObjectMapper', \OCP\SystemTag\ISystemTagObjectMapper::class);
299 299
 
300
-		$this->registerService(\OCP\Files\IRootFolder::class, function (Server $c) {
301
-			return new LazyRoot(function () use ($c) {
300
+		$this->registerService(\OCP\Files\IRootFolder::class, function(Server $c) {
301
+			return new LazyRoot(function() use ($c) {
302 302
 				return $c->query('RootFolder');
303 303
 			});
304 304
 		});
305 305
 		$this->registerAlias('LazyRootFolder', \OCP\Files\IRootFolder::class);
306 306
 
307
-		$this->registerService(\OC\User\Manager::class, function (Server $c) {
307
+		$this->registerService(\OC\User\Manager::class, function(Server $c) {
308 308
 			$config = $c->getConfig();
309 309
 			return new \OC\User\Manager($config);
310 310
 		});
311 311
 		$this->registerAlias('UserManager', \OC\User\Manager::class);
312 312
 		$this->registerAlias(\OCP\IUserManager::class, \OC\User\Manager::class);
313 313
 
314
-		$this->registerService(\OCP\IGroupManager::class, function (Server $c) {
314
+		$this->registerService(\OCP\IGroupManager::class, function(Server $c) {
315 315
 			$groupManager = new \OC\Group\Manager($this->getUserManager(), $this->getLogger());
316
-			$groupManager->listen('\OC\Group', 'preCreate', function ($gid) {
316
+			$groupManager->listen('\OC\Group', 'preCreate', function($gid) {
317 317
 				\OC_Hook::emit('OC_Group', 'pre_createGroup', array('run' => true, 'gid' => $gid));
318 318
 			});
319
-			$groupManager->listen('\OC\Group', 'postCreate', function (\OC\Group\Group $gid) {
319
+			$groupManager->listen('\OC\Group', 'postCreate', function(\OC\Group\Group $gid) {
320 320
 				\OC_Hook::emit('OC_User', 'post_createGroup', array('gid' => $gid->getGID()));
321 321
 			});
322
-			$groupManager->listen('\OC\Group', 'preDelete', function (\OC\Group\Group $group) {
322
+			$groupManager->listen('\OC\Group', 'preDelete', function(\OC\Group\Group $group) {
323 323
 				\OC_Hook::emit('OC_Group', 'pre_deleteGroup', array('run' => true, 'gid' => $group->getGID()));
324 324
 			});
325
-			$groupManager->listen('\OC\Group', 'postDelete', function (\OC\Group\Group $group) {
325
+			$groupManager->listen('\OC\Group', 'postDelete', function(\OC\Group\Group $group) {
326 326
 				\OC_Hook::emit('OC_User', 'post_deleteGroup', array('gid' => $group->getGID()));
327 327
 			});
328
-			$groupManager->listen('\OC\Group', 'preAddUser', function (\OC\Group\Group $group, \OC\User\User $user) {
328
+			$groupManager->listen('\OC\Group', 'preAddUser', function(\OC\Group\Group $group, \OC\User\User $user) {
329 329
 				\OC_Hook::emit('OC_Group', 'pre_addToGroup', array('run' => true, 'uid' => $user->getUID(), 'gid' => $group->getGID()));
330 330
 			});
331
-			$groupManager->listen('\OC\Group', 'postAddUser', function (\OC\Group\Group $group, \OC\User\User $user) {
331
+			$groupManager->listen('\OC\Group', 'postAddUser', function(\OC\Group\Group $group, \OC\User\User $user) {
332 332
 				\OC_Hook::emit('OC_Group', 'post_addToGroup', array('uid' => $user->getUID(), 'gid' => $group->getGID()));
333 333
 				//Minimal fix to keep it backward compatible TODO: clean up all the GroupManager hooks
334 334
 				\OC_Hook::emit('OC_User', 'post_addToGroup', array('uid' => $user->getUID(), 'gid' => $group->getGID()));
@@ -337,7 +337,7 @@  discard block
 block discarded – undo
337 337
 		});
338 338
 		$this->registerAlias('GroupManager', \OCP\IGroupManager::class);
339 339
 
340
-		$this->registerService(Store::class, function (Server $c) {
340
+		$this->registerService(Store::class, function(Server $c) {
341 341
 			$session = $c->getSession();
342 342
 			if (\OC::$server->getSystemConfig()->getValue('installed', false)) {
343 343
 				$tokenProvider = $c->query(IProvider::class);
@@ -348,13 +348,13 @@  discard block
 block discarded – undo
348 348
 			return new Store($session, $logger, $tokenProvider);
349 349
 		});
350 350
 		$this->registerAlias(IStore::class, Store::class);
351
-		$this->registerService(Authentication\Token\DefaultTokenMapper::class, function (Server $c) {
351
+		$this->registerService(Authentication\Token\DefaultTokenMapper::class, function(Server $c) {
352 352
 			$dbConnection = $c->getDatabaseConnection();
353 353
 			return new Authentication\Token\DefaultTokenMapper($dbConnection);
354 354
 		});
355 355
 		$this->registerAlias(IProvider::class, Authentication\Token\Manager::class);
356 356
 
357
-		$this->registerService(\OCP\IUserSession::class, function (Server $c) {
357
+		$this->registerService(\OCP\IUserSession::class, function(Server $c) {
358 358
 			$manager = $c->getUserManager();
359 359
 			$session = new \OC\Session\Memory('');
360 360
 			$timeFactory = new TimeFactory();
@@ -378,45 +378,45 @@  discard block
 block discarded – undo
378 378
 				$c->getLockdownManager(),
379 379
 				$c->getLogger()
380 380
 			);
381
-			$userSession->listen('\OC\User', 'preCreateUser', function ($uid, $password) {
381
+			$userSession->listen('\OC\User', 'preCreateUser', function($uid, $password) {
382 382
 				\OC_Hook::emit('OC_User', 'pre_createUser', array('run' => true, 'uid' => $uid, 'password' => $password));
383 383
 			});
384
-			$userSession->listen('\OC\User', 'postCreateUser', function ($user, $password) {
384
+			$userSession->listen('\OC\User', 'postCreateUser', function($user, $password) {
385 385
 				/** @var $user \OC\User\User */
386 386
 				\OC_Hook::emit('OC_User', 'post_createUser', array('uid' => $user->getUID(), 'password' => $password));
387 387
 			});
388
-			$userSession->listen('\OC\User', 'preDelete', function ($user) use ($dispatcher) {
388
+			$userSession->listen('\OC\User', 'preDelete', function($user) use ($dispatcher) {
389 389
 				/** @var $user \OC\User\User */
390 390
 				\OC_Hook::emit('OC_User', 'pre_deleteUser', array('run' => true, 'uid' => $user->getUID()));
391 391
 				$dispatcher->dispatch('OCP\IUser::preDelete', new GenericEvent($user));
392 392
 			});
393
-			$userSession->listen('\OC\User', 'postDelete', function ($user) {
393
+			$userSession->listen('\OC\User', 'postDelete', function($user) {
394 394
 				/** @var $user \OC\User\User */
395 395
 				\OC_Hook::emit('OC_User', 'post_deleteUser', array('uid' => $user->getUID()));
396 396
 			});
397
-			$userSession->listen('\OC\User', 'preSetPassword', function ($user, $password, $recoveryPassword) {
397
+			$userSession->listen('\OC\User', 'preSetPassword', function($user, $password, $recoveryPassword) {
398 398
 				/** @var $user \OC\User\User */
399 399
 				\OC_Hook::emit('OC_User', 'pre_setPassword', array('run' => true, 'uid' => $user->getUID(), 'password' => $password, 'recoveryPassword' => $recoveryPassword));
400 400
 			});
401
-			$userSession->listen('\OC\User', 'postSetPassword', function ($user, $password, $recoveryPassword) {
401
+			$userSession->listen('\OC\User', 'postSetPassword', function($user, $password, $recoveryPassword) {
402 402
 				/** @var $user \OC\User\User */
403 403
 				\OC_Hook::emit('OC_User', 'post_setPassword', array('run' => true, 'uid' => $user->getUID(), 'password' => $password, 'recoveryPassword' => $recoveryPassword));
404 404
 			});
405
-			$userSession->listen('\OC\User', 'preLogin', function ($uid, $password) {
405
+			$userSession->listen('\OC\User', 'preLogin', function($uid, $password) {
406 406
 				\OC_Hook::emit('OC_User', 'pre_login', array('run' => true, 'uid' => $uid, 'password' => $password));
407 407
 			});
408
-			$userSession->listen('\OC\User', 'postLogin', function ($user, $password) {
408
+			$userSession->listen('\OC\User', 'postLogin', function($user, $password) {
409 409
 				/** @var $user \OC\User\User */
410 410
 				\OC_Hook::emit('OC_User', 'post_login', array('run' => true, 'uid' => $user->getUID(), 'password' => $password));
411 411
 			});
412
-			$userSession->listen('\OC\User', 'postRememberedLogin', function ($user, $password) {
412
+			$userSession->listen('\OC\User', 'postRememberedLogin', function($user, $password) {
413 413
 				/** @var $user \OC\User\User */
414 414
 				\OC_Hook::emit('OC_User', 'post_login', array('run' => true, 'uid' => $user->getUID(), 'password' => $password));
415 415
 			});
416
-			$userSession->listen('\OC\User', 'logout', function () {
416
+			$userSession->listen('\OC\User', 'logout', function() {
417 417
 				\OC_Hook::emit('OC_User', 'logout', array());
418 418
 			});
419
-			$userSession->listen('\OC\User', 'changeUser', function ($user, $feature, $value, $oldValue) use ($dispatcher) {
419
+			$userSession->listen('\OC\User', 'changeUser', function($user, $feature, $value, $oldValue) use ($dispatcher) {
420 420
 				/** @var $user \OC\User\User */
421 421
 				\OC_Hook::emit('OC_User', 'changeUser', array('run' => true, 'user' => $user, 'feature' => $feature, 'value' => $value, 'old_value' => $oldValue));
422 422
 				$dispatcher->dispatch('OCP\IUser::changeUser', new GenericEvent($user, ['feature' => $feature, 'oldValue' => $oldValue, 'value' => $value]));
@@ -430,7 +430,7 @@  discard block
 block discarded – undo
430 430
 		$this->registerAlias(\OCP\INavigationManager::class, \OC\NavigationManager::class);
431 431
 		$this->registerAlias('NavigationManager', \OCP\INavigationManager::class);
432 432
 
433
-		$this->registerService(\OC\AllConfig::class, function (Server $c) {
433
+		$this->registerService(\OC\AllConfig::class, function(Server $c) {
434 434
 			return new \OC\AllConfig(
435 435
 				$c->getSystemConfig()
436 436
 			);
@@ -438,17 +438,17 @@  discard block
 block discarded – undo
438 438
 		$this->registerAlias('AllConfig', \OC\AllConfig::class);
439 439
 		$this->registerAlias(\OCP\IConfig::class, \OC\AllConfig::class);
440 440
 
441
-		$this->registerService('SystemConfig', function ($c) use ($config) {
441
+		$this->registerService('SystemConfig', function($c) use ($config) {
442 442
 			return new \OC\SystemConfig($config);
443 443
 		});
444 444
 
445
-		$this->registerService(\OC\AppConfig::class, function (Server $c) {
445
+		$this->registerService(\OC\AppConfig::class, function(Server $c) {
446 446
 			return new \OC\AppConfig($c->getDatabaseConnection());
447 447
 		});
448 448
 		$this->registerAlias('AppConfig', \OC\AppConfig::class);
449 449
 		$this->registerAlias(\OCP\IAppConfig::class, \OC\AppConfig::class);
450 450
 
451
-		$this->registerService(\OCP\L10N\IFactory::class, function (Server $c) {
451
+		$this->registerService(\OCP\L10N\IFactory::class, function(Server $c) {
452 452
 			return new \OC\L10N\Factory(
453 453
 				$c->getConfig(),
454 454
 				$c->getRequest(),
@@ -458,7 +458,7 @@  discard block
 block discarded – undo
458 458
 		});
459 459
 		$this->registerAlias('L10NFactory', \OCP\L10N\IFactory::class);
460 460
 
461
-		$this->registerService(\OCP\IURLGenerator::class, function (Server $c) {
461
+		$this->registerService(\OCP\IURLGenerator::class, function(Server $c) {
462 462
 			$config = $c->getConfig();
463 463
 			$cacheFactory = $c->getMemCacheFactory();
464 464
 			$request = $c->getRequest();
@@ -473,12 +473,12 @@  discard block
 block discarded – undo
473 473
 		$this->registerAlias('AppFetcher', AppFetcher::class);
474 474
 		$this->registerAlias('CategoryFetcher', CategoryFetcher::class);
475 475
 
476
-		$this->registerService(\OCP\ICache::class, function ($c) {
476
+		$this->registerService(\OCP\ICache::class, function($c) {
477 477
 			return new Cache\File();
478 478
 		});
479 479
 		$this->registerAlias('UserCache', \OCP\ICache::class);
480 480
 
481
-		$this->registerService(Factory::class, function (Server $c) {
481
+		$this->registerService(Factory::class, function(Server $c) {
482 482
 
483 483
 			$arrayCacheFactory = new \OC\Memcache\Factory('', $c->getLogger(),
484 484
 				ArrayCache::class,
@@ -495,7 +495,7 @@  discard block
 block discarded – undo
495 495
 				$version = implode(',', $v);
496 496
 				$instanceId = \OC_Util::getInstanceId();
497 497
 				$path = \OC::$SERVERROOT;
498
-				$prefix = md5($instanceId . '-' . $version . '-' . $path);
498
+				$prefix = md5($instanceId.'-'.$version.'-'.$path);
499 499
 				return new \OC\Memcache\Factory($prefix, $c->getLogger(),
500 500
 					$config->getSystemValue('memcache.local', null),
501 501
 					$config->getSystemValue('memcache.distributed', null),
@@ -508,12 +508,12 @@  discard block
 block discarded – undo
508 508
 		$this->registerAlias('MemCacheFactory', Factory::class);
509 509
 		$this->registerAlias(ICacheFactory::class, Factory::class);
510 510
 
511
-		$this->registerService('RedisFactory', function (Server $c) {
511
+		$this->registerService('RedisFactory', function(Server $c) {
512 512
 			$systemConfig = $c->getSystemConfig();
513 513
 			return new RedisFactory($systemConfig);
514 514
 		});
515 515
 
516
-		$this->registerService(\OCP\Activity\IManager::class, function (Server $c) {
516
+		$this->registerService(\OCP\Activity\IManager::class, function(Server $c) {
517 517
 			return new \OC\Activity\Manager(
518 518
 				$c->getRequest(),
519 519
 				$c->getUserSession(),
@@ -523,14 +523,14 @@  discard block
 block discarded – undo
523 523
 		});
524 524
 		$this->registerAlias('ActivityManager', \OCP\Activity\IManager::class);
525 525
 
526
-		$this->registerService(\OCP\Activity\IEventMerger::class, function (Server $c) {
526
+		$this->registerService(\OCP\Activity\IEventMerger::class, function(Server $c) {
527 527
 			return new \OC\Activity\EventMerger(
528 528
 				$c->getL10N('lib')
529 529
 			);
530 530
 		});
531 531
 		$this->registerAlias(IValidator::class, Validator::class);
532 532
 
533
-		$this->registerService(\OCP\IAvatarManager::class, function (Server $c) {
533
+		$this->registerService(\OCP\IAvatarManager::class, function(Server $c) {
534 534
 			return new AvatarManager(
535 535
 				$c->query(\OC\User\Manager::class),
536 536
 				$c->getAppDataDir('avatar'),
@@ -543,7 +543,7 @@  discard block
 block discarded – undo
543 543
 
544 544
 		$this->registerAlias(\OCP\Support\CrashReport\IRegistry::class, \OC\Support\CrashReport\Registry::class);
545 545
 
546
-		$this->registerService(\OCP\ILogger::class, function (Server $c) {
546
+		$this->registerService(\OCP\ILogger::class, function(Server $c) {
547 547
 			$logType = $c->query('AllConfig')->getSystemValue('log_type', 'file');
548 548
 			$factory = new LogFactory($c, $this->getSystemConfig());
549 549
 			$logger = $factory->get($logType);
@@ -553,11 +553,11 @@  discard block
 block discarded – undo
553 553
 		});
554 554
 		$this->registerAlias('Logger', \OCP\ILogger::class);
555 555
 
556
-		$this->registerService(ILogFactory::class, function (Server $c) {
556
+		$this->registerService(ILogFactory::class, function(Server $c) {
557 557
 			return new LogFactory($c, $this->getSystemConfig());
558 558
 		});
559 559
 
560
-		$this->registerService(\OCP\BackgroundJob\IJobList::class, function (Server $c) {
560
+		$this->registerService(\OCP\BackgroundJob\IJobList::class, function(Server $c) {
561 561
 			$config = $c->getConfig();
562 562
 			return new \OC\BackgroundJob\JobList(
563 563
 				$c->getDatabaseConnection(),
@@ -567,7 +567,7 @@  discard block
 block discarded – undo
567 567
 		});
568 568
 		$this->registerAlias('JobList', \OCP\BackgroundJob\IJobList::class);
569 569
 
570
-		$this->registerService(\OCP\Route\IRouter::class, function (Server $c) {
570
+		$this->registerService(\OCP\Route\IRouter::class, function(Server $c) {
571 571
 			$cacheFactory = $c->getMemCacheFactory();
572 572
 			$logger = $c->getLogger();
573 573
 			if ($cacheFactory->isLocalCacheAvailable()) {
@@ -579,12 +579,12 @@  discard block
 block discarded – undo
579 579
 		});
580 580
 		$this->registerAlias('Router', \OCP\Route\IRouter::class);
581 581
 
582
-		$this->registerService(\OCP\ISearch::class, function ($c) {
582
+		$this->registerService(\OCP\ISearch::class, function($c) {
583 583
 			return new Search();
584 584
 		});
585 585
 		$this->registerAlias('Search', \OCP\ISearch::class);
586 586
 
587
-		$this->registerService(\OC\Security\RateLimiting\Limiter::class, function (Server $c) {
587
+		$this->registerService(\OC\Security\RateLimiting\Limiter::class, function(Server $c) {
588 588
 			return new \OC\Security\RateLimiting\Limiter(
589 589
 				$this->getUserSession(),
590 590
 				$this->getRequest(),
@@ -592,34 +592,34 @@  discard block
 block discarded – undo
592 592
 				$c->query(\OC\Security\RateLimiting\Backend\IBackend::class)
593 593
 			);
594 594
 		});
595
-		$this->registerService(\OC\Security\RateLimiting\Backend\IBackend::class, function ($c) {
595
+		$this->registerService(\OC\Security\RateLimiting\Backend\IBackend::class, function($c) {
596 596
 			return new \OC\Security\RateLimiting\Backend\MemoryCache(
597 597
 				$this->getMemCacheFactory(),
598 598
 				new \OC\AppFramework\Utility\TimeFactory()
599 599
 			);
600 600
 		});
601 601
 
602
-		$this->registerService(\OCP\Security\ISecureRandom::class, function ($c) {
602
+		$this->registerService(\OCP\Security\ISecureRandom::class, function($c) {
603 603
 			return new SecureRandom();
604 604
 		});
605 605
 		$this->registerAlias('SecureRandom', \OCP\Security\ISecureRandom::class);
606 606
 
607
-		$this->registerService(\OCP\Security\ICrypto::class, function (Server $c) {
607
+		$this->registerService(\OCP\Security\ICrypto::class, function(Server $c) {
608 608
 			return new Crypto($c->getConfig(), $c->getSecureRandom());
609 609
 		});
610 610
 		$this->registerAlias('Crypto', \OCP\Security\ICrypto::class);
611 611
 
612
-		$this->registerService(\OCP\Security\IHasher::class, function (Server $c) {
612
+		$this->registerService(\OCP\Security\IHasher::class, function(Server $c) {
613 613
 			return new Hasher($c->getConfig());
614 614
 		});
615 615
 		$this->registerAlias('Hasher', \OCP\Security\IHasher::class);
616 616
 
617
-		$this->registerService(\OCP\Security\ICredentialsManager::class, function (Server $c) {
617
+		$this->registerService(\OCP\Security\ICredentialsManager::class, function(Server $c) {
618 618
 			return new CredentialsManager($c->getCrypto(), $c->getDatabaseConnection());
619 619
 		});
620 620
 		$this->registerAlias('CredentialsManager', \OCP\Security\ICredentialsManager::class);
621 621
 
622
-		$this->registerService(IDBConnection::class, function (Server $c) {
622
+		$this->registerService(IDBConnection::class, function(Server $c) {
623 623
 			$systemConfig = $c->getSystemConfig();
624 624
 			$factory = new \OC\DB\ConnectionFactory($systemConfig);
625 625
 			$type = $systemConfig->getValue('dbtype', 'sqlite');
@@ -634,7 +634,7 @@  discard block
 block discarded – undo
634 634
 		$this->registerAlias('DatabaseConnection', IDBConnection::class);
635 635
 
636 636
 
637
-		$this->registerService(\OCP\Http\Client\IClientService::class, function (Server $c) {
637
+		$this->registerService(\OCP\Http\Client\IClientService::class, function(Server $c) {
638 638
 			$user = \OC_User::getUser();
639 639
 			$uid = $user ? $user : null;
640 640
 			return new ClientService(
@@ -649,7 +649,7 @@  discard block
 block discarded – undo
649 649
 			);
650 650
 		});
651 651
 		$this->registerAlias('HttpClientService', \OCP\Http\Client\IClientService::class);
652
-		$this->registerService(\OCP\Diagnostics\IEventLogger::class, function (Server $c) {
652
+		$this->registerService(\OCP\Diagnostics\IEventLogger::class, function(Server $c) {
653 653
 			$eventLogger = new EventLogger();
654 654
 			if ($c->getSystemConfig()->getValue('debug', false)) {
655 655
 				// In debug mode, module is being activated by default
@@ -659,7 +659,7 @@  discard block
 block discarded – undo
659 659
 		});
660 660
 		$this->registerAlias('EventLogger', \OCP\Diagnostics\IEventLogger::class);
661 661
 
662
-		$this->registerService(\OCP\Diagnostics\IQueryLogger::class, function (Server $c) {
662
+		$this->registerService(\OCP\Diagnostics\IQueryLogger::class, function(Server $c) {
663 663
 			$queryLogger = new QueryLogger();
664 664
 			if ($c->getSystemConfig()->getValue('debug', false)) {
665 665
 				// In debug mode, module is being activated by default
@@ -669,7 +669,7 @@  discard block
 block discarded – undo
669 669
 		});
670 670
 		$this->registerAlias('QueryLogger', \OCP\Diagnostics\IQueryLogger::class);
671 671
 
672
-		$this->registerService(TempManager::class, function (Server $c) {
672
+		$this->registerService(TempManager::class, function(Server $c) {
673 673
 			return new TempManager(
674 674
 				$c->getLogger(),
675 675
 				$c->getConfig()
@@ -678,7 +678,7 @@  discard block
 block discarded – undo
678 678
 		$this->registerAlias('TempManager', TempManager::class);
679 679
 		$this->registerAlias(ITempManager::class, TempManager::class);
680 680
 
681
-		$this->registerService(AppManager::class, function (Server $c) {
681
+		$this->registerService(AppManager::class, function(Server $c) {
682 682
 			return new \OC\App\AppManager(
683 683
 				$c->getUserSession(),
684 684
 				$c->query(\OC\AppConfig::class),
@@ -690,7 +690,7 @@  discard block
 block discarded – undo
690 690
 		$this->registerAlias('AppManager', AppManager::class);
691 691
 		$this->registerAlias(IAppManager::class, AppManager::class);
692 692
 
693
-		$this->registerService(\OCP\IDateTimeZone::class, function (Server $c) {
693
+		$this->registerService(\OCP\IDateTimeZone::class, function(Server $c) {
694 694
 			return new DateTimeZone(
695 695
 				$c->getConfig(),
696 696
 				$c->getSession()
@@ -698,7 +698,7 @@  discard block
 block discarded – undo
698 698
 		});
699 699
 		$this->registerAlias('DateTimeZone', \OCP\IDateTimeZone::class);
700 700
 
701
-		$this->registerService(\OCP\IDateTimeFormatter::class, function (Server $c) {
701
+		$this->registerService(\OCP\IDateTimeFormatter::class, function(Server $c) {
702 702
 			$language = $c->getConfig()->getUserValue($c->getSession()->get('user_id'), 'core', 'lang', null);
703 703
 
704 704
 			return new DateTimeFormatter(
@@ -708,7 +708,7 @@  discard block
 block discarded – undo
708 708
 		});
709 709
 		$this->registerAlias('DateTimeFormatter', \OCP\IDateTimeFormatter::class);
710 710
 
711
-		$this->registerService(\OCP\Files\Config\IUserMountCache::class, function (Server $c) {
711
+		$this->registerService(\OCP\Files\Config\IUserMountCache::class, function(Server $c) {
712 712
 			$mountCache = new UserMountCache($c->getDatabaseConnection(), $c->getUserManager(), $c->getLogger());
713 713
 			$listener = new UserMountCacheListener($mountCache);
714 714
 			$listener->listen($c->getUserManager());
@@ -716,7 +716,7 @@  discard block
 block discarded – undo
716 716
 		});
717 717
 		$this->registerAlias('UserMountCache', \OCP\Files\Config\IUserMountCache::class);
718 718
 
719
-		$this->registerService(\OCP\Files\Config\IMountProviderCollection::class, function (Server $c) {
719
+		$this->registerService(\OCP\Files\Config\IMountProviderCollection::class, function(Server $c) {
720 720
 			$loader = \OC\Files\Filesystem::getLoader();
721 721
 			$mountCache = $c->query('UserMountCache');
722 722
 			$manager = new \OC\Files\Config\MountProviderCollection($loader, $mountCache);
@@ -732,10 +732,10 @@  discard block
 block discarded – undo
732 732
 		});
733 733
 		$this->registerAlias('MountConfigManager', \OCP\Files\Config\IMountProviderCollection::class);
734 734
 
735
-		$this->registerService('IniWrapper', function ($c) {
735
+		$this->registerService('IniWrapper', function($c) {
736 736
 			return new IniGetWrapper();
737 737
 		});
738
-		$this->registerService('AsyncCommandBus', function (Server $c) {
738
+		$this->registerService('AsyncCommandBus', function(Server $c) {
739 739
 			$busClass = $c->getConfig()->getSystemValue('commandbus');
740 740
 			if ($busClass) {
741 741
 				list($app, $class) = explode('::', $busClass, 2);
@@ -750,10 +750,10 @@  discard block
 block discarded – undo
750 750
 				return new CronBus($jobList);
751 751
 			}
752 752
 		});
753
-		$this->registerService('TrustedDomainHelper', function ($c) {
753
+		$this->registerService('TrustedDomainHelper', function($c) {
754 754
 			return new TrustedDomainHelper($this->getConfig());
755 755
 		});
756
-		$this->registerService('Throttler', function (Server $c) {
756
+		$this->registerService('Throttler', function(Server $c) {
757 757
 			return new Throttler(
758 758
 				$c->getDatabaseConnection(),
759 759
 				new TimeFactory(),
@@ -761,7 +761,7 @@  discard block
 block discarded – undo
761 761
 				$c->getConfig()
762 762
 			);
763 763
 		});
764
-		$this->registerService('IntegrityCodeChecker', function (Server $c) {
764
+		$this->registerService('IntegrityCodeChecker', function(Server $c) {
765 765
 			// IConfig and IAppManager requires a working database. This code
766 766
 			// might however be called when ownCloud is not yet setup.
767 767
 			if (\OC::$server->getSystemConfig()->getValue('installed', false)) {
@@ -782,7 +782,7 @@  discard block
 block discarded – undo
782 782
 				$c->getTempManager()
783 783
 			);
784 784
 		});
785
-		$this->registerService(\OCP\IRequest::class, function ($c) {
785
+		$this->registerService(\OCP\IRequest::class, function($c) {
786 786
 			if (isset($this['urlParams'])) {
787 787
 				$urlParams = $this['urlParams'];
788 788
 			} else {
@@ -818,7 +818,7 @@  discard block
 block discarded – undo
818 818
 		});
819 819
 		$this->registerAlias('Request', \OCP\IRequest::class);
820 820
 
821
-		$this->registerService(\OCP\Mail\IMailer::class, function (Server $c) {
821
+		$this->registerService(\OCP\Mail\IMailer::class, function(Server $c) {
822 822
 			return new Mailer(
823 823
 				$c->getConfig(),
824 824
 				$c->getLogger(),
@@ -829,7 +829,7 @@  discard block
 block discarded – undo
829 829
 		});
830 830
 		$this->registerAlias('Mailer', \OCP\Mail\IMailer::class);
831 831
 
832
-		$this->registerService('LDAPProvider', function (Server $c) {
832
+		$this->registerService('LDAPProvider', function(Server $c) {
833 833
 			$config = $c->getConfig();
834 834
 			$factoryClass = $config->getSystemValue('ldapProviderFactory', null);
835 835
 			if (is_null($factoryClass)) {
@@ -839,7 +839,7 @@  discard block
 block discarded – undo
839 839
 			$factory = new $factoryClass($this);
840 840
 			return $factory->getLDAPProvider();
841 841
 		});
842
-		$this->registerService(ILockingProvider::class, function (Server $c) {
842
+		$this->registerService(ILockingProvider::class, function(Server $c) {
843 843
 			$ini = $c->getIniWrapper();
844 844
 			$config = $c->getConfig();
845 845
 			$ttl = $config->getSystemValue('filelocking.ttl', max(3600, $ini->getNumeric('max_execution_time')));
@@ -862,49 +862,49 @@  discard block
 block discarded – undo
862 862
 		});
863 863
 		$this->registerAlias('LockingProvider', ILockingProvider::class);
864 864
 
865
-		$this->registerService(\OCP\Files\Mount\IMountManager::class, function () {
865
+		$this->registerService(\OCP\Files\Mount\IMountManager::class, function() {
866 866
 			return new \OC\Files\Mount\Manager();
867 867
 		});
868 868
 		$this->registerAlias('MountManager', \OCP\Files\Mount\IMountManager::class);
869 869
 
870
-		$this->registerService(\OCP\Files\IMimeTypeDetector::class, function (Server $c) {
870
+		$this->registerService(\OCP\Files\IMimeTypeDetector::class, function(Server $c) {
871 871
 			return new \OC\Files\Type\Detection(
872 872
 				$c->getURLGenerator(),
873 873
 				\OC::$configDir,
874
-				\OC::$SERVERROOT . '/resources/config/'
874
+				\OC::$SERVERROOT.'/resources/config/'
875 875
 			);
876 876
 		});
877 877
 		$this->registerAlias('MimeTypeDetector', \OCP\Files\IMimeTypeDetector::class);
878 878
 
879
-		$this->registerService(\OCP\Files\IMimeTypeLoader::class, function (Server $c) {
879
+		$this->registerService(\OCP\Files\IMimeTypeLoader::class, function(Server $c) {
880 880
 			return new \OC\Files\Type\Loader(
881 881
 				$c->getDatabaseConnection()
882 882
 			);
883 883
 		});
884 884
 		$this->registerAlias('MimeTypeLoader', \OCP\Files\IMimeTypeLoader::class);
885
-		$this->registerService(BundleFetcher::class, function () {
885
+		$this->registerService(BundleFetcher::class, function() {
886 886
 			return new BundleFetcher($this->getL10N('lib'));
887 887
 		});
888
-		$this->registerService(\OCP\Notification\IManager::class, function (Server $c) {
888
+		$this->registerService(\OCP\Notification\IManager::class, function(Server $c) {
889 889
 			return new Manager(
890 890
 				$c->query(IValidator::class)
891 891
 			);
892 892
 		});
893 893
 		$this->registerAlias('NotificationManager', \OCP\Notification\IManager::class);
894 894
 
895
-		$this->registerService(\OC\CapabilitiesManager::class, function (Server $c) {
895
+		$this->registerService(\OC\CapabilitiesManager::class, function(Server $c) {
896 896
 			$manager = new \OC\CapabilitiesManager($c->getLogger());
897
-			$manager->registerCapability(function () use ($c) {
897
+			$manager->registerCapability(function() use ($c) {
898 898
 				return new \OC\OCS\CoreCapabilities($c->getConfig());
899 899
 			});
900
-			$manager->registerCapability(function () use ($c) {
900
+			$manager->registerCapability(function() use ($c) {
901 901
 				return $c->query(\OC\Security\Bruteforce\Capabilities::class);
902 902
 			});
903 903
 			return $manager;
904 904
 		});
905 905
 		$this->registerAlias('CapabilitiesManager', \OC\CapabilitiesManager::class);
906 906
 
907
-		$this->registerService(\OCP\Comments\ICommentsManager::class, function (Server $c) {
907
+		$this->registerService(\OCP\Comments\ICommentsManager::class, function(Server $c) {
908 908
 			$config = $c->getConfig();
909 909
 			$factoryClass = $config->getSystemValue('comments.managerFactory', CommentsManagerFactory::class);
910 910
 			/** @var \OCP\Comments\ICommentsManagerFactory $factory */
@@ -914,7 +914,7 @@  discard block
 block discarded – undo
914 914
 			$manager->registerDisplayNameResolver('user', function($id) use ($c) {
915 915
 				$manager = $c->getUserManager();
916 916
 				$user = $manager->get($id);
917
-				if(is_null($user)) {
917
+				if (is_null($user)) {
918 918
 					$l = $c->getL10N('core');
919 919
 					$displayName = $l->t('Unknown user');
920 920
 				} else {
@@ -927,7 +927,7 @@  discard block
 block discarded – undo
927 927
 		});
928 928
 		$this->registerAlias('CommentsManager', \OCP\Comments\ICommentsManager::class);
929 929
 
930
-		$this->registerService('ThemingDefaults', function (Server $c) {
930
+		$this->registerService('ThemingDefaults', function(Server $c) {
931 931
 			/*
932 932
 			 * Dark magic for autoloader.
933 933
 			 * If we do a class_exists it will try to load the class which will
@@ -954,7 +954,7 @@  discard block
 block discarded – undo
954 954
 			}
955 955
 			return new \OC_Defaults();
956 956
 		});
957
-		$this->registerService(SCSSCacher::class, function (Server $c) {
957
+		$this->registerService(SCSSCacher::class, function(Server $c) {
958 958
 			/** @var Factory $cacheFactory */
959 959
 			$cacheFactory = $c->query(Factory::class);
960 960
 			return new SCSSCacher(
@@ -969,7 +969,7 @@  discard block
 block discarded – undo
969 969
 				new TimeFactory()
970 970
 			);
971 971
 		});
972
-		$this->registerService(JSCombiner::class, function (Server $c) {
972
+		$this->registerService(JSCombiner::class, function(Server $c) {
973 973
 			/** @var Factory $cacheFactory */
974 974
 			$cacheFactory = $c->query(Factory::class);
975 975
 			return new JSCombiner(
@@ -980,13 +980,13 @@  discard block
 block discarded – undo
980 980
 				$c->getLogger()
981 981
 			);
982 982
 		});
983
-		$this->registerService(EventDispatcher::class, function () {
983
+		$this->registerService(EventDispatcher::class, function() {
984 984
 			return new EventDispatcher();
985 985
 		});
986 986
 		$this->registerAlias('EventDispatcher', EventDispatcher::class);
987 987
 		$this->registerAlias(EventDispatcherInterface::class, EventDispatcher::class);
988 988
 
989
-		$this->registerService('CryptoWrapper', function (Server $c) {
989
+		$this->registerService('CryptoWrapper', function(Server $c) {
990 990
 			// FIXME: Instantiiated here due to cyclic dependency
991 991
 			$request = new Request(
992 992
 				[
@@ -1011,7 +1011,7 @@  discard block
 block discarded – undo
1011 1011
 				$request
1012 1012
 			);
1013 1013
 		});
1014
-		$this->registerService('CsrfTokenManager', function (Server $c) {
1014
+		$this->registerService('CsrfTokenManager', function(Server $c) {
1015 1015
 			$tokenGenerator = new CsrfTokenGenerator($c->getSecureRandom());
1016 1016
 
1017 1017
 			return new CsrfTokenManager(
@@ -1019,22 +1019,22 @@  discard block
 block discarded – undo
1019 1019
 				$c->query(SessionStorage::class)
1020 1020
 			);
1021 1021
 		});
1022
-		$this->registerService(SessionStorage::class, function (Server $c) {
1022
+		$this->registerService(SessionStorage::class, function(Server $c) {
1023 1023
 			return new SessionStorage($c->getSession());
1024 1024
 		});
1025
-		$this->registerService(\OCP\Security\IContentSecurityPolicyManager::class, function (Server $c) {
1025
+		$this->registerService(\OCP\Security\IContentSecurityPolicyManager::class, function(Server $c) {
1026 1026
 			return new ContentSecurityPolicyManager();
1027 1027
 		});
1028 1028
 		$this->registerAlias('ContentSecurityPolicyManager', \OCP\Security\IContentSecurityPolicyManager::class);
1029 1029
 
1030
-		$this->registerService('ContentSecurityPolicyNonceManager', function (Server $c) {
1030
+		$this->registerService('ContentSecurityPolicyNonceManager', function(Server $c) {
1031 1031
 			return new ContentSecurityPolicyNonceManager(
1032 1032
 				$c->getCsrfTokenManager(),
1033 1033
 				$c->getRequest()
1034 1034
 			);
1035 1035
 		});
1036 1036
 
1037
-		$this->registerService(\OCP\Share\IManager::class, function (Server $c) {
1037
+		$this->registerService(\OCP\Share\IManager::class, function(Server $c) {
1038 1038
 			$config = $c->getConfig();
1039 1039
 			$factoryClass = $config->getSystemValue('sharing.managerFactory', ProviderFactory::class);
1040 1040
 			/** @var \OCP\Share\IProviderFactory $factory */
@@ -1078,7 +1078,7 @@  discard block
 block discarded – undo
1078 1078
 
1079 1079
 		$this->registerAlias(\OCP\Collaboration\AutoComplete\IManager::class, \OC\Collaboration\AutoComplete\Manager::class);
1080 1080
 
1081
-		$this->registerService('SettingsManager', function (Server $c) {
1081
+		$this->registerService('SettingsManager', function(Server $c) {
1082 1082
 			$manager = new \OC\Settings\Manager(
1083 1083
 				$c->getLogger(),
1084 1084
 				$c->getL10N('lib'),
@@ -1087,36 +1087,36 @@  discard block
 block discarded – undo
1087 1087
 			);
1088 1088
 			return $manager;
1089 1089
 		});
1090
-		$this->registerService(\OC\Files\AppData\Factory::class, function (Server $c) {
1090
+		$this->registerService(\OC\Files\AppData\Factory::class, function(Server $c) {
1091 1091
 			return new \OC\Files\AppData\Factory(
1092 1092
 				$c->getRootFolder(),
1093 1093
 				$c->getSystemConfig()
1094 1094
 			);
1095 1095
 		});
1096 1096
 
1097
-		$this->registerService('LockdownManager', function (Server $c) {
1098
-			return new LockdownManager(function () use ($c) {
1097
+		$this->registerService('LockdownManager', function(Server $c) {
1098
+			return new LockdownManager(function() use ($c) {
1099 1099
 				return $c->getSession();
1100 1100
 			});
1101 1101
 		});
1102 1102
 
1103
-		$this->registerService(\OCP\OCS\IDiscoveryService::class, function (Server $c) {
1103
+		$this->registerService(\OCP\OCS\IDiscoveryService::class, function(Server $c) {
1104 1104
 			return new DiscoveryService($c->getMemCacheFactory(), $c->getHTTPClientService());
1105 1105
 		});
1106 1106
 
1107
-		$this->registerService(ICloudIdManager::class, function (Server $c) {
1107
+		$this->registerService(ICloudIdManager::class, function(Server $c) {
1108 1108
 			return new CloudIdManager();
1109 1109
 		});
1110 1110
 
1111
-		$this->registerService(IConfig::class, function (Server $c) {
1111
+		$this->registerService(IConfig::class, function(Server $c) {
1112 1112
 			return new GlobalScale\Config($c->getConfig());
1113 1113
 		});
1114 1114
 
1115
-		$this->registerService(ICloudFederationProviderManager::class, function (Server $c) {
1115
+		$this->registerService(ICloudFederationProviderManager::class, function(Server $c) {
1116 1116
 			return new CloudFederationProviderManager($c->getAppManager(), $c->getHTTPClientService(), $c->getCloudIdManager(), $c->getLogger());
1117 1117
 		});
1118 1118
 
1119
-		$this->registerService(ICloudFederationFactory::class, function (Server $c) {
1119
+		$this->registerService(ICloudFederationFactory::class, function(Server $c) {
1120 1120
 			return new CloudFederationFactory();
1121 1121
 		});
1122 1122
 
@@ -1126,18 +1126,18 @@  discard block
 block discarded – undo
1126 1126
 		$this->registerAlias(\OCP\AppFramework\Utility\ITimeFactory::class, \OC\AppFramework\Utility\TimeFactory::class);
1127 1127
 		$this->registerAlias('TimeFactory', \OCP\AppFramework\Utility\ITimeFactory::class);
1128 1128
 
1129
-		$this->registerService(Defaults::class, function (Server $c) {
1129
+		$this->registerService(Defaults::class, function(Server $c) {
1130 1130
 			return new Defaults(
1131 1131
 				$c->getThemingDefaults()
1132 1132
 			);
1133 1133
 		});
1134 1134
 		$this->registerAlias('Defaults', \OCP\Defaults::class);
1135 1135
 
1136
-		$this->registerService(\OCP\ISession::class, function (SimpleContainer $c) {
1136
+		$this->registerService(\OCP\ISession::class, function(SimpleContainer $c) {
1137 1137
 			return $c->query(\OCP\IUserSession::class)->getSession();
1138 1138
 		});
1139 1139
 
1140
-		$this->registerService(IShareHelper::class, function (Server $c) {
1140
+		$this->registerService(IShareHelper::class, function(Server $c) {
1141 1141
 			return new ShareHelper(
1142 1142
 				$c->query(\OCP\Share\IManager::class)
1143 1143
 			);
@@ -1213,11 +1213,11 @@  discard block
 block discarded – undo
1213 1213
 				// no avatar to remove
1214 1214
 			} catch (\Exception $e) {
1215 1215
 				// Ignore exceptions
1216
-				$logger->info('Could not cleanup avatar of ' . $user->getUID());
1216
+				$logger->info('Could not cleanup avatar of '.$user->getUID());
1217 1217
 			}
1218 1218
 		});
1219 1219
 
1220
-		$dispatcher->addListener('OCP\IUser::changeUser', function (GenericEvent $e) {
1220
+		$dispatcher->addListener('OCP\IUser::changeUser', function(GenericEvent $e) {
1221 1221
 			$manager = $this->getAvatarManager();
1222 1222
 			/** @var IUser $user */
1223 1223
 			$user = $e->getSubject();
@@ -1368,7 +1368,7 @@  discard block
 block discarded – undo
1368 1368
 	 * @deprecated since 9.2.0 use IAppData
1369 1369
 	 */
1370 1370
 	public function getAppFolder() {
1371
-		$dir = '/' . \OC_App::getCurrentApp();
1371
+		$dir = '/'.\OC_App::getCurrentApp();
1372 1372
 		$root = $this->getRootFolder();
1373 1373
 		if (!$root->nodeExists($dir)) {
1374 1374
 			$folder = $root->newFolder($dir);
@@ -1943,7 +1943,7 @@  discard block
 block discarded – undo
1943 1943
 	/**
1944 1944
 	 * @return \OCP\Collaboration\AutoComplete\IManager
1945 1945
 	 */
1946
-	public function getAutoCompleteManager(){
1946
+	public function getAutoCompleteManager() {
1947 1947
 		return $this->query(IManager::class);
1948 1948
 	}
1949 1949
 
Please login to merge, or discard this patch.
Unused Use Statements   -2 removed lines patch added patch discarded remove patch
@@ -48,7 +48,6 @@  discard block
 block discarded – undo
48 48
 namespace OC;
49 49
 
50 50
 use bantu\IniGetWrapper\IniGetWrapper;
51
-use OC\Accounts\AccountManager;
52 51
 use OC\App\AppManager;
53 52
 use OC\App\AppStore\Bundles\BundleFetcher;
54 53
 use OC\App\AppStore\Fetcher\AppFetcher;
@@ -122,7 +121,6 @@  discard block
 block discarded – undo
122 121
 use OC\Dashboard\DashboardManager;
123 122
 use OCA\Theming\ImageManager;
124 123
 use OCA\Theming\ThemingDefaults;
125
-
126 124
 use OCP\App\IAppManager;
127 125
 use OCP\AppFramework\Utility\ITimeFactory;
128 126
 use OCP\Collaboration\AutoComplete\IManager;
Please login to merge, or discard this patch.
Indentation   +1868 added lines, -1868 removed lines patch added patch discarded remove patch
@@ -164,1877 +164,1877 @@
 block discarded – undo
164 164
  * TODO: hookup all manager classes
165 165
  */
166 166
 class Server extends ServerContainer implements IServerContainer {
167
-	/** @var string */
168
-	private $webRoot;
169
-
170
-	/**
171
-	 * @param string $webRoot
172
-	 * @param \OC\Config $config
173
-	 */
174
-	public function __construct($webRoot, \OC\Config $config) {
175
-		parent::__construct();
176
-		$this->webRoot = $webRoot;
177
-
178
-		// To find out if we are running from CLI or not
179
-		$this->registerParameter('isCLI', \OC::$CLI);
180
-
181
-		$this->registerService(\OCP\IServerContainer::class, function (IServerContainer $c) {
182
-			return $c;
183
-		});
184
-
185
-		$this->registerAlias(\OCP\Calendar\IManager::class, \OC\Calendar\Manager::class);
186
-		$this->registerAlias('CalendarManager', \OC\Calendar\Manager::class);
187
-
188
-		$this->registerAlias(\OCP\Calendar\Resource\IManager::class, \OC\Calendar\Resource\Manager::class);
189
-		$this->registerAlias('CalendarResourceBackendManager', \OC\Calendar\Resource\Manager::class);
190
-
191
-		$this->registerAlias(\OCP\Calendar\Room\IManager::class, \OC\Calendar\Room\Manager::class);
192
-		$this->registerAlias('CalendarRoomBackendManager', \OC\Calendar\Room\Manager::class);
193
-
194
-		$this->registerAlias(\OCP\Contacts\IManager::class, \OC\ContactsManager::class);
195
-		$this->registerAlias('ContactsManager', \OCP\Contacts\IManager::class);
196
-
197
-		$this->registerAlias(IActionFactory::class, ActionFactory::class);
198
-
199
-
200
-		$this->registerService(\OCP\IPreview::class, function (Server $c) {
201
-			return new PreviewManager(
202
-				$c->getConfig(),
203
-				$c->getRootFolder(),
204
-				$c->getAppDataDir('preview'),
205
-				$c->getEventDispatcher(),
206
-				$c->getSession()->get('user_id')
207
-			);
208
-		});
209
-		$this->registerAlias('PreviewManager', \OCP\IPreview::class);
210
-
211
-		$this->registerService(\OC\Preview\Watcher::class, function (Server $c) {
212
-			return new \OC\Preview\Watcher(
213
-				$c->getAppDataDir('preview')
214
-			);
215
-		});
216
-
217
-		$this->registerService('EncryptionManager', function (Server $c) {
218
-			$view = new View();
219
-			$util = new Encryption\Util(
220
-				$view,
221
-				$c->getUserManager(),
222
-				$c->getGroupManager(),
223
-				$c->getConfig()
224
-			);
225
-			return new Encryption\Manager(
226
-				$c->getConfig(),
227
-				$c->getLogger(),
228
-				$c->getL10N('core'),
229
-				new View(),
230
-				$util,
231
-				new ArrayCache()
232
-			);
233
-		});
234
-
235
-		$this->registerService('EncryptionFileHelper', function (Server $c) {
236
-			$util = new Encryption\Util(
237
-				new View(),
238
-				$c->getUserManager(),
239
-				$c->getGroupManager(),
240
-				$c->getConfig()
241
-			);
242
-			return new Encryption\File(
243
-				$util,
244
-				$c->getRootFolder(),
245
-				$c->getShareManager()
246
-			);
247
-		});
248
-
249
-		$this->registerService('EncryptionKeyStorage', function (Server $c) {
250
-			$view = new View();
251
-			$util = new Encryption\Util(
252
-				$view,
253
-				$c->getUserManager(),
254
-				$c->getGroupManager(),
255
-				$c->getConfig()
256
-			);
257
-
258
-			return new Encryption\Keys\Storage($view, $util);
259
-		});
260
-		$this->registerService('TagMapper', function (Server $c) {
261
-			return new TagMapper($c->getDatabaseConnection());
262
-		});
263
-
264
-		$this->registerService(\OCP\ITagManager::class, function (Server $c) {
265
-			$tagMapper = $c->query('TagMapper');
266
-			return new TagManager($tagMapper, $c->getUserSession());
267
-		});
268
-		$this->registerAlias('TagManager', \OCP\ITagManager::class);
269
-
270
-		$this->registerService('SystemTagManagerFactory', function (Server $c) {
271
-			$config = $c->getConfig();
272
-			$factoryClass = $config->getSystemValue('systemtags.managerFactory', SystemTagManagerFactory::class);
273
-			return new $factoryClass($this);
274
-		});
275
-		$this->registerService(\OCP\SystemTag\ISystemTagManager::class, function (Server $c) {
276
-			return $c->query('SystemTagManagerFactory')->getManager();
277
-		});
278
-		$this->registerAlias('SystemTagManager', \OCP\SystemTag\ISystemTagManager::class);
279
-
280
-		$this->registerService(\OCP\SystemTag\ISystemTagObjectMapper::class, function (Server $c) {
281
-			return $c->query('SystemTagManagerFactory')->getObjectMapper();
282
-		});
283
-		$this->registerService('RootFolder', function (Server $c) {
284
-			$manager = \OC\Files\Filesystem::getMountManager(null);
285
-			$view = new View();
286
-			$root = new Root(
287
-				$manager,
288
-				$view,
289
-				null,
290
-				$c->getUserMountCache(),
291
-				$this->getLogger(),
292
-				$this->getUserManager()
293
-			);
294
-			$connector = new HookConnector($root, $view);
295
-			$connector->viewToNode();
296
-
297
-			$previewConnector = new \OC\Preview\WatcherConnector($root, $c->getSystemConfig());
298
-			$previewConnector->connectWatcher();
299
-
300
-			return $root;
301
-		});
302
-		$this->registerAlias('SystemTagObjectMapper', \OCP\SystemTag\ISystemTagObjectMapper::class);
303
-
304
-		$this->registerService(\OCP\Files\IRootFolder::class, function (Server $c) {
305
-			return new LazyRoot(function () use ($c) {
306
-				return $c->query('RootFolder');
307
-			});
308
-		});
309
-		$this->registerAlias('LazyRootFolder', \OCP\Files\IRootFolder::class);
310
-
311
-		$this->registerService(\OC\User\Manager::class, function (Server $c) {
312
-			$config = $c->getConfig();
313
-			return new \OC\User\Manager($config);
314
-		});
315
-		$this->registerAlias('UserManager', \OC\User\Manager::class);
316
-		$this->registerAlias(\OCP\IUserManager::class, \OC\User\Manager::class);
317
-
318
-		$this->registerService(\OCP\IGroupManager::class, function (Server $c) {
319
-			$groupManager = new \OC\Group\Manager($this->getUserManager(), $this->getLogger());
320
-			$groupManager->listen('\OC\Group', 'preCreate', function ($gid) {
321
-				\OC_Hook::emit('OC_Group', 'pre_createGroup', array('run' => true, 'gid' => $gid));
322
-			});
323
-			$groupManager->listen('\OC\Group', 'postCreate', function (\OC\Group\Group $gid) {
324
-				\OC_Hook::emit('OC_User', 'post_createGroup', array('gid' => $gid->getGID()));
325
-			});
326
-			$groupManager->listen('\OC\Group', 'preDelete', function (\OC\Group\Group $group) {
327
-				\OC_Hook::emit('OC_Group', 'pre_deleteGroup', array('run' => true, 'gid' => $group->getGID()));
328
-			});
329
-			$groupManager->listen('\OC\Group', 'postDelete', function (\OC\Group\Group $group) {
330
-				\OC_Hook::emit('OC_User', 'post_deleteGroup', array('gid' => $group->getGID()));
331
-			});
332
-			$groupManager->listen('\OC\Group', 'preAddUser', function (\OC\Group\Group $group, \OC\User\User $user) {
333
-				\OC_Hook::emit('OC_Group', 'pre_addToGroup', array('run' => true, 'uid' => $user->getUID(), 'gid' => $group->getGID()));
334
-			});
335
-			$groupManager->listen('\OC\Group', 'postAddUser', function (\OC\Group\Group $group, \OC\User\User $user) {
336
-				\OC_Hook::emit('OC_Group', 'post_addToGroup', array('uid' => $user->getUID(), 'gid' => $group->getGID()));
337
-				//Minimal fix to keep it backward compatible TODO: clean up all the GroupManager hooks
338
-				\OC_Hook::emit('OC_User', 'post_addToGroup', array('uid' => $user->getUID(), 'gid' => $group->getGID()));
339
-			});
340
-			return $groupManager;
341
-		});
342
-		$this->registerAlias('GroupManager', \OCP\IGroupManager::class);
343
-
344
-		$this->registerService(Store::class, function (Server $c) {
345
-			$session = $c->getSession();
346
-			if (\OC::$server->getSystemConfig()->getValue('installed', false)) {
347
-				$tokenProvider = $c->query(IProvider::class);
348
-			} else {
349
-				$tokenProvider = null;
350
-			}
351
-			$logger = $c->getLogger();
352
-			return new Store($session, $logger, $tokenProvider);
353
-		});
354
-		$this->registerAlias(IStore::class, Store::class);
355
-		$this->registerService(Authentication\Token\DefaultTokenMapper::class, function (Server $c) {
356
-			$dbConnection = $c->getDatabaseConnection();
357
-			return new Authentication\Token\DefaultTokenMapper($dbConnection);
358
-		});
359
-		$this->registerAlias(IProvider::class, Authentication\Token\Manager::class);
360
-
361
-		$this->registerService(\OCP\IUserSession::class, function (Server $c) {
362
-			$manager = $c->getUserManager();
363
-			$session = new \OC\Session\Memory('');
364
-			$timeFactory = new TimeFactory();
365
-			// Token providers might require a working database. This code
366
-			// might however be called when ownCloud is not yet setup.
367
-			if (\OC::$server->getSystemConfig()->getValue('installed', false)) {
368
-				$defaultTokenProvider = $c->query(IProvider::class);
369
-			} else {
370
-				$defaultTokenProvider = null;
371
-			}
372
-
373
-			$dispatcher = $c->getEventDispatcher();
374
-
375
-			$userSession = new \OC\User\Session(
376
-				$manager,
377
-				$session,
378
-				$timeFactory,
379
-				$defaultTokenProvider,
380
-				$c->getConfig(),
381
-				$c->getSecureRandom(),
382
-				$c->getLockdownManager(),
383
-				$c->getLogger()
384
-			);
385
-			$userSession->listen('\OC\User', 'preCreateUser', function ($uid, $password) {
386
-				\OC_Hook::emit('OC_User', 'pre_createUser', array('run' => true, 'uid' => $uid, 'password' => $password));
387
-			});
388
-			$userSession->listen('\OC\User', 'postCreateUser', function ($user, $password) {
389
-				/** @var $user \OC\User\User */
390
-				\OC_Hook::emit('OC_User', 'post_createUser', array('uid' => $user->getUID(), 'password' => $password));
391
-			});
392
-			$userSession->listen('\OC\User', 'preDelete', function ($user) use ($dispatcher) {
393
-				/** @var $user \OC\User\User */
394
-				\OC_Hook::emit('OC_User', 'pre_deleteUser', array('run' => true, 'uid' => $user->getUID()));
395
-				$dispatcher->dispatch('OCP\IUser::preDelete', new GenericEvent($user));
396
-			});
397
-			$userSession->listen('\OC\User', 'postDelete', function ($user) {
398
-				/** @var $user \OC\User\User */
399
-				\OC_Hook::emit('OC_User', 'post_deleteUser', array('uid' => $user->getUID()));
400
-			});
401
-			$userSession->listen('\OC\User', 'preSetPassword', function ($user, $password, $recoveryPassword) {
402
-				/** @var $user \OC\User\User */
403
-				\OC_Hook::emit('OC_User', 'pre_setPassword', array('run' => true, 'uid' => $user->getUID(), 'password' => $password, 'recoveryPassword' => $recoveryPassword));
404
-			});
405
-			$userSession->listen('\OC\User', 'postSetPassword', function ($user, $password, $recoveryPassword) {
406
-				/** @var $user \OC\User\User */
407
-				\OC_Hook::emit('OC_User', 'post_setPassword', array('run' => true, 'uid' => $user->getUID(), 'password' => $password, 'recoveryPassword' => $recoveryPassword));
408
-			});
409
-			$userSession->listen('\OC\User', 'preLogin', function ($uid, $password) {
410
-				\OC_Hook::emit('OC_User', 'pre_login', array('run' => true, 'uid' => $uid, 'password' => $password));
411
-			});
412
-			$userSession->listen('\OC\User', 'postLogin', function ($user, $password) {
413
-				/** @var $user \OC\User\User */
414
-				\OC_Hook::emit('OC_User', 'post_login', array('run' => true, 'uid' => $user->getUID(), 'password' => $password));
415
-			});
416
-			$userSession->listen('\OC\User', 'postRememberedLogin', function ($user, $password) {
417
-				/** @var $user \OC\User\User */
418
-				\OC_Hook::emit('OC_User', 'post_login', array('run' => true, 'uid' => $user->getUID(), 'password' => $password));
419
-			});
420
-			$userSession->listen('\OC\User', 'logout', function () {
421
-				\OC_Hook::emit('OC_User', 'logout', array());
422
-			});
423
-			$userSession->listen('\OC\User', 'changeUser', function ($user, $feature, $value, $oldValue) use ($dispatcher) {
424
-				/** @var $user \OC\User\User */
425
-				\OC_Hook::emit('OC_User', 'changeUser', array('run' => true, 'user' => $user, 'feature' => $feature, 'value' => $value, 'old_value' => $oldValue));
426
-				$dispatcher->dispatch('OCP\IUser::changeUser', new GenericEvent($user, ['feature' => $feature, 'oldValue' => $oldValue, 'value' => $value]));
427
-			});
428
-			return $userSession;
429
-		});
430
-		$this->registerAlias('UserSession', \OCP\IUserSession::class);
431
-
432
-		$this->registerAlias(\OCP\Authentication\TwoFactorAuth\IRegistry::class, \OC\Authentication\TwoFactorAuth\Registry::class);
433
-
434
-		$this->registerAlias(\OCP\INavigationManager::class, \OC\NavigationManager::class);
435
-		$this->registerAlias('NavigationManager', \OCP\INavigationManager::class);
436
-
437
-		$this->registerService(\OC\AllConfig::class, function (Server $c) {
438
-			return new \OC\AllConfig(
439
-				$c->getSystemConfig()
440
-			);
441
-		});
442
-		$this->registerAlias('AllConfig', \OC\AllConfig::class);
443
-		$this->registerAlias(\OCP\IConfig::class, \OC\AllConfig::class);
444
-
445
-		$this->registerService('SystemConfig', function ($c) use ($config) {
446
-			return new \OC\SystemConfig($config);
447
-		});
448
-
449
-		$this->registerService(\OC\AppConfig::class, function (Server $c) {
450
-			return new \OC\AppConfig($c->getDatabaseConnection());
451
-		});
452
-		$this->registerAlias('AppConfig', \OC\AppConfig::class);
453
-		$this->registerAlias(\OCP\IAppConfig::class, \OC\AppConfig::class);
454
-
455
-		$this->registerService(\OCP\L10N\IFactory::class, function (Server $c) {
456
-			return new \OC\L10N\Factory(
457
-				$c->getConfig(),
458
-				$c->getRequest(),
459
-				$c->getUserSession(),
460
-				\OC::$SERVERROOT
461
-			);
462
-		});
463
-		$this->registerAlias('L10NFactory', \OCP\L10N\IFactory::class);
464
-
465
-		$this->registerService(\OCP\IURLGenerator::class, function (Server $c) {
466
-			$config = $c->getConfig();
467
-			$cacheFactory = $c->getMemCacheFactory();
468
-			$request = $c->getRequest();
469
-			return new \OC\URLGenerator(
470
-				$config,
471
-				$cacheFactory,
472
-				$request
473
-			);
474
-		});
475
-		$this->registerAlias('URLGenerator', \OCP\IURLGenerator::class);
476
-
477
-		$this->registerAlias('AppFetcher', AppFetcher::class);
478
-		$this->registerAlias('CategoryFetcher', CategoryFetcher::class);
479
-
480
-		$this->registerService(\OCP\ICache::class, function ($c) {
481
-			return new Cache\File();
482
-		});
483
-		$this->registerAlias('UserCache', \OCP\ICache::class);
484
-
485
-		$this->registerService(Factory::class, function (Server $c) {
486
-
487
-			$arrayCacheFactory = new \OC\Memcache\Factory('', $c->getLogger(),
488
-				ArrayCache::class,
489
-				ArrayCache::class,
490
-				ArrayCache::class
491
-			);
492
-			$config = $c->getConfig();
493
-			$request = $c->getRequest();
494
-			$urlGenerator = new URLGenerator($config, $arrayCacheFactory, $request);
495
-
496
-			if ($config->getSystemValue('installed', false) && !(defined('PHPUNIT_RUN') && PHPUNIT_RUN)) {
497
-				$v = \OC_App::getAppVersions();
498
-				$v['core'] = implode(',', \OC_Util::getVersion());
499
-				$version = implode(',', $v);
500
-				$instanceId = \OC_Util::getInstanceId();
501
-				$path = \OC::$SERVERROOT;
502
-				$prefix = md5($instanceId . '-' . $version . '-' . $path);
503
-				return new \OC\Memcache\Factory($prefix, $c->getLogger(),
504
-					$config->getSystemValue('memcache.local', null),
505
-					$config->getSystemValue('memcache.distributed', null),
506
-					$config->getSystemValue('memcache.locking', null)
507
-				);
508
-			}
509
-			return $arrayCacheFactory;
510
-
511
-		});
512
-		$this->registerAlias('MemCacheFactory', Factory::class);
513
-		$this->registerAlias(ICacheFactory::class, Factory::class);
514
-
515
-		$this->registerService('RedisFactory', function (Server $c) {
516
-			$systemConfig = $c->getSystemConfig();
517
-			return new RedisFactory($systemConfig);
518
-		});
519
-
520
-		$this->registerService(\OCP\Activity\IManager::class, function (Server $c) {
521
-			return new \OC\Activity\Manager(
522
-				$c->getRequest(),
523
-				$c->getUserSession(),
524
-				$c->getConfig(),
525
-				$c->query(IValidator::class)
526
-			);
527
-		});
528
-		$this->registerAlias('ActivityManager', \OCP\Activity\IManager::class);
529
-
530
-		$this->registerService(\OCP\Activity\IEventMerger::class, function (Server $c) {
531
-			return new \OC\Activity\EventMerger(
532
-				$c->getL10N('lib')
533
-			);
534
-		});
535
-		$this->registerAlias(IValidator::class, Validator::class);
536
-
537
-		$this->registerService(\OCP\IAvatarManager::class, function (Server $c) {
538
-			return new AvatarManager(
539
-				$c->query(\OC\User\Manager::class),
540
-				$c->getAppDataDir('avatar'),
541
-				$c->getL10N('lib'),
542
-				$c->getLogger(),
543
-				$c->getConfig()
544
-			);
545
-		});
546
-		$this->registerAlias('AvatarManager', \OCP\IAvatarManager::class);
547
-
548
-		$this->registerAlias(\OCP\Support\CrashReport\IRegistry::class, \OC\Support\CrashReport\Registry::class);
549
-
550
-		$this->registerService(\OCP\ILogger::class, function (Server $c) {
551
-			$logType = $c->query('AllConfig')->getSystemValue('log_type', 'file');
552
-			$factory = new LogFactory($c, $this->getSystemConfig());
553
-			$logger = $factory->get($logType);
554
-			$registry = $c->query(\OCP\Support\CrashReport\IRegistry::class);
555
-
556
-			return new Log($logger, $this->getSystemConfig(), null, $registry);
557
-		});
558
-		$this->registerAlias('Logger', \OCP\ILogger::class);
559
-
560
-		$this->registerService(ILogFactory::class, function (Server $c) {
561
-			return new LogFactory($c, $this->getSystemConfig());
562
-		});
563
-
564
-		$this->registerService(\OCP\BackgroundJob\IJobList::class, function (Server $c) {
565
-			$config = $c->getConfig();
566
-			return new \OC\BackgroundJob\JobList(
567
-				$c->getDatabaseConnection(),
568
-				$config,
569
-				new TimeFactory()
570
-			);
571
-		});
572
-		$this->registerAlias('JobList', \OCP\BackgroundJob\IJobList::class);
573
-
574
-		$this->registerService(\OCP\Route\IRouter::class, function (Server $c) {
575
-			$cacheFactory = $c->getMemCacheFactory();
576
-			$logger = $c->getLogger();
577
-			if ($cacheFactory->isLocalCacheAvailable()) {
578
-				$router = new \OC\Route\CachingRouter($cacheFactory->createLocal('route'), $logger);
579
-			} else {
580
-				$router = new \OC\Route\Router($logger);
581
-			}
582
-			return $router;
583
-		});
584
-		$this->registerAlias('Router', \OCP\Route\IRouter::class);
585
-
586
-		$this->registerService(\OCP\ISearch::class, function ($c) {
587
-			return new Search();
588
-		});
589
-		$this->registerAlias('Search', \OCP\ISearch::class);
590
-
591
-		$this->registerService(\OC\Security\RateLimiting\Limiter::class, function (Server $c) {
592
-			return new \OC\Security\RateLimiting\Limiter(
593
-				$this->getUserSession(),
594
-				$this->getRequest(),
595
-				new \OC\AppFramework\Utility\TimeFactory(),
596
-				$c->query(\OC\Security\RateLimiting\Backend\IBackend::class)
597
-			);
598
-		});
599
-		$this->registerService(\OC\Security\RateLimiting\Backend\IBackend::class, function ($c) {
600
-			return new \OC\Security\RateLimiting\Backend\MemoryCache(
601
-				$this->getMemCacheFactory(),
602
-				new \OC\AppFramework\Utility\TimeFactory()
603
-			);
604
-		});
605
-
606
-		$this->registerService(\OCP\Security\ISecureRandom::class, function ($c) {
607
-			return new SecureRandom();
608
-		});
609
-		$this->registerAlias('SecureRandom', \OCP\Security\ISecureRandom::class);
610
-
611
-		$this->registerService(\OCP\Security\ICrypto::class, function (Server $c) {
612
-			return new Crypto($c->getConfig(), $c->getSecureRandom());
613
-		});
614
-		$this->registerAlias('Crypto', \OCP\Security\ICrypto::class);
615
-
616
-		$this->registerService(\OCP\Security\IHasher::class, function (Server $c) {
617
-			return new Hasher($c->getConfig());
618
-		});
619
-		$this->registerAlias('Hasher', \OCP\Security\IHasher::class);
620
-
621
-		$this->registerService(\OCP\Security\ICredentialsManager::class, function (Server $c) {
622
-			return new CredentialsManager($c->getCrypto(), $c->getDatabaseConnection());
623
-		});
624
-		$this->registerAlias('CredentialsManager', \OCP\Security\ICredentialsManager::class);
625
-
626
-		$this->registerService(IDBConnection::class, function (Server $c) {
627
-			$systemConfig = $c->getSystemConfig();
628
-			$factory = new \OC\DB\ConnectionFactory($systemConfig);
629
-			$type = $systemConfig->getValue('dbtype', 'sqlite');
630
-			if (!$factory->isValidType($type)) {
631
-				throw new \OC\DatabaseException('Invalid database type');
632
-			}
633
-			$connectionParams = $factory->createConnectionParams();
634
-			$connection = $factory->getConnection($type, $connectionParams);
635
-			$connection->getConfiguration()->setSQLLogger($c->getQueryLogger());
636
-			return $connection;
637
-		});
638
-		$this->registerAlias('DatabaseConnection', IDBConnection::class);
639
-
640
-
641
-		$this->registerService(\OCP\Http\Client\IClientService::class, function (Server $c) {
642
-			$user = \OC_User::getUser();
643
-			$uid = $user ? $user : null;
644
-			return new ClientService(
645
-				$c->getConfig(),
646
-				new \OC\Security\CertificateManager(
647
-					$uid,
648
-					new View(),
649
-					$c->getConfig(),
650
-					$c->getLogger(),
651
-					$c->getSecureRandom()
652
-				)
653
-			);
654
-		});
655
-		$this->registerAlias('HttpClientService', \OCP\Http\Client\IClientService::class);
656
-		$this->registerService(\OCP\Diagnostics\IEventLogger::class, function (Server $c) {
657
-			$eventLogger = new EventLogger();
658
-			if ($c->getSystemConfig()->getValue('debug', false)) {
659
-				// In debug mode, module is being activated by default
660
-				$eventLogger->activate();
661
-			}
662
-			return $eventLogger;
663
-		});
664
-		$this->registerAlias('EventLogger', \OCP\Diagnostics\IEventLogger::class);
665
-
666
-		$this->registerService(\OCP\Diagnostics\IQueryLogger::class, function (Server $c) {
667
-			$queryLogger = new QueryLogger();
668
-			if ($c->getSystemConfig()->getValue('debug', false)) {
669
-				// In debug mode, module is being activated by default
670
-				$queryLogger->activate();
671
-			}
672
-			return $queryLogger;
673
-		});
674
-		$this->registerAlias('QueryLogger', \OCP\Diagnostics\IQueryLogger::class);
675
-
676
-		$this->registerService(TempManager::class, function (Server $c) {
677
-			return new TempManager(
678
-				$c->getLogger(),
679
-				$c->getConfig()
680
-			);
681
-		});
682
-		$this->registerAlias('TempManager', TempManager::class);
683
-		$this->registerAlias(ITempManager::class, TempManager::class);
684
-
685
-		$this->registerService(AppManager::class, function (Server $c) {
686
-			return new \OC\App\AppManager(
687
-				$c->getUserSession(),
688
-				$c->query(\OC\AppConfig::class),
689
-				$c->getGroupManager(),
690
-				$c->getMemCacheFactory(),
691
-				$c->getEventDispatcher()
692
-			);
693
-		});
694
-		$this->registerAlias('AppManager', AppManager::class);
695
-		$this->registerAlias(IAppManager::class, AppManager::class);
696
-
697
-		$this->registerService(\OCP\IDateTimeZone::class, function (Server $c) {
698
-			return new DateTimeZone(
699
-				$c->getConfig(),
700
-				$c->getSession()
701
-			);
702
-		});
703
-		$this->registerAlias('DateTimeZone', \OCP\IDateTimeZone::class);
704
-
705
-		$this->registerService(\OCP\IDateTimeFormatter::class, function (Server $c) {
706
-			$language = $c->getConfig()->getUserValue($c->getSession()->get('user_id'), 'core', 'lang', null);
707
-
708
-			return new DateTimeFormatter(
709
-				$c->getDateTimeZone()->getTimeZone(),
710
-				$c->getL10N('lib', $language)
711
-			);
712
-		});
713
-		$this->registerAlias('DateTimeFormatter', \OCP\IDateTimeFormatter::class);
714
-
715
-		$this->registerService(\OCP\Files\Config\IUserMountCache::class, function (Server $c) {
716
-			$mountCache = new UserMountCache($c->getDatabaseConnection(), $c->getUserManager(), $c->getLogger());
717
-			$listener = new UserMountCacheListener($mountCache);
718
-			$listener->listen($c->getUserManager());
719
-			return $mountCache;
720
-		});
721
-		$this->registerAlias('UserMountCache', \OCP\Files\Config\IUserMountCache::class);
722
-
723
-		$this->registerService(\OCP\Files\Config\IMountProviderCollection::class, function (Server $c) {
724
-			$loader = \OC\Files\Filesystem::getLoader();
725
-			$mountCache = $c->query('UserMountCache');
726
-			$manager = new \OC\Files\Config\MountProviderCollection($loader, $mountCache);
727
-
728
-			// builtin providers
729
-
730
-			$config = $c->getConfig();
731
-			$manager->registerProvider(new CacheMountProvider($config));
732
-			$manager->registerHomeProvider(new LocalHomeMountProvider());
733
-			$manager->registerHomeProvider(new ObjectHomeMountProvider($config));
734
-
735
-			return $manager;
736
-		});
737
-		$this->registerAlias('MountConfigManager', \OCP\Files\Config\IMountProviderCollection::class);
738
-
739
-		$this->registerService('IniWrapper', function ($c) {
740
-			return new IniGetWrapper();
741
-		});
742
-		$this->registerService('AsyncCommandBus', function (Server $c) {
743
-			$busClass = $c->getConfig()->getSystemValue('commandbus');
744
-			if ($busClass) {
745
-				list($app, $class) = explode('::', $busClass, 2);
746
-				if ($c->getAppManager()->isInstalled($app)) {
747
-					\OC_App::loadApp($app);
748
-					return $c->query($class);
749
-				} else {
750
-					throw new ServiceUnavailableException("The app providing the command bus ($app) is not enabled");
751
-				}
752
-			} else {
753
-				$jobList = $c->getJobList();
754
-				return new CronBus($jobList);
755
-			}
756
-		});
757
-		$this->registerService('TrustedDomainHelper', function ($c) {
758
-			return new TrustedDomainHelper($this->getConfig());
759
-		});
760
-		$this->registerService('Throttler', function (Server $c) {
761
-			return new Throttler(
762
-				$c->getDatabaseConnection(),
763
-				new TimeFactory(),
764
-				$c->getLogger(),
765
-				$c->getConfig()
766
-			);
767
-		});
768
-		$this->registerService('IntegrityCodeChecker', function (Server $c) {
769
-			// IConfig and IAppManager requires a working database. This code
770
-			// might however be called when ownCloud is not yet setup.
771
-			if (\OC::$server->getSystemConfig()->getValue('installed', false)) {
772
-				$config = $c->getConfig();
773
-				$appManager = $c->getAppManager();
774
-			} else {
775
-				$config = null;
776
-				$appManager = null;
777
-			}
778
-
779
-			return new Checker(
780
-				new EnvironmentHelper(),
781
-				new FileAccessHelper(),
782
-				new AppLocator(),
783
-				$config,
784
-				$c->getMemCacheFactory(),
785
-				$appManager,
786
-				$c->getTempManager()
787
-			);
788
-		});
789
-		$this->registerService(\OCP\IRequest::class, function ($c) {
790
-			if (isset($this['urlParams'])) {
791
-				$urlParams = $this['urlParams'];
792
-			} else {
793
-				$urlParams = [];
794
-			}
795
-
796
-			if (defined('PHPUNIT_RUN') && PHPUNIT_RUN
797
-				&& in_array('fakeinput', stream_get_wrappers())
798
-			) {
799
-				$stream = 'fakeinput://data';
800
-			} else {
801
-				$stream = 'php://input';
802
-			}
803
-
804
-			return new Request(
805
-				[
806
-					'get' => $_GET,
807
-					'post' => $_POST,
808
-					'files' => $_FILES,
809
-					'server' => $_SERVER,
810
-					'env' => $_ENV,
811
-					'cookies' => $_COOKIE,
812
-					'method' => (isset($_SERVER) && isset($_SERVER['REQUEST_METHOD']))
813
-						? $_SERVER['REQUEST_METHOD']
814
-						: '',
815
-					'urlParams' => $urlParams,
816
-				],
817
-				$this->getSecureRandom(),
818
-				$this->getConfig(),
819
-				$this->getCsrfTokenManager(),
820
-				$stream
821
-			);
822
-		});
823
-		$this->registerAlias('Request', \OCP\IRequest::class);
824
-
825
-		$this->registerService(\OCP\Mail\IMailer::class, function (Server $c) {
826
-			return new Mailer(
827
-				$c->getConfig(),
828
-				$c->getLogger(),
829
-				$c->query(Defaults::class),
830
-				$c->getURLGenerator(),
831
-				$c->getL10N('lib')
832
-			);
833
-		});
834
-		$this->registerAlias('Mailer', \OCP\Mail\IMailer::class);
835
-
836
-		$this->registerService('LDAPProvider', function (Server $c) {
837
-			$config = $c->getConfig();
838
-			$factoryClass = $config->getSystemValue('ldapProviderFactory', null);
839
-			if (is_null($factoryClass)) {
840
-				throw new \Exception('ldapProviderFactory not set');
841
-			}
842
-			/** @var \OCP\LDAP\ILDAPProviderFactory $factory */
843
-			$factory = new $factoryClass($this);
844
-			return $factory->getLDAPProvider();
845
-		});
846
-		$this->registerService(ILockingProvider::class, function (Server $c) {
847
-			$ini = $c->getIniWrapper();
848
-			$config = $c->getConfig();
849
-			$ttl = $config->getSystemValue('filelocking.ttl', max(3600, $ini->getNumeric('max_execution_time')));
850
-			if ($config->getSystemValue('filelocking.enabled', true) or (defined('PHPUNIT_RUN') && PHPUNIT_RUN)) {
851
-				/** @var \OC\Memcache\Factory $memcacheFactory */
852
-				$memcacheFactory = $c->getMemCacheFactory();
853
-				$memcache = $memcacheFactory->createLocking('lock');
854
-				if (!($memcache instanceof \OC\Memcache\NullCache)) {
855
-					return new MemcacheLockingProvider($memcache, $ttl);
856
-				}
857
-				return new DBLockingProvider(
858
-					$c->getDatabaseConnection(),
859
-					$c->getLogger(),
860
-					new TimeFactory(),
861
-					$ttl,
862
-					!\OC::$CLI
863
-				);
864
-			}
865
-			return new NoopLockingProvider();
866
-		});
867
-		$this->registerAlias('LockingProvider', ILockingProvider::class);
868
-
869
-		$this->registerService(\OCP\Files\Mount\IMountManager::class, function () {
870
-			return new \OC\Files\Mount\Manager();
871
-		});
872
-		$this->registerAlias('MountManager', \OCP\Files\Mount\IMountManager::class);
873
-
874
-		$this->registerService(\OCP\Files\IMimeTypeDetector::class, function (Server $c) {
875
-			return new \OC\Files\Type\Detection(
876
-				$c->getURLGenerator(),
877
-				\OC::$configDir,
878
-				\OC::$SERVERROOT . '/resources/config/'
879
-			);
880
-		});
881
-		$this->registerAlias('MimeTypeDetector', \OCP\Files\IMimeTypeDetector::class);
882
-
883
-		$this->registerService(\OCP\Files\IMimeTypeLoader::class, function (Server $c) {
884
-			return new \OC\Files\Type\Loader(
885
-				$c->getDatabaseConnection()
886
-			);
887
-		});
888
-		$this->registerAlias('MimeTypeLoader', \OCP\Files\IMimeTypeLoader::class);
889
-		$this->registerService(BundleFetcher::class, function () {
890
-			return new BundleFetcher($this->getL10N('lib'));
891
-		});
892
-		$this->registerService(\OCP\Notification\IManager::class, function (Server $c) {
893
-			return new Manager(
894
-				$c->query(IValidator::class)
895
-			);
896
-		});
897
-		$this->registerAlias('NotificationManager', \OCP\Notification\IManager::class);
898
-
899
-		$this->registerService(\OC\CapabilitiesManager::class, function (Server $c) {
900
-			$manager = new \OC\CapabilitiesManager($c->getLogger());
901
-			$manager->registerCapability(function () use ($c) {
902
-				return new \OC\OCS\CoreCapabilities($c->getConfig());
903
-			});
904
-			$manager->registerCapability(function () use ($c) {
905
-				return $c->query(\OC\Security\Bruteforce\Capabilities::class);
906
-			});
907
-			return $manager;
908
-		});
909
-		$this->registerAlias('CapabilitiesManager', \OC\CapabilitiesManager::class);
910
-
911
-		$this->registerService(\OCP\Comments\ICommentsManager::class, function (Server $c) {
912
-			$config = $c->getConfig();
913
-			$factoryClass = $config->getSystemValue('comments.managerFactory', CommentsManagerFactory::class);
914
-			/** @var \OCP\Comments\ICommentsManagerFactory $factory */
915
-			$factory = new $factoryClass($this);
916
-			$manager = $factory->getManager();
917
-
918
-			$manager->registerDisplayNameResolver('user', function($id) use ($c) {
919
-				$manager = $c->getUserManager();
920
-				$user = $manager->get($id);
921
-				if(is_null($user)) {
922
-					$l = $c->getL10N('core');
923
-					$displayName = $l->t('Unknown user');
924
-				} else {
925
-					$displayName = $user->getDisplayName();
926
-				}
927
-				return $displayName;
928
-			});
929
-
930
-			return $manager;
931
-		});
932
-		$this->registerAlias('CommentsManager', \OCP\Comments\ICommentsManager::class);
933
-
934
-		$this->registerService('ThemingDefaults', function (Server $c) {
935
-			/*
167
+    /** @var string */
168
+    private $webRoot;
169
+
170
+    /**
171
+     * @param string $webRoot
172
+     * @param \OC\Config $config
173
+     */
174
+    public function __construct($webRoot, \OC\Config $config) {
175
+        parent::__construct();
176
+        $this->webRoot = $webRoot;
177
+
178
+        // To find out if we are running from CLI or not
179
+        $this->registerParameter('isCLI', \OC::$CLI);
180
+
181
+        $this->registerService(\OCP\IServerContainer::class, function (IServerContainer $c) {
182
+            return $c;
183
+        });
184
+
185
+        $this->registerAlias(\OCP\Calendar\IManager::class, \OC\Calendar\Manager::class);
186
+        $this->registerAlias('CalendarManager', \OC\Calendar\Manager::class);
187
+
188
+        $this->registerAlias(\OCP\Calendar\Resource\IManager::class, \OC\Calendar\Resource\Manager::class);
189
+        $this->registerAlias('CalendarResourceBackendManager', \OC\Calendar\Resource\Manager::class);
190
+
191
+        $this->registerAlias(\OCP\Calendar\Room\IManager::class, \OC\Calendar\Room\Manager::class);
192
+        $this->registerAlias('CalendarRoomBackendManager', \OC\Calendar\Room\Manager::class);
193
+
194
+        $this->registerAlias(\OCP\Contacts\IManager::class, \OC\ContactsManager::class);
195
+        $this->registerAlias('ContactsManager', \OCP\Contacts\IManager::class);
196
+
197
+        $this->registerAlias(IActionFactory::class, ActionFactory::class);
198
+
199
+
200
+        $this->registerService(\OCP\IPreview::class, function (Server $c) {
201
+            return new PreviewManager(
202
+                $c->getConfig(),
203
+                $c->getRootFolder(),
204
+                $c->getAppDataDir('preview'),
205
+                $c->getEventDispatcher(),
206
+                $c->getSession()->get('user_id')
207
+            );
208
+        });
209
+        $this->registerAlias('PreviewManager', \OCP\IPreview::class);
210
+
211
+        $this->registerService(\OC\Preview\Watcher::class, function (Server $c) {
212
+            return new \OC\Preview\Watcher(
213
+                $c->getAppDataDir('preview')
214
+            );
215
+        });
216
+
217
+        $this->registerService('EncryptionManager', function (Server $c) {
218
+            $view = new View();
219
+            $util = new Encryption\Util(
220
+                $view,
221
+                $c->getUserManager(),
222
+                $c->getGroupManager(),
223
+                $c->getConfig()
224
+            );
225
+            return new Encryption\Manager(
226
+                $c->getConfig(),
227
+                $c->getLogger(),
228
+                $c->getL10N('core'),
229
+                new View(),
230
+                $util,
231
+                new ArrayCache()
232
+            );
233
+        });
234
+
235
+        $this->registerService('EncryptionFileHelper', function (Server $c) {
236
+            $util = new Encryption\Util(
237
+                new View(),
238
+                $c->getUserManager(),
239
+                $c->getGroupManager(),
240
+                $c->getConfig()
241
+            );
242
+            return new Encryption\File(
243
+                $util,
244
+                $c->getRootFolder(),
245
+                $c->getShareManager()
246
+            );
247
+        });
248
+
249
+        $this->registerService('EncryptionKeyStorage', function (Server $c) {
250
+            $view = new View();
251
+            $util = new Encryption\Util(
252
+                $view,
253
+                $c->getUserManager(),
254
+                $c->getGroupManager(),
255
+                $c->getConfig()
256
+            );
257
+
258
+            return new Encryption\Keys\Storage($view, $util);
259
+        });
260
+        $this->registerService('TagMapper', function (Server $c) {
261
+            return new TagMapper($c->getDatabaseConnection());
262
+        });
263
+
264
+        $this->registerService(\OCP\ITagManager::class, function (Server $c) {
265
+            $tagMapper = $c->query('TagMapper');
266
+            return new TagManager($tagMapper, $c->getUserSession());
267
+        });
268
+        $this->registerAlias('TagManager', \OCP\ITagManager::class);
269
+
270
+        $this->registerService('SystemTagManagerFactory', function (Server $c) {
271
+            $config = $c->getConfig();
272
+            $factoryClass = $config->getSystemValue('systemtags.managerFactory', SystemTagManagerFactory::class);
273
+            return new $factoryClass($this);
274
+        });
275
+        $this->registerService(\OCP\SystemTag\ISystemTagManager::class, function (Server $c) {
276
+            return $c->query('SystemTagManagerFactory')->getManager();
277
+        });
278
+        $this->registerAlias('SystemTagManager', \OCP\SystemTag\ISystemTagManager::class);
279
+
280
+        $this->registerService(\OCP\SystemTag\ISystemTagObjectMapper::class, function (Server $c) {
281
+            return $c->query('SystemTagManagerFactory')->getObjectMapper();
282
+        });
283
+        $this->registerService('RootFolder', function (Server $c) {
284
+            $manager = \OC\Files\Filesystem::getMountManager(null);
285
+            $view = new View();
286
+            $root = new Root(
287
+                $manager,
288
+                $view,
289
+                null,
290
+                $c->getUserMountCache(),
291
+                $this->getLogger(),
292
+                $this->getUserManager()
293
+            );
294
+            $connector = new HookConnector($root, $view);
295
+            $connector->viewToNode();
296
+
297
+            $previewConnector = new \OC\Preview\WatcherConnector($root, $c->getSystemConfig());
298
+            $previewConnector->connectWatcher();
299
+
300
+            return $root;
301
+        });
302
+        $this->registerAlias('SystemTagObjectMapper', \OCP\SystemTag\ISystemTagObjectMapper::class);
303
+
304
+        $this->registerService(\OCP\Files\IRootFolder::class, function (Server $c) {
305
+            return new LazyRoot(function () use ($c) {
306
+                return $c->query('RootFolder');
307
+            });
308
+        });
309
+        $this->registerAlias('LazyRootFolder', \OCP\Files\IRootFolder::class);
310
+
311
+        $this->registerService(\OC\User\Manager::class, function (Server $c) {
312
+            $config = $c->getConfig();
313
+            return new \OC\User\Manager($config);
314
+        });
315
+        $this->registerAlias('UserManager', \OC\User\Manager::class);
316
+        $this->registerAlias(\OCP\IUserManager::class, \OC\User\Manager::class);
317
+
318
+        $this->registerService(\OCP\IGroupManager::class, function (Server $c) {
319
+            $groupManager = new \OC\Group\Manager($this->getUserManager(), $this->getLogger());
320
+            $groupManager->listen('\OC\Group', 'preCreate', function ($gid) {
321
+                \OC_Hook::emit('OC_Group', 'pre_createGroup', array('run' => true, 'gid' => $gid));
322
+            });
323
+            $groupManager->listen('\OC\Group', 'postCreate', function (\OC\Group\Group $gid) {
324
+                \OC_Hook::emit('OC_User', 'post_createGroup', array('gid' => $gid->getGID()));
325
+            });
326
+            $groupManager->listen('\OC\Group', 'preDelete', function (\OC\Group\Group $group) {
327
+                \OC_Hook::emit('OC_Group', 'pre_deleteGroup', array('run' => true, 'gid' => $group->getGID()));
328
+            });
329
+            $groupManager->listen('\OC\Group', 'postDelete', function (\OC\Group\Group $group) {
330
+                \OC_Hook::emit('OC_User', 'post_deleteGroup', array('gid' => $group->getGID()));
331
+            });
332
+            $groupManager->listen('\OC\Group', 'preAddUser', function (\OC\Group\Group $group, \OC\User\User $user) {
333
+                \OC_Hook::emit('OC_Group', 'pre_addToGroup', array('run' => true, 'uid' => $user->getUID(), 'gid' => $group->getGID()));
334
+            });
335
+            $groupManager->listen('\OC\Group', 'postAddUser', function (\OC\Group\Group $group, \OC\User\User $user) {
336
+                \OC_Hook::emit('OC_Group', 'post_addToGroup', array('uid' => $user->getUID(), 'gid' => $group->getGID()));
337
+                //Minimal fix to keep it backward compatible TODO: clean up all the GroupManager hooks
338
+                \OC_Hook::emit('OC_User', 'post_addToGroup', array('uid' => $user->getUID(), 'gid' => $group->getGID()));
339
+            });
340
+            return $groupManager;
341
+        });
342
+        $this->registerAlias('GroupManager', \OCP\IGroupManager::class);
343
+
344
+        $this->registerService(Store::class, function (Server $c) {
345
+            $session = $c->getSession();
346
+            if (\OC::$server->getSystemConfig()->getValue('installed', false)) {
347
+                $tokenProvider = $c->query(IProvider::class);
348
+            } else {
349
+                $tokenProvider = null;
350
+            }
351
+            $logger = $c->getLogger();
352
+            return new Store($session, $logger, $tokenProvider);
353
+        });
354
+        $this->registerAlias(IStore::class, Store::class);
355
+        $this->registerService(Authentication\Token\DefaultTokenMapper::class, function (Server $c) {
356
+            $dbConnection = $c->getDatabaseConnection();
357
+            return new Authentication\Token\DefaultTokenMapper($dbConnection);
358
+        });
359
+        $this->registerAlias(IProvider::class, Authentication\Token\Manager::class);
360
+
361
+        $this->registerService(\OCP\IUserSession::class, function (Server $c) {
362
+            $manager = $c->getUserManager();
363
+            $session = new \OC\Session\Memory('');
364
+            $timeFactory = new TimeFactory();
365
+            // Token providers might require a working database. This code
366
+            // might however be called when ownCloud is not yet setup.
367
+            if (\OC::$server->getSystemConfig()->getValue('installed', false)) {
368
+                $defaultTokenProvider = $c->query(IProvider::class);
369
+            } else {
370
+                $defaultTokenProvider = null;
371
+            }
372
+
373
+            $dispatcher = $c->getEventDispatcher();
374
+
375
+            $userSession = new \OC\User\Session(
376
+                $manager,
377
+                $session,
378
+                $timeFactory,
379
+                $defaultTokenProvider,
380
+                $c->getConfig(),
381
+                $c->getSecureRandom(),
382
+                $c->getLockdownManager(),
383
+                $c->getLogger()
384
+            );
385
+            $userSession->listen('\OC\User', 'preCreateUser', function ($uid, $password) {
386
+                \OC_Hook::emit('OC_User', 'pre_createUser', array('run' => true, 'uid' => $uid, 'password' => $password));
387
+            });
388
+            $userSession->listen('\OC\User', 'postCreateUser', function ($user, $password) {
389
+                /** @var $user \OC\User\User */
390
+                \OC_Hook::emit('OC_User', 'post_createUser', array('uid' => $user->getUID(), 'password' => $password));
391
+            });
392
+            $userSession->listen('\OC\User', 'preDelete', function ($user) use ($dispatcher) {
393
+                /** @var $user \OC\User\User */
394
+                \OC_Hook::emit('OC_User', 'pre_deleteUser', array('run' => true, 'uid' => $user->getUID()));
395
+                $dispatcher->dispatch('OCP\IUser::preDelete', new GenericEvent($user));
396
+            });
397
+            $userSession->listen('\OC\User', 'postDelete', function ($user) {
398
+                /** @var $user \OC\User\User */
399
+                \OC_Hook::emit('OC_User', 'post_deleteUser', array('uid' => $user->getUID()));
400
+            });
401
+            $userSession->listen('\OC\User', 'preSetPassword', function ($user, $password, $recoveryPassword) {
402
+                /** @var $user \OC\User\User */
403
+                \OC_Hook::emit('OC_User', 'pre_setPassword', array('run' => true, 'uid' => $user->getUID(), 'password' => $password, 'recoveryPassword' => $recoveryPassword));
404
+            });
405
+            $userSession->listen('\OC\User', 'postSetPassword', function ($user, $password, $recoveryPassword) {
406
+                /** @var $user \OC\User\User */
407
+                \OC_Hook::emit('OC_User', 'post_setPassword', array('run' => true, 'uid' => $user->getUID(), 'password' => $password, 'recoveryPassword' => $recoveryPassword));
408
+            });
409
+            $userSession->listen('\OC\User', 'preLogin', function ($uid, $password) {
410
+                \OC_Hook::emit('OC_User', 'pre_login', array('run' => true, 'uid' => $uid, 'password' => $password));
411
+            });
412
+            $userSession->listen('\OC\User', 'postLogin', function ($user, $password) {
413
+                /** @var $user \OC\User\User */
414
+                \OC_Hook::emit('OC_User', 'post_login', array('run' => true, 'uid' => $user->getUID(), 'password' => $password));
415
+            });
416
+            $userSession->listen('\OC\User', 'postRememberedLogin', function ($user, $password) {
417
+                /** @var $user \OC\User\User */
418
+                \OC_Hook::emit('OC_User', 'post_login', array('run' => true, 'uid' => $user->getUID(), 'password' => $password));
419
+            });
420
+            $userSession->listen('\OC\User', 'logout', function () {
421
+                \OC_Hook::emit('OC_User', 'logout', array());
422
+            });
423
+            $userSession->listen('\OC\User', 'changeUser', function ($user, $feature, $value, $oldValue) use ($dispatcher) {
424
+                /** @var $user \OC\User\User */
425
+                \OC_Hook::emit('OC_User', 'changeUser', array('run' => true, 'user' => $user, 'feature' => $feature, 'value' => $value, 'old_value' => $oldValue));
426
+                $dispatcher->dispatch('OCP\IUser::changeUser', new GenericEvent($user, ['feature' => $feature, 'oldValue' => $oldValue, 'value' => $value]));
427
+            });
428
+            return $userSession;
429
+        });
430
+        $this->registerAlias('UserSession', \OCP\IUserSession::class);
431
+
432
+        $this->registerAlias(\OCP\Authentication\TwoFactorAuth\IRegistry::class, \OC\Authentication\TwoFactorAuth\Registry::class);
433
+
434
+        $this->registerAlias(\OCP\INavigationManager::class, \OC\NavigationManager::class);
435
+        $this->registerAlias('NavigationManager', \OCP\INavigationManager::class);
436
+
437
+        $this->registerService(\OC\AllConfig::class, function (Server $c) {
438
+            return new \OC\AllConfig(
439
+                $c->getSystemConfig()
440
+            );
441
+        });
442
+        $this->registerAlias('AllConfig', \OC\AllConfig::class);
443
+        $this->registerAlias(\OCP\IConfig::class, \OC\AllConfig::class);
444
+
445
+        $this->registerService('SystemConfig', function ($c) use ($config) {
446
+            return new \OC\SystemConfig($config);
447
+        });
448
+
449
+        $this->registerService(\OC\AppConfig::class, function (Server $c) {
450
+            return new \OC\AppConfig($c->getDatabaseConnection());
451
+        });
452
+        $this->registerAlias('AppConfig', \OC\AppConfig::class);
453
+        $this->registerAlias(\OCP\IAppConfig::class, \OC\AppConfig::class);
454
+
455
+        $this->registerService(\OCP\L10N\IFactory::class, function (Server $c) {
456
+            return new \OC\L10N\Factory(
457
+                $c->getConfig(),
458
+                $c->getRequest(),
459
+                $c->getUserSession(),
460
+                \OC::$SERVERROOT
461
+            );
462
+        });
463
+        $this->registerAlias('L10NFactory', \OCP\L10N\IFactory::class);
464
+
465
+        $this->registerService(\OCP\IURLGenerator::class, function (Server $c) {
466
+            $config = $c->getConfig();
467
+            $cacheFactory = $c->getMemCacheFactory();
468
+            $request = $c->getRequest();
469
+            return new \OC\URLGenerator(
470
+                $config,
471
+                $cacheFactory,
472
+                $request
473
+            );
474
+        });
475
+        $this->registerAlias('URLGenerator', \OCP\IURLGenerator::class);
476
+
477
+        $this->registerAlias('AppFetcher', AppFetcher::class);
478
+        $this->registerAlias('CategoryFetcher', CategoryFetcher::class);
479
+
480
+        $this->registerService(\OCP\ICache::class, function ($c) {
481
+            return new Cache\File();
482
+        });
483
+        $this->registerAlias('UserCache', \OCP\ICache::class);
484
+
485
+        $this->registerService(Factory::class, function (Server $c) {
486
+
487
+            $arrayCacheFactory = new \OC\Memcache\Factory('', $c->getLogger(),
488
+                ArrayCache::class,
489
+                ArrayCache::class,
490
+                ArrayCache::class
491
+            );
492
+            $config = $c->getConfig();
493
+            $request = $c->getRequest();
494
+            $urlGenerator = new URLGenerator($config, $arrayCacheFactory, $request);
495
+
496
+            if ($config->getSystemValue('installed', false) && !(defined('PHPUNIT_RUN') && PHPUNIT_RUN)) {
497
+                $v = \OC_App::getAppVersions();
498
+                $v['core'] = implode(',', \OC_Util::getVersion());
499
+                $version = implode(',', $v);
500
+                $instanceId = \OC_Util::getInstanceId();
501
+                $path = \OC::$SERVERROOT;
502
+                $prefix = md5($instanceId . '-' . $version . '-' . $path);
503
+                return new \OC\Memcache\Factory($prefix, $c->getLogger(),
504
+                    $config->getSystemValue('memcache.local', null),
505
+                    $config->getSystemValue('memcache.distributed', null),
506
+                    $config->getSystemValue('memcache.locking', null)
507
+                );
508
+            }
509
+            return $arrayCacheFactory;
510
+
511
+        });
512
+        $this->registerAlias('MemCacheFactory', Factory::class);
513
+        $this->registerAlias(ICacheFactory::class, Factory::class);
514
+
515
+        $this->registerService('RedisFactory', function (Server $c) {
516
+            $systemConfig = $c->getSystemConfig();
517
+            return new RedisFactory($systemConfig);
518
+        });
519
+
520
+        $this->registerService(\OCP\Activity\IManager::class, function (Server $c) {
521
+            return new \OC\Activity\Manager(
522
+                $c->getRequest(),
523
+                $c->getUserSession(),
524
+                $c->getConfig(),
525
+                $c->query(IValidator::class)
526
+            );
527
+        });
528
+        $this->registerAlias('ActivityManager', \OCP\Activity\IManager::class);
529
+
530
+        $this->registerService(\OCP\Activity\IEventMerger::class, function (Server $c) {
531
+            return new \OC\Activity\EventMerger(
532
+                $c->getL10N('lib')
533
+            );
534
+        });
535
+        $this->registerAlias(IValidator::class, Validator::class);
536
+
537
+        $this->registerService(\OCP\IAvatarManager::class, function (Server $c) {
538
+            return new AvatarManager(
539
+                $c->query(\OC\User\Manager::class),
540
+                $c->getAppDataDir('avatar'),
541
+                $c->getL10N('lib'),
542
+                $c->getLogger(),
543
+                $c->getConfig()
544
+            );
545
+        });
546
+        $this->registerAlias('AvatarManager', \OCP\IAvatarManager::class);
547
+
548
+        $this->registerAlias(\OCP\Support\CrashReport\IRegistry::class, \OC\Support\CrashReport\Registry::class);
549
+
550
+        $this->registerService(\OCP\ILogger::class, function (Server $c) {
551
+            $logType = $c->query('AllConfig')->getSystemValue('log_type', 'file');
552
+            $factory = new LogFactory($c, $this->getSystemConfig());
553
+            $logger = $factory->get($logType);
554
+            $registry = $c->query(\OCP\Support\CrashReport\IRegistry::class);
555
+
556
+            return new Log($logger, $this->getSystemConfig(), null, $registry);
557
+        });
558
+        $this->registerAlias('Logger', \OCP\ILogger::class);
559
+
560
+        $this->registerService(ILogFactory::class, function (Server $c) {
561
+            return new LogFactory($c, $this->getSystemConfig());
562
+        });
563
+
564
+        $this->registerService(\OCP\BackgroundJob\IJobList::class, function (Server $c) {
565
+            $config = $c->getConfig();
566
+            return new \OC\BackgroundJob\JobList(
567
+                $c->getDatabaseConnection(),
568
+                $config,
569
+                new TimeFactory()
570
+            );
571
+        });
572
+        $this->registerAlias('JobList', \OCP\BackgroundJob\IJobList::class);
573
+
574
+        $this->registerService(\OCP\Route\IRouter::class, function (Server $c) {
575
+            $cacheFactory = $c->getMemCacheFactory();
576
+            $logger = $c->getLogger();
577
+            if ($cacheFactory->isLocalCacheAvailable()) {
578
+                $router = new \OC\Route\CachingRouter($cacheFactory->createLocal('route'), $logger);
579
+            } else {
580
+                $router = new \OC\Route\Router($logger);
581
+            }
582
+            return $router;
583
+        });
584
+        $this->registerAlias('Router', \OCP\Route\IRouter::class);
585
+
586
+        $this->registerService(\OCP\ISearch::class, function ($c) {
587
+            return new Search();
588
+        });
589
+        $this->registerAlias('Search', \OCP\ISearch::class);
590
+
591
+        $this->registerService(\OC\Security\RateLimiting\Limiter::class, function (Server $c) {
592
+            return new \OC\Security\RateLimiting\Limiter(
593
+                $this->getUserSession(),
594
+                $this->getRequest(),
595
+                new \OC\AppFramework\Utility\TimeFactory(),
596
+                $c->query(\OC\Security\RateLimiting\Backend\IBackend::class)
597
+            );
598
+        });
599
+        $this->registerService(\OC\Security\RateLimiting\Backend\IBackend::class, function ($c) {
600
+            return new \OC\Security\RateLimiting\Backend\MemoryCache(
601
+                $this->getMemCacheFactory(),
602
+                new \OC\AppFramework\Utility\TimeFactory()
603
+            );
604
+        });
605
+
606
+        $this->registerService(\OCP\Security\ISecureRandom::class, function ($c) {
607
+            return new SecureRandom();
608
+        });
609
+        $this->registerAlias('SecureRandom', \OCP\Security\ISecureRandom::class);
610
+
611
+        $this->registerService(\OCP\Security\ICrypto::class, function (Server $c) {
612
+            return new Crypto($c->getConfig(), $c->getSecureRandom());
613
+        });
614
+        $this->registerAlias('Crypto', \OCP\Security\ICrypto::class);
615
+
616
+        $this->registerService(\OCP\Security\IHasher::class, function (Server $c) {
617
+            return new Hasher($c->getConfig());
618
+        });
619
+        $this->registerAlias('Hasher', \OCP\Security\IHasher::class);
620
+
621
+        $this->registerService(\OCP\Security\ICredentialsManager::class, function (Server $c) {
622
+            return new CredentialsManager($c->getCrypto(), $c->getDatabaseConnection());
623
+        });
624
+        $this->registerAlias('CredentialsManager', \OCP\Security\ICredentialsManager::class);
625
+
626
+        $this->registerService(IDBConnection::class, function (Server $c) {
627
+            $systemConfig = $c->getSystemConfig();
628
+            $factory = new \OC\DB\ConnectionFactory($systemConfig);
629
+            $type = $systemConfig->getValue('dbtype', 'sqlite');
630
+            if (!$factory->isValidType($type)) {
631
+                throw new \OC\DatabaseException('Invalid database type');
632
+            }
633
+            $connectionParams = $factory->createConnectionParams();
634
+            $connection = $factory->getConnection($type, $connectionParams);
635
+            $connection->getConfiguration()->setSQLLogger($c->getQueryLogger());
636
+            return $connection;
637
+        });
638
+        $this->registerAlias('DatabaseConnection', IDBConnection::class);
639
+
640
+
641
+        $this->registerService(\OCP\Http\Client\IClientService::class, function (Server $c) {
642
+            $user = \OC_User::getUser();
643
+            $uid = $user ? $user : null;
644
+            return new ClientService(
645
+                $c->getConfig(),
646
+                new \OC\Security\CertificateManager(
647
+                    $uid,
648
+                    new View(),
649
+                    $c->getConfig(),
650
+                    $c->getLogger(),
651
+                    $c->getSecureRandom()
652
+                )
653
+            );
654
+        });
655
+        $this->registerAlias('HttpClientService', \OCP\Http\Client\IClientService::class);
656
+        $this->registerService(\OCP\Diagnostics\IEventLogger::class, function (Server $c) {
657
+            $eventLogger = new EventLogger();
658
+            if ($c->getSystemConfig()->getValue('debug', false)) {
659
+                // In debug mode, module is being activated by default
660
+                $eventLogger->activate();
661
+            }
662
+            return $eventLogger;
663
+        });
664
+        $this->registerAlias('EventLogger', \OCP\Diagnostics\IEventLogger::class);
665
+
666
+        $this->registerService(\OCP\Diagnostics\IQueryLogger::class, function (Server $c) {
667
+            $queryLogger = new QueryLogger();
668
+            if ($c->getSystemConfig()->getValue('debug', false)) {
669
+                // In debug mode, module is being activated by default
670
+                $queryLogger->activate();
671
+            }
672
+            return $queryLogger;
673
+        });
674
+        $this->registerAlias('QueryLogger', \OCP\Diagnostics\IQueryLogger::class);
675
+
676
+        $this->registerService(TempManager::class, function (Server $c) {
677
+            return new TempManager(
678
+                $c->getLogger(),
679
+                $c->getConfig()
680
+            );
681
+        });
682
+        $this->registerAlias('TempManager', TempManager::class);
683
+        $this->registerAlias(ITempManager::class, TempManager::class);
684
+
685
+        $this->registerService(AppManager::class, function (Server $c) {
686
+            return new \OC\App\AppManager(
687
+                $c->getUserSession(),
688
+                $c->query(\OC\AppConfig::class),
689
+                $c->getGroupManager(),
690
+                $c->getMemCacheFactory(),
691
+                $c->getEventDispatcher()
692
+            );
693
+        });
694
+        $this->registerAlias('AppManager', AppManager::class);
695
+        $this->registerAlias(IAppManager::class, AppManager::class);
696
+
697
+        $this->registerService(\OCP\IDateTimeZone::class, function (Server $c) {
698
+            return new DateTimeZone(
699
+                $c->getConfig(),
700
+                $c->getSession()
701
+            );
702
+        });
703
+        $this->registerAlias('DateTimeZone', \OCP\IDateTimeZone::class);
704
+
705
+        $this->registerService(\OCP\IDateTimeFormatter::class, function (Server $c) {
706
+            $language = $c->getConfig()->getUserValue($c->getSession()->get('user_id'), 'core', 'lang', null);
707
+
708
+            return new DateTimeFormatter(
709
+                $c->getDateTimeZone()->getTimeZone(),
710
+                $c->getL10N('lib', $language)
711
+            );
712
+        });
713
+        $this->registerAlias('DateTimeFormatter', \OCP\IDateTimeFormatter::class);
714
+
715
+        $this->registerService(\OCP\Files\Config\IUserMountCache::class, function (Server $c) {
716
+            $mountCache = new UserMountCache($c->getDatabaseConnection(), $c->getUserManager(), $c->getLogger());
717
+            $listener = new UserMountCacheListener($mountCache);
718
+            $listener->listen($c->getUserManager());
719
+            return $mountCache;
720
+        });
721
+        $this->registerAlias('UserMountCache', \OCP\Files\Config\IUserMountCache::class);
722
+
723
+        $this->registerService(\OCP\Files\Config\IMountProviderCollection::class, function (Server $c) {
724
+            $loader = \OC\Files\Filesystem::getLoader();
725
+            $mountCache = $c->query('UserMountCache');
726
+            $manager = new \OC\Files\Config\MountProviderCollection($loader, $mountCache);
727
+
728
+            // builtin providers
729
+
730
+            $config = $c->getConfig();
731
+            $manager->registerProvider(new CacheMountProvider($config));
732
+            $manager->registerHomeProvider(new LocalHomeMountProvider());
733
+            $manager->registerHomeProvider(new ObjectHomeMountProvider($config));
734
+
735
+            return $manager;
736
+        });
737
+        $this->registerAlias('MountConfigManager', \OCP\Files\Config\IMountProviderCollection::class);
738
+
739
+        $this->registerService('IniWrapper', function ($c) {
740
+            return new IniGetWrapper();
741
+        });
742
+        $this->registerService('AsyncCommandBus', function (Server $c) {
743
+            $busClass = $c->getConfig()->getSystemValue('commandbus');
744
+            if ($busClass) {
745
+                list($app, $class) = explode('::', $busClass, 2);
746
+                if ($c->getAppManager()->isInstalled($app)) {
747
+                    \OC_App::loadApp($app);
748
+                    return $c->query($class);
749
+                } else {
750
+                    throw new ServiceUnavailableException("The app providing the command bus ($app) is not enabled");
751
+                }
752
+            } else {
753
+                $jobList = $c->getJobList();
754
+                return new CronBus($jobList);
755
+            }
756
+        });
757
+        $this->registerService('TrustedDomainHelper', function ($c) {
758
+            return new TrustedDomainHelper($this->getConfig());
759
+        });
760
+        $this->registerService('Throttler', function (Server $c) {
761
+            return new Throttler(
762
+                $c->getDatabaseConnection(),
763
+                new TimeFactory(),
764
+                $c->getLogger(),
765
+                $c->getConfig()
766
+            );
767
+        });
768
+        $this->registerService('IntegrityCodeChecker', function (Server $c) {
769
+            // IConfig and IAppManager requires a working database. This code
770
+            // might however be called when ownCloud is not yet setup.
771
+            if (\OC::$server->getSystemConfig()->getValue('installed', false)) {
772
+                $config = $c->getConfig();
773
+                $appManager = $c->getAppManager();
774
+            } else {
775
+                $config = null;
776
+                $appManager = null;
777
+            }
778
+
779
+            return new Checker(
780
+                new EnvironmentHelper(),
781
+                new FileAccessHelper(),
782
+                new AppLocator(),
783
+                $config,
784
+                $c->getMemCacheFactory(),
785
+                $appManager,
786
+                $c->getTempManager()
787
+            );
788
+        });
789
+        $this->registerService(\OCP\IRequest::class, function ($c) {
790
+            if (isset($this['urlParams'])) {
791
+                $urlParams = $this['urlParams'];
792
+            } else {
793
+                $urlParams = [];
794
+            }
795
+
796
+            if (defined('PHPUNIT_RUN') && PHPUNIT_RUN
797
+                && in_array('fakeinput', stream_get_wrappers())
798
+            ) {
799
+                $stream = 'fakeinput://data';
800
+            } else {
801
+                $stream = 'php://input';
802
+            }
803
+
804
+            return new Request(
805
+                [
806
+                    'get' => $_GET,
807
+                    'post' => $_POST,
808
+                    'files' => $_FILES,
809
+                    'server' => $_SERVER,
810
+                    'env' => $_ENV,
811
+                    'cookies' => $_COOKIE,
812
+                    'method' => (isset($_SERVER) && isset($_SERVER['REQUEST_METHOD']))
813
+                        ? $_SERVER['REQUEST_METHOD']
814
+                        : '',
815
+                    'urlParams' => $urlParams,
816
+                ],
817
+                $this->getSecureRandom(),
818
+                $this->getConfig(),
819
+                $this->getCsrfTokenManager(),
820
+                $stream
821
+            );
822
+        });
823
+        $this->registerAlias('Request', \OCP\IRequest::class);
824
+
825
+        $this->registerService(\OCP\Mail\IMailer::class, function (Server $c) {
826
+            return new Mailer(
827
+                $c->getConfig(),
828
+                $c->getLogger(),
829
+                $c->query(Defaults::class),
830
+                $c->getURLGenerator(),
831
+                $c->getL10N('lib')
832
+            );
833
+        });
834
+        $this->registerAlias('Mailer', \OCP\Mail\IMailer::class);
835
+
836
+        $this->registerService('LDAPProvider', function (Server $c) {
837
+            $config = $c->getConfig();
838
+            $factoryClass = $config->getSystemValue('ldapProviderFactory', null);
839
+            if (is_null($factoryClass)) {
840
+                throw new \Exception('ldapProviderFactory not set');
841
+            }
842
+            /** @var \OCP\LDAP\ILDAPProviderFactory $factory */
843
+            $factory = new $factoryClass($this);
844
+            return $factory->getLDAPProvider();
845
+        });
846
+        $this->registerService(ILockingProvider::class, function (Server $c) {
847
+            $ini = $c->getIniWrapper();
848
+            $config = $c->getConfig();
849
+            $ttl = $config->getSystemValue('filelocking.ttl', max(3600, $ini->getNumeric('max_execution_time')));
850
+            if ($config->getSystemValue('filelocking.enabled', true) or (defined('PHPUNIT_RUN') && PHPUNIT_RUN)) {
851
+                /** @var \OC\Memcache\Factory $memcacheFactory */
852
+                $memcacheFactory = $c->getMemCacheFactory();
853
+                $memcache = $memcacheFactory->createLocking('lock');
854
+                if (!($memcache instanceof \OC\Memcache\NullCache)) {
855
+                    return new MemcacheLockingProvider($memcache, $ttl);
856
+                }
857
+                return new DBLockingProvider(
858
+                    $c->getDatabaseConnection(),
859
+                    $c->getLogger(),
860
+                    new TimeFactory(),
861
+                    $ttl,
862
+                    !\OC::$CLI
863
+                );
864
+            }
865
+            return new NoopLockingProvider();
866
+        });
867
+        $this->registerAlias('LockingProvider', ILockingProvider::class);
868
+
869
+        $this->registerService(\OCP\Files\Mount\IMountManager::class, function () {
870
+            return new \OC\Files\Mount\Manager();
871
+        });
872
+        $this->registerAlias('MountManager', \OCP\Files\Mount\IMountManager::class);
873
+
874
+        $this->registerService(\OCP\Files\IMimeTypeDetector::class, function (Server $c) {
875
+            return new \OC\Files\Type\Detection(
876
+                $c->getURLGenerator(),
877
+                \OC::$configDir,
878
+                \OC::$SERVERROOT . '/resources/config/'
879
+            );
880
+        });
881
+        $this->registerAlias('MimeTypeDetector', \OCP\Files\IMimeTypeDetector::class);
882
+
883
+        $this->registerService(\OCP\Files\IMimeTypeLoader::class, function (Server $c) {
884
+            return new \OC\Files\Type\Loader(
885
+                $c->getDatabaseConnection()
886
+            );
887
+        });
888
+        $this->registerAlias('MimeTypeLoader', \OCP\Files\IMimeTypeLoader::class);
889
+        $this->registerService(BundleFetcher::class, function () {
890
+            return new BundleFetcher($this->getL10N('lib'));
891
+        });
892
+        $this->registerService(\OCP\Notification\IManager::class, function (Server $c) {
893
+            return new Manager(
894
+                $c->query(IValidator::class)
895
+            );
896
+        });
897
+        $this->registerAlias('NotificationManager', \OCP\Notification\IManager::class);
898
+
899
+        $this->registerService(\OC\CapabilitiesManager::class, function (Server $c) {
900
+            $manager = new \OC\CapabilitiesManager($c->getLogger());
901
+            $manager->registerCapability(function () use ($c) {
902
+                return new \OC\OCS\CoreCapabilities($c->getConfig());
903
+            });
904
+            $manager->registerCapability(function () use ($c) {
905
+                return $c->query(\OC\Security\Bruteforce\Capabilities::class);
906
+            });
907
+            return $manager;
908
+        });
909
+        $this->registerAlias('CapabilitiesManager', \OC\CapabilitiesManager::class);
910
+
911
+        $this->registerService(\OCP\Comments\ICommentsManager::class, function (Server $c) {
912
+            $config = $c->getConfig();
913
+            $factoryClass = $config->getSystemValue('comments.managerFactory', CommentsManagerFactory::class);
914
+            /** @var \OCP\Comments\ICommentsManagerFactory $factory */
915
+            $factory = new $factoryClass($this);
916
+            $manager = $factory->getManager();
917
+
918
+            $manager->registerDisplayNameResolver('user', function($id) use ($c) {
919
+                $manager = $c->getUserManager();
920
+                $user = $manager->get($id);
921
+                if(is_null($user)) {
922
+                    $l = $c->getL10N('core');
923
+                    $displayName = $l->t('Unknown user');
924
+                } else {
925
+                    $displayName = $user->getDisplayName();
926
+                }
927
+                return $displayName;
928
+            });
929
+
930
+            return $manager;
931
+        });
932
+        $this->registerAlias('CommentsManager', \OCP\Comments\ICommentsManager::class);
933
+
934
+        $this->registerService('ThemingDefaults', function (Server $c) {
935
+            /*
936 936
 			 * Dark magic for autoloader.
937 937
 			 * If we do a class_exists it will try to load the class which will
938 938
 			 * make composer cache the result. Resulting in errors when enabling
939 939
 			 * the theming app.
940 940
 			 */
941
-			$prefixes = \OC::$composerAutoloader->getPrefixesPsr4();
942
-			if (isset($prefixes['OCA\\Theming\\'])) {
943
-				$classExists = true;
944
-			} else {
945
-				$classExists = false;
946
-			}
947
-
948
-			if ($classExists && $c->getConfig()->getSystemValue('installed', false) && $c->getAppManager()->isInstalled('theming') && $c->getTrustedDomainHelper()->isTrustedDomain($c->getRequest()->getInsecureServerHost())) {
949
-				return new ThemingDefaults(
950
-					$c->getConfig(),
951
-					$c->getL10N('theming'),
952
-					$c->getURLGenerator(),
953
-					$c->getMemCacheFactory(),
954
-					new Util($c->getConfig(), $this->getAppManager(), $c->getAppDataDir('theming')),
955
-					new ImageManager($c->getConfig(), $c->getAppDataDir('theming'), $c->getURLGenerator(), $this->getMemCacheFactory(), $this->getLogger()),
956
-					$c->getAppManager()
957
-				);
958
-			}
959
-			return new \OC_Defaults();
960
-		});
961
-		$this->registerService(SCSSCacher::class, function (Server $c) {
962
-			/** @var Factory $cacheFactory */
963
-			$cacheFactory = $c->query(Factory::class);
964
-			return new SCSSCacher(
965
-				$c->getLogger(),
966
-				$c->query(\OC\Files\AppData\Factory::class),
967
-				$c->getURLGenerator(),
968
-				$c->getConfig(),
969
-				$c->getThemingDefaults(),
970
-				\OC::$SERVERROOT,
971
-				$this->getMemCacheFactory(),
972
-				$c->query(IconsCacher::class),
973
-				new TimeFactory()
974
-			);
975
-		});
976
-		$this->registerService(JSCombiner::class, function (Server $c) {
977
-			/** @var Factory $cacheFactory */
978
-			$cacheFactory = $c->query(Factory::class);
979
-			return new JSCombiner(
980
-				$c->getAppDataDir('js'),
981
-				$c->getURLGenerator(),
982
-				$this->getMemCacheFactory(),
983
-				$c->getSystemConfig(),
984
-				$c->getLogger()
985
-			);
986
-		});
987
-		$this->registerService(EventDispatcher::class, function () {
988
-			return new EventDispatcher();
989
-		});
990
-		$this->registerAlias('EventDispatcher', EventDispatcher::class);
991
-		$this->registerAlias(EventDispatcherInterface::class, EventDispatcher::class);
992
-
993
-		$this->registerService('CryptoWrapper', function (Server $c) {
994
-			// FIXME: Instantiiated here due to cyclic dependency
995
-			$request = new Request(
996
-				[
997
-					'get' => $_GET,
998
-					'post' => $_POST,
999
-					'files' => $_FILES,
1000
-					'server' => $_SERVER,
1001
-					'env' => $_ENV,
1002
-					'cookies' => $_COOKIE,
1003
-					'method' => (isset($_SERVER) && isset($_SERVER['REQUEST_METHOD']))
1004
-						? $_SERVER['REQUEST_METHOD']
1005
-						: null,
1006
-				],
1007
-				$c->getSecureRandom(),
1008
-				$c->getConfig()
1009
-			);
1010
-
1011
-			return new CryptoWrapper(
1012
-				$c->getConfig(),
1013
-				$c->getCrypto(),
1014
-				$c->getSecureRandom(),
1015
-				$request
1016
-			);
1017
-		});
1018
-		$this->registerService('CsrfTokenManager', function (Server $c) {
1019
-			$tokenGenerator = new CsrfTokenGenerator($c->getSecureRandom());
1020
-
1021
-			return new CsrfTokenManager(
1022
-				$tokenGenerator,
1023
-				$c->query(SessionStorage::class)
1024
-			);
1025
-		});
1026
-		$this->registerService(SessionStorage::class, function (Server $c) {
1027
-			return new SessionStorage($c->getSession());
1028
-		});
1029
-		$this->registerService(\OCP\Security\IContentSecurityPolicyManager::class, function (Server $c) {
1030
-			return new ContentSecurityPolicyManager();
1031
-		});
1032
-		$this->registerAlias('ContentSecurityPolicyManager', \OCP\Security\IContentSecurityPolicyManager::class);
1033
-
1034
-		$this->registerService('ContentSecurityPolicyNonceManager', function (Server $c) {
1035
-			return new ContentSecurityPolicyNonceManager(
1036
-				$c->getCsrfTokenManager(),
1037
-				$c->getRequest()
1038
-			);
1039
-		});
1040
-
1041
-		$this->registerService(\OCP\Share\IManager::class, function (Server $c) {
1042
-			$config = $c->getConfig();
1043
-			$factoryClass = $config->getSystemValue('sharing.managerFactory', ProviderFactory::class);
1044
-			/** @var \OCP\Share\IProviderFactory $factory */
1045
-			$factory = new $factoryClass($this);
1046
-
1047
-			$manager = new \OC\Share20\Manager(
1048
-				$c->getLogger(),
1049
-				$c->getConfig(),
1050
-				$c->getSecureRandom(),
1051
-				$c->getHasher(),
1052
-				$c->getMountManager(),
1053
-				$c->getGroupManager(),
1054
-				$c->getL10N('lib'),
1055
-				$c->getL10NFactory(),
1056
-				$factory,
1057
-				$c->getUserManager(),
1058
-				$c->getLazyRootFolder(),
1059
-				$c->getEventDispatcher(),
1060
-				$c->getMailer(),
1061
-				$c->getURLGenerator(),
1062
-				$c->getThemingDefaults()
1063
-			);
1064
-
1065
-			return $manager;
1066
-		});
1067
-		$this->registerAlias('ShareManager', \OCP\Share\IManager::class);
1068
-
1069
-		$this->registerService(\OCP\Collaboration\Collaborators\ISearch::class, function(Server $c) {
1070
-			$instance = new Collaboration\Collaborators\Search($c);
1071
-
1072
-			// register default plugins
1073
-			$instance->registerPlugin(['shareType' => 'SHARE_TYPE_USER', 'class' => UserPlugin::class]);
1074
-			$instance->registerPlugin(['shareType' => 'SHARE_TYPE_GROUP', 'class' => GroupPlugin::class]);
1075
-			$instance->registerPlugin(['shareType' => 'SHARE_TYPE_EMAIL', 'class' => MailPlugin::class]);
1076
-			$instance->registerPlugin(['shareType' => 'SHARE_TYPE_REMOTE', 'class' => RemotePlugin::class]);
1077
-			$instance->registerPlugin(['shareType' => 'SHARE_TYPE_REMOTE_GROUP', 'class' => RemoteGroupPlugin::class]);
1078
-
1079
-			return $instance;
1080
-		});
1081
-		$this->registerAlias('CollaboratorSearch', \OCP\Collaboration\Collaborators\ISearch::class);
1082
-
1083
-		$this->registerAlias(\OCP\Collaboration\AutoComplete\IManager::class, \OC\Collaboration\AutoComplete\Manager::class);
1084
-
1085
-		$this->registerService('SettingsManager', function (Server $c) {
1086
-			$manager = new \OC\Settings\Manager(
1087
-				$c->getLogger(),
1088
-				$c->getL10N('lib'),
1089
-				$c->getURLGenerator(),
1090
-				$c
1091
-			);
1092
-			return $manager;
1093
-		});
1094
-		$this->registerService(\OC\Files\AppData\Factory::class, function (Server $c) {
1095
-			return new \OC\Files\AppData\Factory(
1096
-				$c->getRootFolder(),
1097
-				$c->getSystemConfig()
1098
-			);
1099
-		});
1100
-
1101
-		$this->registerService('LockdownManager', function (Server $c) {
1102
-			return new LockdownManager(function () use ($c) {
1103
-				return $c->getSession();
1104
-			});
1105
-		});
1106
-
1107
-		$this->registerService(\OCP\OCS\IDiscoveryService::class, function (Server $c) {
1108
-			return new DiscoveryService($c->getMemCacheFactory(), $c->getHTTPClientService());
1109
-		});
1110
-
1111
-		$this->registerService(ICloudIdManager::class, function (Server $c) {
1112
-			return new CloudIdManager();
1113
-		});
1114
-
1115
-		$this->registerService(IConfig::class, function (Server $c) {
1116
-			return new GlobalScale\Config($c->getConfig());
1117
-		});
1118
-
1119
-		$this->registerService(ICloudFederationProviderManager::class, function (Server $c) {
1120
-			return new CloudFederationProviderManager($c->getAppManager(), $c->getHTTPClientService(), $c->getCloudIdManager(), $c->getLogger());
1121
-		});
1122
-
1123
-		$this->registerService(ICloudFederationFactory::class, function (Server $c) {
1124
-			return new CloudFederationFactory();
1125
-		});
1126
-
1127
-		$this->registerAlias(\OCP\AppFramework\Utility\IControllerMethodReflector::class, \OC\AppFramework\Utility\ControllerMethodReflector::class);
1128
-		$this->registerAlias('ControllerMethodReflector', \OCP\AppFramework\Utility\IControllerMethodReflector::class);
1129
-
1130
-		$this->registerAlias(\OCP\AppFramework\Utility\ITimeFactory::class, \OC\AppFramework\Utility\TimeFactory::class);
1131
-		$this->registerAlias('TimeFactory', \OCP\AppFramework\Utility\ITimeFactory::class);
1132
-
1133
-		$this->registerService(Defaults::class, function (Server $c) {
1134
-			return new Defaults(
1135
-				$c->getThemingDefaults()
1136
-			);
1137
-		});
1138
-		$this->registerAlias('Defaults', \OCP\Defaults::class);
1139
-
1140
-		$this->registerService(\OCP\ISession::class, function (SimpleContainer $c) {
1141
-			return $c->query(\OCP\IUserSession::class)->getSession();
1142
-		});
1143
-
1144
-		$this->registerService(IShareHelper::class, function (Server $c) {
1145
-			return new ShareHelper(
1146
-				$c->query(\OCP\Share\IManager::class)
1147
-			);
1148
-		});
1149
-
1150
-		$this->registerService(Installer::class, function(Server $c) {
1151
-			return new Installer(
1152
-				$c->getAppFetcher(),
1153
-				$c->getHTTPClientService(),
1154
-				$c->getTempManager(),
1155
-				$c->getLogger(),
1156
-				$c->getConfig()
1157
-			);
1158
-		});
1159
-
1160
-		$this->registerService(IApiFactory::class, function(Server $c) {
1161
-			return new ApiFactory($c->getHTTPClientService());
1162
-		});
1163
-
1164
-		$this->registerService(IInstanceFactory::class, function(Server $c) {
1165
-			$memcacheFactory = $c->getMemCacheFactory();
1166
-			return new InstanceFactory($memcacheFactory->createLocal('remoteinstance.'), $c->getHTTPClientService());
1167
-		});
1168
-
1169
-		$this->registerService(IContactsStore::class, function(Server $c) {
1170
-			return new ContactsStore(
1171
-				$c->getContactsManager(),
1172
-				$c->getConfig(),
1173
-				$c->getUserManager(),
1174
-				$c->getGroupManager()
1175
-			);
1176
-		});
1177
-		$this->registerAlias(IContactsStore::class, ContactsStore::class);
1178
-
1179
-		$this->registerService(IStorageFactory::class, function() {
1180
-			return new StorageFactory();
1181
-		});
1182
-
1183
-		$this->registerAlias(IDashboardManager::class, Dashboard\DashboardManager::class);
1184
-
1185
-		$this->connectDispatcher();
1186
-	}
1187
-
1188
-	/**
1189
-	 * @return \OCP\Calendar\IManager
1190
-	 */
1191
-	public function getCalendarManager() {
1192
-		return $this->query('CalendarManager');
1193
-	}
1194
-
1195
-	/**
1196
-	 * @return \OCP\Calendar\Resource\IManager
1197
-	 */
1198
-	public function getCalendarResourceBackendManager() {
1199
-		return $this->query('CalendarResourceBackendManager');
1200
-	}
1201
-
1202
-	/**
1203
-	 * @return \OCP\Calendar\Room\IManager
1204
-	 */
1205
-	public function getCalendarRoomBackendManager() {
1206
-		return $this->query('CalendarRoomBackendManager');
1207
-	}
1208
-
1209
-	private function connectDispatcher() {
1210
-		$dispatcher = $this->getEventDispatcher();
1211
-
1212
-		// Delete avatar on user deletion
1213
-		$dispatcher->addListener('OCP\IUser::preDelete', function(GenericEvent $e) {
1214
-			$logger = $this->getLogger();
1215
-			$manager = $this->getAvatarManager();
1216
-			/** @var IUser $user */
1217
-			$user = $e->getSubject();
1218
-
1219
-			try {
1220
-				$avatar = $manager->getAvatar($user->getUID());
1221
-				$avatar->remove();
1222
-			} catch (NotFoundException $e) {
1223
-				// no avatar to remove
1224
-			} catch (\Exception $e) {
1225
-				// Ignore exceptions
1226
-				$logger->info('Could not cleanup avatar of ' . $user->getUID());
1227
-			}
1228
-		});
1229
-
1230
-		$dispatcher->addListener('OCP\IUser::changeUser', function (GenericEvent $e) {
1231
-			$manager = $this->getAvatarManager();
1232
-			/** @var IUser $user */
1233
-			$user = $e->getSubject();
1234
-			$feature = $e->getArgument('feature');
1235
-			$oldValue = $e->getArgument('oldValue');
1236
-			$value = $e->getArgument('value');
1237
-
1238
-			try {
1239
-				$avatar = $manager->getAvatar($user->getUID());
1240
-				$avatar->userChanged($feature, $oldValue, $value);
1241
-			} catch (NotFoundException $e) {
1242
-				// no avatar to remove
1243
-			}
1244
-		});
1245
-	}
1246
-
1247
-	/**
1248
-	 * @return \OCP\Contacts\IManager
1249
-	 */
1250
-	public function getContactsManager() {
1251
-		return $this->query('ContactsManager');
1252
-	}
1253
-
1254
-	/**
1255
-	 * @return \OC\Encryption\Manager
1256
-	 */
1257
-	public function getEncryptionManager() {
1258
-		return $this->query('EncryptionManager');
1259
-	}
1260
-
1261
-	/**
1262
-	 * @return \OC\Encryption\File
1263
-	 */
1264
-	public function getEncryptionFilesHelper() {
1265
-		return $this->query('EncryptionFileHelper');
1266
-	}
1267
-
1268
-	/**
1269
-	 * @return \OCP\Encryption\Keys\IStorage
1270
-	 */
1271
-	public function getEncryptionKeyStorage() {
1272
-		return $this->query('EncryptionKeyStorage');
1273
-	}
1274
-
1275
-	/**
1276
-	 * The current request object holding all information about the request
1277
-	 * currently being processed is returned from this method.
1278
-	 * In case the current execution was not initiated by a web request null is returned
1279
-	 *
1280
-	 * @return \OCP\IRequest
1281
-	 */
1282
-	public function getRequest() {
1283
-		return $this->query('Request');
1284
-	}
1285
-
1286
-	/**
1287
-	 * Returns the preview manager which can create preview images for a given file
1288
-	 *
1289
-	 * @return \OCP\IPreview
1290
-	 */
1291
-	public function getPreviewManager() {
1292
-		return $this->query('PreviewManager');
1293
-	}
1294
-
1295
-	/**
1296
-	 * Returns the tag manager which can get and set tags for different object types
1297
-	 *
1298
-	 * @see \OCP\ITagManager::load()
1299
-	 * @return \OCP\ITagManager
1300
-	 */
1301
-	public function getTagManager() {
1302
-		return $this->query('TagManager');
1303
-	}
1304
-
1305
-	/**
1306
-	 * Returns the system-tag manager
1307
-	 *
1308
-	 * @return \OCP\SystemTag\ISystemTagManager
1309
-	 *
1310
-	 * @since 9.0.0
1311
-	 */
1312
-	public function getSystemTagManager() {
1313
-		return $this->query('SystemTagManager');
1314
-	}
1315
-
1316
-	/**
1317
-	 * Returns the system-tag object mapper
1318
-	 *
1319
-	 * @return \OCP\SystemTag\ISystemTagObjectMapper
1320
-	 *
1321
-	 * @since 9.0.0
1322
-	 */
1323
-	public function getSystemTagObjectMapper() {
1324
-		return $this->query('SystemTagObjectMapper');
1325
-	}
1326
-
1327
-	/**
1328
-	 * Returns the avatar manager, used for avatar functionality
1329
-	 *
1330
-	 * @return \OCP\IAvatarManager
1331
-	 */
1332
-	public function getAvatarManager() {
1333
-		return $this->query('AvatarManager');
1334
-	}
1335
-
1336
-	/**
1337
-	 * Returns the root folder of ownCloud's data directory
1338
-	 *
1339
-	 * @return \OCP\Files\IRootFolder
1340
-	 */
1341
-	public function getRootFolder() {
1342
-		return $this->query('LazyRootFolder');
1343
-	}
1344
-
1345
-	/**
1346
-	 * Returns the root folder of ownCloud's data directory
1347
-	 * This is the lazy variant so this gets only initialized once it
1348
-	 * is actually used.
1349
-	 *
1350
-	 * @return \OCP\Files\IRootFolder
1351
-	 */
1352
-	public function getLazyRootFolder() {
1353
-		return $this->query('LazyRootFolder');
1354
-	}
1355
-
1356
-	/**
1357
-	 * Returns a view to ownCloud's files folder
1358
-	 *
1359
-	 * @param string $userId user ID
1360
-	 * @return \OCP\Files\Folder|null
1361
-	 */
1362
-	public function getUserFolder($userId = null) {
1363
-		if ($userId === null) {
1364
-			$user = $this->getUserSession()->getUser();
1365
-			if (!$user) {
1366
-				return null;
1367
-			}
1368
-			$userId = $user->getUID();
1369
-		}
1370
-		$root = $this->getRootFolder();
1371
-		return $root->getUserFolder($userId);
1372
-	}
1373
-
1374
-	/**
1375
-	 * Returns an app-specific view in ownClouds data directory
1376
-	 *
1377
-	 * @return \OCP\Files\Folder
1378
-	 * @deprecated since 9.2.0 use IAppData
1379
-	 */
1380
-	public function getAppFolder() {
1381
-		$dir = '/' . \OC_App::getCurrentApp();
1382
-		$root = $this->getRootFolder();
1383
-		if (!$root->nodeExists($dir)) {
1384
-			$folder = $root->newFolder($dir);
1385
-		} else {
1386
-			$folder = $root->get($dir);
1387
-		}
1388
-		return $folder;
1389
-	}
1390
-
1391
-	/**
1392
-	 * @return \OC\User\Manager
1393
-	 */
1394
-	public function getUserManager() {
1395
-		return $this->query('UserManager');
1396
-	}
1397
-
1398
-	/**
1399
-	 * @return \OC\Group\Manager
1400
-	 */
1401
-	public function getGroupManager() {
1402
-		return $this->query('GroupManager');
1403
-	}
1404
-
1405
-	/**
1406
-	 * @return \OC\User\Session
1407
-	 */
1408
-	public function getUserSession() {
1409
-		return $this->query('UserSession');
1410
-	}
1411
-
1412
-	/**
1413
-	 * @return \OCP\ISession
1414
-	 */
1415
-	public function getSession() {
1416
-		return $this->query('UserSession')->getSession();
1417
-	}
1418
-
1419
-	/**
1420
-	 * @param \OCP\ISession $session
1421
-	 */
1422
-	public function setSession(\OCP\ISession $session) {
1423
-		$this->query(SessionStorage::class)->setSession($session);
1424
-		$this->query('UserSession')->setSession($session);
1425
-		$this->query(Store::class)->setSession($session);
1426
-	}
1427
-
1428
-	/**
1429
-	 * @return \OC\Authentication\TwoFactorAuth\Manager
1430
-	 */
1431
-	public function getTwoFactorAuthManager() {
1432
-		return $this->query('\OC\Authentication\TwoFactorAuth\Manager');
1433
-	}
1434
-
1435
-	/**
1436
-	 * @return \OC\NavigationManager
1437
-	 */
1438
-	public function getNavigationManager() {
1439
-		return $this->query('NavigationManager');
1440
-	}
1441
-
1442
-	/**
1443
-	 * @return \OCP\IConfig
1444
-	 */
1445
-	public function getConfig() {
1446
-		return $this->query('AllConfig');
1447
-	}
1448
-
1449
-	/**
1450
-	 * @return \OC\SystemConfig
1451
-	 */
1452
-	public function getSystemConfig() {
1453
-		return $this->query('SystemConfig');
1454
-	}
1455
-
1456
-	/**
1457
-	 * Returns the app config manager
1458
-	 *
1459
-	 * @return \OCP\IAppConfig
1460
-	 */
1461
-	public function getAppConfig() {
1462
-		return $this->query('AppConfig');
1463
-	}
1464
-
1465
-	/**
1466
-	 * @return \OCP\L10N\IFactory
1467
-	 */
1468
-	public function getL10NFactory() {
1469
-		return $this->query('L10NFactory');
1470
-	}
1471
-
1472
-	/**
1473
-	 * get an L10N instance
1474
-	 *
1475
-	 * @param string $app appid
1476
-	 * @param string $lang
1477
-	 * @return IL10N
1478
-	 */
1479
-	public function getL10N($app, $lang = null) {
1480
-		return $this->getL10NFactory()->get($app, $lang);
1481
-	}
1482
-
1483
-	/**
1484
-	 * @return \OCP\IURLGenerator
1485
-	 */
1486
-	public function getURLGenerator() {
1487
-		return $this->query('URLGenerator');
1488
-	}
1489
-
1490
-	/**
1491
-	 * @return AppFetcher
1492
-	 */
1493
-	public function getAppFetcher() {
1494
-		return $this->query(AppFetcher::class);
1495
-	}
1496
-
1497
-	/**
1498
-	 * Returns an ICache instance. Since 8.1.0 it returns a fake cache. Use
1499
-	 * getMemCacheFactory() instead.
1500
-	 *
1501
-	 * @return \OCP\ICache
1502
-	 * @deprecated 8.1.0 use getMemCacheFactory to obtain a proper cache
1503
-	 */
1504
-	public function getCache() {
1505
-		return $this->query('UserCache');
1506
-	}
1507
-
1508
-	/**
1509
-	 * Returns an \OCP\CacheFactory instance
1510
-	 *
1511
-	 * @return \OCP\ICacheFactory
1512
-	 */
1513
-	public function getMemCacheFactory() {
1514
-		return $this->query('MemCacheFactory');
1515
-	}
1516
-
1517
-	/**
1518
-	 * Returns an \OC\RedisFactory instance
1519
-	 *
1520
-	 * @return \OC\RedisFactory
1521
-	 */
1522
-	public function getGetRedisFactory() {
1523
-		return $this->query('RedisFactory');
1524
-	}
1525
-
1526
-
1527
-	/**
1528
-	 * Returns the current session
1529
-	 *
1530
-	 * @return \OCP\IDBConnection
1531
-	 */
1532
-	public function getDatabaseConnection() {
1533
-		return $this->query('DatabaseConnection');
1534
-	}
1535
-
1536
-	/**
1537
-	 * Returns the activity manager
1538
-	 *
1539
-	 * @return \OCP\Activity\IManager
1540
-	 */
1541
-	public function getActivityManager() {
1542
-		return $this->query('ActivityManager');
1543
-	}
1544
-
1545
-	/**
1546
-	 * Returns an job list for controlling background jobs
1547
-	 *
1548
-	 * @return \OCP\BackgroundJob\IJobList
1549
-	 */
1550
-	public function getJobList() {
1551
-		return $this->query('JobList');
1552
-	}
1553
-
1554
-	/**
1555
-	 * Returns a logger instance
1556
-	 *
1557
-	 * @return \OCP\ILogger
1558
-	 */
1559
-	public function getLogger() {
1560
-		return $this->query('Logger');
1561
-	}
1562
-
1563
-	/**
1564
-	 * @return ILogFactory
1565
-	 * @throws \OCP\AppFramework\QueryException
1566
-	 */
1567
-	public function getLogFactory() {
1568
-		return $this->query(ILogFactory::class);
1569
-	}
1570
-
1571
-	/**
1572
-	 * Returns a router for generating and matching urls
1573
-	 *
1574
-	 * @return \OCP\Route\IRouter
1575
-	 */
1576
-	public function getRouter() {
1577
-		return $this->query('Router');
1578
-	}
1579
-
1580
-	/**
1581
-	 * Returns a search instance
1582
-	 *
1583
-	 * @return \OCP\ISearch
1584
-	 */
1585
-	public function getSearch() {
1586
-		return $this->query('Search');
1587
-	}
1588
-
1589
-	/**
1590
-	 * Returns a SecureRandom instance
1591
-	 *
1592
-	 * @return \OCP\Security\ISecureRandom
1593
-	 */
1594
-	public function getSecureRandom() {
1595
-		return $this->query('SecureRandom');
1596
-	}
1597
-
1598
-	/**
1599
-	 * Returns a Crypto instance
1600
-	 *
1601
-	 * @return \OCP\Security\ICrypto
1602
-	 */
1603
-	public function getCrypto() {
1604
-		return $this->query('Crypto');
1605
-	}
1606
-
1607
-	/**
1608
-	 * Returns a Hasher instance
1609
-	 *
1610
-	 * @return \OCP\Security\IHasher
1611
-	 */
1612
-	public function getHasher() {
1613
-		return $this->query('Hasher');
1614
-	}
1615
-
1616
-	/**
1617
-	 * Returns a CredentialsManager instance
1618
-	 *
1619
-	 * @return \OCP\Security\ICredentialsManager
1620
-	 */
1621
-	public function getCredentialsManager() {
1622
-		return $this->query('CredentialsManager');
1623
-	}
1624
-
1625
-	/**
1626
-	 * Get the certificate manager for the user
1627
-	 *
1628
-	 * @param string $userId (optional) if not specified the current loggedin user is used, use null to get the system certificate manager
1629
-	 * @return \OCP\ICertificateManager | null if $uid is null and no user is logged in
1630
-	 */
1631
-	public function getCertificateManager($userId = '') {
1632
-		if ($userId === '') {
1633
-			$userSession = $this->getUserSession();
1634
-			$user = $userSession->getUser();
1635
-			if (is_null($user)) {
1636
-				return null;
1637
-			}
1638
-			$userId = $user->getUID();
1639
-		}
1640
-		return new CertificateManager(
1641
-			$userId,
1642
-			new View(),
1643
-			$this->getConfig(),
1644
-			$this->getLogger(),
1645
-			$this->getSecureRandom()
1646
-		);
1647
-	}
1648
-
1649
-	/**
1650
-	 * Returns an instance of the HTTP client service
1651
-	 *
1652
-	 * @return \OCP\Http\Client\IClientService
1653
-	 */
1654
-	public function getHTTPClientService() {
1655
-		return $this->query('HttpClientService');
1656
-	}
1657
-
1658
-	/**
1659
-	 * Create a new event source
1660
-	 *
1661
-	 * @return \OCP\IEventSource
1662
-	 */
1663
-	public function createEventSource() {
1664
-		return new \OC_EventSource();
1665
-	}
1666
-
1667
-	/**
1668
-	 * Get the active event logger
1669
-	 *
1670
-	 * The returned logger only logs data when debug mode is enabled
1671
-	 *
1672
-	 * @return \OCP\Diagnostics\IEventLogger
1673
-	 */
1674
-	public function getEventLogger() {
1675
-		return $this->query('EventLogger');
1676
-	}
1677
-
1678
-	/**
1679
-	 * Get the active query logger
1680
-	 *
1681
-	 * The returned logger only logs data when debug mode is enabled
1682
-	 *
1683
-	 * @return \OCP\Diagnostics\IQueryLogger
1684
-	 */
1685
-	public function getQueryLogger() {
1686
-		return $this->query('QueryLogger');
1687
-	}
1688
-
1689
-	/**
1690
-	 * Get the manager for temporary files and folders
1691
-	 *
1692
-	 * @return \OCP\ITempManager
1693
-	 */
1694
-	public function getTempManager() {
1695
-		return $this->query('TempManager');
1696
-	}
1697
-
1698
-	/**
1699
-	 * Get the app manager
1700
-	 *
1701
-	 * @return \OCP\App\IAppManager
1702
-	 */
1703
-	public function getAppManager() {
1704
-		return $this->query('AppManager');
1705
-	}
1706
-
1707
-	/**
1708
-	 * Creates a new mailer
1709
-	 *
1710
-	 * @return \OCP\Mail\IMailer
1711
-	 */
1712
-	public function getMailer() {
1713
-		return $this->query('Mailer');
1714
-	}
1715
-
1716
-	/**
1717
-	 * Get the webroot
1718
-	 *
1719
-	 * @return string
1720
-	 */
1721
-	public function getWebRoot() {
1722
-		return $this->webRoot;
1723
-	}
1724
-
1725
-	/**
1726
-	 * @return \OC\OCSClient
1727
-	 */
1728
-	public function getOcsClient() {
1729
-		return $this->query('OcsClient');
1730
-	}
1731
-
1732
-	/**
1733
-	 * @return \OCP\IDateTimeZone
1734
-	 */
1735
-	public function getDateTimeZone() {
1736
-		return $this->query('DateTimeZone');
1737
-	}
1738
-
1739
-	/**
1740
-	 * @return \OCP\IDateTimeFormatter
1741
-	 */
1742
-	public function getDateTimeFormatter() {
1743
-		return $this->query('DateTimeFormatter');
1744
-	}
1745
-
1746
-	/**
1747
-	 * @return \OCP\Files\Config\IMountProviderCollection
1748
-	 */
1749
-	public function getMountProviderCollection() {
1750
-		return $this->query('MountConfigManager');
1751
-	}
1752
-
1753
-	/**
1754
-	 * Get the IniWrapper
1755
-	 *
1756
-	 * @return IniGetWrapper
1757
-	 */
1758
-	public function getIniWrapper() {
1759
-		return $this->query('IniWrapper');
1760
-	}
1761
-
1762
-	/**
1763
-	 * @return \OCP\Command\IBus
1764
-	 */
1765
-	public function getCommandBus() {
1766
-		return $this->query('AsyncCommandBus');
1767
-	}
1768
-
1769
-	/**
1770
-	 * Get the trusted domain helper
1771
-	 *
1772
-	 * @return TrustedDomainHelper
1773
-	 */
1774
-	public function getTrustedDomainHelper() {
1775
-		return $this->query('TrustedDomainHelper');
1776
-	}
1777
-
1778
-	/**
1779
-	 * Get the locking provider
1780
-	 *
1781
-	 * @return \OCP\Lock\ILockingProvider
1782
-	 * @since 8.1.0
1783
-	 */
1784
-	public function getLockingProvider() {
1785
-		return $this->query('LockingProvider');
1786
-	}
1787
-
1788
-	/**
1789
-	 * @return \OCP\Files\Mount\IMountManager
1790
-	 **/
1791
-	function getMountManager() {
1792
-		return $this->query('MountManager');
1793
-	}
1794
-
1795
-	/** @return \OCP\Files\Config\IUserMountCache */
1796
-	function getUserMountCache() {
1797
-		return $this->query('UserMountCache');
1798
-	}
1799
-
1800
-	/**
1801
-	 * Get the MimeTypeDetector
1802
-	 *
1803
-	 * @return \OCP\Files\IMimeTypeDetector
1804
-	 */
1805
-	public function getMimeTypeDetector() {
1806
-		return $this->query('MimeTypeDetector');
1807
-	}
1808
-
1809
-	/**
1810
-	 * Get the MimeTypeLoader
1811
-	 *
1812
-	 * @return \OCP\Files\IMimeTypeLoader
1813
-	 */
1814
-	public function getMimeTypeLoader() {
1815
-		return $this->query('MimeTypeLoader');
1816
-	}
1817
-
1818
-	/**
1819
-	 * Get the manager of all the capabilities
1820
-	 *
1821
-	 * @return \OC\CapabilitiesManager
1822
-	 */
1823
-	public function getCapabilitiesManager() {
1824
-		return $this->query('CapabilitiesManager');
1825
-	}
1826
-
1827
-	/**
1828
-	 * Get the EventDispatcher
1829
-	 *
1830
-	 * @return EventDispatcherInterface
1831
-	 * @since 8.2.0
1832
-	 */
1833
-	public function getEventDispatcher() {
1834
-		return $this->query('EventDispatcher');
1835
-	}
1836
-
1837
-	/**
1838
-	 * Get the Notification Manager
1839
-	 *
1840
-	 * @return \OCP\Notification\IManager
1841
-	 * @since 8.2.0
1842
-	 */
1843
-	public function getNotificationManager() {
1844
-		return $this->query('NotificationManager');
1845
-	}
1846
-
1847
-	/**
1848
-	 * @return \OCP\Comments\ICommentsManager
1849
-	 */
1850
-	public function getCommentsManager() {
1851
-		return $this->query('CommentsManager');
1852
-	}
1853
-
1854
-	/**
1855
-	 * @return \OCA\Theming\ThemingDefaults
1856
-	 */
1857
-	public function getThemingDefaults() {
1858
-		return $this->query('ThemingDefaults');
1859
-	}
1860
-
1861
-	/**
1862
-	 * @return \OC\IntegrityCheck\Checker
1863
-	 */
1864
-	public function getIntegrityCodeChecker() {
1865
-		return $this->query('IntegrityCodeChecker');
1866
-	}
1867
-
1868
-	/**
1869
-	 * @return \OC\Session\CryptoWrapper
1870
-	 */
1871
-	public function getSessionCryptoWrapper() {
1872
-		return $this->query('CryptoWrapper');
1873
-	}
1874
-
1875
-	/**
1876
-	 * @return CsrfTokenManager
1877
-	 */
1878
-	public function getCsrfTokenManager() {
1879
-		return $this->query('CsrfTokenManager');
1880
-	}
1881
-
1882
-	/**
1883
-	 * @return Throttler
1884
-	 */
1885
-	public function getBruteForceThrottler() {
1886
-		return $this->query('Throttler');
1887
-	}
1888
-
1889
-	/**
1890
-	 * @return IContentSecurityPolicyManager
1891
-	 */
1892
-	public function getContentSecurityPolicyManager() {
1893
-		return $this->query('ContentSecurityPolicyManager');
1894
-	}
1895
-
1896
-	/**
1897
-	 * @return ContentSecurityPolicyNonceManager
1898
-	 */
1899
-	public function getContentSecurityPolicyNonceManager() {
1900
-		return $this->query('ContentSecurityPolicyNonceManager');
1901
-	}
1902
-
1903
-	/**
1904
-	 * Not a public API as of 8.2, wait for 9.0
1905
-	 *
1906
-	 * @return \OCA\Files_External\Service\BackendService
1907
-	 */
1908
-	public function getStoragesBackendService() {
1909
-		return $this->query('OCA\\Files_External\\Service\\BackendService');
1910
-	}
1911
-
1912
-	/**
1913
-	 * Not a public API as of 8.2, wait for 9.0
1914
-	 *
1915
-	 * @return \OCA\Files_External\Service\GlobalStoragesService
1916
-	 */
1917
-	public function getGlobalStoragesService() {
1918
-		return $this->query('OCA\\Files_External\\Service\\GlobalStoragesService');
1919
-	}
1920
-
1921
-	/**
1922
-	 * Not a public API as of 8.2, wait for 9.0
1923
-	 *
1924
-	 * @return \OCA\Files_External\Service\UserGlobalStoragesService
1925
-	 */
1926
-	public function getUserGlobalStoragesService() {
1927
-		return $this->query('OCA\\Files_External\\Service\\UserGlobalStoragesService');
1928
-	}
1929
-
1930
-	/**
1931
-	 * Not a public API as of 8.2, wait for 9.0
1932
-	 *
1933
-	 * @return \OCA\Files_External\Service\UserStoragesService
1934
-	 */
1935
-	public function getUserStoragesService() {
1936
-		return $this->query('OCA\\Files_External\\Service\\UserStoragesService');
1937
-	}
1938
-
1939
-	/**
1940
-	 * @return \OCP\Share\IManager
1941
-	 */
1942
-	public function getShareManager() {
1943
-		return $this->query('ShareManager');
1944
-	}
1945
-
1946
-	/**
1947
-	 * @return \OCP\Collaboration\Collaborators\ISearch
1948
-	 */
1949
-	public function getCollaboratorSearch() {
1950
-		return $this->query('CollaboratorSearch');
1951
-	}
1952
-
1953
-	/**
1954
-	 * @return \OCP\Collaboration\AutoComplete\IManager
1955
-	 */
1956
-	public function getAutoCompleteManager(){
1957
-		return $this->query(IManager::class);
1958
-	}
1959
-
1960
-	/**
1961
-	 * Returns the LDAP Provider
1962
-	 *
1963
-	 * @return \OCP\LDAP\ILDAPProvider
1964
-	 */
1965
-	public function getLDAPProvider() {
1966
-		return $this->query('LDAPProvider');
1967
-	}
1968
-
1969
-	/**
1970
-	 * @return \OCP\Settings\IManager
1971
-	 */
1972
-	public function getSettingsManager() {
1973
-		return $this->query('SettingsManager');
1974
-	}
1975
-
1976
-	/**
1977
-	 * @return \OCP\Files\IAppData
1978
-	 */
1979
-	public function getAppDataDir($app) {
1980
-		/** @var \OC\Files\AppData\Factory $factory */
1981
-		$factory = $this->query(\OC\Files\AppData\Factory::class);
1982
-		return $factory->get($app);
1983
-	}
1984
-
1985
-	/**
1986
-	 * @return \OCP\Lockdown\ILockdownManager
1987
-	 */
1988
-	public function getLockdownManager() {
1989
-		return $this->query('LockdownManager');
1990
-	}
1991
-
1992
-	/**
1993
-	 * @return \OCP\Federation\ICloudIdManager
1994
-	 */
1995
-	public function getCloudIdManager() {
1996
-		return $this->query(ICloudIdManager::class);
1997
-	}
1998
-
1999
-	/**
2000
-	 * @return \OCP\GlobalScale\IConfig
2001
-	 */
2002
-	public function getGlobalScaleConfig() {
2003
-		return $this->query(IConfig::class);
2004
-	}
2005
-
2006
-	/**
2007
-	 * @return \OCP\Federation\ICloudFederationProviderManager
2008
-	 */
2009
-	public function getCloudFederationProviderManager() {
2010
-		return $this->query(ICloudFederationProviderManager::class);
2011
-	}
2012
-
2013
-	/**
2014
-	 * @return \OCP\Remote\Api\IApiFactory
2015
-	 */
2016
-	public function getRemoteApiFactory() {
2017
-		return $this->query(IApiFactory::class);
2018
-	}
2019
-
2020
-	/**
2021
-	 * @return \OCP\Federation\ICloudFederationFactory
2022
-	 */
2023
-	public function getCloudFederationFactory() {
2024
-		return $this->query(ICloudFederationFactory::class);
2025
-	}
2026
-
2027
-	/**
2028
-	 * @return \OCP\Remote\IInstanceFactory
2029
-	 */
2030
-	public function getRemoteInstanceFactory() {
2031
-		return $this->query(IInstanceFactory::class);
2032
-	}
2033
-
2034
-	/**
2035
-	 * @return IStorageFactory
2036
-	 */
2037
-	public function getStorageFactory() {
2038
-		return $this->query(IStorageFactory::class);
2039
-	}
941
+            $prefixes = \OC::$composerAutoloader->getPrefixesPsr4();
942
+            if (isset($prefixes['OCA\\Theming\\'])) {
943
+                $classExists = true;
944
+            } else {
945
+                $classExists = false;
946
+            }
947
+
948
+            if ($classExists && $c->getConfig()->getSystemValue('installed', false) && $c->getAppManager()->isInstalled('theming') && $c->getTrustedDomainHelper()->isTrustedDomain($c->getRequest()->getInsecureServerHost())) {
949
+                return new ThemingDefaults(
950
+                    $c->getConfig(),
951
+                    $c->getL10N('theming'),
952
+                    $c->getURLGenerator(),
953
+                    $c->getMemCacheFactory(),
954
+                    new Util($c->getConfig(), $this->getAppManager(), $c->getAppDataDir('theming')),
955
+                    new ImageManager($c->getConfig(), $c->getAppDataDir('theming'), $c->getURLGenerator(), $this->getMemCacheFactory(), $this->getLogger()),
956
+                    $c->getAppManager()
957
+                );
958
+            }
959
+            return new \OC_Defaults();
960
+        });
961
+        $this->registerService(SCSSCacher::class, function (Server $c) {
962
+            /** @var Factory $cacheFactory */
963
+            $cacheFactory = $c->query(Factory::class);
964
+            return new SCSSCacher(
965
+                $c->getLogger(),
966
+                $c->query(\OC\Files\AppData\Factory::class),
967
+                $c->getURLGenerator(),
968
+                $c->getConfig(),
969
+                $c->getThemingDefaults(),
970
+                \OC::$SERVERROOT,
971
+                $this->getMemCacheFactory(),
972
+                $c->query(IconsCacher::class),
973
+                new TimeFactory()
974
+            );
975
+        });
976
+        $this->registerService(JSCombiner::class, function (Server $c) {
977
+            /** @var Factory $cacheFactory */
978
+            $cacheFactory = $c->query(Factory::class);
979
+            return new JSCombiner(
980
+                $c->getAppDataDir('js'),
981
+                $c->getURLGenerator(),
982
+                $this->getMemCacheFactory(),
983
+                $c->getSystemConfig(),
984
+                $c->getLogger()
985
+            );
986
+        });
987
+        $this->registerService(EventDispatcher::class, function () {
988
+            return new EventDispatcher();
989
+        });
990
+        $this->registerAlias('EventDispatcher', EventDispatcher::class);
991
+        $this->registerAlias(EventDispatcherInterface::class, EventDispatcher::class);
992
+
993
+        $this->registerService('CryptoWrapper', function (Server $c) {
994
+            // FIXME: Instantiiated here due to cyclic dependency
995
+            $request = new Request(
996
+                [
997
+                    'get' => $_GET,
998
+                    'post' => $_POST,
999
+                    'files' => $_FILES,
1000
+                    'server' => $_SERVER,
1001
+                    'env' => $_ENV,
1002
+                    'cookies' => $_COOKIE,
1003
+                    'method' => (isset($_SERVER) && isset($_SERVER['REQUEST_METHOD']))
1004
+                        ? $_SERVER['REQUEST_METHOD']
1005
+                        : null,
1006
+                ],
1007
+                $c->getSecureRandom(),
1008
+                $c->getConfig()
1009
+            );
1010
+
1011
+            return new CryptoWrapper(
1012
+                $c->getConfig(),
1013
+                $c->getCrypto(),
1014
+                $c->getSecureRandom(),
1015
+                $request
1016
+            );
1017
+        });
1018
+        $this->registerService('CsrfTokenManager', function (Server $c) {
1019
+            $tokenGenerator = new CsrfTokenGenerator($c->getSecureRandom());
1020
+
1021
+            return new CsrfTokenManager(
1022
+                $tokenGenerator,
1023
+                $c->query(SessionStorage::class)
1024
+            );
1025
+        });
1026
+        $this->registerService(SessionStorage::class, function (Server $c) {
1027
+            return new SessionStorage($c->getSession());
1028
+        });
1029
+        $this->registerService(\OCP\Security\IContentSecurityPolicyManager::class, function (Server $c) {
1030
+            return new ContentSecurityPolicyManager();
1031
+        });
1032
+        $this->registerAlias('ContentSecurityPolicyManager', \OCP\Security\IContentSecurityPolicyManager::class);
1033
+
1034
+        $this->registerService('ContentSecurityPolicyNonceManager', function (Server $c) {
1035
+            return new ContentSecurityPolicyNonceManager(
1036
+                $c->getCsrfTokenManager(),
1037
+                $c->getRequest()
1038
+            );
1039
+        });
1040
+
1041
+        $this->registerService(\OCP\Share\IManager::class, function (Server $c) {
1042
+            $config = $c->getConfig();
1043
+            $factoryClass = $config->getSystemValue('sharing.managerFactory', ProviderFactory::class);
1044
+            /** @var \OCP\Share\IProviderFactory $factory */
1045
+            $factory = new $factoryClass($this);
1046
+
1047
+            $manager = new \OC\Share20\Manager(
1048
+                $c->getLogger(),
1049
+                $c->getConfig(),
1050
+                $c->getSecureRandom(),
1051
+                $c->getHasher(),
1052
+                $c->getMountManager(),
1053
+                $c->getGroupManager(),
1054
+                $c->getL10N('lib'),
1055
+                $c->getL10NFactory(),
1056
+                $factory,
1057
+                $c->getUserManager(),
1058
+                $c->getLazyRootFolder(),
1059
+                $c->getEventDispatcher(),
1060
+                $c->getMailer(),
1061
+                $c->getURLGenerator(),
1062
+                $c->getThemingDefaults()
1063
+            );
1064
+
1065
+            return $manager;
1066
+        });
1067
+        $this->registerAlias('ShareManager', \OCP\Share\IManager::class);
1068
+
1069
+        $this->registerService(\OCP\Collaboration\Collaborators\ISearch::class, function(Server $c) {
1070
+            $instance = new Collaboration\Collaborators\Search($c);
1071
+
1072
+            // register default plugins
1073
+            $instance->registerPlugin(['shareType' => 'SHARE_TYPE_USER', 'class' => UserPlugin::class]);
1074
+            $instance->registerPlugin(['shareType' => 'SHARE_TYPE_GROUP', 'class' => GroupPlugin::class]);
1075
+            $instance->registerPlugin(['shareType' => 'SHARE_TYPE_EMAIL', 'class' => MailPlugin::class]);
1076
+            $instance->registerPlugin(['shareType' => 'SHARE_TYPE_REMOTE', 'class' => RemotePlugin::class]);
1077
+            $instance->registerPlugin(['shareType' => 'SHARE_TYPE_REMOTE_GROUP', 'class' => RemoteGroupPlugin::class]);
1078
+
1079
+            return $instance;
1080
+        });
1081
+        $this->registerAlias('CollaboratorSearch', \OCP\Collaboration\Collaborators\ISearch::class);
1082
+
1083
+        $this->registerAlias(\OCP\Collaboration\AutoComplete\IManager::class, \OC\Collaboration\AutoComplete\Manager::class);
1084
+
1085
+        $this->registerService('SettingsManager', function (Server $c) {
1086
+            $manager = new \OC\Settings\Manager(
1087
+                $c->getLogger(),
1088
+                $c->getL10N('lib'),
1089
+                $c->getURLGenerator(),
1090
+                $c
1091
+            );
1092
+            return $manager;
1093
+        });
1094
+        $this->registerService(\OC\Files\AppData\Factory::class, function (Server $c) {
1095
+            return new \OC\Files\AppData\Factory(
1096
+                $c->getRootFolder(),
1097
+                $c->getSystemConfig()
1098
+            );
1099
+        });
1100
+
1101
+        $this->registerService('LockdownManager', function (Server $c) {
1102
+            return new LockdownManager(function () use ($c) {
1103
+                return $c->getSession();
1104
+            });
1105
+        });
1106
+
1107
+        $this->registerService(\OCP\OCS\IDiscoveryService::class, function (Server $c) {
1108
+            return new DiscoveryService($c->getMemCacheFactory(), $c->getHTTPClientService());
1109
+        });
1110
+
1111
+        $this->registerService(ICloudIdManager::class, function (Server $c) {
1112
+            return new CloudIdManager();
1113
+        });
1114
+
1115
+        $this->registerService(IConfig::class, function (Server $c) {
1116
+            return new GlobalScale\Config($c->getConfig());
1117
+        });
1118
+
1119
+        $this->registerService(ICloudFederationProviderManager::class, function (Server $c) {
1120
+            return new CloudFederationProviderManager($c->getAppManager(), $c->getHTTPClientService(), $c->getCloudIdManager(), $c->getLogger());
1121
+        });
1122
+
1123
+        $this->registerService(ICloudFederationFactory::class, function (Server $c) {
1124
+            return new CloudFederationFactory();
1125
+        });
1126
+
1127
+        $this->registerAlias(\OCP\AppFramework\Utility\IControllerMethodReflector::class, \OC\AppFramework\Utility\ControllerMethodReflector::class);
1128
+        $this->registerAlias('ControllerMethodReflector', \OCP\AppFramework\Utility\IControllerMethodReflector::class);
1129
+
1130
+        $this->registerAlias(\OCP\AppFramework\Utility\ITimeFactory::class, \OC\AppFramework\Utility\TimeFactory::class);
1131
+        $this->registerAlias('TimeFactory', \OCP\AppFramework\Utility\ITimeFactory::class);
1132
+
1133
+        $this->registerService(Defaults::class, function (Server $c) {
1134
+            return new Defaults(
1135
+                $c->getThemingDefaults()
1136
+            );
1137
+        });
1138
+        $this->registerAlias('Defaults', \OCP\Defaults::class);
1139
+
1140
+        $this->registerService(\OCP\ISession::class, function (SimpleContainer $c) {
1141
+            return $c->query(\OCP\IUserSession::class)->getSession();
1142
+        });
1143
+
1144
+        $this->registerService(IShareHelper::class, function (Server $c) {
1145
+            return new ShareHelper(
1146
+                $c->query(\OCP\Share\IManager::class)
1147
+            );
1148
+        });
1149
+
1150
+        $this->registerService(Installer::class, function(Server $c) {
1151
+            return new Installer(
1152
+                $c->getAppFetcher(),
1153
+                $c->getHTTPClientService(),
1154
+                $c->getTempManager(),
1155
+                $c->getLogger(),
1156
+                $c->getConfig()
1157
+            );
1158
+        });
1159
+
1160
+        $this->registerService(IApiFactory::class, function(Server $c) {
1161
+            return new ApiFactory($c->getHTTPClientService());
1162
+        });
1163
+
1164
+        $this->registerService(IInstanceFactory::class, function(Server $c) {
1165
+            $memcacheFactory = $c->getMemCacheFactory();
1166
+            return new InstanceFactory($memcacheFactory->createLocal('remoteinstance.'), $c->getHTTPClientService());
1167
+        });
1168
+
1169
+        $this->registerService(IContactsStore::class, function(Server $c) {
1170
+            return new ContactsStore(
1171
+                $c->getContactsManager(),
1172
+                $c->getConfig(),
1173
+                $c->getUserManager(),
1174
+                $c->getGroupManager()
1175
+            );
1176
+        });
1177
+        $this->registerAlias(IContactsStore::class, ContactsStore::class);
1178
+
1179
+        $this->registerService(IStorageFactory::class, function() {
1180
+            return new StorageFactory();
1181
+        });
1182
+
1183
+        $this->registerAlias(IDashboardManager::class, Dashboard\DashboardManager::class);
1184
+
1185
+        $this->connectDispatcher();
1186
+    }
1187
+
1188
+    /**
1189
+     * @return \OCP\Calendar\IManager
1190
+     */
1191
+    public function getCalendarManager() {
1192
+        return $this->query('CalendarManager');
1193
+    }
1194
+
1195
+    /**
1196
+     * @return \OCP\Calendar\Resource\IManager
1197
+     */
1198
+    public function getCalendarResourceBackendManager() {
1199
+        return $this->query('CalendarResourceBackendManager');
1200
+    }
1201
+
1202
+    /**
1203
+     * @return \OCP\Calendar\Room\IManager
1204
+     */
1205
+    public function getCalendarRoomBackendManager() {
1206
+        return $this->query('CalendarRoomBackendManager');
1207
+    }
1208
+
1209
+    private function connectDispatcher() {
1210
+        $dispatcher = $this->getEventDispatcher();
1211
+
1212
+        // Delete avatar on user deletion
1213
+        $dispatcher->addListener('OCP\IUser::preDelete', function(GenericEvent $e) {
1214
+            $logger = $this->getLogger();
1215
+            $manager = $this->getAvatarManager();
1216
+            /** @var IUser $user */
1217
+            $user = $e->getSubject();
1218
+
1219
+            try {
1220
+                $avatar = $manager->getAvatar($user->getUID());
1221
+                $avatar->remove();
1222
+            } catch (NotFoundException $e) {
1223
+                // no avatar to remove
1224
+            } catch (\Exception $e) {
1225
+                // Ignore exceptions
1226
+                $logger->info('Could not cleanup avatar of ' . $user->getUID());
1227
+            }
1228
+        });
1229
+
1230
+        $dispatcher->addListener('OCP\IUser::changeUser', function (GenericEvent $e) {
1231
+            $manager = $this->getAvatarManager();
1232
+            /** @var IUser $user */
1233
+            $user = $e->getSubject();
1234
+            $feature = $e->getArgument('feature');
1235
+            $oldValue = $e->getArgument('oldValue');
1236
+            $value = $e->getArgument('value');
1237
+
1238
+            try {
1239
+                $avatar = $manager->getAvatar($user->getUID());
1240
+                $avatar->userChanged($feature, $oldValue, $value);
1241
+            } catch (NotFoundException $e) {
1242
+                // no avatar to remove
1243
+            }
1244
+        });
1245
+    }
1246
+
1247
+    /**
1248
+     * @return \OCP\Contacts\IManager
1249
+     */
1250
+    public function getContactsManager() {
1251
+        return $this->query('ContactsManager');
1252
+    }
1253
+
1254
+    /**
1255
+     * @return \OC\Encryption\Manager
1256
+     */
1257
+    public function getEncryptionManager() {
1258
+        return $this->query('EncryptionManager');
1259
+    }
1260
+
1261
+    /**
1262
+     * @return \OC\Encryption\File
1263
+     */
1264
+    public function getEncryptionFilesHelper() {
1265
+        return $this->query('EncryptionFileHelper');
1266
+    }
1267
+
1268
+    /**
1269
+     * @return \OCP\Encryption\Keys\IStorage
1270
+     */
1271
+    public function getEncryptionKeyStorage() {
1272
+        return $this->query('EncryptionKeyStorage');
1273
+    }
1274
+
1275
+    /**
1276
+     * The current request object holding all information about the request
1277
+     * currently being processed is returned from this method.
1278
+     * In case the current execution was not initiated by a web request null is returned
1279
+     *
1280
+     * @return \OCP\IRequest
1281
+     */
1282
+    public function getRequest() {
1283
+        return $this->query('Request');
1284
+    }
1285
+
1286
+    /**
1287
+     * Returns the preview manager which can create preview images for a given file
1288
+     *
1289
+     * @return \OCP\IPreview
1290
+     */
1291
+    public function getPreviewManager() {
1292
+        return $this->query('PreviewManager');
1293
+    }
1294
+
1295
+    /**
1296
+     * Returns the tag manager which can get and set tags for different object types
1297
+     *
1298
+     * @see \OCP\ITagManager::load()
1299
+     * @return \OCP\ITagManager
1300
+     */
1301
+    public function getTagManager() {
1302
+        return $this->query('TagManager');
1303
+    }
1304
+
1305
+    /**
1306
+     * Returns the system-tag manager
1307
+     *
1308
+     * @return \OCP\SystemTag\ISystemTagManager
1309
+     *
1310
+     * @since 9.0.0
1311
+     */
1312
+    public function getSystemTagManager() {
1313
+        return $this->query('SystemTagManager');
1314
+    }
1315
+
1316
+    /**
1317
+     * Returns the system-tag object mapper
1318
+     *
1319
+     * @return \OCP\SystemTag\ISystemTagObjectMapper
1320
+     *
1321
+     * @since 9.0.0
1322
+     */
1323
+    public function getSystemTagObjectMapper() {
1324
+        return $this->query('SystemTagObjectMapper');
1325
+    }
1326
+
1327
+    /**
1328
+     * Returns the avatar manager, used for avatar functionality
1329
+     *
1330
+     * @return \OCP\IAvatarManager
1331
+     */
1332
+    public function getAvatarManager() {
1333
+        return $this->query('AvatarManager');
1334
+    }
1335
+
1336
+    /**
1337
+     * Returns the root folder of ownCloud's data directory
1338
+     *
1339
+     * @return \OCP\Files\IRootFolder
1340
+     */
1341
+    public function getRootFolder() {
1342
+        return $this->query('LazyRootFolder');
1343
+    }
1344
+
1345
+    /**
1346
+     * Returns the root folder of ownCloud's data directory
1347
+     * This is the lazy variant so this gets only initialized once it
1348
+     * is actually used.
1349
+     *
1350
+     * @return \OCP\Files\IRootFolder
1351
+     */
1352
+    public function getLazyRootFolder() {
1353
+        return $this->query('LazyRootFolder');
1354
+    }
1355
+
1356
+    /**
1357
+     * Returns a view to ownCloud's files folder
1358
+     *
1359
+     * @param string $userId user ID
1360
+     * @return \OCP\Files\Folder|null
1361
+     */
1362
+    public function getUserFolder($userId = null) {
1363
+        if ($userId === null) {
1364
+            $user = $this->getUserSession()->getUser();
1365
+            if (!$user) {
1366
+                return null;
1367
+            }
1368
+            $userId = $user->getUID();
1369
+        }
1370
+        $root = $this->getRootFolder();
1371
+        return $root->getUserFolder($userId);
1372
+    }
1373
+
1374
+    /**
1375
+     * Returns an app-specific view in ownClouds data directory
1376
+     *
1377
+     * @return \OCP\Files\Folder
1378
+     * @deprecated since 9.2.0 use IAppData
1379
+     */
1380
+    public function getAppFolder() {
1381
+        $dir = '/' . \OC_App::getCurrentApp();
1382
+        $root = $this->getRootFolder();
1383
+        if (!$root->nodeExists($dir)) {
1384
+            $folder = $root->newFolder($dir);
1385
+        } else {
1386
+            $folder = $root->get($dir);
1387
+        }
1388
+        return $folder;
1389
+    }
1390
+
1391
+    /**
1392
+     * @return \OC\User\Manager
1393
+     */
1394
+    public function getUserManager() {
1395
+        return $this->query('UserManager');
1396
+    }
1397
+
1398
+    /**
1399
+     * @return \OC\Group\Manager
1400
+     */
1401
+    public function getGroupManager() {
1402
+        return $this->query('GroupManager');
1403
+    }
1404
+
1405
+    /**
1406
+     * @return \OC\User\Session
1407
+     */
1408
+    public function getUserSession() {
1409
+        return $this->query('UserSession');
1410
+    }
1411
+
1412
+    /**
1413
+     * @return \OCP\ISession
1414
+     */
1415
+    public function getSession() {
1416
+        return $this->query('UserSession')->getSession();
1417
+    }
1418
+
1419
+    /**
1420
+     * @param \OCP\ISession $session
1421
+     */
1422
+    public function setSession(\OCP\ISession $session) {
1423
+        $this->query(SessionStorage::class)->setSession($session);
1424
+        $this->query('UserSession')->setSession($session);
1425
+        $this->query(Store::class)->setSession($session);
1426
+    }
1427
+
1428
+    /**
1429
+     * @return \OC\Authentication\TwoFactorAuth\Manager
1430
+     */
1431
+    public function getTwoFactorAuthManager() {
1432
+        return $this->query('\OC\Authentication\TwoFactorAuth\Manager');
1433
+    }
1434
+
1435
+    /**
1436
+     * @return \OC\NavigationManager
1437
+     */
1438
+    public function getNavigationManager() {
1439
+        return $this->query('NavigationManager');
1440
+    }
1441
+
1442
+    /**
1443
+     * @return \OCP\IConfig
1444
+     */
1445
+    public function getConfig() {
1446
+        return $this->query('AllConfig');
1447
+    }
1448
+
1449
+    /**
1450
+     * @return \OC\SystemConfig
1451
+     */
1452
+    public function getSystemConfig() {
1453
+        return $this->query('SystemConfig');
1454
+    }
1455
+
1456
+    /**
1457
+     * Returns the app config manager
1458
+     *
1459
+     * @return \OCP\IAppConfig
1460
+     */
1461
+    public function getAppConfig() {
1462
+        return $this->query('AppConfig');
1463
+    }
1464
+
1465
+    /**
1466
+     * @return \OCP\L10N\IFactory
1467
+     */
1468
+    public function getL10NFactory() {
1469
+        return $this->query('L10NFactory');
1470
+    }
1471
+
1472
+    /**
1473
+     * get an L10N instance
1474
+     *
1475
+     * @param string $app appid
1476
+     * @param string $lang
1477
+     * @return IL10N
1478
+     */
1479
+    public function getL10N($app, $lang = null) {
1480
+        return $this->getL10NFactory()->get($app, $lang);
1481
+    }
1482
+
1483
+    /**
1484
+     * @return \OCP\IURLGenerator
1485
+     */
1486
+    public function getURLGenerator() {
1487
+        return $this->query('URLGenerator');
1488
+    }
1489
+
1490
+    /**
1491
+     * @return AppFetcher
1492
+     */
1493
+    public function getAppFetcher() {
1494
+        return $this->query(AppFetcher::class);
1495
+    }
1496
+
1497
+    /**
1498
+     * Returns an ICache instance. Since 8.1.0 it returns a fake cache. Use
1499
+     * getMemCacheFactory() instead.
1500
+     *
1501
+     * @return \OCP\ICache
1502
+     * @deprecated 8.1.0 use getMemCacheFactory to obtain a proper cache
1503
+     */
1504
+    public function getCache() {
1505
+        return $this->query('UserCache');
1506
+    }
1507
+
1508
+    /**
1509
+     * Returns an \OCP\CacheFactory instance
1510
+     *
1511
+     * @return \OCP\ICacheFactory
1512
+     */
1513
+    public function getMemCacheFactory() {
1514
+        return $this->query('MemCacheFactory');
1515
+    }
1516
+
1517
+    /**
1518
+     * Returns an \OC\RedisFactory instance
1519
+     *
1520
+     * @return \OC\RedisFactory
1521
+     */
1522
+    public function getGetRedisFactory() {
1523
+        return $this->query('RedisFactory');
1524
+    }
1525
+
1526
+
1527
+    /**
1528
+     * Returns the current session
1529
+     *
1530
+     * @return \OCP\IDBConnection
1531
+     */
1532
+    public function getDatabaseConnection() {
1533
+        return $this->query('DatabaseConnection');
1534
+    }
1535
+
1536
+    /**
1537
+     * Returns the activity manager
1538
+     *
1539
+     * @return \OCP\Activity\IManager
1540
+     */
1541
+    public function getActivityManager() {
1542
+        return $this->query('ActivityManager');
1543
+    }
1544
+
1545
+    /**
1546
+     * Returns an job list for controlling background jobs
1547
+     *
1548
+     * @return \OCP\BackgroundJob\IJobList
1549
+     */
1550
+    public function getJobList() {
1551
+        return $this->query('JobList');
1552
+    }
1553
+
1554
+    /**
1555
+     * Returns a logger instance
1556
+     *
1557
+     * @return \OCP\ILogger
1558
+     */
1559
+    public function getLogger() {
1560
+        return $this->query('Logger');
1561
+    }
1562
+
1563
+    /**
1564
+     * @return ILogFactory
1565
+     * @throws \OCP\AppFramework\QueryException
1566
+     */
1567
+    public function getLogFactory() {
1568
+        return $this->query(ILogFactory::class);
1569
+    }
1570
+
1571
+    /**
1572
+     * Returns a router for generating and matching urls
1573
+     *
1574
+     * @return \OCP\Route\IRouter
1575
+     */
1576
+    public function getRouter() {
1577
+        return $this->query('Router');
1578
+    }
1579
+
1580
+    /**
1581
+     * Returns a search instance
1582
+     *
1583
+     * @return \OCP\ISearch
1584
+     */
1585
+    public function getSearch() {
1586
+        return $this->query('Search');
1587
+    }
1588
+
1589
+    /**
1590
+     * Returns a SecureRandom instance
1591
+     *
1592
+     * @return \OCP\Security\ISecureRandom
1593
+     */
1594
+    public function getSecureRandom() {
1595
+        return $this->query('SecureRandom');
1596
+    }
1597
+
1598
+    /**
1599
+     * Returns a Crypto instance
1600
+     *
1601
+     * @return \OCP\Security\ICrypto
1602
+     */
1603
+    public function getCrypto() {
1604
+        return $this->query('Crypto');
1605
+    }
1606
+
1607
+    /**
1608
+     * Returns a Hasher instance
1609
+     *
1610
+     * @return \OCP\Security\IHasher
1611
+     */
1612
+    public function getHasher() {
1613
+        return $this->query('Hasher');
1614
+    }
1615
+
1616
+    /**
1617
+     * Returns a CredentialsManager instance
1618
+     *
1619
+     * @return \OCP\Security\ICredentialsManager
1620
+     */
1621
+    public function getCredentialsManager() {
1622
+        return $this->query('CredentialsManager');
1623
+    }
1624
+
1625
+    /**
1626
+     * Get the certificate manager for the user
1627
+     *
1628
+     * @param string $userId (optional) if not specified the current loggedin user is used, use null to get the system certificate manager
1629
+     * @return \OCP\ICertificateManager | null if $uid is null and no user is logged in
1630
+     */
1631
+    public function getCertificateManager($userId = '') {
1632
+        if ($userId === '') {
1633
+            $userSession = $this->getUserSession();
1634
+            $user = $userSession->getUser();
1635
+            if (is_null($user)) {
1636
+                return null;
1637
+            }
1638
+            $userId = $user->getUID();
1639
+        }
1640
+        return new CertificateManager(
1641
+            $userId,
1642
+            new View(),
1643
+            $this->getConfig(),
1644
+            $this->getLogger(),
1645
+            $this->getSecureRandom()
1646
+        );
1647
+    }
1648
+
1649
+    /**
1650
+     * Returns an instance of the HTTP client service
1651
+     *
1652
+     * @return \OCP\Http\Client\IClientService
1653
+     */
1654
+    public function getHTTPClientService() {
1655
+        return $this->query('HttpClientService');
1656
+    }
1657
+
1658
+    /**
1659
+     * Create a new event source
1660
+     *
1661
+     * @return \OCP\IEventSource
1662
+     */
1663
+    public function createEventSource() {
1664
+        return new \OC_EventSource();
1665
+    }
1666
+
1667
+    /**
1668
+     * Get the active event logger
1669
+     *
1670
+     * The returned logger only logs data when debug mode is enabled
1671
+     *
1672
+     * @return \OCP\Diagnostics\IEventLogger
1673
+     */
1674
+    public function getEventLogger() {
1675
+        return $this->query('EventLogger');
1676
+    }
1677
+
1678
+    /**
1679
+     * Get the active query logger
1680
+     *
1681
+     * The returned logger only logs data when debug mode is enabled
1682
+     *
1683
+     * @return \OCP\Diagnostics\IQueryLogger
1684
+     */
1685
+    public function getQueryLogger() {
1686
+        return $this->query('QueryLogger');
1687
+    }
1688
+
1689
+    /**
1690
+     * Get the manager for temporary files and folders
1691
+     *
1692
+     * @return \OCP\ITempManager
1693
+     */
1694
+    public function getTempManager() {
1695
+        return $this->query('TempManager');
1696
+    }
1697
+
1698
+    /**
1699
+     * Get the app manager
1700
+     *
1701
+     * @return \OCP\App\IAppManager
1702
+     */
1703
+    public function getAppManager() {
1704
+        return $this->query('AppManager');
1705
+    }
1706
+
1707
+    /**
1708
+     * Creates a new mailer
1709
+     *
1710
+     * @return \OCP\Mail\IMailer
1711
+     */
1712
+    public function getMailer() {
1713
+        return $this->query('Mailer');
1714
+    }
1715
+
1716
+    /**
1717
+     * Get the webroot
1718
+     *
1719
+     * @return string
1720
+     */
1721
+    public function getWebRoot() {
1722
+        return $this->webRoot;
1723
+    }
1724
+
1725
+    /**
1726
+     * @return \OC\OCSClient
1727
+     */
1728
+    public function getOcsClient() {
1729
+        return $this->query('OcsClient');
1730
+    }
1731
+
1732
+    /**
1733
+     * @return \OCP\IDateTimeZone
1734
+     */
1735
+    public function getDateTimeZone() {
1736
+        return $this->query('DateTimeZone');
1737
+    }
1738
+
1739
+    /**
1740
+     * @return \OCP\IDateTimeFormatter
1741
+     */
1742
+    public function getDateTimeFormatter() {
1743
+        return $this->query('DateTimeFormatter');
1744
+    }
1745
+
1746
+    /**
1747
+     * @return \OCP\Files\Config\IMountProviderCollection
1748
+     */
1749
+    public function getMountProviderCollection() {
1750
+        return $this->query('MountConfigManager');
1751
+    }
1752
+
1753
+    /**
1754
+     * Get the IniWrapper
1755
+     *
1756
+     * @return IniGetWrapper
1757
+     */
1758
+    public function getIniWrapper() {
1759
+        return $this->query('IniWrapper');
1760
+    }
1761
+
1762
+    /**
1763
+     * @return \OCP\Command\IBus
1764
+     */
1765
+    public function getCommandBus() {
1766
+        return $this->query('AsyncCommandBus');
1767
+    }
1768
+
1769
+    /**
1770
+     * Get the trusted domain helper
1771
+     *
1772
+     * @return TrustedDomainHelper
1773
+     */
1774
+    public function getTrustedDomainHelper() {
1775
+        return $this->query('TrustedDomainHelper');
1776
+    }
1777
+
1778
+    /**
1779
+     * Get the locking provider
1780
+     *
1781
+     * @return \OCP\Lock\ILockingProvider
1782
+     * @since 8.1.0
1783
+     */
1784
+    public function getLockingProvider() {
1785
+        return $this->query('LockingProvider');
1786
+    }
1787
+
1788
+    /**
1789
+     * @return \OCP\Files\Mount\IMountManager
1790
+     **/
1791
+    function getMountManager() {
1792
+        return $this->query('MountManager');
1793
+    }
1794
+
1795
+    /** @return \OCP\Files\Config\IUserMountCache */
1796
+    function getUserMountCache() {
1797
+        return $this->query('UserMountCache');
1798
+    }
1799
+
1800
+    /**
1801
+     * Get the MimeTypeDetector
1802
+     *
1803
+     * @return \OCP\Files\IMimeTypeDetector
1804
+     */
1805
+    public function getMimeTypeDetector() {
1806
+        return $this->query('MimeTypeDetector');
1807
+    }
1808
+
1809
+    /**
1810
+     * Get the MimeTypeLoader
1811
+     *
1812
+     * @return \OCP\Files\IMimeTypeLoader
1813
+     */
1814
+    public function getMimeTypeLoader() {
1815
+        return $this->query('MimeTypeLoader');
1816
+    }
1817
+
1818
+    /**
1819
+     * Get the manager of all the capabilities
1820
+     *
1821
+     * @return \OC\CapabilitiesManager
1822
+     */
1823
+    public function getCapabilitiesManager() {
1824
+        return $this->query('CapabilitiesManager');
1825
+    }
1826
+
1827
+    /**
1828
+     * Get the EventDispatcher
1829
+     *
1830
+     * @return EventDispatcherInterface
1831
+     * @since 8.2.0
1832
+     */
1833
+    public function getEventDispatcher() {
1834
+        return $this->query('EventDispatcher');
1835
+    }
1836
+
1837
+    /**
1838
+     * Get the Notification Manager
1839
+     *
1840
+     * @return \OCP\Notification\IManager
1841
+     * @since 8.2.0
1842
+     */
1843
+    public function getNotificationManager() {
1844
+        return $this->query('NotificationManager');
1845
+    }
1846
+
1847
+    /**
1848
+     * @return \OCP\Comments\ICommentsManager
1849
+     */
1850
+    public function getCommentsManager() {
1851
+        return $this->query('CommentsManager');
1852
+    }
1853
+
1854
+    /**
1855
+     * @return \OCA\Theming\ThemingDefaults
1856
+     */
1857
+    public function getThemingDefaults() {
1858
+        return $this->query('ThemingDefaults');
1859
+    }
1860
+
1861
+    /**
1862
+     * @return \OC\IntegrityCheck\Checker
1863
+     */
1864
+    public function getIntegrityCodeChecker() {
1865
+        return $this->query('IntegrityCodeChecker');
1866
+    }
1867
+
1868
+    /**
1869
+     * @return \OC\Session\CryptoWrapper
1870
+     */
1871
+    public function getSessionCryptoWrapper() {
1872
+        return $this->query('CryptoWrapper');
1873
+    }
1874
+
1875
+    /**
1876
+     * @return CsrfTokenManager
1877
+     */
1878
+    public function getCsrfTokenManager() {
1879
+        return $this->query('CsrfTokenManager');
1880
+    }
1881
+
1882
+    /**
1883
+     * @return Throttler
1884
+     */
1885
+    public function getBruteForceThrottler() {
1886
+        return $this->query('Throttler');
1887
+    }
1888
+
1889
+    /**
1890
+     * @return IContentSecurityPolicyManager
1891
+     */
1892
+    public function getContentSecurityPolicyManager() {
1893
+        return $this->query('ContentSecurityPolicyManager');
1894
+    }
1895
+
1896
+    /**
1897
+     * @return ContentSecurityPolicyNonceManager
1898
+     */
1899
+    public function getContentSecurityPolicyNonceManager() {
1900
+        return $this->query('ContentSecurityPolicyNonceManager');
1901
+    }
1902
+
1903
+    /**
1904
+     * Not a public API as of 8.2, wait for 9.0
1905
+     *
1906
+     * @return \OCA\Files_External\Service\BackendService
1907
+     */
1908
+    public function getStoragesBackendService() {
1909
+        return $this->query('OCA\\Files_External\\Service\\BackendService');
1910
+    }
1911
+
1912
+    /**
1913
+     * Not a public API as of 8.2, wait for 9.0
1914
+     *
1915
+     * @return \OCA\Files_External\Service\GlobalStoragesService
1916
+     */
1917
+    public function getGlobalStoragesService() {
1918
+        return $this->query('OCA\\Files_External\\Service\\GlobalStoragesService');
1919
+    }
1920
+
1921
+    /**
1922
+     * Not a public API as of 8.2, wait for 9.0
1923
+     *
1924
+     * @return \OCA\Files_External\Service\UserGlobalStoragesService
1925
+     */
1926
+    public function getUserGlobalStoragesService() {
1927
+        return $this->query('OCA\\Files_External\\Service\\UserGlobalStoragesService');
1928
+    }
1929
+
1930
+    /**
1931
+     * Not a public API as of 8.2, wait for 9.0
1932
+     *
1933
+     * @return \OCA\Files_External\Service\UserStoragesService
1934
+     */
1935
+    public function getUserStoragesService() {
1936
+        return $this->query('OCA\\Files_External\\Service\\UserStoragesService');
1937
+    }
1938
+
1939
+    /**
1940
+     * @return \OCP\Share\IManager
1941
+     */
1942
+    public function getShareManager() {
1943
+        return $this->query('ShareManager');
1944
+    }
1945
+
1946
+    /**
1947
+     * @return \OCP\Collaboration\Collaborators\ISearch
1948
+     */
1949
+    public function getCollaboratorSearch() {
1950
+        return $this->query('CollaboratorSearch');
1951
+    }
1952
+
1953
+    /**
1954
+     * @return \OCP\Collaboration\AutoComplete\IManager
1955
+     */
1956
+    public function getAutoCompleteManager(){
1957
+        return $this->query(IManager::class);
1958
+    }
1959
+
1960
+    /**
1961
+     * Returns the LDAP Provider
1962
+     *
1963
+     * @return \OCP\LDAP\ILDAPProvider
1964
+     */
1965
+    public function getLDAPProvider() {
1966
+        return $this->query('LDAPProvider');
1967
+    }
1968
+
1969
+    /**
1970
+     * @return \OCP\Settings\IManager
1971
+     */
1972
+    public function getSettingsManager() {
1973
+        return $this->query('SettingsManager');
1974
+    }
1975
+
1976
+    /**
1977
+     * @return \OCP\Files\IAppData
1978
+     */
1979
+    public function getAppDataDir($app) {
1980
+        /** @var \OC\Files\AppData\Factory $factory */
1981
+        $factory = $this->query(\OC\Files\AppData\Factory::class);
1982
+        return $factory->get($app);
1983
+    }
1984
+
1985
+    /**
1986
+     * @return \OCP\Lockdown\ILockdownManager
1987
+     */
1988
+    public function getLockdownManager() {
1989
+        return $this->query('LockdownManager');
1990
+    }
1991
+
1992
+    /**
1993
+     * @return \OCP\Federation\ICloudIdManager
1994
+     */
1995
+    public function getCloudIdManager() {
1996
+        return $this->query(ICloudIdManager::class);
1997
+    }
1998
+
1999
+    /**
2000
+     * @return \OCP\GlobalScale\IConfig
2001
+     */
2002
+    public function getGlobalScaleConfig() {
2003
+        return $this->query(IConfig::class);
2004
+    }
2005
+
2006
+    /**
2007
+     * @return \OCP\Federation\ICloudFederationProviderManager
2008
+     */
2009
+    public function getCloudFederationProviderManager() {
2010
+        return $this->query(ICloudFederationProviderManager::class);
2011
+    }
2012
+
2013
+    /**
2014
+     * @return \OCP\Remote\Api\IApiFactory
2015
+     */
2016
+    public function getRemoteApiFactory() {
2017
+        return $this->query(IApiFactory::class);
2018
+    }
2019
+
2020
+    /**
2021
+     * @return \OCP\Federation\ICloudFederationFactory
2022
+     */
2023
+    public function getCloudFederationFactory() {
2024
+        return $this->query(ICloudFederationFactory::class);
2025
+    }
2026
+
2027
+    /**
2028
+     * @return \OCP\Remote\IInstanceFactory
2029
+     */
2030
+    public function getRemoteInstanceFactory() {
2031
+        return $this->query(IInstanceFactory::class);
2032
+    }
2033
+
2034
+    /**
2035
+     * @return IStorageFactory
2036
+     */
2037
+    public function getStorageFactory() {
2038
+        return $this->query(IStorageFactory::class);
2039
+    }
2040 2040
 }
Please login to merge, or discard this patch.
apps/dav/lib/CalDAV/Publishing/PublishPlugin.php 3 patches
Doc Comments   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -134,7 +134,7 @@
 block discarded – undo
134 134
 	 * @param RequestInterface $request
135 135
 	 * @param ResponseInterface $response
136 136
 	 *
137
-	 * @return void|bool
137
+	 * @return null|false
138 138
 	 */
139 139
 	public function httpPost(RequestInterface $request, ResponseInterface $response) {
140 140
 		$path = $request->getPath();
Please login to merge, or discard this patch.
Indentation   +189 added lines, -189 removed lines patch added patch discarded remove patch
@@ -34,194 +34,194 @@
 block discarded – undo
34 34
 use OCP\IConfig;
35 35
 
36 36
 class PublishPlugin extends ServerPlugin {
37
-	const NS_CALENDARSERVER = 'http://calendarserver.org/ns/';
38
-
39
-	/**
40
-	 * Reference to SabreDAV server object.
41
-	 *
42
-	 * @var \Sabre\DAV\Server
43
-	 */
44
-	protected $server;
45
-
46
-	/**
47
-	 * Config instance to get instance secret.
48
-	 *
49
-	 * @var IConfig
50
-	 */
51
-	protected $config;
52
-
53
-	/**
54
-	 * URL Generator for absolute URLs.
55
-	 *
56
-	 * @var IURLGenerator
57
-	 */
58
-	protected $urlGenerator;
59
-
60
-	/**
61
-	 * PublishPlugin constructor.
62
-	 *
63
-	 * @param IConfig $config
64
-	 * @param IURLGenerator $urlGenerator
65
-	 */
66
-	public function __construct(IConfig $config, IURLGenerator $urlGenerator) {
67
-		$this->config = $config;
68
-		$this->urlGenerator = $urlGenerator;
69
-	}
70
-
71
-	/**
72
-	 * This method should return a list of server-features.
73
-	 *
74
-	 * This is for example 'versioning' and is added to the DAV: header
75
-	 * in an OPTIONS response.
76
-	 *
77
-	 * @return string[]
78
-	 */
79
-	public function getFeatures() {
80
-		// May have to be changed to be detected
81
-		return ['oc-calendar-publishing', 'calendarserver-sharing'];
82
-	}
83
-
84
-	/**
85
-	 * Returns a plugin name.
86
-	 *
87
-	 * Using this name other plugins will be able to access other plugins
88
-	 * using Sabre\DAV\Server::getPlugin
89
-	 *
90
-	 * @return string
91
-	 */
92
-	public function getPluginName()	{
93
-		return 'oc-calendar-publishing';
94
-	}
95
-
96
-	/**
97
-	 * This initializes the plugin.
98
-	 *
99
-	 * This function is called by Sabre\DAV\Server, after
100
-	 * addPlugin is called.
101
-	 *
102
-	 * This method should set up the required event subscriptions.
103
-	 *
104
-	 * @param Server $server
105
-	 */
106
-	public function initialize(Server $server) {
107
-		$this->server = $server;
108
-
109
-		$this->server->on('method:POST', [$this, 'httpPost']);
110
-		$this->server->on('propFind',    [$this, 'propFind']);
111
-	}
112
-
113
-	public function propFind(PropFind $propFind, INode $node) {
114
-		if ($node instanceof Calendar) {
115
-			$propFind->handle('{'.self::NS_CALENDARSERVER.'}publish-url', function () use ($node) {
116
-				if ($node->getPublishStatus()) {
117
-					// We return the publish-url only if the calendar is published.
118
-					$token = $node->getPublishStatus();
119
-					$publishUrl = $this->urlGenerator->getAbsoluteURL($this->server->getBaseUri().'public-calendars/').$token;
120
-
121
-					return new Publisher($publishUrl, true);
122
-				}
123
-			});
124
-
125
-			$propFind->handle('{'.self::NS_CALENDARSERVER.'}allowed-sharing-modes', function() use ($node) {
126
-				return new AllowedSharingModes(!$node->isSubscription(), !$node->isSubscription());
127
-			});
128
-		}
129
-	}
130
-
131
-	/**
132
-	 * We intercept this to handle POST requests on calendars.
133
-	 *
134
-	 * @param RequestInterface $request
135
-	 * @param ResponseInterface $response
136
-	 *
137
-	 * @return void|bool
138
-	 */
139
-	public function httpPost(RequestInterface $request, ResponseInterface $response) {
140
-		$path = $request->getPath();
141
-
142
-		// Only handling xml
143
-		$contentType = $request->getHeader('Content-Type');
144
-		if (strpos($contentType, 'application/xml') === false && strpos($contentType, 'text/xml') === false) {
145
-			return;
146
-		}
147
-
148
-		// Making sure the node exists
149
-		try {
150
-			$node = $this->server->tree->getNodeForPath($path);
151
-		} catch (NotFound $e) {
152
-			return;
153
-		}
154
-
155
-		$requestBody = $request->getBodyAsString();
156
-
157
-		// If this request handler could not deal with this POST request, it
158
-		// will return 'null' and other plugins get a chance to handle the
159
-		// request.
160
-		//
161
-		// However, we already requested the full body. This is a problem,
162
-		// because a body can only be read once. This is why we preemptively
163
-		// re-populated the request body with the existing data.
164
-		$request->setBody($requestBody);
165
-
166
-		$this->server->xml->parse($requestBody, $request->getUrl(), $documentType);
167
-
168
-		switch ($documentType) {
169
-
170
-			case '{'.self::NS_CALENDARSERVER.'}publish-calendar' :
171
-
172
-			// We can only deal with IShareableCalendar objects
173
-			if (!$node instanceof Calendar) {
174
-				return;
175
-			}
176
-			$this->server->transactionType = 'post-publish-calendar';
177
-
178
-			// Getting ACL info
179
-			$acl = $this->server->getPlugin('acl');
180
-
181
-			// If there's no ACL support, we allow everything
182
-			if ($acl) {
183
-				$acl->checkPrivileges($path, '{DAV:}write');
184
-			}
185
-
186
-			$node->setPublishStatus(true);
187
-
188
-			// iCloud sends back the 202, so we will too.
189
-			$response->setStatus(202);
190
-
191
-			// Adding this because sending a response body may cause issues,
192
-			// and I wanted some type of indicator the response was handled.
193
-			$response->setHeader('X-Sabre-Status', 'everything-went-well');
194
-
195
-			// Breaking the event chain
196
-			return false;
197
-
198
-			case '{'.self::NS_CALENDARSERVER.'}unpublish-calendar' :
199
-
200
-			// We can only deal with IShareableCalendar objects
201
-			if (!$node instanceof Calendar) {
202
-				return;
203
-			}
204
-			$this->server->transactionType = 'post-unpublish-calendar';
205
-
206
-			// Getting ACL info
207
-			$acl = $this->server->getPlugin('acl');
208
-
209
-			// If there's no ACL support, we allow everything
210
-			if ($acl) {
211
-				$acl->checkPrivileges($path, '{DAV:}write');
212
-			}
213
-
214
-			$node->setPublishStatus(false);
215
-
216
-			$response->setStatus(200);
217
-
218
-			// Adding this because sending a response body may cause issues,
219
-			// and I wanted some type of indicator the response was handled.
220
-			$response->setHeader('X-Sabre-Status', 'everything-went-well');
221
-
222
-			// Breaking the event chain
223
-			return false;
37
+    const NS_CALENDARSERVER = 'http://calendarserver.org/ns/';
38
+
39
+    /**
40
+     * Reference to SabreDAV server object.
41
+     *
42
+     * @var \Sabre\DAV\Server
43
+     */
44
+    protected $server;
45
+
46
+    /**
47
+     * Config instance to get instance secret.
48
+     *
49
+     * @var IConfig
50
+     */
51
+    protected $config;
52
+
53
+    /**
54
+     * URL Generator for absolute URLs.
55
+     *
56
+     * @var IURLGenerator
57
+     */
58
+    protected $urlGenerator;
59
+
60
+    /**
61
+     * PublishPlugin constructor.
62
+     *
63
+     * @param IConfig $config
64
+     * @param IURLGenerator $urlGenerator
65
+     */
66
+    public function __construct(IConfig $config, IURLGenerator $urlGenerator) {
67
+        $this->config = $config;
68
+        $this->urlGenerator = $urlGenerator;
69
+    }
70
+
71
+    /**
72
+     * This method should return a list of server-features.
73
+     *
74
+     * This is for example 'versioning' and is added to the DAV: header
75
+     * in an OPTIONS response.
76
+     *
77
+     * @return string[]
78
+     */
79
+    public function getFeatures() {
80
+        // May have to be changed to be detected
81
+        return ['oc-calendar-publishing', 'calendarserver-sharing'];
82
+    }
83
+
84
+    /**
85
+     * Returns a plugin name.
86
+     *
87
+     * Using this name other plugins will be able to access other plugins
88
+     * using Sabre\DAV\Server::getPlugin
89
+     *
90
+     * @return string
91
+     */
92
+    public function getPluginName()	{
93
+        return 'oc-calendar-publishing';
94
+    }
95
+
96
+    /**
97
+     * This initializes the plugin.
98
+     *
99
+     * This function is called by Sabre\DAV\Server, after
100
+     * addPlugin is called.
101
+     *
102
+     * This method should set up the required event subscriptions.
103
+     *
104
+     * @param Server $server
105
+     */
106
+    public function initialize(Server $server) {
107
+        $this->server = $server;
108
+
109
+        $this->server->on('method:POST', [$this, 'httpPost']);
110
+        $this->server->on('propFind',    [$this, 'propFind']);
111
+    }
112
+
113
+    public function propFind(PropFind $propFind, INode $node) {
114
+        if ($node instanceof Calendar) {
115
+            $propFind->handle('{'.self::NS_CALENDARSERVER.'}publish-url', function () use ($node) {
116
+                if ($node->getPublishStatus()) {
117
+                    // We return the publish-url only if the calendar is published.
118
+                    $token = $node->getPublishStatus();
119
+                    $publishUrl = $this->urlGenerator->getAbsoluteURL($this->server->getBaseUri().'public-calendars/').$token;
120
+
121
+                    return new Publisher($publishUrl, true);
122
+                }
123
+            });
124
+
125
+            $propFind->handle('{'.self::NS_CALENDARSERVER.'}allowed-sharing-modes', function() use ($node) {
126
+                return new AllowedSharingModes(!$node->isSubscription(), !$node->isSubscription());
127
+            });
128
+        }
129
+    }
130
+
131
+    /**
132
+     * We intercept this to handle POST requests on calendars.
133
+     *
134
+     * @param RequestInterface $request
135
+     * @param ResponseInterface $response
136
+     *
137
+     * @return void|bool
138
+     */
139
+    public function httpPost(RequestInterface $request, ResponseInterface $response) {
140
+        $path = $request->getPath();
141
+
142
+        // Only handling xml
143
+        $contentType = $request->getHeader('Content-Type');
144
+        if (strpos($contentType, 'application/xml') === false && strpos($contentType, 'text/xml') === false) {
145
+            return;
146
+        }
147
+
148
+        // Making sure the node exists
149
+        try {
150
+            $node = $this->server->tree->getNodeForPath($path);
151
+        } catch (NotFound $e) {
152
+            return;
153
+        }
154
+
155
+        $requestBody = $request->getBodyAsString();
156
+
157
+        // If this request handler could not deal with this POST request, it
158
+        // will return 'null' and other plugins get a chance to handle the
159
+        // request.
160
+        //
161
+        // However, we already requested the full body. This is a problem,
162
+        // because a body can only be read once. This is why we preemptively
163
+        // re-populated the request body with the existing data.
164
+        $request->setBody($requestBody);
165
+
166
+        $this->server->xml->parse($requestBody, $request->getUrl(), $documentType);
167
+
168
+        switch ($documentType) {
169
+
170
+            case '{'.self::NS_CALENDARSERVER.'}publish-calendar' :
171
+
172
+            // We can only deal with IShareableCalendar objects
173
+            if (!$node instanceof Calendar) {
174
+                return;
175
+            }
176
+            $this->server->transactionType = 'post-publish-calendar';
177
+
178
+            // Getting ACL info
179
+            $acl = $this->server->getPlugin('acl');
180
+
181
+            // If there's no ACL support, we allow everything
182
+            if ($acl) {
183
+                $acl->checkPrivileges($path, '{DAV:}write');
184
+            }
185
+
186
+            $node->setPublishStatus(true);
187
+
188
+            // iCloud sends back the 202, so we will too.
189
+            $response->setStatus(202);
190
+
191
+            // Adding this because sending a response body may cause issues,
192
+            // and I wanted some type of indicator the response was handled.
193
+            $response->setHeader('X-Sabre-Status', 'everything-went-well');
194
+
195
+            // Breaking the event chain
196
+            return false;
197
+
198
+            case '{'.self::NS_CALENDARSERVER.'}unpublish-calendar' :
199
+
200
+            // We can only deal with IShareableCalendar objects
201
+            if (!$node instanceof Calendar) {
202
+                return;
203
+            }
204
+            $this->server->transactionType = 'post-unpublish-calendar';
205
+
206
+            // Getting ACL info
207
+            $acl = $this->server->getPlugin('acl');
208
+
209
+            // If there's no ACL support, we allow everything
210
+            if ($acl) {
211
+                $acl->checkPrivileges($path, '{DAV:}write');
212
+            }
213
+
214
+            $node->setPublishStatus(false);
215
+
216
+            $response->setStatus(200);
217
+
218
+            // Adding this because sending a response body may cause issues,
219
+            // and I wanted some type of indicator the response was handled.
220
+            $response->setHeader('X-Sabre-Status', 'everything-went-well');
221
+
222
+            // Breaking the event chain
223
+            return false;
224 224
 
225
-		}
226
-	}
225
+        }
226
+    }
227 227
 }
Please login to merge, or discard this patch.
Spacing   +3 added lines, -3 removed lines patch added patch discarded remove patch
@@ -89,7 +89,7 @@  discard block
 block discarded – undo
89 89
 	 *
90 90
 	 * @return string
91 91
 	 */
92
-	public function getPluginName()	{
92
+	public function getPluginName() {
93 93
 		return 'oc-calendar-publishing';
94 94
 	}
95 95
 
@@ -107,12 +107,12 @@  discard block
 block discarded – undo
107 107
 		$this->server = $server;
108 108
 
109 109
 		$this->server->on('method:POST', [$this, 'httpPost']);
110
-		$this->server->on('propFind',    [$this, 'propFind']);
110
+		$this->server->on('propFind', [$this, 'propFind']);
111 111
 	}
112 112
 
113 113
 	public function propFind(PropFind $propFind, INode $node) {
114 114
 		if ($node instanceof Calendar) {
115
-			$propFind->handle('{'.self::NS_CALENDARSERVER.'}publish-url', function () use ($node) {
115
+			$propFind->handle('{'.self::NS_CALENDARSERVER.'}publish-url', function() use ($node) {
116 116
 				if ($node->getPublishStatus()) {
117 117
 					// We return the publish-url only if the calendar is published.
118 118
 					$token = $node->getPublishStatus();
Please login to merge, or discard this patch.
apps/dav/lib/CardDAV/AddressBookRoot.php 2 patches
Doc Comments   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -30,7 +30,7 @@
 block discarded – undo
30 30
 
31 31
 	/**
32 32
 	 * @param \Sabre\DAVACL\PrincipalBackend\BackendInterface $principalBackend
33
-	 * @param \Sabre\CardDAV\Backend\BackendInterface $carddavBackend
33
+	 * @param CardDavBackend $carddavBackend
34 34
 	 * @param string $principalPrefix
35 35
 	 */
36 36
 	public function __construct(\Sabre\DAVACL\PrincipalBackend\BackendInterface $principalBackend, \Sabre\CardDAV\Backend\BackendInterface $carddavBackend, $principalPrefix = 'principals') {
Please login to merge, or discard this patch.
Indentation   +33 added lines, -33 removed lines patch added patch discarded remove patch
@@ -25,46 +25,46 @@
 block discarded – undo
25 25
 
26 26
 class AddressBookRoot extends \Sabre\CardDAV\AddressBookRoot {
27 27
 
28
-	/** @var IL10N */
29
-	protected $l10n;
28
+    /** @var IL10N */
29
+    protected $l10n;
30 30
 
31
-	/**
32
-	 * @param \Sabre\DAVACL\PrincipalBackend\BackendInterface $principalBackend
33
-	 * @param \Sabre\CardDAV\Backend\BackendInterface $carddavBackend
34
-	 * @param string $principalPrefix
35
-	 */
36
-	public function __construct(\Sabre\DAVACL\PrincipalBackend\BackendInterface $principalBackend, \Sabre\CardDAV\Backend\BackendInterface $carddavBackend, $principalPrefix = 'principals') {
37
-		parent::__construct($principalBackend, $carddavBackend, $principalPrefix);
38
-		$this->l10n = \OC::$server->getL10N('dav');
39
-	}
31
+    /**
32
+     * @param \Sabre\DAVACL\PrincipalBackend\BackendInterface $principalBackend
33
+     * @param \Sabre\CardDAV\Backend\BackendInterface $carddavBackend
34
+     * @param string $principalPrefix
35
+     */
36
+    public function __construct(\Sabre\DAVACL\PrincipalBackend\BackendInterface $principalBackend, \Sabre\CardDAV\Backend\BackendInterface $carddavBackend, $principalPrefix = 'principals') {
37
+        parent::__construct($principalBackend, $carddavBackend, $principalPrefix);
38
+        $this->l10n = \OC::$server->getL10N('dav');
39
+    }
40 40
 
41
-	/**
42
-	 * This method returns a node for a principal.
43
-	 *
44
-	 * The passed array contains principal information, and is guaranteed to
45
-	 * at least contain a uri item. Other properties may or may not be
46
-	 * supplied by the authentication backend.
47
-	 *
48
-	 * @param array $principal
49
-	 * @return \Sabre\DAV\INode
50
-	 */
51
-	function getChildForPrincipal(array $principal) {
41
+    /**
42
+     * This method returns a node for a principal.
43
+     *
44
+     * The passed array contains principal information, and is guaranteed to
45
+     * at least contain a uri item. Other properties may or may not be
46
+     * supplied by the authentication backend.
47
+     *
48
+     * @param array $principal
49
+     * @return \Sabre\DAV\INode
50
+     */
51
+    function getChildForPrincipal(array $principal) {
52 52
 
53
-		return new UserAddressBooks($this->carddavBackend, $principal['uri'], $this->l10n);
53
+        return new UserAddressBooks($this->carddavBackend, $principal['uri'], $this->l10n);
54 54
 
55
-	}
55
+    }
56 56
 
57
-	function getName() {
57
+    function getName() {
58 58
 
59
-		if ($this->principalPrefix === 'principals') {
60
-			return parent::getName();
61
-		}
62
-		// Grabbing all the components of the principal path.
63
-		$parts = explode('/', $this->principalPrefix);
59
+        if ($this->principalPrefix === 'principals') {
60
+            return parent::getName();
61
+        }
62
+        // Grabbing all the components of the principal path.
63
+        $parts = explode('/', $this->principalPrefix);
64 64
 
65
-		// We are only interested in the second part.
66
-		return $parts[1];
65
+        // We are only interested in the second part.
66
+        return $parts[1];
67 67
 
68
-	}
68
+    }
69 69
 
70 70
 }
Please login to merge, or discard this patch.
lib/private/Share20/DefaultShareProvider.php 4 patches
Doc Comments   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -770,7 +770,7 @@
 block discarded – undo
770 770
 
771 771
 	/**
772 772
 	 * @param Share[] $shares
773
-	 * @param $userId
773
+	 * @param string $userId
774 774
 	 * @return Share[] The updates shares if no update is found for a share return the original
775 775
 	 */
776 776
 	private function resolveGroupShares($shares, $userId) {
Please login to merge, or discard this patch.
Unused Use Statements   -1 removed lines patch added patch discarded remove patch
@@ -37,7 +37,6 @@
 block discarded – undo
37 37
 use OCP\IUser;
38 38
 use OCP\Mail\IMailer;
39 39
 use OCP\Share\IShare;
40
-use OCP\Share\IShareHelper;
41 40
 use OCP\Share\IShareProvider;
42 41
 use OC\Share20\Exception\InvalidShare;
43 42
 use OC\Share20\Exception\ProviderException;
Please login to merge, or discard this patch.
Indentation   +1271 added lines, -1271 removed lines patch added patch discarded remove patch
@@ -58,1308 +58,1308 @@
 block discarded – undo
58 58
  */
59 59
 class DefaultShareProvider implements IShareProvider {
60 60
 
61
-	// Special share type for user modified group shares
62
-	const SHARE_TYPE_USERGROUP = 2;
63
-
64
-	/** @var IDBConnection */
65
-	private $dbConn;
66
-
67
-	/** @var IUserManager */
68
-	private $userManager;
69
-
70
-	/** @var IGroupManager */
71
-	private $groupManager;
72
-
73
-	/** @var IRootFolder */
74
-	private $rootFolder;
75
-
76
-	/** @var IMailer */
77
-	private $mailer;
78
-
79
-	/** @var Defaults */
80
-	private $defaults;
81
-
82
-	/** @var IL10N */
83
-	private $l;
84
-
85
-	/** @var IURLGenerator */
86
-	private $urlGenerator;
87
-
88
-	/**
89
-	 * DefaultShareProvider constructor.
90
-	 *
91
-	 * @param IDBConnection $connection
92
-	 * @param IUserManager $userManager
93
-	 * @param IGroupManager $groupManager
94
-	 * @param IRootFolder $rootFolder
95
-	 * @param IMailer $mailer ;
96
-	 * @param Defaults $defaults
97
-	 * @param IL10N $l
98
-	 * @param IURLGenerator $urlGenerator
99
-	 */
100
-	public function __construct(
101
-			IDBConnection $connection,
102
-			IUserManager $userManager,
103
-			IGroupManager $groupManager,
104
-			IRootFolder $rootFolder,
105
-			IMailer $mailer,
106
-			Defaults $defaults,
107
-			IL10N $l,
108
-			IURLGenerator $urlGenerator) {
109
-		$this->dbConn = $connection;
110
-		$this->userManager = $userManager;
111
-		$this->groupManager = $groupManager;
112
-		$this->rootFolder = $rootFolder;
113
-		$this->mailer = $mailer;
114
-		$this->defaults = $defaults;
115
-		$this->l = $l;
116
-		$this->urlGenerator = $urlGenerator;
117
-	}
118
-
119
-	/**
120
-	 * Return the identifier of this provider.
121
-	 *
122
-	 * @return string Containing only [a-zA-Z0-9]
123
-	 */
124
-	public function identifier() {
125
-		return 'ocinternal';
126
-	}
127
-
128
-	/**
129
-	 * Share a path
130
-	 *
131
-	 * @param \OCP\Share\IShare $share
132
-	 * @return \OCP\Share\IShare The share object
133
-	 * @throws ShareNotFound
134
-	 * @throws \Exception
135
-	 */
136
-	public function create(\OCP\Share\IShare $share) {
137
-		$qb = $this->dbConn->getQueryBuilder();
138
-
139
-		$qb->insert('share');
140
-		$qb->setValue('share_type', $qb->createNamedParameter($share->getShareType()));
141
-
142
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
143
-			//Set the UID of the user we share with
144
-			$qb->setValue('share_with', $qb->createNamedParameter($share->getSharedWith()));
145
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
146
-			//Set the GID of the group we share with
147
-			$qb->setValue('share_with', $qb->createNamedParameter($share->getSharedWith()));
148
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
149
-			//Set the token of the share
150
-			$qb->setValue('token', $qb->createNamedParameter($share->getToken()));
151
-
152
-			//If a password is set store it
153
-			if ($share->getPassword() !== null) {
154
-				$qb->setValue('password', $qb->createNamedParameter($share->getPassword()));
155
-			}
156
-
157
-			//If an expiration date is set store it
158
-			if ($share->getExpirationDate() !== null) {
159
-				$qb->setValue('expiration', $qb->createNamedParameter($share->getExpirationDate(), 'datetime'));
160
-			}
161
-
162
-			if (method_exists($share, 'getParent')) {
163
-				$qb->setValue('parent', $qb->createNamedParameter($share->getParent()));
164
-			}
165
-		} else {
166
-			throw new \Exception('invalid share type!');
167
-		}
168
-
169
-		// Set what is shares
170
-		$qb->setValue('item_type', $qb->createParameter('itemType'));
171
-		if ($share->getNode() instanceof \OCP\Files\File) {
172
-			$qb->setParameter('itemType', 'file');
173
-		} else {
174
-			$qb->setParameter('itemType', 'folder');
175
-		}
176
-
177
-		// Set the file id
178
-		$qb->setValue('item_source', $qb->createNamedParameter($share->getNode()->getId()));
179
-		$qb->setValue('file_source', $qb->createNamedParameter($share->getNode()->getId()));
180
-
181
-		// set the permissions
182
-		$qb->setValue('permissions', $qb->createNamedParameter($share->getPermissions()));
183
-
184
-		// Set who created this share
185
-		$qb->setValue('uid_initiator', $qb->createNamedParameter($share->getSharedBy()));
186
-
187
-		// Set who is the owner of this file/folder (and this the owner of the share)
188
-		$qb->setValue('uid_owner', $qb->createNamedParameter($share->getShareOwner()));
189
-
190
-		// Set the file target
191
-		$qb->setValue('file_target', $qb->createNamedParameter($share->getTarget()));
192
-
193
-		// Set the time this share was created
194
-		$qb->setValue('stime', $qb->createNamedParameter(time()));
195
-
196
-		// insert the data and fetch the id of the share
197
-		$this->dbConn->beginTransaction();
198
-		$qb->execute();
199
-		$id = $this->dbConn->lastInsertId('*PREFIX*share');
200
-
201
-		// Now fetch the inserted share and create a complete share object
202
-		$qb = $this->dbConn->getQueryBuilder();
203
-		$qb->select('*')
204
-			->from('share')
205
-			->where($qb->expr()->eq('id', $qb->createNamedParameter($id)));
206
-
207
-		$cursor = $qb->execute();
208
-		$data = $cursor->fetch();
209
-		$this->dbConn->commit();
210
-		$cursor->closeCursor();
211
-
212
-		if ($data === false) {
213
-			throw new ShareNotFound();
214
-		}
215
-
216
-		$mailSendValue = $share->getMailSend();
217
-		$data['mail_send'] = ($mailSendValue === null) ? true : $mailSendValue;
218
-
219
-		$share = $this->createShare($data);
220
-		return $share;
221
-	}
222
-
223
-	/**
224
-	 * Update a share
225
-	 *
226
-	 * @param \OCP\Share\IShare $share
227
-	 * @return \OCP\Share\IShare The share object
228
-	 */
229
-	public function update(\OCP\Share\IShare $share) {
230
-
231
-		$originalShare = $this->getShareById($share->getId());
232
-
233
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
234
-			/*
61
+    // Special share type for user modified group shares
62
+    const SHARE_TYPE_USERGROUP = 2;
63
+
64
+    /** @var IDBConnection */
65
+    private $dbConn;
66
+
67
+    /** @var IUserManager */
68
+    private $userManager;
69
+
70
+    /** @var IGroupManager */
71
+    private $groupManager;
72
+
73
+    /** @var IRootFolder */
74
+    private $rootFolder;
75
+
76
+    /** @var IMailer */
77
+    private $mailer;
78
+
79
+    /** @var Defaults */
80
+    private $defaults;
81
+
82
+    /** @var IL10N */
83
+    private $l;
84
+
85
+    /** @var IURLGenerator */
86
+    private $urlGenerator;
87
+
88
+    /**
89
+     * DefaultShareProvider constructor.
90
+     *
91
+     * @param IDBConnection $connection
92
+     * @param IUserManager $userManager
93
+     * @param IGroupManager $groupManager
94
+     * @param IRootFolder $rootFolder
95
+     * @param IMailer $mailer ;
96
+     * @param Defaults $defaults
97
+     * @param IL10N $l
98
+     * @param IURLGenerator $urlGenerator
99
+     */
100
+    public function __construct(
101
+            IDBConnection $connection,
102
+            IUserManager $userManager,
103
+            IGroupManager $groupManager,
104
+            IRootFolder $rootFolder,
105
+            IMailer $mailer,
106
+            Defaults $defaults,
107
+            IL10N $l,
108
+            IURLGenerator $urlGenerator) {
109
+        $this->dbConn = $connection;
110
+        $this->userManager = $userManager;
111
+        $this->groupManager = $groupManager;
112
+        $this->rootFolder = $rootFolder;
113
+        $this->mailer = $mailer;
114
+        $this->defaults = $defaults;
115
+        $this->l = $l;
116
+        $this->urlGenerator = $urlGenerator;
117
+    }
118
+
119
+    /**
120
+     * Return the identifier of this provider.
121
+     *
122
+     * @return string Containing only [a-zA-Z0-9]
123
+     */
124
+    public function identifier() {
125
+        return 'ocinternal';
126
+    }
127
+
128
+    /**
129
+     * Share a path
130
+     *
131
+     * @param \OCP\Share\IShare $share
132
+     * @return \OCP\Share\IShare The share object
133
+     * @throws ShareNotFound
134
+     * @throws \Exception
135
+     */
136
+    public function create(\OCP\Share\IShare $share) {
137
+        $qb = $this->dbConn->getQueryBuilder();
138
+
139
+        $qb->insert('share');
140
+        $qb->setValue('share_type', $qb->createNamedParameter($share->getShareType()));
141
+
142
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
143
+            //Set the UID of the user we share with
144
+            $qb->setValue('share_with', $qb->createNamedParameter($share->getSharedWith()));
145
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
146
+            //Set the GID of the group we share with
147
+            $qb->setValue('share_with', $qb->createNamedParameter($share->getSharedWith()));
148
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
149
+            //Set the token of the share
150
+            $qb->setValue('token', $qb->createNamedParameter($share->getToken()));
151
+
152
+            //If a password is set store it
153
+            if ($share->getPassword() !== null) {
154
+                $qb->setValue('password', $qb->createNamedParameter($share->getPassword()));
155
+            }
156
+
157
+            //If an expiration date is set store it
158
+            if ($share->getExpirationDate() !== null) {
159
+                $qb->setValue('expiration', $qb->createNamedParameter($share->getExpirationDate(), 'datetime'));
160
+            }
161
+
162
+            if (method_exists($share, 'getParent')) {
163
+                $qb->setValue('parent', $qb->createNamedParameter($share->getParent()));
164
+            }
165
+        } else {
166
+            throw new \Exception('invalid share type!');
167
+        }
168
+
169
+        // Set what is shares
170
+        $qb->setValue('item_type', $qb->createParameter('itemType'));
171
+        if ($share->getNode() instanceof \OCP\Files\File) {
172
+            $qb->setParameter('itemType', 'file');
173
+        } else {
174
+            $qb->setParameter('itemType', 'folder');
175
+        }
176
+
177
+        // Set the file id
178
+        $qb->setValue('item_source', $qb->createNamedParameter($share->getNode()->getId()));
179
+        $qb->setValue('file_source', $qb->createNamedParameter($share->getNode()->getId()));
180
+
181
+        // set the permissions
182
+        $qb->setValue('permissions', $qb->createNamedParameter($share->getPermissions()));
183
+
184
+        // Set who created this share
185
+        $qb->setValue('uid_initiator', $qb->createNamedParameter($share->getSharedBy()));
186
+
187
+        // Set who is the owner of this file/folder (and this the owner of the share)
188
+        $qb->setValue('uid_owner', $qb->createNamedParameter($share->getShareOwner()));
189
+
190
+        // Set the file target
191
+        $qb->setValue('file_target', $qb->createNamedParameter($share->getTarget()));
192
+
193
+        // Set the time this share was created
194
+        $qb->setValue('stime', $qb->createNamedParameter(time()));
195
+
196
+        // insert the data and fetch the id of the share
197
+        $this->dbConn->beginTransaction();
198
+        $qb->execute();
199
+        $id = $this->dbConn->lastInsertId('*PREFIX*share');
200
+
201
+        // Now fetch the inserted share and create a complete share object
202
+        $qb = $this->dbConn->getQueryBuilder();
203
+        $qb->select('*')
204
+            ->from('share')
205
+            ->where($qb->expr()->eq('id', $qb->createNamedParameter($id)));
206
+
207
+        $cursor = $qb->execute();
208
+        $data = $cursor->fetch();
209
+        $this->dbConn->commit();
210
+        $cursor->closeCursor();
211
+
212
+        if ($data === false) {
213
+            throw new ShareNotFound();
214
+        }
215
+
216
+        $mailSendValue = $share->getMailSend();
217
+        $data['mail_send'] = ($mailSendValue === null) ? true : $mailSendValue;
218
+
219
+        $share = $this->createShare($data);
220
+        return $share;
221
+    }
222
+
223
+    /**
224
+     * Update a share
225
+     *
226
+     * @param \OCP\Share\IShare $share
227
+     * @return \OCP\Share\IShare The share object
228
+     */
229
+    public function update(\OCP\Share\IShare $share) {
230
+
231
+        $originalShare = $this->getShareById($share->getId());
232
+
233
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
234
+            /*
235 235
 			 * We allow updating the recipient on user shares.
236 236
 			 */
237
-			$qb = $this->dbConn->getQueryBuilder();
238
-			$qb->update('share')
239
-				->where($qb->expr()->eq('id', $qb->createNamedParameter($share->getId())))
240
-				->set('share_with', $qb->createNamedParameter($share->getSharedWith()))
241
-				->set('uid_owner', $qb->createNamedParameter($share->getShareOwner()))
242
-				->set('uid_initiator', $qb->createNamedParameter($share->getSharedBy()))
243
-				->set('permissions', $qb->createNamedParameter($share->getPermissions()))
244
-				->set('item_source', $qb->createNamedParameter($share->getNode()->getId()))
245
-				->set('file_source', $qb->createNamedParameter($share->getNode()->getId()))
246
-				->set('expiration', $qb->createNamedParameter($share->getExpirationDate(), IQueryBuilder::PARAM_DATE))
247
-				->set('note', $qb->createNamedParameter($share->getNote()))
248
-				->execute();
249
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
250
-			$qb = $this->dbConn->getQueryBuilder();
251
-			$qb->update('share')
252
-				->where($qb->expr()->eq('id', $qb->createNamedParameter($share->getId())))
253
-				->set('uid_owner', $qb->createNamedParameter($share->getShareOwner()))
254
-				->set('uid_initiator', $qb->createNamedParameter($share->getSharedBy()))
255
-				->set('permissions', $qb->createNamedParameter($share->getPermissions()))
256
-				->set('item_source', $qb->createNamedParameter($share->getNode()->getId()))
257
-				->set('file_source', $qb->createNamedParameter($share->getNode()->getId()))
258
-				->set('expiration', $qb->createNamedParameter($share->getExpirationDate(), IQueryBuilder::PARAM_DATE))
259
-				->set('note', $qb->createNamedParameter($share->getNote()))
260
-				->execute();
261
-
262
-			/*
237
+            $qb = $this->dbConn->getQueryBuilder();
238
+            $qb->update('share')
239
+                ->where($qb->expr()->eq('id', $qb->createNamedParameter($share->getId())))
240
+                ->set('share_with', $qb->createNamedParameter($share->getSharedWith()))
241
+                ->set('uid_owner', $qb->createNamedParameter($share->getShareOwner()))
242
+                ->set('uid_initiator', $qb->createNamedParameter($share->getSharedBy()))
243
+                ->set('permissions', $qb->createNamedParameter($share->getPermissions()))
244
+                ->set('item_source', $qb->createNamedParameter($share->getNode()->getId()))
245
+                ->set('file_source', $qb->createNamedParameter($share->getNode()->getId()))
246
+                ->set('expiration', $qb->createNamedParameter($share->getExpirationDate(), IQueryBuilder::PARAM_DATE))
247
+                ->set('note', $qb->createNamedParameter($share->getNote()))
248
+                ->execute();
249
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
250
+            $qb = $this->dbConn->getQueryBuilder();
251
+            $qb->update('share')
252
+                ->where($qb->expr()->eq('id', $qb->createNamedParameter($share->getId())))
253
+                ->set('uid_owner', $qb->createNamedParameter($share->getShareOwner()))
254
+                ->set('uid_initiator', $qb->createNamedParameter($share->getSharedBy()))
255
+                ->set('permissions', $qb->createNamedParameter($share->getPermissions()))
256
+                ->set('item_source', $qb->createNamedParameter($share->getNode()->getId()))
257
+                ->set('file_source', $qb->createNamedParameter($share->getNode()->getId()))
258
+                ->set('expiration', $qb->createNamedParameter($share->getExpirationDate(), IQueryBuilder::PARAM_DATE))
259
+                ->set('note', $qb->createNamedParameter($share->getNote()))
260
+                ->execute();
261
+
262
+            /*
263 263
 			 * Update all user defined group shares
264 264
 			 */
265
-			$qb = $this->dbConn->getQueryBuilder();
266
-			$qb->update('share')
267
-				->where($qb->expr()->eq('parent', $qb->createNamedParameter($share->getId())))
268
-				->set('uid_owner', $qb->createNamedParameter($share->getShareOwner()))
269
-				->set('uid_initiator', $qb->createNamedParameter($share->getSharedBy()))
270
-				->set('item_source', $qb->createNamedParameter($share->getNode()->getId()))
271
-				->set('file_source', $qb->createNamedParameter($share->getNode()->getId()))
272
-				->set('expiration', $qb->createNamedParameter($share->getExpirationDate(), IQueryBuilder::PARAM_DATE))
273
-				->set('note', $qb->createNamedParameter($share->getNote()))
274
-				->execute();
275
-
276
-			/*
265
+            $qb = $this->dbConn->getQueryBuilder();
266
+            $qb->update('share')
267
+                ->where($qb->expr()->eq('parent', $qb->createNamedParameter($share->getId())))
268
+                ->set('uid_owner', $qb->createNamedParameter($share->getShareOwner()))
269
+                ->set('uid_initiator', $qb->createNamedParameter($share->getSharedBy()))
270
+                ->set('item_source', $qb->createNamedParameter($share->getNode()->getId()))
271
+                ->set('file_source', $qb->createNamedParameter($share->getNode()->getId()))
272
+                ->set('expiration', $qb->createNamedParameter($share->getExpirationDate(), IQueryBuilder::PARAM_DATE))
273
+                ->set('note', $qb->createNamedParameter($share->getNote()))
274
+                ->execute();
275
+
276
+            /*
277 277
 			 * Now update the permissions for all children that have not set it to 0
278 278
 			 */
279
-			$qb = $this->dbConn->getQueryBuilder();
280
-			$qb->update('share')
281
-				->where($qb->expr()->eq('parent', $qb->createNamedParameter($share->getId())))
282
-				->andWhere($qb->expr()->neq('permissions', $qb->createNamedParameter(0)))
283
-				->set('permissions', $qb->createNamedParameter($share->getPermissions()))
284
-				->execute();
285
-
286
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
287
-			$qb = $this->dbConn->getQueryBuilder();
288
-			$qb->update('share')
289
-				->where($qb->expr()->eq('id', $qb->createNamedParameter($share->getId())))
290
-				->set('password', $qb->createNamedParameter($share->getPassword()))
291
-				->set('uid_owner', $qb->createNamedParameter($share->getShareOwner()))
292
-				->set('uid_initiator', $qb->createNamedParameter($share->getSharedBy()))
293
-				->set('permissions', $qb->createNamedParameter($share->getPermissions()))
294
-				->set('item_source', $qb->createNamedParameter($share->getNode()->getId()))
295
-				->set('file_source', $qb->createNamedParameter($share->getNode()->getId()))
296
-				->set('token', $qb->createNamedParameter($share->getToken()))
297
-				->set('expiration', $qb->createNamedParameter($share->getExpirationDate(), IQueryBuilder::PARAM_DATE))
298
-				->set('note', $qb->createNamedParameter($share->getNote()))
299
-				->execute();
300
-		}
301
-
302
-		if ($originalShare->getNote() !== $share->getNote() && $share->getNote() !== '') {
303
-			$this->propagateNote($share);
304
-		}
305
-
306
-
307
-		return $share;
308
-	}
309
-
310
-	/**
311
-	 * Get all children of this share
312
-	 * FIXME: remove once https://github.com/owncloud/core/pull/21660 is in
313
-	 *
314
-	 * @param \OCP\Share\IShare $parent
315
-	 * @return \OCP\Share\IShare[]
316
-	 */
317
-	public function getChildren(\OCP\Share\IShare $parent) {
318
-		$children = [];
319
-
320
-		$qb = $this->dbConn->getQueryBuilder();
321
-		$qb->select('*')
322
-			->from('share')
323
-			->where($qb->expr()->eq('parent', $qb->createNamedParameter($parent->getId())))
324
-			->andWhere(
325
-				$qb->expr()->in(
326
-					'share_type',
327
-					$qb->createNamedParameter([
328
-						\OCP\Share::SHARE_TYPE_USER,
329
-						\OCP\Share::SHARE_TYPE_GROUP,
330
-						\OCP\Share::SHARE_TYPE_LINK,
331
-					], IQueryBuilder::PARAM_INT_ARRAY)
332
-				)
333
-			)
334
-			->andWhere($qb->expr()->orX(
335
-				$qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
336
-				$qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
337
-			))
338
-			->orderBy('id');
339
-
340
-		$cursor = $qb->execute();
341
-		while($data = $cursor->fetch()) {
342
-			$children[] = $this->createShare($data);
343
-		}
344
-		$cursor->closeCursor();
345
-
346
-		return $children;
347
-	}
348
-
349
-	/**
350
-	 * Delete a share
351
-	 *
352
-	 * @param \OCP\Share\IShare $share
353
-	 */
354
-	public function delete(\OCP\Share\IShare $share) {
355
-		$qb = $this->dbConn->getQueryBuilder();
356
-		$qb->delete('share')
357
-			->where($qb->expr()->eq('id', $qb->createNamedParameter($share->getId())));
358
-
359
-		/*
279
+            $qb = $this->dbConn->getQueryBuilder();
280
+            $qb->update('share')
281
+                ->where($qb->expr()->eq('parent', $qb->createNamedParameter($share->getId())))
282
+                ->andWhere($qb->expr()->neq('permissions', $qb->createNamedParameter(0)))
283
+                ->set('permissions', $qb->createNamedParameter($share->getPermissions()))
284
+                ->execute();
285
+
286
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
287
+            $qb = $this->dbConn->getQueryBuilder();
288
+            $qb->update('share')
289
+                ->where($qb->expr()->eq('id', $qb->createNamedParameter($share->getId())))
290
+                ->set('password', $qb->createNamedParameter($share->getPassword()))
291
+                ->set('uid_owner', $qb->createNamedParameter($share->getShareOwner()))
292
+                ->set('uid_initiator', $qb->createNamedParameter($share->getSharedBy()))
293
+                ->set('permissions', $qb->createNamedParameter($share->getPermissions()))
294
+                ->set('item_source', $qb->createNamedParameter($share->getNode()->getId()))
295
+                ->set('file_source', $qb->createNamedParameter($share->getNode()->getId()))
296
+                ->set('token', $qb->createNamedParameter($share->getToken()))
297
+                ->set('expiration', $qb->createNamedParameter($share->getExpirationDate(), IQueryBuilder::PARAM_DATE))
298
+                ->set('note', $qb->createNamedParameter($share->getNote()))
299
+                ->execute();
300
+        }
301
+
302
+        if ($originalShare->getNote() !== $share->getNote() && $share->getNote() !== '') {
303
+            $this->propagateNote($share);
304
+        }
305
+
306
+
307
+        return $share;
308
+    }
309
+
310
+    /**
311
+     * Get all children of this share
312
+     * FIXME: remove once https://github.com/owncloud/core/pull/21660 is in
313
+     *
314
+     * @param \OCP\Share\IShare $parent
315
+     * @return \OCP\Share\IShare[]
316
+     */
317
+    public function getChildren(\OCP\Share\IShare $parent) {
318
+        $children = [];
319
+
320
+        $qb = $this->dbConn->getQueryBuilder();
321
+        $qb->select('*')
322
+            ->from('share')
323
+            ->where($qb->expr()->eq('parent', $qb->createNamedParameter($parent->getId())))
324
+            ->andWhere(
325
+                $qb->expr()->in(
326
+                    'share_type',
327
+                    $qb->createNamedParameter([
328
+                        \OCP\Share::SHARE_TYPE_USER,
329
+                        \OCP\Share::SHARE_TYPE_GROUP,
330
+                        \OCP\Share::SHARE_TYPE_LINK,
331
+                    ], IQueryBuilder::PARAM_INT_ARRAY)
332
+                )
333
+            )
334
+            ->andWhere($qb->expr()->orX(
335
+                $qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
336
+                $qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
337
+            ))
338
+            ->orderBy('id');
339
+
340
+        $cursor = $qb->execute();
341
+        while($data = $cursor->fetch()) {
342
+            $children[] = $this->createShare($data);
343
+        }
344
+        $cursor->closeCursor();
345
+
346
+        return $children;
347
+    }
348
+
349
+    /**
350
+     * Delete a share
351
+     *
352
+     * @param \OCP\Share\IShare $share
353
+     */
354
+    public function delete(\OCP\Share\IShare $share) {
355
+        $qb = $this->dbConn->getQueryBuilder();
356
+        $qb->delete('share')
357
+            ->where($qb->expr()->eq('id', $qb->createNamedParameter($share->getId())));
358
+
359
+        /*
360 360
 		 * If the share is a group share delete all possible
361 361
 		 * user defined groups shares.
362 362
 		 */
363
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
364
-			$qb->orWhere($qb->expr()->eq('parent', $qb->createNamedParameter($share->getId())));
365
-		}
366
-
367
-		$qb->execute();
368
-	}
369
-
370
-	/**
371
-	 * Unshare a share from the recipient. If this is a group share
372
-	 * this means we need a special entry in the share db.
373
-	 *
374
-	 * @param \OCP\Share\IShare $share
375
-	 * @param string $recipient UserId of recipient
376
-	 * @throws BackendError
377
-	 * @throws ProviderException
378
-	 */
379
-	public function deleteFromSelf(\OCP\Share\IShare $share, $recipient) {
380
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
381
-
382
-			$group = $this->groupManager->get($share->getSharedWith());
383
-			$user = $this->userManager->get($recipient);
384
-
385
-			if (is_null($group)) {
386
-				throw new ProviderException('Group "' . $share->getSharedWith() . '" does not exist');
387
-			}
388
-
389
-			if (!$group->inGroup($user)) {
390
-				throw new ProviderException('Recipient not in receiving group');
391
-			}
392
-
393
-			// Try to fetch user specific share
394
-			$qb = $this->dbConn->getQueryBuilder();
395
-			$stmt = $qb->select('*')
396
-				->from('share')
397
-				->where($qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP)))
398
-				->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($recipient)))
399
-				->andWhere($qb->expr()->eq('parent', $qb->createNamedParameter($share->getId())))
400
-				->andWhere($qb->expr()->orX(
401
-					$qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
402
-					$qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
403
-				))
404
-				->execute();
405
-
406
-			$data = $stmt->fetch();
407
-
408
-			/*
363
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
364
+            $qb->orWhere($qb->expr()->eq('parent', $qb->createNamedParameter($share->getId())));
365
+        }
366
+
367
+        $qb->execute();
368
+    }
369
+
370
+    /**
371
+     * Unshare a share from the recipient. If this is a group share
372
+     * this means we need a special entry in the share db.
373
+     *
374
+     * @param \OCP\Share\IShare $share
375
+     * @param string $recipient UserId of recipient
376
+     * @throws BackendError
377
+     * @throws ProviderException
378
+     */
379
+    public function deleteFromSelf(\OCP\Share\IShare $share, $recipient) {
380
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
381
+
382
+            $group = $this->groupManager->get($share->getSharedWith());
383
+            $user = $this->userManager->get($recipient);
384
+
385
+            if (is_null($group)) {
386
+                throw new ProviderException('Group "' . $share->getSharedWith() . '" does not exist');
387
+            }
388
+
389
+            if (!$group->inGroup($user)) {
390
+                throw new ProviderException('Recipient not in receiving group');
391
+            }
392
+
393
+            // Try to fetch user specific share
394
+            $qb = $this->dbConn->getQueryBuilder();
395
+            $stmt = $qb->select('*')
396
+                ->from('share')
397
+                ->where($qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP)))
398
+                ->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($recipient)))
399
+                ->andWhere($qb->expr()->eq('parent', $qb->createNamedParameter($share->getId())))
400
+                ->andWhere($qb->expr()->orX(
401
+                    $qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
402
+                    $qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
403
+                ))
404
+                ->execute();
405
+
406
+            $data = $stmt->fetch();
407
+
408
+            /*
409 409
 			 * Check if there already is a user specific group share.
410 410
 			 * If there is update it (if required).
411 411
 			 */
412
-			if ($data === false) {
413
-				$qb = $this->dbConn->getQueryBuilder();
414
-
415
-				$type = $share->getNodeType();
416
-
417
-				//Insert new share
418
-				$qb->insert('share')
419
-					->values([
420
-						'share_type' => $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP),
421
-						'share_with' => $qb->createNamedParameter($recipient),
422
-						'uid_owner' => $qb->createNamedParameter($share->getShareOwner()),
423
-						'uid_initiator' => $qb->createNamedParameter($share->getSharedBy()),
424
-						'parent' => $qb->createNamedParameter($share->getId()),
425
-						'item_type' => $qb->createNamedParameter($type),
426
-						'item_source' => $qb->createNamedParameter($share->getNodeId()),
427
-						'file_source' => $qb->createNamedParameter($share->getNodeId()),
428
-						'file_target' => $qb->createNamedParameter($share->getTarget()),
429
-						'permissions' => $qb->createNamedParameter(0),
430
-						'stime' => $qb->createNamedParameter($share->getShareTime()->getTimestamp()),
431
-					])->execute();
432
-
433
-			} else if ($data['permissions'] !== 0) {
434
-
435
-				// Update existing usergroup share
436
-				$qb = $this->dbConn->getQueryBuilder();
437
-				$qb->update('share')
438
-					->set('permissions', $qb->createNamedParameter(0))
439
-					->where($qb->expr()->eq('id', $qb->createNamedParameter($data['id'])))
440
-					->execute();
441
-			}
442
-
443
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
444
-
445
-			if ($share->getSharedWith() !== $recipient) {
446
-				throw new ProviderException('Recipient does not match');
447
-			}
448
-
449
-			// We can just delete user and link shares
450
-			$this->delete($share);
451
-		} else {
452
-			throw new ProviderException('Invalid shareType');
453
-		}
454
-	}
455
-
456
-	/**
457
-	 * @inheritdoc
458
-	 *
459
-	 * For now this only works for group shares
460
-	 * If this gets implemented for normal shares we have to extend it
461
-	 */
462
-	public function restore(IShare $share, string $recipient): IShare {
463
-		$qb = $this->dbConn->getQueryBuilder();
464
-		$qb->select('permissions')
465
-			->from('share')
466
-			->where(
467
-				$qb->expr()->eq('id', $qb->createNamedParameter($share->getId()))
468
-			);
469
-		$cursor = $qb->execute();
470
-		$data = $cursor->fetch();
471
-		$cursor->closeCursor();
472
-
473
-		$originalPermission = $data['permissions'];
474
-
475
-		$qb = $this->dbConn->getQueryBuilder();
476
-		$qb->update('share')
477
-			->set('permissions', $qb->createNamedParameter($originalPermission))
478
-			->where(
479
-				$qb->expr()->eq('parent', $qb->createNamedParameter($share->getParent()))
480
-			)->andWhere(
481
-				$qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP))
482
-			)->andWhere(
483
-				$qb->expr()->eq('share_with', $qb->createNamedParameter($recipient))
484
-			);
485
-
486
-		$qb->execute();
487
-
488
-		return $this->getShareById($share->getId(), $recipient);
489
-	}
490
-
491
-	/**
492
-	 * @inheritdoc
493
-	 */
494
-	public function move(\OCP\Share\IShare $share, $recipient) {
495
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
496
-			// Just update the target
497
-			$qb = $this->dbConn->getQueryBuilder();
498
-			$qb->update('share')
499
-				->set('file_target', $qb->createNamedParameter($share->getTarget()))
500
-				->where($qb->expr()->eq('id', $qb->createNamedParameter($share->getId())))
501
-				->execute();
502
-
503
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
504
-
505
-			// Check if there is a usergroup share
506
-			$qb = $this->dbConn->getQueryBuilder();
507
-			$stmt = $qb->select('id')
508
-				->from('share')
509
-				->where($qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP)))
510
-				->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($recipient)))
511
-				->andWhere($qb->expr()->eq('parent', $qb->createNamedParameter($share->getId())))
512
-				->andWhere($qb->expr()->orX(
513
-					$qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
514
-					$qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
515
-				))
516
-				->setMaxResults(1)
517
-				->execute();
518
-
519
-			$data = $stmt->fetch();
520
-			$stmt->closeCursor();
521
-
522
-			if ($data === false) {
523
-				// No usergroup share yet. Create one.
524
-				$qb = $this->dbConn->getQueryBuilder();
525
-				$qb->insert('share')
526
-					->values([
527
-						'share_type' => $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP),
528
-						'share_with' => $qb->createNamedParameter($recipient),
529
-						'uid_owner' => $qb->createNamedParameter($share->getShareOwner()),
530
-						'uid_initiator' => $qb->createNamedParameter($share->getSharedBy()),
531
-						'parent' => $qb->createNamedParameter($share->getId()),
532
-						'item_type' => $qb->createNamedParameter($share->getNodeType()),
533
-						'item_source' => $qb->createNamedParameter($share->getNodeId()),
534
-						'file_source' => $qb->createNamedParameter($share->getNodeId()),
535
-						'file_target' => $qb->createNamedParameter($share->getTarget()),
536
-						'permissions' => $qb->createNamedParameter($share->getPermissions()),
537
-						'stime' => $qb->createNamedParameter($share->getShareTime()->getTimestamp()),
538
-					])->execute();
539
-			} else {
540
-				// Already a usergroup share. Update it.
541
-				$qb = $this->dbConn->getQueryBuilder();
542
-				$qb->update('share')
543
-					->set('file_target', $qb->createNamedParameter($share->getTarget()))
544
-					->where($qb->expr()->eq('id', $qb->createNamedParameter($data['id'])))
545
-					->execute();
546
-			}
547
-		}
548
-
549
-		return $share;
550
-	}
551
-
552
-	public function getSharesInFolder($userId, Folder $node, $reshares) {
553
-		$qb = $this->dbConn->getQueryBuilder();
554
-		$qb->select('*')
555
-			->from('share', 's')
556
-			->andWhere($qb->expr()->orX(
557
-				$qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
558
-				$qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
559
-			));
560
-
561
-		$qb->andWhere($qb->expr()->orX(
562
-			$qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_USER)),
563
-			$qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_GROUP)),
564
-			$qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_LINK))
565
-		));
566
-
567
-		/**
568
-		 * Reshares for this user are shares where they are the owner.
569
-		 */
570
-		if ($reshares === false) {
571
-			$qb->andWhere($qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId)));
572
-		} else {
573
-			$qb->andWhere(
574
-				$qb->expr()->orX(
575
-					$qb->expr()->eq('uid_owner', $qb->createNamedParameter($userId)),
576
-					$qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId))
577
-				)
578
-			);
579
-		}
580
-
581
-		$qb->innerJoin('s', 'filecache' ,'f', $qb->expr()->eq('s.file_source', 'f.fileid'));
582
-		$qb->andWhere($qb->expr()->eq('f.parent', $qb->createNamedParameter($node->getId())));
583
-
584
-		$qb->orderBy('id');
585
-
586
-		$cursor = $qb->execute();
587
-		$shares = [];
588
-		while ($data = $cursor->fetch()) {
589
-			$shares[$data['fileid']][] = $this->createShare($data);
590
-		}
591
-		$cursor->closeCursor();
592
-
593
-		return $shares;
594
-	}
595
-
596
-	/**
597
-	 * @inheritdoc
598
-	 */
599
-	public function getSharesBy($userId, $shareType, $node, $reshares, $limit, $offset) {
600
-		$qb = $this->dbConn->getQueryBuilder();
601
-		$qb->select('*')
602
-			->from('share')
603
-			->andWhere($qb->expr()->orX(
604
-				$qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
605
-				$qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
606
-			));
607
-
608
-		$qb->andWhere($qb->expr()->eq('share_type', $qb->createNamedParameter($shareType)));
609
-
610
-		/**
611
-		 * Reshares for this user are shares where they are the owner.
612
-		 */
613
-		if ($reshares === false) {
614
-			$qb->andWhere($qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId)));
615
-		} else {
616
-			$qb->andWhere(
617
-				$qb->expr()->orX(
618
-					$qb->expr()->eq('uid_owner', $qb->createNamedParameter($userId)),
619
-					$qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId))
620
-				)
621
-			);
622
-		}
623
-
624
-		if ($node !== null) {
625
-			$qb->andWhere($qb->expr()->eq('file_source', $qb->createNamedParameter($node->getId())));
626
-		}
627
-
628
-		if ($limit !== -1) {
629
-			$qb->setMaxResults($limit);
630
-		}
631
-
632
-		$qb->setFirstResult($offset);
633
-		$qb->orderBy('id');
634
-
635
-		$cursor = $qb->execute();
636
-		$shares = [];
637
-		while($data = $cursor->fetch()) {
638
-			$shares[] = $this->createShare($data);
639
-		}
640
-		$cursor->closeCursor();
641
-
642
-		return $shares;
643
-	}
644
-
645
-	/**
646
-	 * @inheritdoc
647
-	 */
648
-	public function getShareById($id, $recipientId = null) {
649
-		$qb = $this->dbConn->getQueryBuilder();
650
-
651
-		$qb->select('*')
652
-			->from('share')
653
-			->where($qb->expr()->eq('id', $qb->createNamedParameter($id)))
654
-			->andWhere(
655
-				$qb->expr()->in(
656
-					'share_type',
657
-					$qb->createNamedParameter([
658
-						\OCP\Share::SHARE_TYPE_USER,
659
-						\OCP\Share::SHARE_TYPE_GROUP,
660
-						\OCP\Share::SHARE_TYPE_LINK,
661
-					], IQueryBuilder::PARAM_INT_ARRAY)
662
-				)
663
-			)
664
-			->andWhere($qb->expr()->orX(
665
-				$qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
666
-				$qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
667
-			));
668
-
669
-		$cursor = $qb->execute();
670
-		$data = $cursor->fetch();
671
-		$cursor->closeCursor();
672
-
673
-		if ($data === false) {
674
-			throw new ShareNotFound();
675
-		}
676
-
677
-		try {
678
-			$share = $this->createShare($data);
679
-		} catch (InvalidShare $e) {
680
-			throw new ShareNotFound();
681
-		}
682
-
683
-		// If the recipient is set for a group share resolve to that user
684
-		if ($recipientId !== null && $share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
685
-			$share = $this->resolveGroupShares([$share], $recipientId)[0];
686
-		}
687
-
688
-		return $share;
689
-	}
690
-
691
-	/**
692
-	 * Get shares for a given path
693
-	 *
694
-	 * @param \OCP\Files\Node $path
695
-	 * @return \OCP\Share\IShare[]
696
-	 */
697
-	public function getSharesByPath(Node $path) {
698
-		$qb = $this->dbConn->getQueryBuilder();
699
-
700
-		$cursor = $qb->select('*')
701
-			->from('share')
702
-			->andWhere($qb->expr()->eq('file_source', $qb->createNamedParameter($path->getId())))
703
-			->andWhere(
704
-				$qb->expr()->orX(
705
-					$qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_USER)),
706
-					$qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_GROUP))
707
-				)
708
-			)
709
-			->andWhere($qb->expr()->orX(
710
-				$qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
711
-				$qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
712
-			))
713
-			->execute();
714
-
715
-		$shares = [];
716
-		while($data = $cursor->fetch()) {
717
-			$shares[] = $this->createShare($data);
718
-		}
719
-		$cursor->closeCursor();
720
-
721
-		return $shares;
722
-	}
723
-
724
-	/**
725
-	 * Returns whether the given database result can be interpreted as
726
-	 * a share with accessible file (not trashed, not deleted)
727
-	 */
728
-	private function isAccessibleResult($data) {
729
-		// exclude shares leading to deleted file entries
730
-		if ($data['fileid'] === null) {
731
-			return false;
732
-		}
733
-
734
-		// exclude shares leading to trashbin on home storages
735
-		$pathSections = explode('/', $data['path'], 2);
736
-		// FIXME: would not detect rare md5'd home storage case properly
737
-		if ($pathSections[0] !== 'files'
738
-		    	&& in_array(explode(':', $data['storage_string_id'], 2)[0], array('home', 'object'))) {
739
-			return false;
740
-		}
741
-		return true;
742
-	}
743
-
744
-	/**
745
-	 * @inheritdoc
746
-	 */
747
-	public function getSharedWith($userId, $shareType, $node, $limit, $offset) {
748
-		/** @var Share[] $shares */
749
-		$shares = [];
750
-
751
-		if ($shareType === \OCP\Share::SHARE_TYPE_USER) {
752
-			//Get shares directly with this user
753
-			$qb = $this->dbConn->getQueryBuilder();
754
-			$qb->select('s.*',
755
-				'f.fileid', 'f.path', 'f.permissions AS f_permissions', 'f.storage', 'f.path_hash',
756
-				'f.parent AS f_parent', 'f.name', 'f.mimetype', 'f.mimepart', 'f.size', 'f.mtime', 'f.storage_mtime',
757
-				'f.encrypted', 'f.unencrypted_size', 'f.etag', 'f.checksum'
758
-			)
759
-				->selectAlias('st.id', 'storage_string_id')
760
-				->from('share', 's')
761
-				->leftJoin('s', 'filecache', 'f', $qb->expr()->eq('s.file_source', 'f.fileid'))
762
-				->leftJoin('f', 'storages', 'st', $qb->expr()->eq('f.storage', 'st.numeric_id'));
763
-
764
-			// Order by id
765
-			$qb->orderBy('s.id');
766
-
767
-			// Set limit and offset
768
-			if ($limit !== -1) {
769
-				$qb->setMaxResults($limit);
770
-			}
771
-			$qb->setFirstResult($offset);
772
-
773
-			$qb->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_USER)))
774
-				->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($userId)))
775
-				->andWhere($qb->expr()->orX(
776
-					$qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
777
-					$qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
778
-				));
779
-
780
-			// Filter by node if provided
781
-			if ($node !== null) {
782
-				$qb->andWhere($qb->expr()->eq('file_source', $qb->createNamedParameter($node->getId())));
783
-			}
784
-
785
-			$cursor = $qb->execute();
786
-
787
-			while($data = $cursor->fetch()) {
788
-				if ($this->isAccessibleResult($data)) {
789
-					$shares[] = $this->createShare($data);
790
-				}
791
-			}
792
-			$cursor->closeCursor();
793
-
794
-		} else if ($shareType === \OCP\Share::SHARE_TYPE_GROUP) {
795
-			$user = $this->userManager->get($userId);
796
-			$allGroups = $this->groupManager->getUserGroups($user);
797
-
798
-			/** @var Share[] $shares2 */
799
-			$shares2 = [];
800
-
801
-			$start = 0;
802
-			while(true) {
803
-				$groups = array_slice($allGroups, $start, 100);
804
-				$start += 100;
805
-
806
-				if ($groups === []) {
807
-					break;
808
-				}
809
-
810
-				$qb = $this->dbConn->getQueryBuilder();
811
-				$qb->select('s.*',
812
-					'f.fileid', 'f.path', 'f.permissions AS f_permissions', 'f.storage', 'f.path_hash',
813
-					'f.parent AS f_parent', 'f.name', 'f.mimetype', 'f.mimepart', 'f.size', 'f.mtime', 'f.storage_mtime',
814
-					'f.encrypted', 'f.unencrypted_size', 'f.etag', 'f.checksum'
815
-				)
816
-					->selectAlias('st.id', 'storage_string_id')
817
-					->from('share', 's')
818
-					->leftJoin('s', 'filecache', 'f', $qb->expr()->eq('s.file_source', 'f.fileid'))
819
-					->leftJoin('f', 'storages', 'st', $qb->expr()->eq('f.storage', 'st.numeric_id'))
820
-					->orderBy('s.id')
821
-					->setFirstResult(0);
822
-
823
-				if ($limit !== -1) {
824
-					$qb->setMaxResults($limit - count($shares));
825
-				}
826
-
827
-				// Filter by node if provided
828
-				if ($node !== null) {
829
-					$qb->andWhere($qb->expr()->eq('file_source', $qb->createNamedParameter($node->getId())));
830
-				}
831
-
832
-
833
-				$groups = array_filter($groups, function($group) { return $group instanceof IGroup; });
834
-				$groups = array_map(function(IGroup $group) { return $group->getGID(); }, $groups);
835
-
836
-				$qb->andWhere($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_GROUP)))
837
-					->andWhere($qb->expr()->in('share_with', $qb->createNamedParameter(
838
-						$groups,
839
-						IQueryBuilder::PARAM_STR_ARRAY
840
-					)))
841
-					->andWhere($qb->expr()->orX(
842
-						$qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
843
-						$qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
844
-					));
845
-
846
-				$cursor = $qb->execute();
847
-				while($data = $cursor->fetch()) {
848
-					if ($offset > 0) {
849
-						$offset--;
850
-						continue;
851
-					}
852
-
853
-					if ($this->isAccessibleResult($data)) {
854
-						$shares2[] = $this->createShare($data);
855
-					}
856
-				}
857
-				$cursor->closeCursor();
858
-			}
859
-
860
-			/*
412
+            if ($data === false) {
413
+                $qb = $this->dbConn->getQueryBuilder();
414
+
415
+                $type = $share->getNodeType();
416
+
417
+                //Insert new share
418
+                $qb->insert('share')
419
+                    ->values([
420
+                        'share_type' => $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP),
421
+                        'share_with' => $qb->createNamedParameter($recipient),
422
+                        'uid_owner' => $qb->createNamedParameter($share->getShareOwner()),
423
+                        'uid_initiator' => $qb->createNamedParameter($share->getSharedBy()),
424
+                        'parent' => $qb->createNamedParameter($share->getId()),
425
+                        'item_type' => $qb->createNamedParameter($type),
426
+                        'item_source' => $qb->createNamedParameter($share->getNodeId()),
427
+                        'file_source' => $qb->createNamedParameter($share->getNodeId()),
428
+                        'file_target' => $qb->createNamedParameter($share->getTarget()),
429
+                        'permissions' => $qb->createNamedParameter(0),
430
+                        'stime' => $qb->createNamedParameter($share->getShareTime()->getTimestamp()),
431
+                    ])->execute();
432
+
433
+            } else if ($data['permissions'] !== 0) {
434
+
435
+                // Update existing usergroup share
436
+                $qb = $this->dbConn->getQueryBuilder();
437
+                $qb->update('share')
438
+                    ->set('permissions', $qb->createNamedParameter(0))
439
+                    ->where($qb->expr()->eq('id', $qb->createNamedParameter($data['id'])))
440
+                    ->execute();
441
+            }
442
+
443
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
444
+
445
+            if ($share->getSharedWith() !== $recipient) {
446
+                throw new ProviderException('Recipient does not match');
447
+            }
448
+
449
+            // We can just delete user and link shares
450
+            $this->delete($share);
451
+        } else {
452
+            throw new ProviderException('Invalid shareType');
453
+        }
454
+    }
455
+
456
+    /**
457
+     * @inheritdoc
458
+     *
459
+     * For now this only works for group shares
460
+     * If this gets implemented for normal shares we have to extend it
461
+     */
462
+    public function restore(IShare $share, string $recipient): IShare {
463
+        $qb = $this->dbConn->getQueryBuilder();
464
+        $qb->select('permissions')
465
+            ->from('share')
466
+            ->where(
467
+                $qb->expr()->eq('id', $qb->createNamedParameter($share->getId()))
468
+            );
469
+        $cursor = $qb->execute();
470
+        $data = $cursor->fetch();
471
+        $cursor->closeCursor();
472
+
473
+        $originalPermission = $data['permissions'];
474
+
475
+        $qb = $this->dbConn->getQueryBuilder();
476
+        $qb->update('share')
477
+            ->set('permissions', $qb->createNamedParameter($originalPermission))
478
+            ->where(
479
+                $qb->expr()->eq('parent', $qb->createNamedParameter($share->getParent()))
480
+            )->andWhere(
481
+                $qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP))
482
+            )->andWhere(
483
+                $qb->expr()->eq('share_with', $qb->createNamedParameter($recipient))
484
+            );
485
+
486
+        $qb->execute();
487
+
488
+        return $this->getShareById($share->getId(), $recipient);
489
+    }
490
+
491
+    /**
492
+     * @inheritdoc
493
+     */
494
+    public function move(\OCP\Share\IShare $share, $recipient) {
495
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
496
+            // Just update the target
497
+            $qb = $this->dbConn->getQueryBuilder();
498
+            $qb->update('share')
499
+                ->set('file_target', $qb->createNamedParameter($share->getTarget()))
500
+                ->where($qb->expr()->eq('id', $qb->createNamedParameter($share->getId())))
501
+                ->execute();
502
+
503
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
504
+
505
+            // Check if there is a usergroup share
506
+            $qb = $this->dbConn->getQueryBuilder();
507
+            $stmt = $qb->select('id')
508
+                ->from('share')
509
+                ->where($qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP)))
510
+                ->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($recipient)))
511
+                ->andWhere($qb->expr()->eq('parent', $qb->createNamedParameter($share->getId())))
512
+                ->andWhere($qb->expr()->orX(
513
+                    $qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
514
+                    $qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
515
+                ))
516
+                ->setMaxResults(1)
517
+                ->execute();
518
+
519
+            $data = $stmt->fetch();
520
+            $stmt->closeCursor();
521
+
522
+            if ($data === false) {
523
+                // No usergroup share yet. Create one.
524
+                $qb = $this->dbConn->getQueryBuilder();
525
+                $qb->insert('share')
526
+                    ->values([
527
+                        'share_type' => $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP),
528
+                        'share_with' => $qb->createNamedParameter($recipient),
529
+                        'uid_owner' => $qb->createNamedParameter($share->getShareOwner()),
530
+                        'uid_initiator' => $qb->createNamedParameter($share->getSharedBy()),
531
+                        'parent' => $qb->createNamedParameter($share->getId()),
532
+                        'item_type' => $qb->createNamedParameter($share->getNodeType()),
533
+                        'item_source' => $qb->createNamedParameter($share->getNodeId()),
534
+                        'file_source' => $qb->createNamedParameter($share->getNodeId()),
535
+                        'file_target' => $qb->createNamedParameter($share->getTarget()),
536
+                        'permissions' => $qb->createNamedParameter($share->getPermissions()),
537
+                        'stime' => $qb->createNamedParameter($share->getShareTime()->getTimestamp()),
538
+                    ])->execute();
539
+            } else {
540
+                // Already a usergroup share. Update it.
541
+                $qb = $this->dbConn->getQueryBuilder();
542
+                $qb->update('share')
543
+                    ->set('file_target', $qb->createNamedParameter($share->getTarget()))
544
+                    ->where($qb->expr()->eq('id', $qb->createNamedParameter($data['id'])))
545
+                    ->execute();
546
+            }
547
+        }
548
+
549
+        return $share;
550
+    }
551
+
552
+    public function getSharesInFolder($userId, Folder $node, $reshares) {
553
+        $qb = $this->dbConn->getQueryBuilder();
554
+        $qb->select('*')
555
+            ->from('share', 's')
556
+            ->andWhere($qb->expr()->orX(
557
+                $qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
558
+                $qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
559
+            ));
560
+
561
+        $qb->andWhere($qb->expr()->orX(
562
+            $qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_USER)),
563
+            $qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_GROUP)),
564
+            $qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_LINK))
565
+        ));
566
+
567
+        /**
568
+         * Reshares for this user are shares where they are the owner.
569
+         */
570
+        if ($reshares === false) {
571
+            $qb->andWhere($qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId)));
572
+        } else {
573
+            $qb->andWhere(
574
+                $qb->expr()->orX(
575
+                    $qb->expr()->eq('uid_owner', $qb->createNamedParameter($userId)),
576
+                    $qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId))
577
+                )
578
+            );
579
+        }
580
+
581
+        $qb->innerJoin('s', 'filecache' ,'f', $qb->expr()->eq('s.file_source', 'f.fileid'));
582
+        $qb->andWhere($qb->expr()->eq('f.parent', $qb->createNamedParameter($node->getId())));
583
+
584
+        $qb->orderBy('id');
585
+
586
+        $cursor = $qb->execute();
587
+        $shares = [];
588
+        while ($data = $cursor->fetch()) {
589
+            $shares[$data['fileid']][] = $this->createShare($data);
590
+        }
591
+        $cursor->closeCursor();
592
+
593
+        return $shares;
594
+    }
595
+
596
+    /**
597
+     * @inheritdoc
598
+     */
599
+    public function getSharesBy($userId, $shareType, $node, $reshares, $limit, $offset) {
600
+        $qb = $this->dbConn->getQueryBuilder();
601
+        $qb->select('*')
602
+            ->from('share')
603
+            ->andWhere($qb->expr()->orX(
604
+                $qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
605
+                $qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
606
+            ));
607
+
608
+        $qb->andWhere($qb->expr()->eq('share_type', $qb->createNamedParameter($shareType)));
609
+
610
+        /**
611
+         * Reshares for this user are shares where they are the owner.
612
+         */
613
+        if ($reshares === false) {
614
+            $qb->andWhere($qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId)));
615
+        } else {
616
+            $qb->andWhere(
617
+                $qb->expr()->orX(
618
+                    $qb->expr()->eq('uid_owner', $qb->createNamedParameter($userId)),
619
+                    $qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId))
620
+                )
621
+            );
622
+        }
623
+
624
+        if ($node !== null) {
625
+            $qb->andWhere($qb->expr()->eq('file_source', $qb->createNamedParameter($node->getId())));
626
+        }
627
+
628
+        if ($limit !== -1) {
629
+            $qb->setMaxResults($limit);
630
+        }
631
+
632
+        $qb->setFirstResult($offset);
633
+        $qb->orderBy('id');
634
+
635
+        $cursor = $qb->execute();
636
+        $shares = [];
637
+        while($data = $cursor->fetch()) {
638
+            $shares[] = $this->createShare($data);
639
+        }
640
+        $cursor->closeCursor();
641
+
642
+        return $shares;
643
+    }
644
+
645
+    /**
646
+     * @inheritdoc
647
+     */
648
+    public function getShareById($id, $recipientId = null) {
649
+        $qb = $this->dbConn->getQueryBuilder();
650
+
651
+        $qb->select('*')
652
+            ->from('share')
653
+            ->where($qb->expr()->eq('id', $qb->createNamedParameter($id)))
654
+            ->andWhere(
655
+                $qb->expr()->in(
656
+                    'share_type',
657
+                    $qb->createNamedParameter([
658
+                        \OCP\Share::SHARE_TYPE_USER,
659
+                        \OCP\Share::SHARE_TYPE_GROUP,
660
+                        \OCP\Share::SHARE_TYPE_LINK,
661
+                    ], IQueryBuilder::PARAM_INT_ARRAY)
662
+                )
663
+            )
664
+            ->andWhere($qb->expr()->orX(
665
+                $qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
666
+                $qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
667
+            ));
668
+
669
+        $cursor = $qb->execute();
670
+        $data = $cursor->fetch();
671
+        $cursor->closeCursor();
672
+
673
+        if ($data === false) {
674
+            throw new ShareNotFound();
675
+        }
676
+
677
+        try {
678
+            $share = $this->createShare($data);
679
+        } catch (InvalidShare $e) {
680
+            throw new ShareNotFound();
681
+        }
682
+
683
+        // If the recipient is set for a group share resolve to that user
684
+        if ($recipientId !== null && $share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
685
+            $share = $this->resolveGroupShares([$share], $recipientId)[0];
686
+        }
687
+
688
+        return $share;
689
+    }
690
+
691
+    /**
692
+     * Get shares for a given path
693
+     *
694
+     * @param \OCP\Files\Node $path
695
+     * @return \OCP\Share\IShare[]
696
+     */
697
+    public function getSharesByPath(Node $path) {
698
+        $qb = $this->dbConn->getQueryBuilder();
699
+
700
+        $cursor = $qb->select('*')
701
+            ->from('share')
702
+            ->andWhere($qb->expr()->eq('file_source', $qb->createNamedParameter($path->getId())))
703
+            ->andWhere(
704
+                $qb->expr()->orX(
705
+                    $qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_USER)),
706
+                    $qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_GROUP))
707
+                )
708
+            )
709
+            ->andWhere($qb->expr()->orX(
710
+                $qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
711
+                $qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
712
+            ))
713
+            ->execute();
714
+
715
+        $shares = [];
716
+        while($data = $cursor->fetch()) {
717
+            $shares[] = $this->createShare($data);
718
+        }
719
+        $cursor->closeCursor();
720
+
721
+        return $shares;
722
+    }
723
+
724
+    /**
725
+     * Returns whether the given database result can be interpreted as
726
+     * a share with accessible file (not trashed, not deleted)
727
+     */
728
+    private function isAccessibleResult($data) {
729
+        // exclude shares leading to deleted file entries
730
+        if ($data['fileid'] === null) {
731
+            return false;
732
+        }
733
+
734
+        // exclude shares leading to trashbin on home storages
735
+        $pathSections = explode('/', $data['path'], 2);
736
+        // FIXME: would not detect rare md5'd home storage case properly
737
+        if ($pathSections[0] !== 'files'
738
+                && in_array(explode(':', $data['storage_string_id'], 2)[0], array('home', 'object'))) {
739
+            return false;
740
+        }
741
+        return true;
742
+    }
743
+
744
+    /**
745
+     * @inheritdoc
746
+     */
747
+    public function getSharedWith($userId, $shareType, $node, $limit, $offset) {
748
+        /** @var Share[] $shares */
749
+        $shares = [];
750
+
751
+        if ($shareType === \OCP\Share::SHARE_TYPE_USER) {
752
+            //Get shares directly with this user
753
+            $qb = $this->dbConn->getQueryBuilder();
754
+            $qb->select('s.*',
755
+                'f.fileid', 'f.path', 'f.permissions AS f_permissions', 'f.storage', 'f.path_hash',
756
+                'f.parent AS f_parent', 'f.name', 'f.mimetype', 'f.mimepart', 'f.size', 'f.mtime', 'f.storage_mtime',
757
+                'f.encrypted', 'f.unencrypted_size', 'f.etag', 'f.checksum'
758
+            )
759
+                ->selectAlias('st.id', 'storage_string_id')
760
+                ->from('share', 's')
761
+                ->leftJoin('s', 'filecache', 'f', $qb->expr()->eq('s.file_source', 'f.fileid'))
762
+                ->leftJoin('f', 'storages', 'st', $qb->expr()->eq('f.storage', 'st.numeric_id'));
763
+
764
+            // Order by id
765
+            $qb->orderBy('s.id');
766
+
767
+            // Set limit and offset
768
+            if ($limit !== -1) {
769
+                $qb->setMaxResults($limit);
770
+            }
771
+            $qb->setFirstResult($offset);
772
+
773
+            $qb->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_USER)))
774
+                ->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($userId)))
775
+                ->andWhere($qb->expr()->orX(
776
+                    $qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
777
+                    $qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
778
+                ));
779
+
780
+            // Filter by node if provided
781
+            if ($node !== null) {
782
+                $qb->andWhere($qb->expr()->eq('file_source', $qb->createNamedParameter($node->getId())));
783
+            }
784
+
785
+            $cursor = $qb->execute();
786
+
787
+            while($data = $cursor->fetch()) {
788
+                if ($this->isAccessibleResult($data)) {
789
+                    $shares[] = $this->createShare($data);
790
+                }
791
+            }
792
+            $cursor->closeCursor();
793
+
794
+        } else if ($shareType === \OCP\Share::SHARE_TYPE_GROUP) {
795
+            $user = $this->userManager->get($userId);
796
+            $allGroups = $this->groupManager->getUserGroups($user);
797
+
798
+            /** @var Share[] $shares2 */
799
+            $shares2 = [];
800
+
801
+            $start = 0;
802
+            while(true) {
803
+                $groups = array_slice($allGroups, $start, 100);
804
+                $start += 100;
805
+
806
+                if ($groups === []) {
807
+                    break;
808
+                }
809
+
810
+                $qb = $this->dbConn->getQueryBuilder();
811
+                $qb->select('s.*',
812
+                    'f.fileid', 'f.path', 'f.permissions AS f_permissions', 'f.storage', 'f.path_hash',
813
+                    'f.parent AS f_parent', 'f.name', 'f.mimetype', 'f.mimepart', 'f.size', 'f.mtime', 'f.storage_mtime',
814
+                    'f.encrypted', 'f.unencrypted_size', 'f.etag', 'f.checksum'
815
+                )
816
+                    ->selectAlias('st.id', 'storage_string_id')
817
+                    ->from('share', 's')
818
+                    ->leftJoin('s', 'filecache', 'f', $qb->expr()->eq('s.file_source', 'f.fileid'))
819
+                    ->leftJoin('f', 'storages', 'st', $qb->expr()->eq('f.storage', 'st.numeric_id'))
820
+                    ->orderBy('s.id')
821
+                    ->setFirstResult(0);
822
+
823
+                if ($limit !== -1) {
824
+                    $qb->setMaxResults($limit - count($shares));
825
+                }
826
+
827
+                // Filter by node if provided
828
+                if ($node !== null) {
829
+                    $qb->andWhere($qb->expr()->eq('file_source', $qb->createNamedParameter($node->getId())));
830
+                }
831
+
832
+
833
+                $groups = array_filter($groups, function($group) { return $group instanceof IGroup; });
834
+                $groups = array_map(function(IGroup $group) { return $group->getGID(); }, $groups);
835
+
836
+                $qb->andWhere($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_GROUP)))
837
+                    ->andWhere($qb->expr()->in('share_with', $qb->createNamedParameter(
838
+                        $groups,
839
+                        IQueryBuilder::PARAM_STR_ARRAY
840
+                    )))
841
+                    ->andWhere($qb->expr()->orX(
842
+                        $qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
843
+                        $qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
844
+                    ));
845
+
846
+                $cursor = $qb->execute();
847
+                while($data = $cursor->fetch()) {
848
+                    if ($offset > 0) {
849
+                        $offset--;
850
+                        continue;
851
+                    }
852
+
853
+                    if ($this->isAccessibleResult($data)) {
854
+                        $shares2[] = $this->createShare($data);
855
+                    }
856
+                }
857
+                $cursor->closeCursor();
858
+            }
859
+
860
+            /*
861 861
  			 * Resolve all group shares to user specific shares
862 862
  			 */
863
-			$shares = $this->resolveGroupShares($shares2, $userId);
864
-		} else {
865
-			throw new BackendError('Invalid backend');
866
-		}
867
-
868
-
869
-		return $shares;
870
-	}
871
-
872
-	/**
873
-	 * Get a share by token
874
-	 *
875
-	 * @param string $token
876
-	 * @return \OCP\Share\IShare
877
-	 * @throws ShareNotFound
878
-	 */
879
-	public function getShareByToken($token) {
880
-		$qb = $this->dbConn->getQueryBuilder();
881
-
882
-		$cursor = $qb->select('*')
883
-			->from('share')
884
-			->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_LINK)))
885
-			->andWhere($qb->expr()->eq('token', $qb->createNamedParameter($token)))
886
-			->andWhere($qb->expr()->orX(
887
-				$qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
888
-				$qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
889
-			))
890
-			->execute();
891
-
892
-		$data = $cursor->fetch();
893
-
894
-		if ($data === false) {
895
-			throw new ShareNotFound();
896
-		}
897
-
898
-		try {
899
-			$share = $this->createShare($data);
900
-		} catch (InvalidShare $e) {
901
-			throw new ShareNotFound();
902
-		}
903
-
904
-		return $share;
905
-	}
906
-
907
-	/**
908
-	 * Create a share object from an database row
909
-	 *
910
-	 * @param mixed[] $data
911
-	 * @return \OCP\Share\IShare
912
-	 * @throws InvalidShare
913
-	 */
914
-	private function createShare($data) {
915
-		$share = new Share($this->rootFolder, $this->userManager);
916
-		$share->setId((int)$data['id'])
917
-			->setShareType((int)$data['share_type'])
918
-			->setPermissions((int)$data['permissions'])
919
-			->setTarget($data['file_target'])
920
-			->setNote($data['note'])
921
-			->setMailSend((bool)$data['mail_send']);
922
-
923
-		$shareTime = new \DateTime();
924
-		$shareTime->setTimestamp((int)$data['stime']);
925
-		$share->setShareTime($shareTime);
926
-
927
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
928
-			$share->setSharedWith($data['share_with']);
929
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
930
-			$share->setSharedWith($data['share_with']);
931
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
932
-			$share->setPassword($data['password']);
933
-			$share->setToken($data['token']);
934
-		}
935
-
936
-		$share->setSharedBy($data['uid_initiator']);
937
-		$share->setShareOwner($data['uid_owner']);
938
-
939
-		$share->setNodeId((int)$data['file_source']);
940
-		$share->setNodeType($data['item_type']);
941
-
942
-		if ($data['expiration'] !== null) {
943
-			$expiration = \DateTime::createFromFormat('Y-m-d H:i:s', $data['expiration']);
944
-			$share->setExpirationDate($expiration);
945
-		}
946
-
947
-		if (isset($data['f_permissions'])) {
948
-			$entryData = $data;
949
-			$entryData['permissions'] = $entryData['f_permissions'];
950
-			$entryData['parent'] = $entryData['f_parent'];
951
-			$share->setNodeCacheEntry(Cache::cacheEntryFromData($entryData,
952
-				\OC::$server->getMimeTypeLoader()));
953
-		}
954
-
955
-		$share->setProviderId($this->identifier());
956
-
957
-		return $share;
958
-	}
959
-
960
-	/**
961
-	 * @param Share[] $shares
962
-	 * @param $userId
963
-	 * @return Share[] The updates shares if no update is found for a share return the original
964
-	 */
965
-	private function resolveGroupShares($shares, $userId) {
966
-		$result = [];
967
-
968
-		$start = 0;
969
-		while(true) {
970
-			/** @var Share[] $shareSlice */
971
-			$shareSlice = array_slice($shares, $start, 100);
972
-			$start += 100;
973
-
974
-			if ($shareSlice === []) {
975
-				break;
976
-			}
977
-
978
-			/** @var int[] $ids */
979
-			$ids = [];
980
-			/** @var Share[] $shareMap */
981
-			$shareMap = [];
982
-
983
-			foreach ($shareSlice as $share) {
984
-				$ids[] = (int)$share->getId();
985
-				$shareMap[$share->getId()] = $share;
986
-			}
987
-
988
-			$qb = $this->dbConn->getQueryBuilder();
989
-
990
-			$query = $qb->select('*')
991
-				->from('share')
992
-				->where($qb->expr()->in('parent', $qb->createNamedParameter($ids, IQueryBuilder::PARAM_INT_ARRAY)))
993
-				->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($userId)))
994
-				->andWhere($qb->expr()->orX(
995
-					$qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
996
-					$qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
997
-				));
998
-
999
-			$stmt = $query->execute();
1000
-
1001
-			while($data = $stmt->fetch()) {
1002
-				$shareMap[$data['parent']]->setPermissions((int)$data['permissions']);
1003
-				$shareMap[$data['parent']]->setTarget($data['file_target']);
1004
-				$shareMap[$data['parent']]->setParent($data['parent']);
1005
-			}
1006
-
1007
-			$stmt->closeCursor();
1008
-
1009
-			foreach ($shareMap as $share) {
1010
-				$result[] = $share;
1011
-			}
1012
-		}
1013
-
1014
-		return $result;
1015
-	}
1016
-
1017
-	/**
1018
-	 * A user is deleted from the system
1019
-	 * So clean up the relevant shares.
1020
-	 *
1021
-	 * @param string $uid
1022
-	 * @param int $shareType
1023
-	 */
1024
-	public function userDeleted($uid, $shareType) {
1025
-		$qb = $this->dbConn->getQueryBuilder();
1026
-
1027
-		$qb->delete('share');
1028
-
1029
-		if ($shareType === \OCP\Share::SHARE_TYPE_USER) {
1030
-			/*
863
+            $shares = $this->resolveGroupShares($shares2, $userId);
864
+        } else {
865
+            throw new BackendError('Invalid backend');
866
+        }
867
+
868
+
869
+        return $shares;
870
+    }
871
+
872
+    /**
873
+     * Get a share by token
874
+     *
875
+     * @param string $token
876
+     * @return \OCP\Share\IShare
877
+     * @throws ShareNotFound
878
+     */
879
+    public function getShareByToken($token) {
880
+        $qb = $this->dbConn->getQueryBuilder();
881
+
882
+        $cursor = $qb->select('*')
883
+            ->from('share')
884
+            ->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_LINK)))
885
+            ->andWhere($qb->expr()->eq('token', $qb->createNamedParameter($token)))
886
+            ->andWhere($qb->expr()->orX(
887
+                $qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
888
+                $qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
889
+            ))
890
+            ->execute();
891
+
892
+        $data = $cursor->fetch();
893
+
894
+        if ($data === false) {
895
+            throw new ShareNotFound();
896
+        }
897
+
898
+        try {
899
+            $share = $this->createShare($data);
900
+        } catch (InvalidShare $e) {
901
+            throw new ShareNotFound();
902
+        }
903
+
904
+        return $share;
905
+    }
906
+
907
+    /**
908
+     * Create a share object from an database row
909
+     *
910
+     * @param mixed[] $data
911
+     * @return \OCP\Share\IShare
912
+     * @throws InvalidShare
913
+     */
914
+    private function createShare($data) {
915
+        $share = new Share($this->rootFolder, $this->userManager);
916
+        $share->setId((int)$data['id'])
917
+            ->setShareType((int)$data['share_type'])
918
+            ->setPermissions((int)$data['permissions'])
919
+            ->setTarget($data['file_target'])
920
+            ->setNote($data['note'])
921
+            ->setMailSend((bool)$data['mail_send']);
922
+
923
+        $shareTime = new \DateTime();
924
+        $shareTime->setTimestamp((int)$data['stime']);
925
+        $share->setShareTime($shareTime);
926
+
927
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
928
+            $share->setSharedWith($data['share_with']);
929
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
930
+            $share->setSharedWith($data['share_with']);
931
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
932
+            $share->setPassword($data['password']);
933
+            $share->setToken($data['token']);
934
+        }
935
+
936
+        $share->setSharedBy($data['uid_initiator']);
937
+        $share->setShareOwner($data['uid_owner']);
938
+
939
+        $share->setNodeId((int)$data['file_source']);
940
+        $share->setNodeType($data['item_type']);
941
+
942
+        if ($data['expiration'] !== null) {
943
+            $expiration = \DateTime::createFromFormat('Y-m-d H:i:s', $data['expiration']);
944
+            $share->setExpirationDate($expiration);
945
+        }
946
+
947
+        if (isset($data['f_permissions'])) {
948
+            $entryData = $data;
949
+            $entryData['permissions'] = $entryData['f_permissions'];
950
+            $entryData['parent'] = $entryData['f_parent'];
951
+            $share->setNodeCacheEntry(Cache::cacheEntryFromData($entryData,
952
+                \OC::$server->getMimeTypeLoader()));
953
+        }
954
+
955
+        $share->setProviderId($this->identifier());
956
+
957
+        return $share;
958
+    }
959
+
960
+    /**
961
+     * @param Share[] $shares
962
+     * @param $userId
963
+     * @return Share[] The updates shares if no update is found for a share return the original
964
+     */
965
+    private function resolveGroupShares($shares, $userId) {
966
+        $result = [];
967
+
968
+        $start = 0;
969
+        while(true) {
970
+            /** @var Share[] $shareSlice */
971
+            $shareSlice = array_slice($shares, $start, 100);
972
+            $start += 100;
973
+
974
+            if ($shareSlice === []) {
975
+                break;
976
+            }
977
+
978
+            /** @var int[] $ids */
979
+            $ids = [];
980
+            /** @var Share[] $shareMap */
981
+            $shareMap = [];
982
+
983
+            foreach ($shareSlice as $share) {
984
+                $ids[] = (int)$share->getId();
985
+                $shareMap[$share->getId()] = $share;
986
+            }
987
+
988
+            $qb = $this->dbConn->getQueryBuilder();
989
+
990
+            $query = $qb->select('*')
991
+                ->from('share')
992
+                ->where($qb->expr()->in('parent', $qb->createNamedParameter($ids, IQueryBuilder::PARAM_INT_ARRAY)))
993
+                ->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($userId)))
994
+                ->andWhere($qb->expr()->orX(
995
+                    $qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
996
+                    $qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
997
+                ));
998
+
999
+            $stmt = $query->execute();
1000
+
1001
+            while($data = $stmt->fetch()) {
1002
+                $shareMap[$data['parent']]->setPermissions((int)$data['permissions']);
1003
+                $shareMap[$data['parent']]->setTarget($data['file_target']);
1004
+                $shareMap[$data['parent']]->setParent($data['parent']);
1005
+            }
1006
+
1007
+            $stmt->closeCursor();
1008
+
1009
+            foreach ($shareMap as $share) {
1010
+                $result[] = $share;
1011
+            }
1012
+        }
1013
+
1014
+        return $result;
1015
+    }
1016
+
1017
+    /**
1018
+     * A user is deleted from the system
1019
+     * So clean up the relevant shares.
1020
+     *
1021
+     * @param string $uid
1022
+     * @param int $shareType
1023
+     */
1024
+    public function userDeleted($uid, $shareType) {
1025
+        $qb = $this->dbConn->getQueryBuilder();
1026
+
1027
+        $qb->delete('share');
1028
+
1029
+        if ($shareType === \OCP\Share::SHARE_TYPE_USER) {
1030
+            /*
1031 1031
 			 * Delete all user shares that are owned by this user
1032 1032
 			 * or that are received by this user
1033 1033
 			 */
1034 1034
 
1035
-			$qb->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_USER)));
1035
+            $qb->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_USER)));
1036 1036
 
1037
-			$qb->andWhere(
1038
-				$qb->expr()->orX(
1039
-					$qb->expr()->eq('uid_owner', $qb->createNamedParameter($uid)),
1040
-					$qb->expr()->eq('share_with', $qb->createNamedParameter($uid))
1041
-				)
1042
-			);
1043
-		} else if ($shareType === \OCP\Share::SHARE_TYPE_GROUP) {
1044
-			/*
1037
+            $qb->andWhere(
1038
+                $qb->expr()->orX(
1039
+                    $qb->expr()->eq('uid_owner', $qb->createNamedParameter($uid)),
1040
+                    $qb->expr()->eq('share_with', $qb->createNamedParameter($uid))
1041
+                )
1042
+            );
1043
+        } else if ($shareType === \OCP\Share::SHARE_TYPE_GROUP) {
1044
+            /*
1045 1045
 			 * Delete all group shares that are owned by this user
1046 1046
 			 * Or special user group shares that are received by this user
1047 1047
 			 */
1048
-			$qb->where(
1049
-				$qb->expr()->andX(
1050
-					$qb->expr()->orX(
1051
-						$qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_GROUP)),
1052
-						$qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP))
1053
-					),
1054
-					$qb->expr()->eq('uid_owner', $qb->createNamedParameter($uid))
1055
-				)
1056
-			);
1057
-
1058
-			$qb->orWhere(
1059
-				$qb->expr()->andX(
1060
-					$qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP)),
1061
-					$qb->expr()->eq('share_with', $qb->createNamedParameter($uid))
1062
-				)
1063
-			);
1064
-		} else if ($shareType === \OCP\Share::SHARE_TYPE_LINK) {
1065
-			/*
1048
+            $qb->where(
1049
+                $qb->expr()->andX(
1050
+                    $qb->expr()->orX(
1051
+                        $qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_GROUP)),
1052
+                        $qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP))
1053
+                    ),
1054
+                    $qb->expr()->eq('uid_owner', $qb->createNamedParameter($uid))
1055
+                )
1056
+            );
1057
+
1058
+            $qb->orWhere(
1059
+                $qb->expr()->andX(
1060
+                    $qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP)),
1061
+                    $qb->expr()->eq('share_with', $qb->createNamedParameter($uid))
1062
+                )
1063
+            );
1064
+        } else if ($shareType === \OCP\Share::SHARE_TYPE_LINK) {
1065
+            /*
1066 1066
 			 * Delete all link shares owned by this user.
1067 1067
 			 * And all link shares initiated by this user (until #22327 is in)
1068 1068
 			 */
1069
-			$qb->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_LINK)));
1070
-
1071
-			$qb->andWhere(
1072
-				$qb->expr()->orX(
1073
-					$qb->expr()->eq('uid_owner', $qb->createNamedParameter($uid)),
1074
-					$qb->expr()->eq('uid_initiator', $qb->createNamedParameter($uid))
1075
-				)
1076
-			);
1077
-		}
1078
-
1079
-		$qb->execute();
1080
-	}
1081
-
1082
-	/**
1083
-	 * Delete all shares received by this group. As well as any custom group
1084
-	 * shares for group members.
1085
-	 *
1086
-	 * @param string $gid
1087
-	 */
1088
-	public function groupDeleted($gid) {
1089
-		/*
1069
+            $qb->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_LINK)));
1070
+
1071
+            $qb->andWhere(
1072
+                $qb->expr()->orX(
1073
+                    $qb->expr()->eq('uid_owner', $qb->createNamedParameter($uid)),
1074
+                    $qb->expr()->eq('uid_initiator', $qb->createNamedParameter($uid))
1075
+                )
1076
+            );
1077
+        }
1078
+
1079
+        $qb->execute();
1080
+    }
1081
+
1082
+    /**
1083
+     * Delete all shares received by this group. As well as any custom group
1084
+     * shares for group members.
1085
+     *
1086
+     * @param string $gid
1087
+     */
1088
+    public function groupDeleted($gid) {
1089
+        /*
1090 1090
 		 * First delete all custom group shares for group members
1091 1091
 		 */
1092
-		$qb = $this->dbConn->getQueryBuilder();
1093
-		$qb->select('id')
1094
-			->from('share')
1095
-			->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_GROUP)))
1096
-			->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($gid)));
1097
-
1098
-		$cursor = $qb->execute();
1099
-		$ids = [];
1100
-		while($row = $cursor->fetch()) {
1101
-			$ids[] = (int)$row['id'];
1102
-		}
1103
-		$cursor->closeCursor();
1104
-
1105
-		if (!empty($ids)) {
1106
-			$chunks = array_chunk($ids, 100);
1107
-			foreach ($chunks as $chunk) {
1108
-				$qb->delete('share')
1109
-					->where($qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP)))
1110
-					->andWhere($qb->expr()->in('parent', $qb->createNamedParameter($chunk, IQueryBuilder::PARAM_INT_ARRAY)));
1111
-				$qb->execute();
1112
-			}
1113
-		}
1114
-
1115
-		/*
1092
+        $qb = $this->dbConn->getQueryBuilder();
1093
+        $qb->select('id')
1094
+            ->from('share')
1095
+            ->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_GROUP)))
1096
+            ->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($gid)));
1097
+
1098
+        $cursor = $qb->execute();
1099
+        $ids = [];
1100
+        while($row = $cursor->fetch()) {
1101
+            $ids[] = (int)$row['id'];
1102
+        }
1103
+        $cursor->closeCursor();
1104
+
1105
+        if (!empty($ids)) {
1106
+            $chunks = array_chunk($ids, 100);
1107
+            foreach ($chunks as $chunk) {
1108
+                $qb->delete('share')
1109
+                    ->where($qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP)))
1110
+                    ->andWhere($qb->expr()->in('parent', $qb->createNamedParameter($chunk, IQueryBuilder::PARAM_INT_ARRAY)));
1111
+                $qb->execute();
1112
+            }
1113
+        }
1114
+
1115
+        /*
1116 1116
 		 * Now delete all the group shares
1117 1117
 		 */
1118
-		$qb = $this->dbConn->getQueryBuilder();
1119
-		$qb->delete('share')
1120
-			->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_GROUP)))
1121
-			->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($gid)));
1122
-		$qb->execute();
1123
-	}
1124
-
1125
-	/**
1126
-	 * Delete custom group shares to this group for this user
1127
-	 *
1128
-	 * @param string $uid
1129
-	 * @param string $gid
1130
-	 */
1131
-	public function userDeletedFromGroup($uid, $gid) {
1132
-		/*
1118
+        $qb = $this->dbConn->getQueryBuilder();
1119
+        $qb->delete('share')
1120
+            ->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_GROUP)))
1121
+            ->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($gid)));
1122
+        $qb->execute();
1123
+    }
1124
+
1125
+    /**
1126
+     * Delete custom group shares to this group for this user
1127
+     *
1128
+     * @param string $uid
1129
+     * @param string $gid
1130
+     */
1131
+    public function userDeletedFromGroup($uid, $gid) {
1132
+        /*
1133 1133
 		 * Get all group shares
1134 1134
 		 */
1135
-		$qb = $this->dbConn->getQueryBuilder();
1136
-		$qb->select('id')
1137
-			->from('share')
1138
-			->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_GROUP)))
1139
-			->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($gid)));
1140
-
1141
-		$cursor = $qb->execute();
1142
-		$ids = [];
1143
-		while($row = $cursor->fetch()) {
1144
-			$ids[] = (int)$row['id'];
1145
-		}
1146
-		$cursor->closeCursor();
1147
-
1148
-		if (!empty($ids)) {
1149
-			$chunks = array_chunk($ids, 100);
1150
-			foreach ($chunks as $chunk) {
1151
-				/*
1135
+        $qb = $this->dbConn->getQueryBuilder();
1136
+        $qb->select('id')
1137
+            ->from('share')
1138
+            ->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_GROUP)))
1139
+            ->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($gid)));
1140
+
1141
+        $cursor = $qb->execute();
1142
+        $ids = [];
1143
+        while($row = $cursor->fetch()) {
1144
+            $ids[] = (int)$row['id'];
1145
+        }
1146
+        $cursor->closeCursor();
1147
+
1148
+        if (!empty($ids)) {
1149
+            $chunks = array_chunk($ids, 100);
1150
+            foreach ($chunks as $chunk) {
1151
+                /*
1152 1152
 				 * Delete all special shares wit this users for the found group shares
1153 1153
 				 */
1154
-				$qb->delete('share')
1155
-					->where($qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP)))
1156
-					->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($uid)))
1157
-					->andWhere($qb->expr()->in('parent', $qb->createNamedParameter($chunk, IQueryBuilder::PARAM_INT_ARRAY)));
1158
-				$qb->execute();
1159
-			}
1160
-		}
1161
-	}
1162
-
1163
-	/**
1164
-	 * @inheritdoc
1165
-	 */
1166
-	public function getAccessList($nodes, $currentAccess) {
1167
-		$ids = [];
1168
-		foreach ($nodes as $node) {
1169
-			$ids[] = $node->getId();
1170
-		}
1171
-
1172
-		$qb = $this->dbConn->getQueryBuilder();
1173
-
1174
-		$or = $qb->expr()->orX(
1175
-			$qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_USER)),
1176
-			$qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_GROUP)),
1177
-			$qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_LINK))
1178
-		);
1179
-
1180
-		if ($currentAccess) {
1181
-			$or->add($qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP)));
1182
-		}
1183
-
1184
-		$qb->select('id', 'parent', 'share_type', 'share_with', 'file_source', 'file_target', 'permissions')
1185
-			->from('share')
1186
-			->where(
1187
-				$or
1188
-			)
1189
-			->andWhere($qb->expr()->in('file_source', $qb->createNamedParameter($ids, IQueryBuilder::PARAM_INT_ARRAY)))
1190
-			->andWhere($qb->expr()->orX(
1191
-				$qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
1192
-				$qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
1193
-			));
1194
-		$cursor = $qb->execute();
1195
-
1196
-		$users = [];
1197
-		$link = false;
1198
-		while($row = $cursor->fetch()) {
1199
-			$type = (int)$row['share_type'];
1200
-			if ($type === \OCP\Share::SHARE_TYPE_USER) {
1201
-				$uid = $row['share_with'];
1202
-				$users[$uid] = isset($users[$uid]) ? $users[$uid] : [];
1203
-				$users[$uid][$row['id']] = $row;
1204
-			} else if ($type === \OCP\Share::SHARE_TYPE_GROUP) {
1205
-				$gid = $row['share_with'];
1206
-				$group = $this->groupManager->get($gid);
1207
-
1208
-				if ($group === null) {
1209
-					continue;
1210
-				}
1211
-
1212
-				$userList = $group->getUsers();
1213
-				foreach ($userList as $user) {
1214
-					$uid = $user->getUID();
1215
-					$users[$uid] = isset($users[$uid]) ? $users[$uid] : [];
1216
-					$users[$uid][$row['id']] = $row;
1217
-				}
1218
-			} else if ($type === \OCP\Share::SHARE_TYPE_LINK) {
1219
-				$link = true;
1220
-			} else if ($type === self::SHARE_TYPE_USERGROUP && $currentAccess === true) {
1221
-				$uid = $row['share_with'];
1222
-				$users[$uid] = isset($users[$uid]) ? $users[$uid] : [];
1223
-				$users[$uid][$row['id']] = $row;
1224
-			}
1225
-		}
1226
-		$cursor->closeCursor();
1227
-
1228
-		if ($currentAccess === true) {
1229
-			$users = array_map([$this, 'filterSharesOfUser'], $users);
1230
-			$users = array_filter($users);
1231
-		} else {
1232
-			$users = array_keys($users);
1233
-		}
1234
-
1235
-		return ['users' => $users, 'public' => $link];
1236
-	}
1237
-
1238
-	/**
1239
-	 * For each user the path with the fewest slashes is returned
1240
-	 * @param array $shares
1241
-	 * @return array
1242
-	 */
1243
-	protected function filterSharesOfUser(array $shares) {
1244
-		// Group shares when the user has a share exception
1245
-		foreach ($shares as $id => $share) {
1246
-			$type = (int) $share['share_type'];
1247
-			$permissions = (int) $share['permissions'];
1248
-
1249
-			if ($type === self::SHARE_TYPE_USERGROUP) {
1250
-				unset($shares[$share['parent']]);
1251
-
1252
-				if ($permissions === 0) {
1253
-					unset($shares[$id]);
1254
-				}
1255
-			}
1256
-		}
1257
-
1258
-		$best = [];
1259
-		$bestDepth = 0;
1260
-		foreach ($shares as $id => $share) {
1261
-			$depth = substr_count($share['file_target'], '/');
1262
-			if (empty($best) || $depth < $bestDepth) {
1263
-				$bestDepth = $depth;
1264
-				$best = [
1265
-					'node_id' => $share['file_source'],
1266
-					'node_path' => $share['file_target'],
1267
-				];
1268
-			}
1269
-		}
1270
-
1271
-		return $best;
1272
-	}
1273
-
1274
-	/**
1275
-	 * propagate notes to the recipients
1276
-	 *
1277
-	 * @param IShare $share
1278
-	 * @throws \OCP\Files\NotFoundException
1279
-	 */
1280
-	private function propagateNote(IShare $share) {
1281
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
1282
-			$user = $this->userManager->get($share->getSharedWith());
1283
-			$this->sendNote([$user], $share);
1284
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
1285
-			$group = $this->groupManager->get($share->getSharedWith());
1286
-			$groupMembers = $group->getUsers();
1287
-			$this->sendNote($groupMembers, $share);
1288
-		}
1289
-	}
1290
-
1291
-	/**
1292
-	 * send note by mail
1293
-	 *
1294
-	 * @param array $recipients
1295
-	 * @param IShare $share
1296
-	 * @throws \OCP\Files\NotFoundException
1297
-	 */
1298
-	private function sendNote(array $recipients, IShare $share) {
1299
-
1300
-		$toList = [];
1301
-
1302
-		foreach ($recipients as $recipient) {
1303
-			/** @var IUser $recipient */
1304
-			$email = $recipient->getEMailAddress();
1305
-			if ($email) {
1306
-				$toList[$email] = $recipient->getDisplayName();
1307
-			}
1308
-		}
1309
-
1310
-		if (!empty($toList)) {
1311
-
1312
-			$filename = $share->getNode()->getName();
1313
-			$initiator = $share->getSharedBy();
1314
-			$note = $share->getNote();
1315
-
1316
-			$initiatorUser = $this->userManager->get($initiator);
1317
-			$initiatorDisplayName = ($initiatorUser instanceof IUser) ? $initiatorUser->getDisplayName() : $initiator;
1318
-			$initiatorEmailAddress = ($initiatorUser instanceof IUser) ? $initiatorUser->getEMailAddress() : null;
1319
-			$plainHeading = $this->l->t('%1$s shared »%2$s« with you and wants to add:', [$initiatorDisplayName, $filename]);
1320
-			$htmlHeading = $this->l->t('%1$s shared »%2$s« with you and wants to add', [$initiatorDisplayName, $filename]);
1321
-			$message = $this->mailer->createMessage();
1322
-
1323
-			$emailTemplate = $this->mailer->createEMailTemplate('defaultShareProvider.sendNote');
1324
-
1325
-			$emailTemplate->setSubject($this->l->t('»%s« added a note to a file shared with you', [$initiatorDisplayName]));
1326
-			$emailTemplate->addHeader();
1327
-			$emailTemplate->addHeading($htmlHeading, $plainHeading);
1328
-			$emailTemplate->addBodyText(htmlspecialchars($note), $note);
1329
-
1330
-			$link = $this->urlGenerator->linkToRouteAbsolute('files.viewcontroller.showFile', ['fileid' => $share->getNode()->getId()]);
1331
-			$emailTemplate->addBodyButton(
1332
-				$this->l->t('Open »%s«', [$filename]),
1333
-				$link
1334
-			);
1335
-
1336
-
1337
-			// The "From" contains the sharers name
1338
-			$instanceName = $this->defaults->getName();
1339
-			$senderName = $this->l->t(
1340
-				'%1$s via %2$s',
1341
-				[
1342
-					$initiatorDisplayName,
1343
-					$instanceName
1344
-				]
1345
-			);
1346
-			$message->setFrom([\OCP\Util::getDefaultEmailAddress($instanceName) => $senderName]);
1347
-			if ($initiatorEmailAddress !== null) {
1348
-				$message->setReplyTo([$initiatorEmailAddress => $initiatorDisplayName]);
1349
-				$emailTemplate->addFooter($instanceName . ' - ' . $this->defaults->getSlogan());
1350
-			} else {
1351
-				$emailTemplate->addFooter();
1352
-			}
1353
-
1354
-			if (count($toList) === 1) {
1355
-				$message->setTo($toList);
1356
-			} else {
1357
-				$message->setTo([]);
1358
-				$message->setBcc($toList);
1359
-			}
1360
-			$message->useTemplate($emailTemplate);
1361
-			$this->mailer->send($message);
1362
-		}
1363
-
1364
-	}
1154
+                $qb->delete('share')
1155
+                    ->where($qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP)))
1156
+                    ->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($uid)))
1157
+                    ->andWhere($qb->expr()->in('parent', $qb->createNamedParameter($chunk, IQueryBuilder::PARAM_INT_ARRAY)));
1158
+                $qb->execute();
1159
+            }
1160
+        }
1161
+    }
1162
+
1163
+    /**
1164
+     * @inheritdoc
1165
+     */
1166
+    public function getAccessList($nodes, $currentAccess) {
1167
+        $ids = [];
1168
+        foreach ($nodes as $node) {
1169
+            $ids[] = $node->getId();
1170
+        }
1171
+
1172
+        $qb = $this->dbConn->getQueryBuilder();
1173
+
1174
+        $or = $qb->expr()->orX(
1175
+            $qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_USER)),
1176
+            $qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_GROUP)),
1177
+            $qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_LINK))
1178
+        );
1179
+
1180
+        if ($currentAccess) {
1181
+            $or->add($qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP)));
1182
+        }
1183
+
1184
+        $qb->select('id', 'parent', 'share_type', 'share_with', 'file_source', 'file_target', 'permissions')
1185
+            ->from('share')
1186
+            ->where(
1187
+                $or
1188
+            )
1189
+            ->andWhere($qb->expr()->in('file_source', $qb->createNamedParameter($ids, IQueryBuilder::PARAM_INT_ARRAY)))
1190
+            ->andWhere($qb->expr()->orX(
1191
+                $qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
1192
+                $qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
1193
+            ));
1194
+        $cursor = $qb->execute();
1195
+
1196
+        $users = [];
1197
+        $link = false;
1198
+        while($row = $cursor->fetch()) {
1199
+            $type = (int)$row['share_type'];
1200
+            if ($type === \OCP\Share::SHARE_TYPE_USER) {
1201
+                $uid = $row['share_with'];
1202
+                $users[$uid] = isset($users[$uid]) ? $users[$uid] : [];
1203
+                $users[$uid][$row['id']] = $row;
1204
+            } else if ($type === \OCP\Share::SHARE_TYPE_GROUP) {
1205
+                $gid = $row['share_with'];
1206
+                $group = $this->groupManager->get($gid);
1207
+
1208
+                if ($group === null) {
1209
+                    continue;
1210
+                }
1211
+
1212
+                $userList = $group->getUsers();
1213
+                foreach ($userList as $user) {
1214
+                    $uid = $user->getUID();
1215
+                    $users[$uid] = isset($users[$uid]) ? $users[$uid] : [];
1216
+                    $users[$uid][$row['id']] = $row;
1217
+                }
1218
+            } else if ($type === \OCP\Share::SHARE_TYPE_LINK) {
1219
+                $link = true;
1220
+            } else if ($type === self::SHARE_TYPE_USERGROUP && $currentAccess === true) {
1221
+                $uid = $row['share_with'];
1222
+                $users[$uid] = isset($users[$uid]) ? $users[$uid] : [];
1223
+                $users[$uid][$row['id']] = $row;
1224
+            }
1225
+        }
1226
+        $cursor->closeCursor();
1227
+
1228
+        if ($currentAccess === true) {
1229
+            $users = array_map([$this, 'filterSharesOfUser'], $users);
1230
+            $users = array_filter($users);
1231
+        } else {
1232
+            $users = array_keys($users);
1233
+        }
1234
+
1235
+        return ['users' => $users, 'public' => $link];
1236
+    }
1237
+
1238
+    /**
1239
+     * For each user the path with the fewest slashes is returned
1240
+     * @param array $shares
1241
+     * @return array
1242
+     */
1243
+    protected function filterSharesOfUser(array $shares) {
1244
+        // Group shares when the user has a share exception
1245
+        foreach ($shares as $id => $share) {
1246
+            $type = (int) $share['share_type'];
1247
+            $permissions = (int) $share['permissions'];
1248
+
1249
+            if ($type === self::SHARE_TYPE_USERGROUP) {
1250
+                unset($shares[$share['parent']]);
1251
+
1252
+                if ($permissions === 0) {
1253
+                    unset($shares[$id]);
1254
+                }
1255
+            }
1256
+        }
1257
+
1258
+        $best = [];
1259
+        $bestDepth = 0;
1260
+        foreach ($shares as $id => $share) {
1261
+            $depth = substr_count($share['file_target'], '/');
1262
+            if (empty($best) || $depth < $bestDepth) {
1263
+                $bestDepth = $depth;
1264
+                $best = [
1265
+                    'node_id' => $share['file_source'],
1266
+                    'node_path' => $share['file_target'],
1267
+                ];
1268
+            }
1269
+        }
1270
+
1271
+        return $best;
1272
+    }
1273
+
1274
+    /**
1275
+     * propagate notes to the recipients
1276
+     *
1277
+     * @param IShare $share
1278
+     * @throws \OCP\Files\NotFoundException
1279
+     */
1280
+    private function propagateNote(IShare $share) {
1281
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
1282
+            $user = $this->userManager->get($share->getSharedWith());
1283
+            $this->sendNote([$user], $share);
1284
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
1285
+            $group = $this->groupManager->get($share->getSharedWith());
1286
+            $groupMembers = $group->getUsers();
1287
+            $this->sendNote($groupMembers, $share);
1288
+        }
1289
+    }
1290
+
1291
+    /**
1292
+     * send note by mail
1293
+     *
1294
+     * @param array $recipients
1295
+     * @param IShare $share
1296
+     * @throws \OCP\Files\NotFoundException
1297
+     */
1298
+    private function sendNote(array $recipients, IShare $share) {
1299
+
1300
+        $toList = [];
1301
+
1302
+        foreach ($recipients as $recipient) {
1303
+            /** @var IUser $recipient */
1304
+            $email = $recipient->getEMailAddress();
1305
+            if ($email) {
1306
+                $toList[$email] = $recipient->getDisplayName();
1307
+            }
1308
+        }
1309
+
1310
+        if (!empty($toList)) {
1311
+
1312
+            $filename = $share->getNode()->getName();
1313
+            $initiator = $share->getSharedBy();
1314
+            $note = $share->getNote();
1315
+
1316
+            $initiatorUser = $this->userManager->get($initiator);
1317
+            $initiatorDisplayName = ($initiatorUser instanceof IUser) ? $initiatorUser->getDisplayName() : $initiator;
1318
+            $initiatorEmailAddress = ($initiatorUser instanceof IUser) ? $initiatorUser->getEMailAddress() : null;
1319
+            $plainHeading = $this->l->t('%1$s shared »%2$s« with you and wants to add:', [$initiatorDisplayName, $filename]);
1320
+            $htmlHeading = $this->l->t('%1$s shared »%2$s« with you and wants to add', [$initiatorDisplayName, $filename]);
1321
+            $message = $this->mailer->createMessage();
1322
+
1323
+            $emailTemplate = $this->mailer->createEMailTemplate('defaultShareProvider.sendNote');
1324
+
1325
+            $emailTemplate->setSubject($this->l->t('»%s« added a note to a file shared with you', [$initiatorDisplayName]));
1326
+            $emailTemplate->addHeader();
1327
+            $emailTemplate->addHeading($htmlHeading, $plainHeading);
1328
+            $emailTemplate->addBodyText(htmlspecialchars($note), $note);
1329
+
1330
+            $link = $this->urlGenerator->linkToRouteAbsolute('files.viewcontroller.showFile', ['fileid' => $share->getNode()->getId()]);
1331
+            $emailTemplate->addBodyButton(
1332
+                $this->l->t('Open »%s«', [$filename]),
1333
+                $link
1334
+            );
1335
+
1336
+
1337
+            // The "From" contains the sharers name
1338
+            $instanceName = $this->defaults->getName();
1339
+            $senderName = $this->l->t(
1340
+                '%1$s via %2$s',
1341
+                [
1342
+                    $initiatorDisplayName,
1343
+                    $instanceName
1344
+                ]
1345
+            );
1346
+            $message->setFrom([\OCP\Util::getDefaultEmailAddress($instanceName) => $senderName]);
1347
+            if ($initiatorEmailAddress !== null) {
1348
+                $message->setReplyTo([$initiatorEmailAddress => $initiatorDisplayName]);
1349
+                $emailTemplate->addFooter($instanceName . ' - ' . $this->defaults->getSlogan());
1350
+            } else {
1351
+                $emailTemplate->addFooter();
1352
+            }
1353
+
1354
+            if (count($toList) === 1) {
1355
+                $message->setTo($toList);
1356
+            } else {
1357
+                $message->setTo([]);
1358
+                $message->setBcc($toList);
1359
+            }
1360
+            $message->useTemplate($emailTemplate);
1361
+            $this->mailer->send($message);
1362
+        }
1363
+
1364
+    }
1365 1365
 }
Please login to merge, or discard this patch.
Spacing   +25 added lines, -25 removed lines patch added patch discarded remove patch
@@ -338,7 +338,7 @@  discard block
 block discarded – undo
338 338
 			->orderBy('id');
339 339
 
340 340
 		$cursor = $qb->execute();
341
-		while($data = $cursor->fetch()) {
341
+		while ($data = $cursor->fetch()) {
342 342
 			$children[] = $this->createShare($data);
343 343
 		}
344 344
 		$cursor->closeCursor();
@@ -383,7 +383,7 @@  discard block
 block discarded – undo
383 383
 			$user = $this->userManager->get($recipient);
384 384
 
385 385
 			if (is_null($group)) {
386
-				throw new ProviderException('Group "' . $share->getSharedWith() . '" does not exist');
386
+				throw new ProviderException('Group "'.$share->getSharedWith().'" does not exist');
387 387
 			}
388 388
 
389 389
 			if (!$group->inGroup($user)) {
@@ -578,7 +578,7 @@  discard block
 block discarded – undo
578 578
 			);
579 579
 		}
580 580
 
581
-		$qb->innerJoin('s', 'filecache' ,'f', $qb->expr()->eq('s.file_source', 'f.fileid'));
581
+		$qb->innerJoin('s', 'filecache', 'f', $qb->expr()->eq('s.file_source', 'f.fileid'));
582 582
 		$qb->andWhere($qb->expr()->eq('f.parent', $qb->createNamedParameter($node->getId())));
583 583
 
584 584
 		$qb->orderBy('id');
@@ -634,7 +634,7 @@  discard block
 block discarded – undo
634 634
 
635 635
 		$cursor = $qb->execute();
636 636
 		$shares = [];
637
-		while($data = $cursor->fetch()) {
637
+		while ($data = $cursor->fetch()) {
638 638
 			$shares[] = $this->createShare($data);
639 639
 		}
640 640
 		$cursor->closeCursor();
@@ -713,7 +713,7 @@  discard block
 block discarded – undo
713 713
 			->execute();
714 714
 
715 715
 		$shares = [];
716
-		while($data = $cursor->fetch()) {
716
+		while ($data = $cursor->fetch()) {
717 717
 			$shares[] = $this->createShare($data);
718 718
 		}
719 719
 		$cursor->closeCursor();
@@ -784,7 +784,7 @@  discard block
 block discarded – undo
784 784
 
785 785
 			$cursor = $qb->execute();
786 786
 
787
-			while($data = $cursor->fetch()) {
787
+			while ($data = $cursor->fetch()) {
788 788
 				if ($this->isAccessibleResult($data)) {
789 789
 					$shares[] = $this->createShare($data);
790 790
 				}
@@ -799,7 +799,7 @@  discard block
 block discarded – undo
799 799
 			$shares2 = [];
800 800
 
801 801
 			$start = 0;
802
-			while(true) {
802
+			while (true) {
803 803
 				$groups = array_slice($allGroups, $start, 100);
804 804
 				$start += 100;
805 805
 
@@ -844,7 +844,7 @@  discard block
 block discarded – undo
844 844
 					));
845 845
 
846 846
 				$cursor = $qb->execute();
847
-				while($data = $cursor->fetch()) {
847
+				while ($data = $cursor->fetch()) {
848 848
 					if ($offset > 0) {
849 849
 						$offset--;
850 850
 						continue;
@@ -913,15 +913,15 @@  discard block
 block discarded – undo
913 913
 	 */
914 914
 	private function createShare($data) {
915 915
 		$share = new Share($this->rootFolder, $this->userManager);
916
-		$share->setId((int)$data['id'])
917
-			->setShareType((int)$data['share_type'])
918
-			->setPermissions((int)$data['permissions'])
916
+		$share->setId((int) $data['id'])
917
+			->setShareType((int) $data['share_type'])
918
+			->setPermissions((int) $data['permissions'])
919 919
 			->setTarget($data['file_target'])
920 920
 			->setNote($data['note'])
921
-			->setMailSend((bool)$data['mail_send']);
921
+			->setMailSend((bool) $data['mail_send']);
922 922
 
923 923
 		$shareTime = new \DateTime();
924
-		$shareTime->setTimestamp((int)$data['stime']);
924
+		$shareTime->setTimestamp((int) $data['stime']);
925 925
 		$share->setShareTime($shareTime);
926 926
 
927 927
 		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
@@ -936,7 +936,7 @@  discard block
 block discarded – undo
936 936
 		$share->setSharedBy($data['uid_initiator']);
937 937
 		$share->setShareOwner($data['uid_owner']);
938 938
 
939
-		$share->setNodeId((int)$data['file_source']);
939
+		$share->setNodeId((int) $data['file_source']);
940 940
 		$share->setNodeType($data['item_type']);
941 941
 
942 942
 		if ($data['expiration'] !== null) {
@@ -966,7 +966,7 @@  discard block
 block discarded – undo
966 966
 		$result = [];
967 967
 
968 968
 		$start = 0;
969
-		while(true) {
969
+		while (true) {
970 970
 			/** @var Share[] $shareSlice */
971 971
 			$shareSlice = array_slice($shares, $start, 100);
972 972
 			$start += 100;
@@ -981,7 +981,7 @@  discard block
 block discarded – undo
981 981
 			$shareMap = [];
982 982
 
983 983
 			foreach ($shareSlice as $share) {
984
-				$ids[] = (int)$share->getId();
984
+				$ids[] = (int) $share->getId();
985 985
 				$shareMap[$share->getId()] = $share;
986 986
 			}
987 987
 
@@ -998,8 +998,8 @@  discard block
 block discarded – undo
998 998
 
999 999
 			$stmt = $query->execute();
1000 1000
 
1001
-			while($data = $stmt->fetch()) {
1002
-				$shareMap[$data['parent']]->setPermissions((int)$data['permissions']);
1001
+			while ($data = $stmt->fetch()) {
1002
+				$shareMap[$data['parent']]->setPermissions((int) $data['permissions']);
1003 1003
 				$shareMap[$data['parent']]->setTarget($data['file_target']);
1004 1004
 				$shareMap[$data['parent']]->setParent($data['parent']);
1005 1005
 			}
@@ -1097,8 +1097,8 @@  discard block
 block discarded – undo
1097 1097
 
1098 1098
 		$cursor = $qb->execute();
1099 1099
 		$ids = [];
1100
-		while($row = $cursor->fetch()) {
1101
-			$ids[] = (int)$row['id'];
1100
+		while ($row = $cursor->fetch()) {
1101
+			$ids[] = (int) $row['id'];
1102 1102
 		}
1103 1103
 		$cursor->closeCursor();
1104 1104
 
@@ -1140,8 +1140,8 @@  discard block
 block discarded – undo
1140 1140
 
1141 1141
 		$cursor = $qb->execute();
1142 1142
 		$ids = [];
1143
-		while($row = $cursor->fetch()) {
1144
-			$ids[] = (int)$row['id'];
1143
+		while ($row = $cursor->fetch()) {
1144
+			$ids[] = (int) $row['id'];
1145 1145
 		}
1146 1146
 		$cursor->closeCursor();
1147 1147
 
@@ -1195,8 +1195,8 @@  discard block
 block discarded – undo
1195 1195
 
1196 1196
 		$users = [];
1197 1197
 		$link = false;
1198
-		while($row = $cursor->fetch()) {
1199
-			$type = (int)$row['share_type'];
1198
+		while ($row = $cursor->fetch()) {
1199
+			$type = (int) $row['share_type'];
1200 1200
 			if ($type === \OCP\Share::SHARE_TYPE_USER) {
1201 1201
 				$uid = $row['share_with'];
1202 1202
 				$users[$uid] = isset($users[$uid]) ? $users[$uid] : [];
@@ -1346,7 +1346,7 @@  discard block
 block discarded – undo
1346 1346
 			$message->setFrom([\OCP\Util::getDefaultEmailAddress($instanceName) => $senderName]);
1347 1347
 			if ($initiatorEmailAddress !== null) {
1348 1348
 				$message->setReplyTo([$initiatorEmailAddress => $initiatorDisplayName]);
1349
-				$emailTemplate->addFooter($instanceName . ' - ' . $this->defaults->getSlogan());
1349
+				$emailTemplate->addFooter($instanceName.' - '.$this->defaults->getSlogan());
1350 1350
 			} else {
1351 1351
 				$emailTemplate->addFooter();
1352 1352
 			}
Please login to merge, or discard this patch.