Passed
Push — master ( 2b3684...9979b6 )
by Morris
13:31 queued 10s
created
apps/workflowengine/lib/Manager.php 1 patch
Indentation   +657 added lines, -657 removed lines patch added patch discarded remove patch
@@ -62,661 +62,661 @@
 block discarded – undo
62 62
 
63 63
 class Manager implements IManager {
64 64
 
65
-	/** @var IStorage */
66
-	protected $storage;
67
-
68
-	/** @var string */
69
-	protected $path;
70
-
71
-	/** @var object */
72
-	protected $entity;
73
-
74
-	/** @var array[] */
75
-	protected $operations = [];
76
-
77
-	/** @var array[] */
78
-	protected $checks = [];
79
-
80
-	/** @var IDBConnection */
81
-	protected $connection;
82
-
83
-	/** @var IServerContainer|\OC\Server */
84
-	protected $container;
85
-
86
-	/** @var IL10N */
87
-	protected $l;
88
-
89
-	/** @var LegacyDispatcher */
90
-	protected $legacyEventDispatcher;
91
-
92
-	/** @var IEntity[] */
93
-	protected $registeredEntities = [];
94
-
95
-	/** @var IOperation[] */
96
-	protected $registeredOperators = [];
97
-
98
-	/** @var ICheck[] */
99
-	protected $registeredChecks = [];
100
-
101
-	/** @var ILogger */
102
-	protected $logger;
103
-
104
-	/** @var CappedMemoryCache */
105
-	protected $operationsByScope = [];
106
-
107
-	/** @var IUserSession */
108
-	protected $session;
109
-
110
-	/** @var IEventDispatcher */
111
-	private $dispatcher;
112
-
113
-	/** @var IConfig */
114
-	private $config;
115
-
116
-	public function __construct(
117
-		IDBConnection $connection,
118
-		IServerContainer $container,
119
-		IL10N $l,
120
-		LegacyDispatcher $eventDispatcher,
121
-		ILogger $logger,
122
-		IUserSession $session,
123
-		IEventDispatcher $dispatcher,
124
-		IConfig $config
125
-	) {
126
-		$this->connection = $connection;
127
-		$this->container = $container;
128
-		$this->l = $l;
129
-		$this->legacyEventDispatcher = $eventDispatcher;
130
-		$this->logger = $logger;
131
-		$this->operationsByScope = new CappedMemoryCache(64);
132
-		$this->session = $session;
133
-		$this->dispatcher = $dispatcher;
134
-		$this->config = $config;
135
-	}
136
-
137
-	public function getRuleMatcher(): IRuleMatcher {
138
-		return new RuleMatcher(
139
-			$this->session,
140
-			$this->container,
141
-			$this->l,
142
-			$this,
143
-			$this->container->query(Logger::class)
144
-		);
145
-	}
146
-
147
-	public function getAllConfiguredEvents() {
148
-		$query = $this->connection->getQueryBuilder();
149
-
150
-		$query->select('class', 'entity', $query->expr()->castColumn('events', IQueryBuilder::PARAM_STR))
151
-			->from('flow_operations')
152
-			->where($query->expr()->neq('events', $query->createNamedParameter('[]'), IQueryBuilder::PARAM_STR))
153
-			->groupBy('class', 'entity', $query->expr()->castColumn('events', IQueryBuilder::PARAM_STR));
154
-
155
-		$result = $query->execute();
156
-		$operations = [];
157
-		while ($row = $result->fetch()) {
158
-			$eventNames = \json_decode($row['events']);
159
-
160
-			$operation = $row['class'];
161
-			$entity = $row['entity'];
162
-
163
-			$operations[$operation] = $operations[$row['class']] ?? [];
164
-			$operations[$operation][$entity] = $operations[$operation][$entity] ?? [];
165
-
166
-			$operations[$operation][$entity] = array_unique(array_merge($operations[$operation][$entity], $eventNames ?? []));
167
-		}
168
-		$result->closeCursor();
169
-
170
-		return $operations;
171
-	}
172
-
173
-	/**
174
-	 * @param string $operationClass
175
-	 * @return ScopeContext[]
176
-	 */
177
-	public function getAllConfiguredScopesForOperation(string $operationClass): array {
178
-		static $scopesByOperation = [];
179
-		if (isset($scopesByOperation[$operationClass])) {
180
-			return $scopesByOperation[$operationClass];
181
-		}
182
-
183
-		$query = $this->connection->getQueryBuilder();
184
-
185
-		$query->selectDistinct('s.type')
186
-			->addSelect('s.value')
187
-			->from('flow_operations', 'o')
188
-			->leftJoin('o', 'flow_operations_scope', 's', $query->expr()->eq('o.id', 's.operation_id'))
189
-			->where($query->expr()->eq('o.class', $query->createParameter('operationClass')));
190
-
191
-		$query->setParameters(['operationClass' => $operationClass]);
192
-		$result = $query->execute();
193
-
194
-		$scopesByOperation[$operationClass] = [];
195
-		while ($row = $result->fetch()) {
196
-			$scope = new ScopeContext($row['type'], $row['value']);
197
-			$scopesByOperation[$operationClass][$scope->getHash()] = $scope;
198
-		}
199
-
200
-		return $scopesByOperation[$operationClass];
201
-	}
202
-
203
-	public function getAllOperations(ScopeContext $scopeContext): array {
204
-		if (isset($this->operations[$scopeContext->getHash()])) {
205
-			return $this->operations[$scopeContext->getHash()];
206
-		}
207
-
208
-		$query = $this->connection->getQueryBuilder();
209
-
210
-		$query->select('o.*')
211
-			->selectAlias('s.type', 'scope_type')
212
-			->selectAlias('s.value', 'scope_actor_id')
213
-			->from('flow_operations', 'o')
214
-			->leftJoin('o', 'flow_operations_scope', 's', $query->expr()->eq('o.id', 's.operation_id'))
215
-			->where($query->expr()->eq('s.type', $query->createParameter('scope')));
216
-
217
-		if ($scopeContext->getScope() === IManager::SCOPE_USER) {
218
-			$query->andWhere($query->expr()->eq('s.value', $query->createParameter('scopeId')));
219
-		}
220
-
221
-		$query->setParameters(['scope' => $scopeContext->getScope(), 'scopeId' => $scopeContext->getScopeId()]);
222
-		$result = $query->execute();
223
-
224
-		$this->operations[$scopeContext->getHash()] = [];
225
-		while ($row = $result->fetch()) {
226
-			if (!isset($this->operations[$scopeContext->getHash()][$row['class']])) {
227
-				$this->operations[$scopeContext->getHash()][$row['class']] = [];
228
-			}
229
-			$this->operations[$scopeContext->getHash()][$row['class']][] = $row;
230
-		}
231
-
232
-		return $this->operations[$scopeContext->getHash()];
233
-	}
234
-
235
-	public function getOperations(string $class, ScopeContext $scopeContext): array {
236
-		if (!isset($this->operations[$scopeContext->getHash()])) {
237
-			$this->getAllOperations($scopeContext);
238
-		}
239
-		return $this->operations[$scopeContext->getHash()][$class] ?? [];
240
-	}
241
-
242
-	/**
243
-	 * @param int $id
244
-	 * @return array
245
-	 * @throws \UnexpectedValueException
246
-	 */
247
-	protected function getOperation($id) {
248
-		$query = $this->connection->getQueryBuilder();
249
-		$query->select('*')
250
-			->from('flow_operations')
251
-			->where($query->expr()->eq('id', $query->createNamedParameter($id)));
252
-		$result = $query->execute();
253
-		$row = $result->fetch();
254
-		$result->closeCursor();
255
-
256
-		if ($row) {
257
-			return $row;
258
-		}
259
-
260
-		throw new \UnexpectedValueException($this->l->t('Operation #%s does not exist', [$id]));
261
-	}
262
-
263
-	protected function insertOperation(
264
-		string $class,
265
-		string $name,
266
-		array $checkIds,
267
-		string $operation,
268
-		string $entity,
269
-		array $events
270
-	): int {
271
-		$query = $this->connection->getQueryBuilder();
272
-		$query->insert('flow_operations')
273
-			->values([
274
-				'class' => $query->createNamedParameter($class),
275
-				'name' => $query->createNamedParameter($name),
276
-				'checks' => $query->createNamedParameter(json_encode(array_unique($checkIds))),
277
-				'operation' => $query->createNamedParameter($operation),
278
-				'entity' => $query->createNamedParameter($entity),
279
-				'events' => $query->createNamedParameter(json_encode($events))
280
-			]);
281
-		$query->execute();
282
-
283
-		return $query->getLastInsertId();
284
-	}
285
-
286
-	/**
287
-	 * @param string $class
288
-	 * @param string $name
289
-	 * @param array[] $checks
290
-	 * @param string $operation
291
-	 * @return array The added operation
292
-	 * @throws \UnexpectedValueException
293
-	 * @throws DBALException
294
-	 */
295
-	public function addOperation(
296
-		string $class,
297
-		string $name,
298
-		array $checks,
299
-		string $operation,
300
-		ScopeContext $scope,
301
-		string $entity,
302
-		array $events
303
-	) {
304
-		$this->validateOperation($class, $name, $checks, $operation, $entity, $events);
305
-
306
-		$this->connection->beginTransaction();
307
-
308
-		try {
309
-			$checkIds = [];
310
-			foreach ($checks as $check) {
311
-				$checkIds[] = $this->addCheck($check['class'], $check['operator'], $check['value']);
312
-			}
313
-
314
-			$id = $this->insertOperation($class, $name, $checkIds, $operation, $entity, $events);
315
-			$this->addScope($id, $scope);
316
-
317
-			$this->connection->commit();
318
-		} catch (DBALException $e) {
319
-			$this->connection->rollBack();
320
-			throw $e;
321
-		}
322
-
323
-		return $this->getOperation($id);
324
-	}
325
-
326
-	protected function canModify(int $id, ScopeContext $scopeContext):bool {
327
-		if (isset($this->operationsByScope[$scopeContext->getHash()])) {
328
-			return in_array($id, $this->operationsByScope[$scopeContext->getHash()], true);
329
-		}
330
-
331
-		$qb = $this->connection->getQueryBuilder();
332
-		$qb = $qb->select('o.id')
333
-			->from('flow_operations', 'o')
334
-			->leftJoin('o', 'flow_operations_scope', 's', $qb->expr()->eq('o.id', 's.operation_id'))
335
-			->where($qb->expr()->eq('s.type', $qb->createParameter('scope')));
336
-
337
-		if ($scopeContext->getScope() !== IManager::SCOPE_ADMIN) {
338
-			$qb->where($qb->expr()->eq('s.value', $qb->createParameter('scopeId')));
339
-		}
340
-
341
-		$qb->setParameters(['scope' => $scopeContext->getScope(), 'scopeId' => $scopeContext->getScopeId()]);
342
-		$result = $qb->execute();
343
-
344
-		$this->operationsByScope[$scopeContext->getHash()] = [];
345
-		while ($opId = $result->fetchColumn(0)) {
346
-			$this->operationsByScope[$scopeContext->getHash()][] = (int)$opId;
347
-		}
348
-		$result->closeCursor();
349
-
350
-		return in_array($id, $this->operationsByScope[$scopeContext->getHash()], true);
351
-	}
352
-
353
-	/**
354
-	 * @param int $id
355
-	 * @param string $name
356
-	 * @param array[] $checks
357
-	 * @param string $operation
358
-	 * @return array The updated operation
359
-	 * @throws \UnexpectedValueException
360
-	 * @throws \DomainException
361
-	 * @throws DBALException
362
-	 */
363
-	public function updateOperation(
364
-		int $id,
365
-		string $name,
366
-		array $checks,
367
-		string $operation,
368
-		ScopeContext $scopeContext,
369
-		string $entity,
370
-		array $events
371
-	): array {
372
-		if (!$this->canModify($id, $scopeContext)) {
373
-			throw new \DomainException('Target operation not within scope');
374
-		};
375
-		$row = $this->getOperation($id);
376
-		$this->validateOperation($row['class'], $name, $checks, $operation, $entity, $events);
377
-
378
-		$checkIds = [];
379
-		try {
380
-			$this->connection->beginTransaction();
381
-			foreach ($checks as $check) {
382
-				$checkIds[] = $this->addCheck($check['class'], $check['operator'], $check['value']);
383
-			}
384
-
385
-			$query = $this->connection->getQueryBuilder();
386
-			$query->update('flow_operations')
387
-				->set('name', $query->createNamedParameter($name))
388
-				->set('checks', $query->createNamedParameter(json_encode(array_unique($checkIds))))
389
-				->set('operation', $query->createNamedParameter($operation))
390
-				->set('entity', $query->createNamedParameter($entity))
391
-				->set('events', $query->createNamedParameter(json_encode($events)))
392
-				->where($query->expr()->eq('id', $query->createNamedParameter($id)));
393
-			$query->execute();
394
-			$this->connection->commit();
395
-		} catch (DBALException $e) {
396
-			$this->connection->rollBack();
397
-			throw $e;
398
-		}
399
-		unset($this->operations[$scopeContext->getHash()]);
400
-
401
-		return $this->getOperation($id);
402
-	}
403
-
404
-	/**
405
-	 * @param int $id
406
-	 * @return bool
407
-	 * @throws \UnexpectedValueException
408
-	 * @throws DBALException
409
-	 * @throws \DomainException
410
-	 */
411
-	public function deleteOperation($id, ScopeContext $scopeContext) {
412
-		if (!$this->canModify($id, $scopeContext)) {
413
-			throw new \DomainException('Target operation not within scope');
414
-		};
415
-		$query = $this->connection->getQueryBuilder();
416
-		try {
417
-			$this->connection->beginTransaction();
418
-			$result = (bool)$query->delete('flow_operations')
419
-				->where($query->expr()->eq('id', $query->createNamedParameter($id)))
420
-				->execute();
421
-			if ($result) {
422
-				$qb = $this->connection->getQueryBuilder();
423
-				$result &= (bool)$qb->delete('flow_operations_scope')
424
-					->where($qb->expr()->eq('operation_id', $qb->createNamedParameter($id)))
425
-					->execute();
426
-			}
427
-			$this->connection->commit();
428
-		} catch (DBALException $e) {
429
-			$this->connection->rollBack();
430
-			throw $e;
431
-		}
432
-
433
-		if (isset($this->operations[$scopeContext->getHash()])) {
434
-			unset($this->operations[$scopeContext->getHash()]);
435
-		}
436
-
437
-		return $result;
438
-	}
439
-
440
-	protected function validateEvents(string $entity, array $events, IOperation $operation) {
441
-		try {
442
-			/** @var IEntity $instance */
443
-			$instance = $this->container->query($entity);
444
-		} catch (QueryException $e) {
445
-			throw new \UnexpectedValueException($this->l->t('Entity %s does not exist', [$entity]));
446
-		}
447
-
448
-		if (!$instance instanceof IEntity) {
449
-			throw new \UnexpectedValueException($this->l->t('Entity %s is invalid', [$entity]));
450
-		}
451
-
452
-		if (empty($events)) {
453
-			if (!$operation instanceof IComplexOperation) {
454
-				throw new \UnexpectedValueException($this->l->t('No events are chosen.'));
455
-			}
456
-			return;
457
-		}
458
-
459
-		$availableEvents = [];
460
-		foreach ($instance->getEvents() as $event) {
461
-			/** @var IEntityEvent $event */
462
-			$availableEvents[] = $event->getEventName();
463
-		}
464
-
465
-		$diff = array_diff($events, $availableEvents);
466
-		if (!empty($diff)) {
467
-			throw new \UnexpectedValueException($this->l->t('Entity %s has no event %s', [$entity, array_shift($diff)]));
468
-		}
469
-	}
470
-
471
-	/**
472
-	 * @param string $class
473
-	 * @param string $name
474
-	 * @param array[] $checks
475
-	 * @param string $operation
476
-	 * @throws \UnexpectedValueException
477
-	 */
478
-	public function validateOperation($class, $name, array $checks, $operation, string $entity, array $events) {
479
-		try {
480
-			/** @var IOperation $instance */
481
-			$instance = $this->container->query($class);
482
-		} catch (QueryException $e) {
483
-			throw new \UnexpectedValueException($this->l->t('Operation %s does not exist', [$class]));
484
-		}
485
-
486
-		if (!($instance instanceof IOperation)) {
487
-			throw new \UnexpectedValueException($this->l->t('Operation %s is invalid', [$class]));
488
-		}
489
-
490
-		$this->validateEvents($entity, $events, $instance);
491
-
492
-		if (count($checks) === 0) {
493
-			throw new \UnexpectedValueException($this->l->t('At least one check needs to be provided'));
494
-		}
495
-		$instance->validateOperation($name, $checks, $operation);
496
-
497
-		foreach ($checks as $check) {
498
-			if (!is_string($check['class'])) {
499
-				throw new \UnexpectedValueException($this->l->t('Invalid check provided'));
500
-			}
501
-
502
-			try {
503
-				/** @var ICheck $instance */
504
-				$instance = $this->container->query($check['class']);
505
-			} catch (QueryException $e) {
506
-				throw new \UnexpectedValueException($this->l->t('Check %s does not exist', [$class]));
507
-			}
508
-
509
-			if (!($instance instanceof ICheck)) {
510
-				throw new \UnexpectedValueException($this->l->t('Check %s is invalid', [$class]));
511
-			}
512
-
513
-			if (!empty($instance->supportedEntities())
514
-				&& !in_array($entity, $instance->supportedEntities())
515
-			) {
516
-				throw new \UnexpectedValueException($this->l->t('Check %s is not allowed with this entity', [$class]));
517
-			}
518
-
519
-			$instance->validateCheck($check['operator'], $check['value']);
520
-		}
521
-	}
522
-
523
-	/**
524
-	 * @param int[] $checkIds
525
-	 * @return array[]
526
-	 */
527
-	public function getChecks(array $checkIds) {
528
-		$checkIds = array_map('intval', $checkIds);
529
-
530
-		$checks = [];
531
-		foreach ($checkIds as $i => $checkId) {
532
-			if (isset($this->checks[$checkId])) {
533
-				$checks[$checkId] = $this->checks[$checkId];
534
-				unset($checkIds[$i]);
535
-			}
536
-		}
537
-
538
-		if (empty($checkIds)) {
539
-			return $checks;
540
-		}
541
-
542
-		$query = $this->connection->getQueryBuilder();
543
-		$query->select('*')
544
-			->from('flow_checks')
545
-			->where($query->expr()->in('id', $query->createNamedParameter($checkIds, IQueryBuilder::PARAM_INT_ARRAY)));
546
-		$result = $query->execute();
547
-
548
-		while ($row = $result->fetch()) {
549
-			$this->checks[(int) $row['id']] = $row;
550
-			$checks[(int) $row['id']] = $row;
551
-		}
552
-		$result->closeCursor();
553
-
554
-		$checkIds = array_diff($checkIds, array_keys($checks));
555
-
556
-		if (!empty($checkIds)) {
557
-			$missingCheck = array_pop($checkIds);
558
-			throw new \UnexpectedValueException($this->l->t('Check #%s does not exist', $missingCheck));
559
-		}
560
-
561
-		return $checks;
562
-	}
563
-
564
-	/**
565
-	 * @param string $class
566
-	 * @param string $operator
567
-	 * @param string $value
568
-	 * @return int Check unique ID
569
-	 */
570
-	protected function addCheck($class, $operator, $value) {
571
-		$hash = md5($class . '::' . $operator . '::' . $value);
572
-
573
-		$query = $this->connection->getQueryBuilder();
574
-		$query->select('id')
575
-			->from('flow_checks')
576
-			->where($query->expr()->eq('hash', $query->createNamedParameter($hash)));
577
-		$result = $query->execute();
578
-
579
-		if ($row = $result->fetch()) {
580
-			$result->closeCursor();
581
-			return (int) $row['id'];
582
-		}
583
-
584
-		$query = $this->connection->getQueryBuilder();
585
-		$query->insert('flow_checks')
586
-			->values([
587
-				'class' => $query->createNamedParameter($class),
588
-				'operator' => $query->createNamedParameter($operator),
589
-				'value' => $query->createNamedParameter($value),
590
-				'hash' => $query->createNamedParameter($hash),
591
-			]);
592
-		$query->execute();
593
-
594
-		return $query->getLastInsertId();
595
-	}
596
-
597
-	protected function addScope(int $operationId, ScopeContext $scope): void {
598
-		$query = $this->connection->getQueryBuilder();
599
-
600
-		$insertQuery = $query->insert('flow_operations_scope');
601
-		$insertQuery->values([
602
-			'operation_id' => $query->createNamedParameter($operationId),
603
-			'type' => $query->createNamedParameter($scope->getScope()),
604
-			'value' => $query->createNamedParameter($scope->getScopeId()),
605
-		]);
606
-		$insertQuery->execute();
607
-	}
608
-
609
-	public function formatOperation(array $operation): array {
610
-		$checkIds = json_decode($operation['checks'], true);
611
-		$checks = $this->getChecks($checkIds);
612
-
613
-		$operation['checks'] = [];
614
-		foreach ($checks as $check) {
615
-			// Remove internal values
616
-			unset($check['id']);
617
-			unset($check['hash']);
618
-
619
-			$operation['checks'][] = $check;
620
-		}
621
-		$operation['events'] = json_decode($operation['events'], true) ?? [];
622
-
623
-
624
-		return $operation;
625
-	}
626
-
627
-	/**
628
-	 * @return IEntity[]
629
-	 */
630
-	public function getEntitiesList(): array {
631
-		$this->dispatcher->dispatchTyped(new RegisterEntitiesEvent($this));
632
-		$this->legacyEventDispatcher->dispatch(IManager::EVENT_NAME_REG_ENTITY, new GenericEvent($this));
633
-
634
-		return array_values(array_merge($this->getBuildInEntities(), $this->registeredEntities));
635
-	}
636
-
637
-	/**
638
-	 * @return IOperation[]
639
-	 */
640
-	public function getOperatorList(): array {
641
-		$this->dispatcher->dispatchTyped(new RegisterOperationsEvent($this));
642
-		$this->legacyEventDispatcher->dispatch(IManager::EVENT_NAME_REG_OPERATION, new GenericEvent($this));
643
-
644
-		return array_merge($this->getBuildInOperators(), $this->registeredOperators);
645
-	}
646
-
647
-	/**
648
-	 * @return ICheck[]
649
-	 */
650
-	public function getCheckList(): array {
651
-		$this->dispatcher->dispatchTyped(new RegisterChecksEvent($this));
652
-		$this->legacyEventDispatcher->dispatch(IManager::EVENT_NAME_REG_CHECK, new GenericEvent($this));
653
-
654
-		return array_merge($this->getBuildInChecks(), $this->registeredChecks);
655
-	}
656
-
657
-	public function registerEntity(IEntity $entity): void {
658
-		$this->registeredEntities[get_class($entity)] = $entity;
659
-	}
660
-
661
-	public function registerOperation(IOperation $operator): void {
662
-		$this->registeredOperators[get_class($operator)] = $operator;
663
-	}
664
-
665
-	public function registerCheck(ICheck $check): void {
666
-		$this->registeredChecks[get_class($check)] = $check;
667
-	}
668
-
669
-	/**
670
-	 * @return IEntity[]
671
-	 */
672
-	protected function getBuildInEntities(): array {
673
-		try {
674
-			return [
675
-				File::class => $this->container->query(File::class),
676
-			];
677
-		} catch (QueryException $e) {
678
-			$this->logger->logException($e);
679
-			return [];
680
-		}
681
-	}
682
-
683
-	/**
684
-	 * @return IOperation[]
685
-	 */
686
-	protected function getBuildInOperators(): array {
687
-		try {
688
-			return [
689
-				// None yet
690
-			];
691
-		} catch (QueryException $e) {
692
-			$this->logger->logException($e);
693
-			return [];
694
-		}
695
-	}
696
-
697
-	/**
698
-	 * @return ICheck[]
699
-	 */
700
-	protected function getBuildInChecks(): array {
701
-		try {
702
-			return [
703
-				$this->container->query(FileMimeType::class),
704
-				$this->container->query(FileName::class),
705
-				$this->container->query(FileSize::class),
706
-				$this->container->query(FileSystemTags::class),
707
-				$this->container->query(RequestRemoteAddress::class),
708
-				$this->container->query(RequestTime::class),
709
-				$this->container->query(RequestURL::class),
710
-				$this->container->query(RequestUserAgent::class),
711
-				$this->container->query(UserGroupMembership::class),
712
-			];
713
-		} catch (QueryException $e) {
714
-			$this->logger->logException($e);
715
-			return [];
716
-		}
717
-	}
718
-
719
-	public function isUserScopeEnabled(): bool {
720
-		return $this->config->getAppValue(Application::APP_ID, 'user_scope_disabled', 'no') === 'no';
721
-	}
65
+    /** @var IStorage */
66
+    protected $storage;
67
+
68
+    /** @var string */
69
+    protected $path;
70
+
71
+    /** @var object */
72
+    protected $entity;
73
+
74
+    /** @var array[] */
75
+    protected $operations = [];
76
+
77
+    /** @var array[] */
78
+    protected $checks = [];
79
+
80
+    /** @var IDBConnection */
81
+    protected $connection;
82
+
83
+    /** @var IServerContainer|\OC\Server */
84
+    protected $container;
85
+
86
+    /** @var IL10N */
87
+    protected $l;
88
+
89
+    /** @var LegacyDispatcher */
90
+    protected $legacyEventDispatcher;
91
+
92
+    /** @var IEntity[] */
93
+    protected $registeredEntities = [];
94
+
95
+    /** @var IOperation[] */
96
+    protected $registeredOperators = [];
97
+
98
+    /** @var ICheck[] */
99
+    protected $registeredChecks = [];
100
+
101
+    /** @var ILogger */
102
+    protected $logger;
103
+
104
+    /** @var CappedMemoryCache */
105
+    protected $operationsByScope = [];
106
+
107
+    /** @var IUserSession */
108
+    protected $session;
109
+
110
+    /** @var IEventDispatcher */
111
+    private $dispatcher;
112
+
113
+    /** @var IConfig */
114
+    private $config;
115
+
116
+    public function __construct(
117
+        IDBConnection $connection,
118
+        IServerContainer $container,
119
+        IL10N $l,
120
+        LegacyDispatcher $eventDispatcher,
121
+        ILogger $logger,
122
+        IUserSession $session,
123
+        IEventDispatcher $dispatcher,
124
+        IConfig $config
125
+    ) {
126
+        $this->connection = $connection;
127
+        $this->container = $container;
128
+        $this->l = $l;
129
+        $this->legacyEventDispatcher = $eventDispatcher;
130
+        $this->logger = $logger;
131
+        $this->operationsByScope = new CappedMemoryCache(64);
132
+        $this->session = $session;
133
+        $this->dispatcher = $dispatcher;
134
+        $this->config = $config;
135
+    }
136
+
137
+    public function getRuleMatcher(): IRuleMatcher {
138
+        return new RuleMatcher(
139
+            $this->session,
140
+            $this->container,
141
+            $this->l,
142
+            $this,
143
+            $this->container->query(Logger::class)
144
+        );
145
+    }
146
+
147
+    public function getAllConfiguredEvents() {
148
+        $query = $this->connection->getQueryBuilder();
149
+
150
+        $query->select('class', 'entity', $query->expr()->castColumn('events', IQueryBuilder::PARAM_STR))
151
+            ->from('flow_operations')
152
+            ->where($query->expr()->neq('events', $query->createNamedParameter('[]'), IQueryBuilder::PARAM_STR))
153
+            ->groupBy('class', 'entity', $query->expr()->castColumn('events', IQueryBuilder::PARAM_STR));
154
+
155
+        $result = $query->execute();
156
+        $operations = [];
157
+        while ($row = $result->fetch()) {
158
+            $eventNames = \json_decode($row['events']);
159
+
160
+            $operation = $row['class'];
161
+            $entity = $row['entity'];
162
+
163
+            $operations[$operation] = $operations[$row['class']] ?? [];
164
+            $operations[$operation][$entity] = $operations[$operation][$entity] ?? [];
165
+
166
+            $operations[$operation][$entity] = array_unique(array_merge($operations[$operation][$entity], $eventNames ?? []));
167
+        }
168
+        $result->closeCursor();
169
+
170
+        return $operations;
171
+    }
172
+
173
+    /**
174
+     * @param string $operationClass
175
+     * @return ScopeContext[]
176
+     */
177
+    public function getAllConfiguredScopesForOperation(string $operationClass): array {
178
+        static $scopesByOperation = [];
179
+        if (isset($scopesByOperation[$operationClass])) {
180
+            return $scopesByOperation[$operationClass];
181
+        }
182
+
183
+        $query = $this->connection->getQueryBuilder();
184
+
185
+        $query->selectDistinct('s.type')
186
+            ->addSelect('s.value')
187
+            ->from('flow_operations', 'o')
188
+            ->leftJoin('o', 'flow_operations_scope', 's', $query->expr()->eq('o.id', 's.operation_id'))
189
+            ->where($query->expr()->eq('o.class', $query->createParameter('operationClass')));
190
+
191
+        $query->setParameters(['operationClass' => $operationClass]);
192
+        $result = $query->execute();
193
+
194
+        $scopesByOperation[$operationClass] = [];
195
+        while ($row = $result->fetch()) {
196
+            $scope = new ScopeContext($row['type'], $row['value']);
197
+            $scopesByOperation[$operationClass][$scope->getHash()] = $scope;
198
+        }
199
+
200
+        return $scopesByOperation[$operationClass];
201
+    }
202
+
203
+    public function getAllOperations(ScopeContext $scopeContext): array {
204
+        if (isset($this->operations[$scopeContext->getHash()])) {
205
+            return $this->operations[$scopeContext->getHash()];
206
+        }
207
+
208
+        $query = $this->connection->getQueryBuilder();
209
+
210
+        $query->select('o.*')
211
+            ->selectAlias('s.type', 'scope_type')
212
+            ->selectAlias('s.value', 'scope_actor_id')
213
+            ->from('flow_operations', 'o')
214
+            ->leftJoin('o', 'flow_operations_scope', 's', $query->expr()->eq('o.id', 's.operation_id'))
215
+            ->where($query->expr()->eq('s.type', $query->createParameter('scope')));
216
+
217
+        if ($scopeContext->getScope() === IManager::SCOPE_USER) {
218
+            $query->andWhere($query->expr()->eq('s.value', $query->createParameter('scopeId')));
219
+        }
220
+
221
+        $query->setParameters(['scope' => $scopeContext->getScope(), 'scopeId' => $scopeContext->getScopeId()]);
222
+        $result = $query->execute();
223
+
224
+        $this->operations[$scopeContext->getHash()] = [];
225
+        while ($row = $result->fetch()) {
226
+            if (!isset($this->operations[$scopeContext->getHash()][$row['class']])) {
227
+                $this->operations[$scopeContext->getHash()][$row['class']] = [];
228
+            }
229
+            $this->operations[$scopeContext->getHash()][$row['class']][] = $row;
230
+        }
231
+
232
+        return $this->operations[$scopeContext->getHash()];
233
+    }
234
+
235
+    public function getOperations(string $class, ScopeContext $scopeContext): array {
236
+        if (!isset($this->operations[$scopeContext->getHash()])) {
237
+            $this->getAllOperations($scopeContext);
238
+        }
239
+        return $this->operations[$scopeContext->getHash()][$class] ?? [];
240
+    }
241
+
242
+    /**
243
+     * @param int $id
244
+     * @return array
245
+     * @throws \UnexpectedValueException
246
+     */
247
+    protected function getOperation($id) {
248
+        $query = $this->connection->getQueryBuilder();
249
+        $query->select('*')
250
+            ->from('flow_operations')
251
+            ->where($query->expr()->eq('id', $query->createNamedParameter($id)));
252
+        $result = $query->execute();
253
+        $row = $result->fetch();
254
+        $result->closeCursor();
255
+
256
+        if ($row) {
257
+            return $row;
258
+        }
259
+
260
+        throw new \UnexpectedValueException($this->l->t('Operation #%s does not exist', [$id]));
261
+    }
262
+
263
+    protected function insertOperation(
264
+        string $class,
265
+        string $name,
266
+        array $checkIds,
267
+        string $operation,
268
+        string $entity,
269
+        array $events
270
+    ): int {
271
+        $query = $this->connection->getQueryBuilder();
272
+        $query->insert('flow_operations')
273
+            ->values([
274
+                'class' => $query->createNamedParameter($class),
275
+                'name' => $query->createNamedParameter($name),
276
+                'checks' => $query->createNamedParameter(json_encode(array_unique($checkIds))),
277
+                'operation' => $query->createNamedParameter($operation),
278
+                'entity' => $query->createNamedParameter($entity),
279
+                'events' => $query->createNamedParameter(json_encode($events))
280
+            ]);
281
+        $query->execute();
282
+
283
+        return $query->getLastInsertId();
284
+    }
285
+
286
+    /**
287
+     * @param string $class
288
+     * @param string $name
289
+     * @param array[] $checks
290
+     * @param string $operation
291
+     * @return array The added operation
292
+     * @throws \UnexpectedValueException
293
+     * @throws DBALException
294
+     */
295
+    public function addOperation(
296
+        string $class,
297
+        string $name,
298
+        array $checks,
299
+        string $operation,
300
+        ScopeContext $scope,
301
+        string $entity,
302
+        array $events
303
+    ) {
304
+        $this->validateOperation($class, $name, $checks, $operation, $entity, $events);
305
+
306
+        $this->connection->beginTransaction();
307
+
308
+        try {
309
+            $checkIds = [];
310
+            foreach ($checks as $check) {
311
+                $checkIds[] = $this->addCheck($check['class'], $check['operator'], $check['value']);
312
+            }
313
+
314
+            $id = $this->insertOperation($class, $name, $checkIds, $operation, $entity, $events);
315
+            $this->addScope($id, $scope);
316
+
317
+            $this->connection->commit();
318
+        } catch (DBALException $e) {
319
+            $this->connection->rollBack();
320
+            throw $e;
321
+        }
322
+
323
+        return $this->getOperation($id);
324
+    }
325
+
326
+    protected function canModify(int $id, ScopeContext $scopeContext):bool {
327
+        if (isset($this->operationsByScope[$scopeContext->getHash()])) {
328
+            return in_array($id, $this->operationsByScope[$scopeContext->getHash()], true);
329
+        }
330
+
331
+        $qb = $this->connection->getQueryBuilder();
332
+        $qb = $qb->select('o.id')
333
+            ->from('flow_operations', 'o')
334
+            ->leftJoin('o', 'flow_operations_scope', 's', $qb->expr()->eq('o.id', 's.operation_id'))
335
+            ->where($qb->expr()->eq('s.type', $qb->createParameter('scope')));
336
+
337
+        if ($scopeContext->getScope() !== IManager::SCOPE_ADMIN) {
338
+            $qb->where($qb->expr()->eq('s.value', $qb->createParameter('scopeId')));
339
+        }
340
+
341
+        $qb->setParameters(['scope' => $scopeContext->getScope(), 'scopeId' => $scopeContext->getScopeId()]);
342
+        $result = $qb->execute();
343
+
344
+        $this->operationsByScope[$scopeContext->getHash()] = [];
345
+        while ($opId = $result->fetchColumn(0)) {
346
+            $this->operationsByScope[$scopeContext->getHash()][] = (int)$opId;
347
+        }
348
+        $result->closeCursor();
349
+
350
+        return in_array($id, $this->operationsByScope[$scopeContext->getHash()], true);
351
+    }
352
+
353
+    /**
354
+     * @param int $id
355
+     * @param string $name
356
+     * @param array[] $checks
357
+     * @param string $operation
358
+     * @return array The updated operation
359
+     * @throws \UnexpectedValueException
360
+     * @throws \DomainException
361
+     * @throws DBALException
362
+     */
363
+    public function updateOperation(
364
+        int $id,
365
+        string $name,
366
+        array $checks,
367
+        string $operation,
368
+        ScopeContext $scopeContext,
369
+        string $entity,
370
+        array $events
371
+    ): array {
372
+        if (!$this->canModify($id, $scopeContext)) {
373
+            throw new \DomainException('Target operation not within scope');
374
+        };
375
+        $row = $this->getOperation($id);
376
+        $this->validateOperation($row['class'], $name, $checks, $operation, $entity, $events);
377
+
378
+        $checkIds = [];
379
+        try {
380
+            $this->connection->beginTransaction();
381
+            foreach ($checks as $check) {
382
+                $checkIds[] = $this->addCheck($check['class'], $check['operator'], $check['value']);
383
+            }
384
+
385
+            $query = $this->connection->getQueryBuilder();
386
+            $query->update('flow_operations')
387
+                ->set('name', $query->createNamedParameter($name))
388
+                ->set('checks', $query->createNamedParameter(json_encode(array_unique($checkIds))))
389
+                ->set('operation', $query->createNamedParameter($operation))
390
+                ->set('entity', $query->createNamedParameter($entity))
391
+                ->set('events', $query->createNamedParameter(json_encode($events)))
392
+                ->where($query->expr()->eq('id', $query->createNamedParameter($id)));
393
+            $query->execute();
394
+            $this->connection->commit();
395
+        } catch (DBALException $e) {
396
+            $this->connection->rollBack();
397
+            throw $e;
398
+        }
399
+        unset($this->operations[$scopeContext->getHash()]);
400
+
401
+        return $this->getOperation($id);
402
+    }
403
+
404
+    /**
405
+     * @param int $id
406
+     * @return bool
407
+     * @throws \UnexpectedValueException
408
+     * @throws DBALException
409
+     * @throws \DomainException
410
+     */
411
+    public function deleteOperation($id, ScopeContext $scopeContext) {
412
+        if (!$this->canModify($id, $scopeContext)) {
413
+            throw new \DomainException('Target operation not within scope');
414
+        };
415
+        $query = $this->connection->getQueryBuilder();
416
+        try {
417
+            $this->connection->beginTransaction();
418
+            $result = (bool)$query->delete('flow_operations')
419
+                ->where($query->expr()->eq('id', $query->createNamedParameter($id)))
420
+                ->execute();
421
+            if ($result) {
422
+                $qb = $this->connection->getQueryBuilder();
423
+                $result &= (bool)$qb->delete('flow_operations_scope')
424
+                    ->where($qb->expr()->eq('operation_id', $qb->createNamedParameter($id)))
425
+                    ->execute();
426
+            }
427
+            $this->connection->commit();
428
+        } catch (DBALException $e) {
429
+            $this->connection->rollBack();
430
+            throw $e;
431
+        }
432
+
433
+        if (isset($this->operations[$scopeContext->getHash()])) {
434
+            unset($this->operations[$scopeContext->getHash()]);
435
+        }
436
+
437
+        return $result;
438
+    }
439
+
440
+    protected function validateEvents(string $entity, array $events, IOperation $operation) {
441
+        try {
442
+            /** @var IEntity $instance */
443
+            $instance = $this->container->query($entity);
444
+        } catch (QueryException $e) {
445
+            throw new \UnexpectedValueException($this->l->t('Entity %s does not exist', [$entity]));
446
+        }
447
+
448
+        if (!$instance instanceof IEntity) {
449
+            throw new \UnexpectedValueException($this->l->t('Entity %s is invalid', [$entity]));
450
+        }
451
+
452
+        if (empty($events)) {
453
+            if (!$operation instanceof IComplexOperation) {
454
+                throw new \UnexpectedValueException($this->l->t('No events are chosen.'));
455
+            }
456
+            return;
457
+        }
458
+
459
+        $availableEvents = [];
460
+        foreach ($instance->getEvents() as $event) {
461
+            /** @var IEntityEvent $event */
462
+            $availableEvents[] = $event->getEventName();
463
+        }
464
+
465
+        $diff = array_diff($events, $availableEvents);
466
+        if (!empty($diff)) {
467
+            throw new \UnexpectedValueException($this->l->t('Entity %s has no event %s', [$entity, array_shift($diff)]));
468
+        }
469
+    }
470
+
471
+    /**
472
+     * @param string $class
473
+     * @param string $name
474
+     * @param array[] $checks
475
+     * @param string $operation
476
+     * @throws \UnexpectedValueException
477
+     */
478
+    public function validateOperation($class, $name, array $checks, $operation, string $entity, array $events) {
479
+        try {
480
+            /** @var IOperation $instance */
481
+            $instance = $this->container->query($class);
482
+        } catch (QueryException $e) {
483
+            throw new \UnexpectedValueException($this->l->t('Operation %s does not exist', [$class]));
484
+        }
485
+
486
+        if (!($instance instanceof IOperation)) {
487
+            throw new \UnexpectedValueException($this->l->t('Operation %s is invalid', [$class]));
488
+        }
489
+
490
+        $this->validateEvents($entity, $events, $instance);
491
+
492
+        if (count($checks) === 0) {
493
+            throw new \UnexpectedValueException($this->l->t('At least one check needs to be provided'));
494
+        }
495
+        $instance->validateOperation($name, $checks, $operation);
496
+
497
+        foreach ($checks as $check) {
498
+            if (!is_string($check['class'])) {
499
+                throw new \UnexpectedValueException($this->l->t('Invalid check provided'));
500
+            }
501
+
502
+            try {
503
+                /** @var ICheck $instance */
504
+                $instance = $this->container->query($check['class']);
505
+            } catch (QueryException $e) {
506
+                throw new \UnexpectedValueException($this->l->t('Check %s does not exist', [$class]));
507
+            }
508
+
509
+            if (!($instance instanceof ICheck)) {
510
+                throw new \UnexpectedValueException($this->l->t('Check %s is invalid', [$class]));
511
+            }
512
+
513
+            if (!empty($instance->supportedEntities())
514
+                && !in_array($entity, $instance->supportedEntities())
515
+            ) {
516
+                throw new \UnexpectedValueException($this->l->t('Check %s is not allowed with this entity', [$class]));
517
+            }
518
+
519
+            $instance->validateCheck($check['operator'], $check['value']);
520
+        }
521
+    }
522
+
523
+    /**
524
+     * @param int[] $checkIds
525
+     * @return array[]
526
+     */
527
+    public function getChecks(array $checkIds) {
528
+        $checkIds = array_map('intval', $checkIds);
529
+
530
+        $checks = [];
531
+        foreach ($checkIds as $i => $checkId) {
532
+            if (isset($this->checks[$checkId])) {
533
+                $checks[$checkId] = $this->checks[$checkId];
534
+                unset($checkIds[$i]);
535
+            }
536
+        }
537
+
538
+        if (empty($checkIds)) {
539
+            return $checks;
540
+        }
541
+
542
+        $query = $this->connection->getQueryBuilder();
543
+        $query->select('*')
544
+            ->from('flow_checks')
545
+            ->where($query->expr()->in('id', $query->createNamedParameter($checkIds, IQueryBuilder::PARAM_INT_ARRAY)));
546
+        $result = $query->execute();
547
+
548
+        while ($row = $result->fetch()) {
549
+            $this->checks[(int) $row['id']] = $row;
550
+            $checks[(int) $row['id']] = $row;
551
+        }
552
+        $result->closeCursor();
553
+
554
+        $checkIds = array_diff($checkIds, array_keys($checks));
555
+
556
+        if (!empty($checkIds)) {
557
+            $missingCheck = array_pop($checkIds);
558
+            throw new \UnexpectedValueException($this->l->t('Check #%s does not exist', $missingCheck));
559
+        }
560
+
561
+        return $checks;
562
+    }
563
+
564
+    /**
565
+     * @param string $class
566
+     * @param string $operator
567
+     * @param string $value
568
+     * @return int Check unique ID
569
+     */
570
+    protected function addCheck($class, $operator, $value) {
571
+        $hash = md5($class . '::' . $operator . '::' . $value);
572
+
573
+        $query = $this->connection->getQueryBuilder();
574
+        $query->select('id')
575
+            ->from('flow_checks')
576
+            ->where($query->expr()->eq('hash', $query->createNamedParameter($hash)));
577
+        $result = $query->execute();
578
+
579
+        if ($row = $result->fetch()) {
580
+            $result->closeCursor();
581
+            return (int) $row['id'];
582
+        }
583
+
584
+        $query = $this->connection->getQueryBuilder();
585
+        $query->insert('flow_checks')
586
+            ->values([
587
+                'class' => $query->createNamedParameter($class),
588
+                'operator' => $query->createNamedParameter($operator),
589
+                'value' => $query->createNamedParameter($value),
590
+                'hash' => $query->createNamedParameter($hash),
591
+            ]);
592
+        $query->execute();
593
+
594
+        return $query->getLastInsertId();
595
+    }
596
+
597
+    protected function addScope(int $operationId, ScopeContext $scope): void {
598
+        $query = $this->connection->getQueryBuilder();
599
+
600
+        $insertQuery = $query->insert('flow_operations_scope');
601
+        $insertQuery->values([
602
+            'operation_id' => $query->createNamedParameter($operationId),
603
+            'type' => $query->createNamedParameter($scope->getScope()),
604
+            'value' => $query->createNamedParameter($scope->getScopeId()),
605
+        ]);
606
+        $insertQuery->execute();
607
+    }
608
+
609
+    public function formatOperation(array $operation): array {
610
+        $checkIds = json_decode($operation['checks'], true);
611
+        $checks = $this->getChecks($checkIds);
612
+
613
+        $operation['checks'] = [];
614
+        foreach ($checks as $check) {
615
+            // Remove internal values
616
+            unset($check['id']);
617
+            unset($check['hash']);
618
+
619
+            $operation['checks'][] = $check;
620
+        }
621
+        $operation['events'] = json_decode($operation['events'], true) ?? [];
622
+
623
+
624
+        return $operation;
625
+    }
626
+
627
+    /**
628
+     * @return IEntity[]
629
+     */
630
+    public function getEntitiesList(): array {
631
+        $this->dispatcher->dispatchTyped(new RegisterEntitiesEvent($this));
632
+        $this->legacyEventDispatcher->dispatch(IManager::EVENT_NAME_REG_ENTITY, new GenericEvent($this));
633
+
634
+        return array_values(array_merge($this->getBuildInEntities(), $this->registeredEntities));
635
+    }
636
+
637
+    /**
638
+     * @return IOperation[]
639
+     */
640
+    public function getOperatorList(): array {
641
+        $this->dispatcher->dispatchTyped(new RegisterOperationsEvent($this));
642
+        $this->legacyEventDispatcher->dispatch(IManager::EVENT_NAME_REG_OPERATION, new GenericEvent($this));
643
+
644
+        return array_merge($this->getBuildInOperators(), $this->registeredOperators);
645
+    }
646
+
647
+    /**
648
+     * @return ICheck[]
649
+     */
650
+    public function getCheckList(): array {
651
+        $this->dispatcher->dispatchTyped(new RegisterChecksEvent($this));
652
+        $this->legacyEventDispatcher->dispatch(IManager::EVENT_NAME_REG_CHECK, new GenericEvent($this));
653
+
654
+        return array_merge($this->getBuildInChecks(), $this->registeredChecks);
655
+    }
656
+
657
+    public function registerEntity(IEntity $entity): void {
658
+        $this->registeredEntities[get_class($entity)] = $entity;
659
+    }
660
+
661
+    public function registerOperation(IOperation $operator): void {
662
+        $this->registeredOperators[get_class($operator)] = $operator;
663
+    }
664
+
665
+    public function registerCheck(ICheck $check): void {
666
+        $this->registeredChecks[get_class($check)] = $check;
667
+    }
668
+
669
+    /**
670
+     * @return IEntity[]
671
+     */
672
+    protected function getBuildInEntities(): array {
673
+        try {
674
+            return [
675
+                File::class => $this->container->query(File::class),
676
+            ];
677
+        } catch (QueryException $e) {
678
+            $this->logger->logException($e);
679
+            return [];
680
+        }
681
+    }
682
+
683
+    /**
684
+     * @return IOperation[]
685
+     */
686
+    protected function getBuildInOperators(): array {
687
+        try {
688
+            return [
689
+                // None yet
690
+            ];
691
+        } catch (QueryException $e) {
692
+            $this->logger->logException($e);
693
+            return [];
694
+        }
695
+    }
696
+
697
+    /**
698
+     * @return ICheck[]
699
+     */
700
+    protected function getBuildInChecks(): array {
701
+        try {
702
+            return [
703
+                $this->container->query(FileMimeType::class),
704
+                $this->container->query(FileName::class),
705
+                $this->container->query(FileSize::class),
706
+                $this->container->query(FileSystemTags::class),
707
+                $this->container->query(RequestRemoteAddress::class),
708
+                $this->container->query(RequestTime::class),
709
+                $this->container->query(RequestURL::class),
710
+                $this->container->query(RequestUserAgent::class),
711
+                $this->container->query(UserGroupMembership::class),
712
+            ];
713
+        } catch (QueryException $e) {
714
+            $this->logger->logException($e);
715
+            return [];
716
+        }
717
+    }
718
+
719
+    public function isUserScopeEnabled(): bool {
720
+        return $this->config->getAppValue(Application::APP_ID, 'user_scope_disabled', 'no') === 'no';
721
+    }
722 722
 }
