Completed
Pull Request — master (#6982)
by Blizzz
17:09 queued 02:05
created
apps/files_sharing/lib/Collaboration/ShareRecipientSorter.php 1 patch
Indentation   +64 added lines, -64 removed lines patch added patch discarded remove patch
@@ -33,78 +33,78 @@
 block discarded – undo
33 33
 
34 34
 class ShareRecipientSorter implements ISorter {
35 35
 
36
-	/** @var IManager */
37
-	private $shareManager;
38
-	/** @var Folder */
39
-	private $rootFolder;
40
-	/** @var IUserSession */
41
-	private $userSession;
36
+    /** @var IManager */
37
+    private $shareManager;
38
+    /** @var Folder */
39
+    private $rootFolder;
40
+    /** @var IUserSession */
41
+    private $userSession;
42 42
 
43
-	public function __construct(IManager $shareManager, IRootFolder $rootFolder, IUserSession $userSession) {
44
-		$this->shareManager = $shareManager;
45
-		$this->rootFolder = $rootFolder;
46
-		$this->userSession = $userSession;
47
-	}
43
+    public function __construct(IManager $shareManager, IRootFolder $rootFolder, IUserSession $userSession) {
44
+        $this->shareManager = $shareManager;
45
+        $this->rootFolder = $rootFolder;
46
+        $this->userSession = $userSession;
47
+    }
48 48
 
49
-	public function getId() {
50
-		return 'share-recipients';
51
-	}
49
+    public function getId() {
50
+        return 'share-recipients';
51
+    }
52 52
 
53
-	public function sort(array &$sortArray, array $context) {
54
-		// let's be tolerant. Comments  uses "files" by default, other usages are often singular
55
-		if($context['itemType'] !== 'files' && $context['itemType'] !== 'file') {
56
-			return;
57
-		}
58
-		/** @var Node[] $nodes */
59
-		$user = $this->userSession->getUser();
60
-		if($user === null) {
61
-			return;
62
-		}
63
-		$userFolder = $this->rootFolder->getUserFolder($user->getUID());
64
-		$nodes = $userFolder->getById((int)$context['itemId']);
65
-		if(count($nodes) === 0) {
66
-			return;
67
-		}
68
-		$al = $this->shareManager->getAccessList($nodes[0]);
53
+    public function sort(array &$sortArray, array $context) {
54
+        // let's be tolerant. Comments  uses "files" by default, other usages are often singular
55
+        if($context['itemType'] !== 'files' && $context['itemType'] !== 'file') {
56
+            return;
57
+        }
58
+        /** @var Node[] $nodes */
59
+        $user = $this->userSession->getUser();
60
+        if($user === null) {
61
+            return;
62
+        }
63
+        $userFolder = $this->rootFolder->getUserFolder($user->getUID());
64
+        $nodes = $userFolder->getById((int)$context['itemId']);
65
+        if(count($nodes) === 0) {
66
+            return;
67
+        }
68
+        $al = $this->shareManager->getAccessList($nodes[0]);
69 69
 
70
-		foreach ($sortArray as $type => &$byType) {
71
-			if(!isset($al[$type]) || !is_array($al[$type])) {
72
-				continue;
73
-			}
70
+        foreach ($sortArray as $type => &$byType) {
71
+            if(!isset($al[$type]) || !is_array($al[$type])) {
72
+                continue;
73
+            }
74 74
 
75
-			// at least on PHP 5.6 usort turned out to be not stable. So we add
76
-			// the current index to the value and compare it on a draw
77
-			$i = 0;
78
-			$workArray = array_map(function($element) use (&$i) {
79
-				return [$i++, $element];
80
-			}, $byType);
75
+            // at least on PHP 5.6 usort turned out to be not stable. So we add
76
+            // the current index to the value and compare it on a draw
77
+            $i = 0;
78
+            $workArray = array_map(function($element) use (&$i) {
79
+                return [$i++, $element];
80
+            }, $byType);
81 81
 
82
-			usort($workArray, function ($a, $b) use ($al, $type) {
83
-				$result = $this->compare($a[1], $b[1], $al[$type]);
84
-				if($result === 0) {
85
-					$result = $a[0] - $b[0];
86
-				}
87
-				return $result;
88
-			});
82
+            usort($workArray, function ($a, $b) use ($al, $type) {
83
+                $result = $this->compare($a[1], $b[1], $al[$type]);
84
+                if($result === 0) {
85
+                    $result = $a[0] - $b[0];
86
+                }
87
+                return $result;
88
+            });
89 89
 
90
-			// and remove the index values again
91
-			$byType = array_column($workArray, 1);
92
-		}
93
-	}
90
+            // and remove the index values again
91
+            $byType = array_column($workArray, 1);
92
+        }
93
+    }
94 94
 
95
-	/**
96
-	 * @param array $a
97
-	 * @param array $b
98
-	 * @param array $al
99
-	 * @return int
100
-	 */
101
-	protected function compare(array $a, array $b, array $al) {
102
-		$a = $a['value']['shareWith'];
103
-		$b = $b['value']['shareWith'];
95
+    /**
96
+     * @param array $a
97
+     * @param array $b
98
+     * @param array $al
99
+     * @return int
100
+     */
101
+    protected function compare(array $a, array $b, array $al) {
102
+        $a = $a['value']['shareWith'];
103
+        $b = $b['value']['shareWith'];
104 104
 
105
-		$valueA = (int)in_array($a, $al, true);
106
-		$valueB = (int)in_array($b, $al, true);
105
+        $valueA = (int)in_array($a, $al, true);
106
+        $valueB = (int)in_array($b, $al, true);
107 107
 
108
-		return $valueB - $valueA;
109
-	}
108
+        return $valueB - $valueA;
109
+    }
110 110
 }
Please login to merge, or discard this patch.
lib/private/Share20/Manager.php 1 patch
Indentation   +1459 added lines, -1459 removed lines patch added patch discarded remove patch
@@ -60,1487 +60,1487 @@
 block discarded – undo
60 60
  */
61 61
 class Manager implements IManager {
62 62
 
63
-	/** @var IProviderFactory */
64
-	private $factory;
65
-	/** @var ILogger */
66
-	private $logger;
67
-	/** @var IConfig */
68
-	private $config;
69
-	/** @var ISecureRandom */
70
-	private $secureRandom;
71
-	/** @var IHasher */
72
-	private $hasher;
73
-	/** @var IMountManager */
74
-	private $mountManager;
75
-	/** @var IGroupManager */
76
-	private $groupManager;
77
-	/** @var IL10N */
78
-	private $l;
79
-	/** @var IFactory */
80
-	private $l10nFactory;
81
-	/** @var IUserManager */
82
-	private $userManager;
83
-	/** @var IRootFolder */
84
-	private $rootFolder;
85
-	/** @var CappedMemoryCache */
86
-	private $sharingDisabledForUsersCache;
87
-	/** @var EventDispatcher */
88
-	private $eventDispatcher;
89
-	/** @var LegacyHooks */
90
-	private $legacyHooks;
91
-	/** @var IMailer */
92
-	private $mailer;
93
-	/** @var IURLGenerator */
94
-	private $urlGenerator;
95
-	/** @var \OC_Defaults */
96
-	private $defaults;
97
-
98
-
99
-	/**
100
-	 * Manager constructor.
101
-	 *
102
-	 * @param ILogger $logger
103
-	 * @param IConfig $config
104
-	 * @param ISecureRandom $secureRandom
105
-	 * @param IHasher $hasher
106
-	 * @param IMountManager $mountManager
107
-	 * @param IGroupManager $groupManager
108
-	 * @param IL10N $l
109
-	 * @param IFactory $l10nFactory
110
-	 * @param IProviderFactory $factory
111
-	 * @param IUserManager $userManager
112
-	 * @param IRootFolder $rootFolder
113
-	 * @param EventDispatcher $eventDispatcher
114
-	 * @param IMailer $mailer
115
-	 * @param IURLGenerator $urlGenerator
116
-	 * @param \OC_Defaults $defaults
117
-	 */
118
-	public function __construct(
119
-			ILogger $logger,
120
-			IConfig $config,
121
-			ISecureRandom $secureRandom,
122
-			IHasher $hasher,
123
-			IMountManager $mountManager,
124
-			IGroupManager $groupManager,
125
-			IL10N $l,
126
-			IFactory $l10nFactory,
127
-			IProviderFactory $factory,
128
-			IUserManager $userManager,
129
-			IRootFolder $rootFolder,
130
-			EventDispatcher $eventDispatcher,
131
-			IMailer $mailer,
132
-			IURLGenerator $urlGenerator,
133
-			\OC_Defaults $defaults
134
-	) {
135
-		$this->logger = $logger;
136
-		$this->config = $config;
137
-		$this->secureRandom = $secureRandom;
138
-		$this->hasher = $hasher;
139
-		$this->mountManager = $mountManager;
140
-		$this->groupManager = $groupManager;
141
-		$this->l = $l;
142
-		$this->l10nFactory = $l10nFactory;
143
-		$this->factory = $factory;
144
-		$this->userManager = $userManager;
145
-		$this->rootFolder = $rootFolder;
146
-		$this->eventDispatcher = $eventDispatcher;
147
-		$this->sharingDisabledForUsersCache = new CappedMemoryCache();
148
-		$this->legacyHooks = new LegacyHooks($this->eventDispatcher);
149
-		$this->mailer = $mailer;
150
-		$this->urlGenerator = $urlGenerator;
151
-		$this->defaults = $defaults;
152
-	}
153
-
154
-	/**
155
-	 * Convert from a full share id to a tuple (providerId, shareId)
156
-	 *
157
-	 * @param string $id
158
-	 * @return string[]
159
-	 */
160
-	private function splitFullId($id) {
161
-		return explode(':', $id, 2);
162
-	}
163
-
164
-	/**
165
-	 * Verify if a password meets all requirements
166
-	 *
167
-	 * @param string $password
168
-	 * @throws \Exception
169
-	 */
170
-	protected function verifyPassword($password) {
171
-		if ($password === null) {
172
-			// No password is set, check if this is allowed.
173
-			if ($this->shareApiLinkEnforcePassword()) {
174
-				throw new \InvalidArgumentException('Passwords are enforced for link shares');
175
-			}
176
-
177
-			return;
178
-		}
179
-
180
-		// Let others verify the password
181
-		try {
182
-			$event = new GenericEvent($password);
183
-			$this->eventDispatcher->dispatch('OCP\PasswordPolicy::validate', $event);
184
-		} catch (HintException $e) {
185
-			throw new \Exception($e->getHint());
186
-		}
187
-	}
188
-
189
-	/**
190
-	 * Check for generic requirements before creating a share
191
-	 *
192
-	 * @param \OCP\Share\IShare $share
193
-	 * @throws \InvalidArgumentException
194
-	 * @throws GenericShareException
195
-	 *
196
-	 * @suppress PhanUndeclaredClassMethod
197
-	 */
198
-	protected function generalCreateChecks(\OCP\Share\IShare $share) {
199
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
200
-			// We expect a valid user as sharedWith for user shares
201
-			if (!$this->userManager->userExists($share->getSharedWith())) {
202
-				throw new \InvalidArgumentException('SharedWith is not a valid user');
203
-			}
204
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
205
-			// We expect a valid group as sharedWith for group shares
206
-			if (!$this->groupManager->groupExists($share->getSharedWith())) {
207
-				throw new \InvalidArgumentException('SharedWith is not a valid group');
208
-			}
209
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
210
-			if ($share->getSharedWith() !== null) {
211
-				throw new \InvalidArgumentException('SharedWith should be empty');
212
-			}
213
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_REMOTE) {
214
-			if ($share->getSharedWith() === null) {
215
-				throw new \InvalidArgumentException('SharedWith should not be empty');
216
-			}
217
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_EMAIL) {
218
-			if ($share->getSharedWith() === null) {
219
-				throw new \InvalidArgumentException('SharedWith should not be empty');
220
-			}
221
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_CIRCLE) {
222
-			$circle = \OCA\Circles\Api\v1\Circles::detailsCircle($share->getSharedWith());
223
-			if ($circle === null) {
224
-				throw new \InvalidArgumentException('SharedWith is not a valid circle');
225
-			}
226
-		} else {
227
-			// We can't handle other types yet
228
-			throw new \InvalidArgumentException('unknown share type');
229
-		}
230
-
231
-		// Verify the initiator of the share is set
232
-		if ($share->getSharedBy() === null) {
233
-			throw new \InvalidArgumentException('SharedBy should be set');
234
-		}
235
-
236
-		// Cannot share with yourself
237
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER &&
238
-			$share->getSharedWith() === $share->getSharedBy()) {
239
-			throw new \InvalidArgumentException('Can’t share with yourself');
240
-		}
241
-
242
-		// The path should be set
243
-		if ($share->getNode() === null) {
244
-			throw new \InvalidArgumentException('Path should be set');
245
-		}
246
-
247
-		// And it should be a file or a folder
248
-		if (!($share->getNode() instanceof \OCP\Files\File) &&
249
-				!($share->getNode() instanceof \OCP\Files\Folder)) {
250
-			throw new \InvalidArgumentException('Path should be either a file or a folder');
251
-		}
252
-
253
-		// And you can't share your rootfolder
254
-		if ($this->userManager->userExists($share->getSharedBy())) {
255
-			$sharedPath = $this->rootFolder->getUserFolder($share->getSharedBy())->getPath();
256
-		} else {
257
-			$sharedPath = $this->rootFolder->getUserFolder($share->getShareOwner())->getPath();
258
-		}
259
-		if ($sharedPath === $share->getNode()->getPath()) {
260
-			throw new \InvalidArgumentException('You can’t share your root folder');
261
-		}
262
-
263
-		// Check if we actually have share permissions
264
-		if (!$share->getNode()->isShareable()) {
265
-			$message_t = $this->l->t('You are not allowed to share %s', [$share->getNode()->getPath()]);
266
-			throw new GenericShareException($message_t, $message_t, 404);
267
-		}
268
-
269
-		// Permissions should be set
270
-		if ($share->getPermissions() === null) {
271
-			throw new \InvalidArgumentException('A share requires permissions');
272
-		}
273
-
274
-		/*
63
+    /** @var IProviderFactory */
64
+    private $factory;
65
+    /** @var ILogger */
66
+    private $logger;
67
+    /** @var IConfig */
68
+    private $config;
69
+    /** @var ISecureRandom */
70
+    private $secureRandom;
71
+    /** @var IHasher */
72
+    private $hasher;
73
+    /** @var IMountManager */
74
+    private $mountManager;
75
+    /** @var IGroupManager */
76
+    private $groupManager;
77
+    /** @var IL10N */
78
+    private $l;
79
+    /** @var IFactory */
80
+    private $l10nFactory;
81
+    /** @var IUserManager */
82
+    private $userManager;
83
+    /** @var IRootFolder */
84
+    private $rootFolder;
85
+    /** @var CappedMemoryCache */
86
+    private $sharingDisabledForUsersCache;
87
+    /** @var EventDispatcher */
88
+    private $eventDispatcher;
89
+    /** @var LegacyHooks */
90
+    private $legacyHooks;
91
+    /** @var IMailer */
92
+    private $mailer;
93
+    /** @var IURLGenerator */
94
+    private $urlGenerator;
95
+    /** @var \OC_Defaults */
96
+    private $defaults;
97
+
98
+
99
+    /**
100
+     * Manager constructor.
101
+     *
102
+     * @param ILogger $logger
103
+     * @param IConfig $config
104
+     * @param ISecureRandom $secureRandom
105
+     * @param IHasher $hasher
106
+     * @param IMountManager $mountManager
107
+     * @param IGroupManager $groupManager
108
+     * @param IL10N $l
109
+     * @param IFactory $l10nFactory
110
+     * @param IProviderFactory $factory
111
+     * @param IUserManager $userManager
112
+     * @param IRootFolder $rootFolder
113
+     * @param EventDispatcher $eventDispatcher
114
+     * @param IMailer $mailer
115
+     * @param IURLGenerator $urlGenerator
116
+     * @param \OC_Defaults $defaults
117
+     */
118
+    public function __construct(
119
+            ILogger $logger,
120
+            IConfig $config,
121
+            ISecureRandom $secureRandom,
122
+            IHasher $hasher,
123
+            IMountManager $mountManager,
124
+            IGroupManager $groupManager,
125
+            IL10N $l,
126
+            IFactory $l10nFactory,
127
+            IProviderFactory $factory,
128
+            IUserManager $userManager,
129
+            IRootFolder $rootFolder,
130
+            EventDispatcher $eventDispatcher,
131
+            IMailer $mailer,
132
+            IURLGenerator $urlGenerator,
133
+            \OC_Defaults $defaults
134
+    ) {
135
+        $this->logger = $logger;
136
+        $this->config = $config;
137
+        $this->secureRandom = $secureRandom;
138
+        $this->hasher = $hasher;
139
+        $this->mountManager = $mountManager;
140
+        $this->groupManager = $groupManager;
141
+        $this->l = $l;
142
+        $this->l10nFactory = $l10nFactory;
143
+        $this->factory = $factory;
144
+        $this->userManager = $userManager;
145
+        $this->rootFolder = $rootFolder;
146
+        $this->eventDispatcher = $eventDispatcher;
147
+        $this->sharingDisabledForUsersCache = new CappedMemoryCache();
148
+        $this->legacyHooks = new LegacyHooks($this->eventDispatcher);
149
+        $this->mailer = $mailer;
150
+        $this->urlGenerator = $urlGenerator;
151
+        $this->defaults = $defaults;
152
+    }
153
+
154
+    /**
155
+     * Convert from a full share id to a tuple (providerId, shareId)
156
+     *
157
+     * @param string $id
158
+     * @return string[]
159
+     */
160
+    private function splitFullId($id) {
161
+        return explode(':', $id, 2);
162
+    }
163
+
164
+    /**
165
+     * Verify if a password meets all requirements
166
+     *
167
+     * @param string $password
168
+     * @throws \Exception
169
+     */
170
+    protected function verifyPassword($password) {
171
+        if ($password === null) {
172
+            // No password is set, check if this is allowed.
173
+            if ($this->shareApiLinkEnforcePassword()) {
174
+                throw new \InvalidArgumentException('Passwords are enforced for link shares');
175
+            }
176
+
177
+            return;
178
+        }
179
+
180
+        // Let others verify the password
181
+        try {
182
+            $event = new GenericEvent($password);
183
+            $this->eventDispatcher->dispatch('OCP\PasswordPolicy::validate', $event);
184
+        } catch (HintException $e) {
185
+            throw new \Exception($e->getHint());
186
+        }
187
+    }
188
+
189
+    /**
190
+     * Check for generic requirements before creating a share
191
+     *
192
+     * @param \OCP\Share\IShare $share
193
+     * @throws \InvalidArgumentException
194
+     * @throws GenericShareException
195
+     *
196
+     * @suppress PhanUndeclaredClassMethod
197
+     */
198
+    protected function generalCreateChecks(\OCP\Share\IShare $share) {
199
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
200
+            // We expect a valid user as sharedWith for user shares
201
+            if (!$this->userManager->userExists($share->getSharedWith())) {
202
+                throw new \InvalidArgumentException('SharedWith is not a valid user');
203
+            }
204
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
205
+            // We expect a valid group as sharedWith for group shares
206
+            if (!$this->groupManager->groupExists($share->getSharedWith())) {
207
+                throw new \InvalidArgumentException('SharedWith is not a valid group');
208
+            }
209
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
210
+            if ($share->getSharedWith() !== null) {
211
+                throw new \InvalidArgumentException('SharedWith should be empty');
212
+            }
213
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_REMOTE) {
214
+            if ($share->getSharedWith() === null) {
215
+                throw new \InvalidArgumentException('SharedWith should not be empty');
216
+            }
217
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_EMAIL) {
218
+            if ($share->getSharedWith() === null) {
219
+                throw new \InvalidArgumentException('SharedWith should not be empty');
220
+            }
221
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_CIRCLE) {
222
+            $circle = \OCA\Circles\Api\v1\Circles::detailsCircle($share->getSharedWith());
223
+            if ($circle === null) {
224
+                throw new \InvalidArgumentException('SharedWith is not a valid circle');
225
+            }
226
+        } else {
227
+            // We can't handle other types yet
228
+            throw new \InvalidArgumentException('unknown share type');
229
+        }
230
+
231
+        // Verify the initiator of the share is set
232
+        if ($share->getSharedBy() === null) {
233
+            throw new \InvalidArgumentException('SharedBy should be set');
234
+        }
235
+
236
+        // Cannot share with yourself
237
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER &&
238
+            $share->getSharedWith() === $share->getSharedBy()) {
239
+            throw new \InvalidArgumentException('Can’t share with yourself');
240
+        }
241
+
242
+        // The path should be set
243
+        if ($share->getNode() === null) {
244
+            throw new \InvalidArgumentException('Path should be set');
245
+        }
246
+
247
+        // And it should be a file or a folder
248
+        if (!($share->getNode() instanceof \OCP\Files\File) &&
249
+                !($share->getNode() instanceof \OCP\Files\Folder)) {
250
+            throw new \InvalidArgumentException('Path should be either a file or a folder');
251
+        }
252
+
253
+        // And you can't share your rootfolder
254
+        if ($this->userManager->userExists($share->getSharedBy())) {
255
+            $sharedPath = $this->rootFolder->getUserFolder($share->getSharedBy())->getPath();
256
+        } else {
257
+            $sharedPath = $this->rootFolder->getUserFolder($share->getShareOwner())->getPath();
258
+        }
259
+        if ($sharedPath === $share->getNode()->getPath()) {
260
+            throw new \InvalidArgumentException('You can’t share your root folder');
261
+        }
262
+
263
+        // Check if we actually have share permissions
264
+        if (!$share->getNode()->isShareable()) {
265
+            $message_t = $this->l->t('You are not allowed to share %s', [$share->getNode()->getPath()]);
266
+            throw new GenericShareException($message_t, $message_t, 404);
267
+        }
268
+
269
+        // Permissions should be set
270
+        if ($share->getPermissions() === null) {
271
+            throw new \InvalidArgumentException('A share requires permissions');
272
+        }
273
+
274
+        /*
275 275
 		 * Quick fix for #23536
276 276
 		 * Non moveable mount points do not have update and delete permissions
277 277
 		 * while we 'most likely' do have that on the storage.
278 278
 		 */
279
-		$permissions = $share->getNode()->getPermissions();
280
-		$mount = $share->getNode()->getMountPoint();
281
-		if (!($mount instanceof MoveableMount)) {
282
-			$permissions |= \OCP\Constants::PERMISSION_DELETE | \OCP\Constants::PERMISSION_UPDATE;
283
-		}
284
-
285
-		// Check that we do not share with more permissions than we have
286
-		if ($share->getPermissions() & ~$permissions) {
287
-			$message_t = $this->l->t('Can’t increase permissions of %s', [$share->getNode()->getPath()]);
288
-			throw new GenericShareException($message_t, $message_t, 404);
289
-		}
290
-
291
-
292
-		// Check that read permissions are always set
293
-		// Link shares are allowed to have no read permissions to allow upload to hidden folders
294
-		$noReadPermissionRequired = $share->getShareType() === \OCP\Share::SHARE_TYPE_LINK
295
-			|| $share->getShareType() === \OCP\Share::SHARE_TYPE_EMAIL;
296
-		if (!$noReadPermissionRequired &&
297
-			($share->getPermissions() & \OCP\Constants::PERMISSION_READ) === 0) {
298
-			throw new \InvalidArgumentException('Shares need at least read permissions');
299
-		}
300
-
301
-		if ($share->getNode() instanceof \OCP\Files\File) {
302
-			if ($share->getPermissions() & \OCP\Constants::PERMISSION_DELETE) {
303
-				$message_t = $this->l->t('Files can’t be shared with delete permissions');
304
-				throw new GenericShareException($message_t);
305
-			}
306
-			if ($share->getPermissions() & \OCP\Constants::PERMISSION_CREATE) {
307
-				$message_t = $this->l->t('Files can’t be shared with create permissions');
308
-				throw new GenericShareException($message_t);
309
-			}
310
-		}
311
-	}
312
-
313
-	/**
314
-	 * Validate if the expiration date fits the system settings
315
-	 *
316
-	 * @param \OCP\Share\IShare $share The share to validate the expiration date of
317
-	 * @return \OCP\Share\IShare The modified share object
318
-	 * @throws GenericShareException
319
-	 * @throws \InvalidArgumentException
320
-	 * @throws \Exception
321
-	 */
322
-	protected function validateExpirationDate(\OCP\Share\IShare $share) {
323
-
324
-		$expirationDate = $share->getExpirationDate();
325
-
326
-		if ($expirationDate !== null) {
327
-			//Make sure the expiration date is a date
328
-			$expirationDate->setTime(0, 0, 0);
329
-
330
-			$date = new \DateTime();
331
-			$date->setTime(0, 0, 0);
332
-			if ($date >= $expirationDate) {
333
-				$message = $this->l->t('Expiration date is in the past');
334
-				throw new GenericShareException($message, $message, 404);
335
-			}
336
-		}
337
-
338
-		// If expiredate is empty set a default one if there is a default
339
-		$fullId = null;
340
-		try {
341
-			$fullId = $share->getFullId();
342
-		} catch (\UnexpectedValueException $e) {
343
-			// This is a new share
344
-		}
345
-
346
-		if ($fullId === null && $expirationDate === null && $this->shareApiLinkDefaultExpireDate()) {
347
-			$expirationDate = new \DateTime();
348
-			$expirationDate->setTime(0,0,0);
349
-			$expirationDate->add(new \DateInterval('P'.$this->shareApiLinkDefaultExpireDays().'D'));
350
-		}
351
-
352
-		// If we enforce the expiration date check that is does not exceed
353
-		if ($this->shareApiLinkDefaultExpireDateEnforced()) {
354
-			if ($expirationDate === null) {
355
-				throw new \InvalidArgumentException('Expiration date is enforced');
356
-			}
357
-
358
-			$date = new \DateTime();
359
-			$date->setTime(0, 0, 0);
360
-			$date->add(new \DateInterval('P' . $this->shareApiLinkDefaultExpireDays() . 'D'));
361
-			if ($date < $expirationDate) {
362
-				$message = $this->l->t('Can’t set expiration date more than %s days in the future', [$this->shareApiLinkDefaultExpireDays()]);
363
-				throw new GenericShareException($message, $message, 404);
364
-			}
365
-		}
366
-
367
-		$accepted = true;
368
-		$message = '';
369
-		\OCP\Util::emitHook('\OC\Share', 'verifyExpirationDate', [
370
-			'expirationDate' => &$expirationDate,
371
-			'accepted' => &$accepted,
372
-			'message' => &$message,
373
-			'passwordSet' => $share->getPassword() !== null,
374
-		]);
375
-
376
-		if (!$accepted) {
377
-			throw new \Exception($message);
378
-		}
379
-
380
-		$share->setExpirationDate($expirationDate);
381
-
382
-		return $share;
383
-	}
384
-
385
-	/**
386
-	 * Check for pre share requirements for user shares
387
-	 *
388
-	 * @param \OCP\Share\IShare $share
389
-	 * @throws \Exception
390
-	 */
391
-	protected function userCreateChecks(\OCP\Share\IShare $share) {
392
-		// Check if we can share with group members only
393
-		if ($this->shareWithGroupMembersOnly()) {
394
-			$sharedBy = $this->userManager->get($share->getSharedBy());
395
-			$sharedWith = $this->userManager->get($share->getSharedWith());
396
-			// Verify we can share with this user
397
-			$groups = array_intersect(
398
-					$this->groupManager->getUserGroupIds($sharedBy),
399
-					$this->groupManager->getUserGroupIds($sharedWith)
400
-			);
401
-			if (empty($groups)) {
402
-				throw new \Exception('Sharing is only allowed with group members');
403
-			}
404
-		}
405
-
406
-		/*
279
+        $permissions = $share->getNode()->getPermissions();
280
+        $mount = $share->getNode()->getMountPoint();
281
+        if (!($mount instanceof MoveableMount)) {
282
+            $permissions |= \OCP\Constants::PERMISSION_DELETE | \OCP\Constants::PERMISSION_UPDATE;
283
+        }
284
+
285
+        // Check that we do not share with more permissions than we have
286
+        if ($share->getPermissions() & ~$permissions) {
287
+            $message_t = $this->l->t('Can’t increase permissions of %s', [$share->getNode()->getPath()]);
288
+            throw new GenericShareException($message_t, $message_t, 404);
289
+        }
290
+
291
+
292
+        // Check that read permissions are always set
293
+        // Link shares are allowed to have no read permissions to allow upload to hidden folders
294
+        $noReadPermissionRequired = $share->getShareType() === \OCP\Share::SHARE_TYPE_LINK
295
+            || $share->getShareType() === \OCP\Share::SHARE_TYPE_EMAIL;
296
+        if (!$noReadPermissionRequired &&
297
+            ($share->getPermissions() & \OCP\Constants::PERMISSION_READ) === 0) {
298
+            throw new \InvalidArgumentException('Shares need at least read permissions');
299
+        }
300
+
301
+        if ($share->getNode() instanceof \OCP\Files\File) {
302
+            if ($share->getPermissions() & \OCP\Constants::PERMISSION_DELETE) {
303
+                $message_t = $this->l->t('Files can’t be shared with delete permissions');
304
+                throw new GenericShareException($message_t);
305
+            }
306
+            if ($share->getPermissions() & \OCP\Constants::PERMISSION_CREATE) {
307
+                $message_t = $this->l->t('Files can’t be shared with create permissions');
308
+                throw new GenericShareException($message_t);
309
+            }
310
+        }
311
+    }
312
+
313
+    /**
314
+     * Validate if the expiration date fits the system settings
315
+     *
316
+     * @param \OCP\Share\IShare $share The share to validate the expiration date of
317
+     * @return \OCP\Share\IShare The modified share object
318
+     * @throws GenericShareException
319
+     * @throws \InvalidArgumentException
320
+     * @throws \Exception
321
+     */
322
+    protected function validateExpirationDate(\OCP\Share\IShare $share) {
323
+
324
+        $expirationDate = $share->getExpirationDate();
325
+
326
+        if ($expirationDate !== null) {
327
+            //Make sure the expiration date is a date
328
+            $expirationDate->setTime(0, 0, 0);
329
+
330
+            $date = new \DateTime();
331
+            $date->setTime(0, 0, 0);
332
+            if ($date >= $expirationDate) {
333
+                $message = $this->l->t('Expiration date is in the past');
334
+                throw new GenericShareException($message, $message, 404);
335
+            }
336
+        }
337
+
338
+        // If expiredate is empty set a default one if there is a default
339
+        $fullId = null;
340
+        try {
341
+            $fullId = $share->getFullId();
342
+        } catch (\UnexpectedValueException $e) {
343
+            // This is a new share
344
+        }
345
+
346
+        if ($fullId === null && $expirationDate === null && $this->shareApiLinkDefaultExpireDate()) {
347
+            $expirationDate = new \DateTime();
348
+            $expirationDate->setTime(0,0,0);
349
+            $expirationDate->add(new \DateInterval('P'.$this->shareApiLinkDefaultExpireDays().'D'));
350
+        }
351
+
352
+        // If we enforce the expiration date check that is does not exceed
353
+        if ($this->shareApiLinkDefaultExpireDateEnforced()) {
354
+            if ($expirationDate === null) {
355
+                throw new \InvalidArgumentException('Expiration date is enforced');
356
+            }
357
+
358
+            $date = new \DateTime();
359
+            $date->setTime(0, 0, 0);
360
+            $date->add(new \DateInterval('P' . $this->shareApiLinkDefaultExpireDays() . 'D'));
361
+            if ($date < $expirationDate) {
362
+                $message = $this->l->t('Can’t set expiration date more than %s days in the future', [$this->shareApiLinkDefaultExpireDays()]);
363
+                throw new GenericShareException($message, $message, 404);
364
+            }
365
+        }
366
+
367
+        $accepted = true;
368
+        $message = '';
369
+        \OCP\Util::emitHook('\OC\Share', 'verifyExpirationDate', [
370
+            'expirationDate' => &$expirationDate,
371
+            'accepted' => &$accepted,
372
+            'message' => &$message,
373
+            'passwordSet' => $share->getPassword() !== null,
374
+        ]);
375
+
376
+        if (!$accepted) {
377
+            throw new \Exception($message);
378
+        }
379
+
380
+        $share->setExpirationDate($expirationDate);
381
+
382
+        return $share;
383
+    }
384
+
385
+    /**
386
+     * Check for pre share requirements for user shares
387
+     *
388
+     * @param \OCP\Share\IShare $share
389
+     * @throws \Exception
390
+     */
391
+    protected function userCreateChecks(\OCP\Share\IShare $share) {
392
+        // Check if we can share with group members only
393
+        if ($this->shareWithGroupMembersOnly()) {
394
+            $sharedBy = $this->userManager->get($share->getSharedBy());
395
+            $sharedWith = $this->userManager->get($share->getSharedWith());
396
+            // Verify we can share with this user
397
+            $groups = array_intersect(
398
+                    $this->groupManager->getUserGroupIds($sharedBy),
399
+                    $this->groupManager->getUserGroupIds($sharedWith)
400
+            );
401
+            if (empty($groups)) {
402
+                throw new \Exception('Sharing is only allowed with group members');
403
+            }
404
+        }
405
+
406
+        /*
407 407
 		 * TODO: Could be costly, fix
408 408
 		 *
409 409
 		 * Also this is not what we want in the future.. then we want to squash identical shares.
410 410
 		 */
411
-		$provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_USER);
412
-		$existingShares = $provider->getSharesByPath($share->getNode());
413
-		foreach($existingShares as $existingShare) {
414
-			// Ignore if it is the same share
415
-			try {
416
-				if ($existingShare->getFullId() === $share->getFullId()) {
417
-					continue;
418
-				}
419
-			} catch (\UnexpectedValueException $e) {
420
-				//Shares are not identical
421
-			}
422
-
423
-			// Identical share already existst
424
-			if ($existingShare->getSharedWith() === $share->getSharedWith()) {
425
-				throw new \Exception('Path is already shared with this user');
426
-			}
427
-
428
-			// The share is already shared with this user via a group share
429
-			if ($existingShare->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
430
-				$group = $this->groupManager->get($existingShare->getSharedWith());
431
-				if (!is_null($group)) {
432
-					$user = $this->userManager->get($share->getSharedWith());
433
-
434
-					if ($group->inGroup($user) && $existingShare->getShareOwner() !== $share->getShareOwner()) {
435
-						throw new \Exception('Path is already shared with this user');
436
-					}
437
-				}
438
-			}
439
-		}
440
-	}
441
-
442
-	/**
443
-	 * Check for pre share requirements for group shares
444
-	 *
445
-	 * @param \OCP\Share\IShare $share
446
-	 * @throws \Exception
447
-	 */
448
-	protected function groupCreateChecks(\OCP\Share\IShare $share) {
449
-		// Verify group shares are allowed
450
-		if (!$this->allowGroupSharing()) {
451
-			throw new \Exception('Group sharing is now allowed');
452
-		}
453
-
454
-		// Verify if the user can share with this group
455
-		if ($this->shareWithGroupMembersOnly()) {
456
-			$sharedBy = $this->userManager->get($share->getSharedBy());
457
-			$sharedWith = $this->groupManager->get($share->getSharedWith());
458
-			if (is_null($sharedWith) || !$sharedWith->inGroup($sharedBy)) {
459
-				throw new \Exception('Sharing is only allowed within your own groups');
460
-			}
461
-		}
462
-
463
-		/*
411
+        $provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_USER);
412
+        $existingShares = $provider->getSharesByPath($share->getNode());
413
+        foreach($existingShares as $existingShare) {
414
+            // Ignore if it is the same share
415
+            try {
416
+                if ($existingShare->getFullId() === $share->getFullId()) {
417
+                    continue;
418
+                }
419
+            } catch (\UnexpectedValueException $e) {
420
+                //Shares are not identical
421
+            }
422
+
423
+            // Identical share already existst
424
+            if ($existingShare->getSharedWith() === $share->getSharedWith()) {
425
+                throw new \Exception('Path is already shared with this user');
426
+            }
427
+
428
+            // The share is already shared with this user via a group share
429
+            if ($existingShare->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
430
+                $group = $this->groupManager->get($existingShare->getSharedWith());
431
+                if (!is_null($group)) {
432
+                    $user = $this->userManager->get($share->getSharedWith());
433
+
434
+                    if ($group->inGroup($user) && $existingShare->getShareOwner() !== $share->getShareOwner()) {
435
+                        throw new \Exception('Path is already shared with this user');
436
+                    }
437
+                }
438
+            }
439
+        }
440
+    }
441
+
442
+    /**
443
+     * Check for pre share requirements for group shares
444
+     *
445
+     * @param \OCP\Share\IShare $share
446
+     * @throws \Exception
447
+     */
448
+    protected function groupCreateChecks(\OCP\Share\IShare $share) {
449
+        // Verify group shares are allowed
450
+        if (!$this->allowGroupSharing()) {
451
+            throw new \Exception('Group sharing is now allowed');
452
+        }
453
+
454
+        // Verify if the user can share with this group
455
+        if ($this->shareWithGroupMembersOnly()) {
456
+            $sharedBy = $this->userManager->get($share->getSharedBy());
457
+            $sharedWith = $this->groupManager->get($share->getSharedWith());
458
+            if (is_null($sharedWith) || !$sharedWith->inGroup($sharedBy)) {
459
+                throw new \Exception('Sharing is only allowed within your own groups');
460
+            }
461
+        }
462
+
463
+        /*
464 464
 		 * TODO: Could be costly, fix
465 465
 		 *
466 466
 		 * Also this is not what we want in the future.. then we want to squash identical shares.
467 467
 		 */
468
-		$provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_GROUP);
469
-		$existingShares = $provider->getSharesByPath($share->getNode());
470
-		foreach($existingShares as $existingShare) {
471
-			try {
472
-				if ($existingShare->getFullId() === $share->getFullId()) {
473
-					continue;
474
-				}
475
-			} catch (\UnexpectedValueException $e) {
476
-				//It is a new share so just continue
477
-			}
478
-
479
-			if ($existingShare->getSharedWith() === $share->getSharedWith()) {
480
-				throw new \Exception('Path is already shared with this group');
481
-			}
482
-		}
483
-	}
484
-
485
-	/**
486
-	 * Check for pre share requirements for link shares
487
-	 *
488
-	 * @param \OCP\Share\IShare $share
489
-	 * @throws \Exception
490
-	 */
491
-	protected function linkCreateChecks(\OCP\Share\IShare $share) {
492
-		// Are link shares allowed?
493
-		if (!$this->shareApiAllowLinks()) {
494
-			throw new \Exception('Link sharing is not allowed');
495
-		}
496
-
497
-		// Link shares by definition can't have share permissions
498
-		if ($share->getPermissions() & \OCP\Constants::PERMISSION_SHARE) {
499
-			throw new \InvalidArgumentException('Link shares can’t have reshare permissions');
500
-		}
501
-
502
-		// Check if public upload is allowed
503
-		if (!$this->shareApiLinkAllowPublicUpload() &&
504
-			($share->getPermissions() & (\OCP\Constants::PERMISSION_CREATE | \OCP\Constants::PERMISSION_UPDATE | \OCP\Constants::PERMISSION_DELETE))) {
505
-			throw new \InvalidArgumentException('Public upload is not allowed');
506
-		}
507
-	}
508
-
509
-	/**
510
-	 * To make sure we don't get invisible link shares we set the parent
511
-	 * of a link if it is a reshare. This is a quick word around
512
-	 * until we can properly display multiple link shares in the UI
513
-	 *
514
-	 * See: https://github.com/owncloud/core/issues/22295
515
-	 *
516
-	 * FIXME: Remove once multiple link shares can be properly displayed
517
-	 *
518
-	 * @param \OCP\Share\IShare $share
519
-	 */
520
-	protected function setLinkParent(\OCP\Share\IShare $share) {
521
-
522
-		// No sense in checking if the method is not there.
523
-		if (method_exists($share, 'setParent')) {
524
-			$storage = $share->getNode()->getStorage();
525
-			if ($storage->instanceOfStorage('\OCA\Files_Sharing\ISharedStorage')) {
526
-				/** @var \OCA\Files_Sharing\SharedStorage $storage */
527
-				$share->setParent($storage->getShareId());
528
-			}
529
-		};
530
-	}
531
-
532
-	/**
533
-	 * @param File|Folder $path
534
-	 */
535
-	protected function pathCreateChecks($path) {
536
-		// Make sure that we do not share a path that contains a shared mountpoint
537
-		if ($path instanceof \OCP\Files\Folder) {
538
-			$mounts = $this->mountManager->findIn($path->getPath());
539
-			foreach($mounts as $mount) {
540
-				if ($mount->getStorage()->instanceOfStorage('\OCA\Files_Sharing\ISharedStorage')) {
541
-					throw new \InvalidArgumentException('Path contains files shared with you');
542
-				}
543
-			}
544
-		}
545
-	}
546
-
547
-	/**
548
-	 * Check if the user that is sharing can actually share
549
-	 *
550
-	 * @param \OCP\Share\IShare $share
551
-	 * @throws \Exception
552
-	 */
553
-	protected function canShare(\OCP\Share\IShare $share) {
554
-		if (!$this->shareApiEnabled()) {
555
-			throw new \Exception('Sharing is disabled');
556
-		}
557
-
558
-		if ($this->sharingDisabledForUser($share->getSharedBy())) {
559
-			throw new \Exception('Sharing is disabled for you');
560
-		}
561
-	}
562
-
563
-	/**
564
-	 * Share a path
565
-	 *
566
-	 * @param \OCP\Share\IShare $share
567
-	 * @return Share The share object
568
-	 * @throws \Exception
569
-	 *
570
-	 * TODO: handle link share permissions or check them
571
-	 */
572
-	public function createShare(\OCP\Share\IShare $share) {
573
-		$this->canShare($share);
574
-
575
-		$this->generalCreateChecks($share);
576
-
577
-		// Verify if there are any issues with the path
578
-		$this->pathCreateChecks($share->getNode());
579
-
580
-		/*
468
+        $provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_GROUP);
469
+        $existingShares = $provider->getSharesByPath($share->getNode());
470
+        foreach($existingShares as $existingShare) {
471
+            try {
472
+                if ($existingShare->getFullId() === $share->getFullId()) {
473
+                    continue;
474
+                }
475
+            } catch (\UnexpectedValueException $e) {
476
+                //It is a new share so just continue
477
+            }
478
+
479
+            if ($existingShare->getSharedWith() === $share->getSharedWith()) {
480
+                throw new \Exception('Path is already shared with this group');
481
+            }
482
+        }
483
+    }
484
+
485
+    /**
486
+     * Check for pre share requirements for link shares
487
+     *
488
+     * @param \OCP\Share\IShare $share
489
+     * @throws \Exception
490
+     */
491
+    protected function linkCreateChecks(\OCP\Share\IShare $share) {
492
+        // Are link shares allowed?
493
+        if (!$this->shareApiAllowLinks()) {
494
+            throw new \Exception('Link sharing is not allowed');
495
+        }
496
+
497
+        // Link shares by definition can't have share permissions
498
+        if ($share->getPermissions() & \OCP\Constants::PERMISSION_SHARE) {
499
+            throw new \InvalidArgumentException('Link shares can’t have reshare permissions');
500
+        }
501
+
502
+        // Check if public upload is allowed
503
+        if (!$this->shareApiLinkAllowPublicUpload() &&
504
+            ($share->getPermissions() & (\OCP\Constants::PERMISSION_CREATE | \OCP\Constants::PERMISSION_UPDATE | \OCP\Constants::PERMISSION_DELETE))) {
505
+            throw new \InvalidArgumentException('Public upload is not allowed');
506
+        }
507
+    }
508
+
509
+    /**
510
+     * To make sure we don't get invisible link shares we set the parent
511
+     * of a link if it is a reshare. This is a quick word around
512
+     * until we can properly display multiple link shares in the UI
513
+     *
514
+     * See: https://github.com/owncloud/core/issues/22295
515
+     *
516
+     * FIXME: Remove once multiple link shares can be properly displayed
517
+     *
518
+     * @param \OCP\Share\IShare $share
519
+     */
520
+    protected function setLinkParent(\OCP\Share\IShare $share) {
521
+
522
+        // No sense in checking if the method is not there.
523
+        if (method_exists($share, 'setParent')) {
524
+            $storage = $share->getNode()->getStorage();
525
+            if ($storage->instanceOfStorage('\OCA\Files_Sharing\ISharedStorage')) {
526
+                /** @var \OCA\Files_Sharing\SharedStorage $storage */
527
+                $share->setParent($storage->getShareId());
528
+            }
529
+        };
530
+    }
531
+
532
+    /**
533
+     * @param File|Folder $path
534
+     */
535
+    protected function pathCreateChecks($path) {
536
+        // Make sure that we do not share a path that contains a shared mountpoint
537
+        if ($path instanceof \OCP\Files\Folder) {
538
+            $mounts = $this->mountManager->findIn($path->getPath());
539
+            foreach($mounts as $mount) {
540
+                if ($mount->getStorage()->instanceOfStorage('\OCA\Files_Sharing\ISharedStorage')) {
541
+                    throw new \InvalidArgumentException('Path contains files shared with you');
542
+                }
543
+            }
544
+        }
545
+    }
546
+
547
+    /**
548
+     * Check if the user that is sharing can actually share
549
+     *
550
+     * @param \OCP\Share\IShare $share
551
+     * @throws \Exception
552
+     */
553
+    protected function canShare(\OCP\Share\IShare $share) {
554
+        if (!$this->shareApiEnabled()) {
555
+            throw new \Exception('Sharing is disabled');
556
+        }
557
+
558
+        if ($this->sharingDisabledForUser($share->getSharedBy())) {
559
+            throw new \Exception('Sharing is disabled for you');
560
+        }
561
+    }
562
+
563
+    /**
564
+     * Share a path
565
+     *
566
+     * @param \OCP\Share\IShare $share
567
+     * @return Share The share object
568
+     * @throws \Exception
569
+     *
570
+     * TODO: handle link share permissions or check them
571
+     */
572
+    public function createShare(\OCP\Share\IShare $share) {
573
+        $this->canShare($share);
574
+
575
+        $this->generalCreateChecks($share);
576
+
577
+        // Verify if there are any issues with the path
578
+        $this->pathCreateChecks($share->getNode());
579
+
580
+        /*
581 581
 		 * On creation of a share the owner is always the owner of the path
582 582
 		 * Except for mounted federated shares.
583 583
 		 */
584
-		$storage = $share->getNode()->getStorage();
585
-		if ($storage->instanceOfStorage('OCA\Files_Sharing\External\Storage')) {
586
-			$parent = $share->getNode()->getParent();
587
-			while($parent->getStorage()->instanceOfStorage('OCA\Files_Sharing\External\Storage')) {
588
-				$parent = $parent->getParent();
589
-			}
590
-			$share->setShareOwner($parent->getOwner()->getUID());
591
-		} else {
592
-			$share->setShareOwner($share->getNode()->getOwner()->getUID());
593
-		}
594
-
595
-		//Verify share type
596
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
597
-			$this->userCreateChecks($share);
598
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
599
-			$this->groupCreateChecks($share);
600
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
601
-			$this->linkCreateChecks($share);
602
-			$this->setLinkParent($share);
603
-
604
-			/*
584
+        $storage = $share->getNode()->getStorage();
585
+        if ($storage->instanceOfStorage('OCA\Files_Sharing\External\Storage')) {
586
+            $parent = $share->getNode()->getParent();
587
+            while($parent->getStorage()->instanceOfStorage('OCA\Files_Sharing\External\Storage')) {
588
+                $parent = $parent->getParent();
589
+            }
590
+            $share->setShareOwner($parent->getOwner()->getUID());
591
+        } else {
592
+            $share->setShareOwner($share->getNode()->getOwner()->getUID());
593
+        }
594
+
595
+        //Verify share type
596
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
597
+            $this->userCreateChecks($share);
598
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
599
+            $this->groupCreateChecks($share);
600
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
601
+            $this->linkCreateChecks($share);
602
+            $this->setLinkParent($share);
603
+
604
+            /*
605 605
 			 * For now ignore a set token.
606 606
 			 */
607
-			$share->setToken(
608
-				$this->secureRandom->generate(
609
-					\OC\Share\Constants::TOKEN_LENGTH,
610
-					\OCP\Security\ISecureRandom::CHAR_HUMAN_READABLE
611
-				)
612
-			);
613
-
614
-			//Verify the expiration date
615
-			$this->validateExpirationDate($share);
616
-
617
-			//Verify the password
618
-			$this->verifyPassword($share->getPassword());
619
-
620
-			// If a password is set. Hash it!
621
-			if ($share->getPassword() !== null) {
622
-				$share->setPassword($this->hasher->hash($share->getPassword()));
623
-			}
624
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_EMAIL) {
625
-			$share->setToken(
626
-				$this->secureRandom->generate(
627
-					\OC\Share\Constants::TOKEN_LENGTH,
628
-					\OCP\Security\ISecureRandom::CHAR_HUMAN_READABLE
629
-				)
630
-			);
631
-		}
632
-
633
-		// Cannot share with the owner
634
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER &&
635
-			$share->getSharedWith() === $share->getShareOwner()) {
636
-			throw new \InvalidArgumentException('Can’t share with the share owner');
637
-		}
638
-
639
-		// Generate the target
640
-		$target = $this->config->getSystemValue('share_folder', '/') .'/'. $share->getNode()->getName();
641
-		$target = \OC\Files\Filesystem::normalizePath($target);
642
-		$share->setTarget($target);
643
-
644
-		// Pre share event
645
-		$event = new GenericEvent($share);
646
-		$a = $this->eventDispatcher->dispatch('OCP\Share::preShare', $event);
647
-		if ($event->isPropagationStopped() && $event->hasArgument('error')) {
648
-			throw new \Exception($event->getArgument('error'));
649
-		}
650
-
651
-		$oldShare = $share;
652
-		$provider = $this->factory->getProviderForType($share->getShareType());
653
-		$share = $provider->create($share);
654
-		//reuse the node we already have
655
-		$share->setNode($oldShare->getNode());
656
-
657
-		// Post share event
658
-		$event = new GenericEvent($share);
659
-		$this->eventDispatcher->dispatch('OCP\Share::postShare', $event);
660
-
661
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
662
-			$user = $this->userManager->get($share->getSharedWith());
663
-			if ($user !== null) {
664
-				$emailAddress = $user->getEMailAddress();
665
-				if ($emailAddress !== null && $emailAddress !== '') {
666
-					$userLang = $this->config->getUserValue($share->getSharedWith(), 'core', 'lang', null);
667
-					$l = $this->l10nFactory->get('lib', $userLang);
668
-					$this->sendMailNotification(
669
-						$l,
670
-						$share->getNode()->getName(),
671
-						$this->urlGenerator->linkToRouteAbsolute('files.viewcontroller.showFile', [ 'fileid' => $share->getNode()->getId() ]),
672
-						$share->getSharedBy(),
673
-						$emailAddress,
674
-						$share->getExpirationDate()
675
-					);
676
-					$this->logger->debug('Send share notification to ' . $emailAddress . ' for share with ID ' . $share->getId(), ['app' => 'share']);
677
-				} else {
678
-					$this->logger->debug('Share notification not send to ' . $share->getSharedWith() . ' because email address is not set.', ['app' => 'share']);
679
-				}
680
-			} else {
681
-				$this->logger->debug('Share notification not send to ' . $share->getSharedWith() . ' because user could not be found.', ['app' => 'share']);
682
-			}
683
-		}
684
-
685
-		return $share;
686
-	}
687
-
688
-	/**
689
-	 * @param IL10N $l Language of the recipient
690
-	 * @param string $filename file/folder name
691
-	 * @param string $link link to the file/folder
692
-	 * @param string $initiator user ID of share sender
693
-	 * @param string $shareWith email address of share receiver
694
-	 * @param \DateTime|null $expiration
695
-	 * @throws \Exception If mail couldn't be sent
696
-	 */
697
-	protected function sendMailNotification(IL10N $l,
698
-											$filename,
699
-											$link,
700
-											$initiator,
701
-											$shareWith,
702
-											\DateTime $expiration = null) {
703
-		$initiatorUser = $this->userManager->get($initiator);
704
-		$initiatorDisplayName = ($initiatorUser instanceof IUser) ? $initiatorUser->getDisplayName() : $initiator;
705
-
706
-		$message = $this->mailer->createMessage();
707
-
708
-		$emailTemplate = $this->mailer->createEMailTemplate('files_sharing.RecipientNotification', [
709
-			'filename' => $filename,
710
-			'link' => $link,
711
-			'initiator' => $initiatorDisplayName,
712
-			'expiration' => $expiration,
713
-			'shareWith' => $shareWith,
714
-		]);
715
-
716
-		$emailTemplate->setSubject($l->t('%s shared »%s« with you', array($initiatorDisplayName, $filename)));
717
-		$emailTemplate->addHeader();
718
-		$emailTemplate->addHeading($l->t('%s shared »%s« with you', [$initiatorDisplayName, $filename]), false);
719
-		$text = $l->t('%s shared »%s« with you.', [$initiatorDisplayName, $filename]);
720
-
721
-		$emailTemplate->addBodyText(
722
-			$text . ' ' . $l->t('Click the button below to open it.'),
723
-			$text
724
-		);
725
-		$emailTemplate->addBodyButton(
726
-			$l->t('Open »%s«', [$filename]),
727
-			$link
728
-		);
729
-
730
-		$message->setTo([$shareWith]);
731
-
732
-		// The "From" contains the sharers name
733
-		$instanceName = $this->defaults->getName();
734
-		$senderName = $l->t(
735
-			'%s via %s',
736
-			[
737
-				$initiatorDisplayName,
738
-				$instanceName
739
-			]
740
-		);
741
-		$message->setFrom([\OCP\Util::getDefaultEmailAddress($instanceName) => $senderName]);
742
-
743
-		// The "Reply-To" is set to the sharer if an mail address is configured
744
-		// also the default footer contains a "Do not reply" which needs to be adjusted.
745
-		$initiatorEmail = $initiatorUser->getEMailAddress();
746
-		if($initiatorEmail !== null) {
747
-			$message->setReplyTo([$initiatorEmail => $initiatorDisplayName]);
748
-			$emailTemplate->addFooter($instanceName . ($this->defaults->getSlogan() !== '' ? ' - ' . $this->defaults->getSlogan() : ''));
749
-		} else {
750
-			$emailTemplate->addFooter();
751
-		}
752
-
753
-		$message->useTemplate($emailTemplate);
754
-		$this->mailer->send($message);
755
-	}
756
-
757
-	/**
758
-	 * Update a share
759
-	 *
760
-	 * @param \OCP\Share\IShare $share
761
-	 * @return \OCP\Share\IShare The share object
762
-	 * @throws \InvalidArgumentException
763
-	 */
764
-	public function updateShare(\OCP\Share\IShare $share) {
765
-		$expirationDateUpdated = false;
766
-
767
-		$this->canShare($share);
768
-
769
-		try {
770
-			$originalShare = $this->getShareById($share->getFullId());
771
-		} catch (\UnexpectedValueException $e) {
772
-			throw new \InvalidArgumentException('Share does not have a full id');
773
-		}
774
-
775
-		// We can't change the share type!
776
-		if ($share->getShareType() !== $originalShare->getShareType()) {
777
-			throw new \InvalidArgumentException('Can’t change share type');
778
-		}
779
-
780
-		// We can only change the recipient on user shares
781
-		if ($share->getSharedWith() !== $originalShare->getSharedWith() &&
782
-		    $share->getShareType() !== \OCP\Share::SHARE_TYPE_USER) {
783
-			throw new \InvalidArgumentException('Can only update recipient on user shares');
784
-		}
785
-
786
-		// Cannot share with the owner
787
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER &&
788
-			$share->getSharedWith() === $share->getShareOwner()) {
789
-			throw new \InvalidArgumentException('Can’t share with the share owner');
790
-		}
791
-
792
-		$this->generalCreateChecks($share);
793
-
794
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
795
-			$this->userCreateChecks($share);
796
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
797
-			$this->groupCreateChecks($share);
798
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
799
-			$this->linkCreateChecks($share);
800
-
801
-			$this->updateSharePasswordIfNeeded($share, $originalShare);
802
-
803
-			if ($share->getExpirationDate() != $originalShare->getExpirationDate()) {
804
-				//Verify the expiration date
805
-				$this->validateExpirationDate($share);
806
-				$expirationDateUpdated = true;
807
-			}
808
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_EMAIL) {
809
-			$plainTextPassword = $share->getPassword();
810
-			if (!$this->updateSharePasswordIfNeeded($share, $originalShare)) {
811
-				$plainTextPassword = null;
812
-			}
813
-		}
814
-
815
-		$this->pathCreateChecks($share->getNode());
816
-
817
-		// Now update the share!
818
-		$provider = $this->factory->getProviderForType($share->getShareType());
819
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_EMAIL) {
820
-			$share = $provider->update($share, $plainTextPassword);
821
-		} else {
822
-			$share = $provider->update($share);
823
-		}
824
-
825
-		if ($expirationDateUpdated === true) {
826
-			\OC_Hook::emit('OCP\Share', 'post_set_expiration_date', [
827
-				'itemType' => $share->getNode() instanceof \OCP\Files\File ? 'file' : 'folder',
828
-				'itemSource' => $share->getNode()->getId(),
829
-				'date' => $share->getExpirationDate(),
830
-				'uidOwner' => $share->getSharedBy(),
831
-			]);
832
-		}
833
-
834
-		if ($share->getPassword() !== $originalShare->getPassword()) {
835
-			\OC_Hook::emit('OCP\Share', 'post_update_password', [
836
-				'itemType' => $share->getNode() instanceof \OCP\Files\File ? 'file' : 'folder',
837
-				'itemSource' => $share->getNode()->getId(),
838
-				'uidOwner' => $share->getSharedBy(),
839
-				'token' => $share->getToken(),
840
-				'disabled' => is_null($share->getPassword()),
841
-			]);
842
-		}
843
-
844
-		if ($share->getPermissions() !== $originalShare->getPermissions()) {
845
-			if ($this->userManager->userExists($share->getShareOwner())) {
846
-				$userFolder = $this->rootFolder->getUserFolder($share->getShareOwner());
847
-			} else {
848
-				$userFolder = $this->rootFolder->getUserFolder($share->getSharedBy());
849
-			}
850
-			\OC_Hook::emit('OCP\Share', 'post_update_permissions', array(
851
-				'itemType' => $share->getNode() instanceof \OCP\Files\File ? 'file' : 'folder',
852
-				'itemSource' => $share->getNode()->getId(),
853
-				'shareType' => $share->getShareType(),
854
-				'shareWith' => $share->getSharedWith(),
855
-				'uidOwner' => $share->getSharedBy(),
856
-				'permissions' => $share->getPermissions(),
857
-				'path' => $userFolder->getRelativePath($share->getNode()->getPath()),
858
-			));
859
-		}
860
-
861
-		return $share;
862
-	}
863
-
864
-	/**
865
-	 * Updates the password of the given share if it is not the same as the
866
-	 * password of the original share.
867
-	 *
868
-	 * @param \OCP\Share\IShare $share the share to update its password.
869
-	 * @param \OCP\Share\IShare $originalShare the original share to compare its
870
-	 *        password with.
871
-	 * @return boolean whether the password was updated or not.
872
-	 */
873
-	private function updateSharePasswordIfNeeded(\OCP\Share\IShare $share, \OCP\Share\IShare $originalShare) {
874
-		// Password updated.
875
-		if ($share->getPassword() !== $originalShare->getPassword()) {
876
-			//Verify the password
877
-			$this->verifyPassword($share->getPassword());
878
-
879
-			// If a password is set. Hash it!
880
-			if ($share->getPassword() !== null) {
881
-				$share->setPassword($this->hasher->hash($share->getPassword()));
882
-
883
-				return true;
884
-			}
885
-		}
886
-
887
-		return false;
888
-	}
889
-
890
-	/**
891
-	 * Delete all the children of this share
892
-	 * FIXME: remove once https://github.com/owncloud/core/pull/21660 is in
893
-	 *
894
-	 * @param \OCP\Share\IShare $share
895
-	 * @return \OCP\Share\IShare[] List of deleted shares
896
-	 */
897
-	protected function deleteChildren(\OCP\Share\IShare $share) {
898
-		$deletedShares = [];
899
-
900
-		$provider = $this->factory->getProviderForType($share->getShareType());
901
-
902
-		foreach ($provider->getChildren($share) as $child) {
903
-			$deletedChildren = $this->deleteChildren($child);
904
-			$deletedShares = array_merge($deletedShares, $deletedChildren);
905
-
906
-			$provider->delete($child);
907
-			$deletedShares[] = $child;
908
-		}
909
-
910
-		return $deletedShares;
911
-	}
912
-
913
-	/**
914
-	 * Delete a share
915
-	 *
916
-	 * @param \OCP\Share\IShare $share
917
-	 * @throws ShareNotFound
918
-	 * @throws \InvalidArgumentException
919
-	 */
920
-	public function deleteShare(\OCP\Share\IShare $share) {
921
-
922
-		try {
923
-			$share->getFullId();
924
-		} catch (\UnexpectedValueException $e) {
925
-			throw new \InvalidArgumentException('Share does not have a full id');
926
-		}
927
-
928
-		$event = new GenericEvent($share);
929
-		$this->eventDispatcher->dispatch('OCP\Share::preUnshare', $event);
930
-
931
-		// Get all children and delete them as well
932
-		$deletedShares = $this->deleteChildren($share);
933
-
934
-		// Do the actual delete
935
-		$provider = $this->factory->getProviderForType($share->getShareType());
936
-		$provider->delete($share);
937
-
938
-		// All the deleted shares caused by this delete
939
-		$deletedShares[] = $share;
940
-
941
-		// Emit post hook
942
-		$event->setArgument('deletedShares', $deletedShares);
943
-		$this->eventDispatcher->dispatch('OCP\Share::postUnshare', $event);
944
-	}
945
-
946
-
947
-	/**
948
-	 * Unshare a file as the recipient.
949
-	 * This can be different from a regular delete for example when one of
950
-	 * the users in a groups deletes that share. But the provider should
951
-	 * handle this.
952
-	 *
953
-	 * @param \OCP\Share\IShare $share
954
-	 * @param string $recipientId
955
-	 */
956
-	public function deleteFromSelf(\OCP\Share\IShare $share, $recipientId) {
957
-		list($providerId, ) = $this->splitFullId($share->getFullId());
958
-		$provider = $this->factory->getProvider($providerId);
959
-
960
-		$provider->deleteFromSelf($share, $recipientId);
961
-		$event = new GenericEvent($share);
962
-		$this->eventDispatcher->dispatch('OCP\Share::postUnshareFromSelf', $event);
963
-	}
964
-
965
-	/**
966
-	 * @inheritdoc
967
-	 */
968
-	public function moveShare(\OCP\Share\IShare $share, $recipientId) {
969
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
970
-			throw new \InvalidArgumentException('Can’t change target of link share');
971
-		}
972
-
973
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER && $share->getSharedWith() !== $recipientId) {
974
-			throw new \InvalidArgumentException('Invalid recipient');
975
-		}
976
-
977
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
978
-			$sharedWith = $this->groupManager->get($share->getSharedWith());
979
-			if (is_null($sharedWith)) {
980
-				throw new \InvalidArgumentException('Group "' . $share->getSharedWith() . '" does not exist');
981
-			}
982
-			$recipient = $this->userManager->get($recipientId);
983
-			if (!$sharedWith->inGroup($recipient)) {
984
-				throw new \InvalidArgumentException('Invalid recipient');
985
-			}
986
-		}
987
-
988
-		list($providerId, ) = $this->splitFullId($share->getFullId());
989
-		$provider = $this->factory->getProvider($providerId);
990
-
991
-		$provider->move($share, $recipientId);
992
-	}
993
-
994
-	public function getSharesInFolder($userId, Folder $node, $reshares = false) {
995
-		$providers = $this->factory->getAllProviders();
996
-
997
-		return array_reduce($providers, function($shares, IShareProvider $provider) use ($userId, $node, $reshares) {
998
-			$newShares = $provider->getSharesInFolder($userId, $node, $reshares);
999
-			foreach ($newShares as $fid => $data) {
1000
-				if (!isset($shares[$fid])) {
1001
-					$shares[$fid] = [];
1002
-				}
1003
-
1004
-				$shares[$fid] = array_merge($shares[$fid], $data);
1005
-			}
1006
-			return $shares;
1007
-		}, []);
1008
-	}
1009
-
1010
-	/**
1011
-	 * @inheritdoc
1012
-	 */
1013
-	public function getSharesBy($userId, $shareType, $path = null, $reshares = false, $limit = 50, $offset = 0) {
1014
-		if ($path !== null &&
1015
-				!($path instanceof \OCP\Files\File) &&
1016
-				!($path instanceof \OCP\Files\Folder)) {
1017
-			throw new \InvalidArgumentException('invalid path');
1018
-		}
1019
-
1020
-		try {
1021
-			$provider = $this->factory->getProviderForType($shareType);
1022
-		} catch (ProviderException $e) {
1023
-			return [];
1024
-		}
1025
-
1026
-		$shares = $provider->getSharesBy($userId, $shareType, $path, $reshares, $limit, $offset);
1027
-
1028
-		/*
607
+            $share->setToken(
608
+                $this->secureRandom->generate(
609
+                    \OC\Share\Constants::TOKEN_LENGTH,
610
+                    \OCP\Security\ISecureRandom::CHAR_HUMAN_READABLE
611
+                )
612
+            );
613
+
614
+            //Verify the expiration date
615
+            $this->validateExpirationDate($share);
616
+
617
+            //Verify the password
618
+            $this->verifyPassword($share->getPassword());
619
+
620
+            // If a password is set. Hash it!
621
+            if ($share->getPassword() !== null) {
622
+                $share->setPassword($this->hasher->hash($share->getPassword()));
623
+            }
624
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_EMAIL) {
625
+            $share->setToken(
626
+                $this->secureRandom->generate(
627
+                    \OC\Share\Constants::TOKEN_LENGTH,
628
+                    \OCP\Security\ISecureRandom::CHAR_HUMAN_READABLE
629
+                )
630
+            );
631
+        }
632
+
633
+        // Cannot share with the owner
634
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER &&
635
+            $share->getSharedWith() === $share->getShareOwner()) {
636
+            throw new \InvalidArgumentException('Can’t share with the share owner');
637
+        }
638
+
639
+        // Generate the target
640
+        $target = $this->config->getSystemValue('share_folder', '/') .'/'. $share->getNode()->getName();
641
+        $target = \OC\Files\Filesystem::normalizePath($target);
642
+        $share->setTarget($target);
643
+
644
+        // Pre share event
645
+        $event = new GenericEvent($share);
646
+        $a = $this->eventDispatcher->dispatch('OCP\Share::preShare', $event);
647
+        if ($event->isPropagationStopped() && $event->hasArgument('error')) {
648
+            throw new \Exception($event->getArgument('error'));
649
+        }
650
+
651
+        $oldShare = $share;
652
+        $provider = $this->factory->getProviderForType($share->getShareType());
653
+        $share = $provider->create($share);
654
+        //reuse the node we already have
655
+        $share->setNode($oldShare->getNode());
656
+
657
+        // Post share event
658
+        $event = new GenericEvent($share);
659
+        $this->eventDispatcher->dispatch('OCP\Share::postShare', $event);
660
+
661
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
662
+            $user = $this->userManager->get($share->getSharedWith());
663
+            if ($user !== null) {
664
+                $emailAddress = $user->getEMailAddress();
665
+                if ($emailAddress !== null && $emailAddress !== '') {
666
+                    $userLang = $this->config->getUserValue($share->getSharedWith(), 'core', 'lang', null);
667
+                    $l = $this->l10nFactory->get('lib', $userLang);
668
+                    $this->sendMailNotification(
669
+                        $l,
670
+                        $share->getNode()->getName(),
671
+                        $this->urlGenerator->linkToRouteAbsolute('files.viewcontroller.showFile', [ 'fileid' => $share->getNode()->getId() ]),
672
+                        $share->getSharedBy(),
673
+                        $emailAddress,
674
+                        $share->getExpirationDate()
675
+                    );
676
+                    $this->logger->debug('Send share notification to ' . $emailAddress . ' for share with ID ' . $share->getId(), ['app' => 'share']);
677
+                } else {
678
+                    $this->logger->debug('Share notification not send to ' . $share->getSharedWith() . ' because email address is not set.', ['app' => 'share']);
679
+                }
680
+            } else {
681
+                $this->logger->debug('Share notification not send to ' . $share->getSharedWith() . ' because user could not be found.', ['app' => 'share']);
682
+            }
683
+        }
684
+
685
+        return $share;
686
+    }
687
+
688
+    /**
689
+     * @param IL10N $l Language of the recipient
690
+     * @param string $filename file/folder name
691
+     * @param string $link link to the file/folder
692
+     * @param string $initiator user ID of share sender
693
+     * @param string $shareWith email address of share receiver
694
+     * @param \DateTime|null $expiration
695
+     * @throws \Exception If mail couldn't be sent
696
+     */
697
+    protected function sendMailNotification(IL10N $l,
698
+                                            $filename,
699
+                                            $link,
700
+                                            $initiator,
701
+                                            $shareWith,
702
+                                            \DateTime $expiration = null) {
703
+        $initiatorUser = $this->userManager->get($initiator);
704
+        $initiatorDisplayName = ($initiatorUser instanceof IUser) ? $initiatorUser->getDisplayName() : $initiator;
705
+
706
+        $message = $this->mailer->createMessage();
707
+
708
+        $emailTemplate = $this->mailer->createEMailTemplate('files_sharing.RecipientNotification', [
709
+            'filename' => $filename,
710
+            'link' => $link,
711
+            'initiator' => $initiatorDisplayName,
712
+            'expiration' => $expiration,
713
+            'shareWith' => $shareWith,
714
+        ]);
715
+
716
+        $emailTemplate->setSubject($l->t('%s shared »%s« with you', array($initiatorDisplayName, $filename)));
717
+        $emailTemplate->addHeader();
718
+        $emailTemplate->addHeading($l->t('%s shared »%s« with you', [$initiatorDisplayName, $filename]), false);
719
+        $text = $l->t('%s shared »%s« with you.', [$initiatorDisplayName, $filename]);
720
+
721
+        $emailTemplate->addBodyText(
722
+            $text . ' ' . $l->t('Click the button below to open it.'),
723
+            $text
724
+        );
725
+        $emailTemplate->addBodyButton(
726
+            $l->t('Open »%s«', [$filename]),
727
+            $link
728
+        );
729
+
730
+        $message->setTo([$shareWith]);
731
+
732
+        // The "From" contains the sharers name
733
+        $instanceName = $this->defaults->getName();
734
+        $senderName = $l->t(
735
+            '%s via %s',
736
+            [
737
+                $initiatorDisplayName,
738
+                $instanceName
739
+            ]
740
+        );
741
+        $message->setFrom([\OCP\Util::getDefaultEmailAddress($instanceName) => $senderName]);
742
+
743
+        // The "Reply-To" is set to the sharer if an mail address is configured
744
+        // also the default footer contains a "Do not reply" which needs to be adjusted.
745
+        $initiatorEmail = $initiatorUser->getEMailAddress();
746
+        if($initiatorEmail !== null) {
747
+            $message->setReplyTo([$initiatorEmail => $initiatorDisplayName]);
748
+            $emailTemplate->addFooter($instanceName . ($this->defaults->getSlogan() !== '' ? ' - ' . $this->defaults->getSlogan() : ''));
749
+        } else {
750
+            $emailTemplate->addFooter();
751
+        }
752
+
753
+        $message->useTemplate($emailTemplate);
754
+        $this->mailer->send($message);
755
+    }
756
+
757
+    /**
758
+     * Update a share
759
+     *
760
+     * @param \OCP\Share\IShare $share
761
+     * @return \OCP\Share\IShare The share object
762
+     * @throws \InvalidArgumentException
763
+     */
764
+    public function updateShare(\OCP\Share\IShare $share) {
765
+        $expirationDateUpdated = false;
766
+
767
+        $this->canShare($share);
768
+
769
+        try {
770
+            $originalShare = $this->getShareById($share->getFullId());
771
+        } catch (\UnexpectedValueException $e) {
772
+            throw new \InvalidArgumentException('Share does not have a full id');
773
+        }
774
+
775
+        // We can't change the share type!
776
+        if ($share->getShareType() !== $originalShare->getShareType()) {
777
+            throw new \InvalidArgumentException('Can’t change share type');
778
+        }
779
+
780
+        // We can only change the recipient on user shares
781
+        if ($share->getSharedWith() !== $originalShare->getSharedWith() &&
782
+            $share->getShareType() !== \OCP\Share::SHARE_TYPE_USER) {
783
+            throw new \InvalidArgumentException('Can only update recipient on user shares');
784
+        }
785
+
786
+        // Cannot share with the owner
787
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER &&
788
+            $share->getSharedWith() === $share->getShareOwner()) {
789
+            throw new \InvalidArgumentException('Can’t share with the share owner');
790
+        }
791
+
792
+        $this->generalCreateChecks($share);
793
+
794
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
795
+            $this->userCreateChecks($share);
796
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
797
+            $this->groupCreateChecks($share);
798
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
799
+            $this->linkCreateChecks($share);
800
+
801
+            $this->updateSharePasswordIfNeeded($share, $originalShare);
802
+
803
+            if ($share->getExpirationDate() != $originalShare->getExpirationDate()) {
804
+                //Verify the expiration date
805
+                $this->validateExpirationDate($share);
806
+                $expirationDateUpdated = true;
807
+            }
808
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_EMAIL) {
809
+            $plainTextPassword = $share->getPassword();
810
+            if (!$this->updateSharePasswordIfNeeded($share, $originalShare)) {
811
+                $plainTextPassword = null;
812
+            }
813
+        }
814
+
815
+        $this->pathCreateChecks($share->getNode());
816
+
817
+        // Now update the share!
818
+        $provider = $this->factory->getProviderForType($share->getShareType());
819
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_EMAIL) {
820
+            $share = $provider->update($share, $plainTextPassword);
821
+        } else {
822
+            $share = $provider->update($share);
823
+        }
824
+
825
+        if ($expirationDateUpdated === true) {
826
+            \OC_Hook::emit('OCP\Share', 'post_set_expiration_date', [
827
+                'itemType' => $share->getNode() instanceof \OCP\Files\File ? 'file' : 'folder',
828
+                'itemSource' => $share->getNode()->getId(),
829
+                'date' => $share->getExpirationDate(),
830
+                'uidOwner' => $share->getSharedBy(),
831
+            ]);
832
+        }
833
+
834
+        if ($share->getPassword() !== $originalShare->getPassword()) {
835
+            \OC_Hook::emit('OCP\Share', 'post_update_password', [
836
+                'itemType' => $share->getNode() instanceof \OCP\Files\File ? 'file' : 'folder',
837
+                'itemSource' => $share->getNode()->getId(),
838
+                'uidOwner' => $share->getSharedBy(),
839
+                'token' => $share->getToken(),
840
+                'disabled' => is_null($share->getPassword()),
841
+            ]);
842
+        }
843
+
844
+        if ($share->getPermissions() !== $originalShare->getPermissions()) {
845
+            if ($this->userManager->userExists($share->getShareOwner())) {
846
+                $userFolder = $this->rootFolder->getUserFolder($share->getShareOwner());
847
+            } else {
848
+                $userFolder = $this->rootFolder->getUserFolder($share->getSharedBy());
849
+            }
850
+            \OC_Hook::emit('OCP\Share', 'post_update_permissions', array(
851
+                'itemType' => $share->getNode() instanceof \OCP\Files\File ? 'file' : 'folder',
852
+                'itemSource' => $share->getNode()->getId(),
853
+                'shareType' => $share->getShareType(),
854
+                'shareWith' => $share->getSharedWith(),
855
+                'uidOwner' => $share->getSharedBy(),
856
+                'permissions' => $share->getPermissions(),
857
+                'path' => $userFolder->getRelativePath($share->getNode()->getPath()),
858
+            ));
859
+        }
860
+
861
+        return $share;
862
+    }
863
+
864
+    /**
865
+     * Updates the password of the given share if it is not the same as the
866
+     * password of the original share.
867
+     *
868
+     * @param \OCP\Share\IShare $share the share to update its password.
869
+     * @param \OCP\Share\IShare $originalShare the original share to compare its
870
+     *        password with.
871
+     * @return boolean whether the password was updated or not.
872
+     */
873
+    private function updateSharePasswordIfNeeded(\OCP\Share\IShare $share, \OCP\Share\IShare $originalShare) {
874
+        // Password updated.
875
+        if ($share->getPassword() !== $originalShare->getPassword()) {
876
+            //Verify the password
877
+            $this->verifyPassword($share->getPassword());
878
+
879
+            // If a password is set. Hash it!
880
+            if ($share->getPassword() !== null) {
881
+                $share->setPassword($this->hasher->hash($share->getPassword()));
882
+
883
+                return true;
884
+            }
885
+        }
886
+
887
+        return false;
888
+    }
889
+
890
+    /**
891
+     * Delete all the children of this share
892
+     * FIXME: remove once https://github.com/owncloud/core/pull/21660 is in
893
+     *
894
+     * @param \OCP\Share\IShare $share
895
+     * @return \OCP\Share\IShare[] List of deleted shares
896
+     */
897
+    protected function deleteChildren(\OCP\Share\IShare $share) {
898
+        $deletedShares = [];
899
+
900
+        $provider = $this->factory->getProviderForType($share->getShareType());
901
+
902
+        foreach ($provider->getChildren($share) as $child) {
903
+            $deletedChildren = $this->deleteChildren($child);
904
+            $deletedShares = array_merge($deletedShares, $deletedChildren);
905
+
906
+            $provider->delete($child);
907
+            $deletedShares[] = $child;
908
+        }
909
+
910
+        return $deletedShares;
911
+    }
912
+
913
+    /**
914
+     * Delete a share
915
+     *
916
+     * @param \OCP\Share\IShare $share
917
+     * @throws ShareNotFound
918
+     * @throws \InvalidArgumentException
919
+     */
920
+    public function deleteShare(\OCP\Share\IShare $share) {
921
+
922
+        try {
923
+            $share->getFullId();
924
+        } catch (\UnexpectedValueException $e) {
925
+            throw new \InvalidArgumentException('Share does not have a full id');
926
+        }
927
+
928
+        $event = new GenericEvent($share);
929
+        $this->eventDispatcher->dispatch('OCP\Share::preUnshare', $event);
930
+
931
+        // Get all children and delete them as well
932
+        $deletedShares = $this->deleteChildren($share);
933
+
934
+        // Do the actual delete
935
+        $provider = $this->factory->getProviderForType($share->getShareType());
936
+        $provider->delete($share);
937
+
938
+        // All the deleted shares caused by this delete
939
+        $deletedShares[] = $share;
940
+
941
+        // Emit post hook
942
+        $event->setArgument('deletedShares', $deletedShares);
943
+        $this->eventDispatcher->dispatch('OCP\Share::postUnshare', $event);
944
+    }
945
+
946
+
947
+    /**
948
+     * Unshare a file as the recipient.
949
+     * This can be different from a regular delete for example when one of
950
+     * the users in a groups deletes that share. But the provider should
951
+     * handle this.
952
+     *
953
+     * @param \OCP\Share\IShare $share
954
+     * @param string $recipientId
955
+     */
956
+    public function deleteFromSelf(\OCP\Share\IShare $share, $recipientId) {
957
+        list($providerId, ) = $this->splitFullId($share->getFullId());
958
+        $provider = $this->factory->getProvider($providerId);
959
+
960
+        $provider->deleteFromSelf($share, $recipientId);
961
+        $event = new GenericEvent($share);
962
+        $this->eventDispatcher->dispatch('OCP\Share::postUnshareFromSelf', $event);
963
+    }
964
+
965
+    /**
966
+     * @inheritdoc
967
+     */
968
+    public function moveShare(\OCP\Share\IShare $share, $recipientId) {
969
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
970
+            throw new \InvalidArgumentException('Can’t change target of link share');
971
+        }
972
+
973
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER && $share->getSharedWith() !== $recipientId) {
974
+            throw new \InvalidArgumentException('Invalid recipient');
975
+        }
976
+
977
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
978
+            $sharedWith = $this->groupManager->get($share->getSharedWith());
979
+            if (is_null($sharedWith)) {
980
+                throw new \InvalidArgumentException('Group "' . $share->getSharedWith() . '" does not exist');
981
+            }
982
+            $recipient = $this->userManager->get($recipientId);
983
+            if (!$sharedWith->inGroup($recipient)) {
984
+                throw new \InvalidArgumentException('Invalid recipient');
985
+            }
986
+        }
987
+
988
+        list($providerId, ) = $this->splitFullId($share->getFullId());
989
+        $provider = $this->factory->getProvider($providerId);
990
+
991
+        $provider->move($share, $recipientId);
992
+    }
993
+
994
+    public function getSharesInFolder($userId, Folder $node, $reshares = false) {
995
+        $providers = $this->factory->getAllProviders();
996
+
997
+        return array_reduce($providers, function($shares, IShareProvider $provider) use ($userId, $node, $reshares) {
998
+            $newShares = $provider->getSharesInFolder($userId, $node, $reshares);
999
+            foreach ($newShares as $fid => $data) {
1000
+                if (!isset($shares[$fid])) {
1001
+                    $shares[$fid] = [];
1002
+                }
1003
+
1004
+                $shares[$fid] = array_merge($shares[$fid], $data);
1005
+            }
1006
+            return $shares;
1007
+        }, []);
1008
+    }
1009
+
1010
+    /**
1011
+     * @inheritdoc
1012
+     */
1013
+    public function getSharesBy($userId, $shareType, $path = null, $reshares = false, $limit = 50, $offset = 0) {
1014
+        if ($path !== null &&
1015
+                !($path instanceof \OCP\Files\File) &&
1016
+                !($path instanceof \OCP\Files\Folder)) {
1017
+            throw new \InvalidArgumentException('invalid path');
1018
+        }
1019
+
1020
+        try {
1021
+            $provider = $this->factory->getProviderForType($shareType);
1022
+        } catch (ProviderException $e) {
1023
+            return [];
1024
+        }
1025
+
1026
+        $shares = $provider->getSharesBy($userId, $shareType, $path, $reshares, $limit, $offset);
1027
+
1028
+        /*
1029 1029
 		 * Work around so we don't return expired shares but still follow
1030 1030
 		 * proper pagination.
1031 1031
 		 */
1032 1032
 
1033
-		$shares2 = [];
1034
-
1035
-		while(true) {
1036
-			$added = 0;
1037
-			foreach ($shares as $share) {
1038
-
1039
-				try {
1040
-					$this->checkExpireDate($share);
1041
-				} catch (ShareNotFound $e) {
1042
-					//Ignore since this basically means the share is deleted
1043
-					continue;
1044
-				}
1045
-
1046
-				$added++;
1047
-				$shares2[] = $share;
1048
-
1049
-				if (count($shares2) === $limit) {
1050
-					break;
1051
-				}
1052
-			}
1053
-
1054
-			// If we did not fetch more shares than the limit then there are no more shares
1055
-			if (count($shares) < $limit) {
1056
-				break;
1057
-			}
1058
-
1059
-			if (count($shares2) === $limit) {
1060
-				break;
1061
-			}
1062
-
1063
-			// If there was no limit on the select we are done
1064
-			if ($limit === -1) {
1065
-				break;
1066
-			}
1067
-
1068
-			$offset += $added;
1069
-
1070
-			// Fetch again $limit shares
1071
-			$shares = $provider->getSharesBy($userId, $shareType, $path, $reshares, $limit, $offset);
1072
-
1073
-			// No more shares means we are done
1074
-			if (empty($shares)) {
1075
-				break;
1076
-			}
1077
-		}
1078
-
1079
-		$shares = $shares2;
1080
-
1081
-		return $shares;
1082
-	}
1083
-
1084
-	/**
1085
-	 * @inheritdoc
1086
-	 */
1087
-	public function getSharedWith($userId, $shareType, $node = null, $limit = 50, $offset = 0) {
1088
-		try {
1089
-			$provider = $this->factory->getProviderForType($shareType);
1090
-		} catch (ProviderException $e) {
1091
-			return [];
1092
-		}
1093
-
1094
-		$shares = $provider->getSharedWith($userId, $shareType, $node, $limit, $offset);
1095
-
1096
-		// remove all shares which are already expired
1097
-		foreach ($shares as $key => $share) {
1098
-			try {
1099
-				$this->checkExpireDate($share);
1100
-			} catch (ShareNotFound $e) {
1101
-				unset($shares[$key]);
1102
-			}
1103
-		}
1104
-
1105
-		return $shares;
1106
-	}
1107
-
1108
-	/**
1109
-	 * @inheritdoc
1110
-	 */
1111
-	public function getShareById($id, $recipient = null) {
1112
-		if ($id === null) {
1113
-			throw new ShareNotFound();
1114
-		}
1115
-
1116
-		list($providerId, $id) = $this->splitFullId($id);
1117
-
1118
-		try {
1119
-			$provider = $this->factory->getProvider($providerId);
1120
-		} catch (ProviderException $e) {
1121
-			throw new ShareNotFound();
1122
-		}
1123
-
1124
-		$share = $provider->getShareById($id, $recipient);
1125
-
1126
-		$this->checkExpireDate($share);
1127
-
1128
-		return $share;
1129
-	}
1130
-
1131
-	/**
1132
-	 * Get all the shares for a given path
1133
-	 *
1134
-	 * @param \OCP\Files\Node $path
1135
-	 * @param int $page
1136
-	 * @param int $perPage
1137
-	 *
1138
-	 * @return Share[]
1139
-	 */
1140
-	public function getSharesByPath(\OCP\Files\Node $path, $page=0, $perPage=50) {
1141
-		return [];
1142
-	}
1143
-
1144
-	/**
1145
-	 * Get the share by token possible with password
1146
-	 *
1147
-	 * @param string $token
1148
-	 * @return Share
1149
-	 *
1150
-	 * @throws ShareNotFound
1151
-	 */
1152
-	public function getShareByToken($token) {
1153
-		$share = null;
1154
-		try {
1155
-			if($this->shareApiAllowLinks()) {
1156
-				$provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_LINK);
1157
-				$share = $provider->getShareByToken($token);
1158
-			}
1159
-		} catch (ProviderException $e) {
1160
-		} catch (ShareNotFound $e) {
1161
-		}
1162
-
1163
-
1164
-		// If it is not a link share try to fetch a federated share by token
1165
-		if ($share === null) {
1166
-			try {
1167
-				$provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_REMOTE);
1168
-				$share = $provider->getShareByToken($token);
1169
-			} catch (ProviderException $e) {
1170
-			} catch (ShareNotFound $e) {
1171
-			}
1172
-		}
1173
-
1174
-		// If it is not a link share try to fetch a mail share by token
1175
-		if ($share === null && $this->shareProviderExists(\OCP\Share::SHARE_TYPE_EMAIL)) {
1176
-			try {
1177
-				$provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_EMAIL);
1178
-				$share = $provider->getShareByToken($token);
1179
-			} catch (ProviderException $e) {
1180
-			} catch (ShareNotFound $e) {
1181
-			}
1182
-		}
1183
-
1184
-		if ($share === null && $this->shareProviderExists(\OCP\Share::SHARE_TYPE_CIRCLE)) {
1185
-			try {
1186
-				$provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_CIRCLE);
1187
-				$share = $provider->getShareByToken($token);
1188
-			} catch (ProviderException $e) {
1189
-			} catch (ShareNotFound $e) {
1190
-			}
1191
-		}
1192
-
1193
-		if ($share === null) {
1194
-			throw new ShareNotFound($this->l->t('The requested share does not exist anymore'));
1195
-		}
1196
-
1197
-		$this->checkExpireDate($share);
1198
-
1199
-		/*
1033
+        $shares2 = [];
1034
+
1035
+        while(true) {
1036
+            $added = 0;
1037
+            foreach ($shares as $share) {
1038
+
1039
+                try {
1040
+                    $this->checkExpireDate($share);
1041
+                } catch (ShareNotFound $e) {
1042
+                    //Ignore since this basically means the share is deleted
1043
+                    continue;
1044
+                }
1045
+
1046
+                $added++;
1047
+                $shares2[] = $share;
1048
+
1049
+                if (count($shares2) === $limit) {
1050
+                    break;
1051
+                }
1052
+            }
1053
+
1054
+            // If we did not fetch more shares than the limit then there are no more shares
1055
+            if (count($shares) < $limit) {
1056
+                break;
1057
+            }
1058
+
1059
+            if (count($shares2) === $limit) {
1060
+                break;
1061
+            }
1062
+
1063
+            // If there was no limit on the select we are done
1064
+            if ($limit === -1) {
1065
+                break;
1066
+            }
1067
+
1068
+            $offset += $added;
1069
+
1070
+            // Fetch again $limit shares
1071
+            $shares = $provider->getSharesBy($userId, $shareType, $path, $reshares, $limit, $offset);
1072
+
1073
+            // No more shares means we are done
1074
+            if (empty($shares)) {
1075
+                break;
1076
+            }
1077
+        }
1078
+
1079
+        $shares = $shares2;
1080
+
1081
+        return $shares;
1082
+    }
1083
+
1084
+    /**
1085
+     * @inheritdoc
1086
+     */
1087
+    public function getSharedWith($userId, $shareType, $node = null, $limit = 50, $offset = 0) {
1088
+        try {
1089
+            $provider = $this->factory->getProviderForType($shareType);
1090
+        } catch (ProviderException $e) {
1091
+            return [];
1092
+        }
1093
+
1094
+        $shares = $provider->getSharedWith($userId, $shareType, $node, $limit, $offset);
1095
+
1096
+        // remove all shares which are already expired
1097
+        foreach ($shares as $key => $share) {
1098
+            try {
1099
+                $this->checkExpireDate($share);
1100
+            } catch (ShareNotFound $e) {
1101
+                unset($shares[$key]);
1102
+            }
1103
+        }
1104
+
1105
+        return $shares;
1106
+    }
1107
+
1108
+    /**
1109
+     * @inheritdoc
1110
+     */
1111
+    public function getShareById($id, $recipient = null) {
1112
+        if ($id === null) {
1113
+            throw new ShareNotFound();
1114
+        }
1115
+
1116
+        list($providerId, $id) = $this->splitFullId($id);
1117
+
1118
+        try {
1119
+            $provider = $this->factory->getProvider($providerId);
1120
+        } catch (ProviderException $e) {
1121
+            throw new ShareNotFound();
1122
+        }
1123
+
1124
+        $share = $provider->getShareById($id, $recipient);
1125
+
1126
+        $this->checkExpireDate($share);
1127
+
1128
+        return $share;
1129
+    }
1130
+
1131
+    /**
1132
+     * Get all the shares for a given path
1133
+     *
1134
+     * @param \OCP\Files\Node $path
1135
+     * @param int $page
1136
+     * @param int $perPage
1137
+     *
1138
+     * @return Share[]
1139
+     */
1140
+    public function getSharesByPath(\OCP\Files\Node $path, $page=0, $perPage=50) {
1141
+        return [];
1142
+    }
1143
+
1144
+    /**
1145
+     * Get the share by token possible with password
1146
+     *
1147
+     * @param string $token
1148
+     * @return Share
1149
+     *
1150
+     * @throws ShareNotFound
1151
+     */
1152
+    public function getShareByToken($token) {
1153
+        $share = null;
1154
+        try {
1155
+            if($this->shareApiAllowLinks()) {
1156
+                $provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_LINK);
1157
+                $share = $provider->getShareByToken($token);
1158
+            }
1159
+        } catch (ProviderException $e) {
1160
+        } catch (ShareNotFound $e) {
1161
+        }
1162
+
1163
+
1164
+        // If it is not a link share try to fetch a federated share by token
1165
+        if ($share === null) {
1166
+            try {
1167
+                $provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_REMOTE);
1168
+                $share = $provider->getShareByToken($token);
1169
+            } catch (ProviderException $e) {
1170
+            } catch (ShareNotFound $e) {
1171
+            }
1172
+        }
1173
+
1174
+        // If it is not a link share try to fetch a mail share by token
1175
+        if ($share === null && $this->shareProviderExists(\OCP\Share::SHARE_TYPE_EMAIL)) {
1176
+            try {
1177
+                $provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_EMAIL);
1178
+                $share = $provider->getShareByToken($token);
1179
+            } catch (ProviderException $e) {
1180
+            } catch (ShareNotFound $e) {
1181
+            }
1182
+        }
1183
+
1184
+        if ($share === null && $this->shareProviderExists(\OCP\Share::SHARE_TYPE_CIRCLE)) {
1185
+            try {
1186
+                $provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_CIRCLE);
1187
+                $share = $provider->getShareByToken($token);
1188
+            } catch (ProviderException $e) {
1189
+            } catch (ShareNotFound $e) {
1190
+            }
1191
+        }
1192
+
1193
+        if ($share === null) {
1194
+            throw new ShareNotFound($this->l->t('The requested share does not exist anymore'));
1195
+        }
1196
+
1197
+        $this->checkExpireDate($share);
1198
+
1199
+        /*
1200 1200
 		 * Reduce the permissions for link shares if public upload is not enabled
1201 1201
 		 */
1202
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK &&
1203
-			!$this->shareApiLinkAllowPublicUpload()) {
1204
-			$share->setPermissions($share->getPermissions() & ~(\OCP\Constants::PERMISSION_CREATE | \OCP\Constants::PERMISSION_UPDATE));
1205
-		}
1206
-
1207
-		return $share;
1208
-	}
1209
-
1210
-	protected function checkExpireDate($share) {
1211
-		if ($share->getExpirationDate() !== null &&
1212
-			$share->getExpirationDate() <= new \DateTime()) {
1213
-			$this->deleteShare($share);
1214
-			throw new ShareNotFound($this->l->t('The requested share does not exist anymore'));
1215
-		}
1216
-
1217
-	}
1218
-
1219
-	/**
1220
-	 * Verify the password of a public share
1221
-	 *
1222
-	 * @param \OCP\Share\IShare $share
1223
-	 * @param string $password
1224
-	 * @return bool
1225
-	 */
1226
-	public function checkPassword(\OCP\Share\IShare $share, $password) {
1227
-		$passwordProtected = $share->getShareType() !== \OCP\Share::SHARE_TYPE_LINK
1228
-			|| $share->getShareType() !== \OCP\Share::SHARE_TYPE_EMAIL;
1229
-		if (!$passwordProtected) {
1230
-			//TODO maybe exception?
1231
-			return false;
1232
-		}
1233
-
1234
-		if ($password === null || $share->getPassword() === null) {
1235
-			return false;
1236
-		}
1237
-
1238
-		$newHash = '';
1239
-		if (!$this->hasher->verify($password, $share->getPassword(), $newHash)) {
1240
-			return false;
1241
-		}
1242
-
1243
-		if (!empty($newHash)) {
1244
-			$share->setPassword($newHash);
1245
-			$provider = $this->factory->getProviderForType($share->getShareType());
1246
-			$provider->update($share);
1247
-		}
1248
-
1249
-		return true;
1250
-	}
1251
-
1252
-	/**
1253
-	 * @inheritdoc
1254
-	 */
1255
-	public function userDeleted($uid) {
1256
-		$types = [\OCP\Share::SHARE_TYPE_USER, \OCP\Share::SHARE_TYPE_GROUP, \OCP\Share::SHARE_TYPE_LINK, \OCP\Share::SHARE_TYPE_REMOTE, \OCP\Share::SHARE_TYPE_EMAIL];
1257
-
1258
-		foreach ($types as $type) {
1259
-			try {
1260
-				$provider = $this->factory->getProviderForType($type);
1261
-			} catch (ProviderException $e) {
1262
-				continue;
1263
-			}
1264
-			$provider->userDeleted($uid, $type);
1265
-		}
1266
-	}
1267
-
1268
-	/**
1269
-	 * @inheritdoc
1270
-	 */
1271
-	public function groupDeleted($gid) {
1272
-		$provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_GROUP);
1273
-		$provider->groupDeleted($gid);
1274
-	}
1275
-
1276
-	/**
1277
-	 * @inheritdoc
1278
-	 */
1279
-	public function userDeletedFromGroup($uid, $gid) {
1280
-		$provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_GROUP);
1281
-		$provider->userDeletedFromGroup($uid, $gid);
1282
-	}
1283
-
1284
-	/**
1285
-	 * Get access list to a path. This means
1286
-	 * all the users that can access a given path.
1287
-	 *
1288
-	 * Consider:
1289
-	 * -root
1290
-	 * |-folder1 (23)
1291
-	 *  |-folder2 (32)
1292
-	 *   |-fileA (42)
1293
-	 *
1294
-	 * fileA is shared with user1 and user1@server1
1295
-	 * folder2 is shared with group2 (user4 is a member of group2)
1296
-	 * folder1 is shared with user2 (renamed to "folder (1)") and user2@server2
1297
-	 *
1298
-	 * Then the access list to '/folder1/folder2/fileA' with $currentAccess is:
1299
-	 * [
1300
-	 *  users  => [
1301
-	 *      'user1' => ['node_id' => 42, 'node_path' => '/fileA'],
1302
-	 *      'user4' => ['node_id' => 32, 'node_path' => '/folder2'],
1303
-	 *      'user2' => ['node_id' => 23, 'node_path' => '/folder (1)'],
1304
-	 *  ],
1305
-	 *  remote => [
1306
-	 *      'user1@server1' => ['node_id' => 42, 'token' => 'SeCr3t'],
1307
-	 *      'user2@server2' => ['node_id' => 23, 'token' => 'FooBaR'],
1308
-	 *  ],
1309
-	 *  public => bool
1310
-	 *  mail => bool
1311
-	 * ]
1312
-	 *
1313
-	 * The access list to '/folder1/folder2/fileA' **without** $currentAccess is:
1314
-	 * [
1315
-	 *  users  => ['user1', 'user2', 'user4'],
1316
-	 *  remote => bool,
1317
-	 *  public => bool
1318
-	 *  mail => bool
1319
-	 * ]
1320
-	 *
1321
-	 * This is required for encryption/activity
1322
-	 *
1323
-	 * @param \OCP\Files\Node $path
1324
-	 * @param bool $recursive Should we check all parent folders as well
1325
-	 * @param bool $currentAccess Ensure the recipient has access to the file (e.g. did not unshare it)
1326
-	 * @return array
1327
-	 */
1328
-	public function getAccessList(\OCP\Files\Node $path, $recursive = true, $currentAccess = false) {
1329
-		$owner = $path->getOwner()->getUID();
1330
-
1331
-		if ($currentAccess) {
1332
-			$al = ['users' => [], 'remote' => [], 'public' => false];
1333
-		} else {
1334
-			$al = ['users' => [], 'remote' => false, 'public' => false];
1335
-		}
1336
-		if (!$this->userManager->userExists($owner)) {
1337
-			return $al;
1338
-		}
1339
-
1340
-		//Get node for the owner
1341
-		$userFolder = $this->rootFolder->getUserFolder($owner);
1342
-		if ($path->getId() !== $userFolder->getId() && !$userFolder->isSubNode($path)) {
1343
-			$path = $userFolder->getById($path->getId())[0];
1344
-		}
1345
-
1346
-		$providers = $this->factory->getAllProviders();
1347
-
1348
-		/** @var Node[] $nodes */
1349
-		$nodes = [];
1350
-
1351
-
1352
-		if ($currentAccess) {
1353
-			$ownerPath = $path->getPath();
1354
-			$ownerPath = explode('/', $ownerPath, 4);
1355
-			if (count($ownerPath) < 4) {
1356
-				$ownerPath = '';
1357
-			} else {
1358
-				$ownerPath = $ownerPath[3];
1359
-			}
1360
-			$al['users'][$owner] = [
1361
-				'node_id' => $path->getId(),
1362
-				'node_path' => '/' . $ownerPath,
1363
-			];
1364
-		} else {
1365
-			$al['users'][] = $owner;
1366
-		}
1367
-
1368
-		// Collect all the shares
1369
-		while ($path->getPath() !== $userFolder->getPath()) {
1370
-			$nodes[] = $path;
1371
-			if (!$recursive) {
1372
-				break;
1373
-			}
1374
-			$path = $path->getParent();
1375
-		}
1376
-
1377
-		foreach ($providers as $provider) {
1378
-			$tmp = $provider->getAccessList($nodes, $currentAccess);
1379
-
1380
-			foreach ($tmp as $k => $v) {
1381
-				if (isset($al[$k])) {
1382
-					if (is_array($al[$k])) {
1383
-						$al[$k] = array_merge($al[$k], $v);
1384
-					} else {
1385
-						$al[$k] = $al[$k] || $v;
1386
-					}
1387
-				} else {
1388
-					$al[$k] = $v;
1389
-				}
1390
-			}
1391
-		}
1392
-
1393
-		return $al;
1394
-	}
1395
-
1396
-	/**
1397
-	 * Create a new share
1398
-	 * @return \OCP\Share\IShare
1399
-	 */
1400
-	public function newShare() {
1401
-		return new \OC\Share20\Share($this->rootFolder, $this->userManager);
1402
-	}
1403
-
1404
-	/**
1405
-	 * Is the share API enabled
1406
-	 *
1407
-	 * @return bool
1408
-	 */
1409
-	public function shareApiEnabled() {
1410
-		return $this->config->getAppValue('core', 'shareapi_enabled', 'yes') === 'yes';
1411
-	}
1412
-
1413
-	/**
1414
-	 * Is public link sharing enabled
1415
-	 *
1416
-	 * @return bool
1417
-	 */
1418
-	public function shareApiAllowLinks() {
1419
-		return $this->config->getAppValue('core', 'shareapi_allow_links', 'yes') === 'yes';
1420
-	}
1421
-
1422
-	/**
1423
-	 * Is password on public link requires
1424
-	 *
1425
-	 * @return bool
1426
-	 */
1427
-	public function shareApiLinkEnforcePassword() {
1428
-		return $this->config->getAppValue('core', 'shareapi_enforce_links_password', 'no') === 'yes';
1429
-	}
1430
-
1431
-	/**
1432
-	 * Is default expire date enabled
1433
-	 *
1434
-	 * @return bool
1435
-	 */
1436
-	public function shareApiLinkDefaultExpireDate() {
1437
-		return $this->config->getAppValue('core', 'shareapi_default_expire_date', 'no') === 'yes';
1438
-	}
1439
-
1440
-	/**
1441
-	 * Is default expire date enforced
1442
-	 *`
1443
-	 * @return bool
1444
-	 */
1445
-	public function shareApiLinkDefaultExpireDateEnforced() {
1446
-		return $this->shareApiLinkDefaultExpireDate() &&
1447
-			$this->config->getAppValue('core', 'shareapi_enforce_expire_date', 'no') === 'yes';
1448
-	}
1449
-
1450
-	/**
1451
-	 * Number of default expire days
1452
-	 *shareApiLinkAllowPublicUpload
1453
-	 * @return int
1454
-	 */
1455
-	public function shareApiLinkDefaultExpireDays() {
1456
-		return (int)$this->config->getAppValue('core', 'shareapi_expire_after_n_days', '7');
1457
-	}
1458
-
1459
-	/**
1460
-	 * Allow public upload on link shares
1461
-	 *
1462
-	 * @return bool
1463
-	 */
1464
-	public function shareApiLinkAllowPublicUpload() {
1465
-		return $this->config->getAppValue('core', 'shareapi_allow_public_upload', 'yes') === 'yes';
1466
-	}
1467
-
1468
-	/**
1469
-	 * check if user can only share with group members
1470
-	 * @return bool
1471
-	 */
1472
-	public function shareWithGroupMembersOnly() {
1473
-		return $this->config->getAppValue('core', 'shareapi_only_share_with_group_members', 'no') === 'yes';
1474
-	}
1475
-
1476
-	/**
1477
-	 * Check if users can share with groups
1478
-	 * @return bool
1479
-	 */
1480
-	public function allowGroupSharing() {
1481
-		return $this->config->getAppValue('core', 'shareapi_allow_group_sharing', 'yes') === 'yes';
1482
-	}
1483
-
1484
-	/**
1485
-	 * Copied from \OC_Util::isSharingDisabledForUser
1486
-	 *
1487
-	 * TODO: Deprecate fuction from OC_Util
1488
-	 *
1489
-	 * @param string $userId
1490
-	 * @return bool
1491
-	 */
1492
-	public function sharingDisabledForUser($userId) {
1493
-		if ($userId === null) {
1494
-			return false;
1495
-		}
1496
-
1497
-		if (isset($this->sharingDisabledForUsersCache[$userId])) {
1498
-			return $this->sharingDisabledForUsersCache[$userId];
1499
-		}
1500
-
1501
-		if ($this->config->getAppValue('core', 'shareapi_exclude_groups', 'no') === 'yes') {
1502
-			$groupsList = $this->config->getAppValue('core', 'shareapi_exclude_groups_list', '');
1503
-			$excludedGroups = json_decode($groupsList);
1504
-			if (is_null($excludedGroups)) {
1505
-				$excludedGroups = explode(',', $groupsList);
1506
-				$newValue = json_encode($excludedGroups);
1507
-				$this->config->setAppValue('core', 'shareapi_exclude_groups_list', $newValue);
1508
-			}
1509
-			$user = $this->userManager->get($userId);
1510
-			$usersGroups = $this->groupManager->getUserGroupIds($user);
1511
-			if (!empty($usersGroups)) {
1512
-				$remainingGroups = array_diff($usersGroups, $excludedGroups);
1513
-				// if the user is only in groups which are disabled for sharing then
1514
-				// sharing is also disabled for the user
1515
-				if (empty($remainingGroups)) {
1516
-					$this->sharingDisabledForUsersCache[$userId] = true;
1517
-					return true;
1518
-				}
1519
-			}
1520
-		}
1521
-
1522
-		$this->sharingDisabledForUsersCache[$userId] = false;
1523
-		return false;
1524
-	}
1525
-
1526
-	/**
1527
-	 * @inheritdoc
1528
-	 */
1529
-	public function outgoingServer2ServerSharesAllowed() {
1530
-		return $this->config->getAppValue('files_sharing', 'outgoing_server2server_share_enabled', 'yes') === 'yes';
1531
-	}
1532
-
1533
-	/**
1534
-	 * @inheritdoc
1535
-	 */
1536
-	public function shareProviderExists($shareType) {
1537
-		try {
1538
-			$this->factory->getProviderForType($shareType);
1539
-		} catch (ProviderException $e) {
1540
-			return false;
1541
-		}
1542
-
1543
-		return true;
1544
-	}
1202
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK &&
1203
+            !$this->shareApiLinkAllowPublicUpload()) {
1204
+            $share->setPermissions($share->getPermissions() & ~(\OCP\Constants::PERMISSION_CREATE | \OCP\Constants::PERMISSION_UPDATE));
1205
+        }
1206
+
1207
+        return $share;
1208
+    }
1209
+
1210
+    protected function checkExpireDate($share) {
1211
+        if ($share->getExpirationDate() !== null &&
1212
+            $share->getExpirationDate() <= new \DateTime()) {
1213
+            $this->deleteShare($share);
1214
+            throw new ShareNotFound($this->l->t('The requested share does not exist anymore'));
1215
+        }
1216
+
1217
+    }
1218
+
1219
+    /**
1220
+     * Verify the password of a public share
1221
+     *
1222
+     * @param \OCP\Share\IShare $share
1223
+     * @param string $password
1224
+     * @return bool
1225
+     */
1226
+    public function checkPassword(\OCP\Share\IShare $share, $password) {
1227
+        $passwordProtected = $share->getShareType() !== \OCP\Share::SHARE_TYPE_LINK
1228
+            || $share->getShareType() !== \OCP\Share::SHARE_TYPE_EMAIL;
1229
+        if (!$passwordProtected) {
1230
+            //TODO maybe exception?
1231
+            return false;
1232
+        }
1233
+
1234
+        if ($password === null || $share->getPassword() === null) {
1235
+            return false;
1236
+        }
1237
+
1238
+        $newHash = '';
1239
+        if (!$this->hasher->verify($password, $share->getPassword(), $newHash)) {
1240
+            return false;
1241
+        }
1242
+
1243
+        if (!empty($newHash)) {
1244
+            $share->setPassword($newHash);
1245
+            $provider = $this->factory->getProviderForType($share->getShareType());
1246
+            $provider->update($share);
1247
+        }
1248
+
1249
+        return true;
1250
+    }
1251
+
1252
+    /**
1253
+     * @inheritdoc
1254
+     */
1255
+    public function userDeleted($uid) {
1256
+        $types = [\OCP\Share::SHARE_TYPE_USER, \OCP\Share::SHARE_TYPE_GROUP, \OCP\Share::SHARE_TYPE_LINK, \OCP\Share::SHARE_TYPE_REMOTE, \OCP\Share::SHARE_TYPE_EMAIL];
1257
+
1258
+        foreach ($types as $type) {
1259
+            try {
1260
+                $provider = $this->factory->getProviderForType($type);
1261
+            } catch (ProviderException $e) {
1262
+                continue;
1263
+            }
1264
+            $provider->userDeleted($uid, $type);
1265
+        }
1266
+    }
1267
+
1268
+    /**
1269
+     * @inheritdoc
1270
+     */
1271
+    public function groupDeleted($gid) {
1272
+        $provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_GROUP);
1273
+        $provider->groupDeleted($gid);
1274
+    }
1275
+
1276
+    /**
1277
+     * @inheritdoc
1278
+     */
1279
+    public function userDeletedFromGroup($uid, $gid) {
1280
+        $provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_GROUP);
1281
+        $provider->userDeletedFromGroup($uid, $gid);
1282
+    }
1283
+
1284
+    /**
1285
+     * Get access list to a path. This means
1286
+     * all the users that can access a given path.
1287
+     *
1288
+     * Consider:
1289
+     * -root
1290
+     * |-folder1 (23)
1291
+     *  |-folder2 (32)
1292
+     *   |-fileA (42)
1293
+     *
1294
+     * fileA is shared with user1 and user1@server1
1295
+     * folder2 is shared with group2 (user4 is a member of group2)
1296
+     * folder1 is shared with user2 (renamed to "folder (1)") and user2@server2
1297
+     *
1298
+     * Then the access list to '/folder1/folder2/fileA' with $currentAccess is:
1299
+     * [
1300
+     *  users  => [
1301
+     *      'user1' => ['node_id' => 42, 'node_path' => '/fileA'],
1302
+     *      'user4' => ['node_id' => 32, 'node_path' => '/folder2'],
1303
+     *      'user2' => ['node_id' => 23, 'node_path' => '/folder (1)'],
1304
+     *  ],
1305
+     *  remote => [
1306
+     *      'user1@server1' => ['node_id' => 42, 'token' => 'SeCr3t'],
1307
+     *      'user2@server2' => ['node_id' => 23, 'token' => 'FooBaR'],
1308
+     *  ],
1309
+     *  public => bool
1310
+     *  mail => bool
1311
+     * ]
1312
+     *
1313
+     * The access list to '/folder1/folder2/fileA' **without** $currentAccess is:
1314
+     * [
1315
+     *  users  => ['user1', 'user2', 'user4'],
1316
+     *  remote => bool,
1317
+     *  public => bool
1318
+     *  mail => bool
1319
+     * ]
1320
+     *
1321
+     * This is required for encryption/activity
1322
+     *
1323
+     * @param \OCP\Files\Node $path
1324
+     * @param bool $recursive Should we check all parent folders as well
1325
+     * @param bool $currentAccess Ensure the recipient has access to the file (e.g. did not unshare it)
1326
+     * @return array
1327
+     */
1328
+    public function getAccessList(\OCP\Files\Node $path, $recursive = true, $currentAccess = false) {
1329
+        $owner = $path->getOwner()->getUID();
1330
+
1331
+        if ($currentAccess) {
1332
+            $al = ['users' => [], 'remote' => [], 'public' => false];
1333
+        } else {
1334
+            $al = ['users' => [], 'remote' => false, 'public' => false];
1335
+        }
1336
+        if (!$this->userManager->userExists($owner)) {
1337
+            return $al;
1338
+        }
1339
+
1340
+        //Get node for the owner
1341
+        $userFolder = $this->rootFolder->getUserFolder($owner);
1342
+        if ($path->getId() !== $userFolder->getId() && !$userFolder->isSubNode($path)) {
1343
+            $path = $userFolder->getById($path->getId())[0];
1344
+        }
1345
+
1346
+        $providers = $this->factory->getAllProviders();
1347
+
1348
+        /** @var Node[] $nodes */
1349
+        $nodes = [];
1350
+
1351
+
1352
+        if ($currentAccess) {
1353
+            $ownerPath = $path->getPath();
1354
+            $ownerPath = explode('/', $ownerPath, 4);
1355
+            if (count($ownerPath) < 4) {
1356
+                $ownerPath = '';
1357
+            } else {
1358
+                $ownerPath = $ownerPath[3];
1359
+            }
1360
+            $al['users'][$owner] = [
1361
+                'node_id' => $path->getId(),
1362
+                'node_path' => '/' . $ownerPath,
1363
+            ];
1364
+        } else {
1365
+            $al['users'][] = $owner;
1366
+        }
1367
+
1368
+        // Collect all the shares
1369
+        while ($path->getPath() !== $userFolder->getPath()) {
1370
+            $nodes[] = $path;
1371
+            if (!$recursive) {
1372
+                break;
1373
+            }
1374
+            $path = $path->getParent();
1375
+        }
1376
+
1377
+        foreach ($providers as $provider) {
1378
+            $tmp = $provider->getAccessList($nodes, $currentAccess);
1379
+
1380
+            foreach ($tmp as $k => $v) {
1381
+                if (isset($al[$k])) {
1382
+                    if (is_array($al[$k])) {
1383
+                        $al[$k] = array_merge($al[$k], $v);
1384
+                    } else {
1385
+                        $al[$k] = $al[$k] || $v;
1386
+                    }
1387
+                } else {
1388
+                    $al[$k] = $v;
1389
+                }
1390
+            }
1391
+        }
1392
+
1393
+        return $al;
1394
+    }
1395
+
1396
+    /**
1397
+     * Create a new share
1398
+     * @return \OCP\Share\IShare
1399
+     */
1400
+    public function newShare() {
1401
+        return new \OC\Share20\Share($this->rootFolder, $this->userManager);
1402
+    }
1403
+
1404
+    /**
1405
+     * Is the share API enabled
1406
+     *
1407
+     * @return bool
1408
+     */
1409
+    public function shareApiEnabled() {
1410
+        return $this->config->getAppValue('core', 'shareapi_enabled', 'yes') === 'yes';
1411
+    }
1412
+
1413
+    /**
1414
+     * Is public link sharing enabled
1415
+     *
1416
+     * @return bool
1417
+     */
1418
+    public function shareApiAllowLinks() {
1419
+        return $this->config->getAppValue('core', 'shareapi_allow_links', 'yes') === 'yes';
1420
+    }
1421
+
1422
+    /**
1423
+     * Is password on public link requires
1424
+     *
1425
+     * @return bool
1426
+     */
1427
+    public function shareApiLinkEnforcePassword() {
1428
+        return $this->config->getAppValue('core', 'shareapi_enforce_links_password', 'no') === 'yes';
1429
+    }
1430
+
1431
+    /**
1432
+     * Is default expire date enabled
1433
+     *
1434
+     * @return bool
1435
+     */
1436
+    public function shareApiLinkDefaultExpireDate() {
1437
+        return $this->config->getAppValue('core', 'shareapi_default_expire_date', 'no') === 'yes';
1438
+    }
1439
+
1440
+    /**
1441
+     * Is default expire date enforced
1442
+     *`
1443
+     * @return bool
1444
+     */
1445
+    public function shareApiLinkDefaultExpireDateEnforced() {
1446
+        return $this->shareApiLinkDefaultExpireDate() &&
1447
+            $this->config->getAppValue('core', 'shareapi_enforce_expire_date', 'no') === 'yes';
1448
+    }
1449
+
1450
+    /**
1451
+     * Number of default expire days
1452
+     *shareApiLinkAllowPublicUpload
1453
+     * @return int
1454
+     */
1455
+    public function shareApiLinkDefaultExpireDays() {
1456
+        return (int)$this->config->getAppValue('core', 'shareapi_expire_after_n_days', '7');
1457
+    }
1458
+
1459
+    /**
1460
+     * Allow public upload on link shares
1461
+     *
1462
+     * @return bool
1463
+     */
1464
+    public function shareApiLinkAllowPublicUpload() {
1465
+        return $this->config->getAppValue('core', 'shareapi_allow_public_upload', 'yes') === 'yes';
1466
+    }
1467
+
1468
+    /**
1469
+     * check if user can only share with group members
1470
+     * @return bool
1471
+     */
1472
+    public function shareWithGroupMembersOnly() {
1473
+        return $this->config->getAppValue('core', 'shareapi_only_share_with_group_members', 'no') === 'yes';
1474
+    }
1475
+
1476
+    /**
1477
+     * Check if users can share with groups
1478
+     * @return bool
1479
+     */
1480
+    public function allowGroupSharing() {
1481
+        return $this->config->getAppValue('core', 'shareapi_allow_group_sharing', 'yes') === 'yes';
1482
+    }
1483
+
1484
+    /**
1485
+     * Copied from \OC_Util::isSharingDisabledForUser
1486
+     *
1487
+     * TODO: Deprecate fuction from OC_Util
1488
+     *
1489
+     * @param string $userId
1490
+     * @return bool
1491
+     */
1492
+    public function sharingDisabledForUser($userId) {
1493
+        if ($userId === null) {
1494
+            return false;
1495
+        }
1496
+
1497
+        if (isset($this->sharingDisabledForUsersCache[$userId])) {
1498
+            return $this->sharingDisabledForUsersCache[$userId];
1499
+        }
1500
+
1501
+        if ($this->config->getAppValue('core', 'shareapi_exclude_groups', 'no') === 'yes') {
1502
+            $groupsList = $this->config->getAppValue('core', 'shareapi_exclude_groups_list', '');
1503
+            $excludedGroups = json_decode($groupsList);
1504
+            if (is_null($excludedGroups)) {
1505
+                $excludedGroups = explode(',', $groupsList);
1506
+                $newValue = json_encode($excludedGroups);
1507
+                $this->config->setAppValue('core', 'shareapi_exclude_groups_list', $newValue);
1508
+            }
1509
+            $user = $this->userManager->get($userId);
1510
+            $usersGroups = $this->groupManager->getUserGroupIds($user);
1511
+            if (!empty($usersGroups)) {
1512
+                $remainingGroups = array_diff($usersGroups, $excludedGroups);
1513
+                // if the user is only in groups which are disabled for sharing then
1514
+                // sharing is also disabled for the user
1515
+                if (empty($remainingGroups)) {
1516
+                    $this->sharingDisabledForUsersCache[$userId] = true;
1517
+                    return true;
1518
+                }
1519
+            }
1520
+        }
1521
+
1522
+        $this->sharingDisabledForUsersCache[$userId] = false;
1523
+        return false;
1524
+    }
1525
+
1526
+    /**
1527
+     * @inheritdoc
1528
+     */
1529
+    public function outgoingServer2ServerSharesAllowed() {
1530
+        return $this->config->getAppValue('files_sharing', 'outgoing_server2server_share_enabled', 'yes') === 'yes';
1531
+    }
1532
+
1533
+    /**
1534
+     * @inheritdoc
1535
+     */
1536
+    public function shareProviderExists($shareType) {
1537
+        try {
1538
+            $this->factory->getProviderForType($shareType);
1539
+        } catch (ProviderException $e) {
1540
+            return false;
1541
+        }
1542
+
1543
+        return true;
1544
+    }
1545 1545
 
1546 1546
 }
Please login to merge, or discard this patch.
lib/private/legacy/app.php 1 patch
Indentation   +1192 added lines, -1192 removed lines patch added patch discarded remove patch
@@ -61,1196 +61,1196 @@
 block discarded – undo
61 61
  * upgrading and removing apps.
62 62
  */
63 63
 class OC_App {
64
-	static private $appVersion = [];
65
-	static private $adminForms = array();
66
-	static private $personalForms = array();
67
-	static private $appInfo = array();
68
-	static private $appTypes = array();
69
-	static private $loadedApps = array();
70
-	static private $altLogin = array();
71
-	static private $alreadyRegistered = [];
72
-	const officialApp = 200;
73
-
74
-	/**
75
-	 * clean the appId
76
-	 *
77
-	 * @param string|boolean $app AppId that needs to be cleaned
78
-	 * @return string
79
-	 */
80
-	public static function cleanAppId($app) {
81
-		return str_replace(array('\0', '/', '\\', '..'), '', $app);
82
-	}
83
-
84
-	/**
85
-	 * Check if an app is loaded
86
-	 *
87
-	 * @param string $app
88
-	 * @return bool
89
-	 */
90
-	public static function isAppLoaded($app) {
91
-		return in_array($app, self::$loadedApps, true);
92
-	}
93
-
94
-	/**
95
-	 * loads all apps
96
-	 *
97
-	 * @param string[] | string | null $types
98
-	 * @return bool
99
-	 *
100
-	 * This function walks through the ownCloud directory and loads all apps
101
-	 * it can find. A directory contains an app if the file /appinfo/info.xml
102
-	 * exists.
103
-	 *
104
-	 * if $types is set, only apps of those types will be loaded
105
-	 */
106
-	public static function loadApps($types = null) {
107
-		if (\OC::$server->getSystemConfig()->getValue('maintenance', false)) {
108
-			return false;
109
-		}
110
-		// Load the enabled apps here
111
-		$apps = self::getEnabledApps();
112
-
113
-		// Add each apps' folder as allowed class path
114
-		foreach($apps as $app) {
115
-			$path = self::getAppPath($app);
116
-			if($path !== false) {
117
-				self::registerAutoloading($app, $path);
118
-			}
119
-		}
120
-
121
-		// prevent app.php from printing output
122
-		ob_start();
123
-		foreach ($apps as $app) {
124
-			if ((is_null($types) or self::isType($app, $types)) && !in_array($app, self::$loadedApps)) {
125
-				self::loadApp($app);
126
-			}
127
-		}
128
-		ob_end_clean();
129
-
130
-		return true;
131
-	}
132
-
133
-	/**
134
-	 * load a single app
135
-	 *
136
-	 * @param string $app
137
-	 */
138
-	public static function loadApp($app) {
139
-		self::$loadedApps[] = $app;
140
-		$appPath = self::getAppPath($app);
141
-		if($appPath === false) {
142
-			return;
143
-		}
144
-
145
-		// in case someone calls loadApp() directly
146
-		self::registerAutoloading($app, $appPath);
147
-
148
-		if (is_file($appPath . '/appinfo/app.php')) {
149
-			\OC::$server->getEventLogger()->start('load_app_' . $app, 'Load app: ' . $app);
150
-			self::requireAppFile($app);
151
-			if (self::isType($app, array('authentication'))) {
152
-				// since authentication apps affect the "is app enabled for group" check,
153
-				// the enabled apps cache needs to be cleared to make sure that the
154
-				// next time getEnableApps() is called it will also include apps that were
155
-				// enabled for groups
156
-				self::$enabledAppsCache = array();
157
-			}
158
-			\OC::$server->getEventLogger()->end('load_app_' . $app);
159
-		}
160
-
161
-		$info = self::getAppInfo($app);
162
-		if (!empty($info['activity']['filters'])) {
163
-			foreach ($info['activity']['filters'] as $filter) {
164
-				\OC::$server->getActivityManager()->registerFilter($filter);
165
-			}
166
-		}
167
-		if (!empty($info['activity']['settings'])) {
168
-			foreach ($info['activity']['settings'] as $setting) {
169
-				\OC::$server->getActivityManager()->registerSetting($setting);
170
-			}
171
-		}
172
-		if (!empty($info['activity']['providers'])) {
173
-			foreach ($info['activity']['providers'] as $provider) {
174
-				\OC::$server->getActivityManager()->registerProvider($provider);
175
-			}
176
-		}
177
-		if (!empty($info['collaboration']['plugins'])) {
178
-			// deal with one or many plugin entries
179
-			$plugins = isset($info['collaboration']['plugins']['plugin']['@value']) ?
180
-				[$info['collaboration']['plugins']['plugin']] : $info['collaboration']['plugins']['plugin'];
181
-			foreach ($plugins as $plugin) {
182
-				if($plugin['@attributes']['type'] === 'collaborator-search') {
183
-					$pluginInfo = [
184
-						'shareType' => $plugin['@attributes']['share-type'],
185
-						'class' => $plugin['@value'],
186
-					];
187
-					\OC::$server->getCollaboratorSearch()->registerPlugin($pluginInfo);
188
-				} else if ($plugin['@attributes']['type'] === 'autocomplete-sort') {
189
-					\OC::$server->getAutoCompleteManager()->registerSorter($plugin['@value']);
190
-				}
191
-			}
192
-		}
193
-	}
194
-
195
-	/**
196
-	 * @internal
197
-	 * @param string $app
198
-	 * @param string $path
199
-	 */
200
-	public static function registerAutoloading($app, $path) {
201
-		$key = $app . '-' . $path;
202
-		if(isset(self::$alreadyRegistered[$key])) {
203
-			return;
204
-		}
205
-
206
-		self::$alreadyRegistered[$key] = true;
207
-
208
-		// Register on PSR-4 composer autoloader
209
-		$appNamespace = \OC\AppFramework\App::buildAppNamespace($app);
210
-		\OC::$server->registerNamespace($app, $appNamespace);
211
-
212
-		if (file_exists($path . '/composer/autoload.php')) {
213
-			require_once $path . '/composer/autoload.php';
214
-		} else {
215
-			\OC::$composerAutoloader->addPsr4($appNamespace . '\\', $path . '/lib/', true);
216
-			// Register on legacy autoloader
217
-			\OC::$loader->addValidRoot($path);
218
-		}
219
-
220
-		// Register Test namespace only when testing
221
-		if (defined('PHPUNIT_RUN') || defined('CLI_TEST_RUN')) {
222
-			\OC::$composerAutoloader->addPsr4($appNamespace . '\\Tests\\', $path . '/tests/', true);
223
-		}
224
-	}
225
-
226
-	/**
227
-	 * Load app.php from the given app
228
-	 *
229
-	 * @param string $app app name
230
-	 */
231
-	private static function requireAppFile($app) {
232
-		try {
233
-			// encapsulated here to avoid variable scope conflicts
234
-			require_once $app . '/appinfo/app.php';
235
-		} catch (Error $ex) {
236
-			\OC::$server->getLogger()->logException($ex);
237
-			$blacklist = \OC::$server->getAppManager()->getAlwaysEnabledApps();
238
-			if (!in_array($app, $blacklist)) {
239
-				self::disable($app);
240
-			}
241
-		}
242
-	}
243
-
244
-	/**
245
-	 * check if an app is of a specific type
246
-	 *
247
-	 * @param string $app
248
-	 * @param string|array $types
249
-	 * @return bool
250
-	 */
251
-	public static function isType($app, $types) {
252
-		if (is_string($types)) {
253
-			$types = array($types);
254
-		}
255
-		$appTypes = self::getAppTypes($app);
256
-		foreach ($types as $type) {
257
-			if (array_search($type, $appTypes) !== false) {
258
-				return true;
259
-			}
260
-		}
261
-		return false;
262
-	}
263
-
264
-	/**
265
-	 * get the types of an app
266
-	 *
267
-	 * @param string $app
268
-	 * @return array
269
-	 */
270
-	private static function getAppTypes($app) {
271
-		//load the cache
272
-		if (count(self::$appTypes) == 0) {
273
-			self::$appTypes = \OC::$server->getAppConfig()->getValues(false, 'types');
274
-		}
275
-
276
-		if (isset(self::$appTypes[$app])) {
277
-			return explode(',', self::$appTypes[$app]);
278
-		} else {
279
-			return array();
280
-		}
281
-	}
282
-
283
-	/**
284
-	 * read app types from info.xml and cache them in the database
285
-	 */
286
-	public static function setAppTypes($app) {
287
-		$appData = self::getAppInfo($app);
288
-		if(!is_array($appData)) {
289
-			return;
290
-		}
291
-
292
-		if (isset($appData['types'])) {
293
-			$appTypes = implode(',', $appData['types']);
294
-		} else {
295
-			$appTypes = '';
296
-			$appData['types'] = [];
297
-		}
298
-
299
-		\OC::$server->getAppConfig()->setValue($app, 'types', $appTypes);
300
-
301
-		if (\OC::$server->getAppManager()->hasProtectedAppType($appData['types'])) {
302
-			$enabled = \OC::$server->getAppConfig()->getValue($app, 'enabled', 'yes');
303
-			if ($enabled !== 'yes' && $enabled !== 'no') {
304
-				\OC::$server->getAppConfig()->setValue($app, 'enabled', 'yes');
305
-			}
306
-		}
307
-	}
308
-
309
-	/**
310
-	 * get all enabled apps
311
-	 */
312
-	protected static $enabledAppsCache = array();
313
-
314
-	/**
315
-	 * Returns apps enabled for the current user.
316
-	 *
317
-	 * @param bool $forceRefresh whether to refresh the cache
318
-	 * @param bool $all whether to return apps for all users, not only the
319
-	 * currently logged in one
320
-	 * @return string[]
321
-	 */
322
-	public static function getEnabledApps($forceRefresh = false, $all = false) {
323
-		if (!\OC::$server->getSystemConfig()->getValue('installed', false)) {
324
-			return array();
325
-		}
326
-		// in incognito mode or when logged out, $user will be false,
327
-		// which is also the case during an upgrade
328
-		$appManager = \OC::$server->getAppManager();
329
-		if ($all) {
330
-			$user = null;
331
-		} else {
332
-			$user = \OC::$server->getUserSession()->getUser();
333
-		}
334
-
335
-		if (is_null($user)) {
336
-			$apps = $appManager->getInstalledApps();
337
-		} else {
338
-			$apps = $appManager->getEnabledAppsForUser($user);
339
-		}
340
-		$apps = array_filter($apps, function ($app) {
341
-			return $app !== 'files';//we add this manually
342
-		});
343
-		sort($apps);
344
-		array_unshift($apps, 'files');
345
-		return $apps;
346
-	}
347
-
348
-	/**
349
-	 * checks whether or not an app is enabled
350
-	 *
351
-	 * @param string $app app
352
-	 * @return bool
353
-	 * @deprecated 13.0.0 use \OC::$server->getAppManager()->isEnabledForUser($appId)
354
-	 *
355
-	 * This function checks whether or not an app is enabled.
356
-	 */
357
-	public static function isEnabled($app) {
358
-		return \OC::$server->getAppManager()->isEnabledForUser($app);
359
-	}
360
-
361
-	/**
362
-	 * enables an app
363
-	 *
364
-	 * @param string $appId
365
-	 * @param array $groups (optional) when set, only these groups will have access to the app
366
-	 * @throws \Exception
367
-	 * @return void
368
-	 *
369
-	 * This function set an app as enabled in appconfig.
370
-	 */
371
-	public function enable($appId,
372
-						   $groups = null) {
373
-		self::$enabledAppsCache = []; // flush
374
-
375
-		// Check if app is already downloaded
376
-		$installer = new Installer(
377
-			\OC::$server->getAppFetcher(),
378
-			\OC::$server->getHTTPClientService(),
379
-			\OC::$server->getTempManager(),
380
-			\OC::$server->getLogger(),
381
-			\OC::$server->getConfig()
382
-		);
383
-		$isDownloaded = $installer->isDownloaded($appId);
384
-
385
-		if(!$isDownloaded) {
386
-			$installer->downloadApp($appId);
387
-		}
388
-
389
-		$installer->installApp($appId);
390
-
391
-		$appManager = \OC::$server->getAppManager();
392
-		if (!is_null($groups)) {
393
-			$groupManager = \OC::$server->getGroupManager();
394
-			$groupsList = [];
395
-			foreach ($groups as $group) {
396
-				$groupItem = $groupManager->get($group);
397
-				if ($groupItem instanceof \OCP\IGroup) {
398
-					$groupsList[] = $groupManager->get($group);
399
-				}
400
-			}
401
-			$appManager->enableAppForGroups($appId, $groupsList);
402
-		} else {
403
-			$appManager->enableApp($appId);
404
-		}
405
-	}
406
-
407
-	/**
408
-	 * @param string $app
409
-	 * @return bool
410
-	 */
411
-	public static function removeApp($app) {
412
-		if (\OC::$server->getAppManager()->isShipped($app)) {
413
-			return false;
414
-		}
415
-
416
-		$installer = new Installer(
417
-			\OC::$server->getAppFetcher(),
418
-			\OC::$server->getHTTPClientService(),
419
-			\OC::$server->getTempManager(),
420
-			\OC::$server->getLogger(),
421
-			\OC::$server->getConfig()
422
-		);
423
-		return $installer->removeApp($app);
424
-	}
425
-
426
-	/**
427
-	 * This function set an app as disabled in appconfig.
428
-	 *
429
-	 * @param string $app app
430
-	 * @throws Exception
431
-	 */
432
-	public static function disable($app) {
433
-		// flush
434
-		self::$enabledAppsCache = array();
435
-
436
-		// run uninstall steps
437
-		$appData = OC_App::getAppInfo($app);
438
-		if (!is_null($appData)) {
439
-			OC_App::executeRepairSteps($app, $appData['repair-steps']['uninstall']);
440
-		}
441
-
442
-		// emit disable hook - needed anymore ?
443
-		\OC_Hook::emit('OC_App', 'pre_disable', array('app' => $app));
444
-
445
-		// finally disable it
446
-		$appManager = \OC::$server->getAppManager();
447
-		$appManager->disableApp($app);
448
-	}
449
-
450
-	// This is private as well. It simply works, so don't ask for more details
451
-	private static function proceedNavigation($list) {
452
-		usort($list, function($a, $b) {
453
-			if (isset($a['order']) && isset($b['order'])) {
454
-				return ($a['order'] < $b['order']) ? -1 : 1;
455
-			} else if (isset($a['order']) || isset($b['order'])) {
456
-				return isset($a['order']) ? -1 : 1;
457
-			} else {
458
-				return ($a['name'] < $b['name']) ? -1 : 1;
459
-			}
460
-		});
461
-
462
-		$activeApp = OC::$server->getNavigationManager()->getActiveEntry();
463
-		foreach ($list as $index => &$navEntry) {
464
-			if ($navEntry['id'] == $activeApp) {
465
-				$navEntry['active'] = true;
466
-			} else {
467
-				$navEntry['active'] = false;
468
-			}
469
-		}
470
-		unset($navEntry);
471
-
472
-		return $list;
473
-	}
474
-
475
-	/**
476
-	 * Get the path where to install apps
477
-	 *
478
-	 * @return string|false
479
-	 */
480
-	public static function getInstallPath() {
481
-		if (\OC::$server->getSystemConfig()->getValue('appstoreenabled', true) == false) {
482
-			return false;
483
-		}
484
-
485
-		foreach (OC::$APPSROOTS as $dir) {
486
-			if (isset($dir['writable']) && $dir['writable'] === true) {
487
-				return $dir['path'];
488
-			}
489
-		}
490
-
491
-		\OCP\Util::writeLog('core', 'No application directories are marked as writable.', \OCP\Util::ERROR);
492
-		return null;
493
-	}
494
-
495
-
496
-	/**
497
-	 * search for an app in all app-directories
498
-	 *
499
-	 * @param string $appId
500
-	 * @return false|string
501
-	 */
502
-	public static function findAppInDirectories($appId) {
503
-		$sanitizedAppId = self::cleanAppId($appId);
504
-		if($sanitizedAppId !== $appId) {
505
-			return false;
506
-		}
507
-		static $app_dir = array();
508
-
509
-		if (isset($app_dir[$appId])) {
510
-			return $app_dir[$appId];
511
-		}
512
-
513
-		$possibleApps = array();
514
-		foreach (OC::$APPSROOTS as $dir) {
515
-			if (file_exists($dir['path'] . '/' . $appId)) {
516
-				$possibleApps[] = $dir;
517
-			}
518
-		}
519
-
520
-		if (empty($possibleApps)) {
521
-			return false;
522
-		} elseif (count($possibleApps) === 1) {
523
-			$dir = array_shift($possibleApps);
524
-			$app_dir[$appId] = $dir;
525
-			return $dir;
526
-		} else {
527
-			$versionToLoad = array();
528
-			foreach ($possibleApps as $possibleApp) {
529
-				$version = self::getAppVersionByPath($possibleApp['path']);
530
-				if (empty($versionToLoad) || version_compare($version, $versionToLoad['version'], '>')) {
531
-					$versionToLoad = array(
532
-						'dir' => $possibleApp,
533
-						'version' => $version,
534
-					);
535
-				}
536
-			}
537
-			$app_dir[$appId] = $versionToLoad['dir'];
538
-			return $versionToLoad['dir'];
539
-			//TODO - write test
540
-		}
541
-	}
542
-
543
-	/**
544
-	 * Get the directory for the given app.
545
-	 * If the app is defined in multiple directories, the first one is taken. (false if not found)
546
-	 *
547
-	 * @param string $appId
548
-	 * @return string|false
549
-	 */
550
-	public static function getAppPath($appId) {
551
-		if ($appId === null || trim($appId) === '') {
552
-			return false;
553
-		}
554
-
555
-		if (($dir = self::findAppInDirectories($appId)) != false) {
556
-			return $dir['path'] . '/' . $appId;
557
-		}
558
-		return false;
559
-	}
560
-
561
-	/**
562
-	 * Get the path for the given app on the access
563
-	 * If the app is defined in multiple directories, the first one is taken. (false if not found)
564
-	 *
565
-	 * @param string $appId
566
-	 * @return string|false
567
-	 */
568
-	public static function getAppWebPath($appId) {
569
-		if (($dir = self::findAppInDirectories($appId)) != false) {
570
-			return OC::$WEBROOT . $dir['url'] . '/' . $appId;
571
-		}
572
-		return false;
573
-	}
574
-
575
-	/**
576
-	 * get the last version of the app from appinfo/info.xml
577
-	 *
578
-	 * @param string $appId
579
-	 * @param bool $useCache
580
-	 * @return string
581
-	 */
582
-	public static function getAppVersion($appId, $useCache = true) {
583
-		if($useCache && isset(self::$appVersion[$appId])) {
584
-			return self::$appVersion[$appId];
585
-		}
586
-
587
-		$file = self::getAppPath($appId);
588
-		self::$appVersion[$appId] = ($file !== false) ? self::getAppVersionByPath($file) : '0';
589
-		return self::$appVersion[$appId];
590
-	}
591
-
592
-	/**
593
-	 * get app's version based on it's path
594
-	 *
595
-	 * @param string $path
596
-	 * @return string
597
-	 */
598
-	public static function getAppVersionByPath($path) {
599
-		$infoFile = $path . '/appinfo/info.xml';
600
-		$appData = self::getAppInfo($infoFile, true);
601
-		return isset($appData['version']) ? $appData['version'] : '';
602
-	}
603
-
604
-
605
-	/**
606
-	 * Read all app metadata from the info.xml file
607
-	 *
608
-	 * @param string $appId id of the app or the path of the info.xml file
609
-	 * @param bool $path
610
-	 * @param string $lang
611
-	 * @return array|null
612
-	 * @note all data is read from info.xml, not just pre-defined fields
613
-	 */
614
-	public static function getAppInfo($appId, $path = false, $lang = null) {
615
-		if ($path) {
616
-			$file = $appId;
617
-		} else {
618
-			if ($lang === null && isset(self::$appInfo[$appId])) {
619
-				return self::$appInfo[$appId];
620
-			}
621
-			$appPath = self::getAppPath($appId);
622
-			if($appPath === false) {
623
-				return null;
624
-			}
625
-			$file = $appPath . '/appinfo/info.xml';
626
-		}
627
-
628
-		$parser = new InfoParser(\OC::$server->getMemCacheFactory()->createLocal('core.appinfo'));
629
-		$data = $parser->parse($file);
630
-
631
-		if (is_array($data)) {
632
-			$data = OC_App::parseAppInfo($data, $lang);
633
-		}
634
-		if(isset($data['ocsid'])) {
635
-			$storedId = \OC::$server->getConfig()->getAppValue($appId, 'ocsid');
636
-			if($storedId !== '' && $storedId !== $data['ocsid']) {
637
-				$data['ocsid'] = $storedId;
638
-			}
639
-		}
640
-
641
-		if ($lang === null) {
642
-			self::$appInfo[$appId] = $data;
643
-		}
644
-
645
-		return $data;
646
-	}
647
-
648
-	/**
649
-	 * Returns the navigation
650
-	 *
651
-	 * @return array
652
-	 *
653
-	 * This function returns an array containing all entries added. The
654
-	 * entries are sorted by the key 'order' ascending. Additional to the keys
655
-	 * given for each app the following keys exist:
656
-	 *   - active: boolean, signals if the user is on this navigation entry
657
-	 */
658
-	public static function getNavigation() {
659
-		$entries = OC::$server->getNavigationManager()->getAll();
660
-		return self::proceedNavigation($entries);
661
-	}
662
-
663
-	/**
664
-	 * Returns the Settings Navigation
665
-	 *
666
-	 * @return string[]
667
-	 *
668
-	 * This function returns an array containing all settings pages added. The
669
-	 * entries are sorted by the key 'order' ascending.
670
-	 */
671
-	public static function getSettingsNavigation() {
672
-		$entries = OC::$server->getNavigationManager()->getAll('settings');
673
-		return self::proceedNavigation($entries);
674
-	}
675
-
676
-	/**
677
-	 * get the id of loaded app
678
-	 *
679
-	 * @return string
680
-	 */
681
-	public static function getCurrentApp() {
682
-		$request = \OC::$server->getRequest();
683
-		$script = substr($request->getScriptName(), strlen(OC::$WEBROOT) + 1);
684
-		$topFolder = substr($script, 0, strpos($script, '/'));
685
-		if (empty($topFolder)) {
686
-			$path_info = $request->getPathInfo();
687
-			if ($path_info) {
688
-				$topFolder = substr($path_info, 1, strpos($path_info, '/', 1) - 1);
689
-			}
690
-		}
691
-		if ($topFolder == 'apps') {
692
-			$length = strlen($topFolder);
693
-			return substr($script, $length + 1, strpos($script, '/', $length + 1) - $length - 1);
694
-		} else {
695
-			return $topFolder;
696
-		}
697
-	}
698
-
699
-	/**
700
-	 * @param string $type
701
-	 * @return array
702
-	 */
703
-	public static function getForms($type) {
704
-		$forms = array();
705
-		switch ($type) {
706
-			case 'admin':
707
-				$source = self::$adminForms;
708
-				break;
709
-			case 'personal':
710
-				$source = self::$personalForms;
711
-				break;
712
-			default:
713
-				return array();
714
-		}
715
-		foreach ($source as $form) {
716
-			$forms[] = include $form;
717
-		}
718
-		return $forms;
719
-	}
720
-
721
-	/**
722
-	 * register an admin form to be shown
723
-	 *
724
-	 * @param string $app
725
-	 * @param string $page
726
-	 */
727
-	public static function registerAdmin($app, $page) {
728
-		self::$adminForms[] = $app . '/' . $page . '.php';
729
-	}
730
-
731
-	/**
732
-	 * register a personal form to be shown
733
-	 * @param string $app
734
-	 * @param string $page
735
-	 */
736
-	public static function registerPersonal($app, $page) {
737
-		self::$personalForms[] = $app . '/' . $page . '.php';
738
-	}
739
-
740
-	/**
741
-	 * @param array $entry
742
-	 */
743
-	public static function registerLogIn(array $entry) {
744
-		self::$altLogin[] = $entry;
745
-	}
746
-
747
-	/**
748
-	 * @return array
749
-	 */
750
-	public static function getAlternativeLogIns() {
751
-		return self::$altLogin;
752
-	}
753
-
754
-	/**
755
-	 * get a list of all apps in the apps folder
756
-	 *
757
-	 * @return array an array of app names (string IDs)
758
-	 * @todo: change the name of this method to getInstalledApps, which is more accurate
759
-	 */
760
-	public static function getAllApps() {
761
-
762
-		$apps = array();
763
-
764
-		foreach (OC::$APPSROOTS as $apps_dir) {
765
-			if (!is_readable($apps_dir['path'])) {
766
-				\OCP\Util::writeLog('core', 'unable to read app folder : ' . $apps_dir['path'], \OCP\Util::WARN);
767
-				continue;
768
-			}
769
-			$dh = opendir($apps_dir['path']);
770
-
771
-			if (is_resource($dh)) {
772
-				while (($file = readdir($dh)) !== false) {
773
-
774
-					if ($file[0] != '.' and is_dir($apps_dir['path'] . '/' . $file) and is_file($apps_dir['path'] . '/' . $file . '/appinfo/info.xml')) {
775
-
776
-						$apps[] = $file;
777
-					}
778
-				}
779
-			}
780
-		}
781
-
782
-		$apps = array_unique($apps);
783
-
784
-		return $apps;
785
-	}
786
-
787
-	/**
788
-	 * List all apps, this is used in apps.php
789
-	 *
790
-	 * @return array
791
-	 */
792
-	public function listAllApps() {
793
-		$installedApps = OC_App::getAllApps();
794
-
795
-		$appManager = \OC::$server->getAppManager();
796
-		//we don't want to show configuration for these
797
-		$blacklist = $appManager->getAlwaysEnabledApps();
798
-		$appList = array();
799
-		$langCode = \OC::$server->getL10N('core')->getLanguageCode();
800
-		$urlGenerator = \OC::$server->getURLGenerator();
801
-
802
-		foreach ($installedApps as $app) {
803
-			if (array_search($app, $blacklist) === false) {
804
-
805
-				$info = OC_App::getAppInfo($app, false, $langCode);
806
-				if (!is_array($info)) {
807
-					\OCP\Util::writeLog('core', 'Could not read app info file for app "' . $app . '"', \OCP\Util::ERROR);
808
-					continue;
809
-				}
810
-
811
-				if (!isset($info['name'])) {
812
-					\OCP\Util::writeLog('core', 'App id "' . $app . '" has no name in appinfo', \OCP\Util::ERROR);
813
-					continue;
814
-				}
815
-
816
-				$enabled = \OC::$server->getAppConfig()->getValue($app, 'enabled', 'no');
817
-				$info['groups'] = null;
818
-				if ($enabled === 'yes') {
819
-					$active = true;
820
-				} else if ($enabled === 'no') {
821
-					$active = false;
822
-				} else {
823
-					$active = true;
824
-					$info['groups'] = $enabled;
825
-				}
826
-
827
-				$info['active'] = $active;
828
-
829
-				if ($appManager->isShipped($app)) {
830
-					$info['internal'] = true;
831
-					$info['level'] = self::officialApp;
832
-					$info['removable'] = false;
833
-				} else {
834
-					$info['internal'] = false;
835
-					$info['removable'] = true;
836
-				}
837
-
838
-				$appPath = self::getAppPath($app);
839
-				if($appPath !== false) {
840
-					$appIcon = $appPath . '/img/' . $app . '.svg';
841
-					if (file_exists($appIcon)) {
842
-						$info['preview'] = $urlGenerator->imagePath($app, $app . '.svg');
843
-						$info['previewAsIcon'] = true;
844
-					} else {
845
-						$appIcon = $appPath . '/img/app.svg';
846
-						if (file_exists($appIcon)) {
847
-							$info['preview'] = $urlGenerator->imagePath($app, 'app.svg');
848
-							$info['previewAsIcon'] = true;
849
-						}
850
-					}
851
-				}
852
-				// fix documentation
853
-				if (isset($info['documentation']) && is_array($info['documentation'])) {
854
-					foreach ($info['documentation'] as $key => $url) {
855
-						// If it is not an absolute URL we assume it is a key
856
-						// i.e. admin-ldap will get converted to go.php?to=admin-ldap
857
-						if (stripos($url, 'https://') !== 0 && stripos($url, 'http://') !== 0) {
858
-							$url = $urlGenerator->linkToDocs($url);
859
-						}
860
-
861
-						$info['documentation'][$key] = $url;
862
-					}
863
-				}
864
-
865
-				$info['version'] = OC_App::getAppVersion($app);
866
-				$appList[] = $info;
867
-			}
868
-		}
869
-
870
-		return $appList;
871
-	}
872
-
873
-	public static function shouldUpgrade($app) {
874
-		$versions = self::getAppVersions();
875
-		$currentVersion = OC_App::getAppVersion($app);
876
-		if ($currentVersion && isset($versions[$app])) {
877
-			$installedVersion = $versions[$app];
878
-			if (!version_compare($currentVersion, $installedVersion, '=')) {
879
-				return true;
880
-			}
881
-		}
882
-		return false;
883
-	}
884
-
885
-	/**
886
-	 * Adjust the number of version parts of $version1 to match
887
-	 * the number of version parts of $version2.
888
-	 *
889
-	 * @param string $version1 version to adjust
890
-	 * @param string $version2 version to take the number of parts from
891
-	 * @return string shortened $version1
892
-	 */
893
-	private static function adjustVersionParts($version1, $version2) {
894
-		$version1 = explode('.', $version1);
895
-		$version2 = explode('.', $version2);
896
-		// reduce $version1 to match the number of parts in $version2
897
-		while (count($version1) > count($version2)) {
898
-			array_pop($version1);
899
-		}
900
-		// if $version1 does not have enough parts, add some
901
-		while (count($version1) < count($version2)) {
902
-			$version1[] = '0';
903
-		}
904
-		return implode('.', $version1);
905
-	}
906
-
907
-	/**
908
-	 * Check whether the current ownCloud version matches the given
909
-	 * application's version requirements.
910
-	 *
911
-	 * The comparison is made based on the number of parts that the
912
-	 * app info version has. For example for ownCloud 6.0.3 if the
913
-	 * app info version is expecting version 6.0, the comparison is
914
-	 * made on the first two parts of the ownCloud version.
915
-	 * This means that it's possible to specify "requiremin" => 6
916
-	 * and "requiremax" => 6 and it will still match ownCloud 6.0.3.
917
-	 *
918
-	 * @param string $ocVersion ownCloud version to check against
919
-	 * @param array $appInfo app info (from xml)
920
-	 *
921
-	 * @return boolean true if compatible, otherwise false
922
-	 */
923
-	public static function isAppCompatible($ocVersion, $appInfo) {
924
-		$requireMin = '';
925
-		$requireMax = '';
926
-		if (isset($appInfo['dependencies']['nextcloud']['@attributes']['min-version'])) {
927
-			$requireMin = $appInfo['dependencies']['nextcloud']['@attributes']['min-version'];
928
-		} elseif (isset($appInfo['dependencies']['owncloud']['@attributes']['min-version'])) {
929
-			$requireMin = $appInfo['dependencies']['owncloud']['@attributes']['min-version'];
930
-		} else if (isset($appInfo['requiremin'])) {
931
-			$requireMin = $appInfo['requiremin'];
932
-		} else if (isset($appInfo['require'])) {
933
-			$requireMin = $appInfo['require'];
934
-		}
935
-
936
-		if (isset($appInfo['dependencies']['nextcloud']['@attributes']['max-version'])) {
937
-			$requireMax = $appInfo['dependencies']['nextcloud']['@attributes']['max-version'];
938
-		} elseif (isset($appInfo['dependencies']['owncloud']['@attributes']['max-version'])) {
939
-			$requireMax = $appInfo['dependencies']['owncloud']['@attributes']['max-version'];
940
-		} else if (isset($appInfo['requiremax'])) {
941
-			$requireMax = $appInfo['requiremax'];
942
-		}
943
-
944
-		if (is_array($ocVersion)) {
945
-			$ocVersion = implode('.', $ocVersion);
946
-		}
947
-
948
-		if (!empty($requireMin)
949
-			&& version_compare(self::adjustVersionParts($ocVersion, $requireMin), $requireMin, '<')
950
-		) {
951
-
952
-			return false;
953
-		}
954
-
955
-		if (!empty($requireMax)
956
-			&& version_compare(self::adjustVersionParts($ocVersion, $requireMax), $requireMax, '>')
957
-		) {
958
-			return false;
959
-		}
960
-
961
-		return true;
962
-	}
963
-
964
-	/**
965
-	 * get the installed version of all apps
966
-	 */
967
-	public static function getAppVersions() {
968
-		static $versions;
969
-
970
-		if(!$versions) {
971
-			$appConfig = \OC::$server->getAppConfig();
972
-			$versions = $appConfig->getValues(false, 'installed_version');
973
-		}
974
-		return $versions;
975
-	}
976
-
977
-	/**
978
-	 * @param string $app
979
-	 * @param \OCP\IConfig $config
980
-	 * @param \OCP\IL10N $l
981
-	 * @return bool
982
-	 *
983
-	 * @throws Exception if app is not compatible with this version of ownCloud
984
-	 * @throws Exception if no app-name was specified
985
-	 */
986
-	public function installApp($app,
987
-							   \OCP\IConfig $config,
988
-							   \OCP\IL10N $l) {
989
-		if ($app !== false) {
990
-			// check if the app is compatible with this version of ownCloud
991
-			$info = self::getAppInfo($app);
992
-			if(!is_array($info)) {
993
-				throw new \Exception(
994
-					$l->t('App "%s" cannot be installed because appinfo file cannot be read.',
995
-						[$info['name']]
996
-					)
997
-				);
998
-			}
999
-
1000
-			$version = \OCP\Util::getVersion();
1001
-			if (!self::isAppCompatible($version, $info)) {
1002
-				throw new \Exception(
1003
-					$l->t('App "%s" cannot be installed because it is not compatible with this version of the server.',
1004
-						array($info['name'])
1005
-					)
1006
-				);
1007
-			}
1008
-
1009
-			// check for required dependencies
1010
-			self::checkAppDependencies($config, $l, $info);
1011
-
1012
-			$config->setAppValue($app, 'enabled', 'yes');
1013
-			if (isset($appData['id'])) {
1014
-				$config->setAppValue($app, 'ocsid', $appData['id']);
1015
-			}
1016
-
1017
-			if(isset($info['settings']) && is_array($info['settings'])) {
1018
-				$appPath = self::getAppPath($app);
1019
-				self::registerAutoloading($app, $appPath);
1020
-				\OC::$server->getSettingsManager()->setupSettings($info['settings']);
1021
-			}
1022
-
1023
-			\OC_Hook::emit('OC_App', 'post_enable', array('app' => $app));
1024
-		} else {
1025
-			if(empty($appName) ) {
1026
-				throw new \Exception($l->t("No app name specified"));
1027
-			} else {
1028
-				throw new \Exception($l->t("App '%s' could not be installed!", $appName));
1029
-			}
1030
-		}
1031
-
1032
-		return $app;
1033
-	}
1034
-
1035
-	/**
1036
-	 * update the database for the app and call the update script
1037
-	 *
1038
-	 * @param string $appId
1039
-	 * @return bool
1040
-	 */
1041
-	public static function updateApp($appId) {
1042
-		$appPath = self::getAppPath($appId);
1043
-		if($appPath === false) {
1044
-			return false;
1045
-		}
1046
-		self::registerAutoloading($appId, $appPath);
1047
-
1048
-		$appData = self::getAppInfo($appId);
1049
-		self::executeRepairSteps($appId, $appData['repair-steps']['pre-migration']);
1050
-
1051
-		if (file_exists($appPath . '/appinfo/database.xml')) {
1052
-			OC_DB::updateDbFromStructure($appPath . '/appinfo/database.xml');
1053
-		} else {
1054
-			$ms = new MigrationService($appId, \OC::$server->getDatabaseConnection());
1055
-			$ms->migrate();
1056
-		}
1057
-
1058
-		self::executeRepairSteps($appId, $appData['repair-steps']['post-migration']);
1059
-		self::setupLiveMigrations($appId, $appData['repair-steps']['live-migration']);
1060
-		unset(self::$appVersion[$appId]);
1061
-
1062
-		// run upgrade code
1063
-		if (file_exists($appPath . '/appinfo/update.php')) {
1064
-			self::loadApp($appId);
1065
-			include $appPath . '/appinfo/update.php';
1066
-		}
1067
-		self::setupBackgroundJobs($appData['background-jobs']);
1068
-		if(isset($appData['settings']) && is_array($appData['settings'])) {
1069
-			\OC::$server->getSettingsManager()->setupSettings($appData['settings']);
1070
-		}
1071
-
1072
-		//set remote/public handlers
1073
-		if (array_key_exists('ocsid', $appData)) {
1074
-			\OC::$server->getConfig()->setAppValue($appId, 'ocsid', $appData['ocsid']);
1075
-		} elseif(\OC::$server->getConfig()->getAppValue($appId, 'ocsid', null) !== null) {
1076
-			\OC::$server->getConfig()->deleteAppValue($appId, 'ocsid');
1077
-		}
1078
-		foreach ($appData['remote'] as $name => $path) {
1079
-			\OC::$server->getConfig()->setAppValue('core', 'remote_' . $name, $appId . '/' . $path);
1080
-		}
1081
-		foreach ($appData['public'] as $name => $path) {
1082
-			\OC::$server->getConfig()->setAppValue('core', 'public_' . $name, $appId . '/' . $path);
1083
-		}
1084
-
1085
-		self::setAppTypes($appId);
1086
-
1087
-		$version = \OC_App::getAppVersion($appId);
1088
-		\OC::$server->getAppConfig()->setValue($appId, 'installed_version', $version);
1089
-
1090
-		\OC::$server->getEventDispatcher()->dispatch(ManagerEvent::EVENT_APP_UPDATE, new ManagerEvent(
1091
-			ManagerEvent::EVENT_APP_UPDATE, $appId
1092
-		));
1093
-
1094
-		return true;
1095
-	}
1096
-
1097
-	/**
1098
-	 * @param string $appId
1099
-	 * @param string[] $steps
1100
-	 * @throws \OC\NeedsUpdateException
1101
-	 */
1102
-	public static function executeRepairSteps($appId, array $steps) {
1103
-		if (empty($steps)) {
1104
-			return;
1105
-		}
1106
-		// load the app
1107
-		self::loadApp($appId);
1108
-
1109
-		$dispatcher = OC::$server->getEventDispatcher();
1110
-
1111
-		// load the steps
1112
-		$r = new Repair([], $dispatcher);
1113
-		foreach ($steps as $step) {
1114
-			try {
1115
-				$r->addStep($step);
1116
-			} catch (Exception $ex) {
1117
-				$r->emit('\OC\Repair', 'error', [$ex->getMessage()]);
1118
-				\OC::$server->getLogger()->logException($ex);
1119
-			}
1120
-		}
1121
-		// run the steps
1122
-		$r->run();
1123
-	}
1124
-
1125
-	public static function setupBackgroundJobs(array $jobs) {
1126
-		$queue = \OC::$server->getJobList();
1127
-		foreach ($jobs as $job) {
1128
-			$queue->add($job);
1129
-		}
1130
-	}
1131
-
1132
-	/**
1133
-	 * @param string $appId
1134
-	 * @param string[] $steps
1135
-	 */
1136
-	private static function setupLiveMigrations($appId, array $steps) {
1137
-		$queue = \OC::$server->getJobList();
1138
-		foreach ($steps as $step) {
1139
-			$queue->add('OC\Migration\BackgroundRepair', [
1140
-				'app' => $appId,
1141
-				'step' => $step]);
1142
-		}
1143
-	}
1144
-
1145
-	/**
1146
-	 * @param string $appId
1147
-	 * @return \OC\Files\View|false
1148
-	 */
1149
-	public static function getStorage($appId) {
1150
-		if (\OC::$server->getAppManager()->isEnabledForUser($appId)) { //sanity check
1151
-			if (\OC::$server->getUserSession()->isLoggedIn()) {
1152
-				$view = new \OC\Files\View('/' . OC_User::getUser());
1153
-				if (!$view->file_exists($appId)) {
1154
-					$view->mkdir($appId);
1155
-				}
1156
-				return new \OC\Files\View('/' . OC_User::getUser() . '/' . $appId);
1157
-			} else {
1158
-				\OCP\Util::writeLog('core', 'Can\'t get app storage, app ' . $appId . ', user not logged in', \OCP\Util::ERROR);
1159
-				return false;
1160
-			}
1161
-		} else {
1162
-			\OCP\Util::writeLog('core', 'Can\'t get app storage, app ' . $appId . ' not enabled', \OCP\Util::ERROR);
1163
-			return false;
1164
-		}
1165
-	}
1166
-
1167
-	protected static function findBestL10NOption($options, $lang) {
1168
-		$fallback = $similarLangFallback = $englishFallback = false;
1169
-
1170
-		$lang = strtolower($lang);
1171
-		$similarLang = $lang;
1172
-		if (strpos($similarLang, '_')) {
1173
-			// For "de_DE" we want to find "de" and the other way around
1174
-			$similarLang = substr($lang, 0, strpos($lang, '_'));
1175
-		}
1176
-
1177
-		foreach ($options as $option) {
1178
-			if (is_array($option)) {
1179
-				if ($fallback === false) {
1180
-					$fallback = $option['@value'];
1181
-				}
1182
-
1183
-				if (!isset($option['@attributes']['lang'])) {
1184
-					continue;
1185
-				}
1186
-
1187
-				$attributeLang = strtolower($option['@attributes']['lang']);
1188
-				if ($attributeLang === $lang) {
1189
-					return $option['@value'];
1190
-				}
1191
-
1192
-				if ($attributeLang === $similarLang) {
1193
-					$similarLangFallback = $option['@value'];
1194
-				} else if (strpos($attributeLang, $similarLang . '_') === 0) {
1195
-					if ($similarLangFallback === false) {
1196
-						$similarLangFallback =  $option['@value'];
1197
-					}
1198
-				}
1199
-			} else {
1200
-				$englishFallback = $option;
1201
-			}
1202
-		}
1203
-
1204
-		if ($similarLangFallback !== false) {
1205
-			return $similarLangFallback;
1206
-		} else if ($englishFallback !== false) {
1207
-			return $englishFallback;
1208
-		}
1209
-		return (string) $fallback;
1210
-	}
1211
-
1212
-	/**
1213
-	 * parses the app data array and enhanced the 'description' value
1214
-	 *
1215
-	 * @param array $data the app data
1216
-	 * @param string $lang
1217
-	 * @return array improved app data
1218
-	 */
1219
-	public static function parseAppInfo(array $data, $lang = null) {
1220
-
1221
-		if ($lang && isset($data['name']) && is_array($data['name'])) {
1222
-			$data['name'] = self::findBestL10NOption($data['name'], $lang);
1223
-		}
1224
-		if ($lang && isset($data['summary']) && is_array($data['summary'])) {
1225
-			$data['summary'] = self::findBestL10NOption($data['summary'], $lang);
1226
-		}
1227
-		if ($lang && isset($data['description']) && is_array($data['description'])) {
1228
-			$data['description'] = trim(self::findBestL10NOption($data['description'], $lang));
1229
-		} else if (isset($data['description']) && is_string($data['description'])) {
1230
-			$data['description'] = trim($data['description']);
1231
-		} else  {
1232
-			$data['description'] = '';
1233
-		}
1234
-
1235
-		return $data;
1236
-	}
1237
-
1238
-	/**
1239
-	 * @param \OCP\IConfig $config
1240
-	 * @param \OCP\IL10N $l
1241
-	 * @param array $info
1242
-	 * @throws \Exception
1243
-	 */
1244
-	public static function checkAppDependencies($config, $l, $info) {
1245
-		$dependencyAnalyzer = new DependencyAnalyzer(new Platform($config), $l);
1246
-		$missing = $dependencyAnalyzer->analyze($info);
1247
-		if (!empty($missing)) {
1248
-			$missingMsg = implode(PHP_EOL, $missing);
1249
-			throw new \Exception(
1250
-				$l->t('App "%s" cannot be installed because the following dependencies are not fulfilled: %s',
1251
-					[$info['name'], $missingMsg]
1252
-				)
1253
-			);
1254
-		}
1255
-	}
64
+    static private $appVersion = [];
65
+    static private $adminForms = array();
66
+    static private $personalForms = array();
67
+    static private $appInfo = array();
68
+    static private $appTypes = array();
69
+    static private $loadedApps = array();
70
+    static private $altLogin = array();
71
+    static private $alreadyRegistered = [];
72
+    const officialApp = 200;
73
+
74
+    /**
75
+     * clean the appId
76
+     *
77
+     * @param string|boolean $app AppId that needs to be cleaned
78
+     * @return string
79
+     */
80
+    public static function cleanAppId($app) {
81
+        return str_replace(array('\0', '/', '\\', '..'), '', $app);
82
+    }
83
+
84
+    /**
85
+     * Check if an app is loaded
86
+     *
87
+     * @param string $app
88
+     * @return bool
89
+     */
90
+    public static function isAppLoaded($app) {
91
+        return in_array($app, self::$loadedApps, true);
92
+    }
93
+
94
+    /**
95
+     * loads all apps
96
+     *
97
+     * @param string[] | string | null $types
98
+     * @return bool
99
+     *
100
+     * This function walks through the ownCloud directory and loads all apps
101
+     * it can find. A directory contains an app if the file /appinfo/info.xml
102
+     * exists.
103
+     *
104
+     * if $types is set, only apps of those types will be loaded
105
+     */
106
+    public static function loadApps($types = null) {
107
+        if (\OC::$server->getSystemConfig()->getValue('maintenance', false)) {
108
+            return false;
109
+        }
110
+        // Load the enabled apps here
111
+        $apps = self::getEnabledApps();
112
+
113
+        // Add each apps' folder as allowed class path
114
+        foreach($apps as $app) {
115
+            $path = self::getAppPath($app);
116
+            if($path !== false) {
117
+                self::registerAutoloading($app, $path);
118
+            }
119
+        }
120
+
121
+        // prevent app.php from printing output
122
+        ob_start();
123
+        foreach ($apps as $app) {
124
+            if ((is_null($types) or self::isType($app, $types)) && !in_array($app, self::$loadedApps)) {
125
+                self::loadApp($app);
126
+            }
127
+        }
128
+        ob_end_clean();
129
+
130
+        return true;
131
+    }
132
+
133
+    /**
134
+     * load a single app
135
+     *
136
+     * @param string $app
137
+     */
138
+    public static function loadApp($app) {
139
+        self::$loadedApps[] = $app;
140
+        $appPath = self::getAppPath($app);
141
+        if($appPath === false) {
142
+            return;
143
+        }
144
+
145
+        // in case someone calls loadApp() directly
146
+        self::registerAutoloading($app, $appPath);
147
+
148
+        if (is_file($appPath . '/appinfo/app.php')) {
149
+            \OC::$server->getEventLogger()->start('load_app_' . $app, 'Load app: ' . $app);
150
+            self::requireAppFile($app);
151
+            if (self::isType($app, array('authentication'))) {
152
+                // since authentication apps affect the "is app enabled for group" check,
153
+                // the enabled apps cache needs to be cleared to make sure that the
154
+                // next time getEnableApps() is called it will also include apps that were
155
+                // enabled for groups
156
+                self::$enabledAppsCache = array();
157
+            }
158
+            \OC::$server->getEventLogger()->end('load_app_' . $app);
159
+        }
160
+
161
+        $info = self::getAppInfo($app);
162
+        if (!empty($info['activity']['filters'])) {
163
+            foreach ($info['activity']['filters'] as $filter) {
164
+                \OC::$server->getActivityManager()->registerFilter($filter);
165
+            }
166
+        }
167
+        if (!empty($info['activity']['settings'])) {
168
+            foreach ($info['activity']['settings'] as $setting) {
169
+                \OC::$server->getActivityManager()->registerSetting($setting);
170
+            }
171
+        }
172
+        if (!empty($info['activity']['providers'])) {
173
+            foreach ($info['activity']['providers'] as $provider) {
174
+                \OC::$server->getActivityManager()->registerProvider($provider);
175
+            }
176
+        }
177
+        if (!empty($info['collaboration']['plugins'])) {
178
+            // deal with one or many plugin entries
179
+            $plugins = isset($info['collaboration']['plugins']['plugin']['@value']) ?
180
+                [$info['collaboration']['plugins']['plugin']] : $info['collaboration']['plugins']['plugin'];
181
+            foreach ($plugins as $plugin) {
182
+                if($plugin['@attributes']['type'] === 'collaborator-search') {
183
+                    $pluginInfo = [
184
+                        'shareType' => $plugin['@attributes']['share-type'],
185
+                        'class' => $plugin['@value'],
186
+                    ];
187
+                    \OC::$server->getCollaboratorSearch()->registerPlugin($pluginInfo);
188
+                } else if ($plugin['@attributes']['type'] === 'autocomplete-sort') {
189
+                    \OC::$server->getAutoCompleteManager()->registerSorter($plugin['@value']);
190
+                }
191
+            }
192
+        }
193
+    }
194
+
195
+    /**
196
+     * @internal
197
+     * @param string $app
198
+     * @param string $path
199
+     */
200
+    public static function registerAutoloading($app, $path) {
201
+        $key = $app . '-' . $path;
202
+        if(isset(self::$alreadyRegistered[$key])) {
203
+            return;
204
+        }
205
+
206
+        self::$alreadyRegistered[$key] = true;
207
+
208
+        // Register on PSR-4 composer autoloader
209
+        $appNamespace = \OC\AppFramework\App::buildAppNamespace($app);
210
+        \OC::$server->registerNamespace($app, $appNamespace);
211
+
212
+        if (file_exists($path . '/composer/autoload.php')) {
213
+            require_once $path . '/composer/autoload.php';
214
+        } else {
215
+            \OC::$composerAutoloader->addPsr4($appNamespace . '\\', $path . '/lib/', true);
216
+            // Register on legacy autoloader
217
+            \OC::$loader->addValidRoot($path);
218
+        }
219
+
220
+        // Register Test namespace only when testing
221
+        if (defined('PHPUNIT_RUN') || defined('CLI_TEST_RUN')) {
222
+            \OC::$composerAutoloader->addPsr4($appNamespace . '\\Tests\\', $path . '/tests/', true);
223
+        }
224
+    }
225
+
226
+    /**
227
+     * Load app.php from the given app
228
+     *
229
+     * @param string $app app name
230
+     */
231
+    private static function requireAppFile($app) {
232
+        try {
233
+            // encapsulated here to avoid variable scope conflicts
234
+            require_once $app . '/appinfo/app.php';
235
+        } catch (Error $ex) {
236
+            \OC::$server->getLogger()->logException($ex);
237
+            $blacklist = \OC::$server->getAppManager()->getAlwaysEnabledApps();
238
+            if (!in_array($app, $blacklist)) {
239
+                self::disable($app);
240
+            }
241
+        }
242
+    }
243
+
244
+    /**
245
+     * check if an app is of a specific type
246
+     *
247
+     * @param string $app
248
+     * @param string|array $types
249
+     * @return bool
250
+     */
251
+    public static function isType($app, $types) {
252
+        if (is_string($types)) {
253
+            $types = array($types);
254
+        }
255
+        $appTypes = self::getAppTypes($app);
256
+        foreach ($types as $type) {
257
+            if (array_search($type, $appTypes) !== false) {
258
+                return true;
259
+            }
260
+        }
261
+        return false;
262
+    }
263
+
264
+    /**
265
+     * get the types of an app
266
+     *
267
+     * @param string $app
268
+     * @return array
269
+     */
270
+    private static function getAppTypes($app) {
271
+        //load the cache
272
+        if (count(self::$appTypes) == 0) {
273
+            self::$appTypes = \OC::$server->getAppConfig()->getValues(false, 'types');
274
+        }
275
+
276
+        if (isset(self::$appTypes[$app])) {
277
+            return explode(',', self::$appTypes[$app]);
278
+        } else {
279
+            return array();
280
+        }
281
+    }
282
+
283
+    /**
284
+     * read app types from info.xml and cache them in the database
285
+     */
286
+    public static function setAppTypes($app) {
287
+        $appData = self::getAppInfo($app);
288
+        if(!is_array($appData)) {
289
+            return;
290
+        }
291
+
292
+        if (isset($appData['types'])) {
293
+            $appTypes = implode(',', $appData['types']);
294
+        } else {
295
+            $appTypes = '';
296
+            $appData['types'] = [];
297
+        }
298
+
299
+        \OC::$server->getAppConfig()->setValue($app, 'types', $appTypes);
300
+
301
+        if (\OC::$server->getAppManager()->hasProtectedAppType($appData['types'])) {
302
+            $enabled = \OC::$server->getAppConfig()->getValue($app, 'enabled', 'yes');
303
+            if ($enabled !== 'yes' && $enabled !== 'no') {
304
+                \OC::$server->getAppConfig()->setValue($app, 'enabled', 'yes');
305
+            }
306
+        }
307
+    }
308
+
309
+    /**
310
+     * get all enabled apps
311
+     */
312
+    protected static $enabledAppsCache = array();
313
+
314
+    /**
315
+     * Returns apps enabled for the current user.
316
+     *
317
+     * @param bool $forceRefresh whether to refresh the cache
318
+     * @param bool $all whether to return apps for all users, not only the
319
+     * currently logged in one
320
+     * @return string[]
321
+     */
322
+    public static function getEnabledApps($forceRefresh = false, $all = false) {
323
+        if (!\OC::$server->getSystemConfig()->getValue('installed', false)) {
324
+            return array();
325
+        }
326
+        // in incognito mode or when logged out, $user will be false,
327
+        // which is also the case during an upgrade
328
+        $appManager = \OC::$server->getAppManager();
329
+        if ($all) {
330
+            $user = null;
331
+        } else {
332
+            $user = \OC::$server->getUserSession()->getUser();
333
+        }
334
+
335
+        if (is_null($user)) {
336
+            $apps = $appManager->getInstalledApps();
337
+        } else {
338
+            $apps = $appManager->getEnabledAppsForUser($user);
339
+        }
340
+        $apps = array_filter($apps, function ($app) {
341
+            return $app !== 'files';//we add this manually
342
+        });
343
+        sort($apps);
344
+        array_unshift($apps, 'files');
345
+        return $apps;
346
+    }
347
+
348
+    /**
349
+     * checks whether or not an app is enabled
350
+     *
351
+     * @param string $app app
352
+     * @return bool
353
+     * @deprecated 13.0.0 use \OC::$server->getAppManager()->isEnabledForUser($appId)
354
+     *
355
+     * This function checks whether or not an app is enabled.
356
+     */
357
+    public static function isEnabled($app) {
358
+        return \OC::$server->getAppManager()->isEnabledForUser($app);
359
+    }
360
+
361
+    /**
362
+     * enables an app
363
+     *
364
+     * @param string $appId
365
+     * @param array $groups (optional) when set, only these groups will have access to the app
366
+     * @throws \Exception
367
+     * @return void
368
+     *
369
+     * This function set an app as enabled in appconfig.
370
+     */
371
+    public function enable($appId,
372
+                            $groups = null) {
373
+        self::$enabledAppsCache = []; // flush
374
+
375
+        // Check if app is already downloaded
376
+        $installer = new Installer(
377
+            \OC::$server->getAppFetcher(),
378
+            \OC::$server->getHTTPClientService(),
379
+            \OC::$server->getTempManager(),
380
+            \OC::$server->getLogger(),
381
+            \OC::$server->getConfig()
382
+        );
383
+        $isDownloaded = $installer->isDownloaded($appId);
384
+
385
+        if(!$isDownloaded) {
386
+            $installer->downloadApp($appId);
387
+        }
388
+
389
+        $installer->installApp($appId);
390
+
391
+        $appManager = \OC::$server->getAppManager();
392
+        if (!is_null($groups)) {
393
+            $groupManager = \OC::$server->getGroupManager();
394
+            $groupsList = [];
395
+            foreach ($groups as $group) {
396
+                $groupItem = $groupManager->get($group);
397
+                if ($groupItem instanceof \OCP\IGroup) {
398
+                    $groupsList[] = $groupManager->get($group);
399
+                }
400
+            }
401
+            $appManager->enableAppForGroups($appId, $groupsList);
402
+        } else {
403
+            $appManager->enableApp($appId);
404
+        }
405
+    }
406
+
407
+    /**
408
+     * @param string $app
409
+     * @return bool
410
+     */
411
+    public static function removeApp($app) {
412
+        if (\OC::$server->getAppManager()->isShipped($app)) {
413
+            return false;
414
+        }
415
+
416
+        $installer = new Installer(
417
+            \OC::$server->getAppFetcher(),
418
+            \OC::$server->getHTTPClientService(),
419
+            \OC::$server->getTempManager(),
420
+            \OC::$server->getLogger(),
421
+            \OC::$server->getConfig()
422
+        );
423
+        return $installer->removeApp($app);
424
+    }
425
+
426
+    /**
427
+     * This function set an app as disabled in appconfig.
428
+     *
429
+     * @param string $app app
430
+     * @throws Exception
431
+     */
432
+    public static function disable($app) {
433
+        // flush
434
+        self::$enabledAppsCache = array();
435
+
436
+        // run uninstall steps
437
+        $appData = OC_App::getAppInfo($app);
438
+        if (!is_null($appData)) {
439
+            OC_App::executeRepairSteps($app, $appData['repair-steps']['uninstall']);
440
+        }
441
+
442
+        // emit disable hook - needed anymore ?
443
+        \OC_Hook::emit('OC_App', 'pre_disable', array('app' => $app));
444
+
445
+        // finally disable it
446
+        $appManager = \OC::$server->getAppManager();
447
+        $appManager->disableApp($app);
448
+    }
449
+
450
+    // This is private as well. It simply works, so don't ask for more details
451
+    private static function proceedNavigation($list) {
452
+        usort($list, function($a, $b) {
453
+            if (isset($a['order']) && isset($b['order'])) {
454
+                return ($a['order'] < $b['order']) ? -1 : 1;
455
+            } else if (isset($a['order']) || isset($b['order'])) {
456
+                return isset($a['order']) ? -1 : 1;
457
+            } else {
458
+                return ($a['name'] < $b['name']) ? -1 : 1;
459
+            }
460
+        });
461
+
462
+        $activeApp = OC::$server->getNavigationManager()->getActiveEntry();
463
+        foreach ($list as $index => &$navEntry) {
464
+            if ($navEntry['id'] == $activeApp) {
465
+                $navEntry['active'] = true;
466
+            } else {
467
+                $navEntry['active'] = false;
468
+            }
469
+        }
470
+        unset($navEntry);
471
+
472
+        return $list;
473
+    }
474
+
475
+    /**
476
+     * Get the path where to install apps
477
+     *
478
+     * @return string|false
479
+     */
480
+    public static function getInstallPath() {
481
+        if (\OC::$server->getSystemConfig()->getValue('appstoreenabled', true) == false) {
482
+            return false;
483
+        }
484
+
485
+        foreach (OC::$APPSROOTS as $dir) {
486
+            if (isset($dir['writable']) && $dir['writable'] === true) {
487
+                return $dir['path'];
488
+            }
489
+        }
490
+
491
+        \OCP\Util::writeLog('core', 'No application directories are marked as writable.', \OCP\Util::ERROR);
492
+        return null;
493
+    }
494
+
495
+
496
+    /**
497
+     * search for an app in all app-directories
498
+     *
499
+     * @param string $appId
500
+     * @return false|string
501
+     */
502
+    public static function findAppInDirectories($appId) {
503
+        $sanitizedAppId = self::cleanAppId($appId);
504
+        if($sanitizedAppId !== $appId) {
505
+            return false;
506
+        }
507
+        static $app_dir = array();
508
+
509
+        if (isset($app_dir[$appId])) {
510
+            return $app_dir[$appId];
511
+        }
512
+
513
+        $possibleApps = array();
514
+        foreach (OC::$APPSROOTS as $dir) {
515
+            if (file_exists($dir['path'] . '/' . $appId)) {
516
+                $possibleApps[] = $dir;
517
+            }
518
+        }
519
+
520
+        if (empty($possibleApps)) {
521
+            return false;
522
+        } elseif (count($possibleApps) === 1) {
523
+            $dir = array_shift($possibleApps);
524
+            $app_dir[$appId] = $dir;
525
+            return $dir;
526
+        } else {
527
+            $versionToLoad = array();
528
+            foreach ($possibleApps as $possibleApp) {
529
+                $version = self::getAppVersionByPath($possibleApp['path']);
530
+                if (empty($versionToLoad) || version_compare($version, $versionToLoad['version'], '>')) {
531
+                    $versionToLoad = array(
532
+                        'dir' => $possibleApp,
533
+                        'version' => $version,
534
+                    );
535
+                }
536
+            }
537
+            $app_dir[$appId] = $versionToLoad['dir'];
538
+            return $versionToLoad['dir'];
539
+            //TODO - write test
540
+        }
541
+    }
542
+
543
+    /**
544
+     * Get the directory for the given app.
545
+     * If the app is defined in multiple directories, the first one is taken. (false if not found)
546
+     *
547
+     * @param string $appId
548
+     * @return string|false
549
+     */
550
+    public static function getAppPath($appId) {
551
+        if ($appId === null || trim($appId) === '') {
552
+            return false;
553
+        }
554
+
555
+        if (($dir = self::findAppInDirectories($appId)) != false) {
556
+            return $dir['path'] . '/' . $appId;
557
+        }
558
+        return false;
559
+    }
560
+
561
+    /**
562
+     * Get the path for the given app on the access
563
+     * If the app is defined in multiple directories, the first one is taken. (false if not found)
564
+     *
565
+     * @param string $appId
566
+     * @return string|false
567
+     */
568
+    public static function getAppWebPath($appId) {
569
+        if (($dir = self::findAppInDirectories($appId)) != false) {
570
+            return OC::$WEBROOT . $dir['url'] . '/' . $appId;
571
+        }
572
+        return false;
573
+    }
574
+
575
+    /**
576
+     * get the last version of the app from appinfo/info.xml
577
+     *
578
+     * @param string $appId
579
+     * @param bool $useCache
580
+     * @return string
581
+     */
582
+    public static function getAppVersion($appId, $useCache = true) {
583
+        if($useCache && isset(self::$appVersion[$appId])) {
584
+            return self::$appVersion[$appId];
585
+        }
586
+
587
+        $file = self::getAppPath($appId);
588
+        self::$appVersion[$appId] = ($file !== false) ? self::getAppVersionByPath($file) : '0';
589
+        return self::$appVersion[$appId];
590
+    }
591
+
592
+    /**
593
+     * get app's version based on it's path
594
+     *
595
+     * @param string $path
596
+     * @return string
597
+     */
598
+    public static function getAppVersionByPath($path) {
599
+        $infoFile = $path . '/appinfo/info.xml';
600
+        $appData = self::getAppInfo($infoFile, true);
601
+        return isset($appData['version']) ? $appData['version'] : '';
602
+    }
603
+
604
+
605
+    /**
606
+     * Read all app metadata from the info.xml file
607
+     *
608
+     * @param string $appId id of the app or the path of the info.xml file
609
+     * @param bool $path
610
+     * @param string $lang
611
+     * @return array|null
612
+     * @note all data is read from info.xml, not just pre-defined fields
613
+     */
614
+    public static function getAppInfo($appId, $path = false, $lang = null) {
615
+        if ($path) {
616
+            $file = $appId;
617
+        } else {
618
+            if ($lang === null && isset(self::$appInfo[$appId])) {
619
+                return self::$appInfo[$appId];
620
+            }
621
+            $appPath = self::getAppPath($appId);
622
+            if($appPath === false) {
623
+                return null;
624
+            }
625
+            $file = $appPath . '/appinfo/info.xml';
626
+        }
627
+
628
+        $parser = new InfoParser(\OC::$server->getMemCacheFactory()->createLocal('core.appinfo'));
629
+        $data = $parser->parse($file);
630
+
631
+        if (is_array($data)) {
632
+            $data = OC_App::parseAppInfo($data, $lang);
633
+        }
634
+        if(isset($data['ocsid'])) {
635
+            $storedId = \OC::$server->getConfig()->getAppValue($appId, 'ocsid');
636
+            if($storedId !== '' && $storedId !== $data['ocsid']) {
637
+                $data['ocsid'] = $storedId;
638
+            }
639
+        }
640
+
641
+        if ($lang === null) {
642
+            self::$appInfo[$appId] = $data;
643
+        }
644
+
645
+        return $data;
646
+    }
647
+
648
+    /**
649
+     * Returns the navigation
650
+     *
651
+     * @return array
652
+     *
653
+     * This function returns an array containing all entries added. The
654
+     * entries are sorted by the key 'order' ascending. Additional to the keys
655
+     * given for each app the following keys exist:
656
+     *   - active: boolean, signals if the user is on this navigation entry
657
+     */
658
+    public static function getNavigation() {
659
+        $entries = OC::$server->getNavigationManager()->getAll();
660
+        return self::proceedNavigation($entries);
661
+    }
662
+
663
+    /**
664
+     * Returns the Settings Navigation
665
+     *
666
+     * @return string[]
667
+     *
668
+     * This function returns an array containing all settings pages added. The
669
+     * entries are sorted by the key 'order' ascending.
670
+     */
671
+    public static function getSettingsNavigation() {
672
+        $entries = OC::$server->getNavigationManager()->getAll('settings');
673
+        return self::proceedNavigation($entries);
674
+    }
675
+
676
+    /**
677
+     * get the id of loaded app
678
+     *
679
+     * @return string
680
+     */
681
+    public static function getCurrentApp() {
682
+        $request = \OC::$server->getRequest();
683
+        $script = substr($request->getScriptName(), strlen(OC::$WEBROOT) + 1);
684
+        $topFolder = substr($script, 0, strpos($script, '/'));
685
+        if (empty($topFolder)) {
686
+            $path_info = $request->getPathInfo();
687
+            if ($path_info) {
688
+                $topFolder = substr($path_info, 1, strpos($path_info, '/', 1) - 1);
689
+            }
690
+        }
691
+        if ($topFolder == 'apps') {
692
+            $length = strlen($topFolder);
693
+            return substr($script, $length + 1, strpos($script, '/', $length + 1) - $length - 1);
694
+        } else {
695
+            return $topFolder;
696
+        }
697
+    }
698
+
699
+    /**
700
+     * @param string $type
701
+     * @return array
702
+     */
703
+    public static function getForms($type) {
704
+        $forms = array();
705
+        switch ($type) {
706
+            case 'admin':
707
+                $source = self::$adminForms;
708
+                break;
709
+            case 'personal':
710
+                $source = self::$personalForms;
711
+                break;
712
+            default:
713
+                return array();
714
+        }
715
+        foreach ($source as $form) {
716
+            $forms[] = include $form;
717
+        }
718
+        return $forms;
719
+    }
720
+
721
+    /**
722
+     * register an admin form to be shown
723
+     *
724
+     * @param string $app
725
+     * @param string $page
726
+     */
727
+    public static function registerAdmin($app, $page) {
728
+        self::$adminForms[] = $app . '/' . $page . '.php';
729
+    }
730
+
731
+    /**
732
+     * register a personal form to be shown
733
+     * @param string $app
734
+     * @param string $page
735
+     */
736
+    public static function registerPersonal($app, $page) {
737
+        self::$personalForms[] = $app . '/' . $page . '.php';
738
+    }
739
+
740
+    /**
741
+     * @param array $entry
742
+     */
743
+    public static function registerLogIn(array $entry) {
744
+        self::$altLogin[] = $entry;
745
+    }
746
+
747
+    /**
748
+     * @return array
749
+     */
750
+    public static function getAlternativeLogIns() {
751
+        return self::$altLogin;
752
+    }
753
+
754
+    /**
755
+     * get a list of all apps in the apps folder
756
+     *
757
+     * @return array an array of app names (string IDs)
758
+     * @todo: change the name of this method to getInstalledApps, which is more accurate
759
+     */
760
+    public static function getAllApps() {
761
+
762
+        $apps = array();
763
+
764
+        foreach (OC::$APPSROOTS as $apps_dir) {
765
+            if (!is_readable($apps_dir['path'])) {
766
+                \OCP\Util::writeLog('core', 'unable to read app folder : ' . $apps_dir['path'], \OCP\Util::WARN);
767
+                continue;
768
+            }
769
+            $dh = opendir($apps_dir['path']);
770
+
771
+            if (is_resource($dh)) {
772
+                while (($file = readdir($dh)) !== false) {
773
+
774
+                    if ($file[0] != '.' and is_dir($apps_dir['path'] . '/' . $file) and is_file($apps_dir['path'] . '/' . $file . '/appinfo/info.xml')) {
775
+
776
+                        $apps[] = $file;
777
+                    }
778
+                }
779
+            }
780
+        }
781
+
782
+        $apps = array_unique($apps);
783
+
784
+        return $apps;
785
+    }
786
+
787
+    /**
788
+     * List all apps, this is used in apps.php
789
+     *
790
+     * @return array
791
+     */
792
+    public function listAllApps() {
793
+        $installedApps = OC_App::getAllApps();
794
+
795
+        $appManager = \OC::$server->getAppManager();
796
+        //we don't want to show configuration for these
797
+        $blacklist = $appManager->getAlwaysEnabledApps();
798
+        $appList = array();
799
+        $langCode = \OC::$server->getL10N('core')->getLanguageCode();
800
+        $urlGenerator = \OC::$server->getURLGenerator();
801
+
802
+        foreach ($installedApps as $app) {
803
+            if (array_search($app, $blacklist) === false) {
804
+
805
+                $info = OC_App::getAppInfo($app, false, $langCode);
806
+                if (!is_array($info)) {
807
+                    \OCP\Util::writeLog('core', 'Could not read app info file for app "' . $app . '"', \OCP\Util::ERROR);
808
+                    continue;
809
+                }
810
+
811
+                if (!isset($info['name'])) {
812
+                    \OCP\Util::writeLog('core', 'App id "' . $app . '" has no name in appinfo', \OCP\Util::ERROR);
813
+                    continue;
814
+                }
815
+
816
+                $enabled = \OC::$server->getAppConfig()->getValue($app, 'enabled', 'no');
817
+                $info['groups'] = null;
818
+                if ($enabled === 'yes') {
819
+                    $active = true;
820
+                } else if ($enabled === 'no') {
821
+                    $active = false;
822
+                } else {
823
+                    $active = true;
824
+                    $info['groups'] = $enabled;
825
+                }
826
+
827
+                $info['active'] = $active;
828
+
829
+                if ($appManager->isShipped($app)) {
830
+                    $info['internal'] = true;
831
+                    $info['level'] = self::officialApp;
832
+                    $info['removable'] = false;
833
+                } else {
834
+                    $info['internal'] = false;
835
+                    $info['removable'] = true;
836
+                }
837
+
838
+                $appPath = self::getAppPath($app);
839
+                if($appPath !== false) {
840
+                    $appIcon = $appPath . '/img/' . $app . '.svg';
841
+                    if (file_exists($appIcon)) {
842
+                        $info['preview'] = $urlGenerator->imagePath($app, $app . '.svg');
843
+                        $info['previewAsIcon'] = true;
844
+                    } else {
845
+                        $appIcon = $appPath . '/img/app.svg';
846
+                        if (file_exists($appIcon)) {
847
+                            $info['preview'] = $urlGenerator->imagePath($app, 'app.svg');
848
+                            $info['previewAsIcon'] = true;
849
+                        }
850
+                    }
851
+                }
852
+                // fix documentation
853
+                if (isset($info['documentation']) && is_array($info['documentation'])) {
854
+                    foreach ($info['documentation'] as $key => $url) {
855
+                        // If it is not an absolute URL we assume it is a key
856
+                        // i.e. admin-ldap will get converted to go.php?to=admin-ldap
857
+                        if (stripos($url, 'https://') !== 0 && stripos($url, 'http://') !== 0) {
858
+                            $url = $urlGenerator->linkToDocs($url);
859
+                        }
860
+
861
+                        $info['documentation'][$key] = $url;
862
+                    }
863
+                }
864
+
865
+                $info['version'] = OC_App::getAppVersion($app);
866
+                $appList[] = $info;
867
+            }
868
+        }
869
+
870
+        return $appList;
871
+    }
872
+
873
+    public static function shouldUpgrade($app) {
874
+        $versions = self::getAppVersions();
875
+        $currentVersion = OC_App::getAppVersion($app);
876
+        if ($currentVersion && isset($versions[$app])) {
877
+            $installedVersion = $versions[$app];
878
+            if (!version_compare($currentVersion, $installedVersion, '=')) {
879
+                return true;
880
+            }
881
+        }
882
+        return false;
883
+    }
884
+
885
+    /**
886
+     * Adjust the number of version parts of $version1 to match
887
+     * the number of version parts of $version2.
888
+     *
889
+     * @param string $version1 version to adjust
890
+     * @param string $version2 version to take the number of parts from
891
+     * @return string shortened $version1
892
+     */
893
+    private static function adjustVersionParts($version1, $version2) {
894
+        $version1 = explode('.', $version1);
895
+        $version2 = explode('.', $version2);
896
+        // reduce $version1 to match the number of parts in $version2
897
+        while (count($version1) > count($version2)) {
898
+            array_pop($version1);
899
+        }
900
+        // if $version1 does not have enough parts, add some
901
+        while (count($version1) < count($version2)) {
902
+            $version1[] = '0';
903
+        }
904
+        return implode('.', $version1);
905
+    }
906
+
907
+    /**
908
+     * Check whether the current ownCloud version matches the given
909
+     * application's version requirements.
910
+     *
911
+     * The comparison is made based on the number of parts that the
912
+     * app info version has. For example for ownCloud 6.0.3 if the
913
+     * app info version is expecting version 6.0, the comparison is
914
+     * made on the first two parts of the ownCloud version.
915
+     * This means that it's possible to specify "requiremin" => 6
916
+     * and "requiremax" => 6 and it will still match ownCloud 6.0.3.
917
+     *
918
+     * @param string $ocVersion ownCloud version to check against
919
+     * @param array $appInfo app info (from xml)
920
+     *
921
+     * @return boolean true if compatible, otherwise false
922
+     */
923
+    public static function isAppCompatible($ocVersion, $appInfo) {
924
+        $requireMin = '';
925
+        $requireMax = '';
926
+        if (isset($appInfo['dependencies']['nextcloud']['@attributes']['min-version'])) {
927
+            $requireMin = $appInfo['dependencies']['nextcloud']['@attributes']['min-version'];
928
+        } elseif (isset($appInfo['dependencies']['owncloud']['@attributes']['min-version'])) {
929
+            $requireMin = $appInfo['dependencies']['owncloud']['@attributes']['min-version'];
930
+        } else if (isset($appInfo['requiremin'])) {
931
+            $requireMin = $appInfo['requiremin'];
932
+        } else if (isset($appInfo['require'])) {
933
+            $requireMin = $appInfo['require'];
934
+        }
935
+
936
+        if (isset($appInfo['dependencies']['nextcloud']['@attributes']['max-version'])) {
937
+            $requireMax = $appInfo['dependencies']['nextcloud']['@attributes']['max-version'];
938
+        } elseif (isset($appInfo['dependencies']['owncloud']['@attributes']['max-version'])) {
939
+            $requireMax = $appInfo['dependencies']['owncloud']['@attributes']['max-version'];
940
+        } else if (isset($appInfo['requiremax'])) {
941
+            $requireMax = $appInfo['requiremax'];
942
+        }
943
+
944
+        if (is_array($ocVersion)) {
945
+            $ocVersion = implode('.', $ocVersion);
946
+        }
947
+
948
+        if (!empty($requireMin)
949
+            && version_compare(self::adjustVersionParts($ocVersion, $requireMin), $requireMin, '<')
950
+        ) {
951
+
952
+            return false;
953
+        }
954
+
955
+        if (!empty($requireMax)
956
+            && version_compare(self::adjustVersionParts($ocVersion, $requireMax), $requireMax, '>')
957
+        ) {
958
+            return false;
959
+        }
960
+
961
+        return true;
962
+    }
963
+
964
+    /**
965
+     * get the installed version of all apps
966
+     */
967
+    public static function getAppVersions() {
968
+        static $versions;
969
+
970
+        if(!$versions) {
971
+            $appConfig = \OC::$server->getAppConfig();
972
+            $versions = $appConfig->getValues(false, 'installed_version');
973
+        }
974
+        return $versions;
975
+    }
976
+
977
+    /**
978
+     * @param string $app
979
+     * @param \OCP\IConfig $config
980
+     * @param \OCP\IL10N $l
981
+     * @return bool
982
+     *
983
+     * @throws Exception if app is not compatible with this version of ownCloud
984
+     * @throws Exception if no app-name was specified
985
+     */
986
+    public function installApp($app,
987
+                                \OCP\IConfig $config,
988
+                                \OCP\IL10N $l) {
989
+        if ($app !== false) {
990
+            // check if the app is compatible with this version of ownCloud
991
+            $info = self::getAppInfo($app);
992
+            if(!is_array($info)) {
993
+                throw new \Exception(
994
+                    $l->t('App "%s" cannot be installed because appinfo file cannot be read.',
995
+                        [$info['name']]
996
+                    )
997
+                );
998
+            }
999
+
1000
+            $version = \OCP\Util::getVersion();
1001
+            if (!self::isAppCompatible($version, $info)) {
1002
+                throw new \Exception(
1003
+                    $l->t('App "%s" cannot be installed because it is not compatible with this version of the server.',
1004
+                        array($info['name'])
1005
+                    )
1006
+                );
1007
+            }
1008
+
1009
+            // check for required dependencies
1010
+            self::checkAppDependencies($config, $l, $info);
1011
+
1012
+            $config->setAppValue($app, 'enabled', 'yes');
1013
+            if (isset($appData['id'])) {
1014
+                $config->setAppValue($app, 'ocsid', $appData['id']);
1015
+            }
1016
+
1017
+            if(isset($info['settings']) && is_array($info['settings'])) {
1018
+                $appPath = self::getAppPath($app);
1019
+                self::registerAutoloading($app, $appPath);
1020
+                \OC::$server->getSettingsManager()->setupSettings($info['settings']);
1021
+            }
1022
+
1023
+            \OC_Hook::emit('OC_App', 'post_enable', array('app' => $app));
1024
+        } else {
1025
+            if(empty($appName) ) {
1026
+                throw new \Exception($l->t("No app name specified"));
1027
+            } else {
1028
+                throw new \Exception($l->t("App '%s' could not be installed!", $appName));
1029
+            }
1030
+        }
1031
+
1032
+        return $app;
1033
+    }
1034
+
1035
+    /**
1036
+     * update the database for the app and call the update script
1037
+     *
1038
+     * @param string $appId
1039
+     * @return bool
1040
+     */
1041
+    public static function updateApp($appId) {
1042
+        $appPath = self::getAppPath($appId);
1043
+        if($appPath === false) {
1044
+            return false;
1045
+        }
1046
+        self::registerAutoloading($appId, $appPath);
1047
+
1048
+        $appData = self::getAppInfo($appId);
1049
+        self::executeRepairSteps($appId, $appData['repair-steps']['pre-migration']);
1050
+
1051
+        if (file_exists($appPath . '/appinfo/database.xml')) {
1052
+            OC_DB::updateDbFromStructure($appPath . '/appinfo/database.xml');
1053
+        } else {
1054
+            $ms = new MigrationService($appId, \OC::$server->getDatabaseConnection());
1055
+            $ms->migrate();
1056
+        }
1057
+
1058
+        self::executeRepairSteps($appId, $appData['repair-steps']['post-migration']);
1059
+        self::setupLiveMigrations($appId, $appData['repair-steps']['live-migration']);
1060
+        unset(self::$appVersion[$appId]);
1061
+
1062
+        // run upgrade code
1063
+        if (file_exists($appPath . '/appinfo/update.php')) {
1064
+            self::loadApp($appId);
1065
+            include $appPath . '/appinfo/update.php';
1066
+        }
1067
+        self::setupBackgroundJobs($appData['background-jobs']);
1068
+        if(isset($appData['settings']) && is_array($appData['settings'])) {
1069
+            \OC::$server->getSettingsManager()->setupSettings($appData['settings']);
1070
+        }
1071
+
1072
+        //set remote/public handlers
1073
+        if (array_key_exists('ocsid', $appData)) {
1074
+            \OC::$server->getConfig()->setAppValue($appId, 'ocsid', $appData['ocsid']);
1075
+        } elseif(\OC::$server->getConfig()->getAppValue($appId, 'ocsid', null) !== null) {
1076
+            \OC::$server->getConfig()->deleteAppValue($appId, 'ocsid');
1077
+        }
1078
+        foreach ($appData['remote'] as $name => $path) {
1079
+            \OC::$server->getConfig()->setAppValue('core', 'remote_' . $name, $appId . '/' . $path);
1080
+        }
1081
+        foreach ($appData['public'] as $name => $path) {
1082
+            \OC::$server->getConfig()->setAppValue('core', 'public_' . $name, $appId . '/' . $path);
1083
+        }
1084
+
1085
+        self::setAppTypes($appId);
1086
+
1087
+        $version = \OC_App::getAppVersion($appId);
1088
+        \OC::$server->getAppConfig()->setValue($appId, 'installed_version', $version);
1089
+
1090
+        \OC::$server->getEventDispatcher()->dispatch(ManagerEvent::EVENT_APP_UPDATE, new ManagerEvent(
1091
+            ManagerEvent::EVENT_APP_UPDATE, $appId
1092
+        ));
1093
+
1094
+        return true;
1095
+    }
1096
+
1097
+    /**
1098
+     * @param string $appId
1099
+     * @param string[] $steps
1100
+     * @throws \OC\NeedsUpdateException
1101
+     */
1102
+    public static function executeRepairSteps($appId, array $steps) {
1103
+        if (empty($steps)) {
1104
+            return;
1105
+        }
1106
+        // load the app
1107
+        self::loadApp($appId);
1108
+
1109
+        $dispatcher = OC::$server->getEventDispatcher();
1110
+
1111
+        // load the steps
1112
+        $r = new Repair([], $dispatcher);
1113
+        foreach ($steps as $step) {
1114
+            try {
1115
+                $r->addStep($step);
1116
+            } catch (Exception $ex) {
1117
+                $r->emit('\OC\Repair', 'error', [$ex->getMessage()]);
1118
+                \OC::$server->getLogger()->logException($ex);
1119
+            }
1120
+        }
1121
+        // run the steps
1122
+        $r->run();
1123
+    }
1124
+
1125
+    public static function setupBackgroundJobs(array $jobs) {
1126
+        $queue = \OC::$server->getJobList();
1127
+        foreach ($jobs as $job) {
1128
+            $queue->add($job);
1129
+        }
1130
+    }
1131
+
1132
+    /**
1133
+     * @param string $appId
1134
+     * @param string[] $steps
1135
+     */
1136
+    private static function setupLiveMigrations($appId, array $steps) {
1137
+        $queue = \OC::$server->getJobList();
1138
+        foreach ($steps as $step) {
1139
+            $queue->add('OC\Migration\BackgroundRepair', [
1140
+                'app' => $appId,
1141
+                'step' => $step]);
1142
+        }
1143
+    }
1144
+
1145
+    /**
1146
+     * @param string $appId
1147
+     * @return \OC\Files\View|false
1148
+     */
1149
+    public static function getStorage($appId) {
1150
+        if (\OC::$server->getAppManager()->isEnabledForUser($appId)) { //sanity check
1151
+            if (\OC::$server->getUserSession()->isLoggedIn()) {
1152
+                $view = new \OC\Files\View('/' . OC_User::getUser());
1153
+                if (!$view->file_exists($appId)) {
1154
+                    $view->mkdir($appId);
1155
+                }
1156
+                return new \OC\Files\View('/' . OC_User::getUser() . '/' . $appId);
1157
+            } else {
1158
+                \OCP\Util::writeLog('core', 'Can\'t get app storage, app ' . $appId . ', user not logged in', \OCP\Util::ERROR);
1159
+                return false;
1160
+            }
1161
+        } else {
1162
+            \OCP\Util::writeLog('core', 'Can\'t get app storage, app ' . $appId . ' not enabled', \OCP\Util::ERROR);
1163
+            return false;
1164
+        }
1165
+    }
1166
+
1167
+    protected static function findBestL10NOption($options, $lang) {
1168
+        $fallback = $similarLangFallback = $englishFallback = false;
1169
+
1170
+        $lang = strtolower($lang);
1171
+        $similarLang = $lang;
1172
+        if (strpos($similarLang, '_')) {
1173
+            // For "de_DE" we want to find "de" and the other way around
1174
+            $similarLang = substr($lang, 0, strpos($lang, '_'));
1175
+        }
1176
+
1177
+        foreach ($options as $option) {
1178
+            if (is_array($option)) {
1179
+                if ($fallback === false) {
1180
+                    $fallback = $option['@value'];
1181
+                }
1182
+
1183
+                if (!isset($option['@attributes']['lang'])) {
1184
+                    continue;
1185
+                }
1186
+
1187
+                $attributeLang = strtolower($option['@attributes']['lang']);
1188
+                if ($attributeLang === $lang) {
1189
+                    return $option['@value'];
1190
+                }
1191
+
1192
+                if ($attributeLang === $similarLang) {
1193
+                    $similarLangFallback = $option['@value'];
1194
+                } else if (strpos($attributeLang, $similarLang . '_') === 0) {
1195
+                    if ($similarLangFallback === false) {
1196
+                        $similarLangFallback =  $option['@value'];
1197
+                    }
1198
+                }
1199
+            } else {
1200
+                $englishFallback = $option;
1201
+            }
1202
+        }
1203
+
1204
+        if ($similarLangFallback !== false) {
1205
+            return $similarLangFallback;
1206
+        } else if ($englishFallback !== false) {
1207
+            return $englishFallback;
1208
+        }
1209
+        return (string) $fallback;
1210
+    }
1211
+
1212
+    /**
1213
+     * parses the app data array and enhanced the 'description' value
1214
+     *
1215
+     * @param array $data the app data
1216
+     * @param string $lang
1217
+     * @return array improved app data
1218
+     */
1219
+    public static function parseAppInfo(array $data, $lang = null) {
1220
+
1221
+        if ($lang && isset($data['name']) && is_array($data['name'])) {
1222
+            $data['name'] = self::findBestL10NOption($data['name'], $lang);
1223
+        }
1224
+        if ($lang && isset($data['summary']) && is_array($data['summary'])) {
1225
+            $data['summary'] = self::findBestL10NOption($data['summary'], $lang);
1226
+        }
1227
+        if ($lang && isset($data['description']) && is_array($data['description'])) {
1228
+            $data['description'] = trim(self::findBestL10NOption($data['description'], $lang));
1229
+        } else if (isset($data['description']) && is_string($data['description'])) {
1230
+            $data['description'] = trim($data['description']);
1231
+        } else  {
1232
+            $data['description'] = '';
1233
+        }
1234
+
1235
+        return $data;
1236
+    }
1237
+
1238
+    /**
1239
+     * @param \OCP\IConfig $config
1240
+     * @param \OCP\IL10N $l
1241
+     * @param array $info
1242
+     * @throws \Exception
1243
+     */
1244
+    public static function checkAppDependencies($config, $l, $info) {
1245
+        $dependencyAnalyzer = new DependencyAnalyzer(new Platform($config), $l);
1246
+        $missing = $dependencyAnalyzer->analyze($info);
1247
+        if (!empty($missing)) {
1248
+            $missingMsg = implode(PHP_EOL, $missing);
1249
+            throw new \Exception(
1250
+                $l->t('App "%s" cannot be installed because the following dependencies are not fulfilled: %s',
1251
+                    [$info['name'], $missingMsg]
1252
+                )
1253
+            );
1254
+        }
1255
+    }
1256 1256
 }
Please login to merge, or discard this patch.
lib/private/Collaboration/AutoComplete/Manager.php 1 patch
Indentation   +45 added lines, -45 removed lines patch added patch discarded remove patch
@@ -28,54 +28,54 @@
 block discarded – undo
28 28
 use OCP\IServerContainer;
29 29
 
30 30
 class Manager implements IManager {
31
-	/** @var string[] */
32
-	protected $sorters =[];
31
+    /** @var string[] */
32
+    protected $sorters =[];
33 33
 
34
-	/** @var ISorter[]  */
35
-	protected $sorterInstances = [];
36
-	/** @var IServerContainer */
37
-	private $c;
34
+    /** @var ISorter[]  */
35
+    protected $sorterInstances = [];
36
+    /** @var IServerContainer */
37
+    private $c;
38 38
 
39
-	public function __construct(IServerContainer $container) {
40
-		$this->c = $container;
41
-	}
39
+    public function __construct(IServerContainer $container) {
40
+        $this->c = $container;
41
+    }
42 42
 
43
-	public function runSorters(array $sorters, array &$sortArray, array $context) {
44
-		$sorterInstances = $this->getSorters();
45
-		while($sorter = array_shift($sorters)) {
46
-			if(isset($sorterInstances[$sorter])) {
47
-				$sorterInstances[$sorter]->sort($sortArray, $context);
48
-			} else {
49
-				$this->c->getLogger()->warning('No sorter for ID "{id}", skipping', [
50
-					'app' => 'core', 'id' => $sorter
51
-				]);
52
-			}
53
-		}
54
-	}
43
+    public function runSorters(array $sorters, array &$sortArray, array $context) {
44
+        $sorterInstances = $this->getSorters();
45
+        while($sorter = array_shift($sorters)) {
46
+            if(isset($sorterInstances[$sorter])) {
47
+                $sorterInstances[$sorter]->sort($sortArray, $context);
48
+            } else {
49
+                $this->c->getLogger()->warning('No sorter for ID "{id}", skipping', [
50
+                    'app' => 'core', 'id' => $sorter
51
+                ]);
52
+            }
53
+        }
54
+    }
55 55
 
56
-	public function registerSorter($className) {
57
-		$this->sorters[] = $className;
58
-	}
56
+    public function registerSorter($className) {
57
+        $this->sorters[] = $className;
58
+    }
59 59
 
60
-	protected function getSorters() {
61
-		if(count($this->sorterInstances) === 0) {
62
-			foreach ($this->sorters as $sorter) {
63
-				/** @var ISorter $instance */
64
-				$instance = $this->c->resolve($sorter);
65
-				if(!$instance instanceof ISorter) {
66
-					$this->c->getLogger()->notice('Skipping sorter which is not an instance of ISorter. Class name: {class}',
67
-						['app' => 'core', 'class' => $sorter]);
68
-					continue;
69
-				}
70
-				$sorterId = trim($instance->getId());
71
-				if(trim($sorterId) === '') {
72
-					$this->c->getLogger()->notice('Skipping sorter with empty ID. Class name: {class}',
73
-						['app' => 'core', 'class' => $sorter]);
74
-					continue;
75
-				}
76
-				$this->sorterInstances[$sorterId] = $instance;
77
-			}
78
-		}
79
-		return $this->sorterInstances;
80
-	}
60
+    protected function getSorters() {
61
+        if(count($this->sorterInstances) === 0) {
62
+            foreach ($this->sorters as $sorter) {
63
+                /** @var ISorter $instance */
64
+                $instance = $this->c->resolve($sorter);
65
+                if(!$instance instanceof ISorter) {
66
+                    $this->c->getLogger()->notice('Skipping sorter which is not an instance of ISorter. Class name: {class}',
67
+                        ['app' => 'core', 'class' => $sorter]);
68
+                    continue;
69
+                }
70
+                $sorterId = trim($instance->getId());
71
+                if(trim($sorterId) === '') {
72
+                    $this->c->getLogger()->notice('Skipping sorter with empty ID. Class name: {class}',
73
+                        ['app' => 'core', 'class' => $sorter]);
74
+                    continue;
75
+                }
76
+                $this->sorterInstances[$sorterId] = $instance;
77
+            }
78
+        }
79
+        return $this->sorterInstances;
80
+    }
81 81
 }
Please login to merge, or discard this patch.
lib/private/Server.php 1 patch
Indentation   +1714 added lines, -1714 removed lines patch added patch discarded remove patch
@@ -132,1723 +132,1723 @@
 block discarded – undo
132 132
  * TODO: hookup all manager classes
133 133
  */
134 134
 class Server extends ServerContainer implements IServerContainer {
135
-	/** @var string */
136
-	private $webRoot;
137
-
138
-	/**
139
-	 * @param string $webRoot
140
-	 * @param \OC\Config $config
141
-	 */
142
-	public function __construct($webRoot, \OC\Config $config) {
143
-		parent::__construct();
144
-		$this->webRoot = $webRoot;
145
-
146
-		$this->registerService(\OCP\IServerContainer::class, function (IServerContainer $c) {
147
-			return $c;
148
-		});
149
-
150
-		$this->registerAlias(\OCP\Contacts\IManager::class, \OC\ContactsManager::class);
151
-		$this->registerAlias('ContactsManager', \OCP\Contacts\IManager::class);
152
-
153
-		$this->registerAlias(IActionFactory::class, ActionFactory::class);
154
-
155
-
156
-		$this->registerService(\OCP\IPreview::class, function (Server $c) {
157
-			return new PreviewManager(
158
-				$c->getConfig(),
159
-				$c->getRootFolder(),
160
-				$c->getAppDataDir('preview'),
161
-				$c->getEventDispatcher(),
162
-				$c->getSession()->get('user_id')
163
-			);
164
-		});
165
-		$this->registerAlias('PreviewManager', \OCP\IPreview::class);
166
-
167
-		$this->registerService(\OC\Preview\Watcher::class, function (Server $c) {
168
-			return new \OC\Preview\Watcher(
169
-				$c->getAppDataDir('preview')
170
-			);
171
-		});
172
-
173
-		$this->registerService('EncryptionManager', function (Server $c) {
174
-			$view = new View();
175
-			$util = new Encryption\Util(
176
-				$view,
177
-				$c->getUserManager(),
178
-				$c->getGroupManager(),
179
-				$c->getConfig()
180
-			);
181
-			return new Encryption\Manager(
182
-				$c->getConfig(),
183
-				$c->getLogger(),
184
-				$c->getL10N('core'),
185
-				new View(),
186
-				$util,
187
-				new ArrayCache()
188
-			);
189
-		});
190
-
191
-		$this->registerService('EncryptionFileHelper', function (Server $c) {
192
-			$util = new Encryption\Util(
193
-				new View(),
194
-				$c->getUserManager(),
195
-				$c->getGroupManager(),
196
-				$c->getConfig()
197
-			);
198
-			return new Encryption\File(
199
-				$util,
200
-				$c->getRootFolder(),
201
-				$c->getShareManager()
202
-			);
203
-		});
204
-
205
-		$this->registerService('EncryptionKeyStorage', function (Server $c) {
206
-			$view = new View();
207
-			$util = new Encryption\Util(
208
-				$view,
209
-				$c->getUserManager(),
210
-				$c->getGroupManager(),
211
-				$c->getConfig()
212
-			);
213
-
214
-			return new Encryption\Keys\Storage($view, $util);
215
-		});
216
-		$this->registerService('TagMapper', function (Server $c) {
217
-			return new TagMapper($c->getDatabaseConnection());
218
-		});
219
-
220
-		$this->registerService(\OCP\ITagManager::class, function (Server $c) {
221
-			$tagMapper = $c->query('TagMapper');
222
-			return new TagManager($tagMapper, $c->getUserSession());
223
-		});
224
-		$this->registerAlias('TagManager', \OCP\ITagManager::class);
225
-
226
-		$this->registerService('SystemTagManagerFactory', function (Server $c) {
227
-			$config = $c->getConfig();
228
-			$factoryClass = $config->getSystemValue('systemtags.managerFactory', '\OC\SystemTag\ManagerFactory');
229
-			/** @var \OC\SystemTag\ManagerFactory $factory */
230
-			$factory = new $factoryClass($this);
231
-			return $factory;
232
-		});
233
-		$this->registerService(\OCP\SystemTag\ISystemTagManager::class, function (Server $c) {
234
-			return $c->query('SystemTagManagerFactory')->getManager();
235
-		});
236
-		$this->registerAlias('SystemTagManager', \OCP\SystemTag\ISystemTagManager::class);
237
-
238
-		$this->registerService(\OCP\SystemTag\ISystemTagObjectMapper::class, function (Server $c) {
239
-			return $c->query('SystemTagManagerFactory')->getObjectMapper();
240
-		});
241
-		$this->registerService('RootFolder', function (Server $c) {
242
-			$manager = \OC\Files\Filesystem::getMountManager(null);
243
-			$view = new View();
244
-			$root = new Root(
245
-				$manager,
246
-				$view,
247
-				null,
248
-				$c->getUserMountCache(),
249
-				$this->getLogger(),
250
-				$this->getUserManager()
251
-			);
252
-			$connector = new HookConnector($root, $view);
253
-			$connector->viewToNode();
254
-
255
-			$previewConnector = new \OC\Preview\WatcherConnector($root, $c->getSystemConfig());
256
-			$previewConnector->connectWatcher();
257
-
258
-			return $root;
259
-		});
260
-		$this->registerAlias('SystemTagObjectMapper', \OCP\SystemTag\ISystemTagObjectMapper::class);
261
-
262
-		$this->registerService(\OCP\Files\IRootFolder::class, function (Server $c) {
263
-			return new LazyRoot(function () use ($c) {
264
-				return $c->query('RootFolder');
265
-			});
266
-		});
267
-		$this->registerAlias('LazyRootFolder', \OCP\Files\IRootFolder::class);
268
-
269
-		$this->registerService(\OCP\IUserManager::class, function (Server $c) {
270
-			$config = $c->getConfig();
271
-			return new \OC\User\Manager($config);
272
-		});
273
-		$this->registerAlias('UserManager', \OCP\IUserManager::class);
274
-
275
-		$this->registerService(\OCP\IGroupManager::class, function (Server $c) {
276
-			$groupManager = new \OC\Group\Manager($this->getUserManager(), $this->getLogger());
277
-			$groupManager->listen('\OC\Group', 'preCreate', function ($gid) {
278
-				\OC_Hook::emit('OC_Group', 'pre_createGroup', array('run' => true, 'gid' => $gid));
279
-			});
280
-			$groupManager->listen('\OC\Group', 'postCreate', function (\OC\Group\Group $gid) {
281
-				\OC_Hook::emit('OC_User', 'post_createGroup', array('gid' => $gid->getGID()));
282
-			});
283
-			$groupManager->listen('\OC\Group', 'preDelete', function (\OC\Group\Group $group) {
284
-				\OC_Hook::emit('OC_Group', 'pre_deleteGroup', array('run' => true, 'gid' => $group->getGID()));
285
-			});
286
-			$groupManager->listen('\OC\Group', 'postDelete', function (\OC\Group\Group $group) {
287
-				\OC_Hook::emit('OC_User', 'post_deleteGroup', array('gid' => $group->getGID()));
288
-			});
289
-			$groupManager->listen('\OC\Group', 'preAddUser', function (\OC\Group\Group $group, \OC\User\User $user) {
290
-				\OC_Hook::emit('OC_Group', 'pre_addToGroup', array('run' => true, 'uid' => $user->getUID(), 'gid' => $group->getGID()));
291
-			});
292
-			$groupManager->listen('\OC\Group', 'postAddUser', function (\OC\Group\Group $group, \OC\User\User $user) {
293
-				\OC_Hook::emit('OC_Group', 'post_addToGroup', array('uid' => $user->getUID(), 'gid' => $group->getGID()));
294
-				//Minimal fix to keep it backward compatible TODO: clean up all the GroupManager hooks
295
-				\OC_Hook::emit('OC_User', 'post_addToGroup', array('uid' => $user->getUID(), 'gid' => $group->getGID()));
296
-			});
297
-			return $groupManager;
298
-		});
299
-		$this->registerAlias('GroupManager', \OCP\IGroupManager::class);
300
-
301
-		$this->registerService(Store::class, function (Server $c) {
302
-			$session = $c->getSession();
303
-			if (\OC::$server->getSystemConfig()->getValue('installed', false)) {
304
-				$tokenProvider = $c->query('OC\Authentication\Token\IProvider');
305
-			} else {
306
-				$tokenProvider = null;
307
-			}
308
-			$logger = $c->getLogger();
309
-			return new Store($session, $logger, $tokenProvider);
310
-		});
311
-		$this->registerAlias(IStore::class, Store::class);
312
-		$this->registerService('OC\Authentication\Token\DefaultTokenMapper', function (Server $c) {
313
-			$dbConnection = $c->getDatabaseConnection();
314
-			return new Authentication\Token\DefaultTokenMapper($dbConnection);
315
-		});
316
-		$this->registerService('OC\Authentication\Token\DefaultTokenProvider', function (Server $c) {
317
-			$mapper = $c->query('OC\Authentication\Token\DefaultTokenMapper');
318
-			$crypto = $c->getCrypto();
319
-			$config = $c->getConfig();
320
-			$logger = $c->getLogger();
321
-			$timeFactory = new TimeFactory();
322
-			return new \OC\Authentication\Token\DefaultTokenProvider($mapper, $crypto, $config, $logger, $timeFactory);
323
-		});
324
-		$this->registerAlias('OC\Authentication\Token\IProvider', 'OC\Authentication\Token\DefaultTokenProvider');
325
-
326
-		$this->registerService(\OCP\IUserSession::class, function (Server $c) {
327
-			$manager = $c->getUserManager();
328
-			$session = new \OC\Session\Memory('');
329
-			$timeFactory = new TimeFactory();
330
-			// Token providers might require a working database. This code
331
-			// might however be called when ownCloud is not yet setup.
332
-			if (\OC::$server->getSystemConfig()->getValue('installed', false)) {
333
-				$defaultTokenProvider = $c->query('OC\Authentication\Token\IProvider');
334
-			} else {
335
-				$defaultTokenProvider = null;
336
-			}
337
-
338
-			$userSession = new \OC\User\Session($manager, $session, $timeFactory, $defaultTokenProvider, $c->getConfig(), $c->getSecureRandom(), $c->getLockdownManager());
339
-			$userSession->listen('\OC\User', 'preCreateUser', function ($uid, $password) {
340
-				\OC_Hook::emit('OC_User', 'pre_createUser', array('run' => true, 'uid' => $uid, 'password' => $password));
341
-			});
342
-			$userSession->listen('\OC\User', 'postCreateUser', function ($user, $password) {
343
-				/** @var $user \OC\User\User */
344
-				\OC_Hook::emit('OC_User', 'post_createUser', array('uid' => $user->getUID(), 'password' => $password));
345
-			});
346
-			$userSession->listen('\OC\User', 'preDelete', function ($user) {
347
-				/** @var $user \OC\User\User */
348
-				\OC_Hook::emit('OC_User', 'pre_deleteUser', array('run' => true, 'uid' => $user->getUID()));
349
-			});
350
-			$userSession->listen('\OC\User', 'postDelete', function ($user) {
351
-				/** @var $user \OC\User\User */
352
-				\OC_Hook::emit('OC_User', 'post_deleteUser', array('uid' => $user->getUID()));
353
-			});
354
-			$userSession->listen('\OC\User', 'preSetPassword', function ($user, $password, $recoveryPassword) {
355
-				/** @var $user \OC\User\User */
356
-				\OC_Hook::emit('OC_User', 'pre_setPassword', array('run' => true, 'uid' => $user->getUID(), 'password' => $password, 'recoveryPassword' => $recoveryPassword));
357
-			});
358
-			$userSession->listen('\OC\User', 'postSetPassword', function ($user, $password, $recoveryPassword) {
359
-				/** @var $user \OC\User\User */
360
-				\OC_Hook::emit('OC_User', 'post_setPassword', array('run' => true, 'uid' => $user->getUID(), 'password' => $password, 'recoveryPassword' => $recoveryPassword));
361
-			});
362
-			$userSession->listen('\OC\User', 'preLogin', function ($uid, $password) {
363
-				\OC_Hook::emit('OC_User', 'pre_login', array('run' => true, 'uid' => $uid, 'password' => $password));
364
-			});
365
-			$userSession->listen('\OC\User', 'postLogin', function ($user, $password) {
366
-				/** @var $user \OC\User\User */
367
-				\OC_Hook::emit('OC_User', 'post_login', array('run' => true, 'uid' => $user->getUID(), 'password' => $password));
368
-			});
369
-			$userSession->listen('\OC\User', 'postRememberedLogin', function ($user, $password) {
370
-				/** @var $user \OC\User\User */
371
-				\OC_Hook::emit('OC_User', 'post_login', array('run' => true, 'uid' => $user->getUID(), 'password' => $password));
372
-			});
373
-			$userSession->listen('\OC\User', 'logout', function () {
374
-				\OC_Hook::emit('OC_User', 'logout', array());
375
-			});
376
-			$userSession->listen('\OC\User', 'changeUser', function ($user, $feature, $value, $oldValue) {
377
-				/** @var $user \OC\User\User */
378
-				\OC_Hook::emit('OC_User', 'changeUser', array('run' => true, 'user' => $user, 'feature' => $feature, 'value' => $value, 'old_value' => $oldValue));
379
-			});
380
-			return $userSession;
381
-		});
382
-		$this->registerAlias('UserSession', \OCP\IUserSession::class);
383
-
384
-		$this->registerService(\OC\Authentication\TwoFactorAuth\Manager::class, function (Server $c) {
385
-			return new \OC\Authentication\TwoFactorAuth\Manager(
386
-				$c->getAppManager(),
387
-				$c->getSession(),
388
-				$c->getConfig(),
389
-				$c->getActivityManager(),
390
-				$c->getLogger(),
391
-				$c->query(\OC\Authentication\Token\IProvider::class),
392
-				$c->query(ITimeFactory::class)
393
-			);
394
-		});
395
-
396
-		$this->registerAlias(\OCP\INavigationManager::class, \OC\NavigationManager::class);
397
-		$this->registerAlias('NavigationManager', \OCP\INavigationManager::class);
398
-
399
-		$this->registerService(\OC\AllConfig::class, function (Server $c) {
400
-			return new \OC\AllConfig(
401
-				$c->getSystemConfig()
402
-			);
403
-		});
404
-		$this->registerAlias('AllConfig', \OC\AllConfig::class);
405
-		$this->registerAlias(\OCP\IConfig::class, \OC\AllConfig::class);
406
-
407
-		$this->registerService('SystemConfig', function ($c) use ($config) {
408
-			return new \OC\SystemConfig($config);
409
-		});
410
-
411
-		$this->registerService(\OC\AppConfig::class, function (Server $c) {
412
-			return new \OC\AppConfig($c->getDatabaseConnection());
413
-		});
414
-		$this->registerAlias('AppConfig', \OC\AppConfig::class);
415
-		$this->registerAlias(\OCP\IAppConfig::class, \OC\AppConfig::class);
416
-
417
-		$this->registerService(\OCP\L10N\IFactory::class, function (Server $c) {
418
-			return new \OC\L10N\Factory(
419
-				$c->getConfig(),
420
-				$c->getRequest(),
421
-				$c->getUserSession(),
422
-				\OC::$SERVERROOT
423
-			);
424
-		});
425
-		$this->registerAlias('L10NFactory', \OCP\L10N\IFactory::class);
426
-
427
-		$this->registerService(\OCP\IURLGenerator::class, function (Server $c) {
428
-			$config = $c->getConfig();
429
-			$cacheFactory = $c->getMemCacheFactory();
430
-			$request = $c->getRequest();
431
-			return new \OC\URLGenerator(
432
-				$config,
433
-				$cacheFactory,
434
-				$request
435
-			);
436
-		});
437
-		$this->registerAlias('URLGenerator', \OCP\IURLGenerator::class);
438
-
439
-		$this->registerService('AppHelper', function ($c) {
440
-			return new \OC\AppHelper();
441
-		});
442
-		$this->registerAlias('AppFetcher', AppFetcher::class);
443
-		$this->registerAlias('CategoryFetcher', CategoryFetcher::class);
444
-
445
-		$this->registerService(\OCP\ICache::class, function ($c) {
446
-			return new Cache\File();
447
-		});
448
-		$this->registerAlias('UserCache', \OCP\ICache::class);
449
-
450
-		$this->registerService(Factory::class, function (Server $c) {
451
-
452
-			$arrayCacheFactory = new \OC\Memcache\Factory('', $c->getLogger(),
453
-				'\\OC\\Memcache\\ArrayCache',
454
-				'\\OC\\Memcache\\ArrayCache',
455
-				'\\OC\\Memcache\\ArrayCache'
456
-			);
457
-			$config = $c->getConfig();
458
-			$request = $c->getRequest();
459
-			$urlGenerator = new URLGenerator($config, $arrayCacheFactory, $request);
460
-
461
-			if ($config->getSystemValue('installed', false) && !(defined('PHPUNIT_RUN') && PHPUNIT_RUN)) {
462
-				$v = \OC_App::getAppVersions();
463
-				$v['core'] = implode(',', \OC_Util::getVersion());
464
-				$version = implode(',', $v);
465
-				$instanceId = \OC_Util::getInstanceId();
466
-				$path = \OC::$SERVERROOT;
467
-				$prefix = md5($instanceId . '-' . $version . '-' . $path . '-' . $urlGenerator->getBaseUrl());
468
-				return new \OC\Memcache\Factory($prefix, $c->getLogger(),
469
-					$config->getSystemValue('memcache.local', null),
470
-					$config->getSystemValue('memcache.distributed', null),
471
-					$config->getSystemValue('memcache.locking', null)
472
-				);
473
-			}
474
-			return $arrayCacheFactory;
475
-
476
-		});
477
-		$this->registerAlias('MemCacheFactory', Factory::class);
478
-		$this->registerAlias(ICacheFactory::class, Factory::class);
479
-
480
-		$this->registerService('RedisFactory', function (Server $c) {
481
-			$systemConfig = $c->getSystemConfig();
482
-			return new RedisFactory($systemConfig);
483
-		});
484
-
485
-		$this->registerService(\OCP\Activity\IManager::class, function (Server $c) {
486
-			return new \OC\Activity\Manager(
487
-				$c->getRequest(),
488
-				$c->getUserSession(),
489
-				$c->getConfig(),
490
-				$c->query(IValidator::class)
491
-			);
492
-		});
493
-		$this->registerAlias('ActivityManager', \OCP\Activity\IManager::class);
494
-
495
-		$this->registerService(\OCP\Activity\IEventMerger::class, function (Server $c) {
496
-			return new \OC\Activity\EventMerger(
497
-				$c->getL10N('lib')
498
-			);
499
-		});
500
-		$this->registerAlias(IValidator::class, Validator::class);
501
-
502
-		$this->registerService(\OCP\IAvatarManager::class, function (Server $c) {
503
-			return new AvatarManager(
504
-				$c->getUserManager(),
505
-				$c->getAppDataDir('avatar'),
506
-				$c->getL10N('lib'),
507
-				$c->getLogger(),
508
-				$c->getConfig()
509
-			);
510
-		});
511
-		$this->registerAlias('AvatarManager', \OCP\IAvatarManager::class);
512
-
513
-		$this->registerService(\OCP\ILogger::class, function (Server $c) {
514
-			$logType = $c->query('AllConfig')->getSystemValue('log_type', 'file');
515
-			$logger = Log::getLogClass($logType);
516
-			call_user_func(array($logger, 'init'));
517
-
518
-			return new Log($logger);
519
-		});
520
-		$this->registerAlias('Logger', \OCP\ILogger::class);
521
-
522
-		$this->registerService(\OCP\BackgroundJob\IJobList::class, function (Server $c) {
523
-			$config = $c->getConfig();
524
-			return new \OC\BackgroundJob\JobList(
525
-				$c->getDatabaseConnection(),
526
-				$config,
527
-				new TimeFactory()
528
-			);
529
-		});
530
-		$this->registerAlias('JobList', \OCP\BackgroundJob\IJobList::class);
531
-
532
-		$this->registerService(\OCP\Route\IRouter::class, function (Server $c) {
533
-			$cacheFactory = $c->getMemCacheFactory();
534
-			$logger = $c->getLogger();
535
-			if ($cacheFactory->isAvailableLowLatency()) {
536
-				$router = new \OC\Route\CachingRouter($cacheFactory->createLocal('route'), $logger);
537
-			} else {
538
-				$router = new \OC\Route\Router($logger);
539
-			}
540
-			return $router;
541
-		});
542
-		$this->registerAlias('Router', \OCP\Route\IRouter::class);
543
-
544
-		$this->registerService(\OCP\ISearch::class, function ($c) {
545
-			return new Search();
546
-		});
547
-		$this->registerAlias('Search', \OCP\ISearch::class);
548
-
549
-		$this->registerService(\OC\Security\RateLimiting\Limiter::class, function ($c) {
550
-			return new \OC\Security\RateLimiting\Limiter(
551
-				$this->getUserSession(),
552
-				$this->getRequest(),
553
-				new \OC\AppFramework\Utility\TimeFactory(),
554
-				$c->query(\OC\Security\RateLimiting\Backend\IBackend::class)
555
-			);
556
-		});
557
-		$this->registerService(\OC\Security\RateLimiting\Backend\IBackend::class, function ($c) {
558
-			return new \OC\Security\RateLimiting\Backend\MemoryCache(
559
-				$this->getMemCacheFactory(),
560
-				new \OC\AppFramework\Utility\TimeFactory()
561
-			);
562
-		});
563
-
564
-		$this->registerService(\OCP\Security\ISecureRandom::class, function ($c) {
565
-			return new SecureRandom();
566
-		});
567
-		$this->registerAlias('SecureRandom', \OCP\Security\ISecureRandom::class);
568
-
569
-		$this->registerService(\OCP\Security\ICrypto::class, function (Server $c) {
570
-			return new Crypto($c->getConfig(), $c->getSecureRandom());
571
-		});
572
-		$this->registerAlias('Crypto', \OCP\Security\ICrypto::class);
573
-
574
-		$this->registerService(\OCP\Security\IHasher::class, function (Server $c) {
575
-			return new Hasher($c->getConfig());
576
-		});
577
-		$this->registerAlias('Hasher', \OCP\Security\IHasher::class);
578
-
579
-		$this->registerService(\OCP\Security\ICredentialsManager::class, function (Server $c) {
580
-			return new CredentialsManager($c->getCrypto(), $c->getDatabaseConnection());
581
-		});
582
-		$this->registerAlias('CredentialsManager', \OCP\Security\ICredentialsManager::class);
583
-
584
-		$this->registerService(IDBConnection::class, function (Server $c) {
585
-			$systemConfig = $c->getSystemConfig();
586
-			$factory = new \OC\DB\ConnectionFactory($systemConfig);
587
-			$type = $systemConfig->getValue('dbtype', 'sqlite');
588
-			if (!$factory->isValidType($type)) {
589
-				throw new \OC\DatabaseException('Invalid database type');
590
-			}
591
-			$connectionParams = $factory->createConnectionParams();
592
-			$connection = $factory->getConnection($type, $connectionParams);
593
-			$connection->getConfiguration()->setSQLLogger($c->getQueryLogger());
594
-			return $connection;
595
-		});
596
-		$this->registerAlias('DatabaseConnection', IDBConnection::class);
597
-
598
-		$this->registerService('HTTPHelper', function (Server $c) {
599
-			$config = $c->getConfig();
600
-			return new HTTPHelper(
601
-				$config,
602
-				$c->getHTTPClientService()
603
-			);
604
-		});
605
-
606
-		$this->registerService(\OCP\Http\Client\IClientService::class, function (Server $c) {
607
-			$user = \OC_User::getUser();
608
-			$uid = $user ? $user : null;
609
-			return new ClientService(
610
-				$c->getConfig(),
611
-				new \OC\Security\CertificateManager(
612
-					$uid,
613
-					new View(),
614
-					$c->getConfig(),
615
-					$c->getLogger(),
616
-					$c->getSecureRandom()
617
-				)
618
-			);
619
-		});
620
-		$this->registerAlias('HttpClientService', \OCP\Http\Client\IClientService::class);
621
-		$this->registerService(\OCP\Diagnostics\IEventLogger::class, function (Server $c) {
622
-			$eventLogger = new EventLogger();
623
-			if ($c->getSystemConfig()->getValue('debug', false)) {
624
-				// In debug mode, module is being activated by default
625
-				$eventLogger->activate();
626
-			}
627
-			return $eventLogger;
628
-		});
629
-		$this->registerAlias('EventLogger', \OCP\Diagnostics\IEventLogger::class);
630
-
631
-		$this->registerService(\OCP\Diagnostics\IQueryLogger::class, function (Server $c) {
632
-			$queryLogger = new QueryLogger();
633
-			if ($c->getSystemConfig()->getValue('debug', false)) {
634
-				// In debug mode, module is being activated by default
635
-				$queryLogger->activate();
636
-			}
637
-			return $queryLogger;
638
-		});
639
-		$this->registerAlias('QueryLogger', \OCP\Diagnostics\IQueryLogger::class);
640
-
641
-		$this->registerService(TempManager::class, function (Server $c) {
642
-			return new TempManager(
643
-				$c->getLogger(),
644
-				$c->getConfig()
645
-			);
646
-		});
647
-		$this->registerAlias('TempManager', TempManager::class);
648
-		$this->registerAlias(ITempManager::class, TempManager::class);
649
-
650
-		$this->registerService(AppManager::class, function (Server $c) {
651
-			return new \OC\App\AppManager(
652
-				$c->getUserSession(),
653
-				$c->getAppConfig(),
654
-				$c->getGroupManager(),
655
-				$c->getMemCacheFactory(),
656
-				$c->getEventDispatcher()
657
-			);
658
-		});
659
-		$this->registerAlias('AppManager', AppManager::class);
660
-		$this->registerAlias(IAppManager::class, AppManager::class);
661
-
662
-		$this->registerService(\OCP\IDateTimeZone::class, function (Server $c) {
663
-			return new DateTimeZone(
664
-				$c->getConfig(),
665
-				$c->getSession()
666
-			);
667
-		});
668
-		$this->registerAlias('DateTimeZone', \OCP\IDateTimeZone::class);
669
-
670
-		$this->registerService(\OCP\IDateTimeFormatter::class, function (Server $c) {
671
-			$language = $c->getConfig()->getUserValue($c->getSession()->get('user_id'), 'core', 'lang', null);
672
-
673
-			return new DateTimeFormatter(
674
-				$c->getDateTimeZone()->getTimeZone(),
675
-				$c->getL10N('lib', $language)
676
-			);
677
-		});
678
-		$this->registerAlias('DateTimeFormatter', \OCP\IDateTimeFormatter::class);
679
-
680
-		$this->registerService(\OCP\Files\Config\IUserMountCache::class, function (Server $c) {
681
-			$mountCache = new UserMountCache($c->getDatabaseConnection(), $c->getUserManager(), $c->getLogger());
682
-			$listener = new UserMountCacheListener($mountCache);
683
-			$listener->listen($c->getUserManager());
684
-			return $mountCache;
685
-		});
686
-		$this->registerAlias('UserMountCache', \OCP\Files\Config\IUserMountCache::class);
687
-
688
-		$this->registerService(\OCP\Files\Config\IMountProviderCollection::class, function (Server $c) {
689
-			$loader = \OC\Files\Filesystem::getLoader();
690
-			$mountCache = $c->query('UserMountCache');
691
-			$manager = new \OC\Files\Config\MountProviderCollection($loader, $mountCache);
692
-
693
-			// builtin providers
694
-
695
-			$config = $c->getConfig();
696
-			$manager->registerProvider(new CacheMountProvider($config));
697
-			$manager->registerHomeProvider(new LocalHomeMountProvider());
698
-			$manager->registerHomeProvider(new ObjectHomeMountProvider($config));
699
-
700
-			return $manager;
701
-		});
702
-		$this->registerAlias('MountConfigManager', \OCP\Files\Config\IMountProviderCollection::class);
703
-
704
-		$this->registerService('IniWrapper', function ($c) {
705
-			return new IniGetWrapper();
706
-		});
707
-		$this->registerService('AsyncCommandBus', function (Server $c) {
708
-			$busClass = $c->getConfig()->getSystemValue('commandbus');
709
-			if ($busClass) {
710
-				list($app, $class) = explode('::', $busClass, 2);
711
-				if ($c->getAppManager()->isInstalled($app)) {
712
-					\OC_App::loadApp($app);
713
-					return $c->query($class);
714
-				} else {
715
-					throw new ServiceUnavailableException("The app providing the command bus ($app) is not enabled");
716
-				}
717
-			} else {
718
-				$jobList = $c->getJobList();
719
-				return new CronBus($jobList);
720
-			}
721
-		});
722
-		$this->registerService('TrustedDomainHelper', function ($c) {
723
-			return new TrustedDomainHelper($this->getConfig());
724
-		});
725
-		$this->registerService('Throttler', function (Server $c) {
726
-			return new Throttler(
727
-				$c->getDatabaseConnection(),
728
-				new TimeFactory(),
729
-				$c->getLogger(),
730
-				$c->getConfig()
731
-			);
732
-		});
733
-		$this->registerService('IntegrityCodeChecker', function (Server $c) {
734
-			// IConfig and IAppManager requires a working database. This code
735
-			// might however be called when ownCloud is not yet setup.
736
-			if (\OC::$server->getSystemConfig()->getValue('installed', false)) {
737
-				$config = $c->getConfig();
738
-				$appManager = $c->getAppManager();
739
-			} else {
740
-				$config = null;
741
-				$appManager = null;
742
-			}
743
-
744
-			return new Checker(
745
-				new EnvironmentHelper(),
746
-				new FileAccessHelper(),
747
-				new AppLocator(),
748
-				$config,
749
-				$c->getMemCacheFactory(),
750
-				$appManager,
751
-				$c->getTempManager()
752
-			);
753
-		});
754
-		$this->registerService(\OCP\IRequest::class, function ($c) {
755
-			if (isset($this['urlParams'])) {
756
-				$urlParams = $this['urlParams'];
757
-			} else {
758
-				$urlParams = [];
759
-			}
760
-
761
-			if (defined('PHPUNIT_RUN') && PHPUNIT_RUN
762
-				&& in_array('fakeinput', stream_get_wrappers())
763
-			) {
764
-				$stream = 'fakeinput://data';
765
-			} else {
766
-				$stream = 'php://input';
767
-			}
768
-
769
-			return new Request(
770
-				[
771
-					'get' => $_GET,
772
-					'post' => $_POST,
773
-					'files' => $_FILES,
774
-					'server' => $_SERVER,
775
-					'env' => $_ENV,
776
-					'cookies' => $_COOKIE,
777
-					'method' => (isset($_SERVER) && isset($_SERVER['REQUEST_METHOD']))
778
-						? $_SERVER['REQUEST_METHOD']
779
-						: null,
780
-					'urlParams' => $urlParams,
781
-				],
782
-				$this->getSecureRandom(),
783
-				$this->getConfig(),
784
-				$this->getCsrfTokenManager(),
785
-				$stream
786
-			);
787
-		});
788
-		$this->registerAlias('Request', \OCP\IRequest::class);
789
-
790
-		$this->registerService(\OCP\Mail\IMailer::class, function (Server $c) {
791
-			return new Mailer(
792
-				$c->getConfig(),
793
-				$c->getLogger(),
794
-				$c->query(Defaults::class),
795
-				$c->getURLGenerator(),
796
-				$c->getL10N('lib')
797
-			);
798
-		});
799
-		$this->registerAlias('Mailer', \OCP\Mail\IMailer::class);
800
-
801
-		$this->registerService('LDAPProvider', function (Server $c) {
802
-			$config = $c->getConfig();
803
-			$factoryClass = $config->getSystemValue('ldapProviderFactory', null);
804
-			if (is_null($factoryClass)) {
805
-				throw new \Exception('ldapProviderFactory not set');
806
-			}
807
-			/** @var \OCP\LDAP\ILDAPProviderFactory $factory */
808
-			$factory = new $factoryClass($this);
809
-			return $factory->getLDAPProvider();
810
-		});
811
-		$this->registerService(ILockingProvider::class, function (Server $c) {
812
-			$ini = $c->getIniWrapper();
813
-			$config = $c->getConfig();
814
-			$ttl = $config->getSystemValue('filelocking.ttl', max(3600, $ini->getNumeric('max_execution_time')));
815
-			if ($config->getSystemValue('filelocking.enabled', true) or (defined('PHPUNIT_RUN') && PHPUNIT_RUN)) {
816
-				/** @var \OC\Memcache\Factory $memcacheFactory */
817
-				$memcacheFactory = $c->getMemCacheFactory();
818
-				$memcache = $memcacheFactory->createLocking('lock');
819
-				if (!($memcache instanceof \OC\Memcache\NullCache)) {
820
-					return new MemcacheLockingProvider($memcache, $ttl);
821
-				}
822
-				return new DBLockingProvider($c->getDatabaseConnection(), $c->getLogger(), new TimeFactory(), $ttl);
823
-			}
824
-			return new NoopLockingProvider();
825
-		});
826
-		$this->registerAlias('LockingProvider', ILockingProvider::class);
827
-
828
-		$this->registerService(\OCP\Files\Mount\IMountManager::class, function () {
829
-			return new \OC\Files\Mount\Manager();
830
-		});
831
-		$this->registerAlias('MountManager', \OCP\Files\Mount\IMountManager::class);
832
-
833
-		$this->registerService(\OCP\Files\IMimeTypeDetector::class, function (Server $c) {
834
-			return new \OC\Files\Type\Detection(
835
-				$c->getURLGenerator(),
836
-				\OC::$configDir,
837
-				\OC::$SERVERROOT . '/resources/config/'
838
-			);
839
-		});
840
-		$this->registerAlias('MimeTypeDetector', \OCP\Files\IMimeTypeDetector::class);
841
-
842
-		$this->registerService(\OCP\Files\IMimeTypeLoader::class, function (Server $c) {
843
-			return new \OC\Files\Type\Loader(
844
-				$c->getDatabaseConnection()
845
-			);
846
-		});
847
-		$this->registerAlias('MimeTypeLoader', \OCP\Files\IMimeTypeLoader::class);
848
-		$this->registerService(BundleFetcher::class, function () {
849
-			return new BundleFetcher($this->getL10N('lib'));
850
-		});
851
-		$this->registerService(\OCP\Notification\IManager::class, function (Server $c) {
852
-			return new Manager(
853
-				$c->query(IValidator::class)
854
-			);
855
-		});
856
-		$this->registerAlias('NotificationManager', \OCP\Notification\IManager::class);
857
-
858
-		$this->registerService(\OC\CapabilitiesManager::class, function (Server $c) {
859
-			$manager = new \OC\CapabilitiesManager($c->getLogger());
860
-			$manager->registerCapability(function () use ($c) {
861
-				return new \OC\OCS\CoreCapabilities($c->getConfig());
862
-			});
863
-			$manager->registerCapability(function () use ($c) {
864
-				return $c->query(\OC\Security\Bruteforce\Capabilities::class);
865
-			});
866
-			return $manager;
867
-		});
868
-		$this->registerAlias('CapabilitiesManager', \OC\CapabilitiesManager::class);
869
-
870
-		$this->registerService(\OCP\Comments\ICommentsManager::class, function (Server $c) {
871
-			$config = $c->getConfig();
872
-			$factoryClass = $config->getSystemValue('comments.managerFactory', '\OC\Comments\ManagerFactory');
873
-			/** @var \OCP\Comments\ICommentsManagerFactory $factory */
874
-			$factory = new $factoryClass($this);
875
-			return $factory->getManager();
876
-		});
877
-		$this->registerAlias('CommentsManager', \OCP\Comments\ICommentsManager::class);
878
-
879
-		$this->registerService('ThemingDefaults', function (Server $c) {
880
-			/*
135
+    /** @var string */
136
+    private $webRoot;
137
+
138
+    /**
139
+     * @param string $webRoot
140
+     * @param \OC\Config $config
141
+     */
142
+    public function __construct($webRoot, \OC\Config $config) {
143
+        parent::__construct();
144
+        $this->webRoot = $webRoot;
145
+
146
+        $this->registerService(\OCP\IServerContainer::class, function (IServerContainer $c) {
147
+            return $c;
148
+        });
149
+
150
+        $this->registerAlias(\OCP\Contacts\IManager::class, \OC\ContactsManager::class);
151
+        $this->registerAlias('ContactsManager', \OCP\Contacts\IManager::class);
152
+
153
+        $this->registerAlias(IActionFactory::class, ActionFactory::class);
154
+
155
+
156
+        $this->registerService(\OCP\IPreview::class, function (Server $c) {
157
+            return new PreviewManager(
158
+                $c->getConfig(),
159
+                $c->getRootFolder(),
160
+                $c->getAppDataDir('preview'),
161
+                $c->getEventDispatcher(),
162
+                $c->getSession()->get('user_id')
163
+            );
164
+        });
165
+        $this->registerAlias('PreviewManager', \OCP\IPreview::class);
166
+
167
+        $this->registerService(\OC\Preview\Watcher::class, function (Server $c) {
168
+            return new \OC\Preview\Watcher(
169
+                $c->getAppDataDir('preview')
170
+            );
171
+        });
172
+
173
+        $this->registerService('EncryptionManager', function (Server $c) {
174
+            $view = new View();
175
+            $util = new Encryption\Util(
176
+                $view,
177
+                $c->getUserManager(),
178
+                $c->getGroupManager(),
179
+                $c->getConfig()
180
+            );
181
+            return new Encryption\Manager(
182
+                $c->getConfig(),
183
+                $c->getLogger(),
184
+                $c->getL10N('core'),
185
+                new View(),
186
+                $util,
187
+                new ArrayCache()
188
+            );
189
+        });
190
+
191
+        $this->registerService('EncryptionFileHelper', function (Server $c) {
192
+            $util = new Encryption\Util(
193
+                new View(),
194
+                $c->getUserManager(),
195
+                $c->getGroupManager(),
196
+                $c->getConfig()
197
+            );
198
+            return new Encryption\File(
199
+                $util,
200
+                $c->getRootFolder(),
201
+                $c->getShareManager()
202
+            );
203
+        });
204
+
205
+        $this->registerService('EncryptionKeyStorage', function (Server $c) {
206
+            $view = new View();
207
+            $util = new Encryption\Util(
208
+                $view,
209
+                $c->getUserManager(),
210
+                $c->getGroupManager(),
211
+                $c->getConfig()
212
+            );
213
+
214
+            return new Encryption\Keys\Storage($view, $util);
215
+        });
216
+        $this->registerService('TagMapper', function (Server $c) {
217
+            return new TagMapper($c->getDatabaseConnection());
218
+        });
219
+
220
+        $this->registerService(\OCP\ITagManager::class, function (Server $c) {
221
+            $tagMapper = $c->query('TagMapper');
222
+            return new TagManager($tagMapper, $c->getUserSession());
223
+        });
224
+        $this->registerAlias('TagManager', \OCP\ITagManager::class);
225
+
226
+        $this->registerService('SystemTagManagerFactory', function (Server $c) {
227
+            $config = $c->getConfig();
228
+            $factoryClass = $config->getSystemValue('systemtags.managerFactory', '\OC\SystemTag\ManagerFactory');
229
+            /** @var \OC\SystemTag\ManagerFactory $factory */
230
+            $factory = new $factoryClass($this);
231
+            return $factory;
232
+        });
233
+        $this->registerService(\OCP\SystemTag\ISystemTagManager::class, function (Server $c) {
234
+            return $c->query('SystemTagManagerFactory')->getManager();
235
+        });
236
+        $this->registerAlias('SystemTagManager', \OCP\SystemTag\ISystemTagManager::class);
237
+
238
+        $this->registerService(\OCP\SystemTag\ISystemTagObjectMapper::class, function (Server $c) {
239
+            return $c->query('SystemTagManagerFactory')->getObjectMapper();
240
+        });
241
+        $this->registerService('RootFolder', function (Server $c) {
242
+            $manager = \OC\Files\Filesystem::getMountManager(null);
243
+            $view = new View();
244
+            $root = new Root(
245
+                $manager,
246
+                $view,
247
+                null,
248
+                $c->getUserMountCache(),
249
+                $this->getLogger(),
250
+                $this->getUserManager()
251
+            );
252
+            $connector = new HookConnector($root, $view);
253
+            $connector->viewToNode();
254
+
255
+            $previewConnector = new \OC\Preview\WatcherConnector($root, $c->getSystemConfig());
256
+            $previewConnector->connectWatcher();
257
+
258
+            return $root;
259
+        });
260
+        $this->registerAlias('SystemTagObjectMapper', \OCP\SystemTag\ISystemTagObjectMapper::class);
261
+
262
+        $this->registerService(\OCP\Files\IRootFolder::class, function (Server $c) {
263
+            return new LazyRoot(function () use ($c) {
264
+                return $c->query('RootFolder');
265
+            });
266
+        });
267
+        $this->registerAlias('LazyRootFolder', \OCP\Files\IRootFolder::class);
268
+
269
+        $this->registerService(\OCP\IUserManager::class, function (Server $c) {
270
+            $config = $c->getConfig();
271
+            return new \OC\User\Manager($config);
272
+        });
273
+        $this->registerAlias('UserManager', \OCP\IUserManager::class);
274
+
275
+        $this->registerService(\OCP\IGroupManager::class, function (Server $c) {
276
+            $groupManager = new \OC\Group\Manager($this->getUserManager(), $this->getLogger());
277
+            $groupManager->listen('\OC\Group', 'preCreate', function ($gid) {
278
+                \OC_Hook::emit('OC_Group', 'pre_createGroup', array('run' => true, 'gid' => $gid));
279
+            });
280
+            $groupManager->listen('\OC\Group', 'postCreate', function (\OC\Group\Group $gid) {
281
+                \OC_Hook::emit('OC_User', 'post_createGroup', array('gid' => $gid->getGID()));
282
+            });
283
+            $groupManager->listen('\OC\Group', 'preDelete', function (\OC\Group\Group $group) {
284
+                \OC_Hook::emit('OC_Group', 'pre_deleteGroup', array('run' => true, 'gid' => $group->getGID()));
285
+            });
286
+            $groupManager->listen('\OC\Group', 'postDelete', function (\OC\Group\Group $group) {
287
+                \OC_Hook::emit('OC_User', 'post_deleteGroup', array('gid' => $group->getGID()));
288
+            });
289
+            $groupManager->listen('\OC\Group', 'preAddUser', function (\OC\Group\Group $group, \OC\User\User $user) {
290
+                \OC_Hook::emit('OC_Group', 'pre_addToGroup', array('run' => true, 'uid' => $user->getUID(), 'gid' => $group->getGID()));
291
+            });
292
+            $groupManager->listen('\OC\Group', 'postAddUser', function (\OC\Group\Group $group, \OC\User\User $user) {
293
+                \OC_Hook::emit('OC_Group', 'post_addToGroup', array('uid' => $user->getUID(), 'gid' => $group->getGID()));
294
+                //Minimal fix to keep it backward compatible TODO: clean up all the GroupManager hooks
295
+                \OC_Hook::emit('OC_User', 'post_addToGroup', array('uid' => $user->getUID(), 'gid' => $group->getGID()));
296
+            });
297
+            return $groupManager;
298
+        });
299
+        $this->registerAlias('GroupManager', \OCP\IGroupManager::class);
300
+
301
+        $this->registerService(Store::class, function (Server $c) {
302
+            $session = $c->getSession();
303
+            if (\OC::$server->getSystemConfig()->getValue('installed', false)) {
304
+                $tokenProvider = $c->query('OC\Authentication\Token\IProvider');
305
+            } else {
306
+                $tokenProvider = null;
307
+            }
308
+            $logger = $c->getLogger();
309
+            return new Store($session, $logger, $tokenProvider);
310
+        });
311
+        $this->registerAlias(IStore::class, Store::class);
312
+        $this->registerService('OC\Authentication\Token\DefaultTokenMapper', function (Server $c) {
313
+            $dbConnection = $c->getDatabaseConnection();
314
+            return new Authentication\Token\DefaultTokenMapper($dbConnection);
315
+        });
316
+        $this->registerService('OC\Authentication\Token\DefaultTokenProvider', function (Server $c) {
317
+            $mapper = $c->query('OC\Authentication\Token\DefaultTokenMapper');
318
+            $crypto = $c->getCrypto();
319
+            $config = $c->getConfig();
320
+            $logger = $c->getLogger();
321
+            $timeFactory = new TimeFactory();
322
+            return new \OC\Authentication\Token\DefaultTokenProvider($mapper, $crypto, $config, $logger, $timeFactory);
323
+        });
324
+        $this->registerAlias('OC\Authentication\Token\IProvider', 'OC\Authentication\Token\DefaultTokenProvider');
325
+
326
+        $this->registerService(\OCP\IUserSession::class, function (Server $c) {
327
+            $manager = $c->getUserManager();
328
+            $session = new \OC\Session\Memory('');
329
+            $timeFactory = new TimeFactory();
330
+            // Token providers might require a working database. This code
331
+            // might however be called when ownCloud is not yet setup.
332
+            if (\OC::$server->getSystemConfig()->getValue('installed', false)) {
333
+                $defaultTokenProvider = $c->query('OC\Authentication\Token\IProvider');
334
+            } else {
335
+                $defaultTokenProvider = null;
336
+            }
337
+
338
+            $userSession = new \OC\User\Session($manager, $session, $timeFactory, $defaultTokenProvider, $c->getConfig(), $c->getSecureRandom(), $c->getLockdownManager());
339
+            $userSession->listen('\OC\User', 'preCreateUser', function ($uid, $password) {
340
+                \OC_Hook::emit('OC_User', 'pre_createUser', array('run' => true, 'uid' => $uid, 'password' => $password));
341
+            });
342
+            $userSession->listen('\OC\User', 'postCreateUser', function ($user, $password) {
343
+                /** @var $user \OC\User\User */
344
+                \OC_Hook::emit('OC_User', 'post_createUser', array('uid' => $user->getUID(), 'password' => $password));
345
+            });
346
+            $userSession->listen('\OC\User', 'preDelete', function ($user) {
347
+                /** @var $user \OC\User\User */
348
+                \OC_Hook::emit('OC_User', 'pre_deleteUser', array('run' => true, 'uid' => $user->getUID()));
349
+            });
350
+            $userSession->listen('\OC\User', 'postDelete', function ($user) {
351
+                /** @var $user \OC\User\User */
352
+                \OC_Hook::emit('OC_User', 'post_deleteUser', array('uid' => $user->getUID()));
353
+            });
354
+            $userSession->listen('\OC\User', 'preSetPassword', function ($user, $password, $recoveryPassword) {
355
+                /** @var $user \OC\User\User */
356
+                \OC_Hook::emit('OC_User', 'pre_setPassword', array('run' => true, 'uid' => $user->getUID(), 'password' => $password, 'recoveryPassword' => $recoveryPassword));
357
+            });
358
+            $userSession->listen('\OC\User', 'postSetPassword', function ($user, $password, $recoveryPassword) {
359
+                /** @var $user \OC\User\User */
360
+                \OC_Hook::emit('OC_User', 'post_setPassword', array('run' => true, 'uid' => $user->getUID(), 'password' => $password, 'recoveryPassword' => $recoveryPassword));
361
+            });
362
+            $userSession->listen('\OC\User', 'preLogin', function ($uid, $password) {
363
+                \OC_Hook::emit('OC_User', 'pre_login', array('run' => true, 'uid' => $uid, 'password' => $password));
364
+            });
365
+            $userSession->listen('\OC\User', 'postLogin', function ($user, $password) {
366
+                /** @var $user \OC\User\User */
367
+                \OC_Hook::emit('OC_User', 'post_login', array('run' => true, 'uid' => $user->getUID(), 'password' => $password));
368
+            });
369
+            $userSession->listen('\OC\User', 'postRememberedLogin', function ($user, $password) {
370
+                /** @var $user \OC\User\User */
371
+                \OC_Hook::emit('OC_User', 'post_login', array('run' => true, 'uid' => $user->getUID(), 'password' => $password));
372
+            });
373
+            $userSession->listen('\OC\User', 'logout', function () {
374
+                \OC_Hook::emit('OC_User', 'logout', array());
375
+            });
376
+            $userSession->listen('\OC\User', 'changeUser', function ($user, $feature, $value, $oldValue) {
377
+                /** @var $user \OC\User\User */
378
+                \OC_Hook::emit('OC_User', 'changeUser', array('run' => true, 'user' => $user, 'feature' => $feature, 'value' => $value, 'old_value' => $oldValue));
379
+            });
380
+            return $userSession;
381
+        });
382
+        $this->registerAlias('UserSession', \OCP\IUserSession::class);
383
+
384
+        $this->registerService(\OC\Authentication\TwoFactorAuth\Manager::class, function (Server $c) {
385
+            return new \OC\Authentication\TwoFactorAuth\Manager(
386
+                $c->getAppManager(),
387
+                $c->getSession(),
388
+                $c->getConfig(),
389
+                $c->getActivityManager(),
390
+                $c->getLogger(),
391
+                $c->query(\OC\Authentication\Token\IProvider::class),
392
+                $c->query(ITimeFactory::class)
393
+            );
394
+        });
395
+
396
+        $this->registerAlias(\OCP\INavigationManager::class, \OC\NavigationManager::class);
397
+        $this->registerAlias('NavigationManager', \OCP\INavigationManager::class);
398
+
399
+        $this->registerService(\OC\AllConfig::class, function (Server $c) {
400
+            return new \OC\AllConfig(
401
+                $c->getSystemConfig()
402
+            );
403
+        });
404
+        $this->registerAlias('AllConfig', \OC\AllConfig::class);
405
+        $this->registerAlias(\OCP\IConfig::class, \OC\AllConfig::class);
406
+
407
+        $this->registerService('SystemConfig', function ($c) use ($config) {
408
+            return new \OC\SystemConfig($config);
409
+        });
410
+
411
+        $this->registerService(\OC\AppConfig::class, function (Server $c) {
412
+            return new \OC\AppConfig($c->getDatabaseConnection());
413
+        });
414
+        $this->registerAlias('AppConfig', \OC\AppConfig::class);
415
+        $this->registerAlias(\OCP\IAppConfig::class, \OC\AppConfig::class);
416
+
417
+        $this->registerService(\OCP\L10N\IFactory::class, function (Server $c) {
418
+            return new \OC\L10N\Factory(
419
+                $c->getConfig(),
420
+                $c->getRequest(),
421
+                $c->getUserSession(),
422
+                \OC::$SERVERROOT
423
+            );
424
+        });
425
+        $this->registerAlias('L10NFactory', \OCP\L10N\IFactory::class);
426
+
427
+        $this->registerService(\OCP\IURLGenerator::class, function (Server $c) {
428
+            $config = $c->getConfig();
429
+            $cacheFactory = $c->getMemCacheFactory();
430
+            $request = $c->getRequest();
431
+            return new \OC\URLGenerator(
432
+                $config,
433
+                $cacheFactory,
434
+                $request
435
+            );
436
+        });
437
+        $this->registerAlias('URLGenerator', \OCP\IURLGenerator::class);
438
+
439
+        $this->registerService('AppHelper', function ($c) {
440
+            return new \OC\AppHelper();
441
+        });
442
+        $this->registerAlias('AppFetcher', AppFetcher::class);
443
+        $this->registerAlias('CategoryFetcher', CategoryFetcher::class);
444
+
445
+        $this->registerService(\OCP\ICache::class, function ($c) {
446
+            return new Cache\File();
447
+        });
448
+        $this->registerAlias('UserCache', \OCP\ICache::class);
449
+
450
+        $this->registerService(Factory::class, function (Server $c) {
451
+
452
+            $arrayCacheFactory = new \OC\Memcache\Factory('', $c->getLogger(),
453
+                '\\OC\\Memcache\\ArrayCache',
454
+                '\\OC\\Memcache\\ArrayCache',
455
+                '\\OC\\Memcache\\ArrayCache'
456
+            );
457
+            $config = $c->getConfig();
458
+            $request = $c->getRequest();
459
+            $urlGenerator = new URLGenerator($config, $arrayCacheFactory, $request);
460
+
461
+            if ($config->getSystemValue('installed', false) && !(defined('PHPUNIT_RUN') && PHPUNIT_RUN)) {
462
+                $v = \OC_App::getAppVersions();
463
+                $v['core'] = implode(',', \OC_Util::getVersion());
464
+                $version = implode(',', $v);
465
+                $instanceId = \OC_Util::getInstanceId();
466
+                $path = \OC::$SERVERROOT;
467
+                $prefix = md5($instanceId . '-' . $version . '-' . $path . '-' . $urlGenerator->getBaseUrl());
468
+                return new \OC\Memcache\Factory($prefix, $c->getLogger(),
469
+                    $config->getSystemValue('memcache.local', null),
470
+                    $config->getSystemValue('memcache.distributed', null),
471
+                    $config->getSystemValue('memcache.locking', null)
472
+                );
473
+            }
474
+            return $arrayCacheFactory;
475
+
476
+        });
477
+        $this->registerAlias('MemCacheFactory', Factory::class);
478
+        $this->registerAlias(ICacheFactory::class, Factory::class);
479
+
480
+        $this->registerService('RedisFactory', function (Server $c) {
481
+            $systemConfig = $c->getSystemConfig();
482
+            return new RedisFactory($systemConfig);
483
+        });
484
+
485
+        $this->registerService(\OCP\Activity\IManager::class, function (Server $c) {
486
+            return new \OC\Activity\Manager(
487
+                $c->getRequest(),
488
+                $c->getUserSession(),
489
+                $c->getConfig(),
490
+                $c->query(IValidator::class)
491
+            );
492
+        });
493
+        $this->registerAlias('ActivityManager', \OCP\Activity\IManager::class);
494
+
495
+        $this->registerService(\OCP\Activity\IEventMerger::class, function (Server $c) {
496
+            return new \OC\Activity\EventMerger(
497
+                $c->getL10N('lib')
498
+            );
499
+        });
500
+        $this->registerAlias(IValidator::class, Validator::class);
501
+
502
+        $this->registerService(\OCP\IAvatarManager::class, function (Server $c) {
503
+            return new AvatarManager(
504
+                $c->getUserManager(),
505
+                $c->getAppDataDir('avatar'),
506
+                $c->getL10N('lib'),
507
+                $c->getLogger(),
508
+                $c->getConfig()
509
+            );
510
+        });
511
+        $this->registerAlias('AvatarManager', \OCP\IAvatarManager::class);
512
+
513
+        $this->registerService(\OCP\ILogger::class, function (Server $c) {
514
+            $logType = $c->query('AllConfig')->getSystemValue('log_type', 'file');
515
+            $logger = Log::getLogClass($logType);
516
+            call_user_func(array($logger, 'init'));
517
+
518
+            return new Log($logger);
519
+        });
520
+        $this->registerAlias('Logger', \OCP\ILogger::class);
521
+
522
+        $this->registerService(\OCP\BackgroundJob\IJobList::class, function (Server $c) {
523
+            $config = $c->getConfig();
524
+            return new \OC\BackgroundJob\JobList(
525
+                $c->getDatabaseConnection(),
526
+                $config,
527
+                new TimeFactory()
528
+            );
529
+        });
530
+        $this->registerAlias('JobList', \OCP\BackgroundJob\IJobList::class);
531
+
532
+        $this->registerService(\OCP\Route\IRouter::class, function (Server $c) {
533
+            $cacheFactory = $c->getMemCacheFactory();
534
+            $logger = $c->getLogger();
535
+            if ($cacheFactory->isAvailableLowLatency()) {
536
+                $router = new \OC\Route\CachingRouter($cacheFactory->createLocal('route'), $logger);
537
+            } else {
538
+                $router = new \OC\Route\Router($logger);
539
+            }
540
+            return $router;
541
+        });
542
+        $this->registerAlias('Router', \OCP\Route\IRouter::class);
543
+
544
+        $this->registerService(\OCP\ISearch::class, function ($c) {
545
+            return new Search();
546
+        });
547
+        $this->registerAlias('Search', \OCP\ISearch::class);
548
+
549
+        $this->registerService(\OC\Security\RateLimiting\Limiter::class, function ($c) {
550
+            return new \OC\Security\RateLimiting\Limiter(
551
+                $this->getUserSession(),
552
+                $this->getRequest(),
553
+                new \OC\AppFramework\Utility\TimeFactory(),
554
+                $c->query(\OC\Security\RateLimiting\Backend\IBackend::class)
555
+            );
556
+        });
557
+        $this->registerService(\OC\Security\RateLimiting\Backend\IBackend::class, function ($c) {
558
+            return new \OC\Security\RateLimiting\Backend\MemoryCache(
559
+                $this->getMemCacheFactory(),
560
+                new \OC\AppFramework\Utility\TimeFactory()
561
+            );
562
+        });
563
+
564
+        $this->registerService(\OCP\Security\ISecureRandom::class, function ($c) {
565
+            return new SecureRandom();
566
+        });
567
+        $this->registerAlias('SecureRandom', \OCP\Security\ISecureRandom::class);
568
+
569
+        $this->registerService(\OCP\Security\ICrypto::class, function (Server $c) {
570
+            return new Crypto($c->getConfig(), $c->getSecureRandom());
571
+        });
572
+        $this->registerAlias('Crypto', \OCP\Security\ICrypto::class);
573
+
574
+        $this->registerService(\OCP\Security\IHasher::class, function (Server $c) {
575
+            return new Hasher($c->getConfig());
576
+        });
577
+        $this->registerAlias('Hasher', \OCP\Security\IHasher::class);
578
+
579
+        $this->registerService(\OCP\Security\ICredentialsManager::class, function (Server $c) {
580
+            return new CredentialsManager($c->getCrypto(), $c->getDatabaseConnection());
581
+        });
582
+        $this->registerAlias('CredentialsManager', \OCP\Security\ICredentialsManager::class);
583
+
584
+        $this->registerService(IDBConnection::class, function (Server $c) {
585
+            $systemConfig = $c->getSystemConfig();
586
+            $factory = new \OC\DB\ConnectionFactory($systemConfig);
587
+            $type = $systemConfig->getValue('dbtype', 'sqlite');
588
+            if (!$factory->isValidType($type)) {
589
+                throw new \OC\DatabaseException('Invalid database type');
590
+            }
591
+            $connectionParams = $factory->createConnectionParams();
592
+            $connection = $factory->getConnection($type, $connectionParams);
593
+            $connection->getConfiguration()->setSQLLogger($c->getQueryLogger());
594
+            return $connection;
595
+        });
596
+        $this->registerAlias('DatabaseConnection', IDBConnection::class);
597
+
598
+        $this->registerService('HTTPHelper', function (Server $c) {
599
+            $config = $c->getConfig();
600
+            return new HTTPHelper(
601
+                $config,
602
+                $c->getHTTPClientService()
603
+            );
604
+        });
605
+
606
+        $this->registerService(\OCP\Http\Client\IClientService::class, function (Server $c) {
607
+            $user = \OC_User::getUser();
608
+            $uid = $user ? $user : null;
609
+            return new ClientService(
610
+                $c->getConfig(),
611
+                new \OC\Security\CertificateManager(
612
+                    $uid,
613
+                    new View(),
614
+                    $c->getConfig(),
615
+                    $c->getLogger(),
616
+                    $c->getSecureRandom()
617
+                )
618
+            );
619
+        });
620
+        $this->registerAlias('HttpClientService', \OCP\Http\Client\IClientService::class);
621
+        $this->registerService(\OCP\Diagnostics\IEventLogger::class, function (Server $c) {
622
+            $eventLogger = new EventLogger();
623
+            if ($c->getSystemConfig()->getValue('debug', false)) {
624
+                // In debug mode, module is being activated by default
625
+                $eventLogger->activate();
626
+            }
627
+            return $eventLogger;
628
+        });
629
+        $this->registerAlias('EventLogger', \OCP\Diagnostics\IEventLogger::class);
630
+
631
+        $this->registerService(\OCP\Diagnostics\IQueryLogger::class, function (Server $c) {
632
+            $queryLogger = new QueryLogger();
633
+            if ($c->getSystemConfig()->getValue('debug', false)) {
634
+                // In debug mode, module is being activated by default
635
+                $queryLogger->activate();
636
+            }
637
+            return $queryLogger;
638
+        });
639
+        $this->registerAlias('QueryLogger', \OCP\Diagnostics\IQueryLogger::class);
640
+
641
+        $this->registerService(TempManager::class, function (Server $c) {
642
+            return new TempManager(
643
+                $c->getLogger(),
644
+                $c->getConfig()
645
+            );
646
+        });
647
+        $this->registerAlias('TempManager', TempManager::class);
648
+        $this->registerAlias(ITempManager::class, TempManager::class);
649
+
650
+        $this->registerService(AppManager::class, function (Server $c) {
651
+            return new \OC\App\AppManager(
652
+                $c->getUserSession(),
653
+                $c->getAppConfig(),
654
+                $c->getGroupManager(),
655
+                $c->getMemCacheFactory(),
656
+                $c->getEventDispatcher()
657
+            );
658
+        });
659
+        $this->registerAlias('AppManager', AppManager::class);
660
+        $this->registerAlias(IAppManager::class, AppManager::class);
661
+
662
+        $this->registerService(\OCP\IDateTimeZone::class, function (Server $c) {
663
+            return new DateTimeZone(
664
+                $c->getConfig(),
665
+                $c->getSession()
666
+            );
667
+        });
668
+        $this->registerAlias('DateTimeZone', \OCP\IDateTimeZone::class);
669
+
670
+        $this->registerService(\OCP\IDateTimeFormatter::class, function (Server $c) {
671
+            $language = $c->getConfig()->getUserValue($c->getSession()->get('user_id'), 'core', 'lang', null);
672
+
673
+            return new DateTimeFormatter(
674
+                $c->getDateTimeZone()->getTimeZone(),
675
+                $c->getL10N('lib', $language)
676
+            );
677
+        });
678
+        $this->registerAlias('DateTimeFormatter', \OCP\IDateTimeFormatter::class);
679
+
680
+        $this->registerService(\OCP\Files\Config\IUserMountCache::class, function (Server $c) {
681
+            $mountCache = new UserMountCache($c->getDatabaseConnection(), $c->getUserManager(), $c->getLogger());
682
+            $listener = new UserMountCacheListener($mountCache);
683
+            $listener->listen($c->getUserManager());
684
+            return $mountCache;
685
+        });
686
+        $this->registerAlias('UserMountCache', \OCP\Files\Config\IUserMountCache::class);
687
+
688
+        $this->registerService(\OCP\Files\Config\IMountProviderCollection::class, function (Server $c) {
689
+            $loader = \OC\Files\Filesystem::getLoader();
690
+            $mountCache = $c->query('UserMountCache');
691
+            $manager = new \OC\Files\Config\MountProviderCollection($loader, $mountCache);
692
+
693
+            // builtin providers
694
+
695
+            $config = $c->getConfig();
696
+            $manager->registerProvider(new CacheMountProvider($config));
697
+            $manager->registerHomeProvider(new LocalHomeMountProvider());
698
+            $manager->registerHomeProvider(new ObjectHomeMountProvider($config));
699
+
700
+            return $manager;
701
+        });
702
+        $this->registerAlias('MountConfigManager', \OCP\Files\Config\IMountProviderCollection::class);
703
+
704
+        $this->registerService('IniWrapper', function ($c) {
705
+            return new IniGetWrapper();
706
+        });
707
+        $this->registerService('AsyncCommandBus', function (Server $c) {
708
+            $busClass = $c->getConfig()->getSystemValue('commandbus');
709
+            if ($busClass) {
710
+                list($app, $class) = explode('::', $busClass, 2);
711
+                if ($c->getAppManager()->isInstalled($app)) {
712
+                    \OC_App::loadApp($app);
713
+                    return $c->query($class);
714
+                } else {
715
+                    throw new ServiceUnavailableException("The app providing the command bus ($app) is not enabled");
716
+                }
717
+            } else {
718
+                $jobList = $c->getJobList();
719
+                return new CronBus($jobList);
720
+            }
721
+        });
722
+        $this->registerService('TrustedDomainHelper', function ($c) {
723
+            return new TrustedDomainHelper($this->getConfig());
724
+        });
725
+        $this->registerService('Throttler', function (Server $c) {
726
+            return new Throttler(
727
+                $c->getDatabaseConnection(),
728
+                new TimeFactory(),
729
+                $c->getLogger(),
730
+                $c->getConfig()
731
+            );
732
+        });
733
+        $this->registerService('IntegrityCodeChecker', function (Server $c) {
734
+            // IConfig and IAppManager requires a working database. This code
735
+            // might however be called when ownCloud is not yet setup.
736
+            if (\OC::$server->getSystemConfig()->getValue('installed', false)) {
737
+                $config = $c->getConfig();
738
+                $appManager = $c->getAppManager();
739
+            } else {
740
+                $config = null;
741
+                $appManager = null;
742
+            }
743
+
744
+            return new Checker(
745
+                new EnvironmentHelper(),
746
+                new FileAccessHelper(),
747
+                new AppLocator(),
748
+                $config,
749
+                $c->getMemCacheFactory(),
750
+                $appManager,
751
+                $c->getTempManager()
752
+            );
753
+        });
754
+        $this->registerService(\OCP\IRequest::class, function ($c) {
755
+            if (isset($this['urlParams'])) {
756
+                $urlParams = $this['urlParams'];
757
+            } else {
758
+                $urlParams = [];
759
+            }
760
+
761
+            if (defined('PHPUNIT_RUN') && PHPUNIT_RUN
762
+                && in_array('fakeinput', stream_get_wrappers())
763
+            ) {
764
+                $stream = 'fakeinput://data';
765
+            } else {
766
+                $stream = 'php://input';
767
+            }
768
+
769
+            return new Request(
770
+                [
771
+                    'get' => $_GET,
772
+                    'post' => $_POST,
773
+                    'files' => $_FILES,
774
+                    'server' => $_SERVER,
775
+                    'env' => $_ENV,
776
+                    'cookies' => $_COOKIE,
777
+                    'method' => (isset($_SERVER) && isset($_SERVER['REQUEST_METHOD']))
778
+                        ? $_SERVER['REQUEST_METHOD']
779
+                        : null,
780
+                    'urlParams' => $urlParams,
781
+                ],
782
+                $this->getSecureRandom(),
783
+                $this->getConfig(),
784
+                $this->getCsrfTokenManager(),
785
+                $stream
786
+            );
787
+        });
788
+        $this->registerAlias('Request', \OCP\IRequest::class);
789
+
790
+        $this->registerService(\OCP\Mail\IMailer::class, function (Server $c) {
791
+            return new Mailer(
792
+                $c->getConfig(),
793
+                $c->getLogger(),
794
+                $c->query(Defaults::class),
795
+                $c->getURLGenerator(),
796
+                $c->getL10N('lib')
797
+            );
798
+        });
799
+        $this->registerAlias('Mailer', \OCP\Mail\IMailer::class);
800
+
801
+        $this->registerService('LDAPProvider', function (Server $c) {
802
+            $config = $c->getConfig();
803
+            $factoryClass = $config->getSystemValue('ldapProviderFactory', null);
804
+            if (is_null($factoryClass)) {
805
+                throw new \Exception('ldapProviderFactory not set');
806
+            }
807
+            /** @var \OCP\LDAP\ILDAPProviderFactory $factory */
808
+            $factory = new $factoryClass($this);
809
+            return $factory->getLDAPProvider();
810
+        });
811
+        $this->registerService(ILockingProvider::class, function (Server $c) {
812
+            $ini = $c->getIniWrapper();
813
+            $config = $c->getConfig();
814
+            $ttl = $config->getSystemValue('filelocking.ttl', max(3600, $ini->getNumeric('max_execution_time')));
815
+            if ($config->getSystemValue('filelocking.enabled', true) or (defined('PHPUNIT_RUN') && PHPUNIT_RUN)) {
816
+                /** @var \OC\Memcache\Factory $memcacheFactory */
817
+                $memcacheFactory = $c->getMemCacheFactory();
818
+                $memcache = $memcacheFactory->createLocking('lock');
819
+                if (!($memcache instanceof \OC\Memcache\NullCache)) {
820
+                    return new MemcacheLockingProvider($memcache, $ttl);
821
+                }
822
+                return new DBLockingProvider($c->getDatabaseConnection(), $c->getLogger(), new TimeFactory(), $ttl);
823
+            }
824
+            return new NoopLockingProvider();
825
+        });
826
+        $this->registerAlias('LockingProvider', ILockingProvider::class);
827
+
828
+        $this->registerService(\OCP\Files\Mount\IMountManager::class, function () {
829
+            return new \OC\Files\Mount\Manager();
830
+        });
831
+        $this->registerAlias('MountManager', \OCP\Files\Mount\IMountManager::class);
832
+
833
+        $this->registerService(\OCP\Files\IMimeTypeDetector::class, function (Server $c) {
834
+            return new \OC\Files\Type\Detection(
835
+                $c->getURLGenerator(),
836
+                \OC::$configDir,
837
+                \OC::$SERVERROOT . '/resources/config/'
838
+            );
839
+        });
840
+        $this->registerAlias('MimeTypeDetector', \OCP\Files\IMimeTypeDetector::class);
841
+
842
+        $this->registerService(\OCP\Files\IMimeTypeLoader::class, function (Server $c) {
843
+            return new \OC\Files\Type\Loader(
844
+                $c->getDatabaseConnection()
845
+            );
846
+        });
847
+        $this->registerAlias('MimeTypeLoader', \OCP\Files\IMimeTypeLoader::class);
848
+        $this->registerService(BundleFetcher::class, function () {
849
+            return new BundleFetcher($this->getL10N('lib'));
850
+        });
851
+        $this->registerService(\OCP\Notification\IManager::class, function (Server $c) {
852
+            return new Manager(
853
+                $c->query(IValidator::class)
854
+            );
855
+        });
856
+        $this->registerAlias('NotificationManager', \OCP\Notification\IManager::class);
857
+
858
+        $this->registerService(\OC\CapabilitiesManager::class, function (Server $c) {
859
+            $manager = new \OC\CapabilitiesManager($c->getLogger());
860
+            $manager->registerCapability(function () use ($c) {
861
+                return new \OC\OCS\CoreCapabilities($c->getConfig());
862
+            });
863
+            $manager->registerCapability(function () use ($c) {
864
+                return $c->query(\OC\Security\Bruteforce\Capabilities::class);
865
+            });
866
+            return $manager;
867
+        });
868
+        $this->registerAlias('CapabilitiesManager', \OC\CapabilitiesManager::class);
869
+
870
+        $this->registerService(\OCP\Comments\ICommentsManager::class, function (Server $c) {
871
+            $config = $c->getConfig();
872
+            $factoryClass = $config->getSystemValue('comments.managerFactory', '\OC\Comments\ManagerFactory');
873
+            /** @var \OCP\Comments\ICommentsManagerFactory $factory */
874
+            $factory = new $factoryClass($this);
875
+            return $factory->getManager();
876
+        });
877
+        $this->registerAlias('CommentsManager', \OCP\Comments\ICommentsManager::class);
878
+
879
+        $this->registerService('ThemingDefaults', function (Server $c) {
880
+            /*
881 881
 			 * Dark magic for autoloader.
882 882
 			 * If we do a class_exists it will try to load the class which will
883 883
 			 * make composer cache the result. Resulting in errors when enabling
884 884
 			 * the theming app.
885 885
 			 */
886
-			$prefixes = \OC::$composerAutoloader->getPrefixesPsr4();
887
-			if (isset($prefixes['OCA\\Theming\\'])) {
888
-				$classExists = true;
889
-			} else {
890
-				$classExists = false;
891
-			}
892
-
893
-			if ($classExists && $c->getConfig()->getSystemValue('installed', false) && $c->getAppManager()->isInstalled('theming') && $c->getTrustedDomainHelper()->isTrustedDomain($c->getRequest()->getInsecureServerHost())) {
894
-				return new ThemingDefaults(
895
-					$c->getConfig(),
896
-					$c->getL10N('theming'),
897
-					$c->getURLGenerator(),
898
-					$c->getAppDataDir('theming'),
899
-					$c->getMemCacheFactory(),
900
-					new Util($c->getConfig(), $this->getAppManager(), $this->getAppDataDir('theming')),
901
-					$this->getAppManager()
902
-				);
903
-			}
904
-			return new \OC_Defaults();
905
-		});
906
-		$this->registerService(SCSSCacher::class, function (Server $c) {
907
-			/** @var Factory $cacheFactory */
908
-			$cacheFactory = $c->query(Factory::class);
909
-			return new SCSSCacher(
910
-				$c->getLogger(),
911
-				$c->query(\OC\Files\AppData\Factory::class),
912
-				$c->getURLGenerator(),
913
-				$c->getConfig(),
914
-				$c->getThemingDefaults(),
915
-				\OC::$SERVERROOT,
916
-				$cacheFactory->create('SCSS')
917
-			);
918
-		});
919
-		$this->registerService(EventDispatcher::class, function () {
920
-			return new EventDispatcher();
921
-		});
922
-		$this->registerAlias('EventDispatcher', EventDispatcher::class);
923
-		$this->registerAlias(EventDispatcherInterface::class, EventDispatcher::class);
924
-
925
-		$this->registerService('CryptoWrapper', function (Server $c) {
926
-			// FIXME: Instantiiated here due to cyclic dependency
927
-			$request = new Request(
928
-				[
929
-					'get' => $_GET,
930
-					'post' => $_POST,
931
-					'files' => $_FILES,
932
-					'server' => $_SERVER,
933
-					'env' => $_ENV,
934
-					'cookies' => $_COOKIE,
935
-					'method' => (isset($_SERVER) && isset($_SERVER['REQUEST_METHOD']))
936
-						? $_SERVER['REQUEST_METHOD']
937
-						: null,
938
-				],
939
-				$c->getSecureRandom(),
940
-				$c->getConfig()
941
-			);
942
-
943
-			return new CryptoWrapper(
944
-				$c->getConfig(),
945
-				$c->getCrypto(),
946
-				$c->getSecureRandom(),
947
-				$request
948
-			);
949
-		});
950
-		$this->registerService('CsrfTokenManager', function (Server $c) {
951
-			$tokenGenerator = new CsrfTokenGenerator($c->getSecureRandom());
952
-
953
-			return new CsrfTokenManager(
954
-				$tokenGenerator,
955
-				$c->query(SessionStorage::class)
956
-			);
957
-		});
958
-		$this->registerService(SessionStorage::class, function (Server $c) {
959
-			return new SessionStorage($c->getSession());
960
-		});
961
-		$this->registerService(\OCP\Security\IContentSecurityPolicyManager::class, function (Server $c) {
962
-			return new ContentSecurityPolicyManager();
963
-		});
964
-		$this->registerAlias('ContentSecurityPolicyManager', \OCP\Security\IContentSecurityPolicyManager::class);
965
-
966
-		$this->registerService('ContentSecurityPolicyNonceManager', function (Server $c) {
967
-			return new ContentSecurityPolicyNonceManager(
968
-				$c->getCsrfTokenManager(),
969
-				$c->getRequest()
970
-			);
971
-		});
972
-
973
-		$this->registerService(\OCP\Share\IManager::class, function (Server $c) {
974
-			$config = $c->getConfig();
975
-			$factoryClass = $config->getSystemValue('sharing.managerFactory', '\OC\Share20\ProviderFactory');
976
-			/** @var \OCP\Share\IProviderFactory $factory */
977
-			$factory = new $factoryClass($this);
978
-
979
-			$manager = new \OC\Share20\Manager(
980
-				$c->getLogger(),
981
-				$c->getConfig(),
982
-				$c->getSecureRandom(),
983
-				$c->getHasher(),
984
-				$c->getMountManager(),
985
-				$c->getGroupManager(),
986
-				$c->getL10N('lib'),
987
-				$c->getL10NFactory(),
988
-				$factory,
989
-				$c->getUserManager(),
990
-				$c->getLazyRootFolder(),
991
-				$c->getEventDispatcher(),
992
-				$c->getMailer(),
993
-				$c->getURLGenerator(),
994
-				$c->getThemingDefaults()
995
-			);
996
-
997
-			return $manager;
998
-		});
999
-		$this->registerAlias('ShareManager', \OCP\Share\IManager::class);
1000
-
1001
-		$this->registerService(\OCP\Collaboration\Collaborators\ISearch::class, function(Server $c) {
1002
-			$instance = new Collaboration\Collaborators\Search($c);
1003
-
1004
-			// register default plugins
1005
-			$instance->registerPlugin(['shareType' => 'SHARE_TYPE_USER', 'class' => UserPlugin::class]);
1006
-			$instance->registerPlugin(['shareType' => 'SHARE_TYPE_GROUP', 'class' => GroupPlugin::class]);
1007
-			$instance->registerPlugin(['shareType' => 'SHARE_TYPE_EMAIL', 'class' => MailPlugin::class]);
1008
-			$instance->registerPlugin(['shareType' => 'SHARE_TYPE_REMOTE', 'class' => RemotePlugin::class]);
1009
-
1010
-			return $instance;
1011
-		});
1012
-		$this->registerAlias('CollaboratorSearch', \OCP\Collaboration\Collaborators\ISearch::class);
1013
-
1014
-		$this->registerService(\OCP\Collaboration\AutoComplete\IManager::class, function (Server $c) {
1015
-			return new Collaboration\AutoComplete\Manager($c);
1016
-		});
1017
-		$this->registerAlias('AutoCompleteManager', \OCP\Collaboration\AutoComplete\IManager::class);
1018
-
1019
-		$this->registerService('SettingsManager', function (Server $c) {
1020
-			$manager = new \OC\Settings\Manager(
1021
-				$c->getLogger(),
1022
-				$c->getDatabaseConnection(),
1023
-				$c->getL10N('lib'),
1024
-				$c->getConfig(),
1025
-				$c->getEncryptionManager(),
1026
-				$c->getUserManager(),
1027
-				$c->getLockingProvider(),
1028
-				$c->getRequest(),
1029
-				new \OC\Settings\Mapper($c->getDatabaseConnection()),
1030
-				$c->getURLGenerator(),
1031
-				$c->query(AccountManager::class),
1032
-				$c->getGroupManager(),
1033
-				$c->getL10NFactory(),
1034
-				$c->getThemingDefaults(),
1035
-				$c->getAppManager()
1036
-			);
1037
-			return $manager;
1038
-		});
1039
-		$this->registerService(\OC\Files\AppData\Factory::class, function (Server $c) {
1040
-			return new \OC\Files\AppData\Factory(
1041
-				$c->getRootFolder(),
1042
-				$c->getSystemConfig()
1043
-			);
1044
-		});
1045
-
1046
-		$this->registerService('LockdownManager', function (Server $c) {
1047
-			return new LockdownManager(function () use ($c) {
1048
-				return $c->getSession();
1049
-			});
1050
-		});
1051
-
1052
-		$this->registerService(\OCP\OCS\IDiscoveryService::class, function (Server $c) {
1053
-			return new DiscoveryService($c->getMemCacheFactory(), $c->getHTTPClientService());
1054
-		});
1055
-
1056
-		$this->registerService(ICloudIdManager::class, function (Server $c) {
1057
-			return new CloudIdManager();
1058
-		});
1059
-
1060
-		/* To trick DI since we don't extend the DIContainer here */
1061
-		$this->registerService(CleanPreviewsBackgroundJob::class, function (Server $c) {
1062
-			return new CleanPreviewsBackgroundJob(
1063
-				$c->getRootFolder(),
1064
-				$c->getLogger(),
1065
-				$c->getJobList(),
1066
-				new TimeFactory()
1067
-			);
1068
-		});
1069
-
1070
-		$this->registerAlias(\OCP\AppFramework\Utility\IControllerMethodReflector::class, \OC\AppFramework\Utility\ControllerMethodReflector::class);
1071
-		$this->registerAlias('ControllerMethodReflector', \OCP\AppFramework\Utility\IControllerMethodReflector::class);
1072
-
1073
-		$this->registerAlias(\OCP\AppFramework\Utility\ITimeFactory::class, \OC\AppFramework\Utility\TimeFactory::class);
1074
-		$this->registerAlias('TimeFactory', \OCP\AppFramework\Utility\ITimeFactory::class);
1075
-
1076
-		$this->registerService(Defaults::class, function (Server $c) {
1077
-			return new Defaults(
1078
-				$c->getThemingDefaults()
1079
-			);
1080
-		});
1081
-		$this->registerAlias('Defaults', \OCP\Defaults::class);
1082
-
1083
-		$this->registerService(\OCP\ISession::class, function (SimpleContainer $c) {
1084
-			return $c->query(\OCP\IUserSession::class)->getSession();
1085
-		});
1086
-
1087
-		$this->registerService(IShareHelper::class, function (Server $c) {
1088
-			return new ShareHelper(
1089
-				$c->query(\OCP\Share\IManager::class)
1090
-			);
1091
-		});
1092
-	}
1093
-
1094
-	/**
1095
-	 * @return \OCP\Contacts\IManager
1096
-	 */
1097
-	public function getContactsManager() {
1098
-		return $this->query('ContactsManager');
1099
-	}
1100
-
1101
-	/**
1102
-	 * @return \OC\Encryption\Manager
1103
-	 */
1104
-	public function getEncryptionManager() {
1105
-		return $this->query('EncryptionManager');
1106
-	}
1107
-
1108
-	/**
1109
-	 * @return \OC\Encryption\File
1110
-	 */
1111
-	public function getEncryptionFilesHelper() {
1112
-		return $this->query('EncryptionFileHelper');
1113
-	}
1114
-
1115
-	/**
1116
-	 * @return \OCP\Encryption\Keys\IStorage
1117
-	 */
1118
-	public function getEncryptionKeyStorage() {
1119
-		return $this->query('EncryptionKeyStorage');
1120
-	}
1121
-
1122
-	/**
1123
-	 * The current request object holding all information about the request
1124
-	 * currently being processed is returned from this method.
1125
-	 * In case the current execution was not initiated by a web request null is returned
1126
-	 *
1127
-	 * @return \OCP\IRequest
1128
-	 */
1129
-	public function getRequest() {
1130
-		return $this->query('Request');
1131
-	}
1132
-
1133
-	/**
1134
-	 * Returns the preview manager which can create preview images for a given file
1135
-	 *
1136
-	 * @return \OCP\IPreview
1137
-	 */
1138
-	public function getPreviewManager() {
1139
-		return $this->query('PreviewManager');
1140
-	}
1141
-
1142
-	/**
1143
-	 * Returns the tag manager which can get and set tags for different object types
1144
-	 *
1145
-	 * @see \OCP\ITagManager::load()
1146
-	 * @return \OCP\ITagManager
1147
-	 */
1148
-	public function getTagManager() {
1149
-		return $this->query('TagManager');
1150
-	}
1151
-
1152
-	/**
1153
-	 * Returns the system-tag manager
1154
-	 *
1155
-	 * @return \OCP\SystemTag\ISystemTagManager
1156
-	 *
1157
-	 * @since 9.0.0
1158
-	 */
1159
-	public function getSystemTagManager() {
1160
-		return $this->query('SystemTagManager');
1161
-	}
1162
-
1163
-	/**
1164
-	 * Returns the system-tag object mapper
1165
-	 *
1166
-	 * @return \OCP\SystemTag\ISystemTagObjectMapper
1167
-	 *
1168
-	 * @since 9.0.0
1169
-	 */
1170
-	public function getSystemTagObjectMapper() {
1171
-		return $this->query('SystemTagObjectMapper');
1172
-	}
1173
-
1174
-	/**
1175
-	 * Returns the avatar manager, used for avatar functionality
1176
-	 *
1177
-	 * @return \OCP\IAvatarManager
1178
-	 */
1179
-	public function getAvatarManager() {
1180
-		return $this->query('AvatarManager');
1181
-	}
1182
-
1183
-	/**
1184
-	 * Returns the root folder of ownCloud's data directory
1185
-	 *
1186
-	 * @return \OCP\Files\IRootFolder
1187
-	 */
1188
-	public function getRootFolder() {
1189
-		return $this->query('LazyRootFolder');
1190
-	}
1191
-
1192
-	/**
1193
-	 * Returns the root folder of ownCloud's data directory
1194
-	 * This is the lazy variant so this gets only initialized once it
1195
-	 * is actually used.
1196
-	 *
1197
-	 * @return \OCP\Files\IRootFolder
1198
-	 */
1199
-	public function getLazyRootFolder() {
1200
-		return $this->query('LazyRootFolder');
1201
-	}
1202
-
1203
-	/**
1204
-	 * Returns a view to ownCloud's files folder
1205
-	 *
1206
-	 * @param string $userId user ID
1207
-	 * @return \OCP\Files\Folder|null
1208
-	 */
1209
-	public function getUserFolder($userId = null) {
1210
-		if ($userId === null) {
1211
-			$user = $this->getUserSession()->getUser();
1212
-			if (!$user) {
1213
-				return null;
1214
-			}
1215
-			$userId = $user->getUID();
1216
-		}
1217
-		$root = $this->getRootFolder();
1218
-		return $root->getUserFolder($userId);
1219
-	}
1220
-
1221
-	/**
1222
-	 * Returns an app-specific view in ownClouds data directory
1223
-	 *
1224
-	 * @return \OCP\Files\Folder
1225
-	 * @deprecated since 9.2.0 use IAppData
1226
-	 */
1227
-	public function getAppFolder() {
1228
-		$dir = '/' . \OC_App::getCurrentApp();
1229
-		$root = $this->getRootFolder();
1230
-		if (!$root->nodeExists($dir)) {
1231
-			$folder = $root->newFolder($dir);
1232
-		} else {
1233
-			$folder = $root->get($dir);
1234
-		}
1235
-		return $folder;
1236
-	}
1237
-
1238
-	/**
1239
-	 * @return \OC\User\Manager
1240
-	 */
1241
-	public function getUserManager() {
1242
-		return $this->query('UserManager');
1243
-	}
1244
-
1245
-	/**
1246
-	 * @return \OC\Group\Manager
1247
-	 */
1248
-	public function getGroupManager() {
1249
-		return $this->query('GroupManager');
1250
-	}
1251
-
1252
-	/**
1253
-	 * @return \OC\User\Session
1254
-	 */
1255
-	public function getUserSession() {
1256
-		return $this->query('UserSession');
1257
-	}
1258
-
1259
-	/**
1260
-	 * @return \OCP\ISession
1261
-	 */
1262
-	public function getSession() {
1263
-		return $this->query('UserSession')->getSession();
1264
-	}
1265
-
1266
-	/**
1267
-	 * @param \OCP\ISession $session
1268
-	 */
1269
-	public function setSession(\OCP\ISession $session) {
1270
-		$this->query(SessionStorage::class)->setSession($session);
1271
-		$this->query('UserSession')->setSession($session);
1272
-		$this->query(Store::class)->setSession($session);
1273
-	}
1274
-
1275
-	/**
1276
-	 * @return \OC\Authentication\TwoFactorAuth\Manager
1277
-	 */
1278
-	public function getTwoFactorAuthManager() {
1279
-		return $this->query('\OC\Authentication\TwoFactorAuth\Manager');
1280
-	}
1281
-
1282
-	/**
1283
-	 * @return \OC\NavigationManager
1284
-	 */
1285
-	public function getNavigationManager() {
1286
-		return $this->query('NavigationManager');
1287
-	}
1288
-
1289
-	/**
1290
-	 * @return \OCP\IConfig
1291
-	 */
1292
-	public function getConfig() {
1293
-		return $this->query('AllConfig');
1294
-	}
1295
-
1296
-	/**
1297
-	 * @return \OC\SystemConfig
1298
-	 */
1299
-	public function getSystemConfig() {
1300
-		return $this->query('SystemConfig');
1301
-	}
1302
-
1303
-	/**
1304
-	 * Returns the app config manager
1305
-	 *
1306
-	 * @return \OCP\IAppConfig
1307
-	 */
1308
-	public function getAppConfig() {
1309
-		return $this->query('AppConfig');
1310
-	}
1311
-
1312
-	/**
1313
-	 * @return \OCP\L10N\IFactory
1314
-	 */
1315
-	public function getL10NFactory() {
1316
-		return $this->query('L10NFactory');
1317
-	}
1318
-
1319
-	/**
1320
-	 * get an L10N instance
1321
-	 *
1322
-	 * @param string $app appid
1323
-	 * @param string $lang
1324
-	 * @return IL10N
1325
-	 */
1326
-	public function getL10N($app, $lang = null) {
1327
-		return $this->getL10NFactory()->get($app, $lang);
1328
-	}
1329
-
1330
-	/**
1331
-	 * @return \OCP\IURLGenerator
1332
-	 */
1333
-	public function getURLGenerator() {
1334
-		return $this->query('URLGenerator');
1335
-	}
1336
-
1337
-	/**
1338
-	 * @return \OCP\IHelper
1339
-	 */
1340
-	public function getHelper() {
1341
-		return $this->query('AppHelper');
1342
-	}
1343
-
1344
-	/**
1345
-	 * @return AppFetcher
1346
-	 */
1347
-	public function getAppFetcher() {
1348
-		return $this->query(AppFetcher::class);
1349
-	}
1350
-
1351
-	/**
1352
-	 * Returns an ICache instance. Since 8.1.0 it returns a fake cache. Use
1353
-	 * getMemCacheFactory() instead.
1354
-	 *
1355
-	 * @return \OCP\ICache
1356
-	 * @deprecated 8.1.0 use getMemCacheFactory to obtain a proper cache
1357
-	 */
1358
-	public function getCache() {
1359
-		return $this->query('UserCache');
1360
-	}
1361
-
1362
-	/**
1363
-	 * Returns an \OCP\CacheFactory instance
1364
-	 *
1365
-	 * @return \OCP\ICacheFactory
1366
-	 */
1367
-	public function getMemCacheFactory() {
1368
-		return $this->query('MemCacheFactory');
1369
-	}
1370
-
1371
-	/**
1372
-	 * Returns an \OC\RedisFactory instance
1373
-	 *
1374
-	 * @return \OC\RedisFactory
1375
-	 */
1376
-	public function getGetRedisFactory() {
1377
-		return $this->query('RedisFactory');
1378
-	}
1379
-
1380
-
1381
-	/**
1382
-	 * Returns the current session
1383
-	 *
1384
-	 * @return \OCP\IDBConnection
1385
-	 */
1386
-	public function getDatabaseConnection() {
1387
-		return $this->query('DatabaseConnection');
1388
-	}
1389
-
1390
-	/**
1391
-	 * Returns the activity manager
1392
-	 *
1393
-	 * @return \OCP\Activity\IManager
1394
-	 */
1395
-	public function getActivityManager() {
1396
-		return $this->query('ActivityManager');
1397
-	}
1398
-
1399
-	/**
1400
-	 * Returns an job list for controlling background jobs
1401
-	 *
1402
-	 * @return \OCP\BackgroundJob\IJobList
1403
-	 */
1404
-	public function getJobList() {
1405
-		return $this->query('JobList');
1406
-	}
1407
-
1408
-	/**
1409
-	 * Returns a logger instance
1410
-	 *
1411
-	 * @return \OCP\ILogger
1412
-	 */
1413
-	public function getLogger() {
1414
-		return $this->query('Logger');
1415
-	}
1416
-
1417
-	/**
1418
-	 * Returns a router for generating and matching urls
1419
-	 *
1420
-	 * @return \OCP\Route\IRouter
1421
-	 */
1422
-	public function getRouter() {
1423
-		return $this->query('Router');
1424
-	}
1425
-
1426
-	/**
1427
-	 * Returns a search instance
1428
-	 *
1429
-	 * @return \OCP\ISearch
1430
-	 */
1431
-	public function getSearch() {
1432
-		return $this->query('Search');
1433
-	}
1434
-
1435
-	/**
1436
-	 * Returns a SecureRandom instance
1437
-	 *
1438
-	 * @return \OCP\Security\ISecureRandom
1439
-	 */
1440
-	public function getSecureRandom() {
1441
-		return $this->query('SecureRandom');
1442
-	}
1443
-
1444
-	/**
1445
-	 * Returns a Crypto instance
1446
-	 *
1447
-	 * @return \OCP\Security\ICrypto
1448
-	 */
1449
-	public function getCrypto() {
1450
-		return $this->query('Crypto');
1451
-	}
1452
-
1453
-	/**
1454
-	 * Returns a Hasher instance
1455
-	 *
1456
-	 * @return \OCP\Security\IHasher
1457
-	 */
1458
-	public function getHasher() {
1459
-		return $this->query('Hasher');
1460
-	}
1461
-
1462
-	/**
1463
-	 * Returns a CredentialsManager instance
1464
-	 *
1465
-	 * @return \OCP\Security\ICredentialsManager
1466
-	 */
1467
-	public function getCredentialsManager() {
1468
-		return $this->query('CredentialsManager');
1469
-	}
1470
-
1471
-	/**
1472
-	 * Returns an instance of the HTTP helper class
1473
-	 *
1474
-	 * @deprecated Use getHTTPClientService()
1475
-	 * @return \OC\HTTPHelper
1476
-	 */
1477
-	public function getHTTPHelper() {
1478
-		return $this->query('HTTPHelper');
1479
-	}
1480
-
1481
-	/**
1482
-	 * Get the certificate manager for the user
1483
-	 *
1484
-	 * @param string $userId (optional) if not specified the current loggedin user is used, use null to get the system certificate manager
1485
-	 * @return \OCP\ICertificateManager | null if $uid is null and no user is logged in
1486
-	 */
1487
-	public function getCertificateManager($userId = '') {
1488
-		if ($userId === '') {
1489
-			$userSession = $this->getUserSession();
1490
-			$user = $userSession->getUser();
1491
-			if (is_null($user)) {
1492
-				return null;
1493
-			}
1494
-			$userId = $user->getUID();
1495
-		}
1496
-		return new CertificateManager(
1497
-			$userId,
1498
-			new View(),
1499
-			$this->getConfig(),
1500
-			$this->getLogger(),
1501
-			$this->getSecureRandom()
1502
-		);
1503
-	}
1504
-
1505
-	/**
1506
-	 * Returns an instance of the HTTP client service
1507
-	 *
1508
-	 * @return \OCP\Http\Client\IClientService
1509
-	 */
1510
-	public function getHTTPClientService() {
1511
-		return $this->query('HttpClientService');
1512
-	}
1513
-
1514
-	/**
1515
-	 * Create a new event source
1516
-	 *
1517
-	 * @return \OCP\IEventSource
1518
-	 */
1519
-	public function createEventSource() {
1520
-		return new \OC_EventSource();
1521
-	}
1522
-
1523
-	/**
1524
-	 * Get the active event logger
1525
-	 *
1526
-	 * The returned logger only logs data when debug mode is enabled
1527
-	 *
1528
-	 * @return \OCP\Diagnostics\IEventLogger
1529
-	 */
1530
-	public function getEventLogger() {
1531
-		return $this->query('EventLogger');
1532
-	}
1533
-
1534
-	/**
1535
-	 * Get the active query logger
1536
-	 *
1537
-	 * The returned logger only logs data when debug mode is enabled
1538
-	 *
1539
-	 * @return \OCP\Diagnostics\IQueryLogger
1540
-	 */
1541
-	public function getQueryLogger() {
1542
-		return $this->query('QueryLogger');
1543
-	}
1544
-
1545
-	/**
1546
-	 * Get the manager for temporary files and folders
1547
-	 *
1548
-	 * @return \OCP\ITempManager
1549
-	 */
1550
-	public function getTempManager() {
1551
-		return $this->query('TempManager');
1552
-	}
1553
-
1554
-	/**
1555
-	 * Get the app manager
1556
-	 *
1557
-	 * @return \OCP\App\IAppManager
1558
-	 */
1559
-	public function getAppManager() {
1560
-		return $this->query('AppManager');
1561
-	}
1562
-
1563
-	/**
1564
-	 * Creates a new mailer
1565
-	 *
1566
-	 * @return \OCP\Mail\IMailer
1567
-	 */
1568
-	public function getMailer() {
1569
-		return $this->query('Mailer');
1570
-	}
1571
-
1572
-	/**
1573
-	 * Get the webroot
1574
-	 *
1575
-	 * @return string
1576
-	 */
1577
-	public function getWebRoot() {
1578
-		return $this->webRoot;
1579
-	}
1580
-
1581
-	/**
1582
-	 * @return \OC\OCSClient
1583
-	 */
1584
-	public function getOcsClient() {
1585
-		return $this->query('OcsClient');
1586
-	}
1587
-
1588
-	/**
1589
-	 * @return \OCP\IDateTimeZone
1590
-	 */
1591
-	public function getDateTimeZone() {
1592
-		return $this->query('DateTimeZone');
1593
-	}
1594
-
1595
-	/**
1596
-	 * @return \OCP\IDateTimeFormatter
1597
-	 */
1598
-	public function getDateTimeFormatter() {
1599
-		return $this->query('DateTimeFormatter');
1600
-	}
1601
-
1602
-	/**
1603
-	 * @return \OCP\Files\Config\IMountProviderCollection
1604
-	 */
1605
-	public function getMountProviderCollection() {
1606
-		return $this->query('MountConfigManager');
1607
-	}
1608
-
1609
-	/**
1610
-	 * Get the IniWrapper
1611
-	 *
1612
-	 * @return IniGetWrapper
1613
-	 */
1614
-	public function getIniWrapper() {
1615
-		return $this->query('IniWrapper');
1616
-	}
1617
-
1618
-	/**
1619
-	 * @return \OCP\Command\IBus
1620
-	 */
1621
-	public function getCommandBus() {
1622
-		return $this->query('AsyncCommandBus');
1623
-	}
1624
-
1625
-	/**
1626
-	 * Get the trusted domain helper
1627
-	 *
1628
-	 * @return TrustedDomainHelper
1629
-	 */
1630
-	public function getTrustedDomainHelper() {
1631
-		return $this->query('TrustedDomainHelper');
1632
-	}
1633
-
1634
-	/**
1635
-	 * Get the locking provider
1636
-	 *
1637
-	 * @return \OCP\Lock\ILockingProvider
1638
-	 * @since 8.1.0
1639
-	 */
1640
-	public function getLockingProvider() {
1641
-		return $this->query('LockingProvider');
1642
-	}
1643
-
1644
-	/**
1645
-	 * @return \OCP\Files\Mount\IMountManager
1646
-	 **/
1647
-	function getMountManager() {
1648
-		return $this->query('MountManager');
1649
-	}
1650
-
1651
-	/** @return \OCP\Files\Config\IUserMountCache */
1652
-	function getUserMountCache() {
1653
-		return $this->query('UserMountCache');
1654
-	}
1655
-
1656
-	/**
1657
-	 * Get the MimeTypeDetector
1658
-	 *
1659
-	 * @return \OCP\Files\IMimeTypeDetector
1660
-	 */
1661
-	public function getMimeTypeDetector() {
1662
-		return $this->query('MimeTypeDetector');
1663
-	}
1664
-
1665
-	/**
1666
-	 * Get the MimeTypeLoader
1667
-	 *
1668
-	 * @return \OCP\Files\IMimeTypeLoader
1669
-	 */
1670
-	public function getMimeTypeLoader() {
1671
-		return $this->query('MimeTypeLoader');
1672
-	}
1673
-
1674
-	/**
1675
-	 * Get the manager of all the capabilities
1676
-	 *
1677
-	 * @return \OC\CapabilitiesManager
1678
-	 */
1679
-	public function getCapabilitiesManager() {
1680
-		return $this->query('CapabilitiesManager');
1681
-	}
1682
-
1683
-	/**
1684
-	 * Get the EventDispatcher
1685
-	 *
1686
-	 * @return EventDispatcherInterface
1687
-	 * @since 8.2.0
1688
-	 */
1689
-	public function getEventDispatcher() {
1690
-		return $this->query('EventDispatcher');
1691
-	}
1692
-
1693
-	/**
1694
-	 * Get the Notification Manager
1695
-	 *
1696
-	 * @return \OCP\Notification\IManager
1697
-	 * @since 8.2.0
1698
-	 */
1699
-	public function getNotificationManager() {
1700
-		return $this->query('NotificationManager');
1701
-	}
1702
-
1703
-	/**
1704
-	 * @return \OCP\Comments\ICommentsManager
1705
-	 */
1706
-	public function getCommentsManager() {
1707
-		return $this->query('CommentsManager');
1708
-	}
1709
-
1710
-	/**
1711
-	 * @return \OCA\Theming\ThemingDefaults
1712
-	 */
1713
-	public function getThemingDefaults() {
1714
-		return $this->query('ThemingDefaults');
1715
-	}
1716
-
1717
-	/**
1718
-	 * @return \OC\IntegrityCheck\Checker
1719
-	 */
1720
-	public function getIntegrityCodeChecker() {
1721
-		return $this->query('IntegrityCodeChecker');
1722
-	}
1723
-
1724
-	/**
1725
-	 * @return \OC\Session\CryptoWrapper
1726
-	 */
1727
-	public function getSessionCryptoWrapper() {
1728
-		return $this->query('CryptoWrapper');
1729
-	}
1730
-
1731
-	/**
1732
-	 * @return CsrfTokenManager
1733
-	 */
1734
-	public function getCsrfTokenManager() {
1735
-		return $this->query('CsrfTokenManager');
1736
-	}
1737
-
1738
-	/**
1739
-	 * @return Throttler
1740
-	 */
1741
-	public function getBruteForceThrottler() {
1742
-		return $this->query('Throttler');
1743
-	}
1744
-
1745
-	/**
1746
-	 * @return IContentSecurityPolicyManager
1747
-	 */
1748
-	public function getContentSecurityPolicyManager() {
1749
-		return $this->query('ContentSecurityPolicyManager');
1750
-	}
1751
-
1752
-	/**
1753
-	 * @return ContentSecurityPolicyNonceManager
1754
-	 */
1755
-	public function getContentSecurityPolicyNonceManager() {
1756
-		return $this->query('ContentSecurityPolicyNonceManager');
1757
-	}
1758
-
1759
-	/**
1760
-	 * Not a public API as of 8.2, wait for 9.0
1761
-	 *
1762
-	 * @return \OCA\Files_External\Service\BackendService
1763
-	 */
1764
-	public function getStoragesBackendService() {
1765
-		return $this->query('OCA\\Files_External\\Service\\BackendService');
1766
-	}
1767
-
1768
-	/**
1769
-	 * Not a public API as of 8.2, wait for 9.0
1770
-	 *
1771
-	 * @return \OCA\Files_External\Service\GlobalStoragesService
1772
-	 */
1773
-	public function getGlobalStoragesService() {
1774
-		return $this->query('OCA\\Files_External\\Service\\GlobalStoragesService');
1775
-	}
1776
-
1777
-	/**
1778
-	 * Not a public API as of 8.2, wait for 9.0
1779
-	 *
1780
-	 * @return \OCA\Files_External\Service\UserGlobalStoragesService
1781
-	 */
1782
-	public function getUserGlobalStoragesService() {
1783
-		return $this->query('OCA\\Files_External\\Service\\UserGlobalStoragesService');
1784
-	}
1785
-
1786
-	/**
1787
-	 * Not a public API as of 8.2, wait for 9.0
1788
-	 *
1789
-	 * @return \OCA\Files_External\Service\UserStoragesService
1790
-	 */
1791
-	public function getUserStoragesService() {
1792
-		return $this->query('OCA\\Files_External\\Service\\UserStoragesService');
1793
-	}
1794
-
1795
-	/**
1796
-	 * @return \OCP\Share\IManager
1797
-	 */
1798
-	public function getShareManager() {
1799
-		return $this->query('ShareManager');
1800
-	}
1801
-
1802
-	/**
1803
-	 * @return \OCP\Collaboration\Collaborators\ISearch
1804
-	 */
1805
-	public function getCollaboratorSearch() {
1806
-		return $this->query('CollaboratorSearch');
1807
-	}
1808
-
1809
-	/**
1810
-	 * @return \OCP\Collaboration\AutoComplete\IManager
1811
-	 */
1812
-	public function getAutoCompleteManager(){
1813
-		return $this->query('AutoCompleteManager');
1814
-	}
1815
-
1816
-	/**
1817
-	 * Returns the LDAP Provider
1818
-	 *
1819
-	 * @return \OCP\LDAP\ILDAPProvider
1820
-	 */
1821
-	public function getLDAPProvider() {
1822
-		return $this->query('LDAPProvider');
1823
-	}
1824
-
1825
-	/**
1826
-	 * @return \OCP\Settings\IManager
1827
-	 */
1828
-	public function getSettingsManager() {
1829
-		return $this->query('SettingsManager');
1830
-	}
1831
-
1832
-	/**
1833
-	 * @return \OCP\Files\IAppData
1834
-	 */
1835
-	public function getAppDataDir($app) {
1836
-		/** @var \OC\Files\AppData\Factory $factory */
1837
-		$factory = $this->query(\OC\Files\AppData\Factory::class);
1838
-		return $factory->get($app);
1839
-	}
1840
-
1841
-	/**
1842
-	 * @return \OCP\Lockdown\ILockdownManager
1843
-	 */
1844
-	public function getLockdownManager() {
1845
-		return $this->query('LockdownManager');
1846
-	}
1847
-
1848
-	/**
1849
-	 * @return \OCP\Federation\ICloudIdManager
1850
-	 */
1851
-	public function getCloudIdManager() {
1852
-		return $this->query(ICloudIdManager::class);
1853
-	}
886
+            $prefixes = \OC::$composerAutoloader->getPrefixesPsr4();
887
+            if (isset($prefixes['OCA\\Theming\\'])) {
888
+                $classExists = true;
889
+            } else {
890
+                $classExists = false;
891
+            }
892
+
893
+            if ($classExists && $c->getConfig()->getSystemValue('installed', false) && $c->getAppManager()->isInstalled('theming') && $c->getTrustedDomainHelper()->isTrustedDomain($c->getRequest()->getInsecureServerHost())) {
894
+                return new ThemingDefaults(
895
+                    $c->getConfig(),
896
+                    $c->getL10N('theming'),
897
+                    $c->getURLGenerator(),
898
+                    $c->getAppDataDir('theming'),
899
+                    $c->getMemCacheFactory(),
900
+                    new Util($c->getConfig(), $this->getAppManager(), $this->getAppDataDir('theming')),
901
+                    $this->getAppManager()
902
+                );
903
+            }
904
+            return new \OC_Defaults();
905
+        });
906
+        $this->registerService(SCSSCacher::class, function (Server $c) {
907
+            /** @var Factory $cacheFactory */
908
+            $cacheFactory = $c->query(Factory::class);
909
+            return new SCSSCacher(
910
+                $c->getLogger(),
911
+                $c->query(\OC\Files\AppData\Factory::class),
912
+                $c->getURLGenerator(),
913
+                $c->getConfig(),
914
+                $c->getThemingDefaults(),
915
+                \OC::$SERVERROOT,
916
+                $cacheFactory->create('SCSS')
917
+            );
918
+        });
919
+        $this->registerService(EventDispatcher::class, function () {
920
+            return new EventDispatcher();
921
+        });
922
+        $this->registerAlias('EventDispatcher', EventDispatcher::class);
923
+        $this->registerAlias(EventDispatcherInterface::class, EventDispatcher::class);
924
+
925
+        $this->registerService('CryptoWrapper', function (Server $c) {
926
+            // FIXME: Instantiiated here due to cyclic dependency
927
+            $request = new Request(
928
+                [
929
+                    'get' => $_GET,
930
+                    'post' => $_POST,
931
+                    'files' => $_FILES,
932
+                    'server' => $_SERVER,
933
+                    'env' => $_ENV,
934
+                    'cookies' => $_COOKIE,
935
+                    'method' => (isset($_SERVER) && isset($_SERVER['REQUEST_METHOD']))
936
+                        ? $_SERVER['REQUEST_METHOD']
937
+                        : null,
938
+                ],
939
+                $c->getSecureRandom(),
940
+                $c->getConfig()
941
+            );
942
+
943
+            return new CryptoWrapper(
944
+                $c->getConfig(),
945
+                $c->getCrypto(),
946
+                $c->getSecureRandom(),
947
+                $request
948
+            );
949
+        });
950
+        $this->registerService('CsrfTokenManager', function (Server $c) {
951
+            $tokenGenerator = new CsrfTokenGenerator($c->getSecureRandom());
952
+
953
+            return new CsrfTokenManager(
954
+                $tokenGenerator,
955
+                $c->query(SessionStorage::class)
956
+            );
957
+        });
958
+        $this->registerService(SessionStorage::class, function (Server $c) {
959
+            return new SessionStorage($c->getSession());
960
+        });
961
+        $this->registerService(\OCP\Security\IContentSecurityPolicyManager::class, function (Server $c) {
962
+            return new ContentSecurityPolicyManager();
963
+        });
964
+        $this->registerAlias('ContentSecurityPolicyManager', \OCP\Security\IContentSecurityPolicyManager::class);
965
+
966
+        $this->registerService('ContentSecurityPolicyNonceManager', function (Server $c) {
967
+            return new ContentSecurityPolicyNonceManager(
968
+                $c->getCsrfTokenManager(),
969
+                $c->getRequest()
970
+            );
971
+        });
972
+
973
+        $this->registerService(\OCP\Share\IManager::class, function (Server $c) {
974
+            $config = $c->getConfig();
975
+            $factoryClass = $config->getSystemValue('sharing.managerFactory', '\OC\Share20\ProviderFactory');
976
+            /** @var \OCP\Share\IProviderFactory $factory */
977
+            $factory = new $factoryClass($this);
978
+
979
+            $manager = new \OC\Share20\Manager(
980
+                $c->getLogger(),
981
+                $c->getConfig(),
982
+                $c->getSecureRandom(),
983
+                $c->getHasher(),
984
+                $c->getMountManager(),
985
+                $c->getGroupManager(),
986
+                $c->getL10N('lib'),
987
+                $c->getL10NFactory(),
988
+                $factory,
989
+                $c->getUserManager(),
990
+                $c->getLazyRootFolder(),
991
+                $c->getEventDispatcher(),
992
+                $c->getMailer(),
993
+                $c->getURLGenerator(),
994
+                $c->getThemingDefaults()
995
+            );
996
+
997
+            return $manager;
998
+        });
999
+        $this->registerAlias('ShareManager', \OCP\Share\IManager::class);
1000
+
1001
+        $this->registerService(\OCP\Collaboration\Collaborators\ISearch::class, function(Server $c) {
1002
+            $instance = new Collaboration\Collaborators\Search($c);
1003
+
1004
+            // register default plugins
1005
+            $instance->registerPlugin(['shareType' => 'SHARE_TYPE_USER', 'class' => UserPlugin::class]);
1006
+            $instance->registerPlugin(['shareType' => 'SHARE_TYPE_GROUP', 'class' => GroupPlugin::class]);
1007
+            $instance->registerPlugin(['shareType' => 'SHARE_TYPE_EMAIL', 'class' => MailPlugin::class]);
1008
+            $instance->registerPlugin(['shareType' => 'SHARE_TYPE_REMOTE', 'class' => RemotePlugin::class]);
1009
+
1010
+            return $instance;
1011
+        });
1012
+        $this->registerAlias('CollaboratorSearch', \OCP\Collaboration\Collaborators\ISearch::class);
1013
+
1014
+        $this->registerService(\OCP\Collaboration\AutoComplete\IManager::class, function (Server $c) {
1015
+            return new Collaboration\AutoComplete\Manager($c);
1016
+        });
1017
+        $this->registerAlias('AutoCompleteManager', \OCP\Collaboration\AutoComplete\IManager::class);
1018
+
1019
+        $this->registerService('SettingsManager', function (Server $c) {
1020
+            $manager = new \OC\Settings\Manager(
1021
+                $c->getLogger(),
1022
+                $c->getDatabaseConnection(),
1023
+                $c->getL10N('lib'),
1024
+                $c->getConfig(),
1025
+                $c->getEncryptionManager(),
1026
+                $c->getUserManager(),
1027
+                $c->getLockingProvider(),
1028
+                $c->getRequest(),
1029
+                new \OC\Settings\Mapper($c->getDatabaseConnection()),
1030
+                $c->getURLGenerator(),
1031
+                $c->query(AccountManager::class),
1032
+                $c->getGroupManager(),
1033
+                $c->getL10NFactory(),
1034
+                $c->getThemingDefaults(),
1035
+                $c->getAppManager()
1036
+            );
1037
+            return $manager;
1038
+        });
1039
+        $this->registerService(\OC\Files\AppData\Factory::class, function (Server $c) {
1040
+            return new \OC\Files\AppData\Factory(
1041
+                $c->getRootFolder(),
1042
+                $c->getSystemConfig()
1043
+            );
1044
+        });
1045
+
1046
+        $this->registerService('LockdownManager', function (Server $c) {
1047
+            return new LockdownManager(function () use ($c) {
1048
+                return $c->getSession();
1049
+            });
1050
+        });
1051
+
1052
+        $this->registerService(\OCP\OCS\IDiscoveryService::class, function (Server $c) {
1053
+            return new DiscoveryService($c->getMemCacheFactory(), $c->getHTTPClientService());
1054
+        });
1055
+
1056
+        $this->registerService(ICloudIdManager::class, function (Server $c) {
1057
+            return new CloudIdManager();
1058
+        });
1059
+
1060
+        /* To trick DI since we don't extend the DIContainer here */
1061
+        $this->registerService(CleanPreviewsBackgroundJob::class, function (Server $c) {
1062
+            return new CleanPreviewsBackgroundJob(
1063
+                $c->getRootFolder(),
1064
+                $c->getLogger(),
1065
+                $c->getJobList(),
1066
+                new TimeFactory()
1067
+            );
1068
+        });
1069
+
1070
+        $this->registerAlias(\OCP\AppFramework\Utility\IControllerMethodReflector::class, \OC\AppFramework\Utility\ControllerMethodReflector::class);
1071
+        $this->registerAlias('ControllerMethodReflector', \OCP\AppFramework\Utility\IControllerMethodReflector::class);
1072
+
1073
+        $this->registerAlias(\OCP\AppFramework\Utility\ITimeFactory::class, \OC\AppFramework\Utility\TimeFactory::class);
1074
+        $this->registerAlias('TimeFactory', \OCP\AppFramework\Utility\ITimeFactory::class);
1075
+
1076
+        $this->registerService(Defaults::class, function (Server $c) {
1077
+            return new Defaults(
1078
+                $c->getThemingDefaults()
1079
+            );
1080
+        });
1081
+        $this->registerAlias('Defaults', \OCP\Defaults::class);
1082
+
1083
+        $this->registerService(\OCP\ISession::class, function (SimpleContainer $c) {
1084
+            return $c->query(\OCP\IUserSession::class)->getSession();
1085
+        });
1086
+
1087
+        $this->registerService(IShareHelper::class, function (Server $c) {
1088
+            return new ShareHelper(
1089
+                $c->query(\OCP\Share\IManager::class)
1090
+            );
1091
+        });
1092
+    }
1093
+
1094
+    /**
1095
+     * @return \OCP\Contacts\IManager
1096
+     */
1097
+    public function getContactsManager() {
1098
+        return $this->query('ContactsManager');
1099
+    }
1100
+
1101
+    /**
1102
+     * @return \OC\Encryption\Manager
1103
+     */
1104
+    public function getEncryptionManager() {
1105
+        return $this->query('EncryptionManager');
1106
+    }
1107
+
1108
+    /**
1109
+     * @return \OC\Encryption\File
1110
+     */
1111
+    public function getEncryptionFilesHelper() {
1112
+        return $this->query('EncryptionFileHelper');
1113
+    }
1114
+
1115
+    /**
1116
+     * @return \OCP\Encryption\Keys\IStorage
1117
+     */
1118
+    public function getEncryptionKeyStorage() {
1119
+        return $this->query('EncryptionKeyStorage');
1120
+    }
1121
+
1122
+    /**
1123
+     * The current request object holding all information about the request
1124
+     * currently being processed is returned from this method.
1125
+     * In case the current execution was not initiated by a web request null is returned
1126
+     *
1127
+     * @return \OCP\IRequest
1128
+     */
1129
+    public function getRequest() {
1130
+        return $this->query('Request');
1131
+    }
1132
+
1133
+    /**
1134
+     * Returns the preview manager which can create preview images for a given file
1135
+     *
1136
+     * @return \OCP\IPreview
1137
+     */
1138
+    public function getPreviewManager() {
1139
+        return $this->query('PreviewManager');
1140
+    }
1141
+
1142
+    /**
1143
+     * Returns the tag manager which can get and set tags for different object types
1144
+     *
1145
+     * @see \OCP\ITagManager::load()
1146
+     * @return \OCP\ITagManager
1147
+     */
1148
+    public function getTagManager() {
1149
+        return $this->query('TagManager');
1150
+    }
1151
+
1152
+    /**
1153
+     * Returns the system-tag manager
1154
+     *
1155
+     * @return \OCP\SystemTag\ISystemTagManager
1156
+     *
1157
+     * @since 9.0.0
1158
+     */
1159
+    public function getSystemTagManager() {
1160
+        return $this->query('SystemTagManager');
1161
+    }
1162
+
1163
+    /**
1164
+     * Returns the system-tag object mapper
1165
+     *
1166
+     * @return \OCP\SystemTag\ISystemTagObjectMapper
1167
+     *
1168
+     * @since 9.0.0
1169
+     */
1170
+    public function getSystemTagObjectMapper() {
1171
+        return $this->query('SystemTagObjectMapper');
1172
+    }
1173
+
1174
+    /**
1175
+     * Returns the avatar manager, used for avatar functionality
1176
+     *
1177
+     * @return \OCP\IAvatarManager
1178
+     */
1179
+    public function getAvatarManager() {
1180
+        return $this->query('AvatarManager');
1181
+    }
1182
+
1183
+    /**
1184
+     * Returns the root folder of ownCloud's data directory
1185
+     *
1186
+     * @return \OCP\Files\IRootFolder
1187
+     */
1188
+    public function getRootFolder() {
1189
+        return $this->query('LazyRootFolder');
1190
+    }
1191
+
1192
+    /**
1193
+     * Returns the root folder of ownCloud's data directory
1194
+     * This is the lazy variant so this gets only initialized once it
1195
+     * is actually used.
1196
+     *
1197
+     * @return \OCP\Files\IRootFolder
1198
+     */
1199
+    public function getLazyRootFolder() {
1200
+        return $this->query('LazyRootFolder');
1201
+    }
1202
+
1203
+    /**
1204
+     * Returns a view to ownCloud's files folder
1205
+     *
1206
+     * @param string $userId user ID
1207
+     * @return \OCP\Files\Folder|null
1208
+     */
1209
+    public function getUserFolder($userId = null) {
1210
+        if ($userId === null) {
1211
+            $user = $this->getUserSession()->getUser();
1212
+            if (!$user) {
1213
+                return null;
1214
+            }
1215
+            $userId = $user->getUID();
1216
+        }
1217
+        $root = $this->getRootFolder();
1218
+        return $root->getUserFolder($userId);
1219
+    }
1220
+
1221
+    /**
1222
+     * Returns an app-specific view in ownClouds data directory
1223
+     *
1224
+     * @return \OCP\Files\Folder
1225
+     * @deprecated since 9.2.0 use IAppData
1226
+     */
1227
+    public function getAppFolder() {
1228
+        $dir = '/' . \OC_App::getCurrentApp();
1229
+        $root = $this->getRootFolder();
1230
+        if (!$root->nodeExists($dir)) {
1231
+            $folder = $root->newFolder($dir);
1232
+        } else {
1233
+            $folder = $root->get($dir);
1234
+        }
1235
+        return $folder;
1236
+    }
1237
+
1238
+    /**
1239
+     * @return \OC\User\Manager
1240
+     */
1241
+    public function getUserManager() {
1242
+        return $this->query('UserManager');
1243
+    }
1244
+
1245
+    /**
1246
+     * @return \OC\Group\Manager
1247
+     */
1248
+    public function getGroupManager() {
1249
+        return $this->query('GroupManager');
1250
+    }
1251
+
1252
+    /**
1253
+     * @return \OC\User\Session
1254
+     */
1255
+    public function getUserSession() {
1256
+        return $this->query('UserSession');
1257
+    }
1258
+
1259
+    /**
1260
+     * @return \OCP\ISession
1261
+     */
1262
+    public function getSession() {
1263
+        return $this->query('UserSession')->getSession();
1264
+    }
1265
+
1266
+    /**
1267
+     * @param \OCP\ISession $session
1268
+     */
1269
+    public function setSession(\OCP\ISession $session) {
1270
+        $this->query(SessionStorage::class)->setSession($session);
1271
+        $this->query('UserSession')->setSession($session);
1272
+        $this->query(Store::class)->setSession($session);
1273
+    }
1274
+
1275
+    /**
1276
+     * @return \OC\Authentication\TwoFactorAuth\Manager
1277
+     */
1278
+    public function getTwoFactorAuthManager() {
1279
+        return $this->query('\OC\Authentication\TwoFactorAuth\Manager');
1280
+    }
1281
+
1282
+    /**
1283
+     * @return \OC\NavigationManager
1284
+     */
1285
+    public function getNavigationManager() {
1286
+        return $this->query('NavigationManager');
1287
+    }
1288
+
1289
+    /**
1290
+     * @return \OCP\IConfig
1291
+     */
1292
+    public function getConfig() {
1293
+        return $this->query('AllConfig');
1294
+    }
1295
+
1296
+    /**
1297
+     * @return \OC\SystemConfig
1298
+     */
1299
+    public function getSystemConfig() {
1300
+        return $this->query('SystemConfig');
1301
+    }
1302
+
1303
+    /**
1304
+     * Returns the app config manager
1305
+     *
1306
+     * @return \OCP\IAppConfig
1307
+     */
1308
+    public function getAppConfig() {
1309
+        return $this->query('AppConfig');
1310
+    }
1311
+
1312
+    /**
1313
+     * @return \OCP\L10N\IFactory
1314
+     */
1315
+    public function getL10NFactory() {
1316
+        return $this->query('L10NFactory');
1317
+    }
1318
+
1319
+    /**
1320
+     * get an L10N instance
1321
+     *
1322
+     * @param string $app appid
1323
+     * @param string $lang
1324
+     * @return IL10N
1325
+     */
1326
+    public function getL10N($app, $lang = null) {
1327
+        return $this->getL10NFactory()->get($app, $lang);
1328
+    }
1329
+
1330
+    /**
1331
+     * @return \OCP\IURLGenerator
1332
+     */
1333
+    public function getURLGenerator() {
1334
+        return $this->query('URLGenerator');
1335
+    }
1336
+
1337
+    /**
1338
+     * @return \OCP\IHelper
1339
+     */
1340
+    public function getHelper() {
1341
+        return $this->query('AppHelper');
1342
+    }
1343
+
1344
+    /**
1345
+     * @return AppFetcher
1346
+     */
1347
+    public function getAppFetcher() {
1348
+        return $this->query(AppFetcher::class);
1349
+    }
1350
+
1351
+    /**
1352
+     * Returns an ICache instance. Since 8.1.0 it returns a fake cache. Use
1353
+     * getMemCacheFactory() instead.
1354
+     *
1355
+     * @return \OCP\ICache
1356
+     * @deprecated 8.1.0 use getMemCacheFactory to obtain a proper cache
1357
+     */
1358
+    public function getCache() {
1359
+        return $this->query('UserCache');
1360
+    }
1361
+
1362
+    /**
1363
+     * Returns an \OCP\CacheFactory instance
1364
+     *
1365
+     * @return \OCP\ICacheFactory
1366
+     */
1367
+    public function getMemCacheFactory() {
1368
+        return $this->query('MemCacheFactory');
1369
+    }
1370
+
1371
+    /**
1372
+     * Returns an \OC\RedisFactory instance
1373
+     *
1374
+     * @return \OC\RedisFactory
1375
+     */
1376
+    public function getGetRedisFactory() {
1377
+        return $this->query('RedisFactory');
1378
+    }
1379
+
1380
+
1381
+    /**
1382
+     * Returns the current session
1383
+     *
1384
+     * @return \OCP\IDBConnection
1385
+     */
1386
+    public function getDatabaseConnection() {
1387
+        return $this->query('DatabaseConnection');
1388
+    }
1389
+
1390
+    /**
1391
+     * Returns the activity manager
1392
+     *
1393
+     * @return \OCP\Activity\IManager
1394
+     */
1395
+    public function getActivityManager() {
1396
+        return $this->query('ActivityManager');
1397
+    }
1398
+
1399
+    /**
1400
+     * Returns an job list for controlling background jobs
1401
+     *
1402
+     * @return \OCP\BackgroundJob\IJobList
1403
+     */
1404
+    public function getJobList() {
1405
+        return $this->query('JobList');
1406
+    }
1407
+
1408
+    /**
1409
+     * Returns a logger instance
1410
+     *
1411
+     * @return \OCP\ILogger
1412
+     */
1413
+    public function getLogger() {
1414
+        return $this->query('Logger');
1415
+    }
1416
+
1417
+    /**
1418
+     * Returns a router for generating and matching urls
1419
+     *
1420
+     * @return \OCP\Route\IRouter
1421
+     */
1422
+    public function getRouter() {
1423
+        return $this->query('Router');
1424
+    }
1425
+
1426
+    /**
1427
+     * Returns a search instance
1428
+     *
1429
+     * @return \OCP\ISearch
1430
+     */
1431
+    public function getSearch() {
1432
+        return $this->query('Search');
1433
+    }
1434
+
1435
+    /**
1436
+     * Returns a SecureRandom instance
1437
+     *
1438
+     * @return \OCP\Security\ISecureRandom
1439
+     */
1440
+    public function getSecureRandom() {
1441
+        return $this->query('SecureRandom');
1442
+    }
1443
+
1444
+    /**
1445
+     * Returns a Crypto instance
1446
+     *
1447
+     * @return \OCP\Security\ICrypto
1448
+     */
1449
+    public function getCrypto() {
1450
+        return $this->query('Crypto');
1451
+    }
1452
+
1453
+    /**
1454
+     * Returns a Hasher instance
1455
+     *
1456
+     * @return \OCP\Security\IHasher
1457
+     */
1458
+    public function getHasher() {
1459
+        return $this->query('Hasher');
1460
+    }
1461
+
1462
+    /**
1463
+     * Returns a CredentialsManager instance
1464
+     *
1465
+     * @return \OCP\Security\ICredentialsManager
1466
+     */
1467
+    public function getCredentialsManager() {
1468
+        return $this->query('CredentialsManager');
1469
+    }
1470
+
1471
+    /**
1472
+     * Returns an instance of the HTTP helper class
1473
+     *
1474
+     * @deprecated Use getHTTPClientService()
1475
+     * @return \OC\HTTPHelper
1476
+     */
1477
+    public function getHTTPHelper() {
1478
+        return $this->query('HTTPHelper');
1479
+    }
1480
+
1481
+    /**
1482
+     * Get the certificate manager for the user
1483
+     *
1484
+     * @param string $userId (optional) if not specified the current loggedin user is used, use null to get the system certificate manager
1485
+     * @return \OCP\ICertificateManager | null if $uid is null and no user is logged in
1486
+     */
1487
+    public function getCertificateManager($userId = '') {
1488
+        if ($userId === '') {
1489
+            $userSession = $this->getUserSession();
1490
+            $user = $userSession->getUser();
1491
+            if (is_null($user)) {
1492
+                return null;
1493
+            }
1494
+            $userId = $user->getUID();
1495
+        }
1496
+        return new CertificateManager(
1497
+            $userId,
1498
+            new View(),
1499
+            $this->getConfig(),
1500
+            $this->getLogger(),
1501
+            $this->getSecureRandom()
1502
+        );
1503
+    }
1504
+
1505
+    /**
1506
+     * Returns an instance of the HTTP client service
1507
+     *
1508
+     * @return \OCP\Http\Client\IClientService
1509
+     */
1510
+    public function getHTTPClientService() {
1511
+        return $this->query('HttpClientService');
1512
+    }
1513
+
1514
+    /**
1515
+     * Create a new event source
1516
+     *
1517
+     * @return \OCP\IEventSource
1518
+     */
1519
+    public function createEventSource() {
1520
+        return new \OC_EventSource();
1521
+    }
1522
+
1523
+    /**
1524
+     * Get the active event logger
1525
+     *
1526
+     * The returned logger only logs data when debug mode is enabled
1527
+     *
1528
+     * @return \OCP\Diagnostics\IEventLogger
1529
+     */
1530
+    public function getEventLogger() {
1531
+        return $this->query('EventLogger');
1532
+    }
1533
+
1534
+    /**
1535
+     * Get the active query logger
1536
+     *
1537
+     * The returned logger only logs data when debug mode is enabled
1538
+     *
1539
+     * @return \OCP\Diagnostics\IQueryLogger
1540
+     */
1541
+    public function getQueryLogger() {
1542
+        return $this->query('QueryLogger');
1543
+    }
1544
+
1545
+    /**
1546
+     * Get the manager for temporary files and folders
1547
+     *
1548
+     * @return \OCP\ITempManager
1549
+     */
1550
+    public function getTempManager() {
1551
+        return $this->query('TempManager');
1552
+    }
1553
+
1554
+    /**
1555
+     * Get the app manager
1556
+     *
1557
+     * @return \OCP\App\IAppManager
1558
+     */
1559
+    public function getAppManager() {
1560
+        return $this->query('AppManager');
1561
+    }
1562
+
1563
+    /**
1564
+     * Creates a new mailer
1565
+     *
1566
+     * @return \OCP\Mail\IMailer
1567
+     */
1568
+    public function getMailer() {
1569
+        return $this->query('Mailer');
1570
+    }
1571
+
1572
+    /**
1573
+     * Get the webroot
1574
+     *
1575
+     * @return string
1576
+     */
1577
+    public function getWebRoot() {
1578
+        return $this->webRoot;
1579
+    }
1580
+
1581
+    /**
1582
+     * @return \OC\OCSClient
1583
+     */
1584
+    public function getOcsClient() {
1585
+        return $this->query('OcsClient');
1586
+    }
1587
+
1588
+    /**
1589
+     * @return \OCP\IDateTimeZone
1590
+     */
1591
+    public function getDateTimeZone() {
1592
+        return $this->query('DateTimeZone');
1593
+    }
1594
+
1595
+    /**
1596
+     * @return \OCP\IDateTimeFormatter
1597
+     */
1598
+    public function getDateTimeFormatter() {
1599
+        return $this->query('DateTimeFormatter');
1600
+    }
1601
+
1602
+    /**
1603
+     * @return \OCP\Files\Config\IMountProviderCollection
1604
+     */
1605
+    public function getMountProviderCollection() {
1606
+        return $this->query('MountConfigManager');
1607
+    }
1608
+
1609
+    /**
1610
+     * Get the IniWrapper
1611
+     *
1612
+     * @return IniGetWrapper
1613
+     */
1614
+    public function getIniWrapper() {
1615
+        return $this->query('IniWrapper');
1616
+    }
1617
+
1618
+    /**
1619
+     * @return \OCP\Command\IBus
1620
+     */
1621
+    public function getCommandBus() {
1622
+        return $this->query('AsyncCommandBus');
1623
+    }
1624
+
1625
+    /**
1626
+     * Get the trusted domain helper
1627
+     *
1628
+     * @return TrustedDomainHelper
1629
+     */
1630
+    public function getTrustedDomainHelper() {
1631
+        return $this->query('TrustedDomainHelper');
1632
+    }
1633
+
1634
+    /**
1635
+     * Get the locking provider
1636
+     *
1637
+     * @return \OCP\Lock\ILockingProvider
1638
+     * @since 8.1.0
1639
+     */
1640
+    public function getLockingProvider() {
1641
+        return $this->query('LockingProvider');
1642
+    }
1643
+
1644
+    /**
1645
+     * @return \OCP\Files\Mount\IMountManager
1646
+     **/
1647
+    function getMountManager() {
1648
+        return $this->query('MountManager');
1649
+    }
1650
+
1651
+    /** @return \OCP\Files\Config\IUserMountCache */
1652
+    function getUserMountCache() {
1653
+        return $this->query('UserMountCache');
1654
+    }
1655
+
1656
+    /**
1657
+     * Get the MimeTypeDetector
1658
+     *
1659
+     * @return \OCP\Files\IMimeTypeDetector
1660
+     */
1661
+    public function getMimeTypeDetector() {
1662
+        return $this->query('MimeTypeDetector');
1663
+    }
1664
+
1665
+    /**
1666
+     * Get the MimeTypeLoader
1667
+     *
1668
+     * @return \OCP\Files\IMimeTypeLoader
1669
+     */
1670
+    public function getMimeTypeLoader() {
1671
+        return $this->query('MimeTypeLoader');
1672
+    }
1673
+
1674
+    /**
1675
+     * Get the manager of all the capabilities
1676
+     *
1677
+     * @return \OC\CapabilitiesManager
1678
+     */
1679
+    public function getCapabilitiesManager() {
1680
+        return $this->query('CapabilitiesManager');
1681
+    }
1682
+
1683
+    /**
1684
+     * Get the EventDispatcher
1685
+     *
1686
+     * @return EventDispatcherInterface
1687
+     * @since 8.2.0
1688
+     */
1689
+    public function getEventDispatcher() {
1690
+        return $this->query('EventDispatcher');
1691
+    }
1692
+
1693
+    /**
1694
+     * Get the Notification Manager
1695
+     *
1696
+     * @return \OCP\Notification\IManager
1697
+     * @since 8.2.0
1698
+     */
1699
+    public function getNotificationManager() {
1700
+        return $this->query('NotificationManager');
1701
+    }
1702
+
1703
+    /**
1704
+     * @return \OCP\Comments\ICommentsManager
1705
+     */
1706
+    public function getCommentsManager() {
1707
+        return $this->query('CommentsManager');
1708
+    }
1709
+
1710
+    /**
1711
+     * @return \OCA\Theming\ThemingDefaults
1712
+     */
1713
+    public function getThemingDefaults() {
1714
+        return $this->query('ThemingDefaults');
1715
+    }
1716
+
1717
+    /**
1718
+     * @return \OC\IntegrityCheck\Checker
1719
+     */
1720
+    public function getIntegrityCodeChecker() {
1721
+        return $this->query('IntegrityCodeChecker');
1722
+    }
1723
+
1724
+    /**
1725
+     * @return \OC\Session\CryptoWrapper
1726
+     */
1727
+    public function getSessionCryptoWrapper() {
1728
+        return $this->query('CryptoWrapper');
1729
+    }
1730
+
1731
+    /**
1732
+     * @return CsrfTokenManager
1733
+     */
1734
+    public function getCsrfTokenManager() {
1735
+        return $this->query('CsrfTokenManager');
1736
+    }
1737
+
1738
+    /**
1739
+     * @return Throttler
1740
+     */
1741
+    public function getBruteForceThrottler() {
1742
+        return $this->query('Throttler');
1743
+    }
1744
+
1745
+    /**
1746
+     * @return IContentSecurityPolicyManager
1747
+     */
1748
+    public function getContentSecurityPolicyManager() {
1749
+        return $this->query('ContentSecurityPolicyManager');
1750
+    }
1751
+
1752
+    /**
1753
+     * @return ContentSecurityPolicyNonceManager
1754
+     */
1755
+    public function getContentSecurityPolicyNonceManager() {
1756
+        return $this->query('ContentSecurityPolicyNonceManager');
1757
+    }
1758
+
1759
+    /**
1760
+     * Not a public API as of 8.2, wait for 9.0
1761
+     *
1762
+     * @return \OCA\Files_External\Service\BackendService
1763
+     */
1764
+    public function getStoragesBackendService() {
1765
+        return $this->query('OCA\\Files_External\\Service\\BackendService');
1766
+    }
1767
+
1768
+    /**
1769
+     * Not a public API as of 8.2, wait for 9.0
1770
+     *
1771
+     * @return \OCA\Files_External\Service\GlobalStoragesService
1772
+     */
1773
+    public function getGlobalStoragesService() {
1774
+        return $this->query('OCA\\Files_External\\Service\\GlobalStoragesService');
1775
+    }
1776
+
1777
+    /**
1778
+     * Not a public API as of 8.2, wait for 9.0
1779
+     *
1780
+     * @return \OCA\Files_External\Service\UserGlobalStoragesService
1781
+     */
1782
+    public function getUserGlobalStoragesService() {
1783
+        return $this->query('OCA\\Files_External\\Service\\UserGlobalStoragesService');
1784
+    }
1785
+
1786
+    /**
1787
+     * Not a public API as of 8.2, wait for 9.0
1788
+     *
1789
+     * @return \OCA\Files_External\Service\UserStoragesService
1790
+     */
1791
+    public function getUserStoragesService() {
1792
+        return $this->query('OCA\\Files_External\\Service\\UserStoragesService');
1793
+    }
1794
+
1795
+    /**
1796
+     * @return \OCP\Share\IManager
1797
+     */
1798
+    public function getShareManager() {
1799
+        return $this->query('ShareManager');
1800
+    }
1801
+
1802
+    /**
1803
+     * @return \OCP\Collaboration\Collaborators\ISearch
1804
+     */
1805
+    public function getCollaboratorSearch() {
1806
+        return $this->query('CollaboratorSearch');
1807
+    }
1808
+
1809
+    /**
1810
+     * @return \OCP\Collaboration\AutoComplete\IManager
1811
+     */
1812
+    public function getAutoCompleteManager(){
1813
+        return $this->query('AutoCompleteManager');
1814
+    }
1815
+
1816
+    /**
1817
+     * Returns the LDAP Provider
1818
+     *
1819
+     * @return \OCP\LDAP\ILDAPProvider
1820
+     */
1821
+    public function getLDAPProvider() {
1822
+        return $this->query('LDAPProvider');
1823
+    }
1824
+
1825
+    /**
1826
+     * @return \OCP\Settings\IManager
1827
+     */
1828
+    public function getSettingsManager() {
1829
+        return $this->query('SettingsManager');
1830
+    }
1831
+
1832
+    /**
1833
+     * @return \OCP\Files\IAppData
1834
+     */
1835
+    public function getAppDataDir($app) {
1836
+        /** @var \OC\Files\AppData\Factory $factory */
1837
+        $factory = $this->query(\OC\Files\AppData\Factory::class);
1838
+        return $factory->get($app);
1839
+    }
1840
+
1841
+    /**
1842
+     * @return \OCP\Lockdown\ILockdownManager
1843
+     */
1844
+    public function getLockdownManager() {
1845
+        return $this->query('LockdownManager');
1846
+    }
1847
+
1848
+    /**
1849
+     * @return \OCP\Federation\ICloudIdManager
1850
+     */
1851
+    public function getCloudIdManager() {
1852
+        return $this->query(ICloudIdManager::class);
1853
+    }
1854 1854
 }
Please login to merge, or discard this patch.