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