Please login to merge, or discard this patch.
lib/base.php 2 patches
Indentation   +1011 added lines, -1011 removed lines patch added patch discarded remove patch
@@ -77,1017 +77,1017 @@
 block discarded – undo
77 77
  * OC_autoload!
78 78
  */
79 79
 class OC {
80
-	/**
81
-	 * Associative array for autoloading. classname => filename
82
-	 */
83
-	public static $CLASSPATH = [];
84
-	/**
85
-	 * The installation path for Nextcloud  on the server (e.g. /srv/http/nextcloud)
86
-	 */
87
-	public static $SERVERROOT = '';
88
-	/**
89
-	 * the current request path relative to the Nextcloud root (e.g. files/index.php)
90
-	 */
91
-	private static $SUBURI = '';
92
-	/**
93
-	 * the Nextcloud root path for http requests (e.g. nextcloud/)
94
-	 */
95
-	public static $WEBROOT = '';
96
-	/**
97
-	 * The installation path array of the apps folder on the server (e.g. /srv/http/nextcloud) 'path' and
98
-	 * web path in 'url'
99
-	 */
100
-	public static $APPSROOTS = [];
101
-
102
-	/**
103
-	 * @var string
104
-	 */
105
-	public static $configDir;
106
-
107
-	/**
108
-	 * requested app
109
-	 */
110
-	public static $REQUESTEDAPP = '';
111
-
112
-	/**
113
-	 * check if Nextcloud runs in cli mode
114
-	 */
115
-	public static $CLI = false;
116
-
117
-	/**
118
-	 * @var \OC\Autoloader $loader
119
-	 */
120
-	public static $loader = null;
121
-
122
-	/** @var \Composer\Autoload\ClassLoader $composerAutoloader */
123
-	public static $composerAutoloader = null;
124
-
125
-	/**
126
-	 * @var \OC\Server
127
-	 */
128
-	public static $server = null;
129
-
130
-	/**
131
-	 * @var \OC\Config
132
-	 */
133
-	private static $config = null;
134
-
135
-	/**
136
-	 * @throws \RuntimeException when the 3rdparty directory is missing or
137
-	 * the app path list is empty or contains an invalid path
138
-	 */
139
-	public static function initPaths() {
140
-		if (defined('PHPUNIT_CONFIG_DIR')) {
141
-			self::$configDir = OC::$SERVERROOT . '/' . PHPUNIT_CONFIG_DIR . '/';
142
-		} elseif (defined('PHPUNIT_RUN') and PHPUNIT_RUN and is_dir(OC::$SERVERROOT . '/tests/config/')) {
143
-			self::$configDir = OC::$SERVERROOT . '/tests/config/';
144
-		} elseif ($dir = getenv('NEXTCLOUD_CONFIG_DIR')) {
145
-			self::$configDir = rtrim($dir, '/') . '/';
146
-		} else {
147
-			self::$configDir = OC::$SERVERROOT . '/config/';
148
-		}
149
-		self::$config = new \OC\Config(self::$configDir);
150
-
151
-		OC::$SUBURI = str_replace("\\", "/", substr(realpath($_SERVER["SCRIPT_FILENAME"]), strlen(OC::$SERVERROOT)));
152
-		/**
153
-		 * FIXME: The following lines are required because we can't yet instantiate
154
-		 *        \OC::$server->getRequest() since \OC::$server does not yet exist.
155
-		 */
156
-		$params = [
157
-			'server' => [
158
-				'SCRIPT_NAME' => $_SERVER['SCRIPT_NAME'],
159
-				'SCRIPT_FILENAME' => $_SERVER['SCRIPT_FILENAME'],
160
-			],
161
-		];
162
-		$fakeRequest = new \OC\AppFramework\Http\Request($params, null, new \OC\AllConfig(new \OC\SystemConfig(self::$config)));
163
-		$scriptName = $fakeRequest->getScriptName();
164
-		if (substr($scriptName, -1) == '/') {
165
-			$scriptName .= 'index.php';
166
-			//make sure suburi follows the same rules as scriptName
167
-			if (substr(OC::$SUBURI, -9) != 'index.php') {
168
-				if (substr(OC::$SUBURI, -1) != '/') {
169
-					OC::$SUBURI = OC::$SUBURI . '/';
170
-				}
171
-				OC::$SUBURI = OC::$SUBURI . 'index.php';
172
-			}
173
-		}
174
-
175
-
176
-		if (OC::$CLI) {
177
-			OC::$WEBROOT = self::$config->getValue('overwritewebroot', '');
178
-		} else {
179
-			if (substr($scriptName, 0 - strlen(OC::$SUBURI)) === OC::$SUBURI) {
180
-				OC::$WEBROOT = substr($scriptName, 0, 0 - strlen(OC::$SUBURI));
181
-
182
-				if (OC::$WEBROOT != '' && OC::$WEBROOT[0] !== '/') {
183
-					OC::$WEBROOT = '/' . OC::$WEBROOT;
184
-				}
185
-			} else {
186
-				// The scriptName is not ending with OC::$SUBURI
187
-				// This most likely means that we are calling from CLI.
188
-				// However some cron jobs still need to generate
189
-				// a web URL, so we use overwritewebroot as a fallback.
190
-				OC::$WEBROOT = self::$config->getValue('overwritewebroot', '');
191
-			}
192
-
193
-			// Resolve /nextcloud to /nextcloud/ to ensure to always have a trailing
194
-			// slash which is required by URL generation.
195
-			if (isset($_SERVER['REQUEST_URI']) && $_SERVER['REQUEST_URI'] === \OC::$WEBROOT &&
196
-					substr($_SERVER['REQUEST_URI'], -1) !== '/') {
197
-				header('Location: '.\OC::$WEBROOT.'/');
198
-				exit();
199
-			}
200
-		}
201
-
202
-		// search the apps folder
203
-		$config_paths = self::$config->getValue('apps_paths', []);
204
-		if (!empty($config_paths)) {
205
-			foreach ($config_paths as $paths) {
206
-				if (isset($paths['url']) && isset($paths['path'])) {
207
-					$paths['url'] = rtrim($paths['url'], '/');
208
-					$paths['path'] = rtrim($paths['path'], '/');
209
-					OC::$APPSROOTS[] = $paths;
210
-				}
211
-			}
212
-		} elseif (file_exists(OC::$SERVERROOT . '/apps')) {
213
-			OC::$APPSROOTS[] = ['path' => OC::$SERVERROOT . '/apps', 'url' => '/apps', 'writable' => true];
214
-		} elseif (file_exists(OC::$SERVERROOT . '/../apps')) {
215
-			OC::$APPSROOTS[] = [
216
-				'path' => rtrim(dirname(OC::$SERVERROOT), '/') . '/apps',
217
-				'url' => '/apps',
218
-				'writable' => true
219
-			];
220
-		}
221
-
222
-		if (empty(OC::$APPSROOTS)) {
223
-			throw new \RuntimeException('apps directory not found! Please put the Nextcloud apps folder in the Nextcloud folder'
224
-				. ' or the folder above. You can also configure the location in the config.php file.');
225
-		}
226
-		$paths = [];
227
-		foreach (OC::$APPSROOTS as $path) {
228
-			$paths[] = $path['path'];
229
-			if (!is_dir($path['path'])) {
230
-				throw new \RuntimeException(sprintf('App directory "%s" not found! Please put the Nextcloud apps folder in the'
231
-					. ' Nextcloud folder or the folder above. You can also configure the location in the'
232
-					. ' config.php file.', $path['path']));
233
-			}
234
-		}
235
-
236
-		// set the right include path
237
-		set_include_path(
238
-			implode(PATH_SEPARATOR, $paths)
239
-		);
240
-	}
241
-
242
-	public static function checkConfig() {
243
-		$l = \OC::$server->getL10N('lib');
244
-
245
-		// Create config if it does not already exist
246
-		$configFilePath = self::$configDir .'/config.php';
247
-		if (!file_exists($configFilePath)) {
248
-			@touch($configFilePath);
249
-		}
250
-
251
-		// Check if config is writable
252
-		$configFileWritable = is_writable($configFilePath);
253
-		if (!$configFileWritable && !OC_Helper::isReadOnlyConfigEnabled()
254
-			|| !$configFileWritable && \OCP\Util::needUpgrade()) {
255
-			$urlGenerator = \OC::$server->getURLGenerator();
256
-
257
-			if (self::$CLI) {
258
-				echo $l->t('Cannot write into "config" directory!')."\n";
259
-				echo $l->t('This can usually be fixed by giving the webserver write access to the config directory')."\n";
260
-				echo "\n";
261
-				echo $l->t('Or, if you prefer to keep config.php file read only, set the option "config_is_read_only" to true in it.')."\n";
262
-				echo $l->t('See %s', [ $urlGenerator->linkToDocs('admin-config') ])."\n";
263
-				exit;
264
-			} else {
265
-				OC_Template::printErrorPage(
266
-					$l->t('Cannot write into "config" directory!'),
267
-					$l->t('This can usually be fixed by giving the webserver write access to the config directory.') . '. '
268
-					. $l->t('Or, if you prefer to keep config.php file read only, set the option "config_is_read_only" to true in it. See %s',
269
-					[ $urlGenerator->linkToDocs('admin-config') ]),
270
-					503
271
-				);
272
-			}
273
-		}
274
-	}
275
-
276
-	public static function checkInstalled() {
277
-		if (defined('OC_CONSOLE')) {
278
-			return;
279
-		}
280
-		// Redirect to installer if not installed
281
-		if (!\OC::$server->getSystemConfig()->getValue('installed', false) && OC::$SUBURI !== '/index.php' && OC::$SUBURI !== '/status.php') {
282
-			if (OC::$CLI) {
283
-				throw new Exception('Not installed');
284
-			} else {
285
-				$url = OC::$WEBROOT . '/index.php';
286
-				header('Location: ' . $url);
287
-			}
288
-			exit();
289
-		}
290
-	}
291
-
292
-	public static function checkMaintenanceMode() {
293
-		// Allow ajax update script to execute without being stopped
294
-		if (((bool) \OC::$server->getSystemConfig()->getValue('maintenance', false)) && OC::$SUBURI != '/core/ajax/update.php') {
295
-			// send http status 503
296
-			http_response_code(503);
297
-			header('Retry-After: 120');
298
-
299
-			// render error page
300
-			$template = new OC_Template('', 'update.user', 'guest');
301
-			OC_Util::addScript('dist/maintenance');
302
-			OC_Util::addStyle('core', 'guest');
303
-			$template->printPage();
304
-			die();
305
-		}
306
-	}
307
-
308
-	/**
309
-	 * Prints the upgrade page
310
-	 *
311
-	 * @param \OC\SystemConfig $systemConfig
312
-	 */
313
-	private static function printUpgradePage(\OC\SystemConfig $systemConfig) {
314
-		$disableWebUpdater = $systemConfig->getValue('upgrade.disable-web', false);
315
-		$tooBig = false;
316
-		if (!$disableWebUpdater) {
317
-			$apps = \OC::$server->getAppManager();
318
-			if ($apps->isInstalled('user_ldap')) {
319
-				$qb = \OC::$server->getDatabaseConnection()->getQueryBuilder();
320
-
321
-				$result = $qb->select($qb->func()->count('*', 'user_count'))
322
-					->from('ldap_user_mapping')
323
-					->execute();
324
-				$row = $result->fetch();
325
-				$result->closeCursor();
326
-
327
-				$tooBig = ($row['user_count'] > 50);
328
-			}
329
-			if (!$tooBig && $apps->isInstalled('user_saml')) {
330
-				$qb = \OC::$server->getDatabaseConnection()->getQueryBuilder();
331
-
332
-				$result = $qb->select($qb->func()->count('*', 'user_count'))
333
-					->from('user_saml_users')
334
-					->execute();
335
-				$row = $result->fetch();
336
-				$result->closeCursor();
337
-
338
-				$tooBig = ($row['user_count'] > 50);
339
-			}
340
-			if (!$tooBig) {
341
-				// count users
342
-				$stats = \OC::$server->getUserManager()->countUsers();
343
-				$totalUsers = array_sum($stats);
344
-				$tooBig = ($totalUsers > 50);
345
-			}
346
-		}
347
-		$ignoreTooBigWarning = isset($_GET['IKnowThatThisIsABigInstanceAndTheUpdateRequestCouldRunIntoATimeoutAndHowToRestoreABackup']) &&
348
-			$_GET['IKnowThatThisIsABigInstanceAndTheUpdateRequestCouldRunIntoATimeoutAndHowToRestoreABackup'] === 'IAmSuperSureToDoThis';
349
-
350
-		if ($disableWebUpdater || ($tooBig && !$ignoreTooBigWarning)) {
351
-			// send http status 503
352
-			http_response_code(503);
353
-			header('Retry-After: 120');
354
-
355
-			// render error page
356
-			$template = new OC_Template('', 'update.use-cli', 'guest');
357
-			$template->assign('productName', 'nextcloud'); // for now
358
-			$template->assign('version', OC_Util::getVersionString());
359
-			$template->assign('tooBig', $tooBig);
360
-
361
-			$template->printPage();
362
-			die();
363
-		}
364
-
365
-		// check whether this is a core update or apps update
366
-		$installedVersion = $systemConfig->getValue('version', '0.0.0');
367
-		$currentVersion = implode('.', \OCP\Util::getVersion());
368
-
369
-		// if not a core upgrade, then it's apps upgrade
370
-		$isAppsOnlyUpgrade = version_compare($currentVersion, $installedVersion, '=');
371
-
372
-		$oldTheme = $systemConfig->getValue('theme');
373
-		$systemConfig->setValue('theme', '');
374
-		OC_Util::addScript('config'); // needed for web root
375
-		OC_Util::addScript('update');
376
-
377
-		/** @var \OC\App\AppManager $appManager */
378
-		$appManager = \OC::$server->getAppManager();
379
-
380
-		$tmpl = new OC_Template('', 'update.admin', 'guest');
381
-		$tmpl->assign('version', OC_Util::getVersionString());
382
-		$tmpl->assign('isAppsOnlyUpgrade', $isAppsOnlyUpgrade);
383
-
384
-		// get third party apps
385
-		$ocVersion = \OCP\Util::getVersion();
386
-		$ocVersion = implode('.', $ocVersion);
387
-		$incompatibleApps = $appManager->getIncompatibleApps($ocVersion);
388
-		$incompatibleShippedApps = [];
389
-		foreach ($incompatibleApps as $appInfo) {
390
-			if ($appManager->isShipped($appInfo['id'])) {
391
-				$incompatibleShippedApps[] = $appInfo['name'] . ' (' . $appInfo['id'] . ')';
392
-			}
393
-		}
394
-
395
-		if (!empty($incompatibleShippedApps)) {
396
-			$l = \OC::$server->getL10N('core');
397
-			$hint = $l->t('The files of the app %1$s were not replaced correctly. Make sure it is a version compatible with the server.', [implode(', ', $incompatibleShippedApps)]);
398
-			throw new \OC\HintException('The files of the app ' . implode(', ', $incompatibleShippedApps) . ' were not replaced correctly. Make sure it is a version compatible with the server.', $hint);
399
-		}
400
-
401
-		$tmpl->assign('appsToUpgrade', $appManager->getAppsNeedingUpgrade($ocVersion));
402
-		$tmpl->assign('incompatibleAppsList', $incompatibleApps);
403
-		$tmpl->assign('productName', 'Nextcloud'); // for now
404
-		$tmpl->assign('oldTheme', $oldTheme);
405
-		$tmpl->printPage();
406
-	}
407
-
408
-	public static function initSession() {
409
-		if (self::$server->getRequest()->getServerProtocol() === 'https') {
410
-			ini_set('session.cookie_secure', true);
411
-		}
412
-
413
-		// prevents javascript from accessing php session cookies
414
-		ini_set('session.cookie_httponly', 'true');
415
-
416
-		// set the cookie path to the Nextcloud directory
417
-		$cookie_path = OC::$WEBROOT ? : '/';
418
-		ini_set('session.cookie_path', $cookie_path);
419
-
420
-		// Let the session name be changed in the initSession Hook
421
-		$sessionName = OC_Util::getInstanceId();
422
-
423
-		try {
424
-			// set the session name to the instance id - which is unique
425
-			$session = new \OC\Session\Internal($sessionName);
426
-
427
-			$cryptoWrapper = \OC::$server->getSessionCryptoWrapper();
428
-			$session = $cryptoWrapper->wrapSession($session);
429
-			self::$server->setSession($session);
430
-
431
-			// if session can't be started break with http 500 error
432
-		} catch (Exception $e) {
433
-			\OC::$server->getLogger()->logException($e, ['app' => 'base']);
434
-			//show the user a detailed error page
435
-			OC_Template::printExceptionErrorPage($e, 500);
436
-			die();
437
-		}
438
-
439
-		$sessionLifeTime = self::getSessionLifeTime();
440
-
441
-		// session timeout
442
-		if ($session->exists('LAST_ACTIVITY') && (time() - $session->get('LAST_ACTIVITY') > $sessionLifeTime)) {
443
-			if (isset($_COOKIE[session_name()])) {
444
-				setcookie(session_name(), '', -1, self::$WEBROOT ? : '/');
445
-			}
446
-			\OC::$server->getUserSession()->logout();
447
-		}
448
-
449
-		$session->set('LAST_ACTIVITY', time());
450
-	}
451
-
452
-	/**
453
-	 * @return string
454
-	 */
455
-	private static function getSessionLifeTime() {
456
-		return \OC::$server->getConfig()->getSystemValue('session_lifetime', 60 * 60 * 24);
457
-	}
458
-
459
-	/**
460
-	 * Try to set some values to the required Nextcloud default
461
-	 */
462
-	public static function setRequiredIniValues() {
463
-		@ini_set('default_charset', 'UTF-8');
464
-		@ini_set('gd.jpeg_ignore_warning', '1');
465
-	}
466
-
467
-	/**
468
-	 * Send the same site cookies
469
-	 */
470
-	private static function sendSameSiteCookies() {
471
-		$cookieParams = session_get_cookie_params();
472
-		$secureCookie = ($cookieParams['secure'] === true) ? 'secure; ' : '';
473
-		$policies = [
474
-			'lax',
475
-			'strict',
476
-		];
477
-
478
-		// Append __Host to the cookie if it meets the requirements
479
-		$cookiePrefix = '';
480
-		if ($cookieParams['secure'] === true && $cookieParams['path'] === '/') {
481
-			$cookiePrefix = '__Host-';
482
-		}
483
-
484
-		foreach ($policies as $policy) {
485
-			header(
486
-				sprintf(
487
-					'Set-Cookie: %snc_sameSiteCookie%s=true; path=%s; httponly;' . $secureCookie . 'expires=Fri, 31-Dec-2100 23:59:59 GMT; SameSite=%s',
488
-					$cookiePrefix,
489
-					$policy,
490
-					$cookieParams['path'],
491
-					$policy
492
-				),
493
-				false
494
-			);
495
-		}
496
-	}
497
-
498
-	/**
499
-	 * Same Site cookie to further mitigate CSRF attacks. This cookie has to
500
-	 * be set in every request if cookies are sent to add a second level of
501
-	 * defense against CSRF.
502
-	 *
503
-	 * If the cookie is not sent this will set the cookie and reload the page.
504
-	 * We use an additional cookie since we want to protect logout CSRF and
505
-	 * also we can't directly interfere with PHP's session mechanism.
506
-	 */
507
-	private static function performSameSiteCookieProtection() {
508
-		$request = \OC::$server->getRequest();
509
-
510
-		// Some user agents are notorious and don't really properly follow HTTP
511
-		// specifications. For those, have an automated opt-out. Since the protection
512
-		// for remote.php is applied in base.php as starting point we need to opt out
513
-		// here.
514
-		$incompatibleUserAgents = \OC::$server->getConfig()->getSystemValue('csrf.optout');
515
-
516
-		// Fallback, if csrf.optout is unset
517
-		if (!is_array($incompatibleUserAgents)) {
518
-			$incompatibleUserAgents = [
519
-				// OS X Finder
520
-				'/^WebDAVFS/',
521
-				// Windows webdav drive
522
-				'/^Microsoft-WebDAV-MiniRedir/',
523
-			];
524
-		}
525
-
526
-		if ($request->isUserAgent($incompatibleUserAgents)) {
527
-			return;
528
-		}
529
-
530
-		if (count($_COOKIE) > 0) {
531
-			$requestUri = $request->getScriptName();
532
-			$processingScript = explode('/', $requestUri);
533
-			$processingScript = $processingScript[count($processingScript) - 1];
534
-
535
-			// index.php routes are handled in the middleware
536
-			if ($processingScript === 'index.php') {
537
-				return;
538
-			}
539
-
540
-			// All other endpoints require the lax and the strict cookie
541
-			if (!$request->passesStrictCookieCheck()) {
542
-				self::sendSameSiteCookies();
543
-				// Debug mode gets access to the resources without strict cookie
544
-				// due to the fact that the SabreDAV browser also lives there.
545
-				if (!\OC::$server->getConfig()->getSystemValue('debug', false)) {
546
-					http_response_code(\OCP\AppFramework\Http::STATUS_SERVICE_UNAVAILABLE);
547
-					exit();
548
-				}
549
-			}
550
-		} elseif (!isset($_COOKIE['nc_sameSiteCookielax']) || !isset($_COOKIE['nc_sameSiteCookiestrict'])) {
551
-			self::sendSameSiteCookies();
552
-		}
553
-	}
554
-
555
-	public static function init() {
556
-		// calculate the root directories
557
-		OC::$SERVERROOT = str_replace("\\", '/', substr(__DIR__, 0, -4));
558
-
559
-		// register autoloader
560
-		$loaderStart = microtime(true);
561
-		require_once __DIR__ . '/autoloader.php';
562
-		self::$loader = new \OC\Autoloader([
563
-			OC::$SERVERROOT . '/lib/private/legacy',
564
-		]);
565
-		if (defined('PHPUNIT_RUN')) {
566
-			self::$loader->addValidRoot(OC::$SERVERROOT . '/tests');
567
-		}
568
-		spl_autoload_register([self::$loader, 'load']);
569
-		$loaderEnd = microtime(true);
570
-
571
-		self::$CLI = (php_sapi_name() == 'cli');
572
-
573
-		// Add default composer PSR-4 autoloader
574
-		self::$composerAutoloader = require_once OC::$SERVERROOT . '/lib/composer/autoload.php';
575
-
576
-		try {
577
-			self::initPaths();
578
-			// setup 3rdparty autoloader
579
-			$vendorAutoLoad = OC::$SERVERROOT. '/3rdparty/autoload.php';
580
-			if (!file_exists($vendorAutoLoad)) {
581
-				throw new \RuntimeException('Composer autoloader not found, unable to continue. Check the folder "3rdparty". Running "git submodule update --init" will initialize the git submodule that handles the subfolder "3rdparty".');
582
-			}
583
-			require_once $vendorAutoLoad;
584
-		} catch (\RuntimeException $e) {
585
-			if (!self::$CLI) {
586
-				http_response_code(503);
587
-			}
588
-			// we can't use the template error page here, because this needs the
589
-			// DI container which isn't available yet
590
-			print($e->getMessage());
591
-			exit();
592
-		}
593
-
594
-		// setup the basic server
595
-		self::$server = new \OC\Server(\OC::$WEBROOT, self::$config);
596
-		self::$server->boot();
597
-		\OC::$server->getEventLogger()->log('autoloader', 'Autoloader', $loaderStart, $loaderEnd);
598
-		\OC::$server->getEventLogger()->start('boot', 'Initialize');
599
-
600
-		// Override php.ini and log everything if we're troubleshooting
601
-		if (self::$config->getValue('loglevel') === ILogger::DEBUG) {
602
-			error_reporting(E_ALL);
603
-		}
604
-
605
-		// Don't display errors and log them
606
-		@ini_set('display_errors', '0');
607
-		@ini_set('log_errors', '1');
608
-
609
-		if (!date_default_timezone_set('UTC')) {
610
-			throw new \RuntimeException('Could not set timezone to UTC');
611
-		}
612
-
613
-		//try to configure php to enable big file uploads.
614
-		//this doesn´t work always depending on the webserver and php configuration.
615
-		//Let´s try to overwrite some defaults anyway
616
-
617
-		//try to set the maximum execution time to 60min
618
-		if (strpos(@ini_get('disable_functions'), 'set_time_limit') === false) {
619
-			@set_time_limit(3600);
620
-		}
621
-		@ini_set('max_execution_time', '3600');
622
-		@ini_set('max_input_time', '3600');
623
-
624
-		//try to set the maximum filesize to 10G
625
-		@ini_set('upload_max_filesize', '10G');
626
-		@ini_set('post_max_size', '10G');
627
-		@ini_set('file_uploads', '50');
628
-
629
-		self::setRequiredIniValues();
630
-		self::handleAuthHeaders();
631
-		self::registerAutoloaderCache();
632
-
633
-		// initialize intl fallback is necessary
634
-		\Patchwork\Utf8\Bootup::initIntl();
635
-		OC_Util::isSetLocaleWorking();
636
-
637
-		if (!defined('PHPUNIT_RUN')) {
638
-			OC\Log\ErrorHandler::setLogger(\OC::$server->getLogger());
639
-			$debug = \OC::$server->getConfig()->getSystemValue('debug', false);
640
-			OC\Log\ErrorHandler::register($debug);
641
-		}
642
-
643
-		/** @var \OC\AppFramework\Bootstrap\Coordinator $bootstrapCoordinator */
644
-		$bootstrapCoordinator = \OC::$server->query(\OC\AppFramework\Bootstrap\Coordinator::class);
645
-		$bootstrapCoordinator->runRegistration();
646
-
647
-		\OC::$server->getEventLogger()->start('init_session', 'Initialize session');
648
-		OC_App::loadApps(['session']);
649
-		if (!self::$CLI) {
650
-			self::initSession();
651
-		}
652
-		\OC::$server->getEventLogger()->end('init_session');
653
-		self::checkConfig();
654
-		self::checkInstalled();
655
-
656
-		OC_Response::addSecurityHeaders();
657
-
658
-		self::performSameSiteCookieProtection();
659
-
660
-		if (!defined('OC_CONSOLE')) {
661
-			$errors = OC_Util::checkServer(\OC::$server->getSystemConfig());
662
-			if (count($errors) > 0) {
663
-				if (!self::$CLI) {
664
-					http_response_code(503);
665
-					OC_Util::addStyle('guest');
666
-					try {
667
-						OC_Template::printGuestPage('', 'error', ['errors' => $errors]);
668
-						exit;
669
-					} catch (\Exception $e) {
670
-						// In case any error happens when showing the error page, we simply fall back to posting the text.
671
-						// This might be the case when e.g. the data directory is broken and we can not load/write SCSS to/from it.
672
-					}
673
-				}
674
-
675
-				// Convert l10n string into regular string for usage in database
676
-				$staticErrors = [];
677
-				foreach ($errors as $error) {
678
-					echo $error['error'] . "\n";
679
-					echo $error['hint'] . "\n\n";
680
-					$staticErrors[] = [
681
-						'error' => (string)$error['error'],
682
-						'hint' => (string)$error['hint'],
683
-					];
684
-				}
685
-
686
-				try {
687
-					\OC::$server->getConfig()->setAppValue('core', 'cronErrors', json_encode($staticErrors));
688
-				} catch (\Exception $e) {
689
-					echo('Writing to database failed');
690
-				}
691
-				exit(1);
692
-			} elseif (self::$CLI && \OC::$server->getConfig()->getSystemValue('installed', false)) {
693
-				\OC::$server->getConfig()->deleteAppValue('core', 'cronErrors');
694
-			}
695
-		}
696
-		//try to set the session lifetime
697
-		$sessionLifeTime = self::getSessionLifeTime();
698
-		@ini_set('gc_maxlifetime', (string)$sessionLifeTime);
699
-
700
-		$systemConfig = \OC::$server->getSystemConfig();
701
-
702
-		// User and Groups
703
-		if (!$systemConfig->getValue("installed", false)) {
704
-			self::$server->getSession()->set('user_id', '');
705
-		}
706
-
707
-		OC_User::useBackend(new \OC\User\Database());
708
-		\OC::$server->getGroupManager()->addBackend(new \OC\Group\Database());
709
-
710
-		// Subscribe to the hook
711
-		\OCP\Util::connectHook(
712
-			'\OCA\Files_Sharing\API\Server2Server',
713
-			'preLoginNameUsedAsUserName',
714
-			'\OC\User\Database',
715
-			'preLoginNameUsedAsUserName'
716
-		);
717
-
718
-		//setup extra user backends
719
-		if (!\OCP\Util::needUpgrade()) {
720
-			OC_User::setupBackends();
721
-		} else {
722
-			// Run upgrades in incognito mode
723
-			OC_User::setIncognitoMode(true);
724
-		}
725
-
726
-		self::registerCleanupHooks();
727
-		self::registerFilesystemHooks();
728
-		self::registerShareHooks();
729
-		self::registerEncryptionWrapper();
730
-		self::registerEncryptionHooks();
731
-		self::registerAccountHooks();
732
-		self::registerResourceCollectionHooks();
733
-		self::registerAppRestrictionsHooks();
734
-
735
-		// Make sure that the application class is not loaded before the database is setup
736
-		if ($systemConfig->getValue("installed", false)) {
737
-			OC_App::loadApp('settings');
738
-		}
739
-
740
-		//make sure temporary files are cleaned up
741
-		$tmpManager = \OC::$server->getTempManager();
742
-		register_shutdown_function([$tmpManager, 'clean']);
743
-		$lockProvider = \OC::$server->getLockingProvider();
744
-		register_shutdown_function([$lockProvider, 'releaseAll']);
745
-
746
-		// Check whether the sample configuration has been copied
747
-		if ($systemConfig->getValue('copied_sample_config', false)) {
748
-			$l = \OC::$server->getL10N('lib');
749
-			OC_Template::printErrorPage(
750
-				$l->t('Sample configuration detected'),
751
-				$l->t('It has been detected that the sample configuration has been copied. This can break your installation and is unsupported. Please read the documentation before performing changes on config.php'),
752
-				503
753
-			);
754
-			return;
755
-		}
756
-
757
-		$request = \OC::$server->getRequest();
758
-		$host = $request->getInsecureServerHost();
759
-		/**
760
-		 * if the host passed in headers isn't trusted
761
-		 * FIXME: Should not be in here at all :see_no_evil:
762
-		 */
763
-		if (!OC::$CLI
764
-			&& !\OC::$server->getTrustedDomainHelper()->isTrustedDomain($host)
765
-			&& self::$server->getConfig()->getSystemValue('installed', false)
766
-		) {
767
-			// Allow access to CSS resources
768
-			$isScssRequest = false;
769
-			if (strpos($request->getPathInfo(), '/css/') === 0) {
770
-				$isScssRequest = true;
771
-			}
772
-
773
-			if (substr($request->getRequestUri(), -11) === '/status.php') {
774
-				http_response_code(400);
775
-				header('Content-Type: application/json');
776
-				echo '{"error": "Trusted domain error.", "code": 15}';
777
-				exit();
778
-			}
779
-
780
-			if (!$isScssRequest) {
781
-				http_response_code(400);
782
-
783
-				\OC::$server->getLogger()->info(
784
-					'Trusted domain error. "{remoteAddress}" tried to access using "{host}" as host.',
785
-					[
786
-						'app' => 'core',
787
-						'remoteAddress' => $request->getRemoteAddress(),
788
-						'host' => $host,
789
-					]
790
-				);
791
-
792
-				$tmpl = new OCP\Template('core', 'untrustedDomain', 'guest');
793
-				$tmpl->assign('docUrl', \OC::$server->getURLGenerator()->linkToDocs('admin-trusted-domains'));
794
-				$tmpl->printPage();
795
-
796
-				exit();
797
-			}
798
-		}
799
-		\OC::$server->getEventLogger()->end('boot');
800
-	}
801
-
802
-	/**
803
-	 * register hooks for the cleanup of cache and bruteforce protection
804
-	 */
805
-	public static function registerCleanupHooks() {
806
-		//don't try to do this before we are properly setup
807
-		if (\OC::$server->getSystemConfig()->getValue('installed', false) && !\OCP\Util::needUpgrade()) {
808
-
809
-			// NOTE: This will be replaced to use OCP
810
-			$userSession = self::$server->getUserSession();
811
-			$userSession->listen('\OC\User', 'postLogin', function () use ($userSession) {
812
-				if (!defined('PHPUNIT_RUN') && $userSession->isLoggedIn()) {
813
-					// reset brute force delay for this IP address and username
814
-					$uid = \OC::$server->getUserSession()->getUser()->getUID();
815
-					$request = \OC::$server->getRequest();
816
-					$throttler = \OC::$server->getBruteForceThrottler();
817
-					$throttler->resetDelay($request->getRemoteAddress(), 'login', ['user' => $uid]);
818
-				}
819
-
820
-				try {
821
-					$cache = new \OC\Cache\File();
822
-					$cache->gc();
823
-				} catch (\OC\ServerNotAvailableException $e) {
824
-					// not a GC exception, pass it on
825
-					throw $e;
826
-				} catch (\OC\ForbiddenException $e) {
827
-					// filesystem blocked for this request, ignore
828
-				} catch (\Exception $e) {
829
-					// a GC exception should not prevent users from using OC,
830
-					// so log the exception
831
-					\OC::$server->getLogger()->logException($e, [
832
-						'message' => 'Exception when running cache gc.',
833
-						'level' => ILogger::WARN,
834
-						'app' => 'core',
835
-					]);
836
-				}
837
-			});
838
-		}
839
-	}
840
-
841
-	private static function registerEncryptionWrapper() {
842
-		$manager = self::$server->getEncryptionManager();
843
-		\OCP\Util::connectHook('OC_Filesystem', 'preSetup', $manager, 'setupStorage');
844
-	}
845
-
846
-	private static function registerEncryptionHooks() {
847
-		$enabled = self::$server->getEncryptionManager()->isEnabled();
848
-		if ($enabled) {
849
-			\OCP\Util::connectHook(Share::class, 'post_shared', HookManager::class, 'postShared');
850
-			\OCP\Util::connectHook(Share::class, 'post_unshare', HookManager::class, 'postUnshared');
851
-			\OCP\Util::connectHook('OC_Filesystem', 'post_rename', HookManager::class, 'postRename');
852
-			\OCP\Util::connectHook('\OCA\Files_Trashbin\Trashbin', 'post_restore', HookManager::class, 'postRestore');
853
-		}
854
-	}
855
-
856
-	private static function registerAccountHooks() {
857
-		$hookHandler = new \OC\Accounts\Hooks(\OC::$server->getLogger());
858
-		\OCP\Util::connectHook('OC_User', 'changeUser', $hookHandler, 'changeUserHook');
859
-	}
860
-
861
-	private static function registerAppRestrictionsHooks() {
862
-		/** @var \OC\Group\Manager $groupManager */
863
-		$groupManager = self::$server->query(\OCP\IGroupManager::class);
864
-		$groupManager->listen('\OC\Group', 'postDelete', function (\OCP\IGroup $group) {
865
-			$appManager = self::$server->getAppManager();
866
-			$apps = $appManager->getEnabledAppsForGroup($group);
867
-			foreach ($apps as $appId) {
868
-				$restrictions = $appManager->getAppRestriction($appId);
869
-				if (empty($restrictions)) {
870
-					continue;
871
-				}
872
-				$key = array_search($group->getGID(), $restrictions);
873
-				unset($restrictions[$key]);
874
-				$restrictions = array_values($restrictions);
875
-				if (empty($restrictions)) {
876
-					$appManager->disableApp($appId);
877
-				} else {
878
-					$appManager->enableAppForGroups($appId, $restrictions);
879
-				}
880
-			}
881
-		});
882
-	}
883
-
884
-	private static function registerResourceCollectionHooks() {
885
-		\OC\Collaboration\Resources\Listener::register(\OC::$server->getEventDispatcher());
886
-	}
887
-
888
-	/**
889
-	 * register hooks for the filesystem
890
-	 */
891
-	public static function registerFilesystemHooks() {
892
-		// Check for blacklisted files
893
-		OC_Hook::connect('OC_Filesystem', 'write', Filesystem::class, 'isBlacklisted');
894
-		OC_Hook::connect('OC_Filesystem', 'rename', Filesystem::class, 'isBlacklisted');
895
-	}
896
-
897
-	/**
898
-	 * register hooks for sharing
899
-	 */
900
-	public static function registerShareHooks() {
901
-		if (\OC::$server->getSystemConfig()->getValue('installed')) {
902
-			OC_Hook::connect('OC_User', 'post_deleteUser', Hooks::class, 'post_deleteUser');
903
-			OC_Hook::connect('OC_User', 'post_deleteGroup', Hooks::class, 'post_deleteGroup');
904
-
905
-			/** @var IEventDispatcher $dispatcher */
906
-			$dispatcher = \OC::$server->get(IEventDispatcher::class);
907
-			$dispatcher->addServiceListener(UserRemovedEvent::class, \OC\Share20\UserRemovedListener::class);
908
-		}
909
-	}
910
-
911
-	protected static function registerAutoloaderCache() {
912
-		// The class loader takes an optional low-latency cache, which MUST be
913
-		// namespaced. The instanceid is used for namespacing, but might be
914
-		// unavailable at this point. Furthermore, it might not be possible to
915
-		// generate an instanceid via \OC_Util::getInstanceId() because the
916
-		// config file may not be writable. As such, we only register a class
917
-		// loader cache if instanceid is available without trying to create one.
918
-		$instanceId = \OC::$server->getSystemConfig()->getValue('instanceid', null);
919
-		if ($instanceId) {
920
-			try {
921
-				$memcacheFactory = \OC::$server->getMemCacheFactory();
922
-				self::$loader->setMemoryCache($memcacheFactory->createLocal('Autoloader'));
923
-			} catch (\Exception $ex) {
924
-			}
925
-		}
926
-	}
927
-
928
-	/**
929
-	 * Handle the request
930
-	 */
931
-	public static function handleRequest() {
932
-		\OC::$server->getEventLogger()->start('handle_request', 'Handle request');
933
-		$systemConfig = \OC::$server->getSystemConfig();
934
-
935
-		// Check if Nextcloud is installed or in maintenance (update) mode
936
-		if (!$systemConfig->getValue('installed', false)) {
937
-			\OC::$server->getSession()->clear();
938
-			$setupHelper = new OC\Setup(
939
-				$systemConfig,
940
-				\OC::$server->get(\bantu\IniGetWrapper\IniGetWrapper::class),
941
-				\OC::$server->getL10N('lib'),
942
-				\OC::$server->query(\OCP\Defaults::class),
943
-				\OC::$server->getLogger(),
944
-				\OC::$server->getSecureRandom(),
945
-				\OC::$server->query(\OC\Installer::class)
946
-			);
947
-			$controller = new OC\Core\Controller\SetupController($setupHelper);
948
-			$controller->run($_POST);
949
-			exit();
950
-		}
951
-
952
-		$request = \OC::$server->getRequest();
953
-		$requestPath = $request->getRawPathInfo();
954
-		if ($requestPath === '/heartbeat') {
955
-			return;
956
-		}
957
-		if (substr($requestPath, -3) !== '.js') { // we need these files during the upgrade
958
-			self::checkMaintenanceMode();
959
-
960
-			if (\OCP\Util::needUpgrade()) {
961
-				if (function_exists('opcache_reset')) {
962
-					opcache_reset();
963
-				}
964
-				if (!((bool) $systemConfig->getValue('maintenance', false))) {
965
-					self::printUpgradePage($systemConfig);
966
-					exit();
967
-				}
968
-			}
969
-		}
970
-
971
-		// emergency app disabling
972
-		if ($requestPath === '/disableapp'
973
-			&& $request->getMethod() === 'POST'
974
-			&& ((array)$request->getParam('appid')) !== ''
975
-		) {
976
-			\OC_JSON::callCheck();
977
-			\OC_JSON::checkAdminUser();
978
-			$appIds = (array)$request->getParam('appid');
979
-			foreach ($appIds as $appId) {
980
-				$appId = \OC_App::cleanAppId($appId);
981
-				\OC::$server->getAppManager()->disableApp($appId);
982
-			}
983
-			\OC_JSON::success();
984
-			exit();
985
-		}
986
-
987
-		// Always load authentication apps
988
-		OC_App::loadApps(['authentication']);
989
-
990
-		// Load minimum set of apps
991
-		if (!\OCP\Util::needUpgrade()
992
-			&& !((bool) $systemConfig->getValue('maintenance', false))) {
993
-			// For logged-in users: Load everything
994
-			if (\OC::$server->getUserSession()->isLoggedIn()) {
995
-				OC_App::loadApps();
996
-			} else {
997
-				// For guests: Load only filesystem and logging
998
-				OC_App::loadApps(['filesystem', 'logging']);
999
-				self::handleLogin($request);
1000
-			}
1001
-		}
1002
-
1003
-		if (!self::$CLI) {
1004
-			try {
1005
-				if (!((bool) $systemConfig->getValue('maintenance', false)) && !\OCP\Util::needUpgrade()) {
1006
-					OC_App::loadApps(['filesystem', 'logging']);
1007
-					OC_App::loadApps();
1008
-				}
1009
-				OC_Util::setupFS();
1010
-				OC::$server->getRouter()->match(\OC::$server->getRequest()->getRawPathInfo());
1011
-				return;
1012
-			} catch (Symfony\Component\Routing\Exception\ResourceNotFoundException $e) {
1013
-				//header('HTTP/1.0 404 Not Found');
1014
-			} catch (Symfony\Component\Routing\Exception\MethodNotAllowedException $e) {
1015
-				http_response_code(405);
1016
-				return;
1017
-			}
1018
-		}
1019
-
1020
-		// Handle WebDAV
1021
-		if (isset($_SERVER['REQUEST_METHOD']) && $_SERVER['REQUEST_METHOD'] === 'PROPFIND') {
1022
-			// not allowed any more to prevent people
1023
-			// mounting this root directly.
1024
-			// Users need to mount remote.php/webdav instead.
1025
-			http_response_code(405);
1026
-			return;
1027
-		}
1028
-
1029
-		// Someone is logged in
1030
-		if (\OC::$server->getUserSession()->isLoggedIn()) {
1031
-			OC_App::loadApps();
1032
-			OC_User::setupBackends();
1033
-			OC_Util::setupFS();
1034
-			// FIXME
1035
-			// Redirect to default application
1036
-			OC_Util::redirectToDefaultPage();
1037
-		} else {
1038
-			// Not handled and not logged in
1039
-			header('Location: '.\OC::$server->getURLGenerator()->linkToRouteAbsolute('core.login.showLoginForm'));
1040
-		}
1041
-	}
1042
-
1043
-	/**
1044
-	 * Check login: apache auth, auth token, basic auth
1045
-	 *
1046
-	 * @param OCP\IRequest $request
1047
-	 * @return boolean
1048
-	 */
1049
-	public static function handleLogin(OCP\IRequest $request) {
1050
-		$userSession = self::$server->getUserSession();
1051
-		if (OC_User::handleApacheAuth()) {
1052
-			return true;
1053
-		}
1054
-		if ($userSession->tryTokenLogin($request)) {
1055
-			return true;
1056
-		}
1057
-		if (isset($_COOKIE['nc_username'])
1058
-			&& isset($_COOKIE['nc_token'])
1059
-			&& isset($_COOKIE['nc_session_id'])
1060
-			&& $userSession->loginWithCookie($_COOKIE['nc_username'], $_COOKIE['nc_token'], $_COOKIE['nc_session_id'])) {
1061
-			return true;
1062
-		}
1063
-		if ($userSession->tryBasicAuthLogin($request, \OC::$server->getBruteForceThrottler())) {
1064
-			return true;
1065
-		}
1066
-		return false;
1067
-	}
1068
-
1069
-	protected static function handleAuthHeaders() {
1070
-		//copy http auth headers for apache+php-fcgid work around
1071
-		if (isset($_SERVER['HTTP_XAUTHORIZATION']) && !isset($_SERVER['HTTP_AUTHORIZATION'])) {
1072
-			$_SERVER['HTTP_AUTHORIZATION'] = $_SERVER['HTTP_XAUTHORIZATION'];
1073
-		}
1074
-
1075
-		// Extract PHP_AUTH_USER/PHP_AUTH_PW from other headers if necessary.
1076
-		$vars = [
1077
-			'HTTP_AUTHORIZATION', // apache+php-cgi work around
1078
-			'REDIRECT_HTTP_AUTHORIZATION', // apache+php-cgi alternative
1079
-		];
1080
-		foreach ($vars as $var) {
1081
-			if (isset($_SERVER[$var]) && preg_match('/Basic\s+(.*)$/i', $_SERVER[$var], $matches)) {
1082
-				$credentials = explode(':', base64_decode($matches[1]), 2);
1083
-				if (count($credentials) === 2) {
1084
-					$_SERVER['PHP_AUTH_USER'] = $credentials[0];
1085
-					$_SERVER['PHP_AUTH_PW'] = $credentials[1];
1086
-					break;
1087
-				}
1088
-			}
1089
-		}
1090
-	}
80
+    /**
81
+     * Associative array for autoloading. classname => filename
82
+     */
83
+    public static $CLASSPATH = [];
84
+    /**
85
+     * The installation path for Nextcloud  on the server (e.g. /srv/http/nextcloud)
86
+     */
87
+    public static $SERVERROOT = '';
88
+    /**
89
+     * the current request path relative to the Nextcloud root (e.g. files/index.php)
90
+     */
91
+    private static $SUBURI = '';
92
+    /**
93
+     * the Nextcloud root path for http requests (e.g. nextcloud/)
94
+     */
95
+    public static $WEBROOT = '';
96
+    /**
97
+     * The installation path array of the apps folder on the server (e.g. /srv/http/nextcloud) 'path' and
98
+     * web path in 'url'
99
+     */
100
+    public static $APPSROOTS = [];
101
+
102
+    /**
103
+     * @var string
104
+     */
105
+    public static $configDir;
106
+
107
+    /**
108
+     * requested app
109
+     */
110
+    public static $REQUESTEDAPP = '';
111
+
112
+    /**
113
+     * check if Nextcloud runs in cli mode
114
+     */
115
+    public static $CLI = false;
116
+
117
+    /**
118
+     * @var \OC\Autoloader $loader
119
+     */
120
+    public static $loader = null;
121
+
122
+    /** @var \Composer\Autoload\ClassLoader $composerAutoloader */
123
+    public static $composerAutoloader = null;
124
+
125
+    /**
126
+     * @var \OC\Server
127
+     */
128
+    public static $server = null;
129
+
130
+    /**
131
+     * @var \OC\Config
132
+     */
133
+    private static $config = null;
134
+
135
+    /**
136
+     * @throws \RuntimeException when the 3rdparty directory is missing or
137
+     * the app path list is empty or contains an invalid path
138
+     */
139
+    public static function initPaths() {
140
+        if (defined('PHPUNIT_CONFIG_DIR')) {
141
+            self::$configDir = OC::$SERVERROOT . '/' . PHPUNIT_CONFIG_DIR . '/';
142
+        } elseif (defined('PHPUNIT_RUN') and PHPUNIT_RUN and is_dir(OC::$SERVERROOT . '/tests/config/')) {
143
+            self::$configDir = OC::$SERVERROOT . '/tests/config/';
144
+        } elseif ($dir = getenv('NEXTCLOUD_CONFIG_DIR')) {
145
+            self::$configDir = rtrim($dir, '/') . '/';
146
+        } else {
147
+            self::$configDir = OC::$SERVERROOT . '/config/';
148
+        }
149
+        self::$config = new \OC\Config(self::$configDir);
150
+
151
+        OC::$SUBURI = str_replace("\\", "/", substr(realpath($_SERVER["SCRIPT_FILENAME"]), strlen(OC::$SERVERROOT)));
152
+        /**
153
+         * FIXME: The following lines are required because we can't yet instantiate
154
+         *        \OC::$server->getRequest() since \OC::$server does not yet exist.
155
+         */
156
+        $params = [
157
+            'server' => [
158
+                'SCRIPT_NAME' => $_SERVER['SCRIPT_NAME'],
159
+                'SCRIPT_FILENAME' => $_SERVER['SCRIPT_FILENAME'],
160
+            ],
161
+        ];
162
+        $fakeRequest = new \OC\AppFramework\Http\Request($params, null, new \OC\AllConfig(new \OC\SystemConfig(self::$config)));
163
+        $scriptName = $fakeRequest->getScriptName();
164
+        if (substr($scriptName, -1) == '/') {
165
+            $scriptName .= 'index.php';
166
+            //make sure suburi follows the same rules as scriptName
167
+            if (substr(OC::$SUBURI, -9) != 'index.php') {
168
+                if (substr(OC::$SUBURI, -1) != '/') {
169
+                    OC::$SUBURI = OC::$SUBURI . '/';
170
+                }
171
+                OC::$SUBURI = OC::$SUBURI . 'index.php';
172
+            }
173
+        }
174
+
175
+
176
+        if (OC::$CLI) {
177
+            OC::$WEBROOT = self::$config->getValue('overwritewebroot', '');
178
+        } else {
179
+            if (substr($scriptName, 0 - strlen(OC::$SUBURI)) === OC::$SUBURI) {
180
+                OC::$WEBROOT = substr($scriptName, 0, 0 - strlen(OC::$SUBURI));
181
+
182
+                if (OC::$WEBROOT != '' && OC::$WEBROOT[0] !== '/') {
183
+                    OC::$WEBROOT = '/' . OC::$WEBROOT;
184
+                }
185
+            } else {
186
+                // The scriptName is not ending with OC::$SUBURI
187
+                // This most likely means that we are calling from CLI.
188
+                // However some cron jobs still need to generate
189
+                // a web URL, so we use overwritewebroot as a fallback.
190
+                OC::$WEBROOT = self::$config->getValue('overwritewebroot', '');
191
+            }
192
+
193
+            // Resolve /nextcloud to /nextcloud/ to ensure to always have a trailing
194
+            // slash which is required by URL generation.
195
+            if (isset($_SERVER['REQUEST_URI']) && $_SERVER['REQUEST_URI'] === \OC::$WEBROOT &&
196
+                    substr($_SERVER['REQUEST_URI'], -1) !== '/') {
197
+                header('Location: '.\OC::$WEBROOT.'/');
198
+                exit();
199
+            }
200
+        }
201
+
202
+        // search the apps folder
203
+        $config_paths = self::$config->getValue('apps_paths', []);
204
+        if (!empty($config_paths)) {
205
+            foreach ($config_paths as $paths) {
206
+                if (isset($paths['url']) && isset($paths['path'])) {
207
+                    $paths['url'] = rtrim($paths['url'], '/');
208
+                    $paths['path'] = rtrim($paths['path'], '/');
209
+                    OC::$APPSROOTS[] = $paths;
210
+                }
211
+            }
212
+        } elseif (file_exists(OC::$SERVERROOT . '/apps')) {
213
+            OC::$APPSROOTS[] = ['path' => OC::$SERVERROOT . '/apps', 'url' => '/apps', 'writable' => true];
214
+        } elseif (file_exists(OC::$SERVERROOT . '/../apps')) {
215
+            OC::$APPSROOTS[] = [
216
+                'path' => rtrim(dirname(OC::$SERVERROOT), '/') . '/apps',
217
+                'url' => '/apps',
218
+                'writable' => true
219
+            ];
220
+        }
221
+
222
+        if (empty(OC::$APPSROOTS)) {
223
+            throw new \RuntimeException('apps directory not found! Please put the Nextcloud apps folder in the Nextcloud folder'
224
+                . ' or the folder above. You can also configure the location in the config.php file.');
225
+        }
226
+        $paths = [];
227
+        foreach (OC::$APPSROOTS as $path) {
228
+            $paths[] = $path['path'];
229
+            if (!is_dir($path['path'])) {
230
+                throw new \RuntimeException(sprintf('App directory "%s" not found! Please put the Nextcloud apps folder in the'
231
+                    . ' Nextcloud folder or the folder above. You can also configure the location in the'
232
+                    . ' config.php file.', $path['path']));
233
+            }
234
+        }
235
+
236
+        // set the right include path
237
+        set_include_path(
238
+            implode(PATH_SEPARATOR, $paths)
239
+        );
240
+    }
241
+
242
+    public static function checkConfig() {
243
+        $l = \OC::$server->getL10N('lib');
244
+
245
+        // Create config if it does not already exist
246
+        $configFilePath = self::$configDir .'/config.php';
247
+        if (!file_exists($configFilePath)) {
248
+            @touch($configFilePath);
249
+        }
250
+
251
+        // Check if config is writable
252
+        $configFileWritable = is_writable($configFilePath);
253
+        if (!$configFileWritable && !OC_Helper::isReadOnlyConfigEnabled()
254
+            || !$configFileWritable && \OCP\Util::needUpgrade()) {
255
+            $urlGenerator = \OC::$server->getURLGenerator();
256
+
257
+            if (self::$CLI) {
258
+                echo $l->t('Cannot write into "config" directory!')."\n";
259
+                echo $l->t('This can usually be fixed by giving the webserver write access to the config directory')."\n";
260
+                echo "\n";
261
+                echo $l->t('Or, if you prefer to keep config.php file read only, set the option "config_is_read_only" to true in it.')."\n";
262
+                echo $l->t('See %s', [ $urlGenerator->linkToDocs('admin-config') ])."\n";
263
+                exit;
264
+            } else {
265
+                OC_Template::printErrorPage(
266
+                    $l->t('Cannot write into "config" directory!'),
267
+                    $l->t('This can usually be fixed by giving the webserver write access to the config directory.') . '. '
268
+                    . $l->t('Or, if you prefer to keep config.php file read only, set the option "config_is_read_only" to true in it. See %s',
269
+                    [ $urlGenerator->linkToDocs('admin-config') ]),
270
+                    503
271
+                );
272
+            }
273
+        }
274
+    }
275
+
276
+    public static function checkInstalled() {
277
+        if (defined('OC_CONSOLE')) {
278
+            return;
279
+        }
280
+        // Redirect to installer if not installed
281
+        if (!\OC::$server->getSystemConfig()->getValue('installed', false) && OC::$SUBURI !== '/index.php' && OC::$SUBURI !== '/status.php') {
282
+            if (OC::$CLI) {
283
+                throw new Exception('Not installed');
284
+            } else {
285
+                $url = OC::$WEBROOT . '/index.php';
286
+                header('Location: ' . $url);
287
+            }
288
+            exit();
289
+        }
290
+    }
291
+
292
+    public static function checkMaintenanceMode() {
293
+        // Allow ajax update script to execute without being stopped
294
+        if (((bool) \OC::$server->getSystemConfig()->getValue('maintenance', false)) && OC::$SUBURI != '/core/ajax/update.php') {
295
+            // send http status 503
296
+            http_response_code(503);
297
+            header('Retry-After: 120');
298
+
299
+            // render error page
300
+            $template = new OC_Template('', 'update.user', 'guest');
301
+            OC_Util::addScript('dist/maintenance');
302
+            OC_Util::addStyle('core', 'guest');
303
+            $template->printPage();
304
+            die();
305
+        }
306
+    }
307
+
308
+    /**
309
+     * Prints the upgrade page
310
+     *
311
+     * @param \OC\SystemConfig $systemConfig
312
+     */
313
+    private static function printUpgradePage(\OC\SystemConfig $systemConfig) {
314
+        $disableWebUpdater = $systemConfig->getValue('upgrade.disable-web', false);
315
+        $tooBig = false;
316
+        if (!$disableWebUpdater) {
317
+            $apps = \OC::$server->getAppManager();
318
+            if ($apps->isInstalled('user_ldap')) {
319
+                $qb = \OC::$server->getDatabaseConnection()->getQueryBuilder();
320
+
321
+                $result = $qb->select($qb->func()->count('*', 'user_count'))
322
+                    ->from('ldap_user_mapping')
323
+                    ->execute();
324
+                $row = $result->fetch();
325
+                $result->closeCursor();
326
+
327
+                $tooBig = ($row['user_count'] > 50);
328
+            }
329
+            if (!$tooBig && $apps->isInstalled('user_saml')) {
330
+                $qb = \OC::$server->getDatabaseConnection()->getQueryBuilder();
331
+
332
+                $result = $qb->select($qb->func()->count('*', 'user_count'))
333
+                    ->from('user_saml_users')
334
+                    ->execute();
335
+                $row = $result->fetch();
336
+                $result->closeCursor();
337
+
338
+                $tooBig = ($row['user_count'] > 50);
339
+            }
340
+            if (!$tooBig) {
341
+                // count users
342
+                $stats = \OC::$server->getUserManager()->countUsers();
343
+                $totalUsers = array_sum($stats);
344
+                $tooBig = ($totalUsers > 50);
345
+            }
346
+        }
347
+        $ignoreTooBigWarning = isset($_GET['IKnowThatThisIsABigInstanceAndTheUpdateRequestCouldRunIntoATimeoutAndHowToRestoreABackup']) &&
348
+            $_GET['IKnowThatThisIsABigInstanceAndTheUpdateRequestCouldRunIntoATimeoutAndHowToRestoreABackup'] === 'IAmSuperSureToDoThis';
349
+
350
+        if ($disableWebUpdater || ($tooBig && !$ignoreTooBigWarning)) {
351
+            // send http status 503
352
+            http_response_code(503);
353
+            header('Retry-After: 120');
354
+
355
+            // render error page
356
+            $template = new OC_Template('', 'update.use-cli', 'guest');
357
+            $template->assign('productName', 'nextcloud'); // for now
358
+            $template->assign('version', OC_Util::getVersionString());
359
+            $template->assign('tooBig', $tooBig);
360
+
361
+            $template->printPage();
362
+            die();
363
+        }
364
+
365
+        // check whether this is a core update or apps update
366
+        $installedVersion = $systemConfig->getValue('version', '0.0.0');
367
+        $currentVersion = implode('.', \OCP\Util::getVersion());
368
+
369
+        // if not a core upgrade, then it's apps upgrade
370
+        $isAppsOnlyUpgrade = version_compare($currentVersion, $installedVersion, '=');
371
+
372
+        $oldTheme = $systemConfig->getValue('theme');
373
+        $systemConfig->setValue('theme', '');
374
+        OC_Util::addScript('config'); // needed for web root
375
+        OC_Util::addScript('update');
376
+
377
+        /** @var \OC\App\AppManager $appManager */
378
+        $appManager = \OC::$server->getAppManager();
379
+
380
+        $tmpl = new OC_Template('', 'update.admin', 'guest');
381
+        $tmpl->assign('version', OC_Util::getVersionString());
382
+        $tmpl->assign('isAppsOnlyUpgrade', $isAppsOnlyUpgrade);
383
+
384
+        // get third party apps
385
+        $ocVersion = \OCP\Util::getVersion();
386
+        $ocVersion = implode('.', $ocVersion);
387
+        $incompatibleApps = $appManager->getIncompatibleApps($ocVersion);
388
+        $incompatibleShippedApps = [];
389
+        foreach ($incompatibleApps as $appInfo) {
390
+            if ($appManager->isShipped($appInfo['id'])) {
391
+                $incompatibleShippedApps[] = $appInfo['name'] . ' (' . $appInfo['id'] . ')';
392
+            }
393
+        }
394
+
395
+        if (!empty($incompatibleShippedApps)) {
396
+            $l = \OC::$server->getL10N('core');
397
+            $hint = $l->t('The files of the app %1$s were not replaced correctly. Make sure it is a version compatible with the server.', [implode(', ', $incompatibleShippedApps)]);
398
+            throw new \OC\HintException('The files of the app ' . implode(', ', $incompatibleShippedApps) . ' were not replaced correctly. Make sure it is a version compatible with the server.', $hint);
399
+        }
400
+
401
+        $tmpl->assign('appsToUpgrade', $appManager->getAppsNeedingUpgrade($ocVersion));
402
+        $tmpl->assign('incompatibleAppsList', $incompatibleApps);
403
+        $tmpl->assign('productName', 'Nextcloud'); // for now
404
+        $tmpl->assign('oldTheme', $oldTheme);
405
+        $tmpl->printPage();
406
+    }
407
+
408
+    public static function initSession() {
409
+        if (self::$server->getRequest()->getServerProtocol() === 'https') {
410
+            ini_set('session.cookie_secure', true);
411
+        }
412
+
413
+        // prevents javascript from accessing php session cookies
414
+        ini_set('session.cookie_httponly', 'true');
415
+
416
+        // set the cookie path to the Nextcloud directory
417
+        $cookie_path = OC::$WEBROOT ? : '/';
418
+        ini_set('session.cookie_path', $cookie_path);
419
+
420
+        // Let the session name be changed in the initSession Hook
421
+        $sessionName = OC_Util::getInstanceId();
422
+
423
+        try {
424
+            // set the session name to the instance id - which is unique
425
+            $session = new \OC\Session\Internal($sessionName);
426
+
427
+            $cryptoWrapper = \OC::$server->getSessionCryptoWrapper();
428
+            $session = $cryptoWrapper->wrapSession($session);
429
+            self::$server->setSession($session);
430
+
431
+            // if session can't be started break with http 500 error
432
+        } catch (Exception $e) {
433
+            \OC::$server->getLogger()->logException($e, ['app' => 'base']);
434
+            //show the user a detailed error page
435
+            OC_Template::printExceptionErrorPage($e, 500);
436
+            die();
437
+        }
438
+
439
+        $sessionLifeTime = self::getSessionLifeTime();
440
+
441
+        // session timeout
442
+        if ($session->exists('LAST_ACTIVITY') && (time() - $session->get('LAST_ACTIVITY') > $sessionLifeTime)) {
443
+            if (isset($_COOKIE[session_name()])) {
444
+                setcookie(session_name(), '', -1, self::$WEBROOT ? : '/');
445
+            }
446
+            \OC::$server->getUserSession()->logout();
447
+        }
448
+
449
+        $session->set('LAST_ACTIVITY', time());
450
+    }
451
+
452
+    /**
453
+     * @return string
454
+     */
455
+    private static function getSessionLifeTime() {
456
+        return \OC::$server->getConfig()->getSystemValue('session_lifetime', 60 * 60 * 24);
457
+    }
458
+
459
+    /**
460
+     * Try to set some values to the required Nextcloud default
461
+     */
462
+    public static function setRequiredIniValues() {
463
+        @ini_set('default_charset', 'UTF-8');
464
+        @ini_set('gd.jpeg_ignore_warning', '1');
465
+    }
466
+
467
+    /**
468
+     * Send the same site cookies
469
+     */
470
+    private static function sendSameSiteCookies() {
471
+        $cookieParams = session_get_cookie_params();
472
+        $secureCookie = ($cookieParams['secure'] === true) ? 'secure; ' : '';
473
+        $policies = [
474
+            'lax',
475
+            'strict',
476
+        ];
477
+
478
+        // Append __Host to the cookie if it meets the requirements
479
+        $cookiePrefix = '';
480
+        if ($cookieParams['secure'] === true && $cookieParams['path'] === '/') {
481
+            $cookiePrefix = '__Host-';
482
+        }
483
+
484
+        foreach ($policies as $policy) {
485
+            header(
486
+                sprintf(
487
+                    'Set-Cookie: %snc_sameSiteCookie%s=true; path=%s; httponly;' . $secureCookie . 'expires=Fri, 31-Dec-2100 23:59:59 GMT; SameSite=%s',
488
+                    $cookiePrefix,
489
+                    $policy,
490
+                    $cookieParams['path'],
491
+                    $policy
492
+                ),
493
+                false
494
+            );
495
+        }
496
+    }
497
+
498
+    /**
499
+     * Same Site cookie to further mitigate CSRF attacks. This cookie has to
500
+     * be set in every request if cookies are sent to add a second level of
501
+     * defense against CSRF.
502
+     *
503
+     * If the cookie is not sent this will set the cookie and reload the page.
504
+     * We use an additional cookie since we want to protect logout CSRF and
505
+     * also we can't directly interfere with PHP's session mechanism.
506
+     */
507
+    private static function performSameSiteCookieProtection() {
508
+        $request = \OC::$server->getRequest();
509
+
510
+        // Some user agents are notorious and don't really properly follow HTTP
511
+        // specifications. For those, have an automated opt-out. Since the protection
512
+        // for remote.php is applied in base.php as starting point we need to opt out
513
+        // here.
514
+        $incompatibleUserAgents = \OC::$server->getConfig()->getSystemValue('csrf.optout');
515
+
516
+        // Fallback, if csrf.optout is unset
517
+        if (!is_array($incompatibleUserAgents)) {
518
+            $incompatibleUserAgents = [
519
+                // OS X Finder
520
+                '/^WebDAVFS/',
521
+                // Windows webdav drive
522
+                '/^Microsoft-WebDAV-MiniRedir/',
523
+            ];
524
+        }
525
+
526
+        if ($request->isUserAgent($incompatibleUserAgents)) {
527
+            return;
528
+        }
529
+
530
+        if (count($_COOKIE) > 0) {
531
+            $requestUri = $request->getScriptName();
532
+            $processingScript = explode('/', $requestUri);
533
+            $processingScript = $processingScript[count($processingScript) - 1];
534
+
535
+            // index.php routes are handled in the middleware
536
+            if ($processingScript === 'index.php') {
537
+                return;
538
+            }
539
+
540
+            // All other endpoints require the lax and the strict cookie
541
+            if (!$request->passesStrictCookieCheck()) {
542
+                self::sendSameSiteCookies();
543
+                // Debug mode gets access to the resources without strict cookie
544
+                // due to the fact that the SabreDAV browser also lives there.
545
+                if (!\OC::$server->getConfig()->getSystemValue('debug', false)) {
546
+                    http_response_code(\OCP\AppFramework\Http::STATUS_SERVICE_UNAVAILABLE);
547
+                    exit();
548
+                }
549
+            }
550
+        } elseif (!isset($_COOKIE['nc_sameSiteCookielax']) || !isset($_COOKIE['nc_sameSiteCookiestrict'])) {
551
+            self::sendSameSiteCookies();
552
+        }
553
+    }
554
+
555
+    public static function init() {
556
+        // calculate the root directories
557
+        OC::$SERVERROOT = str_replace("\\", '/', substr(__DIR__, 0, -4));
558
+
559
+        // register autoloader
560
+        $loaderStart = microtime(true);
561
+        require_once __DIR__ . '/autoloader.php';
562
+        self::$loader = new \OC\Autoloader([
563
+            OC::$SERVERROOT . '/lib/private/legacy',
564
+        ]);
565
+        if (defined('PHPUNIT_RUN')) {
566
+            self::$loader->addValidRoot(OC::$SERVERROOT . '/tests');
567
+        }
568
+        spl_autoload_register([self::$loader, 'load']);
569
+        $loaderEnd = microtime(true);
570
+
571
+        self::$CLI = (php_sapi_name() == 'cli');
572
+
573
+        // Add default composer PSR-4 autoloader
574
+        self::$composerAutoloader = require_once OC::$SERVERROOT . '/lib/composer/autoload.php';
575
+
576
+        try {
577
+            self::initPaths();
578
+            // setup 3rdparty autoloader
579
+            $vendorAutoLoad = OC::$SERVERROOT. '/3rdparty/autoload.php';
580
+            if (!file_exists($vendorAutoLoad)) {
581
+                throw new \RuntimeException('Composer autoloader not found, unable to continue. Check the folder "3rdparty". Running "git submodule update --init" will initialize the git submodule that handles the subfolder "3rdparty".');
582
+            }
583
+            require_once $vendorAutoLoad;
584
+        } catch (\RuntimeException $e) {
585
+            if (!self::$CLI) {
586
+                http_response_code(503);
587
+            }
588
+            // we can't use the template error page here, because this needs the
589
+            // DI container which isn't available yet
590
+            print($e->getMessage());
591
+            exit();
592
+        }
593
+
594
+        // setup the basic server
595
+        self::$server = new \OC\Server(\OC::$WEBROOT, self::$config);
596
+        self::$server->boot();
597
+        \OC::$server->getEventLogger()->log('autoloader', 'Autoloader', $loaderStart, $loaderEnd);
598
+        \OC::$server->getEventLogger()->start('boot', 'Initialize');
599
+
600
+        // Override php.ini and log everything if we're troubleshooting
601
+        if (self::$config->getValue('loglevel') === ILogger::DEBUG) {
602
+            error_reporting(E_ALL);
603
+        }
604
+
605
+        // Don't display errors and log them
606
+        @ini_set('display_errors', '0');
607
+        @ini_set('log_errors', '1');
608
+
609
+        if (!date_default_timezone_set('UTC')) {
610
+            throw new \RuntimeException('Could not set timezone to UTC');
611
+        }
612
+
613
+        //try to configure php to enable big file uploads.
614
+        //this doesn´t work always depending on the webserver and php configuration.
615
+        //Let´s try to overwrite some defaults anyway
616
+
617
+        //try to set the maximum execution time to 60min
618
+        if (strpos(@ini_get('disable_functions'), 'set_time_limit') === false) {
619
+            @set_time_limit(3600);
620
+        }
621
+        @ini_set('max_execution_time', '3600');
622
+        @ini_set('max_input_time', '3600');
623
+
624
+        //try to set the maximum filesize to 10G
625
+        @ini_set('upload_max_filesize', '10G');
626
+        @ini_set('post_max_size', '10G');
627
+        @ini_set('file_uploads', '50');
628
+
629
+        self::setRequiredIniValues();
630
+        self::handleAuthHeaders();
631
+        self::registerAutoloaderCache();
632
+
633
+        // initialize intl fallback is necessary
634
+        \Patchwork\Utf8\Bootup::initIntl();
635
+        OC_Util::isSetLocaleWorking();
636
+
637
+        if (!defined('PHPUNIT_RUN')) {
638
+            OC\Log\ErrorHandler::setLogger(\OC::$server->getLogger());
639
+            $debug = \OC::$server->getConfig()->getSystemValue('debug', false);
640
+            OC\Log\ErrorHandler::register($debug);
641
+        }
642
+
643
+        /** @var \OC\AppFramework\Bootstrap\Coordinator $bootstrapCoordinator */
644
+        $bootstrapCoordinator = \OC::$server->query(\OC\AppFramework\Bootstrap\Coordinator::class);
645
+        $bootstrapCoordinator->runRegistration();
646
+
647
+        \OC::$server->getEventLogger()->start('init_session', 'Initialize session');
648
+        OC_App::loadApps(['session']);
649
+        if (!self::$CLI) {
650
+            self::initSession();
651
+        }
652
+        \OC::$server->getEventLogger()->end('init_session');
653
+        self::checkConfig();
654
+        self::checkInstalled();
655
+
656
+        OC_Response::addSecurityHeaders();
657
+
658
+        self::performSameSiteCookieProtection();
659
+
660
+        if (!defined('OC_CONSOLE')) {
661
+            $errors = OC_Util::checkServer(\OC::$server->getSystemConfig());
662
+            if (count($errors) > 0) {
663
+                if (!self::$CLI) {
664
+                    http_response_code(503);
665
+                    OC_Util::addStyle('guest');
666
+                    try {
667
+                        OC_Template::printGuestPage('', 'error', ['errors' => $errors]);
668
+                        exit;
669
+                    } catch (\Exception $e) {
670
+                        // In case any error happens when showing the error page, we simply fall back to posting the text.
671
+                        // This might be the case when e.g. the data directory is broken and we can not load/write SCSS to/from it.
672
+                    }
673
+                }
674
+
675
+                // Convert l10n string into regular string for usage in database
676
+                $staticErrors = [];
677
+                foreach ($errors as $error) {
678
+                    echo $error['error'] . "\n";
679
+                    echo $error['hint'] . "\n\n";
680
+                    $staticErrors[] = [
681
+                        'error' => (string)$error['error'],
682
+                        'hint' => (string)$error['hint'],
683
+                    ];
684
+                }
685
+
686
+                try {
687
+                    \OC::$server->getConfig()->setAppValue('core', 'cronErrors', json_encode($staticErrors));
688
+                } catch (\Exception $e) {
689
+                    echo('Writing to database failed');
690
+                }
691
+                exit(1);
692
+            } elseif (self::$CLI && \OC::$server->getConfig()->getSystemValue('installed', false)) {
693
+                \OC::$server->getConfig()->deleteAppValue('core', 'cronErrors');
694
+            }
695
+        }
696
+        //try to set the session lifetime
697
+        $sessionLifeTime = self::getSessionLifeTime();
698
+        @ini_set('gc_maxlifetime', (string)$sessionLifeTime);
699
+
700
+        $systemConfig = \OC::$server->getSystemConfig();
701
+
702
+        // User and Groups
703
+        if (!$systemConfig->getValue("installed", false)) {
704
+            self::$server->getSession()->set('user_id', '');
705
+        }
706
+
707
+        OC_User::useBackend(new \OC\User\Database());
708
+        \OC::$server->getGroupManager()->addBackend(new \OC\Group\Database());
709
+
710
+        // Subscribe to the hook
711
+        \OCP\Util::connectHook(
712
+            '\OCA\Files_Sharing\API\Server2Server',
713
+            'preLoginNameUsedAsUserName',
714
+            '\OC\User\Database',
715
+            'preLoginNameUsedAsUserName'
716
+        );
717
+
718
+        //setup extra user backends
719
+        if (!\OCP\Util::needUpgrade()) {
720
+            OC_User::setupBackends();
721
+        } else {
722
+            // Run upgrades in incognito mode
723
+            OC_User::setIncognitoMode(true);
724
+        }
725
+
726
+        self::registerCleanupHooks();
727
+        self::registerFilesystemHooks();
728
+        self::registerShareHooks();
729
+        self::registerEncryptionWrapper();
730
+        self::registerEncryptionHooks();
731
+        self::registerAccountHooks();
732
+        self::registerResourceCollectionHooks();
733
+        self::registerAppRestrictionsHooks();
734
+
735
+        // Make sure that the application class is not loaded before the database is setup
736
+        if ($systemConfig->getValue("installed", false)) {
737
+            OC_App::loadApp('settings');
738
+        }
739
+
740
+        //make sure temporary files are cleaned up
741
+        $tmpManager = \OC::$server->getTempManager();
742
+        register_shutdown_function([$tmpManager, 'clean']);
743
+        $lockProvider = \OC::$server->getLockingProvider();
744
+        register_shutdown_function([$lockProvider, 'releaseAll']);
745
+
746
+        // Check whether the sample configuration has been copied
747
+        if ($systemConfig->getValue('copied_sample_config', false)) {
748
+            $l = \OC::$server->getL10N('lib');
749
+            OC_Template::printErrorPage(
750
+                $l->t('Sample configuration detected'),
751
+                $l->t('It has been detected that the sample configuration has been copied. This can break your installation and is unsupported. Please read the documentation before performing changes on config.php'),
752
+                503
753
+            );
754
+            return;
755
+        }
756
+
757
+        $request = \OC::$server->getRequest();
758
+        $host = $request->getInsecureServerHost();
759
+        /**
760
+         * if the host passed in headers isn't trusted
761
+         * FIXME: Should not be in here at all :see_no_evil:
762
+         */
763
+        if (!OC::$CLI
764
+            && !\OC::$server->getTrustedDomainHelper()->isTrustedDomain($host)
765
+            && self::$server->getConfig()->getSystemValue('installed', false)
766
+        ) {
767
+            // Allow access to CSS resources
768
+            $isScssRequest = false;
769
+            if (strpos($request->getPathInfo(), '/css/') === 0) {
770
+                $isScssRequest = true;
771
+            }
772
+
773
+            if (substr($request->getRequestUri(), -11) === '/status.php') {
774
+                http_response_code(400);
775
+                header('Content-Type: application/json');
776
+                echo '{"error": "Trusted domain error.", "code": 15}';
777
+                exit();
778
+            }
779
+
780
+            if (!$isScssRequest) {
781
+                http_response_code(400);
782
+
783
+                \OC::$server->getLogger()->info(
784
+                    'Trusted domain error. "{remoteAddress}" tried to access using "{host}" as host.',
785
+                    [
786
+                        'app' => 'core',
787
+                        'remoteAddress' => $request->getRemoteAddress(),
788
+                        'host' => $host,
789
+                    ]
790
+                );
791
+
792
+                $tmpl = new OCP\Template('core', 'untrustedDomain', 'guest');
793
+                $tmpl->assign('docUrl', \OC::$server->getURLGenerator()->linkToDocs('admin-trusted-domains'));
794
+                $tmpl->printPage();
795
+
796
+                exit();
797
+            }
798
+        }
799
+        \OC::$server->getEventLogger()->end('boot');
800
+    }
801
+
802
+    /**
803
+     * register hooks for the cleanup of cache and bruteforce protection
804
+     */
805
+    public static function registerCleanupHooks() {
806
+        //don't try to do this before we are properly setup
807
+        if (\OC::$server->getSystemConfig()->getValue('installed', false) && !\OCP\Util::needUpgrade()) {
808
+
809
+            // NOTE: This will be replaced to use OCP
810
+            $userSession = self::$server->getUserSession();
811
+            $userSession->listen('\OC\User', 'postLogin', function () use ($userSession) {
812
+                if (!defined('PHPUNIT_RUN') && $userSession->isLoggedIn()) {
813
+                    // reset brute force delay for this IP address and username
814
+                    $uid = \OC::$server->getUserSession()->getUser()->getUID();
815
+                    $request = \OC::$server->getRequest();
816
+                    $throttler = \OC::$server->getBruteForceThrottler();
817
+                    $throttler->resetDelay($request->getRemoteAddress(), 'login', ['user' => $uid]);
818
+                }
819
+
820
+                try {
821
+                    $cache = new \OC\Cache\File();
822
+                    $cache->gc();
823
+                } catch (\OC\ServerNotAvailableException $e) {
824
+                    // not a GC exception, pass it on
825
+                    throw $e;
826
+                } catch (\OC\ForbiddenException $e) {
827
+                    // filesystem blocked for this request, ignore
828
+                } catch (\Exception $e) {
829
+                    // a GC exception should not prevent users from using OC,
830
+                    // so log the exception
831
+                    \OC::$server->getLogger()->logException($e, [
832
+                        'message' => 'Exception when running cache gc.',
833
+                        'level' => ILogger::WARN,
834
+                        'app' => 'core',
835
+                    ]);
836
+                }
837
+            });
838
+        }
839
+    }
840
+
841
+    private static function registerEncryptionWrapper() {
842
+        $manager = self::$server->getEncryptionManager();
843
+        \OCP\Util::connectHook('OC_Filesystem', 'preSetup', $manager, 'setupStorage');
844
+    }
845
+
846
+    private static function registerEncryptionHooks() {
847
+        $enabled = self::$server->getEncryptionManager()->isEnabled();
848
+        if ($enabled) {
849
+            \OCP\Util::connectHook(Share::class, 'post_shared', HookManager::class, 'postShared');
850
+            \OCP\Util::connectHook(Share::class, 'post_unshare', HookManager::class, 'postUnshared');
851
+            \OCP\Util::connectHook('OC_Filesystem', 'post_rename', HookManager::class, 'postRename');
852
+            \OCP\Util::connectHook('\OCA\Files_Trashbin\Trashbin', 'post_restore', HookManager::class, 'postRestore');
853
+        }
854
+    }
855
+
856
+    private static function registerAccountHooks() {
857
+        $hookHandler = new \OC\Accounts\Hooks(\OC::$server->getLogger());
858
+        \OCP\Util::connectHook('OC_User', 'changeUser', $hookHandler, 'changeUserHook');
859
+    }
860
+
861
+    private static function registerAppRestrictionsHooks() {
862
+        /** @var \OC\Group\Manager $groupManager */
863
+        $groupManager = self::$server->query(\OCP\IGroupManager::class);
864
+        $groupManager->listen('\OC\Group', 'postDelete', function (\OCP\IGroup $group) {
865
+            $appManager = self::$server->getAppManager();
866
+            $apps = $appManager->getEnabledAppsForGroup($group);
867
+            foreach ($apps as $appId) {
868
+                $restrictions = $appManager->getAppRestriction($appId);
869
+                if (empty($restrictions)) {
870
+                    continue;
871
+                }
872
+                $key = array_search($group->getGID(), $restrictions);
873
+                unset($restrictions[$key]);
874
+                $restrictions = array_values($restrictions);
875
+                if (empty($restrictions)) {
876
+                    $appManager->disableApp($appId);
877
+                } else {
878
+                    $appManager->enableAppForGroups($appId, $restrictions);
879
+                }
880
+            }
881
+        });
882
+    }
883
+
884
+    private static function registerResourceCollectionHooks() {
885
+        \OC\Collaboration\Resources\Listener::register(\OC::$server->getEventDispatcher());
886
+    }
887
+
888
+    /**
889
+     * register hooks for the filesystem
890
+     */
891
+    public static function registerFilesystemHooks() {
892
+        // Check for blacklisted files
893
+        OC_Hook::connect('OC_Filesystem', 'write', Filesystem::class, 'isBlacklisted');
894
+        OC_Hook::connect('OC_Filesystem', 'rename', Filesystem::class, 'isBlacklisted');
895
+    }
896
+
897
+    /**
898
+     * register hooks for sharing
899
+     */
900
+    public static function registerShareHooks() {
901
+        if (\OC::$server->getSystemConfig()->getValue('installed')) {
902
+            OC_Hook::connect('OC_User', 'post_deleteUser', Hooks::class, 'post_deleteUser');
903
+            OC_Hook::connect('OC_User', 'post_deleteGroup', Hooks::class, 'post_deleteGroup');
904
+
905
+            /** @var IEventDispatcher $dispatcher */
906
+            $dispatcher = \OC::$server->get(IEventDispatcher::class);
907
+            $dispatcher->addServiceListener(UserRemovedEvent::class, \OC\Share20\UserRemovedListener::class);
908
+        }
909
+    }
910
+
911
+    protected static function registerAutoloaderCache() {
912
+        // The class loader takes an optional low-latency cache, which MUST be
913
+        // namespaced. The instanceid is used for namespacing, but might be
914
+        // unavailable at this point. Furthermore, it might not be possible to
915
+        // generate an instanceid via \OC_Util::getInstanceId() because the
916
+        // config file may not be writable. As such, we only register a class
917
+        // loader cache if instanceid is available without trying to create one.
918
+        $instanceId = \OC::$server->getSystemConfig()->getValue('instanceid', null);
919
+        if ($instanceId) {
920
+            try {
921
+                $memcacheFactory = \OC::$server->getMemCacheFactory();
922
+                self::$loader->setMemoryCache($memcacheFactory->createLocal('Autoloader'));
923
+            } catch (\Exception $ex) {
924
+            }
925
+        }
926
+    }
927
+
928
+    /**
929
+     * Handle the request
930
+     */
931
+    public static function handleRequest() {
932
+        \OC::$server->getEventLogger()->start('handle_request', 'Handle request');
933
+        $systemConfig = \OC::$server->getSystemConfig();
934
+
935
+        // Check if Nextcloud is installed or in maintenance (update) mode
936
+        if (!$systemConfig->getValue('installed', false)) {
937
+            \OC::$server->getSession()->clear();
938
+            $setupHelper = new OC\Setup(
939
+                $systemConfig,
940
+                \OC::$server->get(\bantu\IniGetWrapper\IniGetWrapper::class),
941
+                \OC::$server->getL10N('lib'),
942
+                \OC::$server->query(\OCP\Defaults::class),
943
+                \OC::$server->getLogger(),
944
+                \OC::$server->getSecureRandom(),
945
+                \OC::$server->query(\OC\Installer::class)
946
+            );
947
+            $controller = new OC\Core\Controller\SetupController($setupHelper);
948
+            $controller->run($_POST);
949
+            exit();
950
+        }
951
+
952
+        $request = \OC::$server->getRequest();
953
+        $requestPath = $request->getRawPathInfo();
954
+        if ($requestPath === '/heartbeat') {
955
+            return;
956
+        }
957
+        if (substr($requestPath, -3) !== '.js') { // we need these files during the upgrade
958
+            self::checkMaintenanceMode();
959
+
960
+            if (\OCP\Util::needUpgrade()) {
961
+                if (function_exists('opcache_reset')) {
962
+                    opcache_reset();
963
+                }
964
+                if (!((bool) $systemConfig->getValue('maintenance', false))) {
965
+                    self::printUpgradePage($systemConfig);
966
+                    exit();
967
+                }
968
+            }
969
+        }
970
+
971
+        // emergency app disabling
972
+        if ($requestPath === '/disableapp'
973
+            && $request->getMethod() === 'POST'
974
+            && ((array)$request->getParam('appid')) !== ''
975
+        ) {
976
+            \OC_JSON::callCheck();
977
+            \OC_JSON::checkAdminUser();
978
+            $appIds = (array)$request->getParam('appid');
979
+            foreach ($appIds as $appId) {
980
+                $appId = \OC_App::cleanAppId($appId);
981
+                \OC::$server->getAppManager()->disableApp($appId);
982
+            }
983
+            \OC_JSON::success();
984
+            exit();
985
+        }
986
+
987
+        // Always load authentication apps
988
+        OC_App::loadApps(['authentication']);
989
+
990
+        // Load minimum set of apps
991
+        if (!\OCP\Util::needUpgrade()
992
+            && !((bool) $systemConfig->getValue('maintenance', false))) {
993
+            // For logged-in users: Load everything
994
+            if (\OC::$server->getUserSession()->isLoggedIn()) {
995
+                OC_App::loadApps();
996
+            } else {
997
+                // For guests: Load only filesystem and logging
998
+                OC_App::loadApps(['filesystem', 'logging']);
999
+                self::handleLogin($request);
1000
+            }
1001
+        }
1002
+
1003
+        if (!self::$CLI) {
1004
+            try {
1005
+                if (!((bool) $systemConfig->getValue('maintenance', false)) && !\OCP\Util::needUpgrade()) {
1006
+                    OC_App::loadApps(['filesystem', 'logging']);
1007
+                    OC_App::loadApps();
1008
+                }
1009
+                OC_Util::setupFS();
1010
+                OC::$server->getRouter()->match(\OC::$server->getRequest()->getRawPathInfo());
1011
+                return;
1012
+            } catch (Symfony\Component\Routing\Exception\ResourceNotFoundException $e) {
1013
+                //header('HTTP/1.0 404 Not Found');
1014
+            } catch (Symfony\Component\Routing\Exception\MethodNotAllowedException $e) {
1015
+                http_response_code(405);
1016
+                return;
1017
+            }
1018
+        }
1019
+
1020
+        // Handle WebDAV
1021
+        if (isset($_SERVER['REQUEST_METHOD']) && $_SERVER['REQUEST_METHOD'] === 'PROPFIND') {
1022
+            // not allowed any more to prevent people
1023
+            // mounting this root directly.
1024
+            // Users need to mount remote.php/webdav instead.
1025
+            http_response_code(405);
1026
+            return;
1027
+        }
1028
+
1029
+        // Someone is logged in
1030
+        if (\OC::$server->getUserSession()->isLoggedIn()) {
1031
+            OC_App::loadApps();
1032
+            OC_User::setupBackends();
1033
+            OC_Util::setupFS();
1034
+            // FIXME
1035
+            // Redirect to default application
1036
+            OC_Util::redirectToDefaultPage();
1037
+        } else {
1038
+            // Not handled and not logged in
1039
+            header('Location: '.\OC::$server->getURLGenerator()->linkToRouteAbsolute('core.login.showLoginForm'));
1040
+        }
1041
+    }
1042
+
1043
+    /**
1044
+     * Check login: apache auth, auth token, basic auth
1045
+     *
1046
+     * @param OCP\IRequest $request
1047
+     * @return boolean
1048
+     */
1049
+    public static function handleLogin(OCP\IRequest $request) {
1050
+        $userSession = self::$server->getUserSession();
1051
+        if (OC_User::handleApacheAuth()) {
1052
+            return true;
1053
+        }
1054
+        if ($userSession->tryTokenLogin($request)) {
1055
+            return true;
1056
+        }
1057
+        if (isset($_COOKIE['nc_username'])
1058
+            && isset($_COOKIE['nc_token'])
1059
+            && isset($_COOKIE['nc_session_id'])
1060
+            && $userSession->loginWithCookie($_COOKIE['nc_username'], $_COOKIE['nc_token'], $_COOKIE['nc_session_id'])) {
1061
+            return true;
1062
+        }
1063
+        if ($userSession->tryBasicAuthLogin($request, \OC::$server->getBruteForceThrottler())) {
1064
+            return true;
1065
+        }
1066
+        return false;
1067
+    }
1068
+
1069
+    protected static function handleAuthHeaders() {
1070
+        //copy http auth headers for apache+php-fcgid work around
1071
+        if (isset($_SERVER['HTTP_XAUTHORIZATION']) && !isset($_SERVER['HTTP_AUTHORIZATION'])) {
1072
+            $_SERVER['HTTP_AUTHORIZATION'] = $_SERVER['HTTP_XAUTHORIZATION'];
1073
+        }
1074
+
1075
+        // Extract PHP_AUTH_USER/PHP_AUTH_PW from other headers if necessary.
1076
+        $vars = [
1077
+            'HTTP_AUTHORIZATION', // apache+php-cgi work around
1078
+            'REDIRECT_HTTP_AUTHORIZATION', // apache+php-cgi alternative
1079
+        ];
1080
+        foreach ($vars as $var) {
1081
+            if (isset($_SERVER[$var]) && preg_match('/Basic\s+(.*)$/i', $_SERVER[$var], $matches)) {
1082
+                $credentials = explode(':', base64_decode($matches[1]), 2);
1083
+                if (count($credentials) === 2) {
1084
+                    $_SERVER['PHP_AUTH_USER'] = $credentials[0];
1085
+                    $_SERVER['PHP_AUTH_PW'] = $credentials[1];
1086
+                    break;
1087
+                }
1088
+            }
1089
+        }
1090
+    }
1091 1091
 }
