Completed
Pull Request — master (#6637)
by Tobia
13:14
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   +1305 added lines, -1305 removed lines patch added patch discarded remove patch
@@ -38,1311 +38,1311 @@
 block discarded – undo
38 38
 use OC\ServerNotAvailableException;
39 39
 
40 40
 class Wizard extends LDAPUtility {
41
-	/** @var \OCP\IL10N */
42
-	static protected $l;
43
-	protected $access;
44
-	protected $cr;
45
-	protected $configuration;
46
-	protected $result;
47
-	protected $resultCache = array();
48
-
49
-	const LRESULT_PROCESSED_OK = 2;
50
-	const LRESULT_PROCESSED_INVALID = 3;
51
-	const LRESULT_PROCESSED_SKIP = 4;
52
-
53
-	const LFILTER_LOGIN      = 2;
54
-	const LFILTER_USER_LIST  = 3;
55
-	const LFILTER_GROUP_LIST = 4;
56
-
57
-	const LFILTER_MODE_ASSISTED = 2;
58
-	const LFILTER_MODE_RAW = 1;
59
-
60
-	const LDAP_NW_TIMEOUT = 4;
61
-
62
-	/**
63
-	 * Constructor
64
-	 * @param Configuration $configuration an instance of Configuration
65
-	 * @param ILDAPWrapper $ldap an instance of ILDAPWrapper
66
-	 * @param Access $access
67
-	 */
68
-	public function __construct(Configuration $configuration, ILDAPWrapper $ldap, Access $access) {
69
-		parent::__construct($ldap);
70
-		$this->configuration = $configuration;
71
-		if(is_null(Wizard::$l)) {
72
-			Wizard::$l = \OC::$server->getL10N('user_ldap');
73
-		}
74
-		$this->access = $access;
75
-		$this->result = new WizardResult();
76
-	}
77
-
78
-	public function  __destruct() {
79
-		if($this->result->hasChanges()) {
80
-			$this->configuration->saveConfiguration();
81
-		}
82
-	}
83
-
84
-	/**
85
-	 * counts entries in the LDAP directory
86
-	 *
87
-	 * @param string $filter the LDAP search filter
88
-	 * @param string $type a string being either 'users' or 'groups';
89
-	 * @return bool|int
90
-	 * @throws \Exception
91
-	 */
92
-	public function countEntries($filter, $type) {
93
-		$reqs = array('ldapHost', 'ldapPort', 'ldapBase');
94
-		if($type === 'users') {
95
-			$reqs[] = 'ldapUserFilter';
96
-		}
97
-		if(!$this->checkRequirements($reqs)) {
98
-			throw new \Exception('Requirements not met', 400);
99
-		}
100
-
101
-		$attr = array('dn'); // default
102
-		$limit = 1001;
103
-		if($type === 'groups') {
104
-			$result =  $this->access->countGroups($filter, $attr, $limit);
105
-		} else if($type === 'users') {
106
-			$result = $this->access->countUsers($filter, $attr, $limit);
107
-		} else if ($type === 'objects') {
108
-			$result = $this->access->countObjects($limit);
109
-		} else {
110
-			throw new \Exception('Internal error: Invalid object type', 500);
111
-		}
112
-
113
-		return $result;
114
-	}
115
-
116
-	/**
117
-	 * formats the return value of a count operation to the string to be
118
-	 * inserted.
119
-	 *
120
-	 * @param bool|int $count
121
-	 * @return int|string
122
-	 */
123
-	private function formatCountResult($count) {
124
-		$formatted = ($count !== false) ? $count : 0;
125
-		if($formatted > 1000) {
126
-			$formatted = '> 1000';
127
-		}
128
-		return $formatted;
129
-	}
130
-
131
-	public function countGroups() {
132
-		$filter = $this->configuration->ldapGroupFilter;
133
-
134
-		if(empty($filter)) {
135
-			$output = self::$l->n('%s group found', '%s groups found', 0, array(0));
136
-			$this->result->addChange('ldap_group_count', $output);
137
-			return $this->result;
138
-		}
139
-
140
-		try {
141
-			$groupsTotal = $this->formatCountResult($this->countEntries($filter, 'groups'));
142
-		} catch (\Exception $e) {
143
-			//400 can be ignored, 500 is forwarded
144
-			if($e->getCode() === 500) {
145
-				throw $e;
146
-			}
147
-			return false;
148
-		}
149
-		$output = self::$l->n('%s group found', '%s groups found', $groupsTotal, array($groupsTotal));
150
-		$this->result->addChange('ldap_group_count', $output);
151
-		return $this->result;
152
-	}
153
-
154
-	/**
155
-	 * @return WizardResult
156
-	 * @throws \Exception
157
-	 */
158
-	public function countUsers() {
159
-		$filter = $this->access->getFilterForUserCount();
160
-
161
-		$usersTotal = $this->formatCountResult($this->countEntries($filter, 'users'));
162
-		$output = self::$l->n('%s user found', '%s users found', $usersTotal, array($usersTotal));
163
-		$this->result->addChange('ldap_user_count', $output);
164
-		return $this->result;
165
-	}
166
-
167
-	/**
168
-	 * counts any objects in the currently set base dn
169
-	 *
170
-	 * @return WizardResult
171
-	 * @throws \Exception
172
-	 */
173
-	public function countInBaseDN() {
174
-		// we don't need to provide a filter in this case
175
-		$total = $this->countEntries(null, 'objects');
176
-		if($total === false) {
177
-			throw new \Exception('invalid results received');
178
-		}
179
-		$this->result->addChange('ldap_test_base', $total);
180
-		return $this->result;
181
-	}
182
-
183
-	/**
184
-	 * counts users with a specified attribute
185
-	 * @param string $attr
186
-	 * @param bool $existsCheck
187
-	 * @return int|bool
188
-	 */
189
-	public function countUsersWithAttribute($attr, $existsCheck = false) {
190
-		if(!$this->checkRequirements(array('ldapHost',
191
-										   'ldapPort',
192
-										   'ldapBase',
193
-										   'ldapUserFilter',
194
-										   ))) {
195
-			return  false;
196
-		}
197
-
198
-		$filter = $this->access->combineFilterWithAnd(array(
199
-			$this->configuration->ldapUserFilter,
200
-			$attr . '=*'
201
-		));
202
-
203
-		$limit = ($existsCheck === false) ? null : 1;
204
-
205
-		return $this->access->countUsers($filter, array('dn'), $limit);
206
-	}
207
-
208
-	/**
209
-	 * detects the display name attribute. If a setting is already present that
210
-	 * returns at least one hit, the detection will be canceled.
211
-	 * @return WizardResult|bool
212
-	 * @throws \Exception
213
-	 */
214
-	public function detectUserDisplayNameAttribute() {
215
-		if(!$this->checkRequirements(array('ldapHost',
216
-										'ldapPort',
217
-										'ldapBase',
218
-										'ldapUserFilter',
219
-										))) {
220
-			return  false;
221
-		}
222
-
223
-		$attr = $this->configuration->ldapUserDisplayName;
224
-		if ($attr !== '' && $attr !== 'displayName') {
225
-			// most likely not the default value with upper case N,
226
-			// verify it still produces a result
227
-			$count = intval($this->countUsersWithAttribute($attr, true));
228
-			if($count > 0) {
229
-				//no change, but we sent it back to make sure the user interface
230
-				//is still correct, even if the ajax call was cancelled meanwhile
231
-				$this->result->addChange('ldap_display_name', $attr);
232
-				return $this->result;
233
-			}
234
-		}
235
-
236
-		// first attribute that has at least one result wins
237
-		$displayNameAttrs = array('displayname', 'cn');
238
-		foreach ($displayNameAttrs as $attr) {
239
-			$count = intval($this->countUsersWithAttribute($attr, true));
240
-
241
-			if($count > 0) {
242
-				$this->applyFind('ldap_display_name', $attr);
243
-				return $this->result;
244
-			}
245
-		};
246
-
247
-		throw new \Exception(self::$l->t('Could not detect user display name attribute. Please specify it yourself in advanced LDAP settings.'));
248
-	}
249
-
250
-	/**
251
-	 * detects the most often used email attribute for users applying to the
252
-	 * user list filter. If a setting is already present that returns at least
253
-	 * one hit, the detection will be canceled.
254
-	 * @return WizardResult|bool
255
-	 */
256
-	public function detectEmailAttribute() {
257
-		if(!$this->checkRequirements(array('ldapHost',
258
-										   'ldapPort',
259
-										   'ldapBase',
260
-										   'ldapUserFilter',
261
-										   ))) {
262
-			return  false;
263
-		}
264
-
265
-		$attr = $this->configuration->ldapEmailAttribute;
266
-		if ($attr !== '') {
267
-			$count = intval($this->countUsersWithAttribute($attr, true));
268
-			if($count > 0) {
269
-				return false;
270
-			}
271
-			$writeLog = true;
272
-		} else {
273
-			$writeLog = false;
274
-		}
275
-
276
-		$emailAttributes = array('mail', 'mailPrimaryAddress');
277
-		$winner = '';
278
-		$maxUsers = 0;
279
-		foreach($emailAttributes as $attr) {
280
-			$count = $this->countUsersWithAttribute($attr);
281
-			if($count > $maxUsers) {
282
-				$maxUsers = $count;
283
-				$winner = $attr;
284
-			}
285
-		}
286
-
287
-		if($winner !== '') {
288
-			$this->applyFind('ldap_email_attr', $winner);
289
-			if($writeLog) {
290
-				\OCP\Util::writeLog('user_ldap', 'The mail attribute has ' .
291
-					'automatically been reset, because the original value ' .
292
-					'did not return any results.', \OCP\Util::INFO);
293
-			}
294
-		}
295
-
296
-		return $this->result;
297
-	}
298
-
299
-	/**
300
-	 * @return WizardResult
301
-	 * @throws \Exception
302
-	 */
303
-	public function determineAttributes() {
304
-		if(!$this->checkRequirements(array('ldapHost',
305
-										   'ldapPort',
306
-										   'ldapBase',
307
-										   'ldapUserFilter',
308
-										   ))) {
309
-			return  false;
310
-		}
311
-
312
-		$attributes = $this->getUserAttributes();
313
-
314
-		natcasesort($attributes);
315
-		$attributes = array_values($attributes);
316
-
317
-		$this->result->addOptions('ldap_loginfilter_attributes', $attributes);
318
-
319
-		$selected = $this->configuration->ldapLoginFilterAttributes;
320
-		if(is_array($selected) && !empty($selected)) {
321
-			$this->result->addChange('ldap_loginfilter_attributes', $selected);
322
-		}
323
-
324
-		return $this->result;
325
-	}
326
-
327
-	/**
328
-	 * detects the available LDAP attributes
329
-	 * @return array|false The instance's WizardResult instance
330
-	 * @throws \Exception
331
-	 */
332
-	private function getUserAttributes() {
333
-		if(!$this->checkRequirements(array('ldapHost',
334
-										   'ldapPort',
335
-										   'ldapBase',
336
-										   'ldapUserFilter',
337
-										   ))) {
338
-			return  false;
339
-		}
340
-		$cr = $this->getConnection();
341
-		if(!$cr) {
342
-			throw new \Exception('Could not connect to LDAP');
343
-		}
344
-
345
-		$base = $this->configuration->ldapBase[0];
346
-		$filter = $this->configuration->ldapUserFilter;
347
-		$rr = $this->ldap->search($cr, $base, $filter, array(), 1, 1);
348
-		if(!$this->ldap->isResource($rr)) {
349
-			return false;
350
-		}
351
-		$er = $this->ldap->firstEntry($cr, $rr);
352
-		$attributes = $this->ldap->getAttributes($cr, $er);
353
-		$pureAttributes = array();
354
-		for($i = 0; $i < $attributes['count']; $i++) {
355
-			$pureAttributes[] = $attributes[$i];
356
-		}
357
-
358
-		return $pureAttributes;
359
-	}
360
-
361
-	/**
362
-	 * detects the available LDAP groups
363
-	 * @return WizardResult|false the instance's WizardResult instance
364
-	 */
365
-	public function determineGroupsForGroups() {
366
-		return $this->determineGroups('ldap_groupfilter_groups',
367
-									  'ldapGroupFilterGroups',
368
-									  false);
369
-	}
370
-
371
-	/**
372
-	 * detects the available LDAP groups
373
-	 * @return WizardResult|false the instance's WizardResult instance
374
-	 */
375
-	public function determineGroupsForUsers() {
376
-		return $this->determineGroups('ldap_userfilter_groups',
377
-									  'ldapUserFilterGroups');
378
-	}
379
-
380
-	/**
381
-	 * detects the available LDAP groups
382
-	 * @param string $dbKey
383
-	 * @param string $confKey
384
-	 * @param bool $testMemberOf
385
-	 * @return WizardResult|false the instance's WizardResult instance
386
-	 * @throws \Exception
387
-	 */
388
-	private function determineGroups($dbKey, $confKey, $testMemberOf = true) {
389
-		if(!$this->checkRequirements(array('ldapHost',
390
-										   'ldapPort',
391
-										   'ldapBase',
392
-										   ))) {
393
-			return  false;
394
-		}
395
-		$cr = $this->getConnection();
396
-		if(!$cr) {
397
-			throw new \Exception('Could not connect to LDAP');
398
-		}
399
-
400
-		$this->fetchGroups($dbKey, $confKey);
401
-
402
-		if($testMemberOf) {
403
-			$this->configuration->hasMemberOfFilterSupport = $this->testMemberOf();
404
-			$this->result->markChange();
405
-			if(!$this->configuration->hasMemberOfFilterSupport) {
406
-				throw new \Exception('memberOf is not supported by the server');
407
-			}
408
-		}
409
-
410
-		return $this->result;
411
-	}
412
-
413
-	/**
414
-	 * fetches all groups from LDAP and adds them to the result object
415
-	 *
416
-	 * @param string $dbKey
417
-	 * @param string $confKey
418
-	 * @return array $groupEntries
419
-	 * @throws \Exception
420
-	 */
421
-	public function fetchGroups($dbKey, $confKey) {
422
-		$obclasses = array('posixGroup', 'group', 'zimbraDistributionList', 'groupOfNames', 'groupOfUniqueNames');
423
-
424
-		$filterParts = array();
425
-		foreach($obclasses as $obclass) {
426
-			$filterParts[] = 'objectclass='.$obclass;
427
-		}
428
-		//we filter for everything
429
-		//- that looks like a group and
430
-		//- has the group display name set
431
-		$filter = $this->access->combineFilterWithOr($filterParts);
432
-		$filter = $this->access->combineFilterWithAnd(array($filter, 'cn=*'));
433
-
434
-		$groupNames = array();
435
-		$groupEntries = array();
436
-		$limit = 400;
437
-		$offset = 0;
438
-		do {
439
-			// we need to request dn additionally here, otherwise memberOf
440
-			// detection will fail later
441
-			$result = $this->access->searchGroups($filter, array('cn', 'dn'), $limit, $offset);
442
-			foreach($result as $item) {
443
-				if(!isset($item['cn']) && !is_array($item['cn']) && !isset($item['cn'][0])) {
444
-					// just in case - no issue known
445
-					continue;
446
-				}
447
-				$groupNames[] = $item['cn'][0];
448
-				$groupEntries[] = $item;
449
-			}
450
-			$offset += $limit;
451
-		} while ($this->access->hasMoreResults());
452
-
453
-		if(count($groupNames) > 0) {
454
-			natsort($groupNames);
455
-			$this->result->addOptions($dbKey, array_values($groupNames));
456
-		} else {
457
-			throw new \Exception(self::$l->t('Could not find the desired feature'));
458
-		}
459
-
460
-		$setFeatures = $this->configuration->$confKey;
461
-		if(is_array($setFeatures) && !empty($setFeatures)) {
462
-			//something is already configured? pre-select it.
463
-			$this->result->addChange($dbKey, $setFeatures);
464
-		}
465
-		return $groupEntries;
466
-	}
467
-
468
-	public function determineGroupMemberAssoc() {
469
-		if(!$this->checkRequirements(array('ldapHost',
470
-										   'ldapPort',
471
-										   'ldapGroupFilter',
472
-										   ))) {
473
-			return  false;
474
-		}
475
-		$attribute = $this->detectGroupMemberAssoc();
476
-		if($attribute === false) {
477
-			return false;
478
-		}
479
-		$this->configuration->setConfiguration(array('ldapGroupMemberAssocAttr' => $attribute));
480
-		$this->result->addChange('ldap_group_member_assoc_attribute', $attribute);
481
-
482
-		return $this->result;
483
-	}
484
-
485
-	/**
486
-	 * Detects the available object classes
487
-	 * @return WizardResult|false the instance's WizardResult instance
488
-	 * @throws \Exception
489
-	 */
490
-	public function determineGroupObjectClasses() {
491
-		if(!$this->checkRequirements(array('ldapHost',
492
-										   'ldapPort',
493
-										   'ldapBase',
494
-										   ))) {
495
-			return  false;
496
-		}
497
-		$cr = $this->getConnection();
498
-		if(!$cr) {
499
-			throw new \Exception('Could not connect to LDAP');
500
-		}
501
-
502
-		$obclasses = array('groupOfNames', 'groupOfUniqueNames', 'group', 'posixGroup', '*');
503
-		$this->determineFeature($obclasses,
504
-								'objectclass',
505
-								'ldap_groupfilter_objectclass',
506
-								'ldapGroupFilterObjectclass',
507
-								false);
508
-
509
-		return $this->result;
510
-	}
511
-
512
-	/**
513
-	 * detects the available object classes
514
-	 * @return WizardResult
515
-	 * @throws \Exception
516
-	 */
517
-	public function determineUserObjectClasses() {
518
-		if(!$this->checkRequirements(array('ldapHost',
519
-										   'ldapPort',
520
-										   'ldapBase',
521
-										   ))) {
522
-			return  false;
523
-		}
524
-		$cr = $this->getConnection();
525
-		if(!$cr) {
526
-			throw new \Exception('Could not connect to LDAP');
527
-		}
528
-
529
-		$obclasses = array('inetOrgPerson', 'person', 'organizationalPerson',
530
-						   'user', 'posixAccount', '*');
531
-		$filter = $this->configuration->ldapUserFilter;
532
-		//if filter is empty, it is probably the first time the wizard is called
533
-		//then, apply suggestions.
534
-		$this->determineFeature($obclasses,
535
-								'objectclass',
536
-								'ldap_userfilter_objectclass',
537
-								'ldapUserFilterObjectclass',
538
-								empty($filter));
539
-
540
-		return $this->result;
541
-	}
542
-
543
-	/**
544
-	 * @return WizardResult|false
545
-	 * @throws \Exception
546
-	 */
547
-	public function getGroupFilter() {
548
-		if(!$this->checkRequirements(array('ldapHost',
549
-										   'ldapPort',
550
-										   'ldapBase',
551
-										   ))) {
552
-			return false;
553
-		}
554
-		//make sure the use display name is set
555
-		$displayName = $this->configuration->ldapGroupDisplayName;
556
-		if ($displayName === '') {
557
-			$d = $this->configuration->getDefaults();
558
-			$this->applyFind('ldap_group_display_name',
559
-							 $d['ldap_group_display_name']);
560
-		}
561
-		$filter = $this->composeLdapFilter(self::LFILTER_GROUP_LIST);
562
-
563
-		$this->applyFind('ldap_group_filter', $filter);
564
-		return $this->result;
565
-	}
566
-
567
-	/**
568
-	 * @return WizardResult|false
569
-	 * @throws \Exception
570
-	 */
571
-	public function getUserListFilter() {
572
-		if(!$this->checkRequirements(array('ldapHost',
573
-										   'ldapPort',
574
-										   'ldapBase',
575
-										   ))) {
576
-			return false;
577
-		}
578
-		//make sure the use display name is set
579
-		$displayName = $this->configuration->ldapUserDisplayName;
580
-		if ($displayName === '') {
581
-			$d = $this->configuration->getDefaults();
582
-			$this->applyFind('ldap_display_name', $d['ldap_display_name']);
583
-		}
584
-		$filter = $this->composeLdapFilter(self::LFILTER_USER_LIST);
585
-		if(!$filter) {
586
-			throw new \Exception('Cannot create filter');
587
-		}
588
-
589
-		$this->applyFind('ldap_userlist_filter', $filter);
590
-		return $this->result;
591
-	}
592
-
593
-	/**
594
-	 * @return bool|WizardResult
595
-	 * @throws \Exception
596
-	 */
597
-	public function getUserLoginFilter() {
598
-		if(!$this->checkRequirements(array('ldapHost',
599
-										   'ldapPort',
600
-										   'ldapBase',
601
-										   'ldapUserFilter',
602
-										   ))) {
603
-			return false;
604
-		}
605
-
606
-		$filter = $this->composeLdapFilter(self::LFILTER_LOGIN);
607
-		if(!$filter) {
608
-			throw new \Exception('Cannot create filter');
609
-		}
610
-
611
-		$this->applyFind('ldap_login_filter', $filter);
612
-		return $this->result;
613
-	}
614
-
615
-	/**
616
-	 * @return bool|WizardResult
617
-	 * @param string $loginName
618
-	 * @throws \Exception
619
-	 */
620
-	public function testLoginName($loginName) {
621
-		if(!$this->checkRequirements(array('ldapHost',
622
-			'ldapPort',
623
-			'ldapBase',
624
-			'ldapLoginFilter',
625
-		))) {
626
-			return false;
627
-		}
628
-
629
-		$cr = $this->access->connection->getConnectionResource();
630
-		if(!$this->ldap->isResource($cr)) {
631
-			throw new \Exception('connection error');
632
-		}
633
-
634
-		if(mb_strpos($this->access->connection->ldapLoginFilter, '%uid', 0, 'UTF-8')
635
-			=== false) {
636
-			throw new \Exception('missing placeholder');
637
-		}
638
-
639
-		$users = $this->access->countUsersByLoginName($loginName);
640
-		if($this->ldap->errno($cr) !== 0) {
641
-			throw new \Exception($this->ldap->error($cr));
642
-		}
643
-		$filter = str_replace('%uid', $loginName, $this->access->connection->ldapLoginFilter);
644
-		$this->result->addChange('ldap_test_loginname', $users);
645
-		$this->result->addChange('ldap_test_effective_filter', $filter);
646
-		return $this->result;
647
-	}
648
-
649
-	/**
650
-	 * Tries to determine the port, requires given Host, User DN and Password
651
-	 * @return WizardResult|false WizardResult on success, false otherwise
652
-	 * @throws \Exception
653
-	 */
654
-	public function guessPortAndTLS() {
655
-		if(!$this->checkRequirements(array('ldapHost',
656
-										   ))) {
657
-			return false;
658
-		}
659
-		$this->checkHost();
660
-		$portSettings = $this->getPortSettingsToTry();
661
-
662
-		if(!is_array($portSettings)) {
663
-			throw new \Exception(print_r($portSettings, true));
664
-		}
665
-
666
-		//proceed from the best configuration and return on first success
667
-		foreach($portSettings as $setting) {
668
-			$p = $setting['port'];
669
-			$t = $setting['tls'];
670
-			\OCP\Util::writeLog('user_ldap', 'Wiz: trying port '. $p . ', TLS '. $t, \OCP\Util::DEBUG);
671
-			//connectAndBind may throw Exception, it needs to be catched by the
672
-			//callee of this method
673
-
674
-			try {
675
-				$settingsFound = $this->connectAndBind($p, $t);
676
-			} catch (\Exception $e) {
677
-				// any reply other than -1 (= cannot connect) is already okay,
678
-				// because then we found the server
679
-				// unavailable startTLS returns -11
680
-				if($e->getCode() > 0) {
681
-					$settingsFound = true;
682
-				} else {
683
-					throw $e;
684
-				}
685
-			}
686
-
687
-			if ($settingsFound === true) {
688
-				$config = array(
689
-					'ldapPort' => $p,
690
-					'ldapTLS' => intval($t)
691
-				);
692
-				$this->configuration->setConfiguration($config);
693
-				\OCP\Util::writeLog('user_ldap', 'Wiz: detected Port ' . $p, \OCP\Util::DEBUG);
694
-				$this->result->addChange('ldap_port', $p);
695
-				return $this->result;
696
-			}
697
-		}
698
-
699
-		//custom port, undetected (we do not brute force)
700
-		return false;
701
-	}
702
-
703
-	/**
704
-	 * tries to determine a base dn from User DN or LDAP Host
705
-	 * @return WizardResult|false WizardResult on success, false otherwise
706
-	 */
707
-	public function guessBaseDN() {
708
-		if(!$this->checkRequirements(array('ldapHost',
709
-										   'ldapPort',
710
-										   ))) {
711
-			return false;
712
-		}
713
-
714
-		//check whether a DN is given in the agent name (99.9% of all cases)
715
-		$base = null;
716
-		$i = stripos($this->configuration->ldapAgentName, 'dc=');
717
-		if($i !== false) {
718
-			$base = substr($this->configuration->ldapAgentName, $i);
719
-			if($this->testBaseDN($base)) {
720
-				$this->applyFind('ldap_base', $base);
721
-				return $this->result;
722
-			}
723
-		}
724
-
725
-		//this did not help :(
726
-		//Let's see whether we can parse the Host URL and convert the domain to
727
-		//a base DN
728
-		$helper = new Helper(\OC::$server->getConfig());
729
-		$domain = $helper->getDomainFromURL($this->configuration->ldapHost);
730
-		if(!$domain) {
731
-			return false;
732
-		}
733
-
734
-		$dparts = explode('.', $domain);
735
-		while(count($dparts) > 0) {
736
-			$base2 = 'dc=' . implode(',dc=', $dparts);
737
-			if ($base !== $base2 && $this->testBaseDN($base2)) {
738
-				$this->applyFind('ldap_base', $base2);
739
-				return $this->result;
740
-			}
741
-			array_shift($dparts);
742
-		}
743
-
744
-		return false;
745
-	}
746
-
747
-	/**
748
-	 * sets the found value for the configuration key in the WizardResult
749
-	 * as well as in the Configuration instance
750
-	 * @param string $key the configuration key
751
-	 * @param string $value the (detected) value
752
-	 *
753
-	 */
754
-	private function applyFind($key, $value) {
755
-		$this->result->addChange($key, $value);
756
-		$this->configuration->setConfiguration(array($key => $value));
757
-	}
758
-
759
-	/**
760
-	 * Checks, whether a port was entered in the Host configuration
761
-	 * field. In this case the port will be stripped off, but also stored as
762
-	 * setting.
763
-	 */
764
-	private function checkHost() {
765
-		$host = $this->configuration->ldapHost;
766
-		$hostInfo = parse_url($host);
767
-
768
-		//removes Port from Host
769
-		if(is_array($hostInfo) && isset($hostInfo['port'])) {
770
-			$port = $hostInfo['port'];
771
-			$host = str_replace(':'.$port, '', $host);
772
-			$this->applyFind('ldap_host', $host);
773
-			$this->applyFind('ldap_port', $port);
774
-		}
775
-	}
776
-
777
-	/**
778
-	 * tries to detect the group member association attribute which is
779
-	 * one of 'uniqueMember', 'memberUid', 'member', 'gidNumber'
780
-	 * @return string|false, string with the attribute name, false on error
781
-	 * @throws \Exception
782
-	 */
783
-	private function detectGroupMemberAssoc() {
784
-		$possibleAttrs = array('uniqueMember', 'memberUid', 'member', 'gidNumber');
785
-		$filter = $this->configuration->ldapGroupFilter;
786
-		if(empty($filter)) {
787
-			return false;
788
-		}
789
-		$cr = $this->getConnection();
790
-		if(!$cr) {
791
-			throw new \Exception('Could not connect to LDAP');
792
-		}
793
-		$base = $this->configuration->ldapBase[0];
794
-		$rr = $this->ldap->search($cr, $base, $filter, $possibleAttrs, 0, 1000);
795
-		if(!$this->ldap->isResource($rr)) {
796
-			return false;
797
-		}
798
-		$er = $this->ldap->firstEntry($cr, $rr);
799
-		while(is_resource($er)) {
800
-			$this->ldap->getDN($cr, $er);
801
-			$attrs = $this->ldap->getAttributes($cr, $er);
802
-			$result = array();
803
-			$possibleAttrsCount = count($possibleAttrs);
804
-			for($i = 0; $i < $possibleAttrsCount; $i++) {
805
-				if(isset($attrs[$possibleAttrs[$i]])) {
806
-					$result[$possibleAttrs[$i]] = $attrs[$possibleAttrs[$i]]['count'];
807
-				}
808
-			}
809
-			if(!empty($result)) {
810
-				natsort($result);
811
-				return key($result);
812
-			}
813
-
814
-			$er = $this->ldap->nextEntry($cr, $er);
815
-		}
816
-
817
-		return false;
818
-	}
819
-
820
-	/**
821
-	 * Checks whether for a given BaseDN results will be returned
822
-	 * @param string $base the BaseDN to test
823
-	 * @return bool true on success, false otherwise
824
-	 * @throws \Exception
825
-	 */
826
-	private function testBaseDN($base) {
827
-		$cr = $this->getConnection();
828
-		if(!$cr) {
829
-			throw new \Exception('Could not connect to LDAP');
830
-		}
831
-
832
-		//base is there, let's validate it. If we search for anything, we should
833
-		//get a result set > 0 on a proper base
834
-		$rr = $this->ldap->search($cr, $base, 'objectClass=*', array('dn'), 0, 1);
835
-		if(!$this->ldap->isResource($rr)) {
836
-			$errorNo  = $this->ldap->errno($cr);
837
-			$errorMsg = $this->ldap->error($cr);
838
-			\OCP\Util::writeLog('user_ldap', 'Wiz: Could not search base '.$base.
839
-							' Error '.$errorNo.': '.$errorMsg, \OCP\Util::INFO);
840
-			return false;
841
-		}
842
-		$entries = $this->ldap->countEntries($cr, $rr);
843
-		return ($entries !== false) && ($entries > 0);
844
-	}
845
-
846
-	/**
847
-	 * Checks whether the server supports memberOf in LDAP Filter.
848
-	 * Note: at least in OpenLDAP, availability of memberOf is dependent on
849
-	 * a configured objectClass. I.e. not necessarily for all available groups
850
-	 * memberOf does work.
851
-	 *
852
-	 * @return bool true if it does, false otherwise
853
-	 * @throws \Exception
854
-	 */
855
-	private function testMemberOf() {
856
-		$cr = $this->getConnection();
857
-		if(!$cr) {
858
-			throw new \Exception('Could not connect to LDAP');
859
-		}
860
-		$result = $this->access->countUsers('memberOf=*', array('memberOf'), 1);
861
-		if(is_int($result) &&  $result > 0) {
862
-			return true;
863
-		}
864
-		return false;
865
-	}
866
-
867
-	/**
868
-	 * creates an LDAP Filter from given configuration
869
-	 * @param integer $filterType int, for which use case the filter shall be created
870
-	 * can be any of self::LFILTER_USER_LIST, self::LFILTER_LOGIN or
871
-	 * self::LFILTER_GROUP_LIST
872
-	 * @return string|false string with the filter on success, false otherwise
873
-	 * @throws \Exception
874
-	 */
875
-	private function composeLdapFilter($filterType) {
876
-		$filter = '';
877
-		$parts = 0;
878
-		switch ($filterType) {
879
-			case self::LFILTER_USER_LIST:
880
-				$objcs = $this->configuration->ldapUserFilterObjectclass;
881
-				//glue objectclasses
882
-				if(is_array($objcs) && count($objcs) > 0) {
883
-					$filter .= '(|';
884
-					foreach($objcs as $objc) {
885
-						$filter .= '(objectclass=' . $objc . ')';
886
-					}
887
-					$filter .= ')';
888
-					$parts++;
889
-				}
890
-				//glue group memberships
891
-				if($this->configuration->hasMemberOfFilterSupport) {
892
-					$cns = $this->configuration->ldapUserFilterGroups;
893
-					if(is_array($cns) && count($cns) > 0) {
894
-						$filter .= '(|';
895
-						$cr = $this->getConnection();
896
-						if(!$cr) {
897
-							throw new \Exception('Could not connect to LDAP');
898
-						}
899
-						$base = $this->configuration->ldapBase[0];
900
-						foreach($cns as $cn) {
901
-							$rr = $this->ldap->search($cr, $base, 'cn=' . $cn, array('dn', 'primaryGroupToken'));
902
-							if(!$this->ldap->isResource($rr)) {
903
-								continue;
904
-							}
905
-							$er = $this->ldap->firstEntry($cr, $rr);
906
-							$attrs = $this->ldap->getAttributes($cr, $er);
907
-							$dn = $this->ldap->getDN($cr, $er);
908
-							if ($dn === false || $dn === '') {
909
-								continue;
910
-							}
911
-							$filterPart = '(memberof=' . $dn . ')';
912
-							if(isset($attrs['primaryGroupToken'])) {
913
-								$pgt = $attrs['primaryGroupToken'][0];
914
-								$primaryFilterPart = '(primaryGroupID=' . $pgt .')';
915
-								$filterPart = '(|' . $filterPart . $primaryFilterPart . ')';
916
-							}
917
-							$filter .= $filterPart;
918
-						}
919
-						$filter .= ')';
920
-					}
921
-					$parts++;
922
-				}
923
-				//wrap parts in AND condition
924
-				if($parts > 1) {
925
-					$filter = '(&' . $filter . ')';
926
-				}
927
-				if ($filter === '') {
928
-					$filter = '(objectclass=*)';
929
-				}
930
-				break;
931
-
932
-			case self::LFILTER_GROUP_LIST:
933
-				$objcs = $this->configuration->ldapGroupFilterObjectclass;
934
-				//glue objectclasses
935
-				if(is_array($objcs) && count($objcs) > 0) {
936
-					$filter .= '(|';
937
-					foreach($objcs as $objc) {
938
-						$filter .= '(objectclass=' . $objc . ')';
939
-					}
940
-					$filter .= ')';
941
-					$parts++;
942
-				}
943
-				//glue group memberships
944
-				$cns = $this->configuration->ldapGroupFilterGroups;
945
-				if(is_array($cns) && count($cns) > 0) {
946
-					$filter .= '(|';
947
-					foreach($cns as $cn) {
948
-						$filter .= '(cn=' . $cn . ')';
949
-					}
950
-					$filter .= ')';
951
-				}
952
-				$parts++;
953
-				//wrap parts in AND condition
954
-				if($parts > 1) {
955
-					$filter = '(&' . $filter . ')';
956
-				}
957
-				break;
958
-
959
-			case self::LFILTER_LOGIN:
960
-				$ulf = $this->configuration->ldapUserFilter;
961
-				$loginpart = '=%uid';
962
-				$filterUsername = '';
963
-				$userAttributes = $this->getUserAttributes();
964
-				$userAttributes = array_change_key_case(array_flip($userAttributes));
965
-				$parts = 0;
966
-
967
-				if($this->configuration->ldapLoginFilterUsername === '1') {
968
-					$attr = '';
969
-					if(isset($userAttributes['uid'])) {
970
-						$attr = 'uid';
971
-					} else if(isset($userAttributes['samaccountname'])) {
972
-						$attr = 'samaccountname';
973
-					} else if(isset($userAttributes['cn'])) {
974
-						//fallback
975
-						$attr = 'cn';
976
-					}
977
-					if ($attr !== '') {
978
-						$filterUsername = '(' . $attr . $loginpart . ')';
979
-						$parts++;
980
-					}
981
-				}
982
-
983
-				$filterEmail = '';
984
-				if($this->configuration->ldapLoginFilterEmail === '1') {
985
-					$filterEmail = '(|(mailPrimaryAddress=%uid)(mail=%uid))';
986
-					$parts++;
987
-				}
988
-
989
-				$filterAttributes = '';
990
-				$attrsToFilter = $this->configuration->ldapLoginFilterAttributes;
991
-				if(is_array($attrsToFilter) && count($attrsToFilter) > 0) {
992
-					$filterAttributes = '(|';
993
-					foreach($attrsToFilter as $attribute) {
994
-						$filterAttributes .= '(' . $attribute . $loginpart . ')';
995
-					}
996
-					$filterAttributes .= ')';
997
-					$parts++;
998
-				}
999
-
1000
-				$filterLogin = '';
1001
-				if($parts > 1) {
1002
-					$filterLogin = '(|';
1003
-				}
1004
-				$filterLogin .= $filterUsername;
1005
-				$filterLogin .= $filterEmail;
1006
-				$filterLogin .= $filterAttributes;
1007
-				if($parts > 1) {
1008
-					$filterLogin .= ')';
1009
-				}
1010
-
1011
-				$filter = '(&'.$ulf.$filterLogin.')';
1012
-				break;
1013
-		}
1014
-
1015
-		\OCP\Util::writeLog('user_ldap', 'Wiz: Final filter '.$filter, \OCP\Util::DEBUG);
1016
-
1017
-		return $filter;
1018
-	}
1019
-
1020
-	/**
1021
-	 * Connects and Binds to an LDAP Server
1022
-	 *
1023
-	 * @param int $port the port to connect with
1024
-	 * @param bool $tls whether startTLS is to be used
1025
-	 * @return bool
1026
-	 * @throws \Exception
1027
-	 */
1028
-	private function connectAndBind($port, $tls) {
1029
-		//connect, does not really trigger any server communication
1030
-		$host = $this->configuration->ldapHost;
1031
-		$hostInfo = parse_url($host);
1032
-		if(!$hostInfo) {
1033
-			throw new \Exception(self::$l->t('Invalid Host'));
1034
-		}
1035
-		\OCP\Util::writeLog('user_ldap', 'Wiz: Attempting to connect ', \OCP\Util::DEBUG);
1036
-		$cr = $this->ldap->connect($host, $port);
1037
-		if(!is_resource($cr)) {
1038
-			throw new \Exception(self::$l->t('Invalid Host'));
1039
-		}
1040
-
1041
-		//set LDAP options
1042
-		$this->ldap->setOption($cr, LDAP_OPT_PROTOCOL_VERSION, 3);
1043
-		$this->ldap->setOption($cr, LDAP_OPT_REFERRALS, 0);
1044
-		$this->ldap->setOption($cr, LDAP_OPT_NETWORK_TIMEOUT, self::LDAP_NW_TIMEOUT);
1045
-
1046
-		try {
1047
-			if($tls) {
1048
-				$isTlsWorking = @$this->ldap->startTls($cr);
1049
-				if(!$isTlsWorking) {
1050
-					return false;
1051
-				}
1052
-			}
1053
-
1054
-			\OCP\Util::writeLog('user_ldap', 'Wiz: Attemping to Bind ', \OCP\Util::DEBUG);
1055
-			//interesting part: do the bind!
1056
-			$login = $this->ldap->bind($cr,
1057
-				$this->configuration->ldapAgentName,
1058
-				$this->configuration->ldapAgentPassword
1059
-			);
1060
-			$errNo = $this->ldap->errno($cr);
1061
-			$error = ldap_error($cr);
1062
-			$this->ldap->unbind($cr);
1063
-		} catch(ServerNotAvailableException $e) {
1064
-			return false;
1065
-		}
1066
-
1067
-		if($login === true) {
1068
-			$this->ldap->unbind($cr);
1069
-			\OCP\Util::writeLog('user_ldap', 'Wiz: Bind successful to Port '. $port . ' TLS ' . intval($tls), \OCP\Util::DEBUG);
1070
-			return true;
1071
-		}
1072
-
1073
-		if($errNo === -1) {
1074
-			//host, port or TLS wrong
1075
-			return false;
1076
-		}
1077
-		throw new \Exception($error, $errNo);
1078
-	}
1079
-
1080
-	/**
1081
-	 * checks whether a valid combination of agent and password has been
1082
-	 * provided (either two values or nothing for anonymous connect)
1083
-	 * @return bool, true if everything is fine, false otherwise
1084
-	 */
1085
-	private function checkAgentRequirements() {
1086
-		$agent = $this->configuration->ldapAgentName;
1087
-		$pwd = $this->configuration->ldapAgentPassword;
1088
-
1089
-		return
1090
-			($agent !== '' && $pwd !== '')
1091
-			||  ($agent === '' && $pwd === '')
1092
-		;
1093
-	}
1094
-
1095
-	/**
1096
-	 * @param array $reqs
1097
-	 * @return bool
1098
-	 */
1099
-	private function checkRequirements($reqs) {
1100
-		$this->checkAgentRequirements();
1101
-		foreach($reqs as $option) {
1102
-			$value = $this->configuration->$option;
1103
-			if(empty($value)) {
1104
-				return false;
1105
-			}
1106
-		}
1107
-		return true;
1108
-	}
1109
-
1110
-	/**
1111
-	 * does a cumulativeSearch on LDAP to get different values of a
1112
-	 * specified attribute
1113
-	 * @param string[] $filters array, the filters that shall be used in the search
1114
-	 * @param string $attr the attribute of which a list of values shall be returned
1115
-	 * @param int $dnReadLimit the amount of how many DNs should be analyzed.
1116
-	 * The lower, the faster
1117
-	 * @param string $maxF string. if not null, this variable will have the filter that
1118
-	 * yields most result entries
1119
-	 * @return array|false an array with the values on success, false otherwise
1120
-	 */
1121
-	public function cumulativeSearchOnAttribute($filters, $attr, $dnReadLimit = 3, &$maxF = null) {
1122
-		$dnRead = array();
1123
-		$foundItems = array();
1124
-		$maxEntries = 0;
1125
-		if(!is_array($this->configuration->ldapBase)
1126
-		   || !isset($this->configuration->ldapBase[0])) {
1127
-			return false;
1128
-		}
1129
-		$base = $this->configuration->ldapBase[0];
1130
-		$cr = $this->getConnection();
1131
-		if(!$this->ldap->isResource($cr)) {
1132
-			return false;
1133
-		}
1134
-		$lastFilter = null;
1135
-		if(isset($filters[count($filters)-1])) {
1136
-			$lastFilter = $filters[count($filters)-1];
1137
-		}
1138
-		foreach($filters as $filter) {
1139
-			if($lastFilter === $filter && count($foundItems) > 0) {
1140
-				//skip when the filter is a wildcard and results were found
1141
-				continue;
1142
-			}
1143
-			// 20k limit for performance and reason
1144
-			$rr = $this->ldap->search($cr, $base, $filter, array($attr), 0, 20000);
1145
-			if(!$this->ldap->isResource($rr)) {
1146
-				continue;
1147
-			}
1148
-			$entries = $this->ldap->countEntries($cr, $rr);
1149
-			$getEntryFunc = 'firstEntry';
1150
-			if(($entries !== false) && ($entries > 0)) {
1151
-				if(!is_null($maxF) && $entries > $maxEntries) {
1152
-					$maxEntries = $entries;
1153
-					$maxF = $filter;
1154
-				}
1155
-				$dnReadCount = 0;
1156
-				do {
1157
-					$entry = $this->ldap->$getEntryFunc($cr, $rr);
1158
-					$getEntryFunc = 'nextEntry';
1159
-					if(!$this->ldap->isResource($entry)) {
1160
-						continue 2;
1161
-					}
1162
-					$rr = $entry; //will be expected by nextEntry next round
1163
-					$attributes = $this->ldap->getAttributes($cr, $entry);
1164
-					$dn = $this->ldap->getDN($cr, $entry);
1165
-					if($dn === false || in_array($dn, $dnRead)) {
1166
-						continue;
1167
-					}
1168
-					$newItems = array();
1169
-					$state = $this->getAttributeValuesFromEntry($attributes,
1170
-																$attr,
1171
-																$newItems);
1172
-					$dnReadCount++;
1173
-					$foundItems = array_merge($foundItems, $newItems);
1174
-					$this->resultCache[$dn][$attr] = $newItems;
1175
-					$dnRead[] = $dn;
1176
-				} while(($state === self::LRESULT_PROCESSED_SKIP
1177
-						|| $this->ldap->isResource($entry))
1178
-						&& ($dnReadLimit === 0 || $dnReadCount < $dnReadLimit));
1179
-			}
1180
-		}
1181
-
1182
-		return array_unique($foundItems);
1183
-	}
1184
-
1185
-	/**
1186
-	 * determines if and which $attr are available on the LDAP server
1187
-	 * @param string[] $objectclasses the objectclasses to use as search filter
1188
-	 * @param string $attr the attribute to look for
1189
-	 * @param string $dbkey the dbkey of the setting the feature is connected to
1190
-	 * @param string $confkey the confkey counterpart for the $dbkey as used in the
1191
-	 * Configuration class
1192
-	 * @param bool $po whether the objectClass with most result entries
1193
-	 * shall be pre-selected via the result
1194
-	 * @return array|false list of found items.
1195
-	 * @throws \Exception
1196
-	 */
1197
-	private function determineFeature($objectclasses, $attr, $dbkey, $confkey, $po = false) {
1198
-		$cr = $this->getConnection();
1199
-		if(!$cr) {
1200
-			throw new \Exception('Could not connect to LDAP');
1201
-		}
1202
-		$p = 'objectclass=';
1203
-		foreach($objectclasses as $key => $value) {
1204
-			$objectclasses[$key] = $p.$value;
1205
-		}
1206
-		$maxEntryObjC = '';
1207
-
1208
-		//how deep to dig?
1209
-		//When looking for objectclasses, testing few entries is sufficient,
1210
-		$dig = 3;
1211
-
1212
-		$availableFeatures =
1213
-			$this->cumulativeSearchOnAttribute($objectclasses, $attr,
1214
-											   $dig, $maxEntryObjC);
1215
-		if(is_array($availableFeatures)
1216
-		   && count($availableFeatures) > 0) {
1217
-			natcasesort($availableFeatures);
1218
-			//natcasesort keeps indices, but we must get rid of them for proper
1219
-			//sorting in the web UI. Therefore: array_values
1220
-			$this->result->addOptions($dbkey, array_values($availableFeatures));
1221
-		} else {
1222
-			throw new \Exception(self::$l->t('Could not find the desired feature'));
1223
-		}
1224
-
1225
-		$setFeatures = $this->configuration->$confkey;
1226
-		if(is_array($setFeatures) && !empty($setFeatures)) {
1227
-			//something is already configured? pre-select it.
1228
-			$this->result->addChange($dbkey, $setFeatures);
1229
-		} else if ($po && $maxEntryObjC !== '') {
1230
-			//pre-select objectclass with most result entries
1231
-			$maxEntryObjC = str_replace($p, '', $maxEntryObjC);
1232
-			$this->applyFind($dbkey, $maxEntryObjC);
1233
-			$this->result->addChange($dbkey, $maxEntryObjC);
1234
-		}
1235
-
1236
-		return $availableFeatures;
1237
-	}
1238
-
1239
-	/**
1240
-	 * appends a list of values fr
1241
-	 * @param resource $result the return value from ldap_get_attributes
1242
-	 * @param string $attribute the attribute values to look for
1243
-	 * @param array &$known new values will be appended here
1244
-	 * @return int, state on of the class constants LRESULT_PROCESSED_OK,
1245
-	 * LRESULT_PROCESSED_INVALID or LRESULT_PROCESSED_SKIP
1246
-	 */
1247
-	private function getAttributeValuesFromEntry($result, $attribute, &$known) {
1248
-		if(!is_array($result)
1249
-		   || !isset($result['count'])
1250
-		   || !$result['count'] > 0) {
1251
-			return self::LRESULT_PROCESSED_INVALID;
1252
-		}
1253
-
1254
-		// strtolower on all keys for proper comparison
1255
-		$result = \OCP\Util::mb_array_change_key_case($result);
1256
-		$attribute = strtolower($attribute);
1257
-		if(isset($result[$attribute])) {
1258
-			foreach($result[$attribute] as $key => $val) {
1259
-				if($key === 'count') {
1260
-					continue;
1261
-				}
1262
-				if(!in_array($val, $known)) {
1263
-					$known[] = $val;
1264
-				}
1265
-			}
1266
-			return self::LRESULT_PROCESSED_OK;
1267
-		} else {
1268
-			return self::LRESULT_PROCESSED_SKIP;
1269
-		}
1270
-	}
1271
-
1272
-	/**
1273
-	 * @return bool|mixed
1274
-	 */
1275
-	private function getConnection() {
1276
-		if(!is_null($this->cr)) {
1277
-			return $this->cr;
1278
-		}
1279
-
1280
-		$cr = $this->ldap->connect(
1281
-			$this->configuration->ldapHost,
1282
-			$this->configuration->ldapPort
1283
-		);
1284
-
1285
-		$this->ldap->setOption($cr, LDAP_OPT_PROTOCOL_VERSION, 3);
1286
-		$this->ldap->setOption($cr, LDAP_OPT_REFERRALS, 0);
1287
-		$this->ldap->setOption($cr, LDAP_OPT_NETWORK_TIMEOUT, self::LDAP_NW_TIMEOUT);
1288
-		if($this->configuration->ldapTLS === 1) {
1289
-			$this->ldap->startTls($cr);
1290
-		}
1291
-
1292
-		$lo = @$this->ldap->bind($cr,
1293
-								 $this->configuration->ldapAgentName,
1294
-								 $this->configuration->ldapAgentPassword);
1295
-		if($lo === true) {
1296
-			$this->$cr = $cr;
1297
-			return $cr;
1298
-		}
1299
-
1300
-		return false;
1301
-	}
1302
-
1303
-	/**
1304
-	 * @return array
1305
-	 */
1306
-	private function getDefaultLdapPortSettings() {
1307
-		static $settings = array(
1308
-								array('port' => 7636, 'tls' => false),
1309
-								array('port' =>  636, 'tls' => false),
1310
-								array('port' => 7389, 'tls' => true),
1311
-								array('port' =>  389, 'tls' => true),
1312
-								array('port' => 7389, 'tls' => false),
1313
-								array('port' =>  389, 'tls' => false),
1314
-						  );
1315
-		return $settings;
1316
-	}
1317
-
1318
-	/**
1319
-	 * @return array
1320
-	 */
1321
-	private function getPortSettingsToTry() {
1322
-		//389 ← LDAP / Unencrypted or StartTLS
1323
-		//636 ← LDAPS / SSL
1324
-		//7xxx ← UCS. need to be checked first, because both ports may be open
1325
-		$host = $this->configuration->ldapHost;
1326
-		$port = intval($this->configuration->ldapPort);
1327
-		$portSettings = array();
1328
-
1329
-		//In case the port is already provided, we will check this first
1330
-		if($port > 0) {
1331
-			$hostInfo = parse_url($host);
1332
-			if(!(is_array($hostInfo)
1333
-				&& isset($hostInfo['scheme'])
1334
-				&& stripos($hostInfo['scheme'], 'ldaps') !== false)) {
1335
-				$portSettings[] = array('port' => $port, 'tls' => true);
1336
-			}
1337
-			$portSettings[] =array('port' => $port, 'tls' => false);
1338
-		}
1339
-
1340
-		//default ports
1341
-		$portSettings = array_merge($portSettings,
1342
-		                            $this->getDefaultLdapPortSettings());
1343
-
1344
-		return $portSettings;
1345
-	}
41
+    /** @var \OCP\IL10N */
42
+    static protected $l;
43
+    protected $access;
44
+    protected $cr;
45
+    protected $configuration;
46
+    protected $result;
47
+    protected $resultCache = array();
48
+
49
+    const LRESULT_PROCESSED_OK = 2;
50
+    const LRESULT_PROCESSED_INVALID = 3;
51
+    const LRESULT_PROCESSED_SKIP = 4;
52
+
53
+    const LFILTER_LOGIN      = 2;
54
+    const LFILTER_USER_LIST  = 3;
55
+    const LFILTER_GROUP_LIST = 4;
56
+
57
+    const LFILTER_MODE_ASSISTED = 2;
58
+    const LFILTER_MODE_RAW = 1;
59
+
60
+    const LDAP_NW_TIMEOUT = 4;
61
+
62
+    /**
63
+     * Constructor
64
+     * @param Configuration $configuration an instance of Configuration
65
+     * @param ILDAPWrapper $ldap an instance of ILDAPWrapper
66
+     * @param Access $access
67
+     */
68
+    public function __construct(Configuration $configuration, ILDAPWrapper $ldap, Access $access) {
69
+        parent::__construct($ldap);
70
+        $this->configuration = $configuration;
71
+        if(is_null(Wizard::$l)) {
72
+            Wizard::$l = \OC::$server->getL10N('user_ldap');
73
+        }
74
+        $this->access = $access;
75
+        $this->result = new WizardResult();
76
+    }
77
+
78
+    public function  __destruct() {
79
+        if($this->result->hasChanges()) {
80
+            $this->configuration->saveConfiguration();
81
+        }
82
+    }
83
+
84
+    /**
85
+     * counts entries in the LDAP directory
86
+     *
87
+     * @param string $filter the LDAP search filter
88
+     * @param string $type a string being either 'users' or 'groups';
89
+     * @return bool|int
90
+     * @throws \Exception
91
+     */
92
+    public function countEntries($filter, $type) {
93
+        $reqs = array('ldapHost', 'ldapPort', 'ldapBase');
94
+        if($type === 'users') {
95
+            $reqs[] = 'ldapUserFilter';
96
+        }
97
+        if(!$this->checkRequirements($reqs)) {
98
+            throw new \Exception('Requirements not met', 400);
99
+        }
100
+
101
+        $attr = array('dn'); // default
102
+        $limit = 1001;
103
+        if($type === 'groups') {
104
+            $result =  $this->access->countGroups($filter, $attr, $limit);
105
+        } else if($type === 'users') {
106
+            $result = $this->access->countUsers($filter, $attr, $limit);
107
+        } else if ($type === 'objects') {
108
+            $result = $this->access->countObjects($limit);
109
+        } else {
110
+            throw new \Exception('Internal error: Invalid object type', 500);
111
+        }
112
+
113
+        return $result;
114
+    }
115
+
116
+    /**
117
+     * formats the return value of a count operation to the string to be
118
+     * inserted.
119
+     *
120
+     * @param bool|int $count
121
+     * @return int|string
122
+     */
123
+    private function formatCountResult($count) {
124
+        $formatted = ($count !== false) ? $count : 0;
125
+        if($formatted > 1000) {
126
+            $formatted = '> 1000';
127
+        }
128
+        return $formatted;
129
+    }
130
+
131
+    public function countGroups() {
132
+        $filter = $this->configuration->ldapGroupFilter;
133
+
134
+        if(empty($filter)) {
135
+            $output = self::$l->n('%s group found', '%s groups found', 0, array(0));
136
+            $this->result->addChange('ldap_group_count', $output);
137
+            return $this->result;
138
+        }
139
+
140
+        try {
141
+            $groupsTotal = $this->formatCountResult($this->countEntries($filter, 'groups'));
142
+        } catch (\Exception $e) {
143
+            //400 can be ignored, 500 is forwarded
144
+            if($e->getCode() === 500) {
145
+                throw $e;
146
+            }
147
+            return false;
148
+        }
149
+        $output = self::$l->n('%s group found', '%s groups found', $groupsTotal, array($groupsTotal));
150
+        $this->result->addChange('ldap_group_count', $output);
151
+        return $this->result;
152
+    }
153
+
154
+    /**
155
+     * @return WizardResult
156
+     * @throws \Exception
157
+     */
158
+    public function countUsers() {
159
+        $filter = $this->access->getFilterForUserCount();
160
+
161
+        $usersTotal = $this->formatCountResult($this->countEntries($filter, 'users'));
162
+        $output = self::$l->n('%s user found', '%s users found', $usersTotal, array($usersTotal));
163
+        $this->result->addChange('ldap_user_count', $output);
164
+        return $this->result;
165
+    }
166
+
167
+    /**
168
+     * counts any objects in the currently set base dn
169
+     *
170
+     * @return WizardResult
171
+     * @throws \Exception
172
+     */
173
+    public function countInBaseDN() {
174
+        // we don't need to provide a filter in this case
175
+        $total = $this->countEntries(null, 'objects');
176
+        if($total === false) {
177
+            throw new \Exception('invalid results received');
178
+        }
179
+        $this->result->addChange('ldap_test_base', $total);
180
+        return $this->result;
181
+    }
182
+
183
+    /**
184
+     * counts users with a specified attribute
185
+     * @param string $attr
186
+     * @param bool $existsCheck
187
+     * @return int|bool
188
+     */
189
+    public function countUsersWithAttribute($attr, $existsCheck = false) {
190
+        if(!$this->checkRequirements(array('ldapHost',
191
+                                            'ldapPort',
192
+                                            'ldapBase',
193
+                                            'ldapUserFilter',
194
+                                            ))) {
195
+            return  false;
196
+        }
197
+
198
+        $filter = $this->access->combineFilterWithAnd(array(
199
+            $this->configuration->ldapUserFilter,
200
+            $attr . '=*'
201
+        ));
202
+
203
+        $limit = ($existsCheck === false) ? null : 1;
204
+
205
+        return $this->access->countUsers($filter, array('dn'), $limit);
206
+    }
207
+
208
+    /**
209
+     * detects the display name attribute. If a setting is already present that
210
+     * returns at least one hit, the detection will be canceled.
211
+     * @return WizardResult|bool
212
+     * @throws \Exception
213
+     */
214
+    public function detectUserDisplayNameAttribute() {
215
+        if(!$this->checkRequirements(array('ldapHost',
216
+                                        'ldapPort',
217
+                                        'ldapBase',
218
+                                        'ldapUserFilter',
219
+                                        ))) {
220
+            return  false;
221
+        }
222
+
223
+        $attr = $this->configuration->ldapUserDisplayName;
224
+        if ($attr !== '' && $attr !== 'displayName') {
225
+            // most likely not the default value with upper case N,
226
+            // verify it still produces a result
227
+            $count = intval($this->countUsersWithAttribute($attr, true));
228
+            if($count > 0) {
229
+                //no change, but we sent it back to make sure the user interface
230
+                //is still correct, even if the ajax call was cancelled meanwhile
231
+                $this->result->addChange('ldap_display_name', $attr);
232
+                return $this->result;
233
+            }
234
+        }
235
+
236
+        // first attribute that has at least one result wins
237
+        $displayNameAttrs = array('displayname', 'cn');
238
+        foreach ($displayNameAttrs as $attr) {
239
+            $count = intval($this->countUsersWithAttribute($attr, true));
240
+
241
+            if($count > 0) {
242
+                $this->applyFind('ldap_display_name', $attr);
243
+                return $this->result;
244
+            }
245
+        };
246
+
247
+        throw new \Exception(self::$l->t('Could not detect user display name attribute. Please specify it yourself in advanced LDAP settings.'));
248
+    }
249
+
250
+    /**
251
+     * detects the most often used email attribute for users applying to the
252
+     * user list filter. If a setting is already present that returns at least
253
+     * one hit, the detection will be canceled.
254
+     * @return WizardResult|bool
255
+     */
256
+    public function detectEmailAttribute() {
257
+        if(!$this->checkRequirements(array('ldapHost',
258
+                                            'ldapPort',
259
+                                            'ldapBase',
260
+                                            'ldapUserFilter',
261
+                                            ))) {
262
+            return  false;
263
+        }
264
+
265
+        $attr = $this->configuration->ldapEmailAttribute;
266
+        if ($attr !== '') {
267
+            $count = intval($this->countUsersWithAttribute($attr, true));
268
+            if($count > 0) {
269
+                return false;
270
+            }
271
+            $writeLog = true;
272
+        } else {
273
+            $writeLog = false;
274
+        }
275
+
276
+        $emailAttributes = array('mail', 'mailPrimaryAddress');
277
+        $winner = '';
278
+        $maxUsers = 0;
279
+        foreach($emailAttributes as $attr) {
280
+            $count = $this->countUsersWithAttribute($attr);
281
+            if($count > $maxUsers) {
282
+                $maxUsers = $count;
283
+                $winner = $attr;
284
+            }
285
+        }
286
+
287
+        if($winner !== '') {
288
+            $this->applyFind('ldap_email_attr', $winner);
289
+            if($writeLog) {
290
+                \OCP\Util::writeLog('user_ldap', 'The mail attribute has ' .
291
+                    'automatically been reset, because the original value ' .
292
+                    'did not return any results.', \OCP\Util::INFO);
293
+            }
294
+        }
295
+
296
+        return $this->result;
297
+    }
298
+
299
+    /**
300
+     * @return WizardResult
301
+     * @throws \Exception
302
+     */
303
+    public function determineAttributes() {
304
+        if(!$this->checkRequirements(array('ldapHost',
305
+                                            'ldapPort',
306
+                                            'ldapBase',
307
+                                            'ldapUserFilter',
308
+                                            ))) {
309
+            return  false;
310
+        }
311
+
312
+        $attributes = $this->getUserAttributes();
313
+
314
+        natcasesort($attributes);
315
+        $attributes = array_values($attributes);
316
+
317
+        $this->result->addOptions('ldap_loginfilter_attributes', $attributes);
318
+
319
+        $selected = $this->configuration->ldapLoginFilterAttributes;
320
+        if(is_array($selected) && !empty($selected)) {
321
+            $this->result->addChange('ldap_loginfilter_attributes', $selected);
322
+        }
323
+
324
+        return $this->result;
325
+    }
326
+
327
+    /**
328
+     * detects the available LDAP attributes
329
+     * @return array|false The instance's WizardResult instance
330
+     * @throws \Exception
331
+     */
332
+    private function getUserAttributes() {
333
+        if(!$this->checkRequirements(array('ldapHost',
334
+                                            'ldapPort',
335
+                                            'ldapBase',
336
+                                            'ldapUserFilter',
337
+                                            ))) {
338
+            return  false;
339
+        }
340
+        $cr = $this->getConnection();
341
+        if(!$cr) {
342
+            throw new \Exception('Could not connect to LDAP');
343
+        }
344
+
345
+        $base = $this->configuration->ldapBase[0];
346
+        $filter = $this->configuration->ldapUserFilter;
347
+        $rr = $this->ldap->search($cr, $base, $filter, array(), 1, 1);
348
+        if(!$this->ldap->isResource($rr)) {
349
+            return false;
350
+        }
351
+        $er = $this->ldap->firstEntry($cr, $rr);
352
+        $attributes = $this->ldap->getAttributes($cr, $er);
353
+        $pureAttributes = array();
354
+        for($i = 0; $i < $attributes['count']; $i++) {
355
+            $pureAttributes[] = $attributes[$i];
356
+        }
357
+
358
+        return $pureAttributes;
359
+    }
360
+
361
+    /**
362
+     * detects the available LDAP groups
363
+     * @return WizardResult|false the instance's WizardResult instance
364
+     */
365
+    public function determineGroupsForGroups() {
366
+        return $this->determineGroups('ldap_groupfilter_groups',
367
+                                        'ldapGroupFilterGroups',
368
+                                        false);
369
+    }
370
+
371
+    /**
372
+     * detects the available LDAP groups
373
+     * @return WizardResult|false the instance's WizardResult instance
374
+     */
375
+    public function determineGroupsForUsers() {
376
+        return $this->determineGroups('ldap_userfilter_groups',
377
+                                        'ldapUserFilterGroups');
378
+    }
379
+
380
+    /**
381
+     * detects the available LDAP groups
382
+     * @param string $dbKey
383
+     * @param string $confKey
384
+     * @param bool $testMemberOf
385
+     * @return WizardResult|false the instance's WizardResult instance
386
+     * @throws \Exception
387
+     */
388
+    private function determineGroups($dbKey, $confKey, $testMemberOf = true) {
389
+        if(!$this->checkRequirements(array('ldapHost',
390
+                                            'ldapPort',
391
+                                            'ldapBase',
392
+                                            ))) {
393
+            return  false;
394
+        }
395
+        $cr = $this->getConnection();
396
+        if(!$cr) {
397
+            throw new \Exception('Could not connect to LDAP');
398
+        }
399
+
400
+        $this->fetchGroups($dbKey, $confKey);
401
+
402
+        if($testMemberOf) {
403
+            $this->configuration->hasMemberOfFilterSupport = $this->testMemberOf();
404
+            $this->result->markChange();
405
+            if(!$this->configuration->hasMemberOfFilterSupport) {
406
+                throw new \Exception('memberOf is not supported by the server');
407
+            }
408
+        }
409
+
410
+        return $this->result;
411
+    }
412
+
413
+    /**
414
+     * fetches all groups from LDAP and adds them to the result object
415
+     *
416
+     * @param string $dbKey
417
+     * @param string $confKey
418
+     * @return array $groupEntries
419
+     * @throws \Exception
420
+     */
421
+    public function fetchGroups($dbKey, $confKey) {
422
+        $obclasses = array('posixGroup', 'group', 'zimbraDistributionList', 'groupOfNames', 'groupOfUniqueNames');
423
+
424
+        $filterParts = array();
425
+        foreach($obclasses as $obclass) {
426
+            $filterParts[] = 'objectclass='.$obclass;
427
+        }
428
+        //we filter for everything
429
+        //- that looks like a group and
430
+        //- has the group display name set
431
+        $filter = $this->access->combineFilterWithOr($filterParts);
432
+        $filter = $this->access->combineFilterWithAnd(array($filter, 'cn=*'));
433
+
434
+        $groupNames = array();
435
+        $groupEntries = array();
436
+        $limit = 400;
437
+        $offset = 0;
438
+        do {
439
+            // we need to request dn additionally here, otherwise memberOf
440
+            // detection will fail later
441
+            $result = $this->access->searchGroups($filter, array('cn', 'dn'), $limit, $offset);
442
+            foreach($result as $item) {
443
+                if(!isset($item['cn']) && !is_array($item['cn']) && !isset($item['cn'][0])) {
444
+                    // just in case - no issue known
445
+                    continue;
446
+                }
447
+                $groupNames[] = $item['cn'][0];
448
+                $groupEntries[] = $item;
449
+            }
450
+            $offset += $limit;
451
+        } while ($this->access->hasMoreResults());
452
+
453
+        if(count($groupNames) > 0) {
454
+            natsort($groupNames);
455
+            $this->result->addOptions($dbKey, array_values($groupNames));
456
+        } else {
457
+            throw new \Exception(self::$l->t('Could not find the desired feature'));
458
+        }
459
+
460
+        $setFeatures = $this->configuration->$confKey;
461
+        if(is_array($setFeatures) && !empty($setFeatures)) {
462
+            //something is already configured? pre-select it.
463
+            $this->result->addChange($dbKey, $setFeatures);
464
+        }
465
+        return $groupEntries;
466
+    }
467
+
468
+    public function determineGroupMemberAssoc() {
469
+        if(!$this->checkRequirements(array('ldapHost',
470
+                                            'ldapPort',
471
+                                            'ldapGroupFilter',
472
+                                            ))) {
473
+            return  false;
474
+        }
475
+        $attribute = $this->detectGroupMemberAssoc();
476
+        if($attribute === false) {
477
+            return false;
478
+        }
479
+        $this->configuration->setConfiguration(array('ldapGroupMemberAssocAttr' => $attribute));
480
+        $this->result->addChange('ldap_group_member_assoc_attribute', $attribute);
481
+
482
+        return $this->result;
483
+    }
484
+
485
+    /**
486
+     * Detects the available object classes
487
+     * @return WizardResult|false the instance's WizardResult instance
488
+     * @throws \Exception
489
+     */
490
+    public function determineGroupObjectClasses() {
491
+        if(!$this->checkRequirements(array('ldapHost',
492
+                                            'ldapPort',
493
+                                            'ldapBase',
494
+                                            ))) {
495
+            return  false;
496
+        }
497
+        $cr = $this->getConnection();
498
+        if(!$cr) {
499
+            throw new \Exception('Could not connect to LDAP');
500
+        }
501
+
502
+        $obclasses = array('groupOfNames', 'groupOfUniqueNames', 'group', 'posixGroup', '*');
503
+        $this->determineFeature($obclasses,
504
+                                'objectclass',
505
+                                'ldap_groupfilter_objectclass',
506
+                                'ldapGroupFilterObjectclass',
507
+                                false);
508
+
509
+        return $this->result;
510
+    }
511
+
512
+    /**
513
+     * detects the available object classes
514
+     * @return WizardResult
515
+     * @throws \Exception
516
+     */
517
+    public function determineUserObjectClasses() {
518
+        if(!$this->checkRequirements(array('ldapHost',
519
+                                            'ldapPort',
520
+                                            'ldapBase',
521
+                                            ))) {
522
+            return  false;
523
+        }
524
+        $cr = $this->getConnection();
525
+        if(!$cr) {
526
+            throw new \Exception('Could not connect to LDAP');
527
+        }
528
+
529
+        $obclasses = array('inetOrgPerson', 'person', 'organizationalPerson',
530
+                            'user', 'posixAccount', '*');
531
+        $filter = $this->configuration->ldapUserFilter;
532
+        //if filter is empty, it is probably the first time the wizard is called
533
+        //then, apply suggestions.
534
+        $this->determineFeature($obclasses,
535
+                                'objectclass',
536
+                                'ldap_userfilter_objectclass',
537
+                                'ldapUserFilterObjectclass',
538
+                                empty($filter));
539
+
540
+        return $this->result;
541
+    }
542
+
543
+    /**
544
+     * @return WizardResult|false
545
+     * @throws \Exception
546
+     */
547
+    public function getGroupFilter() {
548
+        if(!$this->checkRequirements(array('ldapHost',
549
+                                            'ldapPort',
550
+                                            'ldapBase',
551
+                                            ))) {
552
+            return false;
553
+        }
554
+        //make sure the use display name is set
555
+        $displayName = $this->configuration->ldapGroupDisplayName;
556
+        if ($displayName === '') {
557
+            $d = $this->configuration->getDefaults();
558
+            $this->applyFind('ldap_group_display_name',
559
+                                $d['ldap_group_display_name']);
560
+        }
561
+        $filter = $this->composeLdapFilter(self::LFILTER_GROUP_LIST);
562
+
563
+        $this->applyFind('ldap_group_filter', $filter);
564
+        return $this->result;
565
+    }
566
+
567
+    /**
568
+     * @return WizardResult|false
569
+     * @throws \Exception
570
+     */
571
+    public function getUserListFilter() {
572
+        if(!$this->checkRequirements(array('ldapHost',
573
+                                            'ldapPort',
574
+                                            'ldapBase',
575
+                                            ))) {
576
+            return false;
577
+        }
578
+        //make sure the use display name is set
579
+        $displayName = $this->configuration->ldapUserDisplayName;
580
+        if ($displayName === '') {
581
+            $d = $this->configuration->getDefaults();
582
+            $this->applyFind('ldap_display_name', $d['ldap_display_name']);
583
+        }
584
+        $filter = $this->composeLdapFilter(self::LFILTER_USER_LIST);
585
+        if(!$filter) {
586
+            throw new \Exception('Cannot create filter');
587
+        }
588
+
589
+        $this->applyFind('ldap_userlist_filter', $filter);
590
+        return $this->result;
591
+    }
592
+
593
+    /**
594
+     * @return bool|WizardResult
595
+     * @throws \Exception
596
+     */
597
+    public function getUserLoginFilter() {
598
+        if(!$this->checkRequirements(array('ldapHost',
599
+                                            'ldapPort',
600
+                                            'ldapBase',
601
+                                            'ldapUserFilter',
602
+                                            ))) {
603
+            return false;
604
+        }
605
+
606
+        $filter = $this->composeLdapFilter(self::LFILTER_LOGIN);
607
+        if(!$filter) {
608
+            throw new \Exception('Cannot create filter');
609
+        }
610
+
611
+        $this->applyFind('ldap_login_filter', $filter);
612
+        return $this->result;
613
+    }
614
+
615
+    /**
616
+     * @return bool|WizardResult
617
+     * @param string $loginName
618
+     * @throws \Exception
619
+     */
620
+    public function testLoginName($loginName) {
621
+        if(!$this->checkRequirements(array('ldapHost',
622
+            'ldapPort',
623
+            'ldapBase',
624
+            'ldapLoginFilter',
625
+        ))) {
626
+            return false;
627
+        }
628
+
629
+        $cr = $this->access->connection->getConnectionResource();
630
+        if(!$this->ldap->isResource($cr)) {
631
+            throw new \Exception('connection error');
632
+        }
633
+
634
+        if(mb_strpos($this->access->connection->ldapLoginFilter, '%uid', 0, 'UTF-8')
635
+            === false) {
636
+            throw new \Exception('missing placeholder');
637
+        }
638
+
639
+        $users = $this->access->countUsersByLoginName($loginName);
640
+        if($this->ldap->errno($cr) !== 0) {
641
+            throw new \Exception($this->ldap->error($cr));
642
+        }
643
+        $filter = str_replace('%uid', $loginName, $this->access->connection->ldapLoginFilter);
644
+        $this->result->addChange('ldap_test_loginname', $users);
645
+        $this->result->addChange('ldap_test_effective_filter', $filter);
646
+        return $this->result;
647
+    }
648
+
649
+    /**
650
+     * Tries to determine the port, requires given Host, User DN and Password
651
+     * @return WizardResult|false WizardResult on success, false otherwise
652
+     * @throws \Exception
653
+     */
654
+    public function guessPortAndTLS() {
655
+        if(!$this->checkRequirements(array('ldapHost',
656
+                                            ))) {
657
+            return false;
658
+        }
659
+        $this->checkHost();
660
+        $portSettings = $this->getPortSettingsToTry();
661
+
662
+        if(!is_array($portSettings)) {
663
+            throw new \Exception(print_r($portSettings, true));
664
+        }
665
+
666
+        //proceed from the best configuration and return on first success
667
+        foreach($portSettings as $setting) {
668
+            $p = $setting['port'];
669
+            $t = $setting['tls'];
670
+            \OCP\Util::writeLog('user_ldap', 'Wiz: trying port '. $p . ', TLS '. $t, \OCP\Util::DEBUG);
671
+            //connectAndBind may throw Exception, it needs to be catched by the
672
+            //callee of this method
673
+
674
+            try {
675
+                $settingsFound = $this->connectAndBind($p, $t);
676
+            } catch (\Exception $e) {
677
+                // any reply other than -1 (= cannot connect) is already okay,
678
+                // because then we found the server
679
+                // unavailable startTLS returns -11
680
+                if($e->getCode() > 0) {
681
+                    $settingsFound = true;
682
+                } else {
683
+                    throw $e;
684
+                }
685
+            }
686
+
687
+            if ($settingsFound === true) {
688
+                $config = array(
689
+                    'ldapPort' => $p,
690
+                    'ldapTLS' => intval($t)
691
+                );
692
+                $this->configuration->setConfiguration($config);
693
+                \OCP\Util::writeLog('user_ldap', 'Wiz: detected Port ' . $p, \OCP\Util::DEBUG);
694
+                $this->result->addChange('ldap_port', $p);
695
+                return $this->result;
696
+            }
697
+        }
698
+
699
+        //custom port, undetected (we do not brute force)
700
+        return false;
701
+    }
702
+
703
+    /**
704
+     * tries to determine a base dn from User DN or LDAP Host
705
+     * @return WizardResult|false WizardResult on success, false otherwise
706
+     */
707
+    public function guessBaseDN() {
708
+        if(!$this->checkRequirements(array('ldapHost',
709
+                                            'ldapPort',
710
+                                            ))) {
711
+            return false;
712
+        }
713
+
714
+        //check whether a DN is given in the agent name (99.9% of all cases)
715
+        $base = null;
716
+        $i = stripos($this->configuration->ldapAgentName, 'dc=');
717
+        if($i !== false) {
718
+            $base = substr($this->configuration->ldapAgentName, $i);
719
+            if($this->testBaseDN($base)) {
720
+                $this->applyFind('ldap_base', $base);
721
+                return $this->result;
722
+            }
723
+        }
724
+
725
+        //this did not help :(
726
+        //Let's see whether we can parse the Host URL and convert the domain to
727
+        //a base DN
728
+        $helper = new Helper(\OC::$server->getConfig());
729
+        $domain = $helper->getDomainFromURL($this->configuration->ldapHost);
730
+        if(!$domain) {
731
+            return false;
732
+        }
733
+
734
+        $dparts = explode('.', $domain);
735
+        while(count($dparts) > 0) {
736
+            $base2 = 'dc=' . implode(',dc=', $dparts);
737
+            if ($base !== $base2 && $this->testBaseDN($base2)) {
738
+                $this->applyFind('ldap_base', $base2);
739
+                return $this->result;
740
+            }
741
+            array_shift($dparts);
742
+        }
743
+
744
+        return false;
745
+    }
746
+
747
+    /**
748
+     * sets the found value for the configuration key in the WizardResult
749
+     * as well as in the Configuration instance
750
+     * @param string $key the configuration key
751
+     * @param string $value the (detected) value
752
+     *
753
+     */
754
+    private function applyFind($key, $value) {
755
+        $this->result->addChange($key, $value);
756
+        $this->configuration->setConfiguration(array($key => $value));
757
+    }
758
+
759
+    /**
760
+     * Checks, whether a port was entered in the Host configuration
761
+     * field. In this case the port will be stripped off, but also stored as
762
+     * setting.
763
+     */
764
+    private function checkHost() {
765
+        $host = $this->configuration->ldapHost;
766
+        $hostInfo = parse_url($host);
767
+
768
+        //removes Port from Host
769
+        if(is_array($hostInfo) && isset($hostInfo['port'])) {
770
+            $port = $hostInfo['port'];
771
+            $host = str_replace(':'.$port, '', $host);
772
+            $this->applyFind('ldap_host', $host);
773
+            $this->applyFind('ldap_port', $port);
774
+        }
775
+    }
776
+
777
+    /**
778
+     * tries to detect the group member association attribute which is
779
+     * one of 'uniqueMember', 'memberUid', 'member', 'gidNumber'
780
+     * @return string|false, string with the attribute name, false on error
781
+     * @throws \Exception
782
+     */
783
+    private function detectGroupMemberAssoc() {
784
+        $possibleAttrs = array('uniqueMember', 'memberUid', 'member', 'gidNumber');
785
+        $filter = $this->configuration->ldapGroupFilter;
786
+        if(empty($filter)) {
787
+            return false;
788
+        }
789
+        $cr = $this->getConnection();
790
+        if(!$cr) {
791
+            throw new \Exception('Could not connect to LDAP');
792
+        }
793
+        $base = $this->configuration->ldapBase[0];
794
+        $rr = $this->ldap->search($cr, $base, $filter, $possibleAttrs, 0, 1000);
795
+        if(!$this->ldap->isResource($rr)) {
796
+            return false;
797
+        }
798
+        $er = $this->ldap->firstEntry($cr, $rr);
799
+        while(is_resource($er)) {
800
+            $this->ldap->getDN($cr, $er);
801
+            $attrs = $this->ldap->getAttributes($cr, $er);
802
+            $result = array();
803
+            $possibleAttrsCount = count($possibleAttrs);
804
+            for($i = 0; $i < $possibleAttrsCount; $i++) {
805
+                if(isset($attrs[$possibleAttrs[$i]])) {
806
+                    $result[$possibleAttrs[$i]] = $attrs[$possibleAttrs[$i]]['count'];
807
+                }
808
+            }
809
+            if(!empty($result)) {
810
+                natsort($result);
811
+                return key($result);
812
+            }
813
+
814
+            $er = $this->ldap->nextEntry($cr, $er);
815
+        }
816
+
817
+        return false;
818
+    }
819
+
820
+    /**
821
+     * Checks whether for a given BaseDN results will be returned
822
+     * @param string $base the BaseDN to test
823
+     * @return bool true on success, false otherwise
824
+     * @throws \Exception
825
+     */
826
+    private function testBaseDN($base) {
827
+        $cr = $this->getConnection();
828
+        if(!$cr) {
829
+            throw new \Exception('Could not connect to LDAP');
830
+        }
831
+
832
+        //base is there, let's validate it. If we search for anything, we should
833
+        //get a result set > 0 on a proper base
834
+        $rr = $this->ldap->search($cr, $base, 'objectClass=*', array('dn'), 0, 1);
835
+        if(!$this->ldap->isResource($rr)) {
836
+            $errorNo  = $this->ldap->errno($cr);
837
+            $errorMsg = $this->ldap->error($cr);
838
+            \OCP\Util::writeLog('user_ldap', 'Wiz: Could not search base '.$base.
839
+                            ' Error '.$errorNo.': '.$errorMsg, \OCP\Util::INFO);
840
+            return false;
841
+        }
842
+        $entries = $this->ldap->countEntries($cr, $rr);
843
+        return ($entries !== false) && ($entries > 0);
844
+    }
845
+
846
+    /**
847
+     * Checks whether the server supports memberOf in LDAP Filter.
848
+     * Note: at least in OpenLDAP, availability of memberOf is dependent on
849
+     * a configured objectClass. I.e. not necessarily for all available groups
850
+     * memberOf does work.
851
+     *
852
+     * @return bool true if it does, false otherwise
853
+     * @throws \Exception
854
+     */
855
+    private function testMemberOf() {
856
+        $cr = $this->getConnection();
857
+        if(!$cr) {
858
+            throw new \Exception('Could not connect to LDAP');
859
+        }
860
+        $result = $this->access->countUsers('memberOf=*', array('memberOf'), 1);
861
+        if(is_int($result) &&  $result > 0) {
862
+            return true;
863
+        }
864
+        return false;
865
+    }
866
+
867
+    /**
868
+     * creates an LDAP Filter from given configuration
869
+     * @param integer $filterType int, for which use case the filter shall be created
870
+     * can be any of self::LFILTER_USER_LIST, self::LFILTER_LOGIN or
871
+     * self::LFILTER_GROUP_LIST
872
+     * @return string|false string with the filter on success, false otherwise
873
+     * @throws \Exception
874
+     */
875
+    private function composeLdapFilter($filterType) {
876
+        $filter = '';
877
+        $parts = 0;
878
+        switch ($filterType) {
879
+            case self::LFILTER_USER_LIST:
880
+                $objcs = $this->configuration->ldapUserFilterObjectclass;
881
+                //glue objectclasses
882
+                if(is_array($objcs) && count($objcs) > 0) {
883
+                    $filter .= '(|';
884
+                    foreach($objcs as $objc) {
885
+                        $filter .= '(objectclass=' . $objc . ')';
886
+                    }
887
+                    $filter .= ')';
888
+                    $parts++;
889
+                }
890
+                //glue group memberships
891
+                if($this->configuration->hasMemberOfFilterSupport) {
892
+                    $cns = $this->configuration->ldapUserFilterGroups;
893
+                    if(is_array($cns) && count($cns) > 0) {
894
+                        $filter .= '(|';
895
+                        $cr = $this->getConnection();
896
+                        if(!$cr) {
897
+                            throw new \Exception('Could not connect to LDAP');
898
+                        }
899
+                        $base = $this->configuration->ldapBase[0];
900
+                        foreach($cns as $cn) {
901
+                            $rr = $this->ldap->search($cr, $base, 'cn=' . $cn, array('dn', 'primaryGroupToken'));
902
+                            if(!$this->ldap->isResource($rr)) {
903
+                                continue;
904
+                            }
905
+                            $er = $this->ldap->firstEntry($cr, $rr);
906
+                            $attrs = $this->ldap->getAttributes($cr, $er);
907
+                            $dn = $this->ldap->getDN($cr, $er);
908
+                            if ($dn === false || $dn === '') {
909
+                                continue;
910
+                            }
911
+                            $filterPart = '(memberof=' . $dn . ')';
912
+                            if(isset($attrs['primaryGroupToken'])) {
913
+                                $pgt = $attrs['primaryGroupToken'][0];
914
+                                $primaryFilterPart = '(primaryGroupID=' . $pgt .')';
915
+                                $filterPart = '(|' . $filterPart . $primaryFilterPart . ')';
916
+                            }
917
+                            $filter .= $filterPart;
918
+                        }
919
+                        $filter .= ')';
920
+                    }
921
+                    $parts++;
922
+                }
923
+                //wrap parts in AND condition
924
+                if($parts > 1) {
925
+                    $filter = '(&' . $filter . ')';
926
+                }
927
+                if ($filter === '') {
928
+                    $filter = '(objectclass=*)';
929
+                }
930
+                break;
931
+
932
+            case self::LFILTER_GROUP_LIST:
933
+                $objcs = $this->configuration->ldapGroupFilterObjectclass;
934
+                //glue objectclasses
935
+                if(is_array($objcs) && count($objcs) > 0) {
936
+                    $filter .= '(|';
937
+                    foreach($objcs as $objc) {
938
+                        $filter .= '(objectclass=' . $objc . ')';
939
+                    }
940
+                    $filter .= ')';
941
+                    $parts++;
942
+                }
943
+                //glue group memberships
944
+                $cns = $this->configuration->ldapGroupFilterGroups;
945
+                if(is_array($cns) && count($cns) > 0) {
946
+                    $filter .= '(|';
947
+                    foreach($cns as $cn) {
948
+                        $filter .= '(cn=' . $cn . ')';
949
+                    }
950
+                    $filter .= ')';
951
+                }
952
+                $parts++;
953
+                //wrap parts in AND condition
954
+                if($parts > 1) {
955
+                    $filter = '(&' . $filter . ')';
956
+                }
957
+                break;
958
+
959
+            case self::LFILTER_LOGIN:
960
+                $ulf = $this->configuration->ldapUserFilter;
961
+                $loginpart = '=%uid';
962
+                $filterUsername = '';
963
+                $userAttributes = $this->getUserAttributes();
964
+                $userAttributes = array_change_key_case(array_flip($userAttributes));
965
+                $parts = 0;
966
+
967
+                if($this->configuration->ldapLoginFilterUsername === '1') {
968
+                    $attr = '';
969
+                    if(isset($userAttributes['uid'])) {
970
+                        $attr = 'uid';
971
+                    } else if(isset($userAttributes['samaccountname'])) {
972
+                        $attr = 'samaccountname';
973
+                    } else if(isset($userAttributes['cn'])) {
974
+                        //fallback
975
+                        $attr = 'cn';
976
+                    }
977
+                    if ($attr !== '') {
978
+                        $filterUsername = '(' . $attr . $loginpart . ')';
979
+                        $parts++;
980
+                    }
981
+                }
982
+
983
+                $filterEmail = '';
984
+                if($this->configuration->ldapLoginFilterEmail === '1') {
985
+                    $filterEmail = '(|(mailPrimaryAddress=%uid)(mail=%uid))';
986
+                    $parts++;
987
+                }
988
+
989
+                $filterAttributes = '';
990
+                $attrsToFilter = $this->configuration->ldapLoginFilterAttributes;
991
+                if(is_array($attrsToFilter) && count($attrsToFilter) > 0) {
992
+                    $filterAttributes = '(|';
993
+                    foreach($attrsToFilter as $attribute) {
994
+                        $filterAttributes .= '(' . $attribute . $loginpart . ')';
995
+                    }
996
+                    $filterAttributes .= ')';
997
+                    $parts++;
998
+                }
999
+
1000
+                $filterLogin = '';
1001
+                if($parts > 1) {
1002
+                    $filterLogin = '(|';
1003
+                }
1004
+                $filterLogin .= $filterUsername;
1005
+                $filterLogin .= $filterEmail;
1006
+                $filterLogin .= $filterAttributes;
1007
+                if($parts > 1) {
1008
+                    $filterLogin .= ')';
1009
+                }
1010
+
1011
+                $filter = '(&'.$ulf.$filterLogin.')';
1012
+                break;
1013
+        }
1014
+
1015
+        \OCP\Util::writeLog('user_ldap', 'Wiz: Final filter '.$filter, \OCP\Util::DEBUG);
1016
+
1017
+        return $filter;
1018
+    }
1019
+
1020
+    /**
1021
+     * Connects and Binds to an LDAP Server
1022
+     *
1023
+     * @param int $port the port to connect with
1024
+     * @param bool $tls whether startTLS is to be used
1025
+     * @return bool
1026
+     * @throws \Exception
1027
+     */
1028
+    private function connectAndBind($port, $tls) {
1029
+        //connect, does not really trigger any server communication
1030
+        $host = $this->configuration->ldapHost;
1031
+        $hostInfo = parse_url($host);
1032
+        if(!$hostInfo) {
1033
+            throw new \Exception(self::$l->t('Invalid Host'));
1034
+        }
1035
+        \OCP\Util::writeLog('user_ldap', 'Wiz: Attempting to connect ', \OCP\Util::DEBUG);
1036
+        $cr = $this->ldap->connect($host, $port);
1037
+        if(!is_resource($cr)) {
1038
+            throw new \Exception(self::$l->t('Invalid Host'));
1039
+        }
1040
+
1041
+        //set LDAP options
1042
+        $this->ldap->setOption($cr, LDAP_OPT_PROTOCOL_VERSION, 3);
1043
+        $this->ldap->setOption($cr, LDAP_OPT_REFERRALS, 0);
1044
+        $this->ldap->setOption($cr, LDAP_OPT_NETWORK_TIMEOUT, self::LDAP_NW_TIMEOUT);
1045
+
1046
+        try {
1047
+            if($tls) {
1048
+                $isTlsWorking = @$this->ldap->startTls($cr);
1049
+                if(!$isTlsWorking) {
1050
+                    return false;
1051
+                }
1052
+            }
1053
+
1054
+            \OCP\Util::writeLog('user_ldap', 'Wiz: Attemping to Bind ', \OCP\Util::DEBUG);
1055
+            //interesting part: do the bind!
1056
+            $login = $this->ldap->bind($cr,
1057
+                $this->configuration->ldapAgentName,
1058
+                $this->configuration->ldapAgentPassword
1059
+            );
1060
+            $errNo = $this->ldap->errno($cr);
1061
+            $error = ldap_error($cr);
1062
+            $this->ldap->unbind($cr);
1063
+        } catch(ServerNotAvailableException $e) {
1064
+            return false;
1065
+        }
1066
+
1067
+        if($login === true) {
1068
+            $this->ldap->unbind($cr);
1069
+            \OCP\Util::writeLog('user_ldap', 'Wiz: Bind successful to Port '. $port . ' TLS ' . intval($tls), \OCP\Util::DEBUG);
1070
+            return true;
1071
+        }
1072
+
1073
+        if($errNo === -1) {
1074
+            //host, port or TLS wrong
1075
+            return false;
1076
+        }
1077
+        throw new \Exception($error, $errNo);
1078
+    }
1079
+
1080
+    /**
1081
+     * checks whether a valid combination of agent and password has been
1082
+     * provided (either two values or nothing for anonymous connect)
1083
+     * @return bool, true if everything is fine, false otherwise
1084
+     */
1085
+    private function checkAgentRequirements() {
1086
+        $agent = $this->configuration->ldapAgentName;
1087
+        $pwd = $this->configuration->ldapAgentPassword;
1088
+
1089
+        return
1090
+            ($agent !== '' && $pwd !== '')
1091
+            ||  ($agent === '' && $pwd === '')
1092
+        ;
1093
+    }
1094
+
1095
+    /**
1096
+     * @param array $reqs
1097
+     * @return bool
1098
+     */
1099
+    private function checkRequirements($reqs) {
1100
+        $this->checkAgentRequirements();
1101
+        foreach($reqs as $option) {
1102
+            $value = $this->configuration->$option;
1103
+            if(empty($value)) {
1104
+                return false;
1105
+            }
1106
+        }
1107
+        return true;
1108
+    }
1109
+
1110
+    /**
1111
+     * does a cumulativeSearch on LDAP to get different values of a
1112
+     * specified attribute
1113
+     * @param string[] $filters array, the filters that shall be used in the search
1114
+     * @param string $attr the attribute of which a list of values shall be returned
1115
+     * @param int $dnReadLimit the amount of how many DNs should be analyzed.
1116
+     * The lower, the faster
1117
+     * @param string $maxF string. if not null, this variable will have the filter that
1118
+     * yields most result entries
1119
+     * @return array|false an array with the values on success, false otherwise
1120
+     */
1121
+    public function cumulativeSearchOnAttribute($filters, $attr, $dnReadLimit = 3, &$maxF = null) {
1122
+        $dnRead = array();
1123
+        $foundItems = array();
1124
+        $maxEntries = 0;
1125
+        if(!is_array($this->configuration->ldapBase)
1126
+           || !isset($this->configuration->ldapBase[0])) {
1127
+            return false;
1128
+        }
1129
+        $base = $this->configuration->ldapBase[0];
1130
+        $cr = $this->getConnection();
1131
+        if(!$this->ldap->isResource($cr)) {
1132
+            return false;
1133
+        }
1134
+        $lastFilter = null;
1135
+        if(isset($filters[count($filters)-1])) {
1136
+            $lastFilter = $filters[count($filters)-1];
1137
+        }
1138
+        foreach($filters as $filter) {
1139
+            if($lastFilter === $filter && count($foundItems) > 0) {
1140
+                //skip when the filter is a wildcard and results were found
1141
+                continue;
1142
+            }
1143
+            // 20k limit for performance and reason
1144
+            $rr = $this->ldap->search($cr, $base, $filter, array($attr), 0, 20000);
1145
+            if(!$this->ldap->isResource($rr)) {
1146
+                continue;
1147
+            }
1148
+            $entries = $this->ldap->countEntries($cr, $rr);
1149
+            $getEntryFunc = 'firstEntry';
1150
+            if(($entries !== false) && ($entries > 0)) {
1151
+                if(!is_null($maxF) && $entries > $maxEntries) {
1152
+                    $maxEntries = $entries;
1153
+                    $maxF = $filter;
1154
+                }
1155
+                $dnReadCount = 0;
1156
+                do {
1157
+                    $entry = $this->ldap->$getEntryFunc($cr, $rr);
1158
+                    $getEntryFunc = 'nextEntry';
1159
+                    if(!$this->ldap->isResource($entry)) {
1160
+                        continue 2;
1161
+                    }
1162
+                    $rr = $entry; //will be expected by nextEntry next round
1163
+                    $attributes = $this->ldap->getAttributes($cr, $entry);
1164
+                    $dn = $this->ldap->getDN($cr, $entry);
1165
+                    if($dn === false || in_array($dn, $dnRead)) {
1166
+                        continue;
1167
+                    }
1168
+                    $newItems = array();
1169
+                    $state = $this->getAttributeValuesFromEntry($attributes,
1170
+                                                                $attr,
1171
+                                                                $newItems);
1172
+                    $dnReadCount++;
1173
+                    $foundItems = array_merge($foundItems, $newItems);
1174
+                    $this->resultCache[$dn][$attr] = $newItems;
1175
+                    $dnRead[] = $dn;
1176
+                } while(($state === self::LRESULT_PROCESSED_SKIP
1177
+                        || $this->ldap->isResource($entry))
1178
+                        && ($dnReadLimit === 0 || $dnReadCount < $dnReadLimit));
1179
+            }
1180
+        }
1181
+
1182
+        return array_unique($foundItems);
1183
+    }
1184
+
1185
+    /**
1186
+     * determines if and which $attr are available on the LDAP server
1187
+     * @param string[] $objectclasses the objectclasses to use as search filter
1188
+     * @param string $attr the attribute to look for
1189
+     * @param string $dbkey the dbkey of the setting the feature is connected to
1190
+     * @param string $confkey the confkey counterpart for the $dbkey as used in the
1191
+     * Configuration class
1192
+     * @param bool $po whether the objectClass with most result entries
1193
+     * shall be pre-selected via the result
1194
+     * @return array|false list of found items.
1195
+     * @throws \Exception
1196
+     */
1197
+    private function determineFeature($objectclasses, $attr, $dbkey, $confkey, $po = false) {
1198
+        $cr = $this->getConnection();
1199
+        if(!$cr) {
1200
+            throw new \Exception('Could not connect to LDAP');
1201
+        }
1202
+        $p = 'objectclass=';
1203
+        foreach($objectclasses as $key => $value) {
1204
+            $objectclasses[$key] = $p.$value;
1205
+        }
1206
+        $maxEntryObjC = '';
1207
+
1208
+        //how deep to dig?
1209
+        //When looking for objectclasses, testing few entries is sufficient,
1210
+        $dig = 3;
1211
+
1212
+        $availableFeatures =
1213
+            $this->cumulativeSearchOnAttribute($objectclasses, $attr,
1214
+                                                $dig, $maxEntryObjC);
1215
+        if(is_array($availableFeatures)
1216
+           && count($availableFeatures) > 0) {
1217
+            natcasesort($availableFeatures);
1218
+            //natcasesort keeps indices, but we must get rid of them for proper
1219
+            //sorting in the web UI. Therefore: array_values
1220
+            $this->result->addOptions($dbkey, array_values($availableFeatures));
1221
+        } else {
1222
+            throw new \Exception(self::$l->t('Could not find the desired feature'));
1223
+        }
1224
+
1225
+        $setFeatures = $this->configuration->$confkey;
1226
+        if(is_array($setFeatures) && !empty($setFeatures)) {
1227
+            //something is already configured? pre-select it.
1228
+            $this->result->addChange($dbkey, $setFeatures);
1229
+        } else if ($po && $maxEntryObjC !== '') {
1230
+            //pre-select objectclass with most result entries
1231
+            $maxEntryObjC = str_replace($p, '', $maxEntryObjC);
1232
+            $this->applyFind($dbkey, $maxEntryObjC);
1233
+            $this->result->addChange($dbkey, $maxEntryObjC);
1234
+        }
1235
+
1236
+        return $availableFeatures;
1237
+    }
1238
+
1239
+    /**
1240
+     * appends a list of values fr
1241
+     * @param resource $result the return value from ldap_get_attributes
1242
+     * @param string $attribute the attribute values to look for
1243
+     * @param array &$known new values will be appended here
1244
+     * @return int, state on of the class constants LRESULT_PROCESSED_OK,
1245
+     * LRESULT_PROCESSED_INVALID or LRESULT_PROCESSED_SKIP
1246
+     */
1247
+    private function getAttributeValuesFromEntry($result, $attribute, &$known) {
1248
+        if(!is_array($result)
1249
+           || !isset($result['count'])
1250
+           || !$result['count'] > 0) {
1251
+            return self::LRESULT_PROCESSED_INVALID;
1252
+        }
1253
+
1254
+        // strtolower on all keys for proper comparison
1255
+        $result = \OCP\Util::mb_array_change_key_case($result);
1256
+        $attribute = strtolower($attribute);
1257
+        if(isset($result[$attribute])) {
1258
+            foreach($result[$attribute] as $key => $val) {
1259
+                if($key === 'count') {
1260
+                    continue;
1261
+                }
1262
+                if(!in_array($val, $known)) {
1263
+                    $known[] = $val;
1264
+                }
1265
+            }
1266
+            return self::LRESULT_PROCESSED_OK;
1267
+        } else {
1268
+            return self::LRESULT_PROCESSED_SKIP;
1269
+        }
1270
+    }
1271
+
1272
+    /**
1273
+     * @return bool|mixed
1274
+     */
1275
+    private function getConnection() {
1276
+        if(!is_null($this->cr)) {
1277
+            return $this->cr;
1278
+        }
1279
+
1280
+        $cr = $this->ldap->connect(
1281
+            $this->configuration->ldapHost,
1282
+            $this->configuration->ldapPort
1283
+        );
1284
+
1285
+        $this->ldap->setOption($cr, LDAP_OPT_PROTOCOL_VERSION, 3);
1286
+        $this->ldap->setOption($cr, LDAP_OPT_REFERRALS, 0);
1287
+        $this->ldap->setOption($cr, LDAP_OPT_NETWORK_TIMEOUT, self::LDAP_NW_TIMEOUT);
1288
+        if($this->configuration->ldapTLS === 1) {
1289
+            $this->ldap->startTls($cr);
1290
+        }
1291
+
1292
+        $lo = @$this->ldap->bind($cr,
1293
+                                    $this->configuration->ldapAgentName,
1294
+                                    $this->configuration->ldapAgentPassword);
1295
+        if($lo === true) {
1296
+            $this->$cr = $cr;
1297
+            return $cr;
1298
+        }
1299
+
1300
+        return false;
1301
+    }
1302
+
1303
+    /**
1304
+     * @return array
1305
+     */
1306
+    private function getDefaultLdapPortSettings() {
1307
+        static $settings = array(
1308
+                                array('port' => 7636, 'tls' => false),
1309
+                                array('port' =>  636, 'tls' => false),
1310
+                                array('port' => 7389, 'tls' => true),
1311
+                                array('port' =>  389, 'tls' => true),
1312
+                                array('port' => 7389, 'tls' => false),
1313
+                                array('port' =>  389, 'tls' => false),
1314
+                            );
1315
+        return $settings;
1316
+    }
1317
+
1318
+    /**
1319
+     * @return array
1320
+     */
1321
+    private function getPortSettingsToTry() {
1322
+        //389 ← LDAP / Unencrypted or StartTLS
1323
+        //636 ← LDAPS / SSL
1324
+        //7xxx ← UCS. need to be checked first, because both ports may be open
1325
+        $host = $this->configuration->ldapHost;
1326
+        $port = intval($this->configuration->ldapPort);
1327
+        $portSettings = array();
1328
+
1329
+        //In case the port is already provided, we will check this first
1330
+        if($port > 0) {
1331
+            $hostInfo = parse_url($host);
1332
+            if(!(is_array($hostInfo)
1333
+                && isset($hostInfo['scheme'])
1334
+                && stripos($hostInfo['scheme'], 'ldaps') !== false)) {
1335
+                $portSettings[] = array('port' => $port, 'tls' => true);
1336
+            }
1337
+            $portSettings[] =array('port' => $port, 'tls' => false);
1338
+        }
1339
+
1340
+        //default ports
1341
+        $portSettings = array_merge($portSettings,
1342
+                                    $this->getDefaultLdapPortSettings());
1343
+
1344
+        return $portSettings;
1345
+    }
1346 1346
 
1347 1347
 
1348 1348
 }
Please login to merge, or discard this patch.
Spacing   +149 added lines, -149 removed lines patch added patch discarded remove patch
@@ -68,7 +68,7 @@  discard block
 block discarded – undo
68 68
 	public function __construct(Configuration $configuration, ILDAPWrapper $ldap, Access $access) {
69 69
 		parent::__construct($ldap);
70 70
 		$this->configuration = $configuration;
71
-		if(is_null(Wizard::$l)) {
71
+		if (is_null(Wizard::$l)) {
72 72
 			Wizard::$l = \OC::$server->getL10N('user_ldap');
73 73
 		}
74 74
 		$this->access = $access;
@@ -76,7 +76,7 @@  discard block
 block discarded – undo
76 76
 	}
77 77
 
78 78
 	public function  __destruct() {
79
-		if($this->result->hasChanges()) {
79
+		if ($this->result->hasChanges()) {
80 80
 			$this->configuration->saveConfiguration();
81 81
 		}
82 82
 	}
@@ -91,18 +91,18 @@  discard block
 block discarded – undo
91 91
 	 */
92 92
 	public function countEntries($filter, $type) {
93 93
 		$reqs = array('ldapHost', 'ldapPort', 'ldapBase');
94
-		if($type === 'users') {
94
+		if ($type === 'users') {
95 95
 			$reqs[] = 'ldapUserFilter';
96 96
 		}
97
-		if(!$this->checkRequirements($reqs)) {
97
+		if (!$this->checkRequirements($reqs)) {
98 98
 			throw new \Exception('Requirements not met', 400);
99 99
 		}
100 100
 
101 101
 		$attr = array('dn'); // default
102 102
 		$limit = 1001;
103
-		if($type === 'groups') {
104
-			$result =  $this->access->countGroups($filter, $attr, $limit);
105
-		} else if($type === 'users') {
103
+		if ($type === 'groups') {
104
+			$result = $this->access->countGroups($filter, $attr, $limit);
105
+		} else if ($type === 'users') {
106 106
 			$result = $this->access->countUsers($filter, $attr, $limit);
107 107
 		} else if ($type === 'objects') {
108 108
 			$result = $this->access->countObjects($limit);
@@ -122,7 +122,7 @@  discard block
 block discarded – undo
122 122
 	 */
123 123
 	private function formatCountResult($count) {
124 124
 		$formatted = ($count !== false) ? $count : 0;
125
-		if($formatted > 1000) {
125
+		if ($formatted > 1000) {
126 126
 			$formatted = '> 1000';
127 127
 		}
128 128
 		return $formatted;
@@ -131,7 +131,7 @@  discard block
 block discarded – undo
131 131
 	public function countGroups() {
132 132
 		$filter = $this->configuration->ldapGroupFilter;
133 133
 
134
-		if(empty($filter)) {
134
+		if (empty($filter)) {
135 135
 			$output = self::$l->n('%s group found', '%s groups found', 0, array(0));
136 136
 			$this->result->addChange('ldap_group_count', $output);
137 137
 			return $this->result;
@@ -141,7 +141,7 @@  discard block
 block discarded – undo
141 141
 			$groupsTotal = $this->formatCountResult($this->countEntries($filter, 'groups'));
142 142
 		} catch (\Exception $e) {
143 143
 			//400 can be ignored, 500 is forwarded
144
-			if($e->getCode() === 500) {
144
+			if ($e->getCode() === 500) {
145 145
 				throw $e;
146 146
 			}
147 147
 			return false;
@@ -173,7 +173,7 @@  discard block
 block discarded – undo
173 173
 	public function countInBaseDN() {
174 174
 		// we don't need to provide a filter in this case
175 175
 		$total = $this->countEntries(null, 'objects');
176
-		if($total === false) {
176
+		if ($total === false) {
177 177
 			throw new \Exception('invalid results received');
178 178
 		}
179 179
 		$this->result->addChange('ldap_test_base', $total);
@@ -187,7 +187,7 @@  discard block
 block discarded – undo
187 187
 	 * @return int|bool
188 188
 	 */
189 189
 	public function countUsersWithAttribute($attr, $existsCheck = false) {
190
-		if(!$this->checkRequirements(array('ldapHost',
190
+		if (!$this->checkRequirements(array('ldapHost',
191 191
 										   'ldapPort',
192 192
 										   'ldapBase',
193 193
 										   'ldapUserFilter',
@@ -197,7 +197,7 @@  discard block
 block discarded – undo
197 197
 
198 198
 		$filter = $this->access->combineFilterWithAnd(array(
199 199
 			$this->configuration->ldapUserFilter,
200
-			$attr . '=*'
200
+			$attr.'=*'
201 201
 		));
202 202
 
203 203
 		$limit = ($existsCheck === false) ? null : 1;
@@ -212,7 +212,7 @@  discard block
 block discarded – undo
212 212
 	 * @throws \Exception
213 213
 	 */
214 214
 	public function detectUserDisplayNameAttribute() {
215
-		if(!$this->checkRequirements(array('ldapHost',
215
+		if (!$this->checkRequirements(array('ldapHost',
216 216
 										'ldapPort',
217 217
 										'ldapBase',
218 218
 										'ldapUserFilter',
@@ -225,7 +225,7 @@  discard block
 block discarded – undo
225 225
 			// most likely not the default value with upper case N,
226 226
 			// verify it still produces a result
227 227
 			$count = intval($this->countUsersWithAttribute($attr, true));
228
-			if($count > 0) {
228
+			if ($count > 0) {
229 229
 				//no change, but we sent it back to make sure the user interface
230 230
 				//is still correct, even if the ajax call was cancelled meanwhile
231 231
 				$this->result->addChange('ldap_display_name', $attr);
@@ -238,7 +238,7 @@  discard block
 block discarded – undo
238 238
 		foreach ($displayNameAttrs as $attr) {
239 239
 			$count = intval($this->countUsersWithAttribute($attr, true));
240 240
 
241
-			if($count > 0) {
241
+			if ($count > 0) {
242 242
 				$this->applyFind('ldap_display_name', $attr);
243 243
 				return $this->result;
244 244
 			}
@@ -254,7 +254,7 @@  discard block
 block discarded – undo
254 254
 	 * @return WizardResult|bool
255 255
 	 */
256 256
 	public function detectEmailAttribute() {
257
-		if(!$this->checkRequirements(array('ldapHost',
257
+		if (!$this->checkRequirements(array('ldapHost',
258 258
 										   'ldapPort',
259 259
 										   'ldapBase',
260 260
 										   'ldapUserFilter',
@@ -265,7 +265,7 @@  discard block
 block discarded – undo
265 265
 		$attr = $this->configuration->ldapEmailAttribute;
266 266
 		if ($attr !== '') {
267 267
 			$count = intval($this->countUsersWithAttribute($attr, true));
268
-			if($count > 0) {
268
+			if ($count > 0) {
269 269
 				return false;
270 270
 			}
271 271
 			$writeLog = true;
@@ -276,19 +276,19 @@  discard block
 block discarded – undo
276 276
 		$emailAttributes = array('mail', 'mailPrimaryAddress');
277 277
 		$winner = '';
278 278
 		$maxUsers = 0;
279
-		foreach($emailAttributes as $attr) {
279
+		foreach ($emailAttributes as $attr) {
280 280
 			$count = $this->countUsersWithAttribute($attr);
281
-			if($count > $maxUsers) {
281
+			if ($count > $maxUsers) {
282 282
 				$maxUsers = $count;
283 283
 				$winner = $attr;
284 284
 			}
285 285
 		}
286 286
 
287
-		if($winner !== '') {
287
+		if ($winner !== '') {
288 288
 			$this->applyFind('ldap_email_attr', $winner);
289
-			if($writeLog) {
290
-				\OCP\Util::writeLog('user_ldap', 'The mail attribute has ' .
291
-					'automatically been reset, because the original value ' .
289
+			if ($writeLog) {
290
+				\OCP\Util::writeLog('user_ldap', 'The mail attribute has '.
291
+					'automatically been reset, because the original value '.
292 292
 					'did not return any results.', \OCP\Util::INFO);
293 293
 			}
294 294
 		}
@@ -301,7 +301,7 @@  discard block
 block discarded – undo
301 301
 	 * @throws \Exception
302 302
 	 */
303 303
 	public function determineAttributes() {
304
-		if(!$this->checkRequirements(array('ldapHost',
304
+		if (!$this->checkRequirements(array('ldapHost',
305 305
 										   'ldapPort',
306 306
 										   'ldapBase',
307 307
 										   'ldapUserFilter',
@@ -317,7 +317,7 @@  discard block
 block discarded – undo
317 317
 		$this->result->addOptions('ldap_loginfilter_attributes', $attributes);
318 318
 
319 319
 		$selected = $this->configuration->ldapLoginFilterAttributes;
320
-		if(is_array($selected) && !empty($selected)) {
320
+		if (is_array($selected) && !empty($selected)) {
321 321
 			$this->result->addChange('ldap_loginfilter_attributes', $selected);
322 322
 		}
323 323
 
@@ -330,7 +330,7 @@  discard block
 block discarded – undo
330 330
 	 * @throws \Exception
331 331
 	 */
332 332
 	private function getUserAttributes() {
333
-		if(!$this->checkRequirements(array('ldapHost',
333
+		if (!$this->checkRequirements(array('ldapHost',
334 334
 										   'ldapPort',
335 335
 										   'ldapBase',
336 336
 										   'ldapUserFilter',
@@ -338,20 +338,20 @@  discard block
 block discarded – undo
338 338
 			return  false;
339 339
 		}
340 340
 		$cr = $this->getConnection();
341
-		if(!$cr) {
341
+		if (!$cr) {
342 342
 			throw new \Exception('Could not connect to LDAP');
343 343
 		}
344 344
 
345 345
 		$base = $this->configuration->ldapBase[0];
346 346
 		$filter = $this->configuration->ldapUserFilter;
347 347
 		$rr = $this->ldap->search($cr, $base, $filter, array(), 1, 1);
348
-		if(!$this->ldap->isResource($rr)) {
348
+		if (!$this->ldap->isResource($rr)) {
349 349
 			return false;
350 350
 		}
351 351
 		$er = $this->ldap->firstEntry($cr, $rr);
352 352
 		$attributes = $this->ldap->getAttributes($cr, $er);
353 353
 		$pureAttributes = array();
354
-		for($i = 0; $i < $attributes['count']; $i++) {
354
+		for ($i = 0; $i < $attributes['count']; $i++) {
355 355
 			$pureAttributes[] = $attributes[$i];
356 356
 		}
357 357
 
@@ -386,23 +386,23 @@  discard block
 block discarded – undo
386 386
 	 * @throws \Exception
387 387
 	 */
388 388
 	private function determineGroups($dbKey, $confKey, $testMemberOf = true) {
389
-		if(!$this->checkRequirements(array('ldapHost',
389
+		if (!$this->checkRequirements(array('ldapHost',
390 390
 										   'ldapPort',
391 391
 										   'ldapBase',
392 392
 										   ))) {
393 393
 			return  false;
394 394
 		}
395 395
 		$cr = $this->getConnection();
396
-		if(!$cr) {
396
+		if (!$cr) {
397 397
 			throw new \Exception('Could not connect to LDAP');
398 398
 		}
399 399
 
400 400
 		$this->fetchGroups($dbKey, $confKey);
401 401
 
402
-		if($testMemberOf) {
402
+		if ($testMemberOf) {
403 403
 			$this->configuration->hasMemberOfFilterSupport = $this->testMemberOf();
404 404
 			$this->result->markChange();
405
-			if(!$this->configuration->hasMemberOfFilterSupport) {
405
+			if (!$this->configuration->hasMemberOfFilterSupport) {
406 406
 				throw new \Exception('memberOf is not supported by the server');
407 407
 			}
408 408
 		}
@@ -422,7 +422,7 @@  discard block
 block discarded – undo
422 422
 		$obclasses = array('posixGroup', 'group', 'zimbraDistributionList', 'groupOfNames', 'groupOfUniqueNames');
423 423
 
424 424
 		$filterParts = array();
425
-		foreach($obclasses as $obclass) {
425
+		foreach ($obclasses as $obclass) {
426 426
 			$filterParts[] = 'objectclass='.$obclass;
427 427
 		}
428 428
 		//we filter for everything
@@ -439,8 +439,8 @@  discard block
 block discarded – undo
439 439
 			// we need to request dn additionally here, otherwise memberOf
440 440
 			// detection will fail later
441 441
 			$result = $this->access->searchGroups($filter, array('cn', 'dn'), $limit, $offset);
442
-			foreach($result as $item) {
443
-				if(!isset($item['cn']) && !is_array($item['cn']) && !isset($item['cn'][0])) {
442
+			foreach ($result as $item) {
443
+				if (!isset($item['cn']) && !is_array($item['cn']) && !isset($item['cn'][0])) {
444 444
 					// just in case - no issue known
445 445
 					continue;
446 446
 				}
@@ -450,7 +450,7 @@  discard block
 block discarded – undo
450 450
 			$offset += $limit;
451 451
 		} while ($this->access->hasMoreResults());
452 452
 
453
-		if(count($groupNames) > 0) {
453
+		if (count($groupNames) > 0) {
454 454
 			natsort($groupNames);
455 455
 			$this->result->addOptions($dbKey, array_values($groupNames));
456 456
 		} else {
@@ -458,7 +458,7 @@  discard block
 block discarded – undo
458 458
 		}
459 459
 
460 460
 		$setFeatures = $this->configuration->$confKey;
461
-		if(is_array($setFeatures) && !empty($setFeatures)) {
461
+		if (is_array($setFeatures) && !empty($setFeatures)) {
462 462
 			//something is already configured? pre-select it.
463 463
 			$this->result->addChange($dbKey, $setFeatures);
464 464
 		}
@@ -466,14 +466,14 @@  discard block
 block discarded – undo
466 466
 	}
467 467
 
468 468
 	public function determineGroupMemberAssoc() {
469
-		if(!$this->checkRequirements(array('ldapHost',
469
+		if (!$this->checkRequirements(array('ldapHost',
470 470
 										   'ldapPort',
471 471
 										   'ldapGroupFilter',
472 472
 										   ))) {
473 473
 			return  false;
474 474
 		}
475 475
 		$attribute = $this->detectGroupMemberAssoc();
476
-		if($attribute === false) {
476
+		if ($attribute === false) {
477 477
 			return false;
478 478
 		}
479 479
 		$this->configuration->setConfiguration(array('ldapGroupMemberAssocAttr' => $attribute));
@@ -488,14 +488,14 @@  discard block
 block discarded – undo
488 488
 	 * @throws \Exception
489 489
 	 */
490 490
 	public function determineGroupObjectClasses() {
491
-		if(!$this->checkRequirements(array('ldapHost',
491
+		if (!$this->checkRequirements(array('ldapHost',
492 492
 										   'ldapPort',
493 493
 										   'ldapBase',
494 494
 										   ))) {
495 495
 			return  false;
496 496
 		}
497 497
 		$cr = $this->getConnection();
498
-		if(!$cr) {
498
+		if (!$cr) {
499 499
 			throw new \Exception('Could not connect to LDAP');
500 500
 		}
501 501
 
@@ -515,14 +515,14 @@  discard block
 block discarded – undo
515 515
 	 * @throws \Exception
516 516
 	 */
517 517
 	public function determineUserObjectClasses() {
518
-		if(!$this->checkRequirements(array('ldapHost',
518
+		if (!$this->checkRequirements(array('ldapHost',
519 519
 										   'ldapPort',
520 520
 										   'ldapBase',
521 521
 										   ))) {
522 522
 			return  false;
523 523
 		}
524 524
 		$cr = $this->getConnection();
525
-		if(!$cr) {
525
+		if (!$cr) {
526 526
 			throw new \Exception('Could not connect to LDAP');
527 527
 		}
528 528
 
@@ -545,7 +545,7 @@  discard block
 block discarded – undo
545 545
 	 * @throws \Exception
546 546
 	 */
547 547
 	public function getGroupFilter() {
548
-		if(!$this->checkRequirements(array('ldapHost',
548
+		if (!$this->checkRequirements(array('ldapHost',
549 549
 										   'ldapPort',
550 550
 										   'ldapBase',
551 551
 										   ))) {
@@ -569,7 +569,7 @@  discard block
 block discarded – undo
569 569
 	 * @throws \Exception
570 570
 	 */
571 571
 	public function getUserListFilter() {
572
-		if(!$this->checkRequirements(array('ldapHost',
572
+		if (!$this->checkRequirements(array('ldapHost',
573 573
 										   'ldapPort',
574 574
 										   'ldapBase',
575 575
 										   ))) {
@@ -582,7 +582,7 @@  discard block
 block discarded – undo
582 582
 			$this->applyFind('ldap_display_name', $d['ldap_display_name']);
583 583
 		}
584 584
 		$filter = $this->composeLdapFilter(self::LFILTER_USER_LIST);
585
-		if(!$filter) {
585
+		if (!$filter) {
586 586
 			throw new \Exception('Cannot create filter');
587 587
 		}
588 588
 
@@ -595,7 +595,7 @@  discard block
 block discarded – undo
595 595
 	 * @throws \Exception
596 596
 	 */
597 597
 	public function getUserLoginFilter() {
598
-		if(!$this->checkRequirements(array('ldapHost',
598
+		if (!$this->checkRequirements(array('ldapHost',
599 599
 										   'ldapPort',
600 600
 										   'ldapBase',
601 601
 										   'ldapUserFilter',
@@ -604,7 +604,7 @@  discard block
 block discarded – undo
604 604
 		}
605 605
 
606 606
 		$filter = $this->composeLdapFilter(self::LFILTER_LOGIN);
607
-		if(!$filter) {
607
+		if (!$filter) {
608 608
 			throw new \Exception('Cannot create filter');
609 609
 		}
610 610
 
@@ -618,7 +618,7 @@  discard block
 block discarded – undo
618 618
 	 * @throws \Exception
619 619
 	 */
620 620
 	public function testLoginName($loginName) {
621
-		if(!$this->checkRequirements(array('ldapHost',
621
+		if (!$this->checkRequirements(array('ldapHost',
622 622
 			'ldapPort',
623 623
 			'ldapBase',
624 624
 			'ldapLoginFilter',
@@ -627,17 +627,17 @@  discard block
 block discarded – undo
627 627
 		}
628 628
 
629 629
 		$cr = $this->access->connection->getConnectionResource();
630
-		if(!$this->ldap->isResource($cr)) {
630
+		if (!$this->ldap->isResource($cr)) {
631 631
 			throw new \Exception('connection error');
632 632
 		}
633 633
 
634
-		if(mb_strpos($this->access->connection->ldapLoginFilter, '%uid', 0, 'UTF-8')
634
+		if (mb_strpos($this->access->connection->ldapLoginFilter, '%uid', 0, 'UTF-8')
635 635
 			=== false) {
636 636
 			throw new \Exception('missing placeholder');
637 637
 		}
638 638
 
639 639
 		$users = $this->access->countUsersByLoginName($loginName);
640
-		if($this->ldap->errno($cr) !== 0) {
640
+		if ($this->ldap->errno($cr) !== 0) {
641 641
 			throw new \Exception($this->ldap->error($cr));
642 642
 		}
643 643
 		$filter = str_replace('%uid', $loginName, $this->access->connection->ldapLoginFilter);
@@ -652,22 +652,22 @@  discard block
 block discarded – undo
652 652
 	 * @throws \Exception
653 653
 	 */
654 654
 	public function guessPortAndTLS() {
655
-		if(!$this->checkRequirements(array('ldapHost',
655
+		if (!$this->checkRequirements(array('ldapHost',
656 656
 										   ))) {
657 657
 			return false;
658 658
 		}
659 659
 		$this->checkHost();
660 660
 		$portSettings = $this->getPortSettingsToTry();
661 661
 
662
-		if(!is_array($portSettings)) {
662
+		if (!is_array($portSettings)) {
663 663
 			throw new \Exception(print_r($portSettings, true));
664 664
 		}
665 665
 
666 666
 		//proceed from the best configuration and return on first success
667
-		foreach($portSettings as $setting) {
667
+		foreach ($portSettings as $setting) {
668 668
 			$p = $setting['port'];
669 669
 			$t = $setting['tls'];
670
-			\OCP\Util::writeLog('user_ldap', 'Wiz: trying port '. $p . ', TLS '. $t, \OCP\Util::DEBUG);
670
+			\OCP\Util::writeLog('user_ldap', 'Wiz: trying port '.$p.', TLS '.$t, \OCP\Util::DEBUG);
671 671
 			//connectAndBind may throw Exception, it needs to be catched by the
672 672
 			//callee of this method
673 673
 
@@ -677,7 +677,7 @@  discard block
 block discarded – undo
677 677
 				// any reply other than -1 (= cannot connect) is already okay,
678 678
 				// because then we found the server
679 679
 				// unavailable startTLS returns -11
680
-				if($e->getCode() > 0) {
680
+				if ($e->getCode() > 0) {
681 681
 					$settingsFound = true;
682 682
 				} else {
683 683
 					throw $e;
@@ -690,7 +690,7 @@  discard block
 block discarded – undo
690 690
 					'ldapTLS' => intval($t)
691 691
 				);
692 692
 				$this->configuration->setConfiguration($config);
693
-				\OCP\Util::writeLog('user_ldap', 'Wiz: detected Port ' . $p, \OCP\Util::DEBUG);
693
+				\OCP\Util::writeLog('user_ldap', 'Wiz: detected Port '.$p, \OCP\Util::DEBUG);
694 694
 				$this->result->addChange('ldap_port', $p);
695 695
 				return $this->result;
696 696
 			}
@@ -705,7 +705,7 @@  discard block
 block discarded – undo
705 705
 	 * @return WizardResult|false WizardResult on success, false otherwise
706 706
 	 */
707 707
 	public function guessBaseDN() {
708
-		if(!$this->checkRequirements(array('ldapHost',
708
+		if (!$this->checkRequirements(array('ldapHost',
709 709
 										   'ldapPort',
710 710
 										   ))) {
711 711
 			return false;
@@ -714,9 +714,9 @@  discard block
 block discarded – undo
714 714
 		//check whether a DN is given in the agent name (99.9% of all cases)
715 715
 		$base = null;
716 716
 		$i = stripos($this->configuration->ldapAgentName, 'dc=');
717
-		if($i !== false) {
717
+		if ($i !== false) {
718 718
 			$base = substr($this->configuration->ldapAgentName, $i);
719
-			if($this->testBaseDN($base)) {
719
+			if ($this->testBaseDN($base)) {
720 720
 				$this->applyFind('ldap_base', $base);
721 721
 				return $this->result;
722 722
 			}
@@ -727,13 +727,13 @@  discard block
 block discarded – undo
727 727
 		//a base DN
728 728
 		$helper = new Helper(\OC::$server->getConfig());
729 729
 		$domain = $helper->getDomainFromURL($this->configuration->ldapHost);
730
-		if(!$domain) {
730
+		if (!$domain) {
731 731
 			return false;
732 732
 		}
733 733
 
734 734
 		$dparts = explode('.', $domain);
735
-		while(count($dparts) > 0) {
736
-			$base2 = 'dc=' . implode(',dc=', $dparts);
735
+		while (count($dparts) > 0) {
736
+			$base2 = 'dc='.implode(',dc=', $dparts);
737 737
 			if ($base !== $base2 && $this->testBaseDN($base2)) {
738 738
 				$this->applyFind('ldap_base', $base2);
739 739
 				return $this->result;
@@ -766,7 +766,7 @@  discard block
 block discarded – undo
766 766
 		$hostInfo = parse_url($host);
767 767
 
768 768
 		//removes Port from Host
769
-		if(is_array($hostInfo) && isset($hostInfo['port'])) {
769
+		if (is_array($hostInfo) && isset($hostInfo['port'])) {
770 770
 			$port = $hostInfo['port'];
771 771
 			$host = str_replace(':'.$port, '', $host);
772 772
 			$this->applyFind('ldap_host', $host);
@@ -783,30 +783,30 @@  discard block
 block discarded – undo
783 783
 	private function detectGroupMemberAssoc() {
784 784
 		$possibleAttrs = array('uniqueMember', 'memberUid', 'member', 'gidNumber');
785 785
 		$filter = $this->configuration->ldapGroupFilter;
786
-		if(empty($filter)) {
786
+		if (empty($filter)) {
787 787
 			return false;
788 788
 		}
789 789
 		$cr = $this->getConnection();
790
-		if(!$cr) {
790
+		if (!$cr) {
791 791
 			throw new \Exception('Could not connect to LDAP');
792 792
 		}
793 793
 		$base = $this->configuration->ldapBase[0];
794 794
 		$rr = $this->ldap->search($cr, $base, $filter, $possibleAttrs, 0, 1000);
795
-		if(!$this->ldap->isResource($rr)) {
795
+		if (!$this->ldap->isResource($rr)) {
796 796
 			return false;
797 797
 		}
798 798
 		$er = $this->ldap->firstEntry($cr, $rr);
799
-		while(is_resource($er)) {
799
+		while (is_resource($er)) {
800 800
 			$this->ldap->getDN($cr, $er);
801 801
 			$attrs = $this->ldap->getAttributes($cr, $er);
802 802
 			$result = array();
803 803
 			$possibleAttrsCount = count($possibleAttrs);
804
-			for($i = 0; $i < $possibleAttrsCount; $i++) {
805
-				if(isset($attrs[$possibleAttrs[$i]])) {
804
+			for ($i = 0; $i < $possibleAttrsCount; $i++) {
805
+				if (isset($attrs[$possibleAttrs[$i]])) {
806 806
 					$result[$possibleAttrs[$i]] = $attrs[$possibleAttrs[$i]]['count'];
807 807
 				}
808 808
 			}
809
-			if(!empty($result)) {
809
+			if (!empty($result)) {
810 810
 				natsort($result);
811 811
 				return key($result);
812 812
 			}
@@ -825,14 +825,14 @@  discard block
 block discarded – undo
825 825
 	 */
826 826
 	private function testBaseDN($base) {
827 827
 		$cr = $this->getConnection();
828
-		if(!$cr) {
828
+		if (!$cr) {
829 829
 			throw new \Exception('Could not connect to LDAP');
830 830
 		}
831 831
 
832 832
 		//base is there, let's validate it. If we search for anything, we should
833 833
 		//get a result set > 0 on a proper base
834 834
 		$rr = $this->ldap->search($cr, $base, 'objectClass=*', array('dn'), 0, 1);
835
-		if(!$this->ldap->isResource($rr)) {
835
+		if (!$this->ldap->isResource($rr)) {
836 836
 			$errorNo  = $this->ldap->errno($cr);
837 837
 			$errorMsg = $this->ldap->error($cr);
838 838
 			\OCP\Util::writeLog('user_ldap', 'Wiz: Could not search base '.$base.
@@ -854,11 +854,11 @@  discard block
 block discarded – undo
854 854
 	 */
855 855
 	private function testMemberOf() {
856 856
 		$cr = $this->getConnection();
857
-		if(!$cr) {
857
+		if (!$cr) {
858 858
 			throw new \Exception('Could not connect to LDAP');
859 859
 		}
860 860
 		$result = $this->access->countUsers('memberOf=*', array('memberOf'), 1);
861
-		if(is_int($result) &&  $result > 0) {
861
+		if (is_int($result) && $result > 0) {
862 862
 			return true;
863 863
 		}
864 864
 		return false;
@@ -879,27 +879,27 @@  discard block
 block discarded – undo
879 879
 			case self::LFILTER_USER_LIST:
880 880
 				$objcs = $this->configuration->ldapUserFilterObjectclass;
881 881
 				//glue objectclasses
882
-				if(is_array($objcs) && count($objcs) > 0) {
882
+				if (is_array($objcs) && count($objcs) > 0) {
883 883
 					$filter .= '(|';
884
-					foreach($objcs as $objc) {
885
-						$filter .= '(objectclass=' . $objc . ')';
884
+					foreach ($objcs as $objc) {
885
+						$filter .= '(objectclass='.$objc.')';
886 886
 					}
887 887
 					$filter .= ')';
888 888
 					$parts++;
889 889
 				}
890 890
 				//glue group memberships
891
-				if($this->configuration->hasMemberOfFilterSupport) {
891
+				if ($this->configuration->hasMemberOfFilterSupport) {
892 892
 					$cns = $this->configuration->ldapUserFilterGroups;
893
-					if(is_array($cns) && count($cns) > 0) {
893
+					if (is_array($cns) && count($cns) > 0) {
894 894
 						$filter .= '(|';
895 895
 						$cr = $this->getConnection();
896
-						if(!$cr) {
896
+						if (!$cr) {
897 897
 							throw new \Exception('Could not connect to LDAP');
898 898
 						}
899 899
 						$base = $this->configuration->ldapBase[0];
900
-						foreach($cns as $cn) {
901
-							$rr = $this->ldap->search($cr, $base, 'cn=' . $cn, array('dn', 'primaryGroupToken'));
902
-							if(!$this->ldap->isResource($rr)) {
900
+						foreach ($cns as $cn) {
901
+							$rr = $this->ldap->search($cr, $base, 'cn='.$cn, array('dn', 'primaryGroupToken'));
902
+							if (!$this->ldap->isResource($rr)) {
903 903
 								continue;
904 904
 							}
905 905
 							$er = $this->ldap->firstEntry($cr, $rr);
@@ -908,11 +908,11 @@  discard block
 block discarded – undo
908 908
 							if ($dn === false || $dn === '') {
909 909
 								continue;
910 910
 							}
911
-							$filterPart = '(memberof=' . $dn . ')';
912
-							if(isset($attrs['primaryGroupToken'])) {
911
+							$filterPart = '(memberof='.$dn.')';
912
+							if (isset($attrs['primaryGroupToken'])) {
913 913
 								$pgt = $attrs['primaryGroupToken'][0];
914
-								$primaryFilterPart = '(primaryGroupID=' . $pgt .')';
915
-								$filterPart = '(|' . $filterPart . $primaryFilterPart . ')';
914
+								$primaryFilterPart = '(primaryGroupID='.$pgt.')';
915
+								$filterPart = '(|'.$filterPart.$primaryFilterPart.')';
916 916
 							}
917 917
 							$filter .= $filterPart;
918 918
 						}
@@ -921,8 +921,8 @@  discard block
 block discarded – undo
921 921
 					$parts++;
922 922
 				}
923 923
 				//wrap parts in AND condition
924
-				if($parts > 1) {
925
-					$filter = '(&' . $filter . ')';
924
+				if ($parts > 1) {
925
+					$filter = '(&'.$filter.')';
926 926
 				}
927 927
 				if ($filter === '') {
928 928
 					$filter = '(objectclass=*)';
@@ -932,27 +932,27 @@  discard block
 block discarded – undo
932 932
 			case self::LFILTER_GROUP_LIST:
933 933
 				$objcs = $this->configuration->ldapGroupFilterObjectclass;
934 934
 				//glue objectclasses
935
-				if(is_array($objcs) && count($objcs) > 0) {
935
+				if (is_array($objcs) && count($objcs) > 0) {
936 936
 					$filter .= '(|';
937
-					foreach($objcs as $objc) {
938
-						$filter .= '(objectclass=' . $objc . ')';
937
+					foreach ($objcs as $objc) {
938
+						$filter .= '(objectclass='.$objc.')';
939 939
 					}
940 940
 					$filter .= ')';
941 941
 					$parts++;
942 942
 				}
943 943
 				//glue group memberships
944 944
 				$cns = $this->configuration->ldapGroupFilterGroups;
945
-				if(is_array($cns) && count($cns) > 0) {
945
+				if (is_array($cns) && count($cns) > 0) {
946 946
 					$filter .= '(|';
947
-					foreach($cns as $cn) {
948
-						$filter .= '(cn=' . $cn . ')';
947
+					foreach ($cns as $cn) {
948
+						$filter .= '(cn='.$cn.')';
949 949
 					}
950 950
 					$filter .= ')';
951 951
 				}
952 952
 				$parts++;
953 953
 				//wrap parts in AND condition
954
-				if($parts > 1) {
955
-					$filter = '(&' . $filter . ')';
954
+				if ($parts > 1) {
955
+					$filter = '(&'.$filter.')';
956 956
 				}
957 957
 				break;
958 958
 
@@ -964,47 +964,47 @@  discard block
 block discarded – undo
964 964
 				$userAttributes = array_change_key_case(array_flip($userAttributes));
965 965
 				$parts = 0;
966 966
 
967
-				if($this->configuration->ldapLoginFilterUsername === '1') {
967
+				if ($this->configuration->ldapLoginFilterUsername === '1') {
968 968
 					$attr = '';
969
-					if(isset($userAttributes['uid'])) {
969
+					if (isset($userAttributes['uid'])) {
970 970
 						$attr = 'uid';
971
-					} else if(isset($userAttributes['samaccountname'])) {
971
+					} else if (isset($userAttributes['samaccountname'])) {
972 972
 						$attr = 'samaccountname';
973
-					} else if(isset($userAttributes['cn'])) {
973
+					} else if (isset($userAttributes['cn'])) {
974 974
 						//fallback
975 975
 						$attr = 'cn';
976 976
 					}
977 977
 					if ($attr !== '') {
978
-						$filterUsername = '(' . $attr . $loginpart . ')';
978
+						$filterUsername = '('.$attr.$loginpart.')';
979 979
 						$parts++;
980 980
 					}
981 981
 				}
982 982
 
983 983
 				$filterEmail = '';
984
-				if($this->configuration->ldapLoginFilterEmail === '1') {
984
+				if ($this->configuration->ldapLoginFilterEmail === '1') {
985 985
 					$filterEmail = '(|(mailPrimaryAddress=%uid)(mail=%uid))';
986 986
 					$parts++;
987 987
 				}
988 988
 
989 989
 				$filterAttributes = '';
990 990
 				$attrsToFilter = $this->configuration->ldapLoginFilterAttributes;
991
-				if(is_array($attrsToFilter) && count($attrsToFilter) > 0) {
991
+				if (is_array($attrsToFilter) && count($attrsToFilter) > 0) {
992 992
 					$filterAttributes = '(|';
993
-					foreach($attrsToFilter as $attribute) {
994
-						$filterAttributes .= '(' . $attribute . $loginpart . ')';
993
+					foreach ($attrsToFilter as $attribute) {
994
+						$filterAttributes .= '('.$attribute.$loginpart.')';
995 995
 					}
996 996
 					$filterAttributes .= ')';
997 997
 					$parts++;
998 998
 				}
999 999
 
1000 1000
 				$filterLogin = '';
1001
-				if($parts > 1) {
1001
+				if ($parts > 1) {
1002 1002
 					$filterLogin = '(|';
1003 1003
 				}
1004 1004
 				$filterLogin .= $filterUsername;
1005 1005
 				$filterLogin .= $filterEmail;
1006 1006
 				$filterLogin .= $filterAttributes;
1007
-				if($parts > 1) {
1007
+				if ($parts > 1) {
1008 1008
 					$filterLogin .= ')';
1009 1009
 				}
1010 1010
 
@@ -1029,12 +1029,12 @@  discard block
 block discarded – undo
1029 1029
 		//connect, does not really trigger any server communication
1030 1030
 		$host = $this->configuration->ldapHost;
1031 1031
 		$hostInfo = parse_url($host);
1032
-		if(!$hostInfo) {
1032
+		if (!$hostInfo) {
1033 1033
 			throw new \Exception(self::$l->t('Invalid Host'));
1034 1034
 		}
1035 1035
 		\OCP\Util::writeLog('user_ldap', 'Wiz: Attempting to connect ', \OCP\Util::DEBUG);
1036 1036
 		$cr = $this->ldap->connect($host, $port);
1037
-		if(!is_resource($cr)) {
1037
+		if (!is_resource($cr)) {
1038 1038
 			throw new \Exception(self::$l->t('Invalid Host'));
1039 1039
 		}
1040 1040
 
@@ -1044,9 +1044,9 @@  discard block
 block discarded – undo
1044 1044
 		$this->ldap->setOption($cr, LDAP_OPT_NETWORK_TIMEOUT, self::LDAP_NW_TIMEOUT);
1045 1045
 
1046 1046
 		try {
1047
-			if($tls) {
1047
+			if ($tls) {
1048 1048
 				$isTlsWorking = @$this->ldap->startTls($cr);
1049
-				if(!$isTlsWorking) {
1049
+				if (!$isTlsWorking) {
1050 1050
 					return false;
1051 1051
 				}
1052 1052
 			}
@@ -1060,17 +1060,17 @@  discard block
 block discarded – undo
1060 1060
 			$errNo = $this->ldap->errno($cr);
1061 1061
 			$error = ldap_error($cr);
1062 1062
 			$this->ldap->unbind($cr);
1063
-		} catch(ServerNotAvailableException $e) {
1063
+		} catch (ServerNotAvailableException $e) {
1064 1064
 			return false;
1065 1065
 		}
1066 1066
 
1067
-		if($login === true) {
1067
+		if ($login === true) {
1068 1068
 			$this->ldap->unbind($cr);
1069
-			\OCP\Util::writeLog('user_ldap', 'Wiz: Bind successful to Port '. $port . ' TLS ' . intval($tls), \OCP\Util::DEBUG);
1069
+			\OCP\Util::writeLog('user_ldap', 'Wiz: Bind successful to Port '.$port.' TLS '.intval($tls), \OCP\Util::DEBUG);
1070 1070
 			return true;
1071 1071
 		}
1072 1072
 
1073
-		if($errNo === -1) {
1073
+		if ($errNo === -1) {
1074 1074
 			//host, port or TLS wrong
1075 1075
 			return false;
1076 1076
 		}
@@ -1098,9 +1098,9 @@  discard block
 block discarded – undo
1098 1098
 	 */
1099 1099
 	private function checkRequirements($reqs) {
1100 1100
 		$this->checkAgentRequirements();
1101
-		foreach($reqs as $option) {
1101
+		foreach ($reqs as $option) {
1102 1102
 			$value = $this->configuration->$option;
1103
-			if(empty($value)) {
1103
+			if (empty($value)) {
1104 1104
 				return false;
1105 1105
 			}
1106 1106
 		}
@@ -1122,33 +1122,33 @@  discard block
 block discarded – undo
1122 1122
 		$dnRead = array();
1123 1123
 		$foundItems = array();
1124 1124
 		$maxEntries = 0;
1125
-		if(!is_array($this->configuration->ldapBase)
1125
+		if (!is_array($this->configuration->ldapBase)
1126 1126
 		   || !isset($this->configuration->ldapBase[0])) {
1127 1127
 			return false;
1128 1128
 		}
1129 1129
 		$base = $this->configuration->ldapBase[0];
1130 1130
 		$cr = $this->getConnection();
1131
-		if(!$this->ldap->isResource($cr)) {
1131
+		if (!$this->ldap->isResource($cr)) {
1132 1132
 			return false;
1133 1133
 		}
1134 1134
 		$lastFilter = null;
1135
-		if(isset($filters[count($filters)-1])) {
1136
-			$lastFilter = $filters[count($filters)-1];
1135
+		if (isset($filters[count($filters) - 1])) {
1136
+			$lastFilter = $filters[count($filters) - 1];
1137 1137
 		}
1138
-		foreach($filters as $filter) {
1139
-			if($lastFilter === $filter && count($foundItems) > 0) {
1138
+		foreach ($filters as $filter) {
1139
+			if ($lastFilter === $filter && count($foundItems) > 0) {
1140 1140
 				//skip when the filter is a wildcard and results were found
1141 1141
 				continue;
1142 1142
 			}
1143 1143
 			// 20k limit for performance and reason
1144 1144
 			$rr = $this->ldap->search($cr, $base, $filter, array($attr), 0, 20000);
1145
-			if(!$this->ldap->isResource($rr)) {
1145
+			if (!$this->ldap->isResource($rr)) {
1146 1146
 				continue;
1147 1147
 			}
1148 1148
 			$entries = $this->ldap->countEntries($cr, $rr);
1149 1149
 			$getEntryFunc = 'firstEntry';
1150
-			if(($entries !== false) && ($entries > 0)) {
1151
-				if(!is_null($maxF) && $entries > $maxEntries) {
1150
+			if (($entries !== false) && ($entries > 0)) {
1151
+				if (!is_null($maxF) && $entries > $maxEntries) {
1152 1152
 					$maxEntries = $entries;
1153 1153
 					$maxF = $filter;
1154 1154
 				}
@@ -1156,13 +1156,13 @@  discard block
 block discarded – undo
1156 1156
 				do {
1157 1157
 					$entry = $this->ldap->$getEntryFunc($cr, $rr);
1158 1158
 					$getEntryFunc = 'nextEntry';
1159
-					if(!$this->ldap->isResource($entry)) {
1159
+					if (!$this->ldap->isResource($entry)) {
1160 1160
 						continue 2;
1161 1161
 					}
1162 1162
 					$rr = $entry; //will be expected by nextEntry next round
1163 1163
 					$attributes = $this->ldap->getAttributes($cr, $entry);
1164 1164
 					$dn = $this->ldap->getDN($cr, $entry);
1165
-					if($dn === false || in_array($dn, $dnRead)) {
1165
+					if ($dn === false || in_array($dn, $dnRead)) {
1166 1166
 						continue;
1167 1167
 					}
1168 1168
 					$newItems = array();
@@ -1173,7 +1173,7 @@  discard block
 block discarded – undo
1173 1173
 					$foundItems = array_merge($foundItems, $newItems);
1174 1174
 					$this->resultCache[$dn][$attr] = $newItems;
1175 1175
 					$dnRead[] = $dn;
1176
-				} while(($state === self::LRESULT_PROCESSED_SKIP
1176
+				} while (($state === self::LRESULT_PROCESSED_SKIP
1177 1177
 						|| $this->ldap->isResource($entry))
1178 1178
 						&& ($dnReadLimit === 0 || $dnReadCount < $dnReadLimit));
1179 1179
 			}
@@ -1196,11 +1196,11 @@  discard block
 block discarded – undo
1196 1196
 	 */
1197 1197
 	private function determineFeature($objectclasses, $attr, $dbkey, $confkey, $po = false) {
1198 1198
 		$cr = $this->getConnection();
1199
-		if(!$cr) {
1199
+		if (!$cr) {
1200 1200
 			throw new \Exception('Could not connect to LDAP');
1201 1201
 		}
1202 1202
 		$p = 'objectclass=';
1203
-		foreach($objectclasses as $key => $value) {
1203
+		foreach ($objectclasses as $key => $value) {
1204 1204
 			$objectclasses[$key] = $p.$value;
1205 1205
 		}
1206 1206
 		$maxEntryObjC = '';
@@ -1212,7 +1212,7 @@  discard block
 block discarded – undo
1212 1212
 		$availableFeatures =
1213 1213
 			$this->cumulativeSearchOnAttribute($objectclasses, $attr,
1214 1214
 											   $dig, $maxEntryObjC);
1215
-		if(is_array($availableFeatures)
1215
+		if (is_array($availableFeatures)
1216 1216
 		   && count($availableFeatures) > 0) {
1217 1217
 			natcasesort($availableFeatures);
1218 1218
 			//natcasesort keeps indices, but we must get rid of them for proper
@@ -1223,7 +1223,7 @@  discard block
 block discarded – undo
1223 1223
 		}
1224 1224
 
1225 1225
 		$setFeatures = $this->configuration->$confkey;
1226
-		if(is_array($setFeatures) && !empty($setFeatures)) {
1226
+		if (is_array($setFeatures) && !empty($setFeatures)) {
1227 1227
 			//something is already configured? pre-select it.
1228 1228
 			$this->result->addChange($dbkey, $setFeatures);
1229 1229
 		} else if ($po && $maxEntryObjC !== '') {
@@ -1245,7 +1245,7 @@  discard block
 block discarded – undo
1245 1245
 	 * LRESULT_PROCESSED_INVALID or LRESULT_PROCESSED_SKIP
1246 1246
 	 */
1247 1247
 	private function getAttributeValuesFromEntry($result, $attribute, &$known) {
1248
-		if(!is_array($result)
1248
+		if (!is_array($result)
1249 1249
 		   || !isset($result['count'])
1250 1250
 		   || !$result['count'] > 0) {
1251 1251
 			return self::LRESULT_PROCESSED_INVALID;
@@ -1254,12 +1254,12 @@  discard block
 block discarded – undo
1254 1254
 		// strtolower on all keys for proper comparison
1255 1255
 		$result = \OCP\Util::mb_array_change_key_case($result);
1256 1256
 		$attribute = strtolower($attribute);
1257
-		if(isset($result[$attribute])) {
1258
-			foreach($result[$attribute] as $key => $val) {
1259
-				if($key === 'count') {
1257
+		if (isset($result[$attribute])) {
1258
+			foreach ($result[$attribute] as $key => $val) {
1259
+				if ($key === 'count') {
1260 1260
 					continue;
1261 1261
 				}
1262
-				if(!in_array($val, $known)) {
1262
+				if (!in_array($val, $known)) {
1263 1263
 					$known[] = $val;
1264 1264
 				}
1265 1265
 			}
@@ -1273,7 +1273,7 @@  discard block
 block discarded – undo
1273 1273
 	 * @return bool|mixed
1274 1274
 	 */
1275 1275
 	private function getConnection() {
1276
-		if(!is_null($this->cr)) {
1276
+		if (!is_null($this->cr)) {
1277 1277
 			return $this->cr;
1278 1278
 		}
1279 1279
 
@@ -1285,14 +1285,14 @@  discard block
 block discarded – undo
1285 1285
 		$this->ldap->setOption($cr, LDAP_OPT_PROTOCOL_VERSION, 3);
1286 1286
 		$this->ldap->setOption($cr, LDAP_OPT_REFERRALS, 0);
1287 1287
 		$this->ldap->setOption($cr, LDAP_OPT_NETWORK_TIMEOUT, self::LDAP_NW_TIMEOUT);
1288
-		if($this->configuration->ldapTLS === 1) {
1288
+		if ($this->configuration->ldapTLS === 1) {
1289 1289
 			$this->ldap->startTls($cr);
1290 1290
 		}
1291 1291
 
1292 1292
 		$lo = @$this->ldap->bind($cr,
1293 1293
 								 $this->configuration->ldapAgentName,
1294 1294
 								 $this->configuration->ldapAgentPassword);
1295
-		if($lo === true) {
1295
+		if ($lo === true) {
1296 1296
 			$this->$cr = $cr;
1297 1297
 			return $cr;
1298 1298
 		}
@@ -1327,14 +1327,14 @@  discard block
 block discarded – undo
1327 1327
 		$portSettings = array();
1328 1328
 
1329 1329
 		//In case the port is already provided, we will check this first
1330
-		if($port > 0) {
1330
+		if ($port > 0) {
1331 1331
 			$hostInfo = parse_url($host);
1332
-			if(!(is_array($hostInfo)
1332
+			if (!(is_array($hostInfo)
1333 1333
 				&& isset($hostInfo['scheme'])
1334 1334
 				&& stripos($hostInfo['scheme'], 'ldaps') !== false)) {
1335 1335
 				$portSettings[] = array('port' => $port, 'tls' => true);
1336 1336
 			}
1337
-			$portSettings[] =array('port' => $port, 'tls' => false);
1337
+			$portSettings[] = array('port' => $port, 'tls' => false);
1338 1338
 		}
1339 1339
 
1340 1340
 		//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.
Spacing   +11 added lines, -11 removed lines patch added patch discarded remove patch
@@ -65,14 +65,14 @@  discard block
 block discarded – undo
65 65
 	 */
66 66
 	public function __construct($storage, array $mountpoints, $arguments = null, $loader = null) {
67 67
 		$this->user = $arguments['user'];
68
-		$this->recipientView = new View('/' . $this->user . '/files');
68
+		$this->recipientView = new View('/'.$this->user.'/files');
69 69
 
70 70
 		$this->superShare = $arguments['superShare'];
71 71
 		$this->groupedShares = $arguments['groupedShares'];
72 72
 
73 73
 		$newMountPoint = $this->verifyMountPoint($this->superShare, $mountpoints);
74
-		$absMountPoint = '/' . $this->user . '/files' . $newMountPoint;
75
-		$arguments['ownerView'] = new View('/' . $this->superShare->getShareOwner() . '/files');
74
+		$absMountPoint = '/'.$this->user.'/files'.$newMountPoint;
75
+		$arguments['ownerView'] = new View('/'.$this->superShare->getShareOwner().'/files');
76 76
 		parent::__construct($storage, $absMountPoint, $arguments, $loader);
77 77
 	}
78 78
 
@@ -93,7 +93,7 @@  discard block
 block discarded – undo
93 93
 		}
94 94
 
95 95
 		$newMountPoint = $this->generateUniqueTarget(
96
-			\OC\Files\Filesystem::normalizePath($parent . '/' . $mountPoint),
96
+			\OC\Files\Filesystem::normalizePath($parent.'/'.$mountPoint),
97 97
 			$this->recipientView,
98 98
 			$mountpoints
99 99
 		);
@@ -130,12 +130,12 @@  discard block
 block discarded – undo
130 130
 	 */
131 131
 	private function generateUniqueTarget($path, $view, array $mountpoints) {
132 132
 		$pathinfo = pathinfo($path);
133
-		$ext = (isset($pathinfo['extension'])) ? '.' . $pathinfo['extension'] : '';
133
+		$ext = (isset($pathinfo['extension'])) ? '.'.$pathinfo['extension'] : '';
134 134
 		$name = $pathinfo['filename'];
135 135
 		$dir = $pathinfo['dirname'];
136 136
 
137 137
 		// Helper function to find existing mount points
138
-		$mountpointExists = function ($path) use ($mountpoints) {
138
+		$mountpointExists = function($path) use ($mountpoints) {
139 139
 			foreach ($mountpoints as $mountpoint) {
140 140
 				if ($mountpoint->getShare()->getTarget() === $path) {
141 141
 					return true;
@@ -146,7 +146,7 @@  discard block
 block discarded – undo
146 146
 
147 147
 		$i = 2;
148 148
 		while ($view->file_exists($path) || $mountpointExists($path)) {
149
-			$path = Filesystem::normalizePath($dir . '/' . $name . ' (' . $i . ')' . $ext);
149
+			$path = Filesystem::normalizePath($dir.'/'.$name.' ('.$i.')'.$ext);
150 150
 			$i++;
151 151
 		}
152 152
 
@@ -167,7 +167,7 @@  discard block
 block discarded – undo
167 167
 		// it is not a file relative to data/user/files
168 168
 		if (count($split) < 3 || $split[1] !== 'files') {
169 169
 			\OCP\Util::writeLog('file sharing',
170
-				'Can not strip userid and "files/" from path: ' . $path,
170
+				'Can not strip userid and "files/" from path: '.$path,
171 171
 				\OCP\Util::ERROR);
172 172
 			throw new \OCA\Files_Sharing\Exceptions\BrokenPath('Path does not start with /user/files', 10);
173 173
 		}
@@ -176,7 +176,7 @@  discard block
 block discarded – undo
176 176
 		$sliced = array_slice($split, 2);
177 177
 		$relPath = implode('/', $sliced);
178 178
 
179
-		return '/' . $relPath;
179
+		return '/'.$relPath;
180 180
 	}
181 181
 
182 182
 	/**
@@ -198,7 +198,7 @@  discard block
 block discarded – undo
198 198
 			$this->storage->setMountPoint($relTargetPath);
199 199
 		} catch (\Exception $e) {
200 200
 			\OCP\Util::writeLog('file sharing',
201
-				'Could not rename mount point for shared folder "' . $this->getMountPoint() . '" to "' . $target . '"',
201
+				'Could not rename mount point for shared folder "'.$this->getMountPoint().'" to "'.$target.'"',
202 202
 				\OCP\Util::ERROR);
203 203
 		}
204 204
 
@@ -253,7 +253,7 @@  discard block
 block discarded – undo
253 253
 			$row = $result->fetch();
254 254
 			$result->closeCursor();
255 255
 			if ($row) {
256
-				return (int)$row['storage'];
256
+				return (int) $row['storage'];
257 257
 			}
258 258
 			return -1;
259 259
 		}
Please login to merge, or discard this patch.
Indentation   +226 added lines, -226 removed lines patch added patch discarded remove patch
@@ -36,230 +36,230 @@
 block discarded – undo
36 36
  * Shared mount points can be moved by the user
37 37
  */
38 38
 class SharedMount extends MountPoint implements MoveableMount {
39
-	/**
40
-	 * @var \OCA\Files_Sharing\SharedStorage $storage
41
-	 */
42
-	protected $storage = null;
43
-
44
-	/**
45
-	 * @var \OC\Files\View
46
-	 */
47
-	private $recipientView;
48
-
49
-	/**
50
-	 * @var string
51
-	 */
52
-	private $user;
53
-
54
-	/** @var \OCP\Share\IShare */
55
-	private $superShare;
56
-
57
-	/** @var \OCP\Share\IShare[] */
58
-	private $groupedShares;
59
-
60
-	/**
61
-	 * @param string $storage
62
-	 * @param SharedMount[] $mountpoints
63
-	 * @param array|null $arguments
64
-	 * @param \OCP\Files\Storage\IStorageFactory $loader
65
-	 */
66
-	public function __construct($storage, array $mountpoints, $arguments = null, $loader = null) {
67
-		$this->user = $arguments['user'];
68
-		$this->recipientView = new View('/' . $this->user . '/files');
69
-
70
-		$this->superShare = $arguments['superShare'];
71
-		$this->groupedShares = $arguments['groupedShares'];
72
-
73
-		$newMountPoint = $this->verifyMountPoint($this->superShare, $mountpoints);
74
-		$absMountPoint = '/' . $this->user . '/files' . $newMountPoint;
75
-		$arguments['ownerView'] = new View('/' . $this->superShare->getShareOwner() . '/files');
76
-		parent::__construct($storage, $absMountPoint, $arguments, $loader);
77
-	}
78
-
79
-	/**
80
-	 * check if the parent folder exists otherwise move the mount point up
81
-	 *
82
-	 * @param \OCP\Share\IShare $share
83
-	 * @param SharedMount[] $mountpoints
84
-	 * @return string
85
-	 */
86
-	private function verifyMountPoint(\OCP\Share\IShare $share, array $mountpoints) {
87
-
88
-		$mountPoint = basename($share->getTarget());
89
-		$parent = dirname($share->getTarget());
90
-
91
-		if (!$this->recipientView->is_dir($parent)) {
92
-			$parent = Helper::getShareFolder($this->recipientView);
93
-		}
94
-
95
-		$newMountPoint = $this->generateUniqueTarget(
96
-			\OC\Files\Filesystem::normalizePath($parent . '/' . $mountPoint),
97
-			$this->recipientView,
98
-			$mountpoints
99
-		);
100
-
101
-		if ($newMountPoint !== $share->getTarget()) {
102
-			$this->updateFileTarget($newMountPoint, $share);
103
-		}
104
-
105
-		return $newMountPoint;
106
-	}
107
-
108
-	/**
109
-	 * update fileTarget in the database if the mount point changed
110
-	 *
111
-	 * @param string $newPath
112
-	 * @param \OCP\Share\IShare $share
113
-	 * @return bool
114
-	 */
115
-	private function updateFileTarget($newPath, &$share) {
116
-		$share->setTarget($newPath);
117
-
118
-		foreach ($this->groupedShares as $tmpShare) {
119
-			$tmpShare->setTarget($newPath);
120
-			\OC::$server->getShareManager()->moveShare($tmpShare, $this->user);
121
-		}
122
-	}
123
-
124
-
125
-	/**
126
-	 * @param string $path
127
-	 * @param View $view
128
-	 * @param SharedMount[] $mountpoints
129
-	 * @return mixed
130
-	 */
131
-	private function generateUniqueTarget($path, $view, array $mountpoints) {
132
-		$pathinfo = pathinfo($path);
133
-		$ext = (isset($pathinfo['extension'])) ? '.' . $pathinfo['extension'] : '';
134
-		$name = $pathinfo['filename'];
135
-		$dir = $pathinfo['dirname'];
136
-
137
-		// Helper function to find existing mount points
138
-		$mountpointExists = function ($path) use ($mountpoints) {
139
-			foreach ($mountpoints as $mountpoint) {
140
-				if ($mountpoint->getShare()->getTarget() === $path) {
141
-					return true;
142
-				}
143
-			}
144
-			return false;
145
-		};
146
-
147
-		$i = 2;
148
-		while ($view->file_exists($path) || $mountpointExists($path)) {
149
-			$path = Filesystem::normalizePath($dir . '/' . $name . ' (' . $i . ')' . $ext);
150
-			$i++;
151
-		}
152
-
153
-		return $path;
154
-	}
155
-
156
-	/**
157
-	 * Format a path to be relative to the /user/files/ directory
158
-	 *
159
-	 * @param string $path the absolute path
160
-	 * @return string e.g. turns '/admin/files/test.txt' into '/test.txt'
161
-	 * @throws \OCA\Files_Sharing\Exceptions\BrokenPath
162
-	 */
163
-	protected function stripUserFilesPath($path) {
164
-		$trimmed = ltrim($path, '/');
165
-		$split = explode('/', $trimmed);
166
-
167
-		// it is not a file relative to data/user/files
168
-		if (count($split) < 3 || $split[1] !== 'files') {
169
-			\OCP\Util::writeLog('file sharing',
170
-				'Can not strip userid and "files/" from path: ' . $path,
171
-				\OCP\Util::ERROR);
172
-			throw new \OCA\Files_Sharing\Exceptions\BrokenPath('Path does not start with /user/files', 10);
173
-		}
174
-
175
-		// skip 'user' and 'files'
176
-		$sliced = array_slice($split, 2);
177
-		$relPath = implode('/', $sliced);
178
-
179
-		return '/' . $relPath;
180
-	}
181
-
182
-	/**
183
-	 * Move the mount point to $target
184
-	 *
185
-	 * @param string $target the target mount point
186
-	 * @return bool
187
-	 */
188
-	public function moveMount($target) {
189
-
190
-		$relTargetPath = $this->stripUserFilesPath($target);
191
-		$share = $this->storage->getShare();
192
-
193
-		$result = true;
194
-
195
-		try {
196
-			$this->updateFileTarget($relTargetPath, $share);
197
-			$this->setMountPoint($target);
198
-			$this->storage->setMountPoint($relTargetPath);
199
-		} catch (\Exception $e) {
200
-			\OCP\Util::writeLog('file sharing',
201
-				'Could not rename mount point for shared folder "' . $this->getMountPoint() . '" to "' . $target . '"',
202
-				\OCP\Util::ERROR);
203
-		}
204
-
205
-		return $result;
206
-	}
207
-
208
-	/**
209
-	 * Remove the mount points
210
-	 *
211
-	 * @return bool
212
-	 */
213
-	public function removeMount() {
214
-		$mountManager = \OC\Files\Filesystem::getMountManager();
215
-		/** @var $storage \OCA\Files_Sharing\SharedStorage */
216
-		$storage = $this->getStorage();
217
-		$result = $storage->unshareStorage();
218
-		$mountManager->removeMount($this->mountPoint);
219
-
220
-		return $result;
221
-	}
222
-
223
-	/**
224
-	 * @return \OCP\Share\IShare
225
-	 */
226
-	public function getShare() {
227
-		return $this->superShare;
228
-	}
229
-
230
-	/**
231
-	 * Get the file id of the root of the storage
232
-	 *
233
-	 * @return int
234
-	 */
235
-	public function getStorageRootId() {
236
-		return $this->getShare()->getNodeId();
237
-	}
238
-
239
-	/**
240
-	 * @return int
241
-	 */
242
-	public function getNumericStorageId() {
243
-		if (!is_null($this->getShare()->getNodeCacheEntry())) {
244
-			return $this->getShare()->getNodeCacheEntry()->getStorageId();
245
-		} else {
246
-			$builder = \OC::$server->getDatabaseConnection()->getQueryBuilder();
247
-
248
-			$query = $builder->select('storage')
249
-				->from('filecache')
250
-				->where($builder->expr()->eq('fileid', $builder->createNamedParameter($this->getStorageRootId())));
251
-
252
-			$result = $query->execute();
253
-			$row = $result->fetch();
254
-			$result->closeCursor();
255
-			if ($row) {
256
-				return (int)$row['storage'];
257
-			}
258
-			return -1;
259
-		}
260
-	}
261
-
262
-	public function getMountType() {
263
-		return 'shared';
264
-	}
39
+    /**
40
+     * @var \OCA\Files_Sharing\SharedStorage $storage
41
+     */
42
+    protected $storage = null;
43
+
44
+    /**
45
+     * @var \OC\Files\View
46
+     */
47
+    private $recipientView;
48
+
49
+    /**
50
+     * @var string
51
+     */
52
+    private $user;
53
+
54
+    /** @var \OCP\Share\IShare */
55
+    private $superShare;
56
+
57
+    /** @var \OCP\Share\IShare[] */
58
+    private $groupedShares;
59
+
60
+    /**
61
+     * @param string $storage
62
+     * @param SharedMount[] $mountpoints
63
+     * @param array|null $arguments
64
+     * @param \OCP\Files\Storage\IStorageFactory $loader
65
+     */
66
+    public function __construct($storage, array $mountpoints, $arguments = null, $loader = null) {
67
+        $this->user = $arguments['user'];
68
+        $this->recipientView = new View('/' . $this->user . '/files');
69
+
70
+        $this->superShare = $arguments['superShare'];
71
+        $this->groupedShares = $arguments['groupedShares'];
72
+
73
+        $newMountPoint = $this->verifyMountPoint($this->superShare, $mountpoints);
74
+        $absMountPoint = '/' . $this->user . '/files' . $newMountPoint;
75
+        $arguments['ownerView'] = new View('/' . $this->superShare->getShareOwner() . '/files');
76
+        parent::__construct($storage, $absMountPoint, $arguments, $loader);
77
+    }
78
+
79
+    /**
80
+     * check if the parent folder exists otherwise move the mount point up
81
+     *
82
+     * @param \OCP\Share\IShare $share
83
+     * @param SharedMount[] $mountpoints
84
+     * @return string
85
+     */
86
+    private function verifyMountPoint(\OCP\Share\IShare $share, array $mountpoints) {
87
+
88
+        $mountPoint = basename($share->getTarget());
89
+        $parent = dirname($share->getTarget());
90
+
91
+        if (!$this->recipientView->is_dir($parent)) {
92
+            $parent = Helper::getShareFolder($this->recipientView);
93
+        }
94
+
95
+        $newMountPoint = $this->generateUniqueTarget(
96
+            \OC\Files\Filesystem::normalizePath($parent . '/' . $mountPoint),
97
+            $this->recipientView,
98
+            $mountpoints
99
+        );
100
+
101
+        if ($newMountPoint !== $share->getTarget()) {
102
+            $this->updateFileTarget($newMountPoint, $share);
103
+        }
104
+
105
+        return $newMountPoint;
106
+    }
107
+
108
+    /**
109
+     * update fileTarget in the database if the mount point changed
110
+     *
111
+     * @param string $newPath
112
+     * @param \OCP\Share\IShare $share
113
+     * @return bool
114
+     */
115
+    private function updateFileTarget($newPath, &$share) {
116
+        $share->setTarget($newPath);
117
+
118
+        foreach ($this->groupedShares as $tmpShare) {
119
+            $tmpShare->setTarget($newPath);
120
+            \OC::$server->getShareManager()->moveShare($tmpShare, $this->user);
121
+        }
122
+    }
123
+
124
+
125
+    /**
126
+     * @param string $path
127
+     * @param View $view
128
+     * @param SharedMount[] $mountpoints
129
+     * @return mixed
130
+     */
131
+    private function generateUniqueTarget($path, $view, array $mountpoints) {
132
+        $pathinfo = pathinfo($path);
133
+        $ext = (isset($pathinfo['extension'])) ? '.' . $pathinfo['extension'] : '';
134
+        $name = $pathinfo['filename'];
135
+        $dir = $pathinfo['dirname'];
136
+
137
+        // Helper function to find existing mount points
138
+        $mountpointExists = function ($path) use ($mountpoints) {
139
+            foreach ($mountpoints as $mountpoint) {
140
+                if ($mountpoint->getShare()->getTarget() === $path) {
141
+                    return true;
142
+                }
143
+            }
144
+            return false;
145
+        };
146
+
147
+        $i = 2;
148
+        while ($view->file_exists($path) || $mountpointExists($path)) {
149
+            $path = Filesystem::normalizePath($dir . '/' . $name . ' (' . $i . ')' . $ext);
150
+            $i++;
151
+        }
152
+
153
+        return $path;
154
+    }
155
+
156
+    /**
157
+     * Format a path to be relative to the /user/files/ directory
158
+     *
159
+     * @param string $path the absolute path
160
+     * @return string e.g. turns '/admin/files/test.txt' into '/test.txt'
161
+     * @throws \OCA\Files_Sharing\Exceptions\BrokenPath
162
+     */
163
+    protected function stripUserFilesPath($path) {
164
+        $trimmed = ltrim($path, '/');
165
+        $split = explode('/', $trimmed);
166
+
167
+        // it is not a file relative to data/user/files
168
+        if (count($split) < 3 || $split[1] !== 'files') {
169
+            \OCP\Util::writeLog('file sharing',
170
+                'Can not strip userid and "files/" from path: ' . $path,
171
+                \OCP\Util::ERROR);
172
+            throw new \OCA\Files_Sharing\Exceptions\BrokenPath('Path does not start with /user/files', 10);
173
+        }
174
+
175
+        // skip 'user' and 'files'
176
+        $sliced = array_slice($split, 2);
177
+        $relPath = implode('/', $sliced);
178
+
179
+        return '/' . $relPath;
180
+    }
181
+
182
+    /**
183
+     * Move the mount point to $target
184
+     *
185
+     * @param string $target the target mount point
186
+     * @return bool
187
+     */
188
+    public function moveMount($target) {
189
+
190
+        $relTargetPath = $this->stripUserFilesPath($target);
191
+        $share = $this->storage->getShare();
192
+
193
+        $result = true;
194
+
195
+        try {
196
+            $this->updateFileTarget($relTargetPath, $share);
197
+            $this->setMountPoint($target);
198
+            $this->storage->setMountPoint($relTargetPath);
199
+        } catch (\Exception $e) {
200
+            \OCP\Util::writeLog('file sharing',
201
+                'Could not rename mount point for shared folder "' . $this->getMountPoint() . '" to "' . $target . '"',
202
+                \OCP\Util::ERROR);
203
+        }
204
+
205
+        return $result;
206
+    }
207
+
208
+    /**
209
+     * Remove the mount points
210
+     *
211
+     * @return bool
212
+     */
213
+    public function removeMount() {
214
+        $mountManager = \OC\Files\Filesystem::getMountManager();
215
+        /** @var $storage \OCA\Files_Sharing\SharedStorage */
216
+        $storage = $this->getStorage();
217
+        $result = $storage->unshareStorage();
218
+        $mountManager->removeMount($this->mountPoint);
219
+
220
+        return $result;
221
+    }
222
+
223
+    /**
224
+     * @return \OCP\Share\IShare
225
+     */
226
+    public function getShare() {
227
+        return $this->superShare;
228
+    }
229
+
230
+    /**
231
+     * Get the file id of the root of the storage
232
+     *
233
+     * @return int
234
+     */
235
+    public function getStorageRootId() {
236
+        return $this->getShare()->getNodeId();
237
+    }
238
+
239
+    /**
240
+     * @return int
241
+     */
242
+    public function getNumericStorageId() {
243
+        if (!is_null($this->getShare()->getNodeCacheEntry())) {
244
+            return $this->getShare()->getNodeCacheEntry()->getStorageId();
245
+        } else {
246
+            $builder = \OC::$server->getDatabaseConnection()->getQueryBuilder();
247
+
248
+            $query = $builder->select('storage')
249
+                ->from('filecache')
250
+                ->where($builder->expr()->eq('fileid', $builder->createNamedParameter($this->getStorageRootId())));
251
+
252
+            $result = $query->execute();
253
+            $row = $result->fetch();
254
+            $result->closeCursor();
255
+            if ($row) {
256
+                return (int)$row['storage'];
257
+            }
258
+            return -1;
259
+        }
260
+    }
261
+
262
+    public function getMountType() {
263
+        return 'shared';
264
+    }
265 265
 }
Please login to merge, or discard this patch.
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
@@ -51,10 +51,10 @@  discard block
 block discarded – undo
51 51
 			$rootView = new View();
52 52
 			$user = \OC::$server->getUserSession()->getUser();
53 53
 			Filesystem::initMountPoints($user->getUID());
54
-			if (!$rootView->file_exists('/' . $user->getUID() . '/cache')) {
55
-				$rootView->mkdir('/' . $user->getUID() . '/cache');
54
+			if (!$rootView->file_exists('/'.$user->getUID().'/cache')) {
55
+				$rootView->mkdir('/'.$user->getUID().'/cache');
56 56
 			}
57
-			$this->storage = new View('/' . $user->getUID() . '/cache');
57
+			$this->storage = new View('/'.$user->getUID().'/cache');
58 58
 			return $this->storage;
59 59
 		} else {
60 60
 			\OCP\Util::writeLog('core', 'Can\'t get cache storage, user not logged in', \OCP\Util::ERROR);
@@ -104,12 +104,12 @@  discard block
 block discarded – undo
104 104
 		// unique id to avoid chunk collision, just in case
105 105
 		$uniqueId = \OC::$server->getSecureRandom()->generate(
106 106
 			16,
107
-			ISecureRandom::CHAR_DIGITS . ISecureRandom::CHAR_LOWER . ISecureRandom::CHAR_UPPER
107
+			ISecureRandom::CHAR_DIGITS.ISecureRandom::CHAR_LOWER.ISecureRandom::CHAR_UPPER
108 108
 		);
109 109
 
110 110
 		// use part file to prevent hasKey() to find the key
111 111
 		// while it is being written
112
-		$keyPart = $key . '.' . $uniqueId . '.part';
112
+		$keyPart = $key.'.'.$uniqueId.'.part';
113 113
 		if ($storage and $storage->file_put_contents($keyPart, $value)) {
114 114
 			if ($ttl === 0) {
115 115
 				$ttl = 86400; // 60*60*24
@@ -158,7 +158,7 @@  discard block
 block discarded – undo
158 158
 			if (is_resource($dh)) {
159 159
 				while (($file = readdir($dh)) !== false) {
160 160
 					if ($file != '.' and $file != '..' and ($prefix === '' || strpos($file, $prefix) === 0)) {
161
-						$storage->unlink('/' . $file);
161
+						$storage->unlink('/'.$file);
162 162
 					}
163 163
 				}
164 164
 			}
@@ -183,17 +183,17 @@  discard block
 block discarded – undo
183 183
 			while (($file = readdir($dh)) !== false) {
184 184
 				if ($file != '.' and $file != '..') {
185 185
 					try {
186
-						$mtime = $storage->filemtime('/' . $file);
186
+						$mtime = $storage->filemtime('/'.$file);
187 187
 						if ($mtime < $now) {
188
-							$storage->unlink('/' . $file);
188
+							$storage->unlink('/'.$file);
189 189
 						}
190 190
 					} catch (\OCP\Lock\LockedException $e) {
191 191
 						// ignore locked chunks
192
-						\OC::$server->getLogger()->debug('Could not cleanup locked chunk "' . $file . '"', array('app' => 'core'));
192
+						\OC::$server->getLogger()->debug('Could not cleanup locked chunk "'.$file.'"', array('app' => 'core'));
193 193
 					} catch (\OCP\Files\ForbiddenException $e) {
194
-						\OC::$server->getLogger()->debug('Could not cleanup forbidden chunk "' . $file . '"', array('app' => 'core'));
194
+						\OC::$server->getLogger()->debug('Could not cleanup forbidden chunk "'.$file.'"', array('app' => 'core'));
195 195
 					} catch (\OCP\Files\LockNotAcquiredException $e) {
196
-						\OC::$server->getLogger()->debug('Could not cleanup locked chunk "' . $file . '"', array('app' => 'core'));
196
+						\OC::$server->getLogger()->debug('Could not cleanup locked chunk "'.$file.'"', array('app' => 'core'));
197 197
 					}
198 198
 				}
199 199
 			}
Please login to merge, or discard this patch.
Indentation   +157 added lines, -157 removed lines patch added patch discarded remove patch
@@ -33,170 +33,170 @@
 block discarded – undo
33 33
 
34 34
 class File implements ICache {
35 35
 
36
-	/** @var View */
37
-	protected $storage;
36
+    /** @var View */
37
+    protected $storage;
38 38
 
39
-	/**
40
-	 * Returns the cache storage for the logged in user
41
-	 *
42
-	 * @return \OC\Files\View cache storage
43
-	 * @throws \OC\ForbiddenException
44
-	 * @throws \OC\User\NoUserException
45
-	 */
46
-	protected function getStorage() {
47
-		if (isset($this->storage)) {
48
-			return $this->storage;
49
-		}
50
-		if (\OC::$server->getUserSession()->isLoggedIn()) {
51
-			$rootView = new View();
52
-			$user = \OC::$server->getUserSession()->getUser();
53
-			Filesystem::initMountPoints($user->getUID());
54
-			if (!$rootView->file_exists('/' . $user->getUID() . '/cache')) {
55
-				$rootView->mkdir('/' . $user->getUID() . '/cache');
56
-			}
57
-			$this->storage = new View('/' . $user->getUID() . '/cache');
58
-			return $this->storage;
59
-		} else {
60
-			\OCP\Util::writeLog('core', 'Can\'t get cache storage, user not logged in', \OCP\Util::ERROR);
61
-			throw new \OC\ForbiddenException('Can\t get cache storage, user not logged in');
62
-		}
63
-	}
39
+    /**
40
+     * Returns the cache storage for the logged in user
41
+     *
42
+     * @return \OC\Files\View cache storage
43
+     * @throws \OC\ForbiddenException
44
+     * @throws \OC\User\NoUserException
45
+     */
46
+    protected function getStorage() {
47
+        if (isset($this->storage)) {
48
+            return $this->storage;
49
+        }
50
+        if (\OC::$server->getUserSession()->isLoggedIn()) {
51
+            $rootView = new View();
52
+            $user = \OC::$server->getUserSession()->getUser();
53
+            Filesystem::initMountPoints($user->getUID());
54
+            if (!$rootView->file_exists('/' . $user->getUID() . '/cache')) {
55
+                $rootView->mkdir('/' . $user->getUID() . '/cache');
56
+            }
57
+            $this->storage = new View('/' . $user->getUID() . '/cache');
58
+            return $this->storage;
59
+        } else {
60
+            \OCP\Util::writeLog('core', 'Can\'t get cache storage, user not logged in', \OCP\Util::ERROR);
61
+            throw new \OC\ForbiddenException('Can\t get cache storage, user not logged in');
62
+        }
63
+    }
64 64
 
65
-	/**
66
-	 * @param string $key
67
-	 * @return mixed|null
68
-	 * @throws \OC\ForbiddenException
69
-	 */
70
-	public function get($key) {
71
-		$result = null;
72
-		if ($this->hasKey($key)) {
73
-			$storage = $this->getStorage();
74
-			$result = $storage->file_get_contents($key);
75
-		}
76
-		return $result;
77
-	}
65
+    /**
66
+     * @param string $key
67
+     * @return mixed|null
68
+     * @throws \OC\ForbiddenException
69
+     */
70
+    public function get($key) {
71
+        $result = null;
72
+        if ($this->hasKey($key)) {
73
+            $storage = $this->getStorage();
74
+            $result = $storage->file_get_contents($key);
75
+        }
76
+        return $result;
77
+    }
78 78
 
79
-	/**
80
-	 * Returns the size of the stored/cached data
81
-	 *
82
-	 * @param string $key
83
-	 * @return int
84
-	 */
85
-	public function size($key) {
86
-		$result = 0;
87
-		if ($this->hasKey($key)) {
88
-			$storage = $this->getStorage();
89
-			$result = $storage->filesize($key);
90
-		}
91
-		return $result;
92
-	}
79
+    /**
80
+     * Returns the size of the stored/cached data
81
+     *
82
+     * @param string $key
83
+     * @return int
84
+     */
85
+    public function size($key) {
86
+        $result = 0;
87
+        if ($this->hasKey($key)) {
88
+            $storage = $this->getStorage();
89
+            $result = $storage->filesize($key);
90
+        }
91
+        return $result;
92
+    }
93 93
 
94
-	/**
95
-	 * @param string $key
96
-	 * @param mixed $value
97
-	 * @param int $ttl
98
-	 * @return bool|mixed
99
-	 * @throws \OC\ForbiddenException
100
-	 */
101
-	public function set($key, $value, $ttl = 0) {
102
-		$storage = $this->getStorage();
103
-		$result = false;
104
-		// unique id to avoid chunk collision, just in case
105
-		$uniqueId = \OC::$server->getSecureRandom()->generate(
106
-			16,
107
-			ISecureRandom::CHAR_DIGITS . ISecureRandom::CHAR_LOWER . ISecureRandom::CHAR_UPPER
108
-		);
94
+    /**
95
+     * @param string $key
96
+     * @param mixed $value
97
+     * @param int $ttl
98
+     * @return bool|mixed
99
+     * @throws \OC\ForbiddenException
100
+     */
101
+    public function set($key, $value, $ttl = 0) {
102
+        $storage = $this->getStorage();
103
+        $result = false;
104
+        // unique id to avoid chunk collision, just in case
105
+        $uniqueId = \OC::$server->getSecureRandom()->generate(
106
+            16,
107
+            ISecureRandom::CHAR_DIGITS . ISecureRandom::CHAR_LOWER . ISecureRandom::CHAR_UPPER
108
+        );
109 109
 
110
-		// use part file to prevent hasKey() to find the key
111
-		// while it is being written
112
-		$keyPart = $key . '.' . $uniqueId . '.part';
113
-		if ($storage and $storage->file_put_contents($keyPart, $value)) {
114
-			if ($ttl === 0) {
115
-				$ttl = 86400; // 60*60*24
116
-			}
117
-			$result = $storage->touch($keyPart, time() + $ttl);
118
-			$result &= $storage->rename($keyPart, $key);
119
-		}
120
-		return $result;
121
-	}
110
+        // use part file to prevent hasKey() to find the key
111
+        // while it is being written
112
+        $keyPart = $key . '.' . $uniqueId . '.part';
113
+        if ($storage and $storage->file_put_contents($keyPart, $value)) {
114
+            if ($ttl === 0) {
115
+                $ttl = 86400; // 60*60*24
116
+            }
117
+            $result = $storage->touch($keyPart, time() + $ttl);
118
+            $result &= $storage->rename($keyPart, $key);
119
+        }
120
+        return $result;
121
+    }
122 122
 
123
-	/**
124
-	 * @param string $key
125
-	 * @return bool
126
-	 * @throws \OC\ForbiddenException
127
-	 */
128
-	public function hasKey($key) {
129
-		$storage = $this->getStorage();
130
-		if ($storage && $storage->is_file($key) && $storage->isReadable($key)) {
131
-			return true;
132
-		}
133
-		return false;
134
-	}
123
+    /**
124
+     * @param string $key
125
+     * @return bool
126
+     * @throws \OC\ForbiddenException
127
+     */
128
+    public function hasKey($key) {
129
+        $storage = $this->getStorage();
130
+        if ($storage && $storage->is_file($key) && $storage->isReadable($key)) {
131
+            return true;
132
+        }
133
+        return false;
134
+    }
135 135
 
136
-	/**
137
-	 * @param string $key
138
-	 * @return bool|mixed
139
-	 * @throws \OC\ForbiddenException
140
-	 */
141
-	public function remove($key) {
142
-		$storage = $this->getStorage();
143
-		if (!$storage) {
144
-			return false;
145
-		}
146
-		return $storage->unlink($key);
147
-	}
136
+    /**
137
+     * @param string $key
138
+     * @return bool|mixed
139
+     * @throws \OC\ForbiddenException
140
+     */
141
+    public function remove($key) {
142
+        $storage = $this->getStorage();
143
+        if (!$storage) {
144
+            return false;
145
+        }
146
+        return $storage->unlink($key);
147
+    }
148 148
 
149
-	/**
150
-	 * @param string $prefix
151
-	 * @return bool
152
-	 * @throws \OC\ForbiddenException
153
-	 */
154
-	public function clear($prefix = '') {
155
-		$storage = $this->getStorage();
156
-		if ($storage and $storage->is_dir('/')) {
157
-			$dh = $storage->opendir('/');
158
-			if (is_resource($dh)) {
159
-				while (($file = readdir($dh)) !== false) {
160
-					if ($file != '.' and $file != '..' and ($prefix === '' || strpos($file, $prefix) === 0)) {
161
-						$storage->unlink('/' . $file);
162
-					}
163
-				}
164
-			}
165
-		}
166
-		return true;
167
-	}
149
+    /**
150
+     * @param string $prefix
151
+     * @return bool
152
+     * @throws \OC\ForbiddenException
153
+     */
154
+    public function clear($prefix = '') {
155
+        $storage = $this->getStorage();
156
+        if ($storage and $storage->is_dir('/')) {
157
+            $dh = $storage->opendir('/');
158
+            if (is_resource($dh)) {
159
+                while (($file = readdir($dh)) !== false) {
160
+                    if ($file != '.' and $file != '..' and ($prefix === '' || strpos($file, $prefix) === 0)) {
161
+                        $storage->unlink('/' . $file);
162
+                    }
163
+                }
164
+            }
165
+        }
166
+        return true;
167
+    }
168 168
 
169
-	/**
170
-	 * Runs GC
171
-	 * @throws \OC\ForbiddenException
172
-	 */
173
-	public function gc() {
174
-		$storage = $this->getStorage();
175
-		if ($storage and $storage->is_dir('/')) {
176
-			// extra hour safety, in case of stray part chunks that take longer to write,
177
-			// because touch() is only called after the chunk was finished
178
-			$now = time() - 3600;
179
-			$dh = $storage->opendir('/');
180
-			if (!is_resource($dh)) {
181
-				return null;
182
-			}
183
-			while (($file = readdir($dh)) !== false) {
184
-				if ($file != '.' and $file != '..') {
185
-					try {
186
-						$mtime = $storage->filemtime('/' . $file);
187
-						if ($mtime < $now) {
188
-							$storage->unlink('/' . $file);
189
-						}
190
-					} catch (\OCP\Lock\LockedException $e) {
191
-						// ignore locked chunks
192
-						\OC::$server->getLogger()->debug('Could not cleanup locked chunk "' . $file . '"', array('app' => 'core'));
193
-					} catch (\OCP\Files\ForbiddenException $e) {
194
-						\OC::$server->getLogger()->debug('Could not cleanup forbidden chunk "' . $file . '"', array('app' => 'core'));
195
-					} catch (\OCP\Files\LockNotAcquiredException $e) {
196
-						\OC::$server->getLogger()->debug('Could not cleanup locked chunk "' . $file . '"', array('app' => 'core'));
197
-					}
198
-				}
199
-			}
200
-		}
201
-	}
169
+    /**
170
+     * Runs GC
171
+     * @throws \OC\ForbiddenException
172
+     */
173
+    public function gc() {
174
+        $storage = $this->getStorage();
175
+        if ($storage and $storage->is_dir('/')) {
176
+            // extra hour safety, in case of stray part chunks that take longer to write,
177
+            // because touch() is only called after the chunk was finished
178
+            $now = time() - 3600;
179
+            $dh = $storage->opendir('/');
180
+            if (!is_resource($dh)) {
181
+                return null;
182
+            }
183
+            while (($file = readdir($dh)) !== false) {
184
+                if ($file != '.' and $file != '..') {
185
+                    try {
186
+                        $mtime = $storage->filemtime('/' . $file);
187
+                        if ($mtime < $now) {
188
+                            $storage->unlink('/' . $file);
189
+                        }
190
+                    } catch (\OCP\Lock\LockedException $e) {
191
+                        // ignore locked chunks
192
+                        \OC::$server->getLogger()->debug('Could not cleanup locked chunk "' . $file . '"', array('app' => 'core'));
193
+                    } catch (\OCP\Files\ForbiddenException $e) {
194
+                        \OC::$server->getLogger()->debug('Could not cleanup forbidden chunk "' . $file . '"', array('app' => 'core'));
195
+                    } catch (\OCP\Files\LockNotAcquiredException $e) {
196
+                        \OC::$server->getLogger()->debug('Could not cleanup locked chunk "' . $file . '"', array('app' => 'core'));
197
+                    }
198
+                }
199
+            }
200
+        }
201
+    }
202 202
 }
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.
Spacing   +9 added lines, -9 removed lines patch added patch discarded remove patch
@@ -167,7 +167,7 @@  discard block
 block discarded – undo
167 167
 	 */
168 168
 	protected function checkPasswordResetToken($token, $userId) {
169 169
 		$user = $this->userManager->get($userId);
170
-		if($user === null || !$user->isEnabled()) {
170
+		if ($user === null || !$user->isEnabled()) {
171 171
 			throw new \Exception($this->l10n->t('Couldn\'t reset password because the token is invalid'));
172 172
 		}
173 173
 
@@ -180,11 +180,11 @@  discard block
 block discarded – undo
180 180
 		}
181 181
 
182 182
 		$splittedToken = explode(':', $decryptedToken);
183
-		if(count($splittedToken) !== 2) {
183
+		if (count($splittedToken) !== 2) {
184 184
 			throw new \Exception($this->l10n->t('Couldn\'t reset password because the token is invalid'));
185 185
 		}
186 186
 
187
-		if ($splittedToken[0] < ($this->timeFactory->getTime() - 60*60*12) ||
187
+		if ($splittedToken[0] < ($this->timeFactory->getTime() - 60 * 60 * 12) ||
188 188
 			$user->getLastLogin() > $splittedToken[0]) {
189 189
 			throw new \Exception($this->l10n->t('Couldn\'t reset password because the token is expired'));
190 190
 		}
@@ -199,7 +199,7 @@  discard block
 block discarded – undo
199 199
 	 * @param array $additional
200 200
 	 * @return array
201 201
 	 */
202
-	private function error($message, array $additional=array()) {
202
+	private function error($message, array $additional = array()) {
203 203
 		return array_merge(array('status' => 'error', 'msg' => $message), $additional);
204 204
 	}
205 205
 
@@ -218,7 +218,7 @@  discard block
 block discarded – undo
218 218
 	 * @param string $user
219 219
 	 * @return JSONResponse
220 220
 	 */
221
-	public function email($user){
221
+	public function email($user) {
222 222
 		if ($this->config->getSystemValue('lost_password_link', '') !== '') {
223 223
 			return new JSONResponse($this->error($this->l10n->t('Password reset is disabled')));
224 224
 		}
@@ -226,7 +226,7 @@  discard block
 block discarded – undo
226 226
 		// FIXME: use HTTP error codes
227 227
 		try {
228 228
 			$this->sendEmail($user);
229
-		} catch (\Exception $e){
229
+		} catch (\Exception $e) {
230 230
 			$response = new JSONResponse($this->error($e->getMessage()));
231 231
 			$response->throttle();
232 232
 			return $response;
@@ -268,7 +268,7 @@  discard block
 block discarded – undo
268 268
 
269 269
 			$this->config->deleteUserValue($userId, 'core', 'lostpassword');
270 270
 			@\OC::$server->getUserSession()->unsetMagicInCookie();
271
-		} catch (\Exception $e){
271
+		} catch (\Exception $e) {
272 272
 			return $this->error($e->getMessage());
273 273
 		}
274 274
 
@@ -299,8 +299,8 @@  discard block
 block discarded – undo
299 299
 			ISecureRandom::CHAR_LOWER.
300 300
 			ISecureRandom::CHAR_UPPER
301 301
 		);
302
-		$tokenValue = $this->timeFactory->getTime() .':'. $token;
303
-		$encryptedValue = $this->crypto->encrypt($tokenValue, $email . $this->config->getSystemValue('secret'));
302
+		$tokenValue = $this->timeFactory->getTime().':'.$token;
303
+		$encryptedValue = $this->crypto->encrypt($tokenValue, $email.$this->config->getSystemValue('secret'));
304 304
 		$this->config->setUserValue($user->getUID(), 'core', 'lostpassword', $encryptedValue);
305 305
 
306 306
 		$link = $this->urlGenerator->linkToRouteAbsolute('core.lost.resetform', array('userId' => $user->getUID(), 'token' => $token));
Please login to merge, or discard this patch.
Indentation   +309 added lines, -309 removed lines patch added patch discarded remove patch
@@ -55,313 +55,313 @@
 block discarded – undo
55 55
  */
56 56
 class LostController extends Controller {
57 57
 
58
-	/** @var IURLGenerator */
59
-	protected $urlGenerator;
60
-	/** @var IUserManager */
61
-	protected $userManager;
62
-	/** @var Defaults */
63
-	protected $defaults;
64
-	/** @var IL10N */
65
-	protected $l10n;
66
-	/** @var string */
67
-	protected $from;
68
-	/** @var IManager */
69
-	protected $encryptionManager;
70
-	/** @var IConfig */
71
-	protected $config;
72
-	/** @var ISecureRandom */
73
-	protected $secureRandom;
74
-	/** @var IMailer */
75
-	protected $mailer;
76
-	/** @var ITimeFactory */
77
-	protected $timeFactory;
78
-	/** @var ICrypto */
79
-	protected $crypto;
80
-
81
-	/**
82
-	 * @param string $appName
83
-	 * @param IRequest $request
84
-	 * @param IURLGenerator $urlGenerator
85
-	 * @param IUserManager $userManager
86
-	 * @param Defaults $defaults
87
-	 * @param IL10N $l10n
88
-	 * @param IConfig $config
89
-	 * @param ISecureRandom $secureRandom
90
-	 * @param string $defaultMailAddress
91
-	 * @param IManager $encryptionManager
92
-	 * @param IMailer $mailer
93
-	 * @param ITimeFactory $timeFactory
94
-	 * @param ICrypto $crypto
95
-	 */
96
-	public function __construct($appName,
97
-								IRequest $request,
98
-								IURLGenerator $urlGenerator,
99
-								IUserManager $userManager,
100
-								Defaults $defaults,
101
-								IL10N $l10n,
102
-								IConfig $config,
103
-								ISecureRandom $secureRandom,
104
-								$defaultMailAddress,
105
-								IManager $encryptionManager,
106
-								IMailer $mailer,
107
-								ITimeFactory $timeFactory,
108
-								ICrypto $crypto) {
109
-		parent::__construct($appName, $request);
110
-		$this->urlGenerator = $urlGenerator;
111
-		$this->userManager = $userManager;
112
-		$this->defaults = $defaults;
113
-		$this->l10n = $l10n;
114
-		$this->secureRandom = $secureRandom;
115
-		$this->from = $defaultMailAddress;
116
-		$this->encryptionManager = $encryptionManager;
117
-		$this->config = $config;
118
-		$this->mailer = $mailer;
119
-		$this->timeFactory = $timeFactory;
120
-		$this->crypto = $crypto;
121
-	}
122
-
123
-	/**
124
-	 * Someone wants to reset their password:
125
-	 *
126
-	 * @PublicPage
127
-	 * @NoCSRFRequired
128
-	 *
129
-	 * @param string $token
130
-	 * @param string $userId
131
-	 * @return TemplateResponse
132
-	 */
133
-	public function resetform($token, $userId) {
134
-		if ($this->config->getSystemValue('lost_password_link', '') !== '') {
135
-			return new TemplateResponse('core', 'error', [
136
-					'errors' => [['error' => $this->l10n->t('Password reset is disabled')]]
137
-				],
138
-				'guest'
139
-			);
140
-		}
141
-
142
-		try {
143
-			$this->checkPasswordResetToken($token, $userId);
144
-		} catch (\Exception $e) {
145
-			return new TemplateResponse(
146
-				'core', 'error', [
147
-					"errors" => array(array("error" => $e->getMessage()))
148
-				],
149
-				'guest'
150
-			);
151
-		}
152
-
153
-		return new TemplateResponse(
154
-			'core',
155
-			'lostpassword/resetpassword',
156
-			array(
157
-				'link' => $this->urlGenerator->linkToRouteAbsolute('core.lost.setPassword', array('userId' => $userId, 'token' => $token)),
158
-			),
159
-			'guest'
160
-		);
161
-	}
162
-
163
-	/**
164
-	 * @param string $token
165
-	 * @param string $userId
166
-	 * @throws \Exception
167
-	 */
168
-	protected function checkPasswordResetToken($token, $userId) {
169
-		$user = $this->userManager->get($userId);
170
-		if($user === null || !$user->isEnabled()) {
171
-			throw new \Exception($this->l10n->t('Couldn\'t reset password because the token is invalid'));
172
-		}
173
-
174
-		try {
175
-			$encryptedToken = $this->config->getUserValue($userId, 'core', 'lostpassword', null);
176
-			$mailAddress = !is_null($user->getEMailAddress()) ? $user->getEMailAddress() : '';
177
-			$decryptedToken = $this->crypto->decrypt($encryptedToken, $mailAddress.$this->config->getSystemValue('secret'));
178
-		} catch (\Exception $e) {
179
-			throw new \Exception($this->l10n->t('Couldn\'t reset password because the token is invalid'));
180
-		}
181
-
182
-		$splittedToken = explode(':', $decryptedToken);
183
-		if(count($splittedToken) !== 2) {
184
-			throw new \Exception($this->l10n->t('Couldn\'t reset password because the token is invalid'));
185
-		}
186
-
187
-		if ($splittedToken[0] < ($this->timeFactory->getTime() - 60*60*12) ||
188
-			$user->getLastLogin() > $splittedToken[0]) {
189
-			throw new \Exception($this->l10n->t('Couldn\'t reset password because the token is expired'));
190
-		}
191
-
192
-		if (!hash_equals($splittedToken[1], $token)) {
193
-			throw new \Exception($this->l10n->t('Couldn\'t reset password because the token is invalid'));
194
-		}
195
-	}
196
-
197
-	/**
198
-	 * @param $message
199
-	 * @param array $additional
200
-	 * @return array
201
-	 */
202
-	private function error($message, array $additional=array()) {
203
-		return array_merge(array('status' => 'error', 'msg' => $message), $additional);
204
-	}
205
-
206
-	/**
207
-	 * @return array
208
-	 */
209
-	private function success() {
210
-		return array('status'=>'success');
211
-	}
212
-
213
-	/**
214
-	 * @PublicPage
215
-	 * @BruteForceProtection(action=passwordResetEmail)
216
-	 * @AnonRateThrottle(limit=10, period=300)
217
-	 *
218
-	 * @param string $user
219
-	 * @return JSONResponse
220
-	 */
221
-	public function email($user){
222
-		if ($this->config->getSystemValue('lost_password_link', '') !== '') {
223
-			return new JSONResponse($this->error($this->l10n->t('Password reset is disabled')));
224
-		}
225
-
226
-		// FIXME: use HTTP error codes
227
-		try {
228
-			$this->sendEmail($user);
229
-		} catch (\Exception $e){
230
-			$response = new JSONResponse($this->error($e->getMessage()));
231
-			$response->throttle();
232
-			return $response;
233
-		}
234
-
235
-		$response = new JSONResponse($this->success());
236
-		$response->throttle();
237
-		return $response;
238
-	}
239
-
240
-	/**
241
-	 * @PublicPage
242
-	 * @param string $token
243
-	 * @param string $userId
244
-	 * @param string $password
245
-	 * @param boolean $proceed
246
-	 * @return array
247
-	 */
248
-	public function setPassword($token, $userId, $password, $proceed) {
249
-		if ($this->config->getSystemValue('lost_password_link', '') !== '') {
250
-			return $this->error($this->l10n->t('Password reset is disabled'));
251
-		}
252
-
253
-		if ($this->encryptionManager->isEnabled() && !$proceed) {
254
-			return $this->error('', array('encryption' => true));
255
-		}
256
-
257
-		try {
258
-			$this->checkPasswordResetToken($token, $userId);
259
-			$user = $this->userManager->get($userId);
260
-
261
-			\OC_Hook::emit('\OC\Core\LostPassword\Controller\LostController', 'pre_passwordReset', array('uid' => $userId, 'password' => $password));
262
-
263
-			if (!$user->setPassword($password)) {
264
-				throw new \Exception();
265
-			}
266
-
267
-			\OC_Hook::emit('\OC\Core\LostPassword\Controller\LostController', 'post_passwordReset', array('uid' => $userId, 'password' => $password));
268
-
269
-			$this->config->deleteUserValue($userId, 'core', 'lostpassword');
270
-			@\OC::$server->getUserSession()->unsetMagicInCookie();
271
-		} catch (\Exception $e){
272
-			return $this->error($e->getMessage());
273
-		}
274
-
275
-		return $this->success();
276
-	}
277
-
278
-	/**
279
-	 * @param string $input
280
-	 * @throws \Exception
281
-	 */
282
-	protected function sendEmail($input) {
283
-		$user = $this->findUserByIdOrMail($input);
284
-		$email = $user->getEMailAddress();
285
-
286
-		if (empty($email)) {
287
-			throw new \Exception(
288
-				$this->l10n->t('Could not send reset email because there is no email address for this username. Please contact your administrator.')
289
-			);
290
-		}
291
-
292
-		// Generate the token. It is stored encrypted in the database with the
293
-		// secret being the users' email address appended with the system secret.
294
-		// This makes the token automatically invalidate once the user changes
295
-		// their email address.
296
-		$token = $this->secureRandom->generate(
297
-			21,
298
-			ISecureRandom::CHAR_DIGITS.
299
-			ISecureRandom::CHAR_LOWER.
300
-			ISecureRandom::CHAR_UPPER
301
-		);
302
-		$tokenValue = $this->timeFactory->getTime() .':'. $token;
303
-		$encryptedValue = $this->crypto->encrypt($tokenValue, $email . $this->config->getSystemValue('secret'));
304
-		$this->config->setUserValue($user->getUID(), 'core', 'lostpassword', $encryptedValue);
305
-
306
-		$link = $this->urlGenerator->linkToRouteAbsolute('core.lost.resetform', array('userId' => $user->getUID(), 'token' => $token));
307
-
308
-		$emailTemplate = $this->mailer->createEMailTemplate('core.ResetPassword', [
309
-			'link' => $link,
310
-		]);
311
-
312
-		$emailTemplate->setSubject($this->l10n->t('%s password reset', [$this->defaults->getName()]));
313
-		$emailTemplate->addHeader();
314
-		$emailTemplate->addHeading($this->l10n->t('Password reset'));
315
-
316
-		$emailTemplate->addBodyText(
317
-			$this->l10n->t('Click the following button to reset your password. If you have not requested the password reset, then ignore this email.'),
318
-			$this->l10n->t('Click the following link to reset your password. If you have not requested the password reset, then ignore this email.')
319
-		);
320
-
321
-		$emailTemplate->addBodyButton(
322
-			$this->l10n->t('Reset your password'),
323
-			$link,
324
-			false
325
-		);
326
-		$emailTemplate->addFooter();
327
-
328
-		try {
329
-			$message = $this->mailer->createMessage();
330
-			$message->setTo([$email => $user->getUID()]);
331
-			$message->setFrom([$this->from => $this->defaults->getName()]);
332
-			$message->useTemplate($emailTemplate);
333
-			$this->mailer->send($message);
334
-		} catch (\Exception $e) {
335
-			throw new \Exception($this->l10n->t(
336
-				'Couldn\'t send reset email. Please contact your administrator.'
337
-			));
338
-		}
339
-	}
340
-
341
-	/**
342
-	 * @param string $input
343
-	 * @return IUser
344
-	 * @throws \InvalidArgumentException
345
-	 */
346
-	protected function findUserByIdOrMail($input) {
347
-		$user = $this->userManager->get($input);
348
-		if ($user instanceof IUser) {
349
-			if (!$user->isEnabled()) {
350
-				throw new \InvalidArgumentException($this->l10n->t('Couldn\'t send reset email. Please make sure your username is correct.'));
351
-			}
352
-
353
-			return $user;
354
-		}
355
-		$users = $this->userManager->getByEmail($input);
356
-		if (count($users) === 1) {
357
-			$user = $users[0];
358
-			if (!$user->isEnabled()) {
359
-				throw new \InvalidArgumentException($this->l10n->t('Couldn\'t send reset email. Please make sure your username is correct.'));
360
-			}
361
-
362
-			return $user;
363
-		}
364
-
365
-		throw new \InvalidArgumentException($this->l10n->t('Couldn\'t send reset email. Please make sure your username is correct.'));
366
-	}
58
+    /** @var IURLGenerator */
59
+    protected $urlGenerator;
60
+    /** @var IUserManager */
61
+    protected $userManager;
62
+    /** @var Defaults */
63
+    protected $defaults;
64
+    /** @var IL10N */
65
+    protected $l10n;
66
+    /** @var string */
67
+    protected $from;
68
+    /** @var IManager */
69
+    protected $encryptionManager;
70
+    /** @var IConfig */
71
+    protected $config;
72
+    /** @var ISecureRandom */
73
+    protected $secureRandom;
74
+    /** @var IMailer */
75
+    protected $mailer;
76
+    /** @var ITimeFactory */
77
+    protected $timeFactory;
78
+    /** @var ICrypto */
79
+    protected $crypto;
80
+
81
+    /**
82
+     * @param string $appName
83
+     * @param IRequest $request
84
+     * @param IURLGenerator $urlGenerator
85
+     * @param IUserManager $userManager
86
+     * @param Defaults $defaults
87
+     * @param IL10N $l10n
88
+     * @param IConfig $config
89
+     * @param ISecureRandom $secureRandom
90
+     * @param string $defaultMailAddress
91
+     * @param IManager $encryptionManager
92
+     * @param IMailer $mailer
93
+     * @param ITimeFactory $timeFactory
94
+     * @param ICrypto $crypto
95
+     */
96
+    public function __construct($appName,
97
+                                IRequest $request,
98
+                                IURLGenerator $urlGenerator,
99
+                                IUserManager $userManager,
100
+                                Defaults $defaults,
101
+                                IL10N $l10n,
102
+                                IConfig $config,
103
+                                ISecureRandom $secureRandom,
104
+                                $defaultMailAddress,
105
+                                IManager $encryptionManager,
106
+                                IMailer $mailer,
107
+                                ITimeFactory $timeFactory,
108
+                                ICrypto $crypto) {
109
+        parent::__construct($appName, $request);
110
+        $this->urlGenerator = $urlGenerator;
111
+        $this->userManager = $userManager;
112
+        $this->defaults = $defaults;
113
+        $this->l10n = $l10n;
114
+        $this->secureRandom = $secureRandom;
115
+        $this->from = $defaultMailAddress;
116
+        $this->encryptionManager = $encryptionManager;
117
+        $this->config = $config;
118
+        $this->mailer = $mailer;
119
+        $this->timeFactory = $timeFactory;
120
+        $this->crypto = $crypto;
121
+    }
122
+
123
+    /**
124
+     * Someone wants to reset their password:
125
+     *
126
+     * @PublicPage
127
+     * @NoCSRFRequired
128
+     *
129
+     * @param string $token
130
+     * @param string $userId
131
+     * @return TemplateResponse
132
+     */
133
+    public function resetform($token, $userId) {
134
+        if ($this->config->getSystemValue('lost_password_link', '') !== '') {
135
+            return new TemplateResponse('core', 'error', [
136
+                    'errors' => [['error' => $this->l10n->t('Password reset is disabled')]]
137
+                ],
138
+                'guest'
139
+            );
140
+        }
141
+
142
+        try {
143
+            $this->checkPasswordResetToken($token, $userId);
144
+        } catch (\Exception $e) {
145
+            return new TemplateResponse(
146
+                'core', 'error', [
147
+                    "errors" => array(array("error" => $e->getMessage()))
148
+                ],
149
+                'guest'
150
+            );
151
+        }
152
+
153
+        return new TemplateResponse(
154
+            'core',
155
+            'lostpassword/resetpassword',
156
+            array(
157
+                'link' => $this->urlGenerator->linkToRouteAbsolute('core.lost.setPassword', array('userId' => $userId, 'token' => $token)),
158
+            ),
159
+            'guest'
160
+        );
161
+    }
162
+
163
+    /**
164
+     * @param string $token
165
+     * @param string $userId
166
+     * @throws \Exception
167
+     */
168
+    protected function checkPasswordResetToken($token, $userId) {
169
+        $user = $this->userManager->get($userId);
170
+        if($user === null || !$user->isEnabled()) {
171
+            throw new \Exception($this->l10n->t('Couldn\'t reset password because the token is invalid'));
172
+        }
173
+
174
+        try {
175
+            $encryptedToken = $this->config->getUserValue($userId, 'core', 'lostpassword', null);
176
+            $mailAddress = !is_null($user->getEMailAddress()) ? $user->getEMailAddress() : '';
177
+            $decryptedToken = $this->crypto->decrypt($encryptedToken, $mailAddress.$this->config->getSystemValue('secret'));
178
+        } catch (\Exception $e) {
179
+            throw new \Exception($this->l10n->t('Couldn\'t reset password because the token is invalid'));
180
+        }
181
+
182
+        $splittedToken = explode(':', $decryptedToken);
183
+        if(count($splittedToken) !== 2) {
184
+            throw new \Exception($this->l10n->t('Couldn\'t reset password because the token is invalid'));
185
+        }
186
+
187
+        if ($splittedToken[0] < ($this->timeFactory->getTime() - 60*60*12) ||
188
+            $user->getLastLogin() > $splittedToken[0]) {
189
+            throw new \Exception($this->l10n->t('Couldn\'t reset password because the token is expired'));
190
+        }
191
+
192
+        if (!hash_equals($splittedToken[1], $token)) {
193
+            throw new \Exception($this->l10n->t('Couldn\'t reset password because the token is invalid'));
194
+        }
195
+    }
196
+
197
+    /**
198
+     * @param $message
199
+     * @param array $additional
200
+     * @return array
201
+     */
202
+    private function error($message, array $additional=array()) {
203
+        return array_merge(array('status' => 'error', 'msg' => $message), $additional);
204
+    }
205
+
206
+    /**
207
+     * @return array
208
+     */
209
+    private function success() {
210
+        return array('status'=>'success');
211
+    }
212
+
213
+    /**
214
+     * @PublicPage
215
+     * @BruteForceProtection(action=passwordResetEmail)
216
+     * @AnonRateThrottle(limit=10, period=300)
217
+     *
218
+     * @param string $user
219
+     * @return JSONResponse
220
+     */
221
+    public function email($user){
222
+        if ($this->config->getSystemValue('lost_password_link', '') !== '') {
223
+            return new JSONResponse($this->error($this->l10n->t('Password reset is disabled')));
224
+        }
225
+
226
+        // FIXME: use HTTP error codes
227
+        try {
228
+            $this->sendEmail($user);
229
+        } catch (\Exception $e){
230
+            $response = new JSONResponse($this->error($e->getMessage()));
231
+            $response->throttle();
232
+            return $response;
233
+        }
234
+
235
+        $response = new JSONResponse($this->success());
236
+        $response->throttle();
237
+        return $response;
238
+    }
239
+
240
+    /**
241
+     * @PublicPage
242
+     * @param string $token
243
+     * @param string $userId
244
+     * @param string $password
245
+     * @param boolean $proceed
246
+     * @return array
247
+     */
248
+    public function setPassword($token, $userId, $password, $proceed) {
249
+        if ($this->config->getSystemValue('lost_password_link', '') !== '') {
250
+            return $this->error($this->l10n->t('Password reset is disabled'));
251
+        }
252
+
253
+        if ($this->encryptionManager->isEnabled() && !$proceed) {
254
+            return $this->error('', array('encryption' => true));
255
+        }
256
+
257
+        try {
258
+            $this->checkPasswordResetToken($token, $userId);
259
+            $user = $this->userManager->get($userId);
260
+
261
+            \OC_Hook::emit('\OC\Core\LostPassword\Controller\LostController', 'pre_passwordReset', array('uid' => $userId, 'password' => $password));
262
+
263
+            if (!$user->setPassword($password)) {
264
+                throw new \Exception();
265
+            }
266
+
267
+            \OC_Hook::emit('\OC\Core\LostPassword\Controller\LostController', 'post_passwordReset', array('uid' => $userId, 'password' => $password));
268
+
269
+            $this->config->deleteUserValue($userId, 'core', 'lostpassword');
270
+            @\OC::$server->getUserSession()->unsetMagicInCookie();
271
+        } catch (\Exception $e){
272
+            return $this->error($e->getMessage());
273
+        }
274
+
275
+        return $this->success();
276
+    }
277
+
278
+    /**
279
+     * @param string $input
280
+     * @throws \Exception
281
+     */
282
+    protected function sendEmail($input) {
283
+        $user = $this->findUserByIdOrMail($input);
284
+        $email = $user->getEMailAddress();
285
+
286
+        if (empty($email)) {
287
+            throw new \Exception(
288
+                $this->l10n->t('Could not send reset email because there is no email address for this username. Please contact your administrator.')
289
+            );
290
+        }
291
+
292
+        // Generate the token. It is stored encrypted in the database with the
293
+        // secret being the users' email address appended with the system secret.
294
+        // This makes the token automatically invalidate once the user changes
295
+        // their email address.
296
+        $token = $this->secureRandom->generate(
297
+            21,
298
+            ISecureRandom::CHAR_DIGITS.
299
+            ISecureRandom::CHAR_LOWER.
300
+            ISecureRandom::CHAR_UPPER
301
+        );
302
+        $tokenValue = $this->timeFactory->getTime() .':'. $token;
303
+        $encryptedValue = $this->crypto->encrypt($tokenValue, $email . $this->config->getSystemValue('secret'));
304
+        $this->config->setUserValue($user->getUID(), 'core', 'lostpassword', $encryptedValue);
305
+
306
+        $link = $this->urlGenerator->linkToRouteAbsolute('core.lost.resetform', array('userId' => $user->getUID(), 'token' => $token));
307
+
308
+        $emailTemplate = $this->mailer->createEMailTemplate('core.ResetPassword', [
309
+            'link' => $link,
310
+        ]);
311
+
312
+        $emailTemplate->setSubject($this->l10n->t('%s password reset', [$this->defaults->getName()]));
313
+        $emailTemplate->addHeader();
314
+        $emailTemplate->addHeading($this->l10n->t('Password reset'));
315
+
316
+        $emailTemplate->addBodyText(
317
+            $this->l10n->t('Click the following button to reset your password. If you have not requested the password reset, then ignore this email.'),
318
+            $this->l10n->t('Click the following link to reset your password. If you have not requested the password reset, then ignore this email.')
319
+        );
320
+
321
+        $emailTemplate->addBodyButton(
322
+            $this->l10n->t('Reset your password'),
323
+            $link,
324
+            false
325
+        );
326
+        $emailTemplate->addFooter();
327
+
328
+        try {
329
+            $message = $this->mailer->createMessage();
330
+            $message->setTo([$email => $user->getUID()]);
331
+            $message->setFrom([$this->from => $this->defaults->getName()]);
332
+            $message->useTemplate($emailTemplate);
333
+            $this->mailer->send($message);
334
+        } catch (\Exception $e) {
335
+            throw new \Exception($this->l10n->t(
336
+                'Couldn\'t send reset email. Please contact your administrator.'
337
+            ));
338
+        }
339
+    }
340
+
341
+    /**
342
+     * @param string $input
343
+     * @return IUser
344
+     * @throws \InvalidArgumentException
345
+     */
346
+    protected function findUserByIdOrMail($input) {
347
+        $user = $this->userManager->get($input);
348
+        if ($user instanceof IUser) {
349
+            if (!$user->isEnabled()) {
350
+                throw new \InvalidArgumentException($this->l10n->t('Couldn\'t send reset email. Please make sure your username is correct.'));
351
+            }
352
+
353
+            return $user;
354
+        }
355
+        $users = $this->userManager->getByEmail($input);
356
+        if (count($users) === 1) {
357
+            $user = $users[0];
358
+            if (!$user->isEnabled()) {
359
+                throw new \InvalidArgumentException($this->l10n->t('Couldn\'t send reset email. Please make sure your username is correct.'));
360
+            }
361
+
362
+            return $user;
363
+        }
364
+
365
+        throw new \InvalidArgumentException($this->l10n->t('Couldn\'t send reset email. Please make sure your username is correct.'));
366
+    }
367 367
 }
Please login to merge, or discard this patch.
apps/files_external/lib/Service/DBConfigService.php 3 patches
Doc Comments   +16 added lines patch added patch discarded remove patch
@@ -89,6 +89,9 @@  discard block
 block discarded – undo
89 89
 		return $this->getMountsFromQuery($query);
90 90
 	}
91 91
 
92
+	/**
93
+	 * @param string $userId
94
+	 */
92 95
 	public function getMountsForUser($userId, $groupIds) {
93 96
 		$builder = $this->connection->getQueryBuilder();
94 97
 		$query = $builder->select(['m.mount_id', 'mount_point', 'storage_backend', 'auth_backend', 'priority', 'm.type'])
@@ -125,6 +128,10 @@  discard block
 block discarded – undo
125 128
 		return $this->getMountsFromQuery($query);
126 129
 	}
127 130
 
131
+	/**
132
+	 * @param integer $type
133
+	 * @param string|null $value
134
+	 */
128 135
 	protected function getForQuery(IQueryBuilder $builder, $type, $value) {
129 136
 		$query = $builder->select(['m.mount_id', 'mount_point', 'storage_backend', 'auth_backend', 'priority', 'm.type'])
130 137
 			->from('external_mounts', 'm')
@@ -332,6 +339,9 @@  discard block
 block discarded – undo
332 339
 		}
333 340
 	}
334 341
 
342
+	/**
343
+	 * @param integer $mountId
344
+	 */
335 345
 	public function addApplicable($mountId, $type, $value) {
336 346
 		$this->connection->insertIfNotExist('*PREFIX*external_applicable', [
337 347
 			'mount_id' => $mountId,
@@ -340,6 +350,9 @@  discard block
 block discarded – undo
340 350
 		], ['mount_id', 'type', 'value']);
341 351
 	}
342 352
 
353
+	/**
354
+	 * @param integer $mountId
355
+	 */
343 356
 	public function removeApplicable($mountId, $type, $value) {
344 357
 		$builder = $this->connection->getQueryBuilder();
345 358
 		$query = $builder->delete('external_applicable')
@@ -473,6 +486,9 @@  discard block
 block discarded – undo
473 486
 		return array_combine($keys, $values);
474 487
 	}
475 488
 
489
+	/**
490
+	 * @param string $value
491
+	 */
476 492
 	private function encryptValue($value) {
477 493
 		return $this->crypto->encrypt($value);
478 494
 	}
Please login to merge, or discard this patch.
Spacing   +13 added lines, -13 removed lines patch added patch discarded remove patch
@@ -178,7 +178,7 @@  discard block
 block discarded – undo
178 178
 	 */
179 179
 	public function getAdminMountsForMultiple($type, array $values) {
180 180
 		$builder = $this->connection->getQueryBuilder();
181
-		$params = array_map(function ($value) use ($builder) {
181
+		$params = array_map(function($value) use ($builder) {
182 182
 			return $builder->createNamedParameter($value, IQueryBuilder::PARAM_STR);
183 183
 		}, $values);
184 184
 
@@ -231,7 +231,7 @@  discard block
 block discarded – undo
231 231
 				'type' => $builder->createNamedParameter($type, IQueryBuilder::PARAM_INT)
232 232
 			]);
233 233
 		$query->execute();
234
-		return (int)$this->connection->lastInsertId('*PREFIX*external_mounts');
234
+		return (int) $this->connection->lastInsertId('*PREFIX*external_mounts');
235 235
 	}
236 236
 
237 237
 	/**
@@ -367,7 +367,7 @@  discard block
 block discarded – undo
367 367
 		}
368 368
 		$uniqueMounts = array_values($uniqueMounts);
369 369
 
370
-		$mountIds = array_map(function ($mount) {
370
+		$mountIds = array_map(function($mount) {
371 371
 			return $mount['mount_id'];
372 372
 		}, $uniqueMounts);
373 373
 		$mountIds = array_values(array_unique($mountIds));
@@ -376,9 +376,9 @@  discard block
 block discarded – undo
376 376
 		$config = $this->getConfigForMounts($mountIds);
377 377
 		$options = $this->getOptionsForMounts($mountIds);
378 378
 
379
-		return array_map(function ($mount, $applicable, $config, $options) {
380
-			$mount['type'] = (int)$mount['type'];
381
-			$mount['priority'] = (int)$mount['priority'];
379
+		return array_map(function($mount, $applicable, $config, $options) {
380
+			$mount['type'] = (int) $mount['type'];
381
+			$mount['priority'] = (int) $mount['priority'];
382 382
 			$mount['applicable'] = $applicable;
383 383
 			$mount['config'] = $config;
384 384
 			$mount['options'] = $options;
@@ -400,7 +400,7 @@  discard block
 block discarded – undo
400 400
 		}
401 401
 		$builder = $this->connection->getQueryBuilder();
402 402
 		$fields[] = 'mount_id';
403
-		$placeHolders = array_map(function ($id) use ($builder) {
403
+		$placeHolders = array_map(function($id) use ($builder) {
404 404
 			return $builder->createPositionalParameter($id, IQueryBuilder::PARAM_INT);
405 405
 		}, $mountIds);
406 406
 		$query = $builder->select($fields)
@@ -414,7 +414,7 @@  discard block
 block discarded – undo
414 414
 		}
415 415
 		foreach ($rows as $row) {
416 416
 			if (isset($row['type'])) {
417
-				$row['type'] = (int)$row['type'];
417
+				$row['type'] = (int) $row['type'];
418 418
 			}
419 419
 			$result[$row['mount_id']][] = $row;
420 420
 		}
@@ -445,8 +445,8 @@  discard block
 block discarded – undo
445 445
 	public function getOptionsForMounts($mountIds) {
446 446
 		$mountOptions = $this->selectForMounts('external_options', ['key', 'value'], $mountIds);
447 447
 		$optionsMap = array_map([$this, 'createKeyValueMap'], $mountOptions);
448
-		return array_map(function (array $options) {
449
-			return array_map(function ($option) {
448
+		return array_map(function(array $options) {
449
+			return array_map(function($option) {
450 450
 				return json_decode($option);
451 451
 			}, $options);
452 452
 		}, $optionsMap);
@@ -457,16 +457,16 @@  discard block
 block discarded – undo
457 457
 	 * @return array ['key1' => $value1, ...]
458 458
 	 */
459 459
 	private function createKeyValueMap(array $keyValuePairs) {
460
-		$decryptedPairts = array_map(function ($pair) {
460
+		$decryptedPairts = array_map(function($pair) {
461 461
 			if ($pair['key'] === 'password') {
462 462
 				$pair['value'] = $this->decryptValue($pair['value']);
463 463
 			}
464 464
 			return $pair;
465 465
 		}, $keyValuePairs);
466
-		$keys = array_map(function ($pair) {
466
+		$keys = array_map(function($pair) {
467 467
 			return $pair['key'];
468 468
 		}, $decryptedPairts);
469
-		$values = array_map(function ($pair) {
469
+		$values = array_map(function($pair) {
470 470
 			return $pair['value'];
471 471
 		}, $decryptedPairts);
472 472
 
Please login to merge, or discard this patch.
Indentation   +456 added lines, -456 removed lines patch added patch discarded remove patch
@@ -32,460 +32,460 @@
 block discarded – undo
32 32
  * Stores the mount config in the database
33 33
  */
34 34
 class DBConfigService {
35
-	const MOUNT_TYPE_ADMIN = 1;
36
-	const MOUNT_TYPE_PERSONAl = 2;
37
-
38
-	const APPLICABLE_TYPE_GLOBAL = 1;
39
-	const APPLICABLE_TYPE_GROUP = 2;
40
-	const APPLICABLE_TYPE_USER = 3;
41
-
42
-	/**
43
-	 * @var IDBConnection
44
-	 */
45
-	private $connection;
46
-
47
-	/**
48
-	 * @var ICrypto
49
-	 */
50
-	private $crypto;
51
-
52
-	/**
53
-	 * DBConfigService constructor.
54
-	 *
55
-	 * @param IDBConnection $connection
56
-	 * @param ICrypto $crypto
57
-	 */
58
-	public function __construct(IDBConnection $connection, ICrypto $crypto) {
59
-		$this->connection = $connection;
60
-		$this->crypto = $crypto;
61
-	}
62
-
63
-	/**
64
-	 * @param int $mountId
65
-	 * @return array
66
-	 */
67
-	public function getMountById($mountId) {
68
-		$builder = $this->connection->getQueryBuilder();
69
-		$query = $builder->select(['mount_id', 'mount_point', 'storage_backend', 'auth_backend', 'priority', 'type'])
70
-			->from('external_mounts', 'm')
71
-			->where($builder->expr()->eq('mount_id', $builder->createNamedParameter($mountId, IQueryBuilder::PARAM_INT)));
72
-		$mounts = $this->getMountsFromQuery($query);
73
-		if (count($mounts) > 0) {
74
-			return $mounts[0];
75
-		} else {
76
-			return null;
77
-		}
78
-	}
79
-
80
-	/**
81
-	 * Get all configured mounts
82
-	 *
83
-	 * @return array
84
-	 */
85
-	public function getAllMounts() {
86
-		$builder = $this->connection->getQueryBuilder();
87
-		$query = $builder->select(['mount_id', 'mount_point', 'storage_backend', 'auth_backend', 'priority', 'type'])
88
-			->from('external_mounts');
89
-		return $this->getMountsFromQuery($query);
90
-	}
91
-
92
-	public function getMountsForUser($userId, $groupIds) {
93
-		$builder = $this->connection->getQueryBuilder();
94
-		$query = $builder->select(['m.mount_id', 'mount_point', 'storage_backend', 'auth_backend', 'priority', 'm.type'])
95
-			->from('external_mounts', 'm')
96
-			->innerJoin('m', 'external_applicable', 'a', $builder->expr()->eq('m.mount_id', 'a.mount_id'))
97
-			->where($builder->expr()->orX(
98
-				$builder->expr()->andX( // global mounts
99
-					$builder->expr()->eq('a.type', $builder->createNamedParameter(self::APPLICABLE_TYPE_GLOBAL, IQueryBuilder::PARAM_INT)),
100
-					$builder->expr()->isNull('a.value')
101
-				),
102
-				$builder->expr()->andX( // mounts for user
103
-					$builder->expr()->eq('a.type', $builder->createNamedParameter(self::APPLICABLE_TYPE_USER, IQueryBuilder::PARAM_INT)),
104
-					$builder->expr()->eq('a.value', $builder->createNamedParameter($userId))
105
-				),
106
-				$builder->expr()->andX( // mounts for group
107
-					$builder->expr()->eq('a.type', $builder->createNamedParameter(self::APPLICABLE_TYPE_GROUP, IQueryBuilder::PARAM_INT)),
108
-					$builder->expr()->in('a.value', $builder->createNamedParameter($groupIds, IQueryBuilder::PARAM_STR_ARRAY))
109
-				)
110
-			));
111
-
112
-		return $this->getMountsFromQuery($query);
113
-	}
114
-
115
-	/**
116
-	 * Get admin defined mounts
117
-	 *
118
-	 * @return array
119
-	 * @suppress SqlInjectionChecker
120
-	 */
121
-	public function getAdminMounts() {
122
-		$builder = $this->connection->getQueryBuilder();
123
-		$query = $builder->select(['mount_id', 'mount_point', 'storage_backend', 'auth_backend', 'priority', 'type'])
124
-			->from('external_mounts')
125
-			->where($builder->expr()->eq('type', $builder->expr()->literal(self::MOUNT_TYPE_ADMIN, IQueryBuilder::PARAM_INT)));
126
-		return $this->getMountsFromQuery($query);
127
-	}
128
-
129
-	protected function getForQuery(IQueryBuilder $builder, $type, $value) {
130
-		$query = $builder->select(['m.mount_id', 'mount_point', 'storage_backend', 'auth_backend', 'priority', 'm.type'])
131
-			->from('external_mounts', 'm')
132
-			->innerJoin('m', 'external_applicable', 'a', $builder->expr()->eq('m.mount_id', 'a.mount_id'))
133
-			->where($builder->expr()->eq('a.type', $builder->createNamedParameter($type, IQueryBuilder::PARAM_INT)));
134
-
135
-		if (is_null($value)) {
136
-			$query = $query->andWhere($builder->expr()->isNull('a.value'));
137
-		} else {
138
-			$query = $query->andWhere($builder->expr()->eq('a.value', $builder->createNamedParameter($value)));
139
-		}
140
-
141
-		return $query;
142
-	}
143
-
144
-	/**
145
-	 * Get mounts by applicable
146
-	 *
147
-	 * @param int $type any of the self::APPLICABLE_TYPE_ constants
148
-	 * @param string|null $value user_id, group_id or null for global mounts
149
-	 * @return array
150
-	 */
151
-	public function getMountsFor($type, $value) {
152
-		$builder = $this->connection->getQueryBuilder();
153
-		$query = $this->getForQuery($builder, $type, $value);
154
-
155
-		return $this->getMountsFromQuery($query);
156
-	}
157
-
158
-	/**
159
-	 * Get admin defined mounts by applicable
160
-	 *
161
-	 * @param int $type any of the self::APPLICABLE_TYPE_ constants
162
-	 * @param string|null $value user_id, group_id or null for global mounts
163
-	 * @return array
164
-	 * @suppress SqlInjectionChecker
165
-	 */
166
-	public function getAdminMountsFor($type, $value) {
167
-		$builder = $this->connection->getQueryBuilder();
168
-		$query = $this->getForQuery($builder, $type, $value);
169
-		$query->andWhere($builder->expr()->eq('m.type', $builder->expr()->literal(self::MOUNT_TYPE_ADMIN, IQueryBuilder::PARAM_INT)));
170
-
171
-		return $this->getMountsFromQuery($query);
172
-	}
173
-
174
-	/**
175
-	 * Get admin defined mounts for multiple applicable
176
-	 *
177
-	 * @param int $type any of the self::APPLICABLE_TYPE_ constants
178
-	 * @param string[] $values user_ids or group_ids
179
-	 * @return array
180
-	 * @suppress SqlInjectionChecker
181
-	 */
182
-	public function getAdminMountsForMultiple($type, array $values) {
183
-		$builder = $this->connection->getQueryBuilder();
184
-		$params = array_map(function ($value) use ($builder) {
185
-			return $builder->createNamedParameter($value, IQueryBuilder::PARAM_STR);
186
-		}, $values);
187
-
188
-		$query = $builder->select(['m.mount_id', 'mount_point', 'storage_backend', 'auth_backend', 'priority', 'm.type'])
189
-			->from('external_mounts', 'm')
190
-			->innerJoin('m', 'external_applicable', 'a', $builder->expr()->eq('m.mount_id', 'a.mount_id'))
191
-			->where($builder->expr()->eq('a.type', $builder->createNamedParameter($type, IQueryBuilder::PARAM_INT)))
192
-			->andWhere($builder->expr()->in('a.value', $params));
193
-		$query->andWhere($builder->expr()->eq('m.type', $builder->expr()->literal(self::MOUNT_TYPE_ADMIN, IQueryBuilder::PARAM_INT)));
194
-
195
-		return $this->getMountsFromQuery($query);
196
-	}
197
-
198
-	/**
199
-	 * Get user defined mounts by applicable
200
-	 *
201
-	 * @param int $type any of the self::APPLICABLE_TYPE_ constants
202
-	 * @param string|null $value user_id, group_id or null for global mounts
203
-	 * @return array
204
-	 * @suppress SqlInjectionChecker
205
-	 */
206
-	public function getUserMountsFor($type, $value) {
207
-		$builder = $this->connection->getQueryBuilder();
208
-		$query = $this->getForQuery($builder, $type, $value);
209
-		$query->andWhere($builder->expr()->eq('m.type', $builder->expr()->literal(self::MOUNT_TYPE_PERSONAl, IQueryBuilder::PARAM_INT)));
210
-
211
-		return $this->getMountsFromQuery($query);
212
-	}
213
-
214
-	/**
215
-	 * Add a mount to the database
216
-	 *
217
-	 * @param string $mountPoint
218
-	 * @param string $storageBackend
219
-	 * @param string $authBackend
220
-	 * @param int $priority
221
-	 * @param int $type self::MOUNT_TYPE_ADMIN or self::MOUNT_TYPE_PERSONAL
222
-	 * @return int the id of the new mount
223
-	 */
224
-	public function addMount($mountPoint, $storageBackend, $authBackend, $priority, $type) {
225
-		if (!$priority) {
226
-			$priority = 100;
227
-		}
228
-		$builder = $this->connection->getQueryBuilder();
229
-		$query = $builder->insert('external_mounts')
230
-			->values([
231
-				'mount_point' => $builder->createNamedParameter($mountPoint, IQueryBuilder::PARAM_STR),
232
-				'storage_backend' => $builder->createNamedParameter($storageBackend, IQueryBuilder::PARAM_STR),
233
-				'auth_backend' => $builder->createNamedParameter($authBackend, IQueryBuilder::PARAM_STR),
234
-				'priority' => $builder->createNamedParameter($priority, IQueryBuilder::PARAM_INT),
235
-				'type' => $builder->createNamedParameter($type, IQueryBuilder::PARAM_INT)
236
-			]);
237
-		$query->execute();
238
-		return (int)$this->connection->lastInsertId('*PREFIX*external_mounts');
239
-	}
240
-
241
-	/**
242
-	 * Remove a mount from the database
243
-	 *
244
-	 * @param int $mountId
245
-	 */
246
-	public function removeMount($mountId) {
247
-		$builder = $this->connection->getQueryBuilder();
248
-		$query = $builder->delete('external_mounts')
249
-			->where($builder->expr()->eq('mount_id', $builder->createNamedParameter($mountId, IQueryBuilder::PARAM_INT)));
250
-		$query->execute();
251
-
252
-		$query = $builder->delete('external_applicable')
253
-			->where($builder->expr()->eq('mount_id', $builder->createNamedParameter($mountId, IQueryBuilder::PARAM_INT)));
254
-		$query->execute();
255
-
256
-		$query = $builder->delete('external_config')
257
-			->where($builder->expr()->eq('mount_id', $builder->createNamedParameter($mountId, IQueryBuilder::PARAM_INT)));
258
-		$query->execute();
259
-
260
-		$query = $builder->delete('external_options')
261
-			->where($builder->expr()->eq('mount_id', $builder->createNamedParameter($mountId, IQueryBuilder::PARAM_INT)));
262
-		$query->execute();
263
-	}
264
-
265
-	/**
266
-	 * @param int $mountId
267
-	 * @param string $newMountPoint
268
-	 */
269
-	public function setMountPoint($mountId, $newMountPoint) {
270
-		$builder = $this->connection->getQueryBuilder();
271
-
272
-		$query = $builder->update('external_mounts')
273
-			->set('mount_point', $builder->createNamedParameter($newMountPoint))
274
-			->where($builder->expr()->eq('mount_id', $builder->createNamedParameter($mountId, IQueryBuilder::PARAM_INT)));
275
-
276
-		$query->execute();
277
-	}
278
-
279
-	/**
280
-	 * @param int $mountId
281
-	 * @param string $newAuthBackend
282
-	 */
283
-	public function setAuthBackend($mountId, $newAuthBackend) {
284
-		$builder = $this->connection->getQueryBuilder();
285
-
286
-		$query = $builder->update('external_mounts')
287
-			->set('auth_backend', $builder->createNamedParameter($newAuthBackend))
288
-			->where($builder->expr()->eq('mount_id', $builder->createNamedParameter($mountId, IQueryBuilder::PARAM_INT)));
289
-
290
-		$query->execute();
291
-	}
292
-
293
-	/**
294
-	 * @param int $mountId
295
-	 * @param string $key
296
-	 * @param string $value
297
-	 */
298
-	public function setConfig($mountId, $key, $value) {
299
-		if ($key === 'password') {
300
-			$value = $this->encryptValue($value);
301
-		}
302
-		$count = $this->connection->insertIfNotExist('*PREFIX*external_config', [
303
-			'mount_id' => $mountId,
304
-			'key' => $key,
305
-			'value' => $value
306
-		], ['mount_id', 'key']);
307
-		if ($count === 0) {
308
-			$builder = $this->connection->getQueryBuilder();
309
-			$query = $builder->update('external_config')
310
-				->set('value', $builder->createNamedParameter($value, IQueryBuilder::PARAM_STR))
311
-				->where($builder->expr()->eq('mount_id', $builder->createNamedParameter($mountId, IQueryBuilder::PARAM_INT)))
312
-				->andWhere($builder->expr()->eq('key', $builder->createNamedParameter($key, IQueryBuilder::PARAM_STR)));
313
-			$query->execute();
314
-		}
315
-	}
316
-
317
-	/**
318
-	 * @param int $mountId
319
-	 * @param string $key
320
-	 * @param string $value
321
-	 */
322
-	public function setOption($mountId, $key, $value) {
323
-
324
-		$count = $this->connection->insertIfNotExist('*PREFIX*external_options', [
325
-			'mount_id' => $mountId,
326
-			'key' => $key,
327
-			'value' => json_encode($value)
328
-		], ['mount_id', 'key']);
329
-		if ($count === 0) {
330
-			$builder = $this->connection->getQueryBuilder();
331
-			$query = $builder->update('external_options')
332
-				->set('value', $builder->createNamedParameter(json_encode($value), IQueryBuilder::PARAM_STR))
333
-				->where($builder->expr()->eq('mount_id', $builder->createNamedParameter($mountId, IQueryBuilder::PARAM_INT)))
334
-				->andWhere($builder->expr()->eq('key', $builder->createNamedParameter($key, IQueryBuilder::PARAM_STR)));
335
-			$query->execute();
336
-		}
337
-	}
338
-
339
-	public function addApplicable($mountId, $type, $value) {
340
-		$this->connection->insertIfNotExist('*PREFIX*external_applicable', [
341
-			'mount_id' => $mountId,
342
-			'type' => $type,
343
-			'value' => $value
344
-		], ['mount_id', 'type', 'value']);
345
-	}
346
-
347
-	public function removeApplicable($mountId, $type, $value) {
348
-		$builder = $this->connection->getQueryBuilder();
349
-		$query = $builder->delete('external_applicable')
350
-			->where($builder->expr()->eq('mount_id', $builder->createNamedParameter($mountId, IQueryBuilder::PARAM_INT)))
351
-			->andWhere($builder->expr()->eq('type', $builder->createNamedParameter($type, IQueryBuilder::PARAM_INT)));
352
-
353
-		if (is_null($value)) {
354
-			$query = $query->andWhere($builder->expr()->isNull('value'));
355
-		} else {
356
-			$query = $query->andWhere($builder->expr()->eq('value', $builder->createNamedParameter($value, IQueryBuilder::PARAM_STR)));
357
-		}
358
-
359
-		$query->execute();
360
-	}
361
-
362
-	private function getMountsFromQuery(IQueryBuilder $query) {
363
-		$result = $query->execute();
364
-		$mounts = $result->fetchAll();
365
-		$uniqueMounts = [];
366
-		foreach ($mounts as $mount) {
367
-			$id = $mount['mount_id'];
368
-			if (!isset($uniqueMounts[$id])) {
369
-				$uniqueMounts[$id] = $mount;
370
-			}
371
-		}
372
-		$uniqueMounts = array_values($uniqueMounts);
373
-
374
-		$mountIds = array_map(function ($mount) {
375
-			return $mount['mount_id'];
376
-		}, $uniqueMounts);
377
-		$mountIds = array_values(array_unique($mountIds));
378
-
379
-		$applicable = $this->getApplicableForMounts($mountIds);
380
-		$config = $this->getConfigForMounts($mountIds);
381
-		$options = $this->getOptionsForMounts($mountIds);
382
-
383
-		return array_map(function ($mount, $applicable, $config, $options) {
384
-			$mount['type'] = (int)$mount['type'];
385
-			$mount['priority'] = (int)$mount['priority'];
386
-			$mount['applicable'] = $applicable;
387
-			$mount['config'] = $config;
388
-			$mount['options'] = $options;
389
-			return $mount;
390
-		}, $uniqueMounts, $applicable, $config, $options);
391
-	}
392
-
393
-	/**
394
-	 * Get mount options from a table grouped by mount id
395
-	 *
396
-	 * @param string $table
397
-	 * @param string[] $fields
398
-	 * @param int[] $mountIds
399
-	 * @return array [$mountId => [['field1' => $value1, ...], ...], ...]
400
-	 */
401
-	private function selectForMounts($table, array $fields, array $mountIds) {
402
-		if (count($mountIds) === 0) {
403
-			return [];
404
-		}
405
-		$builder = $this->connection->getQueryBuilder();
406
-		$fields[] = 'mount_id';
407
-		$placeHolders = array_map(function ($id) use ($builder) {
408
-			return $builder->createPositionalParameter($id, IQueryBuilder::PARAM_INT);
409
-		}, $mountIds);
410
-		$query = $builder->select($fields)
411
-			->from($table)
412
-			->where($builder->expr()->in('mount_id', $placeHolders));
413
-		$rows = $query->execute()->fetchAll();
414
-
415
-		$result = [];
416
-		foreach ($mountIds as $mountId) {
417
-			$result[$mountId] = [];
418
-		}
419
-		foreach ($rows as $row) {
420
-			if (isset($row['type'])) {
421
-				$row['type'] = (int)$row['type'];
422
-			}
423
-			$result[$row['mount_id']][] = $row;
424
-		}
425
-		return $result;
426
-	}
427
-
428
-	/**
429
-	 * @param int[] $mountIds
430
-	 * @return array [$id => [['type' => $type, 'value' => $value], ...], ...]
431
-	 */
432
-	public function getApplicableForMounts($mountIds) {
433
-		return $this->selectForMounts('external_applicable', ['type', 'value'], $mountIds);
434
-	}
435
-
436
-	/**
437
-	 * @param int[] $mountIds
438
-	 * @return array [$id => ['key1' => $value1, ...], ...]
439
-	 */
440
-	public function getConfigForMounts($mountIds) {
441
-		$mountConfigs = $this->selectForMounts('external_config', ['key', 'value'], $mountIds);
442
-		return array_map([$this, 'createKeyValueMap'], $mountConfigs);
443
-	}
444
-
445
-	/**
446
-	 * @param int[] $mountIds
447
-	 * @return array [$id => ['key1' => $value1, ...], ...]
448
-	 */
449
-	public function getOptionsForMounts($mountIds) {
450
-		$mountOptions = $this->selectForMounts('external_options', ['key', 'value'], $mountIds);
451
-		$optionsMap = array_map([$this, 'createKeyValueMap'], $mountOptions);
452
-		return array_map(function (array $options) {
453
-			return array_map(function ($option) {
454
-				return json_decode($option);
455
-			}, $options);
456
-		}, $optionsMap);
457
-	}
458
-
459
-	/**
460
-	 * @param array $keyValuePairs [['key'=>$key, 'value=>$value], ...]
461
-	 * @return array ['key1' => $value1, ...]
462
-	 */
463
-	private function createKeyValueMap(array $keyValuePairs) {
464
-		$decryptedPairts = array_map(function ($pair) {
465
-			if ($pair['key'] === 'password') {
466
-				$pair['value'] = $this->decryptValue($pair['value']);
467
-			}
468
-			return $pair;
469
-		}, $keyValuePairs);
470
-		$keys = array_map(function ($pair) {
471
-			return $pair['key'];
472
-		}, $decryptedPairts);
473
-		$values = array_map(function ($pair) {
474
-			return $pair['value'];
475
-		}, $decryptedPairts);
476
-
477
-		return array_combine($keys, $values);
478
-	}
479
-
480
-	private function encryptValue($value) {
481
-		return $this->crypto->encrypt($value);
482
-	}
483
-
484
-	private function decryptValue($value) {
485
-		try {
486
-			return $this->crypto->decrypt($value);
487
-		} catch (\Exception $e) {
488
-			return $value;
489
-		}
490
-	}
35
+    const MOUNT_TYPE_ADMIN = 1;
36
+    const MOUNT_TYPE_PERSONAl = 2;
37
+
38
+    const APPLICABLE_TYPE_GLOBAL = 1;
39
+    const APPLICABLE_TYPE_GROUP = 2;
40
+    const APPLICABLE_TYPE_USER = 3;
41
+
42
+    /**
43
+     * @var IDBConnection
44
+     */
45
+    private $connection;
46
+
47
+    /**
48
+     * @var ICrypto
49
+     */
50
+    private $crypto;
51
+
52
+    /**
53
+     * DBConfigService constructor.
54
+     *
55
+     * @param IDBConnection $connection
56
+     * @param ICrypto $crypto
57
+     */
58
+    public function __construct(IDBConnection $connection, ICrypto $crypto) {
59
+        $this->connection = $connection;
60
+        $this->crypto = $crypto;
61
+    }
62
+
63
+    /**
64
+     * @param int $mountId
65
+     * @return array
66
+     */
67
+    public function getMountById($mountId) {
68
+        $builder = $this->connection->getQueryBuilder();
69
+        $query = $builder->select(['mount_id', 'mount_point', 'storage_backend', 'auth_backend', 'priority', 'type'])
70
+            ->from('external_mounts', 'm')
71
+            ->where($builder->expr()->eq('mount_id', $builder->createNamedParameter($mountId, IQueryBuilder::PARAM_INT)));
72
+        $mounts = $this->getMountsFromQuery($query);
73
+        if (count($mounts) > 0) {
74
+            return $mounts[0];
75
+        } else {
76
+            return null;
77
+        }
78
+    }
79
+
80
+    /**
81
+     * Get all configured mounts
82
+     *
83
+     * @return array
84
+     */
85
+    public function getAllMounts() {
86
+        $builder = $this->connection->getQueryBuilder();
87
+        $query = $builder->select(['mount_id', 'mount_point', 'storage_backend', 'auth_backend', 'priority', 'type'])
88
+            ->from('external_mounts');
89
+        return $this->getMountsFromQuery($query);
90
+    }
91
+
92
+    public function getMountsForUser($userId, $groupIds) {
93
+        $builder = $this->connection->getQueryBuilder();
94
+        $query = $builder->select(['m.mount_id', 'mount_point', 'storage_backend', 'auth_backend', 'priority', 'm.type'])
95
+            ->from('external_mounts', 'm')
96
+            ->innerJoin('m', 'external_applicable', 'a', $builder->expr()->eq('m.mount_id', 'a.mount_id'))
97
+            ->where($builder->expr()->orX(
98
+                $builder->expr()->andX( // global mounts
99
+                    $builder->expr()->eq('a.type', $builder->createNamedParameter(self::APPLICABLE_TYPE_GLOBAL, IQueryBuilder::PARAM_INT)),
100
+                    $builder->expr()->isNull('a.value')
101
+                ),
102
+                $builder->expr()->andX( // mounts for user
103
+                    $builder->expr()->eq('a.type', $builder->createNamedParameter(self::APPLICABLE_TYPE_USER, IQueryBuilder::PARAM_INT)),
104
+                    $builder->expr()->eq('a.value', $builder->createNamedParameter($userId))
105
+                ),
106
+                $builder->expr()->andX( // mounts for group
107
+                    $builder->expr()->eq('a.type', $builder->createNamedParameter(self::APPLICABLE_TYPE_GROUP, IQueryBuilder::PARAM_INT)),
108
+                    $builder->expr()->in('a.value', $builder->createNamedParameter($groupIds, IQueryBuilder::PARAM_STR_ARRAY))
109
+                )
110
+            ));
111
+
112
+        return $this->getMountsFromQuery($query);
113
+    }
114
+
115
+    /**
116
+     * Get admin defined mounts
117
+     *
118
+     * @return array
119
+     * @suppress SqlInjectionChecker
120
+     */
121
+    public function getAdminMounts() {
122
+        $builder = $this->connection->getQueryBuilder();
123
+        $query = $builder->select(['mount_id', 'mount_point', 'storage_backend', 'auth_backend', 'priority', 'type'])
124
+            ->from('external_mounts')
125
+            ->where($builder->expr()->eq('type', $builder->expr()->literal(self::MOUNT_TYPE_ADMIN, IQueryBuilder::PARAM_INT)));
126
+        return $this->getMountsFromQuery($query);
127
+    }
128
+
129
+    protected function getForQuery(IQueryBuilder $builder, $type, $value) {
130
+        $query = $builder->select(['m.mount_id', 'mount_point', 'storage_backend', 'auth_backend', 'priority', 'm.type'])
131
+            ->from('external_mounts', 'm')
132
+            ->innerJoin('m', 'external_applicable', 'a', $builder->expr()->eq('m.mount_id', 'a.mount_id'))
133
+            ->where($builder->expr()->eq('a.type', $builder->createNamedParameter($type, IQueryBuilder::PARAM_INT)));
134
+
135
+        if (is_null($value)) {
136
+            $query = $query->andWhere($builder->expr()->isNull('a.value'));
137
+        } else {
138
+            $query = $query->andWhere($builder->expr()->eq('a.value', $builder->createNamedParameter($value)));
139
+        }
140
+
141
+        return $query;
142
+    }
143
+
144
+    /**
145
+     * Get mounts by applicable
146
+     *
147
+     * @param int $type any of the self::APPLICABLE_TYPE_ constants
148
+     * @param string|null $value user_id, group_id or null for global mounts
149
+     * @return array
150
+     */
151
+    public function getMountsFor($type, $value) {
152
+        $builder = $this->connection->getQueryBuilder();
153
+        $query = $this->getForQuery($builder, $type, $value);
154
+
155
+        return $this->getMountsFromQuery($query);
156
+    }
157
+
158
+    /**
159
+     * Get admin defined mounts by applicable
160
+     *
161
+     * @param int $type any of the self::APPLICABLE_TYPE_ constants
162
+     * @param string|null $value user_id, group_id or null for global mounts
163
+     * @return array
164
+     * @suppress SqlInjectionChecker
165
+     */
166
+    public function getAdminMountsFor($type, $value) {
167
+        $builder = $this->connection->getQueryBuilder();
168
+        $query = $this->getForQuery($builder, $type, $value);
169
+        $query->andWhere($builder->expr()->eq('m.type', $builder->expr()->literal(self::MOUNT_TYPE_ADMIN, IQueryBuilder::PARAM_INT)));
170
+
171
+        return $this->getMountsFromQuery($query);
172
+    }
173
+
174
+    /**
175
+     * Get admin defined mounts for multiple applicable
176
+     *
177
+     * @param int $type any of the self::APPLICABLE_TYPE_ constants
178
+     * @param string[] $values user_ids or group_ids
179
+     * @return array
180
+     * @suppress SqlInjectionChecker
181
+     */
182
+    public function getAdminMountsForMultiple($type, array $values) {
183
+        $builder = $this->connection->getQueryBuilder();
184
+        $params = array_map(function ($value) use ($builder) {
185
+            return $builder->createNamedParameter($value, IQueryBuilder::PARAM_STR);
186
+        }, $values);
187
+
188
+        $query = $builder->select(['m.mount_id', 'mount_point', 'storage_backend', 'auth_backend', 'priority', 'm.type'])
189
+            ->from('external_mounts', 'm')
190
+            ->innerJoin('m', 'external_applicable', 'a', $builder->expr()->eq('m.mount_id', 'a.mount_id'))
191
+            ->where($builder->expr()->eq('a.type', $builder->createNamedParameter($type, IQueryBuilder::PARAM_INT)))
192
+            ->andWhere($builder->expr()->in('a.value', $params));
193
+        $query->andWhere($builder->expr()->eq('m.type', $builder->expr()->literal(self::MOUNT_TYPE_ADMIN, IQueryBuilder::PARAM_INT)));
194
+
195
+        return $this->getMountsFromQuery($query);
196
+    }
197
+
198
+    /**
199
+     * Get user defined mounts by applicable
200
+     *
201
+     * @param int $type any of the self::APPLICABLE_TYPE_ constants
202
+     * @param string|null $value user_id, group_id or null for global mounts
203
+     * @return array
204
+     * @suppress SqlInjectionChecker
205
+     */
206
+    public function getUserMountsFor($type, $value) {
207
+        $builder = $this->connection->getQueryBuilder();
208
+        $query = $this->getForQuery($builder, $type, $value);
209
+        $query->andWhere($builder->expr()->eq('m.type', $builder->expr()->literal(self::MOUNT_TYPE_PERSONAl, IQueryBuilder::PARAM_INT)));
210
+
211
+        return $this->getMountsFromQuery($query);
212
+    }
213
+
214
+    /**
215
+     * Add a mount to the database
216
+     *
217
+     * @param string $mountPoint
218
+     * @param string $storageBackend
219
+     * @param string $authBackend
220
+     * @param int $priority
221
+     * @param int $type self::MOUNT_TYPE_ADMIN or self::MOUNT_TYPE_PERSONAL
222
+     * @return int the id of the new mount
223
+     */
224
+    public function addMount($mountPoint, $storageBackend, $authBackend, $priority, $type) {
225
+        if (!$priority) {
226
+            $priority = 100;
227
+        }
228
+        $builder = $this->connection->getQueryBuilder();
229
+        $query = $builder->insert('external_mounts')
230
+            ->values([
231
+                'mount_point' => $builder->createNamedParameter($mountPoint, IQueryBuilder::PARAM_STR),
232
+                'storage_backend' => $builder->createNamedParameter($storageBackend, IQueryBuilder::PARAM_STR),
233
+                'auth_backend' => $builder->createNamedParameter($authBackend, IQueryBuilder::PARAM_STR),
234
+                'priority' => $builder->createNamedParameter($priority, IQueryBuilder::PARAM_INT),
235
+                'type' => $builder->createNamedParameter($type, IQueryBuilder::PARAM_INT)
236
+            ]);
237
+        $query->execute();
238
+        return (int)$this->connection->lastInsertId('*PREFIX*external_mounts');
239
+    }
240
+
241
+    /**
242
+     * Remove a mount from the database
243
+     *
244
+     * @param int $mountId
245
+     */
246
+    public function removeMount($mountId) {
247
+        $builder = $this->connection->getQueryBuilder();
248
+        $query = $builder->delete('external_mounts')
249
+            ->where($builder->expr()->eq('mount_id', $builder->createNamedParameter($mountId, IQueryBuilder::PARAM_INT)));
250
+        $query->execute();
251
+
252
+        $query = $builder->delete('external_applicable')
253
+            ->where($builder->expr()->eq('mount_id', $builder->createNamedParameter($mountId, IQueryBuilder::PARAM_INT)));
254
+        $query->execute();
255
+
256
+        $query = $builder->delete('external_config')
257
+            ->where($builder->expr()->eq('mount_id', $builder->createNamedParameter($mountId, IQueryBuilder::PARAM_INT)));
258
+        $query->execute();
259
+
260
+        $query = $builder->delete('external_options')
261
+            ->where($builder->expr()->eq('mount_id', $builder->createNamedParameter($mountId, IQueryBuilder::PARAM_INT)));
262
+        $query->execute();
263
+    }
264
+
265
+    /**
266
+     * @param int $mountId
267
+     * @param string $newMountPoint
268
+     */
269
+    public function setMountPoint($mountId, $newMountPoint) {
270
+        $builder = $this->connection->getQueryBuilder();
271
+
272
+        $query = $builder->update('external_mounts')
273
+            ->set('mount_point', $builder->createNamedParameter($newMountPoint))
274
+            ->where($builder->expr()->eq('mount_id', $builder->createNamedParameter($mountId, IQueryBuilder::PARAM_INT)));
275
+
276
+        $query->execute();
277
+    }
278
+
279
+    /**
280
+     * @param int $mountId
281
+     * @param string $newAuthBackend
282
+     */
283
+    public function setAuthBackend($mountId, $newAuthBackend) {
284
+        $builder = $this->connection->getQueryBuilder();
285
+
286
+        $query = $builder->update('external_mounts')
287
+            ->set('auth_backend', $builder->createNamedParameter($newAuthBackend))
288
+            ->where($builder->expr()->eq('mount_id', $builder->createNamedParameter($mountId, IQueryBuilder::PARAM_INT)));
289
+
290
+        $query->execute();
291
+    }
292
+
293
+    /**
294
+     * @param int $mountId
295
+     * @param string $key
296
+     * @param string $value
297
+     */
298
+    public function setConfig($mountId, $key, $value) {
299
+        if ($key === 'password') {
300
+            $value = $this->encryptValue($value);
301
+        }
302
+        $count = $this->connection->insertIfNotExist('*PREFIX*external_config', [
303
+            'mount_id' => $mountId,
304
+            'key' => $key,
305
+            'value' => $value
306
+        ], ['mount_id', 'key']);
307
+        if ($count === 0) {
308
+            $builder = $this->connection->getQueryBuilder();
309
+            $query = $builder->update('external_config')
310
+                ->set('value', $builder->createNamedParameter($value, IQueryBuilder::PARAM_STR))
311
+                ->where($builder->expr()->eq('mount_id', $builder->createNamedParameter($mountId, IQueryBuilder::PARAM_INT)))
312
+                ->andWhere($builder->expr()->eq('key', $builder->createNamedParameter($key, IQueryBuilder::PARAM_STR)));
313
+            $query->execute();
314
+        }
315
+    }
316
+
317
+    /**
318
+     * @param int $mountId
319
+     * @param string $key
320
+     * @param string $value
321
+     */
322
+    public function setOption($mountId, $key, $value) {
323
+
324
+        $count = $this->connection->insertIfNotExist('*PREFIX*external_options', [
325
+            'mount_id' => $mountId,
326
+            'key' => $key,
327
+            'value' => json_encode($value)
328
+        ], ['mount_id', 'key']);
329
+        if ($count === 0) {
330
+            $builder = $this->connection->getQueryBuilder();
331
+            $query = $builder->update('external_options')
332
+                ->set('value', $builder->createNamedParameter(json_encode($value), IQueryBuilder::PARAM_STR))
333
+                ->where($builder->expr()->eq('mount_id', $builder->createNamedParameter($mountId, IQueryBuilder::PARAM_INT)))
334
+                ->andWhere($builder->expr()->eq('key', $builder->createNamedParameter($key, IQueryBuilder::PARAM_STR)));
335
+            $query->execute();
336
+        }
337
+    }
338
+
339
+    public function addApplicable($mountId, $type, $value) {
340
+        $this->connection->insertIfNotExist('*PREFIX*external_applicable', [
341
+            'mount_id' => $mountId,
342
+            'type' => $type,
343
+            'value' => $value
344
+        ], ['mount_id', 'type', 'value']);
345
+    }
346
+
347
+    public function removeApplicable($mountId, $type, $value) {
348
+        $builder = $this->connection->getQueryBuilder();
349
+        $query = $builder->delete('external_applicable')
350
+            ->where($builder->expr()->eq('mount_id', $builder->createNamedParameter($mountId, IQueryBuilder::PARAM_INT)))
351
+            ->andWhere($builder->expr()->eq('type', $builder->createNamedParameter($type, IQueryBuilder::PARAM_INT)));
352
+
353
+        if (is_null($value)) {
354
+            $query = $query->andWhere($builder->expr()->isNull('value'));
355
+        } else {
356
+            $query = $query->andWhere($builder->expr()->eq('value', $builder->createNamedParameter($value, IQueryBuilder::PARAM_STR)));
357
+        }
358
+
359
+        $query->execute();
360
+    }
361
+
362
+    private function getMountsFromQuery(IQueryBuilder $query) {
363
+        $result = $query->execute();
364
+        $mounts = $result->fetchAll();
365
+        $uniqueMounts = [];
366
+        foreach ($mounts as $mount) {
367
+            $id = $mount['mount_id'];
368
+            if (!isset($uniqueMounts[$id])) {
369
+                $uniqueMounts[$id] = $mount;
370
+            }
371
+        }
372
+        $uniqueMounts = array_values($uniqueMounts);
373
+
374
+        $mountIds = array_map(function ($mount) {
375
+            return $mount['mount_id'];
376
+        }, $uniqueMounts);
377
+        $mountIds = array_values(array_unique($mountIds));
378
+
379
+        $applicable = $this->getApplicableForMounts($mountIds);
380
+        $config = $this->getConfigForMounts($mountIds);
381
+        $options = $this->getOptionsForMounts($mountIds);
382
+
383
+        return array_map(function ($mount, $applicable, $config, $options) {
384
+            $mount['type'] = (int)$mount['type'];
385
+            $mount['priority'] = (int)$mount['priority'];
386
+            $mount['applicable'] = $applicable;
387
+            $mount['config'] = $config;
388
+            $mount['options'] = $options;
389
+            return $mount;
390
+        }, $uniqueMounts, $applicable, $config, $options);
391
+    }
392
+
393
+    /**
394
+     * Get mount options from a table grouped by mount id
395
+     *
396
+     * @param string $table
397
+     * @param string[] $fields
398
+     * @param int[] $mountIds
399
+     * @return array [$mountId => [['field1' => $value1, ...], ...], ...]
400
+     */
401
+    private function selectForMounts($table, array $fields, array $mountIds) {
402
+        if (count($mountIds) === 0) {
403
+            return [];
404
+        }
405
+        $builder = $this->connection->getQueryBuilder();
406
+        $fields[] = 'mount_id';
407
+        $placeHolders = array_map(function ($id) use ($builder) {
408
+            return $builder->createPositionalParameter($id, IQueryBuilder::PARAM_INT);
409
+        }, $mountIds);
410
+        $query = $builder->select($fields)
411
+            ->from($table)
412
+            ->where($builder->expr()->in('mount_id', $placeHolders));
413
+        $rows = $query->execute()->fetchAll();
414
+
415
+        $result = [];
416
+        foreach ($mountIds as $mountId) {
417
+            $result[$mountId] = [];
418
+        }
419
+        foreach ($rows as $row) {
420
+            if (isset($row['type'])) {
421
+                $row['type'] = (int)$row['type'];
422
+            }
423
+            $result[$row['mount_id']][] = $row;
424
+        }
425
+        return $result;
426
+    }
427
+
428
+    /**
429
+     * @param int[] $mountIds
430
+     * @return array [$id => [['type' => $type, 'value' => $value], ...], ...]
431
+     */
432
+    public function getApplicableForMounts($mountIds) {
433
+        return $this->selectForMounts('external_applicable', ['type', 'value'], $mountIds);
434
+    }
435
+
436
+    /**
437
+     * @param int[] $mountIds
438
+     * @return array [$id => ['key1' => $value1, ...], ...]
439
+     */
440
+    public function getConfigForMounts($mountIds) {
441
+        $mountConfigs = $this->selectForMounts('external_config', ['key', 'value'], $mountIds);
442
+        return array_map([$this, 'createKeyValueMap'], $mountConfigs);
443
+    }
444
+
445
+    /**
446
+     * @param int[] $mountIds
447
+     * @return array [$id => ['key1' => $value1, ...], ...]
448
+     */
449
+    public function getOptionsForMounts($mountIds) {
450
+        $mountOptions = $this->selectForMounts('external_options', ['key', 'value'], $mountIds);
451
+        $optionsMap = array_map([$this, 'createKeyValueMap'], $mountOptions);
452
+        return array_map(function (array $options) {
453
+            return array_map(function ($option) {
454
+                return json_decode($option);
455
+            }, $options);
456
+        }, $optionsMap);
457
+    }
458
+
459
+    /**
460
+     * @param array $keyValuePairs [['key'=>$key, 'value=>$value], ...]
461
+     * @return array ['key1' => $value1, ...]
462
+     */
463
+    private function createKeyValueMap(array $keyValuePairs) {
464
+        $decryptedPairts = array_map(function ($pair) {
465
+            if ($pair['key'] === 'password') {
466
+                $pair['value'] = $this->decryptValue($pair['value']);
467
+            }
468
+            return $pair;
469
+        }, $keyValuePairs);
470
+        $keys = array_map(function ($pair) {
471
+            return $pair['key'];
472
+        }, $decryptedPairts);
473
+        $values = array_map(function ($pair) {
474
+            return $pair['value'];
475
+        }, $decryptedPairts);
476
+
477
+        return array_combine($keys, $values);
478
+    }
479
+
480
+    private function encryptValue($value) {
481
+        return $this->crypto->encrypt($value);
482
+    }
483
+
484
+    private function decryptValue($value) {
485
+        try {
486
+            return $this->crypto->decrypt($value);
487
+        } catch (\Exception $e) {
488
+            return $value;
489
+        }
490
+    }
491 491
 }
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.
Indentation   +56 added lines, -56 removed lines patch added patch discarded remove patch
@@ -27,70 +27,70 @@
 block discarded – undo
27 27
 use OCP\AppFramework\Http\Response;
28 28
 
29 29
 abstract class BaseResponse extends Response   {
30
-	/** @var array */
31
-	protected $data;
30
+    /** @var array */
31
+    protected $data;
32 32
 
33
-	/** @var string */
34
-	protected $format;
33
+    /** @var string */
34
+    protected $format;
35 35
 
36
-	/** @var string */
37
-	protected $statusMessage;
36
+    /** @var string */
37
+    protected $statusMessage;
38 38
 
39
-	/** @var int */
40
-	protected $itemsCount;
39
+    /** @var int */
40
+    protected $itemsCount;
41 41
 
42
-	/** @var int */
43
-	protected $itemsPerPage;
42
+    /** @var int */
43
+    protected $itemsPerPage;
44 44
 
45
-	/**
46
-	 * BaseResponse constructor.
47
-	 *
48
-	 * @param DataResponse|null $dataResponse
49
-	 * @param string $format
50
-	 * @param string|null $statusMessage
51
-	 * @param int|null $itemsCount
52
-	 * @param int|null $itemsPerPage
53
-	 */
54
-	public function __construct(DataResponse $dataResponse,
55
-								$format = 'xml',
56
-								$statusMessage = null,
57
-								$itemsCount = null,
58
-								$itemsPerPage = null) {
59
-		$this->format = $format;
60
-		$this->statusMessage = $statusMessage;
61
-		$this->itemsCount = $itemsCount;
62
-		$this->itemsPerPage = $itemsPerPage;
45
+    /**
46
+     * BaseResponse constructor.
47
+     *
48
+     * @param DataResponse|null $dataResponse
49
+     * @param string $format
50
+     * @param string|null $statusMessage
51
+     * @param int|null $itemsCount
52
+     * @param int|null $itemsPerPage
53
+     */
54
+    public function __construct(DataResponse $dataResponse,
55
+                                $format = 'xml',
56
+                                $statusMessage = null,
57
+                                $itemsCount = null,
58
+                                $itemsPerPage = null) {
59
+        $this->format = $format;
60
+        $this->statusMessage = $statusMessage;
61
+        $this->itemsCount = $itemsCount;
62
+        $this->itemsPerPage = $itemsPerPage;
63 63
 
64
-		$this->data = $dataResponse->getData();
64
+        $this->data = $dataResponse->getData();
65 65
 
66
-		$this->setHeaders($dataResponse->getHeaders());
67
-		$this->setStatus($dataResponse->getStatus());
68
-		$this->setETag($dataResponse->getETag());
69
-		$this->setLastModified($dataResponse->getLastModified());
70
-		$this->setCookies($dataResponse->getCookies());
71
-		$this->setContentSecurityPolicy(new EmptyContentSecurityPolicy());
66
+        $this->setHeaders($dataResponse->getHeaders());
67
+        $this->setStatus($dataResponse->getStatus());
68
+        $this->setETag($dataResponse->getETag());
69
+        $this->setLastModified($dataResponse->getLastModified());
70
+        $this->setCookies($dataResponse->getCookies());
71
+        $this->setContentSecurityPolicy(new EmptyContentSecurityPolicy());
72 72
 
73
-		if ($format === 'json') {
74
-			$this->addHeader(
75
-				'Content-Type', 'application/json; charset=utf-8'
76
-			);
77
-		} else {
78
-			$this->addHeader(
79
-				'Content-Type', 'application/xml; charset=utf-8'
80
-			);
81
-		}
82
-	}
73
+        if ($format === 'json') {
74
+            $this->addHeader(
75
+                'Content-Type', 'application/json; charset=utf-8'
76
+            );
77
+        } else {
78
+            $this->addHeader(
79
+                'Content-Type', 'application/xml; charset=utf-8'
80
+            );
81
+        }
82
+    }
83 83
 
84
-	/**
85
-	 * @param string[] $meta
86
-	 * @return string
87
-	 */
88
-	protected function renderResult($meta) {
89
-		// TODO rewrite functions
90
-		return \OC_API::renderResult($this->format, $meta, $this->data);
91
-	}
84
+    /**
85
+     * @param string[] $meta
86
+     * @return string
87
+     */
88
+    protected function renderResult($meta) {
89
+        // TODO rewrite functions
90
+        return \OC_API::renderResult($this->format, $meta, $this->data);
91
+    }
92 92
 
93
-	public function getOCSStatus() {
94
-		return parent::getStatus();
95
-	}
93
+    public function getOCSStatus() {
94
+        return parent::getStatus();
95
+    }
96 96
 }
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.
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.
Unused Use Statements   -1 removed lines patch added patch discarded remove patch
@@ -103,7 +103,6 @@
 block discarded – undo
103 103
 use OC\Tagging\TagMapper;
104 104
 use OC\Template\SCSSCacher;
105 105
 use OCA\Theming\ThemingDefaults;
106
-
107 106
 use OCP\App\IAppManager;
108 107
 use OCP\AppFramework\Utility\ITimeFactory;
109 108
 use OCP\Collaboration\AutoComplete\IManager;
Please login to merge, or discard this patch.
Spacing   +112 added lines, -112 removed lines patch added patch discarded remove patch
@@ -149,7 +149,7 @@  discard block
 block discarded – undo
149 149
 		parent::__construct();
150 150
 		$this->webRoot = $webRoot;
151 151
 
152
-		$this->registerService(\OCP\IServerContainer::class, function (IServerContainer $c) {
152
+		$this->registerService(\OCP\IServerContainer::class, function(IServerContainer $c) {
153 153
 			return $c;
154 154
 		});
155 155
 
@@ -159,7 +159,7 @@  discard block
 block discarded – undo
159 159
 		$this->registerAlias(IActionFactory::class, ActionFactory::class);
160 160
 
161 161
 
162
-		$this->registerService(\OCP\IPreview::class, function (Server $c) {
162
+		$this->registerService(\OCP\IPreview::class, function(Server $c) {
163 163
 			return new PreviewManager(
164 164
 				$c->getConfig(),
165 165
 				$c->getRootFolder(),
@@ -170,13 +170,13 @@  discard block
 block discarded – undo
170 170
 		});
171 171
 		$this->registerAlias('PreviewManager', \OCP\IPreview::class);
172 172
 
173
-		$this->registerService(\OC\Preview\Watcher::class, function (Server $c) {
173
+		$this->registerService(\OC\Preview\Watcher::class, function(Server $c) {
174 174
 			return new \OC\Preview\Watcher(
175 175
 				$c->getAppDataDir('preview')
176 176
 			);
177 177
 		});
178 178
 
179
-		$this->registerService('EncryptionManager', function (Server $c) {
179
+		$this->registerService('EncryptionManager', function(Server $c) {
180 180
 			$view = new View();
181 181
 			$util = new Encryption\Util(
182 182
 				$view,
@@ -194,7 +194,7 @@  discard block
 block discarded – undo
194 194
 			);
195 195
 		});
196 196
 
197
-		$this->registerService('EncryptionFileHelper', function (Server $c) {
197
+		$this->registerService('EncryptionFileHelper', function(Server $c) {
198 198
 			$util = new Encryption\Util(
199 199
 				new View(),
200 200
 				$c->getUserManager(),
@@ -208,7 +208,7 @@  discard block
 block discarded – undo
208 208
 			);
209 209
 		});
210 210
 
211
-		$this->registerService('EncryptionKeyStorage', function (Server $c) {
211
+		$this->registerService('EncryptionKeyStorage', function(Server $c) {
212 212
 			$view = new View();
213 213
 			$util = new Encryption\Util(
214 214
 				$view,
@@ -219,32 +219,32 @@  discard block
 block discarded – undo
219 219
 
220 220
 			return new Encryption\Keys\Storage($view, $util);
221 221
 		});
222
-		$this->registerService('TagMapper', function (Server $c) {
222
+		$this->registerService('TagMapper', function(Server $c) {
223 223
 			return new TagMapper($c->getDatabaseConnection());
224 224
 		});
225 225
 
226
-		$this->registerService(\OCP\ITagManager::class, function (Server $c) {
226
+		$this->registerService(\OCP\ITagManager::class, function(Server $c) {
227 227
 			$tagMapper = $c->query('TagMapper');
228 228
 			return new TagManager($tagMapper, $c->getUserSession());
229 229
 		});
230 230
 		$this->registerAlias('TagManager', \OCP\ITagManager::class);
231 231
 
232
-		$this->registerService('SystemTagManagerFactory', function (Server $c) {
232
+		$this->registerService('SystemTagManagerFactory', function(Server $c) {
233 233
 			$config = $c->getConfig();
234 234
 			$factoryClass = $config->getSystemValue('systemtags.managerFactory', '\OC\SystemTag\ManagerFactory');
235 235
 			/** @var \OC\SystemTag\ManagerFactory $factory */
236 236
 			$factory = new $factoryClass($this);
237 237
 			return $factory;
238 238
 		});
239
-		$this->registerService(\OCP\SystemTag\ISystemTagManager::class, function (Server $c) {
239
+		$this->registerService(\OCP\SystemTag\ISystemTagManager::class, function(Server $c) {
240 240
 			return $c->query('SystemTagManagerFactory')->getManager();
241 241
 		});
242 242
 		$this->registerAlias('SystemTagManager', \OCP\SystemTag\ISystemTagManager::class);
243 243
 
244
-		$this->registerService(\OCP\SystemTag\ISystemTagObjectMapper::class, function (Server $c) {
244
+		$this->registerService(\OCP\SystemTag\ISystemTagObjectMapper::class, function(Server $c) {
245 245
 			return $c->query('SystemTagManagerFactory')->getObjectMapper();
246 246
 		});
247
-		$this->registerService('RootFolder', function (Server $c) {
247
+		$this->registerService('RootFolder', function(Server $c) {
248 248
 			$manager = \OC\Files\Filesystem::getMountManager(null);
249 249
 			$view = new View();
250 250
 			$root = new Root(
@@ -265,37 +265,37 @@  discard block
 block discarded – undo
265 265
 		});
266 266
 		$this->registerAlias('SystemTagObjectMapper', \OCP\SystemTag\ISystemTagObjectMapper::class);
267 267
 
268
-		$this->registerService(\OCP\Files\IRootFolder::class, function (Server $c) {
269
-			return new LazyRoot(function () use ($c) {
268
+		$this->registerService(\OCP\Files\IRootFolder::class, function(Server $c) {
269
+			return new LazyRoot(function() use ($c) {
270 270
 				return $c->query('RootFolder');
271 271
 			});
272 272
 		});
273 273
 		$this->registerAlias('LazyRootFolder', \OCP\Files\IRootFolder::class);
274 274
 
275
-		$this->registerService(\OCP\IUserManager::class, function (Server $c) {
275
+		$this->registerService(\OCP\IUserManager::class, function(Server $c) {
276 276
 			$config = $c->getConfig();
277 277
 			return new \OC\User\Manager($config);
278 278
 		});
279 279
 		$this->registerAlias('UserManager', \OCP\IUserManager::class);
280 280
 
281
-		$this->registerService(\OCP\IGroupManager::class, function (Server $c) {
281
+		$this->registerService(\OCP\IGroupManager::class, function(Server $c) {
282 282
 			$groupManager = new \OC\Group\Manager($this->getUserManager(), $this->getLogger());
283
-			$groupManager->listen('\OC\Group', 'preCreate', function ($gid) {
283
+			$groupManager->listen('\OC\Group', 'preCreate', function($gid) {
284 284
 				\OC_Hook::emit('OC_Group', 'pre_createGroup', array('run' => true, 'gid' => $gid));
285 285
 			});
286
-			$groupManager->listen('\OC\Group', 'postCreate', function (\OC\Group\Group $gid) {
286
+			$groupManager->listen('\OC\Group', 'postCreate', function(\OC\Group\Group $gid) {
287 287
 				\OC_Hook::emit('OC_User', 'post_createGroup', array('gid' => $gid->getGID()));
288 288
 			});
289
-			$groupManager->listen('\OC\Group', 'preDelete', function (\OC\Group\Group $group) {
289
+			$groupManager->listen('\OC\Group', 'preDelete', function(\OC\Group\Group $group) {
290 290
 				\OC_Hook::emit('OC_Group', 'pre_deleteGroup', array('run' => true, 'gid' => $group->getGID()));
291 291
 			});
292
-			$groupManager->listen('\OC\Group', 'postDelete', function (\OC\Group\Group $group) {
292
+			$groupManager->listen('\OC\Group', 'postDelete', function(\OC\Group\Group $group) {
293 293
 				\OC_Hook::emit('OC_User', 'post_deleteGroup', array('gid' => $group->getGID()));
294 294
 			});
295
-			$groupManager->listen('\OC\Group', 'preAddUser', function (\OC\Group\Group $group, \OC\User\User $user) {
295
+			$groupManager->listen('\OC\Group', 'preAddUser', function(\OC\Group\Group $group, \OC\User\User $user) {
296 296
 				\OC_Hook::emit('OC_Group', 'pre_addToGroup', array('run' => true, 'uid' => $user->getUID(), 'gid' => $group->getGID()));
297 297
 			});
298
-			$groupManager->listen('\OC\Group', 'postAddUser', function (\OC\Group\Group $group, \OC\User\User $user) {
298
+			$groupManager->listen('\OC\Group', 'postAddUser', function(\OC\Group\Group $group, \OC\User\User $user) {
299 299
 				\OC_Hook::emit('OC_Group', 'post_addToGroup', array('uid' => $user->getUID(), 'gid' => $group->getGID()));
300 300
 				//Minimal fix to keep it backward compatible TODO: clean up all the GroupManager hooks
301 301
 				\OC_Hook::emit('OC_User', 'post_addToGroup', array('uid' => $user->getUID(), 'gid' => $group->getGID()));
@@ -304,7 +304,7 @@  discard block
 block discarded – undo
304 304
 		});
305 305
 		$this->registerAlias('GroupManager', \OCP\IGroupManager::class);
306 306
 
307
-		$this->registerService(Store::class, function (Server $c) {
307
+		$this->registerService(Store::class, function(Server $c) {
308 308
 			$session = $c->getSession();
309 309
 			if (\OC::$server->getSystemConfig()->getValue('installed', false)) {
310 310
 				$tokenProvider = $c->query('OC\Authentication\Token\IProvider');
@@ -315,11 +315,11 @@  discard block
 block discarded – undo
315 315
 			return new Store($session, $logger, $tokenProvider);
316 316
 		});
317 317
 		$this->registerAlias(IStore::class, Store::class);
318
-		$this->registerService('OC\Authentication\Token\DefaultTokenMapper', function (Server $c) {
318
+		$this->registerService('OC\Authentication\Token\DefaultTokenMapper', function(Server $c) {
319 319
 			$dbConnection = $c->getDatabaseConnection();
320 320
 			return new Authentication\Token\DefaultTokenMapper($dbConnection);
321 321
 		});
322
-		$this->registerService('OC\Authentication\Token\DefaultTokenProvider', function (Server $c) {
322
+		$this->registerService('OC\Authentication\Token\DefaultTokenProvider', function(Server $c) {
323 323
 			$mapper = $c->query('OC\Authentication\Token\DefaultTokenMapper');
324 324
 			$crypto = $c->getCrypto();
325 325
 			$config = $c->getConfig();
@@ -329,7 +329,7 @@  discard block
 block discarded – undo
329 329
 		});
330 330
 		$this->registerAlias('OC\Authentication\Token\IProvider', 'OC\Authentication\Token\DefaultTokenProvider');
331 331
 
332
-		$this->registerService(\OCP\IUserSession::class, function (Server $c) {
332
+		$this->registerService(\OCP\IUserSession::class, function(Server $c) {
333 333
 			$manager = $c->getUserManager();
334 334
 			$session = new \OC\Session\Memory('');
335 335
 			$timeFactory = new TimeFactory();
@@ -342,44 +342,44 @@  discard block
 block discarded – undo
342 342
 			}
343 343
 
344 344
 			$userSession = new \OC\User\Session($manager, $session, $timeFactory, $defaultTokenProvider, $c->getConfig(), $c->getSecureRandom(), $c->getLockdownManager());
345
-			$userSession->listen('\OC\User', 'preCreateUser', function ($uid, $password) {
345
+			$userSession->listen('\OC\User', 'preCreateUser', function($uid, $password) {
346 346
 				\OC_Hook::emit('OC_User', 'pre_createUser', array('run' => true, 'uid' => $uid, 'password' => $password));
347 347
 			});
348
-			$userSession->listen('\OC\User', 'postCreateUser', function ($user, $password) {
348
+			$userSession->listen('\OC\User', 'postCreateUser', function($user, $password) {
349 349
 				/** @var $user \OC\User\User */
350 350
 				\OC_Hook::emit('OC_User', 'post_createUser', array('uid' => $user->getUID(), 'password' => $password));
351 351
 			});
352
-			$userSession->listen('\OC\User', 'preDelete', function ($user) {
352
+			$userSession->listen('\OC\User', 'preDelete', function($user) {
353 353
 				/** @var $user \OC\User\User */
354 354
 				\OC_Hook::emit('OC_User', 'pre_deleteUser', array('run' => true, 'uid' => $user->getUID()));
355 355
 			});
356
-			$userSession->listen('\OC\User', 'postDelete', function ($user) {
356
+			$userSession->listen('\OC\User', 'postDelete', function($user) {
357 357
 				/** @var $user \OC\User\User */
358 358
 				\OC_Hook::emit('OC_User', 'post_deleteUser', array('uid' => $user->getUID()));
359 359
 			});
360
-			$userSession->listen('\OC\User', 'preSetPassword', function ($user, $password, $recoveryPassword) {
360
+			$userSession->listen('\OC\User', 'preSetPassword', function($user, $password, $recoveryPassword) {
361 361
 				/** @var $user \OC\User\User */
362 362
 				\OC_Hook::emit('OC_User', 'pre_setPassword', array('run' => true, 'uid' => $user->getUID(), 'password' => $password, 'recoveryPassword' => $recoveryPassword));
363 363
 			});
364
-			$userSession->listen('\OC\User', 'postSetPassword', function ($user, $password, $recoveryPassword) {
364
+			$userSession->listen('\OC\User', 'postSetPassword', function($user, $password, $recoveryPassword) {
365 365
 				/** @var $user \OC\User\User */
366 366
 				\OC_Hook::emit('OC_User', 'post_setPassword', array('run' => true, 'uid' => $user->getUID(), 'password' => $password, 'recoveryPassword' => $recoveryPassword));
367 367
 			});
368
-			$userSession->listen('\OC\User', 'preLogin', function ($uid, $password) {
368
+			$userSession->listen('\OC\User', 'preLogin', function($uid, $password) {
369 369
 				\OC_Hook::emit('OC_User', 'pre_login', array('run' => true, 'uid' => $uid, 'password' => $password));
370 370
 			});
371
-			$userSession->listen('\OC\User', 'postLogin', function ($user, $password) {
371
+			$userSession->listen('\OC\User', 'postLogin', function($user, $password) {
372 372
 				/** @var $user \OC\User\User */
373 373
 				\OC_Hook::emit('OC_User', 'post_login', array('run' => true, 'uid' => $user->getUID(), 'password' => $password));
374 374
 			});
375
-			$userSession->listen('\OC\User', 'postRememberedLogin', function ($user, $password) {
375
+			$userSession->listen('\OC\User', 'postRememberedLogin', function($user, $password) {
376 376
 				/** @var $user \OC\User\User */
377 377
 				\OC_Hook::emit('OC_User', 'post_login', array('run' => true, 'uid' => $user->getUID(), 'password' => $password));
378 378
 			});
379
-			$userSession->listen('\OC\User', 'logout', function () {
379
+			$userSession->listen('\OC\User', 'logout', function() {
380 380
 				\OC_Hook::emit('OC_User', 'logout', array());
381 381
 			});
382
-			$userSession->listen('\OC\User', 'changeUser', function ($user, $feature, $value, $oldValue) {
382
+			$userSession->listen('\OC\User', 'changeUser', function($user, $feature, $value, $oldValue) {
383 383
 				/** @var $user \OC\User\User */
384 384
 				\OC_Hook::emit('OC_User', 'changeUser', array('run' => true, 'user' => $user, 'feature' => $feature, 'value' => $value, 'old_value' => $oldValue));
385 385
 			});
@@ -387,7 +387,7 @@  discard block
 block discarded – undo
387 387
 		});
388 388
 		$this->registerAlias('UserSession', \OCP\IUserSession::class);
389 389
 
390
-		$this->registerService(\OC\Authentication\TwoFactorAuth\Manager::class, function (Server $c) {
390
+		$this->registerService(\OC\Authentication\TwoFactorAuth\Manager::class, function(Server $c) {
391 391
 			return new \OC\Authentication\TwoFactorAuth\Manager(
392 392
 				$c->getAppManager(),
393 393
 				$c->getSession(),
@@ -402,7 +402,7 @@  discard block
 block discarded – undo
402 402
 		$this->registerAlias(\OCP\INavigationManager::class, \OC\NavigationManager::class);
403 403
 		$this->registerAlias('NavigationManager', \OCP\INavigationManager::class);
404 404
 
405
-		$this->registerService(\OC\AllConfig::class, function (Server $c) {
405
+		$this->registerService(\OC\AllConfig::class, function(Server $c) {
406 406
 			return new \OC\AllConfig(
407 407
 				$c->getSystemConfig()
408 408
 			);
@@ -410,17 +410,17 @@  discard block
 block discarded – undo
410 410
 		$this->registerAlias('AllConfig', \OC\AllConfig::class);
411 411
 		$this->registerAlias(\OCP\IConfig::class, \OC\AllConfig::class);
412 412
 
413
-		$this->registerService('SystemConfig', function ($c) use ($config) {
413
+		$this->registerService('SystemConfig', function($c) use ($config) {
414 414
 			return new \OC\SystemConfig($config);
415 415
 		});
416 416
 
417
-		$this->registerService(\OC\AppConfig::class, function (Server $c) {
417
+		$this->registerService(\OC\AppConfig::class, function(Server $c) {
418 418
 			return new \OC\AppConfig($c->getDatabaseConnection());
419 419
 		});
420 420
 		$this->registerAlias('AppConfig', \OC\AppConfig::class);
421 421
 		$this->registerAlias(\OCP\IAppConfig::class, \OC\AppConfig::class);
422 422
 
423
-		$this->registerService(\OCP\L10N\IFactory::class, function (Server $c) {
423
+		$this->registerService(\OCP\L10N\IFactory::class, function(Server $c) {
424 424
 			return new \OC\L10N\Factory(
425 425
 				$c->getConfig(),
426 426
 				$c->getRequest(),
@@ -430,7 +430,7 @@  discard block
 block discarded – undo
430 430
 		});
431 431
 		$this->registerAlias('L10NFactory', \OCP\L10N\IFactory::class);
432 432
 
433
-		$this->registerService(\OCP\IURLGenerator::class, function (Server $c) {
433
+		$this->registerService(\OCP\IURLGenerator::class, function(Server $c) {
434 434
 			$config = $c->getConfig();
435 435
 			$cacheFactory = $c->getMemCacheFactory();
436 436
 			$request = $c->getRequest();
@@ -442,18 +442,18 @@  discard block
 block discarded – undo
442 442
 		});
443 443
 		$this->registerAlias('URLGenerator', \OCP\IURLGenerator::class);
444 444
 
445
-		$this->registerService('AppHelper', function ($c) {
445
+		$this->registerService('AppHelper', function($c) {
446 446
 			return new \OC\AppHelper();
447 447
 		});
448 448
 		$this->registerAlias('AppFetcher', AppFetcher::class);
449 449
 		$this->registerAlias('CategoryFetcher', CategoryFetcher::class);
450 450
 
451
-		$this->registerService(\OCP\ICache::class, function ($c) {
451
+		$this->registerService(\OCP\ICache::class, function($c) {
452 452
 			return new Cache\File();
453 453
 		});
454 454
 		$this->registerAlias('UserCache', \OCP\ICache::class);
455 455
 
456
-		$this->registerService(Factory::class, function (Server $c) {
456
+		$this->registerService(Factory::class, function(Server $c) {
457 457
 
458 458
 			$arrayCacheFactory = new \OC\Memcache\Factory('', $c->getLogger(),
459 459
 				'\\OC\\Memcache\\ArrayCache',
@@ -470,7 +470,7 @@  discard block
 block discarded – undo
470 470
 				$version = implode(',', $v);
471 471
 				$instanceId = \OC_Util::getInstanceId();
472 472
 				$path = \OC::$SERVERROOT;
473
-				$prefix = md5($instanceId . '-' . $version . '-' . $path . '-' . $urlGenerator->getBaseUrl());
473
+				$prefix = md5($instanceId.'-'.$version.'-'.$path.'-'.$urlGenerator->getBaseUrl());
474 474
 				return new \OC\Memcache\Factory($prefix, $c->getLogger(),
475 475
 					$config->getSystemValue('memcache.local', null),
476 476
 					$config->getSystemValue('memcache.distributed', null),
@@ -483,12 +483,12 @@  discard block
 block discarded – undo
483 483
 		$this->registerAlias('MemCacheFactory', Factory::class);
484 484
 		$this->registerAlias(ICacheFactory::class, Factory::class);
485 485
 
486
-		$this->registerService('RedisFactory', function (Server $c) {
486
+		$this->registerService('RedisFactory', function(Server $c) {
487 487
 			$systemConfig = $c->getSystemConfig();
488 488
 			return new RedisFactory($systemConfig);
489 489
 		});
490 490
 
491
-		$this->registerService(\OCP\Activity\IManager::class, function (Server $c) {
491
+		$this->registerService(\OCP\Activity\IManager::class, function(Server $c) {
492 492
 			return new \OC\Activity\Manager(
493 493
 				$c->getRequest(),
494 494
 				$c->getUserSession(),
@@ -498,14 +498,14 @@  discard block
 block discarded – undo
498 498
 		});
499 499
 		$this->registerAlias('ActivityManager', \OCP\Activity\IManager::class);
500 500
 
501
-		$this->registerService(\OCP\Activity\IEventMerger::class, function (Server $c) {
501
+		$this->registerService(\OCP\Activity\IEventMerger::class, function(Server $c) {
502 502
 			return new \OC\Activity\EventMerger(
503 503
 				$c->getL10N('lib')
504 504
 			);
505 505
 		});
506 506
 		$this->registerAlias(IValidator::class, Validator::class);
507 507
 
508
-		$this->registerService(\OCP\IAvatarManager::class, function (Server $c) {
508
+		$this->registerService(\OCP\IAvatarManager::class, function(Server $c) {
509 509
 			return new AvatarManager(
510 510
 				$c->getUserManager(),
511 511
 				$c->getAppDataDir('avatar'),
@@ -518,7 +518,7 @@  discard block
 block discarded – undo
518 518
 
519 519
 		$this->registerAlias(\OCP\Support\CrashReport\IRegistry::class, \OC\Support\CrashReport\Registry::class);
520 520
 
521
-		$this->registerService(\OCP\ILogger::class, function (Server $c) {
521
+		$this->registerService(\OCP\ILogger::class, function(Server $c) {
522 522
 			$logType = $c->query('AllConfig')->getSystemValue('log_type', 'file');
523 523
 			$logger = Log::getLogClass($logType);
524 524
 			call_user_func(array($logger, 'init'));
@@ -529,7 +529,7 @@  discard block
 block discarded – undo
529 529
 		});
530 530
 		$this->registerAlias('Logger', \OCP\ILogger::class);
531 531
 
532
-		$this->registerService(\OCP\BackgroundJob\IJobList::class, function (Server $c) {
532
+		$this->registerService(\OCP\BackgroundJob\IJobList::class, function(Server $c) {
533 533
 			$config = $c->getConfig();
534 534
 			return new \OC\BackgroundJob\JobList(
535 535
 				$c->getDatabaseConnection(),
@@ -539,7 +539,7 @@  discard block
 block discarded – undo
539 539
 		});
540 540
 		$this->registerAlias('JobList', \OCP\BackgroundJob\IJobList::class);
541 541
 
542
-		$this->registerService(\OCP\Route\IRouter::class, function (Server $c) {
542
+		$this->registerService(\OCP\Route\IRouter::class, function(Server $c) {
543 543
 			$cacheFactory = $c->getMemCacheFactory();
544 544
 			$logger = $c->getLogger();
545 545
 			if ($cacheFactory->isAvailableLowLatency()) {
@@ -551,12 +551,12 @@  discard block
 block discarded – undo
551 551
 		});
552 552
 		$this->registerAlias('Router', \OCP\Route\IRouter::class);
553 553
 
554
-		$this->registerService(\OCP\ISearch::class, function ($c) {
554
+		$this->registerService(\OCP\ISearch::class, function($c) {
555 555
 			return new Search();
556 556
 		});
557 557
 		$this->registerAlias('Search', \OCP\ISearch::class);
558 558
 
559
-		$this->registerService(\OC\Security\RateLimiting\Limiter::class, function ($c) {
559
+		$this->registerService(\OC\Security\RateLimiting\Limiter::class, function($c) {
560 560
 			return new \OC\Security\RateLimiting\Limiter(
561 561
 				$this->getUserSession(),
562 562
 				$this->getRequest(),
@@ -564,34 +564,34 @@  discard block
 block discarded – undo
564 564
 				$c->query(\OC\Security\RateLimiting\Backend\IBackend::class)
565 565
 			);
566 566
 		});
567
-		$this->registerService(\OC\Security\RateLimiting\Backend\IBackend::class, function ($c) {
567
+		$this->registerService(\OC\Security\RateLimiting\Backend\IBackend::class, function($c) {
568 568
 			return new \OC\Security\RateLimiting\Backend\MemoryCache(
569 569
 				$this->getMemCacheFactory(),
570 570
 				new \OC\AppFramework\Utility\TimeFactory()
571 571
 			);
572 572
 		});
573 573
 
574
-		$this->registerService(\OCP\Security\ISecureRandom::class, function ($c) {
574
+		$this->registerService(\OCP\Security\ISecureRandom::class, function($c) {
575 575
 			return new SecureRandom();
576 576
 		});
577 577
 		$this->registerAlias('SecureRandom', \OCP\Security\ISecureRandom::class);
578 578
 
579
-		$this->registerService(\OCP\Security\ICrypto::class, function (Server $c) {
579
+		$this->registerService(\OCP\Security\ICrypto::class, function(Server $c) {
580 580
 			return new Crypto($c->getConfig(), $c->getSecureRandom());
581 581
 		});
582 582
 		$this->registerAlias('Crypto', \OCP\Security\ICrypto::class);
583 583
 
584
-		$this->registerService(\OCP\Security\IHasher::class, function (Server $c) {
584
+		$this->registerService(\OCP\Security\IHasher::class, function(Server $c) {
585 585
 			return new Hasher($c->getConfig());
586 586
 		});
587 587
 		$this->registerAlias('Hasher', \OCP\Security\IHasher::class);
588 588
 
589
-		$this->registerService(\OCP\Security\ICredentialsManager::class, function (Server $c) {
589
+		$this->registerService(\OCP\Security\ICredentialsManager::class, function(Server $c) {
590 590
 			return new CredentialsManager($c->getCrypto(), $c->getDatabaseConnection());
591 591
 		});
592 592
 		$this->registerAlias('CredentialsManager', \OCP\Security\ICredentialsManager::class);
593 593
 
594
-		$this->registerService(IDBConnection::class, function (Server $c) {
594
+		$this->registerService(IDBConnection::class, function(Server $c) {
595 595
 			$systemConfig = $c->getSystemConfig();
596 596
 			$factory = new \OC\DB\ConnectionFactory($systemConfig);
597 597
 			$type = $systemConfig->getValue('dbtype', 'sqlite');
@@ -605,7 +605,7 @@  discard block
 block discarded – undo
605 605
 		});
606 606
 		$this->registerAlias('DatabaseConnection', IDBConnection::class);
607 607
 
608
-		$this->registerService('HTTPHelper', function (Server $c) {
608
+		$this->registerService('HTTPHelper', function(Server $c) {
609 609
 			$config = $c->getConfig();
610 610
 			return new HTTPHelper(
611 611
 				$config,
@@ -613,7 +613,7 @@  discard block
 block discarded – undo
613 613
 			);
614 614
 		});
615 615
 
616
-		$this->registerService(\OCP\Http\Client\IClientService::class, function (Server $c) {
616
+		$this->registerService(\OCP\Http\Client\IClientService::class, function(Server $c) {
617 617
 			$user = \OC_User::getUser();
618 618
 			$uid = $user ? $user : null;
619 619
 			return new ClientService(
@@ -628,7 +628,7 @@  discard block
 block discarded – undo
628 628
 			);
629 629
 		});
630 630
 		$this->registerAlias('HttpClientService', \OCP\Http\Client\IClientService::class);
631
-		$this->registerService(\OCP\Diagnostics\IEventLogger::class, function (Server $c) {
631
+		$this->registerService(\OCP\Diagnostics\IEventLogger::class, function(Server $c) {
632 632
 			$eventLogger = new EventLogger();
633 633
 			if ($c->getSystemConfig()->getValue('debug', false)) {
634 634
 				// In debug mode, module is being activated by default
@@ -638,7 +638,7 @@  discard block
 block discarded – undo
638 638
 		});
639 639
 		$this->registerAlias('EventLogger', \OCP\Diagnostics\IEventLogger::class);
640 640
 
641
-		$this->registerService(\OCP\Diagnostics\IQueryLogger::class, function (Server $c) {
641
+		$this->registerService(\OCP\Diagnostics\IQueryLogger::class, function(Server $c) {
642 642
 			$queryLogger = new QueryLogger();
643 643
 			if ($c->getSystemConfig()->getValue('debug', false)) {
644 644
 				// In debug mode, module is being activated by default
@@ -648,7 +648,7 @@  discard block
 block discarded – undo
648 648
 		});
649 649
 		$this->registerAlias('QueryLogger', \OCP\Diagnostics\IQueryLogger::class);
650 650
 
651
-		$this->registerService(TempManager::class, function (Server $c) {
651
+		$this->registerService(TempManager::class, function(Server $c) {
652 652
 			return new TempManager(
653 653
 				$c->getLogger(),
654 654
 				$c->getConfig()
@@ -657,7 +657,7 @@  discard block
 block discarded – undo
657 657
 		$this->registerAlias('TempManager', TempManager::class);
658 658
 		$this->registerAlias(ITempManager::class, TempManager::class);
659 659
 
660
-		$this->registerService(AppManager::class, function (Server $c) {
660
+		$this->registerService(AppManager::class, function(Server $c) {
661 661
 			return new \OC\App\AppManager(
662 662
 				$c->getUserSession(),
663 663
 				$c->getAppConfig(),
@@ -669,7 +669,7 @@  discard block
 block discarded – undo
669 669
 		$this->registerAlias('AppManager', AppManager::class);
670 670
 		$this->registerAlias(IAppManager::class, AppManager::class);
671 671
 
672
-		$this->registerService(\OCP\IDateTimeZone::class, function (Server $c) {
672
+		$this->registerService(\OCP\IDateTimeZone::class, function(Server $c) {
673 673
 			return new DateTimeZone(
674 674
 				$c->getConfig(),
675 675
 				$c->getSession()
@@ -677,7 +677,7 @@  discard block
 block discarded – undo
677 677
 		});
678 678
 		$this->registerAlias('DateTimeZone', \OCP\IDateTimeZone::class);
679 679
 
680
-		$this->registerService(\OCP\IDateTimeFormatter::class, function (Server $c) {
680
+		$this->registerService(\OCP\IDateTimeFormatter::class, function(Server $c) {
681 681
 			$language = $c->getConfig()->getUserValue($c->getSession()->get('user_id'), 'core', 'lang', null);
682 682
 
683 683
 			return new DateTimeFormatter(
@@ -687,7 +687,7 @@  discard block
 block discarded – undo
687 687
 		});
688 688
 		$this->registerAlias('DateTimeFormatter', \OCP\IDateTimeFormatter::class);
689 689
 
690
-		$this->registerService(\OCP\Files\Config\IUserMountCache::class, function (Server $c) {
690
+		$this->registerService(\OCP\Files\Config\IUserMountCache::class, function(Server $c) {
691 691
 			$mountCache = new UserMountCache($c->getDatabaseConnection(), $c->getUserManager(), $c->getLogger());
692 692
 			$listener = new UserMountCacheListener($mountCache);
693 693
 			$listener->listen($c->getUserManager());
@@ -695,7 +695,7 @@  discard block
 block discarded – undo
695 695
 		});
696 696
 		$this->registerAlias('UserMountCache', \OCP\Files\Config\IUserMountCache::class);
697 697
 
698
-		$this->registerService(\OCP\Files\Config\IMountProviderCollection::class, function (Server $c) {
698
+		$this->registerService(\OCP\Files\Config\IMountProviderCollection::class, function(Server $c) {
699 699
 			$loader = \OC\Files\Filesystem::getLoader();
700 700
 			$mountCache = $c->query('UserMountCache');
701 701
 			$manager = new \OC\Files\Config\MountProviderCollection($loader, $mountCache);
@@ -711,10 +711,10 @@  discard block
 block discarded – undo
711 711
 		});
712 712
 		$this->registerAlias('MountConfigManager', \OCP\Files\Config\IMountProviderCollection::class);
713 713
 
714
-		$this->registerService('IniWrapper', function ($c) {
714
+		$this->registerService('IniWrapper', function($c) {
715 715
 			return new IniGetWrapper();
716 716
 		});
717
-		$this->registerService('AsyncCommandBus', function (Server $c) {
717
+		$this->registerService('AsyncCommandBus', function(Server $c) {
718 718
 			$busClass = $c->getConfig()->getSystemValue('commandbus');
719 719
 			if ($busClass) {
720 720
 				list($app, $class) = explode('::', $busClass, 2);
@@ -729,10 +729,10 @@  discard block
 block discarded – undo
729 729
 				return new CronBus($jobList);
730 730
 			}
731 731
 		});
732
-		$this->registerService('TrustedDomainHelper', function ($c) {
732
+		$this->registerService('TrustedDomainHelper', function($c) {
733 733
 			return new TrustedDomainHelper($this->getConfig());
734 734
 		});
735
-		$this->registerService('Throttler', function (Server $c) {
735
+		$this->registerService('Throttler', function(Server $c) {
736 736
 			return new Throttler(
737 737
 				$c->getDatabaseConnection(),
738 738
 				new TimeFactory(),
@@ -740,7 +740,7 @@  discard block
 block discarded – undo
740 740
 				$c->getConfig()
741 741
 			);
742 742
 		});
743
-		$this->registerService('IntegrityCodeChecker', function (Server $c) {
743
+		$this->registerService('IntegrityCodeChecker', function(Server $c) {
744 744
 			// IConfig and IAppManager requires a working database. This code
745 745
 			// might however be called when ownCloud is not yet setup.
746 746
 			if (\OC::$server->getSystemConfig()->getValue('installed', false)) {
@@ -761,7 +761,7 @@  discard block
 block discarded – undo
761 761
 				$c->getTempManager()
762 762
 			);
763 763
 		});
764
-		$this->registerService(\OCP\IRequest::class, function ($c) {
764
+		$this->registerService(\OCP\IRequest::class, function($c) {
765 765
 			if (isset($this['urlParams'])) {
766 766
 				$urlParams = $this['urlParams'];
767 767
 			} else {
@@ -797,7 +797,7 @@  discard block
 block discarded – undo
797 797
 		});
798 798
 		$this->registerAlias('Request', \OCP\IRequest::class);
799 799
 
800
-		$this->registerService(\OCP\Mail\IMailer::class, function (Server $c) {
800
+		$this->registerService(\OCP\Mail\IMailer::class, function(Server $c) {
801 801
 			return new Mailer(
802 802
 				$c->getConfig(),
803 803
 				$c->getLogger(),
@@ -808,7 +808,7 @@  discard block
 block discarded – undo
808 808
 		});
809 809
 		$this->registerAlias('Mailer', \OCP\Mail\IMailer::class);
810 810
 
811
-		$this->registerService('LDAPProvider', function (Server $c) {
811
+		$this->registerService('LDAPProvider', function(Server $c) {
812 812
 			$config = $c->getConfig();
813 813
 			$factoryClass = $config->getSystemValue('ldapProviderFactory', null);
814 814
 			if (is_null($factoryClass)) {
@@ -818,7 +818,7 @@  discard block
 block discarded – undo
818 818
 			$factory = new $factoryClass($this);
819 819
 			return $factory->getLDAPProvider();
820 820
 		});
821
-		$this->registerService(ILockingProvider::class, function (Server $c) {
821
+		$this->registerService(ILockingProvider::class, function(Server $c) {
822 822
 			$ini = $c->getIniWrapper();
823 823
 			$config = $c->getConfig();
824 824
 			$ttl = $config->getSystemValue('filelocking.ttl', max(3600, $ini->getNumeric('max_execution_time')));
@@ -835,49 +835,49 @@  discard block
 block discarded – undo
835 835
 		});
836 836
 		$this->registerAlias('LockingProvider', ILockingProvider::class);
837 837
 
838
-		$this->registerService(\OCP\Files\Mount\IMountManager::class, function () {
838
+		$this->registerService(\OCP\Files\Mount\IMountManager::class, function() {
839 839
 			return new \OC\Files\Mount\Manager();
840 840
 		});
841 841
 		$this->registerAlias('MountManager', \OCP\Files\Mount\IMountManager::class);
842 842
 
843
-		$this->registerService(\OCP\Files\IMimeTypeDetector::class, function (Server $c) {
843
+		$this->registerService(\OCP\Files\IMimeTypeDetector::class, function(Server $c) {
844 844
 			return new \OC\Files\Type\Detection(
845 845
 				$c->getURLGenerator(),
846 846
 				\OC::$configDir,
847
-				\OC::$SERVERROOT . '/resources/config/'
847
+				\OC::$SERVERROOT.'/resources/config/'
848 848
 			);
849 849
 		});
850 850
 		$this->registerAlias('MimeTypeDetector', \OCP\Files\IMimeTypeDetector::class);
851 851
 
852
-		$this->registerService(\OCP\Files\IMimeTypeLoader::class, function (Server $c) {
852
+		$this->registerService(\OCP\Files\IMimeTypeLoader::class, function(Server $c) {
853 853
 			return new \OC\Files\Type\Loader(
854 854
 				$c->getDatabaseConnection()
855 855
 			);
856 856
 		});
857 857
 		$this->registerAlias('MimeTypeLoader', \OCP\Files\IMimeTypeLoader::class);
858
-		$this->registerService(BundleFetcher::class, function () {
858
+		$this->registerService(BundleFetcher::class, function() {
859 859
 			return new BundleFetcher($this->getL10N('lib'));
860 860
 		});
861
-		$this->registerService(\OCP\Notification\IManager::class, function (Server $c) {
861
+		$this->registerService(\OCP\Notification\IManager::class, function(Server $c) {
862 862
 			return new Manager(
863 863
 				$c->query(IValidator::class)
864 864
 			);
865 865
 		});
866 866
 		$this->registerAlias('NotificationManager', \OCP\Notification\IManager::class);
867 867
 
868
-		$this->registerService(\OC\CapabilitiesManager::class, function (Server $c) {
868
+		$this->registerService(\OC\CapabilitiesManager::class, function(Server $c) {
869 869
 			$manager = new \OC\CapabilitiesManager($c->getLogger());
870
-			$manager->registerCapability(function () use ($c) {
870
+			$manager->registerCapability(function() use ($c) {
871 871
 				return new \OC\OCS\CoreCapabilities($c->getConfig());
872 872
 			});
873
-			$manager->registerCapability(function () use ($c) {
873
+			$manager->registerCapability(function() use ($c) {
874 874
 				return $c->query(\OC\Security\Bruteforce\Capabilities::class);
875 875
 			});
876 876
 			return $manager;
877 877
 		});
878 878
 		$this->registerAlias('CapabilitiesManager', \OC\CapabilitiesManager::class);
879 879
 
880
-		$this->registerService(\OCP\Comments\ICommentsManager::class, function (Server $c) {
880
+		$this->registerService(\OCP\Comments\ICommentsManager::class, function(Server $c) {
881 881
 			$config = $c->getConfig();
882 882
 			$factoryClass = $config->getSystemValue('comments.managerFactory', '\OC\Comments\ManagerFactory');
883 883
 			/** @var \OCP\Comments\ICommentsManagerFactory $factory */
@@ -886,7 +886,7 @@  discard block
 block discarded – undo
886 886
 		});
887 887
 		$this->registerAlias('CommentsManager', \OCP\Comments\ICommentsManager::class);
888 888
 
889
-		$this->registerService('ThemingDefaults', function (Server $c) {
889
+		$this->registerService('ThemingDefaults', function(Server $c) {
890 890
 			/*
891 891
 			 * Dark magic for autoloader.
892 892
 			 * If we do a class_exists it will try to load the class which will
@@ -913,7 +913,7 @@  discard block
 block discarded – undo
913 913
 			}
914 914
 			return new \OC_Defaults();
915 915
 		});
916
-		$this->registerService(SCSSCacher::class, function (Server $c) {
916
+		$this->registerService(SCSSCacher::class, function(Server $c) {
917 917
 			/** @var Factory $cacheFactory */
918 918
 			$cacheFactory = $c->query(Factory::class);
919 919
 			return new SCSSCacher(
@@ -926,13 +926,13 @@  discard block
 block discarded – undo
926 926
 				$cacheFactory->create('SCSS')
927 927
 			);
928 928
 		});
929
-		$this->registerService(EventDispatcher::class, function () {
929
+		$this->registerService(EventDispatcher::class, function() {
930 930
 			return new EventDispatcher();
931 931
 		});
932 932
 		$this->registerAlias('EventDispatcher', EventDispatcher::class);
933 933
 		$this->registerAlias(EventDispatcherInterface::class, EventDispatcher::class);
934 934
 
935
-		$this->registerService('CryptoWrapper', function (Server $c) {
935
+		$this->registerService('CryptoWrapper', function(Server $c) {
936 936
 			// FIXME: Instantiiated here due to cyclic dependency
937 937
 			$request = new Request(
938 938
 				[
@@ -957,7 +957,7 @@  discard block
 block discarded – undo
957 957
 				$request
958 958
 			);
959 959
 		});
960
-		$this->registerService('CsrfTokenManager', function (Server $c) {
960
+		$this->registerService('CsrfTokenManager', function(Server $c) {
961 961
 			$tokenGenerator = new CsrfTokenGenerator($c->getSecureRandom());
962 962
 
963 963
 			return new CsrfTokenManager(
@@ -965,22 +965,22 @@  discard block
 block discarded – undo
965 965
 				$c->query(SessionStorage::class)
966 966
 			);
967 967
 		});
968
-		$this->registerService(SessionStorage::class, function (Server $c) {
968
+		$this->registerService(SessionStorage::class, function(Server $c) {
969 969
 			return new SessionStorage($c->getSession());
970 970
 		});
971
-		$this->registerService(\OCP\Security\IContentSecurityPolicyManager::class, function (Server $c) {
971
+		$this->registerService(\OCP\Security\IContentSecurityPolicyManager::class, function(Server $c) {
972 972
 			return new ContentSecurityPolicyManager();
973 973
 		});
974 974
 		$this->registerAlias('ContentSecurityPolicyManager', \OCP\Security\IContentSecurityPolicyManager::class);
975 975
 
976
-		$this->registerService('ContentSecurityPolicyNonceManager', function (Server $c) {
976
+		$this->registerService('ContentSecurityPolicyNonceManager', function(Server $c) {
977 977
 			return new ContentSecurityPolicyNonceManager(
978 978
 				$c->getCsrfTokenManager(),
979 979
 				$c->getRequest()
980 980
 			);
981 981
 		});
982 982
 
983
-		$this->registerService(\OCP\Share\IManager::class, function (Server $c) {
983
+		$this->registerService(\OCP\Share\IManager::class, function(Server $c) {
984 984
 			$config = $c->getConfig();
985 985
 			$factoryClass = $config->getSystemValue('sharing.managerFactory', '\OC\Share20\ProviderFactory');
986 986
 			/** @var \OCP\Share\IProviderFactory $factory */
@@ -1023,7 +1023,7 @@  discard block
 block discarded – undo
1023 1023
 
1024 1024
 		$this->registerAlias(\OCP\Collaboration\AutoComplete\IManager::class, \OC\Collaboration\AutoComplete\Manager::class);
1025 1025
 
1026
-		$this->registerService('SettingsManager', function (Server $c) {
1026
+		$this->registerService('SettingsManager', function(Server $c) {
1027 1027
 			$manager = new \OC\Settings\Manager(
1028 1028
 				$c->getLogger(),
1029 1029
 				$c->getDatabaseConnection(),
@@ -1043,29 +1043,29 @@  discard block
 block discarded – undo
1043 1043
 			);
1044 1044
 			return $manager;
1045 1045
 		});
1046
-		$this->registerService(\OC\Files\AppData\Factory::class, function (Server $c) {
1046
+		$this->registerService(\OC\Files\AppData\Factory::class, function(Server $c) {
1047 1047
 			return new \OC\Files\AppData\Factory(
1048 1048
 				$c->getRootFolder(),
1049 1049
 				$c->getSystemConfig()
1050 1050
 			);
1051 1051
 		});
1052 1052
 
1053
-		$this->registerService('LockdownManager', function (Server $c) {
1054
-			return new LockdownManager(function () use ($c) {
1053
+		$this->registerService('LockdownManager', function(Server $c) {
1054
+			return new LockdownManager(function() use ($c) {
1055 1055
 				return $c->getSession();
1056 1056
 			});
1057 1057
 		});
1058 1058
 
1059
-		$this->registerService(\OCP\OCS\IDiscoveryService::class, function (Server $c) {
1059
+		$this->registerService(\OCP\OCS\IDiscoveryService::class, function(Server $c) {
1060 1060
 			return new DiscoveryService($c->getMemCacheFactory(), $c->getHTTPClientService());
1061 1061
 		});
1062 1062
 
1063
-		$this->registerService(ICloudIdManager::class, function (Server $c) {
1063
+		$this->registerService(ICloudIdManager::class, function(Server $c) {
1064 1064
 			return new CloudIdManager();
1065 1065
 		});
1066 1066
 
1067 1067
 		/* To trick DI since we don't extend the DIContainer here */
1068
-		$this->registerService(CleanPreviewsBackgroundJob::class, function (Server $c) {
1068
+		$this->registerService(CleanPreviewsBackgroundJob::class, function(Server $c) {
1069 1069
 			return new CleanPreviewsBackgroundJob(
1070 1070
 				$c->getRootFolder(),
1071 1071
 				$c->getLogger(),
@@ -1080,18 +1080,18 @@  discard block
 block discarded – undo
1080 1080
 		$this->registerAlias(\OCP\AppFramework\Utility\ITimeFactory::class, \OC\AppFramework\Utility\TimeFactory::class);
1081 1081
 		$this->registerAlias('TimeFactory', \OCP\AppFramework\Utility\ITimeFactory::class);
1082 1082
 
1083
-		$this->registerService(Defaults::class, function (Server $c) {
1083
+		$this->registerService(Defaults::class, function(Server $c) {
1084 1084
 			return new Defaults(
1085 1085
 				$c->getThemingDefaults()
1086 1086
 			);
1087 1087
 		});
1088 1088
 		$this->registerAlias('Defaults', \OCP\Defaults::class);
1089 1089
 
1090
-		$this->registerService(\OCP\ISession::class, function (SimpleContainer $c) {
1090
+		$this->registerService(\OCP\ISession::class, function(SimpleContainer $c) {
1091 1091
 			return $c->query(\OCP\IUserSession::class)->getSession();
1092 1092
 		});
1093 1093
 
1094
-		$this->registerService(IShareHelper::class, function (Server $c) {
1094
+		$this->registerService(IShareHelper::class, function(Server $c) {
1095 1095
 			return new ShareHelper(
1096 1096
 				$c->query(\OCP\Share\IManager::class)
1097 1097
 			);
@@ -1232,7 +1232,7 @@  discard block
 block discarded – undo
1232 1232
 	 * @deprecated since 9.2.0 use IAppData
1233 1233
 	 */
1234 1234
 	public function getAppFolder() {
1235
-		$dir = '/' . \OC_App::getCurrentApp();
1235
+		$dir = '/'.\OC_App::getCurrentApp();
1236 1236
 		$root = $this->getRootFolder();
1237 1237
 		if (!$root->nodeExists($dir)) {
1238 1238
 			$folder = $root->newFolder($dir);
@@ -1816,7 +1816,7 @@  discard block
 block discarded – undo
1816 1816
 	/**
1817 1817
 	 * @return \OCP\Collaboration\AutoComplete\IManager
1818 1818
 	 */
1819
-	public function getAutoCompleteManager(){
1819
+	public function getAutoCompleteManager() {
1820 1820
 		return $this->query(IManager::class);
1821 1821
 	}
1822 1822
 
Please login to merge, or discard this patch.
Indentation   +1744 added lines, -1744 removed lines patch added patch discarded remove patch
@@ -139,1753 +139,1753 @@
 block discarded – undo
139 139
  * TODO: hookup all manager classes
140 140
  */
141 141
 class Server extends ServerContainer implements IServerContainer {
142
-	/** @var string */
143
-	private $webRoot;
144
-
145
-	/**
146
-	 * @param string $webRoot
147
-	 * @param \OC\Config $config
148
-	 */
149
-	public function __construct($webRoot, \OC\Config $config) {
150
-		parent::__construct();
151
-		$this->webRoot = $webRoot;
152
-
153
-		$this->registerService(\OCP\IServerContainer::class, function (IServerContainer $c) {
154
-			return $c;
155
-		});
156
-
157
-		$this->registerAlias(\OCP\Calendar\IManager::class, \OC\Calendar\Manager::class);
158
-		$this->registerAlias('CalendarManager', \OC\Calendar\Manager::class);
159
-
160
-		$this->registerAlias(\OCP\Contacts\IManager::class, \OC\ContactsManager::class);
161
-		$this->registerAlias('ContactsManager', \OCP\Contacts\IManager::class);
162
-
163
-		$this->registerAlias(IActionFactory::class, ActionFactory::class);
164
-
165
-
166
-		$this->registerService(\OCP\IPreview::class, function (Server $c) {
167
-			return new PreviewManager(
168
-				$c->getConfig(),
169
-				$c->getRootFolder(),
170
-				$c->getAppDataDir('preview'),
171
-				$c->getEventDispatcher(),
172
-				$c->getSession()->get('user_id')
173
-			);
174
-		});
175
-		$this->registerAlias('PreviewManager', \OCP\IPreview::class);
176
-
177
-		$this->registerService(\OC\Preview\Watcher::class, function (Server $c) {
178
-			return new \OC\Preview\Watcher(
179
-				$c->getAppDataDir('preview')
180
-			);
181
-		});
182
-
183
-		$this->registerService('EncryptionManager', function (Server $c) {
184
-			$view = new View();
185
-			$util = new Encryption\Util(
186
-				$view,
187
-				$c->getUserManager(),
188
-				$c->getGroupManager(),
189
-				$c->getConfig()
190
-			);
191
-			return new Encryption\Manager(
192
-				$c->getConfig(),
193
-				$c->getLogger(),
194
-				$c->getL10N('core'),
195
-				new View(),
196
-				$util,
197
-				new ArrayCache()
198
-			);
199
-		});
200
-
201
-		$this->registerService('EncryptionFileHelper', function (Server $c) {
202
-			$util = new Encryption\Util(
203
-				new View(),
204
-				$c->getUserManager(),
205
-				$c->getGroupManager(),
206
-				$c->getConfig()
207
-			);
208
-			return new Encryption\File(
209
-				$util,
210
-				$c->getRootFolder(),
211
-				$c->getShareManager()
212
-			);
213
-		});
214
-
215
-		$this->registerService('EncryptionKeyStorage', function (Server $c) {
216
-			$view = new View();
217
-			$util = new Encryption\Util(
218
-				$view,
219
-				$c->getUserManager(),
220
-				$c->getGroupManager(),
221
-				$c->getConfig()
222
-			);
223
-
224
-			return new Encryption\Keys\Storage($view, $util);
225
-		});
226
-		$this->registerService('TagMapper', function (Server $c) {
227
-			return new TagMapper($c->getDatabaseConnection());
228
-		});
229
-
230
-		$this->registerService(\OCP\ITagManager::class, function (Server $c) {
231
-			$tagMapper = $c->query('TagMapper');
232
-			return new TagManager($tagMapper, $c->getUserSession());
233
-		});
234
-		$this->registerAlias('TagManager', \OCP\ITagManager::class);
235
-
236
-		$this->registerService('SystemTagManagerFactory', function (Server $c) {
237
-			$config = $c->getConfig();
238
-			$factoryClass = $config->getSystemValue('systemtags.managerFactory', '\OC\SystemTag\ManagerFactory');
239
-			/** @var \OC\SystemTag\ManagerFactory $factory */
240
-			$factory = new $factoryClass($this);
241
-			return $factory;
242
-		});
243
-		$this->registerService(\OCP\SystemTag\ISystemTagManager::class, function (Server $c) {
244
-			return $c->query('SystemTagManagerFactory')->getManager();
245
-		});
246
-		$this->registerAlias('SystemTagManager', \OCP\SystemTag\ISystemTagManager::class);
247
-
248
-		$this->registerService(\OCP\SystemTag\ISystemTagObjectMapper::class, function (Server $c) {
249
-			return $c->query('SystemTagManagerFactory')->getObjectMapper();
250
-		});
251
-		$this->registerService('RootFolder', function (Server $c) {
252
-			$manager = \OC\Files\Filesystem::getMountManager(null);
253
-			$view = new View();
254
-			$root = new Root(
255
-				$manager,
256
-				$view,
257
-				null,
258
-				$c->getUserMountCache(),
259
-				$this->getLogger(),
260
-				$this->getUserManager()
261
-			);
262
-			$connector = new HookConnector($root, $view);
263
-			$connector->viewToNode();
264
-
265
-			$previewConnector = new \OC\Preview\WatcherConnector($root, $c->getSystemConfig());
266
-			$previewConnector->connectWatcher();
267
-
268
-			return $root;
269
-		});
270
-		$this->registerAlias('SystemTagObjectMapper', \OCP\SystemTag\ISystemTagObjectMapper::class);
271
-
272
-		$this->registerService(\OCP\Files\IRootFolder::class, function (Server $c) {
273
-			return new LazyRoot(function () use ($c) {
274
-				return $c->query('RootFolder');
275
-			});
276
-		});
277
-		$this->registerAlias('LazyRootFolder', \OCP\Files\IRootFolder::class);
278
-
279
-		$this->registerService(\OCP\IUserManager::class, function (Server $c) {
280
-			$config = $c->getConfig();
281
-			return new \OC\User\Manager($config);
282
-		});
283
-		$this->registerAlias('UserManager', \OCP\IUserManager::class);
284
-
285
-		$this->registerService(\OCP\IGroupManager::class, function (Server $c) {
286
-			$groupManager = new \OC\Group\Manager($this->getUserManager(), $this->getLogger());
287
-			$groupManager->listen('\OC\Group', 'preCreate', function ($gid) {
288
-				\OC_Hook::emit('OC_Group', 'pre_createGroup', array('run' => true, 'gid' => $gid));
289
-			});
290
-			$groupManager->listen('\OC\Group', 'postCreate', function (\OC\Group\Group $gid) {
291
-				\OC_Hook::emit('OC_User', 'post_createGroup', array('gid' => $gid->getGID()));
292
-			});
293
-			$groupManager->listen('\OC\Group', 'preDelete', function (\OC\Group\Group $group) {
294
-				\OC_Hook::emit('OC_Group', 'pre_deleteGroup', array('run' => true, 'gid' => $group->getGID()));
295
-			});
296
-			$groupManager->listen('\OC\Group', 'postDelete', function (\OC\Group\Group $group) {
297
-				\OC_Hook::emit('OC_User', 'post_deleteGroup', array('gid' => $group->getGID()));
298
-			});
299
-			$groupManager->listen('\OC\Group', 'preAddUser', function (\OC\Group\Group $group, \OC\User\User $user) {
300
-				\OC_Hook::emit('OC_Group', 'pre_addToGroup', array('run' => true, 'uid' => $user->getUID(), 'gid' => $group->getGID()));
301
-			});
302
-			$groupManager->listen('\OC\Group', 'postAddUser', function (\OC\Group\Group $group, \OC\User\User $user) {
303
-				\OC_Hook::emit('OC_Group', 'post_addToGroup', array('uid' => $user->getUID(), 'gid' => $group->getGID()));
304
-				//Minimal fix to keep it backward compatible TODO: clean up all the GroupManager hooks
305
-				\OC_Hook::emit('OC_User', 'post_addToGroup', array('uid' => $user->getUID(), 'gid' => $group->getGID()));
306
-			});
307
-			return $groupManager;
308
-		});
309
-		$this->registerAlias('GroupManager', \OCP\IGroupManager::class);
310
-
311
-		$this->registerService(Store::class, function (Server $c) {
312
-			$session = $c->getSession();
313
-			if (\OC::$server->getSystemConfig()->getValue('installed', false)) {
314
-				$tokenProvider = $c->query('OC\Authentication\Token\IProvider');
315
-			} else {
316
-				$tokenProvider = null;
317
-			}
318
-			$logger = $c->getLogger();
319
-			return new Store($session, $logger, $tokenProvider);
320
-		});
321
-		$this->registerAlias(IStore::class, Store::class);
322
-		$this->registerService('OC\Authentication\Token\DefaultTokenMapper', function (Server $c) {
323
-			$dbConnection = $c->getDatabaseConnection();
324
-			return new Authentication\Token\DefaultTokenMapper($dbConnection);
325
-		});
326
-		$this->registerService('OC\Authentication\Token\DefaultTokenProvider', function (Server $c) {
327
-			$mapper = $c->query('OC\Authentication\Token\DefaultTokenMapper');
328
-			$crypto = $c->getCrypto();
329
-			$config = $c->getConfig();
330
-			$logger = $c->getLogger();
331
-			$timeFactory = new TimeFactory();
332
-			return new \OC\Authentication\Token\DefaultTokenProvider($mapper, $crypto, $config, $logger, $timeFactory);
333
-		});
334
-		$this->registerAlias('OC\Authentication\Token\IProvider', 'OC\Authentication\Token\DefaultTokenProvider');
335
-
336
-		$this->registerService(\OCP\IUserSession::class, function (Server $c) {
337
-			$manager = $c->getUserManager();
338
-			$session = new \OC\Session\Memory('');
339
-			$timeFactory = new TimeFactory();
340
-			// Token providers might require a working database. This code
341
-			// might however be called when ownCloud is not yet setup.
342
-			if (\OC::$server->getSystemConfig()->getValue('installed', false)) {
343
-				$defaultTokenProvider = $c->query('OC\Authentication\Token\IProvider');
344
-			} else {
345
-				$defaultTokenProvider = null;
346
-			}
347
-
348
-			$userSession = new \OC\User\Session($manager, $session, $timeFactory, $defaultTokenProvider, $c->getConfig(), $c->getSecureRandom(), $c->getLockdownManager());
349
-			$userSession->listen('\OC\User', 'preCreateUser', function ($uid, $password) {
350
-				\OC_Hook::emit('OC_User', 'pre_createUser', array('run' => true, 'uid' => $uid, 'password' => $password));
351
-			});
352
-			$userSession->listen('\OC\User', 'postCreateUser', function ($user, $password) {
353
-				/** @var $user \OC\User\User */
354
-				\OC_Hook::emit('OC_User', 'post_createUser', array('uid' => $user->getUID(), 'password' => $password));
355
-			});
356
-			$userSession->listen('\OC\User', 'preDelete', function ($user) {
357
-				/** @var $user \OC\User\User */
358
-				\OC_Hook::emit('OC_User', 'pre_deleteUser', array('run' => true, 'uid' => $user->getUID()));
359
-			});
360
-			$userSession->listen('\OC\User', 'postDelete', function ($user) {
361
-				/** @var $user \OC\User\User */
362
-				\OC_Hook::emit('OC_User', 'post_deleteUser', array('uid' => $user->getUID()));
363
-			});
364
-			$userSession->listen('\OC\User', 'preSetPassword', function ($user, $password, $recoveryPassword) {
365
-				/** @var $user \OC\User\User */
366
-				\OC_Hook::emit('OC_User', 'pre_setPassword', array('run' => true, 'uid' => $user->getUID(), 'password' => $password, 'recoveryPassword' => $recoveryPassword));
367
-			});
368
-			$userSession->listen('\OC\User', 'postSetPassword', function ($user, $password, $recoveryPassword) {
369
-				/** @var $user \OC\User\User */
370
-				\OC_Hook::emit('OC_User', 'post_setPassword', array('run' => true, 'uid' => $user->getUID(), 'password' => $password, 'recoveryPassword' => $recoveryPassword));
371
-			});
372
-			$userSession->listen('\OC\User', 'preLogin', function ($uid, $password) {
373
-				\OC_Hook::emit('OC_User', 'pre_login', array('run' => true, 'uid' => $uid, 'password' => $password));
374
-			});
375
-			$userSession->listen('\OC\User', 'postLogin', function ($user, $password) {
376
-				/** @var $user \OC\User\User */
377
-				\OC_Hook::emit('OC_User', 'post_login', array('run' => true, 'uid' => $user->getUID(), 'password' => $password));
378
-			});
379
-			$userSession->listen('\OC\User', 'postRememberedLogin', function ($user, $password) {
380
-				/** @var $user \OC\User\User */
381
-				\OC_Hook::emit('OC_User', 'post_login', array('run' => true, 'uid' => $user->getUID(), 'password' => $password));
382
-			});
383
-			$userSession->listen('\OC\User', 'logout', function () {
384
-				\OC_Hook::emit('OC_User', 'logout', array());
385
-			});
386
-			$userSession->listen('\OC\User', 'changeUser', function ($user, $feature, $value, $oldValue) {
387
-				/** @var $user \OC\User\User */
388
-				\OC_Hook::emit('OC_User', 'changeUser', array('run' => true, 'user' => $user, 'feature' => $feature, 'value' => $value, 'old_value' => $oldValue));
389
-			});
390
-			return $userSession;
391
-		});
392
-		$this->registerAlias('UserSession', \OCP\IUserSession::class);
393
-
394
-		$this->registerService(\OC\Authentication\TwoFactorAuth\Manager::class, function (Server $c) {
395
-			return new \OC\Authentication\TwoFactorAuth\Manager(
396
-				$c->getAppManager(),
397
-				$c->getSession(),
398
-				$c->getConfig(),
399
-				$c->getActivityManager(),
400
-				$c->getLogger(),
401
-				$c->query(\OC\Authentication\Token\IProvider::class),
402
-				$c->query(ITimeFactory::class)
403
-			);
404
-		});
405
-
406
-		$this->registerAlias(\OCP\INavigationManager::class, \OC\NavigationManager::class);
407
-		$this->registerAlias('NavigationManager', \OCP\INavigationManager::class);
408
-
409
-		$this->registerService(\OC\AllConfig::class, function (Server $c) {
410
-			return new \OC\AllConfig(
411
-				$c->getSystemConfig()
412
-			);
413
-		});
414
-		$this->registerAlias('AllConfig', \OC\AllConfig::class);
415
-		$this->registerAlias(\OCP\IConfig::class, \OC\AllConfig::class);
416
-
417
-		$this->registerService('SystemConfig', function ($c) use ($config) {
418
-			return new \OC\SystemConfig($config);
419
-		});
420
-
421
-		$this->registerService(\OC\AppConfig::class, function (Server $c) {
422
-			return new \OC\AppConfig($c->getDatabaseConnection());
423
-		});
424
-		$this->registerAlias('AppConfig', \OC\AppConfig::class);
425
-		$this->registerAlias(\OCP\IAppConfig::class, \OC\AppConfig::class);
426
-
427
-		$this->registerService(\OCP\L10N\IFactory::class, function (Server $c) {
428
-			return new \OC\L10N\Factory(
429
-				$c->getConfig(),
430
-				$c->getRequest(),
431
-				$c->getUserSession(),
432
-				\OC::$SERVERROOT
433
-			);
434
-		});
435
-		$this->registerAlias('L10NFactory', \OCP\L10N\IFactory::class);
436
-
437
-		$this->registerService(\OCP\IURLGenerator::class, function (Server $c) {
438
-			$config = $c->getConfig();
439
-			$cacheFactory = $c->getMemCacheFactory();
440
-			$request = $c->getRequest();
441
-			return new \OC\URLGenerator(
442
-				$config,
443
-				$cacheFactory,
444
-				$request
445
-			);
446
-		});
447
-		$this->registerAlias('URLGenerator', \OCP\IURLGenerator::class);
448
-
449
-		$this->registerService('AppHelper', function ($c) {
450
-			return new \OC\AppHelper();
451
-		});
452
-		$this->registerAlias('AppFetcher', AppFetcher::class);
453
-		$this->registerAlias('CategoryFetcher', CategoryFetcher::class);
454
-
455
-		$this->registerService(\OCP\ICache::class, function ($c) {
456
-			return new Cache\File();
457
-		});
458
-		$this->registerAlias('UserCache', \OCP\ICache::class);
459
-
460
-		$this->registerService(Factory::class, function (Server $c) {
461
-
462
-			$arrayCacheFactory = new \OC\Memcache\Factory('', $c->getLogger(),
463
-				'\\OC\\Memcache\\ArrayCache',
464
-				'\\OC\\Memcache\\ArrayCache',
465
-				'\\OC\\Memcache\\ArrayCache'
466
-			);
467
-			$config = $c->getConfig();
468
-			$request = $c->getRequest();
469
-			$urlGenerator = new URLGenerator($config, $arrayCacheFactory, $request);
470
-
471
-			if ($config->getSystemValue('installed', false) && !(defined('PHPUNIT_RUN') && PHPUNIT_RUN)) {
472
-				$v = \OC_App::getAppVersions();
473
-				$v['core'] = implode(',', \OC_Util::getVersion());
474
-				$version = implode(',', $v);
475
-				$instanceId = \OC_Util::getInstanceId();
476
-				$path = \OC::$SERVERROOT;
477
-				$prefix = md5($instanceId . '-' . $version . '-' . $path . '-' . $urlGenerator->getBaseUrl());
478
-				return new \OC\Memcache\Factory($prefix, $c->getLogger(),
479
-					$config->getSystemValue('memcache.local', null),
480
-					$config->getSystemValue('memcache.distributed', null),
481
-					$config->getSystemValue('memcache.locking', null)
482
-				);
483
-			}
484
-			return $arrayCacheFactory;
485
-
486
-		});
487
-		$this->registerAlias('MemCacheFactory', Factory::class);
488
-		$this->registerAlias(ICacheFactory::class, Factory::class);
489
-
490
-		$this->registerService('RedisFactory', function (Server $c) {
491
-			$systemConfig = $c->getSystemConfig();
492
-			return new RedisFactory($systemConfig);
493
-		});
494
-
495
-		$this->registerService(\OCP\Activity\IManager::class, function (Server $c) {
496
-			return new \OC\Activity\Manager(
497
-				$c->getRequest(),
498
-				$c->getUserSession(),
499
-				$c->getConfig(),
500
-				$c->query(IValidator::class)
501
-			);
502
-		});
503
-		$this->registerAlias('ActivityManager', \OCP\Activity\IManager::class);
504
-
505
-		$this->registerService(\OCP\Activity\IEventMerger::class, function (Server $c) {
506
-			return new \OC\Activity\EventMerger(
507
-				$c->getL10N('lib')
508
-			);
509
-		});
510
-		$this->registerAlias(IValidator::class, Validator::class);
511
-
512
-		$this->registerService(\OCP\IAvatarManager::class, function (Server $c) {
513
-			return new AvatarManager(
514
-				$c->getUserManager(),
515
-				$c->getAppDataDir('avatar'),
516
-				$c->getL10N('lib'),
517
-				$c->getLogger(),
518
-				$c->getConfig()
519
-			);
520
-		});
521
-		$this->registerAlias('AvatarManager', \OCP\IAvatarManager::class);
522
-
523
-		$this->registerAlias(\OCP\Support\CrashReport\IRegistry::class, \OC\Support\CrashReport\Registry::class);
524
-
525
-		$this->registerService(\OCP\ILogger::class, function (Server $c) {
526
-			$logType = $c->query('AllConfig')->getSystemValue('log_type', 'file');
527
-			$logger = Log::getLogClass($logType);
528
-			call_user_func(array($logger, 'init'));
529
-			$config = $this->getSystemConfig();
530
-			$registry = $c->query(\OCP\Support\CrashReport\IRegistry::class);
531
-
532
-			return new Log($logger, $config, null, $registry);
533
-		});
534
-		$this->registerAlias('Logger', \OCP\ILogger::class);
535
-
536
-		$this->registerService(\OCP\BackgroundJob\IJobList::class, function (Server $c) {
537
-			$config = $c->getConfig();
538
-			return new \OC\BackgroundJob\JobList(
539
-				$c->getDatabaseConnection(),
540
-				$config,
541
-				new TimeFactory()
542
-			);
543
-		});
544
-		$this->registerAlias('JobList', \OCP\BackgroundJob\IJobList::class);
545
-
546
-		$this->registerService(\OCP\Route\IRouter::class, function (Server $c) {
547
-			$cacheFactory = $c->getMemCacheFactory();
548
-			$logger = $c->getLogger();
549
-			if ($cacheFactory->isAvailableLowLatency()) {
550
-				$router = new \OC\Route\CachingRouter($cacheFactory->createLocal('route'), $logger);
551
-			} else {
552
-				$router = new \OC\Route\Router($logger);
553
-			}
554
-			return $router;
555
-		});
556
-		$this->registerAlias('Router', \OCP\Route\IRouter::class);
557
-
558
-		$this->registerService(\OCP\ISearch::class, function ($c) {
559
-			return new Search();
560
-		});
561
-		$this->registerAlias('Search', \OCP\ISearch::class);
562
-
563
-		$this->registerService(\OC\Security\RateLimiting\Limiter::class, function ($c) {
564
-			return new \OC\Security\RateLimiting\Limiter(
565
-				$this->getUserSession(),
566
-				$this->getRequest(),
567
-				new \OC\AppFramework\Utility\TimeFactory(),
568
-				$c->query(\OC\Security\RateLimiting\Backend\IBackend::class)
569
-			);
570
-		});
571
-		$this->registerService(\OC\Security\RateLimiting\Backend\IBackend::class, function ($c) {
572
-			return new \OC\Security\RateLimiting\Backend\MemoryCache(
573
-				$this->getMemCacheFactory(),
574
-				new \OC\AppFramework\Utility\TimeFactory()
575
-			);
576
-		});
577
-
578
-		$this->registerService(\OCP\Security\ISecureRandom::class, function ($c) {
579
-			return new SecureRandom();
580
-		});
581
-		$this->registerAlias('SecureRandom', \OCP\Security\ISecureRandom::class);
582
-
583
-		$this->registerService(\OCP\Security\ICrypto::class, function (Server $c) {
584
-			return new Crypto($c->getConfig(), $c->getSecureRandom());
585
-		});
586
-		$this->registerAlias('Crypto', \OCP\Security\ICrypto::class);
587
-
588
-		$this->registerService(\OCP\Security\IHasher::class, function (Server $c) {
589
-			return new Hasher($c->getConfig());
590
-		});
591
-		$this->registerAlias('Hasher', \OCP\Security\IHasher::class);
592
-
593
-		$this->registerService(\OCP\Security\ICredentialsManager::class, function (Server $c) {
594
-			return new CredentialsManager($c->getCrypto(), $c->getDatabaseConnection());
595
-		});
596
-		$this->registerAlias('CredentialsManager', \OCP\Security\ICredentialsManager::class);
597
-
598
-		$this->registerService(IDBConnection::class, function (Server $c) {
599
-			$systemConfig = $c->getSystemConfig();
600
-			$factory = new \OC\DB\ConnectionFactory($systemConfig);
601
-			$type = $systemConfig->getValue('dbtype', 'sqlite');
602
-			if (!$factory->isValidType($type)) {
603
-				throw new \OC\DatabaseException('Invalid database type');
604
-			}
605
-			$connectionParams = $factory->createConnectionParams();
606
-			$connection = $factory->getConnection($type, $connectionParams);
607
-			$connection->getConfiguration()->setSQLLogger($c->getQueryLogger());
608
-			return $connection;
609
-		});
610
-		$this->registerAlias('DatabaseConnection', IDBConnection::class);
611
-
612
-		$this->registerService('HTTPHelper', function (Server $c) {
613
-			$config = $c->getConfig();
614
-			return new HTTPHelper(
615
-				$config,
616
-				$c->getHTTPClientService()
617
-			);
618
-		});
619
-
620
-		$this->registerService(\OCP\Http\Client\IClientService::class, function (Server $c) {
621
-			$user = \OC_User::getUser();
622
-			$uid = $user ? $user : null;
623
-			return new ClientService(
624
-				$c->getConfig(),
625
-				new \OC\Security\CertificateManager(
626
-					$uid,
627
-					new View(),
628
-					$c->getConfig(),
629
-					$c->getLogger(),
630
-					$c->getSecureRandom()
631
-				)
632
-			);
633
-		});
634
-		$this->registerAlias('HttpClientService', \OCP\Http\Client\IClientService::class);
635
-		$this->registerService(\OCP\Diagnostics\IEventLogger::class, function (Server $c) {
636
-			$eventLogger = new EventLogger();
637
-			if ($c->getSystemConfig()->getValue('debug', false)) {
638
-				// In debug mode, module is being activated by default
639
-				$eventLogger->activate();
640
-			}
641
-			return $eventLogger;
642
-		});
643
-		$this->registerAlias('EventLogger', \OCP\Diagnostics\IEventLogger::class);
644
-
645
-		$this->registerService(\OCP\Diagnostics\IQueryLogger::class, function (Server $c) {
646
-			$queryLogger = new QueryLogger();
647
-			if ($c->getSystemConfig()->getValue('debug', false)) {
648
-				// In debug mode, module is being activated by default
649
-				$queryLogger->activate();
650
-			}
651
-			return $queryLogger;
652
-		});
653
-		$this->registerAlias('QueryLogger', \OCP\Diagnostics\IQueryLogger::class);
654
-
655
-		$this->registerService(TempManager::class, function (Server $c) {
656
-			return new TempManager(
657
-				$c->getLogger(),
658
-				$c->getConfig()
659
-			);
660
-		});
661
-		$this->registerAlias('TempManager', TempManager::class);
662
-		$this->registerAlias(ITempManager::class, TempManager::class);
663
-
664
-		$this->registerService(AppManager::class, function (Server $c) {
665
-			return new \OC\App\AppManager(
666
-				$c->getUserSession(),
667
-				$c->getAppConfig(),
668
-				$c->getGroupManager(),
669
-				$c->getMemCacheFactory(),
670
-				$c->getEventDispatcher()
671
-			);
672
-		});
673
-		$this->registerAlias('AppManager', AppManager::class);
674
-		$this->registerAlias(IAppManager::class, AppManager::class);
675
-
676
-		$this->registerService(\OCP\IDateTimeZone::class, function (Server $c) {
677
-			return new DateTimeZone(
678
-				$c->getConfig(),
679
-				$c->getSession()
680
-			);
681
-		});
682
-		$this->registerAlias('DateTimeZone', \OCP\IDateTimeZone::class);
683
-
684
-		$this->registerService(\OCP\IDateTimeFormatter::class, function (Server $c) {
685
-			$language = $c->getConfig()->getUserValue($c->getSession()->get('user_id'), 'core', 'lang', null);
686
-
687
-			return new DateTimeFormatter(
688
-				$c->getDateTimeZone()->getTimeZone(),
689
-				$c->getL10N('lib', $language)
690
-			);
691
-		});
692
-		$this->registerAlias('DateTimeFormatter', \OCP\IDateTimeFormatter::class);
693
-
694
-		$this->registerService(\OCP\Files\Config\IUserMountCache::class, function (Server $c) {
695
-			$mountCache = new UserMountCache($c->getDatabaseConnection(), $c->getUserManager(), $c->getLogger());
696
-			$listener = new UserMountCacheListener($mountCache);
697
-			$listener->listen($c->getUserManager());
698
-			return $mountCache;
699
-		});
700
-		$this->registerAlias('UserMountCache', \OCP\Files\Config\IUserMountCache::class);
701
-
702
-		$this->registerService(\OCP\Files\Config\IMountProviderCollection::class, function (Server $c) {
703
-			$loader = \OC\Files\Filesystem::getLoader();
704
-			$mountCache = $c->query('UserMountCache');
705
-			$manager = new \OC\Files\Config\MountProviderCollection($loader, $mountCache);
706
-
707
-			// builtin providers
708
-
709
-			$config = $c->getConfig();
710
-			$manager->registerProvider(new CacheMountProvider($config));
711
-			$manager->registerHomeProvider(new LocalHomeMountProvider());
712
-			$manager->registerHomeProvider(new ObjectHomeMountProvider($config));
713
-
714
-			return $manager;
715
-		});
716
-		$this->registerAlias('MountConfigManager', \OCP\Files\Config\IMountProviderCollection::class);
717
-
718
-		$this->registerService('IniWrapper', function ($c) {
719
-			return new IniGetWrapper();
720
-		});
721
-		$this->registerService('AsyncCommandBus', function (Server $c) {
722
-			$busClass = $c->getConfig()->getSystemValue('commandbus');
723
-			if ($busClass) {
724
-				list($app, $class) = explode('::', $busClass, 2);
725
-				if ($c->getAppManager()->isInstalled($app)) {
726
-					\OC_App::loadApp($app);
727
-					return $c->query($class);
728
-				} else {
729
-					throw new ServiceUnavailableException("The app providing the command bus ($app) is not enabled");
730
-				}
731
-			} else {
732
-				$jobList = $c->getJobList();
733
-				return new CronBus($jobList);
734
-			}
735
-		});
736
-		$this->registerService('TrustedDomainHelper', function ($c) {
737
-			return new TrustedDomainHelper($this->getConfig());
738
-		});
739
-		$this->registerService('Throttler', function (Server $c) {
740
-			return new Throttler(
741
-				$c->getDatabaseConnection(),
742
-				new TimeFactory(),
743
-				$c->getLogger(),
744
-				$c->getConfig()
745
-			);
746
-		});
747
-		$this->registerService('IntegrityCodeChecker', function (Server $c) {
748
-			// IConfig and IAppManager requires a working database. This code
749
-			// might however be called when ownCloud is not yet setup.
750
-			if (\OC::$server->getSystemConfig()->getValue('installed', false)) {
751
-				$config = $c->getConfig();
752
-				$appManager = $c->getAppManager();
753
-			} else {
754
-				$config = null;
755
-				$appManager = null;
756
-			}
757
-
758
-			return new Checker(
759
-				new EnvironmentHelper(),
760
-				new FileAccessHelper(),
761
-				new AppLocator(),
762
-				$config,
763
-				$c->getMemCacheFactory(),
764
-				$appManager,
765
-				$c->getTempManager()
766
-			);
767
-		});
768
-		$this->registerService(\OCP\IRequest::class, function ($c) {
769
-			if (isset($this['urlParams'])) {
770
-				$urlParams = $this['urlParams'];
771
-			} else {
772
-				$urlParams = [];
773
-			}
774
-
775
-			if (defined('PHPUNIT_RUN') && PHPUNIT_RUN
776
-				&& in_array('fakeinput', stream_get_wrappers())
777
-			) {
778
-				$stream = 'fakeinput://data';
779
-			} else {
780
-				$stream = 'php://input';
781
-			}
782
-
783
-			return new Request(
784
-				[
785
-					'get' => $_GET,
786
-					'post' => $_POST,
787
-					'files' => $_FILES,
788
-					'server' => $_SERVER,
789
-					'env' => $_ENV,
790
-					'cookies' => $_COOKIE,
791
-					'method' => (isset($_SERVER) && isset($_SERVER['REQUEST_METHOD']))
792
-						? $_SERVER['REQUEST_METHOD']
793
-						: null,
794
-					'urlParams' => $urlParams,
795
-				],
796
-				$this->getSecureRandom(),
797
-				$this->getConfig(),
798
-				$this->getCsrfTokenManager(),
799
-				$stream
800
-			);
801
-		});
802
-		$this->registerAlias('Request', \OCP\IRequest::class);
803
-
804
-		$this->registerService(\OCP\Mail\IMailer::class, function (Server $c) {
805
-			return new Mailer(
806
-				$c->getConfig(),
807
-				$c->getLogger(),
808
-				$c->query(Defaults::class),
809
-				$c->getURLGenerator(),
810
-				$c->getL10N('lib')
811
-			);
812
-		});
813
-		$this->registerAlias('Mailer', \OCP\Mail\IMailer::class);
814
-
815
-		$this->registerService('LDAPProvider', function (Server $c) {
816
-			$config = $c->getConfig();
817
-			$factoryClass = $config->getSystemValue('ldapProviderFactory', null);
818
-			if (is_null($factoryClass)) {
819
-				throw new \Exception('ldapProviderFactory not set');
820
-			}
821
-			/** @var \OCP\LDAP\ILDAPProviderFactory $factory */
822
-			$factory = new $factoryClass($this);
823
-			return $factory->getLDAPProvider();
824
-		});
825
-		$this->registerService(ILockingProvider::class, function (Server $c) {
826
-			$ini = $c->getIniWrapper();
827
-			$config = $c->getConfig();
828
-			$ttl = $config->getSystemValue('filelocking.ttl', max(3600, $ini->getNumeric('max_execution_time')));
829
-			if ($config->getSystemValue('filelocking.enabled', true) or (defined('PHPUNIT_RUN') && PHPUNIT_RUN)) {
830
-				/** @var \OC\Memcache\Factory $memcacheFactory */
831
-				$memcacheFactory = $c->getMemCacheFactory();
832
-				$memcache = $memcacheFactory->createLocking('lock');
833
-				if (!($memcache instanceof \OC\Memcache\NullCache)) {
834
-					return new MemcacheLockingProvider($memcache, $ttl);
835
-				}
836
-				return new DBLockingProvider($c->getDatabaseConnection(), $c->getLogger(), new TimeFactory(), $ttl);
837
-			}
838
-			return new NoopLockingProvider();
839
-		});
840
-		$this->registerAlias('LockingProvider', ILockingProvider::class);
841
-
842
-		$this->registerService(\OCP\Files\Mount\IMountManager::class, function () {
843
-			return new \OC\Files\Mount\Manager();
844
-		});
845
-		$this->registerAlias('MountManager', \OCP\Files\Mount\IMountManager::class);
846
-
847
-		$this->registerService(\OCP\Files\IMimeTypeDetector::class, function (Server $c) {
848
-			return new \OC\Files\Type\Detection(
849
-				$c->getURLGenerator(),
850
-				\OC::$configDir,
851
-				\OC::$SERVERROOT . '/resources/config/'
852
-			);
853
-		});
854
-		$this->registerAlias('MimeTypeDetector', \OCP\Files\IMimeTypeDetector::class);
855
-
856
-		$this->registerService(\OCP\Files\IMimeTypeLoader::class, function (Server $c) {
857
-			return new \OC\Files\Type\Loader(
858
-				$c->getDatabaseConnection()
859
-			);
860
-		});
861
-		$this->registerAlias('MimeTypeLoader', \OCP\Files\IMimeTypeLoader::class);
862
-		$this->registerService(BundleFetcher::class, function () {
863
-			return new BundleFetcher($this->getL10N('lib'));
864
-		});
865
-		$this->registerService(\OCP\Notification\IManager::class, function (Server $c) {
866
-			return new Manager(
867
-				$c->query(IValidator::class)
868
-			);
869
-		});
870
-		$this->registerAlias('NotificationManager', \OCP\Notification\IManager::class);
871
-
872
-		$this->registerService(\OC\CapabilitiesManager::class, function (Server $c) {
873
-			$manager = new \OC\CapabilitiesManager($c->getLogger());
874
-			$manager->registerCapability(function () use ($c) {
875
-				return new \OC\OCS\CoreCapabilities($c->getConfig());
876
-			});
877
-			$manager->registerCapability(function () use ($c) {
878
-				return $c->query(\OC\Security\Bruteforce\Capabilities::class);
879
-			});
880
-			return $manager;
881
-		});
882
-		$this->registerAlias('CapabilitiesManager', \OC\CapabilitiesManager::class);
883
-
884
-		$this->registerService(\OCP\Comments\ICommentsManager::class, function (Server $c) {
885
-			$config = $c->getConfig();
886
-			$factoryClass = $config->getSystemValue('comments.managerFactory', '\OC\Comments\ManagerFactory');
887
-			/** @var \OCP\Comments\ICommentsManagerFactory $factory */
888
-			$factory = new $factoryClass($this);
889
-			return $factory->getManager();
890
-		});
891
-		$this->registerAlias('CommentsManager', \OCP\Comments\ICommentsManager::class);
892
-
893
-		$this->registerService('ThemingDefaults', function (Server $c) {
894
-			/*
142
+    /** @var string */
143
+    private $webRoot;
144
+
145
+    /**
146
+     * @param string $webRoot
147
+     * @param \OC\Config $config
148
+     */
149
+    public function __construct($webRoot, \OC\Config $config) {
150
+        parent::__construct();
151
+        $this->webRoot = $webRoot;
152
+
153
+        $this->registerService(\OCP\IServerContainer::class, function (IServerContainer $c) {
154
+            return $c;
155
+        });
156
+
157
+        $this->registerAlias(\OCP\Calendar\IManager::class, \OC\Calendar\Manager::class);
158
+        $this->registerAlias('CalendarManager', \OC\Calendar\Manager::class);
159
+
160
+        $this->registerAlias(\OCP\Contacts\IManager::class, \OC\ContactsManager::class);
161
+        $this->registerAlias('ContactsManager', \OCP\Contacts\IManager::class);
162
+
163
+        $this->registerAlias(IActionFactory::class, ActionFactory::class);
164
+
165
+
166
+        $this->registerService(\OCP\IPreview::class, function (Server $c) {
167
+            return new PreviewManager(
168
+                $c->getConfig(),
169
+                $c->getRootFolder(),
170
+                $c->getAppDataDir('preview'),
171
+                $c->getEventDispatcher(),
172
+                $c->getSession()->get('user_id')
173
+            );
174
+        });
175
+        $this->registerAlias('PreviewManager', \OCP\IPreview::class);
176
+
177
+        $this->registerService(\OC\Preview\Watcher::class, function (Server $c) {
178
+            return new \OC\Preview\Watcher(
179
+                $c->getAppDataDir('preview')
180
+            );
181
+        });
182
+
183
+        $this->registerService('EncryptionManager', function (Server $c) {
184
+            $view = new View();
185
+            $util = new Encryption\Util(
186
+                $view,
187
+                $c->getUserManager(),
188
+                $c->getGroupManager(),
189
+                $c->getConfig()
190
+            );
191
+            return new Encryption\Manager(
192
+                $c->getConfig(),
193
+                $c->getLogger(),
194
+                $c->getL10N('core'),
195
+                new View(),
196
+                $util,
197
+                new ArrayCache()
198
+            );
199
+        });
200
+
201
+        $this->registerService('EncryptionFileHelper', function (Server $c) {
202
+            $util = new Encryption\Util(
203
+                new View(),
204
+                $c->getUserManager(),
205
+                $c->getGroupManager(),
206
+                $c->getConfig()
207
+            );
208
+            return new Encryption\File(
209
+                $util,
210
+                $c->getRootFolder(),
211
+                $c->getShareManager()
212
+            );
213
+        });
214
+
215
+        $this->registerService('EncryptionKeyStorage', function (Server $c) {
216
+            $view = new View();
217
+            $util = new Encryption\Util(
218
+                $view,
219
+                $c->getUserManager(),
220
+                $c->getGroupManager(),
221
+                $c->getConfig()
222
+            );
223
+
224
+            return new Encryption\Keys\Storage($view, $util);
225
+        });
226
+        $this->registerService('TagMapper', function (Server $c) {
227
+            return new TagMapper($c->getDatabaseConnection());
228
+        });
229
+
230
+        $this->registerService(\OCP\ITagManager::class, function (Server $c) {
231
+            $tagMapper = $c->query('TagMapper');
232
+            return new TagManager($tagMapper, $c->getUserSession());
233
+        });
234
+        $this->registerAlias('TagManager', \OCP\ITagManager::class);
235
+
236
+        $this->registerService('SystemTagManagerFactory', function (Server $c) {
237
+            $config = $c->getConfig();
238
+            $factoryClass = $config->getSystemValue('systemtags.managerFactory', '\OC\SystemTag\ManagerFactory');
239
+            /** @var \OC\SystemTag\ManagerFactory $factory */
240
+            $factory = new $factoryClass($this);
241
+            return $factory;
242
+        });
243
+        $this->registerService(\OCP\SystemTag\ISystemTagManager::class, function (Server $c) {
244
+            return $c->query('SystemTagManagerFactory')->getManager();
245
+        });
246
+        $this->registerAlias('SystemTagManager', \OCP\SystemTag\ISystemTagManager::class);
247
+
248
+        $this->registerService(\OCP\SystemTag\ISystemTagObjectMapper::class, function (Server $c) {
249
+            return $c->query('SystemTagManagerFactory')->getObjectMapper();
250
+        });
251
+        $this->registerService('RootFolder', function (Server $c) {
252
+            $manager = \OC\Files\Filesystem::getMountManager(null);
253
+            $view = new View();
254
+            $root = new Root(
255
+                $manager,
256
+                $view,
257
+                null,
258
+                $c->getUserMountCache(),
259
+                $this->getLogger(),
260
+                $this->getUserManager()
261
+            );
262
+            $connector = new HookConnector($root, $view);
263
+            $connector->viewToNode();
264
+
265
+            $previewConnector = new \OC\Preview\WatcherConnector($root, $c->getSystemConfig());
266
+            $previewConnector->connectWatcher();
267
+
268
+            return $root;
269
+        });
270
+        $this->registerAlias('SystemTagObjectMapper', \OCP\SystemTag\ISystemTagObjectMapper::class);
271
+
272
+        $this->registerService(\OCP\Files\IRootFolder::class, function (Server $c) {
273
+            return new LazyRoot(function () use ($c) {
274
+                return $c->query('RootFolder');
275
+            });
276
+        });
277
+        $this->registerAlias('LazyRootFolder', \OCP\Files\IRootFolder::class);
278
+
279
+        $this->registerService(\OCP\IUserManager::class, function (Server $c) {
280
+            $config = $c->getConfig();
281
+            return new \OC\User\Manager($config);
282
+        });
283
+        $this->registerAlias('UserManager', \OCP\IUserManager::class);
284
+
285
+        $this->registerService(\OCP\IGroupManager::class, function (Server $c) {
286
+            $groupManager = new \OC\Group\Manager($this->getUserManager(), $this->getLogger());
287
+            $groupManager->listen('\OC\Group', 'preCreate', function ($gid) {
288
+                \OC_Hook::emit('OC_Group', 'pre_createGroup', array('run' => true, 'gid' => $gid));
289
+            });
290
+            $groupManager->listen('\OC\Group', 'postCreate', function (\OC\Group\Group $gid) {
291
+                \OC_Hook::emit('OC_User', 'post_createGroup', array('gid' => $gid->getGID()));
292
+            });
293
+            $groupManager->listen('\OC\Group', 'preDelete', function (\OC\Group\Group $group) {
294
+                \OC_Hook::emit('OC_Group', 'pre_deleteGroup', array('run' => true, 'gid' => $group->getGID()));
295
+            });
296
+            $groupManager->listen('\OC\Group', 'postDelete', function (\OC\Group\Group $group) {
297
+                \OC_Hook::emit('OC_User', 'post_deleteGroup', array('gid' => $group->getGID()));
298
+            });
299
+            $groupManager->listen('\OC\Group', 'preAddUser', function (\OC\Group\Group $group, \OC\User\User $user) {
300
+                \OC_Hook::emit('OC_Group', 'pre_addToGroup', array('run' => true, 'uid' => $user->getUID(), 'gid' => $group->getGID()));
301
+            });
302
+            $groupManager->listen('\OC\Group', 'postAddUser', function (\OC\Group\Group $group, \OC\User\User $user) {
303
+                \OC_Hook::emit('OC_Group', 'post_addToGroup', array('uid' => $user->getUID(), 'gid' => $group->getGID()));
304
+                //Minimal fix to keep it backward compatible TODO: clean up all the GroupManager hooks
305
+                \OC_Hook::emit('OC_User', 'post_addToGroup', array('uid' => $user->getUID(), 'gid' => $group->getGID()));
306
+            });
307
+            return $groupManager;
308
+        });
309
+        $this->registerAlias('GroupManager', \OCP\IGroupManager::class);
310
+
311
+        $this->registerService(Store::class, function (Server $c) {
312
+            $session = $c->getSession();
313
+            if (\OC::$server->getSystemConfig()->getValue('installed', false)) {
314
+                $tokenProvider = $c->query('OC\Authentication\Token\IProvider');
315
+            } else {
316
+                $tokenProvider = null;
317
+            }
318
+            $logger = $c->getLogger();
319
+            return new Store($session, $logger, $tokenProvider);
320
+        });
321
+        $this->registerAlias(IStore::class, Store::class);
322
+        $this->registerService('OC\Authentication\Token\DefaultTokenMapper', function (Server $c) {
323
+            $dbConnection = $c->getDatabaseConnection();
324
+            return new Authentication\Token\DefaultTokenMapper($dbConnection);
325
+        });
326
+        $this->registerService('OC\Authentication\Token\DefaultTokenProvider', function (Server $c) {
327
+            $mapper = $c->query('OC\Authentication\Token\DefaultTokenMapper');
328
+            $crypto = $c->getCrypto();
329
+            $config = $c->getConfig();
330
+            $logger = $c->getLogger();
331
+            $timeFactory = new TimeFactory();
332
+            return new \OC\Authentication\Token\DefaultTokenProvider($mapper, $crypto, $config, $logger, $timeFactory);
333
+        });
334
+        $this->registerAlias('OC\Authentication\Token\IProvider', 'OC\Authentication\Token\DefaultTokenProvider');
335
+
336
+        $this->registerService(\OCP\IUserSession::class, function (Server $c) {
337
+            $manager = $c->getUserManager();
338
+            $session = new \OC\Session\Memory('');
339
+            $timeFactory = new TimeFactory();
340
+            // Token providers might require a working database. This code
341
+            // might however be called when ownCloud is not yet setup.
342
+            if (\OC::$server->getSystemConfig()->getValue('installed', false)) {
343
+                $defaultTokenProvider = $c->query('OC\Authentication\Token\IProvider');
344
+            } else {
345
+                $defaultTokenProvider = null;
346
+            }
347
+
348
+            $userSession = new \OC\User\Session($manager, $session, $timeFactory, $defaultTokenProvider, $c->getConfig(), $c->getSecureRandom(), $c->getLockdownManager());
349
+            $userSession->listen('\OC\User', 'preCreateUser', function ($uid, $password) {
350
+                \OC_Hook::emit('OC_User', 'pre_createUser', array('run' => true, 'uid' => $uid, 'password' => $password));
351
+            });
352
+            $userSession->listen('\OC\User', 'postCreateUser', function ($user, $password) {
353
+                /** @var $user \OC\User\User */
354
+                \OC_Hook::emit('OC_User', 'post_createUser', array('uid' => $user->getUID(), 'password' => $password));
355
+            });
356
+            $userSession->listen('\OC\User', 'preDelete', function ($user) {
357
+                /** @var $user \OC\User\User */
358
+                \OC_Hook::emit('OC_User', 'pre_deleteUser', array('run' => true, 'uid' => $user->getUID()));
359
+            });
360
+            $userSession->listen('\OC\User', 'postDelete', function ($user) {
361
+                /** @var $user \OC\User\User */
362
+                \OC_Hook::emit('OC_User', 'post_deleteUser', array('uid' => $user->getUID()));
363
+            });
364
+            $userSession->listen('\OC\User', 'preSetPassword', function ($user, $password, $recoveryPassword) {
365
+                /** @var $user \OC\User\User */
366
+                \OC_Hook::emit('OC_User', 'pre_setPassword', array('run' => true, 'uid' => $user->getUID(), 'password' => $password, 'recoveryPassword' => $recoveryPassword));
367
+            });
368
+            $userSession->listen('\OC\User', 'postSetPassword', function ($user, $password, $recoveryPassword) {
369
+                /** @var $user \OC\User\User */
370
+                \OC_Hook::emit('OC_User', 'post_setPassword', array('run' => true, 'uid' => $user->getUID(), 'password' => $password, 'recoveryPassword' => $recoveryPassword));
371
+            });
372
+            $userSession->listen('\OC\User', 'preLogin', function ($uid, $password) {
373
+                \OC_Hook::emit('OC_User', 'pre_login', array('run' => true, 'uid' => $uid, 'password' => $password));
374
+            });
375
+            $userSession->listen('\OC\User', 'postLogin', function ($user, $password) {
376
+                /** @var $user \OC\User\User */
377
+                \OC_Hook::emit('OC_User', 'post_login', array('run' => true, 'uid' => $user->getUID(), 'password' => $password));
378
+            });
379
+            $userSession->listen('\OC\User', 'postRememberedLogin', function ($user, $password) {
380
+                /** @var $user \OC\User\User */
381
+                \OC_Hook::emit('OC_User', 'post_login', array('run' => true, 'uid' => $user->getUID(), 'password' => $password));
382
+            });
383
+            $userSession->listen('\OC\User', 'logout', function () {
384
+                \OC_Hook::emit('OC_User', 'logout', array());
385
+            });
386
+            $userSession->listen('\OC\User', 'changeUser', function ($user, $feature, $value, $oldValue) {
387
+                /** @var $user \OC\User\User */
388
+                \OC_Hook::emit('OC_User', 'changeUser', array('run' => true, 'user' => $user, 'feature' => $feature, 'value' => $value, 'old_value' => $oldValue));
389
+            });
390
+            return $userSession;
391
+        });
392
+        $this->registerAlias('UserSession', \OCP\IUserSession::class);
393
+
394
+        $this->registerService(\OC\Authentication\TwoFactorAuth\Manager::class, function (Server $c) {
395
+            return new \OC\Authentication\TwoFactorAuth\Manager(
396
+                $c->getAppManager(),
397
+                $c->getSession(),
398
+                $c->getConfig(),
399
+                $c->getActivityManager(),
400
+                $c->getLogger(),
401
+                $c->query(\OC\Authentication\Token\IProvider::class),
402
+                $c->query(ITimeFactory::class)
403
+            );
404
+        });
405
+
406
+        $this->registerAlias(\OCP\INavigationManager::class, \OC\NavigationManager::class);
407
+        $this->registerAlias('NavigationManager', \OCP\INavigationManager::class);
408
+
409
+        $this->registerService(\OC\AllConfig::class, function (Server $c) {
410
+            return new \OC\AllConfig(
411
+                $c->getSystemConfig()
412
+            );
413
+        });
414
+        $this->registerAlias('AllConfig', \OC\AllConfig::class);
415
+        $this->registerAlias(\OCP\IConfig::class, \OC\AllConfig::class);
416
+
417
+        $this->registerService('SystemConfig', function ($c) use ($config) {
418
+            return new \OC\SystemConfig($config);
419
+        });
420
+
421
+        $this->registerService(\OC\AppConfig::class, function (Server $c) {
422
+            return new \OC\AppConfig($c->getDatabaseConnection());
423
+        });
424
+        $this->registerAlias('AppConfig', \OC\AppConfig::class);
425
+        $this->registerAlias(\OCP\IAppConfig::class, \OC\AppConfig::class);
426
+
427
+        $this->registerService(\OCP\L10N\IFactory::class, function (Server $c) {
428
+            return new \OC\L10N\Factory(
429
+                $c->getConfig(),
430
+                $c->getRequest(),
431
+                $c->getUserSession(),
432
+                \OC::$SERVERROOT
433
+            );
434
+        });
435
+        $this->registerAlias('L10NFactory', \OCP\L10N\IFactory::class);
436
+
437
+        $this->registerService(\OCP\IURLGenerator::class, function (Server $c) {
438
+            $config = $c->getConfig();
439
+            $cacheFactory = $c->getMemCacheFactory();
440
+            $request = $c->getRequest();
441
+            return new \OC\URLGenerator(
442
+                $config,
443
+                $cacheFactory,
444
+                $request
445
+            );
446
+        });
447
+        $this->registerAlias('URLGenerator', \OCP\IURLGenerator::class);
448
+
449
+        $this->registerService('AppHelper', function ($c) {
450
+            return new \OC\AppHelper();
451
+        });
452
+        $this->registerAlias('AppFetcher', AppFetcher::class);
453
+        $this->registerAlias('CategoryFetcher', CategoryFetcher::class);
454
+
455
+        $this->registerService(\OCP\ICache::class, function ($c) {
456
+            return new Cache\File();
457
+        });
458
+        $this->registerAlias('UserCache', \OCP\ICache::class);
459
+
460
+        $this->registerService(Factory::class, function (Server $c) {
461
+
462
+            $arrayCacheFactory = new \OC\Memcache\Factory('', $c->getLogger(),
463
+                '\\OC\\Memcache\\ArrayCache',
464
+                '\\OC\\Memcache\\ArrayCache',
465
+                '\\OC\\Memcache\\ArrayCache'
466
+            );
467
+            $config = $c->getConfig();
468
+            $request = $c->getRequest();
469
+            $urlGenerator = new URLGenerator($config, $arrayCacheFactory, $request);
470
+
471
+            if ($config->getSystemValue('installed', false) && !(defined('PHPUNIT_RUN') && PHPUNIT_RUN)) {
472
+                $v = \OC_App::getAppVersions();
473
+                $v['core'] = implode(',', \OC_Util::getVersion());
474
+                $version = implode(',', $v);
475
+                $instanceId = \OC_Util::getInstanceId();
476
+                $path = \OC::$SERVERROOT;
477
+                $prefix = md5($instanceId . '-' . $version . '-' . $path . '-' . $urlGenerator->getBaseUrl());
478
+                return new \OC\Memcache\Factory($prefix, $c->getLogger(),
479
+                    $config->getSystemValue('memcache.local', null),
480
+                    $config->getSystemValue('memcache.distributed', null),
481
+                    $config->getSystemValue('memcache.locking', null)
482
+                );
483
+            }
484
+            return $arrayCacheFactory;
485
+
486
+        });
487
+        $this->registerAlias('MemCacheFactory', Factory::class);
488
+        $this->registerAlias(ICacheFactory::class, Factory::class);
489
+
490
+        $this->registerService('RedisFactory', function (Server $c) {
491
+            $systemConfig = $c->getSystemConfig();
492
+            return new RedisFactory($systemConfig);
493
+        });
494
+
495
+        $this->registerService(\OCP\Activity\IManager::class, function (Server $c) {
496
+            return new \OC\Activity\Manager(
497
+                $c->getRequest(),
498
+                $c->getUserSession(),
499
+                $c->getConfig(),
500
+                $c->query(IValidator::class)
501
+            );
502
+        });
503
+        $this->registerAlias('ActivityManager', \OCP\Activity\IManager::class);
504
+
505
+        $this->registerService(\OCP\Activity\IEventMerger::class, function (Server $c) {
506
+            return new \OC\Activity\EventMerger(
507
+                $c->getL10N('lib')
508
+            );
509
+        });
510
+        $this->registerAlias(IValidator::class, Validator::class);
511
+
512
+        $this->registerService(\OCP\IAvatarManager::class, function (Server $c) {
513
+            return new AvatarManager(
514
+                $c->getUserManager(),
515
+                $c->getAppDataDir('avatar'),
516
+                $c->getL10N('lib'),
517
+                $c->getLogger(),
518
+                $c->getConfig()
519
+            );
520
+        });
521
+        $this->registerAlias('AvatarManager', \OCP\IAvatarManager::class);
522
+
523
+        $this->registerAlias(\OCP\Support\CrashReport\IRegistry::class, \OC\Support\CrashReport\Registry::class);
524
+
525
+        $this->registerService(\OCP\ILogger::class, function (Server $c) {
526
+            $logType = $c->query('AllConfig')->getSystemValue('log_type', 'file');
527
+            $logger = Log::getLogClass($logType);
528
+            call_user_func(array($logger, 'init'));
529
+            $config = $this->getSystemConfig();
530
+            $registry = $c->query(\OCP\Support\CrashReport\IRegistry::class);
531
+
532
+            return new Log($logger, $config, null, $registry);
533
+        });
534
+        $this->registerAlias('Logger', \OCP\ILogger::class);
535
+
536
+        $this->registerService(\OCP\BackgroundJob\IJobList::class, function (Server $c) {
537
+            $config = $c->getConfig();
538
+            return new \OC\BackgroundJob\JobList(
539
+                $c->getDatabaseConnection(),
540
+                $config,
541
+                new TimeFactory()
542
+            );
543
+        });
544
+        $this->registerAlias('JobList', \OCP\BackgroundJob\IJobList::class);
545
+
546
+        $this->registerService(\OCP\Route\IRouter::class, function (Server $c) {
547
+            $cacheFactory = $c->getMemCacheFactory();
548
+            $logger = $c->getLogger();
549
+            if ($cacheFactory->isAvailableLowLatency()) {
550
+                $router = new \OC\Route\CachingRouter($cacheFactory->createLocal('route'), $logger);
551
+            } else {
552
+                $router = new \OC\Route\Router($logger);
553
+            }
554
+            return $router;
555
+        });
556
+        $this->registerAlias('Router', \OCP\Route\IRouter::class);
557
+
558
+        $this->registerService(\OCP\ISearch::class, function ($c) {
559
+            return new Search();
560
+        });
561
+        $this->registerAlias('Search', \OCP\ISearch::class);
562
+
563
+        $this->registerService(\OC\Security\RateLimiting\Limiter::class, function ($c) {
564
+            return new \OC\Security\RateLimiting\Limiter(
565
+                $this->getUserSession(),
566
+                $this->getRequest(),
567
+                new \OC\AppFramework\Utility\TimeFactory(),
568
+                $c->query(\OC\Security\RateLimiting\Backend\IBackend::class)
569
+            );
570
+        });
571
+        $this->registerService(\OC\Security\RateLimiting\Backend\IBackend::class, function ($c) {
572
+            return new \OC\Security\RateLimiting\Backend\MemoryCache(
573
+                $this->getMemCacheFactory(),
574
+                new \OC\AppFramework\Utility\TimeFactory()
575
+            );
576
+        });
577
+
578
+        $this->registerService(\OCP\Security\ISecureRandom::class, function ($c) {
579
+            return new SecureRandom();
580
+        });
581
+        $this->registerAlias('SecureRandom', \OCP\Security\ISecureRandom::class);
582
+
583
+        $this->registerService(\OCP\Security\ICrypto::class, function (Server $c) {
584
+            return new Crypto($c->getConfig(), $c->getSecureRandom());
585
+        });
586
+        $this->registerAlias('Crypto', \OCP\Security\ICrypto::class);
587
+
588
+        $this->registerService(\OCP\Security\IHasher::class, function (Server $c) {
589
+            return new Hasher($c->getConfig());
590
+        });
591
+        $this->registerAlias('Hasher', \OCP\Security\IHasher::class);
592
+
593
+        $this->registerService(\OCP\Security\ICredentialsManager::class, function (Server $c) {
594
+            return new CredentialsManager($c->getCrypto(), $c->getDatabaseConnection());
595
+        });
596
+        $this->registerAlias('CredentialsManager', \OCP\Security\ICredentialsManager::class);
597
+
598
+        $this->registerService(IDBConnection::class, function (Server $c) {
599
+            $systemConfig = $c->getSystemConfig();
600
+            $factory = new \OC\DB\ConnectionFactory($systemConfig);
601
+            $type = $systemConfig->getValue('dbtype', 'sqlite');
602
+            if (!$factory->isValidType($type)) {
603
+                throw new \OC\DatabaseException('Invalid database type');
604
+            }
605
+            $connectionParams = $factory->createConnectionParams();
606
+            $connection = $factory->getConnection($type, $connectionParams);
607
+            $connection->getConfiguration()->setSQLLogger($c->getQueryLogger());
608
+            return $connection;
609
+        });
610
+        $this->registerAlias('DatabaseConnection', IDBConnection::class);
611
+
612
+        $this->registerService('HTTPHelper', function (Server $c) {
613
+            $config = $c->getConfig();
614
+            return new HTTPHelper(
615
+                $config,
616
+                $c->getHTTPClientService()
617
+            );
618
+        });
619
+
620
+        $this->registerService(\OCP\Http\Client\IClientService::class, function (Server $c) {
621
+            $user = \OC_User::getUser();
622
+            $uid = $user ? $user : null;
623
+            return new ClientService(
624
+                $c->getConfig(),
625
+                new \OC\Security\CertificateManager(
626
+                    $uid,
627
+                    new View(),
628
+                    $c->getConfig(),
629
+                    $c->getLogger(),
630
+                    $c->getSecureRandom()
631
+                )
632
+            );
633
+        });
634
+        $this->registerAlias('HttpClientService', \OCP\Http\Client\IClientService::class);
635
+        $this->registerService(\OCP\Diagnostics\IEventLogger::class, function (Server $c) {
636
+            $eventLogger = new EventLogger();
637
+            if ($c->getSystemConfig()->getValue('debug', false)) {
638
+                // In debug mode, module is being activated by default
639
+                $eventLogger->activate();
640
+            }
641
+            return $eventLogger;
642
+        });
643
+        $this->registerAlias('EventLogger', \OCP\Diagnostics\IEventLogger::class);
644
+
645
+        $this->registerService(\OCP\Diagnostics\IQueryLogger::class, function (Server $c) {
646
+            $queryLogger = new QueryLogger();
647
+            if ($c->getSystemConfig()->getValue('debug', false)) {
648
+                // In debug mode, module is being activated by default
649
+                $queryLogger->activate();
650
+            }
651
+            return $queryLogger;
652
+        });
653
+        $this->registerAlias('QueryLogger', \OCP\Diagnostics\IQueryLogger::class);
654
+
655
+        $this->registerService(TempManager::class, function (Server $c) {
656
+            return new TempManager(
657
+                $c->getLogger(),
658
+                $c->getConfig()
659
+            );
660
+        });
661
+        $this->registerAlias('TempManager', TempManager::class);
662
+        $this->registerAlias(ITempManager::class, TempManager::class);
663
+
664
+        $this->registerService(AppManager::class, function (Server $c) {
665
+            return new \OC\App\AppManager(
666
+                $c->getUserSession(),
667
+                $c->getAppConfig(),
668
+                $c->getGroupManager(),
669
+                $c->getMemCacheFactory(),
670
+                $c->getEventDispatcher()
671
+            );
672
+        });
673
+        $this->registerAlias('AppManager', AppManager::class);
674
+        $this->registerAlias(IAppManager::class, AppManager::class);
675
+
676
+        $this->registerService(\OCP\IDateTimeZone::class, function (Server $c) {
677
+            return new DateTimeZone(
678
+                $c->getConfig(),
679
+                $c->getSession()
680
+            );
681
+        });
682
+        $this->registerAlias('DateTimeZone', \OCP\IDateTimeZone::class);
683
+
684
+        $this->registerService(\OCP\IDateTimeFormatter::class, function (Server $c) {
685
+            $language = $c->getConfig()->getUserValue($c->getSession()->get('user_id'), 'core', 'lang', null);
686
+
687
+            return new DateTimeFormatter(
688
+                $c->getDateTimeZone()->getTimeZone(),
689
+                $c->getL10N('lib', $language)
690
+            );
691
+        });
692
+        $this->registerAlias('DateTimeFormatter', \OCP\IDateTimeFormatter::class);
693
+
694
+        $this->registerService(\OCP\Files\Config\IUserMountCache::class, function (Server $c) {
695
+            $mountCache = new UserMountCache($c->getDatabaseConnection(), $c->getUserManager(), $c->getLogger());
696
+            $listener = new UserMountCacheListener($mountCache);
697
+            $listener->listen($c->getUserManager());
698
+            return $mountCache;
699
+        });
700
+        $this->registerAlias('UserMountCache', \OCP\Files\Config\IUserMountCache::class);
701
+
702
+        $this->registerService(\OCP\Files\Config\IMountProviderCollection::class, function (Server $c) {
703
+            $loader = \OC\Files\Filesystem::getLoader();
704
+            $mountCache = $c->query('UserMountCache');
705
+            $manager = new \OC\Files\Config\MountProviderCollection($loader, $mountCache);
706
+
707
+            // builtin providers
708
+
709
+            $config = $c->getConfig();
710
+            $manager->registerProvider(new CacheMountProvider($config));
711
+            $manager->registerHomeProvider(new LocalHomeMountProvider());
712
+            $manager->registerHomeProvider(new ObjectHomeMountProvider($config));
713
+
714
+            return $manager;
715
+        });
716
+        $this->registerAlias('MountConfigManager', \OCP\Files\Config\IMountProviderCollection::class);
717
+
718
+        $this->registerService('IniWrapper', function ($c) {
719
+            return new IniGetWrapper();
720
+        });
721
+        $this->registerService('AsyncCommandBus', function (Server $c) {
722
+            $busClass = $c->getConfig()->getSystemValue('commandbus');
723
+            if ($busClass) {
724
+                list($app, $class) = explode('::', $busClass, 2);
725
+                if ($c->getAppManager()->isInstalled($app)) {
726
+                    \OC_App::loadApp($app);
727
+                    return $c->query($class);
728
+                } else {
729
+                    throw new ServiceUnavailableException("The app providing the command bus ($app) is not enabled");
730
+                }
731
+            } else {
732
+                $jobList = $c->getJobList();
733
+                return new CronBus($jobList);
734
+            }
735
+        });
736
+        $this->registerService('TrustedDomainHelper', function ($c) {
737
+            return new TrustedDomainHelper($this->getConfig());
738
+        });
739
+        $this->registerService('Throttler', function (Server $c) {
740
+            return new Throttler(
741
+                $c->getDatabaseConnection(),
742
+                new TimeFactory(),
743
+                $c->getLogger(),
744
+                $c->getConfig()
745
+            );
746
+        });
747
+        $this->registerService('IntegrityCodeChecker', function (Server $c) {
748
+            // IConfig and IAppManager requires a working database. This code
749
+            // might however be called when ownCloud is not yet setup.
750
+            if (\OC::$server->getSystemConfig()->getValue('installed', false)) {
751
+                $config = $c->getConfig();
752
+                $appManager = $c->getAppManager();
753
+            } else {
754
+                $config = null;
755
+                $appManager = null;
756
+            }
757
+
758
+            return new Checker(
759
+                new EnvironmentHelper(),
760
+                new FileAccessHelper(),
761
+                new AppLocator(),
762
+                $config,
763
+                $c->getMemCacheFactory(),
764
+                $appManager,
765
+                $c->getTempManager()
766
+            );
767
+        });
768
+        $this->registerService(\OCP\IRequest::class, function ($c) {
769
+            if (isset($this['urlParams'])) {
770
+                $urlParams = $this['urlParams'];
771
+            } else {
772
+                $urlParams = [];
773
+            }
774
+
775
+            if (defined('PHPUNIT_RUN') && PHPUNIT_RUN
776
+                && in_array('fakeinput', stream_get_wrappers())
777
+            ) {
778
+                $stream = 'fakeinput://data';
779
+            } else {
780
+                $stream = 'php://input';
781
+            }
782
+
783
+            return new Request(
784
+                [
785
+                    'get' => $_GET,
786
+                    'post' => $_POST,
787
+                    'files' => $_FILES,
788
+                    'server' => $_SERVER,
789
+                    'env' => $_ENV,
790
+                    'cookies' => $_COOKIE,
791
+                    'method' => (isset($_SERVER) && isset($_SERVER['REQUEST_METHOD']))
792
+                        ? $_SERVER['REQUEST_METHOD']
793
+                        : null,
794
+                    'urlParams' => $urlParams,
795
+                ],
796
+                $this->getSecureRandom(),
797
+                $this->getConfig(),
798
+                $this->getCsrfTokenManager(),
799
+                $stream
800
+            );
801
+        });
802
+        $this->registerAlias('Request', \OCP\IRequest::class);
803
+
804
+        $this->registerService(\OCP\Mail\IMailer::class, function (Server $c) {
805
+            return new Mailer(
806
+                $c->getConfig(),
807
+                $c->getLogger(),
808
+                $c->query(Defaults::class),
809
+                $c->getURLGenerator(),
810
+                $c->getL10N('lib')
811
+            );
812
+        });
813
+        $this->registerAlias('Mailer', \OCP\Mail\IMailer::class);
814
+
815
+        $this->registerService('LDAPProvider', function (Server $c) {
816
+            $config = $c->getConfig();
817
+            $factoryClass = $config->getSystemValue('ldapProviderFactory', null);
818
+            if (is_null($factoryClass)) {
819
+                throw new \Exception('ldapProviderFactory not set');
820
+            }
821
+            /** @var \OCP\LDAP\ILDAPProviderFactory $factory */
822
+            $factory = new $factoryClass($this);
823
+            return $factory->getLDAPProvider();
824
+        });
825
+        $this->registerService(ILockingProvider::class, function (Server $c) {
826
+            $ini = $c->getIniWrapper();
827
+            $config = $c->getConfig();
828
+            $ttl = $config->getSystemValue('filelocking.ttl', max(3600, $ini->getNumeric('max_execution_time')));
829
+            if ($config->getSystemValue('filelocking.enabled', true) or (defined('PHPUNIT_RUN') && PHPUNIT_RUN)) {
830
+                /** @var \OC\Memcache\Factory $memcacheFactory */
831
+                $memcacheFactory = $c->getMemCacheFactory();
832
+                $memcache = $memcacheFactory->createLocking('lock');
833
+                if (!($memcache instanceof \OC\Memcache\NullCache)) {
834
+                    return new MemcacheLockingProvider($memcache, $ttl);
835
+                }
836
+                return new DBLockingProvider($c->getDatabaseConnection(), $c->getLogger(), new TimeFactory(), $ttl);
837
+            }
838
+            return new NoopLockingProvider();
839
+        });
840
+        $this->registerAlias('LockingProvider', ILockingProvider::class);
841
+
842
+        $this->registerService(\OCP\Files\Mount\IMountManager::class, function () {
843
+            return new \OC\Files\Mount\Manager();
844
+        });
845
+        $this->registerAlias('MountManager', \OCP\Files\Mount\IMountManager::class);
846
+
847
+        $this->registerService(\OCP\Files\IMimeTypeDetector::class, function (Server $c) {
848
+            return new \OC\Files\Type\Detection(
849
+                $c->getURLGenerator(),
850
+                \OC::$configDir,
851
+                \OC::$SERVERROOT . '/resources/config/'
852
+            );
853
+        });
854
+        $this->registerAlias('MimeTypeDetector', \OCP\Files\IMimeTypeDetector::class);
855
+
856
+        $this->registerService(\OCP\Files\IMimeTypeLoader::class, function (Server $c) {
857
+            return new \OC\Files\Type\Loader(
858
+                $c->getDatabaseConnection()
859
+            );
860
+        });
861
+        $this->registerAlias('MimeTypeLoader', \OCP\Files\IMimeTypeLoader::class);
862
+        $this->registerService(BundleFetcher::class, function () {
863
+            return new BundleFetcher($this->getL10N('lib'));
864
+        });
865
+        $this->registerService(\OCP\Notification\IManager::class, function (Server $c) {
866
+            return new Manager(
867
+                $c->query(IValidator::class)
868
+            );
869
+        });
870
+        $this->registerAlias('NotificationManager', \OCP\Notification\IManager::class);
871
+
872
+        $this->registerService(\OC\CapabilitiesManager::class, function (Server $c) {
873
+            $manager = new \OC\CapabilitiesManager($c->getLogger());
874
+            $manager->registerCapability(function () use ($c) {
875
+                return new \OC\OCS\CoreCapabilities($c->getConfig());
876
+            });
877
+            $manager->registerCapability(function () use ($c) {
878
+                return $c->query(\OC\Security\Bruteforce\Capabilities::class);
879
+            });
880
+            return $manager;
881
+        });
882
+        $this->registerAlias('CapabilitiesManager', \OC\CapabilitiesManager::class);
883
+
884
+        $this->registerService(\OCP\Comments\ICommentsManager::class, function (Server $c) {
885
+            $config = $c->getConfig();
886
+            $factoryClass = $config->getSystemValue('comments.managerFactory', '\OC\Comments\ManagerFactory');
887
+            /** @var \OCP\Comments\ICommentsManagerFactory $factory */
888
+            $factory = new $factoryClass($this);
889
+            return $factory->getManager();
890
+        });
891
+        $this->registerAlias('CommentsManager', \OCP\Comments\ICommentsManager::class);
892
+
893
+        $this->registerService('ThemingDefaults', function (Server $c) {
894
+            /*
895 895
 			 * Dark magic for autoloader.
896 896
 			 * If we do a class_exists it will try to load the class which will
897 897
 			 * make composer cache the result. Resulting in errors when enabling
898 898
 			 * the theming app.
899 899
 			 */
900
-			$prefixes = \OC::$composerAutoloader->getPrefixesPsr4();
901
-			if (isset($prefixes['OCA\\Theming\\'])) {
902
-				$classExists = true;
903
-			} else {
904
-				$classExists = false;
905
-			}
906
-
907
-			if ($classExists && $c->getConfig()->getSystemValue('installed', false) && $c->getAppManager()->isInstalled('theming') && $c->getTrustedDomainHelper()->isTrustedDomain($c->getRequest()->getInsecureServerHost())) {
908
-				return new ThemingDefaults(
909
-					$c->getConfig(),
910
-					$c->getL10N('theming'),
911
-					$c->getURLGenerator(),
912
-					$c->getAppDataDir('theming'),
913
-					$c->getMemCacheFactory(),
914
-					new Util($c->getConfig(), $this->getAppManager(), $this->getAppDataDir('theming')),
915
-					$this->getAppManager()
916
-				);
917
-			}
918
-			return new \OC_Defaults();
919
-		});
920
-		$this->registerService(SCSSCacher::class, function (Server $c) {
921
-			/** @var Factory $cacheFactory */
922
-			$cacheFactory = $c->query(Factory::class);
923
-			return new SCSSCacher(
924
-				$c->getLogger(),
925
-				$c->query(\OC\Files\AppData\Factory::class),
926
-				$c->getURLGenerator(),
927
-				$c->getConfig(),
928
-				$c->getThemingDefaults(),
929
-				\OC::$SERVERROOT,
930
-				$cacheFactory->create('SCSS')
931
-			);
932
-		});
933
-		$this->registerService(EventDispatcher::class, function () {
934
-			return new EventDispatcher();
935
-		});
936
-		$this->registerAlias('EventDispatcher', EventDispatcher::class);
937
-		$this->registerAlias(EventDispatcherInterface::class, EventDispatcher::class);
938
-
939
-		$this->registerService('CryptoWrapper', function (Server $c) {
940
-			// FIXME: Instantiiated here due to cyclic dependency
941
-			$request = new Request(
942
-				[
943
-					'get' => $_GET,
944
-					'post' => $_POST,
945
-					'files' => $_FILES,
946
-					'server' => $_SERVER,
947
-					'env' => $_ENV,
948
-					'cookies' => $_COOKIE,
949
-					'method' => (isset($_SERVER) && isset($_SERVER['REQUEST_METHOD']))
950
-						? $_SERVER['REQUEST_METHOD']
951
-						: null,
952
-				],
953
-				$c->getSecureRandom(),
954
-				$c->getConfig()
955
-			);
956
-
957
-			return new CryptoWrapper(
958
-				$c->getConfig(),
959
-				$c->getCrypto(),
960
-				$c->getSecureRandom(),
961
-				$request
962
-			);
963
-		});
964
-		$this->registerService('CsrfTokenManager', function (Server $c) {
965
-			$tokenGenerator = new CsrfTokenGenerator($c->getSecureRandom());
966
-
967
-			return new CsrfTokenManager(
968
-				$tokenGenerator,
969
-				$c->query(SessionStorage::class)
970
-			);
971
-		});
972
-		$this->registerService(SessionStorage::class, function (Server $c) {
973
-			return new SessionStorage($c->getSession());
974
-		});
975
-		$this->registerService(\OCP\Security\IContentSecurityPolicyManager::class, function (Server $c) {
976
-			return new ContentSecurityPolicyManager();
977
-		});
978
-		$this->registerAlias('ContentSecurityPolicyManager', \OCP\Security\IContentSecurityPolicyManager::class);
979
-
980
-		$this->registerService('ContentSecurityPolicyNonceManager', function (Server $c) {
981
-			return new ContentSecurityPolicyNonceManager(
982
-				$c->getCsrfTokenManager(),
983
-				$c->getRequest()
984
-			);
985
-		});
986
-
987
-		$this->registerService(\OCP\Share\IManager::class, function (Server $c) {
988
-			$config = $c->getConfig();
989
-			$factoryClass = $config->getSystemValue('sharing.managerFactory', '\OC\Share20\ProviderFactory');
990
-			/** @var \OCP\Share\IProviderFactory $factory */
991
-			$factory = new $factoryClass($this);
992
-
993
-			$manager = new \OC\Share20\Manager(
994
-				$c->getLogger(),
995
-				$c->getConfig(),
996
-				$c->getSecureRandom(),
997
-				$c->getHasher(),
998
-				$c->getMountManager(),
999
-				$c->getGroupManager(),
1000
-				$c->getL10N('lib'),
1001
-				$c->getL10NFactory(),
1002
-				$factory,
1003
-				$c->getUserManager(),
1004
-				$c->getLazyRootFolder(),
1005
-				$c->getEventDispatcher(),
1006
-				$c->getMailer(),
1007
-				$c->getURLGenerator(),
1008
-				$c->getThemingDefaults()
1009
-			);
1010
-
1011
-			return $manager;
1012
-		});
1013
-		$this->registerAlias('ShareManager', \OCP\Share\IManager::class);
1014
-
1015
-		$this->registerService(\OCP\Collaboration\Collaborators\ISearch::class, function(Server $c) {
1016
-			$instance = new Collaboration\Collaborators\Search($c);
1017
-
1018
-			// register default plugins
1019
-			$instance->registerPlugin(['shareType' => 'SHARE_TYPE_USER', 'class' => UserPlugin::class]);
1020
-			$instance->registerPlugin(['shareType' => 'SHARE_TYPE_GROUP', 'class' => GroupPlugin::class]);
1021
-			$instance->registerPlugin(['shareType' => 'SHARE_TYPE_EMAIL', 'class' => MailPlugin::class]);
1022
-			$instance->registerPlugin(['shareType' => 'SHARE_TYPE_REMOTE', 'class' => RemotePlugin::class]);
1023
-
1024
-			return $instance;
1025
-		});
1026
-		$this->registerAlias('CollaboratorSearch', \OCP\Collaboration\Collaborators\ISearch::class);
1027
-
1028
-		$this->registerAlias(\OCP\Collaboration\AutoComplete\IManager::class, \OC\Collaboration\AutoComplete\Manager::class);
1029
-
1030
-		$this->registerService('SettingsManager', function (Server $c) {
1031
-			$manager = new \OC\Settings\Manager(
1032
-				$c->getLogger(),
1033
-				$c->getDatabaseConnection(),
1034
-				$c->getL10N('lib'),
1035
-				$c->getConfig(),
1036
-				$c->getEncryptionManager(),
1037
-				$c->getUserManager(),
1038
-				$c->getLockingProvider(),
1039
-				$c->getRequest(),
1040
-				new \OC\Settings\Mapper($c->getDatabaseConnection()),
1041
-				$c->getURLGenerator(),
1042
-				$c->query(AccountManager::class),
1043
-				$c->getGroupManager(),
1044
-				$c->getL10NFactory(),
1045
-				$c->getThemingDefaults(),
1046
-				$c->getAppManager()
1047
-			);
1048
-			return $manager;
1049
-		});
1050
-		$this->registerService(\OC\Files\AppData\Factory::class, function (Server $c) {
1051
-			return new \OC\Files\AppData\Factory(
1052
-				$c->getRootFolder(),
1053
-				$c->getSystemConfig()
1054
-			);
1055
-		});
1056
-
1057
-		$this->registerService('LockdownManager', function (Server $c) {
1058
-			return new LockdownManager(function () use ($c) {
1059
-				return $c->getSession();
1060
-			});
1061
-		});
1062
-
1063
-		$this->registerService(\OCP\OCS\IDiscoveryService::class, function (Server $c) {
1064
-			return new DiscoveryService($c->getMemCacheFactory(), $c->getHTTPClientService());
1065
-		});
1066
-
1067
-		$this->registerService(ICloudIdManager::class, function (Server $c) {
1068
-			return new CloudIdManager();
1069
-		});
1070
-
1071
-		/* To trick DI since we don't extend the DIContainer here */
1072
-		$this->registerService(CleanPreviewsBackgroundJob::class, function (Server $c) {
1073
-			return new CleanPreviewsBackgroundJob(
1074
-				$c->getRootFolder(),
1075
-				$c->getLogger(),
1076
-				$c->getJobList(),
1077
-				new TimeFactory()
1078
-			);
1079
-		});
1080
-
1081
-		$this->registerAlias(\OCP\AppFramework\Utility\IControllerMethodReflector::class, \OC\AppFramework\Utility\ControllerMethodReflector::class);
1082
-		$this->registerAlias('ControllerMethodReflector', \OCP\AppFramework\Utility\IControllerMethodReflector::class);
1083
-
1084
-		$this->registerAlias(\OCP\AppFramework\Utility\ITimeFactory::class, \OC\AppFramework\Utility\TimeFactory::class);
1085
-		$this->registerAlias('TimeFactory', \OCP\AppFramework\Utility\ITimeFactory::class);
1086
-
1087
-		$this->registerService(Defaults::class, function (Server $c) {
1088
-			return new Defaults(
1089
-				$c->getThemingDefaults()
1090
-			);
1091
-		});
1092
-		$this->registerAlias('Defaults', \OCP\Defaults::class);
1093
-
1094
-		$this->registerService(\OCP\ISession::class, function (SimpleContainer $c) {
1095
-			return $c->query(\OCP\IUserSession::class)->getSession();
1096
-		});
1097
-
1098
-		$this->registerService(IShareHelper::class, function (Server $c) {
1099
-			return new ShareHelper(
1100
-				$c->query(\OCP\Share\IManager::class)
1101
-			);
1102
-		});
1103
-
1104
-		$this->registerService(Installer::class, function(Server $c) {
1105
-			return new Installer(
1106
-				$c->getAppFetcher(),
1107
-				$c->getHTTPClientService(),
1108
-				$c->getTempManager(),
1109
-				$c->getLogger(),
1110
-				$c->getConfig()
1111
-			);
1112
-		});
1113
-
1114
-		$this->registerService(\OCP\Contacts\ContactsMenu\IContactsStore::class, function(Server $c) {
1115
-			return new ContactsStore(
1116
-				$this->getContactsManager(),
1117
-				$this->getConfig(),
1118
-				$this->getUserManager(),
1119
-				$this->getGroupManager()
1120
-			);
1121
-		});
1122
-	}
1123
-
1124
-	/**
1125
-	 * @return \OCP\Calendar\IManager
1126
-	 */
1127
-	public function getCalendarManager() {
1128
-		return $this->query('CalendarManager');
1129
-	}
1130
-
1131
-	/**
1132
-	 * @return \OCP\Contacts\IManager
1133
-	 */
1134
-	public function getContactsManager() {
1135
-		return $this->query('ContactsManager');
1136
-	}
1137
-
1138
-	/**
1139
-	 * @return \OC\Encryption\Manager
1140
-	 */
1141
-	public function getEncryptionManager() {
1142
-		return $this->query('EncryptionManager');
1143
-	}
1144
-
1145
-	/**
1146
-	 * @return \OC\Encryption\File
1147
-	 */
1148
-	public function getEncryptionFilesHelper() {
1149
-		return $this->query('EncryptionFileHelper');
1150
-	}
1151
-
1152
-	/**
1153
-	 * @return \OCP\Encryption\Keys\IStorage
1154
-	 */
1155
-	public function getEncryptionKeyStorage() {
1156
-		return $this->query('EncryptionKeyStorage');
1157
-	}
1158
-
1159
-	/**
1160
-	 * The current request object holding all information about the request
1161
-	 * currently being processed is returned from this method.
1162
-	 * In case the current execution was not initiated by a web request null is returned
1163
-	 *
1164
-	 * @return \OCP\IRequest
1165
-	 */
1166
-	public function getRequest() {
1167
-		return $this->query('Request');
1168
-	}
1169
-
1170
-	/**
1171
-	 * Returns the preview manager which can create preview images for a given file
1172
-	 *
1173
-	 * @return \OCP\IPreview
1174
-	 */
1175
-	public function getPreviewManager() {
1176
-		return $this->query('PreviewManager');
1177
-	}
1178
-
1179
-	/**
1180
-	 * Returns the tag manager which can get and set tags for different object types
1181
-	 *
1182
-	 * @see \OCP\ITagManager::load()
1183
-	 * @return \OCP\ITagManager
1184
-	 */
1185
-	public function getTagManager() {
1186
-		return $this->query('TagManager');
1187
-	}
1188
-
1189
-	/**
1190
-	 * Returns the system-tag manager
1191
-	 *
1192
-	 * @return \OCP\SystemTag\ISystemTagManager
1193
-	 *
1194
-	 * @since 9.0.0
1195
-	 */
1196
-	public function getSystemTagManager() {
1197
-		return $this->query('SystemTagManager');
1198
-	}
1199
-
1200
-	/**
1201
-	 * Returns the system-tag object mapper
1202
-	 *
1203
-	 * @return \OCP\SystemTag\ISystemTagObjectMapper
1204
-	 *
1205
-	 * @since 9.0.0
1206
-	 */
1207
-	public function getSystemTagObjectMapper() {
1208
-		return $this->query('SystemTagObjectMapper');
1209
-	}
1210
-
1211
-	/**
1212
-	 * Returns the avatar manager, used for avatar functionality
1213
-	 *
1214
-	 * @return \OCP\IAvatarManager
1215
-	 */
1216
-	public function getAvatarManager() {
1217
-		return $this->query('AvatarManager');
1218
-	}
1219
-
1220
-	/**
1221
-	 * Returns the root folder of ownCloud's data directory
1222
-	 *
1223
-	 * @return \OCP\Files\IRootFolder
1224
-	 */
1225
-	public function getRootFolder() {
1226
-		return $this->query('LazyRootFolder');
1227
-	}
1228
-
1229
-	/**
1230
-	 * Returns the root folder of ownCloud's data directory
1231
-	 * This is the lazy variant so this gets only initialized once it
1232
-	 * is actually used.
1233
-	 *
1234
-	 * @return \OCP\Files\IRootFolder
1235
-	 */
1236
-	public function getLazyRootFolder() {
1237
-		return $this->query('LazyRootFolder');
1238
-	}
1239
-
1240
-	/**
1241
-	 * Returns a view to ownCloud's files folder
1242
-	 *
1243
-	 * @param string $userId user ID
1244
-	 * @return \OCP\Files\Folder|null
1245
-	 */
1246
-	public function getUserFolder($userId = null) {
1247
-		if ($userId === null) {
1248
-			$user = $this->getUserSession()->getUser();
1249
-			if (!$user) {
1250
-				return null;
1251
-			}
1252
-			$userId = $user->getUID();
1253
-		}
1254
-		$root = $this->getRootFolder();
1255
-		return $root->getUserFolder($userId);
1256
-	}
1257
-
1258
-	/**
1259
-	 * Returns an app-specific view in ownClouds data directory
1260
-	 *
1261
-	 * @return \OCP\Files\Folder
1262
-	 * @deprecated since 9.2.0 use IAppData
1263
-	 */
1264
-	public function getAppFolder() {
1265
-		$dir = '/' . \OC_App::getCurrentApp();
1266
-		$root = $this->getRootFolder();
1267
-		if (!$root->nodeExists($dir)) {
1268
-			$folder = $root->newFolder($dir);
1269
-		} else {
1270
-			$folder = $root->get($dir);
1271
-		}
1272
-		return $folder;
1273
-	}
1274
-
1275
-	/**
1276
-	 * @return \OC\User\Manager
1277
-	 */
1278
-	public function getUserManager() {
1279
-		return $this->query('UserManager');
1280
-	}
1281
-
1282
-	/**
1283
-	 * @return \OC\Group\Manager
1284
-	 */
1285
-	public function getGroupManager() {
1286
-		return $this->query('GroupManager');
1287
-	}
1288
-
1289
-	/**
1290
-	 * @return \OC\User\Session
1291
-	 */
1292
-	public function getUserSession() {
1293
-		return $this->query('UserSession');
1294
-	}
1295
-
1296
-	/**
1297
-	 * @return \OCP\ISession
1298
-	 */
1299
-	public function getSession() {
1300
-		return $this->query('UserSession')->getSession();
1301
-	}
1302
-
1303
-	/**
1304
-	 * @param \OCP\ISession $session
1305
-	 */
1306
-	public function setSession(\OCP\ISession $session) {
1307
-		$this->query(SessionStorage::class)->setSession($session);
1308
-		$this->query('UserSession')->setSession($session);
1309
-		$this->query(Store::class)->setSession($session);
1310
-	}
1311
-
1312
-	/**
1313
-	 * @return \OC\Authentication\TwoFactorAuth\Manager
1314
-	 */
1315
-	public function getTwoFactorAuthManager() {
1316
-		return $this->query('\OC\Authentication\TwoFactorAuth\Manager');
1317
-	}
1318
-
1319
-	/**
1320
-	 * @return \OC\NavigationManager
1321
-	 */
1322
-	public function getNavigationManager() {
1323
-		return $this->query('NavigationManager');
1324
-	}
1325
-
1326
-	/**
1327
-	 * @return \OCP\IConfig
1328
-	 */
1329
-	public function getConfig() {
1330
-		return $this->query('AllConfig');
1331
-	}
1332
-
1333
-	/**
1334
-	 * @return \OC\SystemConfig
1335
-	 */
1336
-	public function getSystemConfig() {
1337
-		return $this->query('SystemConfig');
1338
-	}
1339
-
1340
-	/**
1341
-	 * Returns the app config manager
1342
-	 *
1343
-	 * @return \OCP\IAppConfig
1344
-	 */
1345
-	public function getAppConfig() {
1346
-		return $this->query('AppConfig');
1347
-	}
1348
-
1349
-	/**
1350
-	 * @return \OCP\L10N\IFactory
1351
-	 */
1352
-	public function getL10NFactory() {
1353
-		return $this->query('L10NFactory');
1354
-	}
1355
-
1356
-	/**
1357
-	 * get an L10N instance
1358
-	 *
1359
-	 * @param string $app appid
1360
-	 * @param string $lang
1361
-	 * @return IL10N
1362
-	 */
1363
-	public function getL10N($app, $lang = null) {
1364
-		return $this->getL10NFactory()->get($app, $lang);
1365
-	}
1366
-
1367
-	/**
1368
-	 * @return \OCP\IURLGenerator
1369
-	 */
1370
-	public function getURLGenerator() {
1371
-		return $this->query('URLGenerator');
1372
-	}
1373
-
1374
-	/**
1375
-	 * @return \OCP\IHelper
1376
-	 */
1377
-	public function getHelper() {
1378
-		return $this->query('AppHelper');
1379
-	}
1380
-
1381
-	/**
1382
-	 * @return AppFetcher
1383
-	 */
1384
-	public function getAppFetcher() {
1385
-		return $this->query(AppFetcher::class);
1386
-	}
1387
-
1388
-	/**
1389
-	 * Returns an ICache instance. Since 8.1.0 it returns a fake cache. Use
1390
-	 * getMemCacheFactory() instead.
1391
-	 *
1392
-	 * @return \OCP\ICache
1393
-	 * @deprecated 8.1.0 use getMemCacheFactory to obtain a proper cache
1394
-	 */
1395
-	public function getCache() {
1396
-		return $this->query('UserCache');
1397
-	}
1398
-
1399
-	/**
1400
-	 * Returns an \OCP\CacheFactory instance
1401
-	 *
1402
-	 * @return \OCP\ICacheFactory
1403
-	 */
1404
-	public function getMemCacheFactory() {
1405
-		return $this->query('MemCacheFactory');
1406
-	}
1407
-
1408
-	/**
1409
-	 * Returns an \OC\RedisFactory instance
1410
-	 *
1411
-	 * @return \OC\RedisFactory
1412
-	 */
1413
-	public function getGetRedisFactory() {
1414
-		return $this->query('RedisFactory');
1415
-	}
1416
-
1417
-
1418
-	/**
1419
-	 * Returns the current session
1420
-	 *
1421
-	 * @return \OCP\IDBConnection
1422
-	 */
1423
-	public function getDatabaseConnection() {
1424
-		return $this->query('DatabaseConnection');
1425
-	}
1426
-
1427
-	/**
1428
-	 * Returns the activity manager
1429
-	 *
1430
-	 * @return \OCP\Activity\IManager
1431
-	 */
1432
-	public function getActivityManager() {
1433
-		return $this->query('ActivityManager');
1434
-	}
1435
-
1436
-	/**
1437
-	 * Returns an job list for controlling background jobs
1438
-	 *
1439
-	 * @return \OCP\BackgroundJob\IJobList
1440
-	 */
1441
-	public function getJobList() {
1442
-		return $this->query('JobList');
1443
-	}
1444
-
1445
-	/**
1446
-	 * Returns a logger instance
1447
-	 *
1448
-	 * @return \OCP\ILogger
1449
-	 */
1450
-	public function getLogger() {
1451
-		return $this->query('Logger');
1452
-	}
1453
-
1454
-	/**
1455
-	 * Returns a router for generating and matching urls
1456
-	 *
1457
-	 * @return \OCP\Route\IRouter
1458
-	 */
1459
-	public function getRouter() {
1460
-		return $this->query('Router');
1461
-	}
1462
-
1463
-	/**
1464
-	 * Returns a search instance
1465
-	 *
1466
-	 * @return \OCP\ISearch
1467
-	 */
1468
-	public function getSearch() {
1469
-		return $this->query('Search');
1470
-	}
1471
-
1472
-	/**
1473
-	 * Returns a SecureRandom instance
1474
-	 *
1475
-	 * @return \OCP\Security\ISecureRandom
1476
-	 */
1477
-	public function getSecureRandom() {
1478
-		return $this->query('SecureRandom');
1479
-	}
1480
-
1481
-	/**
1482
-	 * Returns a Crypto instance
1483
-	 *
1484
-	 * @return \OCP\Security\ICrypto
1485
-	 */
1486
-	public function getCrypto() {
1487
-		return $this->query('Crypto');
1488
-	}
1489
-
1490
-	/**
1491
-	 * Returns a Hasher instance
1492
-	 *
1493
-	 * @return \OCP\Security\IHasher
1494
-	 */
1495
-	public function getHasher() {
1496
-		return $this->query('Hasher');
1497
-	}
1498
-
1499
-	/**
1500
-	 * Returns a CredentialsManager instance
1501
-	 *
1502
-	 * @return \OCP\Security\ICredentialsManager
1503
-	 */
1504
-	public function getCredentialsManager() {
1505
-		return $this->query('CredentialsManager');
1506
-	}
1507
-
1508
-	/**
1509
-	 * Returns an instance of the HTTP helper class
1510
-	 *
1511
-	 * @deprecated Use getHTTPClientService()
1512
-	 * @return \OC\HTTPHelper
1513
-	 */
1514
-	public function getHTTPHelper() {
1515
-		return $this->query('HTTPHelper');
1516
-	}
1517
-
1518
-	/**
1519
-	 * Get the certificate manager for the user
1520
-	 *
1521
-	 * @param string $userId (optional) if not specified the current loggedin user is used, use null to get the system certificate manager
1522
-	 * @return \OCP\ICertificateManager | null if $uid is null and no user is logged in
1523
-	 */
1524
-	public function getCertificateManager($userId = '') {
1525
-		if ($userId === '') {
1526
-			$userSession = $this->getUserSession();
1527
-			$user = $userSession->getUser();
1528
-			if (is_null($user)) {
1529
-				return null;
1530
-			}
1531
-			$userId = $user->getUID();
1532
-		}
1533
-		return new CertificateManager(
1534
-			$userId,
1535
-			new View(),
1536
-			$this->getConfig(),
1537
-			$this->getLogger(),
1538
-			$this->getSecureRandom()
1539
-		);
1540
-	}
1541
-
1542
-	/**
1543
-	 * Returns an instance of the HTTP client service
1544
-	 *
1545
-	 * @return \OCP\Http\Client\IClientService
1546
-	 */
1547
-	public function getHTTPClientService() {
1548
-		return $this->query('HttpClientService');
1549
-	}
1550
-
1551
-	/**
1552
-	 * Create a new event source
1553
-	 *
1554
-	 * @return \OCP\IEventSource
1555
-	 */
1556
-	public function createEventSource() {
1557
-		return new \OC_EventSource();
1558
-	}
1559
-
1560
-	/**
1561
-	 * Get the active event logger
1562
-	 *
1563
-	 * The returned logger only logs data when debug mode is enabled
1564
-	 *
1565
-	 * @return \OCP\Diagnostics\IEventLogger
1566
-	 */
1567
-	public function getEventLogger() {
1568
-		return $this->query('EventLogger');
1569
-	}
1570
-
1571
-	/**
1572
-	 * Get the active query logger
1573
-	 *
1574
-	 * The returned logger only logs data when debug mode is enabled
1575
-	 *
1576
-	 * @return \OCP\Diagnostics\IQueryLogger
1577
-	 */
1578
-	public function getQueryLogger() {
1579
-		return $this->query('QueryLogger');
1580
-	}
1581
-
1582
-	/**
1583
-	 * Get the manager for temporary files and folders
1584
-	 *
1585
-	 * @return \OCP\ITempManager
1586
-	 */
1587
-	public function getTempManager() {
1588
-		return $this->query('TempManager');
1589
-	}
1590
-
1591
-	/**
1592
-	 * Get the app manager
1593
-	 *
1594
-	 * @return \OCP\App\IAppManager
1595
-	 */
1596
-	public function getAppManager() {
1597
-		return $this->query('AppManager');
1598
-	}
1599
-
1600
-	/**
1601
-	 * Creates a new mailer
1602
-	 *
1603
-	 * @return \OCP\Mail\IMailer
1604
-	 */
1605
-	public function getMailer() {
1606
-		return $this->query('Mailer');
1607
-	}
1608
-
1609
-	/**
1610
-	 * Get the webroot
1611
-	 *
1612
-	 * @return string
1613
-	 */
1614
-	public function getWebRoot() {
1615
-		return $this->webRoot;
1616
-	}
1617
-
1618
-	/**
1619
-	 * @return \OC\OCSClient
1620
-	 */
1621
-	public function getOcsClient() {
1622
-		return $this->query('OcsClient');
1623
-	}
1624
-
1625
-	/**
1626
-	 * @return \OCP\IDateTimeZone
1627
-	 */
1628
-	public function getDateTimeZone() {
1629
-		return $this->query('DateTimeZone');
1630
-	}
1631
-
1632
-	/**
1633
-	 * @return \OCP\IDateTimeFormatter
1634
-	 */
1635
-	public function getDateTimeFormatter() {
1636
-		return $this->query('DateTimeFormatter');
1637
-	}
1638
-
1639
-	/**
1640
-	 * @return \OCP\Files\Config\IMountProviderCollection
1641
-	 */
1642
-	public function getMountProviderCollection() {
1643
-		return $this->query('MountConfigManager');
1644
-	}
1645
-
1646
-	/**
1647
-	 * Get the IniWrapper
1648
-	 *
1649
-	 * @return IniGetWrapper
1650
-	 */
1651
-	public function getIniWrapper() {
1652
-		return $this->query('IniWrapper');
1653
-	}
1654
-
1655
-	/**
1656
-	 * @return \OCP\Command\IBus
1657
-	 */
1658
-	public function getCommandBus() {
1659
-		return $this->query('AsyncCommandBus');
1660
-	}
1661
-
1662
-	/**
1663
-	 * Get the trusted domain helper
1664
-	 *
1665
-	 * @return TrustedDomainHelper
1666
-	 */
1667
-	public function getTrustedDomainHelper() {
1668
-		return $this->query('TrustedDomainHelper');
1669
-	}
1670
-
1671
-	/**
1672
-	 * Get the locking provider
1673
-	 *
1674
-	 * @return \OCP\Lock\ILockingProvider
1675
-	 * @since 8.1.0
1676
-	 */
1677
-	public function getLockingProvider() {
1678
-		return $this->query('LockingProvider');
1679
-	}
1680
-
1681
-	/**
1682
-	 * @return \OCP\Files\Mount\IMountManager
1683
-	 **/
1684
-	function getMountManager() {
1685
-		return $this->query('MountManager');
1686
-	}
1687
-
1688
-	/** @return \OCP\Files\Config\IUserMountCache */
1689
-	function getUserMountCache() {
1690
-		return $this->query('UserMountCache');
1691
-	}
1692
-
1693
-	/**
1694
-	 * Get the MimeTypeDetector
1695
-	 *
1696
-	 * @return \OCP\Files\IMimeTypeDetector
1697
-	 */
1698
-	public function getMimeTypeDetector() {
1699
-		return $this->query('MimeTypeDetector');
1700
-	}
1701
-
1702
-	/**
1703
-	 * Get the MimeTypeLoader
1704
-	 *
1705
-	 * @return \OCP\Files\IMimeTypeLoader
1706
-	 */
1707
-	public function getMimeTypeLoader() {
1708
-		return $this->query('MimeTypeLoader');
1709
-	}
1710
-
1711
-	/**
1712
-	 * Get the manager of all the capabilities
1713
-	 *
1714
-	 * @return \OC\CapabilitiesManager
1715
-	 */
1716
-	public function getCapabilitiesManager() {
1717
-		return $this->query('CapabilitiesManager');
1718
-	}
1719
-
1720
-	/**
1721
-	 * Get the EventDispatcher
1722
-	 *
1723
-	 * @return EventDispatcherInterface
1724
-	 * @since 8.2.0
1725
-	 */
1726
-	public function getEventDispatcher() {
1727
-		return $this->query('EventDispatcher');
1728
-	}
1729
-
1730
-	/**
1731
-	 * Get the Notification Manager
1732
-	 *
1733
-	 * @return \OCP\Notification\IManager
1734
-	 * @since 8.2.0
1735
-	 */
1736
-	public function getNotificationManager() {
1737
-		return $this->query('NotificationManager');
1738
-	}
1739
-
1740
-	/**
1741
-	 * @return \OCP\Comments\ICommentsManager
1742
-	 */
1743
-	public function getCommentsManager() {
1744
-		return $this->query('CommentsManager');
1745
-	}
1746
-
1747
-	/**
1748
-	 * @return \OCA\Theming\ThemingDefaults
1749
-	 */
1750
-	public function getThemingDefaults() {
1751
-		return $this->query('ThemingDefaults');
1752
-	}
1753
-
1754
-	/**
1755
-	 * @return \OC\IntegrityCheck\Checker
1756
-	 */
1757
-	public function getIntegrityCodeChecker() {
1758
-		return $this->query('IntegrityCodeChecker');
1759
-	}
1760
-
1761
-	/**
1762
-	 * @return \OC\Session\CryptoWrapper
1763
-	 */
1764
-	public function getSessionCryptoWrapper() {
1765
-		return $this->query('CryptoWrapper');
1766
-	}
1767
-
1768
-	/**
1769
-	 * @return CsrfTokenManager
1770
-	 */
1771
-	public function getCsrfTokenManager() {
1772
-		return $this->query('CsrfTokenManager');
1773
-	}
1774
-
1775
-	/**
1776
-	 * @return Throttler
1777
-	 */
1778
-	public function getBruteForceThrottler() {
1779
-		return $this->query('Throttler');
1780
-	}
1781
-
1782
-	/**
1783
-	 * @return IContentSecurityPolicyManager
1784
-	 */
1785
-	public function getContentSecurityPolicyManager() {
1786
-		return $this->query('ContentSecurityPolicyManager');
1787
-	}
1788
-
1789
-	/**
1790
-	 * @return ContentSecurityPolicyNonceManager
1791
-	 */
1792
-	public function getContentSecurityPolicyNonceManager() {
1793
-		return $this->query('ContentSecurityPolicyNonceManager');
1794
-	}
1795
-
1796
-	/**
1797
-	 * Not a public API as of 8.2, wait for 9.0
1798
-	 *
1799
-	 * @return \OCA\Files_External\Service\BackendService
1800
-	 */
1801
-	public function getStoragesBackendService() {
1802
-		return $this->query('OCA\\Files_External\\Service\\BackendService');
1803
-	}
1804
-
1805
-	/**
1806
-	 * Not a public API as of 8.2, wait for 9.0
1807
-	 *
1808
-	 * @return \OCA\Files_External\Service\GlobalStoragesService
1809
-	 */
1810
-	public function getGlobalStoragesService() {
1811
-		return $this->query('OCA\\Files_External\\Service\\GlobalStoragesService');
1812
-	}
1813
-
1814
-	/**
1815
-	 * Not a public API as of 8.2, wait for 9.0
1816
-	 *
1817
-	 * @return \OCA\Files_External\Service\UserGlobalStoragesService
1818
-	 */
1819
-	public function getUserGlobalStoragesService() {
1820
-		return $this->query('OCA\\Files_External\\Service\\UserGlobalStoragesService');
1821
-	}
1822
-
1823
-	/**
1824
-	 * Not a public API as of 8.2, wait for 9.0
1825
-	 *
1826
-	 * @return \OCA\Files_External\Service\UserStoragesService
1827
-	 */
1828
-	public function getUserStoragesService() {
1829
-		return $this->query('OCA\\Files_External\\Service\\UserStoragesService');
1830
-	}
1831
-
1832
-	/**
1833
-	 * @return \OCP\Share\IManager
1834
-	 */
1835
-	public function getShareManager() {
1836
-		return $this->query('ShareManager');
1837
-	}
1838
-
1839
-	/**
1840
-	 * @return \OCP\Collaboration\Collaborators\ISearch
1841
-	 */
1842
-	public function getCollaboratorSearch() {
1843
-		return $this->query('CollaboratorSearch');
1844
-	}
1845
-
1846
-	/**
1847
-	 * @return \OCP\Collaboration\AutoComplete\IManager
1848
-	 */
1849
-	public function getAutoCompleteManager(){
1850
-		return $this->query(IManager::class);
1851
-	}
1852
-
1853
-	/**
1854
-	 * Returns the LDAP Provider
1855
-	 *
1856
-	 * @return \OCP\LDAP\ILDAPProvider
1857
-	 */
1858
-	public function getLDAPProvider() {
1859
-		return $this->query('LDAPProvider');
1860
-	}
1861
-
1862
-	/**
1863
-	 * @return \OCP\Settings\IManager
1864
-	 */
1865
-	public function getSettingsManager() {
1866
-		return $this->query('SettingsManager');
1867
-	}
1868
-
1869
-	/**
1870
-	 * @return \OCP\Files\IAppData
1871
-	 */
1872
-	public function getAppDataDir($app) {
1873
-		/** @var \OC\Files\AppData\Factory $factory */
1874
-		$factory = $this->query(\OC\Files\AppData\Factory::class);
1875
-		return $factory->get($app);
1876
-	}
1877
-
1878
-	/**
1879
-	 * @return \OCP\Lockdown\ILockdownManager
1880
-	 */
1881
-	public function getLockdownManager() {
1882
-		return $this->query('LockdownManager');
1883
-	}
1884
-
1885
-	/**
1886
-	 * @return \OCP\Federation\ICloudIdManager
1887
-	 */
1888
-	public function getCloudIdManager() {
1889
-		return $this->query(ICloudIdManager::class);
1890
-	}
900
+            $prefixes = \OC::$composerAutoloader->getPrefixesPsr4();
901
+            if (isset($prefixes['OCA\\Theming\\'])) {
902
+                $classExists = true;
903
+            } else {
904
+                $classExists = false;
905
+            }
906
+
907
+            if ($classExists && $c->getConfig()->getSystemValue('installed', false) && $c->getAppManager()->isInstalled('theming') && $c->getTrustedDomainHelper()->isTrustedDomain($c->getRequest()->getInsecureServerHost())) {
908
+                return new ThemingDefaults(
909
+                    $c->getConfig(),
910
+                    $c->getL10N('theming'),
911
+                    $c->getURLGenerator(),
912
+                    $c->getAppDataDir('theming'),
913
+                    $c->getMemCacheFactory(),
914
+                    new Util($c->getConfig(), $this->getAppManager(), $this->getAppDataDir('theming')),
915
+                    $this->getAppManager()
916
+                );
917
+            }
918
+            return new \OC_Defaults();
919
+        });
920
+        $this->registerService(SCSSCacher::class, function (Server $c) {
921
+            /** @var Factory $cacheFactory */
922
+            $cacheFactory = $c->query(Factory::class);
923
+            return new SCSSCacher(
924
+                $c->getLogger(),
925
+                $c->query(\OC\Files\AppData\Factory::class),
926
+                $c->getURLGenerator(),
927
+                $c->getConfig(),
928
+                $c->getThemingDefaults(),
929
+                \OC::$SERVERROOT,
930
+                $cacheFactory->create('SCSS')
931
+            );
932
+        });
933
+        $this->registerService(EventDispatcher::class, function () {
934
+            return new EventDispatcher();
935
+        });
936
+        $this->registerAlias('EventDispatcher', EventDispatcher::class);
937
+        $this->registerAlias(EventDispatcherInterface::class, EventDispatcher::class);
938
+
939
+        $this->registerService('CryptoWrapper', function (Server $c) {
940
+            // FIXME: Instantiiated here due to cyclic dependency
941
+            $request = new Request(
942
+                [
943
+                    'get' => $_GET,
944
+                    'post' => $_POST,
945
+                    'files' => $_FILES,
946
+                    'server' => $_SERVER,
947
+                    'env' => $_ENV,
948
+                    'cookies' => $_COOKIE,
949
+                    'method' => (isset($_SERVER) && isset($_SERVER['REQUEST_METHOD']))
950
+                        ? $_SERVER['REQUEST_METHOD']
951
+                        : null,
952
+                ],
953
+                $c->getSecureRandom(),
954
+                $c->getConfig()
955
+            );
956
+
957
+            return new CryptoWrapper(
958
+                $c->getConfig(),
959
+                $c->getCrypto(),
960
+                $c->getSecureRandom(),
961
+                $request
962
+            );
963
+        });
964
+        $this->registerService('CsrfTokenManager', function (Server $c) {
965
+            $tokenGenerator = new CsrfTokenGenerator($c->getSecureRandom());
966
+
967
+            return new CsrfTokenManager(
968
+                $tokenGenerator,
969
+                $c->query(SessionStorage::class)
970
+            );
971
+        });
972
+        $this->registerService(SessionStorage::class, function (Server $c) {
973
+            return new SessionStorage($c->getSession());
974
+        });
975
+        $this->registerService(\OCP\Security\IContentSecurityPolicyManager::class, function (Server $c) {
976
+            return new ContentSecurityPolicyManager();
977
+        });
978
+        $this->registerAlias('ContentSecurityPolicyManager', \OCP\Security\IContentSecurityPolicyManager::class);
979
+
980
+        $this->registerService('ContentSecurityPolicyNonceManager', function (Server $c) {
981
+            return new ContentSecurityPolicyNonceManager(
982
+                $c->getCsrfTokenManager(),
983
+                $c->getRequest()
984
+            );
985
+        });
986
+
987
+        $this->registerService(\OCP\Share\IManager::class, function (Server $c) {
988
+            $config = $c->getConfig();
989
+            $factoryClass = $config->getSystemValue('sharing.managerFactory', '\OC\Share20\ProviderFactory');
990
+            /** @var \OCP\Share\IProviderFactory $factory */
991
+            $factory = new $factoryClass($this);
992
+
993
+            $manager = new \OC\Share20\Manager(
994
+                $c->getLogger(),
995
+                $c->getConfig(),
996
+                $c->getSecureRandom(),
997
+                $c->getHasher(),
998
+                $c->getMountManager(),
999
+                $c->getGroupManager(),
1000
+                $c->getL10N('lib'),
1001
+                $c->getL10NFactory(),
1002
+                $factory,
1003
+                $c->getUserManager(),
1004
+                $c->getLazyRootFolder(),
1005
+                $c->getEventDispatcher(),
1006
+                $c->getMailer(),
1007
+                $c->getURLGenerator(),
1008
+                $c->getThemingDefaults()
1009
+            );
1010
+
1011
+            return $manager;
1012
+        });
1013
+        $this->registerAlias('ShareManager', \OCP\Share\IManager::class);
1014
+
1015
+        $this->registerService(\OCP\Collaboration\Collaborators\ISearch::class, function(Server $c) {
1016
+            $instance = new Collaboration\Collaborators\Search($c);
1017
+
1018
+            // register default plugins
1019
+            $instance->registerPlugin(['shareType' => 'SHARE_TYPE_USER', 'class' => UserPlugin::class]);
1020
+            $instance->registerPlugin(['shareType' => 'SHARE_TYPE_GROUP', 'class' => GroupPlugin::class]);
1021
+            $instance->registerPlugin(['shareType' => 'SHARE_TYPE_EMAIL', 'class' => MailPlugin::class]);
1022
+            $instance->registerPlugin(['shareType' => 'SHARE_TYPE_REMOTE', 'class' => RemotePlugin::class]);
1023
+
1024
+            return $instance;
1025
+        });
1026
+        $this->registerAlias('CollaboratorSearch', \OCP\Collaboration\Collaborators\ISearch::class);
1027
+
1028
+        $this->registerAlias(\OCP\Collaboration\AutoComplete\IManager::class, \OC\Collaboration\AutoComplete\Manager::class);
1029
+
1030
+        $this->registerService('SettingsManager', function (Server $c) {
1031
+            $manager = new \OC\Settings\Manager(
1032
+                $c->getLogger(),
1033
+                $c->getDatabaseConnection(),
1034
+                $c->getL10N('lib'),
1035
+                $c->getConfig(),
1036
+                $c->getEncryptionManager(),
1037
+                $c->getUserManager(),
1038
+                $c->getLockingProvider(),
1039
+                $c->getRequest(),
1040
+                new \OC\Settings\Mapper($c->getDatabaseConnection()),
1041
+                $c->getURLGenerator(),
1042
+                $c->query(AccountManager::class),
1043
+                $c->getGroupManager(),
1044
+                $c->getL10NFactory(),
1045
+                $c->getThemingDefaults(),
1046
+                $c->getAppManager()
1047
+            );
1048
+            return $manager;
1049
+        });
1050
+        $this->registerService(\OC\Files\AppData\Factory::class, function (Server $c) {
1051
+            return new \OC\Files\AppData\Factory(
1052
+                $c->getRootFolder(),
1053
+                $c->getSystemConfig()
1054
+            );
1055
+        });
1056
+
1057
+        $this->registerService('LockdownManager', function (Server $c) {
1058
+            return new LockdownManager(function () use ($c) {
1059
+                return $c->getSession();
1060
+            });
1061
+        });
1062
+
1063
+        $this->registerService(\OCP\OCS\IDiscoveryService::class, function (Server $c) {
1064
+            return new DiscoveryService($c->getMemCacheFactory(), $c->getHTTPClientService());
1065
+        });
1066
+
1067
+        $this->registerService(ICloudIdManager::class, function (Server $c) {
1068
+            return new CloudIdManager();
1069
+        });
1070
+
1071
+        /* To trick DI since we don't extend the DIContainer here */
1072
+        $this->registerService(CleanPreviewsBackgroundJob::class, function (Server $c) {
1073
+            return new CleanPreviewsBackgroundJob(
1074
+                $c->getRootFolder(),
1075
+                $c->getLogger(),
1076
+                $c->getJobList(),
1077
+                new TimeFactory()
1078
+            );
1079
+        });
1080
+
1081
+        $this->registerAlias(\OCP\AppFramework\Utility\IControllerMethodReflector::class, \OC\AppFramework\Utility\ControllerMethodReflector::class);
1082
+        $this->registerAlias('ControllerMethodReflector', \OCP\AppFramework\Utility\IControllerMethodReflector::class);
1083
+
1084
+        $this->registerAlias(\OCP\AppFramework\Utility\ITimeFactory::class, \OC\AppFramework\Utility\TimeFactory::class);
1085
+        $this->registerAlias('TimeFactory', \OCP\AppFramework\Utility\ITimeFactory::class);
1086
+
1087
+        $this->registerService(Defaults::class, function (Server $c) {
1088
+            return new Defaults(
1089
+                $c->getThemingDefaults()
1090
+            );
1091
+        });
1092
+        $this->registerAlias('Defaults', \OCP\Defaults::class);
1093
+
1094
+        $this->registerService(\OCP\ISession::class, function (SimpleContainer $c) {
1095
+            return $c->query(\OCP\IUserSession::class)->getSession();
1096
+        });
1097
+
1098
+        $this->registerService(IShareHelper::class, function (Server $c) {
1099
+            return new ShareHelper(
1100
+                $c->query(\OCP\Share\IManager::class)
1101
+            );
1102
+        });
1103
+
1104
+        $this->registerService(Installer::class, function(Server $c) {
1105
+            return new Installer(
1106
+                $c->getAppFetcher(),
1107
+                $c->getHTTPClientService(),
1108
+                $c->getTempManager(),
1109
+                $c->getLogger(),
1110
+                $c->getConfig()
1111
+            );
1112
+        });
1113
+
1114
+        $this->registerService(\OCP\Contacts\ContactsMenu\IContactsStore::class, function(Server $c) {
1115
+            return new ContactsStore(
1116
+                $this->getContactsManager(),
1117
+                $this->getConfig(),
1118
+                $this->getUserManager(),
1119
+                $this->getGroupManager()
1120
+            );
1121
+        });
1122
+    }
1123
+
1124
+    /**
1125
+     * @return \OCP\Calendar\IManager
1126
+     */
1127
+    public function getCalendarManager() {
1128
+        return $this->query('CalendarManager');
1129
+    }
1130
+
1131
+    /**
1132
+     * @return \OCP\Contacts\IManager
1133
+     */
1134
+    public function getContactsManager() {
1135
+        return $this->query('ContactsManager');
1136
+    }
1137
+
1138
+    /**
1139
+     * @return \OC\Encryption\Manager
1140
+     */
1141
+    public function getEncryptionManager() {
1142
+        return $this->query('EncryptionManager');
1143
+    }
1144
+
1145
+    /**
1146
+     * @return \OC\Encryption\File
1147
+     */
1148
+    public function getEncryptionFilesHelper() {
1149
+        return $this->query('EncryptionFileHelper');
1150
+    }
1151
+
1152
+    /**
1153
+     * @return \OCP\Encryption\Keys\IStorage
1154
+     */
1155
+    public function getEncryptionKeyStorage() {
1156
+        return $this->query('EncryptionKeyStorage');
1157
+    }
1158
+
1159
+    /**
1160
+     * The current request object holding all information about the request
1161
+     * currently being processed is returned from this method.
1162
+     * In case the current execution was not initiated by a web request null is returned
1163
+     *
1164
+     * @return \OCP\IRequest
1165
+     */
1166
+    public function getRequest() {
1167
+        return $this->query('Request');
1168
+    }
1169
+
1170
+    /**
1171
+     * Returns the preview manager which can create preview images for a given file
1172
+     *
1173
+     * @return \OCP\IPreview
1174
+     */
1175
+    public function getPreviewManager() {
1176
+        return $this->query('PreviewManager');
1177
+    }
1178
+
1179
+    /**
1180
+     * Returns the tag manager which can get and set tags for different object types
1181
+     *
1182
+     * @see \OCP\ITagManager::load()
1183
+     * @return \OCP\ITagManager
1184
+     */
1185
+    public function getTagManager() {
1186
+        return $this->query('TagManager');
1187
+    }
1188
+
1189
+    /**
1190
+     * Returns the system-tag manager
1191
+     *
1192
+     * @return \OCP\SystemTag\ISystemTagManager
1193
+     *
1194
+     * @since 9.0.0
1195
+     */
1196
+    public function getSystemTagManager() {
1197
+        return $this->query('SystemTagManager');
1198
+    }
1199
+
1200
+    /**
1201
+     * Returns the system-tag object mapper
1202
+     *
1203
+     * @return \OCP\SystemTag\ISystemTagObjectMapper
1204
+     *
1205
+     * @since 9.0.0
1206
+     */
1207
+    public function getSystemTagObjectMapper() {
1208
+        return $this->query('SystemTagObjectMapper');
1209
+    }
1210
+
1211
+    /**
1212
+     * Returns the avatar manager, used for avatar functionality
1213
+     *
1214
+     * @return \OCP\IAvatarManager
1215
+     */
1216
+    public function getAvatarManager() {
1217
+        return $this->query('AvatarManager');
1218
+    }
1219
+
1220
+    /**
1221
+     * Returns the root folder of ownCloud's data directory
1222
+     *
1223
+     * @return \OCP\Files\IRootFolder
1224
+     */
1225
+    public function getRootFolder() {
1226
+        return $this->query('LazyRootFolder');
1227
+    }
1228
+
1229
+    /**
1230
+     * Returns the root folder of ownCloud's data directory
1231
+     * This is the lazy variant so this gets only initialized once it
1232
+     * is actually used.
1233
+     *
1234
+     * @return \OCP\Files\IRootFolder
1235
+     */
1236
+    public function getLazyRootFolder() {
1237
+        return $this->query('LazyRootFolder');
1238
+    }
1239
+
1240
+    /**
1241
+     * Returns a view to ownCloud's files folder
1242
+     *
1243
+     * @param string $userId user ID
1244
+     * @return \OCP\Files\Folder|null
1245
+     */
1246
+    public function getUserFolder($userId = null) {
1247
+        if ($userId === null) {
1248
+            $user = $this->getUserSession()->getUser();
1249
+            if (!$user) {
1250
+                return null;
1251
+            }
1252
+            $userId = $user->getUID();
1253
+        }
1254
+        $root = $this->getRootFolder();
1255
+        return $root->getUserFolder($userId);
1256
+    }
1257
+
1258
+    /**
1259
+     * Returns an app-specific view in ownClouds data directory
1260
+     *
1261
+     * @return \OCP\Files\Folder
1262
+     * @deprecated since 9.2.0 use IAppData
1263
+     */
1264
+    public function getAppFolder() {
1265
+        $dir = '/' . \OC_App::getCurrentApp();
1266
+        $root = $this->getRootFolder();
1267
+        if (!$root->nodeExists($dir)) {
1268
+            $folder = $root->newFolder($dir);
1269
+        } else {
1270
+            $folder = $root->get($dir);
1271
+        }
1272
+        return $folder;
1273
+    }
1274
+
1275
+    /**
1276
+     * @return \OC\User\Manager
1277
+     */
1278
+    public function getUserManager() {
1279
+        return $this->query('UserManager');
1280
+    }
1281
+
1282
+    /**
1283
+     * @return \OC\Group\Manager
1284
+     */
1285
+    public function getGroupManager() {
1286
+        return $this->query('GroupManager');
1287
+    }
1288
+
1289
+    /**
1290
+     * @return \OC\User\Session
1291
+     */
1292
+    public function getUserSession() {
1293
+        return $this->query('UserSession');
1294
+    }
1295
+
1296
+    /**
1297
+     * @return \OCP\ISession
1298
+     */
1299
+    public function getSession() {
1300
+        return $this->query('UserSession')->getSession();
1301
+    }
1302
+
1303
+    /**
1304
+     * @param \OCP\ISession $session
1305
+     */
1306
+    public function setSession(\OCP\ISession $session) {
1307
+        $this->query(SessionStorage::class)->setSession($session);
1308
+        $this->query('UserSession')->setSession($session);
1309
+        $this->query(Store::class)->setSession($session);
1310
+    }
1311
+
1312
+    /**
1313
+     * @return \OC\Authentication\TwoFactorAuth\Manager
1314
+     */
1315
+    public function getTwoFactorAuthManager() {
1316
+        return $this->query('\OC\Authentication\TwoFactorAuth\Manager');
1317
+    }
1318
+
1319
+    /**
1320
+     * @return \OC\NavigationManager
1321
+     */
1322
+    public function getNavigationManager() {
1323
+        return $this->query('NavigationManager');
1324
+    }
1325
+
1326
+    /**
1327
+     * @return \OCP\IConfig
1328
+     */
1329
+    public function getConfig() {
1330
+        return $this->query('AllConfig');
1331
+    }
1332
+
1333
+    /**
1334
+     * @return \OC\SystemConfig
1335
+     */
1336
+    public function getSystemConfig() {
1337
+        return $this->query('SystemConfig');
1338
+    }
1339
+
1340
+    /**
1341
+     * Returns the app config manager
1342
+     *
1343
+     * @return \OCP\IAppConfig
1344
+     */
1345
+    public function getAppConfig() {
1346
+        return $this->query('AppConfig');
1347
+    }
1348
+
1349
+    /**
1350
+     * @return \OCP\L10N\IFactory
1351
+     */
1352
+    public function getL10NFactory() {
1353
+        return $this->query('L10NFactory');
1354
+    }
1355
+
1356
+    /**
1357
+     * get an L10N instance
1358
+     *
1359
+     * @param string $app appid
1360
+     * @param string $lang
1361
+     * @return IL10N
1362
+     */
1363
+    public function getL10N($app, $lang = null) {
1364
+        return $this->getL10NFactory()->get($app, $lang);
1365
+    }
1366
+
1367
+    /**
1368
+     * @return \OCP\IURLGenerator
1369
+     */
1370
+    public function getURLGenerator() {
1371
+        return $this->query('URLGenerator');
1372
+    }
1373
+
1374
+    /**
1375
+     * @return \OCP\IHelper
1376
+     */
1377
+    public function getHelper() {
1378
+        return $this->query('AppHelper');
1379
+    }
1380
+
1381
+    /**
1382
+     * @return AppFetcher
1383
+     */
1384
+    public function getAppFetcher() {
1385
+        return $this->query(AppFetcher::class);
1386
+    }
1387
+
1388
+    /**
1389
+     * Returns an ICache instance. Since 8.1.0 it returns a fake cache. Use
1390
+     * getMemCacheFactory() instead.
1391
+     *
1392
+     * @return \OCP\ICache
1393
+     * @deprecated 8.1.0 use getMemCacheFactory to obtain a proper cache
1394
+     */
1395
+    public function getCache() {
1396
+        return $this->query('UserCache');
1397
+    }
1398
+
1399
+    /**
1400
+     * Returns an \OCP\CacheFactory instance
1401
+     *
1402
+     * @return \OCP\ICacheFactory
1403
+     */
1404
+    public function getMemCacheFactory() {
1405
+        return $this->query('MemCacheFactory');
1406
+    }
1407
+
1408
+    /**
1409
+     * Returns an \OC\RedisFactory instance
1410
+     *
1411
+     * @return \OC\RedisFactory
1412
+     */
1413
+    public function getGetRedisFactory() {
1414
+        return $this->query('RedisFactory');
1415
+    }
1416
+
1417
+
1418
+    /**
1419
+     * Returns the current session
1420
+     *
1421
+     * @return \OCP\IDBConnection
1422
+     */
1423
+    public function getDatabaseConnection() {
1424
+        return $this->query('DatabaseConnection');
1425
+    }
1426
+
1427
+    /**
1428
+     * Returns the activity manager
1429
+     *
1430
+     * @return \OCP\Activity\IManager
1431
+     */
1432
+    public function getActivityManager() {
1433
+        return $this->query('ActivityManager');
1434
+    }
1435
+
1436
+    /**
1437
+     * Returns an job list for controlling background jobs
1438
+     *
1439
+     * @return \OCP\BackgroundJob\IJobList
1440
+     */
1441
+    public function getJobList() {
1442
+        return $this->query('JobList');
1443
+    }
1444
+
1445
+    /**
1446
+     * Returns a logger instance
1447
+     *
1448
+     * @return \OCP\ILogger
1449
+     */
1450
+    public function getLogger() {
1451
+        return $this->query('Logger');
1452
+    }
1453
+
1454
+    /**
1455
+     * Returns a router for generating and matching urls
1456
+     *
1457
+     * @return \OCP\Route\IRouter
1458
+     */
1459
+    public function getRouter() {
1460
+        return $this->query('Router');
1461
+    }
1462
+
1463
+    /**
1464
+     * Returns a search instance
1465
+     *
1466
+     * @return \OCP\ISearch
1467
+     */
1468
+    public function getSearch() {
1469
+        return $this->query('Search');
1470
+    }
1471
+
1472
+    /**
1473
+     * Returns a SecureRandom instance
1474
+     *
1475
+     * @return \OCP\Security\ISecureRandom
1476
+     */
1477
+    public function getSecureRandom() {
1478
+        return $this->query('SecureRandom');
1479
+    }
1480
+
1481
+    /**
1482
+     * Returns a Crypto instance
1483
+     *
1484
+     * @return \OCP\Security\ICrypto
1485
+     */
1486
+    public function getCrypto() {
1487
+        return $this->query('Crypto');
1488
+    }
1489
+
1490
+    /**
1491
+     * Returns a Hasher instance
1492
+     *
1493
+     * @return \OCP\Security\IHasher
1494
+     */
1495
+    public function getHasher() {
1496
+        return $this->query('Hasher');
1497
+    }
1498
+
1499
+    /**
1500
+     * Returns a CredentialsManager instance
1501
+     *
1502
+     * @return \OCP\Security\ICredentialsManager
1503
+     */
1504
+    public function getCredentialsManager() {
1505
+        return $this->query('CredentialsManager');
1506
+    }
1507
+
1508
+    /**
1509
+     * Returns an instance of the HTTP helper class
1510
+     *
1511
+     * @deprecated Use getHTTPClientService()
1512
+     * @return \OC\HTTPHelper
1513
+     */
1514
+    public function getHTTPHelper() {
1515
+        return $this->query('HTTPHelper');
1516
+    }
1517
+
1518
+    /**
1519
+     * Get the certificate manager for the user
1520
+     *
1521
+     * @param string $userId (optional) if not specified the current loggedin user is used, use null to get the system certificate manager
1522
+     * @return \OCP\ICertificateManager | null if $uid is null and no user is logged in
1523
+     */
1524
+    public function getCertificateManager($userId = '') {
1525
+        if ($userId === '') {
1526
+            $userSession = $this->getUserSession();
1527
+            $user = $userSession->getUser();
1528
+            if (is_null($user)) {
1529
+                return null;
1530
+            }
1531
+            $userId = $user->getUID();
1532
+        }
1533
+        return new CertificateManager(
1534
+            $userId,
1535
+            new View(),
1536
+            $this->getConfig(),
1537
+            $this->getLogger(),
1538
+            $this->getSecureRandom()
1539
+        );
1540
+    }
1541
+
1542
+    /**
1543
+     * Returns an instance of the HTTP client service
1544
+     *
1545
+     * @return \OCP\Http\Client\IClientService
1546
+     */
1547
+    public function getHTTPClientService() {
1548
+        return $this->query('HttpClientService');
1549
+    }
1550
+
1551
+    /**
1552
+     * Create a new event source
1553
+     *
1554
+     * @return \OCP\IEventSource
1555
+     */
1556
+    public function createEventSource() {
1557
+        return new \OC_EventSource();
1558
+    }
1559
+
1560
+    /**
1561
+     * Get the active event logger
1562
+     *
1563
+     * The returned logger only logs data when debug mode is enabled
1564
+     *
1565
+     * @return \OCP\Diagnostics\IEventLogger
1566
+     */
1567
+    public function getEventLogger() {
1568
+        return $this->query('EventLogger');
1569
+    }
1570
+
1571
+    /**
1572
+     * Get the active query logger
1573
+     *
1574
+     * The returned logger only logs data when debug mode is enabled
1575
+     *
1576
+     * @return \OCP\Diagnostics\IQueryLogger
1577
+     */
1578
+    public function getQueryLogger() {
1579
+        return $this->query('QueryLogger');
1580
+    }
1581
+
1582
+    /**
1583
+     * Get the manager for temporary files and folders
1584
+     *
1585
+     * @return \OCP\ITempManager
1586
+     */
1587
+    public function getTempManager() {
1588
+        return $this->query('TempManager');
1589
+    }
1590
+
1591
+    /**
1592
+     * Get the app manager
1593
+     *
1594
+     * @return \OCP\App\IAppManager
1595
+     */
1596
+    public function getAppManager() {
1597
+        return $this->query('AppManager');
1598
+    }
1599
+
1600
+    /**
1601
+     * Creates a new mailer
1602
+     *
1603
+     * @return \OCP\Mail\IMailer
1604
+     */
1605
+    public function getMailer() {
1606
+        return $this->query('Mailer');
1607
+    }
1608
+
1609
+    /**
1610
+     * Get the webroot
1611
+     *
1612
+     * @return string
1613
+     */
1614
+    public function getWebRoot() {
1615
+        return $this->webRoot;
1616
+    }
1617
+
1618
+    /**
1619
+     * @return \OC\OCSClient
1620
+     */
1621
+    public function getOcsClient() {
1622
+        return $this->query('OcsClient');
1623
+    }
1624
+
1625
+    /**
1626
+     * @return \OCP\IDateTimeZone
1627
+     */
1628
+    public function getDateTimeZone() {
1629
+        return $this->query('DateTimeZone');
1630
+    }
1631
+
1632
+    /**
1633
+     * @return \OCP\IDateTimeFormatter
1634
+     */
1635
+    public function getDateTimeFormatter() {
1636
+        return $this->query('DateTimeFormatter');
1637
+    }
1638
+
1639
+    /**
1640
+     * @return \OCP\Files\Config\IMountProviderCollection
1641
+     */
1642
+    public function getMountProviderCollection() {
1643
+        return $this->query('MountConfigManager');
1644
+    }
1645
+
1646
+    /**
1647
+     * Get the IniWrapper
1648
+     *
1649
+     * @return IniGetWrapper
1650
+     */
1651
+    public function getIniWrapper() {
1652
+        return $this->query('IniWrapper');
1653
+    }
1654
+
1655
+    /**
1656
+     * @return \OCP\Command\IBus
1657
+     */
1658
+    public function getCommandBus() {
1659
+        return $this->query('AsyncCommandBus');
1660
+    }
1661
+
1662
+    /**
1663
+     * Get the trusted domain helper
1664
+     *
1665
+     * @return TrustedDomainHelper
1666
+     */
1667
+    public function getTrustedDomainHelper() {
1668
+        return $this->query('TrustedDomainHelper');
1669
+    }
1670
+
1671
+    /**
1672
+     * Get the locking provider
1673
+     *
1674
+     * @return \OCP\Lock\ILockingProvider
1675
+     * @since 8.1.0
1676
+     */
1677
+    public function getLockingProvider() {
1678
+        return $this->query('LockingProvider');
1679
+    }
1680
+
1681
+    /**
1682
+     * @return \OCP\Files\Mount\IMountManager
1683
+     **/
1684
+    function getMountManager() {
1685
+        return $this->query('MountManager');
1686
+    }
1687
+
1688
+    /** @return \OCP\Files\Config\IUserMountCache */
1689
+    function getUserMountCache() {
1690
+        return $this->query('UserMountCache');
1691
+    }
1692
+
1693
+    /**
1694
+     * Get the MimeTypeDetector
1695
+     *
1696
+     * @return \OCP\Files\IMimeTypeDetector
1697
+     */
1698
+    public function getMimeTypeDetector() {
1699
+        return $this->query('MimeTypeDetector');
1700
+    }
1701
+
1702
+    /**
1703
+     * Get the MimeTypeLoader
1704
+     *
1705
+     * @return \OCP\Files\IMimeTypeLoader
1706
+     */
1707
+    public function getMimeTypeLoader() {
1708
+        return $this->query('MimeTypeLoader');
1709
+    }
1710
+
1711
+    /**
1712
+     * Get the manager of all the capabilities
1713
+     *
1714
+     * @return \OC\CapabilitiesManager
1715
+     */
1716
+    public function getCapabilitiesManager() {
1717
+        return $this->query('CapabilitiesManager');
1718
+    }
1719
+
1720
+    /**
1721
+     * Get the EventDispatcher
1722
+     *
1723
+     * @return EventDispatcherInterface
1724
+     * @since 8.2.0
1725
+     */
1726
+    public function getEventDispatcher() {
1727
+        return $this->query('EventDispatcher');
1728
+    }
1729
+
1730
+    /**
1731
+     * Get the Notification Manager
1732
+     *
1733
+     * @return \OCP\Notification\IManager
1734
+     * @since 8.2.0
1735
+     */
1736
+    public function getNotificationManager() {
1737
+        return $this->query('NotificationManager');
1738
+    }
1739
+
1740
+    /**
1741
+     * @return \OCP\Comments\ICommentsManager
1742
+     */
1743
+    public function getCommentsManager() {
1744
+        return $this->query('CommentsManager');
1745
+    }
1746
+
1747
+    /**
1748
+     * @return \OCA\Theming\ThemingDefaults
1749
+     */
1750
+    public function getThemingDefaults() {
1751
+        return $this->query('ThemingDefaults');
1752
+    }
1753
+
1754
+    /**
1755
+     * @return \OC\IntegrityCheck\Checker
1756
+     */
1757
+    public function getIntegrityCodeChecker() {
1758
+        return $this->query('IntegrityCodeChecker');
1759
+    }
1760
+
1761
+    /**
1762
+     * @return \OC\Session\CryptoWrapper
1763
+     */
1764
+    public function getSessionCryptoWrapper() {
1765
+        return $this->query('CryptoWrapper');
1766
+    }
1767
+
1768
+    /**
1769
+     * @return CsrfTokenManager
1770
+     */
1771
+    public function getCsrfTokenManager() {
1772
+        return $this->query('CsrfTokenManager');
1773
+    }
1774
+
1775
+    /**
1776
+     * @return Throttler
1777
+     */
1778
+    public function getBruteForceThrottler() {
1779
+        return $this->query('Throttler');
1780
+    }
1781
+
1782
+    /**
1783
+     * @return IContentSecurityPolicyManager
1784
+     */
1785
+    public function getContentSecurityPolicyManager() {
1786
+        return $this->query('ContentSecurityPolicyManager');
1787
+    }
1788
+
1789
+    /**
1790
+     * @return ContentSecurityPolicyNonceManager
1791
+     */
1792
+    public function getContentSecurityPolicyNonceManager() {
1793
+        return $this->query('ContentSecurityPolicyNonceManager');
1794
+    }
1795
+
1796
+    /**
1797
+     * Not a public API as of 8.2, wait for 9.0
1798
+     *
1799
+     * @return \OCA\Files_External\Service\BackendService
1800
+     */
1801
+    public function getStoragesBackendService() {
1802
+        return $this->query('OCA\\Files_External\\Service\\BackendService');
1803
+    }
1804
+
1805
+    /**
1806
+     * Not a public API as of 8.2, wait for 9.0
1807
+     *
1808
+     * @return \OCA\Files_External\Service\GlobalStoragesService
1809
+     */
1810
+    public function getGlobalStoragesService() {
1811
+        return $this->query('OCA\\Files_External\\Service\\GlobalStoragesService');
1812
+    }
1813
+
1814
+    /**
1815
+     * Not a public API as of 8.2, wait for 9.0
1816
+     *
1817
+     * @return \OCA\Files_External\Service\UserGlobalStoragesService
1818
+     */
1819
+    public function getUserGlobalStoragesService() {
1820
+        return $this->query('OCA\\Files_External\\Service\\UserGlobalStoragesService');
1821
+    }
1822
+
1823
+    /**
1824
+     * Not a public API as of 8.2, wait for 9.0
1825
+     *
1826
+     * @return \OCA\Files_External\Service\UserStoragesService
1827
+     */
1828
+    public function getUserStoragesService() {
1829
+        return $this->query('OCA\\Files_External\\Service\\UserStoragesService');
1830
+    }
1831
+
1832
+    /**
1833
+     * @return \OCP\Share\IManager
1834
+     */
1835
+    public function getShareManager() {
1836
+        return $this->query('ShareManager');
1837
+    }
1838
+
1839
+    /**
1840
+     * @return \OCP\Collaboration\Collaborators\ISearch
1841
+     */
1842
+    public function getCollaboratorSearch() {
1843
+        return $this->query('CollaboratorSearch');
1844
+    }
1845
+
1846
+    /**
1847
+     * @return \OCP\Collaboration\AutoComplete\IManager
1848
+     */
1849
+    public function getAutoCompleteManager(){
1850
+        return $this->query(IManager::class);
1851
+    }
1852
+
1853
+    /**
1854
+     * Returns the LDAP Provider
1855
+     *
1856
+     * @return \OCP\LDAP\ILDAPProvider
1857
+     */
1858
+    public function getLDAPProvider() {
1859
+        return $this->query('LDAPProvider');
1860
+    }
1861
+
1862
+    /**
1863
+     * @return \OCP\Settings\IManager
1864
+     */
1865
+    public function getSettingsManager() {
1866
+        return $this->query('SettingsManager');
1867
+    }
1868
+
1869
+    /**
1870
+     * @return \OCP\Files\IAppData
1871
+     */
1872
+    public function getAppDataDir($app) {
1873
+        /** @var \OC\Files\AppData\Factory $factory */
1874
+        $factory = $this->query(\OC\Files\AppData\Factory::class);
1875
+        return $factory->get($app);
1876
+    }
1877
+
1878
+    /**
1879
+     * @return \OCP\Lockdown\ILockdownManager
1880
+     */
1881
+    public function getLockdownManager() {
1882
+        return $this->query('LockdownManager');
1883
+    }
1884
+
1885
+    /**
1886
+     * @return \OCP\Federation\ICloudIdManager
1887
+     */
1888
+    public function getCloudIdManager() {
1889
+        return $this->query(ICloudIdManager::class);
1890
+    }
1891 1891
 }
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.