Completed
Pull Request — master (#7462)
by Björn
15:09
created
apps/files_sharing/lib/SharedMount.php 3 patches
Doc Comments   +2 added lines, -2 removed lines patch added patch discarded remove patch
@@ -110,7 +110,7 @@  discard block
 block discarded – undo
110 110
 	 *
111 111
 	 * @param string $newPath
112 112
 	 * @param \OCP\Share\IShare $share
113
-	 * @return bool
113
+	 * @return boolean|null
114 114
 	 */
115 115
 	private function updateFileTarget($newPath, &$share) {
116 116
 		$share->setTarget($newPath);
@@ -126,7 +126,7 @@  discard block
 block discarded – undo
126 126
 	 * @param string $path
127 127
 	 * @param View $view
128 128
 	 * @param SharedMount[] $mountpoints
129
-	 * @return mixed
129
+	 * @return string
130 130
 	 */
131 131
 	private function generateUniqueTarget($path, $view, array $mountpoints) {
132 132
 		$pathinfo = pathinfo($path);
Please login to merge, or discard this patch.
Spacing   +11 added lines, -11 removed lines patch added patch discarded remove patch
@@ -65,14 +65,14 @@  discard block
 block discarded – undo
65 65
 	 */
66 66
 	public function __construct($storage, array $mountpoints, $arguments = null, $loader = null) {
67 67
 		$this->user = $arguments['user'];
68
-		$this->recipientView = new View('/' . $this->user . '/files');
68
+		$this->recipientView = new View('/'.$this->user.'/files');
69 69
 
70 70
 		$this->superShare = $arguments['superShare'];
71 71
 		$this->groupedShares = $arguments['groupedShares'];
72 72
 
73 73
 		$newMountPoint = $this->verifyMountPoint($this->superShare, $mountpoints);
74
-		$absMountPoint = '/' . $this->user . '/files' . $newMountPoint;
75
-		$arguments['ownerView'] = new View('/' . $this->superShare->getShareOwner() . '/files');
74
+		$absMountPoint = '/'.$this->user.'/files'.$newMountPoint;
75
+		$arguments['ownerView'] = new View('/'.$this->superShare->getShareOwner().'/files');
76 76
 		parent::__construct($storage, $absMountPoint, $arguments, $loader);
77 77
 	}
78 78
 
@@ -93,7 +93,7 @@  discard block
 block discarded – undo
93 93
 		}
94 94
 
95 95
 		$newMountPoint = $this->generateUniqueTarget(
96
-			\OC\Files\Filesystem::normalizePath($parent . '/' . $mountPoint),
96
+			\OC\Files\Filesystem::normalizePath($parent.'/'.$mountPoint),
97 97
 			$this->recipientView,
98 98
 			$mountpoints
99 99
 		);
@@ -130,12 +130,12 @@  discard block
 block discarded – undo
130 130
 	 */
131 131
 	private function generateUniqueTarget($path, $view, array $mountpoints) {
132 132
 		$pathinfo = pathinfo($path);
133
-		$ext = (isset($pathinfo['extension'])) ? '.' . $pathinfo['extension'] : '';
133
+		$ext = (isset($pathinfo['extension'])) ? '.'.$pathinfo['extension'] : '';
134 134
 		$name = $pathinfo['filename'];
135 135
 		$dir = $pathinfo['dirname'];
136 136
 
137 137
 		// Helper function to find existing mount points
138
-		$mountpointExists = function ($path) use ($mountpoints) {
138
+		$mountpointExists = function($path) use ($mountpoints) {
139 139
 			foreach ($mountpoints as $mountpoint) {
140 140
 				if ($mountpoint->getShare()->getTarget() === $path) {
141 141
 					return true;
@@ -146,7 +146,7 @@  discard block
 block discarded – undo
146 146
 
147 147
 		$i = 2;
148 148
 		while ($view->file_exists($path) || $mountpointExists($path)) {
149
-			$path = Filesystem::normalizePath($dir . '/' . $name . ' (' . $i . ')' . $ext);
149
+			$path = Filesystem::normalizePath($dir.'/'.$name.' ('.$i.')'.$ext);
150 150
 			$i++;
151 151
 		}
152 152
 
@@ -167,7 +167,7 @@  discard block
 block discarded – undo
167 167
 		// it is not a file relative to data/user/files
168 168
 		if (count($split) < 3 || $split[1] !== 'files') {
169 169
 			\OCP\Util::writeLog('file sharing',
170
-				'Can not strip userid and "files/" from path: ' . $path,
170
+				'Can not strip userid and "files/" from path: '.$path,
171 171
 				\OCP\Util::ERROR);
172 172
 			throw new \OCA\Files_Sharing\Exceptions\BrokenPath('Path does not start with /user/files', 10);
173 173
 		}
@@ -176,7 +176,7 @@  discard block
 block discarded – undo
176 176
 		$sliced = array_slice($split, 2);
177 177
 		$relPath = implode('/', $sliced);
178 178
 
179
-		return '/' . $relPath;
179
+		return '/'.$relPath;
180 180
 	}
181 181
 
182 182
 	/**
@@ -198,7 +198,7 @@  discard block
 block discarded – undo
198 198
 			$this->storage->setMountPoint($relTargetPath);
199 199
 		} catch (\Exception $e) {
200 200
 			\OCP\Util::writeLog('file sharing',
201
-				'Could not rename mount point for shared folder "' . $this->getMountPoint() . '" to "' . $target . '"',
201
+				'Could not rename mount point for shared folder "'.$this->getMountPoint().'" to "'.$target.'"',
202 202
 				\OCP\Util::ERROR);
203 203
 		}
204 204
 
@@ -253,7 +253,7 @@  discard block
 block discarded – undo
253 253
 			$row = $result->fetch();
254 254
 			$result->closeCursor();
255 255
 			if ($row) {
256
-				return (int)$row['storage'];
256
+				return (int) $row['storage'];
257 257
 			}
258 258
 			return -1;
259 259
 		}
Please login to merge, or discard this patch.
Indentation   +226 added lines, -226 removed lines patch added patch discarded remove patch
@@ -36,230 +36,230 @@
 block discarded – undo
36 36
  * Shared mount points can be moved by the user
37 37
  */
38 38
 class SharedMount extends MountPoint implements MoveableMount {
39
-	/**
40
-	 * @var \OCA\Files_Sharing\SharedStorage $storage
41
-	 */
42
-	protected $storage = null;
43
-
44
-	/**
45
-	 * @var \OC\Files\View
46
-	 */
47
-	private $recipientView;
48
-
49
-	/**
50
-	 * @var string
51
-	 */
52
-	private $user;
53
-
54
-	/** @var \OCP\Share\IShare */
55
-	private $superShare;
56
-
57
-	/** @var \OCP\Share\IShare[] */
58
-	private $groupedShares;
59
-
60
-	/**
61
-	 * @param string $storage
62
-	 * @param SharedMount[] $mountpoints
63
-	 * @param array|null $arguments
64
-	 * @param \OCP\Files\Storage\IStorageFactory $loader
65
-	 */
66
-	public function __construct($storage, array $mountpoints, $arguments = null, $loader = null) {
67
-		$this->user = $arguments['user'];
68
-		$this->recipientView = new View('/' . $this->user . '/files');
69
-
70
-		$this->superShare = $arguments['superShare'];
71
-		$this->groupedShares = $arguments['groupedShares'];
72
-
73
-		$newMountPoint = $this->verifyMountPoint($this->superShare, $mountpoints);
74
-		$absMountPoint = '/' . $this->user . '/files' . $newMountPoint;
75
-		$arguments['ownerView'] = new View('/' . $this->superShare->getShareOwner() . '/files');
76
-		parent::__construct($storage, $absMountPoint, $arguments, $loader);
77
-	}
78
-
79
-	/**
80
-	 * check if the parent folder exists otherwise move the mount point up
81
-	 *
82
-	 * @param \OCP\Share\IShare $share
83
-	 * @param SharedMount[] $mountpoints
84
-	 * @return string
85
-	 */
86
-	private function verifyMountPoint(\OCP\Share\IShare $share, array $mountpoints) {
87
-
88
-		$mountPoint = basename($share->getTarget());
89
-		$parent = dirname($share->getTarget());
90
-
91
-		if (!$this->recipientView->is_dir($parent)) {
92
-			$parent = Helper::getShareFolder($this->recipientView);
93
-		}
94
-
95
-		$newMountPoint = $this->generateUniqueTarget(
96
-			\OC\Files\Filesystem::normalizePath($parent . '/' . $mountPoint),
97
-			$this->recipientView,
98
-			$mountpoints
99
-		);
100
-
101
-		if ($newMountPoint !== $share->getTarget()) {
102
-			$this->updateFileTarget($newMountPoint, $share);
103
-		}
104
-
105
-		return $newMountPoint;
106
-	}
107
-
108
-	/**
109
-	 * update fileTarget in the database if the mount point changed
110
-	 *
111
-	 * @param string $newPath
112
-	 * @param \OCP\Share\IShare $share
113
-	 * @return bool
114
-	 */
115
-	private function updateFileTarget($newPath, &$share) {
116
-		$share->setTarget($newPath);
117
-
118
-		foreach ($this->groupedShares as $tmpShare) {
119
-			$tmpShare->setTarget($newPath);
120
-			\OC::$server->getShareManager()->moveShare($tmpShare, $this->user);
121
-		}
122
-	}
123
-
124
-
125
-	/**
126
-	 * @param string $path
127
-	 * @param View $view
128
-	 * @param SharedMount[] $mountpoints
129
-	 * @return mixed
130
-	 */
131
-	private function generateUniqueTarget($path, $view, array $mountpoints) {
132
-		$pathinfo = pathinfo($path);
133
-		$ext = (isset($pathinfo['extension'])) ? '.' . $pathinfo['extension'] : '';
134
-		$name = $pathinfo['filename'];
135
-		$dir = $pathinfo['dirname'];
136
-
137
-		// Helper function to find existing mount points
138
-		$mountpointExists = function ($path) use ($mountpoints) {
139
-			foreach ($mountpoints as $mountpoint) {
140
-				if ($mountpoint->getShare()->getTarget() === $path) {
141
-					return true;
142
-				}
143
-			}
144
-			return false;
145
-		};
146
-
147
-		$i = 2;
148
-		while ($view->file_exists($path) || $mountpointExists($path)) {
149
-			$path = Filesystem::normalizePath($dir . '/' . $name . ' (' . $i . ')' . $ext);
150
-			$i++;
151
-		}
152
-
153
-		return $path;
154
-	}
155
-
156
-	/**
157
-	 * Format a path to be relative to the /user/files/ directory
158
-	 *
159
-	 * @param string $path the absolute path
160
-	 * @return string e.g. turns '/admin/files/test.txt' into '/test.txt'
161
-	 * @throws \OCA\Files_Sharing\Exceptions\BrokenPath
162
-	 */
163
-	protected function stripUserFilesPath($path) {
164
-		$trimmed = ltrim($path, '/');
165
-		$split = explode('/', $trimmed);
166
-
167
-		// it is not a file relative to data/user/files
168
-		if (count($split) < 3 || $split[1] !== 'files') {
169
-			\OCP\Util::writeLog('file sharing',
170
-				'Can not strip userid and "files/" from path: ' . $path,
171
-				\OCP\Util::ERROR);
172
-			throw new \OCA\Files_Sharing\Exceptions\BrokenPath('Path does not start with /user/files', 10);
173
-		}
174
-
175
-		// skip 'user' and 'files'
176
-		$sliced = array_slice($split, 2);
177
-		$relPath = implode('/', $sliced);
178
-
179
-		return '/' . $relPath;
180
-	}
181
-
182
-	/**
183
-	 * Move the mount point to $target
184
-	 *
185
-	 * @param string $target the target mount point
186
-	 * @return bool
187
-	 */
188
-	public function moveMount($target) {
189
-
190
-		$relTargetPath = $this->stripUserFilesPath($target);
191
-		$share = $this->storage->getShare();
192
-
193
-		$result = true;
194
-
195
-		try {
196
-			$this->updateFileTarget($relTargetPath, $share);
197
-			$this->setMountPoint($target);
198
-			$this->storage->setMountPoint($relTargetPath);
199
-		} catch (\Exception $e) {
200
-			\OCP\Util::writeLog('file sharing',
201
-				'Could not rename mount point for shared folder "' . $this->getMountPoint() . '" to "' . $target . '"',
202
-				\OCP\Util::ERROR);
203
-		}
204
-
205
-		return $result;
206
-	}
207
-
208
-	/**
209
-	 * Remove the mount points
210
-	 *
211
-	 * @return bool
212
-	 */
213
-	public function removeMount() {
214
-		$mountManager = \OC\Files\Filesystem::getMountManager();
215
-		/** @var $storage \OCA\Files_Sharing\SharedStorage */
216
-		$storage = $this->getStorage();
217
-		$result = $storage->unshareStorage();
218
-		$mountManager->removeMount($this->mountPoint);
219
-
220
-		return $result;
221
-	}
222
-
223
-	/**
224
-	 * @return \OCP\Share\IShare
225
-	 */
226
-	public function getShare() {
227
-		return $this->superShare;
228
-	}
229
-
230
-	/**
231
-	 * Get the file id of the root of the storage
232
-	 *
233
-	 * @return int
234
-	 */
235
-	public function getStorageRootId() {
236
-		return $this->getShare()->getNodeId();
237
-	}
238
-
239
-	/**
240
-	 * @return int
241
-	 */
242
-	public function getNumericStorageId() {
243
-		if (!is_null($this->getShare()->getNodeCacheEntry())) {
244
-			return $this->getShare()->getNodeCacheEntry()->getStorageId();
245
-		} else {
246
-			$builder = \OC::$server->getDatabaseConnection()->getQueryBuilder();
247
-
248
-			$query = $builder->select('storage')
249
-				->from('filecache')
250
-				->where($builder->expr()->eq('fileid', $builder->createNamedParameter($this->getStorageRootId())));
251
-
252
-			$result = $query->execute();
253
-			$row = $result->fetch();
254
-			$result->closeCursor();
255
-			if ($row) {
256
-				return (int)$row['storage'];
257
-			}
258
-			return -1;
259
-		}
260
-	}
261
-
262
-	public function getMountType() {
263
-		return 'shared';
264
-	}
39
+    /**
40
+     * @var \OCA\Files_Sharing\SharedStorage $storage
41
+     */
42
+    protected $storage = null;
43
+
44
+    /**
45
+     * @var \OC\Files\View
46
+     */
47
+    private $recipientView;
48
+
49
+    /**
50
+     * @var string
51
+     */
52
+    private $user;
53
+
54
+    /** @var \OCP\Share\IShare */
55
+    private $superShare;
56
+
57
+    /** @var \OCP\Share\IShare[] */
58
+    private $groupedShares;
59
+
60
+    /**
61
+     * @param string $storage
62
+     * @param SharedMount[] $mountpoints
63
+     * @param array|null $arguments
64
+     * @param \OCP\Files\Storage\IStorageFactory $loader
65
+     */
66
+    public function __construct($storage, array $mountpoints, $arguments = null, $loader = null) {
67
+        $this->user = $arguments['user'];
68
+        $this->recipientView = new View('/' . $this->user . '/files');
69
+
70
+        $this->superShare = $arguments['superShare'];
71
+        $this->groupedShares = $arguments['groupedShares'];
72
+
73
+        $newMountPoint = $this->verifyMountPoint($this->superShare, $mountpoints);
74
+        $absMountPoint = '/' . $this->user . '/files' . $newMountPoint;
75
+        $arguments['ownerView'] = new View('/' . $this->superShare->getShareOwner() . '/files');
76
+        parent::__construct($storage, $absMountPoint, $arguments, $loader);
77
+    }
78
+
79
+    /**
80
+     * check if the parent folder exists otherwise move the mount point up
81
+     *
82
+     * @param \OCP\Share\IShare $share
83
+     * @param SharedMount[] $mountpoints
84
+     * @return string
85
+     */
86
+    private function verifyMountPoint(\OCP\Share\IShare $share, array $mountpoints) {
87
+
88
+        $mountPoint = basename($share->getTarget());
89
+        $parent = dirname($share->getTarget());
90
+
91
+        if (!$this->recipientView->is_dir($parent)) {
92
+            $parent = Helper::getShareFolder($this->recipientView);
93
+        }
94
+
95
+        $newMountPoint = $this->generateUniqueTarget(
96
+            \OC\Files\Filesystem::normalizePath($parent . '/' . $mountPoint),
97
+            $this->recipientView,
98
+            $mountpoints
99
+        );
100
+
101
+        if ($newMountPoint !== $share->getTarget()) {
102
+            $this->updateFileTarget($newMountPoint, $share);
103
+        }
104
+
105
+        return $newMountPoint;
106
+    }
107
+
108
+    /**
109
+     * update fileTarget in the database if the mount point changed
110
+     *
111
+     * @param string $newPath
112
+     * @param \OCP\Share\IShare $share
113
+     * @return bool
114
+     */
115
+    private function updateFileTarget($newPath, &$share) {
116
+        $share->setTarget($newPath);
117
+
118
+        foreach ($this->groupedShares as $tmpShare) {
119
+            $tmpShare->setTarget($newPath);
120
+            \OC::$server->getShareManager()->moveShare($tmpShare, $this->user);
121
+        }
122
+    }
123
+
124
+
125
+    /**
126
+     * @param string $path
127
+     * @param View $view
128
+     * @param SharedMount[] $mountpoints
129
+     * @return mixed
130
+     */
131
+    private function generateUniqueTarget($path, $view, array $mountpoints) {
132
+        $pathinfo = pathinfo($path);
133
+        $ext = (isset($pathinfo['extension'])) ? '.' . $pathinfo['extension'] : '';
134
+        $name = $pathinfo['filename'];
135
+        $dir = $pathinfo['dirname'];
136
+
137
+        // Helper function to find existing mount points
138
+        $mountpointExists = function ($path) use ($mountpoints) {
139
+            foreach ($mountpoints as $mountpoint) {
140
+                if ($mountpoint->getShare()->getTarget() === $path) {
141
+                    return true;
142
+                }
143
+            }
144
+            return false;
145
+        };
146
+
147
+        $i = 2;
148
+        while ($view->file_exists($path) || $mountpointExists($path)) {
149
+            $path = Filesystem::normalizePath($dir . '/' . $name . ' (' . $i . ')' . $ext);
150
+            $i++;
151
+        }
152
+
153
+        return $path;
154
+    }
155
+
156
+    /**
157
+     * Format a path to be relative to the /user/files/ directory
158
+     *
159
+     * @param string $path the absolute path
160
+     * @return string e.g. turns '/admin/files/test.txt' into '/test.txt'
161
+     * @throws \OCA\Files_Sharing\Exceptions\BrokenPath
162
+     */
163
+    protected function stripUserFilesPath($path) {
164
+        $trimmed = ltrim($path, '/');
165
+        $split = explode('/', $trimmed);
166
+
167
+        // it is not a file relative to data/user/files
168
+        if (count($split) < 3 || $split[1] !== 'files') {
169
+            \OCP\Util::writeLog('file sharing',
170
+                'Can not strip userid and "files/" from path: ' . $path,
171
+                \OCP\Util::ERROR);
172
+            throw new \OCA\Files_Sharing\Exceptions\BrokenPath('Path does not start with /user/files', 10);
173
+        }
174
+
175
+        // skip 'user' and 'files'
176
+        $sliced = array_slice($split, 2);
177
+        $relPath = implode('/', $sliced);
178
+
179
+        return '/' . $relPath;
180
+    }
181
+
182
+    /**
183
+     * Move the mount point to $target
184
+     *
185
+     * @param string $target the target mount point
186
+     * @return bool
187
+     */
188
+    public function moveMount($target) {
189
+
190
+        $relTargetPath = $this->stripUserFilesPath($target);
191
+        $share = $this->storage->getShare();
192
+
193
+        $result = true;
194
+
195
+        try {
196
+            $this->updateFileTarget($relTargetPath, $share);
197
+            $this->setMountPoint($target);
198
+            $this->storage->setMountPoint($relTargetPath);
199
+        } catch (\Exception $e) {
200
+            \OCP\Util::writeLog('file sharing',
201
+                'Could not rename mount point for shared folder "' . $this->getMountPoint() . '" to "' . $target . '"',
202
+                \OCP\Util::ERROR);
203
+        }
204
+
205
+        return $result;
206
+    }
207
+
208
+    /**
209
+     * Remove the mount points
210
+     *
211
+     * @return bool
212
+     */
213
+    public function removeMount() {
214
+        $mountManager = \OC\Files\Filesystem::getMountManager();
215
+        /** @var $storage \OCA\Files_Sharing\SharedStorage */
216
+        $storage = $this->getStorage();
217
+        $result = $storage->unshareStorage();
218
+        $mountManager->removeMount($this->mountPoint);
219
+
220
+        return $result;
221
+    }
222
+
223
+    /**
224
+     * @return \OCP\Share\IShare
225
+     */
226
+    public function getShare() {
227
+        return $this->superShare;
228
+    }
229
+
230
+    /**
231
+     * Get the file id of the root of the storage
232
+     *
233
+     * @return int
234
+     */
235
+    public function getStorageRootId() {
236
+        return $this->getShare()->getNodeId();
237
+    }
238
+
239
+    /**
240
+     * @return int
241
+     */
242
+    public function getNumericStorageId() {
243
+        if (!is_null($this->getShare()->getNodeCacheEntry())) {
244
+            return $this->getShare()->getNodeCacheEntry()->getStorageId();
245
+        } else {
246
+            $builder = \OC::$server->getDatabaseConnection()->getQueryBuilder();
247
+
248
+            $query = $builder->select('storage')
249
+                ->from('filecache')
250
+                ->where($builder->expr()->eq('fileid', $builder->createNamedParameter($this->getStorageRootId())));
251
+
252
+            $result = $query->execute();
253
+            $row = $result->fetch();
254
+            $result->closeCursor();
255
+            if ($row) {
256
+                return (int)$row['storage'];
257
+            }
258
+            return -1;
259
+        }
260
+    }
261
+
262
+    public function getMountType() {
263
+        return 'shared';
264
+    }
265 265
 }
Please login to merge, or discard this patch.
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.
Spacing   +113 added lines, -113 removed lines patch added patch discarded remove patch
@@ -156,7 +156,7 @@  discard block
 block discarded – undo
156 156
 		parent::__construct();
157 157
 		$this->webRoot = $webRoot;
158 158
 
159
-		$this->registerService(\OCP\IServerContainer::class, function (IServerContainer $c) {
159
+		$this->registerService(\OCP\IServerContainer::class, function(IServerContainer $c) {
160 160
 			return $c;
161 161
 		});
162 162
 
@@ -169,7 +169,7 @@  discard block
 block discarded – undo
169 169
 		$this->registerAlias(IActionFactory::class, ActionFactory::class);
170 170
 
171 171
 
172
-		$this->registerService(\OCP\IPreview::class, function (Server $c) {
172
+		$this->registerService(\OCP\IPreview::class, function(Server $c) {
173 173
 			return new PreviewManager(
174 174
 				$c->getConfig(),
175 175
 				$c->getRootFolder(),
@@ -180,13 +180,13 @@  discard block
 block discarded – undo
180 180
 		});
181 181
 		$this->registerAlias('PreviewManager', \OCP\IPreview::class);
182 182
 
183
-		$this->registerService(\OC\Preview\Watcher::class, function (Server $c) {
183
+		$this->registerService(\OC\Preview\Watcher::class, function(Server $c) {
184 184
 			return new \OC\Preview\Watcher(
185 185
 				$c->getAppDataDir('preview')
186 186
 			);
187 187
 		});
188 188
 
189
-		$this->registerService('EncryptionManager', function (Server $c) {
189
+		$this->registerService('EncryptionManager', function(Server $c) {
190 190
 			$view = new View();
191 191
 			$util = new Encryption\Util(
192 192
 				$view,
@@ -204,7 +204,7 @@  discard block
 block discarded – undo
204 204
 			);
205 205
 		});
206 206
 
207
-		$this->registerService('EncryptionFileHelper', function (Server $c) {
207
+		$this->registerService('EncryptionFileHelper', function(Server $c) {
208 208
 			$util = new Encryption\Util(
209 209
 				new View(),
210 210
 				$c->getUserManager(),
@@ -218,7 +218,7 @@  discard block
 block discarded – undo
218 218
 			);
219 219
 		});
220 220
 
221
-		$this->registerService('EncryptionKeyStorage', function (Server $c) {
221
+		$this->registerService('EncryptionKeyStorage', function(Server $c) {
222 222
 			$view = new View();
223 223
 			$util = new Encryption\Util(
224 224
 				$view,
@@ -229,32 +229,32 @@  discard block
 block discarded – undo
229 229
 
230 230
 			return new Encryption\Keys\Storage($view, $util);
231 231
 		});
232
-		$this->registerService('TagMapper', function (Server $c) {
232
+		$this->registerService('TagMapper', function(Server $c) {
233 233
 			return new TagMapper($c->getDatabaseConnection());
234 234
 		});
235 235
 
236
-		$this->registerService(\OCP\ITagManager::class, function (Server $c) {
236
+		$this->registerService(\OCP\ITagManager::class, function(Server $c) {
237 237
 			$tagMapper = $c->query('TagMapper');
238 238
 			return new TagManager($tagMapper, $c->getUserSession());
239 239
 		});
240 240
 		$this->registerAlias('TagManager', \OCP\ITagManager::class);
241 241
 
242
-		$this->registerService('SystemTagManagerFactory', function (Server $c) {
242
+		$this->registerService('SystemTagManagerFactory', function(Server $c) {
243 243
 			$config = $c->getConfig();
244 244
 			$factoryClass = $config->getSystemValue('systemtags.managerFactory', '\OC\SystemTag\ManagerFactory');
245 245
 			/** @var \OC\SystemTag\ManagerFactory $factory */
246 246
 			$factory = new $factoryClass($this);
247 247
 			return $factory;
248 248
 		});
249
-		$this->registerService(\OCP\SystemTag\ISystemTagManager::class, function (Server $c) {
249
+		$this->registerService(\OCP\SystemTag\ISystemTagManager::class, function(Server $c) {
250 250
 			return $c->query('SystemTagManagerFactory')->getManager();
251 251
 		});
252 252
 		$this->registerAlias('SystemTagManager', \OCP\SystemTag\ISystemTagManager::class);
253 253
 
254
-		$this->registerService(\OCP\SystemTag\ISystemTagObjectMapper::class, function (Server $c) {
254
+		$this->registerService(\OCP\SystemTag\ISystemTagObjectMapper::class, function(Server $c) {
255 255
 			return $c->query('SystemTagManagerFactory')->getObjectMapper();
256 256
 		});
257
-		$this->registerService('RootFolder', function (Server $c) {
257
+		$this->registerService('RootFolder', function(Server $c) {
258 258
 			$manager = \OC\Files\Filesystem::getMountManager(null);
259 259
 			$view = new View();
260 260
 			$root = new Root(
@@ -275,37 +275,37 @@  discard block
 block discarded – undo
275 275
 		});
276 276
 		$this->registerAlias('SystemTagObjectMapper', \OCP\SystemTag\ISystemTagObjectMapper::class);
277 277
 
278
-		$this->registerService(\OCP\Files\IRootFolder::class, function (Server $c) {
279
-			return new LazyRoot(function () use ($c) {
278
+		$this->registerService(\OCP\Files\IRootFolder::class, function(Server $c) {
279
+			return new LazyRoot(function() use ($c) {
280 280
 				return $c->query('RootFolder');
281 281
 			});
282 282
 		});
283 283
 		$this->registerAlias('LazyRootFolder', \OCP\Files\IRootFolder::class);
284 284
 
285
-		$this->registerService(\OCP\IUserManager::class, function (Server $c) {
285
+		$this->registerService(\OCP\IUserManager::class, function(Server $c) {
286 286
 			$config = $c->getConfig();
287 287
 			return new \OC\User\Manager($config);
288 288
 		});
289 289
 		$this->registerAlias('UserManager', \OCP\IUserManager::class);
290 290
 
291
-		$this->registerService(\OCP\IGroupManager::class, function (Server $c) {
291
+		$this->registerService(\OCP\IGroupManager::class, function(Server $c) {
292 292
 			$groupManager = new \OC\Group\Manager($this->getUserManager(), $this->getLogger());
293
-			$groupManager->listen('\OC\Group', 'preCreate', function ($gid) {
293
+			$groupManager->listen('\OC\Group', 'preCreate', function($gid) {
294 294
 				\OC_Hook::emit('OC_Group', 'pre_createGroup', array('run' => true, 'gid' => $gid));
295 295
 			});
296
-			$groupManager->listen('\OC\Group', 'postCreate', function (\OC\Group\Group $gid) {
296
+			$groupManager->listen('\OC\Group', 'postCreate', function(\OC\Group\Group $gid) {
297 297
 				\OC_Hook::emit('OC_User', 'post_createGroup', array('gid' => $gid->getGID()));
298 298
 			});
299
-			$groupManager->listen('\OC\Group', 'preDelete', function (\OC\Group\Group $group) {
299
+			$groupManager->listen('\OC\Group', 'preDelete', function(\OC\Group\Group $group) {
300 300
 				\OC_Hook::emit('OC_Group', 'pre_deleteGroup', array('run' => true, 'gid' => $group->getGID()));
301 301
 			});
302
-			$groupManager->listen('\OC\Group', 'postDelete', function (\OC\Group\Group $group) {
302
+			$groupManager->listen('\OC\Group', 'postDelete', function(\OC\Group\Group $group) {
303 303
 				\OC_Hook::emit('OC_User', 'post_deleteGroup', array('gid' => $group->getGID()));
304 304
 			});
305
-			$groupManager->listen('\OC\Group', 'preAddUser', function (\OC\Group\Group $group, \OC\User\User $user) {
305
+			$groupManager->listen('\OC\Group', 'preAddUser', function(\OC\Group\Group $group, \OC\User\User $user) {
306 306
 				\OC_Hook::emit('OC_Group', 'pre_addToGroup', array('run' => true, 'uid' => $user->getUID(), 'gid' => $group->getGID()));
307 307
 			});
308
-			$groupManager->listen('\OC\Group', 'postAddUser', function (\OC\Group\Group $group, \OC\User\User $user) {
308
+			$groupManager->listen('\OC\Group', 'postAddUser', function(\OC\Group\Group $group, \OC\User\User $user) {
309 309
 				\OC_Hook::emit('OC_Group', 'post_addToGroup', array('uid' => $user->getUID(), 'gid' => $group->getGID()));
310 310
 				//Minimal fix to keep it backward compatible TODO: clean up all the GroupManager hooks
311 311
 				\OC_Hook::emit('OC_User', 'post_addToGroup', array('uid' => $user->getUID(), 'gid' => $group->getGID()));
@@ -314,7 +314,7 @@  discard block
 block discarded – undo
314 314
 		});
315 315
 		$this->registerAlias('GroupManager', \OCP\IGroupManager::class);
316 316
 
317
-		$this->registerService(Store::class, function (Server $c) {
317
+		$this->registerService(Store::class, function(Server $c) {
318 318
 			$session = $c->getSession();
319 319
 			if (\OC::$server->getSystemConfig()->getValue('installed', false)) {
320 320
 				$tokenProvider = $c->query('OC\Authentication\Token\IProvider');
@@ -325,11 +325,11 @@  discard block
 block discarded – undo
325 325
 			return new Store($session, $logger, $tokenProvider);
326 326
 		});
327 327
 		$this->registerAlias(IStore::class, Store::class);
328
-		$this->registerService('OC\Authentication\Token\DefaultTokenMapper', function (Server $c) {
328
+		$this->registerService('OC\Authentication\Token\DefaultTokenMapper', function(Server $c) {
329 329
 			$dbConnection = $c->getDatabaseConnection();
330 330
 			return new Authentication\Token\DefaultTokenMapper($dbConnection);
331 331
 		});
332
-		$this->registerService('OC\Authentication\Token\DefaultTokenProvider', function (Server $c) {
332
+		$this->registerService('OC\Authentication\Token\DefaultTokenProvider', function(Server $c) {
333 333
 			$mapper = $c->query('OC\Authentication\Token\DefaultTokenMapper');
334 334
 			$crypto = $c->getCrypto();
335 335
 			$config = $c->getConfig();
@@ -339,7 +339,7 @@  discard block
 block discarded – undo
339 339
 		});
340 340
 		$this->registerAlias('OC\Authentication\Token\IProvider', 'OC\Authentication\Token\DefaultTokenProvider');
341 341
 
342
-		$this->registerService(\OCP\IUserSession::class, function (Server $c) {
342
+		$this->registerService(\OCP\IUserSession::class, function(Server $c) {
343 343
 			$manager = $c->getUserManager();
344 344
 			$session = new \OC\Session\Memory('');
345 345
 			$timeFactory = new TimeFactory();
@@ -354,45 +354,45 @@  discard block
 block discarded – undo
354 354
 			$dispatcher = $c->getEventDispatcher();
355 355
 
356 356
 			$userSession = new \OC\User\Session($manager, $session, $timeFactory, $defaultTokenProvider, $c->getConfig(), $c->getSecureRandom(), $c->getLockdownManager());
357
-			$userSession->listen('\OC\User', 'preCreateUser', function ($uid, $password) {
357
+			$userSession->listen('\OC\User', 'preCreateUser', function($uid, $password) {
358 358
 				\OC_Hook::emit('OC_User', 'pre_createUser', array('run' => true, 'uid' => $uid, 'password' => $password));
359 359
 			});
360
-			$userSession->listen('\OC\User', 'postCreateUser', function ($user, $password) {
360
+			$userSession->listen('\OC\User', 'postCreateUser', function($user, $password) {
361 361
 				/** @var $user \OC\User\User */
362 362
 				\OC_Hook::emit('OC_User', 'post_createUser', array('uid' => $user->getUID(), 'password' => $password));
363 363
 			});
364
-			$userSession->listen('\OC\User', 'preDelete', function ($user) use ($dispatcher) {
364
+			$userSession->listen('\OC\User', 'preDelete', function($user) use ($dispatcher) {
365 365
 				/** @var $user \OC\User\User */
366 366
 				\OC_Hook::emit('OC_User', 'pre_deleteUser', array('run' => true, 'uid' => $user->getUID()));
367 367
 				$dispatcher->dispatch('OCP\IUser::preDelete', new GenericEvent($user));
368 368
 			});
369
-			$userSession->listen('\OC\User', 'postDelete', function ($user) {
369
+			$userSession->listen('\OC\User', 'postDelete', function($user) {
370 370
 				/** @var $user \OC\User\User */
371 371
 				\OC_Hook::emit('OC_User', 'post_deleteUser', array('uid' => $user->getUID()));
372 372
 			});
373
-			$userSession->listen('\OC\User', 'preSetPassword', function ($user, $password, $recoveryPassword) {
373
+			$userSession->listen('\OC\User', 'preSetPassword', function($user, $password, $recoveryPassword) {
374 374
 				/** @var $user \OC\User\User */
375 375
 				\OC_Hook::emit('OC_User', 'pre_setPassword', array('run' => true, 'uid' => $user->getUID(), 'password' => $password, 'recoveryPassword' => $recoveryPassword));
376 376
 			});
377
-			$userSession->listen('\OC\User', 'postSetPassword', function ($user, $password, $recoveryPassword) {
377
+			$userSession->listen('\OC\User', 'postSetPassword', function($user, $password, $recoveryPassword) {
378 378
 				/** @var $user \OC\User\User */
379 379
 				\OC_Hook::emit('OC_User', 'post_setPassword', array('run' => true, 'uid' => $user->getUID(), 'password' => $password, 'recoveryPassword' => $recoveryPassword));
380 380
 			});
381
-			$userSession->listen('\OC\User', 'preLogin', function ($uid, $password) {
381
+			$userSession->listen('\OC\User', 'preLogin', function($uid, $password) {
382 382
 				\OC_Hook::emit('OC_User', 'pre_login', array('run' => true, 'uid' => $uid, 'password' => $password));
383 383
 			});
384
-			$userSession->listen('\OC\User', 'postLogin', function ($user, $password) {
384
+			$userSession->listen('\OC\User', 'postLogin', function($user, $password) {
385 385
 				/** @var $user \OC\User\User */
386 386
 				\OC_Hook::emit('OC_User', 'post_login', array('run' => true, 'uid' => $user->getUID(), 'password' => $password));
387 387
 			});
388
-			$userSession->listen('\OC\User', 'postRememberedLogin', function ($user, $password) {
388
+			$userSession->listen('\OC\User', 'postRememberedLogin', function($user, $password) {
389 389
 				/** @var $user \OC\User\User */
390 390
 				\OC_Hook::emit('OC_User', 'post_login', array('run' => true, 'uid' => $user->getUID(), 'password' => $password));
391 391
 			});
392
-			$userSession->listen('\OC\User', 'logout', function () {
392
+			$userSession->listen('\OC\User', 'logout', function() {
393 393
 				\OC_Hook::emit('OC_User', 'logout', array());
394 394
 			});
395
-			$userSession->listen('\OC\User', 'changeUser', function ($user, $feature, $value, $oldValue) {
395
+			$userSession->listen('\OC\User', 'changeUser', function($user, $feature, $value, $oldValue) {
396 396
 				/** @var $user \OC\User\User */
397 397
 				\OC_Hook::emit('OC_User', 'changeUser', array('run' => true, 'user' => $user, 'feature' => $feature, 'value' => $value, 'old_value' => $oldValue));
398 398
 			});
@@ -400,7 +400,7 @@  discard block
 block discarded – undo
400 400
 		});
401 401
 		$this->registerAlias('UserSession', \OCP\IUserSession::class);
402 402
 
403
-		$this->registerService(\OC\Authentication\TwoFactorAuth\Manager::class, function (Server $c) {
403
+		$this->registerService(\OC\Authentication\TwoFactorAuth\Manager::class, function(Server $c) {
404 404
 			return new \OC\Authentication\TwoFactorAuth\Manager(
405 405
 				$c->getAppManager(),
406 406
 				$c->getSession(),
@@ -415,7 +415,7 @@  discard block
 block discarded – undo
415 415
 		$this->registerAlias(\OCP\INavigationManager::class, \OC\NavigationManager::class);
416 416
 		$this->registerAlias('NavigationManager', \OCP\INavigationManager::class);
417 417
 
418
-		$this->registerService(\OC\AllConfig::class, function (Server $c) {
418
+		$this->registerService(\OC\AllConfig::class, function(Server $c) {
419 419
 			return new \OC\AllConfig(
420 420
 				$c->getSystemConfig()
421 421
 			);
@@ -423,17 +423,17 @@  discard block
 block discarded – undo
423 423
 		$this->registerAlias('AllConfig', \OC\AllConfig::class);
424 424
 		$this->registerAlias(\OCP\IConfig::class, \OC\AllConfig::class);
425 425
 
426
-		$this->registerService('SystemConfig', function ($c) use ($config) {
426
+		$this->registerService('SystemConfig', function($c) use ($config) {
427 427
 			return new \OC\SystemConfig($config);
428 428
 		});
429 429
 
430
-		$this->registerService(\OC\AppConfig::class, function (Server $c) {
430
+		$this->registerService(\OC\AppConfig::class, function(Server $c) {
431 431
 			return new \OC\AppConfig($c->getDatabaseConnection());
432 432
 		});
433 433
 		$this->registerAlias('AppConfig', \OC\AppConfig::class);
434 434
 		$this->registerAlias(\OCP\IAppConfig::class, \OC\AppConfig::class);
435 435
 
436
-		$this->registerService(\OCP\L10N\IFactory::class, function (Server $c) {
436
+		$this->registerService(\OCP\L10N\IFactory::class, function(Server $c) {
437 437
 			return new \OC\L10N\Factory(
438 438
 				$c->getConfig(),
439 439
 				$c->getRequest(),
@@ -443,7 +443,7 @@  discard block
 block discarded – undo
443 443
 		});
444 444
 		$this->registerAlias('L10NFactory', \OCP\L10N\IFactory::class);
445 445
 
446
-		$this->registerService(\OCP\IURLGenerator::class, function (Server $c) {
446
+		$this->registerService(\OCP\IURLGenerator::class, function(Server $c) {
447 447
 			$config = $c->getConfig();
448 448
 			$cacheFactory = $c->getMemCacheFactory();
449 449
 			$request = $c->getRequest();
@@ -455,18 +455,18 @@  discard block
 block discarded – undo
455 455
 		});
456 456
 		$this->registerAlias('URLGenerator', \OCP\IURLGenerator::class);
457 457
 
458
-		$this->registerService('AppHelper', function ($c) {
458
+		$this->registerService('AppHelper', function($c) {
459 459
 			return new \OC\AppHelper();
460 460
 		});
461 461
 		$this->registerAlias('AppFetcher', AppFetcher::class);
462 462
 		$this->registerAlias('CategoryFetcher', CategoryFetcher::class);
463 463
 
464
-		$this->registerService(\OCP\ICache::class, function ($c) {
464
+		$this->registerService(\OCP\ICache::class, function($c) {
465 465
 			return new Cache\File();
466 466
 		});
467 467
 		$this->registerAlias('UserCache', \OCP\ICache::class);
468 468
 
469
-		$this->registerService(Factory::class, function (Server $c) {
469
+		$this->registerService(Factory::class, function(Server $c) {
470 470
 
471 471
 			$arrayCacheFactory = new \OC\Memcache\Factory('', $c->getLogger(),
472 472
 				'\\OC\\Memcache\\ArrayCache',
@@ -483,7 +483,7 @@  discard block
 block discarded – undo
483 483
 				$version = implode(',', $v);
484 484
 				$instanceId = \OC_Util::getInstanceId();
485 485
 				$path = \OC::$SERVERROOT;
486
-				$prefix = md5($instanceId . '-' . $version . '-' . $path . '-' . $urlGenerator->getBaseUrl());
486
+				$prefix = md5($instanceId.'-'.$version.'-'.$path.'-'.$urlGenerator->getBaseUrl());
487 487
 				return new \OC\Memcache\Factory($prefix, $c->getLogger(),
488 488
 					$config->getSystemValue('memcache.local', null),
489 489
 					$config->getSystemValue('memcache.distributed', null),
@@ -496,12 +496,12 @@  discard block
 block discarded – undo
496 496
 		$this->registerAlias('MemCacheFactory', Factory::class);
497 497
 		$this->registerAlias(ICacheFactory::class, Factory::class);
498 498
 
499
-		$this->registerService('RedisFactory', function (Server $c) {
499
+		$this->registerService('RedisFactory', function(Server $c) {
500 500
 			$systemConfig = $c->getSystemConfig();
501 501
 			return new RedisFactory($systemConfig);
502 502
 		});
503 503
 
504
-		$this->registerService(\OCP\Activity\IManager::class, function (Server $c) {
504
+		$this->registerService(\OCP\Activity\IManager::class, function(Server $c) {
505 505
 			return new \OC\Activity\Manager(
506 506
 				$c->getRequest(),
507 507
 				$c->getUserSession(),
@@ -511,14 +511,14 @@  discard block
 block discarded – undo
511 511
 		});
512 512
 		$this->registerAlias('ActivityManager', \OCP\Activity\IManager::class);
513 513
 
514
-		$this->registerService(\OCP\Activity\IEventMerger::class, function (Server $c) {
514
+		$this->registerService(\OCP\Activity\IEventMerger::class, function(Server $c) {
515 515
 			return new \OC\Activity\EventMerger(
516 516
 				$c->getL10N('lib')
517 517
 			);
518 518
 		});
519 519
 		$this->registerAlias(IValidator::class, Validator::class);
520 520
 
521
-		$this->registerService(\OCP\IAvatarManager::class, function (Server $c) {
521
+		$this->registerService(\OCP\IAvatarManager::class, function(Server $c) {
522 522
 			return new AvatarManager(
523 523
 				$c->getUserManager(),
524 524
 				$c->getAppDataDir('avatar'),
@@ -531,7 +531,7 @@  discard block
 block discarded – undo
531 531
 
532 532
 		$this->registerAlias(\OCP\Support\CrashReport\IRegistry::class, \OC\Support\CrashReport\Registry::class);
533 533
 
534
-		$this->registerService(\OCP\ILogger::class, function (Server $c) {
534
+		$this->registerService(\OCP\ILogger::class, function(Server $c) {
535 535
 			$logType = $c->query('AllConfig')->getSystemValue('log_type', 'file');
536 536
 			$logger = Log::getLogClass($logType);
537 537
 			call_user_func(array($logger, 'init'));
@@ -542,7 +542,7 @@  discard block
 block discarded – undo
542 542
 		});
543 543
 		$this->registerAlias('Logger', \OCP\ILogger::class);
544 544
 
545
-		$this->registerService(\OCP\BackgroundJob\IJobList::class, function (Server $c) {
545
+		$this->registerService(\OCP\BackgroundJob\IJobList::class, function(Server $c) {
546 546
 			$config = $c->getConfig();
547 547
 			return new \OC\BackgroundJob\JobList(
548 548
 				$c->getDatabaseConnection(),
@@ -552,7 +552,7 @@  discard block
 block discarded – undo
552 552
 		});
553 553
 		$this->registerAlias('JobList', \OCP\BackgroundJob\IJobList::class);
554 554
 
555
-		$this->registerService(\OCP\Route\IRouter::class, function (Server $c) {
555
+		$this->registerService(\OCP\Route\IRouter::class, function(Server $c) {
556 556
 			$cacheFactory = $c->getMemCacheFactory();
557 557
 			$logger = $c->getLogger();
558 558
 			if ($cacheFactory->isAvailableLowLatency()) {
@@ -564,12 +564,12 @@  discard block
 block discarded – undo
564 564
 		});
565 565
 		$this->registerAlias('Router', \OCP\Route\IRouter::class);
566 566
 
567
-		$this->registerService(\OCP\ISearch::class, function ($c) {
567
+		$this->registerService(\OCP\ISearch::class, function($c) {
568 568
 			return new Search();
569 569
 		});
570 570
 		$this->registerAlias('Search', \OCP\ISearch::class);
571 571
 
572
-		$this->registerService(\OC\Security\RateLimiting\Limiter::class, function ($c) {
572
+		$this->registerService(\OC\Security\RateLimiting\Limiter::class, function($c) {
573 573
 			return new \OC\Security\RateLimiting\Limiter(
574 574
 				$this->getUserSession(),
575 575
 				$this->getRequest(),
@@ -577,34 +577,34 @@  discard block
 block discarded – undo
577 577
 				$c->query(\OC\Security\RateLimiting\Backend\IBackend::class)
578 578
 			);
579 579
 		});
580
-		$this->registerService(\OC\Security\RateLimiting\Backend\IBackend::class, function ($c) {
580
+		$this->registerService(\OC\Security\RateLimiting\Backend\IBackend::class, function($c) {
581 581
 			return new \OC\Security\RateLimiting\Backend\MemoryCache(
582 582
 				$this->getMemCacheFactory(),
583 583
 				new \OC\AppFramework\Utility\TimeFactory()
584 584
 			);
585 585
 		});
586 586
 
587
-		$this->registerService(\OCP\Security\ISecureRandom::class, function ($c) {
587
+		$this->registerService(\OCP\Security\ISecureRandom::class, function($c) {
588 588
 			return new SecureRandom();
589 589
 		});
590 590
 		$this->registerAlias('SecureRandom', \OCP\Security\ISecureRandom::class);
591 591
 
592
-		$this->registerService(\OCP\Security\ICrypto::class, function (Server $c) {
592
+		$this->registerService(\OCP\Security\ICrypto::class, function(Server $c) {
593 593
 			return new Crypto($c->getConfig(), $c->getSecureRandom());
594 594
 		});
595 595
 		$this->registerAlias('Crypto', \OCP\Security\ICrypto::class);
596 596
 
597
-		$this->registerService(\OCP\Security\IHasher::class, function (Server $c) {
597
+		$this->registerService(\OCP\Security\IHasher::class, function(Server $c) {
598 598
 			return new Hasher($c->getConfig());
599 599
 		});
600 600
 		$this->registerAlias('Hasher', \OCP\Security\IHasher::class);
601 601
 
602
-		$this->registerService(\OCP\Security\ICredentialsManager::class, function (Server $c) {
602
+		$this->registerService(\OCP\Security\ICredentialsManager::class, function(Server $c) {
603 603
 			return new CredentialsManager($c->getCrypto(), $c->getDatabaseConnection());
604 604
 		});
605 605
 		$this->registerAlias('CredentialsManager', \OCP\Security\ICredentialsManager::class);
606 606
 
607
-		$this->registerService(IDBConnection::class, function (Server $c) {
607
+		$this->registerService(IDBConnection::class, function(Server $c) {
608 608
 			$systemConfig = $c->getSystemConfig();
609 609
 			$factory = new \OC\DB\ConnectionFactory($systemConfig);
610 610
 			$type = $systemConfig->getValue('dbtype', 'sqlite');
@@ -618,7 +618,7 @@  discard block
 block discarded – undo
618 618
 		});
619 619
 		$this->registerAlias('DatabaseConnection', IDBConnection::class);
620 620
 
621
-		$this->registerService('HTTPHelper', function (Server $c) {
621
+		$this->registerService('HTTPHelper', function(Server $c) {
622 622
 			$config = $c->getConfig();
623 623
 			return new HTTPHelper(
624 624
 				$config,
@@ -626,7 +626,7 @@  discard block
 block discarded – undo
626 626
 			);
627 627
 		});
628 628
 
629
-		$this->registerService(\OCP\Http\Client\IClientService::class, function (Server $c) {
629
+		$this->registerService(\OCP\Http\Client\IClientService::class, function(Server $c) {
630 630
 			$user = \OC_User::getUser();
631 631
 			$uid = $user ? $user : null;
632 632
 			return new ClientService(
@@ -641,7 +641,7 @@  discard block
 block discarded – undo
641 641
 			);
642 642
 		});
643 643
 		$this->registerAlias('HttpClientService', \OCP\Http\Client\IClientService::class);
644
-		$this->registerService(\OCP\Diagnostics\IEventLogger::class, function (Server $c) {
644
+		$this->registerService(\OCP\Diagnostics\IEventLogger::class, function(Server $c) {
645 645
 			$eventLogger = new EventLogger();
646 646
 			if ($c->getSystemConfig()->getValue('debug', false)) {
647 647
 				// In debug mode, module is being activated by default
@@ -651,7 +651,7 @@  discard block
 block discarded – undo
651 651
 		});
652 652
 		$this->registerAlias('EventLogger', \OCP\Diagnostics\IEventLogger::class);
653 653
 
654
-		$this->registerService(\OCP\Diagnostics\IQueryLogger::class, function (Server $c) {
654
+		$this->registerService(\OCP\Diagnostics\IQueryLogger::class, function(Server $c) {
655 655
 			$queryLogger = new QueryLogger();
656 656
 			if ($c->getSystemConfig()->getValue('debug', false)) {
657 657
 				// In debug mode, module is being activated by default
@@ -661,7 +661,7 @@  discard block
 block discarded – undo
661 661
 		});
662 662
 		$this->registerAlias('QueryLogger', \OCP\Diagnostics\IQueryLogger::class);
663 663
 
664
-		$this->registerService(TempManager::class, function (Server $c) {
664
+		$this->registerService(TempManager::class, function(Server $c) {
665 665
 			return new TempManager(
666 666
 				$c->getLogger(),
667 667
 				$c->getConfig()
@@ -670,7 +670,7 @@  discard block
 block discarded – undo
670 670
 		$this->registerAlias('TempManager', TempManager::class);
671 671
 		$this->registerAlias(ITempManager::class, TempManager::class);
672 672
 
673
-		$this->registerService(AppManager::class, function (Server $c) {
673
+		$this->registerService(AppManager::class, function(Server $c) {
674 674
 			return new \OC\App\AppManager(
675 675
 				$c->getUserSession(),
676 676
 				$c->getAppConfig(),
@@ -682,7 +682,7 @@  discard block
 block discarded – undo
682 682
 		$this->registerAlias('AppManager', AppManager::class);
683 683
 		$this->registerAlias(IAppManager::class, AppManager::class);
684 684
 
685
-		$this->registerService(\OCP\IDateTimeZone::class, function (Server $c) {
685
+		$this->registerService(\OCP\IDateTimeZone::class, function(Server $c) {
686 686
 			return new DateTimeZone(
687 687
 				$c->getConfig(),
688 688
 				$c->getSession()
@@ -690,7 +690,7 @@  discard block
 block discarded – undo
690 690
 		});
691 691
 		$this->registerAlias('DateTimeZone', \OCP\IDateTimeZone::class);
692 692
 
693
-		$this->registerService(\OCP\IDateTimeFormatter::class, function (Server $c) {
693
+		$this->registerService(\OCP\IDateTimeFormatter::class, function(Server $c) {
694 694
 			$language = $c->getConfig()->getUserValue($c->getSession()->get('user_id'), 'core', 'lang', null);
695 695
 
696 696
 			return new DateTimeFormatter(
@@ -700,7 +700,7 @@  discard block
 block discarded – undo
700 700
 		});
701 701
 		$this->registerAlias('DateTimeFormatter', \OCP\IDateTimeFormatter::class);
702 702
 
703
-		$this->registerService(\OCP\Files\Config\IUserMountCache::class, function (Server $c) {
703
+		$this->registerService(\OCP\Files\Config\IUserMountCache::class, function(Server $c) {
704 704
 			$mountCache = new UserMountCache($c->getDatabaseConnection(), $c->getUserManager(), $c->getLogger());
705 705
 			$listener = new UserMountCacheListener($mountCache);
706 706
 			$listener->listen($c->getUserManager());
@@ -708,7 +708,7 @@  discard block
 block discarded – undo
708 708
 		});
709 709
 		$this->registerAlias('UserMountCache', \OCP\Files\Config\IUserMountCache::class);
710 710
 
711
-		$this->registerService(\OCP\Files\Config\IMountProviderCollection::class, function (Server $c) {
711
+		$this->registerService(\OCP\Files\Config\IMountProviderCollection::class, function(Server $c) {
712 712
 			$loader = \OC\Files\Filesystem::getLoader();
713 713
 			$mountCache = $c->query('UserMountCache');
714 714
 			$manager = new \OC\Files\Config\MountProviderCollection($loader, $mountCache);
@@ -724,10 +724,10 @@  discard block
 block discarded – undo
724 724
 		});
725 725
 		$this->registerAlias('MountConfigManager', \OCP\Files\Config\IMountProviderCollection::class);
726 726
 
727
-		$this->registerService('IniWrapper', function ($c) {
727
+		$this->registerService('IniWrapper', function($c) {
728 728
 			return new IniGetWrapper();
729 729
 		});
730
-		$this->registerService('AsyncCommandBus', function (Server $c) {
730
+		$this->registerService('AsyncCommandBus', function(Server $c) {
731 731
 			$busClass = $c->getConfig()->getSystemValue('commandbus');
732 732
 			if ($busClass) {
733 733
 				list($app, $class) = explode('::', $busClass, 2);
@@ -742,10 +742,10 @@  discard block
 block discarded – undo
742 742
 				return new CronBus($jobList);
743 743
 			}
744 744
 		});
745
-		$this->registerService('TrustedDomainHelper', function ($c) {
745
+		$this->registerService('TrustedDomainHelper', function($c) {
746 746
 			return new TrustedDomainHelper($this->getConfig());
747 747
 		});
748
-		$this->registerService('Throttler', function (Server $c) {
748
+		$this->registerService('Throttler', function(Server $c) {
749 749
 			return new Throttler(
750 750
 				$c->getDatabaseConnection(),
751 751
 				new TimeFactory(),
@@ -753,7 +753,7 @@  discard block
 block discarded – undo
753 753
 				$c->getConfig()
754 754
 			);
755 755
 		});
756
-		$this->registerService('IntegrityCodeChecker', function (Server $c) {
756
+		$this->registerService('IntegrityCodeChecker', function(Server $c) {
757 757
 			// IConfig and IAppManager requires a working database. This code
758 758
 			// might however be called when ownCloud is not yet setup.
759 759
 			if (\OC::$server->getSystemConfig()->getValue('installed', false)) {
@@ -774,7 +774,7 @@  discard block
 block discarded – undo
774 774
 				$c->getTempManager()
775 775
 			);
776 776
 		});
777
-		$this->registerService(\OCP\IRequest::class, function ($c) {
777
+		$this->registerService(\OCP\IRequest::class, function($c) {
778 778
 			if (isset($this['urlParams'])) {
779 779
 				$urlParams = $this['urlParams'];
780 780
 			} else {
@@ -810,7 +810,7 @@  discard block
 block discarded – undo
810 810
 		});
811 811
 		$this->registerAlias('Request', \OCP\IRequest::class);
812 812
 
813
-		$this->registerService(\OCP\Mail\IMailer::class, function (Server $c) {
813
+		$this->registerService(\OCP\Mail\IMailer::class, function(Server $c) {
814 814
 			return new Mailer(
815 815
 				$c->getConfig(),
816 816
 				$c->getLogger(),
@@ -821,7 +821,7 @@  discard block
 block discarded – undo
821 821
 		});
822 822
 		$this->registerAlias('Mailer', \OCP\Mail\IMailer::class);
823 823
 
824
-		$this->registerService('LDAPProvider', function (Server $c) {
824
+		$this->registerService('LDAPProvider', function(Server $c) {
825 825
 			$config = $c->getConfig();
826 826
 			$factoryClass = $config->getSystemValue('ldapProviderFactory', null);
827 827
 			if (is_null($factoryClass)) {
@@ -831,7 +831,7 @@  discard block
 block discarded – undo
831 831
 			$factory = new $factoryClass($this);
832 832
 			return $factory->getLDAPProvider();
833 833
 		});
834
-		$this->registerService(ILockingProvider::class, function (Server $c) {
834
+		$this->registerService(ILockingProvider::class, function(Server $c) {
835 835
 			$ini = $c->getIniWrapper();
836 836
 			$config = $c->getConfig();
837 837
 			$ttl = $config->getSystemValue('filelocking.ttl', max(3600, $ini->getNumeric('max_execution_time')));
@@ -848,49 +848,49 @@  discard block
 block discarded – undo
848 848
 		});
849 849
 		$this->registerAlias('LockingProvider', ILockingProvider::class);
850 850
 
851
-		$this->registerService(\OCP\Files\Mount\IMountManager::class, function () {
851
+		$this->registerService(\OCP\Files\Mount\IMountManager::class, function() {
852 852
 			return new \OC\Files\Mount\Manager();
853 853
 		});
854 854
 		$this->registerAlias('MountManager', \OCP\Files\Mount\IMountManager::class);
855 855
 
856
-		$this->registerService(\OCP\Files\IMimeTypeDetector::class, function (Server $c) {
856
+		$this->registerService(\OCP\Files\IMimeTypeDetector::class, function(Server $c) {
857 857
 			return new \OC\Files\Type\Detection(
858 858
 				$c->getURLGenerator(),
859 859
 				\OC::$configDir,
860
-				\OC::$SERVERROOT . '/resources/config/'
860
+				\OC::$SERVERROOT.'/resources/config/'
861 861
 			);
862 862
 		});
863 863
 		$this->registerAlias('MimeTypeDetector', \OCP\Files\IMimeTypeDetector::class);
864 864
 
865
-		$this->registerService(\OCP\Files\IMimeTypeLoader::class, function (Server $c) {
865
+		$this->registerService(\OCP\Files\IMimeTypeLoader::class, function(Server $c) {
866 866
 			return new \OC\Files\Type\Loader(
867 867
 				$c->getDatabaseConnection()
868 868
 			);
869 869
 		});
870 870
 		$this->registerAlias('MimeTypeLoader', \OCP\Files\IMimeTypeLoader::class);
871
-		$this->registerService(BundleFetcher::class, function () {
871
+		$this->registerService(BundleFetcher::class, function() {
872 872
 			return new BundleFetcher($this->getL10N('lib'));
873 873
 		});
874
-		$this->registerService(\OCP\Notification\IManager::class, function (Server $c) {
874
+		$this->registerService(\OCP\Notification\IManager::class, function(Server $c) {
875 875
 			return new Manager(
876 876
 				$c->query(IValidator::class)
877 877
 			);
878 878
 		});
879 879
 		$this->registerAlias('NotificationManager', \OCP\Notification\IManager::class);
880 880
 
881
-		$this->registerService(\OC\CapabilitiesManager::class, function (Server $c) {
881
+		$this->registerService(\OC\CapabilitiesManager::class, function(Server $c) {
882 882
 			$manager = new \OC\CapabilitiesManager($c->getLogger());
883
-			$manager->registerCapability(function () use ($c) {
883
+			$manager->registerCapability(function() use ($c) {
884 884
 				return new \OC\OCS\CoreCapabilities($c->getConfig());
885 885
 			});
886
-			$manager->registerCapability(function () use ($c) {
886
+			$manager->registerCapability(function() use ($c) {
887 887
 				return $c->query(\OC\Security\Bruteforce\Capabilities::class);
888 888
 			});
889 889
 			return $manager;
890 890
 		});
891 891
 		$this->registerAlias('CapabilitiesManager', \OC\CapabilitiesManager::class);
892 892
 
893
-		$this->registerService(\OCP\Comments\ICommentsManager::class, function (Server $c) {
893
+		$this->registerService(\OCP\Comments\ICommentsManager::class, function(Server $c) {
894 894
 			$config = $c->getConfig();
895 895
 			$factoryClass = $config->getSystemValue('comments.managerFactory', '\OC\Comments\ManagerFactory');
896 896
 			/** @var \OCP\Comments\ICommentsManagerFactory $factory */
@@ -899,7 +899,7 @@  discard block
 block discarded – undo
899 899
 		});
900 900
 		$this->registerAlias('CommentsManager', \OCP\Comments\ICommentsManager::class);
901 901
 
902
-		$this->registerService('ThemingDefaults', function (Server $c) {
902
+		$this->registerService('ThemingDefaults', function(Server $c) {
903 903
 			/*
904 904
 			 * Dark magic for autoloader.
905 905
 			 * If we do a class_exists it will try to load the class which will
@@ -926,7 +926,7 @@  discard block
 block discarded – undo
926 926
 			}
927 927
 			return new \OC_Defaults();
928 928
 		});
929
-		$this->registerService(SCSSCacher::class, function (Server $c) {
929
+		$this->registerService(SCSSCacher::class, function(Server $c) {
930 930
 			/** @var Factory $cacheFactory */
931 931
 			$cacheFactory = $c->query(Factory::class);
932 932
 			return new SCSSCacher(
@@ -939,13 +939,13 @@  discard block
 block discarded – undo
939 939
 				$cacheFactory->create('SCSS')
940 940
 			);
941 941
 		});
942
-		$this->registerService(EventDispatcher::class, function () {
942
+		$this->registerService(EventDispatcher::class, function() {
943 943
 			return new EventDispatcher();
944 944
 		});
945 945
 		$this->registerAlias('EventDispatcher', EventDispatcher::class);
946 946
 		$this->registerAlias(EventDispatcherInterface::class, EventDispatcher::class);
947 947
 
948
-		$this->registerService('CryptoWrapper', function (Server $c) {
948
+		$this->registerService('CryptoWrapper', function(Server $c) {
949 949
 			// FIXME: Instantiiated here due to cyclic dependency
950 950
 			$request = new Request(
951 951
 				[
@@ -970,7 +970,7 @@  discard block
 block discarded – undo
970 970
 				$request
971 971
 			);
972 972
 		});
973
-		$this->registerService('CsrfTokenManager', function (Server $c) {
973
+		$this->registerService('CsrfTokenManager', function(Server $c) {
974 974
 			$tokenGenerator = new CsrfTokenGenerator($c->getSecureRandom());
975 975
 
976 976
 			return new CsrfTokenManager(
@@ -978,22 +978,22 @@  discard block
 block discarded – undo
978 978
 				$c->query(SessionStorage::class)
979 979
 			);
980 980
 		});
981
-		$this->registerService(SessionStorage::class, function (Server $c) {
981
+		$this->registerService(SessionStorage::class, function(Server $c) {
982 982
 			return new SessionStorage($c->getSession());
983 983
 		});
984
-		$this->registerService(\OCP\Security\IContentSecurityPolicyManager::class, function (Server $c) {
984
+		$this->registerService(\OCP\Security\IContentSecurityPolicyManager::class, function(Server $c) {
985 985
 			return new ContentSecurityPolicyManager();
986 986
 		});
987 987
 		$this->registerAlias('ContentSecurityPolicyManager', \OCP\Security\IContentSecurityPolicyManager::class);
988 988
 
989
-		$this->registerService('ContentSecurityPolicyNonceManager', function (Server $c) {
989
+		$this->registerService('ContentSecurityPolicyNonceManager', function(Server $c) {
990 990
 			return new ContentSecurityPolicyNonceManager(
991 991
 				$c->getCsrfTokenManager(),
992 992
 				$c->getRequest()
993 993
 			);
994 994
 		});
995 995
 
996
-		$this->registerService(\OCP\Share\IManager::class, function (Server $c) {
996
+		$this->registerService(\OCP\Share\IManager::class, function(Server $c) {
997 997
 			$config = $c->getConfig();
998 998
 			$factoryClass = $config->getSystemValue('sharing.managerFactory', '\OC\Share20\ProviderFactory');
999 999
 			/** @var \OCP\Share\IProviderFactory $factory */
@@ -1036,7 +1036,7 @@  discard block
 block discarded – undo
1036 1036
 
1037 1037
 		$this->registerAlias(\OCP\Collaboration\AutoComplete\IManager::class, \OC\Collaboration\AutoComplete\Manager::class);
1038 1038
 
1039
-		$this->registerService('SettingsManager', function (Server $c) {
1039
+		$this->registerService('SettingsManager', function(Server $c) {
1040 1040
 			$manager = new \OC\Settings\Manager(
1041 1041
 				$c->getLogger(),
1042 1042
 				$c->getDatabaseConnection(),
@@ -1056,29 +1056,29 @@  discard block
 block discarded – undo
1056 1056
 			);
1057 1057
 			return $manager;
1058 1058
 		});
1059
-		$this->registerService(\OC\Files\AppData\Factory::class, function (Server $c) {
1059
+		$this->registerService(\OC\Files\AppData\Factory::class, function(Server $c) {
1060 1060
 			return new \OC\Files\AppData\Factory(
1061 1061
 				$c->getRootFolder(),
1062 1062
 				$c->getSystemConfig()
1063 1063
 			);
1064 1064
 		});
1065 1065
 
1066
-		$this->registerService('LockdownManager', function (Server $c) {
1067
-			return new LockdownManager(function () use ($c) {
1066
+		$this->registerService('LockdownManager', function(Server $c) {
1067
+			return new LockdownManager(function() use ($c) {
1068 1068
 				return $c->getSession();
1069 1069
 			});
1070 1070
 		});
1071 1071
 
1072
-		$this->registerService(\OCP\OCS\IDiscoveryService::class, function (Server $c) {
1072
+		$this->registerService(\OCP\OCS\IDiscoveryService::class, function(Server $c) {
1073 1073
 			return new DiscoveryService($c->getMemCacheFactory(), $c->getHTTPClientService());
1074 1074
 		});
1075 1075
 
1076
-		$this->registerService(ICloudIdManager::class, function (Server $c) {
1076
+		$this->registerService(ICloudIdManager::class, function(Server $c) {
1077 1077
 			return new CloudIdManager();
1078 1078
 		});
1079 1079
 
1080 1080
 		/* To trick DI since we don't extend the DIContainer here */
1081
-		$this->registerService(CleanPreviewsBackgroundJob::class, function (Server $c) {
1081
+		$this->registerService(CleanPreviewsBackgroundJob::class, function(Server $c) {
1082 1082
 			return new CleanPreviewsBackgroundJob(
1083 1083
 				$c->getRootFolder(),
1084 1084
 				$c->getLogger(),
@@ -1093,18 +1093,18 @@  discard block
 block discarded – undo
1093 1093
 		$this->registerAlias(\OCP\AppFramework\Utility\ITimeFactory::class, \OC\AppFramework\Utility\TimeFactory::class);
1094 1094
 		$this->registerAlias('TimeFactory', \OCP\AppFramework\Utility\ITimeFactory::class);
1095 1095
 
1096
-		$this->registerService(Defaults::class, function (Server $c) {
1096
+		$this->registerService(Defaults::class, function(Server $c) {
1097 1097
 			return new Defaults(
1098 1098
 				$c->getThemingDefaults()
1099 1099
 			);
1100 1100
 		});
1101 1101
 		$this->registerAlias('Defaults', \OCP\Defaults::class);
1102 1102
 
1103
-		$this->registerService(\OCP\ISession::class, function (SimpleContainer $c) {
1103
+		$this->registerService(\OCP\ISession::class, function(SimpleContainer $c) {
1104 1104
 			return $c->query(\OCP\IUserSession::class)->getSession();
1105 1105
 		});
1106 1106
 
1107
-		$this->registerService(IShareHelper::class, function (Server $c) {
1107
+		$this->registerService(IShareHelper::class, function(Server $c) {
1108 1108
 			return new ShareHelper(
1109 1109
 				$c->query(\OCP\Share\IManager::class)
1110 1110
 			);
@@ -1156,7 +1156,7 @@  discard block
 block discarded – undo
1156 1156
 				// no avatar to remove
1157 1157
 			} catch (\Exception $e) {
1158 1158
 				// Ignore exceptions
1159
-				$logger->info('Could not cleanup avatar of ' . $user->getUID());
1159
+				$logger->info('Could not cleanup avatar of '.$user->getUID());
1160 1160
 			}
1161 1161
 		});
1162 1162
 	}
@@ -1295,7 +1295,7 @@  discard block
 block discarded – undo
1295 1295
 	 * @deprecated since 9.2.0 use IAppData
1296 1296
 	 */
1297 1297
 	public function getAppFolder() {
1298
-		$dir = '/' . \OC_App::getCurrentApp();
1298
+		$dir = '/'.\OC_App::getCurrentApp();
1299 1299
 		$root = $this->getRootFolder();
1300 1300
 		if (!$root->nodeExists($dir)) {
1301 1301
 			$folder = $root->newFolder($dir);
@@ -1879,7 +1879,7 @@  discard block
 block discarded – undo
1879 1879
 	/**
1880 1880
 	 * @return \OCP\Collaboration\AutoComplete\IManager
1881 1881
 	 */
1882
-	public function getAutoCompleteManager(){
1882
+	public function getAutoCompleteManager() {
1883 1883
 		return $this->query(IManager::class);
1884 1884
 	}
1885 1885
 
Please login to merge, or discard this patch.
Indentation   +1795 added lines, -1795 removed lines patch added patch discarded remove patch
@@ -147,1804 +147,1804 @@
 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
-			return $factory->getManager();
901
-		});
902
-		$this->registerAlias('CommentsManager', \OCP\Comments\ICommentsManager::class);
903
-
904
-		$this->registerService('ThemingDefaults', function (Server $c) {
905
-			/*
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
+            return $factory->getManager();
901
+        });
902
+        $this->registerAlias('CommentsManager', \OCP\Comments\ICommentsManager::class);
903
+
904
+        $this->registerService('ThemingDefaults', function (Server $c) {
905
+            /*
906 906
 			 * Dark magic for autoloader.
907 907
 			 * If we do a class_exists it will try to load the class which will
908 908
 			 * make composer cache the result. Resulting in errors when enabling
909 909
 			 * the theming app.
910 910
 			 */
911
-			$prefixes = \OC::$composerAutoloader->getPrefixesPsr4();
912
-			if (isset($prefixes['OCA\\Theming\\'])) {
913
-				$classExists = true;
914
-			} else {
915
-				$classExists = false;
916
-			}
917
-
918
-			if ($classExists && $c->getConfig()->getSystemValue('installed', false) && $c->getAppManager()->isInstalled('theming') && $c->getTrustedDomainHelper()->isTrustedDomain($c->getRequest()->getInsecureServerHost())) {
919
-				return new ThemingDefaults(
920
-					$c->getConfig(),
921
-					$c->getL10N('theming'),
922
-					$c->getURLGenerator(),
923
-					$c->getAppDataDir('theming'),
924
-					$c->getMemCacheFactory(),
925
-					new Util($c->getConfig(), $this->getAppManager(), $this->getAppDataDir('theming')),
926
-					$this->getAppManager()
927
-				);
928
-			}
929
-			return new \OC_Defaults();
930
-		});
931
-		$this->registerService(SCSSCacher::class, function (Server $c) {
932
-			/** @var Factory $cacheFactory */
933
-			$cacheFactory = $c->query(Factory::class);
934
-			return new SCSSCacher(
935
-				$c->getLogger(),
936
-				$c->query(\OC\Files\AppData\Factory::class),
937
-				$c->getURLGenerator(),
938
-				$c->getConfig(),
939
-				$c->getThemingDefaults(),
940
-				\OC::$SERVERROOT,
941
-				$cacheFactory->create('SCSS')
942
-			);
943
-		});
944
-		$this->registerService(EventDispatcher::class, function () {
945
-			return new EventDispatcher();
946
-		});
947
-		$this->registerAlias('EventDispatcher', EventDispatcher::class);
948
-		$this->registerAlias(EventDispatcherInterface::class, EventDispatcher::class);
949
-
950
-		$this->registerService('CryptoWrapper', function (Server $c) {
951
-			// FIXME: Instantiiated here due to cyclic dependency
952
-			$request = new Request(
953
-				[
954
-					'get' => $_GET,
955
-					'post' => $_POST,
956
-					'files' => $_FILES,
957
-					'server' => $_SERVER,
958
-					'env' => $_ENV,
959
-					'cookies' => $_COOKIE,
960
-					'method' => (isset($_SERVER) && isset($_SERVER['REQUEST_METHOD']))
961
-						? $_SERVER['REQUEST_METHOD']
962
-						: null,
963
-				],
964
-				$c->getSecureRandom(),
965
-				$c->getConfig()
966
-			);
967
-
968
-			return new CryptoWrapper(
969
-				$c->getConfig(),
970
-				$c->getCrypto(),
971
-				$c->getSecureRandom(),
972
-				$request
973
-			);
974
-		});
975
-		$this->registerService('CsrfTokenManager', function (Server $c) {
976
-			$tokenGenerator = new CsrfTokenGenerator($c->getSecureRandom());
977
-
978
-			return new CsrfTokenManager(
979
-				$tokenGenerator,
980
-				$c->query(SessionStorage::class)
981
-			);
982
-		});
983
-		$this->registerService(SessionStorage::class, function (Server $c) {
984
-			return new SessionStorage($c->getSession());
985
-		});
986
-		$this->registerService(\OCP\Security\IContentSecurityPolicyManager::class, function (Server $c) {
987
-			return new ContentSecurityPolicyManager();
988
-		});
989
-		$this->registerAlias('ContentSecurityPolicyManager', \OCP\Security\IContentSecurityPolicyManager::class);
990
-
991
-		$this->registerService('ContentSecurityPolicyNonceManager', function (Server $c) {
992
-			return new ContentSecurityPolicyNonceManager(
993
-				$c->getCsrfTokenManager(),
994
-				$c->getRequest()
995
-			);
996
-		});
997
-
998
-		$this->registerService(\OCP\Share\IManager::class, function (Server $c) {
999
-			$config = $c->getConfig();
1000
-			$factoryClass = $config->getSystemValue('sharing.managerFactory', '\OC\Share20\ProviderFactory');
1001
-			/** @var \OCP\Share\IProviderFactory $factory */
1002
-			$factory = new $factoryClass($this);
1003
-
1004
-			$manager = new \OC\Share20\Manager(
1005
-				$c->getLogger(),
1006
-				$c->getConfig(),
1007
-				$c->getSecureRandom(),
1008
-				$c->getHasher(),
1009
-				$c->getMountManager(),
1010
-				$c->getGroupManager(),
1011
-				$c->getL10N('lib'),
1012
-				$c->getL10NFactory(),
1013
-				$factory,
1014
-				$c->getUserManager(),
1015
-				$c->getLazyRootFolder(),
1016
-				$c->getEventDispatcher(),
1017
-				$c->getMailer(),
1018
-				$c->getURLGenerator(),
1019
-				$c->getThemingDefaults()
1020
-			);
1021
-
1022
-			return $manager;
1023
-		});
1024
-		$this->registerAlias('ShareManager', \OCP\Share\IManager::class);
1025
-
1026
-		$this->registerService(\OCP\Collaboration\Collaborators\ISearch::class, function(Server $c) {
1027
-			$instance = new Collaboration\Collaborators\Search($c);
1028
-
1029
-			// register default plugins
1030
-			$instance->registerPlugin(['shareType' => 'SHARE_TYPE_USER', 'class' => UserPlugin::class]);
1031
-			$instance->registerPlugin(['shareType' => 'SHARE_TYPE_GROUP', 'class' => GroupPlugin::class]);
1032
-			$instance->registerPlugin(['shareType' => 'SHARE_TYPE_EMAIL', 'class' => MailPlugin::class]);
1033
-			$instance->registerPlugin(['shareType' => 'SHARE_TYPE_REMOTE', 'class' => RemotePlugin::class]);
1034
-
1035
-			return $instance;
1036
-		});
1037
-		$this->registerAlias('CollaboratorSearch', \OCP\Collaboration\Collaborators\ISearch::class);
1038
-
1039
-		$this->registerAlias(\OCP\Collaboration\AutoComplete\IManager::class, \OC\Collaboration\AutoComplete\Manager::class);
1040
-
1041
-		$this->registerService('SettingsManager', function (Server $c) {
1042
-			$manager = new \OC\Settings\Manager(
1043
-				$c->getLogger(),
1044
-				$c->getDatabaseConnection(),
1045
-				$c->getL10N('lib'),
1046
-				$c->getConfig(),
1047
-				$c->getEncryptionManager(),
1048
-				$c->getUserManager(),
1049
-				$c->getLockingProvider(),
1050
-				$c->getRequest(),
1051
-				new \OC\Settings\Mapper($c->getDatabaseConnection()),
1052
-				$c->getURLGenerator(),
1053
-				$c->query(AccountManager::class),
1054
-				$c->getGroupManager(),
1055
-				$c->getL10NFactory(),
1056
-				$c->getThemingDefaults(),
1057
-				$c->getAppManager()
1058
-			);
1059
-			return $manager;
1060
-		});
1061
-		$this->registerService(\OC\Files\AppData\Factory::class, function (Server $c) {
1062
-			return new \OC\Files\AppData\Factory(
1063
-				$c->getRootFolder(),
1064
-				$c->getSystemConfig()
1065
-			);
1066
-		});
1067
-
1068
-		$this->registerService('LockdownManager', function (Server $c) {
1069
-			return new LockdownManager(function () use ($c) {
1070
-				return $c->getSession();
1071
-			});
1072
-		});
1073
-
1074
-		$this->registerService(\OCP\OCS\IDiscoveryService::class, function (Server $c) {
1075
-			return new DiscoveryService($c->getMemCacheFactory(), $c->getHTTPClientService());
1076
-		});
1077
-
1078
-		$this->registerService(ICloudIdManager::class, function (Server $c) {
1079
-			return new CloudIdManager();
1080
-		});
1081
-
1082
-		/* To trick DI since we don't extend the DIContainer here */
1083
-		$this->registerService(CleanPreviewsBackgroundJob::class, function (Server $c) {
1084
-			return new CleanPreviewsBackgroundJob(
1085
-				$c->getRootFolder(),
1086
-				$c->getLogger(),
1087
-				$c->getJobList(),
1088
-				new TimeFactory()
1089
-			);
1090
-		});
1091
-
1092
-		$this->registerAlias(\OCP\AppFramework\Utility\IControllerMethodReflector::class, \OC\AppFramework\Utility\ControllerMethodReflector::class);
1093
-		$this->registerAlias('ControllerMethodReflector', \OCP\AppFramework\Utility\IControllerMethodReflector::class);
1094
-
1095
-		$this->registerAlias(\OCP\AppFramework\Utility\ITimeFactory::class, \OC\AppFramework\Utility\TimeFactory::class);
1096
-		$this->registerAlias('TimeFactory', \OCP\AppFramework\Utility\ITimeFactory::class);
1097
-
1098
-		$this->registerService(Defaults::class, function (Server $c) {
1099
-			return new Defaults(
1100
-				$c->getThemingDefaults()
1101
-			);
1102
-		});
1103
-		$this->registerAlias('Defaults', \OCP\Defaults::class);
1104
-
1105
-		$this->registerService(\OCP\ISession::class, function (SimpleContainer $c) {
1106
-			return $c->query(\OCP\IUserSession::class)->getSession();
1107
-		});
1108
-
1109
-		$this->registerService(IShareHelper::class, function (Server $c) {
1110
-			return new ShareHelper(
1111
-				$c->query(\OCP\Share\IManager::class)
1112
-			);
1113
-		});
1114
-
1115
-		$this->registerService(Installer::class, function(Server $c) {
1116
-			return new Installer(
1117
-				$c->getAppFetcher(),
1118
-				$c->getHTTPClientService(),
1119
-				$c->getTempManager(),
1120
-				$c->getLogger(),
1121
-				$c->getConfig()
1122
-			);
1123
-		});
1124
-
1125
-		$this->registerService(IApiFactory::class, function(Server $c) {
1126
-			return new ApiFactory($c->getHTTPClientService());
1127
-		});
1128
-
1129
-		$this->registerService(IInstanceFactory::class, function(Server $c) {
1130
-			$memcacheFactory = $c->getMemCacheFactory();
1131
-			return new InstanceFactory($memcacheFactory->createLocal('remoteinstance.'), $c->getHTTPClientService());
1132
-		});
1133
-
1134
-		$this->registerService(IContactsStore::class, function(Server $c) {
1135
-			return new ContactsStore(
1136
-				$c->getContactsManager(),
1137
-				$c->getConfig(),
1138
-				$c->getUserManager(),
1139
-				$c->getGroupManager()
1140
-			);
1141
-		});
1142
-		$this->registerAlias(IContactsStore::class, ContactsStore::class);
1143
-
1144
-		$this->connectDispatcher();
1145
-	}
1146
-
1147
-	/**
1148
-	 * @return \OCP\Calendar\IManager
1149
-	 */
1150
-	public function getCalendarManager() {
1151
-		return $this->query('CalendarManager');
1152
-	}
1153
-
1154
-	private function connectDispatcher() {
1155
-		$dispatcher = $this->getEventDispatcher();
1156
-
1157
-		// Delete avatar on user deletion
1158
-		$dispatcher->addListener('OCP\IUser::preDelete', function(GenericEvent $e) {
1159
-			$logger = $this->getLogger();
1160
-			$manager = $this->getAvatarManager();
1161
-			/** @var IUser $user */
1162
-			$user = $e->getSubject();
1163
-
1164
-			try {
1165
-				$avatar = $manager->getAvatar($user->getUID());
1166
-				$avatar->remove();
1167
-			} catch (NotFoundException $e) {
1168
-				// no avatar to remove
1169
-			} catch (\Exception $e) {
1170
-				// Ignore exceptions
1171
-				$logger->info('Could not cleanup avatar of ' . $user->getUID());
1172
-			}
1173
-		});
1174
-	}
1175
-
1176
-	/**
1177
-	 * @return \OCP\Contacts\IManager
1178
-	 */
1179
-	public function getContactsManager() {
1180
-		return $this->query('ContactsManager');
1181
-	}
1182
-
1183
-	/**
1184
-	 * @return \OC\Encryption\Manager
1185
-	 */
1186
-	public function getEncryptionManager() {
1187
-		return $this->query('EncryptionManager');
1188
-	}
1189
-
1190
-	/**
1191
-	 * @return \OC\Encryption\File
1192
-	 */
1193
-	public function getEncryptionFilesHelper() {
1194
-		return $this->query('EncryptionFileHelper');
1195
-	}
1196
-
1197
-	/**
1198
-	 * @return \OCP\Encryption\Keys\IStorage
1199
-	 */
1200
-	public function getEncryptionKeyStorage() {
1201
-		return $this->query('EncryptionKeyStorage');
1202
-	}
1203
-
1204
-	/**
1205
-	 * The current request object holding all information about the request
1206
-	 * currently being processed is returned from this method.
1207
-	 * In case the current execution was not initiated by a web request null is returned
1208
-	 *
1209
-	 * @return \OCP\IRequest
1210
-	 */
1211
-	public function getRequest() {
1212
-		return $this->query('Request');
1213
-	}
1214
-
1215
-	/**
1216
-	 * Returns the preview manager which can create preview images for a given file
1217
-	 *
1218
-	 * @return \OCP\IPreview
1219
-	 */
1220
-	public function getPreviewManager() {
1221
-		return $this->query('PreviewManager');
1222
-	}
1223
-
1224
-	/**
1225
-	 * Returns the tag manager which can get and set tags for different object types
1226
-	 *
1227
-	 * @see \OCP\ITagManager::load()
1228
-	 * @return \OCP\ITagManager
1229
-	 */
1230
-	public function getTagManager() {
1231
-		return $this->query('TagManager');
1232
-	}
1233
-
1234
-	/**
1235
-	 * Returns the system-tag manager
1236
-	 *
1237
-	 * @return \OCP\SystemTag\ISystemTagManager
1238
-	 *
1239
-	 * @since 9.0.0
1240
-	 */
1241
-	public function getSystemTagManager() {
1242
-		return $this->query('SystemTagManager');
1243
-	}
1244
-
1245
-	/**
1246
-	 * Returns the system-tag object mapper
1247
-	 *
1248
-	 * @return \OCP\SystemTag\ISystemTagObjectMapper
1249
-	 *
1250
-	 * @since 9.0.0
1251
-	 */
1252
-	public function getSystemTagObjectMapper() {
1253
-		return $this->query('SystemTagObjectMapper');
1254
-	}
1255
-
1256
-	/**
1257
-	 * Returns the avatar manager, used for avatar functionality
1258
-	 *
1259
-	 * @return \OCP\IAvatarManager
1260
-	 */
1261
-	public function getAvatarManager() {
1262
-		return $this->query('AvatarManager');
1263
-	}
1264
-
1265
-	/**
1266
-	 * Returns the root folder of ownCloud's data directory
1267
-	 *
1268
-	 * @return \OCP\Files\IRootFolder
1269
-	 */
1270
-	public function getRootFolder() {
1271
-		return $this->query('LazyRootFolder');
1272
-	}
1273
-
1274
-	/**
1275
-	 * Returns the root folder of ownCloud's data directory
1276
-	 * This is the lazy variant so this gets only initialized once it
1277
-	 * is actually used.
1278
-	 *
1279
-	 * @return \OCP\Files\IRootFolder
1280
-	 */
1281
-	public function getLazyRootFolder() {
1282
-		return $this->query('LazyRootFolder');
1283
-	}
1284
-
1285
-	/**
1286
-	 * Returns a view to ownCloud's files folder
1287
-	 *
1288
-	 * @param string $userId user ID
1289
-	 * @return \OCP\Files\Folder|null
1290
-	 */
1291
-	public function getUserFolder($userId = null) {
1292
-		if ($userId === null) {
1293
-			$user = $this->getUserSession()->getUser();
1294
-			if (!$user) {
1295
-				return null;
1296
-			}
1297
-			$userId = $user->getUID();
1298
-		}
1299
-		$root = $this->getRootFolder();
1300
-		return $root->getUserFolder($userId);
1301
-	}
1302
-
1303
-	/**
1304
-	 * Returns an app-specific view in ownClouds data directory
1305
-	 *
1306
-	 * @return \OCP\Files\Folder
1307
-	 * @deprecated since 9.2.0 use IAppData
1308
-	 */
1309
-	public function getAppFolder() {
1310
-		$dir = '/' . \OC_App::getCurrentApp();
1311
-		$root = $this->getRootFolder();
1312
-		if (!$root->nodeExists($dir)) {
1313
-			$folder = $root->newFolder($dir);
1314
-		} else {
1315
-			$folder = $root->get($dir);
1316
-		}
1317
-		return $folder;
1318
-	}
1319
-
1320
-	/**
1321
-	 * @return \OC\User\Manager
1322
-	 */
1323
-	public function getUserManager() {
1324
-		return $this->query('UserManager');
1325
-	}
1326
-
1327
-	/**
1328
-	 * @return \OC\Group\Manager
1329
-	 */
1330
-	public function getGroupManager() {
1331
-		return $this->query('GroupManager');
1332
-	}
1333
-
1334
-	/**
1335
-	 * @return \OC\User\Session
1336
-	 */
1337
-	public function getUserSession() {
1338
-		return $this->query('UserSession');
1339
-	}
1340
-
1341
-	/**
1342
-	 * @return \OCP\ISession
1343
-	 */
1344
-	public function getSession() {
1345
-		return $this->query('UserSession')->getSession();
1346
-	}
1347
-
1348
-	/**
1349
-	 * @param \OCP\ISession $session
1350
-	 */
1351
-	public function setSession(\OCP\ISession $session) {
1352
-		$this->query(SessionStorage::class)->setSession($session);
1353
-		$this->query('UserSession')->setSession($session);
1354
-		$this->query(Store::class)->setSession($session);
1355
-	}
1356
-
1357
-	/**
1358
-	 * @return \OC\Authentication\TwoFactorAuth\Manager
1359
-	 */
1360
-	public function getTwoFactorAuthManager() {
1361
-		return $this->query('\OC\Authentication\TwoFactorAuth\Manager');
1362
-	}
1363
-
1364
-	/**
1365
-	 * @return \OC\NavigationManager
1366
-	 */
1367
-	public function getNavigationManager() {
1368
-		return $this->query('NavigationManager');
1369
-	}
1370
-
1371
-	/**
1372
-	 * @return \OCP\IConfig
1373
-	 */
1374
-	public function getConfig() {
1375
-		return $this->query('AllConfig');
1376
-	}
1377
-
1378
-	/**
1379
-	 * @return \OC\SystemConfig
1380
-	 */
1381
-	public function getSystemConfig() {
1382
-		return $this->query('SystemConfig');
1383
-	}
1384
-
1385
-	/**
1386
-	 * Returns the app config manager
1387
-	 *
1388
-	 * @return \OCP\IAppConfig
1389
-	 */
1390
-	public function getAppConfig() {
1391
-		return $this->query('AppConfig');
1392
-	}
1393
-
1394
-	/**
1395
-	 * @return \OCP\L10N\IFactory
1396
-	 */
1397
-	public function getL10NFactory() {
1398
-		return $this->query('L10NFactory');
1399
-	}
1400
-
1401
-	/**
1402
-	 * get an L10N instance
1403
-	 *
1404
-	 * @param string $app appid
1405
-	 * @param string $lang
1406
-	 * @return IL10N
1407
-	 */
1408
-	public function getL10N($app, $lang = null) {
1409
-		return $this->getL10NFactory()->get($app, $lang);
1410
-	}
1411
-
1412
-	/**
1413
-	 * @return \OCP\IURLGenerator
1414
-	 */
1415
-	public function getURLGenerator() {
1416
-		return $this->query('URLGenerator');
1417
-	}
1418
-
1419
-	/**
1420
-	 * @return \OCP\IHelper
1421
-	 */
1422
-	public function getHelper() {
1423
-		return $this->query('AppHelper');
1424
-	}
1425
-
1426
-	/**
1427
-	 * @return AppFetcher
1428
-	 */
1429
-	public function getAppFetcher() {
1430
-		return $this->query(AppFetcher::class);
1431
-	}
1432
-
1433
-	/**
1434
-	 * Returns an ICache instance. Since 8.1.0 it returns a fake cache. Use
1435
-	 * getMemCacheFactory() instead.
1436
-	 *
1437
-	 * @return \OCP\ICache
1438
-	 * @deprecated 8.1.0 use getMemCacheFactory to obtain a proper cache
1439
-	 */
1440
-	public function getCache() {
1441
-		return $this->query('UserCache');
1442
-	}
1443
-
1444
-	/**
1445
-	 * Returns an \OCP\CacheFactory instance
1446
-	 *
1447
-	 * @return \OCP\ICacheFactory
1448
-	 */
1449
-	public function getMemCacheFactory() {
1450
-		return $this->query('MemCacheFactory');
1451
-	}
1452
-
1453
-	/**
1454
-	 * Returns an \OC\RedisFactory instance
1455
-	 *
1456
-	 * @return \OC\RedisFactory
1457
-	 */
1458
-	public function getGetRedisFactory() {
1459
-		return $this->query('RedisFactory');
1460
-	}
1461
-
1462
-
1463
-	/**
1464
-	 * Returns the current session
1465
-	 *
1466
-	 * @return \OCP\IDBConnection
1467
-	 */
1468
-	public function getDatabaseConnection() {
1469
-		return $this->query('DatabaseConnection');
1470
-	}
1471
-
1472
-	/**
1473
-	 * Returns the activity manager
1474
-	 *
1475
-	 * @return \OCP\Activity\IManager
1476
-	 */
1477
-	public function getActivityManager() {
1478
-		return $this->query('ActivityManager');
1479
-	}
1480
-
1481
-	/**
1482
-	 * Returns an job list for controlling background jobs
1483
-	 *
1484
-	 * @return \OCP\BackgroundJob\IJobList
1485
-	 */
1486
-	public function getJobList() {
1487
-		return $this->query('JobList');
1488
-	}
1489
-
1490
-	/**
1491
-	 * Returns a logger instance
1492
-	 *
1493
-	 * @return \OCP\ILogger
1494
-	 */
1495
-	public function getLogger() {
1496
-		return $this->query('Logger');
1497
-	}
1498
-
1499
-	/**
1500
-	 * Returns a router for generating and matching urls
1501
-	 *
1502
-	 * @return \OCP\Route\IRouter
1503
-	 */
1504
-	public function getRouter() {
1505
-		return $this->query('Router');
1506
-	}
1507
-
1508
-	/**
1509
-	 * Returns a search instance
1510
-	 *
1511
-	 * @return \OCP\ISearch
1512
-	 */
1513
-	public function getSearch() {
1514
-		return $this->query('Search');
1515
-	}
1516
-
1517
-	/**
1518
-	 * Returns a SecureRandom instance
1519
-	 *
1520
-	 * @return \OCP\Security\ISecureRandom
1521
-	 */
1522
-	public function getSecureRandom() {
1523
-		return $this->query('SecureRandom');
1524
-	}
1525
-
1526
-	/**
1527
-	 * Returns a Crypto instance
1528
-	 *
1529
-	 * @return \OCP\Security\ICrypto
1530
-	 */
1531
-	public function getCrypto() {
1532
-		return $this->query('Crypto');
1533
-	}
1534
-
1535
-	/**
1536
-	 * Returns a Hasher instance
1537
-	 *
1538
-	 * @return \OCP\Security\IHasher
1539
-	 */
1540
-	public function getHasher() {
1541
-		return $this->query('Hasher');
1542
-	}
1543
-
1544
-	/**
1545
-	 * Returns a CredentialsManager instance
1546
-	 *
1547
-	 * @return \OCP\Security\ICredentialsManager
1548
-	 */
1549
-	public function getCredentialsManager() {
1550
-		return $this->query('CredentialsManager');
1551
-	}
1552
-
1553
-	/**
1554
-	 * Returns an instance of the HTTP helper class
1555
-	 *
1556
-	 * @deprecated Use getHTTPClientService()
1557
-	 * @return \OC\HTTPHelper
1558
-	 */
1559
-	public function getHTTPHelper() {
1560
-		return $this->query('HTTPHelper');
1561
-	}
1562
-
1563
-	/**
1564
-	 * Get the certificate manager for the user
1565
-	 *
1566
-	 * @param string $userId (optional) if not specified the current loggedin user is used, use null to get the system certificate manager
1567
-	 * @return \OCP\ICertificateManager | null if $uid is null and no user is logged in
1568
-	 */
1569
-	public function getCertificateManager($userId = '') {
1570
-		if ($userId === '') {
1571
-			$userSession = $this->getUserSession();
1572
-			$user = $userSession->getUser();
1573
-			if (is_null($user)) {
1574
-				return null;
1575
-			}
1576
-			$userId = $user->getUID();
1577
-		}
1578
-		return new CertificateManager(
1579
-			$userId,
1580
-			new View(),
1581
-			$this->getConfig(),
1582
-			$this->getLogger(),
1583
-			$this->getSecureRandom()
1584
-		);
1585
-	}
1586
-
1587
-	/**
1588
-	 * Returns an instance of the HTTP client service
1589
-	 *
1590
-	 * @return \OCP\Http\Client\IClientService
1591
-	 */
1592
-	public function getHTTPClientService() {
1593
-		return $this->query('HttpClientService');
1594
-	}
1595
-
1596
-	/**
1597
-	 * Create a new event source
1598
-	 *
1599
-	 * @return \OCP\IEventSource
1600
-	 */
1601
-	public function createEventSource() {
1602
-		return new \OC_EventSource();
1603
-	}
1604
-
1605
-	/**
1606
-	 * Get the active event logger
1607
-	 *
1608
-	 * The returned logger only logs data when debug mode is enabled
1609
-	 *
1610
-	 * @return \OCP\Diagnostics\IEventLogger
1611
-	 */
1612
-	public function getEventLogger() {
1613
-		return $this->query('EventLogger');
1614
-	}
1615
-
1616
-	/**
1617
-	 * Get the active query logger
1618
-	 *
1619
-	 * The returned logger only logs data when debug mode is enabled
1620
-	 *
1621
-	 * @return \OCP\Diagnostics\IQueryLogger
1622
-	 */
1623
-	public function getQueryLogger() {
1624
-		return $this->query('QueryLogger');
1625
-	}
1626
-
1627
-	/**
1628
-	 * Get the manager for temporary files and folders
1629
-	 *
1630
-	 * @return \OCP\ITempManager
1631
-	 */
1632
-	public function getTempManager() {
1633
-		return $this->query('TempManager');
1634
-	}
1635
-
1636
-	/**
1637
-	 * Get the app manager
1638
-	 *
1639
-	 * @return \OCP\App\IAppManager
1640
-	 */
1641
-	public function getAppManager() {
1642
-		return $this->query('AppManager');
1643
-	}
1644
-
1645
-	/**
1646
-	 * Creates a new mailer
1647
-	 *
1648
-	 * @return \OCP\Mail\IMailer
1649
-	 */
1650
-	public function getMailer() {
1651
-		return $this->query('Mailer');
1652
-	}
1653
-
1654
-	/**
1655
-	 * Get the webroot
1656
-	 *
1657
-	 * @return string
1658
-	 */
1659
-	public function getWebRoot() {
1660
-		return $this->webRoot;
1661
-	}
1662
-
1663
-	/**
1664
-	 * @return \OC\OCSClient
1665
-	 */
1666
-	public function getOcsClient() {
1667
-		return $this->query('OcsClient');
1668
-	}
1669
-
1670
-	/**
1671
-	 * @return \OCP\IDateTimeZone
1672
-	 */
1673
-	public function getDateTimeZone() {
1674
-		return $this->query('DateTimeZone');
1675
-	}
1676
-
1677
-	/**
1678
-	 * @return \OCP\IDateTimeFormatter
1679
-	 */
1680
-	public function getDateTimeFormatter() {
1681
-		return $this->query('DateTimeFormatter');
1682
-	}
1683
-
1684
-	/**
1685
-	 * @return \OCP\Files\Config\IMountProviderCollection
1686
-	 */
1687
-	public function getMountProviderCollection() {
1688
-		return $this->query('MountConfigManager');
1689
-	}
1690
-
1691
-	/**
1692
-	 * Get the IniWrapper
1693
-	 *
1694
-	 * @return IniGetWrapper
1695
-	 */
1696
-	public function getIniWrapper() {
1697
-		return $this->query('IniWrapper');
1698
-	}
1699
-
1700
-	/**
1701
-	 * @return \OCP\Command\IBus
1702
-	 */
1703
-	public function getCommandBus() {
1704
-		return $this->query('AsyncCommandBus');
1705
-	}
1706
-
1707
-	/**
1708
-	 * Get the trusted domain helper
1709
-	 *
1710
-	 * @return TrustedDomainHelper
1711
-	 */
1712
-	public function getTrustedDomainHelper() {
1713
-		return $this->query('TrustedDomainHelper');
1714
-	}
1715
-
1716
-	/**
1717
-	 * Get the locking provider
1718
-	 *
1719
-	 * @return \OCP\Lock\ILockingProvider
1720
-	 * @since 8.1.0
1721
-	 */
1722
-	public function getLockingProvider() {
1723
-		return $this->query('LockingProvider');
1724
-	}
1725
-
1726
-	/**
1727
-	 * @return \OCP\Files\Mount\IMountManager
1728
-	 **/
1729
-	function getMountManager() {
1730
-		return $this->query('MountManager');
1731
-	}
1732
-
1733
-	/** @return \OCP\Files\Config\IUserMountCache */
1734
-	function getUserMountCache() {
1735
-		return $this->query('UserMountCache');
1736
-	}
1737
-
1738
-	/**
1739
-	 * Get the MimeTypeDetector
1740
-	 *
1741
-	 * @return \OCP\Files\IMimeTypeDetector
1742
-	 */
1743
-	public function getMimeTypeDetector() {
1744
-		return $this->query('MimeTypeDetector');
1745
-	}
1746
-
1747
-	/**
1748
-	 * Get the MimeTypeLoader
1749
-	 *
1750
-	 * @return \OCP\Files\IMimeTypeLoader
1751
-	 */
1752
-	public function getMimeTypeLoader() {
1753
-		return $this->query('MimeTypeLoader');
1754
-	}
1755
-
1756
-	/**
1757
-	 * Get the manager of all the capabilities
1758
-	 *
1759
-	 * @return \OC\CapabilitiesManager
1760
-	 */
1761
-	public function getCapabilitiesManager() {
1762
-		return $this->query('CapabilitiesManager');
1763
-	}
1764
-
1765
-	/**
1766
-	 * Get the EventDispatcher
1767
-	 *
1768
-	 * @return EventDispatcherInterface
1769
-	 * @since 8.2.0
1770
-	 */
1771
-	public function getEventDispatcher() {
1772
-		return $this->query('EventDispatcher');
1773
-	}
1774
-
1775
-	/**
1776
-	 * Get the Notification Manager
1777
-	 *
1778
-	 * @return \OCP\Notification\IManager
1779
-	 * @since 8.2.0
1780
-	 */
1781
-	public function getNotificationManager() {
1782
-		return $this->query('NotificationManager');
1783
-	}
1784
-
1785
-	/**
1786
-	 * @return \OCP\Comments\ICommentsManager
1787
-	 */
1788
-	public function getCommentsManager() {
1789
-		return $this->query('CommentsManager');
1790
-	}
1791
-
1792
-	/**
1793
-	 * @return \OCA\Theming\ThemingDefaults
1794
-	 */
1795
-	public function getThemingDefaults() {
1796
-		return $this->query('ThemingDefaults');
1797
-	}
1798
-
1799
-	/**
1800
-	 * @return \OC\IntegrityCheck\Checker
1801
-	 */
1802
-	public function getIntegrityCodeChecker() {
1803
-		return $this->query('IntegrityCodeChecker');
1804
-	}
1805
-
1806
-	/**
1807
-	 * @return \OC\Session\CryptoWrapper
1808
-	 */
1809
-	public function getSessionCryptoWrapper() {
1810
-		return $this->query('CryptoWrapper');
1811
-	}
1812
-
1813
-	/**
1814
-	 * @return CsrfTokenManager
1815
-	 */
1816
-	public function getCsrfTokenManager() {
1817
-		return $this->query('CsrfTokenManager');
1818
-	}
1819
-
1820
-	/**
1821
-	 * @return Throttler
1822
-	 */
1823
-	public function getBruteForceThrottler() {
1824
-		return $this->query('Throttler');
1825
-	}
1826
-
1827
-	/**
1828
-	 * @return IContentSecurityPolicyManager
1829
-	 */
1830
-	public function getContentSecurityPolicyManager() {
1831
-		return $this->query('ContentSecurityPolicyManager');
1832
-	}
1833
-
1834
-	/**
1835
-	 * @return ContentSecurityPolicyNonceManager
1836
-	 */
1837
-	public function getContentSecurityPolicyNonceManager() {
1838
-		return $this->query('ContentSecurityPolicyNonceManager');
1839
-	}
1840
-
1841
-	/**
1842
-	 * Not a public API as of 8.2, wait for 9.0
1843
-	 *
1844
-	 * @return \OCA\Files_External\Service\BackendService
1845
-	 */
1846
-	public function getStoragesBackendService() {
1847
-		return $this->query('OCA\\Files_External\\Service\\BackendService');
1848
-	}
1849
-
1850
-	/**
1851
-	 * Not a public API as of 8.2, wait for 9.0
1852
-	 *
1853
-	 * @return \OCA\Files_External\Service\GlobalStoragesService
1854
-	 */
1855
-	public function getGlobalStoragesService() {
1856
-		return $this->query('OCA\\Files_External\\Service\\GlobalStoragesService');
1857
-	}
1858
-
1859
-	/**
1860
-	 * Not a public API as of 8.2, wait for 9.0
1861
-	 *
1862
-	 * @return \OCA\Files_External\Service\UserGlobalStoragesService
1863
-	 */
1864
-	public function getUserGlobalStoragesService() {
1865
-		return $this->query('OCA\\Files_External\\Service\\UserGlobalStoragesService');
1866
-	}
1867
-
1868
-	/**
1869
-	 * Not a public API as of 8.2, wait for 9.0
1870
-	 *
1871
-	 * @return \OCA\Files_External\Service\UserStoragesService
1872
-	 */
1873
-	public function getUserStoragesService() {
1874
-		return $this->query('OCA\\Files_External\\Service\\UserStoragesService');
1875
-	}
1876
-
1877
-	/**
1878
-	 * @return \OCP\Share\IManager
1879
-	 */
1880
-	public function getShareManager() {
1881
-		return $this->query('ShareManager');
1882
-	}
1883
-
1884
-	/**
1885
-	 * @return \OCP\Collaboration\Collaborators\ISearch
1886
-	 */
1887
-	public function getCollaboratorSearch() {
1888
-		return $this->query('CollaboratorSearch');
1889
-	}
1890
-
1891
-	/**
1892
-	 * @return \OCP\Collaboration\AutoComplete\IManager
1893
-	 */
1894
-	public function getAutoCompleteManager(){
1895
-		return $this->query(IManager::class);
1896
-	}
1897
-
1898
-	/**
1899
-	 * Returns the LDAP Provider
1900
-	 *
1901
-	 * @return \OCP\LDAP\ILDAPProvider
1902
-	 */
1903
-	public function getLDAPProvider() {
1904
-		return $this->query('LDAPProvider');
1905
-	}
1906
-
1907
-	/**
1908
-	 * @return \OCP\Settings\IManager
1909
-	 */
1910
-	public function getSettingsManager() {
1911
-		return $this->query('SettingsManager');
1912
-	}
1913
-
1914
-	/**
1915
-	 * @return \OCP\Files\IAppData
1916
-	 */
1917
-	public function getAppDataDir($app) {
1918
-		/** @var \OC\Files\AppData\Factory $factory */
1919
-		$factory = $this->query(\OC\Files\AppData\Factory::class);
1920
-		return $factory->get($app);
1921
-	}
1922
-
1923
-	/**
1924
-	 * @return \OCP\Lockdown\ILockdownManager
1925
-	 */
1926
-	public function getLockdownManager() {
1927
-		return $this->query('LockdownManager');
1928
-	}
1929
-
1930
-	/**
1931
-	 * @return \OCP\Federation\ICloudIdManager
1932
-	 */
1933
-	public function getCloudIdManager() {
1934
-		return $this->query(ICloudIdManager::class);
1935
-	}
1936
-
1937
-	/**
1938
-	 * @return \OCP\Remote\Api\IApiFactory
1939
-	 */
1940
-	public function getRemoteApiFactory() {
1941
-		return $this->query(IApiFactory::class);
1942
-	}
1943
-
1944
-	/**
1945
-	 * @return \OCP\Remote\IInstanceFactory
1946
-	 */
1947
-	public function getRemoteInstanceFactory() {
1948
-		return $this->query(IInstanceFactory::class);
1949
-	}
911
+            $prefixes = \OC::$composerAutoloader->getPrefixesPsr4();
912
+            if (isset($prefixes['OCA\\Theming\\'])) {
913
+                $classExists = true;
914
+            } else {
915
+                $classExists = false;
916
+            }
917
+
918
+            if ($classExists && $c->getConfig()->getSystemValue('installed', false) && $c->getAppManager()->isInstalled('theming') && $c->getTrustedDomainHelper()->isTrustedDomain($c->getRequest()->getInsecureServerHost())) {
919
+                return new ThemingDefaults(
920
+                    $c->getConfig(),
921
+                    $c->getL10N('theming'),
922
+                    $c->getURLGenerator(),
923
+                    $c->getAppDataDir('theming'),
924
+                    $c->getMemCacheFactory(),
925
+                    new Util($c->getConfig(), $this->getAppManager(), $this->getAppDataDir('theming')),
926
+                    $this->getAppManager()
927
+                );
928
+            }
929
+            return new \OC_Defaults();
930
+        });
931
+        $this->registerService(SCSSCacher::class, function (Server $c) {
932
+            /** @var Factory $cacheFactory */
933
+            $cacheFactory = $c->query(Factory::class);
934
+            return new SCSSCacher(
935
+                $c->getLogger(),
936
+                $c->query(\OC\Files\AppData\Factory::class),
937
+                $c->getURLGenerator(),
938
+                $c->getConfig(),
939
+                $c->getThemingDefaults(),
940
+                \OC::$SERVERROOT,
941
+                $cacheFactory->create('SCSS')
942
+            );
943
+        });
944
+        $this->registerService(EventDispatcher::class, function () {
945
+            return new EventDispatcher();
946
+        });
947
+        $this->registerAlias('EventDispatcher', EventDispatcher::class);
948
+        $this->registerAlias(EventDispatcherInterface::class, EventDispatcher::class);
949
+
950
+        $this->registerService('CryptoWrapper', function (Server $c) {
951
+            // FIXME: Instantiiated here due to cyclic dependency
952
+            $request = new Request(
953
+                [
954
+                    'get' => $_GET,
955
+                    'post' => $_POST,
956
+                    'files' => $_FILES,
957
+                    'server' => $_SERVER,
958
+                    'env' => $_ENV,
959
+                    'cookies' => $_COOKIE,
960
+                    'method' => (isset($_SERVER) && isset($_SERVER['REQUEST_METHOD']))
961
+                        ? $_SERVER['REQUEST_METHOD']
962
+                        : null,
963
+                ],
964
+                $c->getSecureRandom(),
965
+                $c->getConfig()
966
+            );
967
+
968
+            return new CryptoWrapper(
969
+                $c->getConfig(),
970
+                $c->getCrypto(),
971
+                $c->getSecureRandom(),
972
+                $request
973
+            );
974
+        });
975
+        $this->registerService('CsrfTokenManager', function (Server $c) {
976
+            $tokenGenerator = new CsrfTokenGenerator($c->getSecureRandom());
977
+
978
+            return new CsrfTokenManager(
979
+                $tokenGenerator,
980
+                $c->query(SessionStorage::class)
981
+            );
982
+        });
983
+        $this->registerService(SessionStorage::class, function (Server $c) {
984
+            return new SessionStorage($c->getSession());
985
+        });
986
+        $this->registerService(\OCP\Security\IContentSecurityPolicyManager::class, function (Server $c) {
987
+            return new ContentSecurityPolicyManager();
988
+        });
989
+        $this->registerAlias('ContentSecurityPolicyManager', \OCP\Security\IContentSecurityPolicyManager::class);
990
+
991
+        $this->registerService('ContentSecurityPolicyNonceManager', function (Server $c) {
992
+            return new ContentSecurityPolicyNonceManager(
993
+                $c->getCsrfTokenManager(),
994
+                $c->getRequest()
995
+            );
996
+        });
997
+
998
+        $this->registerService(\OCP\Share\IManager::class, function (Server $c) {
999
+            $config = $c->getConfig();
1000
+            $factoryClass = $config->getSystemValue('sharing.managerFactory', '\OC\Share20\ProviderFactory');
1001
+            /** @var \OCP\Share\IProviderFactory $factory */
1002
+            $factory = new $factoryClass($this);
1003
+
1004
+            $manager = new \OC\Share20\Manager(
1005
+                $c->getLogger(),
1006
+                $c->getConfig(),
1007
+                $c->getSecureRandom(),
1008
+                $c->getHasher(),
1009
+                $c->getMountManager(),
1010
+                $c->getGroupManager(),
1011
+                $c->getL10N('lib'),
1012
+                $c->getL10NFactory(),
1013
+                $factory,
1014
+                $c->getUserManager(),
1015
+                $c->getLazyRootFolder(),
1016
+                $c->getEventDispatcher(),
1017
+                $c->getMailer(),
1018
+                $c->getURLGenerator(),
1019
+                $c->getThemingDefaults()
1020
+            );
1021
+
1022
+            return $manager;
1023
+        });
1024
+        $this->registerAlias('ShareManager', \OCP\Share\IManager::class);
1025
+
1026
+        $this->registerService(\OCP\Collaboration\Collaborators\ISearch::class, function(Server $c) {
1027
+            $instance = new Collaboration\Collaborators\Search($c);
1028
+
1029
+            // register default plugins
1030
+            $instance->registerPlugin(['shareType' => 'SHARE_TYPE_USER', 'class' => UserPlugin::class]);
1031
+            $instance->registerPlugin(['shareType' => 'SHARE_TYPE_GROUP', 'class' => GroupPlugin::class]);
1032
+            $instance->registerPlugin(['shareType' => 'SHARE_TYPE_EMAIL', 'class' => MailPlugin::class]);
1033
+            $instance->registerPlugin(['shareType' => 'SHARE_TYPE_REMOTE', 'class' => RemotePlugin::class]);
1034
+
1035
+            return $instance;
1036
+        });
1037
+        $this->registerAlias('CollaboratorSearch', \OCP\Collaboration\Collaborators\ISearch::class);
1038
+
1039
+        $this->registerAlias(\OCP\Collaboration\AutoComplete\IManager::class, \OC\Collaboration\AutoComplete\Manager::class);
1040
+
1041
+        $this->registerService('SettingsManager', function (Server $c) {
1042
+            $manager = new \OC\Settings\Manager(
1043
+                $c->getLogger(),
1044
+                $c->getDatabaseConnection(),
1045
+                $c->getL10N('lib'),
1046
+                $c->getConfig(),
1047
+                $c->getEncryptionManager(),
1048
+                $c->getUserManager(),
1049
+                $c->getLockingProvider(),
1050
+                $c->getRequest(),
1051
+                new \OC\Settings\Mapper($c->getDatabaseConnection()),
1052
+                $c->getURLGenerator(),
1053
+                $c->query(AccountManager::class),
1054
+                $c->getGroupManager(),
1055
+                $c->getL10NFactory(),
1056
+                $c->getThemingDefaults(),
1057
+                $c->getAppManager()
1058
+            );
1059
+            return $manager;
1060
+        });
1061
+        $this->registerService(\OC\Files\AppData\Factory::class, function (Server $c) {
1062
+            return new \OC\Files\AppData\Factory(
1063
+                $c->getRootFolder(),
1064
+                $c->getSystemConfig()
1065
+            );
1066
+        });
1067
+
1068
+        $this->registerService('LockdownManager', function (Server $c) {
1069
+            return new LockdownManager(function () use ($c) {
1070
+                return $c->getSession();
1071
+            });
1072
+        });
1073
+
1074
+        $this->registerService(\OCP\OCS\IDiscoveryService::class, function (Server $c) {
1075
+            return new DiscoveryService($c->getMemCacheFactory(), $c->getHTTPClientService());
1076
+        });
1077
+
1078
+        $this->registerService(ICloudIdManager::class, function (Server $c) {
1079
+            return new CloudIdManager();
1080
+        });
1081
+
1082
+        /* To trick DI since we don't extend the DIContainer here */
1083
+        $this->registerService(CleanPreviewsBackgroundJob::class, function (Server $c) {
1084
+            return new CleanPreviewsBackgroundJob(
1085
+                $c->getRootFolder(),
1086
+                $c->getLogger(),
1087
+                $c->getJobList(),
1088
+                new TimeFactory()
1089
+            );
1090
+        });
1091
+
1092
+        $this->registerAlias(\OCP\AppFramework\Utility\IControllerMethodReflector::class, \OC\AppFramework\Utility\ControllerMethodReflector::class);
1093
+        $this->registerAlias('ControllerMethodReflector', \OCP\AppFramework\Utility\IControllerMethodReflector::class);
1094
+
1095
+        $this->registerAlias(\OCP\AppFramework\Utility\ITimeFactory::class, \OC\AppFramework\Utility\TimeFactory::class);
1096
+        $this->registerAlias('TimeFactory', \OCP\AppFramework\Utility\ITimeFactory::class);
1097
+
1098
+        $this->registerService(Defaults::class, function (Server $c) {
1099
+            return new Defaults(
1100
+                $c->getThemingDefaults()
1101
+            );
1102
+        });
1103
+        $this->registerAlias('Defaults', \OCP\Defaults::class);
1104
+
1105
+        $this->registerService(\OCP\ISession::class, function (SimpleContainer $c) {
1106
+            return $c->query(\OCP\IUserSession::class)->getSession();
1107
+        });
1108
+
1109
+        $this->registerService(IShareHelper::class, function (Server $c) {
1110
+            return new ShareHelper(
1111
+                $c->query(\OCP\Share\IManager::class)
1112
+            );
1113
+        });
1114
+
1115
+        $this->registerService(Installer::class, function(Server $c) {
1116
+            return new Installer(
1117
+                $c->getAppFetcher(),
1118
+                $c->getHTTPClientService(),
1119
+                $c->getTempManager(),
1120
+                $c->getLogger(),
1121
+                $c->getConfig()
1122
+            );
1123
+        });
1124
+
1125
+        $this->registerService(IApiFactory::class, function(Server $c) {
1126
+            return new ApiFactory($c->getHTTPClientService());
1127
+        });
1128
+
1129
+        $this->registerService(IInstanceFactory::class, function(Server $c) {
1130
+            $memcacheFactory = $c->getMemCacheFactory();
1131
+            return new InstanceFactory($memcacheFactory->createLocal('remoteinstance.'), $c->getHTTPClientService());
1132
+        });
1133
+
1134
+        $this->registerService(IContactsStore::class, function(Server $c) {
1135
+            return new ContactsStore(
1136
+                $c->getContactsManager(),
1137
+                $c->getConfig(),
1138
+                $c->getUserManager(),
1139
+                $c->getGroupManager()
1140
+            );
1141
+        });
1142
+        $this->registerAlias(IContactsStore::class, ContactsStore::class);
1143
+
1144
+        $this->connectDispatcher();
1145
+    }
1146
+
1147
+    /**
1148
+     * @return \OCP\Calendar\IManager
1149
+     */
1150
+    public function getCalendarManager() {
1151
+        return $this->query('CalendarManager');
1152
+    }
1153
+
1154
+    private function connectDispatcher() {
1155
+        $dispatcher = $this->getEventDispatcher();
1156
+
1157
+        // Delete avatar on user deletion
1158
+        $dispatcher->addListener('OCP\IUser::preDelete', function(GenericEvent $e) {
1159
+            $logger = $this->getLogger();
1160
+            $manager = $this->getAvatarManager();
1161
+            /** @var IUser $user */
1162
+            $user = $e->getSubject();
1163
+
1164
+            try {
1165
+                $avatar = $manager->getAvatar($user->getUID());
1166
+                $avatar->remove();
1167
+            } catch (NotFoundException $e) {
1168
+                // no avatar to remove
1169
+            } catch (\Exception $e) {
1170
+                // Ignore exceptions
1171
+                $logger->info('Could not cleanup avatar of ' . $user->getUID());
1172
+            }
1173
+        });
1174
+    }
1175
+
1176
+    /**
1177
+     * @return \OCP\Contacts\IManager
1178
+     */
1179
+    public function getContactsManager() {
1180
+        return $this->query('ContactsManager');
1181
+    }
1182
+
1183
+    /**
1184
+     * @return \OC\Encryption\Manager
1185
+     */
1186
+    public function getEncryptionManager() {
1187
+        return $this->query('EncryptionManager');
1188
+    }
1189
+
1190
+    /**
1191
+     * @return \OC\Encryption\File
1192
+     */
1193
+    public function getEncryptionFilesHelper() {
1194
+        return $this->query('EncryptionFileHelper');
1195
+    }
1196
+
1197
+    /**
1198
+     * @return \OCP\Encryption\Keys\IStorage
1199
+     */
1200
+    public function getEncryptionKeyStorage() {
1201
+        return $this->query('EncryptionKeyStorage');
1202
+    }
1203
+
1204
+    /**
1205
+     * The current request object holding all information about the request
1206
+     * currently being processed is returned from this method.
1207
+     * In case the current execution was not initiated by a web request null is returned
1208
+     *
1209
+     * @return \OCP\IRequest
1210
+     */
1211
+    public function getRequest() {
1212
+        return $this->query('Request');
1213
+    }
1214
+
1215
+    /**
1216
+     * Returns the preview manager which can create preview images for a given file
1217
+     *
1218
+     * @return \OCP\IPreview
1219
+     */
1220
+    public function getPreviewManager() {
1221
+        return $this->query('PreviewManager');
1222
+    }
1223
+
1224
+    /**
1225
+     * Returns the tag manager which can get and set tags for different object types
1226
+     *
1227
+     * @see \OCP\ITagManager::load()
1228
+     * @return \OCP\ITagManager
1229
+     */
1230
+    public function getTagManager() {
1231
+        return $this->query('TagManager');
1232
+    }
1233
+
1234
+    /**
1235
+     * Returns the system-tag manager
1236
+     *
1237
+     * @return \OCP\SystemTag\ISystemTagManager
1238
+     *
1239
+     * @since 9.0.0
1240
+     */
1241
+    public function getSystemTagManager() {
1242
+        return $this->query('SystemTagManager');
1243
+    }
1244
+
1245
+    /**
1246
+     * Returns the system-tag object mapper
1247
+     *
1248
+     * @return \OCP\SystemTag\ISystemTagObjectMapper
1249
+     *
1250
+     * @since 9.0.0
1251
+     */
1252
+    public function getSystemTagObjectMapper() {
1253
+        return $this->query('SystemTagObjectMapper');
1254
+    }
1255
+
1256
+    /**
1257
+     * Returns the avatar manager, used for avatar functionality
1258
+     *
1259
+     * @return \OCP\IAvatarManager
1260
+     */
1261
+    public function getAvatarManager() {
1262
+        return $this->query('AvatarManager');
1263
+    }
1264
+
1265
+    /**
1266
+     * Returns the root folder of ownCloud's data directory
1267
+     *
1268
+     * @return \OCP\Files\IRootFolder
1269
+     */
1270
+    public function getRootFolder() {
1271
+        return $this->query('LazyRootFolder');
1272
+    }
1273
+
1274
+    /**
1275
+     * Returns the root folder of ownCloud's data directory
1276
+     * This is the lazy variant so this gets only initialized once it
1277
+     * is actually used.
1278
+     *
1279
+     * @return \OCP\Files\IRootFolder
1280
+     */
1281
+    public function getLazyRootFolder() {
1282
+        return $this->query('LazyRootFolder');
1283
+    }
1284
+
1285
+    /**
1286
+     * Returns a view to ownCloud's files folder
1287
+     *
1288
+     * @param string $userId user ID
1289
+     * @return \OCP\Files\Folder|null
1290
+     */
1291
+    public function getUserFolder($userId = null) {
1292
+        if ($userId === null) {
1293
+            $user = $this->getUserSession()->getUser();
1294
+            if (!$user) {
1295
+                return null;
1296
+            }
1297
+            $userId = $user->getUID();
1298
+        }
1299
+        $root = $this->getRootFolder();
1300
+        return $root->getUserFolder($userId);
1301
+    }
1302
+
1303
+    /**
1304
+     * Returns an app-specific view in ownClouds data directory
1305
+     *
1306
+     * @return \OCP\Files\Folder
1307
+     * @deprecated since 9.2.0 use IAppData
1308
+     */
1309
+    public function getAppFolder() {
1310
+        $dir = '/' . \OC_App::getCurrentApp();
1311
+        $root = $this->getRootFolder();
1312
+        if (!$root->nodeExists($dir)) {
1313
+            $folder = $root->newFolder($dir);
1314
+        } else {
1315
+            $folder = $root->get($dir);
1316
+        }
1317
+        return $folder;
1318
+    }
1319
+
1320
+    /**
1321
+     * @return \OC\User\Manager
1322
+     */
1323
+    public function getUserManager() {
1324
+        return $this->query('UserManager');
1325
+    }
1326
+
1327
+    /**
1328
+     * @return \OC\Group\Manager
1329
+     */
1330
+    public function getGroupManager() {
1331
+        return $this->query('GroupManager');
1332
+    }
1333
+
1334
+    /**
1335
+     * @return \OC\User\Session
1336
+     */
1337
+    public function getUserSession() {
1338
+        return $this->query('UserSession');
1339
+    }
1340
+
1341
+    /**
1342
+     * @return \OCP\ISession
1343
+     */
1344
+    public function getSession() {
1345
+        return $this->query('UserSession')->getSession();
1346
+    }
1347
+
1348
+    /**
1349
+     * @param \OCP\ISession $session
1350
+     */
1351
+    public function setSession(\OCP\ISession $session) {
1352
+        $this->query(SessionStorage::class)->setSession($session);
1353
+        $this->query('UserSession')->setSession($session);
1354
+        $this->query(Store::class)->setSession($session);
1355
+    }
1356
+
1357
+    /**
1358
+     * @return \OC\Authentication\TwoFactorAuth\Manager
1359
+     */
1360
+    public function getTwoFactorAuthManager() {
1361
+        return $this->query('\OC\Authentication\TwoFactorAuth\Manager');
1362
+    }
1363
+
1364
+    /**
1365
+     * @return \OC\NavigationManager
1366
+     */
1367
+    public function getNavigationManager() {
1368
+        return $this->query('NavigationManager');
1369
+    }
1370
+
1371
+    /**
1372
+     * @return \OCP\IConfig
1373
+     */
1374
+    public function getConfig() {
1375
+        return $this->query('AllConfig');
1376
+    }
1377
+
1378
+    /**
1379
+     * @return \OC\SystemConfig
1380
+     */
1381
+    public function getSystemConfig() {
1382
+        return $this->query('SystemConfig');
1383
+    }
1384
+
1385
+    /**
1386
+     * Returns the app config manager
1387
+     *
1388
+     * @return \OCP\IAppConfig
1389
+     */
1390
+    public function getAppConfig() {
1391
+        return $this->query('AppConfig');
1392
+    }
1393
+
1394
+    /**
1395
+     * @return \OCP\L10N\IFactory
1396
+     */
1397
+    public function getL10NFactory() {
1398
+        return $this->query('L10NFactory');
1399
+    }
1400
+
1401
+    /**
1402
+     * get an L10N instance
1403
+     *
1404
+     * @param string $app appid
1405
+     * @param string $lang
1406
+     * @return IL10N
1407
+     */
1408
+    public function getL10N($app, $lang = null) {
1409
+        return $this->getL10NFactory()->get($app, $lang);
1410
+    }
1411
+
1412
+    /**
1413
+     * @return \OCP\IURLGenerator
1414
+     */
1415
+    public function getURLGenerator() {
1416
+        return $this->query('URLGenerator');
1417
+    }
1418
+
1419
+    /**
1420
+     * @return \OCP\IHelper
1421
+     */
1422
+    public function getHelper() {
1423
+        return $this->query('AppHelper');
1424
+    }
1425
+
1426
+    /**
1427
+     * @return AppFetcher
1428
+     */
1429
+    public function getAppFetcher() {
1430
+        return $this->query(AppFetcher::class);
1431
+    }
1432
+
1433
+    /**
1434
+     * Returns an ICache instance. Since 8.1.0 it returns a fake cache. Use
1435
+     * getMemCacheFactory() instead.
1436
+     *
1437
+     * @return \OCP\ICache
1438
+     * @deprecated 8.1.0 use getMemCacheFactory to obtain a proper cache
1439
+     */
1440
+    public function getCache() {
1441
+        return $this->query('UserCache');
1442
+    }
1443
+
1444
+    /**
1445
+     * Returns an \OCP\CacheFactory instance
1446
+     *
1447
+     * @return \OCP\ICacheFactory
1448
+     */
1449
+    public function getMemCacheFactory() {
1450
+        return $this->query('MemCacheFactory');
1451
+    }
1452
+
1453
+    /**
1454
+     * Returns an \OC\RedisFactory instance
1455
+     *
1456
+     * @return \OC\RedisFactory
1457
+     */
1458
+    public function getGetRedisFactory() {
1459
+        return $this->query('RedisFactory');
1460
+    }
1461
+
1462
+
1463
+    /**
1464
+     * Returns the current session
1465
+     *
1466
+     * @return \OCP\IDBConnection
1467
+     */
1468
+    public function getDatabaseConnection() {
1469
+        return $this->query('DatabaseConnection');
1470
+    }
1471
+
1472
+    /**
1473
+     * Returns the activity manager
1474
+     *
1475
+     * @return \OCP\Activity\IManager
1476
+     */
1477
+    public function getActivityManager() {
1478
+        return $this->query('ActivityManager');
1479
+    }
1480
+
1481
+    /**
1482
+     * Returns an job list for controlling background jobs
1483
+     *
1484
+     * @return \OCP\BackgroundJob\IJobList
1485
+     */
1486
+    public function getJobList() {
1487
+        return $this->query('JobList');
1488
+    }
1489
+
1490
+    /**
1491
+     * Returns a logger instance
1492
+     *
1493
+     * @return \OCP\ILogger
1494
+     */
1495
+    public function getLogger() {
1496
+        return $this->query('Logger');
1497
+    }
1498
+
1499
+    /**
1500
+     * Returns a router for generating and matching urls
1501
+     *
1502
+     * @return \OCP\Route\IRouter
1503
+     */
1504
+    public function getRouter() {
1505
+        return $this->query('Router');
1506
+    }
1507
+
1508
+    /**
1509
+     * Returns a search instance
1510
+     *
1511
+     * @return \OCP\ISearch
1512
+     */
1513
+    public function getSearch() {
1514
+        return $this->query('Search');
1515
+    }
1516
+
1517
+    /**
1518
+     * Returns a SecureRandom instance
1519
+     *
1520
+     * @return \OCP\Security\ISecureRandom
1521
+     */
1522
+    public function getSecureRandom() {
1523
+        return $this->query('SecureRandom');
1524
+    }
1525
+
1526
+    /**
1527
+     * Returns a Crypto instance
1528
+     *
1529
+     * @return \OCP\Security\ICrypto
1530
+     */
1531
+    public function getCrypto() {
1532
+        return $this->query('Crypto');
1533
+    }
1534
+
1535
+    /**
1536
+     * Returns a Hasher instance
1537
+     *
1538
+     * @return \OCP\Security\IHasher
1539
+     */
1540
+    public function getHasher() {
1541
+        return $this->query('Hasher');
1542
+    }
1543
+
1544
+    /**
1545
+     * Returns a CredentialsManager instance
1546
+     *
1547
+     * @return \OCP\Security\ICredentialsManager
1548
+     */
1549
+    public function getCredentialsManager() {
1550
+        return $this->query('CredentialsManager');
1551
+    }
1552
+
1553
+    /**
1554
+     * Returns an instance of the HTTP helper class
1555
+     *
1556
+     * @deprecated Use getHTTPClientService()
1557
+     * @return \OC\HTTPHelper
1558
+     */
1559
+    public function getHTTPHelper() {
1560
+        return $this->query('HTTPHelper');
1561
+    }
1562
+
1563
+    /**
1564
+     * Get the certificate manager for the user
1565
+     *
1566
+     * @param string $userId (optional) if not specified the current loggedin user is used, use null to get the system certificate manager
1567
+     * @return \OCP\ICertificateManager | null if $uid is null and no user is logged in
1568
+     */
1569
+    public function getCertificateManager($userId = '') {
1570
+        if ($userId === '') {
1571
+            $userSession = $this->getUserSession();
1572
+            $user = $userSession->getUser();
1573
+            if (is_null($user)) {
1574
+                return null;
1575
+            }
1576
+            $userId = $user->getUID();
1577
+        }
1578
+        return new CertificateManager(
1579
+            $userId,
1580
+            new View(),
1581
+            $this->getConfig(),
1582
+            $this->getLogger(),
1583
+            $this->getSecureRandom()
1584
+        );
1585
+    }
1586
+
1587
+    /**
1588
+     * Returns an instance of the HTTP client service
1589
+     *
1590
+     * @return \OCP\Http\Client\IClientService
1591
+     */
1592
+    public function getHTTPClientService() {
1593
+        return $this->query('HttpClientService');
1594
+    }
1595
+
1596
+    /**
1597
+     * Create a new event source
1598
+     *
1599
+     * @return \OCP\IEventSource
1600
+     */
1601
+    public function createEventSource() {
1602
+        return new \OC_EventSource();
1603
+    }
1604
+
1605
+    /**
1606
+     * Get the active event logger
1607
+     *
1608
+     * The returned logger only logs data when debug mode is enabled
1609
+     *
1610
+     * @return \OCP\Diagnostics\IEventLogger
1611
+     */
1612
+    public function getEventLogger() {
1613
+        return $this->query('EventLogger');
1614
+    }
1615
+
1616
+    /**
1617
+     * Get the active query logger
1618
+     *
1619
+     * The returned logger only logs data when debug mode is enabled
1620
+     *
1621
+     * @return \OCP\Diagnostics\IQueryLogger
1622
+     */
1623
+    public function getQueryLogger() {
1624
+        return $this->query('QueryLogger');
1625
+    }
1626
+
1627
+    /**
1628
+     * Get the manager for temporary files and folders
1629
+     *
1630
+     * @return \OCP\ITempManager
1631
+     */
1632
+    public function getTempManager() {
1633
+        return $this->query('TempManager');
1634
+    }
1635
+
1636
+    /**
1637
+     * Get the app manager
1638
+     *
1639
+     * @return \OCP\App\IAppManager
1640
+     */
1641
+    public function getAppManager() {
1642
+        return $this->query('AppManager');
1643
+    }
1644
+
1645
+    /**
1646
+     * Creates a new mailer
1647
+     *
1648
+     * @return \OCP\Mail\IMailer
1649
+     */
1650
+    public function getMailer() {
1651
+        return $this->query('Mailer');
1652
+    }
1653
+
1654
+    /**
1655
+     * Get the webroot
1656
+     *
1657
+     * @return string
1658
+     */
1659
+    public function getWebRoot() {
1660
+        return $this->webRoot;
1661
+    }
1662
+
1663
+    /**
1664
+     * @return \OC\OCSClient
1665
+     */
1666
+    public function getOcsClient() {
1667
+        return $this->query('OcsClient');
1668
+    }
1669
+
1670
+    /**
1671
+     * @return \OCP\IDateTimeZone
1672
+     */
1673
+    public function getDateTimeZone() {
1674
+        return $this->query('DateTimeZone');
1675
+    }
1676
+
1677
+    /**
1678
+     * @return \OCP\IDateTimeFormatter
1679
+     */
1680
+    public function getDateTimeFormatter() {
1681
+        return $this->query('DateTimeFormatter');
1682
+    }
1683
+
1684
+    /**
1685
+     * @return \OCP\Files\Config\IMountProviderCollection
1686
+     */
1687
+    public function getMountProviderCollection() {
1688
+        return $this->query('MountConfigManager');
1689
+    }
1690
+
1691
+    /**
1692
+     * Get the IniWrapper
1693
+     *
1694
+     * @return IniGetWrapper
1695
+     */
1696
+    public function getIniWrapper() {
1697
+        return $this->query('IniWrapper');
1698
+    }
1699
+
1700
+    /**
1701
+     * @return \OCP\Command\IBus
1702
+     */
1703
+    public function getCommandBus() {
1704
+        return $this->query('AsyncCommandBus');
1705
+    }
1706
+
1707
+    /**
1708
+     * Get the trusted domain helper
1709
+     *
1710
+     * @return TrustedDomainHelper
1711
+     */
1712
+    public function getTrustedDomainHelper() {
1713
+        return $this->query('TrustedDomainHelper');
1714
+    }
1715
+
1716
+    /**
1717
+     * Get the locking provider
1718
+     *
1719
+     * @return \OCP\Lock\ILockingProvider
1720
+     * @since 8.1.0
1721
+     */
1722
+    public function getLockingProvider() {
1723
+        return $this->query('LockingProvider');
1724
+    }
1725
+
1726
+    /**
1727
+     * @return \OCP\Files\Mount\IMountManager
1728
+     **/
1729
+    function getMountManager() {
1730
+        return $this->query('MountManager');
1731
+    }
1732
+
1733
+    /** @return \OCP\Files\Config\IUserMountCache */
1734
+    function getUserMountCache() {
1735
+        return $this->query('UserMountCache');
1736
+    }
1737
+
1738
+    /**
1739
+     * Get the MimeTypeDetector
1740
+     *
1741
+     * @return \OCP\Files\IMimeTypeDetector
1742
+     */
1743
+    public function getMimeTypeDetector() {
1744
+        return $this->query('MimeTypeDetector');
1745
+    }
1746
+
1747
+    /**
1748
+     * Get the MimeTypeLoader
1749
+     *
1750
+     * @return \OCP\Files\IMimeTypeLoader
1751
+     */
1752
+    public function getMimeTypeLoader() {
1753
+        return $this->query('MimeTypeLoader');
1754
+    }
1755
+
1756
+    /**
1757
+     * Get the manager of all the capabilities
1758
+     *
1759
+     * @return \OC\CapabilitiesManager
1760
+     */
1761
+    public function getCapabilitiesManager() {
1762
+        return $this->query('CapabilitiesManager');
1763
+    }
1764
+
1765
+    /**
1766
+     * Get the EventDispatcher
1767
+     *
1768
+     * @return EventDispatcherInterface
1769
+     * @since 8.2.0
1770
+     */
1771
+    public function getEventDispatcher() {
1772
+        return $this->query('EventDispatcher');
1773
+    }
1774
+
1775
+    /**
1776
+     * Get the Notification Manager
1777
+     *
1778
+     * @return \OCP\Notification\IManager
1779
+     * @since 8.2.0
1780
+     */
1781
+    public function getNotificationManager() {
1782
+        return $this->query('NotificationManager');
1783
+    }
1784
+
1785
+    /**
1786
+     * @return \OCP\Comments\ICommentsManager
1787
+     */
1788
+    public function getCommentsManager() {
1789
+        return $this->query('CommentsManager');
1790
+    }
1791
+
1792
+    /**
1793
+     * @return \OCA\Theming\ThemingDefaults
1794
+     */
1795
+    public function getThemingDefaults() {
1796
+        return $this->query('ThemingDefaults');
1797
+    }
1798
+
1799
+    /**
1800
+     * @return \OC\IntegrityCheck\Checker
1801
+     */
1802
+    public function getIntegrityCodeChecker() {
1803
+        return $this->query('IntegrityCodeChecker');
1804
+    }
1805
+
1806
+    /**
1807
+     * @return \OC\Session\CryptoWrapper
1808
+     */
1809
+    public function getSessionCryptoWrapper() {
1810
+        return $this->query('CryptoWrapper');
1811
+    }
1812
+
1813
+    /**
1814
+     * @return CsrfTokenManager
1815
+     */
1816
+    public function getCsrfTokenManager() {
1817
+        return $this->query('CsrfTokenManager');
1818
+    }
1819
+
1820
+    /**
1821
+     * @return Throttler
1822
+     */
1823
+    public function getBruteForceThrottler() {
1824
+        return $this->query('Throttler');
1825
+    }
1826
+
1827
+    /**
1828
+     * @return IContentSecurityPolicyManager
1829
+     */
1830
+    public function getContentSecurityPolicyManager() {
1831
+        return $this->query('ContentSecurityPolicyManager');
1832
+    }
1833
+
1834
+    /**
1835
+     * @return ContentSecurityPolicyNonceManager
1836
+     */
1837
+    public function getContentSecurityPolicyNonceManager() {
1838
+        return $this->query('ContentSecurityPolicyNonceManager');
1839
+    }
1840
+
1841
+    /**
1842
+     * Not a public API as of 8.2, wait for 9.0
1843
+     *
1844
+     * @return \OCA\Files_External\Service\BackendService
1845
+     */
1846
+    public function getStoragesBackendService() {
1847
+        return $this->query('OCA\\Files_External\\Service\\BackendService');
1848
+    }
1849
+
1850
+    /**
1851
+     * Not a public API as of 8.2, wait for 9.0
1852
+     *
1853
+     * @return \OCA\Files_External\Service\GlobalStoragesService
1854
+     */
1855
+    public function getGlobalStoragesService() {
1856
+        return $this->query('OCA\\Files_External\\Service\\GlobalStoragesService');
1857
+    }
1858
+
1859
+    /**
1860
+     * Not a public API as of 8.2, wait for 9.0
1861
+     *
1862
+     * @return \OCA\Files_External\Service\UserGlobalStoragesService
1863
+     */
1864
+    public function getUserGlobalStoragesService() {
1865
+        return $this->query('OCA\\Files_External\\Service\\UserGlobalStoragesService');
1866
+    }
1867
+
1868
+    /**
1869
+     * Not a public API as of 8.2, wait for 9.0
1870
+     *
1871
+     * @return \OCA\Files_External\Service\UserStoragesService
1872
+     */
1873
+    public function getUserStoragesService() {
1874
+        return $this->query('OCA\\Files_External\\Service\\UserStoragesService');
1875
+    }
1876
+
1877
+    /**
1878
+     * @return \OCP\Share\IManager
1879
+     */
1880
+    public function getShareManager() {
1881
+        return $this->query('ShareManager');
1882
+    }
1883
+
1884
+    /**
1885
+     * @return \OCP\Collaboration\Collaborators\ISearch
1886
+     */
1887
+    public function getCollaboratorSearch() {
1888
+        return $this->query('CollaboratorSearch');
1889
+    }
1890
+
1891
+    /**
1892
+     * @return \OCP\Collaboration\AutoComplete\IManager
1893
+     */
1894
+    public function getAutoCompleteManager(){
1895
+        return $this->query(IManager::class);
1896
+    }
1897
+
1898
+    /**
1899
+     * Returns the LDAP Provider
1900
+     *
1901
+     * @return \OCP\LDAP\ILDAPProvider
1902
+     */
1903
+    public function getLDAPProvider() {
1904
+        return $this->query('LDAPProvider');
1905
+    }
1906
+
1907
+    /**
1908
+     * @return \OCP\Settings\IManager
1909
+     */
1910
+    public function getSettingsManager() {
1911
+        return $this->query('SettingsManager');
1912
+    }
1913
+
1914
+    /**
1915
+     * @return \OCP\Files\IAppData
1916
+     */
1917
+    public function getAppDataDir($app) {
1918
+        /** @var \OC\Files\AppData\Factory $factory */
1919
+        $factory = $this->query(\OC\Files\AppData\Factory::class);
1920
+        return $factory->get($app);
1921
+    }
1922
+
1923
+    /**
1924
+     * @return \OCP\Lockdown\ILockdownManager
1925
+     */
1926
+    public function getLockdownManager() {
1927
+        return $this->query('LockdownManager');
1928
+    }
1929
+
1930
+    /**
1931
+     * @return \OCP\Federation\ICloudIdManager
1932
+     */
1933
+    public function getCloudIdManager() {
1934
+        return $this->query(ICloudIdManager::class);
1935
+    }
1936
+
1937
+    /**
1938
+     * @return \OCP\Remote\Api\IApiFactory
1939
+     */
1940
+    public function getRemoteApiFactory() {
1941
+        return $this->query(IApiFactory::class);
1942
+    }
1943
+
1944
+    /**
1945
+     * @return \OCP\Remote\IInstanceFactory
1946
+     */
1947
+    public function getRemoteInstanceFactory() {
1948
+        return $this->query(IInstanceFactory::class);
1949
+    }
1950 1950
 }
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.