1092 1092
 
1093 1093
 OC::init();
Please login to merge, or discard this patch.
Spacing   +37 added lines, -37 removed lines patch added patch discarded remove patch
@@ -138,13 +138,13 @@  discard block
 block discarded – undo
138 138
 	 */
139 139
 	public static function initPaths() {
140 140
 		if (defined('PHPUNIT_CONFIG_DIR')) {
141
-			self::$configDir = OC::$SERVERROOT . '/' . PHPUNIT_CONFIG_DIR . '/';
142
-		} elseif (defined('PHPUNIT_RUN') and PHPUNIT_RUN and is_dir(OC::$SERVERROOT . '/tests/config/')) {
143
-			self::$configDir = OC::$SERVERROOT . '/tests/config/';
141
+			self::$configDir = OC::$SERVERROOT.'/'.PHPUNIT_CONFIG_DIR.'/';
142
+		} elseif (defined('PHPUNIT_RUN') and PHPUNIT_RUN and is_dir(OC::$SERVERROOT.'/tests/config/')) {
143
+			self::$configDir = OC::$SERVERROOT.'/tests/config/';
144 144
 		} elseif ($dir = getenv('NEXTCLOUD_CONFIG_DIR')) {
145
-			self::$configDir = rtrim($dir, '/') . '/';
145
+			self::$configDir = rtrim($dir, '/').'/';
146 146
 		} else {
147
-			self::$configDir = OC::$SERVERROOT . '/config/';
147
+			self::$configDir = OC::$SERVERROOT.'/config/';
148 148
 		}
149 149
 		self::$config = new \OC\Config(self::$configDir);
150 150
 
@@ -166,9 +166,9 @@  discard block
 block discarded – undo
166 166
 			//make sure suburi follows the same rules as scriptName
167 167
 			if (substr(OC::$SUBURI, -9) != 'index.php') {
168 168
 				if (substr(OC::$SUBURI, -1) != '/') {
169
-					OC::$SUBURI = OC::$SUBURI . '/';
169
+					OC::$SUBURI = OC::$SUBURI.'/';
170 170
 				}
171
-				OC::$SUBURI = OC::$SUBURI . 'index.php';
171
+				OC::$SUBURI = OC::$SUBURI.'index.php';
172 172
 			}
173 173
 		}
