Completed
Pull Request — master (#7693)
by Kai
65:47 queued 26:55
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   +9 added lines, -9 removed lines patch added patch discarded remove patch
@@ -167,7 +167,7 @@  discard block
 block discarded – undo
167 167
 	 */
168 168
 	protected function checkPasswordResetToken($token, $userId) {
169 169
 		$user = $this->userManager->get($userId);
170
-		if($user === null || !$user->isEnabled()) {
170
+		if ($user === null || !$user->isEnabled()) {
171 171
 			throw new \Exception($this->l10n->t('Couldn\'t reset password because the token is invalid'));
172 172
 		}
173 173
 
@@ -180,11 +180,11 @@  discard block
 block discarded – undo
180 180
 		}
181 181
 
182 182
 		$splittedToken = explode(':', $decryptedToken);
183
-		if(count($splittedToken) !== 2) {
183
+		if (count($splittedToken) !== 2) {
184 184
 			throw new \Exception($this->l10n->t('Couldn\'t reset password because the token is invalid'));
185 185
 		}
186 186
 
187
-		if ($splittedToken[0] < ($this->timeFactory->getTime() - 60*60*12) ||
187
+		if ($splittedToken[0] < ($this->timeFactory->getTime() - 60 * 60 * 12) ||
188 188
 			$user->getLastLogin() > $splittedToken[0]) {
189 189
 			throw new \Exception($this->l10n->t('Couldn\'t reset password because the token is expired'));
190 190
 		}
@@ -199,7 +199,7 @@  discard block
 block discarded – undo
199 199
 	 * @param array $additional
200 200
 	 * @return array
201 201
 	 */
202
-	private function error($message, array $additional=array()) {
202
+	private function error($message, array $additional = array()) {
203 203
 		return array_merge(array('status' => 'error', 'msg' => $message), $additional);
204 204
 	}
205 205
 
@@ -218,7 +218,7 @@  discard block
 block discarded – undo
218 218
 	 * @param string $user
219 219
 	 * @return JSONResponse
220 220
 	 */
221
-	public function email($user){
221
+	public function email($user) {
222 222
 		if ($this->config->getSystemValue('lost_password_link', '') !== '') {
223 223
 			return new JSONResponse($this->error($this->l10n->t('Password reset is disabled')));
224 224
 		}
@@ -226,7 +226,7 @@  discard block
 block discarded – undo
226 226
 		// FIXME: use HTTP error codes
227 227
 		try {
228 228
 			$this->sendEmail($user);
229
-		} catch (\Exception $e){
229
+		} catch (\Exception $e) {
230 230
 			$response = new JSONResponse($this->error($e->getMessage()));
231 231
 			$response->throttle();
232 232
 			return $response;
@@ -268,7 +268,7 @@  discard block
 block discarded – undo
268 268
 
269 269
 			$this->config->deleteUserValue($userId, 'core', 'lostpassword');
270 270
 			@\OC::$server->getUserSession()->unsetMagicInCookie();
271
-		} catch (\Exception $e){
271
+		} catch (\Exception $e) {
272 272
 			return $this->error($e->getMessage());
273 273
 		}
274 274
 
@@ -299,8 +299,8 @@  discard block
 block discarded – undo
299 299
 			ISecureRandom::CHAR_LOWER.
300 300
 			ISecureRandom::CHAR_UPPER
301 301
 		);
302
-		$tokenValue = $this->timeFactory->getTime() .':'. $token;
303
-		$encryptedValue = $this->crypto->encrypt($tokenValue, $email . $this->config->getSystemValue('secret'));
302
+		$tokenValue = $this->timeFactory->getTime().':'.$token;
303
+		$encryptedValue = $this->crypto->encrypt($tokenValue, $email.$this->config->getSystemValue('secret'));
304 304
 		$this->config->setUserValue($user->getUID(), 'core', 'lostpassword', $encryptedValue);
305 305
 
306 306
 		$link = $this->urlGenerator->linkToRouteAbsolute('core.lost.resetform', array('userId' => $user->getUID(), 'token' => $token));
Please login to merge, or discard this patch.
Indentation   +315 added lines, -315 removed lines patch added patch discarded remove patch
@@ -56,319 +56,319 @@
 block discarded – undo
56 56
  */
57 57
 class LostController extends Controller {
58 58
 
59
-	/** @var IURLGenerator */
60
-	protected $urlGenerator;
61
-	/** @var IUserManager */
62
-	protected $userManager;
63
-	/** @var Defaults */
64
-	protected $defaults;
65
-	/** @var IL10N */
66
-	protected $l10n;
67
-	/** @var string */
68
-	protected $from;
69
-	/** @var IManager */
70
-	protected $encryptionManager;
71
-	/** @var IConfig */
72
-	protected $config;
73
-	/** @var ISecureRandom */
74
-	protected $secureRandom;
75
-	/** @var IMailer */
76
-	protected $mailer;
77
-	/** @var ITimeFactory */
78
-	protected $timeFactory;
79
-	/** @var ICrypto */
80
-	protected $crypto;
81
-
82
-	/**
83
-	 * @param string $appName
84
-	 * @param IRequest $request
85
-	 * @param IURLGenerator $urlGenerator
86
-	 * @param IUserManager $userManager
87
-	 * @param Defaults $defaults
88
-	 * @param IL10N $l10n
89
-	 * @param IConfig $config
90
-	 * @param ISecureRandom $secureRandom
91
-	 * @param string $defaultMailAddress
92
-	 * @param IManager $encryptionManager
93
-	 * @param IMailer $mailer
94
-	 * @param ITimeFactory $timeFactory
95
-	 * @param ICrypto $crypto
96
-	 */
97
-	public function __construct($appName,
98
-								IRequest $request,
99
-								IURLGenerator $urlGenerator,
100
-								IUserManager $userManager,
101
-								Defaults $defaults,
102
-								IL10N $l10n,
103
-								IConfig $config,
104
-								ISecureRandom $secureRandom,
105
-								$defaultMailAddress,
106
-								IManager $encryptionManager,
107
-								IMailer $mailer,
108
-								ITimeFactory $timeFactory,
109
-								ICrypto $crypto) {
110
-		parent::__construct($appName, $request);
111
-		$this->urlGenerator = $urlGenerator;
112
-		$this->userManager = $userManager;
113
-		$this->defaults = $defaults;
114
-		$this->l10n = $l10n;
115
-		$this->secureRandom = $secureRandom;
116
-		$this->from = $defaultMailAddress;
117
-		$this->encryptionManager = $encryptionManager;
118
-		$this->config = $config;
119
-		$this->mailer = $mailer;
120
-		$this->timeFactory = $timeFactory;
121
-		$this->crypto = $crypto;
122
-	}
123
-
124
-	/**
125
-	 * Someone wants to reset their password:
126
-	 *
127
-	 * @PublicPage
128
-	 * @NoCSRFRequired
129
-	 *
130
-	 * @param string $token
131
-	 * @param string $userId
132
-	 * @return TemplateResponse
133
-	 */
134
-	public function resetform($token, $userId) {
135
-		if ($this->config->getSystemValue('lost_password_link', '') !== '') {
136
-			return new TemplateResponse('core', 'error', [
137
-					'errors' => [['error' => $this->l10n->t('Password reset is disabled')]]
138
-				],
139
-				'guest'
140
-			);
141
-		}
142
-
143
-		try {
144
-			$this->checkPasswordResetToken($token, $userId);
145
-		} catch (\Exception $e) {
146
-			return new TemplateResponse(
147
-				'core', 'error', [
148
-					"errors" => array(array("error" => $e->getMessage()))
149
-				],
150
-				'guest'
151
-			);
152
-		}
153
-
154
-		return new TemplateResponse(
155
-			'core',
156
-			'lostpassword/resetpassword',
157
-			array(
158
-				'link' => $this->urlGenerator->linkToRouteAbsolute('core.lost.setPassword', array('userId' => $userId, 'token' => $token)),
159
-			),
160
-			'guest'
161
-		);
162
-	}
163
-
164
-	/**
165
-	 * @param string $token
166
-	 * @param string $userId
167
-	 * @throws \Exception
168
-	 */
169
-	protected function checkPasswordResetToken($token, $userId) {
170
-		$user = $this->userManager->get($userId);
171
-		if($user === null || !$user->isEnabled()) {
172
-			throw new \Exception($this->l10n->t('Couldn\'t reset password because the token is invalid'));
173
-		}
174
-
175
-		try {
176
-			$encryptedToken = $this->config->getUserValue($userId, 'core', 'lostpassword', null);
177
-			$mailAddress = !is_null($user->getEMailAddress()) ? $user->getEMailAddress() : '';
178
-			$decryptedToken = $this->crypto->decrypt($encryptedToken, $mailAddress.$this->config->getSystemValue('secret'));
179
-		} catch (\Exception $e) {
180
-			throw new \Exception($this->l10n->t('Couldn\'t reset password because the token is invalid'));
181
-		}
182
-
183
-		$splittedToken = explode(':', $decryptedToken);
184
-		if(count($splittedToken) !== 2) {
185
-			throw new \Exception($this->l10n->t('Couldn\'t reset password because the token is invalid'));
186
-		}
187
-
188
-		if ($splittedToken[0] < ($this->timeFactory->getTime() - 60*60*12) ||
189
-			$user->getLastLogin() > $splittedToken[0]) {
190
-			throw new \Exception($this->l10n->t('Couldn\'t reset password because the token is expired'));
191
-		}
192
-
193
-		if (!hash_equals($splittedToken[1], $token)) {
194
-			throw new \Exception($this->l10n->t('Couldn\'t reset password because the token is invalid'));
195
-		}
196
-	}
197
-
198
-	/**
199
-	 * @param $message
200
-	 * @param array $additional
201
-	 * @return array
202
-	 */
203
-	private function error($message, array $additional=array()) {
204
-		return array_merge(array('status' => 'error', 'msg' => $message), $additional);
205
-	}
206
-
207
-	/**
208
-	 * @return array
209
-	 */
210
-	private function success() {
211
-		return array('status'=>'success');
212
-	}
213
-
214
-	/**
215
-	 * @PublicPage
216
-	 * @BruteForceProtection(action=passwordResetEmail)
217
-	 * @AnonRateThrottle(limit=10, period=300)
218
-	 *
219
-	 * @param string $user
220
-	 * @return JSONResponse
221
-	 */
222
-	public function email($user){
223
-		if ($this->config->getSystemValue('lost_password_link', '') !== '') {
224
-			return new JSONResponse($this->error($this->l10n->t('Password reset is disabled')));
225
-		}
226
-
227
-		\OCP\Util::emitHook(
228
-			'\OCA\Files_Sharing\API\Server2Server',
229
-			'preLoginNameUsedAsUserName',
230
-			['uid' => &$user]
231
-		);
232
-
233
-		// FIXME: use HTTP error codes
234
-		try {
235
-			$this->sendEmail($user);
236
-		} catch (\Exception $e){
237
-			$response = new JSONResponse($this->error($e->getMessage()));
238
-			$response->throttle();
239
-			return $response;
240
-		}
241
-
242
-		$response = new JSONResponse($this->success());
243
-		$response->throttle();
244
-		return $response;
245
-	}
246
-
247
-	/**
248
-	 * @PublicPage
249
-	 * @param string $token
250
-	 * @param string $userId
251
-	 * @param string $password
252
-	 * @param boolean $proceed
253
-	 * @return array
254
-	 */
255
-	public function setPassword($token, $userId, $password, $proceed) {
256
-		if ($this->config->getSystemValue('lost_password_link', '') !== '') {
257
-			return $this->error($this->l10n->t('Password reset is disabled'));
258
-		}
259
-
260
-		if ($this->encryptionManager->isEnabled() && !$proceed) {
261
-			return $this->error('', array('encryption' => true));
262
-		}
263
-
264
-		try {
265
-			$this->checkPasswordResetToken($token, $userId);
266
-			$user = $this->userManager->get($userId);
267
-
268
-			\OC_Hook::emit('\OC\Core\LostPassword\Controller\LostController', 'pre_passwordReset', array('uid' => $userId, 'password' => $password));
269
-
270
-			if (!$user->setPassword($password)) {
271
-				throw new \Exception();
272
-			}
273
-
274
-			\OC_Hook::emit('\OC\Core\LostPassword\Controller\LostController', 'post_passwordReset', array('uid' => $userId, 'password' => $password));
275
-
276
-			$this->config->deleteUserValue($userId, 'core', 'lostpassword');
277
-			@\OC::$server->getUserSession()->unsetMagicInCookie();
278
-		} catch (\Exception $e){
279
-			return $this->error($e->getMessage());
280
-		}
281
-
282
-		return $this->success();
283
-	}
284
-
285
-	/**
286
-	 * @param string $input
287
-	 * @throws \Exception
288
-	 */
289
-	protected function sendEmail($input) {
290
-		$user = $this->findUserByIdOrMail($input);
291
-		$email = $user->getEMailAddress();
292
-
293
-		if (empty($email)) {
294
-			throw new \Exception(
295
-				$this->l10n->t('Could not send reset email because there is no email address for this username. Please contact your administrator.')
296
-			);
297
-		}
298
-
299
-		// Generate the token. It is stored encrypted in the database with the
300
-		// secret being the users' email address appended with the system secret.
301
-		// This makes the token automatically invalidate once the user changes
302
-		// their email address.
303
-		$token = $this->secureRandom->generate(
304
-			21,
305
-			ISecureRandom::CHAR_DIGITS.
306
-			ISecureRandom::CHAR_LOWER.
307
-			ISecureRandom::CHAR_UPPER
308
-		);
309
-		$tokenValue = $this->timeFactory->getTime() .':'. $token;
310
-		$encryptedValue = $this->crypto->encrypt($tokenValue, $email . $this->config->getSystemValue('secret'));
311
-		$this->config->setUserValue($user->getUID(), 'core', 'lostpassword', $encryptedValue);
312
-
313
-		$link = $this->urlGenerator->linkToRouteAbsolute('core.lost.resetform', array('userId' => $user->getUID(), 'token' => $token));
314
-
315
-		$emailTemplate = $this->mailer->createEMailTemplate('core.ResetPassword', [
316
-			'link' => $link,
317
-		]);
318
-
319
-		$emailTemplate->setSubject($this->l10n->t('%s password reset', [$this->defaults->getName()]));
320
-		$emailTemplate->addHeader();
321
-		$emailTemplate->addHeading($this->l10n->t('Password reset'));
322
-
323
-		$emailTemplate->addBodyText(
324
-			$this->l10n->t('Click the following button to reset your password. If you have not requested the password reset, then ignore this email.'),
325
-			$this->l10n->t('Click the following link to reset your password. If you have not requested the password reset, then ignore this email.')
326
-		);
327
-
328
-		$emailTemplate->addBodyButton(
329
-			$this->l10n->t('Reset your password'),
330
-			$link,
331
-			false
332
-		);
333
-		$emailTemplate->addFooter();
334
-
335
-		try {
336
-			$message = $this->mailer->createMessage();
337
-			$message->setTo([$email => $user->getUID()]);
338
-			$message->setFrom([$this->from => $this->defaults->getName()]);
339
-			$message->useTemplate($emailTemplate);
340
-			$this->mailer->send($message);
341
-		} catch (\Exception $e) {
342
-			throw new \Exception($this->l10n->t(
343
-				'Couldn\'t send reset email. Please contact your administrator.'
344
-			));
345
-		}
346
-	}
347
-
348
-	/**
349
-	 * @param string $input
350
-	 * @return IUser
351
-	 * @throws \InvalidArgumentException
352
-	 */
353
-	protected function findUserByIdOrMail($input) {
354
-		$user = $this->userManager->get($input);
355
-		if ($user instanceof IUser) {
356
-			if (!$user->isEnabled()) {
357
-				throw new \InvalidArgumentException($this->l10n->t('Couldn\'t send reset email. Please make sure your username is correct.'));
358
-			}
359
-
360
-			return $user;
361
-		}
362
-		$users = $this->userManager->getByEmail($input);
363
-		if (count($users) === 1) {
364
-			$user = $users[0];
365
-			if (!$user->isEnabled()) {
366
-				throw new \InvalidArgumentException($this->l10n->t('Couldn\'t send reset email. Please make sure your username is correct.'));
367
-			}
368
-
369
-			return $user;
370
-		}
371
-
372
-		throw new \InvalidArgumentException($this->l10n->t('Couldn\'t send reset email. Please make sure your username is correct.'));
373
-	}
59
+    /** @var IURLGenerator */
60
+    protected $urlGenerator;
61
+    /** @var IUserManager */
62
+    protected $userManager;
63
+    /** @var Defaults */
64
+    protected $defaults;
65
+    /** @var IL10N */
66
+    protected $l10n;
67
+    /** @var string */
68
+    protected $from;
69
+    /** @var IManager */
70
+    protected $encryptionManager;
71
+    /** @var IConfig */
72
+    protected $config;
73
+    /** @var ISecureRandom */
74
+    protected $secureRandom;
75
+    /** @var IMailer */
76
+    protected $mailer;
77
+    /** @var ITimeFactory */
78
+    protected $timeFactory;
79
+    /** @var ICrypto */
80
+    protected $crypto;
81
+
82
+    /**
83
+     * @param string $appName
84
+     * @param IRequest $request
85
+     * @param IURLGenerator $urlGenerator
86
+     * @param IUserManager $userManager
87
+     * @param Defaults $defaults
88
+     * @param IL10N $l10n
89
+     * @param IConfig $config
90
+     * @param ISecureRandom $secureRandom
91
+     * @param string $defaultMailAddress
92
+     * @param IManager $encryptionManager
93
+     * @param IMailer $mailer
94
+     * @param ITimeFactory $timeFactory
95
+     * @param ICrypto $crypto
96
+     */
97
+    public function __construct($appName,
98
+                                IRequest $request,
99
+                                IURLGenerator $urlGenerator,
100
+                                IUserManager $userManager,
101
+                                Defaults $defaults,
102
+                                IL10N $l10n,
103
+                                IConfig $config,
104
+                                ISecureRandom $secureRandom,
105
+                                $defaultMailAddress,
106
+                                IManager $encryptionManager,
107
+                                IMailer $mailer,
108
+                                ITimeFactory $timeFactory,
109
+                                ICrypto $crypto) {
110
+        parent::__construct($appName, $request);
111
+        $this->urlGenerator = $urlGenerator;
112
+        $this->userManager = $userManager;
113
+        $this->defaults = $defaults;
114
+        $this->l10n = $l10n;
115
+        $this->secureRandom = $secureRandom;
116
+        $this->from = $defaultMailAddress;
117
+        $this->encryptionManager = $encryptionManager;
118
+        $this->config = $config;
119
+        $this->mailer = $mailer;
120
+        $this->timeFactory = $timeFactory;
121
+        $this->crypto = $crypto;
122
+    }
123
+
124
+    /**
125
+     * Someone wants to reset their password:
126
+     *
127
+     * @PublicPage
128
+     * @NoCSRFRequired
129
+     *
130
+     * @param string $token
131
+     * @param string $userId
132
+     * @return TemplateResponse
133
+     */
134
+    public function resetform($token, $userId) {
135
+        if ($this->config->getSystemValue('lost_password_link', '') !== '') {
136
+            return new TemplateResponse('core', 'error', [
137
+                    'errors' => [['error' => $this->l10n->t('Password reset is disabled')]]
138
+                ],
139
+                'guest'
140
+            );
141
+        }
142
+
143
+        try {
144
+            $this->checkPasswordResetToken($token, $userId);
145
+        } catch (\Exception $e) {
146
+            return new TemplateResponse(
147
+                'core', 'error', [
148
+                    "errors" => array(array("error" => $e->getMessage()))
149
+                ],
150
+                'guest'
151
+            );
152
+        }
153
+
154
+        return new TemplateResponse(
155
+            'core',
156
+            'lostpassword/resetpassword',
157
+            array(
158
+                'link' => $this->urlGenerator->linkToRouteAbsolute('core.lost.setPassword', array('userId' => $userId, 'token' => $token)),
159
+            ),
160
+            'guest'
161
+        );
162
+    }
163
+
164
+    /**
165
+     * @param string $token
166
+     * @param string $userId
167
+     * @throws \Exception
168
+     */
169
+    protected function checkPasswordResetToken($token, $userId) {
170
+        $user = $this->userManager->get($userId);
171
+        if($user === null || !$user->isEnabled()) {
172
+            throw new \Exception($this->l10n->t('Couldn\'t reset password because the token is invalid'));
173
+        }
174
+
175
+        try {
176
+            $encryptedToken = $this->config->getUserValue($userId, 'core', 'lostpassword', null);
177
+            $mailAddress = !is_null($user->getEMailAddress()) ? $user->getEMailAddress() : '';
178
+            $decryptedToken = $this->crypto->decrypt($encryptedToken, $mailAddress.$this->config->getSystemValue('secret'));
179
+        } catch (\Exception $e) {
180
+            throw new \Exception($this->l10n->t('Couldn\'t reset password because the token is invalid'));
181
+        }
182
+
183
+        $splittedToken = explode(':', $decryptedToken);
184
+        if(count($splittedToken) !== 2) {
185
+            throw new \Exception($this->l10n->t('Couldn\'t reset password because the token is invalid'));
186
+        }
187
+
188
+        if ($splittedToken[0] < ($this->timeFactory->getTime() - 60*60*12) ||
189
+            $user->getLastLogin() > $splittedToken[0]) {
190
+            throw new \Exception($this->l10n->t('Couldn\'t reset password because the token is expired'));
191
+        }
192
+
193
+        if (!hash_equals($splittedToken[1], $token)) {
194
+            throw new \Exception($this->l10n->t('Couldn\'t reset password because the token is invalid'));
195
+        }
196
+    }
197
+
198
+    /**
199
+     * @param $message
200
+     * @param array $additional
201
+     * @return array
202
+     */
203
+    private function error($message, array $additional=array()) {
204
+        return array_merge(array('status' => 'error', 'msg' => $message), $additional);
205
+    }
206
+
207
+    /**
208
+     * @return array
209
+     */
210
+    private function success() {
211
+        return array('status'=>'success');
212
+    }
213
+
214
+    /**
215
+     * @PublicPage
216
+     * @BruteForceProtection(action=passwordResetEmail)
217
+     * @AnonRateThrottle(limit=10, period=300)
218
+     *
219
+     * @param string $user
220
+     * @return JSONResponse
221
+     */
222
+    public function email($user){
223
+        if ($this->config->getSystemValue('lost_password_link', '') !== '') {
224
+            return new JSONResponse($this->error($this->l10n->t('Password reset is disabled')));
225
+        }
226
+
227
+        \OCP\Util::emitHook(
228
+            '\OCA\Files_Sharing\API\Server2Server',
229
+            'preLoginNameUsedAsUserName',
230
+            ['uid' => &$user]
231
+        );
232
+
233
+        // FIXME: use HTTP error codes
234
+        try {
235
+            $this->sendEmail($user);
236
+        } catch (\Exception $e){
237
+            $response = new JSONResponse($this->error($e->getMessage()));
238
+            $response->throttle();
239
+            return $response;
240
+        }
241
+
242
+        $response = new JSONResponse($this->success());
243
+        $response->throttle();
244
+        return $response;
245
+    }
246
+
247
+    /**
248
+     * @PublicPage
249
+     * @param string $token
250
+     * @param string $userId
251
+     * @param string $password
252
+     * @param boolean $proceed
253
+     * @return array
254
+     */
255
+    public function setPassword($token, $userId, $password, $proceed) {
256
+        if ($this->config->getSystemValue('lost_password_link', '') !== '') {
257
+            return $this->error($this->l10n->t('Password reset is disabled'));
258
+        }
259
+
260
+        if ($this->encryptionManager->isEnabled() && !$proceed) {
261
+            return $this->error('', array('encryption' => true));
262
+        }
263
+
264
+        try {
265
+            $this->checkPasswordResetToken($token, $userId);
266
+            $user = $this->userManager->get($userId);
267
+
268
+            \OC_Hook::emit('\OC\Core\LostPassword\Controller\LostController', 'pre_passwordReset', array('uid' => $userId, 'password' => $password));
269
+
270
+            if (!$user->setPassword($password)) {
271
+                throw new \Exception();
272
+            }
273
+
274
+            \OC_Hook::emit('\OC\Core\LostPassword\Controller\LostController', 'post_passwordReset', array('uid' => $userId, 'password' => $password));
275
+
276
+            $this->config->deleteUserValue($userId, 'core', 'lostpassword');
277
+            @\OC::$server->getUserSession()->unsetMagicInCookie();
278
+        } catch (\Exception $e){
279
+            return $this->error($e->getMessage());
280
+        }
281
+
282
+        return $this->success();
283
+    }
284
+
285
+    /**
286
+     * @param string $input
287
+     * @throws \Exception
288
+     */
289
+    protected function sendEmail($input) {
290
+        $user = $this->findUserByIdOrMail($input);
291
+        $email = $user->getEMailAddress();
292
+
293
+        if (empty($email)) {
294
+            throw new \Exception(
295
+                $this->l10n->t('Could not send reset email because there is no email address for this username. Please contact your administrator.')
296
+            );
297
+        }
298
+
299
+        // Generate the token. It is stored encrypted in the database with the
300
+        // secret being the users' email address appended with the system secret.
301
+        // This makes the token automatically invalidate once the user changes
302
+        // their email address.
303
+        $token = $this->secureRandom->generate(
304
+            21,
305
+            ISecureRandom::CHAR_DIGITS.
306
+            ISecureRandom::CHAR_LOWER.
307
+            ISecureRandom::CHAR_UPPER
308
+        );
309
+        $tokenValue = $this->timeFactory->getTime() .':'. $token;
310
+        $encryptedValue = $this->crypto->encrypt($tokenValue, $email . $this->config->getSystemValue('secret'));
311
+        $this->config->setUserValue($user->getUID(), 'core', 'lostpassword', $encryptedValue);
312
+
313
+        $link = $this->urlGenerator->linkToRouteAbsolute('core.lost.resetform', array('userId' => $user->getUID(), 'token' => $token));
314
+
315
+        $emailTemplate = $this->mailer->createEMailTemplate('core.ResetPassword', [
316
+            'link' => $link,
317
+        ]);
318
+
319
+        $emailTemplate->setSubject($this->l10n->t('%s password reset', [$this->defaults->getName()]));
320
+        $emailTemplate->addHeader();
321
+        $emailTemplate->addHeading($this->l10n->t('Password reset'));
322
+
323
+        $emailTemplate->addBodyText(
324
+            $this->l10n->t('Click the following button to reset your password. If you have not requested the password reset, then ignore this email.'),
325
+            $this->l10n->t('Click the following link to reset your password. If you have not requested the password reset, then ignore this email.')
326
+        );
327
+
328
+        $emailTemplate->addBodyButton(
329
+            $this->l10n->t('Reset your password'),
330
+            $link,
331
+            false
332
+        );
333
+        $emailTemplate->addFooter();
334
+
335
+        try {
336
+            $message = $this->mailer->createMessage();
337
+            $message->setTo([$email => $user->getUID()]);
338
+            $message->setFrom([$this->from => $this->defaults->getName()]);
339
+            $message->useTemplate($emailTemplate);
340
+            $this->mailer->send($message);
341
+        } catch (\Exception $e) {
342
+            throw new \Exception($this->l10n->t(
343
+                'Couldn\'t send reset email. Please contact your administrator.'
344
+            ));
345
+        }
346
+    }
347
+
348
+    /**
349
+     * @param string $input
350
+     * @return IUser
351
+     * @throws \InvalidArgumentException
352
+     */
353
+    protected function findUserByIdOrMail($input) {
354
+        $user = $this->userManager->get($input);
355
+        if ($user instanceof IUser) {
356
+            if (!$user->isEnabled()) {
357
+                throw new \InvalidArgumentException($this->l10n->t('Couldn\'t send reset email. Please make sure your username is correct.'));
358
+            }
359
+
360
+            return $user;
361
+        }
362
+        $users = $this->userManager->getByEmail($input);
363
+        if (count($users) === 1) {
364
+            $user = $users[0];
365
+            if (!$user->isEnabled()) {
366
+                throw new \InvalidArgumentException($this->l10n->t('Couldn\'t send reset email. Please make sure your username is correct.'));
367
+            }
368
+
369
+            return $user;
370
+        }
371
+
372
+        throw new \InvalidArgumentException($this->l10n->t('Couldn\'t send reset email. Please make sure your username is correct.'));
373
+    }
374 374
 }
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;
@@ -111,7 +110,6 @@  discard block
 block discarded – undo
111 110
 use OC\Tagging\TagMapper;
112 111
 use OC\Template\SCSSCacher;
113 112
 use OCA\Theming\ThemingDefaults;
114
-
115 113
 use OCP\App\IAppManager;
116 114
 use OCP\AppFramework\Utility\ITimeFactory;
117 115
 use OCP\Collaboration\AutoComplete\IManager;
Please login to merge, or discard this patch.
Indentation   +1816 added lines, -1816 removed lines patch added patch discarded remove patch
@@ -147,1825 +147,1825 @@
 block discarded – undo
147 147
  * TODO: hookup all manager classes
148 148
  */
149 149
 class Server extends ServerContainer implements IServerContainer {
150
-	/** @var string */
151
-	private $webRoot;
152
-
153
-	/**
154
-	 * @param string $webRoot
155
-	 * @param \OC\Config $config
156
-	 */
157
-	public function __construct($webRoot, \OC\Config $config) {
158
-		parent::__construct();
159
-		$this->webRoot = $webRoot;
160
-
161
-		$this->registerService(\OCP\IServerContainer::class, function (IServerContainer $c) {
162
-			return $c;
163
-		});
164
-
165
-		$this->registerAlias(\OCP\Calendar\IManager::class, \OC\Calendar\Manager::class);
166
-		$this->registerAlias('CalendarManager', \OC\Calendar\Manager::class);
167
-
168
-		$this->registerAlias(\OCP\Contacts\IManager::class, \OC\ContactsManager::class);
169
-		$this->registerAlias('ContactsManager', \OCP\Contacts\IManager::class);
170
-
171
-		$this->registerAlias(IActionFactory::class, ActionFactory::class);
172
-
173
-
174
-		$this->registerService(\OCP\IPreview::class, function (Server $c) {
175
-			return new PreviewManager(
176
-				$c->getConfig(),
177
-				$c->getRootFolder(),
178
-				$c->getAppDataDir('preview'),
179
-				$c->getEventDispatcher(),
180
-				$c->getSession()->get('user_id')
181
-			);
182
-		});
183
-		$this->registerAlias('PreviewManager', \OCP\IPreview::class);
184
-
185
-		$this->registerService(\OC\Preview\Watcher::class, function (Server $c) {
186
-			return new \OC\Preview\Watcher(
187
-				$c->getAppDataDir('preview')
188
-			);
189
-		});
190
-
191
-		$this->registerService('EncryptionManager', function (Server $c) {
192
-			$view = new View();
193
-			$util = new Encryption\Util(
194
-				$view,
195
-				$c->getUserManager(),
196
-				$c->getGroupManager(),
197
-				$c->getConfig()
198
-			);
199
-			return new Encryption\Manager(
200
-				$c->getConfig(),
201
-				$c->getLogger(),
202
-				$c->getL10N('core'),
203
-				new View(),
204
-				$util,
205
-				new ArrayCache()
206
-			);
207
-		});
208
-
209
-		$this->registerService('EncryptionFileHelper', function (Server $c) {
210
-			$util = new Encryption\Util(
211
-				new View(),
212
-				$c->getUserManager(),
213
-				$c->getGroupManager(),
214
-				$c->getConfig()
215
-			);
216
-			return new Encryption\File(
217
-				$util,
218
-				$c->getRootFolder(),
219
-				$c->getShareManager()
220
-			);
221
-		});
222
-
223
-		$this->registerService('EncryptionKeyStorage', function (Server $c) {
224
-			$view = new View();
225
-			$util = new Encryption\Util(
226
-				$view,
227
-				$c->getUserManager(),
228
-				$c->getGroupManager(),
229
-				$c->getConfig()
230
-			);
231
-
232
-			return new Encryption\Keys\Storage($view, $util);
233
-		});
234
-		$this->registerService('TagMapper', function (Server $c) {
235
-			return new TagMapper($c->getDatabaseConnection());
236
-		});
237
-
238
-		$this->registerService(\OCP\ITagManager::class, function (Server $c) {
239
-			$tagMapper = $c->query('TagMapper');
240
-			return new TagManager($tagMapper, $c->getUserSession());
241
-		});
242
-		$this->registerAlias('TagManager', \OCP\ITagManager::class);
243
-
244
-		$this->registerService('SystemTagManagerFactory', function (Server $c) {
245
-			$config = $c->getConfig();
246
-			$factoryClass = $config->getSystemValue('systemtags.managerFactory', '\OC\SystemTag\ManagerFactory');
247
-			/** @var \OC\SystemTag\ManagerFactory $factory */
248
-			$factory = new $factoryClass($this);
249
-			return $factory;
250
-		});
251
-		$this->registerService(\OCP\SystemTag\ISystemTagManager::class, function (Server $c) {
252
-			return $c->query('SystemTagManagerFactory')->getManager();
253
-		});
254
-		$this->registerAlias('SystemTagManager', \OCP\SystemTag\ISystemTagManager::class);
255
-
256
-		$this->registerService(\OCP\SystemTag\ISystemTagObjectMapper::class, function (Server $c) {
257
-			return $c->query('SystemTagManagerFactory')->getObjectMapper();
258
-		});
259
-		$this->registerService('RootFolder', function (Server $c) {
260
-			$manager = \OC\Files\Filesystem::getMountManager(null);
261
-			$view = new View();
262
-			$root = new Root(
263
-				$manager,
264
-				$view,
265
-				null,
266
-				$c->getUserMountCache(),
267
-				$this->getLogger(),
268
-				$this->getUserManager()
269
-			);
270
-			$connector = new HookConnector($root, $view);
271
-			$connector->viewToNode();
272
-
273
-			$previewConnector = new \OC\Preview\WatcherConnector($root, $c->getSystemConfig());
274
-			$previewConnector->connectWatcher();
275
-
276
-			return $root;
277
-		});
278
-		$this->registerAlias('SystemTagObjectMapper', \OCP\SystemTag\ISystemTagObjectMapper::class);
279
-
280
-		$this->registerService(\OCP\Files\IRootFolder::class, function (Server $c) {
281
-			return new LazyRoot(function () use ($c) {
282
-				return $c->query('RootFolder');
283
-			});
284
-		});
285
-		$this->registerAlias('LazyRootFolder', \OCP\Files\IRootFolder::class);
286
-
287
-		$this->registerService(\OCP\IUserManager::class, function (Server $c) {
288
-			$config = $c->getConfig();
289
-			return new \OC\User\Manager($config);
290
-		});
291
-		$this->registerAlias('UserManager', \OCP\IUserManager::class);
292
-
293
-		$this->registerService(\OCP\IGroupManager::class, function (Server $c) {
294
-			$groupManager = new \OC\Group\Manager($this->getUserManager(), $this->getLogger());
295
-			$groupManager->listen('\OC\Group', 'preCreate', function ($gid) {
296
-				\OC_Hook::emit('OC_Group', 'pre_createGroup', array('run' => true, 'gid' => $gid));
297
-			});
298
-			$groupManager->listen('\OC\Group', 'postCreate', function (\OC\Group\Group $gid) {
299
-				\OC_Hook::emit('OC_User', 'post_createGroup', array('gid' => $gid->getGID()));
300
-			});
301
-			$groupManager->listen('\OC\Group', 'preDelete', function (\OC\Group\Group $group) {
302
-				\OC_Hook::emit('OC_Group', 'pre_deleteGroup', array('run' => true, 'gid' => $group->getGID()));
303
-			});
304
-			$groupManager->listen('\OC\Group', 'postDelete', function (\OC\Group\Group $group) {
305
-				\OC_Hook::emit('OC_User', 'post_deleteGroup', array('gid' => $group->getGID()));
306
-			});
307
-			$groupManager->listen('\OC\Group', 'preAddUser', function (\OC\Group\Group $group, \OC\User\User $user) {
308
-				\OC_Hook::emit('OC_Group', 'pre_addToGroup', array('run' => true, 'uid' => $user->getUID(), 'gid' => $group->getGID()));
309
-			});
310
-			$groupManager->listen('\OC\Group', 'postAddUser', function (\OC\Group\Group $group, \OC\User\User $user) {
311
-				\OC_Hook::emit('OC_Group', 'post_addToGroup', array('uid' => $user->getUID(), 'gid' => $group->getGID()));
312
-				//Minimal fix to keep it backward compatible TODO: clean up all the GroupManager hooks
313
-				\OC_Hook::emit('OC_User', 'post_addToGroup', array('uid' => $user->getUID(), 'gid' => $group->getGID()));
314
-			});
315
-			return $groupManager;
316
-		});
317
-		$this->registerAlias('GroupManager', \OCP\IGroupManager::class);
318
-
319
-		$this->registerService(Store::class, function (Server $c) {
320
-			$session = $c->getSession();
321
-			if (\OC::$server->getSystemConfig()->getValue('installed', false)) {
322
-				$tokenProvider = $c->query('OC\Authentication\Token\IProvider');
323
-			} else {
324
-				$tokenProvider = null;
325
-			}
326
-			$logger = $c->getLogger();
327
-			return new Store($session, $logger, $tokenProvider);
328
-		});
329
-		$this->registerAlias(IStore::class, Store::class);
330
-		$this->registerService('OC\Authentication\Token\DefaultTokenMapper', function (Server $c) {
331
-			$dbConnection = $c->getDatabaseConnection();
332
-			return new Authentication\Token\DefaultTokenMapper($dbConnection);
333
-		});
334
-		$this->registerService('OC\Authentication\Token\DefaultTokenProvider', function (Server $c) {
335
-			$mapper = $c->query('OC\Authentication\Token\DefaultTokenMapper');
336
-			$crypto = $c->getCrypto();
337
-			$config = $c->getConfig();
338
-			$logger = $c->getLogger();
339
-			$timeFactory = new TimeFactory();
340
-			return new \OC\Authentication\Token\DefaultTokenProvider($mapper, $crypto, $config, $logger, $timeFactory);
341
-		});
342
-		$this->registerAlias('OC\Authentication\Token\IProvider', 'OC\Authentication\Token\DefaultTokenProvider');
343
-
344
-		$this->registerService(\OCP\IUserSession::class, function (Server $c) {
345
-			$manager = $c->getUserManager();
346
-			$session = new \OC\Session\Memory('');
347
-			$timeFactory = new TimeFactory();
348
-			// Token providers might require a working database. This code
349
-			// might however be called when ownCloud is not yet setup.
350
-			if (\OC::$server->getSystemConfig()->getValue('installed', false)) {
351
-				$defaultTokenProvider = $c->query('OC\Authentication\Token\IProvider');
352
-			} else {
353
-				$defaultTokenProvider = null;
354
-			}
355
-
356
-			$dispatcher = $c->getEventDispatcher();
357
-
358
-			$userSession = new \OC\User\Session($manager, $session, $timeFactory, $defaultTokenProvider, $c->getConfig(), $c->getSecureRandom(), $c->getLockdownManager());
359
-			$userSession->listen('\OC\User', 'preCreateUser', function ($uid, $password) {
360
-				\OC_Hook::emit('OC_User', 'pre_createUser', array('run' => true, 'uid' => $uid, 'password' => $password));
361
-			});
362
-			$userSession->listen('\OC\User', 'postCreateUser', function ($user, $password) {
363
-				/** @var $user \OC\User\User */
364
-				\OC_Hook::emit('OC_User', 'post_createUser', array('uid' => $user->getUID(), 'password' => $password));
365
-			});
366
-			$userSession->listen('\OC\User', 'preDelete', function ($user) use ($dispatcher) {
367
-				/** @var $user \OC\User\User */
368
-				\OC_Hook::emit('OC_User', 'pre_deleteUser', array('run' => true, 'uid' => $user->getUID()));
369
-				$dispatcher->dispatch('OCP\IUser::preDelete', new GenericEvent($user));
370
-			});
371
-			$userSession->listen('\OC\User', 'postDelete', function ($user) {
372
-				/** @var $user \OC\User\User */
373
-				\OC_Hook::emit('OC_User', 'post_deleteUser', array('uid' => $user->getUID()));
374
-			});
375
-			$userSession->listen('\OC\User', 'preSetPassword', function ($user, $password, $recoveryPassword) {
376
-				/** @var $user \OC\User\User */
377
-				\OC_Hook::emit('OC_User', 'pre_setPassword', array('run' => true, 'uid' => $user->getUID(), 'password' => $password, 'recoveryPassword' => $recoveryPassword));
378
-			});
379
-			$userSession->listen('\OC\User', 'postSetPassword', function ($user, $password, $recoveryPassword) {
380
-				/** @var $user \OC\User\User */
381
-				\OC_Hook::emit('OC_User', 'post_setPassword', array('run' => true, 'uid' => $user->getUID(), 'password' => $password, 'recoveryPassword' => $recoveryPassword));
382
-			});
383
-			$userSession->listen('\OC\User', 'preLogin', function ($uid, $password) {
384
-				\OC_Hook::emit('OC_User', 'pre_login', array('run' => true, 'uid' => $uid, 'password' => $password));
385
-			});
386
-			$userSession->listen('\OC\User', 'postLogin', function ($user, $password) {
387
-				/** @var $user \OC\User\User */
388
-				\OC_Hook::emit('OC_User', 'post_login', array('run' => true, 'uid' => $user->getUID(), 'password' => $password));
389
-			});
390
-			$userSession->listen('\OC\User', 'postRememberedLogin', function ($user, $password) {
391
-				/** @var $user \OC\User\User */
392
-				\OC_Hook::emit('OC_User', 'post_login', array('run' => true, 'uid' => $user->getUID(), 'password' => $password));
393
-			});
394
-			$userSession->listen('\OC\User', 'logout', function () {
395
-				\OC_Hook::emit('OC_User', 'logout', array());
396
-			});
397
-			$userSession->listen('\OC\User', 'changeUser', function ($user, $feature, $value, $oldValue) use ($dispatcher) {
398
-				/** @var $user \OC\User\User */
399
-				\OC_Hook::emit('OC_User', 'changeUser', array('run' => true, 'user' => $user, 'feature' => $feature, 'value' => $value, 'old_value' => $oldValue));
400
-				$dispatcher->dispatch('OCP\IUser::changeUser', new GenericEvent($user, ['feature' => $feature, 'oldValue' => $oldValue, 'value' => $value]));
401
-			});
402
-			return $userSession;
403
-		});
404
-		$this->registerAlias('UserSession', \OCP\IUserSession::class);
405
-
406
-		$this->registerService(\OC\Authentication\TwoFactorAuth\Manager::class, function (Server $c) {
407
-			return new \OC\Authentication\TwoFactorAuth\Manager(
408
-				$c->getAppManager(),
409
-				$c->getSession(),
410
-				$c->getConfig(),
411
-				$c->getActivityManager(),
412
-				$c->getLogger(),
413
-				$c->query(\OC\Authentication\Token\IProvider::class),
414
-				$c->query(ITimeFactory::class)
415
-			);
416
-		});
417
-
418
-		$this->registerAlias(\OCP\INavigationManager::class, \OC\NavigationManager::class);
419
-		$this->registerAlias('NavigationManager', \OCP\INavigationManager::class);
420
-
421
-		$this->registerService(\OC\AllConfig::class, function (Server $c) {
422
-			return new \OC\AllConfig(
423
-				$c->getSystemConfig()
424
-			);
425
-		});
426
-		$this->registerAlias('AllConfig', \OC\AllConfig::class);
427
-		$this->registerAlias(\OCP\IConfig::class, \OC\AllConfig::class);
428
-
429
-		$this->registerService('SystemConfig', function ($c) use ($config) {
430
-			return new \OC\SystemConfig($config);
431
-		});
432
-
433
-		$this->registerService(\OC\AppConfig::class, function (Server $c) {
434
-			return new \OC\AppConfig($c->getDatabaseConnection());
435
-		});
436
-		$this->registerAlias('AppConfig', \OC\AppConfig::class);
437
-		$this->registerAlias(\OCP\IAppConfig::class, \OC\AppConfig::class);
438
-
439
-		$this->registerService(\OCP\L10N\IFactory::class, function (Server $c) {
440
-			return new \OC\L10N\Factory(
441
-				$c->getConfig(),
442
-				$c->getRequest(),
443
-				$c->getUserSession(),
444
-				\OC::$SERVERROOT
445
-			);
446
-		});
447
-		$this->registerAlias('L10NFactory', \OCP\L10N\IFactory::class);
448
-
449
-		$this->registerService(\OCP\IURLGenerator::class, function (Server $c) {
450
-			$config = $c->getConfig();
451
-			$cacheFactory = $c->getMemCacheFactory();
452
-			$request = $c->getRequest();
453
-			return new \OC\URLGenerator(
454
-				$config,
455
-				$cacheFactory,
456
-				$request
457
-			);
458
-		});
459
-		$this->registerAlias('URLGenerator', \OCP\IURLGenerator::class);
460
-
461
-		$this->registerService('AppHelper', function ($c) {
462
-			return new \OC\AppHelper();
463
-		});
464
-		$this->registerAlias('AppFetcher', AppFetcher::class);
465
-		$this->registerAlias('CategoryFetcher', CategoryFetcher::class);
466
-
467
-		$this->registerService(\OCP\ICache::class, function ($c) {
468
-			return new Cache\File();
469
-		});
470
-		$this->registerAlias('UserCache', \OCP\ICache::class);
471
-
472
-		$this->registerService(Factory::class, function (Server $c) {
473
-
474
-			$arrayCacheFactory = new \OC\Memcache\Factory('', $c->getLogger(),
475
-				'\\OC\\Memcache\\ArrayCache',
476
-				'\\OC\\Memcache\\ArrayCache',
477
-				'\\OC\\Memcache\\ArrayCache'
478
-			);
479
-			$config = $c->getConfig();
480
-			$request = $c->getRequest();
481
-			$urlGenerator = new URLGenerator($config, $arrayCacheFactory, $request);
482
-
483
-			if ($config->getSystemValue('installed', false) && !(defined('PHPUNIT_RUN') && PHPUNIT_RUN)) {
484
-				$v = \OC_App::getAppVersions();
485
-				$v['core'] = implode(',', \OC_Util::getVersion());
486
-				$version = implode(',', $v);
487
-				$instanceId = \OC_Util::getInstanceId();
488
-				$path = \OC::$SERVERROOT;
489
-				$prefix = md5($instanceId . '-' . $version . '-' . $path . '-' . $urlGenerator->getBaseUrl());
490
-				return new \OC\Memcache\Factory($prefix, $c->getLogger(),
491
-					$config->getSystemValue('memcache.local', null),
492
-					$config->getSystemValue('memcache.distributed', null),
493
-					$config->getSystemValue('memcache.locking', null)
494
-				);
495
-			}
496
-			return $arrayCacheFactory;
497
-
498
-		});
499
-		$this->registerAlias('MemCacheFactory', Factory::class);
500
-		$this->registerAlias(ICacheFactory::class, Factory::class);
501
-
502
-		$this->registerService('RedisFactory', function (Server $c) {
503
-			$systemConfig = $c->getSystemConfig();
504
-			return new RedisFactory($systemConfig);
505
-		});
506
-
507
-		$this->registerService(\OCP\Activity\IManager::class, function (Server $c) {
508
-			return new \OC\Activity\Manager(
509
-				$c->getRequest(),
510
-				$c->getUserSession(),
511
-				$c->getConfig(),
512
-				$c->query(IValidator::class)
513
-			);
514
-		});
515
-		$this->registerAlias('ActivityManager', \OCP\Activity\IManager::class);
516
-
517
-		$this->registerService(\OCP\Activity\IEventMerger::class, function (Server $c) {
518
-			return new \OC\Activity\EventMerger(
519
-				$c->getL10N('lib')
520
-			);
521
-		});
522
-		$this->registerAlias(IValidator::class, Validator::class);
523
-
524
-		$this->registerService(\OCP\IAvatarManager::class, function (Server $c) {
525
-			return new AvatarManager(
526
-				$c->getUserManager(),
527
-				$c->getAppDataDir('avatar'),
528
-				$c->getL10N('lib'),
529
-				$c->getLogger(),
530
-				$c->getConfig()
531
-			);
532
-		});
533
-		$this->registerAlias('AvatarManager', \OCP\IAvatarManager::class);
534
-
535
-		$this->registerAlias(\OCP\Support\CrashReport\IRegistry::class, \OC\Support\CrashReport\Registry::class);
536
-
537
-		$this->registerService(\OCP\ILogger::class, function (Server $c) {
538
-			$logType = $c->query('AllConfig')->getSystemValue('log_type', 'file');
539
-			$logger = Log::getLogClass($logType);
540
-			call_user_func(array($logger, 'init'));
541
-			$config = $this->getSystemConfig();
542
-			$registry = $c->query(\OCP\Support\CrashReport\IRegistry::class);
543
-
544
-			return new Log($logger, $config, null, $registry);
545
-		});
546
-		$this->registerAlias('Logger', \OCP\ILogger::class);
547
-
548
-		$this->registerService(\OCP\BackgroundJob\IJobList::class, function (Server $c) {
549
-			$config = $c->getConfig();
550
-			return new \OC\BackgroundJob\JobList(
551
-				$c->getDatabaseConnection(),
552
-				$config,
553
-				new TimeFactory()
554
-			);
555
-		});
556
-		$this->registerAlias('JobList', \OCP\BackgroundJob\IJobList::class);
557
-
558
-		$this->registerService(\OCP\Route\IRouter::class, function (Server $c) {
559
-			$cacheFactory = $c->getMemCacheFactory();
560
-			$logger = $c->getLogger();
561
-			if ($cacheFactory->isAvailableLowLatency()) {
562
-				$router = new \OC\Route\CachingRouter($cacheFactory->createLocal('route'), $logger);
563
-			} else {
564
-				$router = new \OC\Route\Router($logger);
565
-			}
566
-			return $router;
567
-		});
568
-		$this->registerAlias('Router', \OCP\Route\IRouter::class);
569
-
570
-		$this->registerService(\OCP\ISearch::class, function ($c) {
571
-			return new Search();
572
-		});
573
-		$this->registerAlias('Search', \OCP\ISearch::class);
574
-
575
-		$this->registerService(\OC\Security\RateLimiting\Limiter::class, function ($c) {
576
-			return new \OC\Security\RateLimiting\Limiter(
577
-				$this->getUserSession(),
578
-				$this->getRequest(),
579
-				new \OC\AppFramework\Utility\TimeFactory(),
580
-				$c->query(\OC\Security\RateLimiting\Backend\IBackend::class)
581
-			);
582
-		});
583
-		$this->registerService(\OC\Security\RateLimiting\Backend\IBackend::class, function ($c) {
584
-			return new \OC\Security\RateLimiting\Backend\MemoryCache(
585
-				$this->getMemCacheFactory(),
586
-				new \OC\AppFramework\Utility\TimeFactory()
587
-			);
588
-		});
589
-
590
-		$this->registerService(\OCP\Security\ISecureRandom::class, function ($c) {
591
-			return new SecureRandom();
592
-		});
593
-		$this->registerAlias('SecureRandom', \OCP\Security\ISecureRandom::class);
594
-
595
-		$this->registerService(\OCP\Security\ICrypto::class, function (Server $c) {
596
-			return new Crypto($c->getConfig(), $c->getSecureRandom());
597
-		});
598
-		$this->registerAlias('Crypto', \OCP\Security\ICrypto::class);
599
-
600
-		$this->registerService(\OCP\Security\IHasher::class, function (Server $c) {
601
-			return new Hasher($c->getConfig());
602
-		});
603
-		$this->registerAlias('Hasher', \OCP\Security\IHasher::class);
604
-
605
-		$this->registerService(\OCP\Security\ICredentialsManager::class, function (Server $c) {
606
-			return new CredentialsManager($c->getCrypto(), $c->getDatabaseConnection());
607
-		});
608
-		$this->registerAlias('CredentialsManager', \OCP\Security\ICredentialsManager::class);
609
-
610
-		$this->registerService(IDBConnection::class, function (Server $c) {
611
-			$systemConfig = $c->getSystemConfig();
612
-			$factory = new \OC\DB\ConnectionFactory($systemConfig);
613
-			$type = $systemConfig->getValue('dbtype', 'sqlite');
614
-			if (!$factory->isValidType($type)) {
615
-				throw new \OC\DatabaseException('Invalid database type');
616
-			}
617
-			$connectionParams = $factory->createConnectionParams();
618
-			$connection = $factory->getConnection($type, $connectionParams);
619
-			$connection->getConfiguration()->setSQLLogger($c->getQueryLogger());
620
-			return $connection;
621
-		});
622
-		$this->registerAlias('DatabaseConnection', IDBConnection::class);
623
-
624
-		$this->registerService('HTTPHelper', function (Server $c) {
625
-			$config = $c->getConfig();
626
-			return new HTTPHelper(
627
-				$config,
628
-				$c->getHTTPClientService()
629
-			);
630
-		});
631
-
632
-		$this->registerService(\OCP\Http\Client\IClientService::class, function (Server $c) {
633
-			$user = \OC_User::getUser();
634
-			$uid = $user ? $user : null;
635
-			return new ClientService(
636
-				$c->getConfig(),
637
-				new \OC\Security\CertificateManager(
638
-					$uid,
639
-					new View(),
640
-					$c->getConfig(),
641
-					$c->getLogger(),
642
-					$c->getSecureRandom()
643
-				)
644
-			);
645
-		});
646
-		$this->registerAlias('HttpClientService', \OCP\Http\Client\IClientService::class);
647
-		$this->registerService(\OCP\Diagnostics\IEventLogger::class, function (Server $c) {
648
-			$eventLogger = new EventLogger();
649
-			if ($c->getSystemConfig()->getValue('debug', false)) {
650
-				// In debug mode, module is being activated by default
651
-				$eventLogger->activate();
652
-			}
653
-			return $eventLogger;
654
-		});
655
-		$this->registerAlias('EventLogger', \OCP\Diagnostics\IEventLogger::class);
656
-
657
-		$this->registerService(\OCP\Diagnostics\IQueryLogger::class, function (Server $c) {
658
-			$queryLogger = new QueryLogger();
659
-			if ($c->getSystemConfig()->getValue('debug', false)) {
660
-				// In debug mode, module is being activated by default
661
-				$queryLogger->activate();
662
-			}
663
-			return $queryLogger;
664
-		});
665
-		$this->registerAlias('QueryLogger', \OCP\Diagnostics\IQueryLogger::class);
666
-
667
-		$this->registerService(TempManager::class, function (Server $c) {
668
-			return new TempManager(
669
-				$c->getLogger(),
670
-				$c->getConfig()
671
-			);
672
-		});
673
-		$this->registerAlias('TempManager', TempManager::class);
674
-		$this->registerAlias(ITempManager::class, TempManager::class);
675
-
676
-		$this->registerService(AppManager::class, function (Server $c) {
677
-			return new \OC\App\AppManager(
678
-				$c->getUserSession(),
679
-				$c->getAppConfig(),
680
-				$c->getGroupManager(),
681
-				$c->getMemCacheFactory(),
682
-				$c->getEventDispatcher()
683
-			);
684
-		});
685
-		$this->registerAlias('AppManager', AppManager::class);
686
-		$this->registerAlias(IAppManager::class, AppManager::class);
687
-
688
-		$this->registerService(\OCP\IDateTimeZone::class, function (Server $c) {
689
-			return new DateTimeZone(
690
-				$c->getConfig(),
691
-				$c->getSession()
692
-			);
693
-		});
694
-		$this->registerAlias('DateTimeZone', \OCP\IDateTimeZone::class);
695
-
696
-		$this->registerService(\OCP\IDateTimeFormatter::class, function (Server $c) {
697
-			$language = $c->getConfig()->getUserValue($c->getSession()->get('user_id'), 'core', 'lang', null);
698
-
699
-			return new DateTimeFormatter(
700
-				$c->getDateTimeZone()->getTimeZone(),
701
-				$c->getL10N('lib', $language)
702
-			);
703
-		});
704
-		$this->registerAlias('DateTimeFormatter', \OCP\IDateTimeFormatter::class);
705
-
706
-		$this->registerService(\OCP\Files\Config\IUserMountCache::class, function (Server $c) {
707
-			$mountCache = new UserMountCache($c->getDatabaseConnection(), $c->getUserManager(), $c->getLogger());
708
-			$listener = new UserMountCacheListener($mountCache);
709
-			$listener->listen($c->getUserManager());
710
-			return $mountCache;
711
-		});
712
-		$this->registerAlias('UserMountCache', \OCP\Files\Config\IUserMountCache::class);
713
-
714
-		$this->registerService(\OCP\Files\Config\IMountProviderCollection::class, function (Server $c) {
715
-			$loader = \OC\Files\Filesystem::getLoader();
716
-			$mountCache = $c->query('UserMountCache');
717
-			$manager = new \OC\Files\Config\MountProviderCollection($loader, $mountCache);
718
-
719
-			// builtin providers
720
-
721
-			$config = $c->getConfig();
722
-			$manager->registerProvider(new CacheMountProvider($config));
723
-			$manager->registerHomeProvider(new LocalHomeMountProvider());
724
-			$manager->registerHomeProvider(new ObjectHomeMountProvider($config));
725
-
726
-			return $manager;
727
-		});
728
-		$this->registerAlias('MountConfigManager', \OCP\Files\Config\IMountProviderCollection::class);
729
-
730
-		$this->registerService('IniWrapper', function ($c) {
731
-			return new IniGetWrapper();
732
-		});
733
-		$this->registerService('AsyncCommandBus', function (Server $c) {
734
-			$busClass = $c->getConfig()->getSystemValue('commandbus');
735
-			if ($busClass) {
736
-				list($app, $class) = explode('::', $busClass, 2);
737
-				if ($c->getAppManager()->isInstalled($app)) {
738
-					\OC_App::loadApp($app);
739
-					return $c->query($class);
740
-				} else {
741
-					throw new ServiceUnavailableException("The app providing the command bus ($app) is not enabled");
742
-				}
743
-			} else {
744
-				$jobList = $c->getJobList();
745
-				return new CronBus($jobList);
746
-			}
747
-		});
748
-		$this->registerService('TrustedDomainHelper', function ($c) {
749
-			return new TrustedDomainHelper($this->getConfig());
750
-		});
751
-		$this->registerService('Throttler', function (Server $c) {
752
-			return new Throttler(
753
-				$c->getDatabaseConnection(),
754
-				new TimeFactory(),
755
-				$c->getLogger(),
756
-				$c->getConfig()
757
-			);
758
-		});
759
-		$this->registerService('IntegrityCodeChecker', function (Server $c) {
760
-			// IConfig and IAppManager requires a working database. This code
761
-			// might however be called when ownCloud is not yet setup.
762
-			if (\OC::$server->getSystemConfig()->getValue('installed', false)) {
763
-				$config = $c->getConfig();
764
-				$appManager = $c->getAppManager();
765
-			} else {
766
-				$config = null;
767
-				$appManager = null;
768
-			}
769
-
770
-			return new Checker(
771
-				new EnvironmentHelper(),
772
-				new FileAccessHelper(),
773
-				new AppLocator(),
774
-				$config,
775
-				$c->getMemCacheFactory(),
776
-				$appManager,
777
-				$c->getTempManager()
778
-			);
779
-		});
780
-		$this->registerService(\OCP\IRequest::class, function ($c) {
781
-			if (isset($this['urlParams'])) {
782
-				$urlParams = $this['urlParams'];
783
-			} else {
784
-				$urlParams = [];
785
-			}
786
-
787
-			if (defined('PHPUNIT_RUN') && PHPUNIT_RUN
788
-				&& in_array('fakeinput', stream_get_wrappers())
789
-			) {
790
-				$stream = 'fakeinput://data';
791
-			} else {
792
-				$stream = 'php://input';
793
-			}
794
-
795
-			return new Request(
796
-				[
797
-					'get' => $_GET,
798
-					'post' => $_POST,
799
-					'files' => $_FILES,
800
-					'server' => $_SERVER,
801
-					'env' => $_ENV,
802
-					'cookies' => $_COOKIE,
803
-					'method' => (isset($_SERVER) && isset($_SERVER['REQUEST_METHOD']))
804
-						? $_SERVER['REQUEST_METHOD']
805
-						: null,
806
-					'urlParams' => $urlParams,
807
-				],
808
-				$this->getSecureRandom(),
809
-				$this->getConfig(),
810
-				$this->getCsrfTokenManager(),
811
-				$stream
812
-			);
813
-		});
814
-		$this->registerAlias('Request', \OCP\IRequest::class);
815
-
816
-		$this->registerService(\OCP\Mail\IMailer::class, function (Server $c) {
817
-			return new Mailer(
818
-				$c->getConfig(),
819
-				$c->getLogger(),
820
-				$c->query(Defaults::class),
821
-				$c->getURLGenerator(),
822
-				$c->getL10N('lib')
823
-			);
824
-		});
825
-		$this->registerAlias('Mailer', \OCP\Mail\IMailer::class);
826
-
827
-		$this->registerService('LDAPProvider', function (Server $c) {
828
-			$config = $c->getConfig();
829
-			$factoryClass = $config->getSystemValue('ldapProviderFactory', null);
830
-			if (is_null($factoryClass)) {
831
-				throw new \Exception('ldapProviderFactory not set');
832
-			}
833
-			/** @var \OCP\LDAP\ILDAPProviderFactory $factory */
834
-			$factory = new $factoryClass($this);
835
-			return $factory->getLDAPProvider();
836
-		});
837
-		$this->registerService(ILockingProvider::class, function (Server $c) {
838
-			$ini = $c->getIniWrapper();
839
-			$config = $c->getConfig();
840
-			$ttl = $config->getSystemValue('filelocking.ttl', max(3600, $ini->getNumeric('max_execution_time')));
841
-			if ($config->getSystemValue('filelocking.enabled', true) or (defined('PHPUNIT_RUN') && PHPUNIT_RUN)) {
842
-				/** @var \OC\Memcache\Factory $memcacheFactory */
843
-				$memcacheFactory = $c->getMemCacheFactory();
844
-				$memcache = $memcacheFactory->createLocking('lock');
845
-				if (!($memcache instanceof \OC\Memcache\NullCache)) {
846
-					return new MemcacheLockingProvider($memcache, $ttl);
847
-				}
848
-				return new DBLockingProvider($c->getDatabaseConnection(), $c->getLogger(), new TimeFactory(), $ttl);
849
-			}
850
-			return new NoopLockingProvider();
851
-		});
852
-		$this->registerAlias('LockingProvider', ILockingProvider::class);
853
-
854
-		$this->registerService(\OCP\Files\Mount\IMountManager::class, function () {
855
-			return new \OC\Files\Mount\Manager();
856
-		});
857
-		$this->registerAlias('MountManager', \OCP\Files\Mount\IMountManager::class);
858
-
859
-		$this->registerService(\OCP\Files\IMimeTypeDetector::class, function (Server $c) {
860
-			return new \OC\Files\Type\Detection(
861
-				$c->getURLGenerator(),
862
-				\OC::$configDir,
863
-				\OC::$SERVERROOT . '/resources/config/'
864
-			);
865
-		});
866
-		$this->registerAlias('MimeTypeDetector', \OCP\Files\IMimeTypeDetector::class);
867
-
868
-		$this->registerService(\OCP\Files\IMimeTypeLoader::class, function (Server $c) {
869
-			return new \OC\Files\Type\Loader(
870
-				$c->getDatabaseConnection()
871
-			);
872
-		});
873
-		$this->registerAlias('MimeTypeLoader', \OCP\Files\IMimeTypeLoader::class);
874
-		$this->registerService(BundleFetcher::class, function () {
875
-			return new BundleFetcher($this->getL10N('lib'));
876
-		});
877
-		$this->registerService(\OCP\Notification\IManager::class, function (Server $c) {
878
-			return new Manager(
879
-				$c->query(IValidator::class)
880
-			);
881
-		});
882
-		$this->registerAlias('NotificationManager', \OCP\Notification\IManager::class);
883
-
884
-		$this->registerService(\OC\CapabilitiesManager::class, function (Server $c) {
885
-			$manager = new \OC\CapabilitiesManager($c->getLogger());
886
-			$manager->registerCapability(function () use ($c) {
887
-				return new \OC\OCS\CoreCapabilities($c->getConfig());
888
-			});
889
-			$manager->registerCapability(function () use ($c) {
890
-				return $c->query(\OC\Security\Bruteforce\Capabilities::class);
891
-			});
892
-			return $manager;
893
-		});
894
-		$this->registerAlias('CapabilitiesManager', \OC\CapabilitiesManager::class);
895
-
896
-		$this->registerService(\OCP\Comments\ICommentsManager::class, function (Server $c) {
897
-			$config = $c->getConfig();
898
-			$factoryClass = $config->getSystemValue('comments.managerFactory', '\OC\Comments\ManagerFactory');
899
-			/** @var \OCP\Comments\ICommentsManagerFactory $factory */
900
-			$factory = new $factoryClass($this);
901
-			$manager = $factory->getManager();
902
-
903
-			$manager->registerDisplayNameResolver('user', function($id) use ($c) {
904
-				$manager = $c->getUserManager();
905
-				$user = $manager->get($id);
906
-				if(is_null($user)) {
907
-					$l = $c->getL10N('core');
908
-					$displayName = $l->t('Unknown user');
909
-				} else {
910
-					$displayName = $user->getDisplayName();
911
-				}
912
-				return $displayName;
913
-			});
914
-
915
-			return $manager;
916
-		});
917
-		$this->registerAlias('CommentsManager', \OCP\Comments\ICommentsManager::class);
918
-
919
-		$this->registerService('ThemingDefaults', function (Server $c) {
920
-			/*
150
+    /** @var string */
151
+    private $webRoot;
152
+
153
+    /**
154
+     * @param string $webRoot
155
+     * @param \OC\Config $config
156
+     */
157
+    public function __construct($webRoot, \OC\Config $config) {
158
+        parent::__construct();
159
+        $this->webRoot = $webRoot;
160
+
161
+        $this->registerService(\OCP\IServerContainer::class, function (IServerContainer $c) {
162
+            return $c;
163
+        });
164
+
165
+        $this->registerAlias(\OCP\Calendar\IManager::class, \OC\Calendar\Manager::class);
166
+        $this->registerAlias('CalendarManager', \OC\Calendar\Manager::class);
167
+
168
+        $this->registerAlias(\OCP\Contacts\IManager::class, \OC\ContactsManager::class);
169
+        $this->registerAlias('ContactsManager', \OCP\Contacts\IManager::class);
170
+
171
+        $this->registerAlias(IActionFactory::class, ActionFactory::class);
172
+
173
+
174
+        $this->registerService(\OCP\IPreview::class, function (Server $c) {
175
+            return new PreviewManager(
176
+                $c->getConfig(),
177
+                $c->getRootFolder(),
178
+                $c->getAppDataDir('preview'),
179
+                $c->getEventDispatcher(),
180
+                $c->getSession()->get('user_id')
181
+            );
182
+        });
183
+        $this->registerAlias('PreviewManager', \OCP\IPreview::class);
184
+
185
+        $this->registerService(\OC\Preview\Watcher::class, function (Server $c) {
186
+            return new \OC\Preview\Watcher(
187
+                $c->getAppDataDir('preview')
188
+            );
189
+        });
190
+
191
+        $this->registerService('EncryptionManager', function (Server $c) {
192
+            $view = new View();
193
+            $util = new Encryption\Util(
194
+                $view,
195
+                $c->getUserManager(),
196
+                $c->getGroupManager(),
197
+                $c->getConfig()
198
+            );
199
+            return new Encryption\Manager(
200
+                $c->getConfig(),
201
+                $c->getLogger(),
202
+                $c->getL10N('core'),
203
+                new View(),
204
+                $util,
205
+                new ArrayCache()
206
+            );
207
+        });
208
+
209
+        $this->registerService('EncryptionFileHelper', function (Server $c) {
210
+            $util = new Encryption\Util(
211
+                new View(),
212
+                $c->getUserManager(),
213
+                $c->getGroupManager(),
214
+                $c->getConfig()
215
+            );
216
+            return new Encryption\File(
217
+                $util,
218
+                $c->getRootFolder(),
219
+                $c->getShareManager()
220
+            );
221
+        });
222
+
223
+        $this->registerService('EncryptionKeyStorage', function (Server $c) {
224
+            $view = new View();
225
+            $util = new Encryption\Util(
226
+                $view,
227
+                $c->getUserManager(),
228
+                $c->getGroupManager(),
229
+                $c->getConfig()
230
+            );
231
+
232
+            return new Encryption\Keys\Storage($view, $util);
233
+        });
234
+        $this->registerService('TagMapper', function (Server $c) {
235
+            return new TagMapper($c->getDatabaseConnection());
236
+        });
237
+
238
+        $this->registerService(\OCP\ITagManager::class, function (Server $c) {
239
+            $tagMapper = $c->query('TagMapper');
240
+            return new TagManager($tagMapper, $c->getUserSession());
241
+        });
242
+        $this->registerAlias('TagManager', \OCP\ITagManager::class);
243
+
244
+        $this->registerService('SystemTagManagerFactory', function (Server $c) {
245
+            $config = $c->getConfig();
246
+            $factoryClass = $config->getSystemValue('systemtags.managerFactory', '\OC\SystemTag\ManagerFactory');
247
+            /** @var \OC\SystemTag\ManagerFactory $factory */
248
+            $factory = new $factoryClass($this);
249
+            return $factory;
250
+        });
251
+        $this->registerService(\OCP\SystemTag\ISystemTagManager::class, function (Server $c) {
252
+            return $c->query('SystemTagManagerFactory')->getManager();
253
+        });
254
+        $this->registerAlias('SystemTagManager', \OCP\SystemTag\ISystemTagManager::class);
255
+
256
+        $this->registerService(\OCP\SystemTag\ISystemTagObjectMapper::class, function (Server $c) {
257
+            return $c->query('SystemTagManagerFactory')->getObjectMapper();
258
+        });
259
+        $this->registerService('RootFolder', function (Server $c) {
260
+            $manager = \OC\Files\Filesystem::getMountManager(null);
261
+            $view = new View();
262
+            $root = new Root(
263
+                $manager,
264
+                $view,
265
+                null,
266
+                $c->getUserMountCache(),
267
+                $this->getLogger(),
268
+                $this->getUserManager()
269
+            );
270
+            $connector = new HookConnector($root, $view);
271
+            $connector->viewToNode();
272
+
273
+            $previewConnector = new \OC\Preview\WatcherConnector($root, $c->getSystemConfig());
274
+            $previewConnector->connectWatcher();
275
+
276
+            return $root;
277
+        });
278
+        $this->registerAlias('SystemTagObjectMapper', \OCP\SystemTag\ISystemTagObjectMapper::class);
279
+
280
+        $this->registerService(\OCP\Files\IRootFolder::class, function (Server $c) {
281
+            return new LazyRoot(function () use ($c) {
282
+                return $c->query('RootFolder');
283
+            });
284
+        });
285
+        $this->registerAlias('LazyRootFolder', \OCP\Files\IRootFolder::class);
286
+
287
+        $this->registerService(\OCP\IUserManager::class, function (Server $c) {
288
+            $config = $c->getConfig();
289
+            return new \OC\User\Manager($config);
290
+        });
291
+        $this->registerAlias('UserManager', \OCP\IUserManager::class);
292
+
293
+        $this->registerService(\OCP\IGroupManager::class, function (Server $c) {
294
+            $groupManager = new \OC\Group\Manager($this->getUserManager(), $this->getLogger());
295
+            $groupManager->listen('\OC\Group', 'preCreate', function ($gid) {
296
+                \OC_Hook::emit('OC_Group', 'pre_createGroup', array('run' => true, 'gid' => $gid));
297
+            });
298
+            $groupManager->listen('\OC\Group', 'postCreate', function (\OC\Group\Group $gid) {
299
+                \OC_Hook::emit('OC_User', 'post_createGroup', array('gid' => $gid->getGID()));
300
+            });
301
+            $groupManager->listen('\OC\Group', 'preDelete', function (\OC\Group\Group $group) {
302
+                \OC_Hook::emit('OC_Group', 'pre_deleteGroup', array('run' => true, 'gid' => $group->getGID()));
303
+            });
304
+            $groupManager->listen('\OC\Group', 'postDelete', function (\OC\Group\Group $group) {
305
+                \OC_Hook::emit('OC_User', 'post_deleteGroup', array('gid' => $group->getGID()));
306
+            });
307
+            $groupManager->listen('\OC\Group', 'preAddUser', function (\OC\Group\Group $group, \OC\User\User $user) {
308
+                \OC_Hook::emit('OC_Group', 'pre_addToGroup', array('run' => true, 'uid' => $user->getUID(), 'gid' => $group->getGID()));
309
+            });
310
+            $groupManager->listen('\OC\Group', 'postAddUser', function (\OC\Group\Group $group, \OC\User\User $user) {
311
+                \OC_Hook::emit('OC_Group', 'post_addToGroup', array('uid' => $user->getUID(), 'gid' => $group->getGID()));
312
+                //Minimal fix to keep it backward compatible TODO: clean up all the GroupManager hooks
313
+                \OC_Hook::emit('OC_User', 'post_addToGroup', array('uid' => $user->getUID(), 'gid' => $group->getGID()));
314
+            });
315
+            return $groupManager;
316
+        });
317
+        $this->registerAlias('GroupManager', \OCP\IGroupManager::class);
318
+
319
+        $this->registerService(Store::class, function (Server $c) {
320
+            $session = $c->getSession();
321
+            if (\OC::$server->getSystemConfig()->getValue('installed', false)) {
322
+                $tokenProvider = $c->query('OC\Authentication\Token\IProvider');
323
+            } else {
324
+                $tokenProvider = null;
325
+            }
326
+            $logger = $c->getLogger();
327
+            return new Store($session, $logger, $tokenProvider);
328
+        });
329
+        $this->registerAlias(IStore::class, Store::class);
330
+        $this->registerService('OC\Authentication\Token\DefaultTokenMapper', function (Server $c) {
331
+            $dbConnection = $c->getDatabaseConnection();
332
+            return new Authentication\Token\DefaultTokenMapper($dbConnection);
333
+        });
334
+        $this->registerService('OC\Authentication\Token\DefaultTokenProvider', function (Server $c) {
335
+            $mapper = $c->query('OC\Authentication\Token\DefaultTokenMapper');
336
+            $crypto = $c->getCrypto();
337
+            $config = $c->getConfig();
338
+            $logger = $c->getLogger();
339
+            $timeFactory = new TimeFactory();
340
+            return new \OC\Authentication\Token\DefaultTokenProvider($mapper, $crypto, $config, $logger, $timeFactory);
341
+        });
342
+        $this->registerAlias('OC\Authentication\Token\IProvider', 'OC\Authentication\Token\DefaultTokenProvider');
343
+
344
+        $this->registerService(\OCP\IUserSession::class, function (Server $c) {
345
+            $manager = $c->getUserManager();
346
+            $session = new \OC\Session\Memory('');
347
+            $timeFactory = new TimeFactory();
348
+            // Token providers might require a working database. This code
349
+            // might however be called when ownCloud is not yet setup.
350
+            if (\OC::$server->getSystemConfig()->getValue('installed', false)) {
351
+                $defaultTokenProvider = $c->query('OC\Authentication\Token\IProvider');
352
+            } else {
353
+                $defaultTokenProvider = null;
354
+            }
355
+
356
+            $dispatcher = $c->getEventDispatcher();
357
+
358
+            $userSession = new \OC\User\Session($manager, $session, $timeFactory, $defaultTokenProvider, $c->getConfig(), $c->getSecureRandom(), $c->getLockdownManager());
359
+            $userSession->listen('\OC\User', 'preCreateUser', function ($uid, $password) {
360
+                \OC_Hook::emit('OC_User', 'pre_createUser', array('run' => true, 'uid' => $uid, 'password' => $password));
361
+            });
362
+            $userSession->listen('\OC\User', 'postCreateUser', function ($user, $password) {
363
+                /** @var $user \OC\User\User */
364
+                \OC_Hook::emit('OC_User', 'post_createUser', array('uid' => $user->getUID(), 'password' => $password));
365
+            });
366
+            $userSession->listen('\OC\User', 'preDelete', function ($user) use ($dispatcher) {
367
+                /** @var $user \OC\User\User */
368
+                \OC_Hook::emit('OC_User', 'pre_deleteUser', array('run' => true, 'uid' => $user->getUID()));
369
+                $dispatcher->dispatch('OCP\IUser::preDelete', new GenericEvent($user));
370
+            });
371
+            $userSession->listen('\OC\User', 'postDelete', function ($user) {
372
+                /** @var $user \OC\User\User */
373
+                \OC_Hook::emit('OC_User', 'post_deleteUser', array('uid' => $user->getUID()));
374
+            });
375
+            $userSession->listen('\OC\User', 'preSetPassword', function ($user, $password, $recoveryPassword) {
376
+                /** @var $user \OC\User\User */
377
+                \OC_Hook::emit('OC_User', 'pre_setPassword', array('run' => true, 'uid' => $user->getUID(), 'password' => $password, 'recoveryPassword' => $recoveryPassword));
378
+            });
379
+            $userSession->listen('\OC\User', 'postSetPassword', function ($user, $password, $recoveryPassword) {
380
+                /** @var $user \OC\User\User */
381
+                \OC_Hook::emit('OC_User', 'post_setPassword', array('run' => true, 'uid' => $user->getUID(), 'password' => $password, 'recoveryPassword' => $recoveryPassword));
382
+            });
383
+            $userSession->listen('\OC\User', 'preLogin', function ($uid, $password) {
384
+                \OC_Hook::emit('OC_User', 'pre_login', array('run' => true, 'uid' => $uid, 'password' => $password));
385
+            });
386
+            $userSession->listen('\OC\User', 'postLogin', function ($user, $password) {
387
+                /** @var $user \OC\User\User */
388
+                \OC_Hook::emit('OC_User', 'post_login', array('run' => true, 'uid' => $user->getUID(), 'password' => $password));
389
+            });
390
+            $userSession->listen('\OC\User', 'postRememberedLogin', function ($user, $password) {
391
+                /** @var $user \OC\User\User */
392
+                \OC_Hook::emit('OC_User', 'post_login', array('run' => true, 'uid' => $user->getUID(), 'password' => $password));
393
+            });
394
+            $userSession->listen('\OC\User', 'logout', function () {
395
+                \OC_Hook::emit('OC_User', 'logout', array());
396
+            });
397
+            $userSession->listen('\OC\User', 'changeUser', function ($user, $feature, $value, $oldValue) use ($dispatcher) {
398
+                /** @var $user \OC\User\User */
399
+                \OC_Hook::emit('OC_User', 'changeUser', array('run' => true, 'user' => $user, 'feature' => $feature, 'value' => $value, 'old_value' => $oldValue));
400
+                $dispatcher->dispatch('OCP\IUser::changeUser', new GenericEvent($user, ['feature' => $feature, 'oldValue' => $oldValue, 'value' => $value]));
401
+            });
402
+            return $userSession;
403
+        });
404
+        $this->registerAlias('UserSession', \OCP\IUserSession::class);
405
+
406
+        $this->registerService(\OC\Authentication\TwoFactorAuth\Manager::class, function (Server $c) {
407
+            return new \OC\Authentication\TwoFactorAuth\Manager(
408
+                $c->getAppManager(),
409
+                $c->getSession(),
410
+                $c->getConfig(),
411
+                $c->getActivityManager(),
412
+                $c->getLogger(),
413
+                $c->query(\OC\Authentication\Token\IProvider::class),
414
+                $c->query(ITimeFactory::class)
415
+            );
416
+        });
417
+
418
+        $this->registerAlias(\OCP\INavigationManager::class, \OC\NavigationManager::class);
419
+        $this->registerAlias('NavigationManager', \OCP\INavigationManager::class);
420
+
421
+        $this->registerService(\OC\AllConfig::class, function (Server $c) {
422
+            return new \OC\AllConfig(
423
+                $c->getSystemConfig()
424
+            );
425
+        });
426
+        $this->registerAlias('AllConfig', \OC\AllConfig::class);
427
+        $this->registerAlias(\OCP\IConfig::class, \OC\AllConfig::class);
428
+
429
+        $this->registerService('SystemConfig', function ($c) use ($config) {
430
+            return new \OC\SystemConfig($config);
431
+        });
432
+
433
+        $this->registerService(\OC\AppConfig::class, function (Server $c) {
434
+            return new \OC\AppConfig($c->getDatabaseConnection());
435
+        });
436
+        $this->registerAlias('AppConfig', \OC\AppConfig::class);
437
+        $this->registerAlias(\OCP\IAppConfig::class, \OC\AppConfig::class);
438
+
439
+        $this->registerService(\OCP\L10N\IFactory::class, function (Server $c) {
440
+            return new \OC\L10N\Factory(
441
+                $c->getConfig(),
442
+                $c->getRequest(),
443
+                $c->getUserSession(),
444
+                \OC::$SERVERROOT
445
+            );
446
+        });
447
+        $this->registerAlias('L10NFactory', \OCP\L10N\IFactory::class);
448
+
449
+        $this->registerService(\OCP\IURLGenerator::class, function (Server $c) {
450
+            $config = $c->getConfig();
451
+            $cacheFactory = $c->getMemCacheFactory();
452
+            $request = $c->getRequest();
453
+            return new \OC\URLGenerator(
454
+                $config,
455
+                $cacheFactory,
456
+                $request
457
+            );
458
+        });
459
+        $this->registerAlias('URLGenerator', \OCP\IURLGenerator::class);
460
+
461
+        $this->registerService('AppHelper', function ($c) {
462
+            return new \OC\AppHelper();
463
+        });
464
+        $this->registerAlias('AppFetcher', AppFetcher::class);
465
+        $this->registerAlias('CategoryFetcher', CategoryFetcher::class);
466
+
467
+        $this->registerService(\OCP\ICache::class, function ($c) {
468
+            return new Cache\File();
469
+        });
470
+        $this->registerAlias('UserCache', \OCP\ICache::class);
471
+
472
+        $this->registerService(Factory::class, function (Server $c) {
473
+
474
+            $arrayCacheFactory = new \OC\Memcache\Factory('', $c->getLogger(),
475
+                '\\OC\\Memcache\\ArrayCache',
476
+                '\\OC\\Memcache\\ArrayCache',
477
+                '\\OC\\Memcache\\ArrayCache'
478
+            );
479
+            $config = $c->getConfig();
480
+            $request = $c->getRequest();
481
+            $urlGenerator = new URLGenerator($config, $arrayCacheFactory, $request);
482
+
483
+            if ($config->getSystemValue('installed', false) && !(defined('PHPUNIT_RUN') && PHPUNIT_RUN)) {
484
+                $v = \OC_App::getAppVersions();
485
+                $v['core'] = implode(',', \OC_Util::getVersion());
486
+                $version = implode(',', $v);
487
+                $instanceId = \OC_Util::getInstanceId();
488
+                $path = \OC::$SERVERROOT;
489
+                $prefix = md5($instanceId . '-' . $version . '-' . $path . '-' . $urlGenerator->getBaseUrl());
490
+                return new \OC\Memcache\Factory($prefix, $c->getLogger(),
491
+                    $config->getSystemValue('memcache.local', null),
492
+                    $config->getSystemValue('memcache.distributed', null),
493
+                    $config->getSystemValue('memcache.locking', null)
494
+                );
495
+            }
496
+            return $arrayCacheFactory;
497
+
498
+        });
499
+        $this->registerAlias('MemCacheFactory', Factory::class);
500
+        $this->registerAlias(ICacheFactory::class, Factory::class);
501
+
502
+        $this->registerService('RedisFactory', function (Server $c) {
503
+            $systemConfig = $c->getSystemConfig();
504
+            return new RedisFactory($systemConfig);
505
+        });
506
+
507
+        $this->registerService(\OCP\Activity\IManager::class, function (Server $c) {
508
+            return new \OC\Activity\Manager(
509
+                $c->getRequest(),
510
+                $c->getUserSession(),
511
+                $c->getConfig(),
512
+                $c->query(IValidator::class)
513
+            );
514
+        });
515
+        $this->registerAlias('ActivityManager', \OCP\Activity\IManager::class);
516
+
517
+        $this->registerService(\OCP\Activity\IEventMerger::class, function (Server $c) {
518
+            return new \OC\Activity\EventMerger(
519
+                $c->getL10N('lib')
520
+            );
521
+        });
522
+        $this->registerAlias(IValidator::class, Validator::class);
523
+
524
+        $this->registerService(\OCP\IAvatarManager::class, function (Server $c) {
525
+            return new AvatarManager(
526
+                $c->getUserManager(),
527
+                $c->getAppDataDir('avatar'),
528
+                $c->getL10N('lib'),
529
+                $c->getLogger(),
530
+                $c->getConfig()
531
+            );
532
+        });
533
+        $this->registerAlias('AvatarManager', \OCP\IAvatarManager::class);
534
+
535
+        $this->registerAlias(\OCP\Support\CrashReport\IRegistry::class, \OC\Support\CrashReport\Registry::class);
536
+
537
+        $this->registerService(\OCP\ILogger::class, function (Server $c) {
538
+            $logType = $c->query('AllConfig')->getSystemValue('log_type', 'file');
539
+            $logger = Log::getLogClass($logType);
540
+            call_user_func(array($logger, 'init'));
541
+            $config = $this->getSystemConfig();
542
+            $registry = $c->query(\OCP\Support\CrashReport\IRegistry::class);
543
+
544
+            return new Log($logger, $config, null, $registry);
545
+        });
546
+        $this->registerAlias('Logger', \OCP\ILogger::class);
547
+
548
+        $this->registerService(\OCP\BackgroundJob\IJobList::class, function (Server $c) {
549
+            $config = $c->getConfig();
550
+            return new \OC\BackgroundJob\JobList(
551
+                $c->getDatabaseConnection(),
552
+                $config,
553
+                new TimeFactory()
554
+            );
555
+        });
556
+        $this->registerAlias('JobList', \OCP\BackgroundJob\IJobList::class);
557
+
558
+        $this->registerService(\OCP\Route\IRouter::class, function (Server $c) {
559
+            $cacheFactory = $c->getMemCacheFactory();
560
+            $logger = $c->getLogger();
561
+            if ($cacheFactory->isAvailableLowLatency()) {
562
+                $router = new \OC\Route\CachingRouter($cacheFactory->createLocal('route'), $logger);
563
+            } else {
564
+                $router = new \OC\Route\Router($logger);
565
+            }
566
+            return $router;
567
+        });
568
+        $this->registerAlias('Router', \OCP\Route\IRouter::class);
569
+
570
+        $this->registerService(\OCP\ISearch::class, function ($c) {
571
+            return new Search();
572
+        });
573
+        $this->registerAlias('Search', \OCP\ISearch::class);
574
+
575
+        $this->registerService(\OC\Security\RateLimiting\Limiter::class, function ($c) {
576
+            return new \OC\Security\RateLimiting\Limiter(
577
+                $this->getUserSession(),
578
+                $this->getRequest(),
579
+                new \OC\AppFramework\Utility\TimeFactory(),
580
+                $c->query(\OC\Security\RateLimiting\Backend\IBackend::class)
581
+            );
582
+        });
583
+        $this->registerService(\OC\Security\RateLimiting\Backend\IBackend::class, function ($c) {
584
+            return new \OC\Security\RateLimiting\Backend\MemoryCache(
585
+                $this->getMemCacheFactory(),
586
+                new \OC\AppFramework\Utility\TimeFactory()
587
+            );
588
+        });
589
+
590
+        $this->registerService(\OCP\Security\ISecureRandom::class, function ($c) {
591
+            return new SecureRandom();
592
+        });
593
+        $this->registerAlias('SecureRandom', \OCP\Security\ISecureRandom::class);
594
+
595
+        $this->registerService(\OCP\Security\ICrypto::class, function (Server $c) {
596
+            return new Crypto($c->getConfig(), $c->getSecureRandom());
597
+        });
598
+        $this->registerAlias('Crypto', \OCP\Security\ICrypto::class);
599
+
600
+        $this->registerService(\OCP\Security\IHasher::class, function (Server $c) {
601
+            return new Hasher($c->getConfig());
602
+        });
603
+        $this->registerAlias('Hasher', \OCP\Security\IHasher::class);
604
+
605
+        $this->registerService(\OCP\Security\ICredentialsManager::class, function (Server $c) {
606
+            return new CredentialsManager($c->getCrypto(), $c->getDatabaseConnection());
607
+        });
608
+        $this->registerAlias('CredentialsManager', \OCP\Security\ICredentialsManager::class);
609
+
610
+        $this->registerService(IDBConnection::class, function (Server $c) {
611
+            $systemConfig = $c->getSystemConfig();
612
+            $factory = new \OC\DB\ConnectionFactory($systemConfig);
613
+            $type = $systemConfig->getValue('dbtype', 'sqlite');
614
+            if (!$factory->isValidType($type)) {
615
+                throw new \OC\DatabaseException('Invalid database type');
616
+            }
617
+            $connectionParams = $factory->createConnectionParams();
618
+            $connection = $factory->getConnection($type, $connectionParams);
619
+            $connection->getConfiguration()->setSQLLogger($c->getQueryLogger());
620
+            return $connection;
621
+        });
622
+        $this->registerAlias('DatabaseConnection', IDBConnection::class);
623
+
624
+        $this->registerService('HTTPHelper', function (Server $c) {
625
+            $config = $c->getConfig();
626
+            return new HTTPHelper(
627
+                $config,
628
+                $c->getHTTPClientService()
629
+            );
630
+        });
631
+
632
+        $this->registerService(\OCP\Http\Client\IClientService::class, function (Server $c) {
633
+            $user = \OC_User::getUser();
634
+            $uid = $user ? $user : null;
635
+            return new ClientService(
636
+                $c->getConfig(),
637
+                new \OC\Security\CertificateManager(
638
+                    $uid,
639
+                    new View(),
640
+                    $c->getConfig(),
641
+                    $c->getLogger(),
642
+                    $c->getSecureRandom()
643
+                )
644
+            );
645
+        });
646
+        $this->registerAlias('HttpClientService', \OCP\Http\Client\IClientService::class);
647
+        $this->registerService(\OCP\Diagnostics\IEventLogger::class, function (Server $c) {
648
+            $eventLogger = new EventLogger();
649
+            if ($c->getSystemConfig()->getValue('debug', false)) {
650
+                // In debug mode, module is being activated by default
651
+                $eventLogger->activate();
652
+            }
653
+            return $eventLogger;
654
+        });
655
+        $this->registerAlias('EventLogger', \OCP\Diagnostics\IEventLogger::class);
656
+
657
+        $this->registerService(\OCP\Diagnostics\IQueryLogger::class, function (Server $c) {
658
+            $queryLogger = new QueryLogger();
659
+            if ($c->getSystemConfig()->getValue('debug', false)) {
660
+                // In debug mode, module is being activated by default
661
+                $queryLogger->activate();
662
+            }
663
+            return $queryLogger;
664
+        });
665
+        $this->registerAlias('QueryLogger', \OCP\Diagnostics\IQueryLogger::class);
666
+
667
+        $this->registerService(TempManager::class, function (Server $c) {
668
+            return new TempManager(
669
+                $c->getLogger(),
670
+                $c->getConfig()
671
+            );
672
+        });
673
+        $this->registerAlias('TempManager', TempManager::class);
674
+        $this->registerAlias(ITempManager::class, TempManager::class);
675
+
676
+        $this->registerService(AppManager::class, function (Server $c) {
677
+            return new \OC\App\AppManager(
678
+                $c->getUserSession(),
679
+                $c->getAppConfig(),
680
+                $c->getGroupManager(),
681
+                $c->getMemCacheFactory(),
682
+                $c->getEventDispatcher()
683
+            );
684
+        });
685
+        $this->registerAlias('AppManager', AppManager::class);
686
+        $this->registerAlias(IAppManager::class, AppManager::class);
687
+
688
+        $this->registerService(\OCP\IDateTimeZone::class, function (Server $c) {
689
+            return new DateTimeZone(
690
+                $c->getConfig(),
691
+                $c->getSession()
692
+            );
693
+        });
694
+        $this->registerAlias('DateTimeZone', \OCP\IDateTimeZone::class);
695
+
696
+        $this->registerService(\OCP\IDateTimeFormatter::class, function (Server $c) {
697
+            $language = $c->getConfig()->getUserValue($c->getSession()->get('user_id'), 'core', 'lang', null);
698
+
699
+            return new DateTimeFormatter(
700
+                $c->getDateTimeZone()->getTimeZone(),
701
+                $c->getL10N('lib', $language)
702
+            );
703
+        });
704
+        $this->registerAlias('DateTimeFormatter', \OCP\IDateTimeFormatter::class);
705
+
706
+        $this->registerService(\OCP\Files\Config\IUserMountCache::class, function (Server $c) {
707
+            $mountCache = new UserMountCache($c->getDatabaseConnection(), $c->getUserManager(), $c->getLogger());
708
+            $listener = new UserMountCacheListener($mountCache);
709
+            $listener->listen($c->getUserManager());
710
+            return $mountCache;
711
+        });
712
+        $this->registerAlias('UserMountCache', \OCP\Files\Config\IUserMountCache::class);
713
+
714
+        $this->registerService(\OCP\Files\Config\IMountProviderCollection::class, function (Server $c) {
715
+            $loader = \OC\Files\Filesystem::getLoader();
716
+            $mountCache = $c->query('UserMountCache');
717
+            $manager = new \OC\Files\Config\MountProviderCollection($loader, $mountCache);
718
+
719
+            // builtin providers
720
+
721
+            $config = $c->getConfig();
722
+            $manager->registerProvider(new CacheMountProvider($config));
723
+            $manager->registerHomeProvider(new LocalHomeMountProvider());
724
+            $manager->registerHomeProvider(new ObjectHomeMountProvider($config));
725
+
726
+            return $manager;
727
+        });
728
+        $this->registerAlias('MountConfigManager', \OCP\Files\Config\IMountProviderCollection::class);
729
+
730
+        $this->registerService('IniWrapper', function ($c) {
731
+            return new IniGetWrapper();
732
+        });
733
+        $this->registerService('AsyncCommandBus', function (Server $c) {
734
+            $busClass = $c->getConfig()->getSystemValue('commandbus');
735
+            if ($busClass) {
736
+                list($app, $class) = explode('::', $busClass, 2);
737
+                if ($c->getAppManager()->isInstalled($app)) {
738
+                    \OC_App::loadApp($app);
739
+                    return $c->query($class);
740
+                } else {
741
+                    throw new ServiceUnavailableException("The app providing the command bus ($app) is not enabled");
742
+                }
743
+            } else {
744
+                $jobList = $c->getJobList();
745
+                return new CronBus($jobList);
746
+            }
747
+        });
748
+        $this->registerService('TrustedDomainHelper', function ($c) {
749
+            return new TrustedDomainHelper($this->getConfig());
750
+        });
751
+        $this->registerService('Throttler', function (Server $c) {
752
+            return new Throttler(
753
+                $c->getDatabaseConnection(),
754
+                new TimeFactory(),
755
+                $c->getLogger(),
756
+                $c->getConfig()
757
+            );
758
+        });
759
+        $this->registerService('IntegrityCodeChecker', function (Server $c) {
760
+            // IConfig and IAppManager requires a working database. This code
761
+            // might however be called when ownCloud is not yet setup.
762
+            if (\OC::$server->getSystemConfig()->getValue('installed', false)) {
763
+                $config = $c->getConfig();
764
+                $appManager = $c->getAppManager();
765
+            } else {
766
+                $config = null;
767
+                $appManager = null;
768
+            }
769
+
770
+            return new Checker(
771
+                new EnvironmentHelper(),
772
+                new FileAccessHelper(),
773
+                new AppLocator(),
774
+                $config,
775
+                $c->getMemCacheFactory(),
776
+                $appManager,
777
+                $c->getTempManager()
778
+            );
779
+        });
780
+        $this->registerService(\OCP\IRequest::class, function ($c) {
781
+            if (isset($this['urlParams'])) {
782
+                $urlParams = $this['urlParams'];
783
+            } else {
784
+                $urlParams = [];
785
+            }
786
+
787
+            if (defined('PHPUNIT_RUN') && PHPUNIT_RUN
788
+                && in_array('fakeinput', stream_get_wrappers())
789
+            ) {
790
+                $stream = 'fakeinput://data';
791
+            } else {
792
+                $stream = 'php://input';
793
+            }
794
+
795
+            return new Request(
796
+                [
797
+                    'get' => $_GET,
798
+                    'post' => $_POST,
799
+                    'files' => $_FILES,
800
+                    'server' => $_SERVER,
801
+                    'env' => $_ENV,
802
+                    'cookies' => $_COOKIE,
803
+                    'method' => (isset($_SERVER) && isset($_SERVER['REQUEST_METHOD']))
804
+                        ? $_SERVER['REQUEST_METHOD']
805
+                        : null,
806
+                    'urlParams' => $urlParams,
807
+                ],
808
+                $this->getSecureRandom(),
809
+                $this->getConfig(),
810
+                $this->getCsrfTokenManager(),
811
+                $stream
812
+            );
813
+        });
814
+        $this->registerAlias('Request', \OCP\IRequest::class);
815
+
816
+        $this->registerService(\OCP\Mail\IMailer::class, function (Server $c) {
817
+            return new Mailer(
818
+                $c->getConfig(),
819
+                $c->getLogger(),
820
+                $c->query(Defaults::class),
821
+                $c->getURLGenerator(),
822
+                $c->getL10N('lib')
823
+            );
824
+        });
825
+        $this->registerAlias('Mailer', \OCP\Mail\IMailer::class);
826
+
827
+        $this->registerService('LDAPProvider', function (Server $c) {
828
+            $config = $c->getConfig();
829
+            $factoryClass = $config->getSystemValue('ldapProviderFactory', null);
830
+            if (is_null($factoryClass)) {
831
+                throw new \Exception('ldapProviderFactory not set');
832
+            }
833
+            /** @var \OCP\LDAP\ILDAPProviderFactory $factory */
834
+            $factory = new $factoryClass($this);
835
+            return $factory->getLDAPProvider();
836
+        });
837
+        $this->registerService(ILockingProvider::class, function (Server $c) {
838
+            $ini = $c->getIniWrapper();
839
+            $config = $c->getConfig();
840
+            $ttl = $config->getSystemValue('filelocking.ttl', max(3600, $ini->getNumeric('max_execution_time')));
841
+            if ($config->getSystemValue('filelocking.enabled', true) or (defined('PHPUNIT_RUN') && PHPUNIT_RUN)) {
842
+                /** @var \OC\Memcache\Factory $memcacheFactory */
843
+                $memcacheFactory = $c->getMemCacheFactory();
844
+                $memcache = $memcacheFactory->createLocking('lock');
845
+                if (!($memcache instanceof \OC\Memcache\NullCache)) {
846
+                    return new MemcacheLockingProvider($memcache, $ttl);
847
+                }
848
+                return new DBLockingProvider($c->getDatabaseConnection(), $c->getLogger(), new TimeFactory(), $ttl);
849
+            }
850
+            return new NoopLockingProvider();
851
+        });
852
+        $this->registerAlias('LockingProvider', ILockingProvider::class);
853
+
854
+        $this->registerService(\OCP\Files\Mount\IMountManager::class, function () {
855
+            return new \OC\Files\Mount\Manager();
856
+        });
857
+        $this->registerAlias('MountManager', \OCP\Files\Mount\IMountManager::class);
858
+
859
+        $this->registerService(\OCP\Files\IMimeTypeDetector::class, function (Server $c) {
860
+            return new \OC\Files\Type\Detection(
861
+                $c->getURLGenerator(),
862
+                \OC::$configDir,
863
+                \OC::$SERVERROOT . '/resources/config/'
864
+            );
865
+        });
866
+        $this->registerAlias('MimeTypeDetector', \OCP\Files\IMimeTypeDetector::class);
867
+
868
+        $this->registerService(\OCP\Files\IMimeTypeLoader::class, function (Server $c) {
869
+            return new \OC\Files\Type\Loader(
870
+                $c->getDatabaseConnection()
871
+            );
872
+        });
873
+        $this->registerAlias('MimeTypeLoader', \OCP\Files\IMimeTypeLoader::class);
874
+        $this->registerService(BundleFetcher::class, function () {
875
+            return new BundleFetcher($this->getL10N('lib'));
876
+        });
877
+        $this->registerService(\OCP\Notification\IManager::class, function (Server $c) {
878
+            return new Manager(
879
+                $c->query(IValidator::class)
880
+            );
881
+        });
882
+        $this->registerAlias('NotificationManager', \OCP\Notification\IManager::class);
883
+
884
+        $this->registerService(\OC\CapabilitiesManager::class, function (Server $c) {
885
+            $manager = new \OC\CapabilitiesManager($c->getLogger());
886
+            $manager->registerCapability(function () use ($c) {
887
+                return new \OC\OCS\CoreCapabilities($c->getConfig());
888
+            });
889
+            $manager->registerCapability(function () use ($c) {
890
+                return $c->query(\OC\Security\Bruteforce\Capabilities::class);
891
+            });
892
+            return $manager;
893
+        });
894
+        $this->registerAlias('CapabilitiesManager', \OC\CapabilitiesManager::class);
895
+
896
+        $this->registerService(\OCP\Comments\ICommentsManager::class, function (Server $c) {
897
+            $config = $c->getConfig();
898
+            $factoryClass = $config->getSystemValue('comments.managerFactory', '\OC\Comments\ManagerFactory');
899
+            /** @var \OCP\Comments\ICommentsManagerFactory $factory */
900
+            $factory = new $factoryClass($this);
901
+            $manager = $factory->getManager();
902
+
903
+            $manager->registerDisplayNameResolver('user', function($id) use ($c) {
904
+                $manager = $c->getUserManager();
905
+                $user = $manager->get($id);
906
+                if(is_null($user)) {
907
+                    $l = $c->getL10N('core');
908
+                    $displayName = $l->t('Unknown user');
909
+                } else {
910
+                    $displayName = $user->getDisplayName();
911
+                }
912
+                return $displayName;
913
+            });
914
+
915
+            return $manager;
916
+        });
917
+        $this->registerAlias('CommentsManager', \OCP\Comments\ICommentsManager::class);
918
+
919
+        $this->registerService('ThemingDefaults', function (Server $c) {
920
+            /*
921 921
 			 * Dark magic for autoloader.
922 922
 			 * If we do a class_exists it will try to load the class which will
923 923
 			 * make composer cache the result. Resulting in errors when enabling
924 924
 			 * the theming app.
925 925
 			 */
926
-			$prefixes = \OC::$composerAutoloader->getPrefixesPsr4();
927
-			if (isset($prefixes['OCA\\Theming\\'])) {
928
-				$classExists = true;
929
-			} else {
930
-				$classExists = false;
931
-			}
932
-
933
-			if ($classExists && $c->getConfig()->getSystemValue('installed', false) && $c->getAppManager()->isInstalled('theming') && $c->getTrustedDomainHelper()->isTrustedDomain($c->getRequest()->getInsecureServerHost())) {
934
-				return new ThemingDefaults(
935
-					$c->getConfig(),
936
-					$c->getL10N('theming'),
937
-					$c->getURLGenerator(),
938
-					$c->getAppDataDir('theming'),
939
-					$c->getMemCacheFactory(),
940
-					new Util($c->getConfig(), $this->getAppManager(), $this->getAppDataDir('theming')),
941
-					$this->getAppManager()
942
-				);
943
-			}
944
-			return new \OC_Defaults();
945
-		});
946
-		$this->registerService(SCSSCacher::class, function (Server $c) {
947
-			/** @var Factory $cacheFactory */
948
-			$cacheFactory = $c->query(Factory::class);
949
-			return new SCSSCacher(
950
-				$c->getLogger(),
951
-				$c->query(\OC\Files\AppData\Factory::class),
952
-				$c->getURLGenerator(),
953
-				$c->getConfig(),
954
-				$c->getThemingDefaults(),
955
-				\OC::$SERVERROOT,
956
-				$cacheFactory->createDistributed('SCSS')
957
-			);
958
-		});
959
-		$this->registerService(EventDispatcher::class, function () {
960
-			return new EventDispatcher();
961
-		});
962
-		$this->registerAlias('EventDispatcher', EventDispatcher::class);
963
-		$this->registerAlias(EventDispatcherInterface::class, EventDispatcher::class);
964
-
965
-		$this->registerService('CryptoWrapper', function (Server $c) {
966
-			// FIXME: Instantiiated here due to cyclic dependency
967
-			$request = new Request(
968
-				[
969
-					'get' => $_GET,
970
-					'post' => $_POST,
971
-					'files' => $_FILES,
972
-					'server' => $_SERVER,
973
-					'env' => $_ENV,
974
-					'cookies' => $_COOKIE,
975
-					'method' => (isset($_SERVER) && isset($_SERVER['REQUEST_METHOD']))
976
-						? $_SERVER['REQUEST_METHOD']
977
-						: null,
978
-				],
979
-				$c->getSecureRandom(),
980
-				$c->getConfig()
981
-			);
982
-
983
-			return new CryptoWrapper(
984
-				$c->getConfig(),
985
-				$c->getCrypto(),
986
-				$c->getSecureRandom(),
987
-				$request
988
-			);
989
-		});
990
-		$this->registerService('CsrfTokenManager', function (Server $c) {
991
-			$tokenGenerator = new CsrfTokenGenerator($c->getSecureRandom());
992
-
993
-			return new CsrfTokenManager(
994
-				$tokenGenerator,
995
-				$c->query(SessionStorage::class)
996
-			);
997
-		});
998
-		$this->registerService(SessionStorage::class, function (Server $c) {
999
-			return new SessionStorage($c->getSession());
1000
-		});
1001
-		$this->registerService(\OCP\Security\IContentSecurityPolicyManager::class, function (Server $c) {
1002
-			return new ContentSecurityPolicyManager();
1003
-		});
1004
-		$this->registerAlias('ContentSecurityPolicyManager', \OCP\Security\IContentSecurityPolicyManager::class);
1005
-
1006
-		$this->registerService('ContentSecurityPolicyNonceManager', function (Server $c) {
1007
-			return new ContentSecurityPolicyNonceManager(
1008
-				$c->getCsrfTokenManager(),
1009
-				$c->getRequest()
1010
-			);
1011
-		});
1012
-
1013
-		$this->registerService(\OCP\Share\IManager::class, function (Server $c) {
1014
-			$config = $c->getConfig();
1015
-			$factoryClass = $config->getSystemValue('sharing.managerFactory', '\OC\Share20\ProviderFactory');
1016
-			/** @var \OCP\Share\IProviderFactory $factory */
1017
-			$factory = new $factoryClass($this);
1018
-
1019
-			$manager = new \OC\Share20\Manager(
1020
-				$c->getLogger(),
1021
-				$c->getConfig(),
1022
-				$c->getSecureRandom(),
1023
-				$c->getHasher(),
1024
-				$c->getMountManager(),
1025
-				$c->getGroupManager(),
1026
-				$c->getL10N('lib'),
1027
-				$c->getL10NFactory(),
1028
-				$factory,
1029
-				$c->getUserManager(),
1030
-				$c->getLazyRootFolder(),
1031
-				$c->getEventDispatcher(),
1032
-				$c->getMailer(),
1033
-				$c->getURLGenerator(),
1034
-				$c->getThemingDefaults()
1035
-			);
1036
-
1037
-			return $manager;
1038
-		});
1039
-		$this->registerAlias('ShareManager', \OCP\Share\IManager::class);
1040
-
1041
-		$this->registerService(\OCP\Collaboration\Collaborators\ISearch::class, function(Server $c) {
1042
-			$instance = new Collaboration\Collaborators\Search($c);
1043
-
1044
-			// register default plugins
1045
-			$instance->registerPlugin(['shareType' => 'SHARE_TYPE_USER', 'class' => UserPlugin::class]);
1046
-			$instance->registerPlugin(['shareType' => 'SHARE_TYPE_GROUP', 'class' => GroupPlugin::class]);
1047
-			$instance->registerPlugin(['shareType' => 'SHARE_TYPE_EMAIL', 'class' => MailPlugin::class]);
1048
-			$instance->registerPlugin(['shareType' => 'SHARE_TYPE_REMOTE', 'class' => RemotePlugin::class]);
1049
-
1050
-			return $instance;
1051
-		});
1052
-		$this->registerAlias('CollaboratorSearch', \OCP\Collaboration\Collaborators\ISearch::class);
1053
-
1054
-		$this->registerAlias(\OCP\Collaboration\AutoComplete\IManager::class, \OC\Collaboration\AutoComplete\Manager::class);
1055
-
1056
-		$this->registerService('SettingsManager', function (Server $c) {
1057
-			$manager = new \OC\Settings\Manager(
1058
-				$c->getLogger(),
1059
-				$c->getDatabaseConnection(),
1060
-				$c->getL10N('lib'),
1061
-				$c->getConfig(),
1062
-				$c->getEncryptionManager(),
1063
-				$c->getUserManager(),
1064
-				$c->getLockingProvider(),
1065
-				$c->getRequest(),
1066
-				new \OC\Settings\Mapper($c->getDatabaseConnection()),
1067
-				$c->getURLGenerator(),
1068
-				$c->query(AccountManager::class),
1069
-				$c->getGroupManager(),
1070
-				$c->getL10NFactory(),
1071
-				$c->getThemingDefaults(),
1072
-				$c->getAppManager()
1073
-			);
1074
-			return $manager;
1075
-		});
1076
-		$this->registerService(\OC\Files\AppData\Factory::class, function (Server $c) {
1077
-			return new \OC\Files\AppData\Factory(
1078
-				$c->getRootFolder(),
1079
-				$c->getSystemConfig()
1080
-			);
1081
-		});
1082
-
1083
-		$this->registerService('LockdownManager', function (Server $c) {
1084
-			return new LockdownManager(function () use ($c) {
1085
-				return $c->getSession();
1086
-			});
1087
-		});
1088
-
1089
-		$this->registerService(\OCP\OCS\IDiscoveryService::class, function (Server $c) {
1090
-			return new DiscoveryService($c->getMemCacheFactory(), $c->getHTTPClientService());
1091
-		});
1092
-
1093
-		$this->registerService(ICloudIdManager::class, function (Server $c) {
1094
-			return new CloudIdManager();
1095
-		});
1096
-
1097
-		$this->registerAlias(\OCP\AppFramework\Utility\IControllerMethodReflector::class, \OC\AppFramework\Utility\ControllerMethodReflector::class);
1098
-		$this->registerAlias('ControllerMethodReflector', \OCP\AppFramework\Utility\IControllerMethodReflector::class);
1099
-
1100
-		$this->registerAlias(\OCP\AppFramework\Utility\ITimeFactory::class, \OC\AppFramework\Utility\TimeFactory::class);
1101
-		$this->registerAlias('TimeFactory', \OCP\AppFramework\Utility\ITimeFactory::class);
1102
-
1103
-		$this->registerService(Defaults::class, function (Server $c) {
1104
-			return new Defaults(
1105
-				$c->getThemingDefaults()
1106
-			);
1107
-		});
1108
-		$this->registerAlias('Defaults', \OCP\Defaults::class);
1109
-
1110
-		$this->registerService(\OCP\ISession::class, function (SimpleContainer $c) {
1111
-			return $c->query(\OCP\IUserSession::class)->getSession();
1112
-		});
1113
-
1114
-		$this->registerService(IShareHelper::class, function (Server $c) {
1115
-			return new ShareHelper(
1116
-				$c->query(\OCP\Share\IManager::class)
1117
-			);
1118
-		});
1119
-
1120
-		$this->registerService(Installer::class, function(Server $c) {
1121
-			return new Installer(
1122
-				$c->getAppFetcher(),
1123
-				$c->getHTTPClientService(),
1124
-				$c->getTempManager(),
1125
-				$c->getLogger(),
1126
-				$c->getConfig()
1127
-			);
1128
-		});
1129
-
1130
-		$this->registerService(IApiFactory::class, function(Server $c) {
1131
-			return new ApiFactory($c->getHTTPClientService());
1132
-		});
1133
-
1134
-		$this->registerService(IInstanceFactory::class, function(Server $c) {
1135
-			$memcacheFactory = $c->getMemCacheFactory();
1136
-			return new InstanceFactory($memcacheFactory->createLocal('remoteinstance.'), $c->getHTTPClientService());
1137
-		});
1138
-
1139
-		$this->registerService(IContactsStore::class, function(Server $c) {
1140
-			return new ContactsStore(
1141
-				$c->getContactsManager(),
1142
-				$c->getConfig(),
1143
-				$c->getUserManager(),
1144
-				$c->getGroupManager()
1145
-			);
1146
-		});
1147
-		$this->registerAlias(IContactsStore::class, ContactsStore::class);
1148
-
1149
-		$this->connectDispatcher();
1150
-	}
1151
-
1152
-	/**
1153
-	 * @return \OCP\Calendar\IManager
1154
-	 */
1155
-	public function getCalendarManager() {
1156
-		return $this->query('CalendarManager');
1157
-	}
1158
-
1159
-	private function connectDispatcher() {
1160
-		$dispatcher = $this->getEventDispatcher();
1161
-
1162
-		// Delete avatar on user deletion
1163
-		$dispatcher->addListener('OCP\IUser::preDelete', function(GenericEvent $e) {
1164
-			$logger = $this->getLogger();
1165
-			$manager = $this->getAvatarManager();
1166
-			/** @var IUser $user */
1167
-			$user = $e->getSubject();
1168
-
1169
-			try {
1170
-				$avatar = $manager->getAvatar($user->getUID());
1171
-				$avatar->remove();
1172
-			} catch (NotFoundException $e) {
1173
-				// no avatar to remove
1174
-			} catch (\Exception $e) {
1175
-				// Ignore exceptions
1176
-				$logger->info('Could not cleanup avatar of ' . $user->getUID());
1177
-			}
1178
-		});
1179
-
1180
-		$dispatcher->addListener('OCP\IUser::changeUser', function (GenericEvent $e) {
1181
-			$manager = $this->getAvatarManager();
1182
-			/** @var IUser $user */
1183
-			$user = $e->getSubject();
1184
-			$feature = $e->getArgument('feature');
1185
-			$oldValue = $e->getArgument('oldValue');
1186
-			$value = $e->getArgument('value');
1187
-
1188
-			try {
1189
-				$avatar = $manager->getAvatar($user->getUID());
1190
-				$avatar->userChanged($feature, $oldValue, $value);
1191
-			} catch (NotFoundException $e) {
1192
-				// no avatar to remove
1193
-			}
1194
-		});
1195
-	}
1196
-
1197
-	/**
1198
-	 * @return \OCP\Contacts\IManager
1199
-	 */
1200
-	public function getContactsManager() {
1201
-		return $this->query('ContactsManager');
1202
-	}
1203
-
1204
-	/**
1205
-	 * @return \OC\Encryption\Manager
1206
-	 */
1207
-	public function getEncryptionManager() {
1208
-		return $this->query('EncryptionManager');
1209
-	}
1210
-
1211
-	/**
1212
-	 * @return \OC\Encryption\File
1213
-	 */
1214
-	public function getEncryptionFilesHelper() {
1215
-		return $this->query('EncryptionFileHelper');
1216
-	}
1217
-
1218
-	/**
1219
-	 * @return \OCP\Encryption\Keys\IStorage
1220
-	 */
1221
-	public function getEncryptionKeyStorage() {
1222
-		return $this->query('EncryptionKeyStorage');
1223
-	}
1224
-
1225
-	/**
1226
-	 * The current request object holding all information about the request
1227
-	 * currently being processed is returned from this method.
1228
-	 * In case the current execution was not initiated by a web request null is returned
1229
-	 *
1230
-	 * @return \OCP\IRequest
1231
-	 */
1232
-	public function getRequest() {
1233
-		return $this->query('Request');
1234
-	}
1235
-
1236
-	/**
1237
-	 * Returns the preview manager which can create preview images for a given file
1238
-	 *
1239
-	 * @return \OCP\IPreview
1240
-	 */
1241
-	public function getPreviewManager() {
1242
-		return $this->query('PreviewManager');
1243
-	}
1244
-
1245
-	/**
1246
-	 * Returns the tag manager which can get and set tags for different object types
1247
-	 *
1248
-	 * @see \OCP\ITagManager::load()
1249
-	 * @return \OCP\ITagManager
1250
-	 */
1251
-	public function getTagManager() {
1252
-		return $this->query('TagManager');
1253
-	}
1254
-
1255
-	/**
1256
-	 * Returns the system-tag manager
1257
-	 *
1258
-	 * @return \OCP\SystemTag\ISystemTagManager
1259
-	 *
1260
-	 * @since 9.0.0
1261
-	 */
1262
-	public function getSystemTagManager() {
1263
-		return $this->query('SystemTagManager');
1264
-	}
1265
-
1266
-	/**
1267
-	 * Returns the system-tag object mapper
1268
-	 *
1269
-	 * @return \OCP\SystemTag\ISystemTagObjectMapper
1270
-	 *
1271
-	 * @since 9.0.0
1272
-	 */
1273
-	public function getSystemTagObjectMapper() {
1274
-		return $this->query('SystemTagObjectMapper');
1275
-	}
1276
-
1277
-	/**
1278
-	 * Returns the avatar manager, used for avatar functionality
1279
-	 *
1280
-	 * @return \OCP\IAvatarManager
1281
-	 */
1282
-	public function getAvatarManager() {
1283
-		return $this->query('AvatarManager');
1284
-	}
1285
-
1286
-	/**
1287
-	 * Returns the root folder of ownCloud's data directory
1288
-	 *
1289
-	 * @return \OCP\Files\IRootFolder
1290
-	 */
1291
-	public function getRootFolder() {
1292
-		return $this->query('LazyRootFolder');
1293
-	}
1294
-
1295
-	/**
1296
-	 * Returns the root folder of ownCloud's data directory
1297
-	 * This is the lazy variant so this gets only initialized once it
1298
-	 * is actually used.
1299
-	 *
1300
-	 * @return \OCP\Files\IRootFolder
1301
-	 */
1302
-	public function getLazyRootFolder() {
1303
-		return $this->query('LazyRootFolder');
1304
-	}
1305
-
1306
-	/**
1307
-	 * Returns a view to ownCloud's files folder
1308
-	 *
1309
-	 * @param string $userId user ID
1310
-	 * @return \OCP\Files\Folder|null
1311
-	 */
1312
-	public function getUserFolder($userId = null) {
1313
-		if ($userId === null) {
1314
-			$user = $this->getUserSession()->getUser();
1315
-			if (!$user) {
1316
-				return null;
1317
-			}
1318
-			$userId = $user->getUID();
1319
-		}
1320
-		$root = $this->getRootFolder();
1321
-		return $root->getUserFolder($userId);
1322
-	}
1323
-
1324
-	/**
1325
-	 * Returns an app-specific view in ownClouds data directory
1326
-	 *
1327
-	 * @return \OCP\Files\Folder
1328
-	 * @deprecated since 9.2.0 use IAppData
1329
-	 */
1330
-	public function getAppFolder() {
1331
-		$dir = '/' . \OC_App::getCurrentApp();
1332
-		$root = $this->getRootFolder();
1333
-		if (!$root->nodeExists($dir)) {
1334
-			$folder = $root->newFolder($dir);
1335
-		} else {
1336
-			$folder = $root->get($dir);
1337
-		}
1338
-		return $folder;
1339
-	}
1340
-
1341
-	/**
1342
-	 * @return \OC\User\Manager
1343
-	 */
1344
-	public function getUserManager() {
1345
-		return $this->query('UserManager');
1346
-	}
1347
-
1348
-	/**
1349
-	 * @return \OC\Group\Manager
1350
-	 */
1351
-	public function getGroupManager() {
1352
-		return $this->query('GroupManager');
1353
-	}
1354
-
1355
-	/**
1356
-	 * @return \OC\User\Session
1357
-	 */
1358
-	public function getUserSession() {
1359
-		return $this->query('UserSession');
1360
-	}
1361
-
1362
-	/**
1363
-	 * @return \OCP\ISession
1364
-	 */
1365
-	public function getSession() {
1366
-		return $this->query('UserSession')->getSession();
1367
-	}
1368
-
1369
-	/**
1370
-	 * @param \OCP\ISession $session
1371
-	 */
1372
-	public function setSession(\OCP\ISession $session) {
1373
-		$this->query(SessionStorage::class)->setSession($session);
1374
-		$this->query('UserSession')->setSession($session);
1375
-		$this->query(Store::class)->setSession($session);
1376
-	}
1377
-
1378
-	/**
1379
-	 * @return \OC\Authentication\TwoFactorAuth\Manager
1380
-	 */
1381
-	public function getTwoFactorAuthManager() {
1382
-		return $this->query('\OC\Authentication\TwoFactorAuth\Manager');
1383
-	}
1384
-
1385
-	/**
1386
-	 * @return \OC\NavigationManager
1387
-	 */
1388
-	public function getNavigationManager() {
1389
-		return $this->query('NavigationManager');
1390
-	}
1391
-
1392
-	/**
1393
-	 * @return \OCP\IConfig
1394
-	 */
1395
-	public function getConfig() {
1396
-		return $this->query('AllConfig');
1397
-	}
1398
-
1399
-	/**
1400
-	 * @return \OC\SystemConfig
1401
-	 */
1402
-	public function getSystemConfig() {
1403
-		return $this->query('SystemConfig');
1404
-	}
1405
-
1406
-	/**
1407
-	 * Returns the app config manager
1408
-	 *
1409
-	 * @return \OCP\IAppConfig
1410
-	 */
1411
-	public function getAppConfig() {
1412
-		return $this->query('AppConfig');
1413
-	}
1414
-
1415
-	/**
1416
-	 * @return \OCP\L10N\IFactory
1417
-	 */
1418
-	public function getL10NFactory() {
1419
-		return $this->query('L10NFactory');
1420
-	}
1421
-
1422
-	/**
1423
-	 * get an L10N instance
1424
-	 *
1425
-	 * @param string $app appid
1426
-	 * @param string $lang
1427
-	 * @return IL10N
1428
-	 */
1429
-	public function getL10N($app, $lang = null) {
1430
-		return $this->getL10NFactory()->get($app, $lang);
1431
-	}
1432
-
1433
-	/**
1434
-	 * @return \OCP\IURLGenerator
1435
-	 */
1436
-	public function getURLGenerator() {
1437
-		return $this->query('URLGenerator');
1438
-	}
1439
-
1440
-	/**
1441
-	 * @return \OCP\IHelper
1442
-	 */
1443
-	public function getHelper() {
1444
-		return $this->query('AppHelper');
1445
-	}
1446
-
1447
-	/**
1448
-	 * @return AppFetcher
1449
-	 */
1450
-	public function getAppFetcher() {
1451
-		return $this->query(AppFetcher::class);
1452
-	}
1453
-
1454
-	/**
1455
-	 * Returns an ICache instance. Since 8.1.0 it returns a fake cache. Use
1456
-	 * getMemCacheFactory() instead.
1457
-	 *
1458
-	 * @return \OCP\ICache
1459
-	 * @deprecated 8.1.0 use getMemCacheFactory to obtain a proper cache
1460
-	 */
1461
-	public function getCache() {
1462
-		return $this->query('UserCache');
1463
-	}
1464
-
1465
-	/**
1466
-	 * Returns an \OCP\CacheFactory instance
1467
-	 *
1468
-	 * @return \OCP\ICacheFactory
1469
-	 */
1470
-	public function getMemCacheFactory() {
1471
-		return $this->query('MemCacheFactory');
1472
-	}
1473
-
1474
-	/**
1475
-	 * Returns an \OC\RedisFactory instance
1476
-	 *
1477
-	 * @return \OC\RedisFactory
1478
-	 */
1479
-	public function getGetRedisFactory() {
1480
-		return $this->query('RedisFactory');
1481
-	}
1482
-
1483
-
1484
-	/**
1485
-	 * Returns the current session
1486
-	 *
1487
-	 * @return \OCP\IDBConnection
1488
-	 */
1489
-	public function getDatabaseConnection() {
1490
-		return $this->query('DatabaseConnection');
1491
-	}
1492
-
1493
-	/**
1494
-	 * Returns the activity manager
1495
-	 *
1496
-	 * @return \OCP\Activity\IManager
1497
-	 */
1498
-	public function getActivityManager() {
1499
-		return $this->query('ActivityManager');
1500
-	}
1501
-
1502
-	/**
1503
-	 * Returns an job list for controlling background jobs
1504
-	 *
1505
-	 * @return \OCP\BackgroundJob\IJobList
1506
-	 */
1507
-	public function getJobList() {
1508
-		return $this->query('JobList');
1509
-	}
1510
-
1511
-	/**
1512
-	 * Returns a logger instance
1513
-	 *
1514
-	 * @return \OCP\ILogger
1515
-	 */
1516
-	public function getLogger() {
1517
-		return $this->query('Logger');
1518
-	}
1519
-
1520
-	/**
1521
-	 * Returns a router for generating and matching urls
1522
-	 *
1523
-	 * @return \OCP\Route\IRouter
1524
-	 */
1525
-	public function getRouter() {
1526
-		return $this->query('Router');
1527
-	}
1528
-
1529
-	/**
1530
-	 * Returns a search instance
1531
-	 *
1532
-	 * @return \OCP\ISearch
1533
-	 */
1534
-	public function getSearch() {
1535
-		return $this->query('Search');
1536
-	}
1537
-
1538
-	/**
1539
-	 * Returns a SecureRandom instance
1540
-	 *
1541
-	 * @return \OCP\Security\ISecureRandom
1542
-	 */
1543
-	public function getSecureRandom() {
1544
-		return $this->query('SecureRandom');
1545
-	}
1546
-
1547
-	/**
1548
-	 * Returns a Crypto instance
1549
-	 *
1550
-	 * @return \OCP\Security\ICrypto
1551
-	 */
1552
-	public function getCrypto() {
1553
-		return $this->query('Crypto');
1554
-	}
1555
-
1556
-	/**
1557
-	 * Returns a Hasher instance
1558
-	 *
1559
-	 * @return \OCP\Security\IHasher
1560
-	 */
1561
-	public function getHasher() {
1562
-		return $this->query('Hasher');
1563
-	}
1564
-
1565
-	/**
1566
-	 * Returns a CredentialsManager instance
1567
-	 *
1568
-	 * @return \OCP\Security\ICredentialsManager
1569
-	 */
1570
-	public function getCredentialsManager() {
1571
-		return $this->query('CredentialsManager');
1572
-	}
1573
-
1574
-	/**
1575
-	 * Returns an instance of the HTTP helper class
1576
-	 *
1577
-	 * @deprecated Use getHTTPClientService()
1578
-	 * @return \OC\HTTPHelper
1579
-	 */
1580
-	public function getHTTPHelper() {
1581
-		return $this->query('HTTPHelper');
1582
-	}
1583
-
1584
-	/**
1585
-	 * Get the certificate manager for the user
1586
-	 *
1587
-	 * @param string $userId (optional) if not specified the current loggedin user is used, use null to get the system certificate manager
1588
-	 * @return \OCP\ICertificateManager | null if $uid is null and no user is logged in
1589
-	 */
1590
-	public function getCertificateManager($userId = '') {
1591
-		if ($userId === '') {
1592
-			$userSession = $this->getUserSession();
1593
-			$user = $userSession->getUser();
1594
-			if (is_null($user)) {
1595
-				return null;
1596
-			}
1597
-			$userId = $user->getUID();
1598
-		}
1599
-		return new CertificateManager(
1600
-			$userId,
1601
-			new View(),
1602
-			$this->getConfig(),
1603
-			$this->getLogger(),
1604
-			$this->getSecureRandom()
1605
-		);
1606
-	}
1607
-
1608
-	/**
1609
-	 * Returns an instance of the HTTP client service
1610
-	 *
1611
-	 * @return \OCP\Http\Client\IClientService
1612
-	 */
1613
-	public function getHTTPClientService() {
1614
-		return $this->query('HttpClientService');
1615
-	}
1616
-
1617
-	/**
1618
-	 * Create a new event source
1619
-	 *
1620
-	 * @return \OCP\IEventSource
1621
-	 */
1622
-	public function createEventSource() {
1623
-		return new \OC_EventSource();
1624
-	}
1625
-
1626
-	/**
1627
-	 * Get the active event logger
1628
-	 *
1629
-	 * The returned logger only logs data when debug mode is enabled
1630
-	 *
1631
-	 * @return \OCP\Diagnostics\IEventLogger
1632
-	 */
1633
-	public function getEventLogger() {
1634
-		return $this->query('EventLogger');
1635
-	}
1636
-
1637
-	/**
1638
-	 * Get the active query logger
1639
-	 *
1640
-	 * The returned logger only logs data when debug mode is enabled
1641
-	 *
1642
-	 * @return \OCP\Diagnostics\IQueryLogger
1643
-	 */
1644
-	public function getQueryLogger() {
1645
-		return $this->query('QueryLogger');
1646
-	}
1647
-
1648
-	/**
1649
-	 * Get the manager for temporary files and folders
1650
-	 *
1651
-	 * @return \OCP\ITempManager
1652
-	 */
1653
-	public function getTempManager() {
1654
-		return $this->query('TempManager');
1655
-	}
1656
-
1657
-	/**
1658
-	 * Get the app manager
1659
-	 *
1660
-	 * @return \OCP\App\IAppManager
1661
-	 */
1662
-	public function getAppManager() {
1663
-		return $this->query('AppManager');
1664
-	}
1665
-
1666
-	/**
1667
-	 * Creates a new mailer
1668
-	 *
1669
-	 * @return \OCP\Mail\IMailer
1670
-	 */
1671
-	public function getMailer() {
1672
-		return $this->query('Mailer');
1673
-	}
1674
-
1675
-	/**
1676
-	 * Get the webroot
1677
-	 *
1678
-	 * @return string
1679
-	 */
1680
-	public function getWebRoot() {
1681
-		return $this->webRoot;
1682
-	}
1683
-
1684
-	/**
1685
-	 * @return \OC\OCSClient
1686
-	 */
1687
-	public function getOcsClient() {
1688
-		return $this->query('OcsClient');
1689
-	}
1690
-
1691
-	/**
1692
-	 * @return \OCP\IDateTimeZone
1693
-	 */
1694
-	public function getDateTimeZone() {
1695
-		return $this->query('DateTimeZone');
1696
-	}
1697
-
1698
-	/**
1699
-	 * @return \OCP\IDateTimeFormatter
1700
-	 */
1701
-	public function getDateTimeFormatter() {
1702
-		return $this->query('DateTimeFormatter');
1703
-	}
1704
-
1705
-	/**
1706
-	 * @return \OCP\Files\Config\IMountProviderCollection
1707
-	 */
1708
-	public function getMountProviderCollection() {
1709
-		return $this->query('MountConfigManager');
1710
-	}
1711
-
1712
-	/**
1713
-	 * Get the IniWrapper
1714
-	 *
1715
-	 * @return IniGetWrapper
1716
-	 */
1717
-	public function getIniWrapper() {
1718
-		return $this->query('IniWrapper');
1719
-	}
1720
-
1721
-	/**
1722
-	 * @return \OCP\Command\IBus
1723
-	 */
1724
-	public function getCommandBus() {
1725
-		return $this->query('AsyncCommandBus');
1726
-	}
1727
-
1728
-	/**
1729
-	 * Get the trusted domain helper
1730
-	 *
1731
-	 * @return TrustedDomainHelper
1732
-	 */
1733
-	public function getTrustedDomainHelper() {
1734
-		return $this->query('TrustedDomainHelper');
1735
-	}
1736
-
1737
-	/**
1738
-	 * Get the locking provider
1739
-	 *
1740
-	 * @return \OCP\Lock\ILockingProvider
1741
-	 * @since 8.1.0
1742
-	 */
1743
-	public function getLockingProvider() {
1744
-		return $this->query('LockingProvider');
1745
-	}
1746
-
1747
-	/**
1748
-	 * @return \OCP\Files\Mount\IMountManager
1749
-	 **/
1750
-	function getMountManager() {
1751
-		return $this->query('MountManager');
1752
-	}
1753
-
1754
-	/** @return \OCP\Files\Config\IUserMountCache */
1755
-	function getUserMountCache() {
1756
-		return $this->query('UserMountCache');
1757
-	}
1758
-
1759
-	/**
1760
-	 * Get the MimeTypeDetector
1761
-	 *
1762
-	 * @return \OCP\Files\IMimeTypeDetector
1763
-	 */
1764
-	public function getMimeTypeDetector() {
1765
-		return $this->query('MimeTypeDetector');
1766
-	}
1767
-
1768
-	/**
1769
-	 * Get the MimeTypeLoader
1770
-	 *
1771
-	 * @return \OCP\Files\IMimeTypeLoader
1772
-	 */
1773
-	public function getMimeTypeLoader() {
1774
-		return $this->query('MimeTypeLoader');
1775
-	}
1776
-
1777
-	/**
1778
-	 * Get the manager of all the capabilities
1779
-	 *
1780
-	 * @return \OC\CapabilitiesManager
1781
-	 */
1782
-	public function getCapabilitiesManager() {
1783
-		return $this->query('CapabilitiesManager');
1784
-	}
1785
-
1786
-	/**
1787
-	 * Get the EventDispatcher
1788
-	 *
1789
-	 * @return EventDispatcherInterface
1790
-	 * @since 8.2.0
1791
-	 */
1792
-	public function getEventDispatcher() {
1793
-		return $this->query('EventDispatcher');
1794
-	}
1795
-
1796
-	/**
1797
-	 * Get the Notification Manager
1798
-	 *
1799
-	 * @return \OCP\Notification\IManager
1800
-	 * @since 8.2.0
1801
-	 */
1802
-	public function getNotificationManager() {
1803
-		return $this->query('NotificationManager');
1804
-	}
1805
-
1806
-	/**
1807
-	 * @return \OCP\Comments\ICommentsManager
1808
-	 */
1809
-	public function getCommentsManager() {
1810
-		return $this->query('CommentsManager');
1811
-	}
1812
-
1813
-	/**
1814
-	 * @return \OCA\Theming\ThemingDefaults
1815
-	 */
1816
-	public function getThemingDefaults() {
1817
-		return $this->query('ThemingDefaults');
1818
-	}
1819
-
1820
-	/**
1821
-	 * @return \OC\IntegrityCheck\Checker
1822
-	 */
1823
-	public function getIntegrityCodeChecker() {
1824
-		return $this->query('IntegrityCodeChecker');
1825
-	}
1826
-
1827
-	/**
1828
-	 * @return \OC\Session\CryptoWrapper
1829
-	 */
1830
-	public function getSessionCryptoWrapper() {
1831
-		return $this->query('CryptoWrapper');
1832
-	}
1833
-
1834
-	/**
1835
-	 * @return CsrfTokenManager
1836
-	 */
1837
-	public function getCsrfTokenManager() {
1838
-		return $this->query('CsrfTokenManager');
1839
-	}
1840
-
1841
-	/**
1842
-	 * @return Throttler
1843
-	 */
1844
-	public function getBruteForceThrottler() {
1845
-		return $this->query('Throttler');
1846
-	}
1847
-
1848
-	/**
1849
-	 * @return IContentSecurityPolicyManager
1850
-	 */
1851
-	public function getContentSecurityPolicyManager() {
1852
-		return $this->query('ContentSecurityPolicyManager');
1853
-	}
1854
-
1855
-	/**
1856
-	 * @return ContentSecurityPolicyNonceManager
1857
-	 */
1858
-	public function getContentSecurityPolicyNonceManager() {
1859
-		return $this->query('ContentSecurityPolicyNonceManager');
1860
-	}
1861
-
1862
-	/**
1863
-	 * Not a public API as of 8.2, wait for 9.0
1864
-	 *
1865
-	 * @return \OCA\Files_External\Service\BackendService
1866
-	 */
1867
-	public function getStoragesBackendService() {
1868
-		return $this->query('OCA\\Files_External\\Service\\BackendService');
1869
-	}
1870
-
1871
-	/**
1872
-	 * Not a public API as of 8.2, wait for 9.0
1873
-	 *
1874
-	 * @return \OCA\Files_External\Service\GlobalStoragesService
1875
-	 */
1876
-	public function getGlobalStoragesService() {
1877
-		return $this->query('OCA\\Files_External\\Service\\GlobalStoragesService');
1878
-	}
1879
-
1880
-	/**
1881
-	 * Not a public API as of 8.2, wait for 9.0
1882
-	 *
1883
-	 * @return \OCA\Files_External\Service\UserGlobalStoragesService
1884
-	 */
1885
-	public function getUserGlobalStoragesService() {
1886
-		return $this->query('OCA\\Files_External\\Service\\UserGlobalStoragesService');
1887
-	}
1888
-
1889
-	/**
1890
-	 * Not a public API as of 8.2, wait for 9.0
1891
-	 *
1892
-	 * @return \OCA\Files_External\Service\UserStoragesService
1893
-	 */
1894
-	public function getUserStoragesService() {
1895
-		return $this->query('OCA\\Files_External\\Service\\UserStoragesService');
1896
-	}
1897
-
1898
-	/**
1899
-	 * @return \OCP\Share\IManager
1900
-	 */
1901
-	public function getShareManager() {
1902
-		return $this->query('ShareManager');
1903
-	}
1904
-
1905
-	/**
1906
-	 * @return \OCP\Collaboration\Collaborators\ISearch
1907
-	 */
1908
-	public function getCollaboratorSearch() {
1909
-		return $this->query('CollaboratorSearch');
1910
-	}
1911
-
1912
-	/**
1913
-	 * @return \OCP\Collaboration\AutoComplete\IManager
1914
-	 */
1915
-	public function getAutoCompleteManager(){
1916
-		return $this->query(IManager::class);
1917
-	}
1918
-
1919
-	/**
1920
-	 * Returns the LDAP Provider
1921
-	 *
1922
-	 * @return \OCP\LDAP\ILDAPProvider
1923
-	 */
1924
-	public function getLDAPProvider() {
1925
-		return $this->query('LDAPProvider');
1926
-	}
1927
-
1928
-	/**
1929
-	 * @return \OCP\Settings\IManager
1930
-	 */
1931
-	public function getSettingsManager() {
1932
-		return $this->query('SettingsManager');
1933
-	}
1934
-
1935
-	/**
1936
-	 * @return \OCP\Files\IAppData
1937
-	 */
1938
-	public function getAppDataDir($app) {
1939
-		/** @var \OC\Files\AppData\Factory $factory */
1940
-		$factory = $this->query(\OC\Files\AppData\Factory::class);
1941
-		return $factory->get($app);
1942
-	}
1943
-
1944
-	/**
1945
-	 * @return \OCP\Lockdown\ILockdownManager
1946
-	 */
1947
-	public function getLockdownManager() {
1948
-		return $this->query('LockdownManager');
1949
-	}
1950
-
1951
-	/**
1952
-	 * @return \OCP\Federation\ICloudIdManager
1953
-	 */
1954
-	public function getCloudIdManager() {
1955
-		return $this->query(ICloudIdManager::class);
1956
-	}
1957
-
1958
-	/**
1959
-	 * @return \OCP\Remote\Api\IApiFactory
1960
-	 */
1961
-	public function getRemoteApiFactory() {
1962
-		return $this->query(IApiFactory::class);
1963
-	}
1964
-
1965
-	/**
1966
-	 * @return \OCP\Remote\IInstanceFactory
1967
-	 */
1968
-	public function getRemoteInstanceFactory() {
1969
-		return $this->query(IInstanceFactory::class);
1970
-	}
926
+            $prefixes = \OC::$composerAutoloader->getPrefixesPsr4();
927
+            if (isset($prefixes['OCA\\Theming\\'])) {
928
+                $classExists = true;
929
+            } else {
930
+                $classExists = false;
931
+            }
932
+
933
+            if ($classExists && $c->getConfig()->getSystemValue('installed', false) && $c->getAppManager()->isInstalled('theming') && $c->getTrustedDomainHelper()->isTrustedDomain($c->getRequest()->getInsecureServerHost())) {
934
+                return new ThemingDefaults(
935
+                    $c->getConfig(),
936
+                    $c->getL10N('theming'),
937
+                    $c->getURLGenerator(),
938
+                    $c->getAppDataDir('theming'),
939
+                    $c->getMemCacheFactory(),
940
+                    new Util($c->getConfig(), $this->getAppManager(), $this->getAppDataDir('theming')),
941
+                    $this->getAppManager()
942
+                );
943
+            }
944
+            return new \OC_Defaults();
945
+        });
946
+        $this->registerService(SCSSCacher::class, function (Server $c) {
947
+            /** @var Factory $cacheFactory */
948
+            $cacheFactory = $c->query(Factory::class);
949
+            return new SCSSCacher(
950
+                $c->getLogger(),
951
+                $c->query(\OC\Files\AppData\Factory::class),
952
+                $c->getURLGenerator(),
953
+                $c->getConfig(),
954
+                $c->getThemingDefaults(),
955
+                \OC::$SERVERROOT,
956
+                $cacheFactory->createDistributed('SCSS')
957
+            );
958
+        });
959
+        $this->registerService(EventDispatcher::class, function () {
960
+            return new EventDispatcher();
961
+        });
962
+        $this->registerAlias('EventDispatcher', EventDispatcher::class);
963
+        $this->registerAlias(EventDispatcherInterface::class, EventDispatcher::class);
964
+
965
+        $this->registerService('CryptoWrapper', function (Server $c) {
966
+            // FIXME: Instantiiated here due to cyclic dependency
967
+            $request = new Request(
968
+                [
969
+                    'get' => $_GET,
970
+                    'post' => $_POST,
971
+                    'files' => $_FILES,
972
+                    'server' => $_SERVER,
973
+                    'env' => $_ENV,
974
+                    'cookies' => $_COOKIE,
975
+                    'method' => (isset($_SERVER) && isset($_SERVER['REQUEST_METHOD']))
976
+                        ? $_SERVER['REQUEST_METHOD']
977
+                        : null,
978
+                ],
979
+                $c->getSecureRandom(),
980
+                $c->getConfig()
981
+            );
982
+
983
+            return new CryptoWrapper(
984
+                $c->getConfig(),
985
+                $c->getCrypto(),
986
+                $c->getSecureRandom(),
987
+                $request
988
+            );
989
+        });
990
+        $this->registerService('CsrfTokenManager', function (Server $c) {
991
+            $tokenGenerator = new CsrfTokenGenerator($c->getSecureRandom());
992
+
993
+            return new CsrfTokenManager(
994
+                $tokenGenerator,
995
+                $c->query(SessionStorage::class)
996
+            );
997
+        });
998
+        $this->registerService(SessionStorage::class, function (Server $c) {
999
+            return new SessionStorage($c->getSession());
1000
+        });
1001
+        $this->registerService(\OCP\Security\IContentSecurityPolicyManager::class, function (Server $c) {
1002
+            return new ContentSecurityPolicyManager();
1003
+        });
1004
+        $this->registerAlias('ContentSecurityPolicyManager', \OCP\Security\IContentSecurityPolicyManager::class);
1005
+
1006
+        $this->registerService('ContentSecurityPolicyNonceManager', function (Server $c) {
1007
+            return new ContentSecurityPolicyNonceManager(
1008
+                $c->getCsrfTokenManager(),
1009
+                $c->getRequest()
1010
+            );
1011
+        });
1012
+
1013
+        $this->registerService(\OCP\Share\IManager::class, function (Server $c) {
1014
+            $config = $c->getConfig();
1015
+            $factoryClass = $config->getSystemValue('sharing.managerFactory', '\OC\Share20\ProviderFactory');
1016
+            /** @var \OCP\Share\IProviderFactory $factory */
1017
+            $factory = new $factoryClass($this);
1018
+
1019
+            $manager = new \OC\Share20\Manager(
1020
+                $c->getLogger(),
1021
+                $c->getConfig(),
1022
+                $c->getSecureRandom(),
1023
+                $c->getHasher(),
1024
+                $c->getMountManager(),
1025
+                $c->getGroupManager(),
1026
+                $c->getL10N('lib'),
1027
+                $c->getL10NFactory(),
1028
+                $factory,
1029
+                $c->getUserManager(),
1030
+                $c->getLazyRootFolder(),
1031
+                $c->getEventDispatcher(),
1032
+                $c->getMailer(),
1033
+                $c->getURLGenerator(),
1034
+                $c->getThemingDefaults()
1035
+            );
1036
+
1037
+            return $manager;
1038
+        });
1039
+        $this->registerAlias('ShareManager', \OCP\Share\IManager::class);
1040
+
1041
+        $this->registerService(\OCP\Collaboration\Collaborators\ISearch::class, function(Server $c) {
1042
+            $instance = new Collaboration\Collaborators\Search($c);
1043
+
1044
+            // register default plugins
1045
+            $instance->registerPlugin(['shareType' => 'SHARE_TYPE_USER', 'class' => UserPlugin::class]);
1046
+            $instance->registerPlugin(['shareType' => 'SHARE_TYPE_GROUP', 'class' => GroupPlugin::class]);
1047
+            $instance->registerPlugin(['shareType' => 'SHARE_TYPE_EMAIL', 'class' => MailPlugin::class]);
1048
+            $instance->registerPlugin(['shareType' => 'SHARE_TYPE_REMOTE', 'class' => RemotePlugin::class]);
1049
+
1050
+            return $instance;
1051
+        });
1052
+        $this->registerAlias('CollaboratorSearch', \OCP\Collaboration\Collaborators\ISearch::class);
1053
+
1054
+        $this->registerAlias(\OCP\Collaboration\AutoComplete\IManager::class, \OC\Collaboration\AutoComplete\Manager::class);
1055
+
1056
+        $this->registerService('SettingsManager', function (Server $c) {
1057
+            $manager = new \OC\Settings\Manager(
1058
+                $c->getLogger(),
1059
+                $c->getDatabaseConnection(),
1060
+                $c->getL10N('lib'),
1061
+                $c->getConfig(),
1062
+                $c->getEncryptionManager(),
1063
+                $c->getUserManager(),
1064
+                $c->getLockingProvider(),
1065
+                $c->getRequest(),
1066
+                new \OC\Settings\Mapper($c->getDatabaseConnection()),
1067
+                $c->getURLGenerator(),
1068
+                $c->query(AccountManager::class),
1069
+                $c->getGroupManager(),
1070
+                $c->getL10NFactory(),
1071
+                $c->getThemingDefaults(),
1072
+                $c->getAppManager()
1073
+            );
1074
+            return $manager;
1075
+        });
1076
+        $this->registerService(\OC\Files\AppData\Factory::class, function (Server $c) {
1077
+            return new \OC\Files\AppData\Factory(
1078
+                $c->getRootFolder(),
1079
+                $c->getSystemConfig()
1080
+            );
1081
+        });
1082
+
1083
+        $this->registerService('LockdownManager', function (Server $c) {
1084
+            return new LockdownManager(function () use ($c) {
1085
+                return $c->getSession();
1086
+            });
1087
+        });
1088
+
1089
+        $this->registerService(\OCP\OCS\IDiscoveryService::class, function (Server $c) {
1090
+            return new DiscoveryService($c->getMemCacheFactory(), $c->getHTTPClientService());
1091
+        });
1092
+
1093
+        $this->registerService(ICloudIdManager::class, function (Server $c) {
1094
+            return new CloudIdManager();
1095
+        });
1096
+
1097
+        $this->registerAlias(\OCP\AppFramework\Utility\IControllerMethodReflector::class, \OC\AppFramework\Utility\ControllerMethodReflector::class);
1098
+        $this->registerAlias('ControllerMethodReflector', \OCP\AppFramework\Utility\IControllerMethodReflector::class);
1099
+
1100
+        $this->registerAlias(\OCP\AppFramework\Utility\ITimeFactory::class, \OC\AppFramework\Utility\TimeFactory::class);
1101
+        $this->registerAlias('TimeFactory', \OCP\AppFramework\Utility\ITimeFactory::class);
1102
+
1103
+        $this->registerService(Defaults::class, function (Server $c) {
1104
+            return new Defaults(
1105
+                $c->getThemingDefaults()
1106
+            );
1107
+        });
1108
+        $this->registerAlias('Defaults', \OCP\Defaults::class);
1109
+
1110
+        $this->registerService(\OCP\ISession::class, function (SimpleContainer $c) {
1111
+            return $c->query(\OCP\IUserSession::class)->getSession();
1112
+        });
1113
+
1114
+        $this->registerService(IShareHelper::class, function (Server $c) {
1115
+            return new ShareHelper(
1116
+                $c->query(\OCP\Share\IManager::class)
1117
+            );
1118
+        });
1119
+
1120
+        $this->registerService(Installer::class, function(Server $c) {
1121
+            return new Installer(
1122
+                $c->getAppFetcher(),
1123
+                $c->getHTTPClientService(),
1124
+                $c->getTempManager(),
1125
+                $c->getLogger(),
1126
+                $c->getConfig()
1127
+            );
1128
+        });
1129
+
1130
+        $this->registerService(IApiFactory::class, function(Server $c) {
1131
+            return new ApiFactory($c->getHTTPClientService());
1132
+        });
1133
+
1134
+        $this->registerService(IInstanceFactory::class, function(Server $c) {
1135
+            $memcacheFactory = $c->getMemCacheFactory();
1136
+            return new InstanceFactory($memcacheFactory->createLocal('remoteinstance.'), $c->getHTTPClientService());
1137
+        });
1138
+
1139
+        $this->registerService(IContactsStore::class, function(Server $c) {
1140
+            return new ContactsStore(
1141
+                $c->getContactsManager(),
1142
+                $c->getConfig(),
1143
+                $c->getUserManager(),
1144
+                $c->getGroupManager()
1145
+            );
1146
+        });
1147
+        $this->registerAlias(IContactsStore::class, ContactsStore::class);
1148
+
1149
+        $this->connectDispatcher();
1150
+    }
1151
+
1152
+    /**
1153
+     * @return \OCP\Calendar\IManager
1154
+     */
1155
+    public function getCalendarManager() {
1156
+        return $this->query('CalendarManager');
1157
+    }
1158
+
1159
+    private function connectDispatcher() {
1160
+        $dispatcher = $this->getEventDispatcher();
1161
+
1162
+        // Delete avatar on user deletion
1163
+        $dispatcher->addListener('OCP\IUser::preDelete', function(GenericEvent $e) {
1164
+            $logger = $this->getLogger();
1165
+            $manager = $this->getAvatarManager();
1166
+            /** @var IUser $user */
1167
+            $user = $e->getSubject();
1168
+
1169
+            try {
1170
+                $avatar = $manager->getAvatar($user->getUID());
1171
+                $avatar->remove();
1172
+            } catch (NotFoundException $e) {
1173
+                // no avatar to remove
1174
+            } catch (\Exception $e) {
1175
+                // Ignore exceptions
1176
+                $logger->info('Could not cleanup avatar of ' . $user->getUID());
1177
+            }
1178
+        });
1179
+
1180
+        $dispatcher->addListener('OCP\IUser::changeUser', function (GenericEvent $e) {
1181
+            $manager = $this->getAvatarManager();
1182
+            /** @var IUser $user */
1183
+            $user = $e->getSubject();
1184
+            $feature = $e->getArgument('feature');
1185
+            $oldValue = $e->getArgument('oldValue');
1186
+            $value = $e->getArgument('value');
1187
+
1188
+            try {
1189
+                $avatar = $manager->getAvatar($user->getUID());
1190
+                $avatar->userChanged($feature, $oldValue, $value);
1191
+            } catch (NotFoundException $e) {
1192
+                // no avatar to remove
1193
+            }
1194
+        });
1195
+    }
1196
+
1197
+    /**
1198
+     * @return \OCP\Contacts\IManager
1199
+     */
1200
+    public function getContactsManager() {
1201
+        return $this->query('ContactsManager');
1202
+    }
1203
+
1204
+    /**
1205
+     * @return \OC\Encryption\Manager
1206
+     */
1207
+    public function getEncryptionManager() {
1208
+        return $this->query('EncryptionManager');
1209
+    }
1210
+
1211
+    /**
1212
+     * @return \OC\Encryption\File
1213
+     */
1214
+    public function getEncryptionFilesHelper() {
1215
+        return $this->query('EncryptionFileHelper');
1216
+    }
1217
+
1218
+    /**
1219
+     * @return \OCP\Encryption\Keys\IStorage
1220
+     */
1221
+    public function getEncryptionKeyStorage() {
1222
+        return $this->query('EncryptionKeyStorage');
1223
+    }
1224
+
1225
+    /**
1226
+     * The current request object holding all information about the request
1227
+     * currently being processed is returned from this method.
1228
+     * In case the current execution was not initiated by a web request null is returned
1229
+     *
1230
+     * @return \OCP\IRequest
1231
+     */
1232
+    public function getRequest() {
1233
+        return $this->query('Request');
1234
+    }
1235
+
1236
+    /**
1237
+     * Returns the preview manager which can create preview images for a given file
1238
+     *
1239
+     * @return \OCP\IPreview
1240
+     */
1241
+    public function getPreviewManager() {
1242
+        return $this->query('PreviewManager');
1243
+    }
1244
+
1245
+    /**
1246
+     * Returns the tag manager which can get and set tags for different object types
1247
+     *
1248
+     * @see \OCP\ITagManager::load()
1249
+     * @return \OCP\ITagManager
1250
+     */
1251
+    public function getTagManager() {
1252
+        return $this->query('TagManager');
1253
+    }
1254
+
1255
+    /**
1256
+     * Returns the system-tag manager
1257
+     *
1258
+     * @return \OCP\SystemTag\ISystemTagManager
1259
+     *
1260
+     * @since 9.0.0
1261
+     */
1262
+    public function getSystemTagManager() {
1263
+        return $this->query('SystemTagManager');
1264
+    }
1265
+
1266
+    /**
1267
+     * Returns the system-tag object mapper
1268
+     *
1269
+     * @return \OCP\SystemTag\ISystemTagObjectMapper
1270
+     *
1271
+     * @since 9.0.0
1272
+     */
1273
+    public function getSystemTagObjectMapper() {
1274
+        return $this->query('SystemTagObjectMapper');
1275
+    }
1276
+
1277
+    /**
1278
+     * Returns the avatar manager, used for avatar functionality
1279
+     *
1280
+     * @return \OCP\IAvatarManager
1281
+     */
1282
+    public function getAvatarManager() {
1283
+        return $this->query('AvatarManager');
1284
+    }
1285
+
1286
+    /**
1287
+     * Returns the root folder of ownCloud's data directory
1288
+     *
1289
+     * @return \OCP\Files\IRootFolder
1290
+     */
1291
+    public function getRootFolder() {
1292
+        return $this->query('LazyRootFolder');
1293
+    }
1294
+
1295
+    /**
1296
+     * Returns the root folder of ownCloud's data directory
1297
+     * This is the lazy variant so this gets only initialized once it
1298
+     * is actually used.
1299
+     *
1300
+     * @return \OCP\Files\IRootFolder
1301
+     */
1302
+    public function getLazyRootFolder() {
1303
+        return $this->query('LazyRootFolder');
1304
+    }
1305
+
1306
+    /**
1307
+     * Returns a view to ownCloud's files folder
1308
+     *
1309
+     * @param string $userId user ID
1310
+     * @return \OCP\Files\Folder|null
1311
+     */
1312
+    public function getUserFolder($userId = null) {
1313
+        if ($userId === null) {
1314
+            $user = $this->getUserSession()->getUser();
1315
+            if (!$user) {
1316
+                return null;
1317
+            }
1318
+            $userId = $user->getUID();
1319
+        }
1320
+        $root = $this->getRootFolder();
1321
+        return $root->getUserFolder($userId);
1322
+    }
1323
+
1324
+    /**
1325
+     * Returns an app-specific view in ownClouds data directory
1326
+     *
1327
+     * @return \OCP\Files\Folder
1328
+     * @deprecated since 9.2.0 use IAppData
1329
+     */
1330
+    public function getAppFolder() {
1331
+        $dir = '/' . \OC_App::getCurrentApp();
1332
+        $root = $this->getRootFolder();
1333
+        if (!$root->nodeExists($dir)) {
1334
+            $folder = $root->newFolder($dir);
1335
+        } else {
1336
+            $folder = $root->get($dir);
1337
+        }
1338
+        return $folder;
1339
+    }
1340
+
1341
+    /**
1342
+     * @return \OC\User\Manager
1343
+     */
1344
+    public function getUserManager() {
1345
+        return $this->query('UserManager');
1346
+    }
1347
+
1348
+    /**
1349
+     * @return \OC\Group\Manager
1350
+     */
1351
+    public function getGroupManager() {
1352
+        return $this->query('GroupManager');
1353
+    }
1354
+
1355
+    /**
1356
+     * @return \OC\User\Session
1357
+     */
1358
+    public function getUserSession() {
1359
+        return $this->query('UserSession');
1360
+    }
1361
+
1362
+    /**
1363
+     * @return \OCP\ISession
1364
+     */
1365
+    public function getSession() {
1366
+        return $this->query('UserSession')->getSession();
1367
+    }
1368
+
1369
+    /**
1370
+     * @param \OCP\ISession $session
1371
+     */
1372
+    public function setSession(\OCP\ISession $session) {
1373
+        $this->query(SessionStorage::class)->setSession($session);
1374
+        $this->query('UserSession')->setSession($session);
1375
+        $this->query(Store::class)->setSession($session);
1376
+    }
1377
+
1378
+    /**
1379
+     * @return \OC\Authentication\TwoFactorAuth\Manager
1380
+     */
1381
+    public function getTwoFactorAuthManager() {
1382
+        return $this->query('\OC\Authentication\TwoFactorAuth\Manager');
1383
+    }
1384
+
1385
+    /**
1386
+     * @return \OC\NavigationManager
1387
+     */
1388
+    public function getNavigationManager() {
1389
+        return $this->query('NavigationManager');
1390
+    }
1391
+
1392
+    /**
1393
+     * @return \OCP\IConfig
1394
+     */
1395
+    public function getConfig() {
1396
+        return $this->query('AllConfig');
1397
+    }
1398
+
1399
+    /**
1400
+     * @return \OC\SystemConfig
1401
+     */
1402
+    public function getSystemConfig() {
1403
+        return $this->query('SystemConfig');
1404
+    }
1405
+
1406
+    /**
1407
+     * Returns the app config manager
1408
+     *
1409
+     * @return \OCP\IAppConfig
1410
+     */
1411
+    public function getAppConfig() {
1412
+        return $this->query('AppConfig');
1413
+    }
1414
+
1415
+    /**
1416
+     * @return \OCP\L10N\IFactory
1417
+     */
1418
+    public function getL10NFactory() {
1419
+        return $this->query('L10NFactory');
1420
+    }
1421
+
1422
+    /**
1423
+     * get an L10N instance
1424
+     *
1425
+     * @param string $app appid
1426
+     * @param string $lang
1427
+     * @return IL10N
1428
+     */
1429
+    public function getL10N($app, $lang = null) {
1430
+        return $this->getL10NFactory()->get($app, $lang);
1431
+    }
1432
+
1433
+    /**
1434
+     * @return \OCP\IURLGenerator
1435
+     */
1436
+    public function getURLGenerator() {
1437
+        return $this->query('URLGenerator');
1438
+    }
1439
+
1440
+    /**
1441
+     * @return \OCP\IHelper
1442
+     */
1443
+    public function getHelper() {
1444
+        return $this->query('AppHelper');
1445
+    }
1446
+
1447
+    /**
1448
+     * @return AppFetcher
1449
+     */
1450
+    public function getAppFetcher() {
1451
+        return $this->query(AppFetcher::class);
1452
+    }
1453
+
1454
+    /**
1455
+     * Returns an ICache instance. Since 8.1.0 it returns a fake cache. Use
1456
+     * getMemCacheFactory() instead.
1457
+     *
1458
+     * @return \OCP\ICache
1459
+     * @deprecated 8.1.0 use getMemCacheFactory to obtain a proper cache
1460
+     */
1461
+    public function getCache() {
1462
+        return $this->query('UserCache');
1463
+    }
1464
+
1465
+    /**
1466
+     * Returns an \OCP\CacheFactory instance
1467
+     *
1468
+     * @return \OCP\ICacheFactory
1469
+     */
1470
+    public function getMemCacheFactory() {
1471
+        return $this->query('MemCacheFactory');
1472
+    }
1473
+
1474
+    /**
1475
+     * Returns an \OC\RedisFactory instance
1476
+     *
1477
+     * @return \OC\RedisFactory
1478
+     */
1479
+    public function getGetRedisFactory() {
1480
+        return $this->query('RedisFactory');
1481
+    }
1482
+
1483
+
1484
+    /**
1485
+     * Returns the current session
1486
+     *
1487
+     * @return \OCP\IDBConnection
1488
+     */
1489
+    public function getDatabaseConnection() {
1490
+        return $this->query('DatabaseConnection');
1491
+    }
1492
+
1493
+    /**
1494
+     * Returns the activity manager
1495
+     *
1496
+     * @return \OCP\Activity\IManager
1497
+     */
1498
+    public function getActivityManager() {
1499
+        return $this->query('ActivityManager');
1500
+    }
1501
+
1502
+    /**
1503
+     * Returns an job list for controlling background jobs
1504
+     *
1505
+     * @return \OCP\BackgroundJob\IJobList
1506
+     */
1507
+    public function getJobList() {
1508
+        return $this->query('JobList');
1509
+    }
1510
+
1511
+    /**
1512
+     * Returns a logger instance
1513
+     *
1514
+     * @return \OCP\ILogger
1515
+     */
1516
+    public function getLogger() {
1517
+        return $this->query('Logger');
1518
+    }
1519
+
1520
+    /**
1521
+     * Returns a router for generating and matching urls
1522
+     *
1523
+     * @return \OCP\Route\IRouter
1524
+     */
1525
+    public function getRouter() {
1526
+        return $this->query('Router');
1527
+    }
1528
+
1529
+    /**
1530
+     * Returns a search instance
1531
+     *
1532
+     * @return \OCP\ISearch
1533
+     */
1534
+    public function getSearch() {
1535
+        return $this->query('Search');
1536
+    }
1537
+
1538
+    /**
1539
+     * Returns a SecureRandom instance
1540
+     *
1541
+     * @return \OCP\Security\ISecureRandom
1542
+     */
1543
+    public function getSecureRandom() {
1544
+        return $this->query('SecureRandom');
1545
+    }
1546
+
1547
+    /**
1548
+     * Returns a Crypto instance
1549
+     *
1550
+     * @return \OCP\Security\ICrypto
1551
+     */
1552
+    public function getCrypto() {
1553
+        return $this->query('Crypto');
1554
+    }
1555
+
1556
+    /**
1557
+     * Returns a Hasher instance
1558
+     *
1559
+     * @return \OCP\Security\IHasher
1560
+     */
1561
+    public function getHasher() {
1562
+        return $this->query('Hasher');
1563
+    }
1564
+
1565
+    /**
1566
+     * Returns a CredentialsManager instance
1567
+     *
1568
+     * @return \OCP\Security\ICredentialsManager
1569
+     */
1570
+    public function getCredentialsManager() {
1571
+        return $this->query('CredentialsManager');
1572
+    }
1573
+
1574
+    /**
1575
+     * Returns an instance of the HTTP helper class
1576
+     *
1577
+     * @deprecated Use getHTTPClientService()
1578
+     * @return \OC\HTTPHelper
1579
+     */
1580
+    public function getHTTPHelper() {
1581
+        return $this->query('HTTPHelper');
1582
+    }
1583
+
1584
+    /**
1585
+     * Get the certificate manager for the user
1586
+     *
1587
+     * @param string $userId (optional) if not specified the current loggedin user is used, use null to get the system certificate manager
1588
+     * @return \OCP\ICertificateManager | null if $uid is null and no user is logged in
1589
+     */
1590
+    public function getCertificateManager($userId = '') {
1591
+        if ($userId === '') {
1592
+            $userSession = $this->getUserSession();
1593
+            $user = $userSession->getUser();
1594
+            if (is_null($user)) {
1595
+                return null;
1596
+            }
1597
+            $userId = $user->getUID();
1598
+        }
1599
+        return new CertificateManager(
1600
+            $userId,
1601
+            new View(),
1602
+            $this->getConfig(),
1603
+            $this->getLogger(),
1604
+            $this->getSecureRandom()
1605
+        );
1606
+    }
1607
+
1608
+    /**
1609
+     * Returns an instance of the HTTP client service
1610
+     *
1611
+     * @return \OCP\Http\Client\IClientService
1612
+     */
1613
+    public function getHTTPClientService() {
1614
+        return $this->query('HttpClientService');
1615
+    }
1616
+
1617
+    /**
1618
+     * Create a new event source
1619
+     *
1620
+     * @return \OCP\IEventSource
1621
+     */
1622
+    public function createEventSource() {
1623
+        return new \OC_EventSource();
1624
+    }
1625
+
1626
+    /**
1627
+     * Get the active event logger
1628
+     *
1629
+     * The returned logger only logs data when debug mode is enabled
1630
+     *
1631
+     * @return \OCP\Diagnostics\IEventLogger
1632
+     */
1633
+    public function getEventLogger() {
1634
+        return $this->query('EventLogger');
1635
+    }
1636
+
1637
+    /**
1638
+     * Get the active query logger
1639
+     *
1640
+     * The returned logger only logs data when debug mode is enabled
1641
+     *
1642
+     * @return \OCP\Diagnostics\IQueryLogger
1643
+     */
1644
+    public function getQueryLogger() {
1645
+        return $this->query('QueryLogger');
1646
+    }
1647
+
1648
+    /**
1649
+     * Get the manager for temporary files and folders
1650
+     *
1651
+     * @return \OCP\ITempManager
1652
+     */
1653
+    public function getTempManager() {
1654
+        return $this->query('TempManager');
1655
+    }
1656
+
1657
+    /**
1658
+     * Get the app manager
1659
+     *
1660
+     * @return \OCP\App\IAppManager
1661
+     */
1662
+    public function getAppManager() {
1663
+        return $this->query('AppManager');
1664
+    }
1665
+
1666
+    /**
1667
+     * Creates a new mailer
1668
+     *
1669
+     * @return \OCP\Mail\IMailer
1670
+     */
1671
+    public function getMailer() {
1672
+        return $this->query('Mailer');
1673
+    }
1674
+
1675
+    /**
1676
+     * Get the webroot
1677
+     *
1678
+     * @return string
1679
+     */
1680
+    public function getWebRoot() {
1681
+        return $this->webRoot;
1682
+    }
1683
+
1684
+    /**
1685
+     * @return \OC\OCSClient
1686
+     */
1687
+    public function getOcsClient() {
1688
+        return $this->query('OcsClient');
1689
+    }
1690
+
1691
+    /**
1692
+     * @return \OCP\IDateTimeZone
1693
+     */
1694
+    public function getDateTimeZone() {
1695
+        return $this->query('DateTimeZone');
1696
+    }
1697
+
1698
+    /**
1699
+     * @return \OCP\IDateTimeFormatter
1700
+     */
1701
+    public function getDateTimeFormatter() {
1702
+        return $this->query('DateTimeFormatter');
1703
+    }
1704
+
1705
+    /**
1706
+     * @return \OCP\Files\Config\IMountProviderCollection
1707
+     */
1708
+    public function getMountProviderCollection() {
1709
+        return $this->query('MountConfigManager');
1710
+    }
1711
+
1712
+    /**
1713
+     * Get the IniWrapper
1714
+     *
1715
+     * @return IniGetWrapper
1716
+     */
1717
+    public function getIniWrapper() {
1718
+        return $this->query('IniWrapper');
1719
+    }
1720
+
1721
+    /**
1722
+     * @return \OCP\Command\IBus
1723
+     */
1724
+    public function getCommandBus() {
1725
+        return $this->query('AsyncCommandBus');
1726
+    }
1727
+
1728
+    /**
1729
+     * Get the trusted domain helper
1730
+     *
1731
+     * @return TrustedDomainHelper
1732
+     */
1733
+    public function getTrustedDomainHelper() {
1734
+        return $this->query('TrustedDomainHelper');
1735
+    }
1736
+
1737
+    /**
1738
+     * Get the locking provider
1739
+     *
1740
+     * @return \OCP\Lock\ILockingProvider
1741
+     * @since 8.1.0
1742
+     */
1743
+    public function getLockingProvider() {
1744
+        return $this->query('LockingProvider');
1745
+    }
1746
+
1747
+    /**
1748
+     * @return \OCP\Files\Mount\IMountManager
1749
+     **/
1750
+    function getMountManager() {
1751
+        return $this->query('MountManager');
1752
+    }
1753
+
1754
+    /** @return \OCP\Files\Config\IUserMountCache */
1755
+    function getUserMountCache() {
1756
+        return $this->query('UserMountCache');
1757
+    }
1758
+
1759
+    /**
1760
+     * Get the MimeTypeDetector
1761
+     *
1762
+     * @return \OCP\Files\IMimeTypeDetector
1763
+     */
1764
+    public function getMimeTypeDetector() {
1765
+        return $this->query('MimeTypeDetector');
1766
+    }
1767
+
1768
+    /**
1769
+     * Get the MimeTypeLoader
1770
+     *
1771
+     * @return \OCP\Files\IMimeTypeLoader
1772
+     */
1773
+    public function getMimeTypeLoader() {
1774
+        return $this->query('MimeTypeLoader');
1775
+    }
1776
+
1777
+    /**
1778
+     * Get the manager of all the capabilities
1779
+     *
1780
+     * @return \OC\CapabilitiesManager
1781
+     */
1782
+    public function getCapabilitiesManager() {
1783
+        return $this->query('CapabilitiesManager');
1784
+    }
1785
+
1786
+    /**
1787
+     * Get the EventDispatcher
1788
+     *
1789
+     * @return EventDispatcherInterface
1790
+     * @since 8.2.0
1791
+     */
1792
+    public function getEventDispatcher() {
1793
+        return $this->query('EventDispatcher');
1794
+    }
1795
+
1796
+    /**
1797
+     * Get the Notification Manager
1798
+     *
1799
+     * @return \OCP\Notification\IManager
1800
+     * @since 8.2.0
1801
+     */
1802
+    public function getNotificationManager() {
1803
+        return $this->query('NotificationManager');
1804
+    }
1805
+
1806
+    /**
1807
+     * @return \OCP\Comments\ICommentsManager
1808
+     */
1809
+    public function getCommentsManager() {
1810
+        return $this->query('CommentsManager');
1811
+    }
1812
+
1813
+    /**
1814
+     * @return \OCA\Theming\ThemingDefaults
1815
+     */
1816
+    public function getThemingDefaults() {
1817
+        return $this->query('ThemingDefaults');
1818
+    }
1819
+
1820
+    /**
1821
+     * @return \OC\IntegrityCheck\Checker
1822
+     */
1823
+    public function getIntegrityCodeChecker() {
1824
+        return $this->query('IntegrityCodeChecker');
1825
+    }
1826
+
1827
+    /**
1828
+     * @return \OC\Session\CryptoWrapper
1829
+     */
1830
+    public function getSessionCryptoWrapper() {
1831
+        return $this->query('CryptoWrapper');
1832
+    }
1833
+
1834
+    /**
1835
+     * @return CsrfTokenManager
1836
+     */
1837
+    public function getCsrfTokenManager() {
1838
+        return $this->query('CsrfTokenManager');
1839
+    }
1840
+
1841
+    /**
1842
+     * @return Throttler
1843
+     */
1844
+    public function getBruteForceThrottler() {
1845
+        return $this->query('Throttler');
1846
+    }
1847
+
1848
+    /**
1849
+     * @return IContentSecurityPolicyManager
1850
+     */
1851
+    public function getContentSecurityPolicyManager() {
1852
+        return $this->query('ContentSecurityPolicyManager');
1853
+    }
1854
+
1855
+    /**
1856
+     * @return ContentSecurityPolicyNonceManager
1857
+     */
1858
+    public function getContentSecurityPolicyNonceManager() {
1859
+        return $this->query('ContentSecurityPolicyNonceManager');
1860
+    }
1861
+
1862
+    /**
1863
+     * Not a public API as of 8.2, wait for 9.0
1864
+     *
1865
+     * @return \OCA\Files_External\Service\BackendService
1866
+     */
1867
+    public function getStoragesBackendService() {
1868
+        return $this->query('OCA\\Files_External\\Service\\BackendService');
1869
+    }
1870
+
1871
+    /**
1872
+     * Not a public API as of 8.2, wait for 9.0
1873
+     *
1874
+     * @return \OCA\Files_External\Service\GlobalStoragesService
1875
+     */
1876
+    public function getGlobalStoragesService() {
1877
+        return $this->query('OCA\\Files_External\\Service\\GlobalStoragesService');
1878
+    }
1879
+
1880
+    /**
1881
+     * Not a public API as of 8.2, wait for 9.0
1882
+     *
1883
+     * @return \OCA\Files_External\Service\UserGlobalStoragesService
1884
+     */
1885
+    public function getUserGlobalStoragesService() {
1886
+        return $this->query('OCA\\Files_External\\Service\\UserGlobalStoragesService');
1887
+    }
1888
+
1889
+    /**
1890
+     * Not a public API as of 8.2, wait for 9.0
1891
+     *
1892
+     * @return \OCA\Files_External\Service\UserStoragesService
1893
+     */
1894
+    public function getUserStoragesService() {
1895
+        return $this->query('OCA\\Files_External\\Service\\UserStoragesService');
1896
+    }
1897
+
1898
+    /**
1899
+     * @return \OCP\Share\IManager
1900
+     */
1901
+    public function getShareManager() {
1902
+        return $this->query('ShareManager');
1903
+    }
1904
+
1905
+    /**
1906
+     * @return \OCP\Collaboration\Collaborators\ISearch
1907
+     */
1908
+    public function getCollaboratorSearch() {
1909
+        return $this->query('CollaboratorSearch');
1910
+    }
1911
+
1912
+    /**
1913
+     * @return \OCP\Collaboration\AutoComplete\IManager
1914
+     */
1915
+    public function getAutoCompleteManager(){
1916
+        return $this->query(IManager::class);
1917
+    }
1918
+
1919
+    /**
1920
+     * Returns the LDAP Provider
1921
+     *
1922
+     * @return \OCP\LDAP\ILDAPProvider
1923
+     */
1924
+    public function getLDAPProvider() {
1925
+        return $this->query('LDAPProvider');
1926
+    }
1927
+
1928
+    /**
1929
+     * @return \OCP\Settings\IManager
1930
+     */
1931
+    public function getSettingsManager() {
1932
+        return $this->query('SettingsManager');
1933
+    }
1934
+
1935
+    /**
1936
+     * @return \OCP\Files\IAppData
1937
+     */
1938
+    public function getAppDataDir($app) {
1939
+        /** @var \OC\Files\AppData\Factory $factory */
1940
+        $factory = $this->query(\OC\Files\AppData\Factory::class);
1941
+        return $factory->get($app);
1942
+    }
1943
+
1944
+    /**
1945
+     * @return \OCP\Lockdown\ILockdownManager
1946
+     */
1947
+    public function getLockdownManager() {
1948
+        return $this->query('LockdownManager');
1949
+    }
1950
+
1951
+    /**
1952
+     * @return \OCP\Federation\ICloudIdManager
1953
+     */
1954
+    public function getCloudIdManager() {
1955
+        return $this->query(ICloudIdManager::class);
1956
+    }
1957
+
1958
+    /**
1959
+     * @return \OCP\Remote\Api\IApiFactory
1960
+     */
1961
+    public function getRemoteApiFactory() {
1962
+        return $this->query(IApiFactory::class);
1963
+    }
1964
+
1965
+    /**
1966
+     * @return \OCP\Remote\IInstanceFactory
1967
+     */
1968
+    public function getRemoteInstanceFactory() {
1969
+        return $this->query(IInstanceFactory::class);
1970
+    }
1971 1971
 }
Please login to merge, or discard this patch.
Spacing   +114 added lines, -114 removed lines patch added patch discarded remove patch
@@ -158,7 +158,7 @@  discard block
 block discarded – undo
158 158
 		parent::__construct();
159 159
 		$this->webRoot = $webRoot;
160 160
 
161
-		$this->registerService(\OCP\IServerContainer::class, function (IServerContainer $c) {
161
+		$this->registerService(\OCP\IServerContainer::class, function(IServerContainer $c) {
162 162
 			return $c;
163 163
 		});
164 164
 
@@ -171,7 +171,7 @@  discard block
 block discarded – undo
171 171
 		$this->registerAlias(IActionFactory::class, ActionFactory::class);
172 172
 
173 173
 
174
-		$this->registerService(\OCP\IPreview::class, function (Server $c) {
174
+		$this->registerService(\OCP\IPreview::class, function(Server $c) {
175 175
 			return new PreviewManager(
176 176
 				$c->getConfig(),
177 177
 				$c->getRootFolder(),
@@ -182,13 +182,13 @@  discard block
 block discarded – undo
182 182
 		});
183 183
 		$this->registerAlias('PreviewManager', \OCP\IPreview::class);
184 184
 
185
-		$this->registerService(\OC\Preview\Watcher::class, function (Server $c) {
185
+		$this->registerService(\OC\Preview\Watcher::class, function(Server $c) {
186 186
 			return new \OC\Preview\Watcher(
187 187
 				$c->getAppDataDir('preview')
188 188
 			);
189 189
 		});
190 190
 
191
-		$this->registerService('EncryptionManager', function (Server $c) {
191
+		$this->registerService('EncryptionManager', function(Server $c) {
192 192
 			$view = new View();
193 193
 			$util = new Encryption\Util(
194 194
 				$view,
@@ -206,7 +206,7 @@  discard block
 block discarded – undo
206 206
 			);
207 207
 		});
208 208
 
209
-		$this->registerService('EncryptionFileHelper', function (Server $c) {
209
+		$this->registerService('EncryptionFileHelper', function(Server $c) {
210 210
 			$util = new Encryption\Util(
211 211
 				new View(),
212 212
 				$c->getUserManager(),
@@ -220,7 +220,7 @@  discard block
 block discarded – undo
220 220
 			);
221 221
 		});
222 222
 
223
-		$this->registerService('EncryptionKeyStorage', function (Server $c) {
223
+		$this->registerService('EncryptionKeyStorage', function(Server $c) {
224 224
 			$view = new View();
225 225
 			$util = new Encryption\Util(
226 226
 				$view,
@@ -231,32 +231,32 @@  discard block
 block discarded – undo
231 231
 
232 232
 			return new Encryption\Keys\Storage($view, $util);
233 233
 		});
234
-		$this->registerService('TagMapper', function (Server $c) {
234
+		$this->registerService('TagMapper', function(Server $c) {
235 235
 			return new TagMapper($c->getDatabaseConnection());
236 236
 		});
237 237
 
238
-		$this->registerService(\OCP\ITagManager::class, function (Server $c) {
238
+		$this->registerService(\OCP\ITagManager::class, function(Server $c) {
239 239
 			$tagMapper = $c->query('TagMapper');
240 240
 			return new TagManager($tagMapper, $c->getUserSession());
241 241
 		});
242 242
 		$this->registerAlias('TagManager', \OCP\ITagManager::class);
243 243
 
244
-		$this->registerService('SystemTagManagerFactory', function (Server $c) {
244
+		$this->registerService('SystemTagManagerFactory', function(Server $c) {
245 245
 			$config = $c->getConfig();
246 246
 			$factoryClass = $config->getSystemValue('systemtags.managerFactory', '\OC\SystemTag\ManagerFactory');
247 247
 			/** @var \OC\SystemTag\ManagerFactory $factory */
248 248
 			$factory = new $factoryClass($this);
249 249
 			return $factory;
250 250
 		});
251
-		$this->registerService(\OCP\SystemTag\ISystemTagManager::class, function (Server $c) {
251
+		$this->registerService(\OCP\SystemTag\ISystemTagManager::class, function(Server $c) {
252 252
 			return $c->query('SystemTagManagerFactory')->getManager();
253 253
 		});
254 254
 		$this->registerAlias('SystemTagManager', \OCP\SystemTag\ISystemTagManager::class);
255 255
 
256
-		$this->registerService(\OCP\SystemTag\ISystemTagObjectMapper::class, function (Server $c) {
256
+		$this->registerService(\OCP\SystemTag\ISystemTagObjectMapper::class, function(Server $c) {
257 257
 			return $c->query('SystemTagManagerFactory')->getObjectMapper();
258 258
 		});
259
-		$this->registerService('RootFolder', function (Server $c) {
259
+		$this->registerService('RootFolder', function(Server $c) {
260 260
 			$manager = \OC\Files\Filesystem::getMountManager(null);
261 261
 			$view = new View();
262 262
 			$root = new Root(
@@ -277,37 +277,37 @@  discard block
 block discarded – undo
277 277
 		});
278 278
 		$this->registerAlias('SystemTagObjectMapper', \OCP\SystemTag\ISystemTagObjectMapper::class);
279 279
 
280
-		$this->registerService(\OCP\Files\IRootFolder::class, function (Server $c) {
281
-			return new LazyRoot(function () use ($c) {
280
+		$this->registerService(\OCP\Files\IRootFolder::class, function(Server $c) {
281
+			return new LazyRoot(function() use ($c) {
282 282
 				return $c->query('RootFolder');
283 283
 			});
284 284
 		});
285 285
 		$this->registerAlias('LazyRootFolder', \OCP\Files\IRootFolder::class);
286 286
 
287
-		$this->registerService(\OCP\IUserManager::class, function (Server $c) {
287
+		$this->registerService(\OCP\IUserManager::class, function(Server $c) {
288 288
 			$config = $c->getConfig();
289 289
 			return new \OC\User\Manager($config);
290 290
 		});
291 291
 		$this->registerAlias('UserManager', \OCP\IUserManager::class);
292 292
 
293
-		$this->registerService(\OCP\IGroupManager::class, function (Server $c) {
293
+		$this->registerService(\OCP\IGroupManager::class, function(Server $c) {
294 294
 			$groupManager = new \OC\Group\Manager($this->getUserManager(), $this->getLogger());
295
-			$groupManager->listen('\OC\Group', 'preCreate', function ($gid) {
295
+			$groupManager->listen('\OC\Group', 'preCreate', function($gid) {
296 296
 				\OC_Hook::emit('OC_Group', 'pre_createGroup', array('run' => true, 'gid' => $gid));
297 297
 			});
298
-			$groupManager->listen('\OC\Group', 'postCreate', function (\OC\Group\Group $gid) {
298
+			$groupManager->listen('\OC\Group', 'postCreate', function(\OC\Group\Group $gid) {
299 299
 				\OC_Hook::emit('OC_User', 'post_createGroup', array('gid' => $gid->getGID()));
300 300
 			});
301
-			$groupManager->listen('\OC\Group', 'preDelete', function (\OC\Group\Group $group) {
301
+			$groupManager->listen('\OC\Group', 'preDelete', function(\OC\Group\Group $group) {
302 302
 				\OC_Hook::emit('OC_Group', 'pre_deleteGroup', array('run' => true, 'gid' => $group->getGID()));
303 303
 			});
304
-			$groupManager->listen('\OC\Group', 'postDelete', function (\OC\Group\Group $group) {
304
+			$groupManager->listen('\OC\Group', 'postDelete', function(\OC\Group\Group $group) {
305 305
 				\OC_Hook::emit('OC_User', 'post_deleteGroup', array('gid' => $group->getGID()));
306 306
 			});
307
-			$groupManager->listen('\OC\Group', 'preAddUser', function (\OC\Group\Group $group, \OC\User\User $user) {
307
+			$groupManager->listen('\OC\Group', 'preAddUser', function(\OC\Group\Group $group, \OC\User\User $user) {
308 308
 				\OC_Hook::emit('OC_Group', 'pre_addToGroup', array('run' => true, 'uid' => $user->getUID(), 'gid' => $group->getGID()));
309 309
 			});
310
-			$groupManager->listen('\OC\Group', 'postAddUser', function (\OC\Group\Group $group, \OC\User\User $user) {
310
+			$groupManager->listen('\OC\Group', 'postAddUser', function(\OC\Group\Group $group, \OC\User\User $user) {
311 311
 				\OC_Hook::emit('OC_Group', 'post_addToGroup', array('uid' => $user->getUID(), 'gid' => $group->getGID()));
312 312
 				//Minimal fix to keep it backward compatible TODO: clean up all the GroupManager hooks
313 313
 				\OC_Hook::emit('OC_User', 'post_addToGroup', array('uid' => $user->getUID(), 'gid' => $group->getGID()));
@@ -316,7 +316,7 @@  discard block
 block discarded – undo
316 316
 		});
317 317
 		$this->registerAlias('GroupManager', \OCP\IGroupManager::class);
318 318
 
319
-		$this->registerService(Store::class, function (Server $c) {
319
+		$this->registerService(Store::class, function(Server $c) {
320 320
 			$session = $c->getSession();
321 321
 			if (\OC::$server->getSystemConfig()->getValue('installed', false)) {
322 322
 				$tokenProvider = $c->query('OC\Authentication\Token\IProvider');
@@ -327,11 +327,11 @@  discard block
 block discarded – undo
327 327
 			return new Store($session, $logger, $tokenProvider);
328 328
 		});
329 329
 		$this->registerAlias(IStore::class, Store::class);
330
-		$this->registerService('OC\Authentication\Token\DefaultTokenMapper', function (Server $c) {
330
+		$this->registerService('OC\Authentication\Token\DefaultTokenMapper', function(Server $c) {
331 331
 			$dbConnection = $c->getDatabaseConnection();
332 332
 			return new Authentication\Token\DefaultTokenMapper($dbConnection);
333 333
 		});
334
-		$this->registerService('OC\Authentication\Token\DefaultTokenProvider', function (Server $c) {
334
+		$this->registerService('OC\Authentication\Token\DefaultTokenProvider', function(Server $c) {
335 335
 			$mapper = $c->query('OC\Authentication\Token\DefaultTokenMapper');
336 336
 			$crypto = $c->getCrypto();
337 337
 			$config = $c->getConfig();
@@ -341,7 +341,7 @@  discard block
 block discarded – undo
341 341
 		});
342 342
 		$this->registerAlias('OC\Authentication\Token\IProvider', 'OC\Authentication\Token\DefaultTokenProvider');
343 343
 
344
-		$this->registerService(\OCP\IUserSession::class, function (Server $c) {
344
+		$this->registerService(\OCP\IUserSession::class, function(Server $c) {
345 345
 			$manager = $c->getUserManager();
346 346
 			$session = new \OC\Session\Memory('');
347 347
 			$timeFactory = new TimeFactory();
@@ -356,45 +356,45 @@  discard block
 block discarded – undo
356 356
 			$dispatcher = $c->getEventDispatcher();
357 357
 
358 358
 			$userSession = new \OC\User\Session($manager, $session, $timeFactory, $defaultTokenProvider, $c->getConfig(), $c->getSecureRandom(), $c->getLockdownManager());
359
-			$userSession->listen('\OC\User', 'preCreateUser', function ($uid, $password) {
359
+			$userSession->listen('\OC\User', 'preCreateUser', function($uid, $password) {
360 360
 				\OC_Hook::emit('OC_User', 'pre_createUser', array('run' => true, 'uid' => $uid, 'password' => $password));
361 361
 			});
362
-			$userSession->listen('\OC\User', 'postCreateUser', function ($user, $password) {
362
+			$userSession->listen('\OC\User', 'postCreateUser', function($user, $password) {
363 363
 				/** @var $user \OC\User\User */
364 364
 				\OC_Hook::emit('OC_User', 'post_createUser', array('uid' => $user->getUID(), 'password' => $password));
365 365
 			});
366
-			$userSession->listen('\OC\User', 'preDelete', function ($user) use ($dispatcher) {
366
+			$userSession->listen('\OC\User', 'preDelete', function($user) use ($dispatcher) {
367 367
 				/** @var $user \OC\User\User */
368 368
 				\OC_Hook::emit('OC_User', 'pre_deleteUser', array('run' => true, 'uid' => $user->getUID()));
369 369
 				$dispatcher->dispatch('OCP\IUser::preDelete', new GenericEvent($user));
370 370
 			});
371
-			$userSession->listen('\OC\User', 'postDelete', function ($user) {
371
+			$userSession->listen('\OC\User', 'postDelete', function($user) {
372 372
 				/** @var $user \OC\User\User */
373 373
 				\OC_Hook::emit('OC_User', 'post_deleteUser', array('uid' => $user->getUID()));
374 374
 			});
375
-			$userSession->listen('\OC\User', 'preSetPassword', function ($user, $password, $recoveryPassword) {
375
+			$userSession->listen('\OC\User', 'preSetPassword', function($user, $password, $recoveryPassword) {
376 376
 				/** @var $user \OC\User\User */
377 377
 				\OC_Hook::emit('OC_User', 'pre_setPassword', array('run' => true, 'uid' => $user->getUID(), 'password' => $password, 'recoveryPassword' => $recoveryPassword));
378 378
 			});
379
-			$userSession->listen('\OC\User', 'postSetPassword', function ($user, $password, $recoveryPassword) {
379
+			$userSession->listen('\OC\User', 'postSetPassword', function($user, $password, $recoveryPassword) {
380 380
 				/** @var $user \OC\User\User */
381 381
 				\OC_Hook::emit('OC_User', 'post_setPassword', array('run' => true, 'uid' => $user->getUID(), 'password' => $password, 'recoveryPassword' => $recoveryPassword));
382 382
 			});
383
-			$userSession->listen('\OC\User', 'preLogin', function ($uid, $password) {
383
+			$userSession->listen('\OC\User', 'preLogin', function($uid, $password) {
384 384
 				\OC_Hook::emit('OC_User', 'pre_login', array('run' => true, 'uid' => $uid, 'password' => $password));
385 385
 			});
386
-			$userSession->listen('\OC\User', 'postLogin', function ($user, $password) {
386
+			$userSession->listen('\OC\User', 'postLogin', function($user, $password) {
387 387
 				/** @var $user \OC\User\User */
388 388
 				\OC_Hook::emit('OC_User', 'post_login', array('run' => true, 'uid' => $user->getUID(), 'password' => $password));
389 389
 			});
390
-			$userSession->listen('\OC\User', 'postRememberedLogin', function ($user, $password) {
390
+			$userSession->listen('\OC\User', 'postRememberedLogin', function($user, $password) {
391 391
 				/** @var $user \OC\User\User */
392 392
 				\OC_Hook::emit('OC_User', 'post_login', array('run' => true, 'uid' => $user->getUID(), 'password' => $password));
393 393
 			});
394
-			$userSession->listen('\OC\User', 'logout', function () {
394
+			$userSession->listen('\OC\User', 'logout', function() {
395 395
 				\OC_Hook::emit('OC_User', 'logout', array());
396 396
 			});
397
-			$userSession->listen('\OC\User', 'changeUser', function ($user, $feature, $value, $oldValue) use ($dispatcher) {
397
+			$userSession->listen('\OC\User', 'changeUser', function($user, $feature, $value, $oldValue) use ($dispatcher) {
398 398
 				/** @var $user \OC\User\User */
399 399
 				\OC_Hook::emit('OC_User', 'changeUser', array('run' => true, 'user' => $user, 'feature' => $feature, 'value' => $value, 'old_value' => $oldValue));
400 400
 				$dispatcher->dispatch('OCP\IUser::changeUser', new GenericEvent($user, ['feature' => $feature, 'oldValue' => $oldValue, 'value' => $value]));
@@ -403,7 +403,7 @@  discard block
 block discarded – undo
403 403
 		});
404 404
 		$this->registerAlias('UserSession', \OCP\IUserSession::class);
405 405
 
406
-		$this->registerService(\OC\Authentication\TwoFactorAuth\Manager::class, function (Server $c) {
406
+		$this->registerService(\OC\Authentication\TwoFactorAuth\Manager::class, function(Server $c) {
407 407
 			return new \OC\Authentication\TwoFactorAuth\Manager(
408 408
 				$c->getAppManager(),
409 409
 				$c->getSession(),
@@ -418,7 +418,7 @@  discard block
 block discarded – undo
418 418
 		$this->registerAlias(\OCP\INavigationManager::class, \OC\NavigationManager::class);
419 419
 		$this->registerAlias('NavigationManager', \OCP\INavigationManager::class);
420 420
 
421
-		$this->registerService(\OC\AllConfig::class, function (Server $c) {
421
+		$this->registerService(\OC\AllConfig::class, function(Server $c) {
422 422
 			return new \OC\AllConfig(
423 423
 				$c->getSystemConfig()
424 424
 			);
@@ -426,17 +426,17 @@  discard block
 block discarded – undo
426 426
 		$this->registerAlias('AllConfig', \OC\AllConfig::class);
427 427
 		$this->registerAlias(\OCP\IConfig::class, \OC\AllConfig::class);
428 428
 
429
-		$this->registerService('SystemConfig', function ($c) use ($config) {
429
+		$this->registerService('SystemConfig', function($c) use ($config) {
430 430
 			return new \OC\SystemConfig($config);
431 431
 		});
432 432
 
433
-		$this->registerService(\OC\AppConfig::class, function (Server $c) {
433
+		$this->registerService(\OC\AppConfig::class, function(Server $c) {
434 434
 			return new \OC\AppConfig($c->getDatabaseConnection());
435 435
 		});
436 436
 		$this->registerAlias('AppConfig', \OC\AppConfig::class);
437 437
 		$this->registerAlias(\OCP\IAppConfig::class, \OC\AppConfig::class);
438 438
 
439
-		$this->registerService(\OCP\L10N\IFactory::class, function (Server $c) {
439
+		$this->registerService(\OCP\L10N\IFactory::class, function(Server $c) {
440 440
 			return new \OC\L10N\Factory(
441 441
 				$c->getConfig(),
442 442
 				$c->getRequest(),
@@ -446,7 +446,7 @@  discard block
 block discarded – undo
446 446
 		});
447 447
 		$this->registerAlias('L10NFactory', \OCP\L10N\IFactory::class);
448 448
 
449
-		$this->registerService(\OCP\IURLGenerator::class, function (Server $c) {
449
+		$this->registerService(\OCP\IURLGenerator::class, function(Server $c) {
450 450
 			$config = $c->getConfig();
451 451
 			$cacheFactory = $c->getMemCacheFactory();
452 452
 			$request = $c->getRequest();
@@ -458,18 +458,18 @@  discard block
 block discarded – undo
458 458
 		});
459 459
 		$this->registerAlias('URLGenerator', \OCP\IURLGenerator::class);
460 460
 
461
-		$this->registerService('AppHelper', function ($c) {
461
+		$this->registerService('AppHelper', function($c) {
462 462
 			return new \OC\AppHelper();
463 463
 		});
464 464
 		$this->registerAlias('AppFetcher', AppFetcher::class);
465 465
 		$this->registerAlias('CategoryFetcher', CategoryFetcher::class);
466 466
 
467
-		$this->registerService(\OCP\ICache::class, function ($c) {
467
+		$this->registerService(\OCP\ICache::class, function($c) {
468 468
 			return new Cache\File();
469 469
 		});
470 470
 		$this->registerAlias('UserCache', \OCP\ICache::class);
471 471
 
472
-		$this->registerService(Factory::class, function (Server $c) {
472
+		$this->registerService(Factory::class, function(Server $c) {
473 473
 
474 474
 			$arrayCacheFactory = new \OC\Memcache\Factory('', $c->getLogger(),
475 475
 				'\\OC\\Memcache\\ArrayCache',
@@ -486,7 +486,7 @@  discard block
 block discarded – undo
486 486
 				$version = implode(',', $v);
487 487
 				$instanceId = \OC_Util::getInstanceId();
488 488
 				$path = \OC::$SERVERROOT;
489
-				$prefix = md5($instanceId . '-' . $version . '-' . $path . '-' . $urlGenerator->getBaseUrl());
489
+				$prefix = md5($instanceId.'-'.$version.'-'.$path.'-'.$urlGenerator->getBaseUrl());
490 490
 				return new \OC\Memcache\Factory($prefix, $c->getLogger(),
491 491
 					$config->getSystemValue('memcache.local', null),
492 492
 					$config->getSystemValue('memcache.distributed', null),
@@ -499,12 +499,12 @@  discard block
 block discarded – undo
499 499
 		$this->registerAlias('MemCacheFactory', Factory::class);
500 500
 		$this->registerAlias(ICacheFactory::class, Factory::class);
501 501
 
502
-		$this->registerService('RedisFactory', function (Server $c) {
502
+		$this->registerService('RedisFactory', function(Server $c) {
503 503
 			$systemConfig = $c->getSystemConfig();
504 504
 			return new RedisFactory($systemConfig);
505 505
 		});
506 506
 
507
-		$this->registerService(\OCP\Activity\IManager::class, function (Server $c) {
507
+		$this->registerService(\OCP\Activity\IManager::class, function(Server $c) {
508 508
 			return new \OC\Activity\Manager(
509 509
 				$c->getRequest(),
510 510
 				$c->getUserSession(),
@@ -514,14 +514,14 @@  discard block
 block discarded – undo
514 514
 		});
515 515
 		$this->registerAlias('ActivityManager', \OCP\Activity\IManager::class);
516 516
 
517
-		$this->registerService(\OCP\Activity\IEventMerger::class, function (Server $c) {
517
+		$this->registerService(\OCP\Activity\IEventMerger::class, function(Server $c) {
518 518
 			return new \OC\Activity\EventMerger(
519 519
 				$c->getL10N('lib')
520 520
 			);
521 521
 		});
522 522
 		$this->registerAlias(IValidator::class, Validator::class);
523 523
 
524
-		$this->registerService(\OCP\IAvatarManager::class, function (Server $c) {
524
+		$this->registerService(\OCP\IAvatarManager::class, function(Server $c) {
525 525
 			return new AvatarManager(
526 526
 				$c->getUserManager(),
527 527
 				$c->getAppDataDir('avatar'),
@@ -534,7 +534,7 @@  discard block
 block discarded – undo
534 534
 
535 535
 		$this->registerAlias(\OCP\Support\CrashReport\IRegistry::class, \OC\Support\CrashReport\Registry::class);
536 536
 
537
-		$this->registerService(\OCP\ILogger::class, function (Server $c) {
537
+		$this->registerService(\OCP\ILogger::class, function(Server $c) {
538 538
 			$logType = $c->query('AllConfig')->getSystemValue('log_type', 'file');
539 539
 			$logger = Log::getLogClass($logType);
540 540
 			call_user_func(array($logger, 'init'));
@@ -545,7 +545,7 @@  discard block
 block discarded – undo
545 545
 		});
546 546
 		$this->registerAlias('Logger', \OCP\ILogger::class);
547 547
 
548
-		$this->registerService(\OCP\BackgroundJob\IJobList::class, function (Server $c) {
548
+		$this->registerService(\OCP\BackgroundJob\IJobList::class, function(Server $c) {
549 549
 			$config = $c->getConfig();
550 550
 			return new \OC\BackgroundJob\JobList(
551 551
 				$c->getDatabaseConnection(),
@@ -555,7 +555,7 @@  discard block
 block discarded – undo
555 555
 		});
556 556
 		$this->registerAlias('JobList', \OCP\BackgroundJob\IJobList::class);
557 557
 
558
-		$this->registerService(\OCP\Route\IRouter::class, function (Server $c) {
558
+		$this->registerService(\OCP\Route\IRouter::class, function(Server $c) {
559 559
 			$cacheFactory = $c->getMemCacheFactory();
560 560
 			$logger = $c->getLogger();
561 561
 			if ($cacheFactory->isAvailableLowLatency()) {
@@ -567,12 +567,12 @@  discard block
 block discarded – undo
567 567
 		});
568 568
 		$this->registerAlias('Router', \OCP\Route\IRouter::class);
569 569
 
570
-		$this->registerService(\OCP\ISearch::class, function ($c) {
570
+		$this->registerService(\OCP\ISearch::class, function($c) {
571 571
 			return new Search();
572 572
 		});
573 573
 		$this->registerAlias('Search', \OCP\ISearch::class);
574 574
 
575
-		$this->registerService(\OC\Security\RateLimiting\Limiter::class, function ($c) {
575
+		$this->registerService(\OC\Security\RateLimiting\Limiter::class, function($c) {
576 576
 			return new \OC\Security\RateLimiting\Limiter(
577 577
 				$this->getUserSession(),
578 578
 				$this->getRequest(),
@@ -580,34 +580,34 @@  discard block
 block discarded – undo
580 580
 				$c->query(\OC\Security\RateLimiting\Backend\IBackend::class)
581 581
 			);
582 582
 		});
583
-		$this->registerService(\OC\Security\RateLimiting\Backend\IBackend::class, function ($c) {
583
+		$this->registerService(\OC\Security\RateLimiting\Backend\IBackend::class, function($c) {
584 584
 			return new \OC\Security\RateLimiting\Backend\MemoryCache(
585 585
 				$this->getMemCacheFactory(),
586 586
 				new \OC\AppFramework\Utility\TimeFactory()
587 587
 			);
588 588
 		});
589 589
 
590
-		$this->registerService(\OCP\Security\ISecureRandom::class, function ($c) {
590
+		$this->registerService(\OCP\Security\ISecureRandom::class, function($c) {
591 591
 			return new SecureRandom();
592 592
 		});
593 593
 		$this->registerAlias('SecureRandom', \OCP\Security\ISecureRandom::class);
594 594
 
595
-		$this->registerService(\OCP\Security\ICrypto::class, function (Server $c) {
595
+		$this->registerService(\OCP\Security\ICrypto::class, function(Server $c) {
596 596
 			return new Crypto($c->getConfig(), $c->getSecureRandom());
597 597
 		});
598 598
 		$this->registerAlias('Crypto', \OCP\Security\ICrypto::class);
599 599
 
600
-		$this->registerService(\OCP\Security\IHasher::class, function (Server $c) {
600
+		$this->registerService(\OCP\Security\IHasher::class, function(Server $c) {
601 601
 			return new Hasher($c->getConfig());
602 602
 		});
603 603
 		$this->registerAlias('Hasher', \OCP\Security\IHasher::class);
604 604
 
605
-		$this->registerService(\OCP\Security\ICredentialsManager::class, function (Server $c) {
605
+		$this->registerService(\OCP\Security\ICredentialsManager::class, function(Server $c) {
606 606
 			return new CredentialsManager($c->getCrypto(), $c->getDatabaseConnection());
607 607
 		});
608 608
 		$this->registerAlias('CredentialsManager', \OCP\Security\ICredentialsManager::class);
609 609
 
610
-		$this->registerService(IDBConnection::class, function (Server $c) {
610
+		$this->registerService(IDBConnection::class, function(Server $c) {
611 611
 			$systemConfig = $c->getSystemConfig();
612 612
 			$factory = new \OC\DB\ConnectionFactory($systemConfig);
613 613
 			$type = $systemConfig->getValue('dbtype', 'sqlite');
@@ -621,7 +621,7 @@  discard block
 block discarded – undo
621 621
 		});
622 622
 		$this->registerAlias('DatabaseConnection', IDBConnection::class);
623 623
 
624
-		$this->registerService('HTTPHelper', function (Server $c) {
624
+		$this->registerService('HTTPHelper', function(Server $c) {
625 625
 			$config = $c->getConfig();
626 626
 			return new HTTPHelper(
627 627
 				$config,
@@ -629,7 +629,7 @@  discard block
 block discarded – undo
629 629
 			);
630 630
 		});
631 631
 
632
-		$this->registerService(\OCP\Http\Client\IClientService::class, function (Server $c) {
632
+		$this->registerService(\OCP\Http\Client\IClientService::class, function(Server $c) {
633 633
 			$user = \OC_User::getUser();
634 634
 			$uid = $user ? $user : null;
635 635
 			return new ClientService(
@@ -644,7 +644,7 @@  discard block
 block discarded – undo
644 644
 			);
645 645
 		});
646 646
 		$this->registerAlias('HttpClientService', \OCP\Http\Client\IClientService::class);
647
-		$this->registerService(\OCP\Diagnostics\IEventLogger::class, function (Server $c) {
647
+		$this->registerService(\OCP\Diagnostics\IEventLogger::class, function(Server $c) {
648 648
 			$eventLogger = new EventLogger();
649 649
 			if ($c->getSystemConfig()->getValue('debug', false)) {
650 650
 				// In debug mode, module is being activated by default
@@ -654,7 +654,7 @@  discard block
 block discarded – undo
654 654
 		});
655 655
 		$this->registerAlias('EventLogger', \OCP\Diagnostics\IEventLogger::class);
656 656
 
657
-		$this->registerService(\OCP\Diagnostics\IQueryLogger::class, function (Server $c) {
657
+		$this->registerService(\OCP\Diagnostics\IQueryLogger::class, function(Server $c) {
658 658
 			$queryLogger = new QueryLogger();
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('QueryLogger', \OCP\Diagnostics\IQueryLogger::class);
666 666
 
667
-		$this->registerService(TempManager::class, function (Server $c) {
667
+		$this->registerService(TempManager::class, function(Server $c) {
668 668
 			return new TempManager(
669 669
 				$c->getLogger(),
670 670
 				$c->getConfig()
@@ -673,7 +673,7 @@  discard block
 block discarded – undo
673 673
 		$this->registerAlias('TempManager', TempManager::class);
674 674
 		$this->registerAlias(ITempManager::class, TempManager::class);
675 675
 
676
-		$this->registerService(AppManager::class, function (Server $c) {
676
+		$this->registerService(AppManager::class, function(Server $c) {
677 677
 			return new \OC\App\AppManager(
678 678
 				$c->getUserSession(),
679 679
 				$c->getAppConfig(),
@@ -685,7 +685,7 @@  discard block
 block discarded – undo
685 685
 		$this->registerAlias('AppManager', AppManager::class);
686 686
 		$this->registerAlias(IAppManager::class, AppManager::class);
687 687
 
688
-		$this->registerService(\OCP\IDateTimeZone::class, function (Server $c) {
688
+		$this->registerService(\OCP\IDateTimeZone::class, function(Server $c) {
689 689
 			return new DateTimeZone(
690 690
 				$c->getConfig(),
691 691
 				$c->getSession()
@@ -693,7 +693,7 @@  discard block
 block discarded – undo
693 693
 		});
694 694
 		$this->registerAlias('DateTimeZone', \OCP\IDateTimeZone::class);
695 695
 
696
-		$this->registerService(\OCP\IDateTimeFormatter::class, function (Server $c) {
696
+		$this->registerService(\OCP\IDateTimeFormatter::class, function(Server $c) {
697 697
 			$language = $c->getConfig()->getUserValue($c->getSession()->get('user_id'), 'core', 'lang', null);
698 698
 
699 699
 			return new DateTimeFormatter(
@@ -703,7 +703,7 @@  discard block
 block discarded – undo
703 703
 		});
704 704
 		$this->registerAlias('DateTimeFormatter', \OCP\IDateTimeFormatter::class);
705 705
 
706
-		$this->registerService(\OCP\Files\Config\IUserMountCache::class, function (Server $c) {
706
+		$this->registerService(\OCP\Files\Config\IUserMountCache::class, function(Server $c) {
707 707
 			$mountCache = new UserMountCache($c->getDatabaseConnection(), $c->getUserManager(), $c->getLogger());
708 708
 			$listener = new UserMountCacheListener($mountCache);
709 709
 			$listener->listen($c->getUserManager());
@@ -711,7 +711,7 @@  discard block
 block discarded – undo
711 711
 		});
712 712
 		$this->registerAlias('UserMountCache', \OCP\Files\Config\IUserMountCache::class);
713 713
 
714
-		$this->registerService(\OCP\Files\Config\IMountProviderCollection::class, function (Server $c) {
714
+		$this->registerService(\OCP\Files\Config\IMountProviderCollection::class, function(Server $c) {
715 715
 			$loader = \OC\Files\Filesystem::getLoader();
716 716
 			$mountCache = $c->query('UserMountCache');
717 717
 			$manager = new \OC\Files\Config\MountProviderCollection($loader, $mountCache);
@@ -727,10 +727,10 @@  discard block
 block discarded – undo
727 727
 		});
728 728
 		$this->registerAlias('MountConfigManager', \OCP\Files\Config\IMountProviderCollection::class);
729 729
 
730
-		$this->registerService('IniWrapper', function ($c) {
730
+		$this->registerService('IniWrapper', function($c) {
731 731
 			return new IniGetWrapper();
732 732
 		});
733
-		$this->registerService('AsyncCommandBus', function (Server $c) {
733
+		$this->registerService('AsyncCommandBus', function(Server $c) {
734 734
 			$busClass = $c->getConfig()->getSystemValue('commandbus');
735 735
 			if ($busClass) {
736 736
 				list($app, $class) = explode('::', $busClass, 2);
@@ -745,10 +745,10 @@  discard block
 block discarded – undo
745 745
 				return new CronBus($jobList);
746 746
 			}
747 747
 		});
748
-		$this->registerService('TrustedDomainHelper', function ($c) {
748
+		$this->registerService('TrustedDomainHelper', function($c) {
749 749
 			return new TrustedDomainHelper($this->getConfig());
750 750
 		});
751
-		$this->registerService('Throttler', function (Server $c) {
751
+		$this->registerService('Throttler', function(Server $c) {
752 752
 			return new Throttler(
753 753
 				$c->getDatabaseConnection(),
754 754
 				new TimeFactory(),
@@ -756,7 +756,7 @@  discard block
 block discarded – undo
756 756
 				$c->getConfig()
757 757
 			);
758 758
 		});
759
-		$this->registerService('IntegrityCodeChecker', function (Server $c) {
759
+		$this->registerService('IntegrityCodeChecker', function(Server $c) {
760 760
 			// IConfig and IAppManager requires a working database. This code
761 761
 			// might however be called when ownCloud is not yet setup.
762 762
 			if (\OC::$server->getSystemConfig()->getValue('installed', false)) {
@@ -777,7 +777,7 @@  discard block
 block discarded – undo
777 777
 				$c->getTempManager()
778 778
 			);
779 779
 		});
780
-		$this->registerService(\OCP\IRequest::class, function ($c) {
780
+		$this->registerService(\OCP\IRequest::class, function($c) {
781 781
 			if (isset($this['urlParams'])) {
782 782
 				$urlParams = $this['urlParams'];
783 783
 			} else {
@@ -813,7 +813,7 @@  discard block
 block discarded – undo
813 813
 		});
814 814
 		$this->registerAlias('Request', \OCP\IRequest::class);
815 815
 
816
-		$this->registerService(\OCP\Mail\IMailer::class, function (Server $c) {
816
+		$this->registerService(\OCP\Mail\IMailer::class, function(Server $c) {
817 817
 			return new Mailer(
818 818
 				$c->getConfig(),
819 819
 				$c->getLogger(),
@@ -824,7 +824,7 @@  discard block
 block discarded – undo
824 824
 		});
825 825
 		$this->registerAlias('Mailer', \OCP\Mail\IMailer::class);
826 826
 
827
-		$this->registerService('LDAPProvider', function (Server $c) {
827
+		$this->registerService('LDAPProvider', function(Server $c) {
828 828
 			$config = $c->getConfig();
829 829
 			$factoryClass = $config->getSystemValue('ldapProviderFactory', null);
830 830
 			if (is_null($factoryClass)) {
@@ -834,7 +834,7 @@  discard block
 block discarded – undo
834 834
 			$factory = new $factoryClass($this);
835 835
 			return $factory->getLDAPProvider();
836 836
 		});
837
-		$this->registerService(ILockingProvider::class, function (Server $c) {
837
+		$this->registerService(ILockingProvider::class, function(Server $c) {
838 838
 			$ini = $c->getIniWrapper();
839 839
 			$config = $c->getConfig();
840 840
 			$ttl = $config->getSystemValue('filelocking.ttl', max(3600, $ini->getNumeric('max_execution_time')));
@@ -851,49 +851,49 @@  discard block
 block discarded – undo
851 851
 		});
852 852
 		$this->registerAlias('LockingProvider', ILockingProvider::class);
853 853
 
854
-		$this->registerService(\OCP\Files\Mount\IMountManager::class, function () {
854
+		$this->registerService(\OCP\Files\Mount\IMountManager::class, function() {
855 855
 			return new \OC\Files\Mount\Manager();
856 856
 		});
857 857
 		$this->registerAlias('MountManager', \OCP\Files\Mount\IMountManager::class);
858 858
 
859
-		$this->registerService(\OCP\Files\IMimeTypeDetector::class, function (Server $c) {
859
+		$this->registerService(\OCP\Files\IMimeTypeDetector::class, function(Server $c) {
860 860
 			return new \OC\Files\Type\Detection(
861 861
 				$c->getURLGenerator(),
862 862
 				\OC::$configDir,
863
-				\OC::$SERVERROOT . '/resources/config/'
863
+				\OC::$SERVERROOT.'/resources/config/'
864 864
 			);
865 865
 		});
866 866
 		$this->registerAlias('MimeTypeDetector', \OCP\Files\IMimeTypeDetector::class);
867 867
 
868
-		$this->registerService(\OCP\Files\IMimeTypeLoader::class, function (Server $c) {
868
+		$this->registerService(\OCP\Files\IMimeTypeLoader::class, function(Server $c) {
869 869
 			return new \OC\Files\Type\Loader(
870 870
 				$c->getDatabaseConnection()
871 871
 			);
872 872
 		});
873 873
 		$this->registerAlias('MimeTypeLoader', \OCP\Files\IMimeTypeLoader::class);
874
-		$this->registerService(BundleFetcher::class, function () {
874
+		$this->registerService(BundleFetcher::class, function() {
875 875
 			return new BundleFetcher($this->getL10N('lib'));
876 876
 		});
877
-		$this->registerService(\OCP\Notification\IManager::class, function (Server $c) {
877
+		$this->registerService(\OCP\Notification\IManager::class, function(Server $c) {
878 878
 			return new Manager(
879 879
 				$c->query(IValidator::class)
880 880
 			);
881 881
 		});
882 882
 		$this->registerAlias('NotificationManager', \OCP\Notification\IManager::class);
883 883
 
884
-		$this->registerService(\OC\CapabilitiesManager::class, function (Server $c) {
884
+		$this->registerService(\OC\CapabilitiesManager::class, function(Server $c) {
885 885
 			$manager = new \OC\CapabilitiesManager($c->getLogger());
886
-			$manager->registerCapability(function () use ($c) {
886
+			$manager->registerCapability(function() use ($c) {
887 887
 				return new \OC\OCS\CoreCapabilities($c->getConfig());
888 888
 			});
889
-			$manager->registerCapability(function () use ($c) {
889
+			$manager->registerCapability(function() use ($c) {
890 890
 				return $c->query(\OC\Security\Bruteforce\Capabilities::class);
891 891
 			});
892 892
 			return $manager;
893 893
 		});
894 894
 		$this->registerAlias('CapabilitiesManager', \OC\CapabilitiesManager::class);
895 895
 
896
-		$this->registerService(\OCP\Comments\ICommentsManager::class, function (Server $c) {
896
+		$this->registerService(\OCP\Comments\ICommentsManager::class, function(Server $c) {
897 897
 			$config = $c->getConfig();
898 898
 			$factoryClass = $config->getSystemValue('comments.managerFactory', '\OC\Comments\ManagerFactory');
899 899
 			/** @var \OCP\Comments\ICommentsManagerFactory $factory */
@@ -903,7 +903,7 @@  discard block
 block discarded – undo
903 903
 			$manager->registerDisplayNameResolver('user', function($id) use ($c) {
904 904
 				$manager = $c->getUserManager();
905 905
 				$user = $manager->get($id);
906
-				if(is_null($user)) {
906
+				if (is_null($user)) {
907 907
 					$l = $c->getL10N('core');
908 908
 					$displayName = $l->t('Unknown user');
909 909
 				} else {
@@ -916,7 +916,7 @@  discard block
 block discarded – undo
916 916
 		});
917 917
 		$this->registerAlias('CommentsManager', \OCP\Comments\ICommentsManager::class);
918 918
 
919
-		$this->registerService('ThemingDefaults', function (Server $c) {
919
+		$this->registerService('ThemingDefaults', function(Server $c) {
920 920
 			/*
921 921
 			 * Dark magic for autoloader.
922 922
 			 * If we do a class_exists it will try to load the class which will
@@ -943,7 +943,7 @@  discard block
 block discarded – undo
943 943
 			}
944 944
 			return new \OC_Defaults();
945 945
 		});
946
-		$this->registerService(SCSSCacher::class, function (Server $c) {
946
+		$this->registerService(SCSSCacher::class, function(Server $c) {
947 947
 			/** @var Factory $cacheFactory */
948 948
 			$cacheFactory = $c->query(Factory::class);
949 949
 			return new SCSSCacher(
@@ -956,13 +956,13 @@  discard block
 block discarded – undo
956 956
 				$cacheFactory->createDistributed('SCSS')
957 957
 			);
958 958
 		});
959
-		$this->registerService(EventDispatcher::class, function () {
959
+		$this->registerService(EventDispatcher::class, function() {
960 960
 			return new EventDispatcher();
961 961
 		});
962 962
 		$this->registerAlias('EventDispatcher', EventDispatcher::class);
963 963
 		$this->registerAlias(EventDispatcherInterface::class, EventDispatcher::class);
964 964
 
965
-		$this->registerService('CryptoWrapper', function (Server $c) {
965
+		$this->registerService('CryptoWrapper', function(Server $c) {
966 966
 			// FIXME: Instantiiated here due to cyclic dependency
967 967
 			$request = new Request(
968 968
 				[
@@ -987,7 +987,7 @@  discard block
 block discarded – undo
987 987
 				$request
988 988
 			);
989 989
 		});
990
-		$this->registerService('CsrfTokenManager', function (Server $c) {
990
+		$this->registerService('CsrfTokenManager', function(Server $c) {
991 991
 			$tokenGenerator = new CsrfTokenGenerator($c->getSecureRandom());
992 992
 
993 993
 			return new CsrfTokenManager(
@@ -995,22 +995,22 @@  discard block
 block discarded – undo
995 995
 				$c->query(SessionStorage::class)
996 996
 			);
997 997
 		});
998
-		$this->registerService(SessionStorage::class, function (Server $c) {
998
+		$this->registerService(SessionStorage::class, function(Server $c) {
999 999
 			return new SessionStorage($c->getSession());
1000 1000
 		});
1001
-		$this->registerService(\OCP\Security\IContentSecurityPolicyManager::class, function (Server $c) {
1001
+		$this->registerService(\OCP\Security\IContentSecurityPolicyManager::class, function(Server $c) {
1002 1002
 			return new ContentSecurityPolicyManager();
1003 1003
 		});
1004 1004
 		$this->registerAlias('ContentSecurityPolicyManager', \OCP\Security\IContentSecurityPolicyManager::class);
1005 1005
 
1006
-		$this->registerService('ContentSecurityPolicyNonceManager', function (Server $c) {
1006
+		$this->registerService('ContentSecurityPolicyNonceManager', function(Server $c) {
1007 1007
 			return new ContentSecurityPolicyNonceManager(
1008 1008
 				$c->getCsrfTokenManager(),
1009 1009
 				$c->getRequest()
1010 1010
 			);
1011 1011
 		});
1012 1012
 
1013
-		$this->registerService(\OCP\Share\IManager::class, function (Server $c) {
1013
+		$this->registerService(\OCP\Share\IManager::class, function(Server $c) {
1014 1014
 			$config = $c->getConfig();
1015 1015
 			$factoryClass = $config->getSystemValue('sharing.managerFactory', '\OC\Share20\ProviderFactory');
1016 1016
 			/** @var \OCP\Share\IProviderFactory $factory */
@@ -1053,7 +1053,7 @@  discard block
 block discarded – undo
1053 1053
 
1054 1054
 		$this->registerAlias(\OCP\Collaboration\AutoComplete\IManager::class, \OC\Collaboration\AutoComplete\Manager::class);
1055 1055
 
1056
-		$this->registerService('SettingsManager', function (Server $c) {
1056
+		$this->registerService('SettingsManager', function(Server $c) {
1057 1057
 			$manager = new \OC\Settings\Manager(
1058 1058
 				$c->getLogger(),
1059 1059
 				$c->getDatabaseConnection(),
@@ -1073,24 +1073,24 @@  discard block
 block discarded – undo
1073 1073
 			);
1074 1074
 			return $manager;
1075 1075
 		});
1076
-		$this->registerService(\OC\Files\AppData\Factory::class, function (Server $c) {
1076
+		$this->registerService(\OC\Files\AppData\Factory::class, function(Server $c) {
1077 1077
 			return new \OC\Files\AppData\Factory(
1078 1078
 				$c->getRootFolder(),
1079 1079
 				$c->getSystemConfig()
1080 1080
 			);
1081 1081
 		});
1082 1082
 
1083
-		$this->registerService('LockdownManager', function (Server $c) {
1084
-			return new LockdownManager(function () use ($c) {
1083
+		$this->registerService('LockdownManager', function(Server $c) {
1084
+			return new LockdownManager(function() use ($c) {
1085 1085
 				return $c->getSession();
1086 1086
 			});
1087 1087
 		});
1088 1088
 
1089
-		$this->registerService(\OCP\OCS\IDiscoveryService::class, function (Server $c) {
1089
+		$this->registerService(\OCP\OCS\IDiscoveryService::class, function(Server $c) {
1090 1090
 			return new DiscoveryService($c->getMemCacheFactory(), $c->getHTTPClientService());
1091 1091
 		});
1092 1092
 
1093
-		$this->registerService(ICloudIdManager::class, function (Server $c) {
1093
+		$this->registerService(ICloudIdManager::class, function(Server $c) {
1094 1094
 			return new CloudIdManager();
1095 1095
 		});
1096 1096
 
@@ -1100,18 +1100,18 @@  discard block
 block discarded – undo
1100 1100
 		$this->registerAlias(\OCP\AppFramework\Utility\ITimeFactory::class, \OC\AppFramework\Utility\TimeFactory::class);
1101 1101
 		$this->registerAlias('TimeFactory', \OCP\AppFramework\Utility\ITimeFactory::class);
1102 1102
 
1103
-		$this->registerService(Defaults::class, function (Server $c) {
1103
+		$this->registerService(Defaults::class, function(Server $c) {
1104 1104
 			return new Defaults(
1105 1105
 				$c->getThemingDefaults()
1106 1106
 			);
1107 1107
 		});
1108 1108
 		$this->registerAlias('Defaults', \OCP\Defaults::class);
1109 1109
 
1110
-		$this->registerService(\OCP\ISession::class, function (SimpleContainer $c) {
1110
+		$this->registerService(\OCP\ISession::class, function(SimpleContainer $c) {
1111 1111
 			return $c->query(\OCP\IUserSession::class)->getSession();
1112 1112
 		});
1113 1113
 
1114
-		$this->registerService(IShareHelper::class, function (Server $c) {
1114
+		$this->registerService(IShareHelper::class, function(Server $c) {
1115 1115
 			return new ShareHelper(
1116 1116
 				$c->query(\OCP\Share\IManager::class)
1117 1117
 			);
@@ -1173,11 +1173,11 @@  discard block
 block discarded – undo
1173 1173
 				// no avatar to remove
1174 1174
 			} catch (\Exception $e) {
1175 1175
 				// Ignore exceptions
1176
-				$logger->info('Could not cleanup avatar of ' . $user->getUID());
1176
+				$logger->info('Could not cleanup avatar of '.$user->getUID());
1177 1177
 			}
1178 1178
 		});
1179 1179
 
1180
-		$dispatcher->addListener('OCP\IUser::changeUser', function (GenericEvent $e) {
1180
+		$dispatcher->addListener('OCP\IUser::changeUser', function(GenericEvent $e) {
1181 1181
 			$manager = $this->getAvatarManager();
1182 1182
 			/** @var IUser $user */
1183 1183
 			$user = $e->getSubject();
@@ -1328,7 +1328,7 @@  discard block
 block discarded – undo
1328 1328
 	 * @deprecated since 9.2.0 use IAppData
1329 1329
 	 */
1330 1330
 	public function getAppFolder() {
1331
-		$dir = '/' . \OC_App::getCurrentApp();
1331
+		$dir = '/'.\OC_App::getCurrentApp();
1332 1332
 		$root = $this->getRootFolder();
1333 1333
 		if (!$root->nodeExists($dir)) {
1334 1334
 			$folder = $root->newFolder($dir);
@@ -1912,7 +1912,7 @@  discard block
 block discarded – undo
1912 1912
 	/**
1913 1913
 	 * @return \OCP\Collaboration\AutoComplete\IManager
1914 1914
 	 */
1915
-	public function getAutoCompleteManager(){
1915
+	public function getAutoCompleteManager() {
1916 1916
 		return $this->query(IManager::class);
1917 1917
 	}
1918 1918
 
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   +1106 added lines, -1106 removed lines patch added patch discarded remove patch
@@ -46,1143 +46,1143 @@
 block discarded – undo
46 46
  */
47 47
 class DefaultShareProvider implements IShareProvider {
48 48
 
49
-	// Special share type for user modified group shares
50
-	const SHARE_TYPE_USERGROUP = 2;
51
-
52
-	/** @var IDBConnection */
53
-	private $dbConn;
54
-
55
-	/** @var IUserManager */
56
-	private $userManager;
57
-
58
-	/** @var IGroupManager */
59
-	private $groupManager;
60
-
61
-	/** @var IRootFolder */
62
-	private $rootFolder;
63
-
64
-	/**
65
-	 * DefaultShareProvider constructor.
66
-	 *
67
-	 * @param IDBConnection $connection
68
-	 * @param IUserManager $userManager
69
-	 * @param IGroupManager $groupManager
70
-	 * @param IRootFolder $rootFolder
71
-	 */
72
-	public function __construct(
73
-			IDBConnection $connection,
74
-			IUserManager $userManager,
75
-			IGroupManager $groupManager,
76
-			IRootFolder $rootFolder) {
77
-		$this->dbConn = $connection;
78
-		$this->userManager = $userManager;
79
-		$this->groupManager = $groupManager;
80
-		$this->rootFolder = $rootFolder;
81
-	}
82
-
83
-	/**
84
-	 * Return the identifier of this provider.
85
-	 *
86
-	 * @return string Containing only [a-zA-Z0-9]
87
-	 */
88
-	public function identifier() {
89
-		return 'ocinternal';
90
-	}
91
-
92
-	/**
93
-	 * Share a path
94
-	 *
95
-	 * @param \OCP\Share\IShare $share
96
-	 * @return \OCP\Share\IShare The share object
97
-	 * @throws ShareNotFound
98
-	 * @throws \Exception
99
-	 */
100
-	public function create(\OCP\Share\IShare $share) {
101
-		$qb = $this->dbConn->getQueryBuilder();
102
-
103
-		$qb->insert('share');
104
-		$qb->setValue('share_type', $qb->createNamedParameter($share->getShareType()));
105
-
106
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
107
-			//Set the UID of the user we share with
108
-			$qb->setValue('share_with', $qb->createNamedParameter($share->getSharedWith()));
109
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
110
-			//Set the GID of the group we share with
111
-			$qb->setValue('share_with', $qb->createNamedParameter($share->getSharedWith()));
112
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
113
-			//Set the token of the share
114
-			$qb->setValue('token', $qb->createNamedParameter($share->getToken()));
115
-
116
-			//If a password is set store it
117
-			if ($share->getPassword() !== null) {
118
-				$qb->setValue('password', $qb->createNamedParameter($share->getPassword()));
119
-			}
120
-
121
-			//If an expiration date is set store it
122
-			if ($share->getExpirationDate() !== null) {
123
-				$qb->setValue('expiration', $qb->createNamedParameter($share->getExpirationDate(), 'datetime'));
124
-			}
125
-
126
-			if (method_exists($share, 'getParent')) {
127
-				$qb->setValue('parent', $qb->createNamedParameter($share->getParent()));
128
-			}
129
-		} else {
130
-			throw new \Exception('invalid share type!');
131
-		}
132
-
133
-		// Set what is shares
134
-		$qb->setValue('item_type', $qb->createParameter('itemType'));
135
-		if ($share->getNode() instanceof \OCP\Files\File) {
136
-			$qb->setParameter('itemType', 'file');
137
-		} else {
138
-			$qb->setParameter('itemType', 'folder');
139
-		}
140
-
141
-		// Set the file id
142
-		$qb->setValue('item_source', $qb->createNamedParameter($share->getNode()->getId()));
143
-		$qb->setValue('file_source', $qb->createNamedParameter($share->getNode()->getId()));
144
-
145
-		// set the permissions
146
-		$qb->setValue('permissions', $qb->createNamedParameter($share->getPermissions()));
147
-
148
-		// Set who created this share
149
-		$qb->setValue('uid_initiator', $qb->createNamedParameter($share->getSharedBy()));
150
-
151
-		// Set who is the owner of this file/folder (and this the owner of the share)
152
-		$qb->setValue('uid_owner', $qb->createNamedParameter($share->getShareOwner()));
153
-
154
-		// Set the file target
155
-		$qb->setValue('file_target', $qb->createNamedParameter($share->getTarget()));
156
-
157
-		// Set the time this share was created
158
-		$qb->setValue('stime', $qb->createNamedParameter(time()));
159
-
160
-		// insert the data and fetch the id of the share
161
-		$this->dbConn->beginTransaction();
162
-		$qb->execute();
163
-		$id = $this->dbConn->lastInsertId('*PREFIX*share');
164
-
165
-		// Now fetch the inserted share and create a complete share object
166
-		$qb = $this->dbConn->getQueryBuilder();
167
-		$qb->select('*')
168
-			->from('share')
169
-			->where($qb->expr()->eq('id', $qb->createNamedParameter($id)));
170
-
171
-		$cursor = $qb->execute();
172
-		$data = $cursor->fetch();
173
-		$this->dbConn->commit();
174
-		$cursor->closeCursor();
175
-
176
-		if ($data === false) {
177
-			throw new ShareNotFound();
178
-		}
179
-
180
-		$mailSendValue = $share->getMailSend();
181
-		$data['mail_send'] = ($mailSendValue === null) ? true : $mailSendValue;
182
-
183
-		$share = $this->createShare($data);
184
-		return $share;
185
-	}
186
-
187
-	/**
188
-	 * Update a share
189
-	 *
190
-	 * @param \OCP\Share\IShare $share
191
-	 * @return \OCP\Share\IShare The share object
192
-	 */
193
-	public function update(\OCP\Share\IShare $share) {
194
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
195
-			/*
49
+    // Special share type for user modified group shares
50
+    const SHARE_TYPE_USERGROUP = 2;
51
+
52
+    /** @var IDBConnection */
53
+    private $dbConn;
54
+
55
+    /** @var IUserManager */
56
+    private $userManager;
57
+
58
+    /** @var IGroupManager */
59
+    private $groupManager;
60
+
61
+    /** @var IRootFolder */
62
+    private $rootFolder;
63
+
64
+    /**
65
+     * DefaultShareProvider constructor.
66
+     *
67
+     * @param IDBConnection $connection
68
+     * @param IUserManager $userManager
69
+     * @param IGroupManager $groupManager
70
+     * @param IRootFolder $rootFolder
71
+     */
72
+    public function __construct(
73
+            IDBConnection $connection,
74
+            IUserManager $userManager,
75
+            IGroupManager $groupManager,
76
+            IRootFolder $rootFolder) {
77
+        $this->dbConn = $connection;
78
+        $this->userManager = $userManager;
79
+        $this->groupManager = $groupManager;
80
+        $this->rootFolder = $rootFolder;
81
+    }
82
+
83
+    /**
84
+     * Return the identifier of this provider.
85
+     *
86
+     * @return string Containing only [a-zA-Z0-9]
87
+     */
88
+    public function identifier() {
89
+        return 'ocinternal';
90
+    }
91
+
92
+    /**
93
+     * Share a path
94
+     *
95
+     * @param \OCP\Share\IShare $share
96
+     * @return \OCP\Share\IShare The share object
97
+     * @throws ShareNotFound
98
+     * @throws \Exception
99
+     */
100
+    public function create(\OCP\Share\IShare $share) {
101
+        $qb = $this->dbConn->getQueryBuilder();
102
+
103
+        $qb->insert('share');
104
+        $qb->setValue('share_type', $qb->createNamedParameter($share->getShareType()));
105
+
106
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
107
+            //Set the UID of the user we share with
108
+            $qb->setValue('share_with', $qb->createNamedParameter($share->getSharedWith()));
109
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
110
+            //Set the GID of the group we share with
111
+            $qb->setValue('share_with', $qb->createNamedParameter($share->getSharedWith()));
112
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
113
+            //Set the token of the share
114
+            $qb->setValue('token', $qb->createNamedParameter($share->getToken()));
115
+
116
+            //If a password is set store it
117
+            if ($share->getPassword() !== null) {
118
+                $qb->setValue('password', $qb->createNamedParameter($share->getPassword()));
119
+            }
120
+
121
+            //If an expiration date is set store it
122
+            if ($share->getExpirationDate() !== null) {
123
+                $qb->setValue('expiration', $qb->createNamedParameter($share->getExpirationDate(), 'datetime'));
124
+            }
125
+
126
+            if (method_exists($share, 'getParent')) {
127
+                $qb->setValue('parent', $qb->createNamedParameter($share->getParent()));
128
+            }
129
+        } else {
130
+            throw new \Exception('invalid share type!');
131
+        }
132
+
133
+        // Set what is shares
134
+        $qb->setValue('item_type', $qb->createParameter('itemType'));
135
+        if ($share->getNode() instanceof \OCP\Files\File) {
136
+            $qb->setParameter('itemType', 'file');
137
+        } else {
138
+            $qb->setParameter('itemType', 'folder');
139
+        }
140
+
141
+        // Set the file id
142
+        $qb->setValue('item_source', $qb->createNamedParameter($share->getNode()->getId()));
143
+        $qb->setValue('file_source', $qb->createNamedParameter($share->getNode()->getId()));
144
+
145
+        // set the permissions
146
+        $qb->setValue('permissions', $qb->createNamedParameter($share->getPermissions()));
147
+
148
+        // Set who created this share
149
+        $qb->setValue('uid_initiator', $qb->createNamedParameter($share->getSharedBy()));
150
+
151
+        // Set who is the owner of this file/folder (and this the owner of the share)
152
+        $qb->setValue('uid_owner', $qb->createNamedParameter($share->getShareOwner()));
153
+
154
+        // Set the file target
155
+        $qb->setValue('file_target', $qb->createNamedParameter($share->getTarget()));
156
+
157
+        // Set the time this share was created
158
+        $qb->setValue('stime', $qb->createNamedParameter(time()));
159
+
160
+        // insert the data and fetch the id of the share
161
+        $this->dbConn->beginTransaction();
162
+        $qb->execute();
163
+        $id = $this->dbConn->lastInsertId('*PREFIX*share');
164
+
165
+        // Now fetch the inserted share and create a complete share object
166
+        $qb = $this->dbConn->getQueryBuilder();
167
+        $qb->select('*')
168
+            ->from('share')
169
+            ->where($qb->expr()->eq('id', $qb->createNamedParameter($id)));
170
+
171
+        $cursor = $qb->execute();
172
+        $data = $cursor->fetch();
173
+        $this->dbConn->commit();
174
+        $cursor->closeCursor();
175
+
176
+        if ($data === false) {
177
+            throw new ShareNotFound();
178
+        }
179
+
180
+        $mailSendValue = $share->getMailSend();
181
+        $data['mail_send'] = ($mailSendValue === null) ? true : $mailSendValue;
182
+
183
+        $share = $this->createShare($data);
184
+        return $share;
185
+    }
186
+
187
+    /**
188
+     * Update a share
189
+     *
190
+     * @param \OCP\Share\IShare $share
191
+     * @return \OCP\Share\IShare The share object
192
+     */
193
+    public function update(\OCP\Share\IShare $share) {
194
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
195
+            /*
196 196
 			 * We allow updating the recipient on user shares.
197 197
 			 */
198
-			$qb = $this->dbConn->getQueryBuilder();
199
-			$qb->update('share')
200
-				->where($qb->expr()->eq('id', $qb->createNamedParameter($share->getId())))
201
-				->set('share_with', $qb->createNamedParameter($share->getSharedWith()))
202
-				->set('uid_owner', $qb->createNamedParameter($share->getShareOwner()))
203
-				->set('uid_initiator', $qb->createNamedParameter($share->getSharedBy()))
204
-				->set('permissions', $qb->createNamedParameter($share->getPermissions()))
205
-				->set('item_source', $qb->createNamedParameter($share->getNode()->getId()))
206
-				->set('file_source', $qb->createNamedParameter($share->getNode()->getId()))
207
-				->set('expiration', $qb->createNamedParameter($share->getExpirationDate(), IQueryBuilder::PARAM_DATE))
208
-				->execute();
209
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
210
-			$qb = $this->dbConn->getQueryBuilder();
211
-			$qb->update('share')
212
-				->where($qb->expr()->eq('id', $qb->createNamedParameter($share->getId())))
213
-				->set('uid_owner', $qb->createNamedParameter($share->getShareOwner()))
214
-				->set('uid_initiator', $qb->createNamedParameter($share->getSharedBy()))
215
-				->set('permissions', $qb->createNamedParameter($share->getPermissions()))
216
-				->set('item_source', $qb->createNamedParameter($share->getNode()->getId()))
217
-				->set('file_source', $qb->createNamedParameter($share->getNode()->getId()))
218
-				->set('expiration', $qb->createNamedParameter($share->getExpirationDate(), IQueryBuilder::PARAM_DATE))
219
-				->execute();
220
-
221
-			/*
198
+            $qb = $this->dbConn->getQueryBuilder();
199
+            $qb->update('share')
200
+                ->where($qb->expr()->eq('id', $qb->createNamedParameter($share->getId())))
201
+                ->set('share_with', $qb->createNamedParameter($share->getSharedWith()))
202
+                ->set('uid_owner', $qb->createNamedParameter($share->getShareOwner()))
203
+                ->set('uid_initiator', $qb->createNamedParameter($share->getSharedBy()))
204
+                ->set('permissions', $qb->createNamedParameter($share->getPermissions()))
205
+                ->set('item_source', $qb->createNamedParameter($share->getNode()->getId()))
206
+                ->set('file_source', $qb->createNamedParameter($share->getNode()->getId()))
207
+                ->set('expiration', $qb->createNamedParameter($share->getExpirationDate(), IQueryBuilder::PARAM_DATE))
208
+                ->execute();
209
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
210
+            $qb = $this->dbConn->getQueryBuilder();
211
+            $qb->update('share')
212
+                ->where($qb->expr()->eq('id', $qb->createNamedParameter($share->getId())))
213
+                ->set('uid_owner', $qb->createNamedParameter($share->getShareOwner()))
214
+                ->set('uid_initiator', $qb->createNamedParameter($share->getSharedBy()))
215
+                ->set('permissions', $qb->createNamedParameter($share->getPermissions()))
216
+                ->set('item_source', $qb->createNamedParameter($share->getNode()->getId()))
217
+                ->set('file_source', $qb->createNamedParameter($share->getNode()->getId()))
218
+                ->set('expiration', $qb->createNamedParameter($share->getExpirationDate(), IQueryBuilder::PARAM_DATE))
219
+                ->execute();
220
+
221
+            /*
222 222
 			 * Update all user defined group shares
223 223
 			 */
224
-			$qb = $this->dbConn->getQueryBuilder();
225
-			$qb->update('share')
226
-				->where($qb->expr()->eq('parent', $qb->createNamedParameter($share->getId())))
227
-				->set('uid_owner', $qb->createNamedParameter($share->getShareOwner()))
228
-				->set('uid_initiator', $qb->createNamedParameter($share->getSharedBy()))
229
-				->set('item_source', $qb->createNamedParameter($share->getNode()->getId()))
230
-				->set('file_source', $qb->createNamedParameter($share->getNode()->getId()))
231
-				->set('expiration', $qb->createNamedParameter($share->getExpirationDate(), IQueryBuilder::PARAM_DATE))
232
-				->execute();
233
-
234
-			/*
224
+            $qb = $this->dbConn->getQueryBuilder();
225
+            $qb->update('share')
226
+                ->where($qb->expr()->eq('parent', $qb->createNamedParameter($share->getId())))
227
+                ->set('uid_owner', $qb->createNamedParameter($share->getShareOwner()))
228
+                ->set('uid_initiator', $qb->createNamedParameter($share->getSharedBy()))
229
+                ->set('item_source', $qb->createNamedParameter($share->getNode()->getId()))
230
+                ->set('file_source', $qb->createNamedParameter($share->getNode()->getId()))
231
+                ->set('expiration', $qb->createNamedParameter($share->getExpirationDate(), IQueryBuilder::PARAM_DATE))
232
+                ->execute();
233
+
234
+            /*
235 235
 			 * Now update the permissions for all children that have not set it to 0
236 236
 			 */
237
-			$qb = $this->dbConn->getQueryBuilder();
238
-			$qb->update('share')
239
-				->where($qb->expr()->eq('parent', $qb->createNamedParameter($share->getId())))
240
-				->andWhere($qb->expr()->neq('permissions', $qb->createNamedParameter(0)))
241
-				->set('permissions', $qb->createNamedParameter($share->getPermissions()))
242
-				->execute();
243
-
244
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
245
-			$qb = $this->dbConn->getQueryBuilder();
246
-			$qb->update('share')
247
-				->where($qb->expr()->eq('id', $qb->createNamedParameter($share->getId())))
248
-				->set('password', $qb->createNamedParameter($share->getPassword()))
249
-				->set('uid_owner', $qb->createNamedParameter($share->getShareOwner()))
250
-				->set('uid_initiator', $qb->createNamedParameter($share->getSharedBy()))
251
-				->set('permissions', $qb->createNamedParameter($share->getPermissions()))
252
-				->set('item_source', $qb->createNamedParameter($share->getNode()->getId()))
253
-				->set('file_source', $qb->createNamedParameter($share->getNode()->getId()))
254
-				->set('token', $qb->createNamedParameter($share->getToken()))
255
-				->set('expiration', $qb->createNamedParameter($share->getExpirationDate(), IQueryBuilder::PARAM_DATE))
256
-				->execute();
257
-		}
258
-
259
-		return $share;
260
-	}
261
-
262
-	/**
263
-	 * Get all children of this share
264
-	 * FIXME: remove once https://github.com/owncloud/core/pull/21660 is in
265
-	 *
266
-	 * @param \OCP\Share\IShare $parent
267
-	 * @return \OCP\Share\IShare[]
268
-	 */
269
-	public function getChildren(\OCP\Share\IShare $parent) {
270
-		$children = [];
271
-
272
-		$qb = $this->dbConn->getQueryBuilder();
273
-		$qb->select('*')
274
-			->from('share')
275
-			->where($qb->expr()->eq('parent', $qb->createNamedParameter($parent->getId())))
276
-			->andWhere(
277
-				$qb->expr()->in(
278
-					'share_type',
279
-					$qb->createNamedParameter([
280
-						\OCP\Share::SHARE_TYPE_USER,
281
-						\OCP\Share::SHARE_TYPE_GROUP,
282
-						\OCP\Share::SHARE_TYPE_LINK,
283
-					], IQueryBuilder::PARAM_INT_ARRAY)
284
-				)
285
-			)
286
-			->andWhere($qb->expr()->orX(
287
-				$qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
288
-				$qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
289
-			))
290
-			->orderBy('id');
291
-
292
-		$cursor = $qb->execute();
293
-		while($data = $cursor->fetch()) {
294
-			$children[] = $this->createShare($data);
295
-		}
296
-		$cursor->closeCursor();
297
-
298
-		return $children;
299
-	}
300
-
301
-	/**
302
-	 * Delete a share
303
-	 *
304
-	 * @param \OCP\Share\IShare $share
305
-	 */
306
-	public function delete(\OCP\Share\IShare $share) {
307
-		$qb = $this->dbConn->getQueryBuilder();
308
-		$qb->delete('share')
309
-			->where($qb->expr()->eq('id', $qb->createNamedParameter($share->getId())));
310
-
311
-		/*
237
+            $qb = $this->dbConn->getQueryBuilder();
238
+            $qb->update('share')
239
+                ->where($qb->expr()->eq('parent', $qb->createNamedParameter($share->getId())))
240
+                ->andWhere($qb->expr()->neq('permissions', $qb->createNamedParameter(0)))
241
+                ->set('permissions', $qb->createNamedParameter($share->getPermissions()))
242
+                ->execute();
243
+
244
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
245
+            $qb = $this->dbConn->getQueryBuilder();
246
+            $qb->update('share')
247
+                ->where($qb->expr()->eq('id', $qb->createNamedParameter($share->getId())))
248
+                ->set('password', $qb->createNamedParameter($share->getPassword()))
249
+                ->set('uid_owner', $qb->createNamedParameter($share->getShareOwner()))
250
+                ->set('uid_initiator', $qb->createNamedParameter($share->getSharedBy()))
251
+                ->set('permissions', $qb->createNamedParameter($share->getPermissions()))
252
+                ->set('item_source', $qb->createNamedParameter($share->getNode()->getId()))
253
+                ->set('file_source', $qb->createNamedParameter($share->getNode()->getId()))
254
+                ->set('token', $qb->createNamedParameter($share->getToken()))
255
+                ->set('expiration', $qb->createNamedParameter($share->getExpirationDate(), IQueryBuilder::PARAM_DATE))
256
+                ->execute();
257
+        }
258
+
259
+        return $share;
260
+    }
261
+
262
+    /**
263
+     * Get all children of this share
264
+     * FIXME: remove once https://github.com/owncloud/core/pull/21660 is in
265
+     *
266
+     * @param \OCP\Share\IShare $parent
267
+     * @return \OCP\Share\IShare[]
268
+     */
269
+    public function getChildren(\OCP\Share\IShare $parent) {
270
+        $children = [];
271
+
272
+        $qb = $this->dbConn->getQueryBuilder();
273
+        $qb->select('*')
274
+            ->from('share')
275
+            ->where($qb->expr()->eq('parent', $qb->createNamedParameter($parent->getId())))
276
+            ->andWhere(
277
+                $qb->expr()->in(
278
+                    'share_type',
279
+                    $qb->createNamedParameter([
280
+                        \OCP\Share::SHARE_TYPE_USER,
281
+                        \OCP\Share::SHARE_TYPE_GROUP,
282
+                        \OCP\Share::SHARE_TYPE_LINK,
283
+                    ], IQueryBuilder::PARAM_INT_ARRAY)
284
+                )
285
+            )
286
+            ->andWhere($qb->expr()->orX(
287
+                $qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
288
+                $qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
289
+            ))
290
+            ->orderBy('id');
291
+
292
+        $cursor = $qb->execute();
293
+        while($data = $cursor->fetch()) {
294
+            $children[] = $this->createShare($data);
295
+        }
296
+        $cursor->closeCursor();
297
+
298
+        return $children;
299
+    }
300
+
301
+    /**
302
+     * Delete a share
303
+     *
304
+     * @param \OCP\Share\IShare $share
305
+     */
306
+    public function delete(\OCP\Share\IShare $share) {
307
+        $qb = $this->dbConn->getQueryBuilder();
308
+        $qb->delete('share')
309
+            ->where($qb->expr()->eq('id', $qb->createNamedParameter($share->getId())));
310
+
311
+        /*
312 312
 		 * If the share is a group share delete all possible
313 313
 		 * user defined groups shares.
314 314
 		 */
315
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
316
-			$qb->orWhere($qb->expr()->eq('parent', $qb->createNamedParameter($share->getId())));
317
-		}
318
-
319
-		$qb->execute();
320
-	}
321
-
322
-	/**
323
-	 * Unshare a share from the recipient. If this is a group share
324
-	 * this means we need a special entry in the share db.
325
-	 *
326
-	 * @param \OCP\Share\IShare $share
327
-	 * @param string $recipient UserId of recipient
328
-	 * @throws BackendError
329
-	 * @throws ProviderException
330
-	 */
331
-	public function deleteFromSelf(\OCP\Share\IShare $share, $recipient) {
332
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
333
-
334
-			$group = $this->groupManager->get($share->getSharedWith());
335
-			$user = $this->userManager->get($recipient);
336
-
337
-			if (is_null($group)) {
338
-				throw new ProviderException('Group "' . $share->getSharedWith() . '" does not exist');
339
-			}
340
-
341
-			if (!$group->inGroup($user)) {
342
-				throw new ProviderException('Recipient not in receiving group');
343
-			}
344
-
345
-			// Try to fetch user specific share
346
-			$qb = $this->dbConn->getQueryBuilder();
347
-			$stmt = $qb->select('*')
348
-				->from('share')
349
-				->where($qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP)))
350
-				->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($recipient)))
351
-				->andWhere($qb->expr()->eq('parent', $qb->createNamedParameter($share->getId())))
352
-				->andWhere($qb->expr()->orX(
353
-					$qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
354
-					$qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
355
-				))
356
-				->execute();
357
-
358
-			$data = $stmt->fetch();
359
-
360
-			/*
315
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
316
+            $qb->orWhere($qb->expr()->eq('parent', $qb->createNamedParameter($share->getId())));
317
+        }
318
+
319
+        $qb->execute();
320
+    }
321
+
322
+    /**
323
+     * Unshare a share from the recipient. If this is a group share
324
+     * this means we need a special entry in the share db.
325
+     *
326
+     * @param \OCP\Share\IShare $share
327
+     * @param string $recipient UserId of recipient
328
+     * @throws BackendError
329
+     * @throws ProviderException
330
+     */
331
+    public function deleteFromSelf(\OCP\Share\IShare $share, $recipient) {
332
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
333
+
334
+            $group = $this->groupManager->get($share->getSharedWith());
335
+            $user = $this->userManager->get($recipient);
336
+
337
+            if (is_null($group)) {
338
+                throw new ProviderException('Group "' . $share->getSharedWith() . '" does not exist');
339
+            }
340
+
341
+            if (!$group->inGroup($user)) {
342
+                throw new ProviderException('Recipient not in receiving group');
343
+            }
344
+
345
+            // Try to fetch user specific share
346
+            $qb = $this->dbConn->getQueryBuilder();
347
+            $stmt = $qb->select('*')
348
+                ->from('share')
349
+                ->where($qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP)))
350
+                ->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($recipient)))
351
+                ->andWhere($qb->expr()->eq('parent', $qb->createNamedParameter($share->getId())))
352
+                ->andWhere($qb->expr()->orX(
353
+                    $qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
354
+                    $qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
355
+                ))
356
+                ->execute();
357
+
358
+            $data = $stmt->fetch();
359
+
360
+            /*
361 361
 			 * Check if there already is a user specific group share.
362 362
 			 * If there is update it (if required).
363 363
 			 */
364
-			if ($data === false) {
365
-				$qb = $this->dbConn->getQueryBuilder();
366
-
367
-				$type = $share->getNodeType();
368
-
369
-				//Insert new share
370
-				$qb->insert('share')
371
-					->values([
372
-						'share_type' => $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP),
373
-						'share_with' => $qb->createNamedParameter($recipient),
374
-						'uid_owner' => $qb->createNamedParameter($share->getShareOwner()),
375
-						'uid_initiator' => $qb->createNamedParameter($share->getSharedBy()),
376
-						'parent' => $qb->createNamedParameter($share->getId()),
377
-						'item_type' => $qb->createNamedParameter($type),
378
-						'item_source' => $qb->createNamedParameter($share->getNodeId()),
379
-						'file_source' => $qb->createNamedParameter($share->getNodeId()),
380
-						'file_target' => $qb->createNamedParameter($share->getTarget()),
381
-						'permissions' => $qb->createNamedParameter(0),
382
-						'stime' => $qb->createNamedParameter($share->getShareTime()->getTimestamp()),
383
-					])->execute();
384
-
385
-			} else if ($data['permissions'] !== 0) {
386
-
387
-				// Update existing usergroup share
388
-				$qb = $this->dbConn->getQueryBuilder();
389
-				$qb->update('share')
390
-					->set('permissions', $qb->createNamedParameter(0))
391
-					->where($qb->expr()->eq('id', $qb->createNamedParameter($data['id'])))
392
-					->execute();
393
-			}
394
-
395
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
396
-
397
-			if ($share->getSharedWith() !== $recipient) {
398
-				throw new ProviderException('Recipient does not match');
399
-			}
400
-
401
-			// We can just delete user and link shares
402
-			$this->delete($share);
403
-		} else {
404
-			throw new ProviderException('Invalid shareType');
405
-		}
406
-	}
407
-
408
-	/**
409
-	 * @inheritdoc
410
-	 */
411
-	public function move(\OCP\Share\IShare $share, $recipient) {
412
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
413
-			// Just update the target
414
-			$qb = $this->dbConn->getQueryBuilder();
415
-			$qb->update('share')
416
-				->set('file_target', $qb->createNamedParameter($share->getTarget()))
417
-				->where($qb->expr()->eq('id', $qb->createNamedParameter($share->getId())))
418
-				->execute();
419
-
420
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
421
-
422
-			// Check if there is a usergroup share
423
-			$qb = $this->dbConn->getQueryBuilder();
424
-			$stmt = $qb->select('id')
425
-				->from('share')
426
-				->where($qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP)))
427
-				->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($recipient)))
428
-				->andWhere($qb->expr()->eq('parent', $qb->createNamedParameter($share->getId())))
429
-				->andWhere($qb->expr()->orX(
430
-					$qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
431
-					$qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
432
-				))
433
-				->setMaxResults(1)
434
-				->execute();
435
-
436
-			$data = $stmt->fetch();
437
-			$stmt->closeCursor();
438
-
439
-			if ($data === false) {
440
-				// No usergroup share yet. Create one.
441
-				$qb = $this->dbConn->getQueryBuilder();
442
-				$qb->insert('share')
443
-					->values([
444
-						'share_type' => $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP),
445
-						'share_with' => $qb->createNamedParameter($recipient),
446
-						'uid_owner' => $qb->createNamedParameter($share->getShareOwner()),
447
-						'uid_initiator' => $qb->createNamedParameter($share->getSharedBy()),
448
-						'parent' => $qb->createNamedParameter($share->getId()),
449
-						'item_type' => $qb->createNamedParameter($share->getNode() instanceof File ? 'file' : 'folder'),
450
-						'item_source' => $qb->createNamedParameter($share->getNode()->getId()),
451
-						'file_source' => $qb->createNamedParameter($share->getNode()->getId()),
452
-						'file_target' => $qb->createNamedParameter($share->getTarget()),
453
-						'permissions' => $qb->createNamedParameter($share->getPermissions()),
454
-						'stime' => $qb->createNamedParameter($share->getShareTime()->getTimestamp()),
455
-					])->execute();
456
-			} else {
457
-				// Already a usergroup share. Update it.
458
-				$qb = $this->dbConn->getQueryBuilder();
459
-				$qb->update('share')
460
-					->set('file_target', $qb->createNamedParameter($share->getTarget()))
461
-					->where($qb->expr()->eq('id', $qb->createNamedParameter($data['id'])))
462
-					->execute();
463
-			}
464
-		}
465
-
466
-		return $share;
467
-	}
468
-
469
-	public function getSharesInFolder($userId, Folder $node, $reshares) {
470
-		$qb = $this->dbConn->getQueryBuilder();
471
-		$qb->select('*')
472
-			->from('share', 's')
473
-			->andWhere($qb->expr()->orX(
474
-				$qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
475
-				$qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
476
-			));
477
-
478
-		$qb->andWhere($qb->expr()->orX(
479
-			$qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_USER)),
480
-			$qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_GROUP)),
481
-			$qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_LINK))
482
-		));
483
-
484
-		/**
485
-		 * Reshares for this user are shares where they are the owner.
486
-		 */
487
-		if ($reshares === false) {
488
-			$qb->andWhere($qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId)));
489
-		} else {
490
-			$qb->andWhere(
491
-				$qb->expr()->orX(
492
-					$qb->expr()->eq('uid_owner', $qb->createNamedParameter($userId)),
493
-					$qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId))
494
-				)
495
-			);
496
-		}
497
-
498
-		$qb->innerJoin('s', 'filecache' ,'f', $qb->expr()->eq('s.file_source', 'f.fileid'));
499
-		$qb->andWhere($qb->expr()->eq('f.parent', $qb->createNamedParameter($node->getId())));
500
-
501
-		$qb->orderBy('id');
502
-
503
-		$cursor = $qb->execute();
504
-		$shares = [];
505
-		while ($data = $cursor->fetch()) {
506
-			$shares[$data['fileid']][] = $this->createShare($data);
507
-		}
508
-		$cursor->closeCursor();
509
-
510
-		return $shares;
511
-	}
512
-
513
-	/**
514
-	 * @inheritdoc
515
-	 */
516
-	public function getSharesBy($userId, $shareType, $node, $reshares, $limit, $offset) {
517
-		$qb = $this->dbConn->getQueryBuilder();
518
-		$qb->select('*')
519
-			->from('share')
520
-			->andWhere($qb->expr()->orX(
521
-				$qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
522
-				$qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
523
-			));
524
-
525
-		$qb->andWhere($qb->expr()->eq('share_type', $qb->createNamedParameter($shareType)));
526
-
527
-		/**
528
-		 * Reshares for this user are shares where they are the owner.
529
-		 */
530
-		if ($reshares === false) {
531
-			$qb->andWhere($qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId)));
532
-		} else {
533
-			$qb->andWhere(
534
-				$qb->expr()->orX(
535
-					$qb->expr()->eq('uid_owner', $qb->createNamedParameter($userId)),
536
-					$qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId))
537
-				)
538
-			);
539
-		}
540
-
541
-		if ($node !== null) {
542
-			$qb->andWhere($qb->expr()->eq('file_source', $qb->createNamedParameter($node->getId())));
543
-		}
544
-
545
-		if ($limit !== -1) {
546
-			$qb->setMaxResults($limit);
547
-		}
548
-
549
-		$qb->setFirstResult($offset);
550
-		$qb->orderBy('id');
551
-
552
-		$cursor = $qb->execute();
553
-		$shares = [];
554
-		while($data = $cursor->fetch()) {
555
-			$shares[] = $this->createShare($data);
556
-		}
557
-		$cursor->closeCursor();
558
-
559
-		return $shares;
560
-	}
561
-
562
-	/**
563
-	 * @inheritdoc
564
-	 */
565
-	public function getShareById($id, $recipientId = null) {
566
-		$qb = $this->dbConn->getQueryBuilder();
567
-
568
-		$qb->select('*')
569
-			->from('share')
570
-			->where($qb->expr()->eq('id', $qb->createNamedParameter($id)))
571
-			->andWhere(
572
-				$qb->expr()->in(
573
-					'share_type',
574
-					$qb->createNamedParameter([
575
-						\OCP\Share::SHARE_TYPE_USER,
576
-						\OCP\Share::SHARE_TYPE_GROUP,
577
-						\OCP\Share::SHARE_TYPE_LINK,
578
-					], IQueryBuilder::PARAM_INT_ARRAY)
579
-				)
580
-			)
581
-			->andWhere($qb->expr()->orX(
582
-				$qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
583
-				$qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
584
-			));
585
-
586
-		$cursor = $qb->execute();
587
-		$data = $cursor->fetch();
588
-		$cursor->closeCursor();
589
-
590
-		if ($data === false) {
591
-			throw new ShareNotFound();
592
-		}
593
-
594
-		try {
595
-			$share = $this->createShare($data);
596
-		} catch (InvalidShare $e) {
597
-			throw new ShareNotFound();
598
-		}
599
-
600
-		// If the recipient is set for a group share resolve to that user
601
-		if ($recipientId !== null && $share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
602
-			$share = $this->resolveGroupShares([$share], $recipientId)[0];
603
-		}
604
-
605
-		return $share;
606
-	}
607
-
608
-	/**
609
-	 * Get shares for a given path
610
-	 *
611
-	 * @param \OCP\Files\Node $path
612
-	 * @return \OCP\Share\IShare[]
613
-	 */
614
-	public function getSharesByPath(Node $path) {
615
-		$qb = $this->dbConn->getQueryBuilder();
616
-
617
-		$cursor = $qb->select('*')
618
-			->from('share')
619
-			->andWhere($qb->expr()->eq('file_source', $qb->createNamedParameter($path->getId())))
620
-			->andWhere(
621
-				$qb->expr()->orX(
622
-					$qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_USER)),
623
-					$qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_GROUP))
624
-				)
625
-			)
626
-			->andWhere($qb->expr()->orX(
627
-				$qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
628
-				$qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
629
-			))
630
-			->execute();
631
-
632
-		$shares = [];
633
-		while($data = $cursor->fetch()) {
634
-			$shares[] = $this->createShare($data);
635
-		}
636
-		$cursor->closeCursor();
637
-
638
-		return $shares;
639
-	}
640
-
641
-	/**
642
-	 * Returns whether the given database result can be interpreted as
643
-	 * a share with accessible file (not trashed, not deleted)
644
-	 */
645
-	private function isAccessibleResult($data) {
646
-		// exclude shares leading to deleted file entries
647
-		if ($data['fileid'] === null) {
648
-			return false;
649
-		}
650
-
651
-		// exclude shares leading to trashbin on home storages
652
-		$pathSections = explode('/', $data['path'], 2);
653
-		// FIXME: would not detect rare md5'd home storage case properly
654
-		if ($pathSections[0] !== 'files'
655
-		    	&& in_array(explode(':', $data['storage_string_id'], 2)[0], array('home', 'object'))) {
656
-			return false;
657
-		}
658
-		return true;
659
-	}
660
-
661
-	/**
662
-	 * @inheritdoc
663
-	 */
664
-	public function getSharedWith($userId, $shareType, $node, $limit, $offset) {
665
-		/** @var Share[] $shares */
666
-		$shares = [];
667
-
668
-		if ($shareType === \OCP\Share::SHARE_TYPE_USER) {
669
-			//Get shares directly with this user
670
-			$qb = $this->dbConn->getQueryBuilder();
671
-			$qb->select('s.*',
672
-				'f.fileid', 'f.path', 'f.permissions AS f_permissions', 'f.storage', 'f.path_hash',
673
-				'f.parent AS f_parent', 'f.name', 'f.mimetype', 'f.mimepart', 'f.size', 'f.mtime', 'f.storage_mtime',
674
-				'f.encrypted', 'f.unencrypted_size', 'f.etag', 'f.checksum'
675
-			)
676
-				->selectAlias('st.id', 'storage_string_id')
677
-				->from('share', 's')
678
-				->leftJoin('s', 'filecache', 'f', $qb->expr()->eq('s.file_source', 'f.fileid'))
679
-				->leftJoin('f', 'storages', 'st', $qb->expr()->eq('f.storage', 'st.numeric_id'));
680
-
681
-			// Order by id
682
-			$qb->orderBy('s.id');
683
-
684
-			// Set limit and offset
685
-			if ($limit !== -1) {
686
-				$qb->setMaxResults($limit);
687
-			}
688
-			$qb->setFirstResult($offset);
689
-
690
-			$qb->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_USER)))
691
-				->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($userId)))
692
-				->andWhere($qb->expr()->orX(
693
-					$qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
694
-					$qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
695
-				));
696
-
697
-			// Filter by node if provided
698
-			if ($node !== null) {
699
-				$qb->andWhere($qb->expr()->eq('file_source', $qb->createNamedParameter($node->getId())));
700
-			}
701
-
702
-			$cursor = $qb->execute();
703
-
704
-			while($data = $cursor->fetch()) {
705
-				if ($this->isAccessibleResult($data)) {
706
-					$shares[] = $this->createShare($data);
707
-				}
708
-			}
709
-			$cursor->closeCursor();
710
-
711
-		} else if ($shareType === \OCP\Share::SHARE_TYPE_GROUP) {
712
-			$user = $this->userManager->get($userId);
713
-			$allGroups = $this->groupManager->getUserGroups($user);
714
-
715
-			/** @var Share[] $shares2 */
716
-			$shares2 = [];
717
-
718
-			$start = 0;
719
-			while(true) {
720
-				$groups = array_slice($allGroups, $start, 100);
721
-				$start += 100;
722
-
723
-				if ($groups === []) {
724
-					break;
725
-				}
726
-
727
-				$qb = $this->dbConn->getQueryBuilder();
728
-				$qb->select('s.*',
729
-					'f.fileid', 'f.path', 'f.permissions AS f_permissions', 'f.storage', 'f.path_hash',
730
-					'f.parent AS f_parent', 'f.name', 'f.mimetype', 'f.mimepart', 'f.size', 'f.mtime', 'f.storage_mtime',
731
-					'f.encrypted', 'f.unencrypted_size', 'f.etag', 'f.checksum'
732
-				)
733
-					->selectAlias('st.id', 'storage_string_id')
734
-					->from('share', 's')
735
-					->leftJoin('s', 'filecache', 'f', $qb->expr()->eq('s.file_source', 'f.fileid'))
736
-					->leftJoin('f', 'storages', 'st', $qb->expr()->eq('f.storage', 'st.numeric_id'))
737
-					->orderBy('s.id')
738
-					->setFirstResult(0);
739
-
740
-				if ($limit !== -1) {
741
-					$qb->setMaxResults($limit - count($shares));
742
-				}
743
-
744
-				// Filter by node if provided
745
-				if ($node !== null) {
746
-					$qb->andWhere($qb->expr()->eq('file_source', $qb->createNamedParameter($node->getId())));
747
-				}
748
-
749
-
750
-				$groups = array_filter($groups, function($group) { return $group instanceof IGroup; });
751
-				$groups = array_map(function(IGroup $group) { return $group->getGID(); }, $groups);
752
-
753
-				$qb->andWhere($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_GROUP)))
754
-					->andWhere($qb->expr()->in('share_with', $qb->createNamedParameter(
755
-						$groups,
756
-						IQueryBuilder::PARAM_STR_ARRAY
757
-					)))
758
-					->andWhere($qb->expr()->orX(
759
-						$qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
760
-						$qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
761
-					));
762
-
763
-				$cursor = $qb->execute();
764
-				while($data = $cursor->fetch()) {
765
-					if ($offset > 0) {
766
-						$offset--;
767
-						continue;
768
-					}
769
-
770
-					if ($this->isAccessibleResult($data)) {
771
-						$shares2[] = $this->createShare($data);
772
-					}
773
-				}
774
-				$cursor->closeCursor();
775
-			}
776
-
777
-			/*
364
+            if ($data === false) {
365
+                $qb = $this->dbConn->getQueryBuilder();
366
+
367
+                $type = $share->getNodeType();
368
+
369
+                //Insert new share
370
+                $qb->insert('share')
371
+                    ->values([
372
+                        'share_type' => $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP),
373
+                        'share_with' => $qb->createNamedParameter($recipient),
374
+                        'uid_owner' => $qb->createNamedParameter($share->getShareOwner()),
375
+                        'uid_initiator' => $qb->createNamedParameter($share->getSharedBy()),
376
+                        'parent' => $qb->createNamedParameter($share->getId()),
377
+                        'item_type' => $qb->createNamedParameter($type),
378
+                        'item_source' => $qb->createNamedParameter($share->getNodeId()),
379
+                        'file_source' => $qb->createNamedParameter($share->getNodeId()),
380
+                        'file_target' => $qb->createNamedParameter($share->getTarget()),
381
+                        'permissions' => $qb->createNamedParameter(0),
382
+                        'stime' => $qb->createNamedParameter($share->getShareTime()->getTimestamp()),
383
+                    ])->execute();
384
+
385
+            } else if ($data['permissions'] !== 0) {
386
+
387
+                // Update existing usergroup share
388
+                $qb = $this->dbConn->getQueryBuilder();
389
+                $qb->update('share')
390
+                    ->set('permissions', $qb->createNamedParameter(0))
391
+                    ->where($qb->expr()->eq('id', $qb->createNamedParameter($data['id'])))
392
+                    ->execute();
393
+            }
394
+
395
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
396
+
397
+            if ($share->getSharedWith() !== $recipient) {
398
+                throw new ProviderException('Recipient does not match');
399
+            }
400
+
401
+            // We can just delete user and link shares
402
+            $this->delete($share);
403
+        } else {
404
+            throw new ProviderException('Invalid shareType');
405
+        }
406
+    }
407
+
408
+    /**
409
+     * @inheritdoc
410
+     */
411
+    public function move(\OCP\Share\IShare $share, $recipient) {
412
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
413
+            // Just update the target
414
+            $qb = $this->dbConn->getQueryBuilder();
415
+            $qb->update('share')
416
+                ->set('file_target', $qb->createNamedParameter($share->getTarget()))
417
+                ->where($qb->expr()->eq('id', $qb->createNamedParameter($share->getId())))
418
+                ->execute();
419
+
420
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
421
+
422
+            // Check if there is a usergroup share
423
+            $qb = $this->dbConn->getQueryBuilder();
424
+            $stmt = $qb->select('id')
425
+                ->from('share')
426
+                ->where($qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP)))
427
+                ->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($recipient)))
428
+                ->andWhere($qb->expr()->eq('parent', $qb->createNamedParameter($share->getId())))
429
+                ->andWhere($qb->expr()->orX(
430
+                    $qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
431
+                    $qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
432
+                ))
433
+                ->setMaxResults(1)
434
+                ->execute();
435
+
436
+            $data = $stmt->fetch();
437
+            $stmt->closeCursor();
438
+
439
+            if ($data === false) {
440
+                // No usergroup share yet. Create one.
441
+                $qb = $this->dbConn->getQueryBuilder();
442
+                $qb->insert('share')
443
+                    ->values([
444
+                        'share_type' => $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP),
445
+                        'share_with' => $qb->createNamedParameter($recipient),
446
+                        'uid_owner' => $qb->createNamedParameter($share->getShareOwner()),
447
+                        'uid_initiator' => $qb->createNamedParameter($share->getSharedBy()),
448
+                        'parent' => $qb->createNamedParameter($share->getId()),
449
+                        'item_type' => $qb->createNamedParameter($share->getNode() instanceof File ? 'file' : 'folder'),
450
+                        'item_source' => $qb->createNamedParameter($share->getNode()->getId()),
451
+                        'file_source' => $qb->createNamedParameter($share->getNode()->getId()),
452
+                        'file_target' => $qb->createNamedParameter($share->getTarget()),
453
+                        'permissions' => $qb->createNamedParameter($share->getPermissions()),
454
+                        'stime' => $qb->createNamedParameter($share->getShareTime()->getTimestamp()),
455
+                    ])->execute();
456
+            } else {
457
+                // Already a usergroup share. Update it.
458
+                $qb = $this->dbConn->getQueryBuilder();
459
+                $qb->update('share')
460
+                    ->set('file_target', $qb->createNamedParameter($share->getTarget()))
461
+                    ->where($qb->expr()->eq('id', $qb->createNamedParameter($data['id'])))
462
+                    ->execute();
463
+            }
464
+        }
465
+
466
+        return $share;
467
+    }
468
+
469
+    public function getSharesInFolder($userId, Folder $node, $reshares) {
470
+        $qb = $this->dbConn->getQueryBuilder();
471
+        $qb->select('*')
472
+            ->from('share', 's')
473
+            ->andWhere($qb->expr()->orX(
474
+                $qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
475
+                $qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
476
+            ));
477
+
478
+        $qb->andWhere($qb->expr()->orX(
479
+            $qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_USER)),
480
+            $qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_GROUP)),
481
+            $qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_LINK))
482
+        ));
483
+
484
+        /**
485
+         * Reshares for this user are shares where they are the owner.
486
+         */
487
+        if ($reshares === false) {
488
+            $qb->andWhere($qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId)));
489
+        } else {
490
+            $qb->andWhere(
491
+                $qb->expr()->orX(
492
+                    $qb->expr()->eq('uid_owner', $qb->createNamedParameter($userId)),
493
+                    $qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId))
494
+                )
495
+            );
496
+        }
497
+
498
+        $qb->innerJoin('s', 'filecache' ,'f', $qb->expr()->eq('s.file_source', 'f.fileid'));
499
+        $qb->andWhere($qb->expr()->eq('f.parent', $qb->createNamedParameter($node->getId())));
500
+
501
+        $qb->orderBy('id');
502
+
503
+        $cursor = $qb->execute();
504
+        $shares = [];
505
+        while ($data = $cursor->fetch()) {
506
+            $shares[$data['fileid']][] = $this->createShare($data);
507
+        }
508
+        $cursor->closeCursor();
509
+
510
+        return $shares;
511
+    }
512
+
513
+    /**
514
+     * @inheritdoc
515
+     */
516
+    public function getSharesBy($userId, $shareType, $node, $reshares, $limit, $offset) {
517
+        $qb = $this->dbConn->getQueryBuilder();
518
+        $qb->select('*')
519
+            ->from('share')
520
+            ->andWhere($qb->expr()->orX(
521
+                $qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
522
+                $qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
523
+            ));
524
+
525
+        $qb->andWhere($qb->expr()->eq('share_type', $qb->createNamedParameter($shareType)));
526
+
527
+        /**
528
+         * Reshares for this user are shares where they are the owner.
529
+         */
530
+        if ($reshares === false) {
531
+            $qb->andWhere($qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId)));
532
+        } else {
533
+            $qb->andWhere(
534
+                $qb->expr()->orX(
535
+                    $qb->expr()->eq('uid_owner', $qb->createNamedParameter($userId)),
536
+                    $qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId))
537
+                )
538
+            );
539
+        }
540
+
541
+        if ($node !== null) {
542
+            $qb->andWhere($qb->expr()->eq('file_source', $qb->createNamedParameter($node->getId())));
543
+        }
544
+
545
+        if ($limit !== -1) {
546
+            $qb->setMaxResults($limit);
547
+        }
548
+
549
+        $qb->setFirstResult($offset);
550
+        $qb->orderBy('id');
551
+
552
+        $cursor = $qb->execute();
553
+        $shares = [];
554
+        while($data = $cursor->fetch()) {
555
+            $shares[] = $this->createShare($data);
556
+        }
557
+        $cursor->closeCursor();
558
+
559
+        return $shares;
560
+    }
561
+
562
+    /**
563
+     * @inheritdoc
564
+     */
565
+    public function getShareById($id, $recipientId = null) {
566
+        $qb = $this->dbConn->getQueryBuilder();
567
+
568
+        $qb->select('*')
569
+            ->from('share')
570
+            ->where($qb->expr()->eq('id', $qb->createNamedParameter($id)))
571
+            ->andWhere(
572
+                $qb->expr()->in(
573
+                    'share_type',
574
+                    $qb->createNamedParameter([
575
+                        \OCP\Share::SHARE_TYPE_USER,
576
+                        \OCP\Share::SHARE_TYPE_GROUP,
577
+                        \OCP\Share::SHARE_TYPE_LINK,
578
+                    ], IQueryBuilder::PARAM_INT_ARRAY)
579
+                )
580
+            )
581
+            ->andWhere($qb->expr()->orX(
582
+                $qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
583
+                $qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
584
+            ));
585
+
586
+        $cursor = $qb->execute();
587
+        $data = $cursor->fetch();
588
+        $cursor->closeCursor();
589
+
590
+        if ($data === false) {
591
+            throw new ShareNotFound();
592
+        }
593
+
594
+        try {
595
+            $share = $this->createShare($data);
596
+        } catch (InvalidShare $e) {
597
+            throw new ShareNotFound();
598
+        }
599
+
600
+        // If the recipient is set for a group share resolve to that user
601
+        if ($recipientId !== null && $share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
602
+            $share = $this->resolveGroupShares([$share], $recipientId)[0];
603
+        }
604
+
605
+        return $share;
606
+    }
607
+
608
+    /**
609
+     * Get shares for a given path
610
+     *
611
+     * @param \OCP\Files\Node $path
612
+     * @return \OCP\Share\IShare[]
613
+     */
614
+    public function getSharesByPath(Node $path) {
615
+        $qb = $this->dbConn->getQueryBuilder();
616
+
617
+        $cursor = $qb->select('*')
618
+            ->from('share')
619
+            ->andWhere($qb->expr()->eq('file_source', $qb->createNamedParameter($path->getId())))
620
+            ->andWhere(
621
+                $qb->expr()->orX(
622
+                    $qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_USER)),
623
+                    $qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_GROUP))
624
+                )
625
+            )
626
+            ->andWhere($qb->expr()->orX(
627
+                $qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
628
+                $qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
629
+            ))
630
+            ->execute();
631
+
632
+        $shares = [];
633
+        while($data = $cursor->fetch()) {
634
+            $shares[] = $this->createShare($data);
635
+        }
636
+        $cursor->closeCursor();
637
+
638
+        return $shares;
639
+    }
640
+
641
+    /**
642
+     * Returns whether the given database result can be interpreted as
643
+     * a share with accessible file (not trashed, not deleted)
644
+     */
645
+    private function isAccessibleResult($data) {
646
+        // exclude shares leading to deleted file entries
647
+        if ($data['fileid'] === null) {
648
+            return false;
649
+        }
650
+
651
+        // exclude shares leading to trashbin on home storages
652
+        $pathSections = explode('/', $data['path'], 2);
653
+        // FIXME: would not detect rare md5'd home storage case properly
654
+        if ($pathSections[0] !== 'files'
655
+                && in_array(explode(':', $data['storage_string_id'], 2)[0], array('home', 'object'))) {
656
+            return false;
657
+        }
658
+        return true;
659
+    }
660
+
661
+    /**
662
+     * @inheritdoc
663
+     */
664
+    public function getSharedWith($userId, $shareType, $node, $limit, $offset) {
665
+        /** @var Share[] $shares */
666
+        $shares = [];
667
+
668
+        if ($shareType === \OCP\Share::SHARE_TYPE_USER) {
669
+            //Get shares directly with this user
670
+            $qb = $this->dbConn->getQueryBuilder();
671
+            $qb->select('s.*',
672
+                'f.fileid', 'f.path', 'f.permissions AS f_permissions', 'f.storage', 'f.path_hash',
673
+                'f.parent AS f_parent', 'f.name', 'f.mimetype', 'f.mimepart', 'f.size', 'f.mtime', 'f.storage_mtime',
674
+                'f.encrypted', 'f.unencrypted_size', 'f.etag', 'f.checksum'
675
+            )
676
+                ->selectAlias('st.id', 'storage_string_id')
677
+                ->from('share', 's')
678
+                ->leftJoin('s', 'filecache', 'f', $qb->expr()->eq('s.file_source', 'f.fileid'))
679
+                ->leftJoin('f', 'storages', 'st', $qb->expr()->eq('f.storage', 'st.numeric_id'));
680
+
681
+            // Order by id
682
+            $qb->orderBy('s.id');
683
+
684
+            // Set limit and offset
685
+            if ($limit !== -1) {
686
+                $qb->setMaxResults($limit);
687
+            }
688
+            $qb->setFirstResult($offset);
689
+
690
+            $qb->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_USER)))
691
+                ->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($userId)))
692
+                ->andWhere($qb->expr()->orX(
693
+                    $qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
694
+                    $qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
695
+                ));
696
+
697
+            // Filter by node if provided
698
+            if ($node !== null) {
699
+                $qb->andWhere($qb->expr()->eq('file_source', $qb->createNamedParameter($node->getId())));
700
+            }
701
+
702
+            $cursor = $qb->execute();
703
+
704
+            while($data = $cursor->fetch()) {
705
+                if ($this->isAccessibleResult($data)) {
706
+                    $shares[] = $this->createShare($data);
707
+                }
708
+            }
709
+            $cursor->closeCursor();
710
+
711
+        } else if ($shareType === \OCP\Share::SHARE_TYPE_GROUP) {
712
+            $user = $this->userManager->get($userId);
713
+            $allGroups = $this->groupManager->getUserGroups($user);
714
+
715
+            /** @var Share[] $shares2 */
716
+            $shares2 = [];
717
+
718
+            $start = 0;
719
+            while(true) {
720
+                $groups = array_slice($allGroups, $start, 100);
721
+                $start += 100;
722
+
723
+                if ($groups === []) {
724
+                    break;
725
+                }
726
+
727
+                $qb = $this->dbConn->getQueryBuilder();
728
+                $qb->select('s.*',
729
+                    'f.fileid', 'f.path', 'f.permissions AS f_permissions', 'f.storage', 'f.path_hash',
730
+                    'f.parent AS f_parent', 'f.name', 'f.mimetype', 'f.mimepart', 'f.size', 'f.mtime', 'f.storage_mtime',
731
+                    'f.encrypted', 'f.unencrypted_size', 'f.etag', 'f.checksum'
732
+                )
733
+                    ->selectAlias('st.id', 'storage_string_id')
734
+                    ->from('share', 's')
735
+                    ->leftJoin('s', 'filecache', 'f', $qb->expr()->eq('s.file_source', 'f.fileid'))
736
+                    ->leftJoin('f', 'storages', 'st', $qb->expr()->eq('f.storage', 'st.numeric_id'))
737
+                    ->orderBy('s.id')
738
+                    ->setFirstResult(0);
739
+
740
+                if ($limit !== -1) {
741
+                    $qb->setMaxResults($limit - count($shares));
742
+                }
743
+
744
+                // Filter by node if provided
745
+                if ($node !== null) {
746
+                    $qb->andWhere($qb->expr()->eq('file_source', $qb->createNamedParameter($node->getId())));
747
+                }
748
+
749
+
750
+                $groups = array_filter($groups, function($group) { return $group instanceof IGroup; });
751
+                $groups = array_map(function(IGroup $group) { return $group->getGID(); }, $groups);
752
+
753
+                $qb->andWhere($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_GROUP)))
754
+                    ->andWhere($qb->expr()->in('share_with', $qb->createNamedParameter(
755
+                        $groups,
756
+                        IQueryBuilder::PARAM_STR_ARRAY
757
+                    )))
758
+                    ->andWhere($qb->expr()->orX(
759
+                        $qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
760
+                        $qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
761
+                    ));
762
+
763
+                $cursor = $qb->execute();
764
+                while($data = $cursor->fetch()) {
765
+                    if ($offset > 0) {
766
+                        $offset--;
767
+                        continue;
768
+                    }
769
+
770
+                    if ($this->isAccessibleResult($data)) {
771
+                        $shares2[] = $this->createShare($data);
772
+                    }
773
+                }
774
+                $cursor->closeCursor();
775
+            }
776
+
777
+            /*
778 778
  			 * Resolve all group shares to user specific shares
779 779
  			 */
780
-			$shares = $this->resolveGroupShares($shares2, $userId);
781
-		} else {
782
-			throw new BackendError('Invalid backend');
783
-		}
784
-
785
-
786
-		return $shares;
787
-	}
788
-
789
-	/**
790
-	 * Get a share by token
791
-	 *
792
-	 * @param string $token
793
-	 * @return \OCP\Share\IShare
794
-	 * @throws ShareNotFound
795
-	 */
796
-	public function getShareByToken($token) {
797
-		$qb = $this->dbConn->getQueryBuilder();
798
-
799
-		$cursor = $qb->select('*')
800
-			->from('share')
801
-			->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_LINK)))
802
-			->andWhere($qb->expr()->eq('token', $qb->createNamedParameter($token)))
803
-			->andWhere($qb->expr()->orX(
804
-				$qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
805
-				$qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
806
-			))
807
-			->execute();
808
-
809
-		$data = $cursor->fetch();
810
-
811
-		if ($data === false) {
812
-			throw new ShareNotFound();
813
-		}
814
-
815
-		try {
816
-			$share = $this->createShare($data);
817
-		} catch (InvalidShare $e) {
818
-			throw new ShareNotFound();
819
-		}
820
-
821
-		return $share;
822
-	}
823
-
824
-	/**
825
-	 * Create a share object from an database row
826
-	 *
827
-	 * @param mixed[] $data
828
-	 * @return \OCP\Share\IShare
829
-	 * @throws InvalidShare
830
-	 */
831
-	private function createShare($data) {
832
-		$share = new Share($this->rootFolder, $this->userManager);
833
-		$share->setId((int)$data['id'])
834
-			->setShareType((int)$data['share_type'])
835
-			->setPermissions((int)$data['permissions'])
836
-			->setTarget($data['file_target'])
837
-			->setMailSend((bool)$data['mail_send']);
838
-
839
-		$shareTime = new \DateTime();
840
-		$shareTime->setTimestamp((int)$data['stime']);
841
-		$share->setShareTime($shareTime);
842
-
843
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
844
-			$share->setSharedWith($data['share_with']);
845
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
846
-			$share->setSharedWith($data['share_with']);
847
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
848
-			$share->setPassword($data['password']);
849
-			$share->setToken($data['token']);
850
-		}
851
-
852
-		$share->setSharedBy($data['uid_initiator']);
853
-		$share->setShareOwner($data['uid_owner']);
854
-
855
-		$share->setNodeId((int)$data['file_source']);
856
-		$share->setNodeType($data['item_type']);
857
-
858
-		if ($data['expiration'] !== null) {
859
-			$expiration = \DateTime::createFromFormat('Y-m-d H:i:s', $data['expiration']);
860
-			$share->setExpirationDate($expiration);
861
-		}
862
-
863
-		if (isset($data['f_permissions'])) {
864
-			$entryData = $data;
865
-			$entryData['permissions'] = $entryData['f_permissions'];
866
-			$entryData['parent'] = $entryData['f_parent'];
867
-			$share->setNodeCacheEntry(Cache::cacheEntryFromData($entryData,
868
-				\OC::$server->getMimeTypeLoader()));
869
-		}
870
-
871
-		$share->setProviderId($this->identifier());
872
-
873
-		return $share;
874
-	}
875
-
876
-	/**
877
-	 * @param Share[] $shares
878
-	 * @param $userId
879
-	 * @return Share[] The updates shares if no update is found for a share return the original
880
-	 */
881
-	private function resolveGroupShares($shares, $userId) {
882
-		$result = [];
883
-
884
-		$start = 0;
885
-		while(true) {
886
-			/** @var Share[] $shareSlice */
887
-			$shareSlice = array_slice($shares, $start, 100);
888
-			$start += 100;
889
-
890
-			if ($shareSlice === []) {
891
-				break;
892
-			}
893
-
894
-			/** @var int[] $ids */
895
-			$ids = [];
896
-			/** @var Share[] $shareMap */
897
-			$shareMap = [];
898
-
899
-			foreach ($shareSlice as $share) {
900
-				$ids[] = (int)$share->getId();
901
-				$shareMap[$share->getId()] = $share;
902
-			}
903
-
904
-			$qb = $this->dbConn->getQueryBuilder();
905
-
906
-			$query = $qb->select('*')
907
-				->from('share')
908
-				->where($qb->expr()->in('parent', $qb->createNamedParameter($ids, IQueryBuilder::PARAM_INT_ARRAY)))
909
-				->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($userId)))
910
-				->andWhere($qb->expr()->orX(
911
-					$qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
912
-					$qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
913
-				));
914
-
915
-			$stmt = $query->execute();
916
-
917
-			while($data = $stmt->fetch()) {
918
-				$shareMap[$data['parent']]->setPermissions((int)$data['permissions']);
919
-				$shareMap[$data['parent']]->setTarget($data['file_target']);
920
-			}
921
-
922
-			$stmt->closeCursor();
923
-
924
-			foreach ($shareMap as $share) {
925
-				$result[] = $share;
926
-			}
927
-		}
928
-
929
-		return $result;
930
-	}
931
-
932
-	/**
933
-	 * A user is deleted from the system
934
-	 * So clean up the relevant shares.
935
-	 *
936
-	 * @param string $uid
937
-	 * @param int $shareType
938
-	 */
939
-	public function userDeleted($uid, $shareType) {
940
-		$qb = $this->dbConn->getQueryBuilder();
941
-
942
-		$qb->delete('share');
943
-
944
-		if ($shareType === \OCP\Share::SHARE_TYPE_USER) {
945
-			/*
780
+            $shares = $this->resolveGroupShares($shares2, $userId);
781
+        } else {
782
+            throw new BackendError('Invalid backend');
783
+        }
784
+
785
+
786
+        return $shares;
787
+    }
788
+
789
+    /**
790
+     * Get a share by token
791
+     *
792
+     * @param string $token
793
+     * @return \OCP\Share\IShare
794
+     * @throws ShareNotFound
795
+     */
796
+    public function getShareByToken($token) {
797
+        $qb = $this->dbConn->getQueryBuilder();
798
+
799
+        $cursor = $qb->select('*')
800
+            ->from('share')
801
+            ->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_LINK)))
802
+            ->andWhere($qb->expr()->eq('token', $qb->createNamedParameter($token)))
803
+            ->andWhere($qb->expr()->orX(
804
+                $qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
805
+                $qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
806
+            ))
807
+            ->execute();
808
+
809
+        $data = $cursor->fetch();
810
+
811
+        if ($data === false) {
812
+            throw new ShareNotFound();
813
+        }
814
+
815
+        try {
816
+            $share = $this->createShare($data);
817
+        } catch (InvalidShare $e) {
818
+            throw new ShareNotFound();
819
+        }
820
+
821
+        return $share;
822
+    }
823
+
824
+    /**
825
+     * Create a share object from an database row
826
+     *
827
+     * @param mixed[] $data
828
+     * @return \OCP\Share\IShare
829
+     * @throws InvalidShare
830
+     */
831
+    private function createShare($data) {
832
+        $share = new Share($this->rootFolder, $this->userManager);
833
+        $share->setId((int)$data['id'])
834
+            ->setShareType((int)$data['share_type'])
835
+            ->setPermissions((int)$data['permissions'])
836
+            ->setTarget($data['file_target'])
837
+            ->setMailSend((bool)$data['mail_send']);
838
+
839
+        $shareTime = new \DateTime();
840
+        $shareTime->setTimestamp((int)$data['stime']);
841
+        $share->setShareTime($shareTime);
842
+
843
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
844
+            $share->setSharedWith($data['share_with']);
845
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
846
+            $share->setSharedWith($data['share_with']);
847
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
848
+            $share->setPassword($data['password']);
849
+            $share->setToken($data['token']);
850
+        }
851
+
852
+        $share->setSharedBy($data['uid_initiator']);
853
+        $share->setShareOwner($data['uid_owner']);
854
+
855
+        $share->setNodeId((int)$data['file_source']);
856
+        $share->setNodeType($data['item_type']);
857
+
858
+        if ($data['expiration'] !== null) {
859
+            $expiration = \DateTime::createFromFormat('Y-m-d H:i:s', $data['expiration']);
860
+            $share->setExpirationDate($expiration);
861
+        }
862
+
863
+        if (isset($data['f_permissions'])) {
864
+            $entryData = $data;
865
+            $entryData['permissions'] = $entryData['f_permissions'];
866
+            $entryData['parent'] = $entryData['f_parent'];
867
+            $share->setNodeCacheEntry(Cache::cacheEntryFromData($entryData,
868
+                \OC::$server->getMimeTypeLoader()));
869
+        }
870
+
871
+        $share->setProviderId($this->identifier());
872
+
873
+        return $share;
874
+    }
875
+
876
+    /**
877
+     * @param Share[] $shares
878
+     * @param $userId
879
+     * @return Share[] The updates shares if no update is found for a share return the original
880
+     */
881
+    private function resolveGroupShares($shares, $userId) {
882
+        $result = [];
883
+
884
+        $start = 0;
885
+        while(true) {
886
+            /** @var Share[] $shareSlice */
887
+            $shareSlice = array_slice($shares, $start, 100);
888
+            $start += 100;
889
+
890
+            if ($shareSlice === []) {
891
+                break;
892
+            }
893
+
894
+            /** @var int[] $ids */
895
+            $ids = [];
896
+            /** @var Share[] $shareMap */
897
+            $shareMap = [];
898
+
899
+            foreach ($shareSlice as $share) {
900
+                $ids[] = (int)$share->getId();
901
+                $shareMap[$share->getId()] = $share;
902
+            }
903
+
904
+            $qb = $this->dbConn->getQueryBuilder();
905
+
906
+            $query = $qb->select('*')
907
+                ->from('share')
908
+                ->where($qb->expr()->in('parent', $qb->createNamedParameter($ids, IQueryBuilder::PARAM_INT_ARRAY)))
909
+                ->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($userId)))
910
+                ->andWhere($qb->expr()->orX(
911
+                    $qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
912
+                    $qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
913
+                ));
914
+
915
+            $stmt = $query->execute();
916
+
917
+            while($data = $stmt->fetch()) {
918
+                $shareMap[$data['parent']]->setPermissions((int)$data['permissions']);
919
+                $shareMap[$data['parent']]->setTarget($data['file_target']);
920
+            }
921
+
922
+            $stmt->closeCursor();
923
+
924
+            foreach ($shareMap as $share) {
925
+                $result[] = $share;
926
+            }
927
+        }
928
+
929
+        return $result;
930
+    }
931
+
932
+    /**
933
+     * A user is deleted from the system
934
+     * So clean up the relevant shares.
935
+     *
936
+     * @param string $uid
937
+     * @param int $shareType
938
+     */
939
+    public function userDeleted($uid, $shareType) {
940
+        $qb = $this->dbConn->getQueryBuilder();
941
+
942
+        $qb->delete('share');
943
+
944
+        if ($shareType === \OCP\Share::SHARE_TYPE_USER) {
945
+            /*
946 946
 			 * Delete all user shares that are owned by this user
947 947
 			 * or that are received by this user
948 948
 			 */
949 949
 
950
-			$qb->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_USER)));
950
+            $qb->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_USER)));
951 951
 
952
-			$qb->andWhere(
953
-				$qb->expr()->orX(
954
-					$qb->expr()->eq('uid_owner', $qb->createNamedParameter($uid)),
955
-					$qb->expr()->eq('share_with', $qb->createNamedParameter($uid))
956
-				)
957
-			);
958
-		} else if ($shareType === \OCP\Share::SHARE_TYPE_GROUP) {
959
-			/*
952
+            $qb->andWhere(
953
+                $qb->expr()->orX(
954
+                    $qb->expr()->eq('uid_owner', $qb->createNamedParameter($uid)),
955
+                    $qb->expr()->eq('share_with', $qb->createNamedParameter($uid))
956
+                )
957
+            );
958
+        } else if ($shareType === \OCP\Share::SHARE_TYPE_GROUP) {
959
+            /*
960 960
 			 * Delete all group shares that are owned by this user
961 961
 			 * Or special user group shares that are received by this user
962 962
 			 */
963
-			$qb->where(
964
-				$qb->expr()->andX(
965
-					$qb->expr()->orX(
966
-						$qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_GROUP)),
967
-						$qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP))
968
-					),
969
-					$qb->expr()->eq('uid_owner', $qb->createNamedParameter($uid))
970
-				)
971
-			);
972
-
973
-			$qb->orWhere(
974
-				$qb->expr()->andX(
975
-					$qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP)),
976
-					$qb->expr()->eq('share_with', $qb->createNamedParameter($uid))
977
-				)
978
-			);
979
-		} else if ($shareType === \OCP\Share::SHARE_TYPE_LINK) {
980
-			/*
963
+            $qb->where(
964
+                $qb->expr()->andX(
965
+                    $qb->expr()->orX(
966
+                        $qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_GROUP)),
967
+                        $qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP))
968
+                    ),
969
+                    $qb->expr()->eq('uid_owner', $qb->createNamedParameter($uid))
970
+                )
971
+            );
972
+
973
+            $qb->orWhere(
974
+                $qb->expr()->andX(
975
+                    $qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP)),
976
+                    $qb->expr()->eq('share_with', $qb->createNamedParameter($uid))
977
+                )
978
+            );
979
+        } else if ($shareType === \OCP\Share::SHARE_TYPE_LINK) {
980
+            /*
981 981
 			 * Delete all link shares owned by this user.
982 982
 			 * And all link shares initiated by this user (until #22327 is in)
983 983
 			 */
984
-			$qb->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_LINK)));
985
-
986
-			$qb->andWhere(
987
-				$qb->expr()->orX(
988
-					$qb->expr()->eq('uid_owner', $qb->createNamedParameter($uid)),
989
-					$qb->expr()->eq('uid_initiator', $qb->createNamedParameter($uid))
990
-				)
991
-			);
992
-		}
993
-
994
-		$qb->execute();
995
-	}
996
-
997
-	/**
998
-	 * Delete all shares received by this group. As well as any custom group
999
-	 * shares for group members.
1000
-	 *
1001
-	 * @param string $gid
1002
-	 */
1003
-	public function groupDeleted($gid) {
1004
-		/*
984
+            $qb->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_LINK)));
985
+
986
+            $qb->andWhere(
987
+                $qb->expr()->orX(
988
+                    $qb->expr()->eq('uid_owner', $qb->createNamedParameter($uid)),
989
+                    $qb->expr()->eq('uid_initiator', $qb->createNamedParameter($uid))
990
+                )
991
+            );
992
+        }
993
+
994
+        $qb->execute();
995
+    }
996
+
997
+    /**
998
+     * Delete all shares received by this group. As well as any custom group
999
+     * shares for group members.
1000
+     *
1001
+     * @param string $gid
1002
+     */
1003
+    public function groupDeleted($gid) {
1004
+        /*
1005 1005
 		 * First delete all custom group shares for group members
1006 1006
 		 */
1007
-		$qb = $this->dbConn->getQueryBuilder();
1008
-		$qb->select('id')
1009
-			->from('share')
1010
-			->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_GROUP)))
1011
-			->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($gid)));
1012
-
1013
-		$cursor = $qb->execute();
1014
-		$ids = [];
1015
-		while($row = $cursor->fetch()) {
1016
-			$ids[] = (int)$row['id'];
1017
-		}
1018
-		$cursor->closeCursor();
1019
-
1020
-		if (!empty($ids)) {
1021
-			$chunks = array_chunk($ids, 100);
1022
-			foreach ($chunks as $chunk) {
1023
-				$qb->delete('share')
1024
-					->where($qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP)))
1025
-					->andWhere($qb->expr()->in('parent', $qb->createNamedParameter($chunk, IQueryBuilder::PARAM_INT_ARRAY)));
1026
-				$qb->execute();
1027
-			}
1028
-		}
1029
-
1030
-		/*
1007
+        $qb = $this->dbConn->getQueryBuilder();
1008
+        $qb->select('id')
1009
+            ->from('share')
1010
+            ->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_GROUP)))
1011
+            ->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($gid)));
1012
+
1013
+        $cursor = $qb->execute();
1014
+        $ids = [];
1015
+        while($row = $cursor->fetch()) {
1016
+            $ids[] = (int)$row['id'];
1017
+        }
1018
+        $cursor->closeCursor();
1019
+
1020
+        if (!empty($ids)) {
1021
+            $chunks = array_chunk($ids, 100);
1022
+            foreach ($chunks as $chunk) {
1023
+                $qb->delete('share')
1024
+                    ->where($qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP)))
1025
+                    ->andWhere($qb->expr()->in('parent', $qb->createNamedParameter($chunk, IQueryBuilder::PARAM_INT_ARRAY)));
1026
+                $qb->execute();
1027
+            }
1028
+        }
1029
+
1030
+        /*
1031 1031
 		 * Now delete all the group shares
1032 1032
 		 */
1033
-		$qb = $this->dbConn->getQueryBuilder();
1034
-		$qb->delete('share')
1035
-			->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_GROUP)))
1036
-			->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($gid)));
1037
-		$qb->execute();
1038
-	}
1039
-
1040
-	/**
1041
-	 * Delete custom group shares to this group for this user
1042
-	 *
1043
-	 * @param string $uid
1044
-	 * @param string $gid
1045
-	 */
1046
-	public function userDeletedFromGroup($uid, $gid) {
1047
-		/*
1033
+        $qb = $this->dbConn->getQueryBuilder();
1034
+        $qb->delete('share')
1035
+            ->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_GROUP)))
1036
+            ->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($gid)));
1037
+        $qb->execute();
1038
+    }
1039
+
1040
+    /**
1041
+     * Delete custom group shares to this group for this user
1042
+     *
1043
+     * @param string $uid
1044
+     * @param string $gid
1045
+     */
1046
+    public function userDeletedFromGroup($uid, $gid) {
1047
+        /*
1048 1048
 		 * Get all group shares
1049 1049
 		 */
1050
-		$qb = $this->dbConn->getQueryBuilder();
1051
-		$qb->select('id')
1052
-			->from('share')
1053
-			->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_GROUP)))
1054
-			->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($gid)));
1055
-
1056
-		$cursor = $qb->execute();
1057
-		$ids = [];
1058
-		while($row = $cursor->fetch()) {
1059
-			$ids[] = (int)$row['id'];
1060
-		}
1061
-		$cursor->closeCursor();
1062
-
1063
-		if (!empty($ids)) {
1064
-			$chunks = array_chunk($ids, 100);
1065
-			foreach ($chunks as $chunk) {
1066
-				/*
1050
+        $qb = $this->dbConn->getQueryBuilder();
1051
+        $qb->select('id')
1052
+            ->from('share')
1053
+            ->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_GROUP)))
1054
+            ->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($gid)));
1055
+
1056
+        $cursor = $qb->execute();
1057
+        $ids = [];
1058
+        while($row = $cursor->fetch()) {
1059
+            $ids[] = (int)$row['id'];
1060
+        }
1061
+        $cursor->closeCursor();
1062
+
1063
+        if (!empty($ids)) {
1064
+            $chunks = array_chunk($ids, 100);
1065
+            foreach ($chunks as $chunk) {
1066
+                /*
1067 1067
 				 * Delete all special shares wit this users for the found group shares
1068 1068
 				 */
1069
-				$qb->delete('share')
1070
-					->where($qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP)))
1071
-					->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($uid)))
1072
-					->andWhere($qb->expr()->in('parent', $qb->createNamedParameter($chunk, IQueryBuilder::PARAM_INT_ARRAY)));
1073
-				$qb->execute();
1074
-			}
1075
-		}
1076
-	}
1077
-
1078
-	/**
1079
-	 * @inheritdoc
1080
-	 */
1081
-	public function getAccessList($nodes, $currentAccess) {
1082
-		$ids = [];
1083
-		foreach ($nodes as $node) {
1084
-			$ids[] = $node->getId();
1085
-		}
1086
-
1087
-		$qb = $this->dbConn->getQueryBuilder();
1088
-
1089
-		$or = $qb->expr()->orX(
1090
-			$qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_USER)),
1091
-			$qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_GROUP)),
1092
-			$qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_LINK))
1093
-		);
1094
-
1095
-		if ($currentAccess) {
1096
-			$or->add($qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP)));
1097
-		}
1098
-
1099
-		$qb->select('id', 'parent', 'share_type', 'share_with', 'file_source', 'file_target', 'permissions')
1100
-			->from('share')
1101
-			->where(
1102
-				$or
1103
-			)
1104
-			->andWhere($qb->expr()->in('file_source', $qb->createNamedParameter($ids, IQueryBuilder::PARAM_INT_ARRAY)))
1105
-			->andWhere($qb->expr()->orX(
1106
-				$qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
1107
-				$qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
1108
-			));
1109
-		$cursor = $qb->execute();
1110
-
1111
-		$users = [];
1112
-		$link = false;
1113
-		while($row = $cursor->fetch()) {
1114
-			$type = (int)$row['share_type'];
1115
-			if ($type === \OCP\Share::SHARE_TYPE_USER) {
1116
-				$uid = $row['share_with'];
1117
-				$users[$uid] = isset($users[$uid]) ? $users[$uid] : [];
1118
-				$users[$uid][$row['id']] = $row;
1119
-			} else if ($type === \OCP\Share::SHARE_TYPE_GROUP) {
1120
-				$gid = $row['share_with'];
1121
-				$group = $this->groupManager->get($gid);
1122
-
1123
-				if ($group === null) {
1124
-					continue;
1125
-				}
1126
-
1127
-				$userList = $group->getUsers();
1128
-				foreach ($userList as $user) {
1129
-					$uid = $user->getUID();
1130
-					$users[$uid] = isset($users[$uid]) ? $users[$uid] : [];
1131
-					$users[$uid][$row['id']] = $row;
1132
-				}
1133
-			} else if ($type === \OCP\Share::SHARE_TYPE_LINK) {
1134
-				$link = true;
1135
-			} else if ($type === self::SHARE_TYPE_USERGROUP && $currentAccess === true) {
1136
-				$uid = $row['share_with'];
1137
-				$users[$uid] = isset($users[$uid]) ? $users[$uid] : [];
1138
-				$users[$uid][$row['id']] = $row;
1139
-			}
1140
-		}
1141
-		$cursor->closeCursor();
1142
-
1143
-		if ($currentAccess === true) {
1144
-			$users = array_map([$this, 'filterSharesOfUser'], $users);
1145
-			$users = array_filter($users);
1146
-		} else {
1147
-			$users = array_keys($users);
1148
-		}
1149
-
1150
-		return ['users' => $users, 'public' => $link];
1151
-	}
1152
-
1153
-	/**
1154
-	 * For each user the path with the fewest slashes is returned
1155
-	 * @param array $shares
1156
-	 * @return array
1157
-	 */
1158
-	protected function filterSharesOfUser(array $shares) {
1159
-		// Group shares when the user has a share exception
1160
-		foreach ($shares as $id => $share) {
1161
-			$type = (int) $share['share_type'];
1162
-			$permissions = (int) $share['permissions'];
1163
-
1164
-			if ($type === self::SHARE_TYPE_USERGROUP) {
1165
-				unset($shares[$share['parent']]);
1166
-
1167
-				if ($permissions === 0) {
1168
-					unset($shares[$id]);
1169
-				}
1170
-			}
1171
-		}
1172
-
1173
-		$best = [];
1174
-		$bestDepth = 0;
1175
-		foreach ($shares as $id => $share) {
1176
-			$depth = substr_count($share['file_target'], '/');
1177
-			if (empty($best) || $depth < $bestDepth) {
1178
-				$bestDepth = $depth;
1179
-				$best = [
1180
-					'node_id' => $share['file_source'],
1181
-					'node_path' => $share['file_target'],
1182
-				];
1183
-			}
1184
-		}
1185
-
1186
-		return $best;
1187
-	}
1069
+                $qb->delete('share')
1070
+                    ->where($qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP)))
1071
+                    ->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($uid)))
1072
+                    ->andWhere($qb->expr()->in('parent', $qb->createNamedParameter($chunk, IQueryBuilder::PARAM_INT_ARRAY)));
1073
+                $qb->execute();
1074
+            }
1075
+        }
1076
+    }
1077
+
1078
+    /**
1079
+     * @inheritdoc
1080
+     */
1081
+    public function getAccessList($nodes, $currentAccess) {
1082
+        $ids = [];
1083
+        foreach ($nodes as $node) {
1084
+            $ids[] = $node->getId();
1085
+        }
1086
+
1087
+        $qb = $this->dbConn->getQueryBuilder();
1088
+
1089
+        $or = $qb->expr()->orX(
1090
+            $qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_USER)),
1091
+            $qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_GROUP)),
1092
+            $qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_LINK))
1093
+        );
1094
+
1095
+        if ($currentAccess) {
1096
+            $or->add($qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP)));
1097
+        }
1098
+
1099
+        $qb->select('id', 'parent', 'share_type', 'share_with', 'file_source', 'file_target', 'permissions')
1100
+            ->from('share')
1101
+            ->where(
1102
+                $or
1103
+            )
1104
+            ->andWhere($qb->expr()->in('file_source', $qb->createNamedParameter($ids, IQueryBuilder::PARAM_INT_ARRAY)))
1105
+            ->andWhere($qb->expr()->orX(
1106
+                $qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
1107
+                $qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
1108
+            ));
1109
+        $cursor = $qb->execute();
1110
+
1111
+        $users = [];
1112
+        $link = false;
1113
+        while($row = $cursor->fetch()) {
1114
+            $type = (int)$row['share_type'];
1115
+            if ($type === \OCP\Share::SHARE_TYPE_USER) {
1116
+                $uid = $row['share_with'];
1117
+                $users[$uid] = isset($users[$uid]) ? $users[$uid] : [];
1118
+                $users[$uid][$row['id']] = $row;
1119
+            } else if ($type === \OCP\Share::SHARE_TYPE_GROUP) {
1120
+                $gid = $row['share_with'];
1121
+                $group = $this->groupManager->get($gid);
1122
+
1123
+                if ($group === null) {
1124
+                    continue;
1125
+                }
1126
+
1127
+                $userList = $group->getUsers();
1128
+                foreach ($userList as $user) {
1129
+                    $uid = $user->getUID();
1130
+                    $users[$uid] = isset($users[$uid]) ? $users[$uid] : [];
1131
+                    $users[$uid][$row['id']] = $row;
1132
+                }
1133
+            } else if ($type === \OCP\Share::SHARE_TYPE_LINK) {
1134
+                $link = true;
1135
+            } else if ($type === self::SHARE_TYPE_USERGROUP && $currentAccess === true) {
1136
+                $uid = $row['share_with'];
1137
+                $users[$uid] = isset($users[$uid]) ? $users[$uid] : [];
1138
+                $users[$uid][$row['id']] = $row;
1139
+            }
1140
+        }
1141
+        $cursor->closeCursor();
1142
+
1143
+        if ($currentAccess === true) {
1144
+            $users = array_map([$this, 'filterSharesOfUser'], $users);
1145
+            $users = array_filter($users);
1146
+        } else {
1147
+            $users = array_keys($users);
1148
+        }
1149
+
1150
+        return ['users' => $users, 'public' => $link];
1151
+    }
1152
+
1153
+    /**
1154
+     * For each user the path with the fewest slashes is returned
1155
+     * @param array $shares
1156
+     * @return array
1157
+     */
1158
+    protected function filterSharesOfUser(array $shares) {
1159
+        // Group shares when the user has a share exception
1160
+        foreach ($shares as $id => $share) {
1161
+            $type = (int) $share['share_type'];
1162
+            $permissions = (int) $share['permissions'];
1163
+
1164
+            if ($type === self::SHARE_TYPE_USERGROUP) {
1165
+                unset($shares[$share['parent']]);
1166
+
1167
+                if ($permissions === 0) {
1168
+                    unset($shares[$id]);
1169
+                }
1170
+            }
1171
+        }
1172
+
1173
+        $best = [];
1174
+        $bestDepth = 0;
1175
+        foreach ($shares as $id => $share) {
1176
+            $depth = substr_count($share['file_target'], '/');
1177
+            if (empty($best) || $depth < $bestDepth) {
1178
+                $bestDepth = $depth;
1179
+                $best = [
1180
+                    'node_id' => $share['file_source'],
1181
+                    'node_path' => $share['file_target'],
1182
+                ];
1183
+            }
1184
+        }
1185
+
1186
+        return $best;
1187
+    }
1188 1188
 }
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.