Completed
Push — stable13 ( a2d82d...e3b401 )
by
unknown
20:25 queued 10:05
created
lib/private/Cache/File.php 3 patches
Doc Comments   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -95,7 +95,7 @@
 block discarded – undo
95 95
 	 * @param string $key
96 96
 	 * @param mixed $value
97 97
 	 * @param int $ttl
98
-	 * @return bool|mixed
98
+	 * @return boolean
99 99
 	 * @throws \OC\ForbiddenException
100 100
 	 */
101 101
 	public function set($key, $value, $ttl = 0) {
Please login to merge, or discard this patch.
Spacing   +11 added lines, -11 removed lines patch added patch discarded remove patch
@@ -51,10 +51,10 @@  discard block
 block discarded – undo
51 51
 			$rootView = new View();
52 52
 			$user = \OC::$server->getUserSession()->getUser();
53 53
 			Filesystem::initMountPoints($user->getUID());
54
-			if (!$rootView->file_exists('/' . $user->getUID() . '/cache')) {
55
-				$rootView->mkdir('/' . $user->getUID() . '/cache');
54
+			if (!$rootView->file_exists('/'.$user->getUID().'/cache')) {
55
+				$rootView->mkdir('/'.$user->getUID().'/cache');
56 56
 			}
57
-			$this->storage = new View('/' . $user->getUID() . '/cache');
57
+			$this->storage = new View('/'.$user->getUID().'/cache');
58 58
 			return $this->storage;
59 59
 		} else {
60 60
 			\OCP\Util::writeLog('core', 'Can\'t get cache storage, user not logged in', \OCP\Util::ERROR);
@@ -104,12 +104,12 @@  discard block
 block discarded – undo
104 104
 		// unique id to avoid chunk collision, just in case
105 105
 		$uniqueId = \OC::$server->getSecureRandom()->generate(
106 106
 			16,
107
-			ISecureRandom::CHAR_DIGITS . ISecureRandom::CHAR_LOWER . ISecureRandom::CHAR_UPPER
107
+			ISecureRandom::CHAR_DIGITS.ISecureRandom::CHAR_LOWER.ISecureRandom::CHAR_UPPER
108 108
 		);
109 109
 
110 110
 		// use part file to prevent hasKey() to find the key
111 111
 		// while it is being written
112
-		$keyPart = $key . '.' . $uniqueId . '.part';
112
+		$keyPart = $key.'.'.$uniqueId.'.part';
113 113
 		if ($storage and $storage->file_put_contents($keyPart, $value)) {
114 114
 			if ($ttl === 0) {
115 115
 				$ttl = 86400; // 60*60*24
@@ -158,7 +158,7 @@  discard block
 block discarded – undo
158 158
 			if (is_resource($dh)) {
159 159
 				while (($file = readdir($dh)) !== false) {
160 160
 					if ($file != '.' and $file != '..' and ($prefix === '' || strpos($file, $prefix) === 0)) {
161
-						$storage->unlink('/' . $file);
161
+						$storage->unlink('/'.$file);
162 162
 					}
163 163
 				}
164 164
 			}
@@ -183,17 +183,17 @@  discard block
 block discarded – undo
183 183
 			while (($file = readdir($dh)) !== false) {
184 184
 				if ($file != '.' and $file != '..') {
185 185
 					try {
186
-						$mtime = $storage->filemtime('/' . $file);
186
+						$mtime = $storage->filemtime('/'.$file);
187 187
 						if ($mtime < $now) {
188
-							$storage->unlink('/' . $file);
188
+							$storage->unlink('/'.$file);
189 189
 						}
190 190
 					} catch (\OCP\Lock\LockedException $e) {
191 191
 						// ignore locked chunks
192
-						\OC::$server->getLogger()->debug('Could not cleanup locked chunk "' . $file . '"', array('app' => 'core'));
192
+						\OC::$server->getLogger()->debug('Could not cleanup locked chunk "'.$file.'"', array('app' => 'core'));
193 193
 					} catch (\OCP\Files\ForbiddenException $e) {
194
-						\OC::$server->getLogger()->debug('Could not cleanup forbidden chunk "' . $file . '"', array('app' => 'core'));
194
+						\OC::$server->getLogger()->debug('Could not cleanup forbidden chunk "'.$file.'"', array('app' => 'core'));
195 195
 					} catch (\OCP\Files\LockNotAcquiredException $e) {
196
-						\OC::$server->getLogger()->debug('Could not cleanup locked chunk "' . $file . '"', array('app' => 'core'));
196
+						\OC::$server->getLogger()->debug('Could not cleanup locked chunk "'.$file.'"', array('app' => 'core'));
197 197
 					}
198 198
 				}
199 199
 			}
Please login to merge, or discard this patch.
Indentation   +157 added lines, -157 removed lines patch added patch discarded remove patch
@@ -33,170 +33,170 @@
 block discarded – undo
33 33
 
34 34
 class File implements ICache {
35 35
 
36
-	/** @var View */
37
-	protected $storage;
36
+    /** @var View */
37
+    protected $storage;
38 38
 
39
-	/**
40
-	 * Returns the cache storage for the logged in user
41
-	 *
42
-	 * @return \OC\Files\View cache storage
43
-	 * @throws \OC\ForbiddenException
44
-	 * @throws \OC\User\NoUserException
45
-	 */
46
-	protected function getStorage() {
47
-		if (isset($this->storage)) {
48
-			return $this->storage;
49
-		}
50
-		if (\OC::$server->getUserSession()->isLoggedIn()) {
51
-			$rootView = new View();
52
-			$user = \OC::$server->getUserSession()->getUser();
53
-			Filesystem::initMountPoints($user->getUID());
54
-			if (!$rootView->file_exists('/' . $user->getUID() . '/cache')) {
55
-				$rootView->mkdir('/' . $user->getUID() . '/cache');
56
-			}
57
-			$this->storage = new View('/' . $user->getUID() . '/cache');
58
-			return $this->storage;
59
-		} else {
60
-			\OCP\Util::writeLog('core', 'Can\'t get cache storage, user not logged in', \OCP\Util::ERROR);
61
-			throw new \OC\ForbiddenException('Can\t get cache storage, user not logged in');
62
-		}
63
-	}
39
+    /**
40
+     * Returns the cache storage for the logged in user
41
+     *
42
+     * @return \OC\Files\View cache storage
43
+     * @throws \OC\ForbiddenException
44
+     * @throws \OC\User\NoUserException
45
+     */
46
+    protected function getStorage() {
47
+        if (isset($this->storage)) {
48
+            return $this->storage;
49
+        }
50
+        if (\OC::$server->getUserSession()->isLoggedIn()) {
51
+            $rootView = new View();
52
+            $user = \OC::$server->getUserSession()->getUser();
53
+            Filesystem::initMountPoints($user->getUID());
54
+            if (!$rootView->file_exists('/' . $user->getUID() . '/cache')) {
55
+                $rootView->mkdir('/' . $user->getUID() . '/cache');
56
+            }
57
+            $this->storage = new View('/' . $user->getUID() . '/cache');
58
+            return $this->storage;
59
+        } else {
60
+            \OCP\Util::writeLog('core', 'Can\'t get cache storage, user not logged in', \OCP\Util::ERROR);
61
+            throw new \OC\ForbiddenException('Can\t get cache storage, user not logged in');
62
+        }
63
+    }
64 64
 
65
-	/**
66
-	 * @param string $key
67
-	 * @return mixed|null
68
-	 * @throws \OC\ForbiddenException
69
-	 */
70
-	public function get($key) {
71
-		$result = null;
72
-		if ($this->hasKey($key)) {
73
-			$storage = $this->getStorage();
74
-			$result = $storage->file_get_contents($key);
75
-		}
76
-		return $result;
77
-	}
65
+    /**
66
+     * @param string $key
67
+     * @return mixed|null
68
+     * @throws \OC\ForbiddenException
69
+     */
70
+    public function get($key) {
71
+        $result = null;
72
+        if ($this->hasKey($key)) {
73
+            $storage = $this->getStorage();
74
+            $result = $storage->file_get_contents($key);
75
+        }
76
+        return $result;
77
+    }
78 78
 
79
-	/**
80
-	 * Returns the size of the stored/cached data
81
-	 *
82
-	 * @param string $key
83
-	 * @return int
84
-	 */
85
-	public function size($key) {
86
-		$result = 0;
87
-		if ($this->hasKey($key)) {
88
-			$storage = $this->getStorage();
89
-			$result = $storage->filesize($key);
90
-		}
91
-		return $result;
92
-	}
79
+    /**
80
+     * Returns the size of the stored/cached data
81
+     *
82
+     * @param string $key
83
+     * @return int
84
+     */
85
+    public function size($key) {
86
+        $result = 0;
87
+        if ($this->hasKey($key)) {
88
+            $storage = $this->getStorage();
89
+            $result = $storage->filesize($key);
90
+        }
91
+        return $result;
92
+    }
93 93
 
94
-	/**
95
-	 * @param string $key
96
-	 * @param mixed $value
97
-	 * @param int $ttl
98
-	 * @return bool|mixed
99
-	 * @throws \OC\ForbiddenException
100
-	 */
101
-	public function set($key, $value, $ttl = 0) {
102
-		$storage = $this->getStorage();
103
-		$result = false;
104
-		// unique id to avoid chunk collision, just in case
105
-		$uniqueId = \OC::$server->getSecureRandom()->generate(
106
-			16,
107
-			ISecureRandom::CHAR_DIGITS . ISecureRandom::CHAR_LOWER . ISecureRandom::CHAR_UPPER
108
-		);
94
+    /**
95
+     * @param string $key
96
+     * @param mixed $value
97
+     * @param int $ttl
98
+     * @return bool|mixed
99
+     * @throws \OC\ForbiddenException
100
+     */
101
+    public function set($key, $value, $ttl = 0) {
102
+        $storage = $this->getStorage();
103
+        $result = false;
104
+        // unique id to avoid chunk collision, just in case
105
+        $uniqueId = \OC::$server->getSecureRandom()->generate(
106
+            16,
107
+            ISecureRandom::CHAR_DIGITS . ISecureRandom::CHAR_LOWER . ISecureRandom::CHAR_UPPER
108
+        );
109 109
 
110
-		// use part file to prevent hasKey() to find the key
111
-		// while it is being written
112
-		$keyPart = $key . '.' . $uniqueId . '.part';
113
-		if ($storage and $storage->file_put_contents($keyPart, $value)) {
114
-			if ($ttl === 0) {
115
-				$ttl = 86400; // 60*60*24
116
-			}
117
-			$result = $storage->touch($keyPart, time() + $ttl);
118
-			$result &= $storage->rename($keyPart, $key);
119
-		}
120
-		return $result;
121
-	}
110
+        // use part file to prevent hasKey() to find the key
111
+        // while it is being written
112
+        $keyPart = $key . '.' . $uniqueId . '.part';
113
+        if ($storage and $storage->file_put_contents($keyPart, $value)) {
114
+            if ($ttl === 0) {
115
+                $ttl = 86400; // 60*60*24
116
+            }
117
+            $result = $storage->touch($keyPart, time() + $ttl);
118
+            $result &= $storage->rename($keyPart, $key);
119
+        }
120
+        return $result;
121
+    }
122 122
 
123
-	/**
124
-	 * @param string $key
125
-	 * @return bool
126
-	 * @throws \OC\ForbiddenException
127
-	 */
128
-	public function hasKey($key) {
129
-		$storage = $this->getStorage();
130
-		if ($storage && $storage->is_file($key) && $storage->isReadable($key)) {
131
-			return true;
132
-		}
133
-		return false;
134
-	}
123
+    /**
124
+     * @param string $key
125
+     * @return bool
126
+     * @throws \OC\ForbiddenException
127
+     */
128
+    public function hasKey($key) {
129
+        $storage = $this->getStorage();
130
+        if ($storage && $storage->is_file($key) && $storage->isReadable($key)) {
131
+            return true;
132
+        }
133
+        return false;
134
+    }
135 135
 
136
-	/**
137
-	 * @param string $key
138
-	 * @return bool|mixed
139
-	 * @throws \OC\ForbiddenException
140
-	 */
141
-	public function remove($key) {
142
-		$storage = $this->getStorage();
143
-		if (!$storage) {
144
-			return false;
145
-		}
146
-		return $storage->unlink($key);
147
-	}
136
+    /**
137
+     * @param string $key
138
+     * @return bool|mixed
139
+     * @throws \OC\ForbiddenException
140
+     */
141
+    public function remove($key) {
142
+        $storage = $this->getStorage();
143
+        if (!$storage) {
144
+            return false;
145
+        }
146
+        return $storage->unlink($key);
147
+    }
148 148
 
149
-	/**
150
-	 * @param string $prefix
151
-	 * @return bool
152
-	 * @throws \OC\ForbiddenException
153
-	 */
154
-	public function clear($prefix = '') {
155
-		$storage = $this->getStorage();
156
-		if ($storage and $storage->is_dir('/')) {
157
-			$dh = $storage->opendir('/');
158
-			if (is_resource($dh)) {
159
-				while (($file = readdir($dh)) !== false) {
160
-					if ($file != '.' and $file != '..' and ($prefix === '' || strpos($file, $prefix) === 0)) {
161
-						$storage->unlink('/' . $file);
162
-					}
163
-				}
164
-			}
165
-		}
166
-		return true;
167
-	}
149
+    /**
150
+     * @param string $prefix
151
+     * @return bool
152
+     * @throws \OC\ForbiddenException
153
+     */
154
+    public function clear($prefix = '') {
155
+        $storage = $this->getStorage();
156
+        if ($storage and $storage->is_dir('/')) {
157
+            $dh = $storage->opendir('/');
158
+            if (is_resource($dh)) {
159
+                while (($file = readdir($dh)) !== false) {
160
+                    if ($file != '.' and $file != '..' and ($prefix === '' || strpos($file, $prefix) === 0)) {
161
+                        $storage->unlink('/' . $file);
162
+                    }
163
+                }
164
+            }
165
+        }
166
+        return true;
167
+    }
168 168
 
169
-	/**
170
-	 * Runs GC
171
-	 * @throws \OC\ForbiddenException
172
-	 */
173
-	public function gc() {
174
-		$storage = $this->getStorage();
175
-		if ($storage and $storage->is_dir('/')) {
176
-			// extra hour safety, in case of stray part chunks that take longer to write,
177
-			// because touch() is only called after the chunk was finished
178
-			$now = time() - 3600;
179
-			$dh = $storage->opendir('/');
180
-			if (!is_resource($dh)) {
181
-				return null;
182
-			}
183
-			while (($file = readdir($dh)) !== false) {
184
-				if ($file != '.' and $file != '..') {
185
-					try {
186
-						$mtime = $storage->filemtime('/' . $file);
187
-						if ($mtime < $now) {
188
-							$storage->unlink('/' . $file);
189
-						}
190
-					} catch (\OCP\Lock\LockedException $e) {
191
-						// ignore locked chunks
192
-						\OC::$server->getLogger()->debug('Could not cleanup locked chunk "' . $file . '"', array('app' => 'core'));
193
-					} catch (\OCP\Files\ForbiddenException $e) {
194
-						\OC::$server->getLogger()->debug('Could not cleanup forbidden chunk "' . $file . '"', array('app' => 'core'));
195
-					} catch (\OCP\Files\LockNotAcquiredException $e) {
196
-						\OC::$server->getLogger()->debug('Could not cleanup locked chunk "' . $file . '"', array('app' => 'core'));
197
-					}
198
-				}
199
-			}
200
-		}
201
-	}
169
+    /**
170
+     * Runs GC
171
+     * @throws \OC\ForbiddenException
172
+     */
173
+    public function gc() {
174
+        $storage = $this->getStorage();
175
+        if ($storage and $storage->is_dir('/')) {
176
+            // extra hour safety, in case of stray part chunks that take longer to write,
177
+            // because touch() is only called after the chunk was finished
178
+            $now = time() - 3600;
179
+            $dh = $storage->opendir('/');
180
+            if (!is_resource($dh)) {
181
+                return null;
182
+            }
183
+            while (($file = readdir($dh)) !== false) {
184
+                if ($file != '.' and $file != '..') {
185
+                    try {
186
+                        $mtime = $storage->filemtime('/' . $file);
187
+                        if ($mtime < $now) {
188
+                            $storage->unlink('/' . $file);
189
+                        }
190
+                    } catch (\OCP\Lock\LockedException $e) {
191
+                        // ignore locked chunks
192
+                        \OC::$server->getLogger()->debug('Could not cleanup locked chunk "' . $file . '"', array('app' => 'core'));
193
+                    } catch (\OCP\Files\ForbiddenException $e) {
194
+                        \OC::$server->getLogger()->debug('Could not cleanup forbidden chunk "' . $file . '"', array('app' => 'core'));
195
+                    } catch (\OCP\Files\LockNotAcquiredException $e) {
196
+                        \OC::$server->getLogger()->debug('Could not cleanup locked chunk "' . $file . '"', array('app' => 'core'));
197
+                    }
198
+                }
199
+            }
200
+        }
201
+    }
202 202
 }
Please login to merge, or discard this patch.
core/Controller/LostController.php 3 patches
Doc Comments   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -132,7 +132,7 @@
 block discarded – undo
132 132
 	}
133 133
 
134 134
 	/**
135
-	 * @param $message
135
+	 * @param string $message
136 136
 	 * @param array $additional
137 137
 	 * @return array
138 138
 	 */
Please login to merge, or discard this patch.
Spacing   +10 added lines, -10 removed lines patch added patch discarded remove patch
@@ -170,7 +170,7 @@  discard block
 block discarded – undo
170 170
 	 */
171 171
 	protected function checkPasswordResetToken($token, $userId) {
172 172
 		$user = $this->userManager->get($userId);
173
-		if($user === null || !$user->isEnabled()) {
173
+		if ($user === null || !$user->isEnabled()) {
174 174
 			throw new \Exception($this->l10n->t('Couldn\'t reset password because the token is invalid'));
175 175
 		}
176 176
 
@@ -183,11 +183,11 @@  discard block
 block discarded – undo
183 183
 		}
184 184
 
185 185
 		$splittedToken = explode(':', $decryptedToken);
186
-		if(count($splittedToken) !== 2) {
186
+		if (count($splittedToken) !== 2) {
187 187
 			throw new \Exception($this->l10n->t('Couldn\'t reset password because the token is invalid'));
188 188
 		}
189 189
 
190
-		if ($splittedToken[0] < ($this->timeFactory->getTime() - 60*60*24*7) ||
190
+		if ($splittedToken[0] < ($this->timeFactory->getTime() - 60 * 60 * 24 * 7) ||
191 191
 			$user->getLastLogin() > $splittedToken[0]) {
192 192
 			throw new \Exception($this->l10n->t('Couldn\'t reset password because the token is expired'));
193 193
 		}
@@ -202,7 +202,7 @@  discard block
 block discarded – undo
202 202
 	 * @param array $additional
203 203
 	 * @return array
204 204
 	 */
205
-	private function error($message, array $additional=array()) {
205
+	private function error($message, array $additional = array()) {
206 206
 		return array_merge(array('status' => 'error', 'msg' => $message), $additional);
207 207
 	}
208 208
 
@@ -222,7 +222,7 @@  discard block
 block discarded – undo
222 222
 	 * @param string $user
223 223
 	 * @return JSONResponse
224 224
 	 */
225
-	public function email($user){
225
+	public function email($user) {
226 226
 		if ($this->config->getSystemValue('lost_password_link', '') !== '') {
227 227
 			return new JSONResponse($this->error($this->l10n->t('Password reset is disabled')));
228 228
 		}
@@ -236,7 +236,7 @@  discard block
 block discarded – undo
236 236
 		// FIXME: use HTTP error codes
237 237
 		try {
238 238
 			$this->sendEmail($user);
239
-		} catch (\Exception $e){
239
+		} catch (\Exception $e) {
240 240
 			$response = new JSONResponse($this->error($e->getMessage()));
241 241
 			$response->throttle();
242 242
 			return $response;
@@ -286,9 +286,9 @@  discard block
 block discarded – undo
286 286
 
287 287
 			$this->config->deleteUserValue($userId, 'core', 'lostpassword');
288 288
 			@\OC::$server->getUserSession()->unsetMagicInCookie();
289
-		} catch (HintException $e){
289
+		} catch (HintException $e) {
290 290
 			return $this->error($e->getHint());
291
-		} catch (\Exception $e){
291
+		} catch (\Exception $e) {
292 292
 			return $this->error($e->getMessage());
293 293
 		}
294 294
 
@@ -319,8 +319,8 @@  discard block
 block discarded – undo
319 319
 			ISecureRandom::CHAR_LOWER.
320 320
 			ISecureRandom::CHAR_UPPER
321 321
 		);
322
-		$tokenValue = $this->timeFactory->getTime() .':'. $token;
323
-		$encryptedValue = $this->crypto->encrypt($tokenValue, $email . $this->config->getSystemValue('secret'));
322
+		$tokenValue = $this->timeFactory->getTime().':'.$token;
323
+		$encryptedValue = $this->crypto->encrypt($tokenValue, $email.$this->config->getSystemValue('secret'));
324 324
 		$this->config->setUserValue($user->getUID(), 'core', 'lostpassword', $encryptedValue);
325 325
 
326 326
 		$link = $this->urlGenerator->linkToRouteAbsolute('core.lost.resetform', array('userId' => $user->getUID(), 'token' => $token));
Please login to merge, or discard this patch.
Indentation   +331 added lines, -331 removed lines patch added patch discarded remove patch
@@ -58,335 +58,335 @@
 block discarded – undo
58 58
  * @package OC\Core\Controller
59 59
  */
60 60
 class LostController extends Controller {
61
-	/** @var IURLGenerator */
62
-	protected $urlGenerator;
63
-	/** @var IUserManager */
64
-	protected $userManager;
65
-	/** @var Defaults */
66
-	protected $defaults;
67
-	/** @var IL10N */
68
-	protected $l10n;
69
-	/** @var string */
70
-	protected $from;
71
-	/** @var IManager */
72
-	protected $encryptionManager;
73
-	/** @var IConfig */
74
-	protected $config;
75
-	/** @var ISecureRandom */
76
-	protected $secureRandom;
77
-	/** @var IMailer */
78
-	protected $mailer;
79
-	/** @var ITimeFactory */
80
-	protected $timeFactory;
81
-	/** @var ICrypto */
82
-	protected $crypto;
83
-	/** @var Manager */
84
-	private $twoFactorManager;
85
-
86
-	/**
87
-	 * @param string $appName
88
-	 * @param IRequest $request
89
-	 * @param IURLGenerator $urlGenerator
90
-	 * @param IUserManager $userManager
91
-	 * @param Defaults $defaults
92
-	 * @param IL10N $l10n
93
-	 * @param IConfig $config
94
-	 * @param ISecureRandom $secureRandom
95
-	 * @param string $defaultMailAddress
96
-	 * @param IManager $encryptionManager
97
-	 * @param IMailer $mailer
98
-	 * @param ITimeFactory $timeFactory
99
-	 * @param ICrypto $crypto
100
-	 */
101
-	public function __construct($appName,
102
-								IRequest $request,
103
-								IURLGenerator $urlGenerator,
104
-								IUserManager $userManager,
105
-								Defaults $defaults,
106
-								IL10N $l10n,
107
-								IConfig $config,
108
-								ISecureRandom $secureRandom,
109
-								$defaultMailAddress,
110
-								IManager $encryptionManager,
111
-								IMailer $mailer,
112
-								ITimeFactory $timeFactory,
113
-								ICrypto $crypto,
114
-								Manager $twoFactorManager) {
115
-		parent::__construct($appName, $request);
116
-		$this->urlGenerator = $urlGenerator;
117
-		$this->userManager = $userManager;
118
-		$this->defaults = $defaults;
119
-		$this->l10n = $l10n;
120
-		$this->secureRandom = $secureRandom;
121
-		$this->from = $defaultMailAddress;
122
-		$this->encryptionManager = $encryptionManager;
123
-		$this->config = $config;
124
-		$this->mailer = $mailer;
125
-		$this->timeFactory = $timeFactory;
126
-		$this->crypto = $crypto;
127
-		$this->twoFactorManager = $twoFactorManager;
128
-	}
129
-
130
-	/**
131
-	 * Someone wants to reset their password:
132
-	 *
133
-	 * @PublicPage
134
-	 * @NoCSRFRequired
135
-	 *
136
-	 * @param string $token
137
-	 * @param string $userId
138
-	 * @return TemplateResponse
139
-	 */
140
-	public function resetform($token, $userId) {
141
-		if ($this->config->getSystemValue('lost_password_link', '') !== '') {
142
-			return new TemplateResponse('core', 'error', [
143
-					'errors' => [['error' => $this->l10n->t('Password reset is disabled')]]
144
-				],
145
-				'guest'
146
-			);
147
-		}
148
-
149
-		try {
150
-			$this->checkPasswordResetToken($token, $userId);
151
-		} catch (\Exception $e) {
152
-			return new TemplateResponse(
153
-				'core', 'error', [
154
-					"errors" => array(array("error" => $e->getMessage()))
155
-				],
156
-				'guest'
157
-			);
158
-		}
159
-
160
-		return new TemplateResponse(
161
-			'core',
162
-			'lostpassword/resetpassword',
163
-			array(
164
-				'link' => $this->urlGenerator->linkToRouteAbsolute('core.lost.setPassword', array('userId' => $userId, 'token' => $token)),
165
-			),
166
-			'guest'
167
-		);
168
-	}
169
-
170
-	/**
171
-	 * @param string $token
172
-	 * @param string $userId
173
-	 * @throws \Exception
174
-	 */
175
-	protected function checkPasswordResetToken($token, $userId) {
176
-		$user = $this->userManager->get($userId);
177
-		if($user === null || !$user->isEnabled()) {
178
-			throw new \Exception($this->l10n->t('Couldn\'t reset password because the token is invalid'));
179
-		}
180
-
181
-		try {
182
-			$encryptedToken = $this->config->getUserValue($userId, 'core', 'lostpassword', null);
183
-			$mailAddress = !is_null($user->getEMailAddress()) ? $user->getEMailAddress() : '';
184
-			$decryptedToken = $this->crypto->decrypt($encryptedToken, $mailAddress.$this->config->getSystemValue('secret'));
185
-		} catch (\Exception $e) {
186
-			throw new \Exception($this->l10n->t('Couldn\'t reset password because the token is invalid'));
187
-		}
188
-
189
-		$splittedToken = explode(':', $decryptedToken);
190
-		if(count($splittedToken) !== 2) {
191
-			throw new \Exception($this->l10n->t('Couldn\'t reset password because the token is invalid'));
192
-		}
193
-
194
-		if ($splittedToken[0] < ($this->timeFactory->getTime() - 60*60*24*7) ||
195
-			$user->getLastLogin() > $splittedToken[0]) {
196
-			throw new \Exception($this->l10n->t('Couldn\'t reset password because the token is expired'));
197
-		}
198
-
199
-		if (!hash_equals($splittedToken[1], $token)) {
200
-			throw new \Exception($this->l10n->t('Couldn\'t reset password because the token is invalid'));
201
-		}
202
-	}
203
-
204
-	/**
205
-	 * @param $message
206
-	 * @param array $additional
207
-	 * @return array
208
-	 */
209
-	private function error($message, array $additional=array()) {
210
-		return array_merge(array('status' => 'error', 'msg' => $message), $additional);
211
-	}
212
-
213
-	/**
214
-	 * @return array
215
-	 */
216
-	private function success() {
217
-		return array('status'=>'success');
218
-	}
219
-
220
-	/**
221
-	 * @PublicPage
222
-	 * @BruteForceProtection(action=passwordResetEmail)
223
-	 * @AnonRateThrottle(limit=10, period=300)
224
-	 *
225
-	 * @param string $user
226
-	 * @return JSONResponse
227
-	 */
228
-	public function email($user){
229
-		if ($this->config->getSystemValue('lost_password_link', '') !== '') {
230
-			return new JSONResponse($this->error($this->l10n->t('Password reset is disabled')));
231
-		}
232
-
233
-		\OCP\Util::emitHook(
234
-			'\OCA\Files_Sharing\API\Server2Server',
235
-			'preLoginNameUsedAsUserName',
236
-			['uid' => &$user]
237
-		);
238
-
239
-		// FIXME: use HTTP error codes
240
-		try {
241
-			$this->sendEmail($user);
242
-		} catch (\Exception $e){
243
-			$response = new JSONResponse($this->error($e->getMessage()));
244
-			$response->throttle();
245
-			return $response;
246
-		}
247
-
248
-		$response = new JSONResponse($this->success());
249
-		$response->throttle();
250
-		return $response;
251
-	}
252
-
253
-	/**
254
-	 * @PublicPage
255
-	 * @param string $token
256
-	 * @param string $userId
257
-	 * @param string $password
258
-	 * @param boolean $proceed
259
-	 * @return array
260
-	 */
261
-	public function setPassword($token, $userId, $password, $proceed) {
262
-		if ($this->config->getSystemValue('lost_password_link', '') !== '') {
263
-			return $this->error($this->l10n->t('Password reset is disabled'));
264
-		}
265
-
266
-		if ($this->encryptionManager->isEnabled() && !$proceed) {
267
-			$encryptionModules = $this->encryptionManager->getEncryptionModules();
268
-			foreach ($encryptionModules as $module) {
269
-				/** @var IEncryptionModule $instance */
270
-				$instance = call_user_func($module['callback']);
271
-				// this way we can find out whether per-user keys are used or a system wide encryption key
272
-				if ($instance->needDetailedAccessList()) {
273
-					return $this->error('', array('encryption' => true));
274
-				}
275
-			}
276
-		}
277
-
278
-		try {
279
-			$this->checkPasswordResetToken($token, $userId);
280
-			$user = $this->userManager->get($userId);
281
-
282
-			\OC_Hook::emit('\OC\Core\LostPassword\Controller\LostController', 'pre_passwordReset', array('uid' => $userId, 'password' => $password));
283
-
284
-			if (!$user->setPassword($password)) {
285
-				throw new \Exception();
286
-			}
287
-
288
-			\OC_Hook::emit('\OC\Core\LostPassword\Controller\LostController', 'post_passwordReset', array('uid' => $userId, 'password' => $password));
289
-
290
-			$this->twoFactorManager->clearTwoFactorPending($userId);
291
-
292
-			$this->config->deleteUserValue($userId, 'core', 'lostpassword');
293
-			@\OC::$server->getUserSession()->unsetMagicInCookie();
294
-		} catch (HintException $e){
295
-			return $this->error($e->getHint());
296
-		} catch (\Exception $e){
297
-			return $this->error($e->getMessage());
298
-		}
299
-
300
-		return $this->success();
301
-	}
302
-
303
-	/**
304
-	 * @param string $input
305
-	 * @throws \Exception
306
-	 */
307
-	protected function sendEmail($input) {
308
-		$user = $this->findUserByIdOrMail($input);
309
-		$email = $user->getEMailAddress();
310
-
311
-		if (empty($email)) {
312
-			throw new \Exception(
313
-				$this->l10n->t('Could not send reset email because there is no email address for this username. Please contact your administrator.')
314
-			);
315
-		}
316
-
317
-		// Generate the token. It is stored encrypted in the database with the
318
-		// secret being the users' email address appended with the system secret.
319
-		// This makes the token automatically invalidate once the user changes
320
-		// their email address.
321
-		$token = $this->secureRandom->generate(
322
-			21,
323
-			ISecureRandom::CHAR_DIGITS.
324
-			ISecureRandom::CHAR_LOWER.
325
-			ISecureRandom::CHAR_UPPER
326
-		);
327
-		$tokenValue = $this->timeFactory->getTime() .':'. $token;
328
-		$encryptedValue = $this->crypto->encrypt($tokenValue, $email . $this->config->getSystemValue('secret'));
329
-		$this->config->setUserValue($user->getUID(), 'core', 'lostpassword', $encryptedValue);
330
-
331
-		$link = $this->urlGenerator->linkToRouteAbsolute('core.lost.resetform', array('userId' => $user->getUID(), 'token' => $token));
332
-
333
-		$emailTemplate = $this->mailer->createEMailTemplate('core.ResetPassword', [
334
-			'link' => $link,
335
-		]);
336
-
337
-		$emailTemplate->setSubject($this->l10n->t('%s password reset', [$this->defaults->getName()]));
338
-		$emailTemplate->addHeader();
339
-		$emailTemplate->addHeading($this->l10n->t('Password reset'));
340
-
341
-		$emailTemplate->addBodyText(
342
-			$this->l10n->t('Click the following button to reset your password. If you have not requested the password reset, then ignore this email.'),
343
-			$this->l10n->t('Click the following link to reset your password. If you have not requested the password reset, then ignore this email.')
344
-		);
345
-
346
-		$emailTemplate->addBodyButton(
347
-			$this->l10n->t('Reset your password'),
348
-			$link,
349
-			false
350
-		);
351
-		$emailTemplate->addFooter();
352
-
353
-		try {
354
-			$message = $this->mailer->createMessage();
355
-			$message->setTo([$email => $user->getUID()]);
356
-			$message->setFrom([$this->from => $this->defaults->getName()]);
357
-			$message->useTemplate($emailTemplate);
358
-			$this->mailer->send($message);
359
-		} catch (\Exception $e) {
360
-			throw new \Exception($this->l10n->t(
361
-				'Couldn\'t send reset email. Please contact your administrator.'
362
-			));
363
-		}
364
-	}
365
-
366
-	/**
367
-	 * @param string $input
368
-	 * @return IUser
369
-	 * @throws \InvalidArgumentException
370
-	 */
371
-	protected function findUserByIdOrMail($input) {
372
-		$user = $this->userManager->get($input);
373
-		if ($user instanceof IUser) {
374
-			if (!$user->isEnabled()) {
375
-				throw new \InvalidArgumentException($this->l10n->t('Couldn\'t send reset email. Please make sure your username is correct.'));
376
-			}
377
-
378
-			return $user;
379
-		}
380
-		$users = $this->userManager->getByEmail($input);
381
-		if (count($users) === 1) {
382
-			$user = $users[0];
383
-			if (!$user->isEnabled()) {
384
-				throw new \InvalidArgumentException($this->l10n->t('Couldn\'t send reset email. Please make sure your username is correct.'));
385
-			}
386
-
387
-			return $user;
388
-		}
389
-
390
-		throw new \InvalidArgumentException($this->l10n->t('Couldn\'t send reset email. Please make sure your username is correct.'));
391
-	}
61
+    /** @var IURLGenerator */
62
+    protected $urlGenerator;
63
+    /** @var IUserManager */
64
+    protected $userManager;
65
+    /** @var Defaults */
66
+    protected $defaults;
67
+    /** @var IL10N */
68
+    protected $l10n;
69
+    /** @var string */
70
+    protected $from;
71
+    /** @var IManager */
72
+    protected $encryptionManager;
73
+    /** @var IConfig */
74
+    protected $config;
75
+    /** @var ISecureRandom */
76
+    protected $secureRandom;
77
+    /** @var IMailer */
78
+    protected $mailer;
79
+    /** @var ITimeFactory */
80
+    protected $timeFactory;
81
+    /** @var ICrypto */
82
+    protected $crypto;
83
+    /** @var Manager */
84
+    private $twoFactorManager;
85
+
86
+    /**
87
+     * @param string $appName
88
+     * @param IRequest $request
89
+     * @param IURLGenerator $urlGenerator
90
+     * @param IUserManager $userManager
91
+     * @param Defaults $defaults
92
+     * @param IL10N $l10n
93
+     * @param IConfig $config
94
+     * @param ISecureRandom $secureRandom
95
+     * @param string $defaultMailAddress
96
+     * @param IManager $encryptionManager
97
+     * @param IMailer $mailer
98
+     * @param ITimeFactory $timeFactory
99
+     * @param ICrypto $crypto
100
+     */
101
+    public function __construct($appName,
102
+                                IRequest $request,
103
+                                IURLGenerator $urlGenerator,
104
+                                IUserManager $userManager,
105
+                                Defaults $defaults,
106
+                                IL10N $l10n,
107
+                                IConfig $config,
108
+                                ISecureRandom $secureRandom,
109
+                                $defaultMailAddress,
110
+                                IManager $encryptionManager,
111
+                                IMailer $mailer,
112
+                                ITimeFactory $timeFactory,
113
+                                ICrypto $crypto,
114
+                                Manager $twoFactorManager) {
115
+        parent::__construct($appName, $request);
116
+        $this->urlGenerator = $urlGenerator;
117
+        $this->userManager = $userManager;
118
+        $this->defaults = $defaults;
119
+        $this->l10n = $l10n;
120
+        $this->secureRandom = $secureRandom;
121
+        $this->from = $defaultMailAddress;
122
+        $this->encryptionManager = $encryptionManager;
123
+        $this->config = $config;
124
+        $this->mailer = $mailer;
125
+        $this->timeFactory = $timeFactory;
126
+        $this->crypto = $crypto;
127
+        $this->twoFactorManager = $twoFactorManager;
128
+    }
129
+
130
+    /**
131
+     * Someone wants to reset their password:
132
+     *
133
+     * @PublicPage
134
+     * @NoCSRFRequired
135
+     *
136
+     * @param string $token
137
+     * @param string $userId
138
+     * @return TemplateResponse
139
+     */
140
+    public function resetform($token, $userId) {
141
+        if ($this->config->getSystemValue('lost_password_link', '') !== '') {
142
+            return new TemplateResponse('core', 'error', [
143
+                    'errors' => [['error' => $this->l10n->t('Password reset is disabled')]]
144
+                ],
145
+                'guest'
146
+            );
147
+        }
148
+
149
+        try {
150
+            $this->checkPasswordResetToken($token, $userId);
151
+        } catch (\Exception $e) {
152
+            return new TemplateResponse(
153
+                'core', 'error', [
154
+                    "errors" => array(array("error" => $e->getMessage()))
155
+                ],
156
+                'guest'
157
+            );
158
+        }
159
+
160
+        return new TemplateResponse(
161
+            'core',
162
+            'lostpassword/resetpassword',
163
+            array(
164
+                'link' => $this->urlGenerator->linkToRouteAbsolute('core.lost.setPassword', array('userId' => $userId, 'token' => $token)),
165
+            ),
166
+            'guest'
167
+        );
168
+    }
169
+
170
+    /**
171
+     * @param string $token
172
+     * @param string $userId
173
+     * @throws \Exception
174
+     */
175
+    protected function checkPasswordResetToken($token, $userId) {
176
+        $user = $this->userManager->get($userId);
177
+        if($user === null || !$user->isEnabled()) {
178
+            throw new \Exception($this->l10n->t('Couldn\'t reset password because the token is invalid'));
179
+        }
180
+
181
+        try {
182
+            $encryptedToken = $this->config->getUserValue($userId, 'core', 'lostpassword', null);
183
+            $mailAddress = !is_null($user->getEMailAddress()) ? $user->getEMailAddress() : '';
184
+            $decryptedToken = $this->crypto->decrypt($encryptedToken, $mailAddress.$this->config->getSystemValue('secret'));
185
+        } catch (\Exception $e) {
186
+            throw new \Exception($this->l10n->t('Couldn\'t reset password because the token is invalid'));
187
+        }
188
+
189
+        $splittedToken = explode(':', $decryptedToken);
190
+        if(count($splittedToken) !== 2) {
191
+            throw new \Exception($this->l10n->t('Couldn\'t reset password because the token is invalid'));
192
+        }
193
+
194
+        if ($splittedToken[0] < ($this->timeFactory->getTime() - 60*60*24*7) ||
195
+            $user->getLastLogin() > $splittedToken[0]) {
196
+            throw new \Exception($this->l10n->t('Couldn\'t reset password because the token is expired'));
197
+        }
198
+
199
+        if (!hash_equals($splittedToken[1], $token)) {
200
+            throw new \Exception($this->l10n->t('Couldn\'t reset password because the token is invalid'));
201
+        }
202
+    }
203
+
204
+    /**
205
+     * @param $message
206
+     * @param array $additional
207
+     * @return array
208
+     */
209
+    private function error($message, array $additional=array()) {
210
+        return array_merge(array('status' => 'error', 'msg' => $message), $additional);
211
+    }
212
+
213
+    /**
214
+     * @return array
215
+     */
216
+    private function success() {
217
+        return array('status'=>'success');
218
+    }
219
+
220
+    /**
221
+     * @PublicPage
222
+     * @BruteForceProtection(action=passwordResetEmail)
223
+     * @AnonRateThrottle(limit=10, period=300)
224
+     *
225
+     * @param string $user
226
+     * @return JSONResponse
227
+     */
228
+    public function email($user){
229
+        if ($this->config->getSystemValue('lost_password_link', '') !== '') {
230
+            return new JSONResponse($this->error($this->l10n->t('Password reset is disabled')));
231
+        }
232
+
233
+        \OCP\Util::emitHook(
234
+            '\OCA\Files_Sharing\API\Server2Server',
235
+            'preLoginNameUsedAsUserName',
236
+            ['uid' => &$user]
237
+        );
238
+
239
+        // FIXME: use HTTP error codes
240
+        try {
241
+            $this->sendEmail($user);
242
+        } catch (\Exception $e){
243
+            $response = new JSONResponse($this->error($e->getMessage()));
244
+            $response->throttle();
245
+            return $response;
246
+        }
247
+
248
+        $response = new JSONResponse($this->success());
249
+        $response->throttle();
250
+        return $response;
251
+    }
252
+
253
+    /**
254
+     * @PublicPage
255
+     * @param string $token
256
+     * @param string $userId
257
+     * @param string $password
258
+     * @param boolean $proceed
259
+     * @return array
260
+     */
261
+    public function setPassword($token, $userId, $password, $proceed) {
262
+        if ($this->config->getSystemValue('lost_password_link', '') !== '') {
263
+            return $this->error($this->l10n->t('Password reset is disabled'));
264
+        }
265
+
266
+        if ($this->encryptionManager->isEnabled() && !$proceed) {
267
+            $encryptionModules = $this->encryptionManager->getEncryptionModules();
268
+            foreach ($encryptionModules as $module) {
269
+                /** @var IEncryptionModule $instance */
270
+                $instance = call_user_func($module['callback']);
271
+                // this way we can find out whether per-user keys are used or a system wide encryption key
272
+                if ($instance->needDetailedAccessList()) {
273
+                    return $this->error('', array('encryption' => true));
274
+                }
275
+            }
276
+        }
277
+
278
+        try {
279
+            $this->checkPasswordResetToken($token, $userId);
280
+            $user = $this->userManager->get($userId);
281
+
282
+            \OC_Hook::emit('\OC\Core\LostPassword\Controller\LostController', 'pre_passwordReset', array('uid' => $userId, 'password' => $password));
283
+
284
+            if (!$user->setPassword($password)) {
285
+                throw new \Exception();
286
+            }
287
+
288
+            \OC_Hook::emit('\OC\Core\LostPassword\Controller\LostController', 'post_passwordReset', array('uid' => $userId, 'password' => $password));
289
+
290
+            $this->twoFactorManager->clearTwoFactorPending($userId);
291
+
292
+            $this->config->deleteUserValue($userId, 'core', 'lostpassword');
293
+            @\OC::$server->getUserSession()->unsetMagicInCookie();
294
+        } catch (HintException $e){
295
+            return $this->error($e->getHint());
296
+        } catch (\Exception $e){
297
+            return $this->error($e->getMessage());
298
+        }
299
+
300
+        return $this->success();
301
+    }
302
+
303
+    /**
304
+     * @param string $input
305
+     * @throws \Exception
306
+     */
307
+    protected function sendEmail($input) {
308
+        $user = $this->findUserByIdOrMail($input);
309
+        $email = $user->getEMailAddress();
310
+
311
+        if (empty($email)) {
312
+            throw new \Exception(
313
+                $this->l10n->t('Could not send reset email because there is no email address for this username. Please contact your administrator.')
314
+            );
315
+        }
316
+
317
+        // Generate the token. It is stored encrypted in the database with the
318
+        // secret being the users' email address appended with the system secret.
319
+        // This makes the token automatically invalidate once the user changes
320
+        // their email address.
321
+        $token = $this->secureRandom->generate(
322
+            21,
323
+            ISecureRandom::CHAR_DIGITS.
324
+            ISecureRandom::CHAR_LOWER.
325
+            ISecureRandom::CHAR_UPPER
326
+        );
327
+        $tokenValue = $this->timeFactory->getTime() .':'. $token;
328
+        $encryptedValue = $this->crypto->encrypt($tokenValue, $email . $this->config->getSystemValue('secret'));
329
+        $this->config->setUserValue($user->getUID(), 'core', 'lostpassword', $encryptedValue);
330
+
331
+        $link = $this->urlGenerator->linkToRouteAbsolute('core.lost.resetform', array('userId' => $user->getUID(), 'token' => $token));
332
+
333
+        $emailTemplate = $this->mailer->createEMailTemplate('core.ResetPassword', [
334
+            'link' => $link,
335
+        ]);
336
+
337
+        $emailTemplate->setSubject($this->l10n->t('%s password reset', [$this->defaults->getName()]));
338
+        $emailTemplate->addHeader();
339
+        $emailTemplate->addHeading($this->l10n->t('Password reset'));
340
+
341
+        $emailTemplate->addBodyText(
342
+            $this->l10n->t('Click the following button to reset your password. If you have not requested the password reset, then ignore this email.'),
343
+            $this->l10n->t('Click the following link to reset your password. If you have not requested the password reset, then ignore this email.')
344
+        );
345
+
346
+        $emailTemplate->addBodyButton(
347
+            $this->l10n->t('Reset your password'),
348
+            $link,
349
+            false
350
+        );
351
+        $emailTemplate->addFooter();
352
+
353
+        try {
354
+            $message = $this->mailer->createMessage();
355
+            $message->setTo([$email => $user->getUID()]);
356
+            $message->setFrom([$this->from => $this->defaults->getName()]);
357
+            $message->useTemplate($emailTemplate);
358
+            $this->mailer->send($message);
359
+        } catch (\Exception $e) {
360
+            throw new \Exception($this->l10n->t(
361
+                'Couldn\'t send reset email. Please contact your administrator.'
362
+            ));
363
+        }
364
+    }
365
+
366
+    /**
367
+     * @param string $input
368
+     * @return IUser
369
+     * @throws \InvalidArgumentException
370
+     */
371
+    protected function findUserByIdOrMail($input) {
372
+        $user = $this->userManager->get($input);
373
+        if ($user instanceof IUser) {
374
+            if (!$user->isEnabled()) {
375
+                throw new \InvalidArgumentException($this->l10n->t('Couldn\'t send reset email. Please make sure your username is correct.'));
376
+            }
377
+
378
+            return $user;
379
+        }
380
+        $users = $this->userManager->getByEmail($input);
381
+        if (count($users) === 1) {
382
+            $user = $users[0];
383
+            if (!$user->isEnabled()) {
384
+                throw new \InvalidArgumentException($this->l10n->t('Couldn\'t send reset email. Please make sure your username is correct.'));
385
+            }
386
+
387
+            return $user;
388
+        }
389
+
390
+        throw new \InvalidArgumentException($this->l10n->t('Couldn\'t send reset email. Please make sure your username is correct.'));
391
+    }
392 392
 }
Please login to merge, or discard this patch.
apps/files_external/lib/Service/DBConfigService.php 3 patches
Doc Comments   +16 added lines patch added patch discarded remove patch
@@ -89,6 +89,9 @@  discard block
 block discarded – undo
89 89
 		return $this->getMountsFromQuery($query);
90 90
 	}
91 91
 
92
+	/**
93
+	 * @param string $userId
94
+	 */
92 95
 	public function getMountsForUser($userId, $groupIds) {
93 96
 		$builder = $this->connection->getQueryBuilder();
94 97
 		$query = $builder->select(['m.mount_id', 'mount_point', 'storage_backend', 'auth_backend', 'priority', 'm.type'])
@@ -125,6 +128,10 @@  discard block
 block discarded – undo
125 128
 		return $this->getMountsFromQuery($query);
126 129
 	}
127 130
 
131
+	/**
132
+	 * @param integer $type
133
+	 * @param string|null $value
134
+	 */
128 135
 	protected function getForQuery(IQueryBuilder $builder, $type, $value) {
129 136
 		$query = $builder->select(['m.mount_id', 'mount_point', 'storage_backend', 'auth_backend', 'priority', 'm.type'])
130 137
 			->from('external_mounts', 'm')
@@ -332,6 +339,9 @@  discard block
 block discarded – undo
332 339
 		}
333 340
 	}
334 341
 
342
+	/**
343
+	 * @param integer $mountId
344
+	 */
335 345
 	public function addApplicable($mountId, $type, $value) {
336 346
 		$this->connection->insertIfNotExist('*PREFIX*external_applicable', [
337 347
 			'mount_id' => $mountId,
@@ -340,6 +350,9 @@  discard block
 block discarded – undo
340 350
 		], ['mount_id', 'type', 'value']);
341 351
 	}
342 352
 
353
+	/**
354
+	 * @param integer $mountId
355
+	 */
343 356
 	public function removeApplicable($mountId, $type, $value) {
344 357
 		$builder = $this->connection->getQueryBuilder();
345 358
 		$query = $builder->delete('external_applicable')
@@ -473,6 +486,9 @@  discard block
 block discarded – undo
473 486
 		return array_combine($keys, $values);
474 487
 	}
475 488
 
489
+	/**
490
+	 * @param string $value
491
+	 */
476 492
 	private function encryptValue($value) {
477 493
 		return $this->crypto->encrypt($value);
478 494
 	}
Please login to merge, or discard this patch.
Spacing   +13 added lines, -13 removed lines patch added patch discarded remove patch
@@ -178,7 +178,7 @@  discard block
 block discarded – undo
178 178
 	 */
179 179
 	public function getAdminMountsForMultiple($type, array $values) {
180 180
 		$builder = $this->connection->getQueryBuilder();
181
-		$params = array_map(function ($value) use ($builder) {
181
+		$params = array_map(function($value) use ($builder) {
182 182
 			return $builder->createNamedParameter($value, IQueryBuilder::PARAM_STR);
183 183
 		}, $values);
184 184
 
@@ -231,7 +231,7 @@  discard block
 block discarded – undo
231 231
 				'type' => $builder->createNamedParameter($type, IQueryBuilder::PARAM_INT)
232 232
 			]);
233 233
 		$query->execute();
234
-		return (int)$this->connection->lastInsertId('*PREFIX*external_mounts');
234
+		return (int) $this->connection->lastInsertId('*PREFIX*external_mounts');
235 235
 	}
236 236
 
237 237
 	/**
@@ -367,7 +367,7 @@  discard block
 block discarded – undo
367 367
 		}
368 368
 		$uniqueMounts = array_values($uniqueMounts);
369 369
 
370
-		$mountIds = array_map(function ($mount) {
370
+		$mountIds = array_map(function($mount) {
371 371
 			return $mount['mount_id'];
372 372
 		}, $uniqueMounts);
373 373
 		$mountIds = array_values(array_unique($mountIds));
@@ -376,9 +376,9 @@  discard block
 block discarded – undo
376 376
 		$config = $this->getConfigForMounts($mountIds);
377 377
 		$options = $this->getOptionsForMounts($mountIds);
378 378
 
379
-		return array_map(function ($mount, $applicable, $config, $options) {
380
-			$mount['type'] = (int)$mount['type'];
381
-			$mount['priority'] = (int)$mount['priority'];
379
+		return array_map(function($mount, $applicable, $config, $options) {
380
+			$mount['type'] = (int) $mount['type'];
381
+			$mount['priority'] = (int) $mount['priority'];
382 382
 			$mount['applicable'] = $applicable;
383 383
 			$mount['config'] = $config;
384 384
 			$mount['options'] = $options;
@@ -400,7 +400,7 @@  discard block
 block discarded – undo
400 400
 		}
401 401
 		$builder = $this->connection->getQueryBuilder();
402 402
 		$fields[] = 'mount_id';
403
-		$placeHolders = array_map(function ($id) use ($builder) {
403
+		$placeHolders = array_map(function($id) use ($builder) {
404 404
 			return $builder->createPositionalParameter($id, IQueryBuilder::PARAM_INT);
405 405
 		}, $mountIds);
406 406
 		$query = $builder->select($fields)
@@ -414,7 +414,7 @@  discard block
 block discarded – undo
414 414
 		}
415 415
 		foreach ($rows as $row) {
416 416
 			if (isset($row['type'])) {
417
-				$row['type'] = (int)$row['type'];
417
+				$row['type'] = (int) $row['type'];
418 418
 			}
419 419
 			$result[$row['mount_id']][] = $row;
420 420
 		}
@@ -445,8 +445,8 @@  discard block
 block discarded – undo
445 445
 	public function getOptionsForMounts($mountIds) {
446 446
 		$mountOptions = $this->selectForMounts('external_options', ['key', 'value'], $mountIds);
447 447
 		$optionsMap = array_map([$this, 'createKeyValueMap'], $mountOptions);
448
-		return array_map(function (array $options) {
449
-			return array_map(function ($option) {
448
+		return array_map(function(array $options) {
449
+			return array_map(function($option) {
450 450
 				return json_decode($option);
451 451
 			}, $options);
452 452
 		}, $optionsMap);
@@ -457,16 +457,16 @@  discard block
 block discarded – undo
457 457
 	 * @return array ['key1' => $value1, ...]
458 458
 	 */
459 459
 	private function createKeyValueMap(array $keyValuePairs) {
460
-		$decryptedPairts = array_map(function ($pair) {
460
+		$decryptedPairts = array_map(function($pair) {
461 461
 			if ($pair['key'] === 'password') {
462 462
 				$pair['value'] = $this->decryptValue($pair['value']);
463 463
 			}
464 464
 			return $pair;
465 465
 		}, $keyValuePairs);
466
-		$keys = array_map(function ($pair) {
466
+		$keys = array_map(function($pair) {
467 467
 			return $pair['key'];
468 468
 		}, $decryptedPairts);
469
-		$values = array_map(function ($pair) {
469
+		$values = array_map(function($pair) {
470 470
 			return $pair['value'];
471 471
 		}, $decryptedPairts);
472 472
 
Please login to merge, or discard this patch.
Indentation   +456 added lines, -456 removed lines patch added patch discarded remove patch
@@ -32,460 +32,460 @@
 block discarded – undo
32 32
  * Stores the mount config in the database
33 33
  */
34 34
 class DBConfigService {
35
-	const MOUNT_TYPE_ADMIN = 1;
36
-	const MOUNT_TYPE_PERSONAl = 2;
37
-
38
-	const APPLICABLE_TYPE_GLOBAL = 1;
39
-	const APPLICABLE_TYPE_GROUP = 2;
40
-	const APPLICABLE_TYPE_USER = 3;
41
-
42
-	/**
43
-	 * @var IDBConnection
44
-	 */
45
-	private $connection;
46
-
47
-	/**
48
-	 * @var ICrypto
49
-	 */
50
-	private $crypto;
51
-
52
-	/**
53
-	 * DBConfigService constructor.
54
-	 *
55
-	 * @param IDBConnection $connection
56
-	 * @param ICrypto $crypto
57
-	 */
58
-	public function __construct(IDBConnection $connection, ICrypto $crypto) {
59
-		$this->connection = $connection;
60
-		$this->crypto = $crypto;
61
-	}
62
-
63
-	/**
64
-	 * @param int $mountId
65
-	 * @return array
66
-	 */
67
-	public function getMountById($mountId) {
68
-		$builder = $this->connection->getQueryBuilder();
69
-		$query = $builder->select(['mount_id', 'mount_point', 'storage_backend', 'auth_backend', 'priority', 'type'])
70
-			->from('external_mounts', 'm')
71
-			->where($builder->expr()->eq('mount_id', $builder->createNamedParameter($mountId, IQueryBuilder::PARAM_INT)));
72
-		$mounts = $this->getMountsFromQuery($query);
73
-		if (count($mounts) > 0) {
74
-			return $mounts[0];
75
-		} else {
76
-			return null;
77
-		}
78
-	}
79
-
80
-	/**
81
-	 * Get all configured mounts
82
-	 *
83
-	 * @return array
84
-	 */
85
-	public function getAllMounts() {
86
-		$builder = $this->connection->getQueryBuilder();
87
-		$query = $builder->select(['mount_id', 'mount_point', 'storage_backend', 'auth_backend', 'priority', 'type'])
88
-			->from('external_mounts');
89
-		return $this->getMountsFromQuery($query);
90
-	}
91
-
92
-	public function getMountsForUser($userId, $groupIds) {
93
-		$builder = $this->connection->getQueryBuilder();
94
-		$query = $builder->select(['m.mount_id', 'mount_point', 'storage_backend', 'auth_backend', 'priority', 'm.type'])
95
-			->from('external_mounts', 'm')
96
-			->innerJoin('m', 'external_applicable', 'a', $builder->expr()->eq('m.mount_id', 'a.mount_id'))
97
-			->where($builder->expr()->orX(
98
-				$builder->expr()->andX( // global mounts
99
-					$builder->expr()->eq('a.type', $builder->createNamedParameter(self::APPLICABLE_TYPE_GLOBAL, IQueryBuilder::PARAM_INT)),
100
-					$builder->expr()->isNull('a.value')
101
-				),
102
-				$builder->expr()->andX( // mounts for user
103
-					$builder->expr()->eq('a.type', $builder->createNamedParameter(self::APPLICABLE_TYPE_USER, IQueryBuilder::PARAM_INT)),
104
-					$builder->expr()->eq('a.value', $builder->createNamedParameter($userId))
105
-				),
106
-				$builder->expr()->andX( // mounts for group
107
-					$builder->expr()->eq('a.type', $builder->createNamedParameter(self::APPLICABLE_TYPE_GROUP, IQueryBuilder::PARAM_INT)),
108
-					$builder->expr()->in('a.value', $builder->createNamedParameter($groupIds, IQueryBuilder::PARAM_STR_ARRAY))
109
-				)
110
-			));
111
-
112
-		return $this->getMountsFromQuery($query);
113
-	}
114
-
115
-	/**
116
-	 * Get admin defined mounts
117
-	 *
118
-	 * @return array
119
-	 * @suppress SqlInjectionChecker
120
-	 */
121
-	public function getAdminMounts() {
122
-		$builder = $this->connection->getQueryBuilder();
123
-		$query = $builder->select(['mount_id', 'mount_point', 'storage_backend', 'auth_backend', 'priority', 'type'])
124
-			->from('external_mounts')
125
-			->where($builder->expr()->eq('type', $builder->expr()->literal(self::MOUNT_TYPE_ADMIN, IQueryBuilder::PARAM_INT)));
126
-		return $this->getMountsFromQuery($query);
127
-	}
128
-
129
-	protected function getForQuery(IQueryBuilder $builder, $type, $value) {
130
-		$query = $builder->select(['m.mount_id', 'mount_point', 'storage_backend', 'auth_backend', 'priority', 'm.type'])
131
-			->from('external_mounts', 'm')
132
-			->innerJoin('m', 'external_applicable', 'a', $builder->expr()->eq('m.mount_id', 'a.mount_id'))
133
-			->where($builder->expr()->eq('a.type', $builder->createNamedParameter($type, IQueryBuilder::PARAM_INT)));
134
-
135
-		if (is_null($value)) {
136
-			$query = $query->andWhere($builder->expr()->isNull('a.value'));
137
-		} else {
138
-			$query = $query->andWhere($builder->expr()->eq('a.value', $builder->createNamedParameter($value)));
139
-		}
140
-
141
-		return $query;
142
-	}
143
-
144
-	/**
145
-	 * Get mounts by applicable
146
-	 *
147
-	 * @param int $type any of the self::APPLICABLE_TYPE_ constants
148
-	 * @param string|null $value user_id, group_id or null for global mounts
149
-	 * @return array
150
-	 */
151
-	public function getMountsFor($type, $value) {
152
-		$builder = $this->connection->getQueryBuilder();
153
-		$query = $this->getForQuery($builder, $type, $value);
154
-
155
-		return $this->getMountsFromQuery($query);
156
-	}
157
-
158
-	/**
159
-	 * Get admin defined mounts by applicable
160
-	 *
161
-	 * @param int $type any of the self::APPLICABLE_TYPE_ constants
162
-	 * @param string|null $value user_id, group_id or null for global mounts
163
-	 * @return array
164
-	 * @suppress SqlInjectionChecker
165
-	 */
166
-	public function getAdminMountsFor($type, $value) {
167
-		$builder = $this->connection->getQueryBuilder();
168
-		$query = $this->getForQuery($builder, $type, $value);
169
-		$query->andWhere($builder->expr()->eq('m.type', $builder->expr()->literal(self::MOUNT_TYPE_ADMIN, IQueryBuilder::PARAM_INT)));
170
-
171
-		return $this->getMountsFromQuery($query);
172
-	}
173
-
174
-	/**
175
-	 * Get admin defined mounts for multiple applicable
176
-	 *
177
-	 * @param int $type any of the self::APPLICABLE_TYPE_ constants
178
-	 * @param string[] $values user_ids or group_ids
179
-	 * @return array
180
-	 * @suppress SqlInjectionChecker
181
-	 */
182
-	public function getAdminMountsForMultiple($type, array $values) {
183
-		$builder = $this->connection->getQueryBuilder();
184
-		$params = array_map(function ($value) use ($builder) {
185
-			return $builder->createNamedParameter($value, IQueryBuilder::PARAM_STR);
186
-		}, $values);
187
-
188
-		$query = $builder->select(['m.mount_id', 'mount_point', 'storage_backend', 'auth_backend', 'priority', 'm.type'])
189
-			->from('external_mounts', 'm')
190
-			->innerJoin('m', 'external_applicable', 'a', $builder->expr()->eq('m.mount_id', 'a.mount_id'))
191
-			->where($builder->expr()->eq('a.type', $builder->createNamedParameter($type, IQueryBuilder::PARAM_INT)))
192
-			->andWhere($builder->expr()->in('a.value', $params));
193
-		$query->andWhere($builder->expr()->eq('m.type', $builder->expr()->literal(self::MOUNT_TYPE_ADMIN, IQueryBuilder::PARAM_INT)));
194
-
195
-		return $this->getMountsFromQuery($query);
196
-	}
197
-
198
-	/**
199
-	 * Get user defined mounts by applicable
200
-	 *
201
-	 * @param int $type any of the self::APPLICABLE_TYPE_ constants
202
-	 * @param string|null $value user_id, group_id or null for global mounts
203
-	 * @return array
204
-	 * @suppress SqlInjectionChecker
205
-	 */
206
-	public function getUserMountsFor($type, $value) {
207
-		$builder = $this->connection->getQueryBuilder();
208
-		$query = $this->getForQuery($builder, $type, $value);
209
-		$query->andWhere($builder->expr()->eq('m.type', $builder->expr()->literal(self::MOUNT_TYPE_PERSONAl, IQueryBuilder::PARAM_INT)));
210
-
211
-		return $this->getMountsFromQuery($query);
212
-	}
213
-
214
-	/**
215
-	 * Add a mount to the database
216
-	 *
217
-	 * @param string $mountPoint
218
-	 * @param string $storageBackend
219
-	 * @param string $authBackend
220
-	 * @param int $priority
221
-	 * @param int $type self::MOUNT_TYPE_ADMIN or self::MOUNT_TYPE_PERSONAL
222
-	 * @return int the id of the new mount
223
-	 */
224
-	public function addMount($mountPoint, $storageBackend, $authBackend, $priority, $type) {
225
-		if (!$priority) {
226
-			$priority = 100;
227
-		}
228
-		$builder = $this->connection->getQueryBuilder();
229
-		$query = $builder->insert('external_mounts')
230
-			->values([
231
-				'mount_point' => $builder->createNamedParameter($mountPoint, IQueryBuilder::PARAM_STR),
232
-				'storage_backend' => $builder->createNamedParameter($storageBackend, IQueryBuilder::PARAM_STR),
233
-				'auth_backend' => $builder->createNamedParameter($authBackend, IQueryBuilder::PARAM_STR),
234
-				'priority' => $builder->createNamedParameter($priority, IQueryBuilder::PARAM_INT),
235
-				'type' => $builder->createNamedParameter($type, IQueryBuilder::PARAM_INT)
236
-			]);
237
-		$query->execute();
238
-		return (int)$this->connection->lastInsertId('*PREFIX*external_mounts');
239
-	}
240
-
241
-	/**
242
-	 * Remove a mount from the database
243
-	 *
244
-	 * @param int $mountId
245
-	 */
246
-	public function removeMount($mountId) {
247
-		$builder = $this->connection->getQueryBuilder();
248
-		$query = $builder->delete('external_mounts')
249
-			->where($builder->expr()->eq('mount_id', $builder->createNamedParameter($mountId, IQueryBuilder::PARAM_INT)));
250
-		$query->execute();
251
-
252
-		$query = $builder->delete('external_applicable')
253
-			->where($builder->expr()->eq('mount_id', $builder->createNamedParameter($mountId, IQueryBuilder::PARAM_INT)));
254
-		$query->execute();
255
-
256
-		$query = $builder->delete('external_config')
257
-			->where($builder->expr()->eq('mount_id', $builder->createNamedParameter($mountId, IQueryBuilder::PARAM_INT)));
258
-		$query->execute();
259
-
260
-		$query = $builder->delete('external_options')
261
-			->where($builder->expr()->eq('mount_id', $builder->createNamedParameter($mountId, IQueryBuilder::PARAM_INT)));
262
-		$query->execute();
263
-	}
264
-
265
-	/**
266
-	 * @param int $mountId
267
-	 * @param string $newMountPoint
268
-	 */
269
-	public function setMountPoint($mountId, $newMountPoint) {
270
-		$builder = $this->connection->getQueryBuilder();
271
-
272
-		$query = $builder->update('external_mounts')
273
-			->set('mount_point', $builder->createNamedParameter($newMountPoint))
274
-			->where($builder->expr()->eq('mount_id', $builder->createNamedParameter($mountId, IQueryBuilder::PARAM_INT)));
275
-
276
-		$query->execute();
277
-	}
278
-
279
-	/**
280
-	 * @param int $mountId
281
-	 * @param string $newAuthBackend
282
-	 */
283
-	public function setAuthBackend($mountId, $newAuthBackend) {
284
-		$builder = $this->connection->getQueryBuilder();
285
-
286
-		$query = $builder->update('external_mounts')
287
-			->set('auth_backend', $builder->createNamedParameter($newAuthBackend))
288
-			->where($builder->expr()->eq('mount_id', $builder->createNamedParameter($mountId, IQueryBuilder::PARAM_INT)));
289
-
290
-		$query->execute();
291
-	}
292
-
293
-	/**
294
-	 * @param int $mountId
295
-	 * @param string $key
296
-	 * @param string $value
297
-	 */
298
-	public function setConfig($mountId, $key, $value) {
299
-		if ($key === 'password') {
300
-			$value = $this->encryptValue($value);
301
-		}
302
-		$count = $this->connection->insertIfNotExist('*PREFIX*external_config', [
303
-			'mount_id' => $mountId,
304
-			'key' => $key,
305
-			'value' => $value
306
-		], ['mount_id', 'key']);
307
-		if ($count === 0) {
308
-			$builder = $this->connection->getQueryBuilder();
309
-			$query = $builder->update('external_config')
310
-				->set('value', $builder->createNamedParameter($value, IQueryBuilder::PARAM_STR))
311
-				->where($builder->expr()->eq('mount_id', $builder->createNamedParameter($mountId, IQueryBuilder::PARAM_INT)))
312
-				->andWhere($builder->expr()->eq('key', $builder->createNamedParameter($key, IQueryBuilder::PARAM_STR)));
313
-			$query->execute();
314
-		}
315
-	}
316
-
317
-	/**
318
-	 * @param int $mountId
319
-	 * @param string $key
320
-	 * @param string $value
321
-	 */
322
-	public function setOption($mountId, $key, $value) {
323
-
324
-		$count = $this->connection->insertIfNotExist('*PREFIX*external_options', [
325
-			'mount_id' => $mountId,
326
-			'key' => $key,
327
-			'value' => json_encode($value)
328
-		], ['mount_id', 'key']);
329
-		if ($count === 0) {
330
-			$builder = $this->connection->getQueryBuilder();
331
-			$query = $builder->update('external_options')
332
-				->set('value', $builder->createNamedParameter(json_encode($value), IQueryBuilder::PARAM_STR))
333
-				->where($builder->expr()->eq('mount_id', $builder->createNamedParameter($mountId, IQueryBuilder::PARAM_INT)))
334
-				->andWhere($builder->expr()->eq('key', $builder->createNamedParameter($key, IQueryBuilder::PARAM_STR)));
335
-			$query->execute();
336
-		}
337
-	}
338
-
339
-	public function addApplicable($mountId, $type, $value) {
340
-		$this->connection->insertIfNotExist('*PREFIX*external_applicable', [
341
-			'mount_id' => $mountId,
342
-			'type' => $type,
343
-			'value' => $value
344
-		], ['mount_id', 'type', 'value']);
345
-	}
346
-
347
-	public function removeApplicable($mountId, $type, $value) {
348
-		$builder = $this->connection->getQueryBuilder();
349
-		$query = $builder->delete('external_applicable')
350
-			->where($builder->expr()->eq('mount_id', $builder->createNamedParameter($mountId, IQueryBuilder::PARAM_INT)))
351
-			->andWhere($builder->expr()->eq('type', $builder->createNamedParameter($type, IQueryBuilder::PARAM_INT)));
352
-
353
-		if (is_null($value)) {
354
-			$query = $query->andWhere($builder->expr()->isNull('value'));
355
-		} else {
356
-			$query = $query->andWhere($builder->expr()->eq('value', $builder->createNamedParameter($value, IQueryBuilder::PARAM_STR)));
357
-		}
358
-
359
-		$query->execute();
360
-	}
361
-
362
-	private function getMountsFromQuery(IQueryBuilder $query) {
363
-		$result = $query->execute();
364
-		$mounts = $result->fetchAll();
365
-		$uniqueMounts = [];
366
-		foreach ($mounts as $mount) {
367
-			$id = $mount['mount_id'];
368
-			if (!isset($uniqueMounts[$id])) {
369
-				$uniqueMounts[$id] = $mount;
370
-			}
371
-		}
372
-		$uniqueMounts = array_values($uniqueMounts);
373
-
374
-		$mountIds = array_map(function ($mount) {
375
-			return $mount['mount_id'];
376
-		}, $uniqueMounts);
377
-		$mountIds = array_values(array_unique($mountIds));
378
-
379
-		$applicable = $this->getApplicableForMounts($mountIds);
380
-		$config = $this->getConfigForMounts($mountIds);
381
-		$options = $this->getOptionsForMounts($mountIds);
382
-
383
-		return array_map(function ($mount, $applicable, $config, $options) {
384
-			$mount['type'] = (int)$mount['type'];
385
-			$mount['priority'] = (int)$mount['priority'];
386
-			$mount['applicable'] = $applicable;
387
-			$mount['config'] = $config;
388
-			$mount['options'] = $options;
389
-			return $mount;
390
-		}, $uniqueMounts, $applicable, $config, $options);
391
-	}
392
-
393
-	/**
394
-	 * Get mount options from a table grouped by mount id
395
-	 *
396
-	 * @param string $table
397
-	 * @param string[] $fields
398
-	 * @param int[] $mountIds
399
-	 * @return array [$mountId => [['field1' => $value1, ...], ...], ...]
400
-	 */
401
-	private function selectForMounts($table, array $fields, array $mountIds) {
402
-		if (count($mountIds) === 0) {
403
-			return [];
404
-		}
405
-		$builder = $this->connection->getQueryBuilder();
406
-		$fields[] = 'mount_id';
407
-		$placeHolders = array_map(function ($id) use ($builder) {
408
-			return $builder->createPositionalParameter($id, IQueryBuilder::PARAM_INT);
409
-		}, $mountIds);
410
-		$query = $builder->select($fields)
411
-			->from($table)
412
-			->where($builder->expr()->in('mount_id', $placeHolders));
413
-		$rows = $query->execute()->fetchAll();
414
-
415
-		$result = [];
416
-		foreach ($mountIds as $mountId) {
417
-			$result[$mountId] = [];
418
-		}
419
-		foreach ($rows as $row) {
420
-			if (isset($row['type'])) {
421
-				$row['type'] = (int)$row['type'];
422
-			}
423
-			$result[$row['mount_id']][] = $row;
424
-		}
425
-		return $result;
426
-	}
427
-
428
-	/**
429
-	 * @param int[] $mountIds
430
-	 * @return array [$id => [['type' => $type, 'value' => $value], ...], ...]
431
-	 */
432
-	public function getApplicableForMounts($mountIds) {
433
-		return $this->selectForMounts('external_applicable', ['type', 'value'], $mountIds);
434
-	}
435
-
436
-	/**
437
-	 * @param int[] $mountIds
438
-	 * @return array [$id => ['key1' => $value1, ...], ...]
439
-	 */
440
-	public function getConfigForMounts($mountIds) {
441
-		$mountConfigs = $this->selectForMounts('external_config', ['key', 'value'], $mountIds);
442
-		return array_map([$this, 'createKeyValueMap'], $mountConfigs);
443
-	}
444
-
445
-	/**
446
-	 * @param int[] $mountIds
447
-	 * @return array [$id => ['key1' => $value1, ...], ...]
448
-	 */
449
-	public function getOptionsForMounts($mountIds) {
450
-		$mountOptions = $this->selectForMounts('external_options', ['key', 'value'], $mountIds);
451
-		$optionsMap = array_map([$this, 'createKeyValueMap'], $mountOptions);
452
-		return array_map(function (array $options) {
453
-			return array_map(function ($option) {
454
-				return json_decode($option);
455
-			}, $options);
456
-		}, $optionsMap);
457
-	}
458
-
459
-	/**
460
-	 * @param array $keyValuePairs [['key'=>$key, 'value=>$value], ...]
461
-	 * @return array ['key1' => $value1, ...]
462
-	 */
463
-	private function createKeyValueMap(array $keyValuePairs) {
464
-		$decryptedPairts = array_map(function ($pair) {
465
-			if ($pair['key'] === 'password') {
466
-				$pair['value'] = $this->decryptValue($pair['value']);
467
-			}
468
-			return $pair;
469
-		}, $keyValuePairs);
470
-		$keys = array_map(function ($pair) {
471
-			return $pair['key'];
472
-		}, $decryptedPairts);
473
-		$values = array_map(function ($pair) {
474
-			return $pair['value'];
475
-		}, $decryptedPairts);
476
-
477
-		return array_combine($keys, $values);
478
-	}
479
-
480
-	private function encryptValue($value) {
481
-		return $this->crypto->encrypt($value);
482
-	}
483
-
484
-	private function decryptValue($value) {
485
-		try {
486
-			return $this->crypto->decrypt($value);
487
-		} catch (\Exception $e) {
488
-			return $value;
489
-		}
490
-	}
35
+    const MOUNT_TYPE_ADMIN = 1;
36
+    const MOUNT_TYPE_PERSONAl = 2;
37
+
38
+    const APPLICABLE_TYPE_GLOBAL = 1;
39
+    const APPLICABLE_TYPE_GROUP = 2;
40
+    const APPLICABLE_TYPE_USER = 3;
41
+
42
+    /**
43
+     * @var IDBConnection
44
+     */
45
+    private $connection;
46
+
47
+    /**
48
+     * @var ICrypto
49
+     */
50
+    private $crypto;
51
+
52
+    /**
53
+     * DBConfigService constructor.
54
+     *
55
+     * @param IDBConnection $connection
56
+     * @param ICrypto $crypto
57
+     */
58
+    public function __construct(IDBConnection $connection, ICrypto $crypto) {
59
+        $this->connection = $connection;
60
+        $this->crypto = $crypto;
61
+    }
62
+
63
+    /**
64
+     * @param int $mountId
65
+     * @return array
66
+     */
67
+    public function getMountById($mountId) {
68
+        $builder = $this->connection->getQueryBuilder();
69
+        $query = $builder->select(['mount_id', 'mount_point', 'storage_backend', 'auth_backend', 'priority', 'type'])
70
+            ->from('external_mounts', 'm')
71
+            ->where($builder->expr()->eq('mount_id', $builder->createNamedParameter($mountId, IQueryBuilder::PARAM_INT)));
72
+        $mounts = $this->getMountsFromQuery($query);
73
+        if (count($mounts) > 0) {
74
+            return $mounts[0];
75
+        } else {
76
+            return null;
77
+        }
78
+    }
79
+
80
+    /**
81
+     * Get all configured mounts
82
+     *
83
+     * @return array
84
+     */
85
+    public function getAllMounts() {
86
+        $builder = $this->connection->getQueryBuilder();
87
+        $query = $builder->select(['mount_id', 'mount_point', 'storage_backend', 'auth_backend', 'priority', 'type'])
88
+            ->from('external_mounts');
89
+        return $this->getMountsFromQuery($query);
90
+    }
91
+
92
+    public function getMountsForUser($userId, $groupIds) {
93
+        $builder = $this->connection->getQueryBuilder();
94
+        $query = $builder->select(['m.mount_id', 'mount_point', 'storage_backend', 'auth_backend', 'priority', 'm.type'])
95
+            ->from('external_mounts', 'm')
96
+            ->innerJoin('m', 'external_applicable', 'a', $builder->expr()->eq('m.mount_id', 'a.mount_id'))
97
+            ->where($builder->expr()->orX(
98
+                $builder->expr()->andX( // global mounts
99
+                    $builder->expr()->eq('a.type', $builder->createNamedParameter(self::APPLICABLE_TYPE_GLOBAL, IQueryBuilder::PARAM_INT)),
100
+                    $builder->expr()->isNull('a.value')
101
+                ),
102
+                $builder->expr()->andX( // mounts for user
103
+                    $builder->expr()->eq('a.type', $builder->createNamedParameter(self::APPLICABLE_TYPE_USER, IQueryBuilder::PARAM_INT)),
104
+                    $builder->expr()->eq('a.value', $builder->createNamedParameter($userId))
105
+                ),
106
+                $builder->expr()->andX( // mounts for group
107
+                    $builder->expr()->eq('a.type', $builder->createNamedParameter(self::APPLICABLE_TYPE_GROUP, IQueryBuilder::PARAM_INT)),
108
+                    $builder->expr()->in('a.value', $builder->createNamedParameter($groupIds, IQueryBuilder::PARAM_STR_ARRAY))
109
+                )
110
+            ));
111
+
112
+        return $this->getMountsFromQuery($query);
113
+    }
114
+
115
+    /**
116
+     * Get admin defined mounts
117
+     *
118
+     * @return array
119
+     * @suppress SqlInjectionChecker
120
+     */
121
+    public function getAdminMounts() {
122
+        $builder = $this->connection->getQueryBuilder();
123
+        $query = $builder->select(['mount_id', 'mount_point', 'storage_backend', 'auth_backend', 'priority', 'type'])
124
+            ->from('external_mounts')
125
+            ->where($builder->expr()->eq('type', $builder->expr()->literal(self::MOUNT_TYPE_ADMIN, IQueryBuilder::PARAM_INT)));
126
+        return $this->getMountsFromQuery($query);
127
+    }
128
+
129
+    protected function getForQuery(IQueryBuilder $builder, $type, $value) {
130
+        $query = $builder->select(['m.mount_id', 'mount_point', 'storage_backend', 'auth_backend', 'priority', 'm.type'])
131
+            ->from('external_mounts', 'm')
132
+            ->innerJoin('m', 'external_applicable', 'a', $builder->expr()->eq('m.mount_id', 'a.mount_id'))
133
+            ->where($builder->expr()->eq('a.type', $builder->createNamedParameter($type, IQueryBuilder::PARAM_INT)));
134
+
135
+        if (is_null($value)) {
136
+            $query = $query->andWhere($builder->expr()->isNull('a.value'));
137
+        } else {
138
+            $query = $query->andWhere($builder->expr()->eq('a.value', $builder->createNamedParameter($value)));
139
+        }
140
+
141
+        return $query;
142
+    }
143
+
144
+    /**
145
+     * Get mounts by applicable
146
+     *
147
+     * @param int $type any of the self::APPLICABLE_TYPE_ constants
148
+     * @param string|null $value user_id, group_id or null for global mounts
149
+     * @return array
150
+     */
151
+    public function getMountsFor($type, $value) {
152
+        $builder = $this->connection->getQueryBuilder();
153
+        $query = $this->getForQuery($builder, $type, $value);
154
+
155
+        return $this->getMountsFromQuery($query);
156
+    }
157
+
158
+    /**
159
+     * Get admin defined mounts by applicable
160
+     *
161
+     * @param int $type any of the self::APPLICABLE_TYPE_ constants
162
+     * @param string|null $value user_id, group_id or null for global mounts
163
+     * @return array
164
+     * @suppress SqlInjectionChecker
165
+     */
166
+    public function getAdminMountsFor($type, $value) {
167
+        $builder = $this->connection->getQueryBuilder();
168
+        $query = $this->getForQuery($builder, $type, $value);
169
+        $query->andWhere($builder->expr()->eq('m.type', $builder->expr()->literal(self::MOUNT_TYPE_ADMIN, IQueryBuilder::PARAM_INT)));
170
+
171
+        return $this->getMountsFromQuery($query);
172
+    }
173
+
174
+    /**
175
+     * Get admin defined mounts for multiple applicable
176
+     *
177
+     * @param int $type any of the self::APPLICABLE_TYPE_ constants
178
+     * @param string[] $values user_ids or group_ids
179
+     * @return array
180
+     * @suppress SqlInjectionChecker
181
+     */
182
+    public function getAdminMountsForMultiple($type, array $values) {
183
+        $builder = $this->connection->getQueryBuilder();
184
+        $params = array_map(function ($value) use ($builder) {
185
+            return $builder->createNamedParameter($value, IQueryBuilder::PARAM_STR);
186
+        }, $values);
187
+
188
+        $query = $builder->select(['m.mount_id', 'mount_point', 'storage_backend', 'auth_backend', 'priority', 'm.type'])
189
+            ->from('external_mounts', 'm')
190
+            ->innerJoin('m', 'external_applicable', 'a', $builder->expr()->eq('m.mount_id', 'a.mount_id'))
191
+            ->where($builder->expr()->eq('a.type', $builder->createNamedParameter($type, IQueryBuilder::PARAM_INT)))
192
+            ->andWhere($builder->expr()->in('a.value', $params));
193
+        $query->andWhere($builder->expr()->eq('m.type', $builder->expr()->literal(self::MOUNT_TYPE_ADMIN, IQueryBuilder::PARAM_INT)));
194
+
195
+        return $this->getMountsFromQuery($query);
196
+    }
197
+
198
+    /**
199
+     * Get user defined mounts by applicable
200
+     *
201
+     * @param int $type any of the self::APPLICABLE_TYPE_ constants
202
+     * @param string|null $value user_id, group_id or null for global mounts
203
+     * @return array
204
+     * @suppress SqlInjectionChecker
205
+     */
206
+    public function getUserMountsFor($type, $value) {
207
+        $builder = $this->connection->getQueryBuilder();
208
+        $query = $this->getForQuery($builder, $type, $value);
209
+        $query->andWhere($builder->expr()->eq('m.type', $builder->expr()->literal(self::MOUNT_TYPE_PERSONAl, IQueryBuilder::PARAM_INT)));
210
+
211
+        return $this->getMountsFromQuery($query);
212
+    }
213
+
214
+    /**
215
+     * Add a mount to the database
216
+     *
217
+     * @param string $mountPoint
218
+     * @param string $storageBackend
219
+     * @param string $authBackend
220
+     * @param int $priority
221
+     * @param int $type self::MOUNT_TYPE_ADMIN or self::MOUNT_TYPE_PERSONAL
222
+     * @return int the id of the new mount
223
+     */
224
+    public function addMount($mountPoint, $storageBackend, $authBackend, $priority, $type) {
225
+        if (!$priority) {
226
+            $priority = 100;
227
+        }
228
+        $builder = $this->connection->getQueryBuilder();
229
+        $query = $builder->insert('external_mounts')
230
+            ->values([
231
+                'mount_point' => $builder->createNamedParameter($mountPoint, IQueryBuilder::PARAM_STR),
232
+                'storage_backend' => $builder->createNamedParameter($storageBackend, IQueryBuilder::PARAM_STR),
233
+                'auth_backend' => $builder->createNamedParameter($authBackend, IQueryBuilder::PARAM_STR),
234
+                'priority' => $builder->createNamedParameter($priority, IQueryBuilder::PARAM_INT),
235
+                'type' => $builder->createNamedParameter($type, IQueryBuilder::PARAM_INT)
236
+            ]);
237
+        $query->execute();
238
+        return (int)$this->connection->lastInsertId('*PREFIX*external_mounts');
239
+    }
240
+
241
+    /**
242
+     * Remove a mount from the database
243
+     *
244
+     * @param int $mountId
245
+     */
246
+    public function removeMount($mountId) {
247
+        $builder = $this->connection->getQueryBuilder();
248
+        $query = $builder->delete('external_mounts')
249
+            ->where($builder->expr()->eq('mount_id', $builder->createNamedParameter($mountId, IQueryBuilder::PARAM_INT)));
250
+        $query->execute();
251
+
252
+        $query = $builder->delete('external_applicable')
253
+            ->where($builder->expr()->eq('mount_id', $builder->createNamedParameter($mountId, IQueryBuilder::PARAM_INT)));
254
+        $query->execute();
255
+
256
+        $query = $builder->delete('external_config')
257
+            ->where($builder->expr()->eq('mount_id', $builder->createNamedParameter($mountId, IQueryBuilder::PARAM_INT)));
258
+        $query->execute();
259
+
260
+        $query = $builder->delete('external_options')
261
+            ->where($builder->expr()->eq('mount_id', $builder->createNamedParameter($mountId, IQueryBuilder::PARAM_INT)));
262
+        $query->execute();
263
+    }
264
+
265
+    /**
266
+     * @param int $mountId
267
+     * @param string $newMountPoint
268
+     */
269
+    public function setMountPoint($mountId, $newMountPoint) {
270
+        $builder = $this->connection->getQueryBuilder();
271
+
272
+        $query = $builder->update('external_mounts')
273
+            ->set('mount_point', $builder->createNamedParameter($newMountPoint))
274
+            ->where($builder->expr()->eq('mount_id', $builder->createNamedParameter($mountId, IQueryBuilder::PARAM_INT)));
275
+
276
+        $query->execute();
277
+    }
278
+
279
+    /**
280
+     * @param int $mountId
281
+     * @param string $newAuthBackend
282
+     */
283
+    public function setAuthBackend($mountId, $newAuthBackend) {
284
+        $builder = $this->connection->getQueryBuilder();
285
+
286
+        $query = $builder->update('external_mounts')
287
+            ->set('auth_backend', $builder->createNamedParameter($newAuthBackend))
288
+            ->where($builder->expr()->eq('mount_id', $builder->createNamedParameter($mountId, IQueryBuilder::PARAM_INT)));
289
+
290
+        $query->execute();
291
+    }
292
+
293
+    /**
294
+     * @param int $mountId
295
+     * @param string $key
296
+     * @param string $value
297
+     */
298
+    public function setConfig($mountId, $key, $value) {
299
+        if ($key === 'password') {
300
+            $value = $this->encryptValue($value);
301
+        }
302
+        $count = $this->connection->insertIfNotExist('*PREFIX*external_config', [
303
+            'mount_id' => $mountId,
304
+            'key' => $key,
305
+            'value' => $value
306
+        ], ['mount_id', 'key']);
307
+        if ($count === 0) {
308
+            $builder = $this->connection->getQueryBuilder();
309
+            $query = $builder->update('external_config')
310
+                ->set('value', $builder->createNamedParameter($value, IQueryBuilder::PARAM_STR))
311
+                ->where($builder->expr()->eq('mount_id', $builder->createNamedParameter($mountId, IQueryBuilder::PARAM_INT)))
312
+                ->andWhere($builder->expr()->eq('key', $builder->createNamedParameter($key, IQueryBuilder::PARAM_STR)));
313
+            $query->execute();
314
+        }
315
+    }
316
+
317
+    /**
318
+     * @param int $mountId
319
+     * @param string $key
320
+     * @param string $value
321
+     */
322
+    public function setOption($mountId, $key, $value) {
323
+
324
+        $count = $this->connection->insertIfNotExist('*PREFIX*external_options', [
325
+            'mount_id' => $mountId,
326
+            'key' => $key,
327
+            'value' => json_encode($value)
328
+        ], ['mount_id', 'key']);
329
+        if ($count === 0) {
330
+            $builder = $this->connection->getQueryBuilder();
331
+            $query = $builder->update('external_options')
332
+                ->set('value', $builder->createNamedParameter(json_encode($value), IQueryBuilder::PARAM_STR))
333
+                ->where($builder->expr()->eq('mount_id', $builder->createNamedParameter($mountId, IQueryBuilder::PARAM_INT)))
334
+                ->andWhere($builder->expr()->eq('key', $builder->createNamedParameter($key, IQueryBuilder::PARAM_STR)));
335
+            $query->execute();
336
+        }
337
+    }
338
+
339
+    public function addApplicable($mountId, $type, $value) {
340
+        $this->connection->insertIfNotExist('*PREFIX*external_applicable', [
341
+            'mount_id' => $mountId,
342
+            'type' => $type,
343
+            'value' => $value
344
+        ], ['mount_id', 'type', 'value']);
345
+    }
346
+
347
+    public function removeApplicable($mountId, $type, $value) {
348
+        $builder = $this->connection->getQueryBuilder();
349
+        $query = $builder->delete('external_applicable')
350
+            ->where($builder->expr()->eq('mount_id', $builder->createNamedParameter($mountId, IQueryBuilder::PARAM_INT)))
351
+            ->andWhere($builder->expr()->eq('type', $builder->createNamedParameter($type, IQueryBuilder::PARAM_INT)));
352
+
353
+        if (is_null($value)) {
354
+            $query = $query->andWhere($builder->expr()->isNull('value'));
355
+        } else {
356
+            $query = $query->andWhere($builder->expr()->eq('value', $builder->createNamedParameter($value, IQueryBuilder::PARAM_STR)));
357
+        }
358
+
359
+        $query->execute();
360
+    }
361
+
362
+    private function getMountsFromQuery(IQueryBuilder $query) {
363
+        $result = $query->execute();
364
+        $mounts = $result->fetchAll();
365
+        $uniqueMounts = [];
366
+        foreach ($mounts as $mount) {
367
+            $id = $mount['mount_id'];
368
+            if (!isset($uniqueMounts[$id])) {
369
+                $uniqueMounts[$id] = $mount;
370
+            }
371
+        }
372
+        $uniqueMounts = array_values($uniqueMounts);
373
+
374
+        $mountIds = array_map(function ($mount) {
375
+            return $mount['mount_id'];
376
+        }, $uniqueMounts);
377
+        $mountIds = array_values(array_unique($mountIds));
378
+
379
+        $applicable = $this->getApplicableForMounts($mountIds);
380
+        $config = $this->getConfigForMounts($mountIds);
381
+        $options = $this->getOptionsForMounts($mountIds);
382
+
383
+        return array_map(function ($mount, $applicable, $config, $options) {
384
+            $mount['type'] = (int)$mount['type'];
385
+            $mount['priority'] = (int)$mount['priority'];
386
+            $mount['applicable'] = $applicable;
387
+            $mount['config'] = $config;
388
+            $mount['options'] = $options;
389
+            return $mount;
390
+        }, $uniqueMounts, $applicable, $config, $options);
391
+    }
392
+
393
+    /**
394
+     * Get mount options from a table grouped by mount id
395
+     *
396
+     * @param string $table
397
+     * @param string[] $fields
398
+     * @param int[] $mountIds
399
+     * @return array [$mountId => [['field1' => $value1, ...], ...], ...]
400
+     */
401
+    private function selectForMounts($table, array $fields, array $mountIds) {
402
+        if (count($mountIds) === 0) {
403
+            return [];
404
+        }
405
+        $builder = $this->connection->getQueryBuilder();
406
+        $fields[] = 'mount_id';
407
+        $placeHolders = array_map(function ($id) use ($builder) {
408
+            return $builder->createPositionalParameter($id, IQueryBuilder::PARAM_INT);
409
+        }, $mountIds);
410
+        $query = $builder->select($fields)
411
+            ->from($table)
412
+            ->where($builder->expr()->in('mount_id', $placeHolders));
413
+        $rows = $query->execute()->fetchAll();
414
+
415
+        $result = [];
416
+        foreach ($mountIds as $mountId) {
417
+            $result[$mountId] = [];
418
+        }
419
+        foreach ($rows as $row) {
420
+            if (isset($row['type'])) {
421
+                $row['type'] = (int)$row['type'];
422
+            }
423
+            $result[$row['mount_id']][] = $row;
424
+        }
425
+        return $result;
426
+    }
427
+
428
+    /**
429
+     * @param int[] $mountIds
430
+     * @return array [$id => [['type' => $type, 'value' => $value], ...], ...]
431
+     */
432
+    public function getApplicableForMounts($mountIds) {
433
+        return $this->selectForMounts('external_applicable', ['type', 'value'], $mountIds);
434
+    }
435
+
436
+    /**
437
+     * @param int[] $mountIds
438
+     * @return array [$id => ['key1' => $value1, ...], ...]
439
+     */
440
+    public function getConfigForMounts($mountIds) {
441
+        $mountConfigs = $this->selectForMounts('external_config', ['key', 'value'], $mountIds);
442
+        return array_map([$this, 'createKeyValueMap'], $mountConfigs);
443
+    }
444
+
445
+    /**
446
+     * @param int[] $mountIds
447
+     * @return array [$id => ['key1' => $value1, ...], ...]
448
+     */
449
+    public function getOptionsForMounts($mountIds) {
450
+        $mountOptions = $this->selectForMounts('external_options', ['key', 'value'], $mountIds);
451
+        $optionsMap = array_map([$this, 'createKeyValueMap'], $mountOptions);
452
+        return array_map(function (array $options) {
453
+            return array_map(function ($option) {
454
+                return json_decode($option);
455
+            }, $options);
456
+        }, $optionsMap);
457
+    }
458
+
459
+    /**
460
+     * @param array $keyValuePairs [['key'=>$key, 'value=>$value], ...]
461
+     * @return array ['key1' => $value1, ...]
462
+     */
463
+    private function createKeyValueMap(array $keyValuePairs) {
464
+        $decryptedPairts = array_map(function ($pair) {
465
+            if ($pair['key'] === 'password') {
466
+                $pair['value'] = $this->decryptValue($pair['value']);
467
+            }
468
+            return $pair;
469
+        }, $keyValuePairs);
470
+        $keys = array_map(function ($pair) {
471
+            return $pair['key'];
472
+        }, $decryptedPairts);
473
+        $values = array_map(function ($pair) {
474
+            return $pair['value'];
475
+        }, $decryptedPairts);
476
+
477
+        return array_combine($keys, $values);
478
+    }
479
+
480
+    private function encryptValue($value) {
481
+        return $this->crypto->encrypt($value);
482
+    }
483
+
484
+    private function decryptValue($value) {
485
+        try {
486
+            return $this->crypto->decrypt($value);
487
+        } catch (\Exception $e) {
488
+            return $value;
489
+        }
490
+    }
491 491
 }
Please login to merge, or discard this patch.
lib/private/AppFramework/OCS/BaseResponse.php 3 patches
Doc Comments   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -24,7 +24,7 @@
 block discarded – undo
24 24
 	/**
25 25
 	 * BaseResponse constructor.
26 26
 	 *
27
-	 * @param DataResponse|null $dataResponse
27
+	 * @param DataResponse $dataResponse
28 28
 	 * @param string $format
29 29
 	 * @param string|null $statusMessage
30 30
 	 * @param int|null $itemsCount
Please login to merge, or discard this patch.
Indentation   +56 added lines, -56 removed lines patch added patch discarded remove patch
@@ -27,70 +27,70 @@
 block discarded – undo
27 27
 use OCP\AppFramework\Http\Response;
28 28
 
29 29
 abstract class BaseResponse extends Response   {
30
-	/** @var array */
31
-	protected $data;
30
+    /** @var array */
31
+    protected $data;
32 32
 
33
-	/** @var string */
34
-	protected $format;
33
+    /** @var string */
34
+    protected $format;
35 35
 
36
-	/** @var string */
37
-	protected $statusMessage;
36
+    /** @var string */
37
+    protected $statusMessage;
38 38
 
39
-	/** @var int */
40
-	protected $itemsCount;
39
+    /** @var int */
40
+    protected $itemsCount;
41 41
 
42
-	/** @var int */
43
-	protected $itemsPerPage;
42
+    /** @var int */
43
+    protected $itemsPerPage;
44 44
 
45
-	/**
46
-	 * BaseResponse constructor.
47
-	 *
48
-	 * @param DataResponse|null $dataResponse
49
-	 * @param string $format
50
-	 * @param string|null $statusMessage
51
-	 * @param int|null $itemsCount
52
-	 * @param int|null $itemsPerPage
53
-	 */
54
-	public function __construct(DataResponse $dataResponse,
55
-								$format = 'xml',
56
-								$statusMessage = null,
57
-								$itemsCount = null,
58
-								$itemsPerPage = null) {
59
-		$this->format = $format;
60
-		$this->statusMessage = $statusMessage;
61
-		$this->itemsCount = $itemsCount;
62
-		$this->itemsPerPage = $itemsPerPage;
45
+    /**
46
+     * BaseResponse constructor.
47
+     *
48
+     * @param DataResponse|null $dataResponse
49
+     * @param string $format
50
+     * @param string|null $statusMessage
51
+     * @param int|null $itemsCount
52
+     * @param int|null $itemsPerPage
53
+     */
54
+    public function __construct(DataResponse $dataResponse,
55
+                                $format = 'xml',
56
+                                $statusMessage = null,
57
+                                $itemsCount = null,
58
+                                $itemsPerPage = null) {
59
+        $this->format = $format;
60
+        $this->statusMessage = $statusMessage;
61
+        $this->itemsCount = $itemsCount;
62
+        $this->itemsPerPage = $itemsPerPage;
63 63
 
64
-		$this->data = $dataResponse->getData();
64
+        $this->data = $dataResponse->getData();
65 65
 
66
-		$this->setHeaders($dataResponse->getHeaders());
67
-		$this->setStatus($dataResponse->getStatus());
68
-		$this->setETag($dataResponse->getETag());
69
-		$this->setLastModified($dataResponse->getLastModified());
70
-		$this->setCookies($dataResponse->getCookies());
71
-		$this->setContentSecurityPolicy(new EmptyContentSecurityPolicy());
66
+        $this->setHeaders($dataResponse->getHeaders());
67
+        $this->setStatus($dataResponse->getStatus());
68
+        $this->setETag($dataResponse->getETag());
69
+        $this->setLastModified($dataResponse->getLastModified());
70
+        $this->setCookies($dataResponse->getCookies());
71
+        $this->setContentSecurityPolicy(new EmptyContentSecurityPolicy());
72 72
 
73
-		if ($format === 'json') {
74
-			$this->addHeader(
75
-				'Content-Type', 'application/json; charset=utf-8'
76
-			);
77
-		} else {
78
-			$this->addHeader(
79
-				'Content-Type', 'application/xml; charset=utf-8'
80
-			);
81
-		}
82
-	}
73
+        if ($format === 'json') {
74
+            $this->addHeader(
75
+                'Content-Type', 'application/json; charset=utf-8'
76
+            );
77
+        } else {
78
+            $this->addHeader(
79
+                'Content-Type', 'application/xml; charset=utf-8'
80
+            );
81
+        }
82
+    }
83 83
 
84
-	/**
85
-	 * @param string[] $meta
86
-	 * @return string
87
-	 */
88
-	protected function renderResult($meta) {
89
-		// TODO rewrite functions
90
-		return \OC_API::renderResult($this->format, $meta, $this->data);
91
-	}
84
+    /**
85
+     * @param string[] $meta
86
+     * @return string
87
+     */
88
+    protected function renderResult($meta) {
89
+        // TODO rewrite functions
90
+        return \OC_API::renderResult($this->format, $meta, $this->data);
91
+    }
92 92
 
93
-	public function getOCSStatus() {
94
-		return parent::getStatus();
95
-	}
93
+    public function getOCSStatus() {
94
+        return parent::getStatus();
95
+    }
96 96
 }
Please login to merge, or discard this patch.
Spacing   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -26,7 +26,7 @@
 block discarded – undo
26 26
 use OCP\AppFramework\Http\EmptyContentSecurityPolicy;
27 27
 use OCP\AppFramework\Http\Response;
28 28
 
29
-abstract class BaseResponse extends Response   {
29
+abstract class BaseResponse extends Response {
30 30
 	/** @var array */
31 31
 	protected $data;
32 32
 
Please login to merge, or discard this patch.
lib/private/Server.php 4 patches
Doc Comments   +2 added lines, -1 removed lines patch added patch discarded remove patch
@@ -1143,7 +1143,7 @@  discard block
 block discarded – undo
1143 1143
 	 * Get the certificate manager for the user
1144 1144
 	 *
1145 1145
 	 * @param string $userId (optional) if not specified the current loggedin user is used, use null to get the system certificate manager
1146
-	 * @return \OCP\ICertificateManager | null if $uid is null and no user is logged in
1146
+	 * @return null|CertificateManager | null if $uid is null and no user is logged in
1147 1147
 	 */
1148 1148
 	public function getCertificateManager($userId = '') {
1149 1149
 		if ($userId === '') {
@@ -1464,6 +1464,7 @@  discard block
 block discarded – undo
1464 1464
 	}
1465 1465
 
1466 1466
 	/**
1467
+	 * @param string $app
1467 1468
 	 * @return \OCP\Files\IAppData
1468 1469
 	 */
1469 1470
 	public function getAppDataDir($app) {
Please login to merge, or discard this patch.
Unused Use Statements   -2 removed lines patch added patch discarded remove patch
@@ -92,7 +92,6 @@  discard block
 block discarded – undo
92 92
 use OC\OCS\DiscoveryService;
93 93
 use OC\Remote\Api\ApiFactory;
94 94
 use OC\Remote\InstanceFactory;
95
-use OC\Repair\NC11\CleanPreviewsBackgroundJob;
96 95
 use OC\RichObjectStrings\Validator;
97 96
 use OC\Security\Bruteforce\Throttler;
98 97
 use OC\Security\CertificateManager;
@@ -112,7 +111,6 @@  discard block
 block discarded – undo
112 111
 use OC\Template\JSCombiner;
113 112
 use OC\Template\SCSSCacher;
114 113
 use OCA\Theming\ThemingDefaults;
115
-
116 114
 use OCP\App\IAppManager;
117 115
 use OCP\AppFramework\Utility\ITimeFactory;
118 116
 use OCP\Collaboration\AutoComplete\IManager;
Please login to merge, or discard this patch.
Indentation   +1837 added lines, -1837 removed lines patch added patch discarded remove patch
@@ -148,1846 +148,1846 @@
 block discarded – undo
148 148
  * TODO: hookup all manager classes
149 149
  */
150 150
 class Server extends ServerContainer implements IServerContainer {
151
-	/** @var string */
152
-	private $webRoot;
153
-
154
-	/**
155
-	 * @param string $webRoot
156
-	 * @param \OC\Config $config
157
-	 */
158
-	public function __construct($webRoot, \OC\Config $config) {
159
-		parent::__construct();
160
-		$this->webRoot = $webRoot;
161
-
162
-		$this->registerService(\OCP\IServerContainer::class, function (IServerContainer $c) {
163
-			return $c;
164
-		});
165
-
166
-		$this->registerAlias(\OCP\Calendar\IManager::class, \OC\Calendar\Manager::class);
167
-		$this->registerAlias('CalendarManager', \OC\Calendar\Manager::class);
168
-
169
-		$this->registerAlias(\OCP\Contacts\IManager::class, \OC\ContactsManager::class);
170
-		$this->registerAlias('ContactsManager', \OCP\Contacts\IManager::class);
171
-
172
-		$this->registerAlias(IActionFactory::class, ActionFactory::class);
173
-
174
-
175
-		$this->registerService(\OCP\IPreview::class, function (Server $c) {
176
-			return new PreviewManager(
177
-				$c->getConfig(),
178
-				$c->getRootFolder(),
179
-				$c->getAppDataDir('preview'),
180
-				$c->getEventDispatcher(),
181
-				$c->getSession()->get('user_id')
182
-			);
183
-		});
184
-		$this->registerAlias('PreviewManager', \OCP\IPreview::class);
185
-
186
-		$this->registerService(\OC\Preview\Watcher::class, function (Server $c) {
187
-			return new \OC\Preview\Watcher(
188
-				$c->getAppDataDir('preview')
189
-			);
190
-		});
191
-
192
-		$this->registerService('EncryptionManager', function (Server $c) {
193
-			$view = new View();
194
-			$util = new Encryption\Util(
195
-				$view,
196
-				$c->getUserManager(),
197
-				$c->getGroupManager(),
198
-				$c->getConfig()
199
-			);
200
-			return new Encryption\Manager(
201
-				$c->getConfig(),
202
-				$c->getLogger(),
203
-				$c->getL10N('core'),
204
-				new View(),
205
-				$util,
206
-				new ArrayCache()
207
-			);
208
-		});
209
-
210
-		$this->registerService('EncryptionFileHelper', function (Server $c) {
211
-			$util = new Encryption\Util(
212
-				new View(),
213
-				$c->getUserManager(),
214
-				$c->getGroupManager(),
215
-				$c->getConfig()
216
-			);
217
-			return new Encryption\File(
218
-				$util,
219
-				$c->getRootFolder(),
220
-				$c->getShareManager()
221
-			);
222
-		});
223
-
224
-		$this->registerService('EncryptionKeyStorage', function (Server $c) {
225
-			$view = new View();
226
-			$util = new Encryption\Util(
227
-				$view,
228
-				$c->getUserManager(),
229
-				$c->getGroupManager(),
230
-				$c->getConfig()
231
-			);
232
-
233
-			return new Encryption\Keys\Storage($view, $util);
234
-		});
235
-		$this->registerService('TagMapper', function (Server $c) {
236
-			return new TagMapper($c->getDatabaseConnection());
237
-		});
238
-
239
-		$this->registerService(\OCP\ITagManager::class, function (Server $c) {
240
-			$tagMapper = $c->query('TagMapper');
241
-			return new TagManager($tagMapper, $c->getUserSession());
242
-		});
243
-		$this->registerAlias('TagManager', \OCP\ITagManager::class);
244
-
245
-		$this->registerService('SystemTagManagerFactory', function (Server $c) {
246
-			$config = $c->getConfig();
247
-			$factoryClass = $config->getSystemValue('systemtags.managerFactory', '\OC\SystemTag\ManagerFactory');
248
-			/** @var \OC\SystemTag\ManagerFactory $factory */
249
-			$factory = new $factoryClass($this);
250
-			return $factory;
251
-		});
252
-		$this->registerService(\OCP\SystemTag\ISystemTagManager::class, function (Server $c) {
253
-			return $c->query('SystemTagManagerFactory')->getManager();
254
-		});
255
-		$this->registerAlias('SystemTagManager', \OCP\SystemTag\ISystemTagManager::class);
256
-
257
-		$this->registerService(\OCP\SystemTag\ISystemTagObjectMapper::class, function (Server $c) {
258
-			return $c->query('SystemTagManagerFactory')->getObjectMapper();
259
-		});
260
-		$this->registerService('RootFolder', function (Server $c) {
261
-			$manager = \OC\Files\Filesystem::getMountManager(null);
262
-			$view = new View();
263
-			$root = new Root(
264
-				$manager,
265
-				$view,
266
-				null,
267
-				$c->getUserMountCache(),
268
-				$this->getLogger(),
269
-				$this->getUserManager()
270
-			);
271
-			$connector = new HookConnector($root, $view);
272
-			$connector->viewToNode();
273
-
274
-			$previewConnector = new \OC\Preview\WatcherConnector($root, $c->getSystemConfig());
275
-			$previewConnector->connectWatcher();
276
-
277
-			return $root;
278
-		});
279
-		$this->registerAlias('SystemTagObjectMapper', \OCP\SystemTag\ISystemTagObjectMapper::class);
280
-
281
-		$this->registerService(\OCP\Files\IRootFolder::class, function (Server $c) {
282
-			return new LazyRoot(function () use ($c) {
283
-				return $c->query('RootFolder');
284
-			});
285
-		});
286
-		$this->registerAlias('LazyRootFolder', \OCP\Files\IRootFolder::class);
287
-
288
-		$this->registerService(\OCP\IUserManager::class, function (Server $c) {
289
-			$config = $c->getConfig();
290
-			return new \OC\User\Manager($config);
291
-		});
292
-		$this->registerAlias('UserManager', \OCP\IUserManager::class);
293
-
294
-		$this->registerService(\OCP\IGroupManager::class, function (Server $c) {
295
-			$groupManager = new \OC\Group\Manager($this->getUserManager(), $this->getLogger());
296
-			$groupManager->listen('\OC\Group', 'preCreate', function ($gid) {
297
-				\OC_Hook::emit('OC_Group', 'pre_createGroup', array('run' => true, 'gid' => $gid));
298
-			});
299
-			$groupManager->listen('\OC\Group', 'postCreate', function (\OC\Group\Group $gid) {
300
-				\OC_Hook::emit('OC_User', 'post_createGroup', array('gid' => $gid->getGID()));
301
-			});
302
-			$groupManager->listen('\OC\Group', 'preDelete', function (\OC\Group\Group $group) {
303
-				\OC_Hook::emit('OC_Group', 'pre_deleteGroup', array('run' => true, 'gid' => $group->getGID()));
304
-			});
305
-			$groupManager->listen('\OC\Group', 'postDelete', function (\OC\Group\Group $group) {
306
-				\OC_Hook::emit('OC_User', 'post_deleteGroup', array('gid' => $group->getGID()));
307
-			});
308
-			$groupManager->listen('\OC\Group', 'preAddUser', function (\OC\Group\Group $group, \OC\User\User $user) {
309
-				\OC_Hook::emit('OC_Group', 'pre_addToGroup', array('run' => true, 'uid' => $user->getUID(), 'gid' => $group->getGID()));
310
-			});
311
-			$groupManager->listen('\OC\Group', 'postAddUser', function (\OC\Group\Group $group, \OC\User\User $user) {
312
-				\OC_Hook::emit('OC_Group', 'post_addToGroup', array('uid' => $user->getUID(), 'gid' => $group->getGID()));
313
-				//Minimal fix to keep it backward compatible TODO: clean up all the GroupManager hooks
314
-				\OC_Hook::emit('OC_User', 'post_addToGroup', array('uid' => $user->getUID(), 'gid' => $group->getGID()));
315
-			});
316
-			return $groupManager;
317
-		});
318
-		$this->registerAlias('GroupManager', \OCP\IGroupManager::class);
319
-
320
-		$this->registerService(Store::class, function (Server $c) {
321
-			$session = $c->getSession();
322
-			if (\OC::$server->getSystemConfig()->getValue('installed', false)) {
323
-				$tokenProvider = $c->query('OC\Authentication\Token\IProvider');
324
-			} else {
325
-				$tokenProvider = null;
326
-			}
327
-			$logger = $c->getLogger();
328
-			return new Store($session, $logger, $tokenProvider);
329
-		});
330
-		$this->registerAlias(IStore::class, Store::class);
331
-		$this->registerService('OC\Authentication\Token\DefaultTokenMapper', function (Server $c) {
332
-			$dbConnection = $c->getDatabaseConnection();
333
-			return new Authentication\Token\DefaultTokenMapper($dbConnection);
334
-		});
335
-		$this->registerService('OC\Authentication\Token\DefaultTokenProvider', function (Server $c) {
336
-			$mapper = $c->query('OC\Authentication\Token\DefaultTokenMapper');
337
-			$crypto = $c->getCrypto();
338
-			$config = $c->getConfig();
339
-			$logger = $c->getLogger();
340
-			$timeFactory = new TimeFactory();
341
-			return new \OC\Authentication\Token\DefaultTokenProvider($mapper, $crypto, $config, $logger, $timeFactory);
342
-		});
343
-		$this->registerAlias('OC\Authentication\Token\IProvider', 'OC\Authentication\Token\DefaultTokenProvider');
344
-
345
-		$this->registerService(\OCP\IUserSession::class, function (Server $c) {
346
-			$manager = $c->getUserManager();
347
-			$session = new \OC\Session\Memory('');
348
-			$timeFactory = new TimeFactory();
349
-			// Token providers might require a working database. This code
350
-			// might however be called when ownCloud is not yet setup.
351
-			if (\OC::$server->getSystemConfig()->getValue('installed', false)) {
352
-				$defaultTokenProvider = $c->query('OC\Authentication\Token\IProvider');
353
-			} else {
354
-				$defaultTokenProvider = null;
355
-			}
356
-
357
-			$dispatcher = $c->getEventDispatcher();
358
-
359
-			$userSession = new \OC\User\Session(
360
-				$manager,
361
-				$session,
362
-				$timeFactory,
363
-				$defaultTokenProvider,
364
-				$c->getConfig(),
365
-				$c->getSecureRandom(),
366
-				$c->getLockdownManager(),
367
-				$c->getLogger()
368
-			);
369
-			$userSession->listen('\OC\User', 'preCreateUser', function ($uid, $password) {
370
-				\OC_Hook::emit('OC_User', 'pre_createUser', array('run' => true, 'uid' => $uid, 'password' => $password));
371
-			});
372
-			$userSession->listen('\OC\User', 'postCreateUser', function ($user, $password) {
373
-				/** @var $user \OC\User\User */
374
-				\OC_Hook::emit('OC_User', 'post_createUser', array('uid' => $user->getUID(), 'password' => $password));
375
-			});
376
-			$userSession->listen('\OC\User', 'preDelete', function ($user) use ($dispatcher) {
377
-				/** @var $user \OC\User\User */
378
-				\OC_Hook::emit('OC_User', 'pre_deleteUser', array('run' => true, 'uid' => $user->getUID()));
379
-				$dispatcher->dispatch('OCP\IUser::preDelete', new GenericEvent($user));
380
-			});
381
-			$userSession->listen('\OC\User', 'postDelete', function ($user) {
382
-				/** @var $user \OC\User\User */
383
-				\OC_Hook::emit('OC_User', 'post_deleteUser', array('uid' => $user->getUID()));
384
-			});
385
-			$userSession->listen('\OC\User', 'preSetPassword', function ($user, $password, $recoveryPassword) {
386
-				/** @var $user \OC\User\User */
387
-				\OC_Hook::emit('OC_User', 'pre_setPassword', array('run' => true, 'uid' => $user->getUID(), 'password' => $password, 'recoveryPassword' => $recoveryPassword));
388
-			});
389
-			$userSession->listen('\OC\User', 'postSetPassword', function ($user, $password, $recoveryPassword) {
390
-				/** @var $user \OC\User\User */
391
-				\OC_Hook::emit('OC_User', 'post_setPassword', array('run' => true, 'uid' => $user->getUID(), 'password' => $password, 'recoveryPassword' => $recoveryPassword));
392
-			});
393
-			$userSession->listen('\OC\User', 'preLogin', function ($uid, $password) {
394
-				\OC_Hook::emit('OC_User', 'pre_login', array('run' => true, 'uid' => $uid, 'password' => $password));
395
-			});
396
-			$userSession->listen('\OC\User', 'postLogin', function ($user, $password) {
397
-				/** @var $user \OC\User\User */
398
-				\OC_Hook::emit('OC_User', 'post_login', array('run' => true, 'uid' => $user->getUID(), 'password' => $password));
399
-			});
400
-			$userSession->listen('\OC\User', 'postRememberedLogin', function ($user, $password) {
401
-				/** @var $user \OC\User\User */
402
-				\OC_Hook::emit('OC_User', 'post_login', array('run' => true, 'uid' => $user->getUID(), 'password' => $password));
403
-			});
404
-			$userSession->listen('\OC\User', 'logout', function () {
405
-				\OC_Hook::emit('OC_User', 'logout', array());
406
-			});
407
-			$userSession->listen('\OC\User', 'changeUser', function ($user, $feature, $value, $oldValue) use ($dispatcher) {
408
-				/** @var $user \OC\User\User */
409
-				\OC_Hook::emit('OC_User', 'changeUser', array('run' => true, 'user' => $user, 'feature' => $feature, 'value' => $value, 'old_value' => $oldValue));
410
-				$dispatcher->dispatch('OCP\IUser::changeUser', new GenericEvent($user, ['feature' => $feature, 'oldValue' => $oldValue, 'value' => $value]));
411
-			});
412
-			return $userSession;
413
-		});
414
-		$this->registerAlias('UserSession', \OCP\IUserSession::class);
415
-
416
-		$this->registerService(\OC\Authentication\TwoFactorAuth\Manager::class, function (Server $c) {
417
-			return new \OC\Authentication\TwoFactorAuth\Manager(
418
-				$c->getAppManager(),
419
-				$c->getSession(),
420
-				$c->getConfig(),
421
-				$c->getActivityManager(),
422
-				$c->getLogger(),
423
-				$c->query(\OC\Authentication\Token\IProvider::class),
424
-				$c->query(ITimeFactory::class)
425
-			);
426
-		});
427
-
428
-		$this->registerAlias(\OCP\INavigationManager::class, \OC\NavigationManager::class);
429
-		$this->registerAlias('NavigationManager', \OCP\INavigationManager::class);
430
-
431
-		$this->registerService(\OC\AllConfig::class, function (Server $c) {
432
-			return new \OC\AllConfig(
433
-				$c->getSystemConfig()
434
-			);
435
-		});
436
-		$this->registerAlias('AllConfig', \OC\AllConfig::class);
437
-		$this->registerAlias(\OCP\IConfig::class, \OC\AllConfig::class);
438
-
439
-		$this->registerService('SystemConfig', function ($c) use ($config) {
440
-			return new \OC\SystemConfig($config);
441
-		});
442
-
443
-		$this->registerService(\OC\AppConfig::class, function (Server $c) {
444
-			return new \OC\AppConfig($c->getDatabaseConnection());
445
-		});
446
-		$this->registerAlias('AppConfig', \OC\AppConfig::class);
447
-		$this->registerAlias(\OCP\IAppConfig::class, \OC\AppConfig::class);
448
-
449
-		$this->registerService(\OCP\L10N\IFactory::class, function (Server $c) {
450
-			return new \OC\L10N\Factory(
451
-				$c->getConfig(),
452
-				$c->getRequest(),
453
-				$c->getUserSession(),
454
-				\OC::$SERVERROOT
455
-			);
456
-		});
457
-		$this->registerAlias('L10NFactory', \OCP\L10N\IFactory::class);
458
-
459
-		$this->registerService(\OCP\IURLGenerator::class, function (Server $c) {
460
-			$config = $c->getConfig();
461
-			$cacheFactory = $c->getMemCacheFactory();
462
-			$request = $c->getRequest();
463
-			return new \OC\URLGenerator(
464
-				$config,
465
-				$cacheFactory,
466
-				$request
467
-			);
468
-		});
469
-		$this->registerAlias('URLGenerator', \OCP\IURLGenerator::class);
470
-
471
-		$this->registerService('AppHelper', function ($c) {
472
-			return new \OC\AppHelper();
473
-		});
474
-		$this->registerAlias('AppFetcher', AppFetcher::class);
475
-		$this->registerAlias('CategoryFetcher', CategoryFetcher::class);
476
-
477
-		$this->registerService(\OCP\ICache::class, function ($c) {
478
-			return new Cache\File();
479
-		});
480
-		$this->registerAlias('UserCache', \OCP\ICache::class);
481
-
482
-		$this->registerService(Factory::class, function (Server $c) {
483
-
484
-			$arrayCacheFactory = new \OC\Memcache\Factory('', $c->getLogger(),
485
-				'\\OC\\Memcache\\ArrayCache',
486
-				'\\OC\\Memcache\\ArrayCache',
487
-				'\\OC\\Memcache\\ArrayCache'
488
-			);
489
-			$config = $c->getConfig();
490
-			$request = $c->getRequest();
491
-			$urlGenerator = new URLGenerator($config, $arrayCacheFactory, $request);
492
-
493
-			if ($config->getSystemValue('installed', false) && !(defined('PHPUNIT_RUN') && PHPUNIT_RUN)) {
494
-				$v = \OC_App::getAppVersions();
495
-				$v['core'] = implode(',', \OC_Util::getVersion());
496
-				$version = implode(',', $v);
497
-				$instanceId = \OC_Util::getInstanceId();
498
-				$path = \OC::$SERVERROOT;
499
-				$prefix = md5($instanceId . '-' . $version . '-' . $path);
500
-				return new \OC\Memcache\Factory($prefix, $c->getLogger(),
501
-					$config->getSystemValue('memcache.local', null),
502
-					$config->getSystemValue('memcache.distributed', null),
503
-					$config->getSystemValue('memcache.locking', null)
504
-				);
505
-			}
506
-			return $arrayCacheFactory;
507
-
508
-		});
509
-		$this->registerAlias('MemCacheFactory', Factory::class);
510
-		$this->registerAlias(ICacheFactory::class, Factory::class);
511
-
512
-		$this->registerService('RedisFactory', function (Server $c) {
513
-			$systemConfig = $c->getSystemConfig();
514
-			return new RedisFactory($systemConfig);
515
-		});
516
-
517
-		$this->registerService(\OCP\Activity\IManager::class, function (Server $c) {
518
-			return new \OC\Activity\Manager(
519
-				$c->getRequest(),
520
-				$c->getUserSession(),
521
-				$c->getConfig(),
522
-				$c->query(IValidator::class)
523
-			);
524
-		});
525
-		$this->registerAlias('ActivityManager', \OCP\Activity\IManager::class);
526
-
527
-		$this->registerService(\OCP\Activity\IEventMerger::class, function (Server $c) {
528
-			return new \OC\Activity\EventMerger(
529
-				$c->getL10N('lib')
530
-			);
531
-		});
532
-		$this->registerAlias(IValidator::class, Validator::class);
533
-
534
-		$this->registerService(\OCP\IAvatarManager::class, function (Server $c) {
535
-			return new AvatarManager(
536
-				$c->getUserManager(),
537
-				$c->getAppDataDir('avatar'),
538
-				$c->getL10N('lib'),
539
-				$c->getLogger(),
540
-				$c->getConfig()
541
-			);
542
-		});
543
-		$this->registerAlias('AvatarManager', \OCP\IAvatarManager::class);
544
-
545
-		$this->registerAlias(\OCP\Support\CrashReport\IRegistry::class, \OC\Support\CrashReport\Registry::class);
546
-
547
-		$this->registerService(\OCP\ILogger::class, function (Server $c) {
548
-			$logType = $c->query('AllConfig')->getSystemValue('log_type', 'file');
549
-			$logger = Log::getLogClass($logType);
550
-			call_user_func(array($logger, 'init'));
551
-			$config = $this->getSystemConfig();
552
-			$registry = $c->query(\OCP\Support\CrashReport\IRegistry::class);
553
-
554
-			return new Log($logger, $config, null, $registry);
555
-		});
556
-		$this->registerAlias('Logger', \OCP\ILogger::class);
557
-
558
-		$this->registerService(\OCP\BackgroundJob\IJobList::class, function (Server $c) {
559
-			$config = $c->getConfig();
560
-			return new \OC\BackgroundJob\JobList(
561
-				$c->getDatabaseConnection(),
562
-				$config,
563
-				new TimeFactory()
564
-			);
565
-		});
566
-		$this->registerAlias('JobList', \OCP\BackgroundJob\IJobList::class);
567
-
568
-		$this->registerService(\OCP\Route\IRouter::class, function (Server $c) {
569
-			$cacheFactory = $c->getMemCacheFactory();
570
-			$logger = $c->getLogger();
571
-			if ($cacheFactory->isAvailableLowLatency()) {
572
-				$router = new \OC\Route\CachingRouter($cacheFactory->createLocal('route'), $logger);
573
-			} else {
574
-				$router = new \OC\Route\Router($logger);
575
-			}
576
-			return $router;
577
-		});
578
-		$this->registerAlias('Router', \OCP\Route\IRouter::class);
579
-
580
-		$this->registerService(\OCP\ISearch::class, function ($c) {
581
-			return new Search();
582
-		});
583
-		$this->registerAlias('Search', \OCP\ISearch::class);
584
-
585
-		$this->registerService(\OC\Security\RateLimiting\Limiter::class, function ($c) {
586
-			return new \OC\Security\RateLimiting\Limiter(
587
-				$this->getUserSession(),
588
-				$this->getRequest(),
589
-				new \OC\AppFramework\Utility\TimeFactory(),
590
-				$c->query(\OC\Security\RateLimiting\Backend\IBackend::class)
591
-			);
592
-		});
593
-		$this->registerService(\OC\Security\RateLimiting\Backend\IBackend::class, function ($c) {
594
-			return new \OC\Security\RateLimiting\Backend\MemoryCache(
595
-				$this->getMemCacheFactory(),
596
-				new \OC\AppFramework\Utility\TimeFactory()
597
-			);
598
-		});
599
-
600
-		$this->registerService(\OCP\Security\ISecureRandom::class, function ($c) {
601
-			return new SecureRandom();
602
-		});
603
-		$this->registerAlias('SecureRandom', \OCP\Security\ISecureRandom::class);
604
-
605
-		$this->registerService(\OCP\Security\ICrypto::class, function (Server $c) {
606
-			return new Crypto($c->getConfig(), $c->getSecureRandom());
607
-		});
608
-		$this->registerAlias('Crypto', \OCP\Security\ICrypto::class);
609
-
610
-		$this->registerService(\OCP\Security\IHasher::class, function (Server $c) {
611
-			return new Hasher($c->getConfig());
612
-		});
613
-		$this->registerAlias('Hasher', \OCP\Security\IHasher::class);
614
-
615
-		$this->registerService(\OCP\Security\ICredentialsManager::class, function (Server $c) {
616
-			return new CredentialsManager($c->getCrypto(), $c->getDatabaseConnection());
617
-		});
618
-		$this->registerAlias('CredentialsManager', \OCP\Security\ICredentialsManager::class);
619
-
620
-		$this->registerService(IDBConnection::class, function (Server $c) {
621
-			$systemConfig = $c->getSystemConfig();
622
-			$factory = new \OC\DB\ConnectionFactory($systemConfig);
623
-			$type = $systemConfig->getValue('dbtype', 'sqlite');
624
-			if (!$factory->isValidType($type)) {
625
-				throw new \OC\DatabaseException('Invalid database type');
626
-			}
627
-			$connectionParams = $factory->createConnectionParams();
628
-			$connection = $factory->getConnection($type, $connectionParams);
629
-			$connection->getConfiguration()->setSQLLogger($c->getQueryLogger());
630
-			return $connection;
631
-		});
632
-		$this->registerAlias('DatabaseConnection', IDBConnection::class);
633
-
634
-		$this->registerService('HTTPHelper', function (Server $c) {
635
-			$config = $c->getConfig();
636
-			return new HTTPHelper(
637
-				$config,
638
-				$c->getHTTPClientService()
639
-			);
640
-		});
641
-
642
-		$this->registerService(\OCP\Http\Client\IClientService::class, function (Server $c) {
643
-			$user = \OC_User::getUser();
644
-			$uid = $user ? $user : null;
645
-			return new ClientService(
646
-				$c->getConfig(),
647
-				new \OC\Security\CertificateManager(
648
-					$uid,
649
-					new View(),
650
-					$c->getConfig(),
651
-					$c->getLogger(),
652
-					$c->getSecureRandom()
653
-				)
654
-			);
655
-		});
656
-		$this->registerAlias('HttpClientService', \OCP\Http\Client\IClientService::class);
657
-		$this->registerService(\OCP\Diagnostics\IEventLogger::class, function (Server $c) {
658
-			$eventLogger = new EventLogger();
659
-			if ($c->getSystemConfig()->getValue('debug', false)) {
660
-				// In debug mode, module is being activated by default
661
-				$eventLogger->activate();
662
-			}
663
-			return $eventLogger;
664
-		});
665
-		$this->registerAlias('EventLogger', \OCP\Diagnostics\IEventLogger::class);
666
-
667
-		$this->registerService(\OCP\Diagnostics\IQueryLogger::class, function (Server $c) {
668
-			$queryLogger = new QueryLogger();
669
-			if ($c->getSystemConfig()->getValue('debug', false)) {
670
-				// In debug mode, module is being activated by default
671
-				$queryLogger->activate();
672
-			}
673
-			return $queryLogger;
674
-		});
675
-		$this->registerAlias('QueryLogger', \OCP\Diagnostics\IQueryLogger::class);
676
-
677
-		$this->registerService(TempManager::class, function (Server $c) {
678
-			return new TempManager(
679
-				$c->getLogger(),
680
-				$c->getConfig()
681
-			);
682
-		});
683
-		$this->registerAlias('TempManager', TempManager::class);
684
-		$this->registerAlias(ITempManager::class, TempManager::class);
685
-
686
-		$this->registerService(AppManager::class, function (Server $c) {
687
-			return new \OC\App\AppManager(
688
-				$c->getUserSession(),
689
-				$c->getAppConfig(),
690
-				$c->getGroupManager(),
691
-				$c->getMemCacheFactory(),
692
-				$c->getEventDispatcher()
693
-			);
694
-		});
695
-		$this->registerAlias('AppManager', AppManager::class);
696
-		$this->registerAlias(IAppManager::class, AppManager::class);
697
-
698
-		$this->registerService(\OCP\IDateTimeZone::class, function (Server $c) {
699
-			return new DateTimeZone(
700
-				$c->getConfig(),
701
-				$c->getSession()
702
-			);
703
-		});
704
-		$this->registerAlias('DateTimeZone', \OCP\IDateTimeZone::class);
705
-
706
-		$this->registerService(\OCP\IDateTimeFormatter::class, function (Server $c) {
707
-			$language = $c->getConfig()->getUserValue($c->getSession()->get('user_id'), 'core', 'lang', null);
708
-
709
-			return new DateTimeFormatter(
710
-				$c->getDateTimeZone()->getTimeZone(),
711
-				$c->getL10N('lib', $language)
712
-			);
713
-		});
714
-		$this->registerAlias('DateTimeFormatter', \OCP\IDateTimeFormatter::class);
715
-
716
-		$this->registerService(\OCP\Files\Config\IUserMountCache::class, function (Server $c) {
717
-			$mountCache = new UserMountCache($c->getDatabaseConnection(), $c->getUserManager(), $c->getLogger());
718
-			$listener = new UserMountCacheListener($mountCache);
719
-			$listener->listen($c->getUserManager());
720
-			return $mountCache;
721
-		});
722
-		$this->registerAlias('UserMountCache', \OCP\Files\Config\IUserMountCache::class);
723
-
724
-		$this->registerService(\OCP\Files\Config\IMountProviderCollection::class, function (Server $c) {
725
-			$loader = \OC\Files\Filesystem::getLoader();
726
-			$mountCache = $c->query('UserMountCache');
727
-			$manager = new \OC\Files\Config\MountProviderCollection($loader, $mountCache);
728
-
729
-			// builtin providers
730
-
731
-			$config = $c->getConfig();
732
-			$manager->registerProvider(new CacheMountProvider($config));
733
-			$manager->registerHomeProvider(new LocalHomeMountProvider());
734
-			$manager->registerHomeProvider(new ObjectHomeMountProvider($config));
735
-
736
-			return $manager;
737
-		});
738
-		$this->registerAlias('MountConfigManager', \OCP\Files\Config\IMountProviderCollection::class);
739
-
740
-		$this->registerService('IniWrapper', function ($c) {
741
-			return new IniGetWrapper();
742
-		});
743
-		$this->registerService('AsyncCommandBus', function (Server $c) {
744
-			$busClass = $c->getConfig()->getSystemValue('commandbus');
745
-			if ($busClass) {
746
-				list($app, $class) = explode('::', $busClass, 2);
747
-				if ($c->getAppManager()->isInstalled($app)) {
748
-					\OC_App::loadApp($app);
749
-					return $c->query($class);
750
-				} else {
751
-					throw new ServiceUnavailableException("The app providing the command bus ($app) is not enabled");
752
-				}
753
-			} else {
754
-				$jobList = $c->getJobList();
755
-				return new CronBus($jobList);
756
-			}
757
-		});
758
-		$this->registerService('TrustedDomainHelper', function ($c) {
759
-			return new TrustedDomainHelper($this->getConfig());
760
-		});
761
-		$this->registerService(Throttler::class, function (Server $c) {
762
-			return new Throttler(
763
-				$c->getDatabaseConnection(),
764
-				new TimeFactory(),
765
-				$c->getLogger(),
766
-				$c->getConfig()
767
-			);
768
-		});
769
-		$this->registerAlias('Throttler', Throttler::class);
770
-		$this->registerService('IntegrityCodeChecker', function (Server $c) {
771
-			// IConfig and IAppManager requires a working database. This code
772
-			// might however be called when ownCloud is not yet setup.
773
-			if (\OC::$server->getSystemConfig()->getValue('installed', false)) {
774
-				$config = $c->getConfig();
775
-				$appManager = $c->getAppManager();
776
-			} else {
777
-				$config = null;
778
-				$appManager = null;
779
-			}
780
-
781
-			return new Checker(
782
-				new EnvironmentHelper(),
783
-				new FileAccessHelper(),
784
-				new AppLocator(),
785
-				$config,
786
-				$c->getMemCacheFactory(),
787
-				$appManager,
788
-				$c->getTempManager()
789
-			);
790
-		});
791
-		$this->registerService(\OCP\IRequest::class, function ($c) {
792
-			if (isset($this['urlParams'])) {
793
-				$urlParams = $this['urlParams'];
794
-			} else {
795
-				$urlParams = [];
796
-			}
797
-
798
-			if (defined('PHPUNIT_RUN') && PHPUNIT_RUN
799
-				&& in_array('fakeinput', stream_get_wrappers())
800
-			) {
801
-				$stream = 'fakeinput://data';
802
-			} else {
803
-				$stream = 'php://input';
804
-			}
805
-
806
-			return new Request(
807
-				[
808
-					'get' => $_GET,
809
-					'post' => $_POST,
810
-					'files' => $_FILES,
811
-					'server' => $_SERVER,
812
-					'env' => $_ENV,
813
-					'cookies' => $_COOKIE,
814
-					'method' => (isset($_SERVER) && isset($_SERVER['REQUEST_METHOD']))
815
-						? $_SERVER['REQUEST_METHOD']
816
-						: null,
817
-					'urlParams' => $urlParams,
818
-				],
819
-				$this->getSecureRandom(),
820
-				$this->getConfig(),
821
-				$this->getCsrfTokenManager(),
822
-				$stream
823
-			);
824
-		});
825
-		$this->registerAlias('Request', \OCP\IRequest::class);
826
-
827
-		$this->registerService(\OCP\Mail\IMailer::class, function (Server $c) {
828
-			return new Mailer(
829
-				$c->getConfig(),
830
-				$c->getLogger(),
831
-				$c->query(Defaults::class),
832
-				$c->getURLGenerator(),
833
-				$c->getL10N('lib')
834
-			);
835
-		});
836
-		$this->registerAlias('Mailer', \OCP\Mail\IMailer::class);
837
-
838
-		$this->registerService('LDAPProvider', function (Server $c) {
839
-			$config = $c->getConfig();
840
-			$factoryClass = $config->getSystemValue('ldapProviderFactory', null);
841
-			if (is_null($factoryClass)) {
842
-				throw new \Exception('ldapProviderFactory not set');
843
-			}
844
-			/** @var \OCP\LDAP\ILDAPProviderFactory $factory */
845
-			$factory = new $factoryClass($this);
846
-			return $factory->getLDAPProvider();
847
-		});
848
-		$this->registerService(ILockingProvider::class, function (Server $c) {
849
-			$ini = $c->getIniWrapper();
850
-			$config = $c->getConfig();
851
-			$ttl = $config->getSystemValue('filelocking.ttl', max(3600, $ini->getNumeric('max_execution_time')));
852
-			if ($config->getSystemValue('filelocking.enabled', true) or (defined('PHPUNIT_RUN') && PHPUNIT_RUN)) {
853
-				/** @var \OC\Memcache\Factory $memcacheFactory */
854
-				$memcacheFactory = $c->getMemCacheFactory();
855
-				$memcache = $memcacheFactory->createLocking('lock');
856
-				if (!($memcache instanceof \OC\Memcache\NullCache)) {
857
-					return new MemcacheLockingProvider($memcache, $ttl);
858
-				}
859
-				return new DBLockingProvider($c->getDatabaseConnection(), $c->getLogger(), new TimeFactory(), $ttl);
860
-			}
861
-			return new NoopLockingProvider();
862
-		});
863
-		$this->registerAlias('LockingProvider', ILockingProvider::class);
864
-
865
-		$this->registerService(\OCP\Files\Mount\IMountManager::class, function () {
866
-			return new \OC\Files\Mount\Manager();
867
-		});
868
-		$this->registerAlias('MountManager', \OCP\Files\Mount\IMountManager::class);
869
-
870
-		$this->registerService(\OCP\Files\IMimeTypeDetector::class, function (Server $c) {
871
-			return new \OC\Files\Type\Detection(
872
-				$c->getURLGenerator(),
873
-				\OC::$configDir,
874
-				\OC::$SERVERROOT . '/resources/config/'
875
-			);
876
-		});
877
-		$this->registerAlias('MimeTypeDetector', \OCP\Files\IMimeTypeDetector::class);
878
-
879
-		$this->registerService(\OCP\Files\IMimeTypeLoader::class, function (Server $c) {
880
-			return new \OC\Files\Type\Loader(
881
-				$c->getDatabaseConnection()
882
-			);
883
-		});
884
-		$this->registerAlias('MimeTypeLoader', \OCP\Files\IMimeTypeLoader::class);
885
-		$this->registerService(BundleFetcher::class, function () {
886
-			return new BundleFetcher($this->getL10N('lib'));
887
-		});
888
-		$this->registerService(\OCP\Notification\IManager::class, function (Server $c) {
889
-			return new Manager(
890
-				$c->query(IValidator::class)
891
-			);
892
-		});
893
-		$this->registerAlias('NotificationManager', \OCP\Notification\IManager::class);
894
-
895
-		$this->registerService(\OC\CapabilitiesManager::class, function (Server $c) {
896
-			$manager = new \OC\CapabilitiesManager($c->getLogger());
897
-			$manager->registerCapability(function () use ($c) {
898
-				return new \OC\OCS\CoreCapabilities($c->getConfig());
899
-			});
900
-			$manager->registerCapability(function () use ($c) {
901
-				return $c->query(\OC\Security\Bruteforce\Capabilities::class);
902
-			});
903
-			return $manager;
904
-		});
905
-		$this->registerAlias('CapabilitiesManager', \OC\CapabilitiesManager::class);
906
-
907
-		$this->registerService(\OCP\Comments\ICommentsManager::class, function (Server $c) {
908
-			$config = $c->getConfig();
909
-			$factoryClass = $config->getSystemValue('comments.managerFactory', '\OC\Comments\ManagerFactory');
910
-			/** @var \OCP\Comments\ICommentsManagerFactory $factory */
911
-			$factory = new $factoryClass($this);
912
-			$manager = $factory->getManager();
913
-
914
-			$manager->registerDisplayNameResolver('user', function($id) use ($c) {
915
-				$manager = $c->getUserManager();
916
-				$user = $manager->get($id);
917
-				if(is_null($user)) {
918
-					$l = $c->getL10N('core');
919
-					$displayName = $l->t('Unknown user');
920
-				} else {
921
-					$displayName = $user->getDisplayName();
922
-				}
923
-				return $displayName;
924
-			});
925
-
926
-			return $manager;
927
-		});
928
-		$this->registerAlias('CommentsManager', \OCP\Comments\ICommentsManager::class);
929
-
930
-		$this->registerService('ThemingDefaults', function (Server $c) {
931
-			/*
151
+    /** @var string */
152
+    private $webRoot;
153
+
154
+    /**
155
+     * @param string $webRoot
156
+     * @param \OC\Config $config
157
+     */
158
+    public function __construct($webRoot, \OC\Config $config) {
159
+        parent::__construct();
160
+        $this->webRoot = $webRoot;
161
+
162
+        $this->registerService(\OCP\IServerContainer::class, function (IServerContainer $c) {
163
+            return $c;
164
+        });
165
+
166
+        $this->registerAlias(\OCP\Calendar\IManager::class, \OC\Calendar\Manager::class);
167
+        $this->registerAlias('CalendarManager', \OC\Calendar\Manager::class);
168
+
169
+        $this->registerAlias(\OCP\Contacts\IManager::class, \OC\ContactsManager::class);
170
+        $this->registerAlias('ContactsManager', \OCP\Contacts\IManager::class);
171
+
172
+        $this->registerAlias(IActionFactory::class, ActionFactory::class);
173
+
174
+
175
+        $this->registerService(\OCP\IPreview::class, function (Server $c) {
176
+            return new PreviewManager(
177
+                $c->getConfig(),
178
+                $c->getRootFolder(),
179
+                $c->getAppDataDir('preview'),
180
+                $c->getEventDispatcher(),
181
+                $c->getSession()->get('user_id')
182
+            );
183
+        });
184
+        $this->registerAlias('PreviewManager', \OCP\IPreview::class);
185
+
186
+        $this->registerService(\OC\Preview\Watcher::class, function (Server $c) {
187
+            return new \OC\Preview\Watcher(
188
+                $c->getAppDataDir('preview')
189
+            );
190
+        });
191
+
192
+        $this->registerService('EncryptionManager', function (Server $c) {
193
+            $view = new View();
194
+            $util = new Encryption\Util(
195
+                $view,
196
+                $c->getUserManager(),
197
+                $c->getGroupManager(),
198
+                $c->getConfig()
199
+            );
200
+            return new Encryption\Manager(
201
+                $c->getConfig(),
202
+                $c->getLogger(),
203
+                $c->getL10N('core'),
204
+                new View(),
205
+                $util,
206
+                new ArrayCache()
207
+            );
208
+        });
209
+
210
+        $this->registerService('EncryptionFileHelper', function (Server $c) {
211
+            $util = new Encryption\Util(
212
+                new View(),
213
+                $c->getUserManager(),
214
+                $c->getGroupManager(),
215
+                $c->getConfig()
216
+            );
217
+            return new Encryption\File(
218
+                $util,
219
+                $c->getRootFolder(),
220
+                $c->getShareManager()
221
+            );
222
+        });
223
+
224
+        $this->registerService('EncryptionKeyStorage', function (Server $c) {
225
+            $view = new View();
226
+            $util = new Encryption\Util(
227
+                $view,
228
+                $c->getUserManager(),
229
+                $c->getGroupManager(),
230
+                $c->getConfig()
231
+            );
232
+
233
+            return new Encryption\Keys\Storage($view, $util);
234
+        });
235
+        $this->registerService('TagMapper', function (Server $c) {
236
+            return new TagMapper($c->getDatabaseConnection());
237
+        });
238
+
239
+        $this->registerService(\OCP\ITagManager::class, function (Server $c) {
240
+            $tagMapper = $c->query('TagMapper');
241
+            return new TagManager($tagMapper, $c->getUserSession());
242
+        });
243
+        $this->registerAlias('TagManager', \OCP\ITagManager::class);
244
+
245
+        $this->registerService('SystemTagManagerFactory', function (Server $c) {
246
+            $config = $c->getConfig();
247
+            $factoryClass = $config->getSystemValue('systemtags.managerFactory', '\OC\SystemTag\ManagerFactory');
248
+            /** @var \OC\SystemTag\ManagerFactory $factory */
249
+            $factory = new $factoryClass($this);
250
+            return $factory;
251
+        });
252
+        $this->registerService(\OCP\SystemTag\ISystemTagManager::class, function (Server $c) {
253
+            return $c->query('SystemTagManagerFactory')->getManager();
254
+        });
255
+        $this->registerAlias('SystemTagManager', \OCP\SystemTag\ISystemTagManager::class);
256
+
257
+        $this->registerService(\OCP\SystemTag\ISystemTagObjectMapper::class, function (Server $c) {
258
+            return $c->query('SystemTagManagerFactory')->getObjectMapper();
259
+        });
260
+        $this->registerService('RootFolder', function (Server $c) {
261
+            $manager = \OC\Files\Filesystem::getMountManager(null);
262
+            $view = new View();
263
+            $root = new Root(
264
+                $manager,
265
+                $view,
266
+                null,
267
+                $c->getUserMountCache(),
268
+                $this->getLogger(),
269
+                $this->getUserManager()
270
+            );
271
+            $connector = new HookConnector($root, $view);
272
+            $connector->viewToNode();
273
+
274
+            $previewConnector = new \OC\Preview\WatcherConnector($root, $c->getSystemConfig());
275
+            $previewConnector->connectWatcher();
276
+
277
+            return $root;
278
+        });
279
+        $this->registerAlias('SystemTagObjectMapper', \OCP\SystemTag\ISystemTagObjectMapper::class);
280
+
281
+        $this->registerService(\OCP\Files\IRootFolder::class, function (Server $c) {
282
+            return new LazyRoot(function () use ($c) {
283
+                return $c->query('RootFolder');
284
+            });
285
+        });
286
+        $this->registerAlias('LazyRootFolder', \OCP\Files\IRootFolder::class);
287
+
288
+        $this->registerService(\OCP\IUserManager::class, function (Server $c) {
289
+            $config = $c->getConfig();
290
+            return new \OC\User\Manager($config);
291
+        });
292
+        $this->registerAlias('UserManager', \OCP\IUserManager::class);
293
+
294
+        $this->registerService(\OCP\IGroupManager::class, function (Server $c) {
295
+            $groupManager = new \OC\Group\Manager($this->getUserManager(), $this->getLogger());
296
+            $groupManager->listen('\OC\Group', 'preCreate', function ($gid) {
297
+                \OC_Hook::emit('OC_Group', 'pre_createGroup', array('run' => true, 'gid' => $gid));
298
+            });
299
+            $groupManager->listen('\OC\Group', 'postCreate', function (\OC\Group\Group $gid) {
300
+                \OC_Hook::emit('OC_User', 'post_createGroup', array('gid' => $gid->getGID()));
301
+            });
302
+            $groupManager->listen('\OC\Group', 'preDelete', function (\OC\Group\Group $group) {
303
+                \OC_Hook::emit('OC_Group', 'pre_deleteGroup', array('run' => true, 'gid' => $group->getGID()));
304
+            });
305
+            $groupManager->listen('\OC\Group', 'postDelete', function (\OC\Group\Group $group) {
306
+                \OC_Hook::emit('OC_User', 'post_deleteGroup', array('gid' => $group->getGID()));
307
+            });
308
+            $groupManager->listen('\OC\Group', 'preAddUser', function (\OC\Group\Group $group, \OC\User\User $user) {
309
+                \OC_Hook::emit('OC_Group', 'pre_addToGroup', array('run' => true, 'uid' => $user->getUID(), 'gid' => $group->getGID()));
310
+            });
311
+            $groupManager->listen('\OC\Group', 'postAddUser', function (\OC\Group\Group $group, \OC\User\User $user) {
312
+                \OC_Hook::emit('OC_Group', 'post_addToGroup', array('uid' => $user->getUID(), 'gid' => $group->getGID()));
313
+                //Minimal fix to keep it backward compatible TODO: clean up all the GroupManager hooks
314
+                \OC_Hook::emit('OC_User', 'post_addToGroup', array('uid' => $user->getUID(), 'gid' => $group->getGID()));
315
+            });
316
+            return $groupManager;
317
+        });
318
+        $this->registerAlias('GroupManager', \OCP\IGroupManager::class);
319
+
320
+        $this->registerService(Store::class, function (Server $c) {
321
+            $session = $c->getSession();
322
+            if (\OC::$server->getSystemConfig()->getValue('installed', false)) {
323
+                $tokenProvider = $c->query('OC\Authentication\Token\IProvider');
324
+            } else {
325
+                $tokenProvider = null;
326
+            }
327
+            $logger = $c->getLogger();
328
+            return new Store($session, $logger, $tokenProvider);
329
+        });
330
+        $this->registerAlias(IStore::class, Store::class);
331
+        $this->registerService('OC\Authentication\Token\DefaultTokenMapper', function (Server $c) {
332
+            $dbConnection = $c->getDatabaseConnection();
333
+            return new Authentication\Token\DefaultTokenMapper($dbConnection);
334
+        });
335
+        $this->registerService('OC\Authentication\Token\DefaultTokenProvider', function (Server $c) {
336
+            $mapper = $c->query('OC\Authentication\Token\DefaultTokenMapper');
337
+            $crypto = $c->getCrypto();
338
+            $config = $c->getConfig();
339
+            $logger = $c->getLogger();
340
+            $timeFactory = new TimeFactory();
341
+            return new \OC\Authentication\Token\DefaultTokenProvider($mapper, $crypto, $config, $logger, $timeFactory);
342
+        });
343
+        $this->registerAlias('OC\Authentication\Token\IProvider', 'OC\Authentication\Token\DefaultTokenProvider');
344
+
345
+        $this->registerService(\OCP\IUserSession::class, function (Server $c) {
346
+            $manager = $c->getUserManager();
347
+            $session = new \OC\Session\Memory('');
348
+            $timeFactory = new TimeFactory();
349
+            // Token providers might require a working database. This code
350
+            // might however be called when ownCloud is not yet setup.
351
+            if (\OC::$server->getSystemConfig()->getValue('installed', false)) {
352
+                $defaultTokenProvider = $c->query('OC\Authentication\Token\IProvider');
353
+            } else {
354
+                $defaultTokenProvider = null;
355
+            }
356
+
357
+            $dispatcher = $c->getEventDispatcher();
358
+
359
+            $userSession = new \OC\User\Session(
360
+                $manager,
361
+                $session,
362
+                $timeFactory,
363
+                $defaultTokenProvider,
364
+                $c->getConfig(),
365
+                $c->getSecureRandom(),
366
+                $c->getLockdownManager(),
367
+                $c->getLogger()
368
+            );
369
+            $userSession->listen('\OC\User', 'preCreateUser', function ($uid, $password) {
370
+                \OC_Hook::emit('OC_User', 'pre_createUser', array('run' => true, 'uid' => $uid, 'password' => $password));
371
+            });
372
+            $userSession->listen('\OC\User', 'postCreateUser', function ($user, $password) {
373
+                /** @var $user \OC\User\User */
374
+                \OC_Hook::emit('OC_User', 'post_createUser', array('uid' => $user->getUID(), 'password' => $password));
375
+            });
376
+            $userSession->listen('\OC\User', 'preDelete', function ($user) use ($dispatcher) {
377
+                /** @var $user \OC\User\User */
378
+                \OC_Hook::emit('OC_User', 'pre_deleteUser', array('run' => true, 'uid' => $user->getUID()));
379
+                $dispatcher->dispatch('OCP\IUser::preDelete', new GenericEvent($user));
380
+            });
381
+            $userSession->listen('\OC\User', 'postDelete', function ($user) {
382
+                /** @var $user \OC\User\User */
383
+                \OC_Hook::emit('OC_User', 'post_deleteUser', array('uid' => $user->getUID()));
384
+            });
385
+            $userSession->listen('\OC\User', 'preSetPassword', function ($user, $password, $recoveryPassword) {
386
+                /** @var $user \OC\User\User */
387
+                \OC_Hook::emit('OC_User', 'pre_setPassword', array('run' => true, 'uid' => $user->getUID(), 'password' => $password, 'recoveryPassword' => $recoveryPassword));
388
+            });
389
+            $userSession->listen('\OC\User', 'postSetPassword', function ($user, $password, $recoveryPassword) {
390
+                /** @var $user \OC\User\User */
391
+                \OC_Hook::emit('OC_User', 'post_setPassword', array('run' => true, 'uid' => $user->getUID(), 'password' => $password, 'recoveryPassword' => $recoveryPassword));
392
+            });
393
+            $userSession->listen('\OC\User', 'preLogin', function ($uid, $password) {
394
+                \OC_Hook::emit('OC_User', 'pre_login', array('run' => true, 'uid' => $uid, 'password' => $password));
395
+            });
396
+            $userSession->listen('\OC\User', 'postLogin', function ($user, $password) {
397
+                /** @var $user \OC\User\User */
398
+                \OC_Hook::emit('OC_User', 'post_login', array('run' => true, 'uid' => $user->getUID(), 'password' => $password));
399
+            });
400
+            $userSession->listen('\OC\User', 'postRememberedLogin', function ($user, $password) {
401
+                /** @var $user \OC\User\User */
402
+                \OC_Hook::emit('OC_User', 'post_login', array('run' => true, 'uid' => $user->getUID(), 'password' => $password));
403
+            });
404
+            $userSession->listen('\OC\User', 'logout', function () {
405
+                \OC_Hook::emit('OC_User', 'logout', array());
406
+            });
407
+            $userSession->listen('\OC\User', 'changeUser', function ($user, $feature, $value, $oldValue) use ($dispatcher) {
408
+                /** @var $user \OC\User\User */
409
+                \OC_Hook::emit('OC_User', 'changeUser', array('run' => true, 'user' => $user, 'feature' => $feature, 'value' => $value, 'old_value' => $oldValue));
410
+                $dispatcher->dispatch('OCP\IUser::changeUser', new GenericEvent($user, ['feature' => $feature, 'oldValue' => $oldValue, 'value' => $value]));
411
+            });
412
+            return $userSession;
413
+        });
414
+        $this->registerAlias('UserSession', \OCP\IUserSession::class);
415
+
416
+        $this->registerService(\OC\Authentication\TwoFactorAuth\Manager::class, function (Server $c) {
417
+            return new \OC\Authentication\TwoFactorAuth\Manager(
418
+                $c->getAppManager(),
419
+                $c->getSession(),
420
+                $c->getConfig(),
421
+                $c->getActivityManager(),
422
+                $c->getLogger(),
423
+                $c->query(\OC\Authentication\Token\IProvider::class),
424
+                $c->query(ITimeFactory::class)
425
+            );
426
+        });
427
+
428
+        $this->registerAlias(\OCP\INavigationManager::class, \OC\NavigationManager::class);
429
+        $this->registerAlias('NavigationManager', \OCP\INavigationManager::class);
430
+
431
+        $this->registerService(\OC\AllConfig::class, function (Server $c) {
432
+            return new \OC\AllConfig(
433
+                $c->getSystemConfig()
434
+            );
435
+        });
436
+        $this->registerAlias('AllConfig', \OC\AllConfig::class);
437
+        $this->registerAlias(\OCP\IConfig::class, \OC\AllConfig::class);
438
+
439
+        $this->registerService('SystemConfig', function ($c) use ($config) {
440
+            return new \OC\SystemConfig($config);
441
+        });
442
+
443
+        $this->registerService(\OC\AppConfig::class, function (Server $c) {
444
+            return new \OC\AppConfig($c->getDatabaseConnection());
445
+        });
446
+        $this->registerAlias('AppConfig', \OC\AppConfig::class);
447
+        $this->registerAlias(\OCP\IAppConfig::class, \OC\AppConfig::class);
448
+
449
+        $this->registerService(\OCP\L10N\IFactory::class, function (Server $c) {
450
+            return new \OC\L10N\Factory(
451
+                $c->getConfig(),
452
+                $c->getRequest(),
453
+                $c->getUserSession(),
454
+                \OC::$SERVERROOT
455
+            );
456
+        });
457
+        $this->registerAlias('L10NFactory', \OCP\L10N\IFactory::class);
458
+
459
+        $this->registerService(\OCP\IURLGenerator::class, function (Server $c) {
460
+            $config = $c->getConfig();
461
+            $cacheFactory = $c->getMemCacheFactory();
462
+            $request = $c->getRequest();
463
+            return new \OC\URLGenerator(
464
+                $config,
465
+                $cacheFactory,
466
+                $request
467
+            );
468
+        });
469
+        $this->registerAlias('URLGenerator', \OCP\IURLGenerator::class);
470
+
471
+        $this->registerService('AppHelper', function ($c) {
472
+            return new \OC\AppHelper();
473
+        });
474
+        $this->registerAlias('AppFetcher', AppFetcher::class);
475
+        $this->registerAlias('CategoryFetcher', CategoryFetcher::class);
476
+
477
+        $this->registerService(\OCP\ICache::class, function ($c) {
478
+            return new Cache\File();
479
+        });
480
+        $this->registerAlias('UserCache', \OCP\ICache::class);
481
+
482
+        $this->registerService(Factory::class, function (Server $c) {
483
+
484
+            $arrayCacheFactory = new \OC\Memcache\Factory('', $c->getLogger(),
485
+                '\\OC\\Memcache\\ArrayCache',
486
+                '\\OC\\Memcache\\ArrayCache',
487
+                '\\OC\\Memcache\\ArrayCache'
488
+            );
489
+            $config = $c->getConfig();
490
+            $request = $c->getRequest();
491
+            $urlGenerator = new URLGenerator($config, $arrayCacheFactory, $request);
492
+
493
+            if ($config->getSystemValue('installed', false) && !(defined('PHPUNIT_RUN') && PHPUNIT_RUN)) {
494
+                $v = \OC_App::getAppVersions();
495
+                $v['core'] = implode(',', \OC_Util::getVersion());
496
+                $version = implode(',', $v);
497
+                $instanceId = \OC_Util::getInstanceId();
498
+                $path = \OC::$SERVERROOT;
499
+                $prefix = md5($instanceId . '-' . $version . '-' . $path);
500
+                return new \OC\Memcache\Factory($prefix, $c->getLogger(),
501
+                    $config->getSystemValue('memcache.local', null),
502
+                    $config->getSystemValue('memcache.distributed', null),
503
+                    $config->getSystemValue('memcache.locking', null)
504
+                );
505
+            }
506
+            return $arrayCacheFactory;
507
+
508
+        });
509
+        $this->registerAlias('MemCacheFactory', Factory::class);
510
+        $this->registerAlias(ICacheFactory::class, Factory::class);
511
+
512
+        $this->registerService('RedisFactory', function (Server $c) {
513
+            $systemConfig = $c->getSystemConfig();
514
+            return new RedisFactory($systemConfig);
515
+        });
516
+
517
+        $this->registerService(\OCP\Activity\IManager::class, function (Server $c) {
518
+            return new \OC\Activity\Manager(
519
+                $c->getRequest(),
520
+                $c->getUserSession(),
521
+                $c->getConfig(),
522
+                $c->query(IValidator::class)
523
+            );
524
+        });
525
+        $this->registerAlias('ActivityManager', \OCP\Activity\IManager::class);
526
+
527
+        $this->registerService(\OCP\Activity\IEventMerger::class, function (Server $c) {
528
+            return new \OC\Activity\EventMerger(
529
+                $c->getL10N('lib')
530
+            );
531
+        });
532
+        $this->registerAlias(IValidator::class, Validator::class);
533
+
534
+        $this->registerService(\OCP\IAvatarManager::class, function (Server $c) {
535
+            return new AvatarManager(
536
+                $c->getUserManager(),
537
+                $c->getAppDataDir('avatar'),
538
+                $c->getL10N('lib'),
539
+                $c->getLogger(),
540
+                $c->getConfig()
541
+            );
542
+        });
543
+        $this->registerAlias('AvatarManager', \OCP\IAvatarManager::class);
544
+
545
+        $this->registerAlias(\OCP\Support\CrashReport\IRegistry::class, \OC\Support\CrashReport\Registry::class);
546
+
547
+        $this->registerService(\OCP\ILogger::class, function (Server $c) {
548
+            $logType = $c->query('AllConfig')->getSystemValue('log_type', 'file');
549
+            $logger = Log::getLogClass($logType);
550
+            call_user_func(array($logger, 'init'));
551
+            $config = $this->getSystemConfig();
552
+            $registry = $c->query(\OCP\Support\CrashReport\IRegistry::class);
553
+
554
+            return new Log($logger, $config, null, $registry);
555
+        });
556
+        $this->registerAlias('Logger', \OCP\ILogger::class);
557
+
558
+        $this->registerService(\OCP\BackgroundJob\IJobList::class, function (Server $c) {
559
+            $config = $c->getConfig();
560
+            return new \OC\BackgroundJob\JobList(
561
+                $c->getDatabaseConnection(),
562
+                $config,
563
+                new TimeFactory()
564
+            );
565
+        });
566
+        $this->registerAlias('JobList', \OCP\BackgroundJob\IJobList::class);
567
+
568
+        $this->registerService(\OCP\Route\IRouter::class, function (Server $c) {
569
+            $cacheFactory = $c->getMemCacheFactory();
570
+            $logger = $c->getLogger();
571
+            if ($cacheFactory->isAvailableLowLatency()) {
572
+                $router = new \OC\Route\CachingRouter($cacheFactory->createLocal('route'), $logger);
573
+            } else {
574
+                $router = new \OC\Route\Router($logger);
575
+            }
576
+            return $router;
577
+        });
578
+        $this->registerAlias('Router', \OCP\Route\IRouter::class);
579
+
580
+        $this->registerService(\OCP\ISearch::class, function ($c) {
581
+            return new Search();
582
+        });
583
+        $this->registerAlias('Search', \OCP\ISearch::class);
584
+
585
+        $this->registerService(\OC\Security\RateLimiting\Limiter::class, function ($c) {
586
+            return new \OC\Security\RateLimiting\Limiter(
587
+                $this->getUserSession(),
588
+                $this->getRequest(),
589
+                new \OC\AppFramework\Utility\TimeFactory(),
590
+                $c->query(\OC\Security\RateLimiting\Backend\IBackend::class)
591
+            );
592
+        });
593
+        $this->registerService(\OC\Security\RateLimiting\Backend\IBackend::class, function ($c) {
594
+            return new \OC\Security\RateLimiting\Backend\MemoryCache(
595
+                $this->getMemCacheFactory(),
596
+                new \OC\AppFramework\Utility\TimeFactory()
597
+            );
598
+        });
599
+
600
+        $this->registerService(\OCP\Security\ISecureRandom::class, function ($c) {
601
+            return new SecureRandom();
602
+        });
603
+        $this->registerAlias('SecureRandom', \OCP\Security\ISecureRandom::class);
604
+
605
+        $this->registerService(\OCP\Security\ICrypto::class, function (Server $c) {
606
+            return new Crypto($c->getConfig(), $c->getSecureRandom());
607
+        });
608
+        $this->registerAlias('Crypto', \OCP\Security\ICrypto::class);
609
+
610
+        $this->registerService(\OCP\Security\IHasher::class, function (Server $c) {
611
+            return new Hasher($c->getConfig());
612
+        });
613
+        $this->registerAlias('Hasher', \OCP\Security\IHasher::class);
614
+
615
+        $this->registerService(\OCP\Security\ICredentialsManager::class, function (Server $c) {
616
+            return new CredentialsManager($c->getCrypto(), $c->getDatabaseConnection());
617
+        });
618
+        $this->registerAlias('CredentialsManager', \OCP\Security\ICredentialsManager::class);
619
+
620
+        $this->registerService(IDBConnection::class, function (Server $c) {
621
+            $systemConfig = $c->getSystemConfig();
622
+            $factory = new \OC\DB\ConnectionFactory($systemConfig);
623
+            $type = $systemConfig->getValue('dbtype', 'sqlite');
624
+            if (!$factory->isValidType($type)) {
625
+                throw new \OC\DatabaseException('Invalid database type');
626
+            }
627
+            $connectionParams = $factory->createConnectionParams();
628
+            $connection = $factory->getConnection($type, $connectionParams);
629
+            $connection->getConfiguration()->setSQLLogger($c->getQueryLogger());
630
+            return $connection;
631
+        });
632
+        $this->registerAlias('DatabaseConnection', IDBConnection::class);
633
+
634
+        $this->registerService('HTTPHelper', function (Server $c) {
635
+            $config = $c->getConfig();
636
+            return new HTTPHelper(
637
+                $config,
638
+                $c->getHTTPClientService()
639
+            );
640
+        });
641
+
642
+        $this->registerService(\OCP\Http\Client\IClientService::class, function (Server $c) {
643
+            $user = \OC_User::getUser();
644
+            $uid = $user ? $user : null;
645
+            return new ClientService(
646
+                $c->getConfig(),
647
+                new \OC\Security\CertificateManager(
648
+                    $uid,
649
+                    new View(),
650
+                    $c->getConfig(),
651
+                    $c->getLogger(),
652
+                    $c->getSecureRandom()
653
+                )
654
+            );
655
+        });
656
+        $this->registerAlias('HttpClientService', \OCP\Http\Client\IClientService::class);
657
+        $this->registerService(\OCP\Diagnostics\IEventLogger::class, function (Server $c) {
658
+            $eventLogger = new EventLogger();
659
+            if ($c->getSystemConfig()->getValue('debug', false)) {
660
+                // In debug mode, module is being activated by default
661
+                $eventLogger->activate();
662
+            }
663
+            return $eventLogger;
664
+        });
665
+        $this->registerAlias('EventLogger', \OCP\Diagnostics\IEventLogger::class);
666
+
667
+        $this->registerService(\OCP\Diagnostics\IQueryLogger::class, function (Server $c) {
668
+            $queryLogger = new QueryLogger();
669
+            if ($c->getSystemConfig()->getValue('debug', false)) {
670
+                // In debug mode, module is being activated by default
671
+                $queryLogger->activate();
672
+            }
673
+            return $queryLogger;
674
+        });
675
+        $this->registerAlias('QueryLogger', \OCP\Diagnostics\IQueryLogger::class);
676
+
677
+        $this->registerService(TempManager::class, function (Server $c) {
678
+            return new TempManager(
679
+                $c->getLogger(),
680
+                $c->getConfig()
681
+            );
682
+        });
683
+        $this->registerAlias('TempManager', TempManager::class);
684
+        $this->registerAlias(ITempManager::class, TempManager::class);
685
+
686
+        $this->registerService(AppManager::class, function (Server $c) {
687
+            return new \OC\App\AppManager(
688
+                $c->getUserSession(),
689
+                $c->getAppConfig(),
690
+                $c->getGroupManager(),
691
+                $c->getMemCacheFactory(),
692
+                $c->getEventDispatcher()
693
+            );
694
+        });
695
+        $this->registerAlias('AppManager', AppManager::class);
696
+        $this->registerAlias(IAppManager::class, AppManager::class);
697
+
698
+        $this->registerService(\OCP\IDateTimeZone::class, function (Server $c) {
699
+            return new DateTimeZone(
700
+                $c->getConfig(),
701
+                $c->getSession()
702
+            );
703
+        });
704
+        $this->registerAlias('DateTimeZone', \OCP\IDateTimeZone::class);
705
+
706
+        $this->registerService(\OCP\IDateTimeFormatter::class, function (Server $c) {
707
+            $language = $c->getConfig()->getUserValue($c->getSession()->get('user_id'), 'core', 'lang', null);
708
+
709
+            return new DateTimeFormatter(
710
+                $c->getDateTimeZone()->getTimeZone(),
711
+                $c->getL10N('lib', $language)
712
+            );
713
+        });
714
+        $this->registerAlias('DateTimeFormatter', \OCP\IDateTimeFormatter::class);
715
+
716
+        $this->registerService(\OCP\Files\Config\IUserMountCache::class, function (Server $c) {
717
+            $mountCache = new UserMountCache($c->getDatabaseConnection(), $c->getUserManager(), $c->getLogger());
718
+            $listener = new UserMountCacheListener($mountCache);
719
+            $listener->listen($c->getUserManager());
720
+            return $mountCache;
721
+        });
722
+        $this->registerAlias('UserMountCache', \OCP\Files\Config\IUserMountCache::class);
723
+
724
+        $this->registerService(\OCP\Files\Config\IMountProviderCollection::class, function (Server $c) {
725
+            $loader = \OC\Files\Filesystem::getLoader();
726
+            $mountCache = $c->query('UserMountCache');
727
+            $manager = new \OC\Files\Config\MountProviderCollection($loader, $mountCache);
728
+
729
+            // builtin providers
730
+
731
+            $config = $c->getConfig();
732
+            $manager->registerProvider(new CacheMountProvider($config));
733
+            $manager->registerHomeProvider(new LocalHomeMountProvider());
734
+            $manager->registerHomeProvider(new ObjectHomeMountProvider($config));
735
+
736
+            return $manager;
737
+        });
738
+        $this->registerAlias('MountConfigManager', \OCP\Files\Config\IMountProviderCollection::class);
739
+
740
+        $this->registerService('IniWrapper', function ($c) {
741
+            return new IniGetWrapper();
742
+        });
743
+        $this->registerService('AsyncCommandBus', function (Server $c) {
744
+            $busClass = $c->getConfig()->getSystemValue('commandbus');
745
+            if ($busClass) {
746
+                list($app, $class) = explode('::', $busClass, 2);
747
+                if ($c->getAppManager()->isInstalled($app)) {
748
+                    \OC_App::loadApp($app);
749
+                    return $c->query($class);
750
+                } else {
751
+                    throw new ServiceUnavailableException("The app providing the command bus ($app) is not enabled");
752
+                }
753
+            } else {
754
+                $jobList = $c->getJobList();
755
+                return new CronBus($jobList);
756
+            }
757
+        });
758
+        $this->registerService('TrustedDomainHelper', function ($c) {
759
+            return new TrustedDomainHelper($this->getConfig());
760
+        });
761
+        $this->registerService(Throttler::class, function (Server $c) {
762
+            return new Throttler(
763
+                $c->getDatabaseConnection(),
764
+                new TimeFactory(),
765
+                $c->getLogger(),
766
+                $c->getConfig()
767
+            );
768
+        });
769
+        $this->registerAlias('Throttler', Throttler::class);
770
+        $this->registerService('IntegrityCodeChecker', function (Server $c) {
771
+            // IConfig and IAppManager requires a working database. This code
772
+            // might however be called when ownCloud is not yet setup.
773
+            if (\OC::$server->getSystemConfig()->getValue('installed', false)) {
774
+                $config = $c->getConfig();
775
+                $appManager = $c->getAppManager();
776
+            } else {
777
+                $config = null;
778
+                $appManager = null;
779
+            }
780
+
781
+            return new Checker(
782
+                new EnvironmentHelper(),
783
+                new FileAccessHelper(),
784
+                new AppLocator(),
785
+                $config,
786
+                $c->getMemCacheFactory(),
787
+                $appManager,
788
+                $c->getTempManager()
789
+            );
790
+        });
791
+        $this->registerService(\OCP\IRequest::class, function ($c) {
792
+            if (isset($this['urlParams'])) {
793
+                $urlParams = $this['urlParams'];
794
+            } else {
795
+                $urlParams = [];
796
+            }
797
+
798
+            if (defined('PHPUNIT_RUN') && PHPUNIT_RUN
799
+                && in_array('fakeinput', stream_get_wrappers())
800
+            ) {
801
+                $stream = 'fakeinput://data';
802
+            } else {
803
+                $stream = 'php://input';
804
+            }
805
+
806
+            return new Request(
807
+                [
808
+                    'get' => $_GET,
809
+                    'post' => $_POST,
810
+                    'files' => $_FILES,
811
+                    'server' => $_SERVER,
812
+                    'env' => $_ENV,
813
+                    'cookies' => $_COOKIE,
814
+                    'method' => (isset($_SERVER) && isset($_SERVER['REQUEST_METHOD']))
815
+                        ? $_SERVER['REQUEST_METHOD']
816
+                        : null,
817
+                    'urlParams' => $urlParams,
818
+                ],
819
+                $this->getSecureRandom(),
820
+                $this->getConfig(),
821
+                $this->getCsrfTokenManager(),
822
+                $stream
823
+            );
824
+        });
825
+        $this->registerAlias('Request', \OCP\IRequest::class);
826
+
827
+        $this->registerService(\OCP\Mail\IMailer::class, function (Server $c) {
828
+            return new Mailer(
829
+                $c->getConfig(),
830
+                $c->getLogger(),
831
+                $c->query(Defaults::class),
832
+                $c->getURLGenerator(),
833
+                $c->getL10N('lib')
834
+            );
835
+        });
836
+        $this->registerAlias('Mailer', \OCP\Mail\IMailer::class);
837
+
838
+        $this->registerService('LDAPProvider', function (Server $c) {
839
+            $config = $c->getConfig();
840
+            $factoryClass = $config->getSystemValue('ldapProviderFactory', null);
841
+            if (is_null($factoryClass)) {
842
+                throw new \Exception('ldapProviderFactory not set');
843
+            }
844
+            /** @var \OCP\LDAP\ILDAPProviderFactory $factory */
845
+            $factory = new $factoryClass($this);
846
+            return $factory->getLDAPProvider();
847
+        });
848
+        $this->registerService(ILockingProvider::class, function (Server $c) {
849
+            $ini = $c->getIniWrapper();
850
+            $config = $c->getConfig();
851
+            $ttl = $config->getSystemValue('filelocking.ttl', max(3600, $ini->getNumeric('max_execution_time')));
852
+            if ($config->getSystemValue('filelocking.enabled', true) or (defined('PHPUNIT_RUN') && PHPUNIT_RUN)) {
853
+                /** @var \OC\Memcache\Factory $memcacheFactory */
854
+                $memcacheFactory = $c->getMemCacheFactory();
855
+                $memcache = $memcacheFactory->createLocking('lock');
856
+                if (!($memcache instanceof \OC\Memcache\NullCache)) {
857
+                    return new MemcacheLockingProvider($memcache, $ttl);
858
+                }
859
+                return new DBLockingProvider($c->getDatabaseConnection(), $c->getLogger(), new TimeFactory(), $ttl);
860
+            }
861
+            return new NoopLockingProvider();
862
+        });
863
+        $this->registerAlias('LockingProvider', ILockingProvider::class);
864
+
865
+        $this->registerService(\OCP\Files\Mount\IMountManager::class, function () {
866
+            return new \OC\Files\Mount\Manager();
867
+        });
868
+        $this->registerAlias('MountManager', \OCP\Files\Mount\IMountManager::class);
869
+
870
+        $this->registerService(\OCP\Files\IMimeTypeDetector::class, function (Server $c) {
871
+            return new \OC\Files\Type\Detection(
872
+                $c->getURLGenerator(),
873
+                \OC::$configDir,
874
+                \OC::$SERVERROOT . '/resources/config/'
875
+            );
876
+        });
877
+        $this->registerAlias('MimeTypeDetector', \OCP\Files\IMimeTypeDetector::class);
878
+
879
+        $this->registerService(\OCP\Files\IMimeTypeLoader::class, function (Server $c) {
880
+            return new \OC\Files\Type\Loader(
881
+                $c->getDatabaseConnection()
882
+            );
883
+        });
884
+        $this->registerAlias('MimeTypeLoader', \OCP\Files\IMimeTypeLoader::class);
885
+        $this->registerService(BundleFetcher::class, function () {
886
+            return new BundleFetcher($this->getL10N('lib'));
887
+        });
888
+        $this->registerService(\OCP\Notification\IManager::class, function (Server $c) {
889
+            return new Manager(
890
+                $c->query(IValidator::class)
891
+            );
892
+        });
893
+        $this->registerAlias('NotificationManager', \OCP\Notification\IManager::class);
894
+
895
+        $this->registerService(\OC\CapabilitiesManager::class, function (Server $c) {
896
+            $manager = new \OC\CapabilitiesManager($c->getLogger());
897
+            $manager->registerCapability(function () use ($c) {
898
+                return new \OC\OCS\CoreCapabilities($c->getConfig());
899
+            });
900
+            $manager->registerCapability(function () use ($c) {
901
+                return $c->query(\OC\Security\Bruteforce\Capabilities::class);
902
+            });
903
+            return $manager;
904
+        });
905
+        $this->registerAlias('CapabilitiesManager', \OC\CapabilitiesManager::class);
906
+
907
+        $this->registerService(\OCP\Comments\ICommentsManager::class, function (Server $c) {
908
+            $config = $c->getConfig();
909
+            $factoryClass = $config->getSystemValue('comments.managerFactory', '\OC\Comments\ManagerFactory');
910
+            /** @var \OCP\Comments\ICommentsManagerFactory $factory */
911
+            $factory = new $factoryClass($this);
912
+            $manager = $factory->getManager();
913
+
914
+            $manager->registerDisplayNameResolver('user', function($id) use ($c) {
915
+                $manager = $c->getUserManager();
916
+                $user = $manager->get($id);
917
+                if(is_null($user)) {
918
+                    $l = $c->getL10N('core');
919
+                    $displayName = $l->t('Unknown user');
920
+                } else {
921
+                    $displayName = $user->getDisplayName();
922
+                }
923
+                return $displayName;
924
+            });
925
+
926
+            return $manager;
927
+        });
928
+        $this->registerAlias('CommentsManager', \OCP\Comments\ICommentsManager::class);
929
+
930
+        $this->registerService('ThemingDefaults', function (Server $c) {
931
+            /*
932 932
 			 * Dark magic for autoloader.
933 933
 			 * If we do a class_exists it will try to load the class which will
934 934
 			 * make composer cache the result. Resulting in errors when enabling
935 935
 			 * the theming app.
936 936
 			 */
937
-			$prefixes = \OC::$composerAutoloader->getPrefixesPsr4();
938
-			if (isset($prefixes['OCA\\Theming\\'])) {
939
-				$classExists = true;
940
-			} else {
941
-				$classExists = false;
942
-			}
943
-
944
-			if ($classExists && $c->getConfig()->getSystemValue('installed', false) && $c->getAppManager()->isInstalled('theming') && $c->getTrustedDomainHelper()->isTrustedDomain($c->getRequest()->getInsecureServerHost())) {
945
-				return new ThemingDefaults(
946
-					$c->getConfig(),
947
-					$c->getL10N('theming'),
948
-					$c->getURLGenerator(),
949
-					$c->getAppDataDir('theming'),
950
-					$c->getMemCacheFactory(),
951
-					new Util($c->getConfig(), $this->getAppManager(), $this->getAppDataDir('theming')),
952
-					$this->getAppManager()
953
-				);
954
-			}
955
-			return new \OC_Defaults();
956
-		});
957
-		$this->registerService(SCSSCacher::class, function (Server $c) {
958
-			/** @var Factory $cacheFactory */
959
-			$cacheFactory = $c->query(Factory::class);
960
-			return new SCSSCacher(
961
-				$c->getLogger(),
962
-				$c->query(\OC\Files\AppData\Factory::class),
963
-				$c->getURLGenerator(),
964
-				$c->getConfig(),
965
-				$c->getThemingDefaults(),
966
-				\OC::$SERVERROOT,
967
-				$this->getMemCacheFactory()
968
-			);
969
-		});
970
-		$this->registerService(JSCombiner::class, function (Server $c) {
971
-			/** @var Factory $cacheFactory */
972
-			$cacheFactory = $c->query(Factory::class);
973
-			return new JSCombiner(
974
-				$c->getAppDataDir('js'),
975
-				$c->getURLGenerator(),
976
-				$this->getMemCacheFactory(),
977
-				$c->getSystemConfig(),
978
-				$c->getLogger()
979
-			);
980
-		});
981
-		$this->registerService(EventDispatcher::class, function () {
982
-			return new EventDispatcher();
983
-		});
984
-		$this->registerAlias('EventDispatcher', EventDispatcher::class);
985
-		$this->registerAlias(EventDispatcherInterface::class, EventDispatcher::class);
986
-
987
-		$this->registerService('CryptoWrapper', function (Server $c) {
988
-			// FIXME: Instantiiated here due to cyclic dependency
989
-			$request = new Request(
990
-				[
991
-					'get' => $_GET,
992
-					'post' => $_POST,
993
-					'files' => $_FILES,
994
-					'server' => $_SERVER,
995
-					'env' => $_ENV,
996
-					'cookies' => $_COOKIE,
997
-					'method' => (isset($_SERVER) && isset($_SERVER['REQUEST_METHOD']))
998
-						? $_SERVER['REQUEST_METHOD']
999
-						: null,
1000
-				],
1001
-				$c->getSecureRandom(),
1002
-				$c->getConfig()
1003
-			);
1004
-
1005
-			return new CryptoWrapper(
1006
-				$c->getConfig(),
1007
-				$c->getCrypto(),
1008
-				$c->getSecureRandom(),
1009
-				$request
1010
-			);
1011
-		});
1012
-		$this->registerService('CsrfTokenManager', function (Server $c) {
1013
-			$tokenGenerator = new CsrfTokenGenerator($c->getSecureRandom());
1014
-
1015
-			return new CsrfTokenManager(
1016
-				$tokenGenerator,
1017
-				$c->query(SessionStorage::class)
1018
-			);
1019
-		});
1020
-		$this->registerService(SessionStorage::class, function (Server $c) {
1021
-			return new SessionStorage($c->getSession());
1022
-		});
1023
-		$this->registerService(\OCP\Security\IContentSecurityPolicyManager::class, function (Server $c) {
1024
-			return new ContentSecurityPolicyManager();
1025
-		});
1026
-		$this->registerAlias('ContentSecurityPolicyManager', \OCP\Security\IContentSecurityPolicyManager::class);
1027
-
1028
-		$this->registerService('ContentSecurityPolicyNonceManager', function (Server $c) {
1029
-			return new ContentSecurityPolicyNonceManager(
1030
-				$c->getCsrfTokenManager(),
1031
-				$c->getRequest()
1032
-			);
1033
-		});
1034
-
1035
-		$this->registerService(\OCP\Share\IManager::class, function (Server $c) {
1036
-			$config = $c->getConfig();
1037
-			$factoryClass = $config->getSystemValue('sharing.managerFactory', '\OC\Share20\ProviderFactory');
1038
-			/** @var \OCP\Share\IProviderFactory $factory */
1039
-			$factory = new $factoryClass($this);
1040
-
1041
-			$manager = new \OC\Share20\Manager(
1042
-				$c->getLogger(),
1043
-				$c->getConfig(),
1044
-				$c->getSecureRandom(),
1045
-				$c->getHasher(),
1046
-				$c->getMountManager(),
1047
-				$c->getGroupManager(),
1048
-				$c->getL10N('lib'),
1049
-				$c->getL10NFactory(),
1050
-				$factory,
1051
-				$c->getUserManager(),
1052
-				$c->getLazyRootFolder(),
1053
-				$c->getEventDispatcher(),
1054
-				$c->getMailer(),
1055
-				$c->getURLGenerator(),
1056
-				$c->getThemingDefaults()
1057
-			);
1058
-
1059
-			return $manager;
1060
-		});
1061
-		$this->registerAlias('ShareManager', \OCP\Share\IManager::class);
1062
-
1063
-		$this->registerService(\OCP\Collaboration\Collaborators\ISearch::class, function(Server $c) {
1064
-			$instance = new Collaboration\Collaborators\Search($c);
1065
-
1066
-			// register default plugins
1067
-			$instance->registerPlugin(['shareType' => 'SHARE_TYPE_USER', 'class' => UserPlugin::class]);
1068
-			$instance->registerPlugin(['shareType' => 'SHARE_TYPE_GROUP', 'class' => GroupPlugin::class]);
1069
-			$instance->registerPlugin(['shareType' => 'SHARE_TYPE_EMAIL', 'class' => MailPlugin::class]);
1070
-			$instance->registerPlugin(['shareType' => 'SHARE_TYPE_REMOTE', 'class' => RemotePlugin::class]);
1071
-
1072
-			return $instance;
1073
-		});
1074
-		$this->registerAlias('CollaboratorSearch', \OCP\Collaboration\Collaborators\ISearch::class);
1075
-
1076
-		$this->registerAlias(\OCP\Collaboration\AutoComplete\IManager::class, \OC\Collaboration\AutoComplete\Manager::class);
1077
-
1078
-		$this->registerService('SettingsManager', function (Server $c) {
1079
-			$manager = new \OC\Settings\Manager(
1080
-				$c->getLogger(),
1081
-				$c->getDatabaseConnection(),
1082
-				$c->getL10N('lib'),
1083
-				$c->getConfig(),
1084
-				$c->getEncryptionManager(),
1085
-				$c->getUserManager(),
1086
-				$c->getLockingProvider(),
1087
-				$c->getRequest(),
1088
-				new \OC\Settings\Mapper($c->getDatabaseConnection()),
1089
-				$c->getURLGenerator(),
1090
-				$c->query(AccountManager::class),
1091
-				$c->getGroupManager(),
1092
-				$c->getL10NFactory(),
1093
-				$c->getThemingDefaults(),
1094
-				$c->getAppManager()
1095
-			);
1096
-			return $manager;
1097
-		});
1098
-		$this->registerService(\OC\Files\AppData\Factory::class, function (Server $c) {
1099
-			return new \OC\Files\AppData\Factory(
1100
-				$c->getRootFolder(),
1101
-				$c->getSystemConfig()
1102
-			);
1103
-		});
1104
-
1105
-		$this->registerService('LockdownManager', function (Server $c) {
1106
-			return new LockdownManager(function () use ($c) {
1107
-				return $c->getSession();
1108
-			});
1109
-		});
1110
-
1111
-		$this->registerService(\OCP\OCS\IDiscoveryService::class, function (Server $c) {
1112
-			return new DiscoveryService($c->getMemCacheFactory(), $c->getHTTPClientService());
1113
-		});
1114
-
1115
-		$this->registerService(ICloudIdManager::class, function (Server $c) {
1116
-			return new CloudIdManager();
1117
-		});
1118
-
1119
-		$this->registerAlias(\OCP\AppFramework\Utility\IControllerMethodReflector::class, \OC\AppFramework\Utility\ControllerMethodReflector::class);
1120
-		$this->registerAlias('ControllerMethodReflector', \OCP\AppFramework\Utility\IControllerMethodReflector::class);
1121
-
1122
-		$this->registerAlias(\OCP\AppFramework\Utility\ITimeFactory::class, \OC\AppFramework\Utility\TimeFactory::class);
1123
-		$this->registerAlias('TimeFactory', \OCP\AppFramework\Utility\ITimeFactory::class);
1124
-
1125
-		$this->registerService(Defaults::class, function (Server $c) {
1126
-			return new Defaults(
1127
-				$c->getThemingDefaults()
1128
-			);
1129
-		});
1130
-		$this->registerAlias('Defaults', \OCP\Defaults::class);
1131
-
1132
-		$this->registerService(\OCP\ISession::class, function (SimpleContainer $c) {
1133
-			return $c->query(\OCP\IUserSession::class)->getSession();
1134
-		});
1135
-
1136
-		$this->registerService(IShareHelper::class, function (Server $c) {
1137
-			return new ShareHelper(
1138
-				$c->query(\OCP\Share\IManager::class)
1139
-			);
1140
-		});
1141
-
1142
-		$this->registerService(Installer::class, function(Server $c) {
1143
-			return new Installer(
1144
-				$c->getAppFetcher(),
1145
-				$c->getHTTPClientService(),
1146
-				$c->getTempManager(),
1147
-				$c->getLogger(),
1148
-				$c->getConfig()
1149
-			);
1150
-		});
1151
-
1152
-		$this->registerService(IApiFactory::class, function(Server $c) {
1153
-			return new ApiFactory($c->getHTTPClientService());
1154
-		});
1155
-
1156
-		$this->registerService(IInstanceFactory::class, function(Server $c) {
1157
-			$memcacheFactory = $c->getMemCacheFactory();
1158
-			return new InstanceFactory($memcacheFactory->createLocal('remoteinstance.'), $c->getHTTPClientService());
1159
-		});
1160
-
1161
-		$this->registerService(IContactsStore::class, function(Server $c) {
1162
-			return new ContactsStore(
1163
-				$c->getContactsManager(),
1164
-				$c->getConfig(),
1165
-				$c->getUserManager(),
1166
-				$c->getGroupManager()
1167
-			);
1168
-		});
1169
-		$this->registerAlias(IContactsStore::class, ContactsStore::class);
1170
-
1171
-		$this->connectDispatcher();
1172
-	}
1173
-
1174
-	/**
1175
-	 * @return \OCP\Calendar\IManager
1176
-	 */
1177
-	public function getCalendarManager() {
1178
-		return $this->query('CalendarManager');
1179
-	}
1180
-
1181
-	private function connectDispatcher() {
1182
-		$dispatcher = $this->getEventDispatcher();
1183
-
1184
-		// Delete avatar on user deletion
1185
-		$dispatcher->addListener('OCP\IUser::preDelete', function(GenericEvent $e) {
1186
-			$logger = $this->getLogger();
1187
-			$manager = $this->getAvatarManager();
1188
-			/** @var IUser $user */
1189
-			$user = $e->getSubject();
1190
-
1191
-			try {
1192
-				$avatar = $manager->getAvatar($user->getUID());
1193
-				$avatar->remove();
1194
-			} catch (NotFoundException $e) {
1195
-				// no avatar to remove
1196
-			} catch (\Exception $e) {
1197
-				// Ignore exceptions
1198
-				$logger->info('Could not cleanup avatar of ' . $user->getUID());
1199
-			}
1200
-		});
1201
-
1202
-		$dispatcher->addListener('OCP\IUser::changeUser', function (GenericEvent $e) {
1203
-			$manager = $this->getAvatarManager();
1204
-			/** @var IUser $user */
1205
-			$user = $e->getSubject();
1206
-			$feature = $e->getArgument('feature');
1207
-			$oldValue = $e->getArgument('oldValue');
1208
-			$value = $e->getArgument('value');
1209
-
1210
-			try {
1211
-				$avatar = $manager->getAvatar($user->getUID());
1212
-				$avatar->userChanged($feature, $oldValue, $value);
1213
-			} catch (NotFoundException $e) {
1214
-				// no avatar to remove
1215
-			}
1216
-		});
1217
-	}
1218
-
1219
-	/**
1220
-	 * @return \OCP\Contacts\IManager
1221
-	 */
1222
-	public function getContactsManager() {
1223
-		return $this->query('ContactsManager');
1224
-	}
1225
-
1226
-	/**
1227
-	 * @return \OC\Encryption\Manager
1228
-	 */
1229
-	public function getEncryptionManager() {
1230
-		return $this->query('EncryptionManager');
1231
-	}
1232
-
1233
-	/**
1234
-	 * @return \OC\Encryption\File
1235
-	 */
1236
-	public function getEncryptionFilesHelper() {
1237
-		return $this->query('EncryptionFileHelper');
1238
-	}
1239
-
1240
-	/**
1241
-	 * @return \OCP\Encryption\Keys\IStorage
1242
-	 */
1243
-	public function getEncryptionKeyStorage() {
1244
-		return $this->query('EncryptionKeyStorage');
1245
-	}
1246
-
1247
-	/**
1248
-	 * The current request object holding all information about the request
1249
-	 * currently being processed is returned from this method.
1250
-	 * In case the current execution was not initiated by a web request null is returned
1251
-	 *
1252
-	 * @return \OCP\IRequest
1253
-	 */
1254
-	public function getRequest() {
1255
-		return $this->query('Request');
1256
-	}
1257
-
1258
-	/**
1259
-	 * Returns the preview manager which can create preview images for a given file
1260
-	 *
1261
-	 * @return \OCP\IPreview
1262
-	 */
1263
-	public function getPreviewManager() {
1264
-		return $this->query('PreviewManager');
1265
-	}
1266
-
1267
-	/**
1268
-	 * Returns the tag manager which can get and set tags for different object types
1269
-	 *
1270
-	 * @see \OCP\ITagManager::load()
1271
-	 * @return \OCP\ITagManager
1272
-	 */
1273
-	public function getTagManager() {
1274
-		return $this->query('TagManager');
1275
-	}
1276
-
1277
-	/**
1278
-	 * Returns the system-tag manager
1279
-	 *
1280
-	 * @return \OCP\SystemTag\ISystemTagManager
1281
-	 *
1282
-	 * @since 9.0.0
1283
-	 */
1284
-	public function getSystemTagManager() {
1285
-		return $this->query('SystemTagManager');
1286
-	}
1287
-
1288
-	/**
1289
-	 * Returns the system-tag object mapper
1290
-	 *
1291
-	 * @return \OCP\SystemTag\ISystemTagObjectMapper
1292
-	 *
1293
-	 * @since 9.0.0
1294
-	 */
1295
-	public function getSystemTagObjectMapper() {
1296
-		return $this->query('SystemTagObjectMapper');
1297
-	}
1298
-
1299
-	/**
1300
-	 * Returns the avatar manager, used for avatar functionality
1301
-	 *
1302
-	 * @return \OCP\IAvatarManager
1303
-	 */
1304
-	public function getAvatarManager() {
1305
-		return $this->query('AvatarManager');
1306
-	}
1307
-
1308
-	/**
1309
-	 * Returns the root folder of ownCloud's data directory
1310
-	 *
1311
-	 * @return \OCP\Files\IRootFolder
1312
-	 */
1313
-	public function getRootFolder() {
1314
-		return $this->query('LazyRootFolder');
1315
-	}
1316
-
1317
-	/**
1318
-	 * Returns the root folder of ownCloud's data directory
1319
-	 * This is the lazy variant so this gets only initialized once it
1320
-	 * is actually used.
1321
-	 *
1322
-	 * @return \OCP\Files\IRootFolder
1323
-	 */
1324
-	public function getLazyRootFolder() {
1325
-		return $this->query('LazyRootFolder');
1326
-	}
1327
-
1328
-	/**
1329
-	 * Returns a view to ownCloud's files folder
1330
-	 *
1331
-	 * @param string $userId user ID
1332
-	 * @return \OCP\Files\Folder|null
1333
-	 */
1334
-	public function getUserFolder($userId = null) {
1335
-		if ($userId === null) {
1336
-			$user = $this->getUserSession()->getUser();
1337
-			if (!$user) {
1338
-				return null;
1339
-			}
1340
-			$userId = $user->getUID();
1341
-		}
1342
-		$root = $this->getRootFolder();
1343
-		return $root->getUserFolder($userId);
1344
-	}
1345
-
1346
-	/**
1347
-	 * Returns an app-specific view in ownClouds data directory
1348
-	 *
1349
-	 * @return \OCP\Files\Folder
1350
-	 * @deprecated since 9.2.0 use IAppData
1351
-	 */
1352
-	public function getAppFolder() {
1353
-		$dir = '/' . \OC_App::getCurrentApp();
1354
-		$root = $this->getRootFolder();
1355
-		if (!$root->nodeExists($dir)) {
1356
-			$folder = $root->newFolder($dir);
1357
-		} else {
1358
-			$folder = $root->get($dir);
1359
-		}
1360
-		return $folder;
1361
-	}
1362
-
1363
-	/**
1364
-	 * @return \OC\User\Manager
1365
-	 */
1366
-	public function getUserManager() {
1367
-		return $this->query('UserManager');
1368
-	}
1369
-
1370
-	/**
1371
-	 * @return \OC\Group\Manager
1372
-	 */
1373
-	public function getGroupManager() {
1374
-		return $this->query('GroupManager');
1375
-	}
1376
-
1377
-	/**
1378
-	 * @return \OC\User\Session
1379
-	 */
1380
-	public function getUserSession() {
1381
-		return $this->query('UserSession');
1382
-	}
1383
-
1384
-	/**
1385
-	 * @return \OCP\ISession
1386
-	 */
1387
-	public function getSession() {
1388
-		return $this->query('UserSession')->getSession();
1389
-	}
1390
-
1391
-	/**
1392
-	 * @param \OCP\ISession $session
1393
-	 */
1394
-	public function setSession(\OCP\ISession $session) {
1395
-		$this->query(SessionStorage::class)->setSession($session);
1396
-		$this->query('UserSession')->setSession($session);
1397
-		$this->query(Store::class)->setSession($session);
1398
-	}
1399
-
1400
-	/**
1401
-	 * @return \OC\Authentication\TwoFactorAuth\Manager
1402
-	 */
1403
-	public function getTwoFactorAuthManager() {
1404
-		return $this->query('\OC\Authentication\TwoFactorAuth\Manager');
1405
-	}
1406
-
1407
-	/**
1408
-	 * @return \OC\NavigationManager
1409
-	 */
1410
-	public function getNavigationManager() {
1411
-		return $this->query('NavigationManager');
1412
-	}
1413
-
1414
-	/**
1415
-	 * @return \OCP\IConfig
1416
-	 */
1417
-	public function getConfig() {
1418
-		return $this->query('AllConfig');
1419
-	}
1420
-
1421
-	/**
1422
-	 * @return \OC\SystemConfig
1423
-	 */
1424
-	public function getSystemConfig() {
1425
-		return $this->query('SystemConfig');
1426
-	}
1427
-
1428
-	/**
1429
-	 * Returns the app config manager
1430
-	 *
1431
-	 * @return \OCP\IAppConfig
1432
-	 */
1433
-	public function getAppConfig() {
1434
-		return $this->query('AppConfig');
1435
-	}
1436
-
1437
-	/**
1438
-	 * @return \OCP\L10N\IFactory
1439
-	 */
1440
-	public function getL10NFactory() {
1441
-		return $this->query('L10NFactory');
1442
-	}
1443
-
1444
-	/**
1445
-	 * get an L10N instance
1446
-	 *
1447
-	 * @param string $app appid
1448
-	 * @param string $lang
1449
-	 * @return IL10N
1450
-	 */
1451
-	public function getL10N($app, $lang = null) {
1452
-		return $this->getL10NFactory()->get($app, $lang);
1453
-	}
1454
-
1455
-	/**
1456
-	 * @return \OCP\IURLGenerator
1457
-	 */
1458
-	public function getURLGenerator() {
1459
-		return $this->query('URLGenerator');
1460
-	}
1461
-
1462
-	/**
1463
-	 * @return \OCP\IHelper
1464
-	 */
1465
-	public function getHelper() {
1466
-		return $this->query('AppHelper');
1467
-	}
1468
-
1469
-	/**
1470
-	 * @return AppFetcher
1471
-	 */
1472
-	public function getAppFetcher() {
1473
-		return $this->query(AppFetcher::class);
1474
-	}
1475
-
1476
-	/**
1477
-	 * Returns an ICache instance. Since 8.1.0 it returns a fake cache. Use
1478
-	 * getMemCacheFactory() instead.
1479
-	 *
1480
-	 * @return \OCP\ICache
1481
-	 * @deprecated 8.1.0 use getMemCacheFactory to obtain a proper cache
1482
-	 */
1483
-	public function getCache() {
1484
-		return $this->query('UserCache');
1485
-	}
1486
-
1487
-	/**
1488
-	 * Returns an \OCP\CacheFactory instance
1489
-	 *
1490
-	 * @return \OCP\ICacheFactory
1491
-	 */
1492
-	public function getMemCacheFactory() {
1493
-		return $this->query('MemCacheFactory');
1494
-	}
1495
-
1496
-	/**
1497
-	 * Returns an \OC\RedisFactory instance
1498
-	 *
1499
-	 * @return \OC\RedisFactory
1500
-	 */
1501
-	public function getGetRedisFactory() {
1502
-		return $this->query('RedisFactory');
1503
-	}
1504
-
1505
-
1506
-	/**
1507
-	 * Returns the current session
1508
-	 *
1509
-	 * @return \OCP\IDBConnection
1510
-	 */
1511
-	public function getDatabaseConnection() {
1512
-		return $this->query('DatabaseConnection');
1513
-	}
1514
-
1515
-	/**
1516
-	 * Returns the activity manager
1517
-	 *
1518
-	 * @return \OCP\Activity\IManager
1519
-	 */
1520
-	public function getActivityManager() {
1521
-		return $this->query('ActivityManager');
1522
-	}
1523
-
1524
-	/**
1525
-	 * Returns an job list for controlling background jobs
1526
-	 *
1527
-	 * @return \OCP\BackgroundJob\IJobList
1528
-	 */
1529
-	public function getJobList() {
1530
-		return $this->query('JobList');
1531
-	}
1532
-
1533
-	/**
1534
-	 * Returns a logger instance
1535
-	 *
1536
-	 * @return \OCP\ILogger
1537
-	 */
1538
-	public function getLogger() {
1539
-		return $this->query('Logger');
1540
-	}
1541
-
1542
-	/**
1543
-	 * Returns a router for generating and matching urls
1544
-	 *
1545
-	 * @return \OCP\Route\IRouter
1546
-	 */
1547
-	public function getRouter() {
1548
-		return $this->query('Router');
1549
-	}
1550
-
1551
-	/**
1552
-	 * Returns a search instance
1553
-	 *
1554
-	 * @return \OCP\ISearch
1555
-	 */
1556
-	public function getSearch() {
1557
-		return $this->query('Search');
1558
-	}
1559
-
1560
-	/**
1561
-	 * Returns a SecureRandom instance
1562
-	 *
1563
-	 * @return \OCP\Security\ISecureRandom
1564
-	 */
1565
-	public function getSecureRandom() {
1566
-		return $this->query('SecureRandom');
1567
-	}
1568
-
1569
-	/**
1570
-	 * Returns a Crypto instance
1571
-	 *
1572
-	 * @return \OCP\Security\ICrypto
1573
-	 */
1574
-	public function getCrypto() {
1575
-		return $this->query('Crypto');
1576
-	}
1577
-
1578
-	/**
1579
-	 * Returns a Hasher instance
1580
-	 *
1581
-	 * @return \OCP\Security\IHasher
1582
-	 */
1583
-	public function getHasher() {
1584
-		return $this->query('Hasher');
1585
-	}
1586
-
1587
-	/**
1588
-	 * Returns a CredentialsManager instance
1589
-	 *
1590
-	 * @return \OCP\Security\ICredentialsManager
1591
-	 */
1592
-	public function getCredentialsManager() {
1593
-		return $this->query('CredentialsManager');
1594
-	}
1595
-
1596
-	/**
1597
-	 * Returns an instance of the HTTP helper class
1598
-	 *
1599
-	 * @deprecated Use getHTTPClientService()
1600
-	 * @return \OC\HTTPHelper
1601
-	 */
1602
-	public function getHTTPHelper() {
1603
-		return $this->query('HTTPHelper');
1604
-	}
1605
-
1606
-	/**
1607
-	 * Get the certificate manager for the user
1608
-	 *
1609
-	 * @param string $userId (optional) if not specified the current loggedin user is used, use null to get the system certificate manager
1610
-	 * @return \OCP\ICertificateManager | null if $uid is null and no user is logged in
1611
-	 */
1612
-	public function getCertificateManager($userId = '') {
1613
-		if ($userId === '') {
1614
-			$userSession = $this->getUserSession();
1615
-			$user = $userSession->getUser();
1616
-			if (is_null($user)) {
1617
-				return null;
1618
-			}
1619
-			$userId = $user->getUID();
1620
-		}
1621
-		return new CertificateManager(
1622
-			$userId,
1623
-			new View(),
1624
-			$this->getConfig(),
1625
-			$this->getLogger(),
1626
-			$this->getSecureRandom()
1627
-		);
1628
-	}
1629
-
1630
-	/**
1631
-	 * Returns an instance of the HTTP client service
1632
-	 *
1633
-	 * @return \OCP\Http\Client\IClientService
1634
-	 */
1635
-	public function getHTTPClientService() {
1636
-		return $this->query('HttpClientService');
1637
-	}
1638
-
1639
-	/**
1640
-	 * Create a new event source
1641
-	 *
1642
-	 * @return \OCP\IEventSource
1643
-	 */
1644
-	public function createEventSource() {
1645
-		return new \OC_EventSource();
1646
-	}
1647
-
1648
-	/**
1649
-	 * Get the active event logger
1650
-	 *
1651
-	 * The returned logger only logs data when debug mode is enabled
1652
-	 *
1653
-	 * @return \OCP\Diagnostics\IEventLogger
1654
-	 */
1655
-	public function getEventLogger() {
1656
-		return $this->query('EventLogger');
1657
-	}
1658
-
1659
-	/**
1660
-	 * Get the active query logger
1661
-	 *
1662
-	 * The returned logger only logs data when debug mode is enabled
1663
-	 *
1664
-	 * @return \OCP\Diagnostics\IQueryLogger
1665
-	 */
1666
-	public function getQueryLogger() {
1667
-		return $this->query('QueryLogger');
1668
-	}
1669
-
1670
-	/**
1671
-	 * Get the manager for temporary files and folders
1672
-	 *
1673
-	 * @return \OCP\ITempManager
1674
-	 */
1675
-	public function getTempManager() {
1676
-		return $this->query('TempManager');
1677
-	}
1678
-
1679
-	/**
1680
-	 * Get the app manager
1681
-	 *
1682
-	 * @return \OCP\App\IAppManager
1683
-	 */
1684
-	public function getAppManager() {
1685
-		return $this->query('AppManager');
1686
-	}
1687
-
1688
-	/**
1689
-	 * Creates a new mailer
1690
-	 *
1691
-	 * @return \OCP\Mail\IMailer
1692
-	 */
1693
-	public function getMailer() {
1694
-		return $this->query('Mailer');
1695
-	}
1696
-
1697
-	/**
1698
-	 * Get the webroot
1699
-	 *
1700
-	 * @return string
1701
-	 */
1702
-	public function getWebRoot() {
1703
-		return $this->webRoot;
1704
-	}
1705
-
1706
-	/**
1707
-	 * @return \OC\OCSClient
1708
-	 */
1709
-	public function getOcsClient() {
1710
-		return $this->query('OcsClient');
1711
-	}
1712
-
1713
-	/**
1714
-	 * @return \OCP\IDateTimeZone
1715
-	 */
1716
-	public function getDateTimeZone() {
1717
-		return $this->query('DateTimeZone');
1718
-	}
1719
-
1720
-	/**
1721
-	 * @return \OCP\IDateTimeFormatter
1722
-	 */
1723
-	public function getDateTimeFormatter() {
1724
-		return $this->query('DateTimeFormatter');
1725
-	}
1726
-
1727
-	/**
1728
-	 * @return \OCP\Files\Config\IMountProviderCollection
1729
-	 */
1730
-	public function getMountProviderCollection() {
1731
-		return $this->query('MountConfigManager');
1732
-	}
1733
-
1734
-	/**
1735
-	 * Get the IniWrapper
1736
-	 *
1737
-	 * @return IniGetWrapper
1738
-	 */
1739
-	public function getIniWrapper() {
1740
-		return $this->query('IniWrapper');
1741
-	}
1742
-
1743
-	/**
1744
-	 * @return \OCP\Command\IBus
1745
-	 */
1746
-	public function getCommandBus() {
1747
-		return $this->query('AsyncCommandBus');
1748
-	}
1749
-
1750
-	/**
1751
-	 * Get the trusted domain helper
1752
-	 *
1753
-	 * @return TrustedDomainHelper
1754
-	 */
1755
-	public function getTrustedDomainHelper() {
1756
-		return $this->query('TrustedDomainHelper');
1757
-	}
1758
-
1759
-	/**
1760
-	 * Get the locking provider
1761
-	 *
1762
-	 * @return \OCP\Lock\ILockingProvider
1763
-	 * @since 8.1.0
1764
-	 */
1765
-	public function getLockingProvider() {
1766
-		return $this->query('LockingProvider');
1767
-	}
1768
-
1769
-	/**
1770
-	 * @return \OCP\Files\Mount\IMountManager
1771
-	 **/
1772
-	function getMountManager() {
1773
-		return $this->query('MountManager');
1774
-	}
1775
-
1776
-	/** @return \OCP\Files\Config\IUserMountCache */
1777
-	function getUserMountCache() {
1778
-		return $this->query('UserMountCache');
1779
-	}
1780
-
1781
-	/**
1782
-	 * Get the MimeTypeDetector
1783
-	 *
1784
-	 * @return \OCP\Files\IMimeTypeDetector
1785
-	 */
1786
-	public function getMimeTypeDetector() {
1787
-		return $this->query('MimeTypeDetector');
1788
-	}
1789
-
1790
-	/**
1791
-	 * Get the MimeTypeLoader
1792
-	 *
1793
-	 * @return \OCP\Files\IMimeTypeLoader
1794
-	 */
1795
-	public function getMimeTypeLoader() {
1796
-		return $this->query('MimeTypeLoader');
1797
-	}
1798
-
1799
-	/**
1800
-	 * Get the manager of all the capabilities
1801
-	 *
1802
-	 * @return \OC\CapabilitiesManager
1803
-	 */
1804
-	public function getCapabilitiesManager() {
1805
-		return $this->query('CapabilitiesManager');
1806
-	}
1807
-
1808
-	/**
1809
-	 * Get the EventDispatcher
1810
-	 *
1811
-	 * @return EventDispatcherInterface
1812
-	 * @since 8.2.0
1813
-	 */
1814
-	public function getEventDispatcher() {
1815
-		return $this->query('EventDispatcher');
1816
-	}
1817
-
1818
-	/**
1819
-	 * Get the Notification Manager
1820
-	 *
1821
-	 * @return \OCP\Notification\IManager
1822
-	 * @since 8.2.0
1823
-	 */
1824
-	public function getNotificationManager() {
1825
-		return $this->query('NotificationManager');
1826
-	}
1827
-
1828
-	/**
1829
-	 * @return \OCP\Comments\ICommentsManager
1830
-	 */
1831
-	public function getCommentsManager() {
1832
-		return $this->query('CommentsManager');
1833
-	}
1834
-
1835
-	/**
1836
-	 * @return \OCA\Theming\ThemingDefaults
1837
-	 */
1838
-	public function getThemingDefaults() {
1839
-		return $this->query('ThemingDefaults');
1840
-	}
1841
-
1842
-	/**
1843
-	 * @return \OC\IntegrityCheck\Checker
1844
-	 */
1845
-	public function getIntegrityCodeChecker() {
1846
-		return $this->query('IntegrityCodeChecker');
1847
-	}
1848
-
1849
-	/**
1850
-	 * @return \OC\Session\CryptoWrapper
1851
-	 */
1852
-	public function getSessionCryptoWrapper() {
1853
-		return $this->query('CryptoWrapper');
1854
-	}
1855
-
1856
-	/**
1857
-	 * @return CsrfTokenManager
1858
-	 */
1859
-	public function getCsrfTokenManager() {
1860
-		return $this->query('CsrfTokenManager');
1861
-	}
1862
-
1863
-	/**
1864
-	 * @return Throttler
1865
-	 */
1866
-	public function getBruteForceThrottler() {
1867
-		return $this->query('Throttler');
1868
-	}
1869
-
1870
-	/**
1871
-	 * @return IContentSecurityPolicyManager
1872
-	 */
1873
-	public function getContentSecurityPolicyManager() {
1874
-		return $this->query('ContentSecurityPolicyManager');
1875
-	}
1876
-
1877
-	/**
1878
-	 * @return ContentSecurityPolicyNonceManager
1879
-	 */
1880
-	public function getContentSecurityPolicyNonceManager() {
1881
-		return $this->query('ContentSecurityPolicyNonceManager');
1882
-	}
1883
-
1884
-	/**
1885
-	 * Not a public API as of 8.2, wait for 9.0
1886
-	 *
1887
-	 * @return \OCA\Files_External\Service\BackendService
1888
-	 */
1889
-	public function getStoragesBackendService() {
1890
-		return $this->query('OCA\\Files_External\\Service\\BackendService');
1891
-	}
1892
-
1893
-	/**
1894
-	 * Not a public API as of 8.2, wait for 9.0
1895
-	 *
1896
-	 * @return \OCA\Files_External\Service\GlobalStoragesService
1897
-	 */
1898
-	public function getGlobalStoragesService() {
1899
-		return $this->query('OCA\\Files_External\\Service\\GlobalStoragesService');
1900
-	}
1901
-
1902
-	/**
1903
-	 * Not a public API as of 8.2, wait for 9.0
1904
-	 *
1905
-	 * @return \OCA\Files_External\Service\UserGlobalStoragesService
1906
-	 */
1907
-	public function getUserGlobalStoragesService() {
1908
-		return $this->query('OCA\\Files_External\\Service\\UserGlobalStoragesService');
1909
-	}
1910
-
1911
-	/**
1912
-	 * Not a public API as of 8.2, wait for 9.0
1913
-	 *
1914
-	 * @return \OCA\Files_External\Service\UserStoragesService
1915
-	 */
1916
-	public function getUserStoragesService() {
1917
-		return $this->query('OCA\\Files_External\\Service\\UserStoragesService');
1918
-	}
1919
-
1920
-	/**
1921
-	 * @return \OCP\Share\IManager
1922
-	 */
1923
-	public function getShareManager() {
1924
-		return $this->query('ShareManager');
1925
-	}
1926
-
1927
-	/**
1928
-	 * @return \OCP\Collaboration\Collaborators\ISearch
1929
-	 */
1930
-	public function getCollaboratorSearch() {
1931
-		return $this->query('CollaboratorSearch');
1932
-	}
1933
-
1934
-	/**
1935
-	 * @return \OCP\Collaboration\AutoComplete\IManager
1936
-	 */
1937
-	public function getAutoCompleteManager(){
1938
-		return $this->query(IManager::class);
1939
-	}
1940
-
1941
-	/**
1942
-	 * Returns the LDAP Provider
1943
-	 *
1944
-	 * @return \OCP\LDAP\ILDAPProvider
1945
-	 */
1946
-	public function getLDAPProvider() {
1947
-		return $this->query('LDAPProvider');
1948
-	}
1949
-
1950
-	/**
1951
-	 * @return \OCP\Settings\IManager
1952
-	 */
1953
-	public function getSettingsManager() {
1954
-		return $this->query('SettingsManager');
1955
-	}
1956
-
1957
-	/**
1958
-	 * @return \OCP\Files\IAppData
1959
-	 */
1960
-	public function getAppDataDir($app) {
1961
-		/** @var \OC\Files\AppData\Factory $factory */
1962
-		$factory = $this->query(\OC\Files\AppData\Factory::class);
1963
-		return $factory->get($app);
1964
-	}
1965
-
1966
-	/**
1967
-	 * @return \OCP\Lockdown\ILockdownManager
1968
-	 */
1969
-	public function getLockdownManager() {
1970
-		return $this->query('LockdownManager');
1971
-	}
1972
-
1973
-	/**
1974
-	 * @return \OCP\Federation\ICloudIdManager
1975
-	 */
1976
-	public function getCloudIdManager() {
1977
-		return $this->query(ICloudIdManager::class);
1978
-	}
1979
-
1980
-	/**
1981
-	 * @return \OCP\Remote\Api\IApiFactory
1982
-	 */
1983
-	public function getRemoteApiFactory() {
1984
-		return $this->query(IApiFactory::class);
1985
-	}
1986
-
1987
-	/**
1988
-	 * @return \OCP\Remote\IInstanceFactory
1989
-	 */
1990
-	public function getRemoteInstanceFactory() {
1991
-		return $this->query(IInstanceFactory::class);
1992
-	}
937
+            $prefixes = \OC::$composerAutoloader->getPrefixesPsr4();
938
+            if (isset($prefixes['OCA\\Theming\\'])) {
939
+                $classExists = true;
940
+            } else {
941
+                $classExists = false;
942
+            }
943
+
944
+            if ($classExists && $c->getConfig()->getSystemValue('installed', false) && $c->getAppManager()->isInstalled('theming') && $c->getTrustedDomainHelper()->isTrustedDomain($c->getRequest()->getInsecureServerHost())) {
945
+                return new ThemingDefaults(
946
+                    $c->getConfig(),
947
+                    $c->getL10N('theming'),
948
+                    $c->getURLGenerator(),
949
+                    $c->getAppDataDir('theming'),
950
+                    $c->getMemCacheFactory(),
951
+                    new Util($c->getConfig(), $this->getAppManager(), $this->getAppDataDir('theming')),
952
+                    $this->getAppManager()
953
+                );
954
+            }
955
+            return new \OC_Defaults();
956
+        });
957
+        $this->registerService(SCSSCacher::class, function (Server $c) {
958
+            /** @var Factory $cacheFactory */
959
+            $cacheFactory = $c->query(Factory::class);
960
+            return new SCSSCacher(
961
+                $c->getLogger(),
962
+                $c->query(\OC\Files\AppData\Factory::class),
963
+                $c->getURLGenerator(),
964
+                $c->getConfig(),
965
+                $c->getThemingDefaults(),
966
+                \OC::$SERVERROOT,
967
+                $this->getMemCacheFactory()
968
+            );
969
+        });
970
+        $this->registerService(JSCombiner::class, function (Server $c) {
971
+            /** @var Factory $cacheFactory */
972
+            $cacheFactory = $c->query(Factory::class);
973
+            return new JSCombiner(
974
+                $c->getAppDataDir('js'),
975
+                $c->getURLGenerator(),
976
+                $this->getMemCacheFactory(),
977
+                $c->getSystemConfig(),
978
+                $c->getLogger()
979
+            );
980
+        });
981
+        $this->registerService(EventDispatcher::class, function () {
982
+            return new EventDispatcher();
983
+        });
984
+        $this->registerAlias('EventDispatcher', EventDispatcher::class);
985
+        $this->registerAlias(EventDispatcherInterface::class, EventDispatcher::class);
986
+
987
+        $this->registerService('CryptoWrapper', function (Server $c) {
988
+            // FIXME: Instantiiated here due to cyclic dependency
989
+            $request = new Request(
990
+                [
991
+                    'get' => $_GET,
992
+                    'post' => $_POST,
993
+                    'files' => $_FILES,
994
+                    'server' => $_SERVER,
995
+                    'env' => $_ENV,
996
+                    'cookies' => $_COOKIE,
997
+                    'method' => (isset($_SERVER) && isset($_SERVER['REQUEST_METHOD']))
998
+                        ? $_SERVER['REQUEST_METHOD']
999
+                        : null,
1000
+                ],
1001
+                $c->getSecureRandom(),
1002
+                $c->getConfig()
1003
+            );
1004
+
1005
+            return new CryptoWrapper(
1006
+                $c->getConfig(),
1007
+                $c->getCrypto(),
1008
+                $c->getSecureRandom(),
1009
+                $request
1010
+            );
1011
+        });
1012
+        $this->registerService('CsrfTokenManager', function (Server $c) {
1013
+            $tokenGenerator = new CsrfTokenGenerator($c->getSecureRandom());
1014
+
1015
+            return new CsrfTokenManager(
1016
+                $tokenGenerator,
1017
+                $c->query(SessionStorage::class)
1018
+            );
1019
+        });
1020
+        $this->registerService(SessionStorage::class, function (Server $c) {
1021
+            return new SessionStorage($c->getSession());
1022
+        });
1023
+        $this->registerService(\OCP\Security\IContentSecurityPolicyManager::class, function (Server $c) {
1024
+            return new ContentSecurityPolicyManager();
1025
+        });
1026
+        $this->registerAlias('ContentSecurityPolicyManager', \OCP\Security\IContentSecurityPolicyManager::class);
1027
+
1028
+        $this->registerService('ContentSecurityPolicyNonceManager', function (Server $c) {
1029
+            return new ContentSecurityPolicyNonceManager(
1030
+                $c->getCsrfTokenManager(),
1031
+                $c->getRequest()
1032
+            );
1033
+        });
1034
+
1035
+        $this->registerService(\OCP\Share\IManager::class, function (Server $c) {
1036
+            $config = $c->getConfig();
1037
+            $factoryClass = $config->getSystemValue('sharing.managerFactory', '\OC\Share20\ProviderFactory');
1038
+            /** @var \OCP\Share\IProviderFactory $factory */
1039
+            $factory = new $factoryClass($this);
1040
+
1041
+            $manager = new \OC\Share20\Manager(
1042
+                $c->getLogger(),
1043
+                $c->getConfig(),
1044
+                $c->getSecureRandom(),
1045
+                $c->getHasher(),
1046
+                $c->getMountManager(),
1047
+                $c->getGroupManager(),
1048
+                $c->getL10N('lib'),
1049
+                $c->getL10NFactory(),
1050
+                $factory,
1051
+                $c->getUserManager(),
1052
+                $c->getLazyRootFolder(),
1053
+                $c->getEventDispatcher(),
1054
+                $c->getMailer(),
1055
+                $c->getURLGenerator(),
1056
+                $c->getThemingDefaults()
1057
+            );
1058
+
1059
+            return $manager;
1060
+        });
1061
+        $this->registerAlias('ShareManager', \OCP\Share\IManager::class);
1062
+
1063
+        $this->registerService(\OCP\Collaboration\Collaborators\ISearch::class, function(Server $c) {
1064
+            $instance = new Collaboration\Collaborators\Search($c);
1065
+
1066
+            // register default plugins
1067
+            $instance->registerPlugin(['shareType' => 'SHARE_TYPE_USER', 'class' => UserPlugin::class]);
1068
+            $instance->registerPlugin(['shareType' => 'SHARE_TYPE_GROUP', 'class' => GroupPlugin::class]);
1069
+            $instance->registerPlugin(['shareType' => 'SHARE_TYPE_EMAIL', 'class' => MailPlugin::class]);
1070
+            $instance->registerPlugin(['shareType' => 'SHARE_TYPE_REMOTE', 'class' => RemotePlugin::class]);
1071
+
1072
+            return $instance;
1073
+        });
1074
+        $this->registerAlias('CollaboratorSearch', \OCP\Collaboration\Collaborators\ISearch::class);
1075
+
1076
+        $this->registerAlias(\OCP\Collaboration\AutoComplete\IManager::class, \OC\Collaboration\AutoComplete\Manager::class);
1077
+
1078
+        $this->registerService('SettingsManager', function (Server $c) {
1079
+            $manager = new \OC\Settings\Manager(
1080
+                $c->getLogger(),
1081
+                $c->getDatabaseConnection(),
1082
+                $c->getL10N('lib'),
1083
+                $c->getConfig(),
1084
+                $c->getEncryptionManager(),
1085
+                $c->getUserManager(),
1086
+                $c->getLockingProvider(),
1087
+                $c->getRequest(),
1088
+                new \OC\Settings\Mapper($c->getDatabaseConnection()),
1089
+                $c->getURLGenerator(),
1090
+                $c->query(AccountManager::class),
1091
+                $c->getGroupManager(),
1092
+                $c->getL10NFactory(),
1093
+                $c->getThemingDefaults(),
1094
+                $c->getAppManager()
1095
+            );
1096
+            return $manager;
1097
+        });
1098
+        $this->registerService(\OC\Files\AppData\Factory::class, function (Server $c) {
1099
+            return new \OC\Files\AppData\Factory(
1100
+                $c->getRootFolder(),
1101
+                $c->getSystemConfig()
1102
+            );
1103
+        });
1104
+
1105
+        $this->registerService('LockdownManager', function (Server $c) {
1106
+            return new LockdownManager(function () use ($c) {
1107
+                return $c->getSession();
1108
+            });
1109
+        });
1110
+
1111
+        $this->registerService(\OCP\OCS\IDiscoveryService::class, function (Server $c) {
1112
+            return new DiscoveryService($c->getMemCacheFactory(), $c->getHTTPClientService());
1113
+        });
1114
+
1115
+        $this->registerService(ICloudIdManager::class, function (Server $c) {
1116
+            return new CloudIdManager();
1117
+        });
1118
+
1119
+        $this->registerAlias(\OCP\AppFramework\Utility\IControllerMethodReflector::class, \OC\AppFramework\Utility\ControllerMethodReflector::class);
1120
+        $this->registerAlias('ControllerMethodReflector', \OCP\AppFramework\Utility\IControllerMethodReflector::class);
1121
+
1122
+        $this->registerAlias(\OCP\AppFramework\Utility\ITimeFactory::class, \OC\AppFramework\Utility\TimeFactory::class);
1123
+        $this->registerAlias('TimeFactory', \OCP\AppFramework\Utility\ITimeFactory::class);
1124
+
1125
+        $this->registerService(Defaults::class, function (Server $c) {
1126
+            return new Defaults(
1127
+                $c->getThemingDefaults()
1128
+            );
1129
+        });
1130
+        $this->registerAlias('Defaults', \OCP\Defaults::class);
1131
+
1132
+        $this->registerService(\OCP\ISession::class, function (SimpleContainer $c) {
1133
+            return $c->query(\OCP\IUserSession::class)->getSession();
1134
+        });
1135
+
1136
+        $this->registerService(IShareHelper::class, function (Server $c) {
1137
+            return new ShareHelper(
1138
+                $c->query(\OCP\Share\IManager::class)
1139
+            );
1140
+        });
1141
+
1142
+        $this->registerService(Installer::class, function(Server $c) {
1143
+            return new Installer(
1144
+                $c->getAppFetcher(),
1145
+                $c->getHTTPClientService(),
1146
+                $c->getTempManager(),
1147
+                $c->getLogger(),
1148
+                $c->getConfig()
1149
+            );
1150
+        });
1151
+
1152
+        $this->registerService(IApiFactory::class, function(Server $c) {
1153
+            return new ApiFactory($c->getHTTPClientService());
1154
+        });
1155
+
1156
+        $this->registerService(IInstanceFactory::class, function(Server $c) {
1157
+            $memcacheFactory = $c->getMemCacheFactory();
1158
+            return new InstanceFactory($memcacheFactory->createLocal('remoteinstance.'), $c->getHTTPClientService());
1159
+        });
1160
+
1161
+        $this->registerService(IContactsStore::class, function(Server $c) {
1162
+            return new ContactsStore(
1163
+                $c->getContactsManager(),
1164
+                $c->getConfig(),
1165
+                $c->getUserManager(),
1166
+                $c->getGroupManager()
1167
+            );
1168
+        });
1169
+        $this->registerAlias(IContactsStore::class, ContactsStore::class);
1170
+
1171
+        $this->connectDispatcher();
1172
+    }
1173
+
1174
+    /**
1175
+     * @return \OCP\Calendar\IManager
1176
+     */
1177
+    public function getCalendarManager() {
1178
+        return $this->query('CalendarManager');
1179
+    }
1180
+
1181
+    private function connectDispatcher() {
1182
+        $dispatcher = $this->getEventDispatcher();
1183
+
1184
+        // Delete avatar on user deletion
1185
+        $dispatcher->addListener('OCP\IUser::preDelete', function(GenericEvent $e) {
1186
+            $logger = $this->getLogger();
1187
+            $manager = $this->getAvatarManager();
1188
+            /** @var IUser $user */
1189
+            $user = $e->getSubject();
1190
+
1191
+            try {
1192
+                $avatar = $manager->getAvatar($user->getUID());
1193
+                $avatar->remove();
1194
+            } catch (NotFoundException $e) {
1195
+                // no avatar to remove
1196
+            } catch (\Exception $e) {
1197
+                // Ignore exceptions
1198
+                $logger->info('Could not cleanup avatar of ' . $user->getUID());
1199
+            }
1200
+        });
1201
+
1202
+        $dispatcher->addListener('OCP\IUser::changeUser', function (GenericEvent $e) {
1203
+            $manager = $this->getAvatarManager();
1204
+            /** @var IUser $user */
1205
+            $user = $e->getSubject();
1206
+            $feature = $e->getArgument('feature');
1207
+            $oldValue = $e->getArgument('oldValue');
1208
+            $value = $e->getArgument('value');
1209
+
1210
+            try {
1211
+                $avatar = $manager->getAvatar($user->getUID());
1212
+                $avatar->userChanged($feature, $oldValue, $value);
1213
+            } catch (NotFoundException $e) {
1214
+                // no avatar to remove
1215
+            }
1216
+        });
1217
+    }
1218
+
1219
+    /**
1220
+     * @return \OCP\Contacts\IManager
1221
+     */
1222
+    public function getContactsManager() {
1223
+        return $this->query('ContactsManager');
1224
+    }
1225
+
1226
+    /**
1227
+     * @return \OC\Encryption\Manager
1228
+     */
1229
+    public function getEncryptionManager() {
1230
+        return $this->query('EncryptionManager');
1231
+    }
1232
+
1233
+    /**
1234
+     * @return \OC\Encryption\File
1235
+     */
1236
+    public function getEncryptionFilesHelper() {
1237
+        return $this->query('EncryptionFileHelper');
1238
+    }
1239
+
1240
+    /**
1241
+     * @return \OCP\Encryption\Keys\IStorage
1242
+     */
1243
+    public function getEncryptionKeyStorage() {
1244
+        return $this->query('EncryptionKeyStorage');
1245
+    }
1246
+
1247
+    /**
1248
+     * The current request object holding all information about the request
1249
+     * currently being processed is returned from this method.
1250
+     * In case the current execution was not initiated by a web request null is returned
1251
+     *
1252
+     * @return \OCP\IRequest
1253
+     */
1254
+    public function getRequest() {
1255
+        return $this->query('Request');
1256
+    }
1257
+
1258
+    /**
1259
+     * Returns the preview manager which can create preview images for a given file
1260
+     *
1261
+     * @return \OCP\IPreview
1262
+     */
1263
+    public function getPreviewManager() {
1264
+        return $this->query('PreviewManager');
1265
+    }
1266
+
1267
+    /**
1268
+     * Returns the tag manager which can get and set tags for different object types
1269
+     *
1270
+     * @see \OCP\ITagManager::load()
1271
+     * @return \OCP\ITagManager
1272
+     */
1273
+    public function getTagManager() {
1274
+        return $this->query('TagManager');
1275
+    }
1276
+
1277
+    /**
1278
+     * Returns the system-tag manager
1279
+     *
1280
+     * @return \OCP\SystemTag\ISystemTagManager
1281
+     *
1282
+     * @since 9.0.0
1283
+     */
1284
+    public function getSystemTagManager() {
1285
+        return $this->query('SystemTagManager');
1286
+    }
1287
+
1288
+    /**
1289
+     * Returns the system-tag object mapper
1290
+     *
1291
+     * @return \OCP\SystemTag\ISystemTagObjectMapper
1292
+     *
1293
+     * @since 9.0.0
1294
+     */
1295
+    public function getSystemTagObjectMapper() {
1296
+        return $this->query('SystemTagObjectMapper');
1297
+    }
1298
+
1299
+    /**
1300
+     * Returns the avatar manager, used for avatar functionality
1301
+     *
1302
+     * @return \OCP\IAvatarManager
1303
+     */
1304
+    public function getAvatarManager() {
1305
+        return $this->query('AvatarManager');
1306
+    }
1307
+
1308
+    /**
1309
+     * Returns the root folder of ownCloud's data directory
1310
+     *
1311
+     * @return \OCP\Files\IRootFolder
1312
+     */
1313
+    public function getRootFolder() {
1314
+        return $this->query('LazyRootFolder');
1315
+    }
1316
+
1317
+    /**
1318
+     * Returns the root folder of ownCloud's data directory
1319
+     * This is the lazy variant so this gets only initialized once it
1320
+     * is actually used.
1321
+     *
1322
+     * @return \OCP\Files\IRootFolder
1323
+     */
1324
+    public function getLazyRootFolder() {
1325
+        return $this->query('LazyRootFolder');
1326
+    }
1327
+
1328
+    /**
1329
+     * Returns a view to ownCloud's files folder
1330
+     *
1331
+     * @param string $userId user ID
1332
+     * @return \OCP\Files\Folder|null
1333
+     */
1334
+    public function getUserFolder($userId = null) {
1335
+        if ($userId === null) {
1336
+            $user = $this->getUserSession()->getUser();
1337
+            if (!$user) {
1338
+                return null;
1339
+            }
1340
+            $userId = $user->getUID();
1341
+        }
1342
+        $root = $this->getRootFolder();
1343
+        return $root->getUserFolder($userId);
1344
+    }
1345
+
1346
+    /**
1347
+     * Returns an app-specific view in ownClouds data directory
1348
+     *
1349
+     * @return \OCP\Files\Folder
1350
+     * @deprecated since 9.2.0 use IAppData
1351
+     */
1352
+    public function getAppFolder() {
1353
+        $dir = '/' . \OC_App::getCurrentApp();
1354
+        $root = $this->getRootFolder();
1355
+        if (!$root->nodeExists($dir)) {
1356
+            $folder = $root->newFolder($dir);
1357
+        } else {
1358
+            $folder = $root->get($dir);
1359
+        }
1360
+        return $folder;
1361
+    }
1362
+
1363
+    /**
1364
+     * @return \OC\User\Manager
1365
+     */
1366
+    public function getUserManager() {
1367
+        return $this->query('UserManager');
1368
+    }
1369
+
1370
+    /**
1371
+     * @return \OC\Group\Manager
1372
+     */
1373
+    public function getGroupManager() {
1374
+        return $this->query('GroupManager');
1375
+    }
1376
+
1377
+    /**
1378
+     * @return \OC\User\Session
1379
+     */
1380
+    public function getUserSession() {
1381
+        return $this->query('UserSession');
1382
+    }
1383
+
1384
+    /**
1385
+     * @return \OCP\ISession
1386
+     */
1387
+    public function getSession() {
1388
+        return $this->query('UserSession')->getSession();
1389
+    }
1390
+
1391
+    /**
1392
+     * @param \OCP\ISession $session
1393
+     */
1394
+    public function setSession(\OCP\ISession $session) {
1395
+        $this->query(SessionStorage::class)->setSession($session);
1396
+        $this->query('UserSession')->setSession($session);
1397
+        $this->query(Store::class)->setSession($session);
1398
+    }
1399
+
1400
+    /**
1401
+     * @return \OC\Authentication\TwoFactorAuth\Manager
1402
+     */
1403
+    public function getTwoFactorAuthManager() {
1404
+        return $this->query('\OC\Authentication\TwoFactorAuth\Manager');
1405
+    }
1406
+
1407
+    /**
1408
+     * @return \OC\NavigationManager
1409
+     */
1410
+    public function getNavigationManager() {
1411
+        return $this->query('NavigationManager');
1412
+    }
1413
+
1414
+    /**
1415
+     * @return \OCP\IConfig
1416
+     */
1417
+    public function getConfig() {
1418
+        return $this->query('AllConfig');
1419
+    }
1420
+
1421
+    /**
1422
+     * @return \OC\SystemConfig
1423
+     */
1424
+    public function getSystemConfig() {
1425
+        return $this->query('SystemConfig');
1426
+    }
1427
+
1428
+    /**
1429
+     * Returns the app config manager
1430
+     *
1431
+     * @return \OCP\IAppConfig
1432
+     */
1433
+    public function getAppConfig() {
1434
+        return $this->query('AppConfig');
1435
+    }
1436
+
1437
+    /**
1438
+     * @return \OCP\L10N\IFactory
1439
+     */
1440
+    public function getL10NFactory() {
1441
+        return $this->query('L10NFactory');
1442
+    }
1443
+
1444
+    /**
1445
+     * get an L10N instance
1446
+     *
1447
+     * @param string $app appid
1448
+     * @param string $lang
1449
+     * @return IL10N
1450
+     */
1451
+    public function getL10N($app, $lang = null) {
1452
+        return $this->getL10NFactory()->get($app, $lang);
1453
+    }
1454
+
1455
+    /**
1456
+     * @return \OCP\IURLGenerator
1457
+     */
1458
+    public function getURLGenerator() {
1459
+        return $this->query('URLGenerator');
1460
+    }
1461
+
1462
+    /**
1463
+     * @return \OCP\IHelper
1464
+     */
1465
+    public function getHelper() {
1466
+        return $this->query('AppHelper');
1467
+    }
1468
+
1469
+    /**
1470
+     * @return AppFetcher
1471
+     */
1472
+    public function getAppFetcher() {
1473
+        return $this->query(AppFetcher::class);
1474
+    }
1475
+
1476
+    /**
1477
+     * Returns an ICache instance. Since 8.1.0 it returns a fake cache. Use
1478
+     * getMemCacheFactory() instead.
1479
+     *
1480
+     * @return \OCP\ICache
1481
+     * @deprecated 8.1.0 use getMemCacheFactory to obtain a proper cache
1482
+     */
1483
+    public function getCache() {
1484
+        return $this->query('UserCache');
1485
+    }
1486
+
1487
+    /**
1488
+     * Returns an \OCP\CacheFactory instance
1489
+     *
1490
+     * @return \OCP\ICacheFactory
1491
+     */
1492
+    public function getMemCacheFactory() {
1493
+        return $this->query('MemCacheFactory');
1494
+    }
1495
+
1496
+    /**
1497
+     * Returns an \OC\RedisFactory instance
1498
+     *
1499
+     * @return \OC\RedisFactory
1500
+     */
1501
+    public function getGetRedisFactory() {
1502
+        return $this->query('RedisFactory');
1503
+    }
1504
+
1505
+
1506
+    /**
1507
+     * Returns the current session
1508
+     *
1509
+     * @return \OCP\IDBConnection
1510
+     */
1511
+    public function getDatabaseConnection() {
1512
+        return $this->query('DatabaseConnection');
1513
+    }
1514
+
1515
+    /**
1516
+     * Returns the activity manager
1517
+     *
1518
+     * @return \OCP\Activity\IManager
1519
+     */
1520
+    public function getActivityManager() {
1521
+        return $this->query('ActivityManager');
1522
+    }
1523
+
1524
+    /**
1525
+     * Returns an job list for controlling background jobs
1526
+     *
1527
+     * @return \OCP\BackgroundJob\IJobList
1528
+     */
1529
+    public function getJobList() {
1530
+        return $this->query('JobList');
1531
+    }
1532
+
1533
+    /**
1534
+     * Returns a logger instance
1535
+     *
1536
+     * @return \OCP\ILogger
1537
+     */
1538
+    public function getLogger() {
1539
+        return $this->query('Logger');
1540
+    }
1541
+
1542
+    /**
1543
+     * Returns a router for generating and matching urls
1544
+     *
1545
+     * @return \OCP\Route\IRouter
1546
+     */
1547
+    public function getRouter() {
1548
+        return $this->query('Router');
1549
+    }
1550
+
1551
+    /**
1552
+     * Returns a search instance
1553
+     *
1554
+     * @return \OCP\ISearch
1555
+     */
1556
+    public function getSearch() {
1557
+        return $this->query('Search');
1558
+    }
1559
+
1560
+    /**
1561
+     * Returns a SecureRandom instance
1562
+     *
1563
+     * @return \OCP\Security\ISecureRandom
1564
+     */
1565
+    public function getSecureRandom() {
1566
+        return $this->query('SecureRandom');
1567
+    }
1568
+
1569
+    /**
1570
+     * Returns a Crypto instance
1571
+     *
1572
+     * @return \OCP\Security\ICrypto
1573
+     */
1574
+    public function getCrypto() {
1575
+        return $this->query('Crypto');
1576
+    }
1577
+
1578
+    /**
1579
+     * Returns a Hasher instance
1580
+     *
1581
+     * @return \OCP\Security\IHasher
1582
+     */
1583
+    public function getHasher() {
1584
+        return $this->query('Hasher');
1585
+    }
1586
+
1587
+    /**
1588
+     * Returns a CredentialsManager instance
1589
+     *
1590
+     * @return \OCP\Security\ICredentialsManager
1591
+     */
1592
+    public function getCredentialsManager() {
1593
+        return $this->query('CredentialsManager');
1594
+    }
1595
+
1596
+    /**
1597
+     * Returns an instance of the HTTP helper class
1598
+     *
1599
+     * @deprecated Use getHTTPClientService()
1600
+     * @return \OC\HTTPHelper
1601
+     */
1602
+    public function getHTTPHelper() {
1603
+        return $this->query('HTTPHelper');
1604
+    }
1605
+
1606
+    /**
1607
+     * Get the certificate manager for the user
1608
+     *
1609
+     * @param string $userId (optional) if not specified the current loggedin user is used, use null to get the system certificate manager
1610
+     * @return \OCP\ICertificateManager | null if $uid is null and no user is logged in
1611
+     */
1612
+    public function getCertificateManager($userId = '') {
1613
+        if ($userId === '') {
1614
+            $userSession = $this->getUserSession();
1615
+            $user = $userSession->getUser();
1616
+            if (is_null($user)) {
1617
+                return null;
1618
+            }
1619
+            $userId = $user->getUID();
1620
+        }
1621
+        return new CertificateManager(
1622
+            $userId,
1623
+            new View(),
1624
+            $this->getConfig(),
1625
+            $this->getLogger(),
1626
+            $this->getSecureRandom()
1627
+        );
1628
+    }
1629
+
1630
+    /**
1631
+     * Returns an instance of the HTTP client service
1632
+     *
1633
+     * @return \OCP\Http\Client\IClientService
1634
+     */
1635
+    public function getHTTPClientService() {
1636
+        return $this->query('HttpClientService');
1637
+    }
1638
+
1639
+    /**
1640
+     * Create a new event source
1641
+     *
1642
+     * @return \OCP\IEventSource
1643
+     */
1644
+    public function createEventSource() {
1645
+        return new \OC_EventSource();
1646
+    }
1647
+
1648
+    /**
1649
+     * Get the active event logger
1650
+     *
1651
+     * The returned logger only logs data when debug mode is enabled
1652
+     *
1653
+     * @return \OCP\Diagnostics\IEventLogger
1654
+     */
1655
+    public function getEventLogger() {
1656
+        return $this->query('EventLogger');
1657
+    }
1658
+
1659
+    /**
1660
+     * Get the active query logger
1661
+     *
1662
+     * The returned logger only logs data when debug mode is enabled
1663
+     *
1664
+     * @return \OCP\Diagnostics\IQueryLogger
1665
+     */
1666
+    public function getQueryLogger() {
1667
+        return $this->query('QueryLogger');
1668
+    }
1669
+
1670
+    /**
1671
+     * Get the manager for temporary files and folders
1672
+     *
1673
+     * @return \OCP\ITempManager
1674
+     */
1675
+    public function getTempManager() {
1676
+        return $this->query('TempManager');
1677
+    }
1678
+
1679
+    /**
1680
+     * Get the app manager
1681
+     *
1682
+     * @return \OCP\App\IAppManager
1683
+     */
1684
+    public function getAppManager() {
1685
+        return $this->query('AppManager');
1686
+    }
1687
+
1688
+    /**
1689
+     * Creates a new mailer
1690
+     *
1691
+     * @return \OCP\Mail\IMailer
1692
+     */
1693
+    public function getMailer() {
1694
+        return $this->query('Mailer');
1695
+    }
1696
+
1697
+    /**
1698
+     * Get the webroot
1699
+     *
1700
+     * @return string
1701
+     */
1702
+    public function getWebRoot() {
1703
+        return $this->webRoot;
1704
+    }
1705
+
1706
+    /**
1707
+     * @return \OC\OCSClient
1708
+     */
1709
+    public function getOcsClient() {
1710
+        return $this->query('OcsClient');
1711
+    }
1712
+
1713
+    /**
1714
+     * @return \OCP\IDateTimeZone
1715
+     */
1716
+    public function getDateTimeZone() {
1717
+        return $this->query('DateTimeZone');
1718
+    }
1719
+
1720
+    /**
1721
+     * @return \OCP\IDateTimeFormatter
1722
+     */
1723
+    public function getDateTimeFormatter() {
1724
+        return $this->query('DateTimeFormatter');
1725
+    }
1726
+
1727
+    /**
1728
+     * @return \OCP\Files\Config\IMountProviderCollection
1729
+     */
1730
+    public function getMountProviderCollection() {
1731
+        return $this->query('MountConfigManager');
1732
+    }
1733
+
1734
+    /**
1735
+     * Get the IniWrapper
1736
+     *
1737
+     * @return IniGetWrapper
1738
+     */
1739
+    public function getIniWrapper() {
1740
+        return $this->query('IniWrapper');
1741
+    }
1742
+
1743
+    /**
1744
+     * @return \OCP\Command\IBus
1745
+     */
1746
+    public function getCommandBus() {
1747
+        return $this->query('AsyncCommandBus');
1748
+    }
1749
+
1750
+    /**
1751
+     * Get the trusted domain helper
1752
+     *
1753
+     * @return TrustedDomainHelper
1754
+     */
1755
+    public function getTrustedDomainHelper() {
1756
+        return $this->query('TrustedDomainHelper');
1757
+    }
1758
+
1759
+    /**
1760
+     * Get the locking provider
1761
+     *
1762
+     * @return \OCP\Lock\ILockingProvider
1763
+     * @since 8.1.0
1764
+     */
1765
+    public function getLockingProvider() {
1766
+        return $this->query('LockingProvider');
1767
+    }
1768
+
1769
+    /**
1770
+     * @return \OCP\Files\Mount\IMountManager
1771
+     **/
1772
+    function getMountManager() {
1773
+        return $this->query('MountManager');
1774
+    }
1775
+
1776
+    /** @return \OCP\Files\Config\IUserMountCache */
1777
+    function getUserMountCache() {
1778
+        return $this->query('UserMountCache');
1779
+    }
1780
+
1781
+    /**
1782
+     * Get the MimeTypeDetector
1783
+     *
1784
+     * @return \OCP\Files\IMimeTypeDetector
1785
+     */
1786
+    public function getMimeTypeDetector() {
1787
+        return $this->query('MimeTypeDetector');
1788
+    }
1789
+
1790
+    /**
1791
+     * Get the MimeTypeLoader
1792
+     *
1793
+     * @return \OCP\Files\IMimeTypeLoader
1794
+     */
1795
+    public function getMimeTypeLoader() {
1796
+        return $this->query('MimeTypeLoader');
1797
+    }
1798
+
1799
+    /**
1800
+     * Get the manager of all the capabilities
1801
+     *
1802
+     * @return \OC\CapabilitiesManager
1803
+     */
1804
+    public function getCapabilitiesManager() {
1805
+        return $this->query('CapabilitiesManager');
1806
+    }
1807
+
1808
+    /**
1809
+     * Get the EventDispatcher
1810
+     *
1811
+     * @return EventDispatcherInterface
1812
+     * @since 8.2.0
1813
+     */
1814
+    public function getEventDispatcher() {
1815
+        return $this->query('EventDispatcher');
1816
+    }
1817
+
1818
+    /**
1819
+     * Get the Notification Manager
1820
+     *
1821
+     * @return \OCP\Notification\IManager
1822
+     * @since 8.2.0
1823
+     */
1824
+    public function getNotificationManager() {
1825
+        return $this->query('NotificationManager');
1826
+    }
1827
+
1828
+    /**
1829
+     * @return \OCP\Comments\ICommentsManager
1830
+     */
1831
+    public function getCommentsManager() {
1832
+        return $this->query('CommentsManager');
1833
+    }
1834
+
1835
+    /**
1836
+     * @return \OCA\Theming\ThemingDefaults
1837
+     */
1838
+    public function getThemingDefaults() {
1839
+        return $this->query('ThemingDefaults');
1840
+    }
1841
+
1842
+    /**
1843
+     * @return \OC\IntegrityCheck\Checker
1844
+     */
1845
+    public function getIntegrityCodeChecker() {
1846
+        return $this->query('IntegrityCodeChecker');
1847
+    }
1848
+
1849
+    /**
1850
+     * @return \OC\Session\CryptoWrapper
1851
+     */
1852
+    public function getSessionCryptoWrapper() {
1853
+        return $this->query('CryptoWrapper');
1854
+    }
1855
+
1856
+    /**
1857
+     * @return CsrfTokenManager
1858
+     */
1859
+    public function getCsrfTokenManager() {
1860
+        return $this->query('CsrfTokenManager');
1861
+    }
1862
+
1863
+    /**
1864
+     * @return Throttler
1865
+     */
1866
+    public function getBruteForceThrottler() {
1867
+        return $this->query('Throttler');
1868
+    }
1869
+
1870
+    /**
1871
+     * @return IContentSecurityPolicyManager
1872
+     */
1873
+    public function getContentSecurityPolicyManager() {
1874
+        return $this->query('ContentSecurityPolicyManager');
1875
+    }
1876
+
1877
+    /**
1878
+     * @return ContentSecurityPolicyNonceManager
1879
+     */
1880
+    public function getContentSecurityPolicyNonceManager() {
1881
+        return $this->query('ContentSecurityPolicyNonceManager');
1882
+    }
1883
+
1884
+    /**
1885
+     * Not a public API as of 8.2, wait for 9.0
1886
+     *
1887
+     * @return \OCA\Files_External\Service\BackendService
1888
+     */
1889
+    public function getStoragesBackendService() {
1890
+        return $this->query('OCA\\Files_External\\Service\\BackendService');
1891
+    }
1892
+
1893
+    /**
1894
+     * Not a public API as of 8.2, wait for 9.0
1895
+     *
1896
+     * @return \OCA\Files_External\Service\GlobalStoragesService
1897
+     */
1898
+    public function getGlobalStoragesService() {
1899
+        return $this->query('OCA\\Files_External\\Service\\GlobalStoragesService');
1900
+    }
1901
+
1902
+    /**
1903
+     * Not a public API as of 8.2, wait for 9.0
1904
+     *
1905
+     * @return \OCA\Files_External\Service\UserGlobalStoragesService
1906
+     */
1907
+    public function getUserGlobalStoragesService() {
1908
+        return $this->query('OCA\\Files_External\\Service\\UserGlobalStoragesService');
1909
+    }
1910
+
1911
+    /**
1912
+     * Not a public API as of 8.2, wait for 9.0
1913
+     *
1914
+     * @return \OCA\Files_External\Service\UserStoragesService
1915
+     */
1916
+    public function getUserStoragesService() {
1917
+        return $this->query('OCA\\Files_External\\Service\\UserStoragesService');
1918
+    }
1919
+
1920
+    /**
1921
+     * @return \OCP\Share\IManager
1922
+     */
1923
+    public function getShareManager() {
1924
+        return $this->query('ShareManager');
1925
+    }
1926
+
1927
+    /**
1928
+     * @return \OCP\Collaboration\Collaborators\ISearch
1929
+     */
1930
+    public function getCollaboratorSearch() {
1931
+        return $this->query('CollaboratorSearch');
1932
+    }
1933
+
1934
+    /**
1935
+     * @return \OCP\Collaboration\AutoComplete\IManager
1936
+     */
1937
+    public function getAutoCompleteManager(){
1938
+        return $this->query(IManager::class);
1939
+    }
1940
+
1941
+    /**
1942
+     * Returns the LDAP Provider
1943
+     *
1944
+     * @return \OCP\LDAP\ILDAPProvider
1945
+     */
1946
+    public function getLDAPProvider() {
1947
+        return $this->query('LDAPProvider');
1948
+    }
1949
+
1950
+    /**
1951
+     * @return \OCP\Settings\IManager
1952
+     */
1953
+    public function getSettingsManager() {
1954
+        return $this->query('SettingsManager');
1955
+    }
1956
+
1957
+    /**
1958
+     * @return \OCP\Files\IAppData
1959
+     */
1960
+    public function getAppDataDir($app) {
1961
+        /** @var \OC\Files\AppData\Factory $factory */
1962
+        $factory = $this->query(\OC\Files\AppData\Factory::class);
1963
+        return $factory->get($app);
1964
+    }
1965
+
1966
+    /**
1967
+     * @return \OCP\Lockdown\ILockdownManager
1968
+     */
1969
+    public function getLockdownManager() {
1970
+        return $this->query('LockdownManager');
1971
+    }
1972
+
1973
+    /**
1974
+     * @return \OCP\Federation\ICloudIdManager
1975
+     */
1976
+    public function getCloudIdManager() {
1977
+        return $this->query(ICloudIdManager::class);
1978
+    }
1979
+
1980
+    /**
1981
+     * @return \OCP\Remote\Api\IApiFactory
1982
+     */
1983
+    public function getRemoteApiFactory() {
1984
+        return $this->query(IApiFactory::class);
1985
+    }
1986
+
1987
+    /**
1988
+     * @return \OCP\Remote\IInstanceFactory
1989
+     */
1990
+    public function getRemoteInstanceFactory() {
1991
+        return $this->query(IInstanceFactory::class);
1992
+    }
1993 1993
 }
Please login to merge, or discard this patch.
Spacing   +115 added lines, -115 removed lines patch added patch discarded remove patch
@@ -159,7 +159,7 @@  discard block
 block discarded – undo
159 159
 		parent::__construct();
160 160
 		$this->webRoot = $webRoot;
161 161
 
162
-		$this->registerService(\OCP\IServerContainer::class, function (IServerContainer $c) {
162
+		$this->registerService(\OCP\IServerContainer::class, function(IServerContainer $c) {
163 163
 			return $c;
164 164
 		});
165 165
 
@@ -172,7 +172,7 @@  discard block
 block discarded – undo
172 172
 		$this->registerAlias(IActionFactory::class, ActionFactory::class);
173 173
 
174 174
 
175
-		$this->registerService(\OCP\IPreview::class, function (Server $c) {
175
+		$this->registerService(\OCP\IPreview::class, function(Server $c) {
176 176
 			return new PreviewManager(
177 177
 				$c->getConfig(),
178 178
 				$c->getRootFolder(),
@@ -183,13 +183,13 @@  discard block
 block discarded – undo
183 183
 		});
184 184
 		$this->registerAlias('PreviewManager', \OCP\IPreview::class);
185 185
 
186
-		$this->registerService(\OC\Preview\Watcher::class, function (Server $c) {
186
+		$this->registerService(\OC\Preview\Watcher::class, function(Server $c) {
187 187
 			return new \OC\Preview\Watcher(
188 188
 				$c->getAppDataDir('preview')
189 189
 			);
190 190
 		});
191 191
 
192
-		$this->registerService('EncryptionManager', function (Server $c) {
192
+		$this->registerService('EncryptionManager', function(Server $c) {
193 193
 			$view = new View();
194 194
 			$util = new Encryption\Util(
195 195
 				$view,
@@ -207,7 +207,7 @@  discard block
 block discarded – undo
207 207
 			);
208 208
 		});
209 209
 
210
-		$this->registerService('EncryptionFileHelper', function (Server $c) {
210
+		$this->registerService('EncryptionFileHelper', function(Server $c) {
211 211
 			$util = new Encryption\Util(
212 212
 				new View(),
213 213
 				$c->getUserManager(),
@@ -221,7 +221,7 @@  discard block
 block discarded – undo
221 221
 			);
222 222
 		});
223 223
 
224
-		$this->registerService('EncryptionKeyStorage', function (Server $c) {
224
+		$this->registerService('EncryptionKeyStorage', function(Server $c) {
225 225
 			$view = new View();
226 226
 			$util = new Encryption\Util(
227 227
 				$view,
@@ -232,32 +232,32 @@  discard block
 block discarded – undo
232 232
 
233 233
 			return new Encryption\Keys\Storage($view, $util);
234 234
 		});
235
-		$this->registerService('TagMapper', function (Server $c) {
235
+		$this->registerService('TagMapper', function(Server $c) {
236 236
 			return new TagMapper($c->getDatabaseConnection());
237 237
 		});
238 238
 
239
-		$this->registerService(\OCP\ITagManager::class, function (Server $c) {
239
+		$this->registerService(\OCP\ITagManager::class, function(Server $c) {
240 240
 			$tagMapper = $c->query('TagMapper');
241 241
 			return new TagManager($tagMapper, $c->getUserSession());
242 242
 		});
243 243
 		$this->registerAlias('TagManager', \OCP\ITagManager::class);
244 244
 
245
-		$this->registerService('SystemTagManagerFactory', function (Server $c) {
245
+		$this->registerService('SystemTagManagerFactory', function(Server $c) {
246 246
 			$config = $c->getConfig();
247 247
 			$factoryClass = $config->getSystemValue('systemtags.managerFactory', '\OC\SystemTag\ManagerFactory');
248 248
 			/** @var \OC\SystemTag\ManagerFactory $factory */
249 249
 			$factory = new $factoryClass($this);
250 250
 			return $factory;
251 251
 		});
252
-		$this->registerService(\OCP\SystemTag\ISystemTagManager::class, function (Server $c) {
252
+		$this->registerService(\OCP\SystemTag\ISystemTagManager::class, function(Server $c) {
253 253
 			return $c->query('SystemTagManagerFactory')->getManager();
254 254
 		});
255 255
 		$this->registerAlias('SystemTagManager', \OCP\SystemTag\ISystemTagManager::class);
256 256
 
257
-		$this->registerService(\OCP\SystemTag\ISystemTagObjectMapper::class, function (Server $c) {
257
+		$this->registerService(\OCP\SystemTag\ISystemTagObjectMapper::class, function(Server $c) {
258 258
 			return $c->query('SystemTagManagerFactory')->getObjectMapper();
259 259
 		});
260
-		$this->registerService('RootFolder', function (Server $c) {
260
+		$this->registerService('RootFolder', function(Server $c) {
261 261
 			$manager = \OC\Files\Filesystem::getMountManager(null);
262 262
 			$view = new View();
263 263
 			$root = new Root(
@@ -278,37 +278,37 @@  discard block
 block discarded – undo
278 278
 		});
279 279
 		$this->registerAlias('SystemTagObjectMapper', \OCP\SystemTag\ISystemTagObjectMapper::class);
280 280
 
281
-		$this->registerService(\OCP\Files\IRootFolder::class, function (Server $c) {
282
-			return new LazyRoot(function () use ($c) {
281
+		$this->registerService(\OCP\Files\IRootFolder::class, function(Server $c) {
282
+			return new LazyRoot(function() use ($c) {
283 283
 				return $c->query('RootFolder');
284 284
 			});
285 285
 		});
286 286
 		$this->registerAlias('LazyRootFolder', \OCP\Files\IRootFolder::class);
287 287
 
288
-		$this->registerService(\OCP\IUserManager::class, function (Server $c) {
288
+		$this->registerService(\OCP\IUserManager::class, function(Server $c) {
289 289
 			$config = $c->getConfig();
290 290
 			return new \OC\User\Manager($config);
291 291
 		});
292 292
 		$this->registerAlias('UserManager', \OCP\IUserManager::class);
293 293
 
294
-		$this->registerService(\OCP\IGroupManager::class, function (Server $c) {
294
+		$this->registerService(\OCP\IGroupManager::class, function(Server $c) {
295 295
 			$groupManager = new \OC\Group\Manager($this->getUserManager(), $this->getLogger());
296
-			$groupManager->listen('\OC\Group', 'preCreate', function ($gid) {
296
+			$groupManager->listen('\OC\Group', 'preCreate', function($gid) {
297 297
 				\OC_Hook::emit('OC_Group', 'pre_createGroup', array('run' => true, 'gid' => $gid));
298 298
 			});
299
-			$groupManager->listen('\OC\Group', 'postCreate', function (\OC\Group\Group $gid) {
299
+			$groupManager->listen('\OC\Group', 'postCreate', function(\OC\Group\Group $gid) {
300 300
 				\OC_Hook::emit('OC_User', 'post_createGroup', array('gid' => $gid->getGID()));
301 301
 			});
302
-			$groupManager->listen('\OC\Group', 'preDelete', function (\OC\Group\Group $group) {
302
+			$groupManager->listen('\OC\Group', 'preDelete', function(\OC\Group\Group $group) {
303 303
 				\OC_Hook::emit('OC_Group', 'pre_deleteGroup', array('run' => true, 'gid' => $group->getGID()));
304 304
 			});
305
-			$groupManager->listen('\OC\Group', 'postDelete', function (\OC\Group\Group $group) {
305
+			$groupManager->listen('\OC\Group', 'postDelete', function(\OC\Group\Group $group) {
306 306
 				\OC_Hook::emit('OC_User', 'post_deleteGroup', array('gid' => $group->getGID()));
307 307
 			});
308
-			$groupManager->listen('\OC\Group', 'preAddUser', function (\OC\Group\Group $group, \OC\User\User $user) {
308
+			$groupManager->listen('\OC\Group', 'preAddUser', function(\OC\Group\Group $group, \OC\User\User $user) {
309 309
 				\OC_Hook::emit('OC_Group', 'pre_addToGroup', array('run' => true, 'uid' => $user->getUID(), 'gid' => $group->getGID()));
310 310
 			});
311
-			$groupManager->listen('\OC\Group', 'postAddUser', function (\OC\Group\Group $group, \OC\User\User $user) {
311
+			$groupManager->listen('\OC\Group', 'postAddUser', function(\OC\Group\Group $group, \OC\User\User $user) {
312 312
 				\OC_Hook::emit('OC_Group', 'post_addToGroup', array('uid' => $user->getUID(), 'gid' => $group->getGID()));
313 313
 				//Minimal fix to keep it backward compatible TODO: clean up all the GroupManager hooks
314 314
 				\OC_Hook::emit('OC_User', 'post_addToGroup', array('uid' => $user->getUID(), 'gid' => $group->getGID()));
@@ -317,7 +317,7 @@  discard block
 block discarded – undo
317 317
 		});
318 318
 		$this->registerAlias('GroupManager', \OCP\IGroupManager::class);
319 319
 
320
-		$this->registerService(Store::class, function (Server $c) {
320
+		$this->registerService(Store::class, function(Server $c) {
321 321
 			$session = $c->getSession();
322 322
 			if (\OC::$server->getSystemConfig()->getValue('installed', false)) {
323 323
 				$tokenProvider = $c->query('OC\Authentication\Token\IProvider');
@@ -328,11 +328,11 @@  discard block
 block discarded – undo
328 328
 			return new Store($session, $logger, $tokenProvider);
329 329
 		});
330 330
 		$this->registerAlias(IStore::class, Store::class);
331
-		$this->registerService('OC\Authentication\Token\DefaultTokenMapper', function (Server $c) {
331
+		$this->registerService('OC\Authentication\Token\DefaultTokenMapper', function(Server $c) {
332 332
 			$dbConnection = $c->getDatabaseConnection();
333 333
 			return new Authentication\Token\DefaultTokenMapper($dbConnection);
334 334
 		});
335
-		$this->registerService('OC\Authentication\Token\DefaultTokenProvider', function (Server $c) {
335
+		$this->registerService('OC\Authentication\Token\DefaultTokenProvider', function(Server $c) {
336 336
 			$mapper = $c->query('OC\Authentication\Token\DefaultTokenMapper');
337 337
 			$crypto = $c->getCrypto();
338 338
 			$config = $c->getConfig();
@@ -342,7 +342,7 @@  discard block
 block discarded – undo
342 342
 		});
343 343
 		$this->registerAlias('OC\Authentication\Token\IProvider', 'OC\Authentication\Token\DefaultTokenProvider');
344 344
 
345
-		$this->registerService(\OCP\IUserSession::class, function (Server $c) {
345
+		$this->registerService(\OCP\IUserSession::class, function(Server $c) {
346 346
 			$manager = $c->getUserManager();
347 347
 			$session = new \OC\Session\Memory('');
348 348
 			$timeFactory = new TimeFactory();
@@ -366,45 +366,45 @@  discard block
 block discarded – undo
366 366
 				$c->getLockdownManager(),
367 367
 				$c->getLogger()
368 368
 			);
369
-			$userSession->listen('\OC\User', 'preCreateUser', function ($uid, $password) {
369
+			$userSession->listen('\OC\User', 'preCreateUser', function($uid, $password) {
370 370
 				\OC_Hook::emit('OC_User', 'pre_createUser', array('run' => true, 'uid' => $uid, 'password' => $password));
371 371
 			});
372
-			$userSession->listen('\OC\User', 'postCreateUser', function ($user, $password) {
372
+			$userSession->listen('\OC\User', 'postCreateUser', function($user, $password) {
373 373
 				/** @var $user \OC\User\User */
374 374
 				\OC_Hook::emit('OC_User', 'post_createUser', array('uid' => $user->getUID(), 'password' => $password));
375 375
 			});
376
-			$userSession->listen('\OC\User', 'preDelete', function ($user) use ($dispatcher) {
376
+			$userSession->listen('\OC\User', 'preDelete', function($user) use ($dispatcher) {
377 377
 				/** @var $user \OC\User\User */
378 378
 				\OC_Hook::emit('OC_User', 'pre_deleteUser', array('run' => true, 'uid' => $user->getUID()));
379 379
 				$dispatcher->dispatch('OCP\IUser::preDelete', new GenericEvent($user));
380 380
 			});
381
-			$userSession->listen('\OC\User', 'postDelete', function ($user) {
381
+			$userSession->listen('\OC\User', 'postDelete', function($user) {
382 382
 				/** @var $user \OC\User\User */
383 383
 				\OC_Hook::emit('OC_User', 'post_deleteUser', array('uid' => $user->getUID()));
384 384
 			});
385
-			$userSession->listen('\OC\User', 'preSetPassword', function ($user, $password, $recoveryPassword) {
385
+			$userSession->listen('\OC\User', 'preSetPassword', function($user, $password, $recoveryPassword) {
386 386
 				/** @var $user \OC\User\User */
387 387
 				\OC_Hook::emit('OC_User', 'pre_setPassword', array('run' => true, 'uid' => $user->getUID(), 'password' => $password, 'recoveryPassword' => $recoveryPassword));
388 388
 			});
389
-			$userSession->listen('\OC\User', 'postSetPassword', function ($user, $password, $recoveryPassword) {
389
+			$userSession->listen('\OC\User', 'postSetPassword', function($user, $password, $recoveryPassword) {
390 390
 				/** @var $user \OC\User\User */
391 391
 				\OC_Hook::emit('OC_User', 'post_setPassword', array('run' => true, 'uid' => $user->getUID(), 'password' => $password, 'recoveryPassword' => $recoveryPassword));
392 392
 			});
393
-			$userSession->listen('\OC\User', 'preLogin', function ($uid, $password) {
393
+			$userSession->listen('\OC\User', 'preLogin', function($uid, $password) {
394 394
 				\OC_Hook::emit('OC_User', 'pre_login', array('run' => true, 'uid' => $uid, 'password' => $password));
395 395
 			});
396
-			$userSession->listen('\OC\User', 'postLogin', function ($user, $password) {
396
+			$userSession->listen('\OC\User', 'postLogin', function($user, $password) {
397 397
 				/** @var $user \OC\User\User */
398 398
 				\OC_Hook::emit('OC_User', 'post_login', array('run' => true, 'uid' => $user->getUID(), 'password' => $password));
399 399
 			});
400
-			$userSession->listen('\OC\User', 'postRememberedLogin', function ($user, $password) {
400
+			$userSession->listen('\OC\User', 'postRememberedLogin', function($user, $password) {
401 401
 				/** @var $user \OC\User\User */
402 402
 				\OC_Hook::emit('OC_User', 'post_login', array('run' => true, 'uid' => $user->getUID(), 'password' => $password));
403 403
 			});
404
-			$userSession->listen('\OC\User', 'logout', function () {
404
+			$userSession->listen('\OC\User', 'logout', function() {
405 405
 				\OC_Hook::emit('OC_User', 'logout', array());
406 406
 			});
407
-			$userSession->listen('\OC\User', 'changeUser', function ($user, $feature, $value, $oldValue) use ($dispatcher) {
407
+			$userSession->listen('\OC\User', 'changeUser', function($user, $feature, $value, $oldValue) use ($dispatcher) {
408 408
 				/** @var $user \OC\User\User */
409 409
 				\OC_Hook::emit('OC_User', 'changeUser', array('run' => true, 'user' => $user, 'feature' => $feature, 'value' => $value, 'old_value' => $oldValue));
410 410
 				$dispatcher->dispatch('OCP\IUser::changeUser', new GenericEvent($user, ['feature' => $feature, 'oldValue' => $oldValue, 'value' => $value]));
@@ -413,7 +413,7 @@  discard block
 block discarded – undo
413 413
 		});
414 414
 		$this->registerAlias('UserSession', \OCP\IUserSession::class);
415 415
 
416
-		$this->registerService(\OC\Authentication\TwoFactorAuth\Manager::class, function (Server $c) {
416
+		$this->registerService(\OC\Authentication\TwoFactorAuth\Manager::class, function(Server $c) {
417 417
 			return new \OC\Authentication\TwoFactorAuth\Manager(
418 418
 				$c->getAppManager(),
419 419
 				$c->getSession(),
@@ -428,7 +428,7 @@  discard block
 block discarded – undo
428 428
 		$this->registerAlias(\OCP\INavigationManager::class, \OC\NavigationManager::class);
429 429
 		$this->registerAlias('NavigationManager', \OCP\INavigationManager::class);
430 430
 
431
-		$this->registerService(\OC\AllConfig::class, function (Server $c) {
431
+		$this->registerService(\OC\AllConfig::class, function(Server $c) {
432 432
 			return new \OC\AllConfig(
433 433
 				$c->getSystemConfig()
434 434
 			);
@@ -436,17 +436,17 @@  discard block
 block discarded – undo
436 436
 		$this->registerAlias('AllConfig', \OC\AllConfig::class);
437 437
 		$this->registerAlias(\OCP\IConfig::class, \OC\AllConfig::class);
438 438
 
439
-		$this->registerService('SystemConfig', function ($c) use ($config) {
439
+		$this->registerService('SystemConfig', function($c) use ($config) {
440 440
 			return new \OC\SystemConfig($config);
441 441
 		});
442 442
 
443
-		$this->registerService(\OC\AppConfig::class, function (Server $c) {
443
+		$this->registerService(\OC\AppConfig::class, function(Server $c) {
444 444
 			return new \OC\AppConfig($c->getDatabaseConnection());
445 445
 		});
446 446
 		$this->registerAlias('AppConfig', \OC\AppConfig::class);
447 447
 		$this->registerAlias(\OCP\IAppConfig::class, \OC\AppConfig::class);
448 448
 
449
-		$this->registerService(\OCP\L10N\IFactory::class, function (Server $c) {
449
+		$this->registerService(\OCP\L10N\IFactory::class, function(Server $c) {
450 450
 			return new \OC\L10N\Factory(
451 451
 				$c->getConfig(),
452 452
 				$c->getRequest(),
@@ -456,7 +456,7 @@  discard block
 block discarded – undo
456 456
 		});
457 457
 		$this->registerAlias('L10NFactory', \OCP\L10N\IFactory::class);
458 458
 
459
-		$this->registerService(\OCP\IURLGenerator::class, function (Server $c) {
459
+		$this->registerService(\OCP\IURLGenerator::class, function(Server $c) {
460 460
 			$config = $c->getConfig();
461 461
 			$cacheFactory = $c->getMemCacheFactory();
462 462
 			$request = $c->getRequest();
@@ -468,18 +468,18 @@  discard block
 block discarded – undo
468 468
 		});
469 469
 		$this->registerAlias('URLGenerator', \OCP\IURLGenerator::class);
470 470
 
471
-		$this->registerService('AppHelper', function ($c) {
471
+		$this->registerService('AppHelper', function($c) {
472 472
 			return new \OC\AppHelper();
473 473
 		});
474 474
 		$this->registerAlias('AppFetcher', AppFetcher::class);
475 475
 		$this->registerAlias('CategoryFetcher', CategoryFetcher::class);
476 476
 
477
-		$this->registerService(\OCP\ICache::class, function ($c) {
477
+		$this->registerService(\OCP\ICache::class, function($c) {
478 478
 			return new Cache\File();
479 479
 		});
480 480
 		$this->registerAlias('UserCache', \OCP\ICache::class);
481 481
 
482
-		$this->registerService(Factory::class, function (Server $c) {
482
+		$this->registerService(Factory::class, function(Server $c) {
483 483
 
484 484
 			$arrayCacheFactory = new \OC\Memcache\Factory('', $c->getLogger(),
485 485
 				'\\OC\\Memcache\\ArrayCache',
@@ -496,7 +496,7 @@  discard block
 block discarded – undo
496 496
 				$version = implode(',', $v);
497 497
 				$instanceId = \OC_Util::getInstanceId();
498 498
 				$path = \OC::$SERVERROOT;
499
-				$prefix = md5($instanceId . '-' . $version . '-' . $path);
499
+				$prefix = md5($instanceId.'-'.$version.'-'.$path);
500 500
 				return new \OC\Memcache\Factory($prefix, $c->getLogger(),
501 501
 					$config->getSystemValue('memcache.local', null),
502 502
 					$config->getSystemValue('memcache.distributed', null),
@@ -509,12 +509,12 @@  discard block
 block discarded – undo
509 509
 		$this->registerAlias('MemCacheFactory', Factory::class);
510 510
 		$this->registerAlias(ICacheFactory::class, Factory::class);
511 511
 
512
-		$this->registerService('RedisFactory', function (Server $c) {
512
+		$this->registerService('RedisFactory', function(Server $c) {
513 513
 			$systemConfig = $c->getSystemConfig();
514 514
 			return new RedisFactory($systemConfig);
515 515
 		});
516 516
 
517
-		$this->registerService(\OCP\Activity\IManager::class, function (Server $c) {
517
+		$this->registerService(\OCP\Activity\IManager::class, function(Server $c) {
518 518
 			return new \OC\Activity\Manager(
519 519
 				$c->getRequest(),
520 520
 				$c->getUserSession(),
@@ -524,14 +524,14 @@  discard block
 block discarded – undo
524 524
 		});
525 525
 		$this->registerAlias('ActivityManager', \OCP\Activity\IManager::class);
526 526
 
527
-		$this->registerService(\OCP\Activity\IEventMerger::class, function (Server $c) {
527
+		$this->registerService(\OCP\Activity\IEventMerger::class, function(Server $c) {
528 528
 			return new \OC\Activity\EventMerger(
529 529
 				$c->getL10N('lib')
530 530
 			);
531 531
 		});
532 532
 		$this->registerAlias(IValidator::class, Validator::class);
533 533
 
534
-		$this->registerService(\OCP\IAvatarManager::class, function (Server $c) {
534
+		$this->registerService(\OCP\IAvatarManager::class, function(Server $c) {
535 535
 			return new AvatarManager(
536 536
 				$c->getUserManager(),
537 537
 				$c->getAppDataDir('avatar'),
@@ -544,7 +544,7 @@  discard block
 block discarded – undo
544 544
 
545 545
 		$this->registerAlias(\OCP\Support\CrashReport\IRegistry::class, \OC\Support\CrashReport\Registry::class);
546 546
 
547
-		$this->registerService(\OCP\ILogger::class, function (Server $c) {
547
+		$this->registerService(\OCP\ILogger::class, function(Server $c) {
548 548
 			$logType = $c->query('AllConfig')->getSystemValue('log_type', 'file');
549 549
 			$logger = Log::getLogClass($logType);
550 550
 			call_user_func(array($logger, 'init'));
@@ -555,7 +555,7 @@  discard block
 block discarded – undo
555 555
 		});
556 556
 		$this->registerAlias('Logger', \OCP\ILogger::class);
557 557
 
558
-		$this->registerService(\OCP\BackgroundJob\IJobList::class, function (Server $c) {
558
+		$this->registerService(\OCP\BackgroundJob\IJobList::class, function(Server $c) {
559 559
 			$config = $c->getConfig();
560 560
 			return new \OC\BackgroundJob\JobList(
561 561
 				$c->getDatabaseConnection(),
@@ -565,7 +565,7 @@  discard block
 block discarded – undo
565 565
 		});
566 566
 		$this->registerAlias('JobList', \OCP\BackgroundJob\IJobList::class);
567 567
 
568
-		$this->registerService(\OCP\Route\IRouter::class, function (Server $c) {
568
+		$this->registerService(\OCP\Route\IRouter::class, function(Server $c) {
569 569
 			$cacheFactory = $c->getMemCacheFactory();
570 570
 			$logger = $c->getLogger();
571 571
 			if ($cacheFactory->isAvailableLowLatency()) {
@@ -577,12 +577,12 @@  discard block
 block discarded – undo
577 577
 		});
578 578
 		$this->registerAlias('Router', \OCP\Route\IRouter::class);
579 579
 
580
-		$this->registerService(\OCP\ISearch::class, function ($c) {
580
+		$this->registerService(\OCP\ISearch::class, function($c) {
581 581
 			return new Search();
582 582
 		});
583 583
 		$this->registerAlias('Search', \OCP\ISearch::class);
584 584
 
585
-		$this->registerService(\OC\Security\RateLimiting\Limiter::class, function ($c) {
585
+		$this->registerService(\OC\Security\RateLimiting\Limiter::class, function($c) {
586 586
 			return new \OC\Security\RateLimiting\Limiter(
587 587
 				$this->getUserSession(),
588 588
 				$this->getRequest(),
@@ -590,34 +590,34 @@  discard block
 block discarded – undo
590 590
 				$c->query(\OC\Security\RateLimiting\Backend\IBackend::class)
591 591
 			);
592 592
 		});
593
-		$this->registerService(\OC\Security\RateLimiting\Backend\IBackend::class, function ($c) {
593
+		$this->registerService(\OC\Security\RateLimiting\Backend\IBackend::class, function($c) {
594 594
 			return new \OC\Security\RateLimiting\Backend\MemoryCache(
595 595
 				$this->getMemCacheFactory(),
596 596
 				new \OC\AppFramework\Utility\TimeFactory()
597 597
 			);
598 598
 		});
599 599
 
600
-		$this->registerService(\OCP\Security\ISecureRandom::class, function ($c) {
600
+		$this->registerService(\OCP\Security\ISecureRandom::class, function($c) {
601 601
 			return new SecureRandom();
602 602
 		});
603 603
 		$this->registerAlias('SecureRandom', \OCP\Security\ISecureRandom::class);
604 604
 
605
-		$this->registerService(\OCP\Security\ICrypto::class, function (Server $c) {
605
+		$this->registerService(\OCP\Security\ICrypto::class, function(Server $c) {
606 606
 			return new Crypto($c->getConfig(), $c->getSecureRandom());
607 607
 		});
608 608
 		$this->registerAlias('Crypto', \OCP\Security\ICrypto::class);
609 609
 
610
-		$this->registerService(\OCP\Security\IHasher::class, function (Server $c) {
610
+		$this->registerService(\OCP\Security\IHasher::class, function(Server $c) {
611 611
 			return new Hasher($c->getConfig());
612 612
 		});
613 613
 		$this->registerAlias('Hasher', \OCP\Security\IHasher::class);
614 614
 
615
-		$this->registerService(\OCP\Security\ICredentialsManager::class, function (Server $c) {
615
+		$this->registerService(\OCP\Security\ICredentialsManager::class, function(Server $c) {
616 616
 			return new CredentialsManager($c->getCrypto(), $c->getDatabaseConnection());
617 617
 		});
618 618
 		$this->registerAlias('CredentialsManager', \OCP\Security\ICredentialsManager::class);
619 619
 
620
-		$this->registerService(IDBConnection::class, function (Server $c) {
620
+		$this->registerService(IDBConnection::class, function(Server $c) {
621 621
 			$systemConfig = $c->getSystemConfig();
622 622
 			$factory = new \OC\DB\ConnectionFactory($systemConfig);
623 623
 			$type = $systemConfig->getValue('dbtype', 'sqlite');
@@ -631,7 +631,7 @@  discard block
 block discarded – undo
631 631
 		});
632 632
 		$this->registerAlias('DatabaseConnection', IDBConnection::class);
633 633
 
634
-		$this->registerService('HTTPHelper', function (Server $c) {
634
+		$this->registerService('HTTPHelper', function(Server $c) {
635 635
 			$config = $c->getConfig();
636 636
 			return new HTTPHelper(
637 637
 				$config,
@@ -639,7 +639,7 @@  discard block
 block discarded – undo
639 639
 			);
640 640
 		});
641 641
 
642
-		$this->registerService(\OCP\Http\Client\IClientService::class, function (Server $c) {
642
+		$this->registerService(\OCP\Http\Client\IClientService::class, function(Server $c) {
643 643
 			$user = \OC_User::getUser();
644 644
 			$uid = $user ? $user : null;
645 645
 			return new ClientService(
@@ -654,7 +654,7 @@  discard block
 block discarded – undo
654 654
 			);
655 655
 		});
656 656
 		$this->registerAlias('HttpClientService', \OCP\Http\Client\IClientService::class);
657
-		$this->registerService(\OCP\Diagnostics\IEventLogger::class, function (Server $c) {
657
+		$this->registerService(\OCP\Diagnostics\IEventLogger::class, function(Server $c) {
658 658
 			$eventLogger = new EventLogger();
659 659
 			if ($c->getSystemConfig()->getValue('debug', false)) {
660 660
 				// In debug mode, module is being activated by default
@@ -664,7 +664,7 @@  discard block
 block discarded – undo
664 664
 		});
665 665
 		$this->registerAlias('EventLogger', \OCP\Diagnostics\IEventLogger::class);
666 666
 
667
-		$this->registerService(\OCP\Diagnostics\IQueryLogger::class, function (Server $c) {
667
+		$this->registerService(\OCP\Diagnostics\IQueryLogger::class, function(Server $c) {
668 668
 			$queryLogger = new QueryLogger();
669 669
 			if ($c->getSystemConfig()->getValue('debug', false)) {
670 670
 				// In debug mode, module is being activated by default
@@ -674,7 +674,7 @@  discard block
 block discarded – undo
674 674
 		});
675 675
 		$this->registerAlias('QueryLogger', \OCP\Diagnostics\IQueryLogger::class);
676 676
 
677
-		$this->registerService(TempManager::class, function (Server $c) {
677
+		$this->registerService(TempManager::class, function(Server $c) {
678 678
 			return new TempManager(
679 679
 				$c->getLogger(),
680 680
 				$c->getConfig()
@@ -683,7 +683,7 @@  discard block
 block discarded – undo
683 683
 		$this->registerAlias('TempManager', TempManager::class);
684 684
 		$this->registerAlias(ITempManager::class, TempManager::class);
685 685
 
686
-		$this->registerService(AppManager::class, function (Server $c) {
686
+		$this->registerService(AppManager::class, function(Server $c) {
687 687
 			return new \OC\App\AppManager(
688 688
 				$c->getUserSession(),
689 689
 				$c->getAppConfig(),
@@ -695,7 +695,7 @@  discard block
 block discarded – undo
695 695
 		$this->registerAlias('AppManager', AppManager::class);
696 696
 		$this->registerAlias(IAppManager::class, AppManager::class);
697 697
 
698
-		$this->registerService(\OCP\IDateTimeZone::class, function (Server $c) {
698
+		$this->registerService(\OCP\IDateTimeZone::class, function(Server $c) {
699 699
 			return new DateTimeZone(
700 700
 				$c->getConfig(),
701 701
 				$c->getSession()
@@ -703,7 +703,7 @@  discard block
 block discarded – undo
703 703
 		});
704 704
 		$this->registerAlias('DateTimeZone', \OCP\IDateTimeZone::class);
705 705
 
706
-		$this->registerService(\OCP\IDateTimeFormatter::class, function (Server $c) {
706
+		$this->registerService(\OCP\IDateTimeFormatter::class, function(Server $c) {
707 707
 			$language = $c->getConfig()->getUserValue($c->getSession()->get('user_id'), 'core', 'lang', null);
708 708
 
709 709
 			return new DateTimeFormatter(
@@ -713,7 +713,7 @@  discard block
 block discarded – undo
713 713
 		});
714 714
 		$this->registerAlias('DateTimeFormatter', \OCP\IDateTimeFormatter::class);
715 715
 
716
-		$this->registerService(\OCP\Files\Config\IUserMountCache::class, function (Server $c) {
716
+		$this->registerService(\OCP\Files\Config\IUserMountCache::class, function(Server $c) {
717 717
 			$mountCache = new UserMountCache($c->getDatabaseConnection(), $c->getUserManager(), $c->getLogger());
718 718
 			$listener = new UserMountCacheListener($mountCache);
719 719
 			$listener->listen($c->getUserManager());
@@ -721,7 +721,7 @@  discard block
 block discarded – undo
721 721
 		});
722 722
 		$this->registerAlias('UserMountCache', \OCP\Files\Config\IUserMountCache::class);
723 723
 
724
-		$this->registerService(\OCP\Files\Config\IMountProviderCollection::class, function (Server $c) {
724
+		$this->registerService(\OCP\Files\Config\IMountProviderCollection::class, function(Server $c) {
725 725
 			$loader = \OC\Files\Filesystem::getLoader();
726 726
 			$mountCache = $c->query('UserMountCache');
727 727
 			$manager = new \OC\Files\Config\MountProviderCollection($loader, $mountCache);
@@ -737,10 +737,10 @@  discard block
 block discarded – undo
737 737
 		});
738 738
 		$this->registerAlias('MountConfigManager', \OCP\Files\Config\IMountProviderCollection::class);
739 739
 
740
-		$this->registerService('IniWrapper', function ($c) {
740
+		$this->registerService('IniWrapper', function($c) {
741 741
 			return new IniGetWrapper();
742 742
 		});
743
-		$this->registerService('AsyncCommandBus', function (Server $c) {
743
+		$this->registerService('AsyncCommandBus', function(Server $c) {
744 744
 			$busClass = $c->getConfig()->getSystemValue('commandbus');
745 745
 			if ($busClass) {
746 746
 				list($app, $class) = explode('::', $busClass, 2);
@@ -755,10 +755,10 @@  discard block
 block discarded – undo
755 755
 				return new CronBus($jobList);
756 756
 			}
757 757
 		});
758
-		$this->registerService('TrustedDomainHelper', function ($c) {
758
+		$this->registerService('TrustedDomainHelper', function($c) {
759 759
 			return new TrustedDomainHelper($this->getConfig());
760 760
 		});
761
-		$this->registerService(Throttler::class, function (Server $c) {
761
+		$this->registerService(Throttler::class, function(Server $c) {
762 762
 			return new Throttler(
763 763
 				$c->getDatabaseConnection(),
764 764
 				new TimeFactory(),
@@ -767,7 +767,7 @@  discard block
 block discarded – undo
767 767
 			);
768 768
 		});
769 769
 		$this->registerAlias('Throttler', Throttler::class);
770
-		$this->registerService('IntegrityCodeChecker', function (Server $c) {
770
+		$this->registerService('IntegrityCodeChecker', function(Server $c) {
771 771
 			// IConfig and IAppManager requires a working database. This code
772 772
 			// might however be called when ownCloud is not yet setup.
773 773
 			if (\OC::$server->getSystemConfig()->getValue('installed', false)) {
@@ -788,7 +788,7 @@  discard block
 block discarded – undo
788 788
 				$c->getTempManager()
789 789
 			);
790 790
 		});
791
-		$this->registerService(\OCP\IRequest::class, function ($c) {
791
+		$this->registerService(\OCP\IRequest::class, function($c) {
792 792
 			if (isset($this['urlParams'])) {
793 793
 				$urlParams = $this['urlParams'];
794 794
 			} else {
@@ -824,7 +824,7 @@  discard block
 block discarded – undo
824 824
 		});
825 825
 		$this->registerAlias('Request', \OCP\IRequest::class);
826 826
 
827
-		$this->registerService(\OCP\Mail\IMailer::class, function (Server $c) {
827
+		$this->registerService(\OCP\Mail\IMailer::class, function(Server $c) {
828 828
 			return new Mailer(
829 829
 				$c->getConfig(),
830 830
 				$c->getLogger(),
@@ -835,7 +835,7 @@  discard block
 block discarded – undo
835 835
 		});
836 836
 		$this->registerAlias('Mailer', \OCP\Mail\IMailer::class);
837 837
 
838
-		$this->registerService('LDAPProvider', function (Server $c) {
838
+		$this->registerService('LDAPProvider', function(Server $c) {
839 839
 			$config = $c->getConfig();
840 840
 			$factoryClass = $config->getSystemValue('ldapProviderFactory', null);
841 841
 			if (is_null($factoryClass)) {
@@ -845,7 +845,7 @@  discard block
 block discarded – undo
845 845
 			$factory = new $factoryClass($this);
846 846
 			return $factory->getLDAPProvider();
847 847
 		});
848
-		$this->registerService(ILockingProvider::class, function (Server $c) {
848
+		$this->registerService(ILockingProvider::class, function(Server $c) {
849 849
 			$ini = $c->getIniWrapper();
850 850
 			$config = $c->getConfig();
851 851
 			$ttl = $config->getSystemValue('filelocking.ttl', max(3600, $ini->getNumeric('max_execution_time')));
@@ -862,49 +862,49 @@  discard block
 block discarded – undo
862 862
 		});
863 863
 		$this->registerAlias('LockingProvider', ILockingProvider::class);
864 864
 
865
-		$this->registerService(\OCP\Files\Mount\IMountManager::class, function () {
865
+		$this->registerService(\OCP\Files\Mount\IMountManager::class, function() {
866 866
 			return new \OC\Files\Mount\Manager();
867 867
 		});
868 868
 		$this->registerAlias('MountManager', \OCP\Files\Mount\IMountManager::class);
869 869
 
870
-		$this->registerService(\OCP\Files\IMimeTypeDetector::class, function (Server $c) {
870
+		$this->registerService(\OCP\Files\IMimeTypeDetector::class, function(Server $c) {
871 871
 			return new \OC\Files\Type\Detection(
872 872
 				$c->getURLGenerator(),
873 873
 				\OC::$configDir,
874
-				\OC::$SERVERROOT . '/resources/config/'
874
+				\OC::$SERVERROOT.'/resources/config/'
875 875
 			);
876 876
 		});
877 877
 		$this->registerAlias('MimeTypeDetector', \OCP\Files\IMimeTypeDetector::class);
878 878
 
879
-		$this->registerService(\OCP\Files\IMimeTypeLoader::class, function (Server $c) {
879
+		$this->registerService(\OCP\Files\IMimeTypeLoader::class, function(Server $c) {
880 880
 			return new \OC\Files\Type\Loader(
881 881
 				$c->getDatabaseConnection()
882 882
 			);
883 883
 		});
884 884
 		$this->registerAlias('MimeTypeLoader', \OCP\Files\IMimeTypeLoader::class);
885
-		$this->registerService(BundleFetcher::class, function () {
885
+		$this->registerService(BundleFetcher::class, function() {
886 886
 			return new BundleFetcher($this->getL10N('lib'));
887 887
 		});
888
-		$this->registerService(\OCP\Notification\IManager::class, function (Server $c) {
888
+		$this->registerService(\OCP\Notification\IManager::class, function(Server $c) {
889 889
 			return new Manager(
890 890
 				$c->query(IValidator::class)
891 891
 			);
892 892
 		});
893 893
 		$this->registerAlias('NotificationManager', \OCP\Notification\IManager::class);
894 894
 
895
-		$this->registerService(\OC\CapabilitiesManager::class, function (Server $c) {
895
+		$this->registerService(\OC\CapabilitiesManager::class, function(Server $c) {
896 896
 			$manager = new \OC\CapabilitiesManager($c->getLogger());
897
-			$manager->registerCapability(function () use ($c) {
897
+			$manager->registerCapability(function() use ($c) {
898 898
 				return new \OC\OCS\CoreCapabilities($c->getConfig());
899 899
 			});
900
-			$manager->registerCapability(function () use ($c) {
900
+			$manager->registerCapability(function() use ($c) {
901 901
 				return $c->query(\OC\Security\Bruteforce\Capabilities::class);
902 902
 			});
903 903
 			return $manager;
904 904
 		});
905 905
 		$this->registerAlias('CapabilitiesManager', \OC\CapabilitiesManager::class);
906 906
 
907
-		$this->registerService(\OCP\Comments\ICommentsManager::class, function (Server $c) {
907
+		$this->registerService(\OCP\Comments\ICommentsManager::class, function(Server $c) {
908 908
 			$config = $c->getConfig();
909 909
 			$factoryClass = $config->getSystemValue('comments.managerFactory', '\OC\Comments\ManagerFactory');
910 910
 			/** @var \OCP\Comments\ICommentsManagerFactory $factory */
@@ -914,7 +914,7 @@  discard block
 block discarded – undo
914 914
 			$manager->registerDisplayNameResolver('user', function($id) use ($c) {
915 915
 				$manager = $c->getUserManager();
916 916
 				$user = $manager->get($id);
917
-				if(is_null($user)) {
917
+				if (is_null($user)) {
918 918
 					$l = $c->getL10N('core');
919 919
 					$displayName = $l->t('Unknown user');
920 920
 				} else {
@@ -927,7 +927,7 @@  discard block
 block discarded – undo
927 927
 		});
928 928
 		$this->registerAlias('CommentsManager', \OCP\Comments\ICommentsManager::class);
929 929
 
930
-		$this->registerService('ThemingDefaults', function (Server $c) {
930
+		$this->registerService('ThemingDefaults', function(Server $c) {
931 931
 			/*
932 932
 			 * Dark magic for autoloader.
933 933
 			 * If we do a class_exists it will try to load the class which will
@@ -954,7 +954,7 @@  discard block
 block discarded – undo
954 954
 			}
955 955
 			return new \OC_Defaults();
956 956
 		});
957
-		$this->registerService(SCSSCacher::class, function (Server $c) {
957
+		$this->registerService(SCSSCacher::class, function(Server $c) {
958 958
 			/** @var Factory $cacheFactory */
959 959
 			$cacheFactory = $c->query(Factory::class);
960 960
 			return new SCSSCacher(
@@ -967,7 +967,7 @@  discard block
 block discarded – undo
967 967
 				$this->getMemCacheFactory()
968 968
 			);
969 969
 		});
970
-		$this->registerService(JSCombiner::class, function (Server $c) {
970
+		$this->registerService(JSCombiner::class, function(Server $c) {
971 971
 			/** @var Factory $cacheFactory */
972 972
 			$cacheFactory = $c->query(Factory::class);
973 973
 			return new JSCombiner(
@@ -978,13 +978,13 @@  discard block
 block discarded – undo
978 978
 				$c->getLogger()
979 979
 			);
980 980
 		});
981
-		$this->registerService(EventDispatcher::class, function () {
981
+		$this->registerService(EventDispatcher::class, function() {
982 982
 			return new EventDispatcher();
983 983
 		});
984 984
 		$this->registerAlias('EventDispatcher', EventDispatcher::class);
985 985
 		$this->registerAlias(EventDispatcherInterface::class, EventDispatcher::class);
986 986
 
987
-		$this->registerService('CryptoWrapper', function (Server $c) {
987
+		$this->registerService('CryptoWrapper', function(Server $c) {
988 988
 			// FIXME: Instantiiated here due to cyclic dependency
989 989
 			$request = new Request(
990 990
 				[
@@ -1009,7 +1009,7 @@  discard block
 block discarded – undo
1009 1009
 				$request
1010 1010
 			);
1011 1011
 		});
1012
-		$this->registerService('CsrfTokenManager', function (Server $c) {
1012
+		$this->registerService('CsrfTokenManager', function(Server $c) {
1013 1013
 			$tokenGenerator = new CsrfTokenGenerator($c->getSecureRandom());
1014 1014
 
1015 1015
 			return new CsrfTokenManager(
@@ -1017,22 +1017,22 @@  discard block
 block discarded – undo
1017 1017
 				$c->query(SessionStorage::class)
1018 1018
 			);
1019 1019
 		});
1020
-		$this->registerService(SessionStorage::class, function (Server $c) {
1020
+		$this->registerService(SessionStorage::class, function(Server $c) {
1021 1021
 			return new SessionStorage($c->getSession());
1022 1022
 		});
1023
-		$this->registerService(\OCP\Security\IContentSecurityPolicyManager::class, function (Server $c) {
1023
+		$this->registerService(\OCP\Security\IContentSecurityPolicyManager::class, function(Server $c) {
1024 1024
 			return new ContentSecurityPolicyManager();
1025 1025
 		});
1026 1026
 		$this->registerAlias('ContentSecurityPolicyManager', \OCP\Security\IContentSecurityPolicyManager::class);
1027 1027
 
1028
-		$this->registerService('ContentSecurityPolicyNonceManager', function (Server $c) {
1028
+		$this->registerService('ContentSecurityPolicyNonceManager', function(Server $c) {
1029 1029
 			return new ContentSecurityPolicyNonceManager(
1030 1030
 				$c->getCsrfTokenManager(),
1031 1031
 				$c->getRequest()
1032 1032
 			);
1033 1033
 		});
1034 1034
 
1035
-		$this->registerService(\OCP\Share\IManager::class, function (Server $c) {
1035
+		$this->registerService(\OCP\Share\IManager::class, function(Server $c) {
1036 1036
 			$config = $c->getConfig();
1037 1037
 			$factoryClass = $config->getSystemValue('sharing.managerFactory', '\OC\Share20\ProviderFactory');
1038 1038
 			/** @var \OCP\Share\IProviderFactory $factory */
@@ -1075,7 +1075,7 @@  discard block
 block discarded – undo
1075 1075
 
1076 1076
 		$this->registerAlias(\OCP\Collaboration\AutoComplete\IManager::class, \OC\Collaboration\AutoComplete\Manager::class);
1077 1077
 
1078
-		$this->registerService('SettingsManager', function (Server $c) {
1078
+		$this->registerService('SettingsManager', function(Server $c) {
1079 1079
 			$manager = new \OC\Settings\Manager(
1080 1080
 				$c->getLogger(),
1081 1081
 				$c->getDatabaseConnection(),
@@ -1095,24 +1095,24 @@  discard block
 block discarded – undo
1095 1095
 			);
1096 1096
 			return $manager;
1097 1097
 		});
1098
-		$this->registerService(\OC\Files\AppData\Factory::class, function (Server $c) {
1098
+		$this->registerService(\OC\Files\AppData\Factory::class, function(Server $c) {
1099 1099
 			return new \OC\Files\AppData\Factory(
1100 1100
 				$c->getRootFolder(),
1101 1101
 				$c->getSystemConfig()
1102 1102
 			);
1103 1103
 		});
1104 1104
 
1105
-		$this->registerService('LockdownManager', function (Server $c) {
1106
-			return new LockdownManager(function () use ($c) {
1105
+		$this->registerService('LockdownManager', function(Server $c) {
1106
+			return new LockdownManager(function() use ($c) {
1107 1107
 				return $c->getSession();
1108 1108
 			});
1109 1109
 		});
1110 1110
 
1111
-		$this->registerService(\OCP\OCS\IDiscoveryService::class, function (Server $c) {
1111
+		$this->registerService(\OCP\OCS\IDiscoveryService::class, function(Server $c) {
1112 1112
 			return new DiscoveryService($c->getMemCacheFactory(), $c->getHTTPClientService());
1113 1113
 		});
1114 1114
 
1115
-		$this->registerService(ICloudIdManager::class, function (Server $c) {
1115
+		$this->registerService(ICloudIdManager::class, function(Server $c) {
1116 1116
 			return new CloudIdManager();
1117 1117
 		});
1118 1118
 
@@ -1122,18 +1122,18 @@  discard block
 block discarded – undo
1122 1122
 		$this->registerAlias(\OCP\AppFramework\Utility\ITimeFactory::class, \OC\AppFramework\Utility\TimeFactory::class);
1123 1123
 		$this->registerAlias('TimeFactory', \OCP\AppFramework\Utility\ITimeFactory::class);
1124 1124
 
1125
-		$this->registerService(Defaults::class, function (Server $c) {
1125
+		$this->registerService(Defaults::class, function(Server $c) {
1126 1126
 			return new Defaults(
1127 1127
 				$c->getThemingDefaults()
1128 1128
 			);
1129 1129
 		});
1130 1130
 		$this->registerAlias('Defaults', \OCP\Defaults::class);
1131 1131
 
1132
-		$this->registerService(\OCP\ISession::class, function (SimpleContainer $c) {
1132
+		$this->registerService(\OCP\ISession::class, function(SimpleContainer $c) {
1133 1133
 			return $c->query(\OCP\IUserSession::class)->getSession();
1134 1134
 		});
1135 1135
 
1136
-		$this->registerService(IShareHelper::class, function (Server $c) {
1136
+		$this->registerService(IShareHelper::class, function(Server $c) {
1137 1137
 			return new ShareHelper(
1138 1138
 				$c->query(\OCP\Share\IManager::class)
1139 1139
 			);
@@ -1195,11 +1195,11 @@  discard block
 block discarded – undo
1195 1195
 				// no avatar to remove
1196 1196
 			} catch (\Exception $e) {
1197 1197
 				// Ignore exceptions
1198
-				$logger->info('Could not cleanup avatar of ' . $user->getUID());
1198
+				$logger->info('Could not cleanup avatar of '.$user->getUID());
1199 1199
 			}
1200 1200
 		});
1201 1201
 
1202
-		$dispatcher->addListener('OCP\IUser::changeUser', function (GenericEvent $e) {
1202
+		$dispatcher->addListener('OCP\IUser::changeUser', function(GenericEvent $e) {
1203 1203
 			$manager = $this->getAvatarManager();
1204 1204
 			/** @var IUser $user */
1205 1205
 			$user = $e->getSubject();
@@ -1350,7 +1350,7 @@  discard block
 block discarded – undo
1350 1350
 	 * @deprecated since 9.2.0 use IAppData
1351 1351
 	 */
1352 1352
 	public function getAppFolder() {
1353
-		$dir = '/' . \OC_App::getCurrentApp();
1353
+		$dir = '/'.\OC_App::getCurrentApp();
1354 1354
 		$root = $this->getRootFolder();
1355 1355
 		if (!$root->nodeExists($dir)) {
1356 1356
 			$folder = $root->newFolder($dir);
@@ -1934,7 +1934,7 @@  discard block
 block discarded – undo
1934 1934
 	/**
1935 1935
 	 * @return \OCP\Collaboration\AutoComplete\IManager
1936 1936
 	 */
1937
-	public function getAutoCompleteManager(){
1937
+	public function getAutoCompleteManager() {
1938 1938
 		return $this->query(IManager::class);
1939 1939
 	}
1940 1940
 
Please login to merge, or discard this patch.
apps/dav/lib/CalDAV/Publishing/PublishPlugin.php 3 patches
Doc Comments   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -134,7 +134,7 @@
 block discarded – undo
134 134
 	 * @param RequestInterface $request
135 135
 	 * @param ResponseInterface $response
136 136
 	 *
137
-	 * @return void|bool
137
+	 * @return null|false
138 138
 	 */
139 139
 	public function httpPost(RequestInterface $request, ResponseInterface $response) {
140 140
 		$path = $request->getPath();
Please login to merge, or discard this patch.
Indentation   +189 added lines, -189 removed lines patch added patch discarded remove patch
@@ -34,194 +34,194 @@
 block discarded – undo
34 34
 use OCP\IConfig;
35 35
 
36 36
 class PublishPlugin extends ServerPlugin {
37
-	const NS_CALENDARSERVER = 'http://calendarserver.org/ns/';
38
-
39
-	/**
40
-	 * Reference to SabreDAV server object.
41
-	 *
42
-	 * @var \Sabre\DAV\Server
43
-	 */
44
-	protected $server;
45
-
46
-	/**
47
-	 * Config instance to get instance secret.
48
-	 *
49
-	 * @var IConfig
50
-	 */
51
-	protected $config;
52
-
53
-	/**
54
-	 * URL Generator for absolute URLs.
55
-	 *
56
-	 * @var IURLGenerator
57
-	 */
58
-	protected $urlGenerator;
59
-
60
-	/**
61
-	 * PublishPlugin constructor.
62
-	 *
63
-	 * @param IConfig $config
64
-	 * @param IURLGenerator $urlGenerator
65
-	 */
66
-	public function __construct(IConfig $config, IURLGenerator $urlGenerator) {
67
-		$this->config = $config;
68
-		$this->urlGenerator = $urlGenerator;
69
-	}
70
-
71
-	/**
72
-	 * This method should return a list of server-features.
73
-	 *
74
-	 * This is for example 'versioning' and is added to the DAV: header
75
-	 * in an OPTIONS response.
76
-	 *
77
-	 * @return string[]
78
-	 */
79
-	public function getFeatures() {
80
-		// May have to be changed to be detected
81
-		return ['oc-calendar-publishing', 'calendarserver-sharing'];
82
-	}
83
-
84
-	/**
85
-	 * Returns a plugin name.
86
-	 *
87
-	 * Using this name other plugins will be able to access other plugins
88
-	 * using Sabre\DAV\Server::getPlugin
89
-	 *
90
-	 * @return string
91
-	 */
92
-	public function getPluginName()	{
93
-		return 'oc-calendar-publishing';
94
-	}
95
-
96
-	/**
97
-	 * This initializes the plugin.
98
-	 *
99
-	 * This function is called by Sabre\DAV\Server, after
100
-	 * addPlugin is called.
101
-	 *
102
-	 * This method should set up the required event subscriptions.
103
-	 *
104
-	 * @param Server $server
105
-	 */
106
-	public function initialize(Server $server) {
107
-		$this->server = $server;
108
-
109
-		$this->server->on('method:POST', [$this, 'httpPost']);
110
-		$this->server->on('propFind',    [$this, 'propFind']);
111
-	}
112
-
113
-	public function propFind(PropFind $propFind, INode $node) {
114
-		if ($node instanceof Calendar) {
115
-			$propFind->handle('{'.self::NS_CALENDARSERVER.'}publish-url', function () use ($node) {
116
-				if ($node->getPublishStatus()) {
117
-					// We return the publish-url only if the calendar is published.
118
-					$token = $node->getPublishStatus();
119
-					$publishUrl = $this->urlGenerator->getAbsoluteURL($this->server->getBaseUri().'public-calendars/').$token;
120
-
121
-					return new Publisher($publishUrl, true);
122
-				}
123
-			});
124
-
125
-			$propFind->handle('{'.self::NS_CALENDARSERVER.'}allowed-sharing-modes', function() use ($node) {
126
-				return new AllowedSharingModes(!$node->isSubscription(), !$node->isSubscription());
127
-			});
128
-		}
129
-	}
130
-
131
-	/**
132
-	 * We intercept this to handle POST requests on calendars.
133
-	 *
134
-	 * @param RequestInterface $request
135
-	 * @param ResponseInterface $response
136
-	 *
137
-	 * @return void|bool
138
-	 */
139
-	public function httpPost(RequestInterface $request, ResponseInterface $response) {
140
-		$path = $request->getPath();
141
-
142
-		// Only handling xml
143
-		$contentType = $request->getHeader('Content-Type');
144
-		if (strpos($contentType, 'application/xml') === false && strpos($contentType, 'text/xml') === false) {
145
-			return;
146
-		}
147
-
148
-		// Making sure the node exists
149
-		try {
150
-			$node = $this->server->tree->getNodeForPath($path);
151
-		} catch (NotFound $e) {
152
-			return;
153
-		}
154
-
155
-		$requestBody = $request->getBodyAsString();
156
-
157
-		// If this request handler could not deal with this POST request, it
158
-		// will return 'null' and other plugins get a chance to handle the
159
-		// request.
160
-		//
161
-		// However, we already requested the full body. This is a problem,
162
-		// because a body can only be read once. This is why we preemptively
163
-		// re-populated the request body with the existing data.
164
-		$request->setBody($requestBody);
165
-
166
-		$this->server->xml->parse($requestBody, $request->getUrl(), $documentType);
167
-
168
-		switch ($documentType) {
169
-
170
-			case '{'.self::NS_CALENDARSERVER.'}publish-calendar' :
171
-
172
-			// We can only deal with IShareableCalendar objects
173
-			if (!$node instanceof Calendar) {
174
-				return;
175
-			}
176
-			$this->server->transactionType = 'post-publish-calendar';
177
-
178
-			// Getting ACL info
179
-			$acl = $this->server->getPlugin('acl');
180
-
181
-			// If there's no ACL support, we allow everything
182
-			if ($acl) {
183
-				$acl->checkPrivileges($path, '{DAV:}write');
184
-			}
185
-
186
-			$node->setPublishStatus(true);
187
-
188
-			// iCloud sends back the 202, so we will too.
189
-			$response->setStatus(202);
190
-
191
-			// Adding this because sending a response body may cause issues,
192
-			// and I wanted some type of indicator the response was handled.
193
-			$response->setHeader('X-Sabre-Status', 'everything-went-well');
194
-
195
-			// Breaking the event chain
196
-			return false;
197
-
198
-			case '{'.self::NS_CALENDARSERVER.'}unpublish-calendar' :
199
-
200
-			// We can only deal with IShareableCalendar objects
201
-			if (!$node instanceof Calendar) {
202
-				return;
203
-			}
204
-			$this->server->transactionType = 'post-unpublish-calendar';
205
-
206
-			// Getting ACL info
207
-			$acl = $this->server->getPlugin('acl');
208
-
209
-			// If there's no ACL support, we allow everything
210
-			if ($acl) {
211
-				$acl->checkPrivileges($path, '{DAV:}write');
212
-			}
213
-
214
-			$node->setPublishStatus(false);
215
-
216
-			$response->setStatus(200);
217
-
218
-			// Adding this because sending a response body may cause issues,
219
-			// and I wanted some type of indicator the response was handled.
220
-			$response->setHeader('X-Sabre-Status', 'everything-went-well');
221
-
222
-			// Breaking the event chain
223
-			return false;
37
+    const NS_CALENDARSERVER = 'http://calendarserver.org/ns/';
38
+
39
+    /**
40
+     * Reference to SabreDAV server object.
41
+     *
42
+     * @var \Sabre\DAV\Server
43
+     */
44
+    protected $server;
45
+
46
+    /**
47
+     * Config instance to get instance secret.
48
+     *
49
+     * @var IConfig
50
+     */
51
+    protected $config;
52
+
53
+    /**
54
+     * URL Generator for absolute URLs.
55
+     *
56
+     * @var IURLGenerator
57
+     */
58
+    protected $urlGenerator;
59
+
60
+    /**
61
+     * PublishPlugin constructor.
62
+     *
63
+     * @param IConfig $config
64
+     * @param IURLGenerator $urlGenerator
65
+     */
66
+    public function __construct(IConfig $config, IURLGenerator $urlGenerator) {
67
+        $this->config = $config;
68
+        $this->urlGenerator = $urlGenerator;
69
+    }
70
+
71
+    /**
72
+     * This method should return a list of server-features.
73
+     *
74
+     * This is for example 'versioning' and is added to the DAV: header
75
+     * in an OPTIONS response.
76
+     *
77
+     * @return string[]
78
+     */
79
+    public function getFeatures() {
80
+        // May have to be changed to be detected
81
+        return ['oc-calendar-publishing', 'calendarserver-sharing'];
82
+    }
83
+
84
+    /**
85
+     * Returns a plugin name.
86
+     *
87
+     * Using this name other plugins will be able to access other plugins
88
+     * using Sabre\DAV\Server::getPlugin
89
+     *
90
+     * @return string
91
+     */
92
+    public function getPluginName()	{
93
+        return 'oc-calendar-publishing';
94
+    }
95
+
96
+    /**
97
+     * This initializes the plugin.
98
+     *
99
+     * This function is called by Sabre\DAV\Server, after
100
+     * addPlugin is called.
101
+     *
102
+     * This method should set up the required event subscriptions.
103
+     *
104
+     * @param Server $server
105
+     */
106
+    public function initialize(Server $server) {
107
+        $this->server = $server;
108
+
109
+        $this->server->on('method:POST', [$this, 'httpPost']);
110
+        $this->server->on('propFind',    [$this, 'propFind']);
111
+    }
112
+
113
+    public function propFind(PropFind $propFind, INode $node) {
114
+        if ($node instanceof Calendar) {
115
+            $propFind->handle('{'.self::NS_CALENDARSERVER.'}publish-url', function () use ($node) {
116
+                if ($node->getPublishStatus()) {
117
+                    // We return the publish-url only if the calendar is published.
118
+                    $token = $node->getPublishStatus();
119
+                    $publishUrl = $this->urlGenerator->getAbsoluteURL($this->server->getBaseUri().'public-calendars/').$token;
120
+
121
+                    return new Publisher($publishUrl, true);
122
+                }
123
+            });
124
+
125
+            $propFind->handle('{'.self::NS_CALENDARSERVER.'}allowed-sharing-modes', function() use ($node) {
126
+                return new AllowedSharingModes(!$node->isSubscription(), !$node->isSubscription());
127
+            });
128
+        }
129
+    }
130
+
131
+    /**
132
+     * We intercept this to handle POST requests on calendars.
133
+     *
134
+     * @param RequestInterface $request
135
+     * @param ResponseInterface $response
136
+     *
137
+     * @return void|bool
138
+     */
139
+    public function httpPost(RequestInterface $request, ResponseInterface $response) {
140
+        $path = $request->getPath();
141
+
142
+        // Only handling xml
143
+        $contentType = $request->getHeader('Content-Type');
144
+        if (strpos($contentType, 'application/xml') === false && strpos($contentType, 'text/xml') === false) {
145
+            return;
146
+        }
147
+
148
+        // Making sure the node exists
149
+        try {
150
+            $node = $this->server->tree->getNodeForPath($path);
151
+        } catch (NotFound $e) {
152
+            return;
153
+        }
154
+
155
+        $requestBody = $request->getBodyAsString();
156
+
157
+        // If this request handler could not deal with this POST request, it
158
+        // will return 'null' and other plugins get a chance to handle the
159
+        // request.
160
+        //
161
+        // However, we already requested the full body. This is a problem,
162
+        // because a body can only be read once. This is why we preemptively
163
+        // re-populated the request body with the existing data.
164
+        $request->setBody($requestBody);
165
+
166
+        $this->server->xml->parse($requestBody, $request->getUrl(), $documentType);
167
+
168
+        switch ($documentType) {
169
+
170
+            case '{'.self::NS_CALENDARSERVER.'}publish-calendar' :
171
+
172
+            // We can only deal with IShareableCalendar objects
173
+            if (!$node instanceof Calendar) {
174
+                return;
175
+            }
176
+            $this->server->transactionType = 'post-publish-calendar';
177
+
178
+            // Getting ACL info
179
+            $acl = $this->server->getPlugin('acl');
180
+
181
+            // If there's no ACL support, we allow everything
182
+            if ($acl) {
183
+                $acl->checkPrivileges($path, '{DAV:}write');
184
+            }
185
+
186
+            $node->setPublishStatus(true);
187
+
188
+            // iCloud sends back the 202, so we will too.
189
+            $response->setStatus(202);
190
+
191
+            // Adding this because sending a response body may cause issues,
192
+            // and I wanted some type of indicator the response was handled.
193
+            $response->setHeader('X-Sabre-Status', 'everything-went-well');
194
+
195
+            // Breaking the event chain
196
+            return false;
197
+
198
+            case '{'.self::NS_CALENDARSERVER.'}unpublish-calendar' :
199
+
200
+            // We can only deal with IShareableCalendar objects
201
+            if (!$node instanceof Calendar) {
202
+                return;
203
+            }
204
+            $this->server->transactionType = 'post-unpublish-calendar';
205
+
206
+            // Getting ACL info
207
+            $acl = $this->server->getPlugin('acl');
208
+
209
+            // If there's no ACL support, we allow everything
210
+            if ($acl) {
211
+                $acl->checkPrivileges($path, '{DAV:}write');
212
+            }
213
+
214
+            $node->setPublishStatus(false);
215
+
216
+            $response->setStatus(200);
217
+
218
+            // Adding this because sending a response body may cause issues,
219
+            // and I wanted some type of indicator the response was handled.
220
+            $response->setHeader('X-Sabre-Status', 'everything-went-well');
221
+
222
+            // Breaking the event chain
223
+            return false;
224 224
 
225
-		}
226
-	}
225
+        }
226
+    }
227 227
 }
Please login to merge, or discard this patch.
Spacing   +3 added lines, -3 removed lines patch added patch discarded remove patch
@@ -89,7 +89,7 @@  discard block
 block discarded – undo
89 89
 	 *
90 90
 	 * @return string
91 91
 	 */
92
-	public function getPluginName()	{
92
+	public function getPluginName() {
93 93
 		return 'oc-calendar-publishing';
94 94
 	}
95 95
 
@@ -107,12 +107,12 @@  discard block
 block discarded – undo
107 107
 		$this->server = $server;
108 108
 
109 109
 		$this->server->on('method:POST', [$this, 'httpPost']);
110
-		$this->server->on('propFind',    [$this, 'propFind']);
110
+		$this->server->on('propFind', [$this, 'propFind']);
111 111
 	}
112 112
 
113 113
 	public function propFind(PropFind $propFind, INode $node) {
114 114
 		if ($node instanceof Calendar) {
115
-			$propFind->handle('{'.self::NS_CALENDARSERVER.'}publish-url', function () use ($node) {
115
+			$propFind->handle('{'.self::NS_CALENDARSERVER.'}publish-url', function() use ($node) {
116 116
 				if ($node->getPublishStatus()) {
117 117
 					// We return the publish-url only if the calendar is published.
118 118
 					$token = $node->getPublishStatus();
Please login to merge, or discard this patch.
apps/dav/lib/CardDAV/AddressBookRoot.php 2 patches
Doc Comments   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -30,7 +30,7 @@
 block discarded – undo
30 30
 
31 31
 	/**
32 32
 	 * @param \Sabre\DAVACL\PrincipalBackend\BackendInterface $principalBackend
33
-	 * @param \Sabre\CardDAV\Backend\BackendInterface $carddavBackend
33
+	 * @param CardDavBackend $carddavBackend
34 34
 	 * @param string $principalPrefix
35 35
 	 */
36 36
 	public function __construct(\Sabre\DAVACL\PrincipalBackend\BackendInterface $principalBackend, \Sabre\CardDAV\Backend\BackendInterface $carddavBackend, $principalPrefix = 'principals') {
Please login to merge, or discard this patch.
Indentation   +33 added lines, -33 removed lines patch added patch discarded remove patch
@@ -25,46 +25,46 @@
 block discarded – undo
25 25
 
26 26
 class AddressBookRoot extends \Sabre\CardDAV\AddressBookRoot {
27 27
 
28
-	/** @var IL10N */
29
-	protected $l10n;
28
+    /** @var IL10N */
29
+    protected $l10n;
30 30
 
31
-	/**
32
-	 * @param \Sabre\DAVACL\PrincipalBackend\BackendInterface $principalBackend
33
-	 * @param \Sabre\CardDAV\Backend\BackendInterface $carddavBackend
34
-	 * @param string $principalPrefix
35
-	 */
36
-	public function __construct(\Sabre\DAVACL\PrincipalBackend\BackendInterface $principalBackend, \Sabre\CardDAV\Backend\BackendInterface $carddavBackend, $principalPrefix = 'principals') {
37
-		parent::__construct($principalBackend, $carddavBackend, $principalPrefix);
38
-		$this->l10n = \OC::$server->getL10N('dav');
39
-	}
31
+    /**
32
+     * @param \Sabre\DAVACL\PrincipalBackend\BackendInterface $principalBackend
33
+     * @param \Sabre\CardDAV\Backend\BackendInterface $carddavBackend
34
+     * @param string $principalPrefix
35
+     */
36
+    public function __construct(\Sabre\DAVACL\PrincipalBackend\BackendInterface $principalBackend, \Sabre\CardDAV\Backend\BackendInterface $carddavBackend, $principalPrefix = 'principals') {
37
+        parent::__construct($principalBackend, $carddavBackend, $principalPrefix);
38
+        $this->l10n = \OC::$server->getL10N('dav');
39
+    }
40 40
 
41
-	/**
42
-	 * This method returns a node for a principal.
43
-	 *
44
-	 * The passed array contains principal information, and is guaranteed to
45
-	 * at least contain a uri item. Other properties may or may not be
46
-	 * supplied by the authentication backend.
47
-	 *
48
-	 * @param array $principal
49
-	 * @return \Sabre\DAV\INode
50
-	 */
51
-	function getChildForPrincipal(array $principal) {
41
+    /**
42
+     * This method returns a node for a principal.
43
+     *
44
+     * The passed array contains principal information, and is guaranteed to
45
+     * at least contain a uri item. Other properties may or may not be
46
+     * supplied by the authentication backend.
47
+     *
48
+     * @param array $principal
49
+     * @return \Sabre\DAV\INode
50
+     */
51
+    function getChildForPrincipal(array $principal) {
52 52
 
53
-		return new UserAddressBooks($this->carddavBackend, $principal['uri'], $this->l10n);
53
+        return new UserAddressBooks($this->carddavBackend, $principal['uri'], $this->l10n);
54 54
 
55
-	}
55
+    }
56 56
 
57
-	function getName() {
57
+    function getName() {
58 58
 
59
-		if ($this->principalPrefix === 'principals') {
60
-			return parent::getName();
61
-		}
62
-		// Grabbing all the components of the principal path.
63
-		$parts = explode('/', $this->principalPrefix);
59
+        if ($this->principalPrefix === 'principals') {
60
+            return parent::getName();
61
+        }
62
+        // Grabbing all the components of the principal path.
63
+        $parts = explode('/', $this->principalPrefix);
64 64
 
65
-		// We are only interested in the second part.
66
-		return $parts[1];
65
+        // We are only interested in the second part.
66
+        return $parts[1];
67 67
 
68
-	}
68
+    }
69 69
 
70 70
 }
Please login to merge, or discard this patch.
lib/private/Share20/DefaultShareProvider.php 3 patches
Doc Comments   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -770,7 +770,7 @@
 block discarded – undo
770 770
 
771 771
 	/**
772 772
 	 * @param Share[] $shares
773
-	 * @param $userId
773
+	 * @param string $userId
774 774
 	 * @return Share[] The updates shares if no update is found for a share return the original
775 775
 	 */
776 776
 	private function resolveGroupShares($shares, $userId) {
Please login to merge, or discard this patch.
Spacing   +24 added lines, -24 removed lines patch added patch discarded remove patch
@@ -287,7 +287,7 @@  discard block
 block discarded – undo
287 287
 			->orderBy('id');
288 288
 
289 289
 		$cursor = $qb->execute();
290
-		while($data = $cursor->fetch()) {
290
+		while ($data = $cursor->fetch()) {
291 291
 			$children[] = $this->createShare($data);
292 292
 		}
293 293
 		$cursor->closeCursor();
@@ -332,7 +332,7 @@  discard block
 block discarded – undo
332 332
 			$user = $this->userManager->get($recipient);
333 333
 
334 334
 			if (is_null($group)) {
335
-				throw new ProviderException('Group "' . $share->getSharedWith() . '" does not exist');
335
+				throw new ProviderException('Group "'.$share->getSharedWith().'" does not exist');
336 336
 			}
337 337
 
338 338
 			if (!$group->inGroup($user)) {
@@ -492,7 +492,7 @@  discard block
 block discarded – undo
492 492
 			);
493 493
 		}
494 494
 
495
-		$qb->innerJoin('s', 'filecache' ,'f', $qb->expr()->eq('s.file_source', 'f.fileid'));
495
+		$qb->innerJoin('s', 'filecache', 'f', $qb->expr()->eq('s.file_source', 'f.fileid'));
496 496
 		$qb->andWhere($qb->expr()->eq('f.parent', $qb->createNamedParameter($node->getId())));
497 497
 
498 498
 		$qb->orderBy('id');
@@ -548,7 +548,7 @@  discard block
 block discarded – undo
548 548
 
549 549
 		$cursor = $qb->execute();
550 550
 		$shares = [];
551
-		while($data = $cursor->fetch()) {
551
+		while ($data = $cursor->fetch()) {
552 552
 			$shares[] = $this->createShare($data);
553 553
 		}
554 554
 		$cursor->closeCursor();
@@ -627,7 +627,7 @@  discard block
 block discarded – undo
627 627
 			->execute();
628 628
 
629 629
 		$shares = [];
630
-		while($data = $cursor->fetch()) {
630
+		while ($data = $cursor->fetch()) {
631 631
 			$shares[] = $this->createShare($data);
632 632
 		}
633 633
 		$cursor->closeCursor();
@@ -698,7 +698,7 @@  discard block
 block discarded – undo
698 698
 
699 699
 			$cursor = $qb->execute();
700 700
 
701
-			while($data = $cursor->fetch()) {
701
+			while ($data = $cursor->fetch()) {
702 702
 				if ($this->isAccessibleResult($data)) {
703 703
 					$shares[] = $this->createShare($data);
704 704
 				}
@@ -713,7 +713,7 @@  discard block
 block discarded – undo
713 713
 			$shares2 = [];
714 714
 
715 715
 			$start = 0;
716
-			while(true) {
716
+			while (true) {
717 717
 				$groups = array_slice($allGroups, $start, 100);
718 718
 				$start += 100;
719 719
 
@@ -758,7 +758,7 @@  discard block
 block discarded – undo
758 758
 					));
759 759
 
760 760
 				$cursor = $qb->execute();
761
-				while($data = $cursor->fetch()) {
761
+				while ($data = $cursor->fetch()) {
762 762
 					if ($offset > 0) {
763 763
 						$offset--;
764 764
 						continue;
@@ -827,14 +827,14 @@  discard block
 block discarded – undo
827 827
 	 */
828 828
 	private function createShare($data) {
829 829
 		$share = new Share($this->rootFolder, $this->userManager);
830
-		$share->setId((int)$data['id'])
831
-			->setShareType((int)$data['share_type'])
832
-			->setPermissions((int)$data['permissions'])
830
+		$share->setId((int) $data['id'])
831
+			->setShareType((int) $data['share_type'])
832
+			->setPermissions((int) $data['permissions'])
833 833
 			->setTarget($data['file_target'])
834
-			->setMailSend((bool)$data['mail_send']);
834
+			->setMailSend((bool) $data['mail_send']);
835 835
 
836 836
 		$shareTime = new \DateTime();
837
-		$shareTime->setTimestamp((int)$data['stime']);
837
+		$shareTime->setTimestamp((int) $data['stime']);
838 838
 		$share->setShareTime($shareTime);
839 839
 
840 840
 		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
@@ -849,7 +849,7 @@  discard block
 block discarded – undo
849 849
 		$share->setSharedBy($data['uid_initiator']);
850 850
 		$share->setShareOwner($data['uid_owner']);
851 851
 
852
-		$share->setNodeId((int)$data['file_source']);
852
+		$share->setNodeId((int) $data['file_source']);
853 853
 		$share->setNodeType($data['item_type']);
854 854
 
855 855
 		if ($data['expiration'] !== null) {
@@ -879,7 +879,7 @@  discard block
 block discarded – undo
879 879
 		$result = [];
880 880
 
881 881
 		$start = 0;
882
-		while(true) {
882
+		while (true) {
883 883
 			/** @var Share[] $shareSlice */
884 884
 			$shareSlice = array_slice($shares, $start, 100);
885 885
 			$start += 100;
@@ -894,7 +894,7 @@  discard block
 block discarded – undo
894 894
 			$shareMap = [];
895 895
 
896 896
 			foreach ($shareSlice as $share) {
897
-				$ids[] = (int)$share->getId();
897
+				$ids[] = (int) $share->getId();
898 898
 				$shareMap[$share->getId()] = $share;
899 899
 			}
900 900
 
@@ -911,8 +911,8 @@  discard block
 block discarded – undo
911 911
 
912 912
 			$stmt = $query->execute();
913 913
 
914
-			while($data = $stmt->fetch()) {
915
-				$shareMap[$data['parent']]->setPermissions((int)$data['permissions']);
914
+			while ($data = $stmt->fetch()) {
915
+				$shareMap[$data['parent']]->setPermissions((int) $data['permissions']);
916 916
 				$shareMap[$data['parent']]->setTarget($data['file_target']);
917 917
 			}
918 918
 
@@ -1009,8 +1009,8 @@  discard block
 block discarded – undo
1009 1009
 
1010 1010
 		$cursor = $qb->execute();
1011 1011
 		$ids = [];
1012
-		while($row = $cursor->fetch()) {
1013
-			$ids[] = (int)$row['id'];
1012
+		while ($row = $cursor->fetch()) {
1013
+			$ids[] = (int) $row['id'];
1014 1014
 		}
1015 1015
 		$cursor->closeCursor();
1016 1016
 
@@ -1052,8 +1052,8 @@  discard block
 block discarded – undo
1052 1052
 
1053 1053
 		$cursor = $qb->execute();
1054 1054
 		$ids = [];
1055
-		while($row = $cursor->fetch()) {
1056
-			$ids[] = (int)$row['id'];
1055
+		while ($row = $cursor->fetch()) {
1056
+			$ids[] = (int) $row['id'];
1057 1057
 		}
1058 1058
 		$cursor->closeCursor();
1059 1059
 
@@ -1107,8 +1107,8 @@  discard block
 block discarded – undo
1107 1107
 
1108 1108
 		$users = [];
1109 1109
 		$link = false;
1110
-		while($row = $cursor->fetch()) {
1111
-			$type = (int)$row['share_type'];
1110
+		while ($row = $cursor->fetch()) {
1111
+			$type = (int) $row['share_type'];
1112 1112
 			if ($type === \OCP\Share::SHARE_TYPE_USER) {
1113 1113
 				$uid = $row['share_with'];
1114 1114
 				$users[$uid] = isset($users[$uid]) ? $users[$uid] : [];
Please login to merge, or discard this patch.
Indentation   +1107 added lines, -1107 removed lines patch added patch discarded remove patch
@@ -52,1144 +52,1144 @@
 block discarded – undo
52 52
  */
53 53
 class DefaultShareProvider implements IShareProvider {
54 54
 
55
-	// Special share type for user modified group shares
56
-	const SHARE_TYPE_USERGROUP = 2;
57
-
58
-	/** @var IDBConnection */
59
-	private $dbConn;
60
-
61
-	/** @var IUserManager */
62
-	private $userManager;
63
-
64
-	/** @var IGroupManager */
65
-	private $groupManager;
66
-
67
-	/** @var IRootFolder */
68
-	private $rootFolder;
69
-
70
-	/**
71
-	 * DefaultShareProvider constructor.
72
-	 *
73
-	 * @param IDBConnection $connection
74
-	 * @param IUserManager $userManager
75
-	 * @param IGroupManager $groupManager
76
-	 * @param IRootFolder $rootFolder
77
-	 */
78
-	public function __construct(
79
-			IDBConnection $connection,
80
-			IUserManager $userManager,
81
-			IGroupManager $groupManager,
82
-			IRootFolder $rootFolder) {
83
-		$this->dbConn = $connection;
84
-		$this->userManager = $userManager;
85
-		$this->groupManager = $groupManager;
86
-		$this->rootFolder = $rootFolder;
87
-	}
88
-
89
-	/**
90
-	 * Return the identifier of this provider.
91
-	 *
92
-	 * @return string Containing only [a-zA-Z0-9]
93
-	 */
94
-	public function identifier() {
95
-		return 'ocinternal';
96
-	}
97
-
98
-	/**
99
-	 * Share a path
100
-	 *
101
-	 * @param \OCP\Share\IShare $share
102
-	 * @return \OCP\Share\IShare The share object
103
-	 * @throws ShareNotFound
104
-	 * @throws \Exception
105
-	 */
106
-	public function create(\OCP\Share\IShare $share) {
107
-		$qb = $this->dbConn->getQueryBuilder();
108
-
109
-		$qb->insert('share');
110
-		$qb->setValue('share_type', $qb->createNamedParameter($share->getShareType()));
111
-
112
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
113
-			//Set the UID of the user we share with
114
-			$qb->setValue('share_with', $qb->createNamedParameter($share->getSharedWith()));
115
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
116
-			//Set the GID of the group we share with
117
-			$qb->setValue('share_with', $qb->createNamedParameter($share->getSharedWith()));
118
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
119
-			//Set the token of the share
120
-			$qb->setValue('token', $qb->createNamedParameter($share->getToken()));
121
-
122
-			//If a password is set store it
123
-			if ($share->getPassword() !== null) {
124
-				$qb->setValue('password', $qb->createNamedParameter($share->getPassword()));
125
-			}
126
-
127
-			//If an expiration date is set store it
128
-			if ($share->getExpirationDate() !== null) {
129
-				$qb->setValue('expiration', $qb->createNamedParameter($share->getExpirationDate(), 'datetime'));
130
-			}
131
-
132
-			if (method_exists($share, 'getParent')) {
133
-				$qb->setValue('parent', $qb->createNamedParameter($share->getParent()));
134
-			}
135
-		} else {
136
-			throw new \Exception('invalid share type!');
137
-		}
138
-
139
-		// Set what is shares
140
-		$qb->setValue('item_type', $qb->createParameter('itemType'));
141
-		if ($share->getNode() instanceof \OCP\Files\File) {
142
-			$qb->setParameter('itemType', 'file');
143
-		} else {
144
-			$qb->setParameter('itemType', 'folder');
145
-		}
146
-
147
-		// Set the file id
148
-		$qb->setValue('item_source', $qb->createNamedParameter($share->getNode()->getId()));
149
-		$qb->setValue('file_source', $qb->createNamedParameter($share->getNode()->getId()));
150
-
151
-		// set the permissions
152
-		$qb->setValue('permissions', $qb->createNamedParameter($share->getPermissions()));
153
-
154
-		// Set who created this share
155
-		$qb->setValue('uid_initiator', $qb->createNamedParameter($share->getSharedBy()));
156
-
157
-		// Set who is the owner of this file/folder (and this the owner of the share)
158
-		$qb->setValue('uid_owner', $qb->createNamedParameter($share->getShareOwner()));
159
-
160
-		// Set the file target
161
-		$qb->setValue('file_target', $qb->createNamedParameter($share->getTarget()));
162
-
163
-		// Set the time this share was created
164
-		$qb->setValue('stime', $qb->createNamedParameter(time()));
165
-
166
-		// insert the data and fetch the id of the share
167
-		$this->dbConn->beginTransaction();
168
-		$qb->execute();
169
-		$id = $this->dbConn->lastInsertId('*PREFIX*share');
170
-
171
-		// Now fetch the inserted share and create a complete share object
172
-		$qb = $this->dbConn->getQueryBuilder();
173
-		$qb->select('*')
174
-			->from('share')
175
-			->where($qb->expr()->eq('id', $qb->createNamedParameter($id)));
176
-
177
-		$cursor = $qb->execute();
178
-		$data = $cursor->fetch();
179
-		$this->dbConn->commit();
180
-		$cursor->closeCursor();
181
-
182
-		if ($data === false) {
183
-			throw new ShareNotFound();
184
-		}
185
-
186
-		$mailSendValue = $share->getMailSend();
187
-		$data['mail_send'] = ($mailSendValue === null) ? true : $mailSendValue;
188
-
189
-		$share = $this->createShare($data);
190
-		return $share;
191
-	}
192
-
193
-	/**
194
-	 * Update a share
195
-	 *
196
-	 * @param \OCP\Share\IShare $share
197
-	 * @return \OCP\Share\IShare The share object
198
-	 */
199
-	public function update(\OCP\Share\IShare $share) {
200
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
201
-			/*
55
+    // Special share type for user modified group shares
56
+    const SHARE_TYPE_USERGROUP = 2;
57
+
58
+    /** @var IDBConnection */
59
+    private $dbConn;
60
+
61
+    /** @var IUserManager */
62
+    private $userManager;
63
+
64
+    /** @var IGroupManager */
65
+    private $groupManager;
66
+
67
+    /** @var IRootFolder */
68
+    private $rootFolder;
69
+
70
+    /**
71
+     * DefaultShareProvider constructor.
72
+     *
73
+     * @param IDBConnection $connection
74
+     * @param IUserManager $userManager
75
+     * @param IGroupManager $groupManager
76
+     * @param IRootFolder $rootFolder
77
+     */
78
+    public function __construct(
79
+            IDBConnection $connection,
80
+            IUserManager $userManager,
81
+            IGroupManager $groupManager,
82
+            IRootFolder $rootFolder) {
83
+        $this->dbConn = $connection;
84
+        $this->userManager = $userManager;
85
+        $this->groupManager = $groupManager;
86
+        $this->rootFolder = $rootFolder;
87
+    }
88
+
89
+    /**
90
+     * Return the identifier of this provider.
91
+     *
92
+     * @return string Containing only [a-zA-Z0-9]
93
+     */
94
+    public function identifier() {
95
+        return 'ocinternal';
96
+    }
97
+
98
+    /**
99
+     * Share a path
100
+     *
101
+     * @param \OCP\Share\IShare $share
102
+     * @return \OCP\Share\IShare The share object
103
+     * @throws ShareNotFound
104
+     * @throws \Exception
105
+     */
106
+    public function create(\OCP\Share\IShare $share) {
107
+        $qb = $this->dbConn->getQueryBuilder();
108
+
109
+        $qb->insert('share');
110
+        $qb->setValue('share_type', $qb->createNamedParameter($share->getShareType()));
111
+
112
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
113
+            //Set the UID of the user we share with
114
+            $qb->setValue('share_with', $qb->createNamedParameter($share->getSharedWith()));
115
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
116
+            //Set the GID of the group we share with
117
+            $qb->setValue('share_with', $qb->createNamedParameter($share->getSharedWith()));
118
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
119
+            //Set the token of the share
120
+            $qb->setValue('token', $qb->createNamedParameter($share->getToken()));
121
+
122
+            //If a password is set store it
123
+            if ($share->getPassword() !== null) {
124
+                $qb->setValue('password', $qb->createNamedParameter($share->getPassword()));
125
+            }
126
+
127
+            //If an expiration date is set store it
128
+            if ($share->getExpirationDate() !== null) {
129
+                $qb->setValue('expiration', $qb->createNamedParameter($share->getExpirationDate(), 'datetime'));
130
+            }
131
+
132
+            if (method_exists($share, 'getParent')) {
133
+                $qb->setValue('parent', $qb->createNamedParameter($share->getParent()));
134
+            }
135
+        } else {
136
+            throw new \Exception('invalid share type!');
137
+        }
138
+
139
+        // Set what is shares
140
+        $qb->setValue('item_type', $qb->createParameter('itemType'));
141
+        if ($share->getNode() instanceof \OCP\Files\File) {
142
+            $qb->setParameter('itemType', 'file');
143
+        } else {
144
+            $qb->setParameter('itemType', 'folder');
145
+        }
146
+
147
+        // Set the file id
148
+        $qb->setValue('item_source', $qb->createNamedParameter($share->getNode()->getId()));
149
+        $qb->setValue('file_source', $qb->createNamedParameter($share->getNode()->getId()));
150
+
151
+        // set the permissions
152
+        $qb->setValue('permissions', $qb->createNamedParameter($share->getPermissions()));
153
+
154
+        // Set who created this share
155
+        $qb->setValue('uid_initiator', $qb->createNamedParameter($share->getSharedBy()));
156
+
157
+        // Set who is the owner of this file/folder (and this the owner of the share)
158
+        $qb->setValue('uid_owner', $qb->createNamedParameter($share->getShareOwner()));
159
+
160
+        // Set the file target
161
+        $qb->setValue('file_target', $qb->createNamedParameter($share->getTarget()));
162
+
163
+        // Set the time this share was created
164
+        $qb->setValue('stime', $qb->createNamedParameter(time()));
165
+
166
+        // insert the data and fetch the id of the share
167
+        $this->dbConn->beginTransaction();
168
+        $qb->execute();
169
+        $id = $this->dbConn->lastInsertId('*PREFIX*share');
170
+
171
+        // Now fetch the inserted share and create a complete share object
172
+        $qb = $this->dbConn->getQueryBuilder();
173
+        $qb->select('*')
174
+            ->from('share')
175
+            ->where($qb->expr()->eq('id', $qb->createNamedParameter($id)));
176
+
177
+        $cursor = $qb->execute();
178
+        $data = $cursor->fetch();
179
+        $this->dbConn->commit();
180
+        $cursor->closeCursor();
181
+
182
+        if ($data === false) {
183
+            throw new ShareNotFound();
184
+        }
185
+
186
+        $mailSendValue = $share->getMailSend();
187
+        $data['mail_send'] = ($mailSendValue === null) ? true : $mailSendValue;
188
+
189
+        $share = $this->createShare($data);
190
+        return $share;
191
+    }
192
+
193
+    /**
194
+     * Update a share
195
+     *
196
+     * @param \OCP\Share\IShare $share
197
+     * @return \OCP\Share\IShare The share object
198
+     */
199
+    public function update(\OCP\Share\IShare $share) {
200
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
201
+            /*
202 202
 			 * We allow updating the recipient on user shares.
203 203
 			 */
204
-			$qb = $this->dbConn->getQueryBuilder();
205
-			$qb->update('share')
206
-				->where($qb->expr()->eq('id', $qb->createNamedParameter($share->getId())))
207
-				->set('share_with', $qb->createNamedParameter($share->getSharedWith()))
208
-				->set('uid_owner', $qb->createNamedParameter($share->getShareOwner()))
209
-				->set('uid_initiator', $qb->createNamedParameter($share->getSharedBy()))
210
-				->set('permissions', $qb->createNamedParameter($share->getPermissions()))
211
-				->set('item_source', $qb->createNamedParameter($share->getNode()->getId()))
212
-				->set('file_source', $qb->createNamedParameter($share->getNode()->getId()))
213
-				->set('expiration', $qb->createNamedParameter($share->getExpirationDate(), IQueryBuilder::PARAM_DATE))
214
-				->execute();
215
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
216
-			$qb = $this->dbConn->getQueryBuilder();
217
-			$qb->update('share')
218
-				->where($qb->expr()->eq('id', $qb->createNamedParameter($share->getId())))
219
-				->set('uid_owner', $qb->createNamedParameter($share->getShareOwner()))
220
-				->set('uid_initiator', $qb->createNamedParameter($share->getSharedBy()))
221
-				->set('permissions', $qb->createNamedParameter($share->getPermissions()))
222
-				->set('item_source', $qb->createNamedParameter($share->getNode()->getId()))
223
-				->set('file_source', $qb->createNamedParameter($share->getNode()->getId()))
224
-				->set('expiration', $qb->createNamedParameter($share->getExpirationDate(), IQueryBuilder::PARAM_DATE))
225
-				->execute();
226
-
227
-			/*
204
+            $qb = $this->dbConn->getQueryBuilder();
205
+            $qb->update('share')
206
+                ->where($qb->expr()->eq('id', $qb->createNamedParameter($share->getId())))
207
+                ->set('share_with', $qb->createNamedParameter($share->getSharedWith()))
208
+                ->set('uid_owner', $qb->createNamedParameter($share->getShareOwner()))
209
+                ->set('uid_initiator', $qb->createNamedParameter($share->getSharedBy()))
210
+                ->set('permissions', $qb->createNamedParameter($share->getPermissions()))
211
+                ->set('item_source', $qb->createNamedParameter($share->getNode()->getId()))
212
+                ->set('file_source', $qb->createNamedParameter($share->getNode()->getId()))
213
+                ->set('expiration', $qb->createNamedParameter($share->getExpirationDate(), IQueryBuilder::PARAM_DATE))
214
+                ->execute();
215
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
216
+            $qb = $this->dbConn->getQueryBuilder();
217
+            $qb->update('share')
218
+                ->where($qb->expr()->eq('id', $qb->createNamedParameter($share->getId())))
219
+                ->set('uid_owner', $qb->createNamedParameter($share->getShareOwner()))
220
+                ->set('uid_initiator', $qb->createNamedParameter($share->getSharedBy()))
221
+                ->set('permissions', $qb->createNamedParameter($share->getPermissions()))
222
+                ->set('item_source', $qb->createNamedParameter($share->getNode()->getId()))
223
+                ->set('file_source', $qb->createNamedParameter($share->getNode()->getId()))
224
+                ->set('expiration', $qb->createNamedParameter($share->getExpirationDate(), IQueryBuilder::PARAM_DATE))
225
+                ->execute();
226
+
227
+            /*
228 228
 			 * Update all user defined group shares
229 229
 			 */
230
-			$qb = $this->dbConn->getQueryBuilder();
231
-			$qb->update('share')
232
-				->where($qb->expr()->eq('parent', $qb->createNamedParameter($share->getId())))
233
-				->andWhere($qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP)))
234
-				->set('uid_owner', $qb->createNamedParameter($share->getShareOwner()))
235
-				->set('uid_initiator', $qb->createNamedParameter($share->getSharedBy()))
236
-				->set('item_source', $qb->createNamedParameter($share->getNode()->getId()))
237
-				->set('file_source', $qb->createNamedParameter($share->getNode()->getId()))
238
-				->set('expiration', $qb->createNamedParameter($share->getExpirationDate(), IQueryBuilder::PARAM_DATE))
239
-				->execute();
240
-
241
-			/*
230
+            $qb = $this->dbConn->getQueryBuilder();
231
+            $qb->update('share')
232
+                ->where($qb->expr()->eq('parent', $qb->createNamedParameter($share->getId())))
233
+                ->andWhere($qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP)))
234
+                ->set('uid_owner', $qb->createNamedParameter($share->getShareOwner()))
235
+                ->set('uid_initiator', $qb->createNamedParameter($share->getSharedBy()))
236
+                ->set('item_source', $qb->createNamedParameter($share->getNode()->getId()))
237
+                ->set('file_source', $qb->createNamedParameter($share->getNode()->getId()))
238
+                ->set('expiration', $qb->createNamedParameter($share->getExpirationDate(), IQueryBuilder::PARAM_DATE))
239
+                ->execute();
240
+
241
+            /*
242 242
 			 * Now update the permissions for all children that have not set it to 0
243 243
 			 */
244
-			$qb = $this->dbConn->getQueryBuilder();
245
-			$qb->update('share')
246
-				->where($qb->expr()->eq('parent', $qb->createNamedParameter($share->getId())))
247
-				->andWhere($qb->expr()->neq('permissions', $qb->createNamedParameter(0)))
248
-				->set('permissions', $qb->createNamedParameter($share->getPermissions()))
249
-				->execute();
250
-
251
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
252
-			$qb = $this->dbConn->getQueryBuilder();
253
-			$qb->update('share')
254
-				->where($qb->expr()->eq('id', $qb->createNamedParameter($share->getId())))
255
-				->set('password', $qb->createNamedParameter($share->getPassword()))
256
-				->set('uid_owner', $qb->createNamedParameter($share->getShareOwner()))
257
-				->set('uid_initiator', $qb->createNamedParameter($share->getSharedBy()))
258
-				->set('permissions', $qb->createNamedParameter($share->getPermissions()))
259
-				->set('item_source', $qb->createNamedParameter($share->getNode()->getId()))
260
-				->set('file_source', $qb->createNamedParameter($share->getNode()->getId()))
261
-				->set('token', $qb->createNamedParameter($share->getToken()))
262
-				->set('expiration', $qb->createNamedParameter($share->getExpirationDate(), IQueryBuilder::PARAM_DATE))
263
-				->execute();
264
-		}
265
-
266
-		return $share;
267
-	}
268
-
269
-	/**
270
-	 * Get all children of this share
271
-	 * FIXME: remove once https://github.com/owncloud/core/pull/21660 is in
272
-	 *
273
-	 * @param \OCP\Share\IShare $parent
274
-	 * @return \OCP\Share\IShare[]
275
-	 */
276
-	public function getChildren(\OCP\Share\IShare $parent) {
277
-		$children = [];
278
-
279
-		$qb = $this->dbConn->getQueryBuilder();
280
-		$qb->select('*')
281
-			->from('share')
282
-			->where($qb->expr()->eq('parent', $qb->createNamedParameter($parent->getId())))
283
-			->andWhere(
284
-				$qb->expr()->in(
285
-					'share_type',
286
-					$qb->createNamedParameter([
287
-						\OCP\Share::SHARE_TYPE_USER,
288
-						\OCP\Share::SHARE_TYPE_GROUP,
289
-						\OCP\Share::SHARE_TYPE_LINK,
290
-					], IQueryBuilder::PARAM_INT_ARRAY)
291
-				)
292
-			)
293
-			->andWhere($qb->expr()->orX(
294
-				$qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
295
-				$qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
296
-			))
297
-			->orderBy('id');
298
-
299
-		$cursor = $qb->execute();
300
-		while($data = $cursor->fetch()) {
301
-			$children[] = $this->createShare($data);
302
-		}
303
-		$cursor->closeCursor();
304
-
305
-		return $children;
306
-	}
307
-
308
-	/**
309
-	 * Delete a share
310
-	 *
311
-	 * @param \OCP\Share\IShare $share
312
-	 */
313
-	public function delete(\OCP\Share\IShare $share) {
314
-		$qb = $this->dbConn->getQueryBuilder();
315
-		$qb->delete('share')
316
-			->where($qb->expr()->eq('id', $qb->createNamedParameter($share->getId())));
317
-
318
-		/*
244
+            $qb = $this->dbConn->getQueryBuilder();
245
+            $qb->update('share')
246
+                ->where($qb->expr()->eq('parent', $qb->createNamedParameter($share->getId())))
247
+                ->andWhere($qb->expr()->neq('permissions', $qb->createNamedParameter(0)))
248
+                ->set('permissions', $qb->createNamedParameter($share->getPermissions()))
249
+                ->execute();
250
+
251
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
252
+            $qb = $this->dbConn->getQueryBuilder();
253
+            $qb->update('share')
254
+                ->where($qb->expr()->eq('id', $qb->createNamedParameter($share->getId())))
255
+                ->set('password', $qb->createNamedParameter($share->getPassword()))
256
+                ->set('uid_owner', $qb->createNamedParameter($share->getShareOwner()))
257
+                ->set('uid_initiator', $qb->createNamedParameter($share->getSharedBy()))
258
+                ->set('permissions', $qb->createNamedParameter($share->getPermissions()))
259
+                ->set('item_source', $qb->createNamedParameter($share->getNode()->getId()))
260
+                ->set('file_source', $qb->createNamedParameter($share->getNode()->getId()))
261
+                ->set('token', $qb->createNamedParameter($share->getToken()))
262
+                ->set('expiration', $qb->createNamedParameter($share->getExpirationDate(), IQueryBuilder::PARAM_DATE))
263
+                ->execute();
264
+        }
265
+
266
+        return $share;
267
+    }
268
+
269
+    /**
270
+     * Get all children of this share
271
+     * FIXME: remove once https://github.com/owncloud/core/pull/21660 is in
272
+     *
273
+     * @param \OCP\Share\IShare $parent
274
+     * @return \OCP\Share\IShare[]
275
+     */
276
+    public function getChildren(\OCP\Share\IShare $parent) {
277
+        $children = [];
278
+
279
+        $qb = $this->dbConn->getQueryBuilder();
280
+        $qb->select('*')
281
+            ->from('share')
282
+            ->where($qb->expr()->eq('parent', $qb->createNamedParameter($parent->getId())))
283
+            ->andWhere(
284
+                $qb->expr()->in(
285
+                    'share_type',
286
+                    $qb->createNamedParameter([
287
+                        \OCP\Share::SHARE_TYPE_USER,
288
+                        \OCP\Share::SHARE_TYPE_GROUP,
289
+                        \OCP\Share::SHARE_TYPE_LINK,
290
+                    ], IQueryBuilder::PARAM_INT_ARRAY)
291
+                )
292
+            )
293
+            ->andWhere($qb->expr()->orX(
294
+                $qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
295
+                $qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
296
+            ))
297
+            ->orderBy('id');
298
+
299
+        $cursor = $qb->execute();
300
+        while($data = $cursor->fetch()) {
301
+            $children[] = $this->createShare($data);
302
+        }
303
+        $cursor->closeCursor();
304
+
305
+        return $children;
306
+    }
307
+
308
+    /**
309
+     * Delete a share
310
+     *
311
+     * @param \OCP\Share\IShare $share
312
+     */
313
+    public function delete(\OCP\Share\IShare $share) {
314
+        $qb = $this->dbConn->getQueryBuilder();
315
+        $qb->delete('share')
316
+            ->where($qb->expr()->eq('id', $qb->createNamedParameter($share->getId())));
317
+
318
+        /*
319 319
 		 * If the share is a group share delete all possible
320 320
 		 * user defined groups shares.
321 321
 		 */
322
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
323
-			$qb->orWhere($qb->expr()->eq('parent', $qb->createNamedParameter($share->getId())));
324
-		}
325
-
326
-		$qb->execute();
327
-	}
328
-
329
-	/**
330
-	 * Unshare a share from the recipient. If this is a group share
331
-	 * this means we need a special entry in the share db.
332
-	 *
333
-	 * @param \OCP\Share\IShare $share
334
-	 * @param string $recipient UserId of recipient
335
-	 * @throws BackendError
336
-	 * @throws ProviderException
337
-	 */
338
-	public function deleteFromSelf(\OCP\Share\IShare $share, $recipient) {
339
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
340
-
341
-			$group = $this->groupManager->get($share->getSharedWith());
342
-			$user = $this->userManager->get($recipient);
343
-
344
-			if (is_null($group)) {
345
-				throw new ProviderException('Group "' . $share->getSharedWith() . '" does not exist');
346
-			}
347
-
348
-			if (!$group->inGroup($user)) {
349
-				throw new ProviderException('Recipient not in receiving group');
350
-			}
351
-
352
-			// Try to fetch user specific share
353
-			$qb = $this->dbConn->getQueryBuilder();
354
-			$stmt = $qb->select('*')
355
-				->from('share')
356
-				->where($qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP)))
357
-				->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($recipient)))
358
-				->andWhere($qb->expr()->eq('parent', $qb->createNamedParameter($share->getId())))
359
-				->andWhere($qb->expr()->orX(
360
-					$qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
361
-					$qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
362
-				))
363
-				->execute();
364
-
365
-			$data = $stmt->fetch();
366
-
367
-			/*
322
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
323
+            $qb->orWhere($qb->expr()->eq('parent', $qb->createNamedParameter($share->getId())));
324
+        }
325
+
326
+        $qb->execute();
327
+    }
328
+
329
+    /**
330
+     * Unshare a share from the recipient. If this is a group share
331
+     * this means we need a special entry in the share db.
332
+     *
333
+     * @param \OCP\Share\IShare $share
334
+     * @param string $recipient UserId of recipient
335
+     * @throws BackendError
336
+     * @throws ProviderException
337
+     */
338
+    public function deleteFromSelf(\OCP\Share\IShare $share, $recipient) {
339
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
340
+
341
+            $group = $this->groupManager->get($share->getSharedWith());
342
+            $user = $this->userManager->get($recipient);
343
+
344
+            if (is_null($group)) {
345
+                throw new ProviderException('Group "' . $share->getSharedWith() . '" does not exist');
346
+            }
347
+
348
+            if (!$group->inGroup($user)) {
349
+                throw new ProviderException('Recipient not in receiving group');
350
+            }
351
+
352
+            // Try to fetch user specific share
353
+            $qb = $this->dbConn->getQueryBuilder();
354
+            $stmt = $qb->select('*')
355
+                ->from('share')
356
+                ->where($qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP)))
357
+                ->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($recipient)))
358
+                ->andWhere($qb->expr()->eq('parent', $qb->createNamedParameter($share->getId())))
359
+                ->andWhere($qb->expr()->orX(
360
+                    $qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
361
+                    $qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
362
+                ))
363
+                ->execute();
364
+
365
+            $data = $stmt->fetch();
366
+
367
+            /*
368 368
 			 * Check if there already is a user specific group share.
369 369
 			 * If there is update it (if required).
370 370
 			 */
371
-			if ($data === false) {
372
-				$qb = $this->dbConn->getQueryBuilder();
373
-
374
-				$type = $share->getNodeType();
375
-
376
-				//Insert new share
377
-				$qb->insert('share')
378
-					->values([
379
-						'share_type' => $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP),
380
-						'share_with' => $qb->createNamedParameter($recipient),
381
-						'uid_owner' => $qb->createNamedParameter($share->getShareOwner()),
382
-						'uid_initiator' => $qb->createNamedParameter($share->getSharedBy()),
383
-						'parent' => $qb->createNamedParameter($share->getId()),
384
-						'item_type' => $qb->createNamedParameter($type),
385
-						'item_source' => $qb->createNamedParameter($share->getNodeId()),
386
-						'file_source' => $qb->createNamedParameter($share->getNodeId()),
387
-						'file_target' => $qb->createNamedParameter($share->getTarget()),
388
-						'permissions' => $qb->createNamedParameter(0),
389
-						'stime' => $qb->createNamedParameter($share->getShareTime()->getTimestamp()),
390
-					])->execute();
391
-
392
-			} else if ($data['permissions'] !== 0) {
393
-
394
-				// Update existing usergroup share
395
-				$qb = $this->dbConn->getQueryBuilder();
396
-				$qb->update('share')
397
-					->set('permissions', $qb->createNamedParameter(0))
398
-					->where($qb->expr()->eq('id', $qb->createNamedParameter($data['id'])))
399
-					->execute();
400
-			}
401
-
402
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
403
-
404
-			if ($share->getSharedWith() !== $recipient) {
405
-				throw new ProviderException('Recipient does not match');
406
-			}
407
-
408
-			// We can just delete user and link shares
409
-			$this->delete($share);
410
-		} else {
411
-			throw new ProviderException('Invalid shareType');
412
-		}
413
-	}
414
-
415
-	/**
416
-	 * @inheritdoc
417
-	 */
418
-	public function move(\OCP\Share\IShare $share, $recipient) {
419
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
420
-			// Just update the target
421
-			$qb = $this->dbConn->getQueryBuilder();
422
-			$qb->update('share')
423
-				->set('file_target', $qb->createNamedParameter($share->getTarget()))
424
-				->where($qb->expr()->eq('id', $qb->createNamedParameter($share->getId())))
425
-				->execute();
426
-
427
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
428
-
429
-			// Check if there is a usergroup share
430
-			$qb = $this->dbConn->getQueryBuilder();
431
-			$stmt = $qb->select('id')
432
-				->from('share')
433
-				->where($qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP)))
434
-				->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($recipient)))
435
-				->andWhere($qb->expr()->eq('parent', $qb->createNamedParameter($share->getId())))
436
-				->andWhere($qb->expr()->orX(
437
-					$qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
438
-					$qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
439
-				))
440
-				->setMaxResults(1)
441
-				->execute();
442
-
443
-			$data = $stmt->fetch();
444
-			$stmt->closeCursor();
445
-
446
-			if ($data === false) {
447
-				// No usergroup share yet. Create one.
448
-				$qb = $this->dbConn->getQueryBuilder();
449
-				$qb->insert('share')
450
-					->values([
451
-						'share_type' => $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP),
452
-						'share_with' => $qb->createNamedParameter($recipient),
453
-						'uid_owner' => $qb->createNamedParameter($share->getShareOwner()),
454
-						'uid_initiator' => $qb->createNamedParameter($share->getSharedBy()),
455
-						'parent' => $qb->createNamedParameter($share->getId()),
456
-						'item_type' => $qb->createNamedParameter($share->getNodeType()),
457
-						'item_source' => $qb->createNamedParameter($share->getNodeId()),
458
-						'file_source' => $qb->createNamedParameter($share->getNodeId()),
459
-						'file_target' => $qb->createNamedParameter($share->getTarget()),
460
-						'permissions' => $qb->createNamedParameter($share->getPermissions()),
461
-						'stime' => $qb->createNamedParameter($share->getShareTime()->getTimestamp()),
462
-					])->execute();
463
-			} else {
464
-				// Already a usergroup share. Update it.
465
-				$qb = $this->dbConn->getQueryBuilder();
466
-				$qb->update('share')
467
-					->set('file_target', $qb->createNamedParameter($share->getTarget()))
468
-					->where($qb->expr()->eq('id', $qb->createNamedParameter($data['id'])))
469
-					->execute();
470
-			}
471
-		}
472
-
473
-		return $share;
474
-	}
475
-
476
-	public function getSharesInFolder($userId, Folder $node, $reshares) {
477
-		$qb = $this->dbConn->getQueryBuilder();
478
-		$qb->select('*')
479
-			->from('share', 's')
480
-			->andWhere($qb->expr()->orX(
481
-				$qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
482
-				$qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
483
-			));
484
-
485
-		$qb->andWhere($qb->expr()->orX(
486
-			$qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_USER)),
487
-			$qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_GROUP)),
488
-			$qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_LINK))
489
-		));
490
-
491
-		/**
492
-		 * Reshares for this user are shares where they are the owner.
493
-		 */
494
-		if ($reshares === false) {
495
-			$qb->andWhere($qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId)));
496
-		} else {
497
-			$qb->andWhere(
498
-				$qb->expr()->orX(
499
-					$qb->expr()->eq('uid_owner', $qb->createNamedParameter($userId)),
500
-					$qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId))
501
-				)
502
-			);
503
-		}
504
-
505
-		$qb->innerJoin('s', 'filecache' ,'f', $qb->expr()->eq('s.file_source', 'f.fileid'));
506
-		$qb->andWhere($qb->expr()->eq('f.parent', $qb->createNamedParameter($node->getId())));
507
-
508
-		$qb->orderBy('id');
509
-
510
-		$cursor = $qb->execute();
511
-		$shares = [];
512
-		while ($data = $cursor->fetch()) {
513
-			$shares[$data['fileid']][] = $this->createShare($data);
514
-		}
515
-		$cursor->closeCursor();
516
-
517
-		return $shares;
518
-	}
519
-
520
-	/**
521
-	 * @inheritdoc
522
-	 */
523
-	public function getSharesBy($userId, $shareType, $node, $reshares, $limit, $offset) {
524
-		$qb = $this->dbConn->getQueryBuilder();
525
-		$qb->select('*')
526
-			->from('share')
527
-			->andWhere($qb->expr()->orX(
528
-				$qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
529
-				$qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
530
-			));
531
-
532
-		$qb->andWhere($qb->expr()->eq('share_type', $qb->createNamedParameter($shareType)));
533
-
534
-		/**
535
-		 * Reshares for this user are shares where they are the owner.
536
-		 */
537
-		if ($reshares === false) {
538
-			$qb->andWhere($qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId)));
539
-		} else {
540
-			$qb->andWhere(
541
-				$qb->expr()->orX(
542
-					$qb->expr()->eq('uid_owner', $qb->createNamedParameter($userId)),
543
-					$qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId))
544
-				)
545
-			);
546
-		}
547
-
548
-		if ($node !== null) {
549
-			$qb->andWhere($qb->expr()->eq('file_source', $qb->createNamedParameter($node->getId())));
550
-		}
551
-
552
-		if ($limit !== -1) {
553
-			$qb->setMaxResults($limit);
554
-		}
555
-
556
-		$qb->setFirstResult($offset);
557
-		$qb->orderBy('id');
558
-
559
-		$cursor = $qb->execute();
560
-		$shares = [];
561
-		while($data = $cursor->fetch()) {
562
-			$shares[] = $this->createShare($data);
563
-		}
564
-		$cursor->closeCursor();
565
-
566
-		return $shares;
567
-	}
568
-
569
-	/**
570
-	 * @inheritdoc
571
-	 */
572
-	public function getShareById($id, $recipientId = null) {
573
-		$qb = $this->dbConn->getQueryBuilder();
574
-
575
-		$qb->select('*')
576
-			->from('share')
577
-			->where($qb->expr()->eq('id', $qb->createNamedParameter($id)))
578
-			->andWhere(
579
-				$qb->expr()->in(
580
-					'share_type',
581
-					$qb->createNamedParameter([
582
-						\OCP\Share::SHARE_TYPE_USER,
583
-						\OCP\Share::SHARE_TYPE_GROUP,
584
-						\OCP\Share::SHARE_TYPE_LINK,
585
-					], IQueryBuilder::PARAM_INT_ARRAY)
586
-				)
587
-			)
588
-			->andWhere($qb->expr()->orX(
589
-				$qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
590
-				$qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
591
-			));
592
-
593
-		$cursor = $qb->execute();
594
-		$data = $cursor->fetch();
595
-		$cursor->closeCursor();
596
-
597
-		if ($data === false) {
598
-			throw new ShareNotFound();
599
-		}
600
-
601
-		try {
602
-			$share = $this->createShare($data);
603
-		} catch (InvalidShare $e) {
604
-			throw new ShareNotFound();
605
-		}
606
-
607
-		// If the recipient is set for a group share resolve to that user
608
-		if ($recipientId !== null && $share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
609
-			$share = $this->resolveGroupShares([$share], $recipientId)[0];
610
-		}
611
-
612
-		return $share;
613
-	}
614
-
615
-	/**
616
-	 * Get shares for a given path
617
-	 *
618
-	 * @param \OCP\Files\Node $path
619
-	 * @return \OCP\Share\IShare[]
620
-	 */
621
-	public function getSharesByPath(Node $path) {
622
-		$qb = $this->dbConn->getQueryBuilder();
623
-
624
-		$cursor = $qb->select('*')
625
-			->from('share')
626
-			->andWhere($qb->expr()->eq('file_source', $qb->createNamedParameter($path->getId())))
627
-			->andWhere(
628
-				$qb->expr()->orX(
629
-					$qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_USER)),
630
-					$qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_GROUP))
631
-				)
632
-			)
633
-			->andWhere($qb->expr()->orX(
634
-				$qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
635
-				$qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
636
-			))
637
-			->execute();
638
-
639
-		$shares = [];
640
-		while($data = $cursor->fetch()) {
641
-			$shares[] = $this->createShare($data);
642
-		}
643
-		$cursor->closeCursor();
644
-
645
-		return $shares;
646
-	}
647
-
648
-	/**
649
-	 * Returns whether the given database result can be interpreted as
650
-	 * a share with accessible file (not trashed, not deleted)
651
-	 */
652
-	private function isAccessibleResult($data) {
653
-		// exclude shares leading to deleted file entries
654
-		if ($data['fileid'] === null) {
655
-			return false;
656
-		}
657
-
658
-		// exclude shares leading to trashbin on home storages
659
-		$pathSections = explode('/', $data['path'], 2);
660
-		// FIXME: would not detect rare md5'd home storage case properly
661
-		if ($pathSections[0] !== 'files'
662
-		    	&& in_array(explode(':', $data['storage_string_id'], 2)[0], array('home', 'object'))) {
663
-			return false;
664
-		}
665
-		return true;
666
-	}
667
-
668
-	/**
669
-	 * @inheritdoc
670
-	 */
671
-	public function getSharedWith($userId, $shareType, $node, $limit, $offset) {
672
-		/** @var Share[] $shares */
673
-		$shares = [];
674
-
675
-		if ($shareType === \OCP\Share::SHARE_TYPE_USER) {
676
-			//Get shares directly with this user
677
-			$qb = $this->dbConn->getQueryBuilder();
678
-			$qb->select('s.*',
679
-				'f.fileid', 'f.path', 'f.permissions AS f_permissions', 'f.storage', 'f.path_hash',
680
-				'f.parent AS f_parent', 'f.name', 'f.mimetype', 'f.mimepart', 'f.size', 'f.mtime', 'f.storage_mtime',
681
-				'f.encrypted', 'f.unencrypted_size', 'f.etag', 'f.checksum'
682
-			)
683
-				->selectAlias('st.id', 'storage_string_id')
684
-				->from('share', 's')
685
-				->leftJoin('s', 'filecache', 'f', $qb->expr()->eq('s.file_source', 'f.fileid'))
686
-				->leftJoin('f', 'storages', 'st', $qb->expr()->eq('f.storage', 'st.numeric_id'));
687
-
688
-			// Order by id
689
-			$qb->orderBy('s.id');
690
-
691
-			// Set limit and offset
692
-			if ($limit !== -1) {
693
-				$qb->setMaxResults($limit);
694
-			}
695
-			$qb->setFirstResult($offset);
696
-
697
-			$qb->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_USER)))
698
-				->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($userId)))
699
-				->andWhere($qb->expr()->orX(
700
-					$qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
701
-					$qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
702
-				));
703
-
704
-			// Filter by node if provided
705
-			if ($node !== null) {
706
-				$qb->andWhere($qb->expr()->eq('file_source', $qb->createNamedParameter($node->getId())));
707
-			}
708
-
709
-			$cursor = $qb->execute();
710
-
711
-			while($data = $cursor->fetch()) {
712
-				if ($this->isAccessibleResult($data)) {
713
-					$shares[] = $this->createShare($data);
714
-				}
715
-			}
716
-			$cursor->closeCursor();
717
-
718
-		} else if ($shareType === \OCP\Share::SHARE_TYPE_GROUP) {
719
-			$user = $this->userManager->get($userId);
720
-			$allGroups = $this->groupManager->getUserGroups($user);
721
-
722
-			/** @var Share[] $shares2 */
723
-			$shares2 = [];
724
-
725
-			$start = 0;
726
-			while(true) {
727
-				$groups = array_slice($allGroups, $start, 100);
728
-				$start += 100;
729
-
730
-				if ($groups === []) {
731
-					break;
732
-				}
733
-
734
-				$qb = $this->dbConn->getQueryBuilder();
735
-				$qb->select('s.*',
736
-					'f.fileid', 'f.path', 'f.permissions AS f_permissions', 'f.storage', 'f.path_hash',
737
-					'f.parent AS f_parent', 'f.name', 'f.mimetype', 'f.mimepart', 'f.size', 'f.mtime', 'f.storage_mtime',
738
-					'f.encrypted', 'f.unencrypted_size', 'f.etag', 'f.checksum'
739
-				)
740
-					->selectAlias('st.id', 'storage_string_id')
741
-					->from('share', 's')
742
-					->leftJoin('s', 'filecache', 'f', $qb->expr()->eq('s.file_source', 'f.fileid'))
743
-					->leftJoin('f', 'storages', 'st', $qb->expr()->eq('f.storage', 'st.numeric_id'))
744
-					->orderBy('s.id')
745
-					->setFirstResult(0);
746
-
747
-				if ($limit !== -1) {
748
-					$qb->setMaxResults($limit - count($shares));
749
-				}
750
-
751
-				// Filter by node if provided
752
-				if ($node !== null) {
753
-					$qb->andWhere($qb->expr()->eq('file_source', $qb->createNamedParameter($node->getId())));
754
-				}
755
-
756
-
757
-				$groups = array_filter($groups, function($group) { return $group instanceof IGroup; });
758
-				$groups = array_map(function(IGroup $group) { return $group->getGID(); }, $groups);
759
-
760
-				$qb->andWhere($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_GROUP)))
761
-					->andWhere($qb->expr()->in('share_with', $qb->createNamedParameter(
762
-						$groups,
763
-						IQueryBuilder::PARAM_STR_ARRAY
764
-					)))
765
-					->andWhere($qb->expr()->orX(
766
-						$qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
767
-						$qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
768
-					));
769
-
770
-				$cursor = $qb->execute();
771
-				while($data = $cursor->fetch()) {
772
-					if ($offset > 0) {
773
-						$offset--;
774
-						continue;
775
-					}
776
-
777
-					if ($this->isAccessibleResult($data)) {
778
-						$shares2[] = $this->createShare($data);
779
-					}
780
-				}
781
-				$cursor->closeCursor();
782
-			}
783
-
784
-			/*
371
+            if ($data === false) {
372
+                $qb = $this->dbConn->getQueryBuilder();
373
+
374
+                $type = $share->getNodeType();
375
+
376
+                //Insert new share
377
+                $qb->insert('share')
378
+                    ->values([
379
+                        'share_type' => $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP),
380
+                        'share_with' => $qb->createNamedParameter($recipient),
381
+                        'uid_owner' => $qb->createNamedParameter($share->getShareOwner()),
382
+                        'uid_initiator' => $qb->createNamedParameter($share->getSharedBy()),
383
+                        'parent' => $qb->createNamedParameter($share->getId()),
384
+                        'item_type' => $qb->createNamedParameter($type),
385
+                        'item_source' => $qb->createNamedParameter($share->getNodeId()),
386
+                        'file_source' => $qb->createNamedParameter($share->getNodeId()),
387
+                        'file_target' => $qb->createNamedParameter($share->getTarget()),
388
+                        'permissions' => $qb->createNamedParameter(0),
389
+                        'stime' => $qb->createNamedParameter($share->getShareTime()->getTimestamp()),
390
+                    ])->execute();
391
+
392
+            } else if ($data['permissions'] !== 0) {
393
+
394
+                // Update existing usergroup share
395
+                $qb = $this->dbConn->getQueryBuilder();
396
+                $qb->update('share')
397
+                    ->set('permissions', $qb->createNamedParameter(0))
398
+                    ->where($qb->expr()->eq('id', $qb->createNamedParameter($data['id'])))
399
+                    ->execute();
400
+            }
401
+
402
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
403
+
404
+            if ($share->getSharedWith() !== $recipient) {
405
+                throw new ProviderException('Recipient does not match');
406
+            }
407
+
408
+            // We can just delete user and link shares
409
+            $this->delete($share);
410
+        } else {
411
+            throw new ProviderException('Invalid shareType');
412
+        }
413
+    }
414
+
415
+    /**
416
+     * @inheritdoc
417
+     */
418
+    public function move(\OCP\Share\IShare $share, $recipient) {
419
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
420
+            // Just update the target
421
+            $qb = $this->dbConn->getQueryBuilder();
422
+            $qb->update('share')
423
+                ->set('file_target', $qb->createNamedParameter($share->getTarget()))
424
+                ->where($qb->expr()->eq('id', $qb->createNamedParameter($share->getId())))
425
+                ->execute();
426
+
427
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
428
+
429
+            // Check if there is a usergroup share
430
+            $qb = $this->dbConn->getQueryBuilder();
431
+            $stmt = $qb->select('id')
432
+                ->from('share')
433
+                ->where($qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP)))
434
+                ->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($recipient)))
435
+                ->andWhere($qb->expr()->eq('parent', $qb->createNamedParameter($share->getId())))
436
+                ->andWhere($qb->expr()->orX(
437
+                    $qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
438
+                    $qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
439
+                ))
440
+                ->setMaxResults(1)
441
+                ->execute();
442
+
443
+            $data = $stmt->fetch();
444
+            $stmt->closeCursor();
445
+
446
+            if ($data === false) {
447
+                // No usergroup share yet. Create one.
448
+                $qb = $this->dbConn->getQueryBuilder();
449
+                $qb->insert('share')
450
+                    ->values([
451
+                        'share_type' => $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP),
452
+                        'share_with' => $qb->createNamedParameter($recipient),
453
+                        'uid_owner' => $qb->createNamedParameter($share->getShareOwner()),
454
+                        'uid_initiator' => $qb->createNamedParameter($share->getSharedBy()),
455
+                        'parent' => $qb->createNamedParameter($share->getId()),
456
+                        'item_type' => $qb->createNamedParameter($share->getNodeType()),
457
+                        'item_source' => $qb->createNamedParameter($share->getNodeId()),
458
+                        'file_source' => $qb->createNamedParameter($share->getNodeId()),
459
+                        'file_target' => $qb->createNamedParameter($share->getTarget()),
460
+                        'permissions' => $qb->createNamedParameter($share->getPermissions()),
461
+                        'stime' => $qb->createNamedParameter($share->getShareTime()->getTimestamp()),
462
+                    ])->execute();
463
+            } else {
464
+                // Already a usergroup share. Update it.
465
+                $qb = $this->dbConn->getQueryBuilder();
466
+                $qb->update('share')
467
+                    ->set('file_target', $qb->createNamedParameter($share->getTarget()))
468
+                    ->where($qb->expr()->eq('id', $qb->createNamedParameter($data['id'])))
469
+                    ->execute();
470
+            }
471
+        }
472
+
473
+        return $share;
474
+    }
475
+
476
+    public function getSharesInFolder($userId, Folder $node, $reshares) {
477
+        $qb = $this->dbConn->getQueryBuilder();
478
+        $qb->select('*')
479
+            ->from('share', 's')
480
+            ->andWhere($qb->expr()->orX(
481
+                $qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
482
+                $qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
483
+            ));
484
+
485
+        $qb->andWhere($qb->expr()->orX(
486
+            $qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_USER)),
487
+            $qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_GROUP)),
488
+            $qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_LINK))
489
+        ));
490
+
491
+        /**
492
+         * Reshares for this user are shares where they are the owner.
493
+         */
494
+        if ($reshares === false) {
495
+            $qb->andWhere($qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId)));
496
+        } else {
497
+            $qb->andWhere(
498
+                $qb->expr()->orX(
499
+                    $qb->expr()->eq('uid_owner', $qb->createNamedParameter($userId)),
500
+                    $qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId))
501
+                )
502
+            );
503
+        }
504
+
505
+        $qb->innerJoin('s', 'filecache' ,'f', $qb->expr()->eq('s.file_source', 'f.fileid'));
506
+        $qb->andWhere($qb->expr()->eq('f.parent', $qb->createNamedParameter($node->getId())));
507
+
508
+        $qb->orderBy('id');
509
+
510
+        $cursor = $qb->execute();
511
+        $shares = [];
512
+        while ($data = $cursor->fetch()) {
513
+            $shares[$data['fileid']][] = $this->createShare($data);
514
+        }
515
+        $cursor->closeCursor();
516
+
517
+        return $shares;
518
+    }
519
+
520
+    /**
521
+     * @inheritdoc
522
+     */
523
+    public function getSharesBy($userId, $shareType, $node, $reshares, $limit, $offset) {
524
+        $qb = $this->dbConn->getQueryBuilder();
525
+        $qb->select('*')
526
+            ->from('share')
527
+            ->andWhere($qb->expr()->orX(
528
+                $qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
529
+                $qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
530
+            ));
531
+
532
+        $qb->andWhere($qb->expr()->eq('share_type', $qb->createNamedParameter($shareType)));
533
+
534
+        /**
535
+         * Reshares for this user are shares where they are the owner.
536
+         */
537
+        if ($reshares === false) {
538
+            $qb->andWhere($qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId)));
539
+        } else {
540
+            $qb->andWhere(
541
+                $qb->expr()->orX(
542
+                    $qb->expr()->eq('uid_owner', $qb->createNamedParameter($userId)),
543
+                    $qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId))
544
+                )
545
+            );
546
+        }
547
+
548
+        if ($node !== null) {
549
+            $qb->andWhere($qb->expr()->eq('file_source', $qb->createNamedParameter($node->getId())));
550
+        }
551
+
552
+        if ($limit !== -1) {
553
+            $qb->setMaxResults($limit);
554
+        }
555
+
556
+        $qb->setFirstResult($offset);
557
+        $qb->orderBy('id');
558
+
559
+        $cursor = $qb->execute();
560
+        $shares = [];
561
+        while($data = $cursor->fetch()) {
562
+            $shares[] = $this->createShare($data);
563
+        }
564
+        $cursor->closeCursor();
565
+
566
+        return $shares;
567
+    }
568
+
569
+    /**
570
+     * @inheritdoc
571
+     */
572
+    public function getShareById($id, $recipientId = null) {
573
+        $qb = $this->dbConn->getQueryBuilder();
574
+
575
+        $qb->select('*')
576
+            ->from('share')
577
+            ->where($qb->expr()->eq('id', $qb->createNamedParameter($id)))
578
+            ->andWhere(
579
+                $qb->expr()->in(
580
+                    'share_type',
581
+                    $qb->createNamedParameter([
582
+                        \OCP\Share::SHARE_TYPE_USER,
583
+                        \OCP\Share::SHARE_TYPE_GROUP,
584
+                        \OCP\Share::SHARE_TYPE_LINK,
585
+                    ], IQueryBuilder::PARAM_INT_ARRAY)
586
+                )
587
+            )
588
+            ->andWhere($qb->expr()->orX(
589
+                $qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
590
+                $qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
591
+            ));
592
+
593
+        $cursor = $qb->execute();
594
+        $data = $cursor->fetch();
595
+        $cursor->closeCursor();
596
+
597
+        if ($data === false) {
598
+            throw new ShareNotFound();
599
+        }
600
+
601
+        try {
602
+            $share = $this->createShare($data);
603
+        } catch (InvalidShare $e) {
604
+            throw new ShareNotFound();
605
+        }
606
+
607
+        // If the recipient is set for a group share resolve to that user
608
+        if ($recipientId !== null && $share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
609
+            $share = $this->resolveGroupShares([$share], $recipientId)[0];
610
+        }
611
+
612
+        return $share;
613
+    }
614
+
615
+    /**
616
+     * Get shares for a given path
617
+     *
618
+     * @param \OCP\Files\Node $path
619
+     * @return \OCP\Share\IShare[]
620
+     */
621
+    public function getSharesByPath(Node $path) {
622
+        $qb = $this->dbConn->getQueryBuilder();
623
+
624
+        $cursor = $qb->select('*')
625
+            ->from('share')
626
+            ->andWhere($qb->expr()->eq('file_source', $qb->createNamedParameter($path->getId())))
627
+            ->andWhere(
628
+                $qb->expr()->orX(
629
+                    $qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_USER)),
630
+                    $qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_GROUP))
631
+                )
632
+            )
633
+            ->andWhere($qb->expr()->orX(
634
+                $qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
635
+                $qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
636
+            ))
637
+            ->execute();
638
+
639
+        $shares = [];
640
+        while($data = $cursor->fetch()) {
641
+            $shares[] = $this->createShare($data);
642
+        }
643
+        $cursor->closeCursor();
644
+
645
+        return $shares;
646
+    }
647
+
648
+    /**
649
+     * Returns whether the given database result can be interpreted as
650
+     * a share with accessible file (not trashed, not deleted)
651
+     */
652
+    private function isAccessibleResult($data) {
653
+        // exclude shares leading to deleted file entries
654
+        if ($data['fileid'] === null) {
655
+            return false;
656
+        }
657
+
658
+        // exclude shares leading to trashbin on home storages
659
+        $pathSections = explode('/', $data['path'], 2);
660
+        // FIXME: would not detect rare md5'd home storage case properly
661
+        if ($pathSections[0] !== 'files'
662
+                && in_array(explode(':', $data['storage_string_id'], 2)[0], array('home', 'object'))) {
663
+            return false;
664
+        }
665
+        return true;
666
+    }
667
+
668
+    /**
669
+     * @inheritdoc
670
+     */
671
+    public function getSharedWith($userId, $shareType, $node, $limit, $offset) {
672
+        /** @var Share[] $shares */
673
+        $shares = [];
674
+
675
+        if ($shareType === \OCP\Share::SHARE_TYPE_USER) {
676
+            //Get shares directly with this user
677
+            $qb = $this->dbConn->getQueryBuilder();
678
+            $qb->select('s.*',
679
+                'f.fileid', 'f.path', 'f.permissions AS f_permissions', 'f.storage', 'f.path_hash',
680
+                'f.parent AS f_parent', 'f.name', 'f.mimetype', 'f.mimepart', 'f.size', 'f.mtime', 'f.storage_mtime',
681
+                'f.encrypted', 'f.unencrypted_size', 'f.etag', 'f.checksum'
682
+            )
683
+                ->selectAlias('st.id', 'storage_string_id')
684
+                ->from('share', 's')
685
+                ->leftJoin('s', 'filecache', 'f', $qb->expr()->eq('s.file_source', 'f.fileid'))
686
+                ->leftJoin('f', 'storages', 'st', $qb->expr()->eq('f.storage', 'st.numeric_id'));
687
+
688
+            // Order by id
689
+            $qb->orderBy('s.id');
690
+
691
+            // Set limit and offset
692
+            if ($limit !== -1) {
693
+                $qb->setMaxResults($limit);
694
+            }
695
+            $qb->setFirstResult($offset);
696
+
697
+            $qb->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_USER)))
698
+                ->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($userId)))
699
+                ->andWhere($qb->expr()->orX(
700
+                    $qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
701
+                    $qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
702
+                ));
703
+
704
+            // Filter by node if provided
705
+            if ($node !== null) {
706
+                $qb->andWhere($qb->expr()->eq('file_source', $qb->createNamedParameter($node->getId())));
707
+            }
708
+
709
+            $cursor = $qb->execute();
710
+
711
+            while($data = $cursor->fetch()) {
712
+                if ($this->isAccessibleResult($data)) {
713
+                    $shares[] = $this->createShare($data);
714
+                }
715
+            }
716
+            $cursor->closeCursor();
717
+
718
+        } else if ($shareType === \OCP\Share::SHARE_TYPE_GROUP) {
719
+            $user = $this->userManager->get($userId);
720
+            $allGroups = $this->groupManager->getUserGroups($user);
721
+
722
+            /** @var Share[] $shares2 */
723
+            $shares2 = [];
724
+
725
+            $start = 0;
726
+            while(true) {
727
+                $groups = array_slice($allGroups, $start, 100);
728
+                $start += 100;
729
+
730
+                if ($groups === []) {
731
+                    break;
732
+                }
733
+
734
+                $qb = $this->dbConn->getQueryBuilder();
735
+                $qb->select('s.*',
736
+                    'f.fileid', 'f.path', 'f.permissions AS f_permissions', 'f.storage', 'f.path_hash',
737
+                    'f.parent AS f_parent', 'f.name', 'f.mimetype', 'f.mimepart', 'f.size', 'f.mtime', 'f.storage_mtime',
738
+                    'f.encrypted', 'f.unencrypted_size', 'f.etag', 'f.checksum'
739
+                )
740
+                    ->selectAlias('st.id', 'storage_string_id')
741
+                    ->from('share', 's')
742
+                    ->leftJoin('s', 'filecache', 'f', $qb->expr()->eq('s.file_source', 'f.fileid'))
743
+                    ->leftJoin('f', 'storages', 'st', $qb->expr()->eq('f.storage', 'st.numeric_id'))
744
+                    ->orderBy('s.id')
745
+                    ->setFirstResult(0);
746
+
747
+                if ($limit !== -1) {
748
+                    $qb->setMaxResults($limit - count($shares));
749
+                }
750
+
751
+                // Filter by node if provided
752
+                if ($node !== null) {
753
+                    $qb->andWhere($qb->expr()->eq('file_source', $qb->createNamedParameter($node->getId())));
754
+                }
755
+
756
+
757
+                $groups = array_filter($groups, function($group) { return $group instanceof IGroup; });
758
+                $groups = array_map(function(IGroup $group) { return $group->getGID(); }, $groups);
759
+
760
+                $qb->andWhere($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_GROUP)))
761
+                    ->andWhere($qb->expr()->in('share_with', $qb->createNamedParameter(
762
+                        $groups,
763
+                        IQueryBuilder::PARAM_STR_ARRAY
764
+                    )))
765
+                    ->andWhere($qb->expr()->orX(
766
+                        $qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
767
+                        $qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
768
+                    ));
769
+
770
+                $cursor = $qb->execute();
771
+                while($data = $cursor->fetch()) {
772
+                    if ($offset > 0) {
773
+                        $offset--;
774
+                        continue;
775
+                    }
776
+
777
+                    if ($this->isAccessibleResult($data)) {
778
+                        $shares2[] = $this->createShare($data);
779
+                    }
780
+                }
781
+                $cursor->closeCursor();
782
+            }
783
+
784
+            /*
785 785
  			 * Resolve all group shares to user specific shares
786 786
  			 */
787
-			$shares = $this->resolveGroupShares($shares2, $userId);
788
-		} else {
789
-			throw new BackendError('Invalid backend');
790
-		}
791
-
792
-
793
-		return $shares;
794
-	}
795
-
796
-	/**
797
-	 * Get a share by token
798
-	 *
799
-	 * @param string $token
800
-	 * @return \OCP\Share\IShare
801
-	 * @throws ShareNotFound
802
-	 */
803
-	public function getShareByToken($token) {
804
-		$qb = $this->dbConn->getQueryBuilder();
805
-
806
-		$cursor = $qb->select('*')
807
-			->from('share')
808
-			->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_LINK)))
809
-			->andWhere($qb->expr()->eq('token', $qb->createNamedParameter($token)))
810
-			->andWhere($qb->expr()->orX(
811
-				$qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
812
-				$qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
813
-			))
814
-			->execute();
815
-
816
-		$data = $cursor->fetch();
817
-
818
-		if ($data === false) {
819
-			throw new ShareNotFound();
820
-		}
821
-
822
-		try {
823
-			$share = $this->createShare($data);
824
-		} catch (InvalidShare $e) {
825
-			throw new ShareNotFound();
826
-		}
827
-
828
-		return $share;
829
-	}
830
-
831
-	/**
832
-	 * Create a share object from an database row
833
-	 *
834
-	 * @param mixed[] $data
835
-	 * @return \OCP\Share\IShare
836
-	 * @throws InvalidShare
837
-	 */
838
-	private function createShare($data) {
839
-		$share = new Share($this->rootFolder, $this->userManager);
840
-		$share->setId((int)$data['id'])
841
-			->setShareType((int)$data['share_type'])
842
-			->setPermissions((int)$data['permissions'])
843
-			->setTarget($data['file_target'])
844
-			->setMailSend((bool)$data['mail_send']);
845
-
846
-		$shareTime = new \DateTime();
847
-		$shareTime->setTimestamp((int)$data['stime']);
848
-		$share->setShareTime($shareTime);
849
-
850
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
851
-			$share->setSharedWith($data['share_with']);
852
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
853
-			$share->setSharedWith($data['share_with']);
854
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
855
-			$share->setPassword($data['password']);
856
-			$share->setToken($data['token']);
857
-		}
858
-
859
-		$share->setSharedBy($data['uid_initiator']);
860
-		$share->setShareOwner($data['uid_owner']);
861
-
862
-		$share->setNodeId((int)$data['file_source']);
863
-		$share->setNodeType($data['item_type']);
864
-
865
-		if ($data['expiration'] !== null) {
866
-			$expiration = \DateTime::createFromFormat('Y-m-d H:i:s', $data['expiration']);
867
-			$share->setExpirationDate($expiration);
868
-		}
869
-
870
-		if (isset($data['f_permissions'])) {
871
-			$entryData = $data;
872
-			$entryData['permissions'] = $entryData['f_permissions'];
873
-			$entryData['parent'] = $entryData['f_parent'];
874
-			$share->setNodeCacheEntry(Cache::cacheEntryFromData($entryData,
875
-				\OC::$server->getMimeTypeLoader()));
876
-		}
877
-
878
-		$share->setProviderId($this->identifier());
879
-
880
-		return $share;
881
-	}
882
-
883
-	/**
884
-	 * @param Share[] $shares
885
-	 * @param $userId
886
-	 * @return Share[] The updates shares if no update is found for a share return the original
887
-	 */
888
-	private function resolveGroupShares($shares, $userId) {
889
-		$result = [];
890
-
891
-		$start = 0;
892
-		while(true) {
893
-			/** @var Share[] $shareSlice */
894
-			$shareSlice = array_slice($shares, $start, 100);
895
-			$start += 100;
896
-
897
-			if ($shareSlice === []) {
898
-				break;
899
-			}
900
-
901
-			/** @var int[] $ids */
902
-			$ids = [];
903
-			/** @var Share[] $shareMap */
904
-			$shareMap = [];
905
-
906
-			foreach ($shareSlice as $share) {
907
-				$ids[] = (int)$share->getId();
908
-				$shareMap[$share->getId()] = $share;
909
-			}
910
-
911
-			$qb = $this->dbConn->getQueryBuilder();
912
-
913
-			$query = $qb->select('*')
914
-				->from('share')
915
-				->where($qb->expr()->in('parent', $qb->createNamedParameter($ids, IQueryBuilder::PARAM_INT_ARRAY)))
916
-				->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($userId)))
917
-				->andWhere($qb->expr()->orX(
918
-					$qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
919
-					$qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
920
-				));
921
-
922
-			$stmt = $query->execute();
923
-
924
-			while($data = $stmt->fetch()) {
925
-				$shareMap[$data['parent']]->setPermissions((int)$data['permissions']);
926
-				$shareMap[$data['parent']]->setTarget($data['file_target']);
927
-			}
928
-
929
-			$stmt->closeCursor();
930
-
931
-			foreach ($shareMap as $share) {
932
-				$result[] = $share;
933
-			}
934
-		}
935
-
936
-		return $result;
937
-	}
938
-
939
-	/**
940
-	 * A user is deleted from the system
941
-	 * So clean up the relevant shares.
942
-	 *
943
-	 * @param string $uid
944
-	 * @param int $shareType
945
-	 */
946
-	public function userDeleted($uid, $shareType) {
947
-		$qb = $this->dbConn->getQueryBuilder();
948
-
949
-		$qb->delete('share');
950
-
951
-		if ($shareType === \OCP\Share::SHARE_TYPE_USER) {
952
-			/*
787
+            $shares = $this->resolveGroupShares($shares2, $userId);
788
+        } else {
789
+            throw new BackendError('Invalid backend');
790
+        }
791
+
792
+
793
+        return $shares;
794
+    }
795
+
796
+    /**
797
+     * Get a share by token
798
+     *
799
+     * @param string $token
800
+     * @return \OCP\Share\IShare
801
+     * @throws ShareNotFound
802
+     */
803
+    public function getShareByToken($token) {
804
+        $qb = $this->dbConn->getQueryBuilder();
805
+
806
+        $cursor = $qb->select('*')
807
+            ->from('share')
808
+            ->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_LINK)))
809
+            ->andWhere($qb->expr()->eq('token', $qb->createNamedParameter($token)))
810
+            ->andWhere($qb->expr()->orX(
811
+                $qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
812
+                $qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
813
+            ))
814
+            ->execute();
815
+
816
+        $data = $cursor->fetch();
817
+
818
+        if ($data === false) {
819
+            throw new ShareNotFound();
820
+        }
821
+
822
+        try {
823
+            $share = $this->createShare($data);
824
+        } catch (InvalidShare $e) {
825
+            throw new ShareNotFound();
826
+        }
827
+
828
+        return $share;
829
+    }
830
+
831
+    /**
832
+     * Create a share object from an database row
833
+     *
834
+     * @param mixed[] $data
835
+     * @return \OCP\Share\IShare
836
+     * @throws InvalidShare
837
+     */
838
+    private function createShare($data) {
839
+        $share = new Share($this->rootFolder, $this->userManager);
840
+        $share->setId((int)$data['id'])
841
+            ->setShareType((int)$data['share_type'])
842
+            ->setPermissions((int)$data['permissions'])
843
+            ->setTarget($data['file_target'])
844
+            ->setMailSend((bool)$data['mail_send']);
845
+
846
+        $shareTime = new \DateTime();
847
+        $shareTime->setTimestamp((int)$data['stime']);
848
+        $share->setShareTime($shareTime);
849
+
850
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
851
+            $share->setSharedWith($data['share_with']);
852
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
853
+            $share->setSharedWith($data['share_with']);
854
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
855
+            $share->setPassword($data['password']);
856
+            $share->setToken($data['token']);
857
+        }
858
+
859
+        $share->setSharedBy($data['uid_initiator']);
860
+        $share->setShareOwner($data['uid_owner']);
861
+
862
+        $share->setNodeId((int)$data['file_source']);
863
+        $share->setNodeType($data['item_type']);
864
+
865
+        if ($data['expiration'] !== null) {
866
+            $expiration = \DateTime::createFromFormat('Y-m-d H:i:s', $data['expiration']);
867
+            $share->setExpirationDate($expiration);
868
+        }
869
+
870
+        if (isset($data['f_permissions'])) {
871
+            $entryData = $data;
872
+            $entryData['permissions'] = $entryData['f_permissions'];
873
+            $entryData['parent'] = $entryData['f_parent'];
874
+            $share->setNodeCacheEntry(Cache::cacheEntryFromData($entryData,
875
+                \OC::$server->getMimeTypeLoader()));
876
+        }
877
+
878
+        $share->setProviderId($this->identifier());
879
+
880
+        return $share;
881
+    }
882
+
883
+    /**
884
+     * @param Share[] $shares
885
+     * @param $userId
886
+     * @return Share[] The updates shares if no update is found for a share return the original
887
+     */
888
+    private function resolveGroupShares($shares, $userId) {
889
+        $result = [];
890
+
891
+        $start = 0;
892
+        while(true) {
893
+            /** @var Share[] $shareSlice */
894
+            $shareSlice = array_slice($shares, $start, 100);
895
+            $start += 100;
896
+
897
+            if ($shareSlice === []) {
898
+                break;
899
+            }
900
+
901
+            /** @var int[] $ids */
902
+            $ids = [];
903
+            /** @var Share[] $shareMap */
904
+            $shareMap = [];
905
+
906
+            foreach ($shareSlice as $share) {
907
+                $ids[] = (int)$share->getId();
908
+                $shareMap[$share->getId()] = $share;
909
+            }
910
+
911
+            $qb = $this->dbConn->getQueryBuilder();
912
+
913
+            $query = $qb->select('*')
914
+                ->from('share')
915
+                ->where($qb->expr()->in('parent', $qb->createNamedParameter($ids, IQueryBuilder::PARAM_INT_ARRAY)))
916
+                ->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($userId)))
917
+                ->andWhere($qb->expr()->orX(
918
+                    $qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
919
+                    $qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
920
+                ));
921
+
922
+            $stmt = $query->execute();
923
+
924
+            while($data = $stmt->fetch()) {
925
+                $shareMap[$data['parent']]->setPermissions((int)$data['permissions']);
926
+                $shareMap[$data['parent']]->setTarget($data['file_target']);
927
+            }
928
+
929
+            $stmt->closeCursor();
930
+
931
+            foreach ($shareMap as $share) {
932
+                $result[] = $share;
933
+            }
934
+        }
935
+
936
+        return $result;
937
+    }
938
+
939
+    /**
940
+     * A user is deleted from the system
941
+     * So clean up the relevant shares.
942
+     *
943
+     * @param string $uid
944
+     * @param int $shareType
945
+     */
946
+    public function userDeleted($uid, $shareType) {
947
+        $qb = $this->dbConn->getQueryBuilder();
948
+
949
+        $qb->delete('share');
950
+
951
+        if ($shareType === \OCP\Share::SHARE_TYPE_USER) {
952
+            /*
953 953
 			 * Delete all user shares that are owned by this user
954 954
 			 * or that are received by this user
955 955
 			 */
956 956
 
957
-			$qb->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_USER)));
957
+            $qb->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_USER)));
958 958
 
959
-			$qb->andWhere(
960
-				$qb->expr()->orX(
961
-					$qb->expr()->eq('uid_owner', $qb->createNamedParameter($uid)),
962
-					$qb->expr()->eq('share_with', $qb->createNamedParameter($uid))
963
-				)
964
-			);
965
-		} else if ($shareType === \OCP\Share::SHARE_TYPE_GROUP) {
966
-			/*
959
+            $qb->andWhere(
960
+                $qb->expr()->orX(
961
+                    $qb->expr()->eq('uid_owner', $qb->createNamedParameter($uid)),
962
+                    $qb->expr()->eq('share_with', $qb->createNamedParameter($uid))
963
+                )
964
+            );
965
+        } else if ($shareType === \OCP\Share::SHARE_TYPE_GROUP) {
966
+            /*
967 967
 			 * Delete all group shares that are owned by this user
968 968
 			 * Or special user group shares that are received by this user
969 969
 			 */
970
-			$qb->where(
971
-				$qb->expr()->andX(
972
-					$qb->expr()->orX(
973
-						$qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_GROUP)),
974
-						$qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP))
975
-					),
976
-					$qb->expr()->eq('uid_owner', $qb->createNamedParameter($uid))
977
-				)
978
-			);
979
-
980
-			$qb->orWhere(
981
-				$qb->expr()->andX(
982
-					$qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP)),
983
-					$qb->expr()->eq('share_with', $qb->createNamedParameter($uid))
984
-				)
985
-			);
986
-		} else if ($shareType === \OCP\Share::SHARE_TYPE_LINK) {
987
-			/*
970
+            $qb->where(
971
+                $qb->expr()->andX(
972
+                    $qb->expr()->orX(
973
+                        $qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_GROUP)),
974
+                        $qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP))
975
+                    ),
976
+                    $qb->expr()->eq('uid_owner', $qb->createNamedParameter($uid))
977
+                )
978
+            );
979
+
980
+            $qb->orWhere(
981
+                $qb->expr()->andX(
982
+                    $qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP)),
983
+                    $qb->expr()->eq('share_with', $qb->createNamedParameter($uid))
984
+                )
985
+            );
986
+        } else if ($shareType === \OCP\Share::SHARE_TYPE_LINK) {
987
+            /*
988 988
 			 * Delete all link shares owned by this user.
989 989
 			 * And all link shares initiated by this user (until #22327 is in)
990 990
 			 */
991
-			$qb->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_LINK)));
992
-
993
-			$qb->andWhere(
994
-				$qb->expr()->orX(
995
-					$qb->expr()->eq('uid_owner', $qb->createNamedParameter($uid)),
996
-					$qb->expr()->eq('uid_initiator', $qb->createNamedParameter($uid))
997
-				)
998
-			);
999
-		}
1000
-
1001
-		$qb->execute();
1002
-	}
1003
-
1004
-	/**
1005
-	 * Delete all shares received by this group. As well as any custom group
1006
-	 * shares for group members.
1007
-	 *
1008
-	 * @param string $gid
1009
-	 */
1010
-	public function groupDeleted($gid) {
1011
-		/*
991
+            $qb->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_LINK)));
992
+
993
+            $qb->andWhere(
994
+                $qb->expr()->orX(
995
+                    $qb->expr()->eq('uid_owner', $qb->createNamedParameter($uid)),
996
+                    $qb->expr()->eq('uid_initiator', $qb->createNamedParameter($uid))
997
+                )
998
+            );
999
+        }
1000
+
1001
+        $qb->execute();
1002
+    }
1003
+
1004
+    /**
1005
+     * Delete all shares received by this group. As well as any custom group
1006
+     * shares for group members.
1007
+     *
1008
+     * @param string $gid
1009
+     */
1010
+    public function groupDeleted($gid) {
1011
+        /*
1012 1012
 		 * First delete all custom group shares for group members
1013 1013
 		 */
1014
-		$qb = $this->dbConn->getQueryBuilder();
1015
-		$qb->select('id')
1016
-			->from('share')
1017
-			->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_GROUP)))
1018
-			->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($gid)));
1019
-
1020
-		$cursor = $qb->execute();
1021
-		$ids = [];
1022
-		while($row = $cursor->fetch()) {
1023
-			$ids[] = (int)$row['id'];
1024
-		}
1025
-		$cursor->closeCursor();
1026
-
1027
-		if (!empty($ids)) {
1028
-			$chunks = array_chunk($ids, 100);
1029
-			foreach ($chunks as $chunk) {
1030
-				$qb->delete('share')
1031
-					->where($qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP)))
1032
-					->andWhere($qb->expr()->in('parent', $qb->createNamedParameter($chunk, IQueryBuilder::PARAM_INT_ARRAY)));
1033
-				$qb->execute();
1034
-			}
1035
-		}
1036
-
1037
-		/*
1014
+        $qb = $this->dbConn->getQueryBuilder();
1015
+        $qb->select('id')
1016
+            ->from('share')
1017
+            ->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_GROUP)))
1018
+            ->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($gid)));
1019
+
1020
+        $cursor = $qb->execute();
1021
+        $ids = [];
1022
+        while($row = $cursor->fetch()) {
1023
+            $ids[] = (int)$row['id'];
1024
+        }
1025
+        $cursor->closeCursor();
1026
+
1027
+        if (!empty($ids)) {
1028
+            $chunks = array_chunk($ids, 100);
1029
+            foreach ($chunks as $chunk) {
1030
+                $qb->delete('share')
1031
+                    ->where($qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP)))
1032
+                    ->andWhere($qb->expr()->in('parent', $qb->createNamedParameter($chunk, IQueryBuilder::PARAM_INT_ARRAY)));
1033
+                $qb->execute();
1034
+            }
1035
+        }
1036
+
1037
+        /*
1038 1038
 		 * Now delete all the group shares
1039 1039
 		 */
1040
-		$qb = $this->dbConn->getQueryBuilder();
1041
-		$qb->delete('share')
1042
-			->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_GROUP)))
1043
-			->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($gid)));
1044
-		$qb->execute();
1045
-	}
1046
-
1047
-	/**
1048
-	 * Delete custom group shares to this group for this user
1049
-	 *
1050
-	 * @param string $uid
1051
-	 * @param string $gid
1052
-	 */
1053
-	public function userDeletedFromGroup($uid, $gid) {
1054
-		/*
1040
+        $qb = $this->dbConn->getQueryBuilder();
1041
+        $qb->delete('share')
1042
+            ->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_GROUP)))
1043
+            ->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($gid)));
1044
+        $qb->execute();
1045
+    }
1046
+
1047
+    /**
1048
+     * Delete custom group shares to this group for this user
1049
+     *
1050
+     * @param string $uid
1051
+     * @param string $gid
1052
+     */
1053
+    public function userDeletedFromGroup($uid, $gid) {
1054
+        /*
1055 1055
 		 * Get all group shares
1056 1056
 		 */
1057
-		$qb = $this->dbConn->getQueryBuilder();
1058
-		$qb->select('id')
1059
-			->from('share')
1060
-			->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_GROUP)))
1061
-			->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($gid)));
1062
-
1063
-		$cursor = $qb->execute();
1064
-		$ids = [];
1065
-		while($row = $cursor->fetch()) {
1066
-			$ids[] = (int)$row['id'];
1067
-		}
1068
-		$cursor->closeCursor();
1069
-
1070
-		if (!empty($ids)) {
1071
-			$chunks = array_chunk($ids, 100);
1072
-			foreach ($chunks as $chunk) {
1073
-				/*
1057
+        $qb = $this->dbConn->getQueryBuilder();
1058
+        $qb->select('id')
1059
+            ->from('share')
1060
+            ->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_GROUP)))
1061
+            ->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($gid)));
1062
+
1063
+        $cursor = $qb->execute();
1064
+        $ids = [];
1065
+        while($row = $cursor->fetch()) {
1066
+            $ids[] = (int)$row['id'];
1067
+        }
1068
+        $cursor->closeCursor();
1069
+
1070
+        if (!empty($ids)) {
1071
+            $chunks = array_chunk($ids, 100);
1072
+            foreach ($chunks as $chunk) {
1073
+                /*
1074 1074
 				 * Delete all special shares wit this users for the found group shares
1075 1075
 				 */
1076
-				$qb->delete('share')
1077
-					->where($qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP)))
1078
-					->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($uid)))
1079
-					->andWhere($qb->expr()->in('parent', $qb->createNamedParameter($chunk, IQueryBuilder::PARAM_INT_ARRAY)));
1080
-				$qb->execute();
1081
-			}
1082
-		}
1083
-	}
1084
-
1085
-	/**
1086
-	 * @inheritdoc
1087
-	 */
1088
-	public function getAccessList($nodes, $currentAccess) {
1089
-		$ids = [];
1090
-		foreach ($nodes as $node) {
1091
-			$ids[] = $node->getId();
1092
-		}
1093
-
1094
-		$qb = $this->dbConn->getQueryBuilder();
1095
-
1096
-		$or = $qb->expr()->orX(
1097
-			$qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_USER)),
1098
-			$qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_GROUP)),
1099
-			$qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_LINK))
1100
-		);
1101
-
1102
-		if ($currentAccess) {
1103
-			$or->add($qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP)));
1104
-		}
1105
-
1106
-		$qb->select('id', 'parent', 'share_type', 'share_with', 'file_source', 'file_target', 'permissions')
1107
-			->from('share')
1108
-			->where(
1109
-				$or
1110
-			)
1111
-			->andWhere($qb->expr()->in('file_source', $qb->createNamedParameter($ids, IQueryBuilder::PARAM_INT_ARRAY)))
1112
-			->andWhere($qb->expr()->orX(
1113
-				$qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
1114
-				$qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
1115
-			));
1116
-		$cursor = $qb->execute();
1117
-
1118
-		$users = [];
1119
-		$link = false;
1120
-		while($row = $cursor->fetch()) {
1121
-			$type = (int)$row['share_type'];
1122
-			if ($type === \OCP\Share::SHARE_TYPE_USER) {
1123
-				$uid = $row['share_with'];
1124
-				$users[$uid] = isset($users[$uid]) ? $users[$uid] : [];
1125
-				$users[$uid][$row['id']] = $row;
1126
-			} else if ($type === \OCP\Share::SHARE_TYPE_GROUP) {
1127
-				$gid = $row['share_with'];
1128
-				$group = $this->groupManager->get($gid);
1129
-
1130
-				if ($group === null) {
1131
-					continue;
1132
-				}
1133
-
1134
-				$userList = $group->getUsers();
1135
-				foreach ($userList as $user) {
1136
-					$uid = $user->getUID();
1137
-					$users[$uid] = isset($users[$uid]) ? $users[$uid] : [];
1138
-					$users[$uid][$row['id']] = $row;
1139
-				}
1140
-			} else if ($type === \OCP\Share::SHARE_TYPE_LINK) {
1141
-				$link = true;
1142
-			} else if ($type === self::SHARE_TYPE_USERGROUP && $currentAccess === true) {
1143
-				$uid = $row['share_with'];
1144
-				$users[$uid] = isset($users[$uid]) ? $users[$uid] : [];
1145
-				$users[$uid][$row['id']] = $row;
1146
-			}
1147
-		}
1148
-		$cursor->closeCursor();
1149
-
1150
-		if ($currentAccess === true) {
1151
-			$users = array_map([$this, 'filterSharesOfUser'], $users);
1152
-			$users = array_filter($users);
1153
-		} else {
1154
-			$users = array_keys($users);
1155
-		}
1156
-
1157
-		return ['users' => $users, 'public' => $link];
1158
-	}
1159
-
1160
-	/**
1161
-	 * For each user the path with the fewest slashes is returned
1162
-	 * @param array $shares
1163
-	 * @return array
1164
-	 */
1165
-	protected function filterSharesOfUser(array $shares) {
1166
-		// Group shares when the user has a share exception
1167
-		foreach ($shares as $id => $share) {
1168
-			$type = (int) $share['share_type'];
1169
-			$permissions = (int) $share['permissions'];
1170
-
1171
-			if ($type === self::SHARE_TYPE_USERGROUP) {
1172
-				unset($shares[$share['parent']]);
1173
-
1174
-				if ($permissions === 0) {
1175
-					unset($shares[$id]);
1176
-				}
1177
-			}
1178
-		}
1179
-
1180
-		$best = [];
1181
-		$bestDepth = 0;
1182
-		foreach ($shares as $id => $share) {
1183
-			$depth = substr_count($share['file_target'], '/');
1184
-			if (empty($best) || $depth < $bestDepth) {
1185
-				$bestDepth = $depth;
1186
-				$best = [
1187
-					'node_id' => $share['file_source'],
1188
-					'node_path' => $share['file_target'],
1189
-				];
1190
-			}
1191
-		}
1192
-
1193
-		return $best;
1194
-	}
1076
+                $qb->delete('share')
1077
+                    ->where($qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP)))
1078
+                    ->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($uid)))
1079
+                    ->andWhere($qb->expr()->in('parent', $qb->createNamedParameter($chunk, IQueryBuilder::PARAM_INT_ARRAY)));
1080
+                $qb->execute();
1081
+            }
1082
+        }
1083
+    }
1084
+
1085
+    /**
1086
+     * @inheritdoc
1087
+     */
1088
+    public function getAccessList($nodes, $currentAccess) {
1089
+        $ids = [];
1090
+        foreach ($nodes as $node) {
1091
+            $ids[] = $node->getId();
1092
+        }
1093
+
1094
+        $qb = $this->dbConn->getQueryBuilder();
1095
+
1096
+        $or = $qb->expr()->orX(
1097
+            $qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_USER)),
1098
+            $qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_GROUP)),
1099
+            $qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_LINK))
1100
+        );
1101
+
1102
+        if ($currentAccess) {
1103
+            $or->add($qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP)));
1104
+        }
1105
+
1106
+        $qb->select('id', 'parent', 'share_type', 'share_with', 'file_source', 'file_target', 'permissions')
1107
+            ->from('share')
1108
+            ->where(
1109
+                $or
1110
+            )
1111
+            ->andWhere($qb->expr()->in('file_source', $qb->createNamedParameter($ids, IQueryBuilder::PARAM_INT_ARRAY)))
1112
+            ->andWhere($qb->expr()->orX(
1113
+                $qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
1114
+                $qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
1115
+            ));
1116
+        $cursor = $qb->execute();
1117
+
1118
+        $users = [];
1119
+        $link = false;
1120
+        while($row = $cursor->fetch()) {
1121
+            $type = (int)$row['share_type'];
1122
+            if ($type === \OCP\Share::SHARE_TYPE_USER) {
1123
+                $uid = $row['share_with'];
1124
+                $users[$uid] = isset($users[$uid]) ? $users[$uid] : [];
1125
+                $users[$uid][$row['id']] = $row;
1126
+            } else if ($type === \OCP\Share::SHARE_TYPE_GROUP) {
1127
+                $gid = $row['share_with'];
1128
+                $group = $this->groupManager->get($gid);
1129
+
1130
+                if ($group === null) {
1131
+                    continue;
1132
+                }
1133
+
1134
+                $userList = $group->getUsers();
1135
+                foreach ($userList as $user) {
1136
+                    $uid = $user->getUID();
1137
+                    $users[$uid] = isset($users[$uid]) ? $users[$uid] : [];
1138
+                    $users[$uid][$row['id']] = $row;
1139
+                }
1140
+            } else if ($type === \OCP\Share::SHARE_TYPE_LINK) {
1141
+                $link = true;
1142
+            } else if ($type === self::SHARE_TYPE_USERGROUP && $currentAccess === true) {
1143
+                $uid = $row['share_with'];
1144
+                $users[$uid] = isset($users[$uid]) ? $users[$uid] : [];
1145
+                $users[$uid][$row['id']] = $row;
1146
+            }
1147
+        }
1148
+        $cursor->closeCursor();
1149
+
1150
+        if ($currentAccess === true) {
1151
+            $users = array_map([$this, 'filterSharesOfUser'], $users);
1152
+            $users = array_filter($users);
1153
+        } else {
1154
+            $users = array_keys($users);
1155
+        }
1156
+
1157
+        return ['users' => $users, 'public' => $link];
1158
+    }
1159
+
1160
+    /**
1161
+     * For each user the path with the fewest slashes is returned
1162
+     * @param array $shares
1163
+     * @return array
1164
+     */
1165
+    protected function filterSharesOfUser(array $shares) {
1166
+        // Group shares when the user has a share exception
1167
+        foreach ($shares as $id => $share) {
1168
+            $type = (int) $share['share_type'];
1169
+            $permissions = (int) $share['permissions'];
1170
+
1171
+            if ($type === self::SHARE_TYPE_USERGROUP) {
1172
+                unset($shares[$share['parent']]);
1173
+
1174
+                if ($permissions === 0) {
1175
+                    unset($shares[$id]);
1176
+                }
1177
+            }
1178
+        }
1179
+
1180
+        $best = [];
1181
+        $bestDepth = 0;
1182
+        foreach ($shares as $id => $share) {
1183
+            $depth = substr_count($share['file_target'], '/');
1184
+            if (empty($best) || $depth < $bestDepth) {
1185
+                $bestDepth = $depth;
1186
+                $best = [
1187
+                    'node_id' => $share['file_source'],
1188
+                    'node_path' => $share['file_target'],
1189
+                ];
1190
+            }
1191
+        }
1192
+
1193
+        return $best;
1194
+    }
1195 1195
 }
Please login to merge, or discard this patch.
apps/dav/lib/Connector/Sabre/ShareTypeList.php 3 patches
Doc Comments   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -61,7 +61,7 @@
 block discarded – undo
61 61
 	 * The deserialize method is called during xml parsing.
62 62
 	 *
63 63
 	 * @param Reader $reader
64
-	 * @return mixed
64
+	 * @return null|ShareTypeList
65 65
 	 */
66 66
 	static function xmlDeserialize(Reader $reader) {
67 67
 		$shareTypes = [];
Please login to merge, or discard this patch.
Indentation   +51 added lines, -51 removed lines patch added patch discarded remove patch
@@ -32,61 +32,61 @@
 block discarded – undo
32 32
  * This property contains multiple "share-type" elements, each containing a share type.
33 33
  */
34 34
 class ShareTypeList implements Element {
35
-	const NS_OWNCLOUD = 'http://owncloud.org/ns';
35
+    const NS_OWNCLOUD = 'http://owncloud.org/ns';
36 36
 
37
-	/**
38
-	 * Share types
39
-	 *
40
-	 * @var int[]
41
-	 */
42
-	private $shareTypes;
37
+    /**
38
+     * Share types
39
+     *
40
+     * @var int[]
41
+     */
42
+    private $shareTypes;
43 43
 
44
-	/**
45
-	 * @param int[] $shareTypes
46
-	 */
47
-	public function __construct($shareTypes) {
48
-		$this->shareTypes = $shareTypes;
49
-	}
44
+    /**
45
+     * @param int[] $shareTypes
46
+     */
47
+    public function __construct($shareTypes) {
48
+        $this->shareTypes = $shareTypes;
49
+    }
50 50
 
51
-	/**
52
-	 * Returns the share types
53
-	 *
54
-	 * @return int[]
55
-	 */
56
-	public function getShareTypes() {
57
-		return $this->shareTypes;
58
-	}
51
+    /**
52
+     * Returns the share types
53
+     *
54
+     * @return int[]
55
+     */
56
+    public function getShareTypes() {
57
+        return $this->shareTypes;
58
+    }
59 59
 
60
-	/**
61
-	 * The deserialize method is called during xml parsing.
62
-	 *
63
-	 * @param Reader $reader
64
-	 * @return mixed
65
-	 */
66
-	static function xmlDeserialize(Reader $reader) {
67
-		$shareTypes = [];
60
+    /**
61
+     * The deserialize method is called during xml parsing.
62
+     *
63
+     * @param Reader $reader
64
+     * @return mixed
65
+     */
66
+    static function xmlDeserialize(Reader $reader) {
67
+        $shareTypes = [];
68 68
 
69
-		$tree = $reader->parseInnerTree();
70
-		if ($tree === null) {
71
-			return null;
72
-		}
73
-		foreach ($tree as $elem) {
74
-			if ($elem['name'] === '{' . self::NS_OWNCLOUD . '}share-type') {
75
-				$shareTypes[] = (int)$elem['value'];
76
-			}
77
-		}
78
-		return new self($shareTypes);
79
-	}
69
+        $tree = $reader->parseInnerTree();
70
+        if ($tree === null) {
71
+            return null;
72
+        }
73
+        foreach ($tree as $elem) {
74
+            if ($elem['name'] === '{' . self::NS_OWNCLOUD . '}share-type') {
75
+                $shareTypes[] = (int)$elem['value'];
76
+            }
77
+        }
78
+        return new self($shareTypes);
79
+    }
80 80
 
81
-	/**
82
-	 * The xmlSerialize metod is called during xml writing.
83
-	 *
84
-	 * @param Writer $writer
85
-	 * @return void
86
-	 */
87
-	function xmlSerialize(Writer $writer) {
88
-		foreach ($this->shareTypes as $shareType) {
89
-			$writer->writeElement('{' . self::NS_OWNCLOUD . '}share-type', $shareType);
90
-		}
91
-	}
81
+    /**
82
+     * The xmlSerialize metod is called during xml writing.
83
+     *
84
+     * @param Writer $writer
85
+     * @return void
86
+     */
87
+    function xmlSerialize(Writer $writer) {
88
+        foreach ($this->shareTypes as $shareType) {
89
+            $writer->writeElement('{' . self::NS_OWNCLOUD . '}share-type', $shareType);
90
+        }
91
+    }
92 92
 }
Please login to merge, or discard this patch.
Spacing   +3 added lines, -3 removed lines patch added patch discarded remove patch
@@ -71,8 +71,8 @@  discard block
 block discarded – undo
71 71
 			return null;
72 72
 		}
73 73
 		foreach ($tree as $elem) {
74
-			if ($elem['name'] === '{' . self::NS_OWNCLOUD . '}share-type') {
75
-				$shareTypes[] = (int)$elem['value'];
74
+			if ($elem['name'] === '{'.self::NS_OWNCLOUD.'}share-type') {
75
+				$shareTypes[] = (int) $elem['value'];
76 76
 			}
77 77
 		}
78 78
 		return new self($shareTypes);
@@ -86,7 +86,7 @@  discard block
 block discarded – undo
86 86
 	 */
87 87
 	function xmlSerialize(Writer $writer) {
88 88
 		foreach ($this->shareTypes as $shareType) {
89
-			$writer->writeElement('{' . self::NS_OWNCLOUD . '}share-type', $shareType);
89
+			$writer->writeElement('{'.self::NS_OWNCLOUD.'}share-type', $shareType);
90 90
 		}
91 91
 	}
92 92
 }
Please login to merge, or discard this patch.