174 174
 
@@ -180,7 +180,7 @@  discard block
 block discarded – undo
180 180
 				OC::$WEBROOT = substr($scriptName, 0, 0 - strlen(OC::$SUBURI));
181 181
 
182 182
 				if (OC::$WEBROOT != '' && OC::$WEBROOT[0] !== '/') {
183
-					OC::$WEBROOT = '/' . OC::$WEBROOT;
183
+					OC::$WEBROOT = '/'.OC::$WEBROOT;
184 184
 				}
185 185
 			} else {
186 186
 				// The scriptName is not ending with OC::$SUBURI
@@ -209,11 +209,11 @@  discard block
 block discarded – undo
209 209
 					OC::$APPSROOTS[] = $paths;
210 210
 				}
211 211
 			}
212
-		} elseif (file_exists(OC::$SERVERROOT . '/apps')) {
213
-			OC::$APPSROOTS[] = ['path' => OC::$SERVERROOT . '/apps', 'url' => '/apps', 'writable' => true];
214
-		} elseif (file_exists(OC::$SERVERROOT . '/../apps')) {
212
+		} elseif (file_exists(OC::$SERVERROOT.'/apps')) {
213
+			OC::$APPSROOTS[] = ['path' => OC::$SERVERROOT.'/apps', 'url' => '/apps', 'writable' => true];
214
+		} elseif (file_exists(OC::$SERVERROOT.'/../apps')) {
215 215
 			OC::$APPSROOTS[] = [
216
-				'path' => rtrim(dirname(OC::$SERVERROOT), '/') . '/apps',
216
+				'path' => rtrim(dirname(OC::$SERVERROOT), '/').'/apps',
217 217
 				'url' => '/apps',
218 218
 				'writable' => true
219 219
 			];
@@ -243,7 +243,7 @@  discard block
 block discarded – undo
243 243
 		$l = \OC::$server->getL10N('lib');
244 244
 
245 245
 		// Create config if it does not already exist
246
-		$configFilePath = self::$configDir .'/config.php';
246
+		$configFilePath = self::$configDir.'/config.php';
247 247
 		if (!file_exists($configFilePath)) {
248 248
 			@touch($configFilePath);
249 249
 		}
@@ -259,14 +259,14 @@  discard block
 block discarded – undo
259 259
 				echo $l->t('This can usually be fixed by giving the webserver write access to the config directory')."\n";
260 260
 				echo "\n";
261 261
 				echo $l->t('Or, if you prefer to keep config.php file read only, set the option "config_is_read_only" to true in it.')."\n";
262
-				echo $l->t('See %s', [ $urlGenerator->linkToDocs('admin-config') ])."\n";
262
+				echo $l->t('See %s', [$urlGenerator->linkToDocs('admin-config')])."\n";
263 263
 				exit;
264 264
 			} else {
265 265
 				OC_Template::printErrorPage(
266 266
 					$l->t('Cannot write into "config" directory!'),
267
-					$l->t('This can usually be fixed by giving the webserver write access to the config directory.') . '. '
267
+					$l->t('This can usually be fixed by giving the webserver write access to the config directory.').'. '
268 268
 					. $l->t('Or, if you prefer to keep config.php file read only, set the option "config_is_read_only" to true in it. See %s',
269
-					[ $urlGenerator->linkToDocs('admin-config') ]),
269
+					[$urlGenerator->linkToDocs('admin-config')]),
270 270
 					503
271 271
 				);
272 272
 			}
@@ -282,8 +282,8 @@  discard block
 block discarded – undo
282 282
 			if (OC::$CLI) {
283 283
 				throw new Exception('Not installed');
284 284
 			} else {
285
-				$url = OC::$WEBROOT . '/index.php';
286
-				header('Location: ' . $url);
285
+				$url = OC::$WEBROOT.'/index.php';
286
+				header('Location: '.$url);
287 287
 			}
288 288
 			exit();
289 289
 		}
@@ -388,14 +388,14 @@  discard block
 block discarded – undo
388 388
 		$incompatibleShippedApps = [];
389 389
 		foreach ($incompatibleApps as $appInfo) {
390 390
 			if ($appManager->isShipped($appInfo['id'])) {
391
-				$incompatibleShippedApps[] = $appInfo['name'] . ' (' . $appInfo['id'] . ')';
391
+				$incompatibleShippedApps[] = $appInfo['name'].' ('.$appInfo['id'].')';
392 392
 			}
393 393
 		}
394 394
 
395 395
 		if (!empty($incompatibleShippedApps)) {
396 396
 			$l = \OC::$server->getL10N('core');
397 397
 			$hint = $l->t('The files of the app %1$s were not replaced correctly. Make sure it is a version compatible with the server.', [implode(', ', $incompatibleShippedApps)]);
398
-			throw new \OC\HintException('The files of the app ' . implode(', ', $incompatibleShippedApps) . ' were not replaced correctly. Make sure it is a version compatible with the server.', $hint);
398
+			throw new \OC\HintException('The files of the app '.implode(', ', $incompatibleShippedApps).' were not replaced correctly. Make sure it is a version compatible with the server.', $hint);
399 399
 		}
400 400
 
401 401
 		$tmpl->assign('appsToUpgrade', $appManager->getAppsNeedingUpgrade($ocVersion));
@@ -414,7 +414,7 @@  discard block
 block discarded – undo
414 414
 		ini_set('session.cookie_httponly', 'true');
415 415
 
416 416
 		// set the cookie path to the Nextcloud directory
417
-		$cookie_path = OC::$WEBROOT ? : '/';
417
+		$cookie_path = OC::$WEBROOT ?: '/';
418 418
 		ini_set('session.cookie_path', $cookie_path);
419 419
 
420 420
 		// Let the session name be changed in the initSession Hook
@@ -441,7 +441,7 @@  discard block
 block discarded – undo
441 441
 		// session timeout
442 442
 		if ($session->exists('LAST_ACTIVITY') && (time() - $session->get('LAST_ACTIVITY') > $sessionLifeTime)) {
443 443
 			if (isset($_COOKIE[session_name()])) {
444
-				setcookie(session_name(), '', -1, self::$WEBROOT ? : '/');
444
+				setcookie(session_name(), '', -1, self::$WEBROOT ?: '/');
445 445
 			}
446 446
 			\OC::$server->getUserSession()->logout();
447 447
 		}
@@ -484,7 +484,7 @@  discard block
 block discarded – undo
484 484
 		foreach ($policies as $policy) {
485 485
 			header(
486 486
 				sprintf(
487
-					'Set-Cookie: %snc_sameSiteCookie%s=true; path=%s; httponly;' . $secureCookie . 'expires=Fri, 31-Dec-2100 23:59:59 GMT; SameSite=%s',
487
+					'Set-Cookie: %snc_sameSiteCookie%s=true; path=%s; httponly;'.$secureCookie.'expires=Fri, 31-Dec-2100 23:59:59 GMT; SameSite=%s',
488 488
 					$cookiePrefix,
489 489
 					$policy,
490 490
 					$cookieParams['path'],
@@ -558,12 +558,12 @@  discard block
 block discarded – undo
558 558
 
559 559
 		// register autoloader
560 560
 		$loaderStart = microtime(true);
561
-		require_once __DIR__ . '/autoloader.php';
561
+		require_once __DIR__.'/autoloader.php';
562 562
 		self::$loader = new \OC\Autoloader([
563
-			OC::$SERVERROOT . '/lib/private/legacy',
563
+			OC::$SERVERROOT.'/lib/private/legacy',
564 564
 		]);
565 565
 		if (defined('PHPUNIT_RUN')) {
566
-			self::$loader->addValidRoot(OC::$SERVERROOT . '/tests');
566
+			self::$loader->addValidRoot(OC::$SERVERROOT.'/tests');
567 567
 		}
568 568
 		spl_autoload_register([self::$loader, 'load']);
569 569
 		$loaderEnd = microtime(true);
@@ -571,12 +571,12 @@  discard block
 block discarded – undo
571 571
 		self::$CLI = (php_sapi_name() == 'cli');
572 572
 
573 573
 		// Add default composer PSR-4 autoloader
574
-		self::$composerAutoloader = require_once OC::$SERVERROOT . '/lib/composer/autoload.php';
574
+		self::$composerAutoloader = require_once OC::$SERVERROOT.'/lib/composer/autoload.php';
575 575
 
576 576
 		try {
577 577
 			self::initPaths();
578 578
 			// setup 3rdparty autoloader
579
-			$vendorAutoLoad = OC::$SERVERROOT. '/3rdparty/autoload.php';
579
+			$vendorAutoLoad = OC::$SERVERROOT.'/3rdparty/autoload.php';
580 580
 			if (!file_exists($vendorAutoLoad)) {
581 581
 				throw new \RuntimeException('Composer autoloader not found, unable to continue. Check the folder "3rdparty". Running "git submodule update --init" will initialize the git submodule that handles the subfolder "3rdparty".');
582 582
 			}
@@ -675,11 +675,11 @@  discard block
 block discarded – undo
675 675
 				// Convert l10n string into regular string for usage in database
676 676
 				$staticErrors = [];
677 677
 				foreach ($errors as $error) {
678
-					echo $error['error'] . "\n";
679
-					echo $error['hint'] . "\n\n";
678
+					echo $error['error']."\n";
679
+					echo $error['hint']."\n\n";
680 680
 					$staticErrors[] = [
681
-						'error' => (string)$error['error'],
682
-						'hint' => (string)$error['hint'],
681
+						'error' => (string) $error['error'],
682
+						'hint' => (string) $error['hint'],
683 683
 					];
684 684
 				}
685 685
 
@@ -695,7 +695,7 @@  discard block
 block discarded – undo
695 695
 		}
696 696
 		//try to set the session lifetime
697 697
 		$sessionLifeTime = self::getSessionLifeTime();
698
-		@ini_set('gc_maxlifetime', (string)$sessionLifeTime);
698
+		@ini_set('gc_maxlifetime', (string) $sessionLifeTime);
699 699
 
700 700
 		$systemConfig = \OC::$server->getSystemConfig();
701 701
 
@@ -808,7 +808,7 @@  discard block
 block discarded – undo
808 808
 
809 809
 			// NOTE: This will be replaced to use OCP
810 810
 			$userSession = self::$server->getUserSession();
811
-			$userSession->listen('\OC\User', 'postLogin', function () use ($userSession) {
811
+			$userSession->listen('\OC\User', 'postLogin', function() use ($userSession) {
812 812
 				if (!defined('PHPUNIT_RUN') && $userSession->isLoggedIn()) {
813 813
 					// reset brute force delay for this IP address and username
814 814
 					$uid = \OC::$server->getUserSession()->getUser()->getUID();
@@ -861,7 +861,7 @@  discard block
 block discarded – undo
861 861
 	private static function registerAppRestrictionsHooks() {
862 862
 		/** @var \OC\Group\Manager $groupManager */
863 863
 		$groupManager = self::$server->query(\OCP\IGroupManager::class);
864
-		$groupManager->listen('\OC\Group', 'postDelete', function (\OCP\IGroup $group) {
864
+		$groupManager->listen('\OC\Group', 'postDelete', function(\OCP\IGroup $group) {
865 865
 			$appManager = self::$server->getAppManager();
866 866
 			$apps = $appManager->getEnabledAppsForGroup($group);
867 867
 			foreach ($apps as $appId) {
@@ -971,11 +971,11 @@  discard block
 block discarded – undo
971 971
 		// emergency app disabling
972 972
 		if ($requestPath === '/disableapp'
973 973
 			&& $request->getMethod() === 'POST'
974
-			&& ((array)$request->getParam('appid')) !== ''
974
+			&& ((array) $request->getParam('appid')) !== ''
975 975
 		) {
976 976
 			\OC_JSON::callCheck();
977 977
 			\OC_JSON::checkAdminUser();
978
-			$appIds = (array)$request->getParam('appid');
978
+			$appIds = (array) $request->getParam('appid');
979 979
 			foreach ($appIds as $appId) {
980 980
 				$appId = \OC_App::cleanAppId($appId);
981 981
 				\OC::$server->getAppManager()->disableApp($appId);
Please login to merge, or discard this patch.
lib/private/AppFramework/App.php 1 patch
Indentation   +176 added lines, -176 removed lines patch added patch discarded remove patch
@@ -50,185 +50,185 @@
 block discarded – undo
50 50
  */
51 51
 class App {
52 52
 
53
-	/** @var string[] */
54
-	private static $nameSpaceCache = [];
55
-
56
-	/**
57
-	 * Turns an app id into a namespace by either reading the appinfo.xml's
58
-	 * namespace tag or uppercasing the appid's first letter
59
-	 * @param string $appId the app id
60
-	 * @param string $topNamespace the namespace which should be prepended to
61
-	 * the transformed app id, defaults to OCA\
62
-	 * @return string the starting namespace for the app
63
-	 */
64
-	public static function buildAppNamespace(string $appId, string $topNamespace = 'OCA\\'): string {
65
-		// Hit the cache!
66
-		if (isset(self::$nameSpaceCache[$appId])) {
67
-			return $topNamespace . self::$nameSpaceCache[$appId];
68
-		}
69
-
70
-		$appInfo = \OC_App::getAppInfo($appId);
71
-		if (isset($appInfo['namespace'])) {
72
-			self::$nameSpaceCache[$appId] = trim($appInfo['namespace']);
73
-		} else {
74
-			if ($appId !== 'spreed') {
75
-				// if the tag is not found, fall back to uppercasing the first letter
76
-				self::$nameSpaceCache[$appId] = ucfirst($appId);
77
-			} else {
78
-				// For the Talk app (appid spreed) the above fallback doesn't work.
79
-				// This leads to a problem when trying to install it freshly,
80
-				// because the apps namespace is already registered before the
81
-				// app is downloaded from the appstore, because of the hackish
82
-				// global route index.php/call/{token} which is registered via
83
-				// the core/routes.php so it does not have the app namespace.
84
-				// @ref https://github.com/nextcloud/server/pull/19433
85
-				self::$nameSpaceCache[$appId] = 'Talk';
86
-			}
87
-		}
88
-
89
-		return $topNamespace . self::$nameSpaceCache[$appId];
90
-	}
91
-
92
-	public static function getAppIdForClass(string $className, string $topNamespace = 'OCA\\'): ?string {
93
-		if (strpos($className, $topNamespace) !== 0) {
94
-			return null;
95
-		}
96
-
97
-		foreach (self::$nameSpaceCache as $appId => $namespace) {
98
-			if (strpos($className, $topNamespace . $namespace . '\\') === 0) {
99
-				return $appId;
100
-			}
101
-		}
102
-
103
-		return null;
104
-	}
105
-
106
-
107
-	/**
108
-	 * Shortcut for calling a controller method and printing the result
109
-	 * @param string $controllerName the name of the controller under which it is
110
-	 *                               stored in the DI container
111
-	 * @param string $methodName the method that you want to call
112
-	 * @param DIContainer $container an instance of a pimple container.
113
-	 * @param array $urlParams list of URL parameters (optional)
114
-	 * @throws HintException
115
-	 */
116
-	public static function main(string $controllerName, string $methodName, DIContainer $container, array $urlParams = null) {
117
-		if (!is_null($urlParams)) {
118
-			/** @var Request $request */
119
-			$request = $container->query(IRequest::class);
120
-			$request->setUrlParameters($urlParams);
121
-		} elseif (isset($container['urlParams']) && !is_null($container['urlParams'])) {
122
-			/** @var Request $request */
123
-			$request = $container->query(IRequest::class);
124
-			$request->setUrlParameters($container['urlParams']);
125
-		}
126
-		$appName = $container['AppName'];
127
-
128
-		// first try $controllerName then go for \OCA\AppName\Controller\$controllerName
129
-		try {
130
-			$controller = $container->query($controllerName);
131
-		} catch (QueryException $e) {
132
-			if (strpos($controllerName, '\\Controller\\') !== false) {
133
-				// This is from a global registered app route that is not enabled.
134
-				[/*OC(A)*/, $app, /* Controller/Name*/] = explode('\\', $controllerName, 3);
135
-				throw new HintException('App ' . strtolower($app) . ' is not enabled');
136
-			}
137
-
138
-			if ($appName === 'core') {
139
-				$appNameSpace = 'OC\\Core';
140
-			} else {
141
-				$appNameSpace = self::buildAppNamespace($appName);
142
-			}
143
-			$controllerName = $appNameSpace . '\\Controller\\' . $controllerName;
144
-			$controller = $container->query($controllerName);
145
-		}
146
-
147
-		// initialize the dispatcher and run all the middleware before the controller
148
-		/** @var Dispatcher $dispatcher */
149
-		$dispatcher = $container['Dispatcher'];
150
-
151
-		list(
152
-			$httpHeaders,
153
-			$responseHeaders,
154
-			$responseCookies,
155
-			$output,
156
-			$response
157
-		) = $dispatcher->dispatch($controller, $methodName);
158
-
159
-		$io = $container[IOutput::class];
160
-
161
-		if (!is_null($httpHeaders)) {
162
-			$io->setHeader($httpHeaders);
163
-		}
164
-
165
-		foreach ($responseHeaders as $name => $value) {
166
-			$io->setHeader($name . ': ' . $value);
167
-		}
168
-
169
-		foreach ($responseCookies as $name => $value) {
170
-			$expireDate = null;
171
-			if ($value['expireDate'] instanceof \DateTime) {
172
-				$expireDate = $value['expireDate']->getTimestamp();
173
-			}
174
-			$sameSite = $value['sameSite'] ?? 'Lax';
175
-
176
-			$io->setCookie(
177
-				$name,
178
-				$value['value'],
179
-				$expireDate,
180
-				$container->getServer()->getWebRoot(),
181
-				null,
182
-				$container->getServer()->getRequest()->getServerProtocol() === 'https',
183
-				true,
184
-				$sameSite
185
-			);
186
-		}
187
-
188
-		/*
53
+    /** @var string[] */
54
+    private static $nameSpaceCache = [];
55
+
56
+    /**
57
+     * Turns an app id into a namespace by either reading the appinfo.xml's
58
+     * namespace tag or uppercasing the appid's first letter
59
+     * @param string $appId the app id
60
+     * @param string $topNamespace the namespace which should be prepended to
61
+     * the transformed app id, defaults to OCA\
62
+     * @return string the starting namespace for the app
63
+     */
64
+    public static function buildAppNamespace(string $appId, string $topNamespace = 'OCA\\'): string {
65
+        // Hit the cache!
66
+        if (isset(self::$nameSpaceCache[$appId])) {
67
+            return $topNamespace . self::$nameSpaceCache[$appId];
68
+        }
69
+
70
+        $appInfo = \OC_App::getAppInfo($appId);
71
+        if (isset($appInfo['namespace'])) {
72
+            self::$nameSpaceCache[$appId] = trim($appInfo['namespace']);
73
+        } else {
74
+            if ($appId !== 'spreed') {
75
+                // if the tag is not found, fall back to uppercasing the first letter
76
+                self::$nameSpaceCache[$appId] = ucfirst($appId);
77
+            } else {
78
+                // For the Talk app (appid spreed) the above fallback doesn't work.
79
+                // This leads to a problem when trying to install it freshly,
80
+                // because the apps namespace is already registered before the
81
+                // app is downloaded from the appstore, because of the hackish
82
+                // global route index.php/call/{token} which is registered via
83
+                // the core/routes.php so it does not have the app namespace.
84
+                // @ref https://github.com/nextcloud/server/pull/19433
85
+                self::$nameSpaceCache[$appId] = 'Talk';
86
+            }
87
+        }
88
+
89
+        return $topNamespace . self::$nameSpaceCache[$appId];
90
+    }
91
+
92
+    public static function getAppIdForClass(string $className, string $topNamespace = 'OCA\\'): ?string {
93
+        if (strpos($className, $topNamespace) !== 0) {
94
+            return null;
95
+        }
96
+
97
+        foreach (self::$nameSpaceCache as $appId => $namespace) {
98
+            if (strpos($className, $topNamespace . $namespace . '\\') === 0) {
99
+                return $appId;
100
+            }
101
+        }
102
+
103
+        return null;
104
+    }
105
+
106
+
107
+    /**
108
+     * Shortcut for calling a controller method and printing the result
109
+     * @param string $controllerName the name of the controller under which it is
110
+     *                               stored in the DI container
111
+     * @param string $methodName the method that you want to call
112
+     * @param DIContainer $container an instance of a pimple container.
113
+     * @param array $urlParams list of URL parameters (optional)
114
+     * @throws HintException
115
+     */
116
+    public static function main(string $controllerName, string $methodName, DIContainer $container, array $urlParams = null) {
117
+        if (!is_null($urlParams)) {
118
+            /** @var Request $request */
119
+            $request = $container->query(IRequest::class);
120
+            $request->setUrlParameters($urlParams);
121
+        } elseif (isset($container['urlParams']) && !is_null($container['urlParams'])) {
122
+            /** @var Request $request */
123
+            $request = $container->query(IRequest::class);
124
+            $request->setUrlParameters($container['urlParams']);
125
+        }
126
+        $appName = $container['AppName'];
127
+
128
+        // first try $controllerName then go for \OCA\AppName\Controller\$controllerName
129
+        try {
130
+            $controller = $container->query($controllerName);
131
+        } catch (QueryException $e) {
132
+            if (strpos($controllerName, '\\Controller\\') !== false) {
133
+                // This is from a global registered app route that is not enabled.
134
+                [/*OC(A)*/, $app, /* Controller/Name*/] = explode('\\', $controllerName, 3);
135
+                throw new HintException('App ' . strtolower($app) . ' is not enabled');
136
+            }
137
+
138
+            if ($appName === 'core') {
139
+                $appNameSpace = 'OC\\Core';
140
+            } else {
141
+                $appNameSpace = self::buildAppNamespace($appName);
142
+            }
143
+            $controllerName = $appNameSpace . '\\Controller\\' . $controllerName;
144
+            $controller = $container->query($controllerName);
145
+        }
146
+
147
+        // initialize the dispatcher and run all the middleware before the controller
148
+        /** @var Dispatcher $dispatcher */
149
+        $dispatcher = $container['Dispatcher'];
150
+
151
+        list(
152
+            $httpHeaders,
153
+            $responseHeaders,
154
+            $responseCookies,
155
+            $output,
156
+            $response
157
+        ) = $dispatcher->dispatch($controller, $methodName);
158
+
159
+        $io = $container[IOutput::class];
160
+
161
+        if (!is_null($httpHeaders)) {
162
+            $io->setHeader($httpHeaders);
163
+        }
164
+
165
+        foreach ($responseHeaders as $name => $value) {
166
+            $io->setHeader($name . ': ' . $value);
167
+        }
168
+
169
+        foreach ($responseCookies as $name => $value) {
170
+            $expireDate = null;
171
+            if ($value['expireDate'] instanceof \DateTime) {
172
+                $expireDate = $value['expireDate']->getTimestamp();
173
+            }
174
+            $sameSite = $value['sameSite'] ?? 'Lax';
175
+
176
+            $io->setCookie(
177
+                $name,
178
+                $value['value'],
179
+                $expireDate,
180
+                $container->getServer()->getWebRoot(),
181
+                null,
182
+                $container->getServer()->getRequest()->getServerProtocol() === 'https',
183
+                true,
184
+                $sameSite
185
+            );
186
+        }
187
+
188
+        /*
189 189
 		 * Status 204 does not have a body and no Content Length
190 190
 		 * Status 304 does not have a body and does not need a Content Length
191 191
 		 * https://tools.ietf.org/html/rfc7230#section-3.3
192 192
 		 * https://tools.ietf.org/html/rfc7230#section-3.3.2
193 193
 		 */
194
-		$emptyResponse = false;
195
-		if (preg_match('/^HTTP\/\d\.\d (\d{3}) .*$/', $httpHeaders, $matches)) {
196
-			$status = (int)$matches[1];
197
-			if ($status === Http::STATUS_NO_CONTENT || $status === Http::STATUS_NOT_MODIFIED) {
198
-				$emptyResponse = true;
199
-			}
200
-		}
201
-
202
-		if (!$emptyResponse) {
203
-			if ($response instanceof ICallbackResponse) {
204
-				$response->callback($io);
205
-			} elseif (!is_null($output)) {
206
-				$io->setHeader('Content-Length: ' . strlen($output));
207
-				$io->setOutput($output);
208
-			}
209
-		}
210
-	}
211
-
212
-	/**
213
-	 * Shortcut for calling a controller method and printing the result.
214
-	 * Similar to App:main except that no headers will be sent.
215
-	 * This should be used for example when registering sections via
216
-	 * \OC\AppFramework\Core\API::registerAdmin()
217
-	 *
218
-	 * @param string $controllerName the name of the controller under which it is
219
-	 *                               stored in the DI container
220
-	 * @param string $methodName the method that you want to call
221
-	 * @param array $urlParams an array with variables extracted from the routes
222
-	 * @param DIContainer $container an instance of a pimple container.
223
-	 */
224
-	public static function part(string $controllerName, string $methodName, array $urlParams,
225
-								DIContainer $container) {
226
-		$container['urlParams'] = $urlParams;
227
-		$controller = $container[$controllerName];
228
-
229
-		$dispatcher = $container['Dispatcher'];
230
-
231
-		list(, , $output) = $dispatcher->dispatch($controller, $methodName);
232
-		return $output;
233
-	}
194
+        $emptyResponse = false;
195
+        if (preg_match('/^HTTP\/\d\.\d (\d{3}) .*$/', $httpHeaders, $matches)) {
196
+            $status = (int)$matches[1];
197
+            if ($status === Http::STATUS_NO_CONTENT || $status === Http::STATUS_NOT_MODIFIED) {
198
+                $emptyResponse = true;
199
+            }
200
+        }
201
+
202
+        if (!$emptyResponse) {
203
+            if ($response instanceof ICallbackResponse) {
204
+                $response->callback($io);
205
+            } elseif (!is_null($output)) {
206
+                $io->setHeader('Content-Length: ' . strlen($output));
207
+                $io->setOutput($output);
208
+            }
209
+        }
210
+    }
211
+
212
+    /**
213
+     * Shortcut for calling a controller method and printing the result.
214
+     * Similar to App:main except that no headers will be sent.
215
+     * This should be used for example when registering sections via
216
+     * \OC\AppFramework\Core\API::registerAdmin()
217
+     *
218
+     * @param string $controllerName the name of the controller under which it is
219
+     *                               stored in the DI container
220
+     * @param string $methodName the method that you want to call
221
+     * @param array $urlParams an array with variables extracted from the routes
222
+     * @param DIContainer $container an instance of a pimple container.
223
+     */
224
+    public static function part(string $controllerName, string $methodName, array $urlParams,
225
+                                DIContainer $container) {
226
+        $container['urlParams'] = $urlParams;
227
+        $controller = $container[$controllerName];
228
+
229
+        $dispatcher = $container['Dispatcher'];
230
+
231
+        list(, , $output) = $dispatcher->dispatch($controller, $methodName);
232
+        return $output;
233
+    }
234 234
 }
Please login to merge, or discard this patch.
lib/private/Collaboration/Collaborators/Search.php 1 patch
Indentation   +63 added lines, -63 removed lines patch added patch discarded remove patch
@@ -34,79 +34,79 @@
 block discarded – undo
34 34
 use OCP\Share;
35 35
 
36 36
 class Search implements ISearch {
37
-	/** @var IContainer */
38
-	private $c;
37
+    /** @var IContainer */
38
+    private $c;
39 39
 
40
-	protected $pluginList = [];
40
+    protected $pluginList = [];
41 41
 
42
-	public function __construct(IContainer $c) {
43
-		$this->c = $c;
44
-	}
42
+    public function __construct(IContainer $c) {
43
+        $this->c = $c;
44
+    }
45 45
 
46
-	/**
47
-	 * @param string $search
48
-	 * @param array $shareTypes
49
-	 * @param bool $lookup
50
-	 * @param int|null $limit
51
-	 * @param int|null $offset
52
-	 * @return array
53
-	 * @throws \OCP\AppFramework\QueryException
54
-	 */
55
-	public function search($search, array $shareTypes, $lookup, $limit, $offset) {
56
-		$hasMoreResults = false;
46
+    /**
47
+     * @param string $search
48
+     * @param array $shareTypes
49
+     * @param bool $lookup
50
+     * @param int|null $limit
51
+     * @param int|null $offset
52
+     * @return array
53
+     * @throws \OCP\AppFramework\QueryException
54
+     */
55
+    public function search($search, array $shareTypes, $lookup, $limit, $offset) {
56
+        $hasMoreResults = false;
57 57
 
58
-		// Trim leading and trailing whitespace characters, e.g. when query is copy-pasted
59
-		$search = trim($search);
58
+        // Trim leading and trailing whitespace characters, e.g. when query is copy-pasted
59
+        $search = trim($search);
60 60
 
61
-		/** @var ISearchResult $searchResult */
62
-		$searchResult = $this->c->resolve(SearchResult::class);
61
+        /** @var ISearchResult $searchResult */
62
+        $searchResult = $this->c->resolve(SearchResult::class);
63 63
 
64
-		foreach ($shareTypes as $type) {
65
-			if (!isset($this->pluginList[$type])) {
66
-				continue;
67
-			}
68
-			foreach ($this->pluginList[$type] as $plugin) {
69
-				/** @var ISearchPlugin $searchPlugin */
70
-				$searchPlugin = $this->c->resolve($plugin);
71
-				$hasMoreResults = $searchPlugin->search($search, $limit, $offset, $searchResult) || $hasMoreResults;
72
-			}
73
-		}
64
+        foreach ($shareTypes as $type) {
65
+            if (!isset($this->pluginList[$type])) {
66
+                continue;
67
+            }
68
+            foreach ($this->pluginList[$type] as $plugin) {
69
+                /** @var ISearchPlugin $searchPlugin */
70
+                $searchPlugin = $this->c->resolve($plugin);
71
+                $hasMoreResults = $searchPlugin->search($search, $limit, $offset, $searchResult) || $hasMoreResults;
72
+            }
73
+        }
74 74
 
75
-		// Get from lookup server, not a separate share type
76
-		if ($lookup) {
77
-			$searchPlugin = $this->c->resolve(LookupPlugin::class);
78
-			$hasMoreResults = $searchPlugin->search($search, $limit, $offset, $searchResult) || $hasMoreResults;
79
-		}
75
+        // Get from lookup server, not a separate share type
76
+        if ($lookup) {
77
+            $searchPlugin = $this->c->resolve(LookupPlugin::class);
78
+            $hasMoreResults = $searchPlugin->search($search, $limit, $offset, $searchResult) || $hasMoreResults;
79
+        }
80 80
 
81
-		// sanitizing, could go into the plugins as well
81
+        // sanitizing, could go into the plugins as well
82 82
 
83
-		// if we have a exact match, either for the federated cloud id or for the
84
-		// email address we only return the exact match. It is highly unlikely
85
-		// that the exact same email address and federated cloud id exists
86
-		$emailType = new SearchResultType('emails');
87
-		$remoteType = new SearchResultType('remotes');
88
-		if ($searchResult->hasExactIdMatch($emailType) && !$searchResult->hasExactIdMatch($remoteType)) {
89
-			$searchResult->unsetResult($remoteType);
90
-		} elseif (!$searchResult->hasExactIdMatch($emailType) && $searchResult->hasExactIdMatch($remoteType)) {
91
-			$searchResult->unsetResult($emailType);
92
-		}
83
+        // if we have a exact match, either for the federated cloud id or for the
84
+        // email address we only return the exact match. It is highly unlikely
85
+        // that the exact same email address and federated cloud id exists
86
+        $emailType = new SearchResultType('emails');
87
+        $remoteType = new SearchResultType('remotes');
88
+        if ($searchResult->hasExactIdMatch($emailType) && !$searchResult->hasExactIdMatch($remoteType)) {
89
+            $searchResult->unsetResult($remoteType);
90
+        } elseif (!$searchResult->hasExactIdMatch($emailType) && $searchResult->hasExactIdMatch($remoteType)) {
91
+            $searchResult->unsetResult($emailType);
92
+        }
93 93
 
94
-		// if we have an exact local user match with an email-a-like query,
95
-		// there is no need to show the remote and email matches.
96
-		$userType = new SearchResultType('users');
97
-		if (strpos($search, '@') !== false && $searchResult->hasExactIdMatch($userType)) {
98
-			$searchResult->unsetResult($remoteType);
99
-			$searchResult->unsetResult($emailType);
100
-		}
94
+        // if we have an exact local user match with an email-a-like query,
95
+        // there is no need to show the remote and email matches.
96
+        $userType = new SearchResultType('users');
97
+        if (strpos($search, '@') !== false && $searchResult->hasExactIdMatch($userType)) {
98
+            $searchResult->unsetResult($remoteType);
99
+            $searchResult->unsetResult($emailType);
100
+        }
101 101
 
102
-		return [$searchResult->asArray(), (bool)$hasMoreResults];
103
-	}
102
+        return [$searchResult->asArray(), (bool)$hasMoreResults];
103
+    }
104 104
 
105
-	public function registerPlugin(array $pluginInfo) {
106
-		$shareType = constant(Share::class . '::' . $pluginInfo['shareType']);
107
-		if ($shareType === null) {
108
-			throw new \InvalidArgumentException('Provided ShareType is invalid');
109
-		}
110
-		$this->pluginList[$shareType][] = $pluginInfo['class'];
111
-	}
105
+    public function registerPlugin(array $pluginInfo) {
106
+        $shareType = constant(Share::class . '::' . $pluginInfo['shareType']);
107
+        if ($shareType === null) {
108
+            throw new \InvalidArgumentException('Provided ShareType is invalid');
109
+        }
110
+        $this->pluginList[$shareType][] = $pluginInfo['class'];
111
+    }
112 112
 }
Please login to merge, or discard this patch.
lib/public/IContainer.php 1 patch
Indentation   +66 added lines, -66 removed lines patch added patch discarded remove patch
@@ -51,74 +51,74 @@
 block discarded – undo
51 51
  */
52 52
 interface IContainer extends ContainerInterface {
53 53
 
54
-	/**
55
-	 * @template T
56
-	 *
57
-	 * If a parameter is not registered in the container try to instantiate it
58
-	 * by using reflection to find out how to build the class
59
-	 * @param string $name the class name to resolve
60
-	 * @psalm-param string|class-string<T> $name
61
-	 * @return \stdClass
62
-	 * @psalm-return ($name is class-string ? T : mixed)
63
-	 * @since 8.2.0
64
-	 * @deprecated 20.0.0 use \Psr\Container\ContainerInterface::get
65
-	 * @throws ContainerExceptionInterface if the class could not be found or instantiated
66
-	 * @throws QueryException if the class could not be found or instantiated
67
-	 */
68
-	public function resolve($name);
54
+    /**
55
+     * @template T
56
+     *
57
+     * If a parameter is not registered in the container try to instantiate it
58
+     * by using reflection to find out how to build the class
59
+     * @param string $name the class name to resolve
60
+     * @psalm-param string|class-string<T> $name
61
+     * @return \stdClass
62
+     * @psalm-return ($name is class-string ? T : mixed)
63
+     * @since 8.2.0
64
+     * @deprecated 20.0.0 use \Psr\Container\ContainerInterface::get
65
+     * @throws ContainerExceptionInterface if the class could not be found or instantiated
66
+     * @throws QueryException if the class could not be found or instantiated
67
+     */
68
+    public function resolve($name);
69 69
 
70
-	/**
71
-	 * Look up a service for a given name in the container.
72
-	 *
73
-	 * @template T
74
-	 *
75
-	 * @param string $name
76
-	 * @psalm-param string|class-string<T> $name
77
-	 * @param bool $autoload Should we try to autoload the service. If we are trying to resolve built in types this makes no sense for example
78
-	 * @return mixed
79
-	 * @psalm-return ($name is class-string ? T : mixed)
80
-	 * @throws ContainerExceptionInterface if the query could not be resolved
81
-	 * @throws QueryException if the query could not be resolved
82
-	 * @since 6.0.0
83
-	 * @deprecated 20.0.0 use \Psr\Container\ContainerInterface::get
84
-	 */
85
-	public function query(string $name, bool $autoload = true);
70
+    /**
71
+     * Look up a service for a given name in the container.
72
+     *
73
+     * @template T
74
+     *
75
+     * @param string $name
76
+     * @psalm-param string|class-string<T> $name
77
+     * @param bool $autoload Should we try to autoload the service. If we are trying to resolve built in types this makes no sense for example
78
+     * @return mixed
79
+     * @psalm-return ($name is class-string ? T : mixed)
80
+     * @throws ContainerExceptionInterface if the query could not be resolved
81
+     * @throws QueryException if the query could not be resolved
82
+     * @since 6.0.0
83
+     * @deprecated 20.0.0 use \Psr\Container\ContainerInterface::get
84
+     */
85
+    public function query(string $name, bool $autoload = true);
86 86
 
87
-	/**
88
-	 * A value is stored in the container with it's corresponding name
89
-	 *
90
-	 * @param string $name
91
-	 * @param mixed $value
92
-	 * @return void
93
-	 * @since 6.0.0
94
-	 * @deprecated 20.0.0 use \OCP\AppFramework\Bootstrap\IRegistrationContext::registerParameter
95
-	 */
96
-	public function registerParameter($name, $value);
87
+    /**
88
+     * A value is stored in the container with it's corresponding name
89
+     *
90
+     * @param string $name
91
+     * @param mixed $value
92
+     * @return void
93
+     * @since 6.0.0
94
+     * @deprecated 20.0.0 use \OCP\AppFramework\Bootstrap\IRegistrationContext::registerParameter
95
+     */
96
+    public function registerParameter($name, $value);
97 97
 
98
-	/**
99
-	 * A service is registered in the container where a closure is passed in which will actually
100
-	 * create the service on demand.
101
-	 * In case the parameter $shared is set to true (the default usage) the once created service will remain in
102
-	 * memory and be reused on subsequent calls.
103
-	 * In case the parameter is false the service will be recreated on every call.
104
-	 *
105
-	 * @param string $name
106
-	 * @param \Closure $closure
107
-	 * @param bool $shared
108
-	 * @return void
109
-	 * @since 6.0.0
110
-	 * @deprecated 20.0.0 use \OCP\AppFramework\Bootstrap\IRegistrationContext::registerService
111
-	 */
112
-	public function registerService($name, Closure $closure, $shared = true);
98
+    /**
99
+     * A service is registered in the container where a closure is passed in which will actually
100
+     * create the service on demand.
101
+     * In case the parameter $shared is set to true (the default usage) the once created service will remain in
102
+     * memory and be reused on subsequent calls.
103
+     * In case the parameter is false the service will be recreated on every call.
104
+     *
105
+     * @param string $name
106
+     * @param \Closure $closure
107
+     * @param bool $shared
108
+     * @return void
109
+     * @since 6.0.0
110
+     * @deprecated 20.0.0 use \OCP\AppFramework\Bootstrap\IRegistrationContext::registerService
111
+     */
112
+    public function registerService($name, Closure $closure, $shared = true);
113 113
 
114
-	/**
115
-	 * Shortcut for returning a service from a service under a different key,
116
-	 * e.g. to tell the container to return a class when queried for an
117
-	 * interface
118
-	 * @param string $alias the alias that should be registered
119
-	 * @param string $target the target that should be resolved instead
120
-	 * @since 8.2.0
121
-	 * @deprecated 20.0.0 use \OCP\AppFramework\Bootstrap\IRegistrationContext::registerServiceAlias
122
-	 */
123
-	public function registerAlias($alias, $target);
114
+    /**
115
+     * Shortcut for returning a service from a service under a different key,
116
+     * e.g. to tell the container to return a class when queried for an
117
+     * interface
118
+     * @param string $alias the alias that should be registered
119
+     * @param string $target the target that should be resolved instead
120
+     * @since 8.2.0
121
+     * @deprecated 20.0.0 use \OCP\AppFramework\Bootstrap\IRegistrationContext::registerServiceAlias
122
+     */
123
+    public function registerAlias($alias, $target);
124 124
 }
Please login to merge, or discard this patch.