Passed
Push — master ( 645109...008e6d )
by Christoph
12:14 queued 12s
created
lib/private/Template/Base.php 3 patches
Indentation   +155 added lines, -155 removed lines patch added patch discarded remove patch
@@ -33,160 +33,160 @@
 block discarded – undo
33 33
 use OCP\Defaults;
34 34
 
35 35
 class Base {
36
-	private $template; // The template
37
-	private $vars; // Vars
38
-
39
-	/** @var \OCP\IL10N */
40
-	private $l10n;
41
-
42
-	/** @var Defaults */
43
-	private $theme;
44
-
45
-	/**
46
-	 * @param string $template
47
-	 * @param string $requestToken
48
-	 * @param \OCP\IL10N $l10n
49
-	 * @param Defaults $theme
50
-	 */
51
-	public function __construct($template, $requestToken, $l10n, $theme) {
52
-		$this->vars = [];
53
-		$this->vars['requesttoken'] = $requestToken;
54
-		$this->l10n = $l10n;
55
-		$this->template = $template;
56
-		$this->theme = $theme;
57
-	}
58
-
59
-	/**
60
-	 * @param string $serverRoot
61
-	 * @param string|false $app_dir
62
-	 * @param string $theme
63
-	 * @param string $app
64
-	 * @return string[]
65
-	 */
66
-	protected function getAppTemplateDirs($theme, $app, $serverRoot, $app_dir) {
67
-		// Check if the app is in the app folder or in the root
68
-		if(file_exists($app_dir.'/templates/')) {
69
-			return [
70
-				$serverRoot.'/themes/'.$theme.'/apps/'.$app.'/templates/',
71
-				$app_dir.'/templates/',
72
-			];
73
-		}
74
-		return [
75
-			$serverRoot.'/themes/'.$theme.'/'.$app.'/templates/',
76
-			$serverRoot.'/'.$app.'/templates/',
77
-		];
78
-	}
79
-
80
-	/**
81
-	 * @param string $serverRoot
82
-	 * @param string $theme
83
-	 * @return string[]
84
-	 */
85
-	protected function getCoreTemplateDirs($theme, $serverRoot) {
86
-		return [
87
-			$serverRoot.'/themes/'.$theme.'/core/templates/',
88
-			$serverRoot.'/core/templates/',
89
-		];
90
-	}
91
-
92
-	/**
93
-	 * Assign variables
94
-	 * @param string $key key
95
-	 * @param array|bool|integer|string $value value
96
-	 * @return bool
97
-	 *
98
-	 * This function assigns a variable. It can be accessed via $_[$key] in
99
-	 * the template.
100
-	 *
101
-	 * If the key existed before, it will be overwritten
102
-	 */
103
-	public function assign($key, $value) {
104
-		$this->vars[$key] = $value;
105
-		return true;
106
-	}
107
-
108
-	/**
109
-	 * Appends a variable
110
-	 * @param string $key key
111
-	 * @param mixed $value value
112
-	 *
113
-	 * This function assigns a variable in an array context. If the key already
114
-	 * exists, the value will be appended. It can be accessed via
115
-	 * $_[$key][$position] in the template.
116
-	 */
117
-	public function append($key, $value) {
118
-		if(array_key_exists($key, $this->vars)) {
119
-			$this->vars[$key][] = $value;
120
-		}
121
-		else{
122
-			$this->vars[$key] = [ $value ];
123
-		}
124
-	}
125
-
126
-	/**
127
-	 * Prints the proceeded template
128
-	 * @return bool
129
-	 *
130
-	 * This function proceeds the template and prints its output.
131
-	 */
132
-	public function printPage() {
133
-		$data = $this->fetchPage();
134
-		if($data === false) {
135
-			return false;
136
-		}
137
-		else{
138
-			print $data;
139
-			return true;
140
-		}
141
-	}
142
-
143
-	/**
144
-	 * Process the template
145
-	 *
146
-	 * @param array|null $additionalParams
147
-	 * @return string This function processes the template.
148
-	 *
149
-	 * This function processes the template.
150
-	 */
151
-	public function fetchPage($additionalParams = null) {
152
-		return $this->load($this->template, $additionalParams);
153
-	}
154
-
155
-	/**
156
-	 * doing the actual work
157
-	 *
158
-	 * @param string $file
159
-	 * @param array|null $additionalParams
160
-	 * @return string content
161
-	 *
162
-	 * Includes the template file, fetches its output
163
-	 */
164
-	protected function load($file, $additionalParams = null) {
165
-		// Register the variables
166
-		$_ = $this->vars;
167
-		$l = $this->l10n;
168
-		$theme = $this->theme;
169
-
170
-		if(!is_null($additionalParams)) {
171
-			$_ = array_merge($additionalParams, $this->vars);
172
-			foreach ($_ as $var => $value) {
173
-				${$var} = $value;
174
-			}
175
-		}
176
-
177
-		// Include
178
-		ob_start();
179
-		try {
180
-			include $file;
181
-			$data = ob_get_contents();
182
-		} catch (\Exception $e) {
183
-			@ob_end_clean();
184
-			throw $e;
185
-		}
186
-		@ob_end_clean();
187
-
188
-		// Return data
189
-		return $data;
190
-	}
36
+    private $template; // The template
37
+    private $vars; // Vars
38
+
39
+    /** @var \OCP\IL10N */
40
+    private $l10n;
41
+
42
+    /** @var Defaults */
43
+    private $theme;
44
+
45
+    /**
46
+     * @param string $template
47
+     * @param string $requestToken
48
+     * @param \OCP\IL10N $l10n
49
+     * @param Defaults $theme
50
+     */
51
+    public function __construct($template, $requestToken, $l10n, $theme) {
52
+        $this->vars = [];
53
+        $this->vars['requesttoken'] = $requestToken;
54
+        $this->l10n = $l10n;
55
+        $this->template = $template;
56
+        $this->theme = $theme;
57
+    }
58
+
59
+    /**
60
+     * @param string $serverRoot
61
+     * @param string|false $app_dir
62
+     * @param string $theme
63
+     * @param string $app
64
+     * @return string[]
65
+     */
66
+    protected function getAppTemplateDirs($theme, $app, $serverRoot, $app_dir) {
67
+        // Check if the app is in the app folder or in the root
68
+        if(file_exists($app_dir.'/templates/')) {
69
+            return [
70
+                $serverRoot.'/themes/'.$theme.'/apps/'.$app.'/templates/',
71
+                $app_dir.'/templates/',
72
+            ];
73
+        }
74
+        return [
75
+            $serverRoot.'/themes/'.$theme.'/'.$app.'/templates/',
76
+            $serverRoot.'/'.$app.'/templates/',
77
+        ];
78
+    }
79
+
80
+    /**
81
+     * @param string $serverRoot
82
+     * @param string $theme
83
+     * @return string[]
84
+     */
85
+    protected function getCoreTemplateDirs($theme, $serverRoot) {
86
+        return [
87
+            $serverRoot.'/themes/'.$theme.'/core/templates/',
88
+            $serverRoot.'/core/templates/',
89
+        ];
90
+    }
91
+
92
+    /**
93
+     * Assign variables
94
+     * @param string $key key
95
+     * @param array|bool|integer|string $value value
96
+     * @return bool
97
+     *
98
+     * This function assigns a variable. It can be accessed via $_[$key] in
99
+     * the template.
100
+     *
101
+     * If the key existed before, it will be overwritten
102
+     */
103
+    public function assign($key, $value) {
104
+        $this->vars[$key] = $value;
105
+        return true;
106
+    }
107
+
108
+    /**
109
+     * Appends a variable
110
+     * @param string $key key
111
+     * @param mixed $value value
112
+     *
113
+     * This function assigns a variable in an array context. If the key already
114
+     * exists, the value will be appended. It can be accessed via
115
+     * $_[$key][$position] in the template.
116
+     */
117
+    public function append($key, $value) {
118
+        if(array_key_exists($key, $this->vars)) {
119
+            $this->vars[$key][] = $value;
120
+        }
121
+        else{
122
+            $this->vars[$key] = [ $value ];
123
+        }
124
+    }
125
+
126
+    /**
127
+     * Prints the proceeded template
128
+     * @return bool
129
+     *
130
+     * This function proceeds the template and prints its output.
131
+     */
132
+    public function printPage() {
133
+        $data = $this->fetchPage();
134
+        if($data === false) {
135
+            return false;
136
+        }
137
+        else{
138
+            print $data;
139
+            return true;
140
+        }
141
+    }
142
+
143
+    /**
144
+     * Process the template
145
+     *
146
+     * @param array|null $additionalParams
147
+     * @return string This function processes the template.
148
+     *
149
+     * This function processes the template.
150
+     */
151
+    public function fetchPage($additionalParams = null) {
152
+        return $this->load($this->template, $additionalParams);
153
+    }
154
+
155
+    /**
156
+     * doing the actual work
157
+     *
158
+     * @param string $file
159
+     * @param array|null $additionalParams
160
+     * @return string content
161
+     *
162
+     * Includes the template file, fetches its output
163
+     */
164
+    protected function load($file, $additionalParams = null) {
165
+        // Register the variables
166
+        $_ = $this->vars;
167
+        $l = $this->l10n;
168
+        $theme = $this->theme;
169
+
170
+        if(!is_null($additionalParams)) {
171
+            $_ = array_merge($additionalParams, $this->vars);
172
+            foreach ($_ as $var => $value) {
173
+                ${$var} = $value;
174
+            }
175
+        }
176
+
177
+        // Include
178
+        ob_start();
179
+        try {
180
+            include $file;
181
+            $data = ob_get_contents();
182
+        } catch (\Exception $e) {
183
+            @ob_end_clean();
184
+            throw $e;
185
+        }
186
+        @ob_end_clean();
187
+
188
+        // Return data
189
+        return $data;
190
+    }
191 191
 
192 192
 }
Please login to merge, or discard this patch.
Spacing   +7 added lines, -7 removed lines patch added patch discarded remove patch
@@ -65,7 +65,7 @@  discard block
 block discarded – undo
65 65
 	 */
66 66
 	protected function getAppTemplateDirs($theme, $app, $serverRoot, $app_dir) {
67 67
 		// Check if the app is in the app folder or in the root
68
-		if(file_exists($app_dir.'/templates/')) {
68
+		if (file_exists($app_dir.'/templates/')) {
69 69
 			return [
70 70
 				$serverRoot.'/themes/'.$theme.'/apps/'.$app.'/templates/',
71 71
 				$app_dir.'/templates/',
@@ -115,11 +115,11 @@  discard block
 block discarded – undo
115 115
 	 * $_[$key][$position] in the template.
116 116
 	 */
117 117
 	public function append($key, $value) {
118
-		if(array_key_exists($key, $this->vars)) {
118
+		if (array_key_exists($key, $this->vars)) {
119 119
 			$this->vars[$key][] = $value;
120 120
 		}
121
-		else{
122
-			$this->vars[$key] = [ $value ];
121
+		else {
122
+			$this->vars[$key] = [$value];
123 123
 		}
124 124
 	}
125 125
 
@@ -131,10 +131,10 @@  discard block
 block discarded – undo
131 131
 	 */
132 132
 	public function printPage() {
133 133
 		$data = $this->fetchPage();
134
-		if($data === false) {
134
+		if ($data === false) {
135 135
 			return false;
136 136
 		}
137
-		else{
137
+		else {
138 138
 			print $data;
139 139
 			return true;
140 140
 		}
@@ -167,7 +167,7 @@  discard block
 block discarded – undo
167 167
 		$l = $this->l10n;
168 168
 		$theme = $this->theme;
169 169
 
170
-		if(!is_null($additionalParams)) {
170
+		if (!is_null($additionalParams)) {
171 171
 			$_ = array_merge($additionalParams, $this->vars);
172 172
 			foreach ($_ as $var => $value) {
173 173
 				${$var} = $value;
Please login to merge, or discard this patch.
Braces   +2 added lines, -4 removed lines patch added patch discarded remove patch
@@ -117,8 +117,7 @@  discard block
 block discarded – undo
117 117
 	public function append($key, $value) {
118 118
 		if(array_key_exists($key, $this->vars)) {
119 119
 			$this->vars[$key][] = $value;
120
-		}
121
-		else{
120
+		} else{
122 121
 			$this->vars[$key] = [ $value ];
123 122
 		}
124 123
 	}
@@ -133,8 +132,7 @@  discard block
 block discarded – undo
133 132
 		$data = $this->fetchPage();
134 133
 		if($data === false) {
135 134
 			return false;
136
-		}
137
-		else{
135
+		} else{
138 136
 			print $data;
139 137
 			return true;
140 138
 		}
Please login to merge, or discard this patch.
lib/private/Encryption/Util.php 2 patches
Indentation   +369 added lines, -369 removed lines patch added patch discarded remove patch
@@ -39,374 +39,374 @@
 block discarded – undo
39 39
 
40 40
 class Util {
41 41
 
42
-	const HEADER_START = 'HBEGIN';
43
-	const HEADER_END = 'HEND';
44
-	const HEADER_PADDING_CHAR = '-';
45
-
46
-	const HEADER_ENCRYPTION_MODULE_KEY = 'oc_encryption_module';
47
-
48
-	/**
49
-	 * block size will always be 8192 for a PHP stream
50
-	 * @see https://bugs.php.net/bug.php?id=21641
51
-	 * @var integer
52
-	 */
53
-	protected $headerSize = 8192;
54
-
55
-	/**
56
-	 * block size will always be 8192 for a PHP stream
57
-	 * @see https://bugs.php.net/bug.php?id=21641
58
-	 * @var integer
59
-	 */
60
-	protected $blockSize = 8192;
61
-
62
-	/** @var View */
63
-	protected $rootView;
64
-
65
-	/** @var array */
66
-	protected $ocHeaderKeys;
67
-
68
-	/** @var \OC\User\Manager */
69
-	protected $userManager;
70
-
71
-	/** @var IConfig */
72
-	protected $config;
73
-
74
-	/** @var array paths excluded from encryption */
75
-	protected $excludedPaths;
76
-
77
-	/** @var \OC\Group\Manager $manager */
78
-	protected $groupManager;
79
-
80
-	/**
81
-	 *
82
-	 * @param View $rootView
83
-	 * @param \OC\User\Manager $userManager
84
-	 * @param \OC\Group\Manager $groupManager
85
-	 * @param IConfig $config
86
-	 */
87
-	public function __construct(
88
-		View $rootView,
89
-		\OC\User\Manager $userManager,
90
-		\OC\Group\Manager $groupManager,
91
-		IConfig $config) {
92
-
93
-		$this->ocHeaderKeys = [
94
-			self::HEADER_ENCRYPTION_MODULE_KEY
95
-		];
96
-
97
-		$this->rootView = $rootView;
98
-		$this->userManager = $userManager;
99
-		$this->groupManager = $groupManager;
100
-		$this->config = $config;
101
-
102
-		$this->excludedPaths[] = 'files_encryption';
103
-		$this->excludedPaths[] = 'appdata_' . $config->getSystemValue('instanceid', null);
104
-		$this->excludedPaths[] = 'files_external';
105
-	}
106
-
107
-	/**
108
-	 * read encryption module ID from header
109
-	 *
110
-	 * @param array $header
111
-	 * @return string
112
-	 * @throws ModuleDoesNotExistsException
113
-	 */
114
-	public function getEncryptionModuleId(array $header = null) {
115
-		$id = '';
116
-		$encryptionModuleKey = self::HEADER_ENCRYPTION_MODULE_KEY;
117
-
118
-		if (isset($header[$encryptionModuleKey])) {
119
-			$id = $header[$encryptionModuleKey];
120
-		} elseif (isset($header['cipher'])) {
121
-			if (class_exists('\OCA\Encryption\Crypto\Encryption')) {
122
-				// fall back to default encryption if the user migrated from
123
-				// ownCloud <= 8.0 with the old encryption
124
-				$id = \OCA\Encryption\Crypto\Encryption::ID;
125
-			} else {
126
-				throw new ModuleDoesNotExistsException('Default encryption module missing');
127
-			}
128
-		}
129
-
130
-		return $id;
131
-	}
132
-
133
-	/**
134
-	 * create header for encrypted file
135
-	 *
136
-	 * @param array $headerData
137
-	 * @param IEncryptionModule $encryptionModule
138
-	 * @return string
139
-	 * @throws EncryptionHeaderToLargeException if header has to many arguments
140
-	 * @throws EncryptionHeaderKeyExistsException if header key is already in use
141
-	 */
142
-	public function createHeader(array $headerData, IEncryptionModule $encryptionModule) {
143
-		$header = self::HEADER_START . ':' . self::HEADER_ENCRYPTION_MODULE_KEY . ':' . $encryptionModule->getId() . ':';
144
-		foreach ($headerData as $key => $value) {
145
-			if (in_array($key, $this->ocHeaderKeys)) {
146
-				throw new EncryptionHeaderKeyExistsException($key);
147
-			}
148
-			$header .= $key . ':' . $value . ':';
149
-		}
150
-		$header .= self::HEADER_END;
151
-
152
-		if (strlen($header) > $this->getHeaderSize()) {
153
-			throw new EncryptionHeaderToLargeException();
154
-		}
155
-
156
-		$paddedHeader = str_pad($header, $this->headerSize, self::HEADER_PADDING_CHAR, STR_PAD_RIGHT);
157
-
158
-		return $paddedHeader;
159
-	}
160
-
161
-	/**
162
-	 * go recursively through a dir and collect all files and sub files.
163
-	 *
164
-	 * @param string $dir relative to the users files folder
165
-	 * @return array with list of files relative to the users files folder
166
-	 */
167
-	public function getAllFiles($dir) {
168
-		$result = [];
169
-		$dirList = [$dir];
170
-
171
-		while ($dirList) {
172
-			$dir = array_pop($dirList);
173
-			$content = $this->rootView->getDirectoryContent($dir);
174
-
175
-			foreach ($content as $c) {
176
-				if ($c->getType() === 'dir') {
177
-					$dirList[] = $c->getPath();
178
-				} else {
179
-					$result[] =  $c->getPath();
180
-				}
181
-			}
182
-
183
-		}
184
-
185
-		return $result;
186
-	}
187
-
188
-	/**
189
-	 * check if it is a file uploaded by the user stored in data/user/files
190
-	 * or a metadata file
191
-	 *
192
-	 * @param string $path relative to the data/ folder
193
-	 * @return boolean
194
-	 */
195
-	public function isFile($path) {
196
-		$parts = explode('/', Filesystem::normalizePath($path), 4);
197
-		if (isset($parts[2]) && $parts[2] === 'files') {
198
-			return true;
199
-		}
200
-		return false;
201
-	}
202
-
203
-	/**
204
-	 * return size of encryption header
205
-	 *
206
-	 * @return integer
207
-	 */
208
-	public function getHeaderSize() {
209
-		return $this->headerSize;
210
-	}
211
-
212
-	/**
213
-	 * return size of block read by a PHP stream
214
-	 *
215
-	 * @return integer
216
-	 */
217
-	public function getBlockSize() {
218
-		return $this->blockSize;
219
-	}
220
-
221
-	/**
222
-	 * get the owner and the path for the file relative to the owners files folder
223
-	 *
224
-	 * @param string $path
225
-	 * @return array
226
-	 * @throws \BadMethodCallException
227
-	 */
228
-	public function getUidAndFilename($path) {
229
-
230
-		$parts = explode('/', $path);
231
-		$uid = '';
232
-		if (count($parts) > 2) {
233
-			$uid = $parts[1];
234
-		}
235
-		if (!$this->userManager->userExists($uid)) {
236
-			throw new \BadMethodCallException(
237
-				'path needs to be relative to the system wide data folder and point to a user specific file'
238
-			);
239
-		}
240
-
241
-		$ownerPath = implode('/', array_slice($parts, 2));
242
-
243
-		return [$uid, Filesystem::normalizePath($ownerPath)];
244
-
245
-	}
246
-
247
-	/**
248
-	 * Remove .path extension from a file path
249
-	 * @param string $path Path that may identify a .part file
250
-	 * @return string File path without .part extension
251
-	 * @note this is needed for reusing keys
252
-	 */
253
-	public function stripPartialFileExtension($path) {
254
-		$extension = pathinfo($path, PATHINFO_EXTENSION);
255
-
256
-		if ($extension === 'part') {
257
-
258
-			$newLength = strlen($path) - 5; // 5 = strlen(".part")
259
-			$fPath = substr($path, 0, $newLength);
260
-
261
-			// if path also contains a transaction id, we remove it too
262
-			$extension = pathinfo($fPath, PATHINFO_EXTENSION);
263
-			if(substr($extension, 0, 12) === 'ocTransferId') { // 12 = strlen("ocTransferId")
264
-				$newLength = strlen($fPath) - strlen($extension) -1;
265
-				$fPath = substr($fPath, 0, $newLength);
266
-			}
267
-			return $fPath;
268
-
269
-		} else {
270
-			return $path;
271
-		}
272
-	}
273
-
274
-	public function getUserWithAccessToMountPoint($users, $groups) {
275
-		$result = [];
276
-		if (in_array('all', $users)) {
277
-			$users = $this->userManager->search('', null, null);
278
-			$result = array_map(function (IUser $user) {
279
-				return $user->getUID();
280
-			}, $users);
281
-		} else {
282
-			$result = array_merge($result, $users);
283
-
284
-			$groupManager = \OC::$server->getGroupManager();
285
-			foreach ($groups as $group) {
286
-				$groupObject = $groupManager->get($group);
287
-				if ($groupObject) {
288
-					$foundUsers = $groupObject->searchUsers('', -1, 0);
289
-					$userIds = [];
290
-					foreach ($foundUsers as $user) {
291
-						$userIds[] = $user->getUID();
292
-					}
293
-					$result = array_merge($result, $userIds);
294
-				}
295
-			}
296
-		}
297
-
298
-		return $result;
299
-	}
300
-
301
-	/**
302
-	 * check if the file is stored on a system wide mount point
303
-	 * @param string $path relative to /data/user with leading '/'
304
-	 * @param string $uid
305
-	 * @return boolean
306
-	 */
307
-	public function isSystemWideMountPoint($path, $uid) {
308
-		if (\OCP\App::isEnabled("files_external")) {
309
-			$mounts = \OC_Mount_Config::getSystemMountPoints();
310
-			foreach ($mounts as $mount) {
311
-				if (strpos($path, '/files/' . $mount['mountpoint']) === 0) {
312
-					if ($this->isMountPointApplicableToUser($mount, $uid)) {
313
-						return true;
314
-					}
315
-				}
316
-			}
317
-		}
318
-		return false;
319
-	}
320
-
321
-	/**
322
-	 * check if mount point is applicable to user
323
-	 *
324
-	 * @param array $mount contains $mount['applicable']['users'], $mount['applicable']['groups']
325
-	 * @param string $uid
326
-	 * @return boolean
327
-	 */
328
-	private function isMountPointApplicableToUser($mount, $uid) {
329
-		$acceptedUids = ['all', $uid];
330
-		// check if mount point is applicable for the user
331
-		$intersection = array_intersect($acceptedUids, $mount['applicable']['users']);
332
-		if (!empty($intersection)) {
333
-			return true;
334
-		}
335
-		// check if mount point is applicable for group where the user is a member
336
-		foreach ($mount['applicable']['groups'] as $gid) {
337
-			if ($this->groupManager->isInGroup($uid, $gid)) {
338
-				return true;
339
-			}
340
-		}
341
-		return false;
342
-	}
343
-
344
-	/**
345
-	 * check if it is a path which is excluded by ownCloud from encryption
346
-	 *
347
-	 * @param string $path
348
-	 * @return boolean
349
-	 */
350
-	public function isExcluded($path) {
351
-		$normalizedPath = Filesystem::normalizePath($path);
352
-		$root = explode('/', $normalizedPath, 4);
353
-		if (count($root) > 1) {
354
-
355
-			// detect alternative key storage root
356
-			$rootDir = $this->getKeyStorageRoot();
357
-			if ($rootDir !== '' &&
358
-				0 === strpos(
359
-					Filesystem::normalizePath($path),
360
-					Filesystem::normalizePath($rootDir)
361
-				)
362
-			) {
363
-				return true;
364
-			}
365
-
366
-
367
-			//detect system wide folders
368
-			if (in_array($root[1], $this->excludedPaths)) {
369
-				return true;
370
-			}
371
-
372
-			// detect user specific folders
373
-			if ($this->userManager->userExists($root[1])
374
-				&& in_array($root[2], $this->excludedPaths)) {
375
-
376
-				return true;
377
-			}
378
-		}
379
-		return false;
380
-	}
381
-
382
-	/**
383
-	 * check if recovery key is enabled for user
384
-	 *
385
-	 * @param string $uid
386
-	 * @return boolean
387
-	 */
388
-	public function recoveryEnabled($uid) {
389
-		$enabled = $this->config->getUserValue($uid, 'encryption', 'recovery_enabled', '0');
390
-
391
-		return $enabled === '1';
392
-	}
393
-
394
-	/**
395
-	 * set new key storage root
396
-	 *
397
-	 * @param string $root new key store root relative to the data folder
398
-	 */
399
-	public function setKeyStorageRoot($root) {
400
-		$this->config->setAppValue('core', 'encryption_key_storage_root', $root);
401
-	}
402
-
403
-	/**
404
-	 * get key storage root
405
-	 *
406
-	 * @return string key storage root
407
-	 */
408
-	public function getKeyStorageRoot() {
409
-		return $this->config->getAppValue('core', 'encryption_key_storage_root', '');
410
-	}
42
+    const HEADER_START = 'HBEGIN';
43
+    const HEADER_END = 'HEND';
44
+    const HEADER_PADDING_CHAR = '-';
45
+
46
+    const HEADER_ENCRYPTION_MODULE_KEY = 'oc_encryption_module';
47
+
48
+    /**
49
+     * block size will always be 8192 for a PHP stream
50
+     * @see https://bugs.php.net/bug.php?id=21641
51
+     * @var integer
52
+     */
53
+    protected $headerSize = 8192;
54
+
55
+    /**
56
+     * block size will always be 8192 for a PHP stream
57
+     * @see https://bugs.php.net/bug.php?id=21641
58
+     * @var integer
59
+     */
60
+    protected $blockSize = 8192;
61
+
62
+    /** @var View */
63
+    protected $rootView;
64
+
65
+    /** @var array */
66
+    protected $ocHeaderKeys;
67
+
68
+    /** @var \OC\User\Manager */
69
+    protected $userManager;
70
+
71
+    /** @var IConfig */
72
+    protected $config;
73
+
74
+    /** @var array paths excluded from encryption */
75
+    protected $excludedPaths;
76
+
77
+    /** @var \OC\Group\Manager $manager */
78
+    protected $groupManager;
79
+
80
+    /**
81
+     *
82
+     * @param View $rootView
83
+     * @param \OC\User\Manager $userManager
84
+     * @param \OC\Group\Manager $groupManager
85
+     * @param IConfig $config
86
+     */
87
+    public function __construct(
88
+        View $rootView,
89
+        \OC\User\Manager $userManager,
90
+        \OC\Group\Manager $groupManager,
91
+        IConfig $config) {
92
+
93
+        $this->ocHeaderKeys = [
94
+            self::HEADER_ENCRYPTION_MODULE_KEY
95
+        ];
96
+
97
+        $this->rootView = $rootView;
98
+        $this->userManager = $userManager;
99
+        $this->groupManager = $groupManager;
100
+        $this->config = $config;
101
+
102
+        $this->excludedPaths[] = 'files_encryption';
103
+        $this->excludedPaths[] = 'appdata_' . $config->getSystemValue('instanceid', null);
104
+        $this->excludedPaths[] = 'files_external';
105
+    }
106
+
107
+    /**
108
+     * read encryption module ID from header
109
+     *
110
+     * @param array $header
111
+     * @return string
112
+     * @throws ModuleDoesNotExistsException
113
+     */
114
+    public function getEncryptionModuleId(array $header = null) {
115
+        $id = '';
116
+        $encryptionModuleKey = self::HEADER_ENCRYPTION_MODULE_KEY;
117
+
118
+        if (isset($header[$encryptionModuleKey])) {
119
+            $id = $header[$encryptionModuleKey];
120
+        } elseif (isset($header['cipher'])) {
121
+            if (class_exists('\OCA\Encryption\Crypto\Encryption')) {
122
+                // fall back to default encryption if the user migrated from
123
+                // ownCloud <= 8.0 with the old encryption
124
+                $id = \OCA\Encryption\Crypto\Encryption::ID;
125
+            } else {
126
+                throw new ModuleDoesNotExistsException('Default encryption module missing');
127
+            }
128
+        }
129
+
130
+        return $id;
131
+    }
132
+
133
+    /**
134
+     * create header for encrypted file
135
+     *
136
+     * @param array $headerData
137
+     * @param IEncryptionModule $encryptionModule
138
+     * @return string
139
+     * @throws EncryptionHeaderToLargeException if header has to many arguments
140
+     * @throws EncryptionHeaderKeyExistsException if header key is already in use
141
+     */
142
+    public function createHeader(array $headerData, IEncryptionModule $encryptionModule) {
143
+        $header = self::HEADER_START . ':' . self::HEADER_ENCRYPTION_MODULE_KEY . ':' . $encryptionModule->getId() . ':';
144
+        foreach ($headerData as $key => $value) {
145
+            if (in_array($key, $this->ocHeaderKeys)) {
146
+                throw new EncryptionHeaderKeyExistsException($key);
147
+            }
148
+            $header .= $key . ':' . $value . ':';
149
+        }
150
+        $header .= self::HEADER_END;
151
+
152
+        if (strlen($header) > $this->getHeaderSize()) {
153
+            throw new EncryptionHeaderToLargeException();
154
+        }
155
+
156
+        $paddedHeader = str_pad($header, $this->headerSize, self::HEADER_PADDING_CHAR, STR_PAD_RIGHT);
157
+
158
+        return $paddedHeader;
159
+    }
160
+
161
+    /**
162
+     * go recursively through a dir and collect all files and sub files.
163
+     *
164
+     * @param string $dir relative to the users files folder
165
+     * @return array with list of files relative to the users files folder
166
+     */
167
+    public function getAllFiles($dir) {
168
+        $result = [];
169
+        $dirList = [$dir];
170
+
171
+        while ($dirList) {
172
+            $dir = array_pop($dirList);
173
+            $content = $this->rootView->getDirectoryContent($dir);
174
+
175
+            foreach ($content as $c) {
176
+                if ($c->getType() === 'dir') {
177
+                    $dirList[] = $c->getPath();
178
+                } else {
179
+                    $result[] =  $c->getPath();
180
+                }
181
+            }
182
+
183
+        }
184
+
185
+        return $result;
186
+    }
187
+
188
+    /**
189
+     * check if it is a file uploaded by the user stored in data/user/files
190
+     * or a metadata file
191
+     *
192
+     * @param string $path relative to the data/ folder
193
+     * @return boolean
194
+     */
195
+    public function isFile($path) {
196
+        $parts = explode('/', Filesystem::normalizePath($path), 4);
197
+        if (isset($parts[2]) && $parts[2] === 'files') {
198
+            return true;
199
+        }
200
+        return false;
201
+    }
202
+
203
+    /**
204
+     * return size of encryption header
205
+     *
206
+     * @return integer
207
+     */
208
+    public function getHeaderSize() {
209
+        return $this->headerSize;
210
+    }
211
+
212
+    /**
213
+     * return size of block read by a PHP stream
214
+     *
215
+     * @return integer
216
+     */
217
+    public function getBlockSize() {
218
+        return $this->blockSize;
219
+    }
220
+
221
+    /**
222
+     * get the owner and the path for the file relative to the owners files folder
223
+     *
224
+     * @param string $path
225
+     * @return array
226
+     * @throws \BadMethodCallException
227
+     */
228
+    public function getUidAndFilename($path) {
229
+
230
+        $parts = explode('/', $path);
231
+        $uid = '';
232
+        if (count($parts) > 2) {
233
+            $uid = $parts[1];
234
+        }
235
+        if (!$this->userManager->userExists($uid)) {
236
+            throw new \BadMethodCallException(
237
+                'path needs to be relative to the system wide data folder and point to a user specific file'
238
+            );
239
+        }
240
+
241
+        $ownerPath = implode('/', array_slice($parts, 2));
242
+
243
+        return [$uid, Filesystem::normalizePath($ownerPath)];
244
+
245
+    }
246
+
247
+    /**
248
+     * Remove .path extension from a file path
249
+     * @param string $path Path that may identify a .part file
250
+     * @return string File path without .part extension
251
+     * @note this is needed for reusing keys
252
+     */
253
+    public function stripPartialFileExtension($path) {
254
+        $extension = pathinfo($path, PATHINFO_EXTENSION);
255
+
256
+        if ($extension === 'part') {
257
+
258
+            $newLength = strlen($path) - 5; // 5 = strlen(".part")
259
+            $fPath = substr($path, 0, $newLength);
260
+
261
+            // if path also contains a transaction id, we remove it too
262
+            $extension = pathinfo($fPath, PATHINFO_EXTENSION);
263
+            if(substr($extension, 0, 12) === 'ocTransferId') { // 12 = strlen("ocTransferId")
264
+                $newLength = strlen($fPath) - strlen($extension) -1;
265
+                $fPath = substr($fPath, 0, $newLength);
266
+            }
267
+            return $fPath;
268
+
269
+        } else {
270
+            return $path;
271
+        }
272
+    }
273
+
274
+    public function getUserWithAccessToMountPoint($users, $groups) {
275
+        $result = [];
276
+        if (in_array('all', $users)) {
277
+            $users = $this->userManager->search('', null, null);
278
+            $result = array_map(function (IUser $user) {
279
+                return $user->getUID();
280
+            }, $users);
281
+        } else {
282
+            $result = array_merge($result, $users);
283
+
284
+            $groupManager = \OC::$server->getGroupManager();
285
+            foreach ($groups as $group) {
286
+                $groupObject = $groupManager->get($group);
287
+                if ($groupObject) {
288
+                    $foundUsers = $groupObject->searchUsers('', -1, 0);
289
+                    $userIds = [];
290
+                    foreach ($foundUsers as $user) {
291
+                        $userIds[] = $user->getUID();
292
+                    }
293
+                    $result = array_merge($result, $userIds);
294
+                }
295
+            }
296
+        }
297
+
298
+        return $result;
299
+    }
300
+
301
+    /**
302
+     * check if the file is stored on a system wide mount point
303
+     * @param string $path relative to /data/user with leading '/'
304
+     * @param string $uid
305
+     * @return boolean
306
+     */
307
+    public function isSystemWideMountPoint($path, $uid) {
308
+        if (\OCP\App::isEnabled("files_external")) {
309
+            $mounts = \OC_Mount_Config::getSystemMountPoints();
310
+            foreach ($mounts as $mount) {
311
+                if (strpos($path, '/files/' . $mount['mountpoint']) === 0) {
312
+                    if ($this->isMountPointApplicableToUser($mount, $uid)) {
313
+                        return true;
314
+                    }
315
+                }
316
+            }
317
+        }
318
+        return false;
319
+    }
320
+
321
+    /**
322
+     * check if mount point is applicable to user
323
+     *
324
+     * @param array $mount contains $mount['applicable']['users'], $mount['applicable']['groups']
325
+     * @param string $uid
326
+     * @return boolean
327
+     */
328
+    private function isMountPointApplicableToUser($mount, $uid) {
329
+        $acceptedUids = ['all', $uid];
330
+        // check if mount point is applicable for the user
331
+        $intersection = array_intersect($acceptedUids, $mount['applicable']['users']);
332
+        if (!empty($intersection)) {
333
+            return true;
334
+        }
335
+        // check if mount point is applicable for group where the user is a member
336
+        foreach ($mount['applicable']['groups'] as $gid) {
337
+            if ($this->groupManager->isInGroup($uid, $gid)) {
338
+                return true;
339
+            }
340
+        }
341
+        return false;
342
+    }
343
+
344
+    /**
345
+     * check if it is a path which is excluded by ownCloud from encryption
346
+     *
347
+     * @param string $path
348
+     * @return boolean
349
+     */
350
+    public function isExcluded($path) {
351
+        $normalizedPath = Filesystem::normalizePath($path);
352
+        $root = explode('/', $normalizedPath, 4);
353
+        if (count($root) > 1) {
354
+
355
+            // detect alternative key storage root
356
+            $rootDir = $this->getKeyStorageRoot();
357
+            if ($rootDir !== '' &&
358
+                0 === strpos(
359
+                    Filesystem::normalizePath($path),
360
+                    Filesystem::normalizePath($rootDir)
361
+                )
362
+            ) {
363
+                return true;
364
+            }
365
+
366
+
367
+            //detect system wide folders
368
+            if (in_array($root[1], $this->excludedPaths)) {
369
+                return true;
370
+            }
371
+
372
+            // detect user specific folders
373
+            if ($this->userManager->userExists($root[1])
374
+                && in_array($root[2], $this->excludedPaths)) {
375
+
376
+                return true;
377
+            }
378
+        }
379
+        return false;
380
+    }
381
+
382
+    /**
383
+     * check if recovery key is enabled for user
384
+     *
385
+     * @param string $uid
386
+     * @return boolean
387
+     */
388
+    public function recoveryEnabled($uid) {
389
+        $enabled = $this->config->getUserValue($uid, 'encryption', 'recovery_enabled', '0');
390
+
391
+        return $enabled === '1';
392
+    }
393
+
394
+    /**
395
+     * set new key storage root
396
+     *
397
+     * @param string $root new key store root relative to the data folder
398
+     */
399
+    public function setKeyStorageRoot($root) {
400
+        $this->config->setAppValue('core', 'encryption_key_storage_root', $root);
401
+    }
402
+
403
+    /**
404
+     * get key storage root
405
+     *
406
+     * @return string key storage root
407
+     */
408
+    public function getKeyStorageRoot() {
409
+        return $this->config->getAppValue('core', 'encryption_key_storage_root', '');
410
+    }
411 411
 
412 412
 }
Please login to merge, or discard this patch.
Spacing   +8 added lines, -8 removed lines patch added patch discarded remove patch
@@ -100,7 +100,7 @@  discard block
 block discarded – undo
100 100
 		$this->config = $config;
101 101
 
102 102
 		$this->excludedPaths[] = 'files_encryption';
103
-		$this->excludedPaths[] = 'appdata_' . $config->getSystemValue('instanceid', null);
103
+		$this->excludedPaths[] = 'appdata_'.$config->getSystemValue('instanceid', null);
104 104
 		$this->excludedPaths[] = 'files_external';
105 105
 	}
106 106
 
@@ -140,12 +140,12 @@  discard block
 block discarded – undo
140 140
 	 * @throws EncryptionHeaderKeyExistsException if header key is already in use
141 141
 	 */
142 142
 	public function createHeader(array $headerData, IEncryptionModule $encryptionModule) {
143
-		$header = self::HEADER_START . ':' . self::HEADER_ENCRYPTION_MODULE_KEY . ':' . $encryptionModule->getId() . ':';
143
+		$header = self::HEADER_START.':'.self::HEADER_ENCRYPTION_MODULE_KEY.':'.$encryptionModule->getId().':';
144 144
 		foreach ($headerData as $key => $value) {
145 145
 			if (in_array($key, $this->ocHeaderKeys)) {
146 146
 				throw new EncryptionHeaderKeyExistsException($key);
147 147
 			}
148
-			$header .= $key . ':' . $value . ':';
148
+			$header .= $key.':'.$value.':';
149 149
 		}
150 150
 		$header .= self::HEADER_END;
151 151
 
@@ -176,7 +176,7 @@  discard block
 block discarded – undo
176 176
 				if ($c->getType() === 'dir') {
177 177
 					$dirList[] = $c->getPath();
178 178
 				} else {
179
-					$result[] =  $c->getPath();
179
+					$result[] = $c->getPath();
180 180
 				}
181 181
 			}
182 182
 
@@ -260,8 +260,8 @@  discard block
 block discarded – undo
260 260
 
261 261
 			// if path also contains a transaction id, we remove it too
262 262
 			$extension = pathinfo($fPath, PATHINFO_EXTENSION);
263
-			if(substr($extension, 0, 12) === 'ocTransferId') { // 12 = strlen("ocTransferId")
264
-				$newLength = strlen($fPath) - strlen($extension) -1;
263
+			if (substr($extension, 0, 12) === 'ocTransferId') { // 12 = strlen("ocTransferId")
264
+				$newLength = strlen($fPath) - strlen($extension) - 1;
265 265
 				$fPath = substr($fPath, 0, $newLength);
266 266
 			}
267 267
 			return $fPath;
@@ -275,7 +275,7 @@  discard block
 block discarded – undo
275 275
 		$result = [];
276 276
 		if (in_array('all', $users)) {
277 277
 			$users = $this->userManager->search('', null, null);
278
-			$result = array_map(function (IUser $user) {
278
+			$result = array_map(function(IUser $user) {
279 279
 				return $user->getUID();
280 280
 			}, $users);
281 281
 		} else {
@@ -308,7 +308,7 @@  discard block
 block discarded – undo
308 308
 		if (\OCP\App::isEnabled("files_external")) {
309 309
 			$mounts = \OC_Mount_Config::getSystemMountPoints();
310 310
 			foreach ($mounts as $mount) {
311
-				if (strpos($path, '/files/' . $mount['mountpoint']) === 0) {
311
+				if (strpos($path, '/files/'.$mount['mountpoint']) === 0) {
312 312
 					if ($this->isMountPointApplicableToUser($mount, $uid)) {
313 313
 						return true;
314 314
 					}
Please login to merge, or discard this patch.
lib/private/Avatar/Avatar.php 2 patches
Indentation   +268 added lines, -268 removed lines patch added patch discarded remove patch
@@ -50,277 +50,277 @@
 block discarded – undo
50 50
  */
51 51
 abstract class Avatar implements IAvatar {
52 52
 
53
-	/** @var ILogger  */
54
-	protected $logger;
55
-
56
-	/**
57
-	 * https://github.com/sebdesign/cap-height -- for 500px height
58
-	 * Automated check: https://codepen.io/skjnldsv/pen/PydLBK/
59
-	 * Noto Sans cap-height is 0.715 and we want a 200px caps height size
60
-	 * (0.4 letter-to-total-height ratio, 500*0.4=200), so: 200/0.715 = 280px.
61
-	 * Since we start from the baseline (text-anchor) we need to
62
-	 * shift the y axis by 100px (half the caps height): 500/2+100=350
63
-	 *
64
-	 * @var string
65
-	 */
66
-	private $svgTemplate = '<?xml version="1.0" encoding="UTF-8" standalone="no"?>
53
+    /** @var ILogger  */
54
+    protected $logger;
55
+
56
+    /**
57
+     * https://github.com/sebdesign/cap-height -- for 500px height
58
+     * Automated check: https://codepen.io/skjnldsv/pen/PydLBK/
59
+     * Noto Sans cap-height is 0.715 and we want a 200px caps height size
60
+     * (0.4 letter-to-total-height ratio, 500*0.4=200), so: 200/0.715 = 280px.
61
+     * Since we start from the baseline (text-anchor) we need to
62
+     * shift the y axis by 100px (half the caps height): 500/2+100=350
63
+     *
64
+     * @var string
65
+     */
66
+    private $svgTemplate = '<?xml version="1.0" encoding="UTF-8" standalone="no"?>
67 67
 		<svg width="{size}" height="{size}" version="1.1" viewBox="0 0 500 500" xmlns="http://www.w3.org/2000/svg">
68 68
 			<rect width="100%" height="100%" fill="#{fill}"></rect>
69 69
 			<text x="50%" y="350" style="font-weight:normal;font-size:280px;font-family:\'Noto Sans\';text-anchor:middle;fill:#fff">{letter}</text>
70 70
 		</svg>';
71 71
 
72
-	/**
73
-	 * The base avatar constructor.
74
-	 *
75
-	 * @param ILogger $logger The logger
76
-	 */
77
-	public function __construct(ILogger $logger) {
78
-		$this->logger = $logger;
79
-	}
80
-
81
-	/**
82
-	 * Returns the user display name.
83
-	 *
84
-	 * @return string
85
-	 */
86
-	abstract public function getDisplayName(): string;
87
-
88
-	/**
89
-	 * Returns the first letter of the display name, or "?" if no name given.
90
-	 *
91
-	 * @return string
92
-	 */
93
-	private function getAvatarText(): string {
94
-		$displayName = $this->getDisplayName();
95
-		if (empty($displayName) === true) {
96
-			return '?';
97
-		}
98
-		$firstTwoLetters = array_map(function ($namePart) {
99
-			return mb_strtoupper(mb_substr($namePart, 0, 1), 'UTF-8');
100
-		}, explode(' ', $displayName, 2));
101
-		return implode('', $firstTwoLetters);
102
-	}
103
-
104
-	/**
105
-	 * @inheritdoc
106
-	 */
107
-	public function get($size = 64) {
108
-		$size = (int) $size;
109
-
110
-		try {
111
-			$file = $this->getFile($size);
112
-		} catch (NotFoundException $e) {
113
-			return false;
114
-		}
115
-
116
-		$avatar = new OC_Image();
117
-		$avatar->loadFromData($file->getContent());
118
-		return $avatar;
119
-	}
120
-
121
-	/**
122
-	 * {size} = 500
123
-	 * {fill} = hex color to fill
124
-	 * {letter} = Letter to display
125
-	 *
126
-	 * Generate SVG avatar
127
-	 *
128
-	 * @param int $size The requested image size in pixel
129
-	 * @return string
130
-	 *
131
-	 */
132
-	protected function getAvatarVector(int $size): string {
133
-		$userDisplayName = $this->getDisplayName();
134
-		$bgRGB = $this->avatarBackgroundColor($userDisplayName);
135
-		$bgHEX = sprintf("%02x%02x%02x", $bgRGB->r, $bgRGB->g, $bgRGB->b);
136
-		$text = $this->getAvatarText();
137
-		$toReplace = ['{size}', '{fill}', '{letter}'];
138
-		return str_replace($toReplace, [$size, $bgHEX, $text], $this->svgTemplate);
139
-	}
140
-
141
-	/**
142
-	 * Generate png avatar from svg with Imagick
143
-	 *
144
-	 * @param int $size
145
-	 * @return string|boolean
146
-	 */
147
-	protected function generateAvatarFromSvg(int $size) {
148
-		if (!extension_loaded('imagick')) {
149
-			return false;
150
-		}
151
-		try {
152
-			$font = __DIR__ . '/../../core/fonts/NotoSans-Regular.ttf';
153
-			$svg = $this->getAvatarVector($size);
154
-			$avatar = new Imagick();
155
-			$avatar->setFont($font);
156
-			$avatar->readImageBlob($svg);
157
-			$avatar->setImageFormat('png');
158
-			$image = new OC_Image();
159
-			$image->loadFromData($avatar);
160
-			return $image->data();
161
-		} catch (\Exception $e) {
162
-			return false;
163
-		}
164
-	}
165
-
166
-	/**
167
-	 * Generate png avatar with GD
168
-	 *
169
-	 * @param string $userDisplayName
170
-	 * @param int $size
171
-	 * @return string
172
-	 */
173
-	protected function generateAvatar($userDisplayName, $size) {
174
-		$text = $this->getAvatarText();
175
-		$backgroundColor = $this->avatarBackgroundColor($userDisplayName);
176
-
177
-		$im = imagecreatetruecolor($size, $size);
178
-		$background = imagecolorallocate(
179
-			$im,
180
-			$backgroundColor->r,
181
-			$backgroundColor->g,
182
-			$backgroundColor->b
183
-		);
184
-		$white = imagecolorallocate($im, 255, 255, 255);
185
-		imagefilledrectangle($im, 0, 0, $size, $size, $background);
186
-
187
-		$font = __DIR__ . '/../../../core/fonts/NotoSans-Regular.ttf';
188
-
189
-		$fontSize = $size * 0.4;
190
-		list($x, $y) = $this->imageTTFCenter(
191
-			$im, $text, $font, (int)$fontSize
192
-		);
193
-
194
-		imagettftext($im, $fontSize, 0, $x, $y, $white, $font, $text);
195
-
196
-		ob_start();
197
-		imagepng($im);
198
-		$data = ob_get_contents();
199
-		ob_end_clean();
200
-
201
-		return $data;
202
-	}
203
-
204
-	/**
205
-	 * Calculate real image ttf center
206
-	 *
207
-	 * @param resource $image
208
-	 * @param string $text text string
209
-	 * @param string $font font path
210
-	 * @param int $size font size
211
-	 * @param int $angle
212
-	 * @return array
213
-	 */
214
-	protected function imageTTFCenter(
215
-		$image,
216
-		string $text,
217
-		string $font,
218
-		int $size,
219
-		$angle = 0
220
-	): array {
221
-		// Image width & height
222
-		$xi = imagesx($image);
223
-		$yi = imagesy($image);
224
-
225
-		// bounding box
226
-		$box = imagettfbbox($size, $angle, $font, $text);
227
-
228
-		// imagettfbbox can return negative int
229
-		$xr = abs(max($box[2], $box[4]));
230
-		$yr = abs(max($box[5], $box[7]));
231
-
232
-		// calculate bottom left placement
233
-		$x = intval(($xi - $xr) / 2);
234
-		$y = intval(($yi + $yr) / 2);
235
-
236
-		return [$x, $y];
237
-	}
238
-
239
-	/**
240
-	 * Calculate steps between two Colors
241
-	 * @param object Color $steps start color
242
-	 * @param object Color $ends end color
243
-	 * @return array [r,g,b] steps for each color to go from $steps to $ends
244
-	 */
245
-	private function stepCalc($steps, $ends) {
246
-		$step = [];
247
-		$step[0] = ($ends[1]->r - $ends[0]->r) / $steps;
248
-		$step[1] = ($ends[1]->g - $ends[0]->g) / $steps;
249
-		$step[2] = ($ends[1]->b - $ends[0]->b) / $steps;
250
-		return $step;
251
-	}
252
-
253
-	/**
254
-	 * Convert a string to an integer evenly
255
-	 * @param string $hash the text to parse
256
-	 * @param int $maximum the maximum range
257
-	 * @return int[] between 0 and $maximum
258
-	 */
259
-	private function mixPalette($steps, $color1, $color2) {
260
-		$palette = [$color1];
261
-		$step = $this->stepCalc($steps, [$color1, $color2]);
262
-		for ($i = 1; $i < $steps; $i++) {
263
-			$r = intval($color1->r + ($step[0] * $i));
264
-			$g = intval($color1->g + ($step[1] * $i));
265
-			$b = intval($color1->b + ($step[2] * $i));
266
-			$palette[] = new Color($r, $g, $b);
267
-		}
268
-		return $palette;
269
-	}
270
-
271
-	/**
272
-	 * Convert a string to an integer evenly
273
-	 * @param string $hash the text to parse
274
-	 * @param int $maximum the maximum range
275
-	 * @return int between 0 and $maximum
276
-	 */
277
-	private function hashToInt($hash, $maximum) {
278
-		$final = 0;
279
-		$result = [];
280
-
281
-		// Splitting evenly the string
282
-		for ($i = 0; $i < strlen($hash); $i++) {
283
-			// chars in md5 goes up to f, hex:16
284
-			$result[] = intval(substr($hash, $i, 1), 16) % 16;
285
-		}
286
-		// Adds up all results
287
-		foreach ($result as $value) {
288
-			$final += $value;
289
-		}
290
-		// chars in md5 goes up to f, hex:16
291
-		return intval($final % $maximum);
292
-	}
293
-
294
-	/**
295
-	 * @param string $hash
296
-	 * @return Color Object containting r g b int in the range [0, 255]
297
-	 */
298
-	public function avatarBackgroundColor(string $hash) {
299
-		// Normalize hash
300
-		$hash = strtolower($hash);
301
-
302
-		// Already a md5 hash?
303
-		if(preg_match('/^([0-9a-f]{4}-?){8}$/', $hash, $matches) !== 1) {
304
-			$hash = md5($hash);
305
-		}
306
-
307
-		// Remove unwanted char
308
-		$hash = preg_replace('/[^0-9a-f]+/', '', $hash);
309
-
310
-		$red = new Color(182, 70, 157);
311
-		$yellow = new Color(221, 203, 85);
312
-		$blue = new Color(0, 130, 201); // Nextcloud blue
313
-
314
-		// Number of steps to go from a color to another
315
-		// 3 colors * 6 will result in 18 generated colors
316
-		$steps = 6;
317
-
318
-		$palette1 = $this->mixPalette($steps, $red, $yellow);
319
-		$palette2 = $this->mixPalette($steps, $yellow, $blue);
320
-		$palette3 = $this->mixPalette($steps, $blue, $red);
321
-
322
-		$finalPalette = array_merge($palette1, $palette2, $palette3);
323
-
324
-		return $finalPalette[$this->hashToInt($hash, $steps * 3)];
325
-	}
72
+    /**
73
+     * The base avatar constructor.
74
+     *
75
+     * @param ILogger $logger The logger
76
+     */
77
+    public function __construct(ILogger $logger) {
78
+        $this->logger = $logger;
79
+    }
80
+
81
+    /**
82
+     * Returns the user display name.
83
+     *
84
+     * @return string
85
+     */
86
+    abstract public function getDisplayName(): string;
87
+
88
+    /**
89
+     * Returns the first letter of the display name, or "?" if no name given.
90
+     *
91
+     * @return string
92
+     */
93
+    private function getAvatarText(): string {
94
+        $displayName = $this->getDisplayName();
95
+        if (empty($displayName) === true) {
96
+            return '?';
97
+        }
98
+        $firstTwoLetters = array_map(function ($namePart) {
99
+            return mb_strtoupper(mb_substr($namePart, 0, 1), 'UTF-8');
100
+        }, explode(' ', $displayName, 2));
101
+        return implode('', $firstTwoLetters);
102
+    }
103
+
104
+    /**
105
+     * @inheritdoc
106
+     */
107
+    public function get($size = 64) {
108
+        $size = (int) $size;
109
+
110
+        try {
111
+            $file = $this->getFile($size);
112
+        } catch (NotFoundException $e) {
113
+            return false;
114
+        }
115
+
116
+        $avatar = new OC_Image();
117
+        $avatar->loadFromData($file->getContent());
118
+        return $avatar;
119
+    }
120
+
121
+    /**
122
+     * {size} = 500
123
+     * {fill} = hex color to fill
124
+     * {letter} = Letter to display
125
+     *
126
+     * Generate SVG avatar
127
+     *
128
+     * @param int $size The requested image size in pixel
129
+     * @return string
130
+     *
131
+     */
132
+    protected function getAvatarVector(int $size): string {
133
+        $userDisplayName = $this->getDisplayName();
134
+        $bgRGB = $this->avatarBackgroundColor($userDisplayName);
135
+        $bgHEX = sprintf("%02x%02x%02x", $bgRGB->r, $bgRGB->g, $bgRGB->b);
136
+        $text = $this->getAvatarText();
137
+        $toReplace = ['{size}', '{fill}', '{letter}'];
138
+        return str_replace($toReplace, [$size, $bgHEX, $text], $this->svgTemplate);
139
+    }
140
+
141
+    /**
142
+     * Generate png avatar from svg with Imagick
143
+     *
144
+     * @param int $size
145
+     * @return string|boolean
146
+     */
147
+    protected function generateAvatarFromSvg(int $size) {
148
+        if (!extension_loaded('imagick')) {
149
+            return false;
150
+        }
151
+        try {
152
+            $font = __DIR__ . '/../../core/fonts/NotoSans-Regular.ttf';
153
+            $svg = $this->getAvatarVector($size);
154
+            $avatar = new Imagick();
155
+            $avatar->setFont($font);
156
+            $avatar->readImageBlob($svg);
157
+            $avatar->setImageFormat('png');
158
+            $image = new OC_Image();
159
+            $image->loadFromData($avatar);
160
+            return $image->data();
161
+        } catch (\Exception $e) {
162
+            return false;
163
+        }
164
+    }
165
+
166
+    /**
167
+     * Generate png avatar with GD
168
+     *
169
+     * @param string $userDisplayName
170
+     * @param int $size
171
+     * @return string
172
+     */
173
+    protected function generateAvatar($userDisplayName, $size) {
174
+        $text = $this->getAvatarText();
175
+        $backgroundColor = $this->avatarBackgroundColor($userDisplayName);
176
+
177
+        $im = imagecreatetruecolor($size, $size);
178
+        $background = imagecolorallocate(
179
+            $im,
180
+            $backgroundColor->r,
181
+            $backgroundColor->g,
182
+            $backgroundColor->b
183
+        );
184
+        $white = imagecolorallocate($im, 255, 255, 255);
185
+        imagefilledrectangle($im, 0, 0, $size, $size, $background);
186
+
187
+        $font = __DIR__ . '/../../../core/fonts/NotoSans-Regular.ttf';
188
+
189
+        $fontSize = $size * 0.4;
190
+        list($x, $y) = $this->imageTTFCenter(
191
+            $im, $text, $font, (int)$fontSize
192
+        );
193
+
194
+        imagettftext($im, $fontSize, 0, $x, $y, $white, $font, $text);
195
+
196
+        ob_start();
197
+        imagepng($im);
198
+        $data = ob_get_contents();
199
+        ob_end_clean();
200
+
201
+        return $data;
202
+    }
203
+
204
+    /**
205
+     * Calculate real image ttf center
206
+     *
207
+     * @param resource $image
208
+     * @param string $text text string
209
+     * @param string $font font path
210
+     * @param int $size font size
211
+     * @param int $angle
212
+     * @return array
213
+     */
214
+    protected function imageTTFCenter(
215
+        $image,
216
+        string $text,
217
+        string $font,
218
+        int $size,
219
+        $angle = 0
220
+    ): array {
221
+        // Image width & height
222
+        $xi = imagesx($image);
223
+        $yi = imagesy($image);
224
+
225
+        // bounding box
226
+        $box = imagettfbbox($size, $angle, $font, $text);
227
+
228
+        // imagettfbbox can return negative int
229
+        $xr = abs(max($box[2], $box[4]));
230
+        $yr = abs(max($box[5], $box[7]));
231
+
232
+        // calculate bottom left placement
233
+        $x = intval(($xi - $xr) / 2);
234
+        $y = intval(($yi + $yr) / 2);
235
+
236
+        return [$x, $y];
237
+    }
238
+
239
+    /**
240
+     * Calculate steps between two Colors
241
+     * @param object Color $steps start color
242
+     * @param object Color $ends end color
243
+     * @return array [r,g,b] steps for each color to go from $steps to $ends
244
+     */
245
+    private function stepCalc($steps, $ends) {
246
+        $step = [];
247
+        $step[0] = ($ends[1]->r - $ends[0]->r) / $steps;
248
+        $step[1] = ($ends[1]->g - $ends[0]->g) / $steps;
249
+        $step[2] = ($ends[1]->b - $ends[0]->b) / $steps;
250
+        return $step;
251
+    }
252
+
253
+    /**
254
+     * Convert a string to an integer evenly
255
+     * @param string $hash the text to parse
256
+     * @param int $maximum the maximum range
257
+     * @return int[] between 0 and $maximum
258
+     */
259
+    private function mixPalette($steps, $color1, $color2) {
260
+        $palette = [$color1];
261
+        $step = $this->stepCalc($steps, [$color1, $color2]);
262
+        for ($i = 1; $i < $steps; $i++) {
263
+            $r = intval($color1->r + ($step[0] * $i));
264
+            $g = intval($color1->g + ($step[1] * $i));
265
+            $b = intval($color1->b + ($step[2] * $i));
266
+            $palette[] = new Color($r, $g, $b);
267
+        }
268
+        return $palette;
269
+    }
270
+
271
+    /**
272
+     * Convert a string to an integer evenly
273
+     * @param string $hash the text to parse
274
+     * @param int $maximum the maximum range
275
+     * @return int between 0 and $maximum
276
+     */
277
+    private function hashToInt($hash, $maximum) {
278
+        $final = 0;
279
+        $result = [];
280
+
281
+        // Splitting evenly the string
282
+        for ($i = 0; $i < strlen($hash); $i++) {
283
+            // chars in md5 goes up to f, hex:16
284
+            $result[] = intval(substr($hash, $i, 1), 16) % 16;
285
+        }
286
+        // Adds up all results
287
+        foreach ($result as $value) {
288
+            $final += $value;
289
+        }
290
+        // chars in md5 goes up to f, hex:16
291
+        return intval($final % $maximum);
292
+    }
293
+
294
+    /**
295
+     * @param string $hash
296
+     * @return Color Object containting r g b int in the range [0, 255]
297
+     */
298
+    public function avatarBackgroundColor(string $hash) {
299
+        // Normalize hash
300
+        $hash = strtolower($hash);
301
+
302
+        // Already a md5 hash?
303
+        if(preg_match('/^([0-9a-f]{4}-?){8}$/', $hash, $matches) !== 1) {
304
+            $hash = md5($hash);
305
+        }
306
+
307
+        // Remove unwanted char
308
+        $hash = preg_replace('/[^0-9a-f]+/', '', $hash);
309
+
310
+        $red = new Color(182, 70, 157);
311
+        $yellow = new Color(221, 203, 85);
312
+        $blue = new Color(0, 130, 201); // Nextcloud blue
313
+
314
+        // Number of steps to go from a color to another
315
+        // 3 colors * 6 will result in 18 generated colors
316
+        $steps = 6;
317
+
318
+        $palette1 = $this->mixPalette($steps, $red, $yellow);
319
+        $palette2 = $this->mixPalette($steps, $yellow, $blue);
320
+        $palette3 = $this->mixPalette($steps, $blue, $red);
321
+
322
+        $finalPalette = array_merge($palette1, $palette2, $palette3);
323
+
324
+        return $finalPalette[$this->hashToInt($hash, $steps * 3)];
325
+    }
326 326
 }
Please login to merge, or discard this patch.
Spacing   +5 added lines, -5 removed lines patch added patch discarded remove patch
@@ -95,7 +95,7 @@  discard block
 block discarded – undo
95 95
 		if (empty($displayName) === true) {
96 96
 			return '?';
97 97
 		}
98
-		$firstTwoLetters = array_map(function ($namePart) {
98
+		$firstTwoLetters = array_map(function($namePart) {
99 99
 			return mb_strtoupper(mb_substr($namePart, 0, 1), 'UTF-8');
100 100
 		}, explode(' ', $displayName, 2));
101 101
 		return implode('', $firstTwoLetters);
@@ -149,7 +149,7 @@  discard block
 block discarded – undo
149 149
 			return false;
150 150
 		}
151 151
 		try {
152
-			$font = __DIR__ . '/../../core/fonts/NotoSans-Regular.ttf';
152
+			$font = __DIR__.'/../../core/fonts/NotoSans-Regular.ttf';
153 153
 			$svg = $this->getAvatarVector($size);
154 154
 			$avatar = new Imagick();
155 155
 			$avatar->setFont($font);
@@ -184,11 +184,11 @@  discard block
 block discarded – undo
184 184
 		$white = imagecolorallocate($im, 255, 255, 255);
185 185
 		imagefilledrectangle($im, 0, 0, $size, $size, $background);
186 186
 
187
-		$font = __DIR__ . '/../../../core/fonts/NotoSans-Regular.ttf';
187
+		$font = __DIR__.'/../../../core/fonts/NotoSans-Regular.ttf';
188 188
 
189 189
 		$fontSize = $size * 0.4;
190 190
 		list($x, $y) = $this->imageTTFCenter(
191
-			$im, $text, $font, (int)$fontSize
191
+			$im, $text, $font, (int) $fontSize
192 192
 		);
193 193
 
194 194
 		imagettftext($im, $fontSize, 0, $x, $y, $white, $font, $text);
@@ -300,7 +300,7 @@  discard block
 block discarded – undo
300 300
 		$hash = strtolower($hash);
301 301
 
302 302
 		// Already a md5 hash?
303
-		if(preg_match('/^([0-9a-f]{4}-?){8}$/', $hash, $matches) !== 1) {
303
+		if (preg_match('/^([0-9a-f]{4}-?){8}$/', $hash, $matches) !== 1) {
304 304
 			$hash = md5($hash);
305 305
 		}
306 306
 
Please login to merge, or discard this patch.
lib/private/Share/Share.php 2 patches
Indentation   +1496 added lines, -1496 removed lines patch added patch discarded remove patch
@@ -49,1500 +49,1500 @@
 block discarded – undo
49 49
  */
50 50
 class Share extends Constants {
51 51
 
52
-	/** CRUDS permissions (Create, Read, Update, Delete, Share) using a bitmask
53
-	 * Construct permissions for share() and setPermissions with Or (|) e.g.
54
-	 * Give user read and update permissions: PERMISSION_READ | PERMISSION_UPDATE
55
-	 *
56
-	 * Check if permission is granted with And (&) e.g. Check if delete is
57
-	 * granted: if ($permissions & PERMISSION_DELETE)
58
-	 *
59
-	 * Remove permissions with And (&) and Not (~) e.g. Remove the update
60
-	 * permission: $permissions &= ~PERMISSION_UPDATE
61
-	 *
62
-	 * Apps are required to handle permissions on their own, this class only
63
-	 * stores and manages the permissions of shares
64
-	 * @see lib/public/constants.php
65
-	 */
66
-
67
-	/**
68
-	 * Register a sharing backend class that implements OCP\Share_Backend for an item type
69
-	 * @param string $itemType Item type
70
-	 * @param string $class Backend class
71
-	 * @param string $collectionOf (optional) Depends on item type
72
-	 * @param array $supportedFileExtensions (optional) List of supported file extensions if this item type depends on files
73
-	 * @return boolean true if backend is registered or false if error
74
-	 */
75
-	public static function registerBackend($itemType, $class, $collectionOf = null, $supportedFileExtensions = null) {
76
-		if (\OC::$server->getConfig()->getAppValue('core', 'shareapi_enabled', 'yes') == 'yes') {
77
-			if (!isset(self::$backendTypes[$itemType])) {
78
-				self::$backendTypes[$itemType] = [
79
-					'class' => $class,
80
-					'collectionOf' => $collectionOf,
81
-					'supportedFileExtensions' => $supportedFileExtensions
82
-				];
83
-				return true;
84
-			}
85
-			\OCP\Util::writeLog('OCP\Share',
86
-				'Sharing backend '.$class.' not registered, '.self::$backendTypes[$itemType]['class']
87
-				.' is already registered for '.$itemType,
88
-				ILogger::WARN);
89
-		}
90
-		return false;
91
-	}
92
-
93
-	/**
94
-	 * Get the items of item type shared with the current user
95
-	 * @param string $itemType
96
-	 * @param int $format (optional) Format type must be defined by the backend
97
-	 * @param mixed $parameters (optional)
98
-	 * @param int $limit Number of items to return (optional) Returns all by default
99
-	 * @param boolean $includeCollections (optional)
100
-	 * @return mixed Return depends on format
101
-	 * @deprecated TESTS ONLY - this methods is only used by tests
102
-	 * called like this:
103
-	 * \OC\Share\Share::getItemsSharedWith('folder'); (apps/files_sharing/tests/UpdaterTest.php)
104
-	 */
105
-	public static function getItemsSharedWith() {
106
-		return self::getItems('folder', null, self::$shareTypeUserAndGroups, \OC_User::getUser(), null, self::FORMAT_NONE,
107
-			null, -1, false);
108
-	}
109
-
110
-	/**
111
-	 * Get the items of item type shared with a user
112
-	 * @param string $itemType
113
-	 * @param string $user id for which user we want the shares
114
-	 * @param int $format (optional) Format type must be defined by the backend
115
-	 * @param mixed $parameters (optional)
116
-	 * @param int $limit Number of items to return (optional) Returns all by default
117
-	 * @param boolean $includeCollections (optional)
118
-	 * @return mixed Return depends on format
119
-	 */
120
-	public static function getItemsSharedWithUser($itemType, $user, $format = self::FORMAT_NONE,
121
-												  $parameters = null, $limit = -1, $includeCollections = false) {
122
-		return self::getItems($itemType, null, self::$shareTypeUserAndGroups, $user, null, $format,
123
-			$parameters, $limit, $includeCollections);
124
-	}
125
-
126
-	/**
127
-	 * Get the item of item type shared with a given user by source
128
-	 * @param string $itemType
129
-	 * @param string $itemSource
130
-	 * @param string $user User to whom the item was shared
131
-	 * @param string $owner Owner of the share
132
-	 * @param int $shareType only look for a specific share type
133
-	 * @return array Return list of items with file_target, permissions and expiration
134
-	 */
135
-	public static function getItemSharedWithUser($itemType, $itemSource, $user, $owner = null, $shareType = null) {
136
-		$shares = [];
137
-		$fileDependent = false;
138
-
139
-		$where = 'WHERE';
140
-		$fileDependentWhere = '';
141
-		if ($itemType === 'file' || $itemType === 'folder') {
142
-			$fileDependent = true;
143
-			$column = 'file_source';
144
-			$fileDependentWhere = 'INNER JOIN `*PREFIX*filecache` ON `file_source` = `*PREFIX*filecache`.`fileid` ';
145
-			$fileDependentWhere .= 'INNER JOIN `*PREFIX*storages` ON `numeric_id` = `*PREFIX*filecache`.`storage` ';
146
-		} else {
147
-			$column = 'item_source';
148
-		}
149
-
150
-		$select = self::createSelectStatement(self::FORMAT_NONE, $fileDependent);
151
-
152
-		$where .= ' `' . $column . '` = ? AND `item_type` = ? ';
153
-		$arguments = [$itemSource, $itemType];
154
-		// for link shares $user === null
155
-		if ($user !== null) {
156
-			$where .= ' AND `share_with` = ? ';
157
-			$arguments[] = $user;
158
-		}
159
-
160
-		if ($shareType !== null) {
161
-			$where .= ' AND `share_type` = ? ';
162
-			$arguments[] = $shareType;
163
-		}
164
-
165
-		if ($owner !== null) {
166
-			$where .= ' AND `uid_owner` = ? ';
167
-			$arguments[] = $owner;
168
-		}
169
-
170
-		$query = \OC_DB::prepare('SELECT ' . $select . ' FROM `*PREFIX*share` '. $fileDependentWhere . $where);
171
-
172
-		$result = \OC_DB::executeAudited($query, $arguments);
173
-
174
-		while ($row = $result->fetchRow()) {
175
-			if ($fileDependent && !self::isFileReachable($row['path'], $row['storage_id'])) {
176
-				continue;
177
-			}
178
-			if ($fileDependent && (int)$row['file_parent'] === -1) {
179
-				// if it is a mount point we need to get the path from the mount manager
180
-				$mountManager = \OC\Files\Filesystem::getMountManager();
181
-				$mountPoint = $mountManager->findByStorageId($row['storage_id']);
182
-				if (!empty($mountPoint)) {
183
-					$path = $mountPoint[0]->getMountPoint();
184
-					$path = trim($path, '/');
185
-					$path = substr($path, strlen($owner) + 1); //normalize path to 'files/foo.txt`
186
-					$row['path'] = $path;
187
-				} else {
188
-					\OC::$server->getLogger()->warning(
189
-						'Could not resolve mount point for ' . $row['storage_id'],
190
-						['app' => 'OCP\Share']
191
-					);
192
-				}
193
-			}
194
-			$shares[] = $row;
195
-		}
196
-
197
-		//if didn't found a result than let's look for a group share.
198
-		if(empty($shares) && $user !== null) {
199
-			$userObject = \OC::$server->getUserManager()->get($user);
200
-			$groups = [];
201
-			if ($userObject) {
202
-				$groups = \OC::$server->getGroupManager()->getUserGroupIds($userObject);
203
-			}
204
-
205
-			if (!empty($groups)) {
206
-				$where = $fileDependentWhere . ' WHERE `' . $column . '` = ? AND `item_type` = ? AND `share_with` in (?)';
207
-				$arguments = [$itemSource, $itemType, $groups];
208
-				$types = [null, null, IQueryBuilder::PARAM_STR_ARRAY];
209
-
210
-				if ($owner !== null) {
211
-					$where .= ' AND `uid_owner` = ?';
212
-					$arguments[] = $owner;
213
-					$types[] = null;
214
-				}
215
-
216
-				// TODO: inject connection, hopefully one day in the future when this
217
-				// class isn't static anymore...
218
-				$conn = \OC::$server->getDatabaseConnection();
219
-				$result = $conn->executeQuery(
220
-					'SELECT ' . $select . ' FROM `*PREFIX*share` ' . $where,
221
-					$arguments,
222
-					$types
223
-				);
224
-
225
-				while ($row = $result->fetch()) {
226
-					$shares[] = $row;
227
-				}
228
-			}
229
-		}
230
-
231
-		return $shares;
232
-
233
-	}
234
-
235
-	/**
236
-	 * Get the item of item type shared with the current user by source
237
-	 * @param string $itemType
238
-	 * @param string $itemSource
239
-	 * @param int $format (optional) Format type must be defined by the backend
240
-	 * @param mixed $parameters
241
-	 * @param boolean $includeCollections
242
-	 * @param string $shareWith (optional) define against which user should be checked, default: current user
243
-	 * @return array
244
-	 */
245
-	public static function getItemSharedWithBySource($itemType, $itemSource, $format = self::FORMAT_NONE,
246
-													 $parameters = null, $includeCollections = false, $shareWith = null) {
247
-		$shareWith = ($shareWith === null) ? \OC_User::getUser() : $shareWith;
248
-		return self::getItems($itemType, $itemSource, self::$shareTypeUserAndGroups, $shareWith, null, $format,
249
-			$parameters, 1, $includeCollections, true);
250
-	}
251
-
252
-	/**
253
-	 * Get the shared item of item type owned by the current user
254
-	 * @param string $itemType
255
-	 * @param string $itemSource
256
-	 * @param int $format (optional) Format type must be defined by the backend
257
-	 * @param mixed $parameters
258
-	 * @param boolean $includeCollections
259
-	 * @return mixed Return depends on format
260
-	 */
261
-	public static function getItemShared($itemType, $itemSource, $format = self::FORMAT_NONE,
262
-										 $parameters = null, $includeCollections = false) {
263
-		return self::getItems($itemType, $itemSource, null, null, \OC_User::getUser(), $format,
264
-			$parameters, -1, $includeCollections);
265
-	}
266
-
267
-	/**
268
-	 * Share an item with a user, group, or via private link
269
-	 * @param string $itemType
270
-	 * @param string $itemSource
271
-	 * @param int $shareType SHARE_TYPE_USER, SHARE_TYPE_GROUP, or SHARE_TYPE_LINK
272
-	 * @param string $shareWith User or group the item is being shared with
273
-	 * @param int $permissions CRUDS
274
-	 * @param string $itemSourceName
275
-	 * @param \DateTime|null $expirationDate
276
-	 * @return boolean|string Returns true on success or false on failure, Returns token on success for links
277
-	 * @throws \OC\HintException when the share type is remote and the shareWith is invalid
278
-	 * @throws \Exception
279
-	 * @since 5.0.0 - parameter $itemSourceName was added in 6.0.0, parameter $expirationDate was added in 7.0.0, parameter $passwordChanged added in 9.0.0
280
-	 * @deprecated 14.0.0 TESTS ONLY - this methods is as of 2018-06 only used by tests
281
-	 * called like this:
282
-	 * \OC\Share\Share::shareItem('test', 1, \OCP\Share::SHARE_TYPE_USER, $otherUserId, \OCP\Constants::PERMISSION_READ);
283
-	 */
284
-	public static function shareItem($itemType, $itemSource, $shareType, $shareWith, $permissions) {
285
-		$backend = self::getBackend($itemType);
286
-
287
-		if ($backend->isShareTypeAllowed($shareType) === false) {
288
-			$message = 'Sharing failed, because the backend does not allow shares from type %i';
289
-			throw new \Exception(sprintf($message, $shareType));
290
-		}
291
-
292
-		$uidOwner = \OC_User::getUser();
293
-
294
-		// Verify share type and sharing conditions are met
295
-		if ($shareType === self::SHARE_TYPE_USER) {
296
-			if ($shareWith == $uidOwner) {
297
-				$message = 'Sharing failed, because you can not share with yourself';
298
-				throw new \Exception($message);
299
-			}
300
-			if (!\OC::$server->getUserManager()->userExists($shareWith)) {
301
-				$message = 'Sharing failed, because the user %s does not exist';
302
-				throw new \Exception(sprintf($message, $shareWith));
303
-			}
304
-			// Check if the item source is already shared with the user, either from the same owner or a different user
305
-			if ($checkExists = self::getItems($itemType, $itemSource, self::$shareTypeUserAndGroups,
306
-				$shareWith, null, self::FORMAT_NONE, null, 1, true, true)) {
307
-				// Only allow the same share to occur again if it is the same
308
-				// owner and is not a user share, this use case is for increasing
309
-				// permissions for a specific user
310
-				if ($checkExists['uid_owner'] != $uidOwner || $checkExists['share_type'] == $shareType) {
311
-					$message = 'Sharing failed, because this item is already shared with %s';
312
-					throw new \Exception(sprintf($message, $shareWith));
313
-				}
314
-			}
315
-			if ($checkExists = self::getItems($itemType, $itemSource, self::SHARE_TYPE_USER,
316
-				$shareWith, null, self::FORMAT_NONE, null, 1, true, true)) {
317
-				// Only allow the same share to occur again if it is the same
318
-				// owner and is not a user share, this use case is for increasing
319
-				// permissions for a specific user
320
-				if ($checkExists['uid_owner'] != $uidOwner || $checkExists['share_type'] == $shareType) {
321
-					$message = 'Sharing failed, because this item is already shared with user %s';
322
-					throw new \Exception(sprintf($message, $shareWith));
323
-				}
324
-			}
325
-		}
326
-
327
-		// Put the item into the database
328
-		$result = self::put('test', $itemSource, self::SHARE_TYPE_USER, $shareWith, $uidOwner, $permissions);
329
-
330
-		return $result ? true : false;
331
-	}
332
-
333
-	/**
334
-	 * Unshare an item from a user, group, or delete a private link
335
-	 * @param string $itemType
336
-	 * @param string $itemSource
337
-	 * @param int $shareType SHARE_TYPE_USER, SHARE_TYPE_GROUP, or SHARE_TYPE_LINK
338
-	 * @param string $shareWith User or group the item is being shared with
339
-	 * @param string $owner owner of the share, if null the current user is used
340
-	 * @return boolean true on success or false on failure
341
-	 */
342
-	public static function unshare($itemType, $itemSource, $shareType, $shareWith, $owner = null) {
343
-
344
-		// check if it is a valid itemType
345
-		self::getBackend($itemType);
346
-
347
-		$items = self::getItemSharedWithUser($itemType, $itemSource, $shareWith, $owner, $shareType);
348
-
349
-		$toDelete = [];
350
-		$newParent = null;
351
-		$currentUser = $owner ? $owner : \OC_User::getUser();
352
-		foreach ($items as $item) {
353
-			// delete the item with the expected share_type and owner
354
-			if ((int)$item['share_type'] === (int)$shareType && $item['uid_owner'] === $currentUser) {
355
-				$toDelete = $item;
356
-				// if there is more then one result we don't have to delete the children
357
-				// but update their parent. For group shares the new parent should always be
358
-				// the original group share and not the db entry with the unique name
359
-			} else if ((int)$item['share_type'] === self::$shareTypeGroupUserUnique) {
360
-				$newParent = $item['parent'];
361
-			} else {
362
-				$newParent = $item['id'];
363
-			}
364
-		}
365
-
366
-		if (!empty($toDelete)) {
367
-			self::unshareItem($toDelete, $newParent);
368
-			return true;
369
-		}
370
-		return false;
371
-	}
372
-
373
-	/**
374
-	 * Checks whether a share has expired, calls unshareItem() if yes.
375
-	 * @param array $item Share data (usually database row)
376
-	 * @return boolean True if item was expired, false otherwise.
377
-	 */
378
-	protected static function expireItem(array $item) {
379
-
380
-		$result = false;
381
-
382
-		// only use default expiration date for link shares
383
-		if ((int) $item['share_type'] === self::SHARE_TYPE_LINK) {
384
-
385
-			// calculate expiration date
386
-			if (!empty($item['expiration'])) {
387
-				$userDefinedExpire = new \DateTime($item['expiration']);
388
-				$expires = $userDefinedExpire->getTimestamp();
389
-			} else {
390
-				$expires = null;
391
-			}
392
-
393
-
394
-			// get default expiration settings
395
-			$defaultSettings = Helper::getDefaultExpireSetting();
396
-			$expires = Helper::calculateExpireDate($defaultSettings, $item['stime'], $expires);
397
-
398
-
399
-			if (is_int($expires)) {
400
-				$now = time();
401
-				if ($now > $expires) {
402
-					self::unshareItem($item);
403
-					$result = true;
404
-				}
405
-			}
406
-		}
407
-		return $result;
408
-	}
409
-
410
-	/**
411
-	 * Unshares a share given a share data array
412
-	 * @param array $item Share data (usually database row)
413
-	 * @param int $newParent parent ID
414
-	 * @return null
415
-	 */
416
-	protected static function unshareItem(array $item, $newParent = null) {
417
-
418
-		$shareType = (int)$item['share_type'];
419
-		$shareWith = null;
420
-		if ($shareType !== \OCP\Share::SHARE_TYPE_LINK) {
421
-			$shareWith = $item['share_with'];
422
-		}
423
-
424
-		// Pass all the vars we have for now, they may be useful
425
-		$hookParams = [
426
-			'id'            => $item['id'],
427
-			'itemType'      => $item['item_type'],
428
-			'itemSource'    => $item['item_source'],
429
-			'shareType'     => $shareType,
430
-			'shareWith'     => $shareWith,
431
-			'itemParent'    => $item['parent'],
432
-			'uidOwner'      => $item['uid_owner'],
433
-		];
434
-		if($item['item_type'] === 'file' || $item['item_type'] === 'folder') {
435
-			$hookParams['fileSource'] = $item['file_source'];
436
-			$hookParams['fileTarget'] = $item['file_target'];
437
-		}
438
-
439
-		\OC_Hook::emit(\OCP\Share::class, 'pre_unshare', $hookParams);
440
-		$deletedShares = Helper::delete($item['id'], false, null, $newParent);
441
-		$deletedShares[] = $hookParams;
442
-		$hookParams['deletedShares'] = $deletedShares;
443
-		\OC_Hook::emit(\OCP\Share::class, 'post_unshare', $hookParams);
444
-		if ((int)$item['share_type'] === \OCP\Share::SHARE_TYPE_REMOTE && \OC::$server->getUserSession()->getUser()) {
445
-			list(, $remote) = Helper::splitUserRemote($item['share_with']);
446
-			self::sendRemoteUnshare($remote, $item['id'], $item['token']);
447
-		}
448
-	}
449
-
450
-	/**
451
-	 * Get the backend class for the specified item type
452
-	 * @param string $itemType
453
-	 * @throws \Exception
454
-	 * @return \OCP\Share_Backend
455
-	 */
456
-	public static function getBackend($itemType) {
457
-		$l = \OC::$server->getL10N('lib');
458
-		if (isset(self::$backends[$itemType])) {
459
-			return self::$backends[$itemType];
460
-		} else if (isset(self::$backendTypes[$itemType]['class'])) {
461
-			$class = self::$backendTypes[$itemType]['class'];
462
-			if (class_exists($class)) {
463
-				self::$backends[$itemType] = new $class;
464
-				if (!(self::$backends[$itemType] instanceof \OCP\Share_Backend)) {
465
-					$message = 'Sharing backend %s must implement the interface OCP\Share_Backend';
466
-					$message_t = $l->t('Sharing backend %s must implement the interface OCP\Share_Backend', [$class]);
467
-					\OCP\Util::writeLog('OCP\Share', sprintf($message, $class), ILogger::ERROR);
468
-					throw new \Exception($message_t);
469
-				}
470
-				return self::$backends[$itemType];
471
-			} else {
472
-				$message = 'Sharing backend %s not found';
473
-				$message_t = $l->t('Sharing backend %s not found', [$class]);
474
-				\OCP\Util::writeLog('OCP\Share', sprintf($message, $class), ILogger::ERROR);
475
-				throw new \Exception($message_t);
476
-			}
477
-		}
478
-		$message = 'Sharing backend for %s not found';
479
-		$message_t = $l->t('Sharing backend for %s not found', [$itemType]);
480
-		\OCP\Util::writeLog('OCP\Share', sprintf($message, $itemType), ILogger::ERROR);
481
-		throw new \Exception($message_t);
482
-	}
483
-
484
-	/**
485
-	 * Check if resharing is allowed
486
-	 * @return boolean true if allowed or false
487
-	 *
488
-	 * Resharing is allowed by default if not configured
489
-	 */
490
-	public static function isResharingAllowed() {
491
-		if (!isset(self::$isResharingAllowed)) {
492
-			if (\OC::$server->getConfig()->getAppValue('core', 'shareapi_allow_resharing', 'yes') == 'yes') {
493
-				self::$isResharingAllowed = true;
494
-			} else {
495
-				self::$isResharingAllowed = false;
496
-			}
497
-		}
498
-		return self::$isResharingAllowed;
499
-	}
500
-
501
-	/**
502
-	 * Get a list of collection item types for the specified item type
503
-	 * @param string $itemType
504
-	 * @return array
505
-	 */
506
-	private static function getCollectionItemTypes($itemType) {
507
-		$collectionTypes = [$itemType];
508
-		foreach (self::$backendTypes as $type => $backend) {
509
-			if (in_array($backend['collectionOf'], $collectionTypes)) {
510
-				$collectionTypes[] = $type;
511
-			}
512
-		}
513
-		// TODO Add option for collections to be collection of themselves, only 'folder' does it now...
514
-		if (isset(self::$backendTypes[$itemType]) && (!self::getBackend($itemType) instanceof \OCP\Share_Backend_Collection || $itemType != 'folder')) {
515
-			unset($collectionTypes[0]);
516
-		}
517
-		// Return array if collections were found or the item type is a
518
-		// collection itself - collections can be inside collections
519
-		if (count($collectionTypes) > 0) {
520
-			return $collectionTypes;
521
-		}
522
-		return false;
523
-	}
524
-
525
-	/**
526
-	 * Get the owners of items shared with a user.
527
-	 *
528
-	 * @param string $user The user the items are shared with.
529
-	 * @param string $type The type of the items shared with the user.
530
-	 * @param boolean $includeCollections Include collection item types (optional)
531
-	 * @param boolean $includeOwner include owner in the list of users the item is shared with (optional)
532
-	 * @return array
533
-	 * @deprecated TESTS ONLY - this methods is only used by tests
534
-	 * called like this:
535
-	 * \OC\Share\Share::getSharedItemsOwners($this->user, $this->type, true)
536
-	 */
537
-	public static function getSharedItemsOwners($user, $type, $includeCollections = false, $includeOwner = false) {
538
-		// First, we find out if $type is part of a collection (and if that collection is part of
539
-		// another one and so on).
540
-		$collectionTypes = [];
541
-		if (!$includeCollections || !$collectionTypes = self::getCollectionItemTypes($type)) {
542
-			$collectionTypes[] = $type;
543
-		}
544
-
545
-		// Of these collection types, along with our original $type, we make a
546
-		// list of the ones for which a sharing backend has been registered.
547
-		// FIXME: Ideally, we wouldn't need to nest getItemsSharedWith in this loop but just call it
548
-		// with its $includeCollections parameter set to true. Unfortunately, this fails currently.
549
-		$allMaybeSharedItems = [];
550
-		foreach ($collectionTypes as $collectionType) {
551
-			if (isset(self::$backends[$collectionType])) {
552
-				$allMaybeSharedItems[$collectionType] = self::getItemsSharedWithUser(
553
-					$collectionType,
554
-					$user,
555
-					self::FORMAT_NONE
556
-				);
557
-			}
558
-		}
559
-
560
-		$owners = [];
561
-		if ($includeOwner) {
562
-			$owners[] = $user;
563
-		}
564
-
565
-		// We take a look at all shared items of the given $type (or of the collections it is part of)
566
-		// and find out their owners. Then, we gather the tags for the original $type from all owners,
567
-		// and return them as elements of a list that look like "Tag (owner)".
568
-		foreach ($allMaybeSharedItems as $collectionType => $maybeSharedItems) {
569
-			foreach ($maybeSharedItems as $sharedItem) {
570
-				if (isset($sharedItem['id'])) { //workaround for https://github.com/owncloud/core/issues/2814
571
-					$owners[] = $sharedItem['uid_owner'];
572
-				}
573
-			}
574
-		}
575
-
576
-		return $owners;
577
-	}
578
-
579
-	/**
580
-	 * Get shared items from the database
581
-	 * @param string $itemType
582
-	 * @param string $item Item source or target (optional)
583
-	 * @param int $shareType SHARE_TYPE_USER, SHARE_TYPE_GROUP, SHARE_TYPE_LINK, $shareTypeUserAndGroups, or $shareTypeGroupUserUnique
584
-	 * @param string $shareWith User or group the item is being shared with
585
-	 * @param string $uidOwner User that is the owner of shared items (optional)
586
-	 * @param int $format Format to convert items to with formatItems() (optional)
587
-	 * @param mixed $parameters to pass to formatItems() (optional)
588
-	 * @param int $limit Number of items to return, -1 to return all matches (optional)
589
-	 * @param boolean $includeCollections Include collection item types (optional)
590
-	 * @param boolean $itemShareWithBySource (optional)
591
-	 * @param boolean $checkExpireDate
592
-	 * @return array
593
-	 *
594
-	 * See public functions getItem(s)... for parameter usage
595
-	 *
596
-	 */
597
-	public static function getItems($itemType, $item = null, $shareType = null, $shareWith = null,
598
-									$uidOwner = null, $format = self::FORMAT_NONE, $parameters = null, $limit = -1,
599
-									$includeCollections = false, $itemShareWithBySource = false, $checkExpireDate  = true) {
600
-		if (\OC::$server->getConfig()->getAppValue('core', 'shareapi_enabled', 'yes') != 'yes') {
601
-			return [];
602
-		}
603
-		$backend = self::getBackend($itemType);
604
-		$collectionTypes = false;
605
-		// Get filesystem root to add it to the file target and remove from the
606
-		// file source, match file_source with the file cache
607
-		if ($itemType == 'file' || $itemType == 'folder') {
608
-			if(!is_null($uidOwner)) {
609
-				$root = \OC\Files\Filesystem::getRoot();
610
-			} else {
611
-				$root = '';
612
-			}
613
-			$where = 'INNER JOIN `*PREFIX*filecache` ON `file_source` = `*PREFIX*filecache`.`fileid` ';
614
-			if (!isset($item)) {
615
-				$where .= ' AND `file_target` IS NOT NULL ';
616
-			}
617
-			$where .= 'INNER JOIN `*PREFIX*storages` ON `numeric_id` = `*PREFIX*filecache`.`storage` ';
618
-			$fileDependent = true;
619
-			$queryArgs = [];
620
-		} else {
621
-			$fileDependent = false;
622
-			$root = '';
623
-			$collectionTypes = self::getCollectionItemTypes($itemType);
624
-			if ($includeCollections && !isset($item) && $collectionTypes) {
625
-				// If includeCollections is true, find collections of this item type, e.g. a music album contains songs
626
-				if (!in_array($itemType, $collectionTypes)) {
627
-					$itemTypes = array_merge([$itemType], $collectionTypes);
628
-				} else {
629
-					$itemTypes = $collectionTypes;
630
-				}
631
-				$placeholders = implode(',', array_fill(0, count($itemTypes), '?'));
632
-				$where = ' WHERE `item_type` IN ('.$placeholders.'))';
633
-				$queryArgs = $itemTypes;
634
-			} else {
635
-				$where = ' WHERE `item_type` = ?';
636
-				$queryArgs = [$itemType];
637
-			}
638
-		}
639
-		if (\OC::$server->getConfig()->getAppValue('core', 'shareapi_allow_links', 'yes') !== 'yes') {
640
-			$where .= ' AND `share_type` != ?';
641
-			$queryArgs[] = self::SHARE_TYPE_LINK;
642
-		}
643
-		if (isset($shareType)) {
644
-			// Include all user and group items
645
-			if ($shareType == self::$shareTypeUserAndGroups && isset($shareWith)) {
646
-				$where .= ' AND ((`share_type` in (?, ?) AND `share_with` = ?) ';
647
-				$queryArgs[] = self::SHARE_TYPE_USER;
648
-				$queryArgs[] = self::$shareTypeGroupUserUnique;
649
-				$queryArgs[] = $shareWith;
650
-
651
-				$user = \OC::$server->getUserManager()->get($shareWith);
652
-				$groups = [];
653
-				if ($user) {
654
-					$groups = \OC::$server->getGroupManager()->getUserGroupIds($user);
655
-				}
656
-				if (!empty($groups)) {
657
-					$placeholders = implode(',', array_fill(0, count($groups), '?'));
658
-					$where .= ' OR (`share_type` = ? AND `share_with` IN ('.$placeholders.')) ';
659
-					$queryArgs[] = self::SHARE_TYPE_GROUP;
660
-					$queryArgs = array_merge($queryArgs, $groups);
661
-				}
662
-				$where .= ')';
663
-				// Don't include own group shares
664
-				$where .= ' AND `uid_owner` != ?';
665
-				$queryArgs[] = $shareWith;
666
-			} else {
667
-				$where .= ' AND `share_type` = ?';
668
-				$queryArgs[] = $shareType;
669
-				if (isset($shareWith)) {
670
-					$where .= ' AND `share_with` = ?';
671
-					$queryArgs[] = $shareWith;
672
-				}
673
-			}
674
-		}
675
-		if (isset($uidOwner)) {
676
-			$where .= ' AND `uid_owner` = ?';
677
-			$queryArgs[] = $uidOwner;
678
-			if (!isset($shareType)) {
679
-				// Prevent unique user targets for group shares from being selected
680
-				$where .= ' AND `share_type` != ?';
681
-				$queryArgs[] = self::$shareTypeGroupUserUnique;
682
-			}
683
-			if ($fileDependent) {
684
-				$column = 'file_source';
685
-			} else {
686
-				$column = 'item_source';
687
-			}
688
-		} else {
689
-			if ($fileDependent) {
690
-				$column = 'file_target';
691
-			} else {
692
-				$column = 'item_target';
693
-			}
694
-		}
695
-		if (isset($item)) {
696
-			$collectionTypes = self::getCollectionItemTypes($itemType);
697
-			if ($includeCollections && $collectionTypes && !in_array('folder', $collectionTypes)) {
698
-				$where .= ' AND (';
699
-			} else {
700
-				$where .= ' AND';
701
-			}
702
-			// If looking for own shared items, check item_source else check item_target
703
-			if (isset($uidOwner) || $itemShareWithBySource) {
704
-				// If item type is a file, file source needs to be checked in case the item was converted
705
-				if ($fileDependent) {
706
-					$where .= ' `file_source` = ?';
707
-					$column = 'file_source';
708
-				} else {
709
-					$where .= ' `item_source` = ?';
710
-					$column = 'item_source';
711
-				}
712
-			} else {
713
-				if ($fileDependent) {
714
-					$where .= ' `file_target` = ?';
715
-					$item = \OC\Files\Filesystem::normalizePath($item);
716
-				} else {
717
-					$where .= ' `item_target` = ?';
718
-				}
719
-			}
720
-			$queryArgs[] = $item;
721
-			if ($includeCollections && $collectionTypes && !in_array('folder', $collectionTypes)) {
722
-				$placeholders = implode(',', array_fill(0, count($collectionTypes), '?'));
723
-				$where .= ' OR `item_type` IN ('.$placeholders.'))';
724
-				$queryArgs = array_merge($queryArgs, $collectionTypes);
725
-			}
726
-		}
727
-
728
-		if ($shareType == self::$shareTypeUserAndGroups && $limit === 1) {
729
-			// Make sure the unique user target is returned if it exists,
730
-			// unique targets should follow the group share in the database
731
-			// If the limit is not 1, the filtering can be done later
732
-			$where .= ' ORDER BY `*PREFIX*share`.`id` DESC';
733
-		} else {
734
-			$where .= ' ORDER BY `*PREFIX*share`.`id` ASC';
735
-		}
736
-
737
-		if ($limit != -1 && !$includeCollections) {
738
-			// The limit must be at least 3, because filtering needs to be done
739
-			if ($limit < 3) {
740
-				$queryLimit = 3;
741
-			} else {
742
-				$queryLimit = $limit;
743
-			}
744
-		} else {
745
-			$queryLimit = null;
746
-		}
747
-		$select = self::createSelectStatement($format, $fileDependent, $uidOwner);
748
-		$root = strlen($root);
749
-		$query = \OC_DB::prepare('SELECT '.$select.' FROM `*PREFIX*share` '.$where, $queryLimit);
750
-		$result = $query->execute($queryArgs);
751
-		if ($result === false) {
752
-			\OCP\Util::writeLog('OCP\Share',
753
-				\OC_DB::getErrorMessage() . ', select=' . $select . ' where=',
754
-				ILogger::ERROR);
755
-		}
756
-		$items = [];
757
-		$targets = [];
758
-		$switchedItems = [];
759
-		$mounts = [];
760
-		while ($row = $result->fetchRow()) {
761
-			self::transformDBResults($row);
762
-			// Filter out duplicate group shares for users with unique targets
763
-			if ($fileDependent && !self::isFileReachable($row['path'], $row['storage_id'])) {
764
-				continue;
765
-			}
766
-			if ($row['share_type'] == self::$shareTypeGroupUserUnique && isset($items[$row['parent']])) {
767
-				$row['share_type'] = self::SHARE_TYPE_GROUP;
768
-				$row['unique_name'] = true; // remember that we use a unique name for this user
769
-				$row['share_with'] = $items[$row['parent']]['share_with'];
770
-				// if the group share was unshared from the user we keep the permission, otherwise
771
-				// we take the permission from the parent because this is always the up-to-date
772
-				// permission for the group share
773
-				if ($row['permissions'] > 0) {
774
-					$row['permissions'] = $items[$row['parent']]['permissions'];
775
-				}
776
-				// Remove the parent group share
777
-				unset($items[$row['parent']]);
778
-				if ($row['permissions'] == 0) {
779
-					continue;
780
-				}
781
-			} else if (!isset($uidOwner)) {
782
-				// Check if the same target already exists
783
-				if (isset($targets[$row['id']])) {
784
-					// Check if the same owner shared with the user twice
785
-					// through a group and user share - this is allowed
786
-					$id = $targets[$row['id']];
787
-					if (isset($items[$id]) && $items[$id]['uid_owner'] == $row['uid_owner']) {
788
-						// Switch to group share type to ensure resharing conditions aren't bypassed
789
-						if ($items[$id]['share_type'] != self::SHARE_TYPE_GROUP) {
790
-							$items[$id]['share_type'] = self::SHARE_TYPE_GROUP;
791
-							$items[$id]['share_with'] = $row['share_with'];
792
-						}
793
-						// Switch ids if sharing permission is granted on only
794
-						// one share to ensure correct parent is used if resharing
795
-						if (~(int)$items[$id]['permissions'] & \OCP\Constants::PERMISSION_SHARE
796
-							&& (int)$row['permissions'] & \OCP\Constants::PERMISSION_SHARE) {
797
-							$items[$row['id']] = $items[$id];
798
-							$switchedItems[$id] = $row['id'];
799
-							unset($items[$id]);
800
-							$id = $row['id'];
801
-						}
802
-						$items[$id]['permissions'] |= (int)$row['permissions'];
803
-
804
-					}
805
-					continue;
806
-				} elseif (!empty($row['parent'])) {
807
-					$targets[$row['parent']] = $row['id'];
808
-				}
809
-			}
810
-			// Remove root from file source paths if retrieving own shared items
811
-			if (isset($uidOwner) && isset($row['path'])) {
812
-				if (isset($row['parent'])) {
813
-					$query = \OC_DB::prepare('SELECT `file_target` FROM `*PREFIX*share` WHERE `id` = ?');
814
-					$parentResult = $query->execute([$row['parent']]);
815
-					if ($result === false) {
816
-						\OCP\Util::writeLog('OCP\Share', 'Can\'t select parent: ' .
817
-							\OC_DB::getErrorMessage() . ', select=' . $select . ' where=' . $where,
818
-							ILogger::ERROR);
819
-					} else {
820
-						$parentRow = $parentResult->fetchRow();
821
-						$tmpPath = $parentRow['file_target'];
822
-						// find the right position where the row path continues from the target path
823
-						$pos = strrpos($row['path'], $parentRow['file_target']);
824
-						$subPath = substr($row['path'], $pos);
825
-						$splitPath = explode('/', $subPath);
826
-						foreach (array_slice($splitPath, 2) as $pathPart) {
827
-							$tmpPath = $tmpPath . '/' . $pathPart;
828
-						}
829
-						$row['path'] = $tmpPath;
830
-					}
831
-				} else {
832
-					if (!isset($mounts[$row['storage']])) {
833
-						$mountPoints = \OC\Files\Filesystem::getMountByNumericId($row['storage']);
834
-						if (is_array($mountPoints) && !empty($mountPoints)) {
835
-							$mounts[$row['storage']] = current($mountPoints);
836
-						}
837
-					}
838
-					if (!empty($mounts[$row['storage']])) {
839
-						$path = $mounts[$row['storage']]->getMountPoint().$row['path'];
840
-						$relPath = substr($path, $root); // path relative to data/user
841
-						$row['path'] = rtrim($relPath, '/');
842
-					}
843
-				}
844
-			}
845
-
846
-			if($checkExpireDate) {
847
-				if (self::expireItem($row)) {
848
-					continue;
849
-				}
850
-			}
851
-			// Check if resharing is allowed, if not remove share permission
852
-			if (isset($row['permissions']) && (!self::isResharingAllowed() | \OCP\Util::isSharingDisabledForUser())) {
853
-				$row['permissions'] &= ~\OCP\Constants::PERMISSION_SHARE;
854
-			}
855
-			// Add display names to result
856
-			$row['share_with_displayname'] = $row['share_with'];
857
-			if (isset($row['share_with']) && $row['share_with'] != '' &&
858
-				$row['share_type'] === self::SHARE_TYPE_USER) {
859
-				$shareWithUser = \OC::$server->getUserManager()->get($row['share_with']);
860
-				$row['share_with_displayname'] = $shareWithUser === null ? $row['share_with'] : $shareWithUser->getDisplayName();
861
-			} else if(isset($row['share_with']) && $row['share_with'] != '' &&
862
-				$row['share_type'] === self::SHARE_TYPE_REMOTE) {
863
-				$addressBookEntries = \OC::$server->getContactsManager()->search($row['share_with'], ['CLOUD']);
864
-				foreach ($addressBookEntries as $entry) {
865
-					foreach ($entry['CLOUD'] as $cloudID) {
866
-						if ($cloudID === $row['share_with']) {
867
-							$row['share_with_displayname'] = $entry['FN'];
868
-						}
869
-					}
870
-				}
871
-			}
872
-			if (isset($row['uid_owner']) && $row['uid_owner'] != '') {
873
-				$ownerUser = \OC::$server->getUserManager()->get($row['uid_owner']);
874
-				$row['displayname_owner'] = $ownerUser === null ? $row['uid_owner'] : $ownerUser->getDisplayName();
875
-			}
876
-
877
-			if ($row['permissions'] > 0) {
878
-				$items[$row['id']] = $row;
879
-			}
880
-
881
-		}
882
-
883
-		// group items if we are looking for items shared with the current user
884
-		if (isset($shareWith) && $shareWith === \OCP\User::getUser()) {
885
-			$items = self::groupItems($items, $itemType);
886
-		}
887
-
888
-		if (!empty($items)) {
889
-			$collectionItems = [];
890
-			foreach ($items as &$row) {
891
-				// Return only the item instead of a 2-dimensional array
892
-				if ($limit == 1 && $row[$column] == $item && ($row['item_type'] == $itemType || $itemType == 'file')) {
893
-					if ($format == self::FORMAT_NONE) {
894
-						return $row;
895
-					} else {
896
-						break;
897
-					}
898
-				}
899
-				// Check if this is a collection of the requested item type
900
-				if ($includeCollections && $collectionTypes && $row['item_type'] !== 'folder' && in_array($row['item_type'], $collectionTypes)) {
901
-					if (($collectionBackend = self::getBackend($row['item_type']))
902
-						&& $collectionBackend instanceof \OCP\Share_Backend_Collection) {
903
-						// Collections can be inside collections, check if the item is a collection
904
-						if (isset($item) && $row['item_type'] == $itemType && $row[$column] == $item) {
905
-							$collectionItems[] = $row;
906
-						} else {
907
-							$collection = [];
908
-							$collection['item_type'] = $row['item_type'];
909
-							if ($row['item_type'] == 'file' || $row['item_type'] == 'folder') {
910
-								$collection['path'] = basename($row['path']);
911
-							}
912
-							$row['collection'] = $collection;
913
-							// Fetch all of the children sources
914
-							$children = $collectionBackend->getChildren($row[$column]);
915
-							foreach ($children as $child) {
916
-								$childItem = $row;
917
-								$childItem['item_type'] = $itemType;
918
-								if ($row['item_type'] != 'file' && $row['item_type'] != 'folder') {
919
-									$childItem['item_source'] = $child['source'];
920
-									$childItem['item_target'] = $child['target'];
921
-								}
922
-								if ($backend instanceof \OCP\Share_Backend_File_Dependent) {
923
-									if ($row['item_type'] == 'file' || $row['item_type'] == 'folder') {
924
-										$childItem['file_source'] = $child['source'];
925
-									} else { // TODO is this really needed if we already know that we use the file backend?
926
-										$meta = \OC\Files\Filesystem::getFileInfo($child['file_path']);
927
-										$childItem['file_source'] = $meta['fileid'];
928
-									}
929
-									$childItem['file_target'] =
930
-										\OC\Files\Filesystem::normalizePath($child['file_path']);
931
-								}
932
-								if (isset($item)) {
933
-									if ($childItem[$column] == $item) {
934
-										// Return only the item instead of a 2-dimensional array
935
-										if ($limit == 1) {
936
-											if ($format == self::FORMAT_NONE) {
937
-												return $childItem;
938
-											} else {
939
-												// Unset the items array and break out of both loops
940
-												$items = [];
941
-												$items[] = $childItem;
942
-												break 2;
943
-											}
944
-										} else {
945
-											$collectionItems[] = $childItem;
946
-										}
947
-									}
948
-								} else {
949
-									$collectionItems[] = $childItem;
950
-								}
951
-							}
952
-						}
953
-					}
954
-					// Remove collection item
955
-					$toRemove = $row['id'];
956
-					if (array_key_exists($toRemove, $switchedItems)) {
957
-						$toRemove = $switchedItems[$toRemove];
958
-					}
959
-					unset($items[$toRemove]);
960
-				} elseif ($includeCollections && $collectionTypes && in_array($row['item_type'], $collectionTypes)) {
961
-					// FIXME: Thats a dirty hack to improve file sharing performance,
962
-					// see github issue #10588 for more details
963
-					// Need to find a solution which works for all back-ends
964
-					$collectionBackend = self::getBackend($row['item_type']);
965
-					$sharedParents = $collectionBackend->getParents($row['item_source']);
966
-					foreach ($sharedParents as $parent) {
967
-						$collectionItems[] = $parent;
968
-					}
969
-				}
970
-			}
971
-			if (!empty($collectionItems)) {
972
-				$collectionItems = array_unique($collectionItems, SORT_REGULAR);
973
-				$items = array_merge($items, $collectionItems);
974
-			}
975
-
976
-			// filter out invalid items, these can appear when subshare entries exist
977
-			// for a group in which the requested user isn't a member any more
978
-			$items = array_filter($items, function ($item) {
979
-				return $item['share_type'] !== self::$shareTypeGroupUserUnique;
980
-			});
981
-
982
-			return self::formatResult($items, $column, $backend, $format, $parameters);
983
-		} elseif ($includeCollections && $collectionTypes && in_array('folder', $collectionTypes)) {
984
-			// FIXME: Thats a dirty hack to improve file sharing performance,
985
-			// see github issue #10588 for more details
986
-			// Need to find a solution which works for all back-ends
987
-			$collectionItems = [];
988
-			$collectionBackend = self::getBackend('folder');
989
-			$sharedParents = $collectionBackend->getParents($item, $shareWith, $uidOwner);
990
-			foreach ($sharedParents as $parent) {
991
-				$collectionItems[] = $parent;
992
-			}
993
-			if ($limit === 1) {
994
-				return reset($collectionItems);
995
-			}
996
-			return self::formatResult($collectionItems, $column, $backend, $format, $parameters);
997
-		}
998
-
999
-		return [];
1000
-	}
1001
-
1002
-	/**
1003
-	 * group items with link to the same source
1004
-	 *
1005
-	 * @param array $items
1006
-	 * @param string $itemType
1007
-	 * @return array of grouped items
1008
-	 */
1009
-	protected static function groupItems($items, $itemType) {
1010
-
1011
-		$fileSharing = $itemType === 'file' || $itemType === 'folder';
1012
-
1013
-		$result = [];
1014
-
1015
-		foreach ($items as $item) {
1016
-			$grouped = false;
1017
-			foreach ($result as $key => $r) {
1018
-				// for file/folder shares we need to compare file_source, otherwise we compare item_source
1019
-				// only group shares if they already point to the same target, otherwise the file where shared
1020
-				// before grouping of shares was added. In this case we don't group them toi avoid confusions
1021
-				if (($fileSharing && $item['file_source'] === $r['file_source'] && $item['file_target'] === $r['file_target']) ||
1022
-					(!$fileSharing && $item['item_source'] === $r['item_source'] && $item['item_target'] === $r['item_target'])) {
1023
-					// add the first item to the list of grouped shares
1024
-					if (!isset($result[$key]['grouped'])) {
1025
-						$result[$key]['grouped'][] = $result[$key];
1026
-					}
1027
-					$result[$key]['permissions'] = (int) $item['permissions'] | (int) $r['permissions'];
1028
-					$result[$key]['grouped'][] = $item;
1029
-					$grouped = true;
1030
-					break;
1031
-				}
1032
-			}
1033
-
1034
-			if (!$grouped) {
1035
-				$result[] = $item;
1036
-			}
1037
-
1038
-		}
1039
-
1040
-		return $result;
1041
-	}
1042
-
1043
-	/**
1044
-	 * Put shared item into the database
1045
-	 * @param string $itemType Item type
1046
-	 * @param string $itemSource Item source
1047
-	 * @param int $shareType SHARE_TYPE_USER, SHARE_TYPE_GROUP, or SHARE_TYPE_LINK
1048
-	 * @param string $shareWith User or group the item is being shared with
1049
-	 * @param string $uidOwner User that is the owner of shared item
1050
-	 * @param int $permissions CRUDS permissions
1051
-	 * @throws \Exception
1052
-	 * @return mixed id of the new share or false
1053
-	 * @deprecated TESTS ONLY - this methods is only used by tests
1054
-	 * called like this:
1055
-	 * self::put('test', $itemSource, self::SHARE_TYPE_USER, $shareWith, $uidOwner, $permissions);
1056
-	 */
1057
-	private static function put($itemType, $itemSource, $shareType, $shareWith, $uidOwner,
1058
-								$permissions) {
1059
-
1060
-		$queriesToExecute = [];
1061
-		$suggestedItemTarget = null;
1062
-		$groupFileTarget = $fileTarget = $suggestedFileTarget = $filePath = '';
1063
-		$groupItemTarget = $itemTarget = $fileSource = $parent = 0;
1064
-
1065
-		$result = self::checkReshare('test', $itemSource, self::SHARE_TYPE_USER, $shareWith, $uidOwner, $permissions, null, null);
1066
-		if(!empty($result)) {
1067
-			$parent = $result['parent'];
1068
-			$itemSource = $result['itemSource'];
1069
-			$fileSource = $result['fileSource'];
1070
-			$suggestedItemTarget = $result['suggestedItemTarget'];
1071
-			$suggestedFileTarget = $result['suggestedFileTarget'];
1072
-			$filePath = $result['filePath'];
1073
-		}
1074
-
1075
-		$isGroupShare = false;
1076
-			$users = [$shareWith];
1077
-			$itemTarget = Helper::generateTarget($itemType, $itemSource, $shareType, $shareWith, $uidOwner,
1078
-				$suggestedItemTarget);
1079
-
1080
-		$run = true;
1081
-		$error = '';
1082
-		$preHookData = [
1083
-			'itemType' => $itemType,
1084
-			'itemSource' => $itemSource,
1085
-			'shareType' => $shareType,
1086
-			'uidOwner' => $uidOwner,
1087
-			'permissions' => $permissions,
1088
-			'fileSource' => $fileSource,
1089
-			'expiration' => null,
1090
-			'token' => null,
1091
-			'run' => &$run,
1092
-			'error' => &$error
1093
-		];
1094
-
1095
-		$preHookData['itemTarget'] = $itemTarget;
1096
-		$preHookData['shareWith'] = $shareWith;
1097
-
1098
-		\OC_Hook::emit(\OCP\Share::class, 'pre_shared', $preHookData);
1099
-
1100
-		if ($run === false) {
1101
-			throw new \Exception($error);
1102
-		}
1103
-
1104
-		foreach ($users as $user) {
1105
-			$sourceId = ($itemType === 'file' || $itemType === 'folder') ? $fileSource : $itemSource;
1106
-			$sourceExists = self::getItemSharedWithBySource($itemType, $sourceId, self::FORMAT_NONE, null, true, $user);
1107
-
1108
-			$userShareType = $shareType;
1109
-
1110
-			if ($sourceExists && $sourceExists['item_source'] === $itemSource) {
1111
-				$fileTarget = $sourceExists['file_target'];
1112
-				$itemTarget = $sourceExists['item_target'];
1113
-
1114
-			} elseif(!$sourceExists)  {
1115
-
1116
-				$itemTarget = Helper::generateTarget($itemType, $itemSource, $userShareType, $user,
1117
-					$uidOwner, $suggestedItemTarget, $parent);
1118
-				if (isset($fileSource)) {
1119
-						$fileTarget = Helper::generateTarget('file', $filePath, $userShareType,
1120
-							$user, $uidOwner, $suggestedFileTarget, $parent);
1121
-				} else {
1122
-					$fileTarget = null;
1123
-				}
1124
-
1125
-			} else {
1126
-
1127
-				// group share which doesn't exists until now, check if we need a unique target for this user
1128
-
1129
-				$itemTarget = Helper::generateTarget($itemType, $itemSource, self::SHARE_TYPE_USER, $user,
1130
-					$uidOwner, $suggestedItemTarget, $parent);
1131
-
1132
-				// do we also need a file target
1133
-				if (isset($fileSource)) {
1134
-					$fileTarget = Helper::generateTarget('file', $filePath, self::SHARE_TYPE_USER, $user,
1135
-						$uidOwner, $suggestedFileTarget, $parent);
1136
-				} else {
1137
-					$fileTarget = null;
1138
-				}
1139
-
1140
-				if (($itemTarget === $groupItemTarget) &&
1141
-					(!isset($fileSource) || $fileTarget === $groupFileTarget)) {
1142
-					continue;
1143
-				}
1144
-			}
1145
-
1146
-			$queriesToExecute[] = [
1147
-				'itemType'			=> $itemType,
1148
-				'itemSource'		=> $itemSource,
1149
-				'itemTarget'		=> $itemTarget,
1150
-				'shareType'			=> $userShareType,
1151
-				'shareWith'			=> $user,
1152
-				'uidOwner'			=> $uidOwner,
1153
-				'permissions'		=> $permissions,
1154
-				'shareTime'			=> time(),
1155
-				'fileSource'		=> $fileSource,
1156
-				'fileTarget'		=> $fileTarget,
1157
-				'token'				=> null,
1158
-				'parent'			=> $parent,
1159
-				'expiration'		=> null,
1160
-			];
1161
-
1162
-		}
1163
-
1164
-		$id = false;
1165
-
1166
-		foreach ($queriesToExecute as $shareQuery) {
1167
-			$shareQuery['parent'] = $parent;
1168
-			$id = self::insertShare($shareQuery);
1169
-		}
1170
-
1171
-		$postHookData = [
1172
-			'itemType' => $itemType,
1173
-			'itemSource' => $itemSource,
1174
-			'parent' => $parent,
1175
-			'shareType' => $shareType,
1176
-			'uidOwner' => $uidOwner,
1177
-			'permissions' => $permissions,
1178
-			'fileSource' => $fileSource,
1179
-			'id' => $parent,
1180
-			'token' => null,
1181
-			'expirationDate' => null,
1182
-		];
1183
-
1184
-		$postHookData['shareWith'] = $isGroupShare ? $shareWith['group'] : $shareWith;
1185
-		$postHookData['itemTarget'] = $isGroupShare ? $groupItemTarget : $itemTarget;
1186
-		$postHookData['fileTarget'] = $isGroupShare ? $groupFileTarget : $fileTarget;
1187
-
1188
-		\OC_Hook::emit(\OCP\Share::class, 'post_shared', $postHookData);
1189
-
1190
-
1191
-		return $id ? $id : false;
1192
-	}
1193
-
1194
-	/**
1195
-	 * @param string $itemType
1196
-	 * @param string $itemSource
1197
-	 * @param int $shareType
1198
-	 * @param string $shareWith
1199
-	 * @param string $uidOwner
1200
-	 * @param int $permissions
1201
-	 * @param string|null $itemSourceName
1202
-	 * @param null|\DateTime $expirationDate
1203
-	 * @deprecated TESTS ONLY - this methods is only used by tests
1204
-	 * called like this:
1205
-	 * self::checkReshare('test', $itemSource, self::SHARE_TYPE_USER, $shareWith, $uidOwner, $permissions, null, null);
1206
-	 */
1207
-	private static function checkReshare($itemType, $itemSource, $shareType, $shareWith, $uidOwner, $permissions, $itemSourceName, $expirationDate) {
1208
-		$backend = self::getBackend($itemType);
1209
-
1210
-		$result = [];
1211
-
1212
-		$column = ($itemType === 'file' || $itemType === 'folder') ? 'file_source' : 'item_source';
1213
-
1214
-		$checkReshare = self::getItemSharedWithBySource($itemType, $itemSource, self::FORMAT_NONE, null, true);
1215
-		if ($checkReshare) {
1216
-			// Check if attempting to share back to owner
1217
-			if ($checkReshare['uid_owner'] == $shareWith) {
1218
-				$message = 'Sharing %1$s failed, because the user %2$s is the original sharer';
1219
-				throw new \Exception(sprintf($message, $itemSourceName, $shareWith));
1220
-			}
1221
-		}
1222
-
1223
-		if ($checkReshare && $checkReshare['uid_owner'] !== \OC_User::getUser()) {
1224
-			// Check if share permissions is granted
1225
-			if (self::isResharingAllowed() && (int)$checkReshare['permissions'] & \OCP\Constants::PERMISSION_SHARE) {
1226
-				if (~(int)$checkReshare['permissions'] & $permissions) {
1227
-					$message = 'Sharing %1$s failed, because the permissions exceed permissions granted to %2$s';
1228
-					throw new \Exception(sprintf($message, $itemSourceName, $uidOwner));
1229
-				} else {
1230
-					// TODO Don't check if inside folder
1231
-					$result['parent'] = $checkReshare['id'];
1232
-
1233
-					$result['expirationDate'] = $expirationDate;
1234
-					// $checkReshare['expiration'] could be null and then is always less than any value
1235
-					if(isset($checkReshare['expiration']) && $checkReshare['expiration'] < $expirationDate) {
1236
-						$result['expirationDate'] = $checkReshare['expiration'];
1237
-					}
1238
-
1239
-					// only suggest the same name as new target if it is a reshare of the
1240
-					// same file/folder and not the reshare of a child
1241
-					if ($checkReshare[$column] === $itemSource) {
1242
-						$result['filePath'] = $checkReshare['file_target'];
1243
-						$result['itemSource'] = $checkReshare['item_source'];
1244
-						$result['fileSource'] = $checkReshare['file_source'];
1245
-						$result['suggestedItemTarget'] = $checkReshare['item_target'];
1246
-						$result['suggestedFileTarget'] = $checkReshare['file_target'];
1247
-					} else {
1248
-						$result['filePath'] = ($backend instanceof \OCP\Share_Backend_File_Dependent) ? $backend->getFilePath($itemSource, $uidOwner) : null;
1249
-						$result['suggestedItemTarget'] = null;
1250
-						$result['suggestedFileTarget'] = null;
1251
-						$result['itemSource'] = $itemSource;
1252
-						$result['fileSource'] = ($backend instanceof \OCP\Share_Backend_File_Dependent) ? $itemSource : null;
1253
-					}
1254
-				}
1255
-			} else {
1256
-				$message = 'Sharing %s failed, because resharing is not allowed';
1257
-				throw new \Exception(sprintf($message, $itemSourceName));
1258
-			}
1259
-		} else {
1260
-			$result['parent'] = null;
1261
-			$result['suggestedItemTarget'] = null;
1262
-			$result['suggestedFileTarget'] = null;
1263
-			$result['itemSource'] = $itemSource;
1264
-			$result['expirationDate'] = $expirationDate;
1265
-			if (!$backend->isValidSource($itemSource, $uidOwner)) {
1266
-				$message = 'Sharing %1$s failed, because the sharing backend for '
1267
-					.'%2$s could not find its source';
1268
-				throw new \Exception(sprintf($message, $itemSource, $itemType));
1269
-			}
1270
-			if ($backend instanceof \OCP\Share_Backend_File_Dependent) {
1271
-				$result['filePath'] = $backend->getFilePath($itemSource, $uidOwner);
1272
-					$meta = \OC\Files\Filesystem::getFileInfo($result['filePath']);
1273
-					$result['fileSource'] = $meta['fileid'];
1274
-				if ($result['fileSource'] == -1) {
1275
-					$message = 'Sharing %s failed, because the file could not be found in the file cache';
1276
-					throw new \Exception(sprintf($message, $itemSource));
1277
-				}
1278
-			} else {
1279
-				$result['filePath'] = null;
1280
-				$result['fileSource'] = null;
1281
-			}
1282
-		}
1283
-
1284
-		return $result;
1285
-	}
1286
-
1287
-	/**
1288
-	 *
1289
-	 * @param array $shareData
1290
-	 * @return mixed false in case of a failure or the id of the new share
1291
-	 */
1292
-	private static function insertShare(array $shareData) {
1293
-
1294
-		$query = \OC_DB::prepare('INSERT INTO `*PREFIX*share` ('
1295
-			.' `item_type`, `item_source`, `item_target`, `share_type`,'
1296
-			.' `share_with`, `uid_owner`, `permissions`, `stime`, `file_source`,'
1297
-			.' `file_target`, `token`, `parent`, `expiration`) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?)');
1298
-		$query->bindValue(1, $shareData['itemType']);
1299
-		$query->bindValue(2, $shareData['itemSource']);
1300
-		$query->bindValue(3, $shareData['itemTarget']);
1301
-		$query->bindValue(4, $shareData['shareType']);
1302
-		$query->bindValue(5, $shareData['shareWith']);
1303
-		$query->bindValue(6, $shareData['uidOwner']);
1304
-		$query->bindValue(7, $shareData['permissions']);
1305
-		$query->bindValue(8, $shareData['shareTime']);
1306
-		$query->bindValue(9, $shareData['fileSource']);
1307
-		$query->bindValue(10, $shareData['fileTarget']);
1308
-		$query->bindValue(11, $shareData['token']);
1309
-		$query->bindValue(12, $shareData['parent']);
1310
-		$query->bindValue(13, $shareData['expiration'], 'datetime');
1311
-		$result = $query->execute();
1312
-
1313
-		$id = false;
1314
-		if ($result) {
1315
-			$id =  \OC::$server->getDatabaseConnection()->lastInsertId('*PREFIX*share');
1316
-		}
1317
-
1318
-		return $id;
1319
-
1320
-	}
1321
-
1322
-	/**
1323
-	 * construct select statement
1324
-	 * @param int $format
1325
-	 * @param boolean $fileDependent ist it a file/folder share or a generla share
1326
-	 * @param string $uidOwner
1327
-	 * @return string select statement
1328
-	 */
1329
-	private static function createSelectStatement($format, $fileDependent, $uidOwner = null) {
1330
-		$select = '*';
1331
-		if ($format == self::FORMAT_STATUSES) {
1332
-			if ($fileDependent) {
1333
-				$select = '`*PREFIX*share`.`id`, `*PREFIX*share`.`parent`, `share_type`, `path`, `storage`, '
1334
-					. '`share_with`, `uid_owner` , `file_source`, `stime`, `*PREFIX*share`.`permissions`, '
1335
-					. '`*PREFIX*storages`.`id` AS `storage_id`, `*PREFIX*filecache`.`parent` as `file_parent`, '
1336
-					. '`uid_initiator`';
1337
-			} else {
1338
-				$select = '`id`, `parent`, `share_type`, `share_with`, `uid_owner`, `item_source`, `stime`, `*PREFIX*share`.`permissions`';
1339
-			}
1340
-		} else {
1341
-			if (isset($uidOwner)) {
1342
-				if ($fileDependent) {
1343
-					$select = '`*PREFIX*share`.`id`, `item_type`, `item_source`, `*PREFIX*share`.`parent`,'
1344
-						. ' `share_type`, `share_with`, `file_source`, `file_target`, `path`, `*PREFIX*share`.`permissions`, `stime`,'
1345
-						. ' `expiration`, `token`, `storage`, `mail_send`, `uid_owner`, '
1346
-						. '`*PREFIX*storages`.`id` AS `storage_id`, `*PREFIX*filecache`.`parent` as `file_parent`';
1347
-				} else {
1348
-					$select = '`id`, `item_type`, `item_source`, `parent`, `share_type`, `share_with`, `*PREFIX*share`.`permissions`,'
1349
-						. ' `stime`, `file_source`, `expiration`, `token`, `mail_send`, `uid_owner`';
1350
-				}
1351
-			} else {
1352
-				if ($fileDependent) {
1353
-					if ($format == \OCA\Files_Sharing\ShareBackend\File::FORMAT_GET_FOLDER_CONTENTS || $format == \OCA\Files_Sharing\ShareBackend\File::FORMAT_FILE_APP_ROOT) {
1354
-						$select = '`*PREFIX*share`.`id`, `item_type`, `item_source`, `*PREFIX*share`.`parent`, `uid_owner`, '
1355
-							. '`share_type`, `share_with`, `file_source`, `path`, `file_target`, `stime`, '
1356
-							. '`*PREFIX*share`.`permissions`, `expiration`, `storage`, `*PREFIX*filecache`.`parent` as `file_parent`, '
1357
-							. '`name`, `mtime`, `mimetype`, `mimepart`, `size`, `encrypted`, `etag`, `mail_send`';
1358
-					} else {
1359
-						$select = '`*PREFIX*share`.`id`, `item_type`, `item_source`, `item_target`,'
1360
-							. '`*PREFIX*share`.`parent`, `share_type`, `share_with`, `uid_owner`,'
1361
-							. '`file_source`, `path`, `file_target`, `*PREFIX*share`.`permissions`,'
1362
-							. '`stime`, `expiration`, `token`, `storage`, `mail_send`,'
1363
-							. '`*PREFIX*storages`.`id` AS `storage_id`, `*PREFIX*filecache`.`parent` as `file_parent`';
1364
-					}
1365
-				}
1366
-			}
1367
-		}
1368
-		return $select;
1369
-	}
1370
-
1371
-
1372
-	/**
1373
-	 * transform db results
1374
-	 * @param array $row result
1375
-	 */
1376
-	private static function transformDBResults(&$row) {
1377
-		if (isset($row['id'])) {
1378
-			$row['id'] = (int) $row['id'];
1379
-		}
1380
-		if (isset($row['share_type'])) {
1381
-			$row['share_type'] = (int) $row['share_type'];
1382
-		}
1383
-		if (isset($row['parent'])) {
1384
-			$row['parent'] = (int) $row['parent'];
1385
-		}
1386
-		if (isset($row['file_parent'])) {
1387
-			$row['file_parent'] = (int) $row['file_parent'];
1388
-		}
1389
-		if (isset($row['file_source'])) {
1390
-			$row['file_source'] = (int) $row['file_source'];
1391
-		}
1392
-		if (isset($row['permissions'])) {
1393
-			$row['permissions'] = (int) $row['permissions'];
1394
-		}
1395
-		if (isset($row['storage'])) {
1396
-			$row['storage'] = (int) $row['storage'];
1397
-		}
1398
-		if (isset($row['stime'])) {
1399
-			$row['stime'] = (int) $row['stime'];
1400
-		}
1401
-		if (isset($row['expiration']) && $row['share_type'] !== self::SHARE_TYPE_LINK) {
1402
-			// discard expiration date for non-link shares, which might have been
1403
-			// set by ancient bugs
1404
-			$row['expiration'] = null;
1405
-		}
1406
-	}
1407
-
1408
-	/**
1409
-	 * format result
1410
-	 * @param array $items result
1411
-	 * @param string $column is it a file share or a general share ('file_target' or 'item_target')
1412
-	 * @param \OCP\Share_Backend $backend sharing backend
1413
-	 * @param int $format
1414
-	 * @param array $parameters additional format parameters
1415
-	 * @return array format result
1416
-	 */
1417
-	private static function formatResult($items, $column, $backend, $format = self::FORMAT_NONE , $parameters = null) {
1418
-		if ($format === self::FORMAT_NONE) {
1419
-			return $items;
1420
-		} else if ($format === self::FORMAT_STATUSES) {
1421
-			$statuses = [];
1422
-			foreach ($items as $item) {
1423
-				if ($item['share_type'] === self::SHARE_TYPE_LINK) {
1424
-					if ($item['uid_initiator'] !== \OC::$server->getUserSession()->getUser()->getUID()) {
1425
-						continue;
1426
-					}
1427
-					$statuses[$item[$column]]['link'] = true;
1428
-				} else if (!isset($statuses[$item[$column]])) {
1429
-					$statuses[$item[$column]]['link'] = false;
1430
-				}
1431
-				if (!empty($item['file_target'])) {
1432
-					$statuses[$item[$column]]['path'] = $item['path'];
1433
-				}
1434
-			}
1435
-			return $statuses;
1436
-		} else {
1437
-			return $backend->formatItems($items, $format, $parameters);
1438
-		}
1439
-	}
1440
-
1441
-	/**
1442
-	 * remove protocol from URL
1443
-	 *
1444
-	 * @param string $url
1445
-	 * @return string
1446
-	 */
1447
-	public static function removeProtocolFromUrl($url) {
1448
-		if (strpos($url, 'https://') === 0) {
1449
-			return substr($url, strlen('https://'));
1450
-		} else if (strpos($url, 'http://') === 0) {
1451
-			return substr($url, strlen('http://'));
1452
-		}
1453
-
1454
-		return $url;
1455
-	}
1456
-
1457
-	/**
1458
-	 * try http post first with https and then with http as a fallback
1459
-	 *
1460
-	 * @param string $remoteDomain
1461
-	 * @param string $urlSuffix
1462
-	 * @param array $fields post parameters
1463
-	 * @return array
1464
-	 */
1465
-	private static function tryHttpPostToShareEndpoint($remoteDomain, $urlSuffix, array $fields) {
1466
-		$protocol = 'https://';
1467
-		$result = [
1468
-			'success' => false,
1469
-			'result' => '',
1470
-		];
1471
-		$try = 0;
1472
-		$discoveryService = \OC::$server->query(\OCP\OCS\IDiscoveryService::class);
1473
-		while ($result['success'] === false && $try < 2) {
1474
-			$federationEndpoints = $discoveryService->discover($protocol . $remoteDomain, 'FEDERATED_SHARING');
1475
-			$endpoint = isset($federationEndpoints['share']) ? $federationEndpoints['share'] : '/ocs/v2.php/cloud/shares';
1476
-			$client = \OC::$server->getHTTPClientService()->newClient();
1477
-
1478
-			try {
1479
-				$response = $client->post(
1480
-					$protocol . $remoteDomain . $endpoint . $urlSuffix . '?format=' . self::RESPONSE_FORMAT,
1481
-					[
1482
-						'body' => $fields,
1483
-						'connect_timeout' => 10,
1484
-					]
1485
-				);
1486
-
1487
-				$result = ['success' => true, 'result' => $response->getBody()];
1488
-			} catch (\Exception $e) {
1489
-				$result = ['success' => false, 'result' => $e->getMessage()];
1490
-			}
1491
-
1492
-			$try++;
1493
-			$protocol = 'http://';
1494
-		}
1495
-
1496
-		return $result;
1497
-	}
1498
-
1499
-	/**
1500
-	 * send server-to-server unshare to remote server
1501
-	 *
1502
-	 * @param string $remote url
1503
-	 * @param int $id share id
1504
-	 * @param string $token
1505
-	 * @return bool
1506
-	 */
1507
-	private static function sendRemoteUnshare($remote, $id, $token) {
1508
-		$url = rtrim($remote, '/');
1509
-		$fields = ['token' => $token, 'format' => 'json'];
1510
-		$url = self::removeProtocolFromUrl($url);
1511
-		$result = self::tryHttpPostToShareEndpoint($url, '/'.$id.'/unshare', $fields);
1512
-		$status = json_decode($result['result'], true);
1513
-
1514
-		return ($result['success'] && ($status['ocs']['meta']['statuscode'] === 100 || $status['ocs']['meta']['statuscode'] === 200));
1515
-	}
1516
-
1517
-	/**
1518
-	 * @return int
1519
-	 */
1520
-	public static function getExpireInterval() {
1521
-		return (int)\OC::$server->getConfig()->getAppValue('core', 'shareapi_expire_after_n_days', '7');
1522
-	}
1523
-
1524
-	/**
1525
-	 * Checks whether the given path is reachable for the given owner
1526
-	 *
1527
-	 * @param string $path path relative to files
1528
-	 * @param string $ownerStorageId storage id of the owner
1529
-	 *
1530
-	 * @return boolean true if file is reachable, false otherwise
1531
-	 */
1532
-	private static function isFileReachable($path, $ownerStorageId) {
1533
-		// if outside the home storage, file is always considered reachable
1534
-		if (!(substr($ownerStorageId, 0, 6) === 'home::' ||
1535
-			substr($ownerStorageId, 0, 13) === 'object::user:'
1536
-		)) {
1537
-			return true;
1538
-		}
1539
-
1540
-		// if inside the home storage, the file has to be under "/files/"
1541
-		$path = ltrim($path, '/');
1542
-		if (substr($path, 0, 6) === 'files/') {
1543
-			return true;
1544
-		}
1545
-
1546
-		return false;
1547
-	}
52
+    /** CRUDS permissions (Create, Read, Update, Delete, Share) using a bitmask
53
+     * Construct permissions for share() and setPermissions with Or (|) e.g.
54
+     * Give user read and update permissions: PERMISSION_READ | PERMISSION_UPDATE
55
+     *
56
+     * Check if permission is granted with And (&) e.g. Check if delete is
57
+     * granted: if ($permissions & PERMISSION_DELETE)
58
+     *
59
+     * Remove permissions with And (&) and Not (~) e.g. Remove the update
60
+     * permission: $permissions &= ~PERMISSION_UPDATE
61
+     *
62
+     * Apps are required to handle permissions on their own, this class only
63
+     * stores and manages the permissions of shares
64
+     * @see lib/public/constants.php
65
+     */
66
+
67
+    /**
68
+     * Register a sharing backend class that implements OCP\Share_Backend for an item type
69
+     * @param string $itemType Item type
70
+     * @param string $class Backend class
71
+     * @param string $collectionOf (optional) Depends on item type
72
+     * @param array $supportedFileExtensions (optional) List of supported file extensions if this item type depends on files
73
+     * @return boolean true if backend is registered or false if error
74
+     */
75
+    public static function registerBackend($itemType, $class, $collectionOf = null, $supportedFileExtensions = null) {
76
+        if (\OC::$server->getConfig()->getAppValue('core', 'shareapi_enabled', 'yes') == 'yes') {
77
+            if (!isset(self::$backendTypes[$itemType])) {
78
+                self::$backendTypes[$itemType] = [
79
+                    'class' => $class,
80
+                    'collectionOf' => $collectionOf,
81
+                    'supportedFileExtensions' => $supportedFileExtensions
82
+                ];
83
+                return true;
84
+            }
85
+            \OCP\Util::writeLog('OCP\Share',
86
+                'Sharing backend '.$class.' not registered, '.self::$backendTypes[$itemType]['class']
87
+                .' is already registered for '.$itemType,
88
+                ILogger::WARN);
89
+        }
90
+        return false;
91
+    }
92
+
93
+    /**
94
+     * Get the items of item type shared with the current user
95
+     * @param string $itemType
96
+     * @param int $format (optional) Format type must be defined by the backend
97
+     * @param mixed $parameters (optional)
98
+     * @param int $limit Number of items to return (optional) Returns all by default
99
+     * @param boolean $includeCollections (optional)
100
+     * @return mixed Return depends on format
101
+     * @deprecated TESTS ONLY - this methods is only used by tests
102
+     * called like this:
103
+     * \OC\Share\Share::getItemsSharedWith('folder'); (apps/files_sharing/tests/UpdaterTest.php)
104
+     */
105
+    public static function getItemsSharedWith() {
106
+        return self::getItems('folder', null, self::$shareTypeUserAndGroups, \OC_User::getUser(), null, self::FORMAT_NONE,
107
+            null, -1, false);
108
+    }
109
+
110
+    /**
111
+     * Get the items of item type shared with a user
112
+     * @param string $itemType
113
+     * @param string $user id for which user we want the shares
114
+     * @param int $format (optional) Format type must be defined by the backend
115
+     * @param mixed $parameters (optional)
116
+     * @param int $limit Number of items to return (optional) Returns all by default
117
+     * @param boolean $includeCollections (optional)
118
+     * @return mixed Return depends on format
119
+     */
120
+    public static function getItemsSharedWithUser($itemType, $user, $format = self::FORMAT_NONE,
121
+                                                    $parameters = null, $limit = -1, $includeCollections = false) {
122
+        return self::getItems($itemType, null, self::$shareTypeUserAndGroups, $user, null, $format,
123
+            $parameters, $limit, $includeCollections);
124
+    }
125
+
126
+    /**
127
+     * Get the item of item type shared with a given user by source
128
+     * @param string $itemType
129
+     * @param string $itemSource
130
+     * @param string $user User to whom the item was shared
131
+     * @param string $owner Owner of the share
132
+     * @param int $shareType only look for a specific share type
133
+     * @return array Return list of items with file_target, permissions and expiration
134
+     */
135
+    public static function getItemSharedWithUser($itemType, $itemSource, $user, $owner = null, $shareType = null) {
136
+        $shares = [];
137
+        $fileDependent = false;
138
+
139
+        $where = 'WHERE';
140
+        $fileDependentWhere = '';
141
+        if ($itemType === 'file' || $itemType === 'folder') {
142
+            $fileDependent = true;
143
+            $column = 'file_source';
144
+            $fileDependentWhere = 'INNER JOIN `*PREFIX*filecache` ON `file_source` = `*PREFIX*filecache`.`fileid` ';
145
+            $fileDependentWhere .= 'INNER JOIN `*PREFIX*storages` ON `numeric_id` = `*PREFIX*filecache`.`storage` ';
146
+        } else {
147
+            $column = 'item_source';
148
+        }
149
+
150
+        $select = self::createSelectStatement(self::FORMAT_NONE, $fileDependent);
151
+
152
+        $where .= ' `' . $column . '` = ? AND `item_type` = ? ';
153
+        $arguments = [$itemSource, $itemType];
154
+        // for link shares $user === null
155
+        if ($user !== null) {
156
+            $where .= ' AND `share_with` = ? ';
157
+            $arguments[] = $user;
158
+        }
159
+
160
+        if ($shareType !== null) {
161
+            $where .= ' AND `share_type` = ? ';
162
+            $arguments[] = $shareType;
163
+        }
164
+
165
+        if ($owner !== null) {
166
+            $where .= ' AND `uid_owner` = ? ';
167
+            $arguments[] = $owner;
168
+        }
169
+
170
+        $query = \OC_DB::prepare('SELECT ' . $select . ' FROM `*PREFIX*share` '. $fileDependentWhere . $where);
171
+
172
+        $result = \OC_DB::executeAudited($query, $arguments);
173
+
174
+        while ($row = $result->fetchRow()) {
175
+            if ($fileDependent && !self::isFileReachable($row['path'], $row['storage_id'])) {
176
+                continue;
177
+            }
178
+            if ($fileDependent && (int)$row['file_parent'] === -1) {
179
+                // if it is a mount point we need to get the path from the mount manager
180
+                $mountManager = \OC\Files\Filesystem::getMountManager();
181
+                $mountPoint = $mountManager->findByStorageId($row['storage_id']);
182
+                if (!empty($mountPoint)) {
183
+                    $path = $mountPoint[0]->getMountPoint();
184
+                    $path = trim($path, '/');
185
+                    $path = substr($path, strlen($owner) + 1); //normalize path to 'files/foo.txt`
186
+                    $row['path'] = $path;
187
+                } else {
188
+                    \OC::$server->getLogger()->warning(
189
+                        'Could not resolve mount point for ' . $row['storage_id'],
190
+                        ['app' => 'OCP\Share']
191
+                    );
192
+                }
193
+            }
194
+            $shares[] = $row;
195
+        }
196
+
197
+        //if didn't found a result than let's look for a group share.
198
+        if(empty($shares) && $user !== null) {
199
+            $userObject = \OC::$server->getUserManager()->get($user);
200
+            $groups = [];
201
+            if ($userObject) {
202
+                $groups = \OC::$server->getGroupManager()->getUserGroupIds($userObject);
203
+            }
204
+
205
+            if (!empty($groups)) {
206
+                $where = $fileDependentWhere . ' WHERE `' . $column . '` = ? AND `item_type` = ? AND `share_with` in (?)';
207
+                $arguments = [$itemSource, $itemType, $groups];
208
+                $types = [null, null, IQueryBuilder::PARAM_STR_ARRAY];
209
+
210
+                if ($owner !== null) {
211
+                    $where .= ' AND `uid_owner` = ?';
212
+                    $arguments[] = $owner;
213
+                    $types[] = null;
214
+                }
215
+
216
+                // TODO: inject connection, hopefully one day in the future when this
217
+                // class isn't static anymore...
218
+                $conn = \OC::$server->getDatabaseConnection();
219
+                $result = $conn->executeQuery(
220
+                    'SELECT ' . $select . ' FROM `*PREFIX*share` ' . $where,
221
+                    $arguments,
222
+                    $types
223
+                );
224
+
225
+                while ($row = $result->fetch()) {
226
+                    $shares[] = $row;
227
+                }
228
+            }
229
+        }
230
+
231
+        return $shares;
232
+
233
+    }
234
+
235
+    /**
236
+     * Get the item of item type shared with the current user by source
237
+     * @param string $itemType
238
+     * @param string $itemSource
239
+     * @param int $format (optional) Format type must be defined by the backend
240
+     * @param mixed $parameters
241
+     * @param boolean $includeCollections
242
+     * @param string $shareWith (optional) define against which user should be checked, default: current user
243
+     * @return array
244
+     */
245
+    public static function getItemSharedWithBySource($itemType, $itemSource, $format = self::FORMAT_NONE,
246
+                                                        $parameters = null, $includeCollections = false, $shareWith = null) {
247
+        $shareWith = ($shareWith === null) ? \OC_User::getUser() : $shareWith;
248
+        return self::getItems($itemType, $itemSource, self::$shareTypeUserAndGroups, $shareWith, null, $format,
249
+            $parameters, 1, $includeCollections, true);
250
+    }
251
+
252
+    /**
253
+     * Get the shared item of item type owned by the current user
254
+     * @param string $itemType
255
+     * @param string $itemSource
256
+     * @param int $format (optional) Format type must be defined by the backend
257
+     * @param mixed $parameters
258
+     * @param boolean $includeCollections
259
+     * @return mixed Return depends on format
260
+     */
261
+    public static function getItemShared($itemType, $itemSource, $format = self::FORMAT_NONE,
262
+                                            $parameters = null, $includeCollections = false) {
263
+        return self::getItems($itemType, $itemSource, null, null, \OC_User::getUser(), $format,
264
+            $parameters, -1, $includeCollections);
265
+    }
266
+
267
+    /**
268
+     * Share an item with a user, group, or via private link
269
+     * @param string $itemType
270
+     * @param string $itemSource
271
+     * @param int $shareType SHARE_TYPE_USER, SHARE_TYPE_GROUP, or SHARE_TYPE_LINK
272
+     * @param string $shareWith User or group the item is being shared with
273
+     * @param int $permissions CRUDS
274
+     * @param string $itemSourceName
275
+     * @param \DateTime|null $expirationDate
276
+     * @return boolean|string Returns true on success or false on failure, Returns token on success for links
277
+     * @throws \OC\HintException when the share type is remote and the shareWith is invalid
278
+     * @throws \Exception
279
+     * @since 5.0.0 - parameter $itemSourceName was added in 6.0.0, parameter $expirationDate was added in 7.0.0, parameter $passwordChanged added in 9.0.0
280
+     * @deprecated 14.0.0 TESTS ONLY - this methods is as of 2018-06 only used by tests
281
+     * called like this:
282
+     * \OC\Share\Share::shareItem('test', 1, \OCP\Share::SHARE_TYPE_USER, $otherUserId, \OCP\Constants::PERMISSION_READ);
283
+     */
284
+    public static function shareItem($itemType, $itemSource, $shareType, $shareWith, $permissions) {
285
+        $backend = self::getBackend($itemType);
286
+
287
+        if ($backend->isShareTypeAllowed($shareType) === false) {
288
+            $message = 'Sharing failed, because the backend does not allow shares from type %i';
289
+            throw new \Exception(sprintf($message, $shareType));
290
+        }
291
+
292
+        $uidOwner = \OC_User::getUser();
293
+
294
+        // Verify share type and sharing conditions are met
295
+        if ($shareType === self::SHARE_TYPE_USER) {
296
+            if ($shareWith == $uidOwner) {
297
+                $message = 'Sharing failed, because you can not share with yourself';
298
+                throw new \Exception($message);
299
+            }
300
+            if (!\OC::$server->getUserManager()->userExists($shareWith)) {
301
+                $message = 'Sharing failed, because the user %s does not exist';
302
+                throw new \Exception(sprintf($message, $shareWith));
303
+            }
304
+            // Check if the item source is already shared with the user, either from the same owner or a different user
305
+            if ($checkExists = self::getItems($itemType, $itemSource, self::$shareTypeUserAndGroups,
306
+                $shareWith, null, self::FORMAT_NONE, null, 1, true, true)) {
307
+                // Only allow the same share to occur again if it is the same
308
+                // owner and is not a user share, this use case is for increasing
309
+                // permissions for a specific user
310
+                if ($checkExists['uid_owner'] != $uidOwner || $checkExists['share_type'] == $shareType) {
311
+                    $message = 'Sharing failed, because this item is already shared with %s';
312
+                    throw new \Exception(sprintf($message, $shareWith));
313
+                }
314
+            }
315
+            if ($checkExists = self::getItems($itemType, $itemSource, self::SHARE_TYPE_USER,
316
+                $shareWith, null, self::FORMAT_NONE, null, 1, true, true)) {
317
+                // Only allow the same share to occur again if it is the same
318
+                // owner and is not a user share, this use case is for increasing
319
+                // permissions for a specific user
320
+                if ($checkExists['uid_owner'] != $uidOwner || $checkExists['share_type'] == $shareType) {
321
+                    $message = 'Sharing failed, because this item is already shared with user %s';
322
+                    throw new \Exception(sprintf($message, $shareWith));
323
+                }
324
+            }
325
+        }
326
+
327
+        // Put the item into the database
328
+        $result = self::put('test', $itemSource, self::SHARE_TYPE_USER, $shareWith, $uidOwner, $permissions);
329
+
330
+        return $result ? true : false;
331
+    }
332
+
333
+    /**
334
+     * Unshare an item from a user, group, or delete a private link
335
+     * @param string $itemType
336
+     * @param string $itemSource
337
+     * @param int $shareType SHARE_TYPE_USER, SHARE_TYPE_GROUP, or SHARE_TYPE_LINK
338
+     * @param string $shareWith User or group the item is being shared with
339
+     * @param string $owner owner of the share, if null the current user is used
340
+     * @return boolean true on success or false on failure
341
+     */
342
+    public static function unshare($itemType, $itemSource, $shareType, $shareWith, $owner = null) {
343
+
344
+        // check if it is a valid itemType
345
+        self::getBackend($itemType);
346
+
347
+        $items = self::getItemSharedWithUser($itemType, $itemSource, $shareWith, $owner, $shareType);
348
+
349
+        $toDelete = [];
350
+        $newParent = null;
351
+        $currentUser = $owner ? $owner : \OC_User::getUser();
352
+        foreach ($items as $item) {
353
+            // delete the item with the expected share_type and owner
354
+            if ((int)$item['share_type'] === (int)$shareType && $item['uid_owner'] === $currentUser) {
355
+                $toDelete = $item;
356
+                // if there is more then one result we don't have to delete the children
357
+                // but update their parent. For group shares the new parent should always be
358
+                // the original group share and not the db entry with the unique name
359
+            } else if ((int)$item['share_type'] === self::$shareTypeGroupUserUnique) {
360
+                $newParent = $item['parent'];
361
+            } else {
362
+                $newParent = $item['id'];
363
+            }
364
+        }
365
+
366
+        if (!empty($toDelete)) {
367
+            self::unshareItem($toDelete, $newParent);
368
+            return true;
369
+        }
370
+        return false;
371
+    }
372
+
373
+    /**
374
+     * Checks whether a share has expired, calls unshareItem() if yes.
375
+     * @param array $item Share data (usually database row)
376
+     * @return boolean True if item was expired, false otherwise.
377
+     */
378
+    protected static function expireItem(array $item) {
379
+
380
+        $result = false;
381
+
382
+        // only use default expiration date for link shares
383
+        if ((int) $item['share_type'] === self::SHARE_TYPE_LINK) {
384
+
385
+            // calculate expiration date
386
+            if (!empty($item['expiration'])) {
387
+                $userDefinedExpire = new \DateTime($item['expiration']);
388
+                $expires = $userDefinedExpire->getTimestamp();
389
+            } else {
390
+                $expires = null;
391
+            }
392
+
393
+
394
+            // get default expiration settings
395
+            $defaultSettings = Helper::getDefaultExpireSetting();
396
+            $expires = Helper::calculateExpireDate($defaultSettings, $item['stime'], $expires);
397
+
398
+
399
+            if (is_int($expires)) {
400
+                $now = time();
401
+                if ($now > $expires) {
402
+                    self::unshareItem($item);
403
+                    $result = true;
404
+                }
405
+            }
406
+        }
407
+        return $result;
408
+    }
409
+
410
+    /**
411
+     * Unshares a share given a share data array
412
+     * @param array $item Share data (usually database row)
413
+     * @param int $newParent parent ID
414
+     * @return null
415
+     */
416
+    protected static function unshareItem(array $item, $newParent = null) {
417
+
418
+        $shareType = (int)$item['share_type'];
419
+        $shareWith = null;
420
+        if ($shareType !== \OCP\Share::SHARE_TYPE_LINK) {
421
+            $shareWith = $item['share_with'];
422
+        }
423
+
424
+        // Pass all the vars we have for now, they may be useful
425
+        $hookParams = [
426
+            'id'            => $item['id'],
427
+            'itemType'      => $item['item_type'],
428
+            'itemSource'    => $item['item_source'],
429
+            'shareType'     => $shareType,
430
+            'shareWith'     => $shareWith,
431
+            'itemParent'    => $item['parent'],
432
+            'uidOwner'      => $item['uid_owner'],
433
+        ];
434
+        if($item['item_type'] === 'file' || $item['item_type'] === 'folder') {
435
+            $hookParams['fileSource'] = $item['file_source'];
436
+            $hookParams['fileTarget'] = $item['file_target'];
437
+        }
438
+
439
+        \OC_Hook::emit(\OCP\Share::class, 'pre_unshare', $hookParams);
440
+        $deletedShares = Helper::delete($item['id'], false, null, $newParent);
441
+        $deletedShares[] = $hookParams;
442
+        $hookParams['deletedShares'] = $deletedShares;
443
+        \OC_Hook::emit(\OCP\Share::class, 'post_unshare', $hookParams);
444
+        if ((int)$item['share_type'] === \OCP\Share::SHARE_TYPE_REMOTE && \OC::$server->getUserSession()->getUser()) {
445
+            list(, $remote) = Helper::splitUserRemote($item['share_with']);
446
+            self::sendRemoteUnshare($remote, $item['id'], $item['token']);
447
+        }
448
+    }
449
+
450
+    /**
451
+     * Get the backend class for the specified item type
452
+     * @param string $itemType
453
+     * @throws \Exception
454
+     * @return \OCP\Share_Backend
455
+     */
456
+    public static function getBackend($itemType) {
457
+        $l = \OC::$server->getL10N('lib');
458
+        if (isset(self::$backends[$itemType])) {
459
+            return self::$backends[$itemType];
460
+        } else if (isset(self::$backendTypes[$itemType]['class'])) {
461
+            $class = self::$backendTypes[$itemType]['class'];
462
+            if (class_exists($class)) {
463
+                self::$backends[$itemType] = new $class;
464
+                if (!(self::$backends[$itemType] instanceof \OCP\Share_Backend)) {
465
+                    $message = 'Sharing backend %s must implement the interface OCP\Share_Backend';
466
+                    $message_t = $l->t('Sharing backend %s must implement the interface OCP\Share_Backend', [$class]);
467
+                    \OCP\Util::writeLog('OCP\Share', sprintf($message, $class), ILogger::ERROR);
468
+                    throw new \Exception($message_t);
469
+                }
470
+                return self::$backends[$itemType];
471
+            } else {
472
+                $message = 'Sharing backend %s not found';
473
+                $message_t = $l->t('Sharing backend %s not found', [$class]);
474
+                \OCP\Util::writeLog('OCP\Share', sprintf($message, $class), ILogger::ERROR);
475
+                throw new \Exception($message_t);
476
+            }
477
+        }
478
+        $message = 'Sharing backend for %s not found';
479
+        $message_t = $l->t('Sharing backend for %s not found', [$itemType]);
480
+        \OCP\Util::writeLog('OCP\Share', sprintf($message, $itemType), ILogger::ERROR);
481
+        throw new \Exception($message_t);
482
+    }
483
+
484
+    /**
485
+     * Check if resharing is allowed
486
+     * @return boolean true if allowed or false
487
+     *
488
+     * Resharing is allowed by default if not configured
489
+     */
490
+    public static function isResharingAllowed() {
491
+        if (!isset(self::$isResharingAllowed)) {
492
+            if (\OC::$server->getConfig()->getAppValue('core', 'shareapi_allow_resharing', 'yes') == 'yes') {
493
+                self::$isResharingAllowed = true;
494
+            } else {
495
+                self::$isResharingAllowed = false;
496
+            }
497
+        }
498
+        return self::$isResharingAllowed;
499
+    }
500
+
501
+    /**
502
+     * Get a list of collection item types for the specified item type
503
+     * @param string $itemType
504
+     * @return array
505
+     */
506
+    private static function getCollectionItemTypes($itemType) {
507
+        $collectionTypes = [$itemType];
508
+        foreach (self::$backendTypes as $type => $backend) {
509
+            if (in_array($backend['collectionOf'], $collectionTypes)) {
510
+                $collectionTypes[] = $type;
511
+            }
512
+        }
513
+        // TODO Add option for collections to be collection of themselves, only 'folder' does it now...
514
+        if (isset(self::$backendTypes[$itemType]) && (!self::getBackend($itemType) instanceof \OCP\Share_Backend_Collection || $itemType != 'folder')) {
515
+            unset($collectionTypes[0]);
516
+        }
517
+        // Return array if collections were found or the item type is a
518
+        // collection itself - collections can be inside collections
519
+        if (count($collectionTypes) > 0) {
520
+            return $collectionTypes;
521
+        }
522
+        return false;
523
+    }
524
+
525
+    /**
526
+     * Get the owners of items shared with a user.
527
+     *
528
+     * @param string $user The user the items are shared with.
529
+     * @param string $type The type of the items shared with the user.
530
+     * @param boolean $includeCollections Include collection item types (optional)
531
+     * @param boolean $includeOwner include owner in the list of users the item is shared with (optional)
532
+     * @return array
533
+     * @deprecated TESTS ONLY - this methods is only used by tests
534
+     * called like this:
535
+     * \OC\Share\Share::getSharedItemsOwners($this->user, $this->type, true)
536
+     */
537
+    public static function getSharedItemsOwners($user, $type, $includeCollections = false, $includeOwner = false) {
538
+        // First, we find out if $type is part of a collection (and if that collection is part of
539
+        // another one and so on).
540
+        $collectionTypes = [];
541
+        if (!$includeCollections || !$collectionTypes = self::getCollectionItemTypes($type)) {
542
+            $collectionTypes[] = $type;
543
+        }
544
+
545
+        // Of these collection types, along with our original $type, we make a
546
+        // list of the ones for which a sharing backend has been registered.
547
+        // FIXME: Ideally, we wouldn't need to nest getItemsSharedWith in this loop but just call it
548
+        // with its $includeCollections parameter set to true. Unfortunately, this fails currently.
549
+        $allMaybeSharedItems = [];
550
+        foreach ($collectionTypes as $collectionType) {
551
+            if (isset(self::$backends[$collectionType])) {
552
+                $allMaybeSharedItems[$collectionType] = self::getItemsSharedWithUser(
553
+                    $collectionType,
554
+                    $user,
555
+                    self::FORMAT_NONE
556
+                );
557
+            }
558
+        }
559
+
560
+        $owners = [];
561
+        if ($includeOwner) {
562
+            $owners[] = $user;
563
+        }
564
+
565
+        // We take a look at all shared items of the given $type (or of the collections it is part of)
566
+        // and find out their owners. Then, we gather the tags for the original $type from all owners,
567
+        // and return them as elements of a list that look like "Tag (owner)".
568
+        foreach ($allMaybeSharedItems as $collectionType => $maybeSharedItems) {
569
+            foreach ($maybeSharedItems as $sharedItem) {
570
+                if (isset($sharedItem['id'])) { //workaround for https://github.com/owncloud/core/issues/2814
571
+                    $owners[] = $sharedItem['uid_owner'];
572
+                }
573
+            }
574
+        }
575
+
576
+        return $owners;
577
+    }
578
+
579
+    /**
580
+     * Get shared items from the database
581
+     * @param string $itemType
582
+     * @param string $item Item source or target (optional)
583
+     * @param int $shareType SHARE_TYPE_USER, SHARE_TYPE_GROUP, SHARE_TYPE_LINK, $shareTypeUserAndGroups, or $shareTypeGroupUserUnique
584
+     * @param string $shareWith User or group the item is being shared with
585
+     * @param string $uidOwner User that is the owner of shared items (optional)
586
+     * @param int $format Format to convert items to with formatItems() (optional)
587
+     * @param mixed $parameters to pass to formatItems() (optional)
588
+     * @param int $limit Number of items to return, -1 to return all matches (optional)
589
+     * @param boolean $includeCollections Include collection item types (optional)
590
+     * @param boolean $itemShareWithBySource (optional)
591
+     * @param boolean $checkExpireDate
592
+     * @return array
593
+     *
594
+     * See public functions getItem(s)... for parameter usage
595
+     *
596
+     */
597
+    public static function getItems($itemType, $item = null, $shareType = null, $shareWith = null,
598
+                                    $uidOwner = null, $format = self::FORMAT_NONE, $parameters = null, $limit = -1,
599
+                                    $includeCollections = false, $itemShareWithBySource = false, $checkExpireDate  = true) {
600
+        if (\OC::$server->getConfig()->getAppValue('core', 'shareapi_enabled', 'yes') != 'yes') {
601
+            return [];
602
+        }
603
+        $backend = self::getBackend($itemType);
604
+        $collectionTypes = false;
605
+        // Get filesystem root to add it to the file target and remove from the
606
+        // file source, match file_source with the file cache
607
+        if ($itemType == 'file' || $itemType == 'folder') {
608
+            if(!is_null($uidOwner)) {
609
+                $root = \OC\Files\Filesystem::getRoot();
610
+            } else {
611
+                $root = '';
612
+            }
613
+            $where = 'INNER JOIN `*PREFIX*filecache` ON `file_source` = `*PREFIX*filecache`.`fileid` ';
614
+            if (!isset($item)) {
615
+                $where .= ' AND `file_target` IS NOT NULL ';
616
+            }
617
+            $where .= 'INNER JOIN `*PREFIX*storages` ON `numeric_id` = `*PREFIX*filecache`.`storage` ';
618
+            $fileDependent = true;
619
+            $queryArgs = [];
620
+        } else {
621
+            $fileDependent = false;
622
+            $root = '';
623
+            $collectionTypes = self::getCollectionItemTypes($itemType);
624
+            if ($includeCollections && !isset($item) && $collectionTypes) {
625
+                // If includeCollections is true, find collections of this item type, e.g. a music album contains songs
626
+                if (!in_array($itemType, $collectionTypes)) {
627
+                    $itemTypes = array_merge([$itemType], $collectionTypes);
628
+                } else {
629
+                    $itemTypes = $collectionTypes;
630
+                }
631
+                $placeholders = implode(',', array_fill(0, count($itemTypes), '?'));
632
+                $where = ' WHERE `item_type` IN ('.$placeholders.'))';
633
+                $queryArgs = $itemTypes;
634
+            } else {
635
+                $where = ' WHERE `item_type` = ?';
636
+                $queryArgs = [$itemType];
637
+            }
638
+        }
639
+        if (\OC::$server->getConfig()->getAppValue('core', 'shareapi_allow_links', 'yes') !== 'yes') {
640
+            $where .= ' AND `share_type` != ?';
641
+            $queryArgs[] = self::SHARE_TYPE_LINK;
642
+        }
643
+        if (isset($shareType)) {
644
+            // Include all user and group items
645
+            if ($shareType == self::$shareTypeUserAndGroups && isset($shareWith)) {
646
+                $where .= ' AND ((`share_type` in (?, ?) AND `share_with` = ?) ';
647
+                $queryArgs[] = self::SHARE_TYPE_USER;
648
+                $queryArgs[] = self::$shareTypeGroupUserUnique;
649
+                $queryArgs[] = $shareWith;
650
+
651
+                $user = \OC::$server->getUserManager()->get($shareWith);
652
+                $groups = [];
653
+                if ($user) {
654
+                    $groups = \OC::$server->getGroupManager()->getUserGroupIds($user);
655
+                }
656
+                if (!empty($groups)) {
657
+                    $placeholders = implode(',', array_fill(0, count($groups), '?'));
658
+                    $where .= ' OR (`share_type` = ? AND `share_with` IN ('.$placeholders.')) ';
659
+                    $queryArgs[] = self::SHARE_TYPE_GROUP;
660
+                    $queryArgs = array_merge($queryArgs, $groups);
661
+                }
662
+                $where .= ')';
663
+                // Don't include own group shares
664
+                $where .= ' AND `uid_owner` != ?';
665
+                $queryArgs[] = $shareWith;
666
+            } else {
667
+                $where .= ' AND `share_type` = ?';
668
+                $queryArgs[] = $shareType;
669
+                if (isset($shareWith)) {
670
+                    $where .= ' AND `share_with` = ?';
671
+                    $queryArgs[] = $shareWith;
672
+                }
673
+            }
674
+        }
675
+        if (isset($uidOwner)) {
676
+            $where .= ' AND `uid_owner` = ?';
677
+            $queryArgs[] = $uidOwner;
678
+            if (!isset($shareType)) {
679
+                // Prevent unique user targets for group shares from being selected
680
+                $where .= ' AND `share_type` != ?';
681
+                $queryArgs[] = self::$shareTypeGroupUserUnique;
682
+            }
683
+            if ($fileDependent) {
684
+                $column = 'file_source';
685
+            } else {
686
+                $column = 'item_source';
687
+            }
688
+        } else {
689
+            if ($fileDependent) {
690
+                $column = 'file_target';
691
+            } else {
692
+                $column = 'item_target';
693
+            }
694
+        }
695
+        if (isset($item)) {
696
+            $collectionTypes = self::getCollectionItemTypes($itemType);
697
+            if ($includeCollections && $collectionTypes && !in_array('folder', $collectionTypes)) {
698
+                $where .= ' AND (';
699
+            } else {
700
+                $where .= ' AND';
701
+            }
702
+            // If looking for own shared items, check item_source else check item_target
703
+            if (isset($uidOwner) || $itemShareWithBySource) {
704
+                // If item type is a file, file source needs to be checked in case the item was converted
705
+                if ($fileDependent) {
706
+                    $where .= ' `file_source` = ?';
707
+                    $column = 'file_source';
708
+                } else {
709
+                    $where .= ' `item_source` = ?';
710
+                    $column = 'item_source';
711
+                }
712
+            } else {
713
+                if ($fileDependent) {
714
+                    $where .= ' `file_target` = ?';
715
+                    $item = \OC\Files\Filesystem::normalizePath($item);
716
+                } else {
717
+                    $where .= ' `item_target` = ?';
718
+                }
719
+            }
720
+            $queryArgs[] = $item;
721
+            if ($includeCollections && $collectionTypes && !in_array('folder', $collectionTypes)) {
722
+                $placeholders = implode(',', array_fill(0, count($collectionTypes), '?'));
723
+                $where .= ' OR `item_type` IN ('.$placeholders.'))';
724
+                $queryArgs = array_merge($queryArgs, $collectionTypes);
725
+            }
726
+        }
727
+
728
+        if ($shareType == self::$shareTypeUserAndGroups && $limit === 1) {
729
+            // Make sure the unique user target is returned if it exists,
730
+            // unique targets should follow the group share in the database
731
+            // If the limit is not 1, the filtering can be done later
732
+            $where .= ' ORDER BY `*PREFIX*share`.`id` DESC';
733
+        } else {
734
+            $where .= ' ORDER BY `*PREFIX*share`.`id` ASC';
735
+        }
736
+
737
+        if ($limit != -1 && !$includeCollections) {
738
+            // The limit must be at least 3, because filtering needs to be done
739
+            if ($limit < 3) {
740
+                $queryLimit = 3;
741
+            } else {
742
+                $queryLimit = $limit;
743
+            }
744
+        } else {
745
+            $queryLimit = null;
746
+        }
747
+        $select = self::createSelectStatement($format, $fileDependent, $uidOwner);
748
+        $root = strlen($root);
749
+        $query = \OC_DB::prepare('SELECT '.$select.' FROM `*PREFIX*share` '.$where, $queryLimit);
750
+        $result = $query->execute($queryArgs);
751
+        if ($result === false) {
752
+            \OCP\Util::writeLog('OCP\Share',
753
+                \OC_DB::getErrorMessage() . ', select=' . $select . ' where=',
754
+                ILogger::ERROR);
755
+        }
756
+        $items = [];
757
+        $targets = [];
758
+        $switchedItems = [];
759
+        $mounts = [];
760
+        while ($row = $result->fetchRow()) {
761
+            self::transformDBResults($row);
762
+            // Filter out duplicate group shares for users with unique targets
763
+            if ($fileDependent && !self::isFileReachable($row['path'], $row['storage_id'])) {
764
+                continue;
765
+            }
766
+            if ($row['share_type'] == self::$shareTypeGroupUserUnique && isset($items[$row['parent']])) {
767
+                $row['share_type'] = self::SHARE_TYPE_GROUP;
768
+                $row['unique_name'] = true; // remember that we use a unique name for this user
769
+                $row['share_with'] = $items[$row['parent']]['share_with'];
770
+                // if the group share was unshared from the user we keep the permission, otherwise
771
+                // we take the permission from the parent because this is always the up-to-date
772
+                // permission for the group share
773
+                if ($row['permissions'] > 0) {
774
+                    $row['permissions'] = $items[$row['parent']]['permissions'];
775
+                }
776
+                // Remove the parent group share
777
+                unset($items[$row['parent']]);
778
+                if ($row['permissions'] == 0) {
779
+                    continue;
780
+                }
781
+            } else if (!isset($uidOwner)) {
782
+                // Check if the same target already exists
783
+                if (isset($targets[$row['id']])) {
784
+                    // Check if the same owner shared with the user twice
785
+                    // through a group and user share - this is allowed
786
+                    $id = $targets[$row['id']];
787
+                    if (isset($items[$id]) && $items[$id]['uid_owner'] == $row['uid_owner']) {
788
+                        // Switch to group share type to ensure resharing conditions aren't bypassed
789
+                        if ($items[$id]['share_type'] != self::SHARE_TYPE_GROUP) {
790
+                            $items[$id]['share_type'] = self::SHARE_TYPE_GROUP;
791
+                            $items[$id]['share_with'] = $row['share_with'];
792
+                        }
793
+                        // Switch ids if sharing permission is granted on only
794
+                        // one share to ensure correct parent is used if resharing
795
+                        if (~(int)$items[$id]['permissions'] & \OCP\Constants::PERMISSION_SHARE
796
+                            && (int)$row['permissions'] & \OCP\Constants::PERMISSION_SHARE) {
797
+                            $items[$row['id']] = $items[$id];
798
+                            $switchedItems[$id] = $row['id'];
799
+                            unset($items[$id]);
800
+                            $id = $row['id'];
801
+                        }
802
+                        $items[$id]['permissions'] |= (int)$row['permissions'];
803
+
804
+                    }
805
+                    continue;
806
+                } elseif (!empty($row['parent'])) {
807
+                    $targets[$row['parent']] = $row['id'];
808
+                }
809
+            }
810
+            // Remove root from file source paths if retrieving own shared items
811
+            if (isset($uidOwner) && isset($row['path'])) {
812
+                if (isset($row['parent'])) {
813
+                    $query = \OC_DB::prepare('SELECT `file_target` FROM `*PREFIX*share` WHERE `id` = ?');
814
+                    $parentResult = $query->execute([$row['parent']]);
815
+                    if ($result === false) {
816
+                        \OCP\Util::writeLog('OCP\Share', 'Can\'t select parent: ' .
817
+                            \OC_DB::getErrorMessage() . ', select=' . $select . ' where=' . $where,
818
+                            ILogger::ERROR);
819
+                    } else {
820
+                        $parentRow = $parentResult->fetchRow();
821
+                        $tmpPath = $parentRow['file_target'];
822
+                        // find the right position where the row path continues from the target path
823
+                        $pos = strrpos($row['path'], $parentRow['file_target']);
824
+                        $subPath = substr($row['path'], $pos);
825
+                        $splitPath = explode('/', $subPath);
826
+                        foreach (array_slice($splitPath, 2) as $pathPart) {
827
+                            $tmpPath = $tmpPath . '/' . $pathPart;
828
+                        }
829
+                        $row['path'] = $tmpPath;
830
+                    }
831
+                } else {
832
+                    if (!isset($mounts[$row['storage']])) {
833
+                        $mountPoints = \OC\Files\Filesystem::getMountByNumericId($row['storage']);
834
+                        if (is_array($mountPoints) && !empty($mountPoints)) {
835
+                            $mounts[$row['storage']] = current($mountPoints);
836
+                        }
837
+                    }
838
+                    if (!empty($mounts[$row['storage']])) {
839
+                        $path = $mounts[$row['storage']]->getMountPoint().$row['path'];
840
+                        $relPath = substr($path, $root); // path relative to data/user
841
+                        $row['path'] = rtrim($relPath, '/');
842
+                    }
843
+                }
844
+            }
845
+
846
+            if($checkExpireDate) {
847
+                if (self::expireItem($row)) {
848
+                    continue;
849
+                }
850
+            }
851
+            // Check if resharing is allowed, if not remove share permission
852
+            if (isset($row['permissions']) && (!self::isResharingAllowed() | \OCP\Util::isSharingDisabledForUser())) {
853
+                $row['permissions'] &= ~\OCP\Constants::PERMISSION_SHARE;
854
+            }
855
+            // Add display names to result
856
+            $row['share_with_displayname'] = $row['share_with'];
857
+            if (isset($row['share_with']) && $row['share_with'] != '' &&
858
+                $row['share_type'] === self::SHARE_TYPE_USER) {
859
+                $shareWithUser = \OC::$server->getUserManager()->get($row['share_with']);
860
+                $row['share_with_displayname'] = $shareWithUser === null ? $row['share_with'] : $shareWithUser->getDisplayName();
861
+            } else if(isset($row['share_with']) && $row['share_with'] != '' &&
862
+                $row['share_type'] === self::SHARE_TYPE_REMOTE) {
863
+                $addressBookEntries = \OC::$server->getContactsManager()->search($row['share_with'], ['CLOUD']);
864
+                foreach ($addressBookEntries as $entry) {
865
+                    foreach ($entry['CLOUD'] as $cloudID) {
866
+                        if ($cloudID === $row['share_with']) {
867
+                            $row['share_with_displayname'] = $entry['FN'];
868
+                        }
869
+                    }
870
+                }
871
+            }
872
+            if (isset($row['uid_owner']) && $row['uid_owner'] != '') {
873
+                $ownerUser = \OC::$server->getUserManager()->get($row['uid_owner']);
874
+                $row['displayname_owner'] = $ownerUser === null ? $row['uid_owner'] : $ownerUser->getDisplayName();
875
+            }
876
+
877
+            if ($row['permissions'] > 0) {
878
+                $items[$row['id']] = $row;
879
+            }
880
+
881
+        }
882
+
883
+        // group items if we are looking for items shared with the current user
884
+        if (isset($shareWith) && $shareWith === \OCP\User::getUser()) {
885
+            $items = self::groupItems($items, $itemType);
886
+        }
887
+
888
+        if (!empty($items)) {
889
+            $collectionItems = [];
890
+            foreach ($items as &$row) {
891
+                // Return only the item instead of a 2-dimensional array
892
+                if ($limit == 1 && $row[$column] == $item && ($row['item_type'] == $itemType || $itemType == 'file')) {
893
+                    if ($format == self::FORMAT_NONE) {
894
+                        return $row;
895
+                    } else {
896
+                        break;
897
+                    }
898
+                }
899
+                // Check if this is a collection of the requested item type
900
+                if ($includeCollections && $collectionTypes && $row['item_type'] !== 'folder' && in_array($row['item_type'], $collectionTypes)) {
901
+                    if (($collectionBackend = self::getBackend($row['item_type']))
902
+                        && $collectionBackend instanceof \OCP\Share_Backend_Collection) {
903
+                        // Collections can be inside collections, check if the item is a collection
904
+                        if (isset($item) && $row['item_type'] == $itemType && $row[$column] == $item) {
905
+                            $collectionItems[] = $row;
906
+                        } else {
907
+                            $collection = [];
908
+                            $collection['item_type'] = $row['item_type'];
909
+                            if ($row['item_type'] == 'file' || $row['item_type'] == 'folder') {
910
+                                $collection['path'] = basename($row['path']);
911
+                            }
912
+                            $row['collection'] = $collection;
913
+                            // Fetch all of the children sources
914
+                            $children = $collectionBackend->getChildren($row[$column]);
915
+                            foreach ($children as $child) {
916
+                                $childItem = $row;
917
+                                $childItem['item_type'] = $itemType;
918
+                                if ($row['item_type'] != 'file' && $row['item_type'] != 'folder') {
919
+                                    $childItem['item_source'] = $child['source'];
920
+                                    $childItem['item_target'] = $child['target'];
921
+                                }
922
+                                if ($backend instanceof \OCP\Share_Backend_File_Dependent) {
923
+                                    if ($row['item_type'] == 'file' || $row['item_type'] == 'folder') {
924
+                                        $childItem['file_source'] = $child['source'];
925
+                                    } else { // TODO is this really needed if we already know that we use the file backend?
926
+                                        $meta = \OC\Files\Filesystem::getFileInfo($child['file_path']);
927
+                                        $childItem['file_source'] = $meta['fileid'];
928
+                                    }
929
+                                    $childItem['file_target'] =
930
+                                        \OC\Files\Filesystem::normalizePath($child['file_path']);
931
+                                }
932
+                                if (isset($item)) {
933
+                                    if ($childItem[$column] == $item) {
934
+                                        // Return only the item instead of a 2-dimensional array
935
+                                        if ($limit == 1) {
936
+                                            if ($format == self::FORMAT_NONE) {
937
+                                                return $childItem;
938
+                                            } else {
939
+                                                // Unset the items array and break out of both loops
940
+                                                $items = [];
941
+                                                $items[] = $childItem;
942
+                                                break 2;
943
+                                            }
944
+                                        } else {
945
+                                            $collectionItems[] = $childItem;
946
+                                        }
947
+                                    }
948
+                                } else {
949
+                                    $collectionItems[] = $childItem;
950
+                                }
951
+                            }
952
+                        }
953
+                    }
954
+                    // Remove collection item
955
+                    $toRemove = $row['id'];
956
+                    if (array_key_exists($toRemove, $switchedItems)) {
957
+                        $toRemove = $switchedItems[$toRemove];
958
+                    }
959
+                    unset($items[$toRemove]);
960
+                } elseif ($includeCollections && $collectionTypes && in_array($row['item_type'], $collectionTypes)) {
961
+                    // FIXME: Thats a dirty hack to improve file sharing performance,
962
+                    // see github issue #10588 for more details
963
+                    // Need to find a solution which works for all back-ends
964
+                    $collectionBackend = self::getBackend($row['item_type']);
965
+                    $sharedParents = $collectionBackend->getParents($row['item_source']);
966
+                    foreach ($sharedParents as $parent) {
967
+                        $collectionItems[] = $parent;
968
+                    }
969
+                }
970
+            }
971
+            if (!empty($collectionItems)) {
972
+                $collectionItems = array_unique($collectionItems, SORT_REGULAR);
973
+                $items = array_merge($items, $collectionItems);
974
+            }
975
+
976
+            // filter out invalid items, these can appear when subshare entries exist
977
+            // for a group in which the requested user isn't a member any more
978
+            $items = array_filter($items, function ($item) {
979
+                return $item['share_type'] !== self::$shareTypeGroupUserUnique;
980
+            });
981
+
982
+            return self::formatResult($items, $column, $backend, $format, $parameters);
983
+        } elseif ($includeCollections && $collectionTypes && in_array('folder', $collectionTypes)) {
984
+            // FIXME: Thats a dirty hack to improve file sharing performance,
985
+            // see github issue #10588 for more details
986
+            // Need to find a solution which works for all back-ends
987
+            $collectionItems = [];
988
+            $collectionBackend = self::getBackend('folder');
989
+            $sharedParents = $collectionBackend->getParents($item, $shareWith, $uidOwner);
990
+            foreach ($sharedParents as $parent) {
991
+                $collectionItems[] = $parent;
992
+            }
993
+            if ($limit === 1) {
994
+                return reset($collectionItems);
995
+            }
996
+            return self::formatResult($collectionItems, $column, $backend, $format, $parameters);
997
+        }
998
+
999
+        return [];
1000
+    }
1001
+
1002
+    /**
1003
+     * group items with link to the same source
1004
+     *
1005
+     * @param array $items
1006
+     * @param string $itemType
1007
+     * @return array of grouped items
1008
+     */
1009
+    protected static function groupItems($items, $itemType) {
1010
+
1011
+        $fileSharing = $itemType === 'file' || $itemType === 'folder';
1012
+
1013
+        $result = [];
1014
+
1015
+        foreach ($items as $item) {
1016
+            $grouped = false;
1017
+            foreach ($result as $key => $r) {
1018
+                // for file/folder shares we need to compare file_source, otherwise we compare item_source
1019
+                // only group shares if they already point to the same target, otherwise the file where shared
1020
+                // before grouping of shares was added. In this case we don't group them toi avoid confusions
1021
+                if (($fileSharing && $item['file_source'] === $r['file_source'] && $item['file_target'] === $r['file_target']) ||
1022
+                    (!$fileSharing && $item['item_source'] === $r['item_source'] && $item['item_target'] === $r['item_target'])) {
1023
+                    // add the first item to the list of grouped shares
1024
+                    if (!isset($result[$key]['grouped'])) {
1025
+                        $result[$key]['grouped'][] = $result[$key];
1026
+                    }
1027
+                    $result[$key]['permissions'] = (int) $item['permissions'] | (int) $r['permissions'];
1028
+                    $result[$key]['grouped'][] = $item;
1029
+                    $grouped = true;
1030
+                    break;
1031
+                }
1032
+            }
1033
+
1034
+            if (!$grouped) {
1035
+                $result[] = $item;
1036
+            }
1037
+
1038
+        }
1039
+
1040
+        return $result;
1041
+    }
1042
+
1043
+    /**
1044
+     * Put shared item into the database
1045
+     * @param string $itemType Item type
1046
+     * @param string $itemSource Item source
1047
+     * @param int $shareType SHARE_TYPE_USER, SHARE_TYPE_GROUP, or SHARE_TYPE_LINK
1048
+     * @param string $shareWith User or group the item is being shared with
1049
+     * @param string $uidOwner User that is the owner of shared item
1050
+     * @param int $permissions CRUDS permissions
1051
+     * @throws \Exception
1052
+     * @return mixed id of the new share or false
1053
+     * @deprecated TESTS ONLY - this methods is only used by tests
1054
+     * called like this:
1055
+     * self::put('test', $itemSource, self::SHARE_TYPE_USER, $shareWith, $uidOwner, $permissions);
1056
+     */
1057
+    private static function put($itemType, $itemSource, $shareType, $shareWith, $uidOwner,
1058
+                                $permissions) {
1059
+
1060
+        $queriesToExecute = [];
1061
+        $suggestedItemTarget = null;
1062
+        $groupFileTarget = $fileTarget = $suggestedFileTarget = $filePath = '';
1063
+        $groupItemTarget = $itemTarget = $fileSource = $parent = 0;
1064
+
1065
+        $result = self::checkReshare('test', $itemSource, self::SHARE_TYPE_USER, $shareWith, $uidOwner, $permissions, null, null);
1066
+        if(!empty($result)) {
1067
+            $parent = $result['parent'];
1068
+            $itemSource = $result['itemSource'];
1069
+            $fileSource = $result['fileSource'];
1070
+            $suggestedItemTarget = $result['suggestedItemTarget'];
1071
+            $suggestedFileTarget = $result['suggestedFileTarget'];
1072
+            $filePath = $result['filePath'];
1073
+        }
1074
+
1075
+        $isGroupShare = false;
1076
+            $users = [$shareWith];
1077
+            $itemTarget = Helper::generateTarget($itemType, $itemSource, $shareType, $shareWith, $uidOwner,
1078
+                $suggestedItemTarget);
1079
+
1080
+        $run = true;
1081
+        $error = '';
1082
+        $preHookData = [
1083
+            'itemType' => $itemType,
1084
+            'itemSource' => $itemSource,
1085
+            'shareType' => $shareType,
1086
+            'uidOwner' => $uidOwner,
1087
+            'permissions' => $permissions,
1088
+            'fileSource' => $fileSource,
1089
+            'expiration' => null,
1090
+            'token' => null,
1091
+            'run' => &$run,
1092
+            'error' => &$error
1093
+        ];
1094
+
1095
+        $preHookData['itemTarget'] = $itemTarget;
1096
+        $preHookData['shareWith'] = $shareWith;
1097
+
1098
+        \OC_Hook::emit(\OCP\Share::class, 'pre_shared', $preHookData);
1099
+
1100
+        if ($run === false) {
1101
+            throw new \Exception($error);
1102
+        }
1103
+
1104
+        foreach ($users as $user) {
1105
+            $sourceId = ($itemType === 'file' || $itemType === 'folder') ? $fileSource : $itemSource;
1106
+            $sourceExists = self::getItemSharedWithBySource($itemType, $sourceId, self::FORMAT_NONE, null, true, $user);
1107
+
1108
+            $userShareType = $shareType;
1109
+
1110
+            if ($sourceExists && $sourceExists['item_source'] === $itemSource) {
1111
+                $fileTarget = $sourceExists['file_target'];
1112
+                $itemTarget = $sourceExists['item_target'];
1113
+
1114
+            } elseif(!$sourceExists)  {
1115
+
1116
+                $itemTarget = Helper::generateTarget($itemType, $itemSource, $userShareType, $user,
1117
+                    $uidOwner, $suggestedItemTarget, $parent);
1118
+                if (isset($fileSource)) {
1119
+                        $fileTarget = Helper::generateTarget('file', $filePath, $userShareType,
1120
+                            $user, $uidOwner, $suggestedFileTarget, $parent);
1121
+                } else {
1122
+                    $fileTarget = null;
1123
+                }
1124
+
1125
+            } else {
1126
+
1127
+                // group share which doesn't exists until now, check if we need a unique target for this user
1128
+
1129
+                $itemTarget = Helper::generateTarget($itemType, $itemSource, self::SHARE_TYPE_USER, $user,
1130
+                    $uidOwner, $suggestedItemTarget, $parent);
1131
+
1132
+                // do we also need a file target
1133
+                if (isset($fileSource)) {
1134
+                    $fileTarget = Helper::generateTarget('file', $filePath, self::SHARE_TYPE_USER, $user,
1135
+                        $uidOwner, $suggestedFileTarget, $parent);
1136
+                } else {
1137
+                    $fileTarget = null;
1138
+                }
1139
+
1140
+                if (($itemTarget === $groupItemTarget) &&
1141
+                    (!isset($fileSource) || $fileTarget === $groupFileTarget)) {
1142
+                    continue;
1143
+                }
1144
+            }
1145
+
1146
+            $queriesToExecute[] = [
1147
+                'itemType'			=> $itemType,
1148
+                'itemSource'		=> $itemSource,
1149
+                'itemTarget'		=> $itemTarget,
1150
+                'shareType'			=> $userShareType,
1151
+                'shareWith'			=> $user,
1152
+                'uidOwner'			=> $uidOwner,
1153
+                'permissions'		=> $permissions,
1154
+                'shareTime'			=> time(),
1155
+                'fileSource'		=> $fileSource,
1156
+                'fileTarget'		=> $fileTarget,
1157
+                'token'				=> null,
1158
+                'parent'			=> $parent,
1159
+                'expiration'		=> null,
1160
+            ];
1161
+
1162
+        }
1163
+
1164
+        $id = false;
1165
+
1166
+        foreach ($queriesToExecute as $shareQuery) {
1167
+            $shareQuery['parent'] = $parent;
1168
+            $id = self::insertShare($shareQuery);
1169
+        }
1170
+
1171
+        $postHookData = [
1172
+            'itemType' => $itemType,
1173
+            'itemSource' => $itemSource,
1174
+            'parent' => $parent,
1175
+            'shareType' => $shareType,
1176
+            'uidOwner' => $uidOwner,
1177
+            'permissions' => $permissions,
1178
+            'fileSource' => $fileSource,
1179
+            'id' => $parent,
1180
+            'token' => null,
1181
+            'expirationDate' => null,
1182
+        ];
1183
+
1184
+        $postHookData['shareWith'] = $isGroupShare ? $shareWith['group'] : $shareWith;
1185
+        $postHookData['itemTarget'] = $isGroupShare ? $groupItemTarget : $itemTarget;
1186
+        $postHookData['fileTarget'] = $isGroupShare ? $groupFileTarget : $fileTarget;
1187
+
1188
+        \OC_Hook::emit(\OCP\Share::class, 'post_shared', $postHookData);
1189
+
1190
+
1191
+        return $id ? $id : false;
1192
+    }
1193
+
1194
+    /**
1195
+     * @param string $itemType
1196
+     * @param string $itemSource
1197
+     * @param int $shareType
1198
+     * @param string $shareWith
1199
+     * @param string $uidOwner
1200
+     * @param int $permissions
1201
+     * @param string|null $itemSourceName
1202
+     * @param null|\DateTime $expirationDate
1203
+     * @deprecated TESTS ONLY - this methods is only used by tests
1204
+     * called like this:
1205
+     * self::checkReshare('test', $itemSource, self::SHARE_TYPE_USER, $shareWith, $uidOwner, $permissions, null, null);
1206
+     */
1207
+    private static function checkReshare($itemType, $itemSource, $shareType, $shareWith, $uidOwner, $permissions, $itemSourceName, $expirationDate) {
1208
+        $backend = self::getBackend($itemType);
1209
+
1210
+        $result = [];
1211
+
1212
+        $column = ($itemType === 'file' || $itemType === 'folder') ? 'file_source' : 'item_source';
1213
+
1214
+        $checkReshare = self::getItemSharedWithBySource($itemType, $itemSource, self::FORMAT_NONE, null, true);
1215
+        if ($checkReshare) {
1216
+            // Check if attempting to share back to owner
1217
+            if ($checkReshare['uid_owner'] == $shareWith) {
1218
+                $message = 'Sharing %1$s failed, because the user %2$s is the original sharer';
1219
+                throw new \Exception(sprintf($message, $itemSourceName, $shareWith));
1220
+            }
1221
+        }
1222
+
1223
+        if ($checkReshare && $checkReshare['uid_owner'] !== \OC_User::getUser()) {
1224
+            // Check if share permissions is granted
1225
+            if (self::isResharingAllowed() && (int)$checkReshare['permissions'] & \OCP\Constants::PERMISSION_SHARE) {
1226
+                if (~(int)$checkReshare['permissions'] & $permissions) {
1227
+                    $message = 'Sharing %1$s failed, because the permissions exceed permissions granted to %2$s';
1228
+                    throw new \Exception(sprintf($message, $itemSourceName, $uidOwner));
1229
+                } else {
1230
+                    // TODO Don't check if inside folder
1231
+                    $result['parent'] = $checkReshare['id'];
1232
+
1233
+                    $result['expirationDate'] = $expirationDate;
1234
+                    // $checkReshare['expiration'] could be null and then is always less than any value
1235
+                    if(isset($checkReshare['expiration']) && $checkReshare['expiration'] < $expirationDate) {
1236
+                        $result['expirationDate'] = $checkReshare['expiration'];
1237
+                    }
1238
+
1239
+                    // only suggest the same name as new target if it is a reshare of the
1240
+                    // same file/folder and not the reshare of a child
1241
+                    if ($checkReshare[$column] === $itemSource) {
1242
+                        $result['filePath'] = $checkReshare['file_target'];
1243
+                        $result['itemSource'] = $checkReshare['item_source'];
1244
+                        $result['fileSource'] = $checkReshare['file_source'];
1245
+                        $result['suggestedItemTarget'] = $checkReshare['item_target'];
1246
+                        $result['suggestedFileTarget'] = $checkReshare['file_target'];
1247
+                    } else {
1248
+                        $result['filePath'] = ($backend instanceof \OCP\Share_Backend_File_Dependent) ? $backend->getFilePath($itemSource, $uidOwner) : null;
1249
+                        $result['suggestedItemTarget'] = null;
1250
+                        $result['suggestedFileTarget'] = null;
1251
+                        $result['itemSource'] = $itemSource;
1252
+                        $result['fileSource'] = ($backend instanceof \OCP\Share_Backend_File_Dependent) ? $itemSource : null;
1253
+                    }
1254
+                }
1255
+            } else {
1256
+                $message = 'Sharing %s failed, because resharing is not allowed';
1257
+                throw new \Exception(sprintf($message, $itemSourceName));
1258
+            }
1259
+        } else {
1260
+            $result['parent'] = null;
1261
+            $result['suggestedItemTarget'] = null;
1262
+            $result['suggestedFileTarget'] = null;
1263
+            $result['itemSource'] = $itemSource;
1264
+            $result['expirationDate'] = $expirationDate;
1265
+            if (!$backend->isValidSource($itemSource, $uidOwner)) {
1266
+                $message = 'Sharing %1$s failed, because the sharing backend for '
1267
+                    .'%2$s could not find its source';
1268
+                throw new \Exception(sprintf($message, $itemSource, $itemType));
1269
+            }
1270
+            if ($backend instanceof \OCP\Share_Backend_File_Dependent) {
1271
+                $result['filePath'] = $backend->getFilePath($itemSource, $uidOwner);
1272
+                    $meta = \OC\Files\Filesystem::getFileInfo($result['filePath']);
1273
+                    $result['fileSource'] = $meta['fileid'];
1274
+                if ($result['fileSource'] == -1) {
1275
+                    $message = 'Sharing %s failed, because the file could not be found in the file cache';
1276
+                    throw new \Exception(sprintf($message, $itemSource));
1277
+                }
1278
+            } else {
1279
+                $result['filePath'] = null;
1280
+                $result['fileSource'] = null;
1281
+            }
1282
+        }
1283
+
1284
+        return $result;
1285
+    }
1286
+
1287
+    /**
1288
+     *
1289
+     * @param array $shareData
1290
+     * @return mixed false in case of a failure or the id of the new share
1291
+     */
1292
+    private static function insertShare(array $shareData) {
1293
+
1294
+        $query = \OC_DB::prepare('INSERT INTO `*PREFIX*share` ('
1295
+            .' `item_type`, `item_source`, `item_target`, `share_type`,'
1296
+            .' `share_with`, `uid_owner`, `permissions`, `stime`, `file_source`,'
1297
+            .' `file_target`, `token`, `parent`, `expiration`) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?)');
1298
+        $query->bindValue(1, $shareData['itemType']);
1299
+        $query->bindValue(2, $shareData['itemSource']);
1300
+        $query->bindValue(3, $shareData['itemTarget']);
1301
+        $query->bindValue(4, $shareData['shareType']);
1302
+        $query->bindValue(5, $shareData['shareWith']);
1303
+        $query->bindValue(6, $shareData['uidOwner']);
1304
+        $query->bindValue(7, $shareData['permissions']);
1305
+        $query->bindValue(8, $shareData['shareTime']);
1306
+        $query->bindValue(9, $shareData['fileSource']);
1307
+        $query->bindValue(10, $shareData['fileTarget']);
1308
+        $query->bindValue(11, $shareData['token']);
1309
+        $query->bindValue(12, $shareData['parent']);
1310
+        $query->bindValue(13, $shareData['expiration'], 'datetime');
1311
+        $result = $query->execute();
1312
+
1313
+        $id = false;
1314
+        if ($result) {
1315
+            $id =  \OC::$server->getDatabaseConnection()->lastInsertId('*PREFIX*share');
1316
+        }
1317
+
1318
+        return $id;
1319
+
1320
+    }
1321
+
1322
+    /**
1323
+     * construct select statement
1324
+     * @param int $format
1325
+     * @param boolean $fileDependent ist it a file/folder share or a generla share
1326
+     * @param string $uidOwner
1327
+     * @return string select statement
1328
+     */
1329
+    private static function createSelectStatement($format, $fileDependent, $uidOwner = null) {
1330
+        $select = '*';
1331
+        if ($format == self::FORMAT_STATUSES) {
1332
+            if ($fileDependent) {
1333
+                $select = '`*PREFIX*share`.`id`, `*PREFIX*share`.`parent`, `share_type`, `path`, `storage`, '
1334
+                    . '`share_with`, `uid_owner` , `file_source`, `stime`, `*PREFIX*share`.`permissions`, '
1335
+                    . '`*PREFIX*storages`.`id` AS `storage_id`, `*PREFIX*filecache`.`parent` as `file_parent`, '
1336
+                    . '`uid_initiator`';
1337
+            } else {
1338
+                $select = '`id`, `parent`, `share_type`, `share_with`, `uid_owner`, `item_source`, `stime`, `*PREFIX*share`.`permissions`';
1339
+            }
1340
+        } else {
1341
+            if (isset($uidOwner)) {
1342
+                if ($fileDependent) {
1343
+                    $select = '`*PREFIX*share`.`id`, `item_type`, `item_source`, `*PREFIX*share`.`parent`,'
1344
+                        . ' `share_type`, `share_with`, `file_source`, `file_target`, `path`, `*PREFIX*share`.`permissions`, `stime`,'
1345
+                        . ' `expiration`, `token`, `storage`, `mail_send`, `uid_owner`, '
1346
+                        . '`*PREFIX*storages`.`id` AS `storage_id`, `*PREFIX*filecache`.`parent` as `file_parent`';
1347
+                } else {
1348
+                    $select = '`id`, `item_type`, `item_source`, `parent`, `share_type`, `share_with`, `*PREFIX*share`.`permissions`,'
1349
+                        . ' `stime`, `file_source`, `expiration`, `token`, `mail_send`, `uid_owner`';
1350
+                }
1351
+            } else {
1352
+                if ($fileDependent) {
1353
+                    if ($format == \OCA\Files_Sharing\ShareBackend\File::FORMAT_GET_FOLDER_CONTENTS || $format == \OCA\Files_Sharing\ShareBackend\File::FORMAT_FILE_APP_ROOT) {
1354
+                        $select = '`*PREFIX*share`.`id`, `item_type`, `item_source`, `*PREFIX*share`.`parent`, `uid_owner`, '
1355
+                            . '`share_type`, `share_with`, `file_source`, `path`, `file_target`, `stime`, '
1356
+                            . '`*PREFIX*share`.`permissions`, `expiration`, `storage`, `*PREFIX*filecache`.`parent` as `file_parent`, '
1357
+                            . '`name`, `mtime`, `mimetype`, `mimepart`, `size`, `encrypted`, `etag`, `mail_send`';
1358
+                    } else {
1359
+                        $select = '`*PREFIX*share`.`id`, `item_type`, `item_source`, `item_target`,'
1360
+                            . '`*PREFIX*share`.`parent`, `share_type`, `share_with`, `uid_owner`,'
1361
+                            . '`file_source`, `path`, `file_target`, `*PREFIX*share`.`permissions`,'
1362
+                            . '`stime`, `expiration`, `token`, `storage`, `mail_send`,'
1363
+                            . '`*PREFIX*storages`.`id` AS `storage_id`, `*PREFIX*filecache`.`parent` as `file_parent`';
1364
+                    }
1365
+                }
1366
+            }
1367
+        }
1368
+        return $select;
1369
+    }
1370
+
1371
+
1372
+    /**
1373
+     * transform db results
1374
+     * @param array $row result
1375
+     */
1376
+    private static function transformDBResults(&$row) {
1377
+        if (isset($row['id'])) {
1378
+            $row['id'] = (int) $row['id'];
1379
+        }
1380
+        if (isset($row['share_type'])) {
1381
+            $row['share_type'] = (int) $row['share_type'];
1382
+        }
1383
+        if (isset($row['parent'])) {
1384
+            $row['parent'] = (int) $row['parent'];
1385
+        }
1386
+        if (isset($row['file_parent'])) {
1387
+            $row['file_parent'] = (int) $row['file_parent'];
1388
+        }
1389
+        if (isset($row['file_source'])) {
1390
+            $row['file_source'] = (int) $row['file_source'];
1391
+        }
1392
+        if (isset($row['permissions'])) {
1393
+            $row['permissions'] = (int) $row['permissions'];
1394
+        }
1395
+        if (isset($row['storage'])) {
1396
+            $row['storage'] = (int) $row['storage'];
1397
+        }
1398
+        if (isset($row['stime'])) {
1399
+            $row['stime'] = (int) $row['stime'];
1400
+        }
1401
+        if (isset($row['expiration']) && $row['share_type'] !== self::SHARE_TYPE_LINK) {
1402
+            // discard expiration date for non-link shares, which might have been
1403
+            // set by ancient bugs
1404
+            $row['expiration'] = null;
1405
+        }
1406
+    }
1407
+
1408
+    /**
1409
+     * format result
1410
+     * @param array $items result
1411
+     * @param string $column is it a file share or a general share ('file_target' or 'item_target')
1412
+     * @param \OCP\Share_Backend $backend sharing backend
1413
+     * @param int $format
1414
+     * @param array $parameters additional format parameters
1415
+     * @return array format result
1416
+     */
1417
+    private static function formatResult($items, $column, $backend, $format = self::FORMAT_NONE , $parameters = null) {
1418
+        if ($format === self::FORMAT_NONE) {
1419
+            return $items;
1420
+        } else if ($format === self::FORMAT_STATUSES) {
1421
+            $statuses = [];
1422
+            foreach ($items as $item) {
1423
+                if ($item['share_type'] === self::SHARE_TYPE_LINK) {
1424
+                    if ($item['uid_initiator'] !== \OC::$server->getUserSession()->getUser()->getUID()) {
1425
+                        continue;
1426
+                    }
1427
+                    $statuses[$item[$column]]['link'] = true;
1428
+                } else if (!isset($statuses[$item[$column]])) {
1429
+                    $statuses[$item[$column]]['link'] = false;
1430
+                }
1431
+                if (!empty($item['file_target'])) {
1432
+                    $statuses[$item[$column]]['path'] = $item['path'];
1433
+                }
1434
+            }
1435
+            return $statuses;
1436
+        } else {
1437
+            return $backend->formatItems($items, $format, $parameters);
1438
+        }
1439
+    }
1440
+
1441
+    /**
1442
+     * remove protocol from URL
1443
+     *
1444
+     * @param string $url
1445
+     * @return string
1446
+     */
1447
+    public static function removeProtocolFromUrl($url) {
1448
+        if (strpos($url, 'https://') === 0) {
1449
+            return substr($url, strlen('https://'));
1450
+        } else if (strpos($url, 'http://') === 0) {
1451
+            return substr($url, strlen('http://'));
1452
+        }
1453
+
1454
+        return $url;
1455
+    }
1456
+
1457
+    /**
1458
+     * try http post first with https and then with http as a fallback
1459
+     *
1460
+     * @param string $remoteDomain
1461
+     * @param string $urlSuffix
1462
+     * @param array $fields post parameters
1463
+     * @return array
1464
+     */
1465
+    private static function tryHttpPostToShareEndpoint($remoteDomain, $urlSuffix, array $fields) {
1466
+        $protocol = 'https://';
1467
+        $result = [
1468
+            'success' => false,
1469
+            'result' => '',
1470
+        ];
1471
+        $try = 0;
1472
+        $discoveryService = \OC::$server->query(\OCP\OCS\IDiscoveryService::class);
1473
+        while ($result['success'] === false && $try < 2) {
1474
+            $federationEndpoints = $discoveryService->discover($protocol . $remoteDomain, 'FEDERATED_SHARING');
1475
+            $endpoint = isset($federationEndpoints['share']) ? $federationEndpoints['share'] : '/ocs/v2.php/cloud/shares';
1476
+            $client = \OC::$server->getHTTPClientService()->newClient();
1477
+
1478
+            try {
1479
+                $response = $client->post(
1480
+                    $protocol . $remoteDomain . $endpoint . $urlSuffix . '?format=' . self::RESPONSE_FORMAT,
1481
+                    [
1482
+                        'body' => $fields,
1483
+                        'connect_timeout' => 10,
1484
+                    ]
1485
+                );
1486
+
1487
+                $result = ['success' => true, 'result' => $response->getBody()];
1488
+            } catch (\Exception $e) {
1489
+                $result = ['success' => false, 'result' => $e->getMessage()];
1490
+            }
1491
+
1492
+            $try++;
1493
+            $protocol = 'http://';
1494
+        }
1495
+
1496
+        return $result;
1497
+    }
1498
+
1499
+    /**
1500
+     * send server-to-server unshare to remote server
1501
+     *
1502
+     * @param string $remote url
1503
+     * @param int $id share id
1504
+     * @param string $token
1505
+     * @return bool
1506
+     */
1507
+    private static function sendRemoteUnshare($remote, $id, $token) {
1508
+        $url = rtrim($remote, '/');
1509
+        $fields = ['token' => $token, 'format' => 'json'];
1510
+        $url = self::removeProtocolFromUrl($url);
1511
+        $result = self::tryHttpPostToShareEndpoint($url, '/'.$id.'/unshare', $fields);
1512
+        $status = json_decode($result['result'], true);
1513
+
1514
+        return ($result['success'] && ($status['ocs']['meta']['statuscode'] === 100 || $status['ocs']['meta']['statuscode'] === 200));
1515
+    }
1516
+
1517
+    /**
1518
+     * @return int
1519
+     */
1520
+    public static function getExpireInterval() {
1521
+        return (int)\OC::$server->getConfig()->getAppValue('core', 'shareapi_expire_after_n_days', '7');
1522
+    }
1523
+
1524
+    /**
1525
+     * Checks whether the given path is reachable for the given owner
1526
+     *
1527
+     * @param string $path path relative to files
1528
+     * @param string $ownerStorageId storage id of the owner
1529
+     *
1530
+     * @return boolean true if file is reachable, false otherwise
1531
+     */
1532
+    private static function isFileReachable($path, $ownerStorageId) {
1533
+        // if outside the home storage, file is always considered reachable
1534
+        if (!(substr($ownerStorageId, 0, 6) === 'home::' ||
1535
+            substr($ownerStorageId, 0, 13) === 'object::user:'
1536
+        )) {
1537
+            return true;
1538
+        }
1539
+
1540
+        // if inside the home storage, the file has to be under "/files/"
1541
+        $path = ltrim($path, '/');
1542
+        if (substr($path, 0, 6) === 'files/') {
1543
+            return true;
1544
+        }
1545
+
1546
+        return false;
1547
+    }
1548 1548
 }
Please login to merge, or discard this patch.
Spacing   +33 added lines, -33 removed lines patch added patch discarded remove patch
@@ -149,7 +149,7 @@  discard block
 block discarded – undo
149 149
 
150 150
 		$select = self::createSelectStatement(self::FORMAT_NONE, $fileDependent);
151 151
 
152
-		$where .= ' `' . $column . '` = ? AND `item_type` = ? ';
152
+		$where .= ' `'.$column.'` = ? AND `item_type` = ? ';
153 153
 		$arguments = [$itemSource, $itemType];
154 154
 		// for link shares $user === null
155 155
 		if ($user !== null) {
@@ -167,7 +167,7 @@  discard block
 block discarded – undo
167 167
 			$arguments[] = $owner;
168 168
 		}
169 169
 
170
-		$query = \OC_DB::prepare('SELECT ' . $select . ' FROM `*PREFIX*share` '. $fileDependentWhere . $where);
170
+		$query = \OC_DB::prepare('SELECT '.$select.' FROM `*PREFIX*share` '.$fileDependentWhere.$where);
171 171
 
172 172
 		$result = \OC_DB::executeAudited($query, $arguments);
173 173
 
@@ -175,7 +175,7 @@  discard block
 block discarded – undo
175 175
 			if ($fileDependent && !self::isFileReachable($row['path'], $row['storage_id'])) {
176 176
 				continue;
177 177
 			}
178
-			if ($fileDependent && (int)$row['file_parent'] === -1) {
178
+			if ($fileDependent && (int) $row['file_parent'] === -1) {
179 179
 				// if it is a mount point we need to get the path from the mount manager
180 180
 				$mountManager = \OC\Files\Filesystem::getMountManager();
181 181
 				$mountPoint = $mountManager->findByStorageId($row['storage_id']);
@@ -186,7 +186,7 @@  discard block
 block discarded – undo
186 186
 					$row['path'] = $path;
187 187
 				} else {
188 188
 					\OC::$server->getLogger()->warning(
189
-						'Could not resolve mount point for ' . $row['storage_id'],
189
+						'Could not resolve mount point for '.$row['storage_id'],
190 190
 						['app' => 'OCP\Share']
191 191
 					);
192 192
 				}
@@ -195,7 +195,7 @@  discard block
 block discarded – undo
195 195
 		}
196 196
 
197 197
 		//if didn't found a result than let's look for a group share.
198
-		if(empty($shares) && $user !== null) {
198
+		if (empty($shares) && $user !== null) {
199 199
 			$userObject = \OC::$server->getUserManager()->get($user);
200 200
 			$groups = [];
201 201
 			if ($userObject) {
@@ -203,7 +203,7 @@  discard block
 block discarded – undo
203 203
 			}
204 204
 
205 205
 			if (!empty($groups)) {
206
-				$where = $fileDependentWhere . ' WHERE `' . $column . '` = ? AND `item_type` = ? AND `share_with` in (?)';
206
+				$where = $fileDependentWhere.' WHERE `'.$column.'` = ? AND `item_type` = ? AND `share_with` in (?)';
207 207
 				$arguments = [$itemSource, $itemType, $groups];
208 208
 				$types = [null, null, IQueryBuilder::PARAM_STR_ARRAY];
209 209
 
@@ -217,7 +217,7 @@  discard block
 block discarded – undo
217 217
 				// class isn't static anymore...
218 218
 				$conn = \OC::$server->getDatabaseConnection();
219 219
 				$result = $conn->executeQuery(
220
-					'SELECT ' . $select . ' FROM `*PREFIX*share` ' . $where,
220
+					'SELECT '.$select.' FROM `*PREFIX*share` '.$where,
221 221
 					$arguments,
222 222
 					$types
223 223
 				);
@@ -351,12 +351,12 @@  discard block
 block discarded – undo
351 351
 		$currentUser = $owner ? $owner : \OC_User::getUser();
352 352
 		foreach ($items as $item) {
353 353
 			// delete the item with the expected share_type and owner
354
-			if ((int)$item['share_type'] === (int)$shareType && $item['uid_owner'] === $currentUser) {
354
+			if ((int) $item['share_type'] === (int) $shareType && $item['uid_owner'] === $currentUser) {
355 355
 				$toDelete = $item;
356 356
 				// if there is more then one result we don't have to delete the children
357 357
 				// but update their parent. For group shares the new parent should always be
358 358
 				// the original group share and not the db entry with the unique name
359
-			} else if ((int)$item['share_type'] === self::$shareTypeGroupUserUnique) {
359
+			} else if ((int) $item['share_type'] === self::$shareTypeGroupUserUnique) {
360 360
 				$newParent = $item['parent'];
361 361
 			} else {
362 362
 				$newParent = $item['id'];
@@ -415,7 +415,7 @@  discard block
 block discarded – undo
415 415
 	 */
416 416
 	protected static function unshareItem(array $item, $newParent = null) {
417 417
 
418
-		$shareType = (int)$item['share_type'];
418
+		$shareType = (int) $item['share_type'];
419 419
 		$shareWith = null;
420 420
 		if ($shareType !== \OCP\Share::SHARE_TYPE_LINK) {
421 421
 			$shareWith = $item['share_with'];
@@ -431,7 +431,7 @@  discard block
 block discarded – undo
431 431
 			'itemParent'    => $item['parent'],
432 432
 			'uidOwner'      => $item['uid_owner'],
433 433
 		];
434
-		if($item['item_type'] === 'file' || $item['item_type'] === 'folder') {
434
+		if ($item['item_type'] === 'file' || $item['item_type'] === 'folder') {
435 435
 			$hookParams['fileSource'] = $item['file_source'];
436 436
 			$hookParams['fileTarget'] = $item['file_target'];
437 437
 		}
@@ -441,7 +441,7 @@  discard block
 block discarded – undo
441 441
 		$deletedShares[] = $hookParams;
442 442
 		$hookParams['deletedShares'] = $deletedShares;
443 443
 		\OC_Hook::emit(\OCP\Share::class, 'post_unshare', $hookParams);
444
-		if ((int)$item['share_type'] === \OCP\Share::SHARE_TYPE_REMOTE && \OC::$server->getUserSession()->getUser()) {
444
+		if ((int) $item['share_type'] === \OCP\Share::SHARE_TYPE_REMOTE && \OC::$server->getUserSession()->getUser()) {
445 445
 			list(, $remote) = Helper::splitUserRemote($item['share_with']);
446 446
 			self::sendRemoteUnshare($remote, $item['id'], $item['token']);
447 447
 		}
@@ -605,7 +605,7 @@  discard block
 block discarded – undo
605 605
 		// Get filesystem root to add it to the file target and remove from the
606 606
 		// file source, match file_source with the file cache
607 607
 		if ($itemType == 'file' || $itemType == 'folder') {
608
-			if(!is_null($uidOwner)) {
608
+			if (!is_null($uidOwner)) {
609 609
 				$root = \OC\Files\Filesystem::getRoot();
610 610
 			} else {
611 611
 				$root = '';
@@ -750,7 +750,7 @@  discard block
 block discarded – undo
750 750
 		$result = $query->execute($queryArgs);
751 751
 		if ($result === false) {
752 752
 			\OCP\Util::writeLog('OCP\Share',
753
-				\OC_DB::getErrorMessage() . ', select=' . $select . ' where=',
753
+				\OC_DB::getErrorMessage().', select='.$select.' where=',
754 754
 				ILogger::ERROR);
755 755
 		}
756 756
 		$items = [];
@@ -792,14 +792,14 @@  discard block
 block discarded – undo
792 792
 						}
793 793
 						// Switch ids if sharing permission is granted on only
794 794
 						// one share to ensure correct parent is used if resharing
795
-						if (~(int)$items[$id]['permissions'] & \OCP\Constants::PERMISSION_SHARE
796
-							&& (int)$row['permissions'] & \OCP\Constants::PERMISSION_SHARE) {
795
+						if (~(int) $items[$id]['permissions'] & \OCP\Constants::PERMISSION_SHARE
796
+							&& (int) $row['permissions'] & \OCP\Constants::PERMISSION_SHARE) {
797 797
 							$items[$row['id']] = $items[$id];
798 798
 							$switchedItems[$id] = $row['id'];
799 799
 							unset($items[$id]);
800 800
 							$id = $row['id'];
801 801
 						}
802
-						$items[$id]['permissions'] |= (int)$row['permissions'];
802
+						$items[$id]['permissions'] |= (int) $row['permissions'];
803 803
 
804 804
 					}
805 805
 					continue;
@@ -813,8 +813,8 @@  discard block
 block discarded – undo
813 813
 					$query = \OC_DB::prepare('SELECT `file_target` FROM `*PREFIX*share` WHERE `id` = ?');
814 814
 					$parentResult = $query->execute([$row['parent']]);
815 815
 					if ($result === false) {
816
-						\OCP\Util::writeLog('OCP\Share', 'Can\'t select parent: ' .
817
-							\OC_DB::getErrorMessage() . ', select=' . $select . ' where=' . $where,
816
+						\OCP\Util::writeLog('OCP\Share', 'Can\'t select parent: '.
817
+							\OC_DB::getErrorMessage().', select='.$select.' where='.$where,
818 818
 							ILogger::ERROR);
819 819
 					} else {
820 820
 						$parentRow = $parentResult->fetchRow();
@@ -824,7 +824,7 @@  discard block
 block discarded – undo
824 824
 						$subPath = substr($row['path'], $pos);
825 825
 						$splitPath = explode('/', $subPath);
826 826
 						foreach (array_slice($splitPath, 2) as $pathPart) {
827
-							$tmpPath = $tmpPath . '/' . $pathPart;
827
+							$tmpPath = $tmpPath.'/'.$pathPart;
828 828
 						}
829 829
 						$row['path'] = $tmpPath;
830 830
 					}
@@ -843,7 +843,7 @@  discard block
 block discarded – undo
843 843
 				}
844 844
 			}
845 845
 
846
-			if($checkExpireDate) {
846
+			if ($checkExpireDate) {
847 847
 				if (self::expireItem($row)) {
848 848
 					continue;
849 849
 				}
@@ -858,7 +858,7 @@  discard block
 block discarded – undo
858 858
 				$row['share_type'] === self::SHARE_TYPE_USER) {
859 859
 				$shareWithUser = \OC::$server->getUserManager()->get($row['share_with']);
860 860
 				$row['share_with_displayname'] = $shareWithUser === null ? $row['share_with'] : $shareWithUser->getDisplayName();
861
-			} else if(isset($row['share_with']) && $row['share_with'] != '' &&
861
+			} else if (isset($row['share_with']) && $row['share_with'] != '' &&
862 862
 				$row['share_type'] === self::SHARE_TYPE_REMOTE) {
863 863
 				$addressBookEntries = \OC::$server->getContactsManager()->search($row['share_with'], ['CLOUD']);
864 864
 				foreach ($addressBookEntries as $entry) {
@@ -975,7 +975,7 @@  discard block
 block discarded – undo
975 975
 
976 976
 			// filter out invalid items, these can appear when subshare entries exist
977 977
 			// for a group in which the requested user isn't a member any more
978
-			$items = array_filter($items, function ($item) {
978
+			$items = array_filter($items, function($item) {
979 979
 				return $item['share_type'] !== self::$shareTypeGroupUserUnique;
980 980
 			});
981 981
 
@@ -1063,7 +1063,7 @@  discard block
 block discarded – undo
1063 1063
 		$groupItemTarget = $itemTarget = $fileSource = $parent = 0;
1064 1064
 
1065 1065
 		$result = self::checkReshare('test', $itemSource, self::SHARE_TYPE_USER, $shareWith, $uidOwner, $permissions, null, null);
1066
-		if(!empty($result)) {
1066
+		if (!empty($result)) {
1067 1067
 			$parent = $result['parent'];
1068 1068
 			$itemSource = $result['itemSource'];
1069 1069
 			$fileSource = $result['fileSource'];
@@ -1111,7 +1111,7 @@  discard block
 block discarded – undo
1111 1111
 				$fileTarget = $sourceExists['file_target'];
1112 1112
 				$itemTarget = $sourceExists['item_target'];
1113 1113
 
1114
-			} elseif(!$sourceExists)  {
1114
+			} elseif (!$sourceExists) {
1115 1115
 
1116 1116
 				$itemTarget = Helper::generateTarget($itemType, $itemSource, $userShareType, $user,
1117 1117
 					$uidOwner, $suggestedItemTarget, $parent);
@@ -1222,8 +1222,8 @@  discard block
 block discarded – undo
1222 1222
 
1223 1223
 		if ($checkReshare && $checkReshare['uid_owner'] !== \OC_User::getUser()) {
1224 1224
 			// Check if share permissions is granted
1225
-			if (self::isResharingAllowed() && (int)$checkReshare['permissions'] & \OCP\Constants::PERMISSION_SHARE) {
1226
-				if (~(int)$checkReshare['permissions'] & $permissions) {
1225
+			if (self::isResharingAllowed() && (int) $checkReshare['permissions'] & \OCP\Constants::PERMISSION_SHARE) {
1226
+				if (~(int) $checkReshare['permissions'] & $permissions) {
1227 1227
 					$message = 'Sharing %1$s failed, because the permissions exceed permissions granted to %2$s';
1228 1228
 					throw new \Exception(sprintf($message, $itemSourceName, $uidOwner));
1229 1229
 				} else {
@@ -1232,7 +1232,7 @@  discard block
 block discarded – undo
1232 1232
 
1233 1233
 					$result['expirationDate'] = $expirationDate;
1234 1234
 					// $checkReshare['expiration'] could be null and then is always less than any value
1235
-					if(isset($checkReshare['expiration']) && $checkReshare['expiration'] < $expirationDate) {
1235
+					if (isset($checkReshare['expiration']) && $checkReshare['expiration'] < $expirationDate) {
1236 1236
 						$result['expirationDate'] = $checkReshare['expiration'];
1237 1237
 					}
1238 1238
 
@@ -1312,7 +1312,7 @@  discard block
 block discarded – undo
1312 1312
 
1313 1313
 		$id = false;
1314 1314
 		if ($result) {
1315
-			$id =  \OC::$server->getDatabaseConnection()->lastInsertId('*PREFIX*share');
1315
+			$id = \OC::$server->getDatabaseConnection()->lastInsertId('*PREFIX*share');
1316 1316
 		}
1317 1317
 
1318 1318
 		return $id;
@@ -1414,7 +1414,7 @@  discard block
 block discarded – undo
1414 1414
 	 * @param array $parameters additional format parameters
1415 1415
 	 * @return array format result
1416 1416
 	 */
1417
-	private static function formatResult($items, $column, $backend, $format = self::FORMAT_NONE , $parameters = null) {
1417
+	private static function formatResult($items, $column, $backend, $format = self::FORMAT_NONE, $parameters = null) {
1418 1418
 		if ($format === self::FORMAT_NONE) {
1419 1419
 			return $items;
1420 1420
 		} else if ($format === self::FORMAT_STATUSES) {
@@ -1471,13 +1471,13 @@  discard block
 block discarded – undo
1471 1471
 		$try = 0;
1472 1472
 		$discoveryService = \OC::$server->query(\OCP\OCS\IDiscoveryService::class);
1473 1473
 		while ($result['success'] === false && $try < 2) {
1474
-			$federationEndpoints = $discoveryService->discover($protocol . $remoteDomain, 'FEDERATED_SHARING');
1474
+			$federationEndpoints = $discoveryService->discover($protocol.$remoteDomain, 'FEDERATED_SHARING');
1475 1475
 			$endpoint = isset($federationEndpoints['share']) ? $federationEndpoints['share'] : '/ocs/v2.php/cloud/shares';
1476 1476
 			$client = \OC::$server->getHTTPClientService()->newClient();
1477 1477
 
1478 1478
 			try {
1479 1479
 				$response = $client->post(
1480
-					$protocol . $remoteDomain . $endpoint . $urlSuffix . '?format=' . self::RESPONSE_FORMAT,
1480
+					$protocol.$remoteDomain.$endpoint.$urlSuffix.'?format='.self::RESPONSE_FORMAT,
1481 1481
 					[
1482 1482
 						'body' => $fields,
1483 1483
 						'connect_timeout' => 10,
@@ -1518,7 +1518,7 @@  discard block
 block discarded – undo
1518 1518
 	 * @return int
1519 1519
 	 */
1520 1520
 	public static function getExpireInterval() {
1521
-		return (int)\OC::$server->getConfig()->getAppValue('core', 'shareapi_expire_after_n_days', '7');
1521
+		return (int) \OC::$server->getConfig()->getAppValue('core', 'shareapi_expire_after_n_days', '7');
1522 1522
 	}
1523 1523
 
1524 1524
 	/**
Please login to merge, or discard this patch.
lib/private/URLGenerator.php 2 patches
Indentation   +194 added lines, -194 removed lines patch added patch discarded remove patch
@@ -50,224 +50,224 @@
 block discarded – undo
50 50
  * Class to generate URLs
51 51
  */
52 52
 class URLGenerator implements IURLGenerator {
53
-	/** @var IConfig */
54
-	private $config;
55
-	/** @var ICacheFactory */
56
-	private $cacheFactory;
57
-	/** @var IRequest */
58
-	private $request;
53
+    /** @var IConfig */
54
+    private $config;
55
+    /** @var ICacheFactory */
56
+    private $cacheFactory;
57
+    /** @var IRequest */
58
+    private $request;
59 59
 
60
-	/**
61
-	 * @param IConfig $config
62
-	 * @param ICacheFactory $cacheFactory
63
-	 * @param IRequest $request
64
-	 */
65
-	public function __construct(IConfig $config,
66
-								ICacheFactory $cacheFactory,
67
-								IRequest $request) {
68
-		$this->config = $config;
69
-		$this->cacheFactory = $cacheFactory;
70
-		$this->request = $request;
71
-	}
60
+    /**
61
+     * @param IConfig $config
62
+     * @param ICacheFactory $cacheFactory
63
+     * @param IRequest $request
64
+     */
65
+    public function __construct(IConfig $config,
66
+                                ICacheFactory $cacheFactory,
67
+                                IRequest $request) {
68
+        $this->config = $config;
69
+        $this->cacheFactory = $cacheFactory;
70
+        $this->request = $request;
71
+    }
72 72
 
73
-	/**
74
-	 * Creates an url using a defined route
75
-	 * @param string $route
76
-	 * @param array $parameters args with param=>value, will be appended to the returned url
77
-	 * @return string the url
78
-	 *
79
-	 * Returns a url to the given route.
80
-	 */
81
-	public function linkToRoute(string $route, array $parameters = []): string {
82
-		// TODO: mock router
83
-		return \OC::$server->getRouter()->generate($route, $parameters);
84
-	}
73
+    /**
74
+     * Creates an url using a defined route
75
+     * @param string $route
76
+     * @param array $parameters args with param=>value, will be appended to the returned url
77
+     * @return string the url
78
+     *
79
+     * Returns a url to the given route.
80
+     */
81
+    public function linkToRoute(string $route, array $parameters = []): string {
82
+        // TODO: mock router
83
+        return \OC::$server->getRouter()->generate($route, $parameters);
84
+    }
85 85
 
86
-	/**
87
-	 * Creates an absolute url using a defined route
88
-	 * @param string $routeName
89
-	 * @param array $arguments args with param=>value, will be appended to the returned url
90
-	 * @return string the url
91
-	 *
92
-	 * Returns an absolute url to the given route.
93
-	 */
94
-	public function linkToRouteAbsolute(string $routeName, array $arguments = []): string {
95
-		return $this->getAbsoluteURL($this->linkToRoute($routeName, $arguments));
96
-	}
86
+    /**
87
+     * Creates an absolute url using a defined route
88
+     * @param string $routeName
89
+     * @param array $arguments args with param=>value, will be appended to the returned url
90
+     * @return string the url
91
+     *
92
+     * Returns an absolute url to the given route.
93
+     */
94
+    public function linkToRouteAbsolute(string $routeName, array $arguments = []): string {
95
+        return $this->getAbsoluteURL($this->linkToRoute($routeName, $arguments));
96
+    }
97 97
 
98
-	public function linkToOCSRouteAbsolute(string $routeName, array $arguments = []): string {
99
-		$route = \OC::$server->getRouter()->generate('ocs.'.$routeName, $arguments, false);
98
+    public function linkToOCSRouteAbsolute(string $routeName, array $arguments = []): string {
99
+        $route = \OC::$server->getRouter()->generate('ocs.'.$routeName, $arguments, false);
100 100
 
101
-		$indexPhpPos = strpos($route, '/index.php/');
102
-		if ($indexPhpPos !== false) {
103
-			$route = substr($route, $indexPhpPos + 10);
104
-		}
101
+        $indexPhpPos = strpos($route, '/index.php/');
102
+        if ($indexPhpPos !== false) {
103
+            $route = substr($route, $indexPhpPos + 10);
104
+        }
105 105
 
106
-		$route = substr($route, 7);
107
-		$route = '/ocs/v2.php' . $route;
106
+        $route = substr($route, 7);
107
+        $route = '/ocs/v2.php' . $route;
108 108
 
109
-		return $this->getAbsoluteURL($route);
110
-	}
109
+        return $this->getAbsoluteURL($route);
110
+    }
111 111
 
112
-	/**
113
-	 * Creates an url
114
-	 * @param string $app app
115
-	 * @param string $file file
116
-	 * @param array $args array with param=>value, will be appended to the returned url
117
-	 *    The value of $args will be urlencoded
118
-	 * @return string the url
119
-	 *
120
-	 * Returns a url to the given app and file.
121
-	 */
122
-	public function linkTo(string $app, string $file, array $args = []): string {
123
-		$frontControllerActive = ($this->config->getSystemValue('htaccess.IgnoreFrontController', false) === true || getenv('front_controller_active') === 'true');
112
+    /**
113
+     * Creates an url
114
+     * @param string $app app
115
+     * @param string $file file
116
+     * @param array $args array with param=>value, will be appended to the returned url
117
+     *    The value of $args will be urlencoded
118
+     * @return string the url
119
+     *
120
+     * Returns a url to the given app and file.
121
+     */
122
+    public function linkTo(string $app, string $file, array $args = []): string {
123
+        $frontControllerActive = ($this->config->getSystemValue('htaccess.IgnoreFrontController', false) === true || getenv('front_controller_active') === 'true');
124 124
 
125
-		if($app !== '') {
126
-			$app_path = \OC_App::getAppPath($app);
127
-			// Check if the app is in the app folder
128
-			if ($app_path && file_exists($app_path . '/' . $file)) {
129
-				if (substr($file, -3) === 'php') {
125
+        if($app !== '') {
126
+            $app_path = \OC_App::getAppPath($app);
127
+            // Check if the app is in the app folder
128
+            if ($app_path && file_exists($app_path . '/' . $file)) {
129
+                if (substr($file, -3) === 'php') {
130 130
 
131
-					$urlLinkTo = \OC::$WEBROOT . '/index.php/apps/' . $app;
132
-					if ($frontControllerActive) {
133
-						$urlLinkTo = \OC::$WEBROOT . '/apps/' . $app;
134
-					}
135
-					$urlLinkTo .= ($file !== 'index.php') ? '/' . $file : '';
136
-				} else {
137
-					$urlLinkTo = \OC_App::getAppWebPath($app) . '/' . $file;
138
-				}
139
-			} else {
140
-				$urlLinkTo = \OC::$WEBROOT . '/' . $app . '/' . $file;
141
-			}
142
-		} else {
143
-			if (file_exists(\OC::$SERVERROOT . '/core/' . $file)) {
144
-				$urlLinkTo = \OC::$WEBROOT . '/core/' . $file;
145
-			} else {
146
-				if ($frontControllerActive && $file === 'index.php') {
147
-					$urlLinkTo = \OC::$WEBROOT . '/';
148
-				} else {
149
-					$urlLinkTo = \OC::$WEBROOT . '/' . $file;
150
-				}
151
-			}
152
-		}
131
+                    $urlLinkTo = \OC::$WEBROOT . '/index.php/apps/' . $app;
132
+                    if ($frontControllerActive) {
133
+                        $urlLinkTo = \OC::$WEBROOT . '/apps/' . $app;
134
+                    }
135
+                    $urlLinkTo .= ($file !== 'index.php') ? '/' . $file : '';
136
+                } else {
137
+                    $urlLinkTo = \OC_App::getAppWebPath($app) . '/' . $file;
138
+                }
139
+            } else {
140
+                $urlLinkTo = \OC::$WEBROOT . '/' . $app . '/' . $file;
141
+            }
142
+        } else {
143
+            if (file_exists(\OC::$SERVERROOT . '/core/' . $file)) {
144
+                $urlLinkTo = \OC::$WEBROOT . '/core/' . $file;
145
+            } else {
146
+                if ($frontControllerActive && $file === 'index.php') {
147
+                    $urlLinkTo = \OC::$WEBROOT . '/';
148
+                } else {
149
+                    $urlLinkTo = \OC::$WEBROOT . '/' . $file;
150
+                }
151
+            }
152
+        }
153 153
 
154
-		if ($args && $query = http_build_query($args, '', '&')) {
155
-			$urlLinkTo .= '?' . $query;
156
-		}
154
+        if ($args && $query = http_build_query($args, '', '&')) {
155
+            $urlLinkTo .= '?' . $query;
156
+        }
157 157
 
158
-		return $urlLinkTo;
159
-	}
158
+        return $urlLinkTo;
159
+    }
160 160
 
161
-	/**
162
-	 * Creates path to an image
163
-	 * @param string $app app
164
-	 * @param string $image image name
165
-	 * @throws \RuntimeException If the image does not exist
166
-	 * @return string the url
167
-	 *
168
-	 * Returns the path to the image.
169
-	 */
170
-	public function imagePath(string $app, string $image): string {
171
-		$cache = $this->cacheFactory->createDistributed('imagePath-'.md5($this->getBaseUrl()).'-');
172
-		$cacheKey = $app.'-'.$image;
173
-		if($key = $cache->get($cacheKey)) {
174
-			return $key;
175
-		}
161
+    /**
162
+     * Creates path to an image
163
+     * @param string $app app
164
+     * @param string $image image name
165
+     * @throws \RuntimeException If the image does not exist
166
+     * @return string the url
167
+     *
168
+     * Returns the path to the image.
169
+     */
170
+    public function imagePath(string $app, string $image): string {
171
+        $cache = $this->cacheFactory->createDistributed('imagePath-'.md5($this->getBaseUrl()).'-');
172
+        $cacheKey = $app.'-'.$image;
173
+        if($key = $cache->get($cacheKey)) {
174
+            return $key;
175
+        }
176 176
 
177
-		// Read the selected theme from the config file
178
-		$theme = \OC_Util::getTheme();
177
+        // Read the selected theme from the config file
178
+        $theme = \OC_Util::getTheme();
179 179
 
180
-		//if a theme has a png but not an svg always use the png
181
-		$basename = substr(basename($image),0,-4);
180
+        //if a theme has a png but not an svg always use the png
181
+        $basename = substr(basename($image),0,-4);
182 182
 
183
-		$appPath = \OC_App::getAppPath($app);
183
+        $appPath = \OC_App::getAppPath($app);
184 184
 
185
-		// Check if the app is in the app folder
186
-		$path = '';
187
-		$themingEnabled = $this->config->getSystemValue('installed', false) && \OCP\App::isEnabled('theming') && \OC_App::isAppLoaded('theming');
188
-		$themingImagePath = false;
189
-		if($themingEnabled) {
190
-			$themingDefaults = \OC::$server->getThemingDefaults();
191
-			if ($themingDefaults instanceof ThemingDefaults) {
192
-				$themingImagePath = $themingDefaults->replaceImagePath($app, $image);
193
-			}
194
-		}
185
+        // Check if the app is in the app folder
186
+        $path = '';
187
+        $themingEnabled = $this->config->getSystemValue('installed', false) && \OCP\App::isEnabled('theming') && \OC_App::isAppLoaded('theming');
188
+        $themingImagePath = false;
189
+        if($themingEnabled) {
190
+            $themingDefaults = \OC::$server->getThemingDefaults();
191
+            if ($themingDefaults instanceof ThemingDefaults) {
192
+                $themingImagePath = $themingDefaults->replaceImagePath($app, $image);
193
+            }
194
+        }
195 195
 
196
-		if (file_exists(\OC::$SERVERROOT . "/themes/$theme/apps/$app/img/$image")) {
197
-			$path = \OC::$WEBROOT . "/themes/$theme/apps/$app/img/$image";
198
-		} elseif (!file_exists(\OC::$SERVERROOT . "/themes/$theme/apps/$app/img/$basename.svg")
199
-			&& file_exists(\OC::$SERVERROOT . "/themes/$theme/apps/$app/img/$basename.png")) {
200
-			$path =  \OC::$WEBROOT . "/themes/$theme/apps/$app/img/$basename.png";
201
-		} elseif (!empty($app) and file_exists(\OC::$SERVERROOT . "/themes/$theme/$app/img/$image")) {
202
-			$path =  \OC::$WEBROOT . "/themes/$theme/$app/img/$image";
203
-		} elseif (!empty($app) and (!file_exists(\OC::$SERVERROOT . "/themes/$theme/$app/img/$basename.svg")
204
-			&& file_exists(\OC::$SERVERROOT . "/themes/$theme/$app/img/$basename.png"))) {
205
-			$path =  \OC::$WEBROOT . "/themes/$theme/$app/img/$basename.png";
206
-		} elseif (file_exists(\OC::$SERVERROOT . "/themes/$theme/core/img/$image")) {
207
-			$path =  \OC::$WEBROOT . "/themes/$theme/core/img/$image";
208
-		} elseif (!file_exists(\OC::$SERVERROOT . "/themes/$theme/core/img/$basename.svg")
209
-			&& file_exists(\OC::$SERVERROOT . "/themes/$theme/core/img/$basename.png")) {
210
-			$path =  \OC::$WEBROOT . "/themes/$theme/core/img/$basename.png";
211
-		} elseif($themingEnabled && $themingImagePath) {
212
-			$path = $themingImagePath;
213
-		} elseif ($appPath && file_exists($appPath . "/img/$image")) {
214
-			$path =  \OC_App::getAppWebPath($app) . "/img/$image";
215
-		} elseif ($appPath && !file_exists($appPath . "/img/$basename.svg")
216
-			&& file_exists($appPath . "/img/$basename.png")) {
217
-			$path =  \OC_App::getAppWebPath($app) . "/img/$basename.png";
218
-		} elseif (!empty($app) and file_exists(\OC::$SERVERROOT . "/$app/img/$image")) {
219
-			$path =  \OC::$WEBROOT . "/$app/img/$image";
220
-		} elseif (!empty($app) and (!file_exists(\OC::$SERVERROOT . "/$app/img/$basename.svg")
221
-				&& file_exists(\OC::$SERVERROOT . "/$app/img/$basename.png"))) {
222
-			$path =  \OC::$WEBROOT . "/$app/img/$basename.png";
223
-		} elseif (file_exists(\OC::$SERVERROOT . "/core/img/$image")) {
224
-			$path =  \OC::$WEBROOT . "/core/img/$image";
225
-		} elseif (!file_exists(\OC::$SERVERROOT . "/core/img/$basename.svg")
226
-			&& file_exists(\OC::$SERVERROOT . "/core/img/$basename.png")) {
227
-			$path =  \OC::$WEBROOT . "/themes/$theme/core/img/$basename.png";
228
-		}
196
+        if (file_exists(\OC::$SERVERROOT . "/themes/$theme/apps/$app/img/$image")) {
197
+            $path = \OC::$WEBROOT . "/themes/$theme/apps/$app/img/$image";
198
+        } elseif (!file_exists(\OC::$SERVERROOT . "/themes/$theme/apps/$app/img/$basename.svg")
199
+            && file_exists(\OC::$SERVERROOT . "/themes/$theme/apps/$app/img/$basename.png")) {
200
+            $path =  \OC::$WEBROOT . "/themes/$theme/apps/$app/img/$basename.png";
201
+        } elseif (!empty($app) and file_exists(\OC::$SERVERROOT . "/themes/$theme/$app/img/$image")) {
202
+            $path =  \OC::$WEBROOT . "/themes/$theme/$app/img/$image";
203
+        } elseif (!empty($app) and (!file_exists(\OC::$SERVERROOT . "/themes/$theme/$app/img/$basename.svg")
204
+            && file_exists(\OC::$SERVERROOT . "/themes/$theme/$app/img/$basename.png"))) {
205
+            $path =  \OC::$WEBROOT . "/themes/$theme/$app/img/$basename.png";
206
+        } elseif (file_exists(\OC::$SERVERROOT . "/themes/$theme/core/img/$image")) {
207
+            $path =  \OC::$WEBROOT . "/themes/$theme/core/img/$image";
208
+        } elseif (!file_exists(\OC::$SERVERROOT . "/themes/$theme/core/img/$basename.svg")
209
+            && file_exists(\OC::$SERVERROOT . "/themes/$theme/core/img/$basename.png")) {
210
+            $path =  \OC::$WEBROOT . "/themes/$theme/core/img/$basename.png";
211
+        } elseif($themingEnabled && $themingImagePath) {
212
+            $path = $themingImagePath;
213
+        } elseif ($appPath && file_exists($appPath . "/img/$image")) {
214
+            $path =  \OC_App::getAppWebPath($app) . "/img/$image";
215
+        } elseif ($appPath && !file_exists($appPath . "/img/$basename.svg")
216
+            && file_exists($appPath . "/img/$basename.png")) {
217
+            $path =  \OC_App::getAppWebPath($app) . "/img/$basename.png";
218
+        } elseif (!empty($app) and file_exists(\OC::$SERVERROOT . "/$app/img/$image")) {
219
+            $path =  \OC::$WEBROOT . "/$app/img/$image";
220
+        } elseif (!empty($app) and (!file_exists(\OC::$SERVERROOT . "/$app/img/$basename.svg")
221
+                && file_exists(\OC::$SERVERROOT . "/$app/img/$basename.png"))) {
222
+            $path =  \OC::$WEBROOT . "/$app/img/$basename.png";
223
+        } elseif (file_exists(\OC::$SERVERROOT . "/core/img/$image")) {
224
+            $path =  \OC::$WEBROOT . "/core/img/$image";
225
+        } elseif (!file_exists(\OC::$SERVERROOT . "/core/img/$basename.svg")
226
+            && file_exists(\OC::$SERVERROOT . "/core/img/$basename.png")) {
227
+            $path =  \OC::$WEBROOT . "/themes/$theme/core/img/$basename.png";
228
+        }
229 229
 
230
-		if($path !== '') {
231
-			$cache->set($cacheKey, $path);
232
-			return $path;
233
-		}
230
+        if($path !== '') {
231
+            $cache->set($cacheKey, $path);
232
+            return $path;
233
+        }
234 234
 
235
-		throw new RuntimeException('image not found: image:' . $image . ' webroot:' . \OC::$WEBROOT . ' serverroot:' . \OC::$SERVERROOT);
236
-	}
235
+        throw new RuntimeException('image not found: image:' . $image . ' webroot:' . \OC::$WEBROOT . ' serverroot:' . \OC::$SERVERROOT);
236
+    }
237 237
 
238 238
 
239
-	/**
240
-	 * Makes an URL absolute
241
-	 * @param string $url the url in the ownCloud host
242
-	 * @return string the absolute version of the url
243
-	 */
244
-	public function getAbsoluteURL(string $url): string {
245
-		$separator = strpos($url, '/') === 0 ? '' : '/';
239
+    /**
240
+     * Makes an URL absolute
241
+     * @param string $url the url in the ownCloud host
242
+     * @return string the absolute version of the url
243
+     */
244
+    public function getAbsoluteURL(string $url): string {
245
+        $separator = strpos($url, '/') === 0 ? '' : '/';
246 246
 
247
-		if (\OC::$CLI && !\defined('PHPUNIT_RUN')) {
248
-			return rtrim($this->config->getSystemValue('overwrite.cli.url'), '/') . '/' . ltrim($url, '/');
249
-		}
250
-		// The ownCloud web root can already be prepended.
251
-		if(\OC::$WEBROOT !== '' && strpos($url, \OC::$WEBROOT) === 0) {
252
-			$url = substr($url, \strlen(\OC::$WEBROOT));
253
-		}
247
+        if (\OC::$CLI && !\defined('PHPUNIT_RUN')) {
248
+            return rtrim($this->config->getSystemValue('overwrite.cli.url'), '/') . '/' . ltrim($url, '/');
249
+        }
250
+        // The ownCloud web root can already be prepended.
251
+        if(\OC::$WEBROOT !== '' && strpos($url, \OC::$WEBROOT) === 0) {
252
+            $url = substr($url, \strlen(\OC::$WEBROOT));
253
+        }
254 254
 
255
-		return $this->getBaseUrl() . $separator . $url;
256
-	}
255
+        return $this->getBaseUrl() . $separator . $url;
256
+    }
257 257
 
258
-	/**
259
-	 * @param string $key
260
-	 * @return string url to the online documentation
261
-	 */
262
-	public function linkToDocs(string $key): string {
263
-		$theme = \OC::$server->getThemingDefaults();
264
-		return $theme->buildDocLinkToKey($key);
265
-	}
258
+    /**
259
+     * @param string $key
260
+     * @return string url to the online documentation
261
+     */
262
+    public function linkToDocs(string $key): string {
263
+        $theme = \OC::$server->getThemingDefaults();
264
+        return $theme->buildDocLinkToKey($key);
265
+    }
266 266
 
267
-	/**
268
-	 * @return string base url of the current request
269
-	 */
270
-	public function getBaseUrl(): string {
271
-		return $this->request->getServerProtocol() . '://' . $this->request->getServerHost() . \OC::$WEBROOT;
272
-	}
267
+    /**
268
+     * @return string base url of the current request
269
+     */
270
+    public function getBaseUrl(): string {
271
+        return $this->request->getServerProtocol() . '://' . $this->request->getServerHost() . \OC::$WEBROOT;
272
+    }
273 273
 }
Please login to merge, or discard this patch.
Spacing   +53 added lines, -53 removed lines patch added patch discarded remove patch
@@ -104,7 +104,7 @@  discard block
 block discarded – undo
104 104
 		}
105 105
 
106 106
 		$route = substr($route, 7);
107
-		$route = '/ocs/v2.php' . $route;
107
+		$route = '/ocs/v2.php'.$route;
108 108
 
109 109
 		return $this->getAbsoluteURL($route);
110 110
 	}
@@ -122,37 +122,37 @@  discard block
 block discarded – undo
122 122
 	public function linkTo(string $app, string $file, array $args = []): string {
123 123
 		$frontControllerActive = ($this->config->getSystemValue('htaccess.IgnoreFrontController', false) === true || getenv('front_controller_active') === 'true');
124 124
 
125
-		if($app !== '') {
125
+		if ($app !== '') {
126 126
 			$app_path = \OC_App::getAppPath($app);
127 127
 			// Check if the app is in the app folder
128
-			if ($app_path && file_exists($app_path . '/' . $file)) {
128
+			if ($app_path && file_exists($app_path.'/'.$file)) {
129 129
 				if (substr($file, -3) === 'php') {
130 130
 
131
-					$urlLinkTo = \OC::$WEBROOT . '/index.php/apps/' . $app;
131
+					$urlLinkTo = \OC::$WEBROOT.'/index.php/apps/'.$app;
132 132
 					if ($frontControllerActive) {
133
-						$urlLinkTo = \OC::$WEBROOT . '/apps/' . $app;
133
+						$urlLinkTo = \OC::$WEBROOT.'/apps/'.$app;
134 134
 					}
135
-					$urlLinkTo .= ($file !== 'index.php') ? '/' . $file : '';
135
+					$urlLinkTo .= ($file !== 'index.php') ? '/'.$file : '';
136 136
 				} else {
137
-					$urlLinkTo = \OC_App::getAppWebPath($app) . '/' . $file;
137
+					$urlLinkTo = \OC_App::getAppWebPath($app).'/'.$file;
138 138
 				}
139 139
 			} else {
140
-				$urlLinkTo = \OC::$WEBROOT . '/' . $app . '/' . $file;
140
+				$urlLinkTo = \OC::$WEBROOT.'/'.$app.'/'.$file;
141 141
 			}
142 142
 		} else {
143
-			if (file_exists(\OC::$SERVERROOT . '/core/' . $file)) {
144
-				$urlLinkTo = \OC::$WEBROOT . '/core/' . $file;
143
+			if (file_exists(\OC::$SERVERROOT.'/core/'.$file)) {
144
+				$urlLinkTo = \OC::$WEBROOT.'/core/'.$file;
145 145
 			} else {
146 146
 				if ($frontControllerActive && $file === 'index.php') {
147
-					$urlLinkTo = \OC::$WEBROOT . '/';
147
+					$urlLinkTo = \OC::$WEBROOT.'/';
148 148
 				} else {
149
-					$urlLinkTo = \OC::$WEBROOT . '/' . $file;
149
+					$urlLinkTo = \OC::$WEBROOT.'/'.$file;
150 150
 				}
151 151
 			}
152 152
 		}
153 153
 
154 154
 		if ($args && $query = http_build_query($args, '', '&')) {
155
-			$urlLinkTo .= '?' . $query;
155
+			$urlLinkTo .= '?'.$query;
156 156
 		}
157 157
 
158 158
 		return $urlLinkTo;
@@ -170,7 +170,7 @@  discard block
 block discarded – undo
170 170
 	public function imagePath(string $app, string $image): string {
171 171
 		$cache = $this->cacheFactory->createDistributed('imagePath-'.md5($this->getBaseUrl()).'-');
172 172
 		$cacheKey = $app.'-'.$image;
173
-		if($key = $cache->get($cacheKey)) {
173
+		if ($key = $cache->get($cacheKey)) {
174 174
 			return $key;
175 175
 		}
176 176
 
@@ -178,7 +178,7 @@  discard block
 block discarded – undo
178 178
 		$theme = \OC_Util::getTheme();
179 179
 
180 180
 		//if a theme has a png but not an svg always use the png
181
-		$basename = substr(basename($image),0,-4);
181
+		$basename = substr(basename($image), 0, -4);
182 182
 
183 183
 		$appPath = \OC_App::getAppPath($app);
184 184
 
@@ -186,53 +186,53 @@  discard block
 block discarded – undo
186 186
 		$path = '';
187 187
 		$themingEnabled = $this->config->getSystemValue('installed', false) && \OCP\App::isEnabled('theming') && \OC_App::isAppLoaded('theming');
188 188
 		$themingImagePath = false;
189
-		if($themingEnabled) {
189
+		if ($themingEnabled) {
190 190
 			$themingDefaults = \OC::$server->getThemingDefaults();
191 191
 			if ($themingDefaults instanceof ThemingDefaults) {
192 192
 				$themingImagePath = $themingDefaults->replaceImagePath($app, $image);
193 193
 			}
194 194
 		}
195 195
 
196
-		if (file_exists(\OC::$SERVERROOT . "/themes/$theme/apps/$app/img/$image")) {
197
-			$path = \OC::$WEBROOT . "/themes/$theme/apps/$app/img/$image";
198
-		} elseif (!file_exists(\OC::$SERVERROOT . "/themes/$theme/apps/$app/img/$basename.svg")
199
-			&& file_exists(\OC::$SERVERROOT . "/themes/$theme/apps/$app/img/$basename.png")) {
200
-			$path =  \OC::$WEBROOT . "/themes/$theme/apps/$app/img/$basename.png";
201
-		} elseif (!empty($app) and file_exists(\OC::$SERVERROOT . "/themes/$theme/$app/img/$image")) {
202
-			$path =  \OC::$WEBROOT . "/themes/$theme/$app/img/$image";
203
-		} elseif (!empty($app) and (!file_exists(\OC::$SERVERROOT . "/themes/$theme/$app/img/$basename.svg")
204
-			&& file_exists(\OC::$SERVERROOT . "/themes/$theme/$app/img/$basename.png"))) {
205
-			$path =  \OC::$WEBROOT . "/themes/$theme/$app/img/$basename.png";
206
-		} elseif (file_exists(\OC::$SERVERROOT . "/themes/$theme/core/img/$image")) {
207
-			$path =  \OC::$WEBROOT . "/themes/$theme/core/img/$image";
208
-		} elseif (!file_exists(\OC::$SERVERROOT . "/themes/$theme/core/img/$basename.svg")
209
-			&& file_exists(\OC::$SERVERROOT . "/themes/$theme/core/img/$basename.png")) {
210
-			$path =  \OC::$WEBROOT . "/themes/$theme/core/img/$basename.png";
211
-		} elseif($themingEnabled && $themingImagePath) {
196
+		if (file_exists(\OC::$SERVERROOT."/themes/$theme/apps/$app/img/$image")) {
197
+			$path = \OC::$WEBROOT."/themes/$theme/apps/$app/img/$image";
198
+		} elseif (!file_exists(\OC::$SERVERROOT."/themes/$theme/apps/$app/img/$basename.svg")
199
+			&& file_exists(\OC::$SERVERROOT."/themes/$theme/apps/$app/img/$basename.png")) {
200
+			$path = \OC::$WEBROOT."/themes/$theme/apps/$app/img/$basename.png";
201
+		} elseif (!empty($app) and file_exists(\OC::$SERVERROOT."/themes/$theme/$app/img/$image")) {
202
+			$path = \OC::$WEBROOT."/themes/$theme/$app/img/$image";
203
+		} elseif (!empty($app) and (!file_exists(\OC::$SERVERROOT."/themes/$theme/$app/img/$basename.svg")
204
+			&& file_exists(\OC::$SERVERROOT."/themes/$theme/$app/img/$basename.png"))) {
205
+			$path = \OC::$WEBROOT."/themes/$theme/$app/img/$basename.png";
206
+		} elseif (file_exists(\OC::$SERVERROOT."/themes/$theme/core/img/$image")) {
207
+			$path = \OC::$WEBROOT."/themes/$theme/core/img/$image";
208
+		} elseif (!file_exists(\OC::$SERVERROOT."/themes/$theme/core/img/$basename.svg")
209
+			&& file_exists(\OC::$SERVERROOT."/themes/$theme/core/img/$basename.png")) {
210
+			$path = \OC::$WEBROOT."/themes/$theme/core/img/$basename.png";
211
+		} elseif ($themingEnabled && $themingImagePath) {
212 212
 			$path = $themingImagePath;
213
-		} elseif ($appPath && file_exists($appPath . "/img/$image")) {
214
-			$path =  \OC_App::getAppWebPath($app) . "/img/$image";
215
-		} elseif ($appPath && !file_exists($appPath . "/img/$basename.svg")
216
-			&& file_exists($appPath . "/img/$basename.png")) {
217
-			$path =  \OC_App::getAppWebPath($app) . "/img/$basename.png";
218
-		} elseif (!empty($app) and file_exists(\OC::$SERVERROOT . "/$app/img/$image")) {
219
-			$path =  \OC::$WEBROOT . "/$app/img/$image";
220
-		} elseif (!empty($app) and (!file_exists(\OC::$SERVERROOT . "/$app/img/$basename.svg")
221
-				&& file_exists(\OC::$SERVERROOT . "/$app/img/$basename.png"))) {
222
-			$path =  \OC::$WEBROOT . "/$app/img/$basename.png";
223
-		} elseif (file_exists(\OC::$SERVERROOT . "/core/img/$image")) {
224
-			$path =  \OC::$WEBROOT . "/core/img/$image";
225
-		} elseif (!file_exists(\OC::$SERVERROOT . "/core/img/$basename.svg")
226
-			&& file_exists(\OC::$SERVERROOT . "/core/img/$basename.png")) {
227
-			$path =  \OC::$WEBROOT . "/themes/$theme/core/img/$basename.png";
213
+		} elseif ($appPath && file_exists($appPath."/img/$image")) {
214
+			$path = \OC_App::getAppWebPath($app)."/img/$image";
215
+		} elseif ($appPath && !file_exists($appPath."/img/$basename.svg")
216
+			&& file_exists($appPath."/img/$basename.png")) {
217
+			$path = \OC_App::getAppWebPath($app)."/img/$basename.png";
218
+		} elseif (!empty($app) and file_exists(\OC::$SERVERROOT."/$app/img/$image")) {
219
+			$path = \OC::$WEBROOT."/$app/img/$image";
220
+		} elseif (!empty($app) and (!file_exists(\OC::$SERVERROOT."/$app/img/$basename.svg")
221
+				&& file_exists(\OC::$SERVERROOT."/$app/img/$basename.png"))) {
222
+			$path = \OC::$WEBROOT."/$app/img/$basename.png";
223
+		} elseif (file_exists(\OC::$SERVERROOT."/core/img/$image")) {
224
+			$path = \OC::$WEBROOT."/core/img/$image";
225
+		} elseif (!file_exists(\OC::$SERVERROOT."/core/img/$basename.svg")
226
+			&& file_exists(\OC::$SERVERROOT."/core/img/$basename.png")) {
227
+			$path = \OC::$WEBROOT."/themes/$theme/core/img/$basename.png";
228 228
 		}
229 229
 
230
-		if($path !== '') {
230
+		if ($path !== '') {
231 231
 			$cache->set($cacheKey, $path);
232 232
 			return $path;
233 233
 		}
234 234
 
235
-		throw new RuntimeException('image not found: image:' . $image . ' webroot:' . \OC::$WEBROOT . ' serverroot:' . \OC::$SERVERROOT);
235
+		throw new RuntimeException('image not found: image:'.$image.' webroot:'.\OC::$WEBROOT.' serverroot:'.\OC::$SERVERROOT);
236 236
 	}
237 237
 
238 238
 
@@ -245,14 +245,14 @@  discard block
 block discarded – undo
245 245
 		$separator = strpos($url, '/') === 0 ? '' : '/';
246 246
 
247 247
 		if (\OC::$CLI && !\defined('PHPUNIT_RUN')) {
248
-			return rtrim($this->config->getSystemValue('overwrite.cli.url'), '/') . '/' . ltrim($url, '/');
248
+			return rtrim($this->config->getSystemValue('overwrite.cli.url'), '/').'/'.ltrim($url, '/');
249 249
 		}
250 250
 		// The ownCloud web root can already be prepended.
251
-		if(\OC::$WEBROOT !== '' && strpos($url, \OC::$WEBROOT) === 0) {
251
+		if (\OC::$WEBROOT !== '' && strpos($url, \OC::$WEBROOT) === 0) {
252 252
 			$url = substr($url, \strlen(\OC::$WEBROOT));
253 253
 		}
254 254
 
255
-		return $this->getBaseUrl() . $separator . $url;
255
+		return $this->getBaseUrl().$separator.$url;
256 256
 	}
257 257
 
258 258
 	/**
@@ -268,6 +268,6 @@  discard block
 block discarded – undo
268 268
 	 * @return string base url of the current request
269 269
 	 */
270 270
 	public function getBaseUrl(): string {
271
-		return $this->request->getServerProtocol() . '://' . $this->request->getServerHost() . \OC::$WEBROOT;
271
+		return $this->request->getServerProtocol().'://'.$this->request->getServerHost().\OC::$WEBROOT;
272 272
 	}
273 273
 }
Please login to merge, or discard this patch.
lib/private/Search.php 2 patches
Indentation   +76 added lines, -76 removed lines patch added patch discarded remove patch
@@ -37,86 +37,86 @@
 block discarded – undo
37 37
  */
38 38
 class Search implements ISearch {
39 39
 
40
-	private $providers = [];
41
-	private $registeredProviders = [];
40
+    private $providers = [];
41
+    private $registeredProviders = [];
42 42
 
43
-	/**
44
-	 * Search all providers for $query
45
-	 * @param string $query
46
-	 * @param string[] $inApps optionally limit results to the given apps
47
-	 * @param int $page pages start at page 1
48
-	 * @param int $size, 0 = all
49
-	 * @return array An array of OC\Search\Result's
50
-	 */
51
-	public function searchPaged($query, array $inApps = [], $page = 1, $size = 30) {
52
-		$this->initProviders();
53
-		$results = [];
54
-		foreach($this->providers as $provider) {
55
-			/** @var $provider Provider */
56
-			if (! $provider->providesResultsFor($inApps)) {
57
-				continue;
58
-			}
59
-			if ($provider instanceof PagedProvider) {
60
-				$results = array_merge($results, $provider->searchPaged($query, $page, $size));
61
-			} else if ($provider instanceof Provider) {
62
-				$providerResults = $provider->search($query);
63
-				if ($size > 0) {
64
-					$slicedResults = array_slice($providerResults, ($page - 1) * $size, $size);
65
-					$results = array_merge($results, $slicedResults);
66
-				} else {
67
-					$results = array_merge($results, $providerResults);
68
-				}
69
-			} else {
70
-				\OC::$server->getLogger()->warning('Ignoring Unknown search provider', ['provider' => $provider]);
71
-			}
72
-		}
73
-		return $results;
74
-	}
43
+    /**
44
+     * Search all providers for $query
45
+     * @param string $query
46
+     * @param string[] $inApps optionally limit results to the given apps
47
+     * @param int $page pages start at page 1
48
+     * @param int $size, 0 = all
49
+     * @return array An array of OC\Search\Result's
50
+     */
51
+    public function searchPaged($query, array $inApps = [], $page = 1, $size = 30) {
52
+        $this->initProviders();
53
+        $results = [];
54
+        foreach($this->providers as $provider) {
55
+            /** @var $provider Provider */
56
+            if (! $provider->providesResultsFor($inApps)) {
57
+                continue;
58
+            }
59
+            if ($provider instanceof PagedProvider) {
60
+                $results = array_merge($results, $provider->searchPaged($query, $page, $size));
61
+            } else if ($provider instanceof Provider) {
62
+                $providerResults = $provider->search($query);
63
+                if ($size > 0) {
64
+                    $slicedResults = array_slice($providerResults, ($page - 1) * $size, $size);
65
+                    $results = array_merge($results, $slicedResults);
66
+                } else {
67
+                    $results = array_merge($results, $providerResults);
68
+                }
69
+            } else {
70
+                \OC::$server->getLogger()->warning('Ignoring Unknown search provider', ['provider' => $provider]);
71
+            }
72
+        }
73
+        return $results;
74
+    }
75 75
 
76
-	/**
77
-	 * Remove all registered search providers
78
-	 */
79
-	public function clearProviders() {
80
-		$this->providers = [];
81
-		$this->registeredProviders = [];
82
-	}
76
+    /**
77
+     * Remove all registered search providers
78
+     */
79
+    public function clearProviders() {
80
+        $this->providers = [];
81
+        $this->registeredProviders = [];
82
+    }
83 83
 
84
-	/**
85
-	 * Remove one existing search provider
86
-	 * @param string $provider class name of a OC\Search\Provider
87
-	 */
88
-	public function removeProvider($provider) {
89
-		$this->registeredProviders = array_filter(
90
-			$this->registeredProviders,
91
-			function ($element) use ($provider) {
92
-				return ($element['class'] != $provider);
93
-			}
94
-		);
95
-		// force regeneration of providers on next search
96
-		$this->providers = [];
97
-	}
84
+    /**
85
+     * Remove one existing search provider
86
+     * @param string $provider class name of a OC\Search\Provider
87
+     */
88
+    public function removeProvider($provider) {
89
+        $this->registeredProviders = array_filter(
90
+            $this->registeredProviders,
91
+            function ($element) use ($provider) {
92
+                return ($element['class'] != $provider);
93
+            }
94
+        );
95
+        // force regeneration of providers on next search
96
+        $this->providers = [];
97
+    }
98 98
 
99
-	/**
100
-	 * Register a new search provider to search with
101
-	 * @param string $class class name of a OC\Search\Provider
102
-	 * @param array $options optional
103
-	 */
104
-	public function registerProvider($class, array $options = []) {
105
-		$this->registeredProviders[] = ['class' => $class, 'options' => $options];
106
-	}
99
+    /**
100
+     * Register a new search provider to search with
101
+     * @param string $class class name of a OC\Search\Provider
102
+     * @param array $options optional
103
+     */
104
+    public function registerProvider($class, array $options = []) {
105
+        $this->registeredProviders[] = ['class' => $class, 'options' => $options];
106
+    }
107 107
 
108
-	/**
109
-	 * Create instances of all the registered search providers
110
-	 */
111
-	private function initProviders() {
112
-		if(! empty($this->providers)) {
113
-			return;
114
-		}
115
-		foreach($this->registeredProviders as $provider) {
116
-			$class = $provider['class'];
117
-			$options = $provider['options'];
118
-			$this->providers[] = new $class($options);
119
-		}
120
-	}
108
+    /**
109
+     * Create instances of all the registered search providers
110
+     */
111
+    private function initProviders() {
112
+        if(! empty($this->providers)) {
113
+            return;
114
+        }
115
+        foreach($this->registeredProviders as $provider) {
116
+            $class = $provider['class'];
117
+            $options = $provider['options'];
118
+            $this->providers[] = new $class($options);
119
+        }
120
+    }
121 121
 
122 122
 }
Please login to merge, or discard this patch.
Spacing   +5 added lines, -5 removed lines patch added patch discarded remove patch
@@ -51,9 +51,9 @@  discard block
 block discarded – undo
51 51
 	public function searchPaged($query, array $inApps = [], $page = 1, $size = 30) {
52 52
 		$this->initProviders();
53 53
 		$results = [];
54
-		foreach($this->providers as $provider) {
54
+		foreach ($this->providers as $provider) {
55 55
 			/** @var $provider Provider */
56
-			if (! $provider->providesResultsFor($inApps)) {
56
+			if (!$provider->providesResultsFor($inApps)) {
57 57
 				continue;
58 58
 			}
59 59
 			if ($provider instanceof PagedProvider) {
@@ -88,7 +88,7 @@  discard block
 block discarded – undo
88 88
 	public function removeProvider($provider) {
89 89
 		$this->registeredProviders = array_filter(
90 90
 			$this->registeredProviders,
91
-			function ($element) use ($provider) {
91
+			function($element) use ($provider) {
92 92
 				return ($element['class'] != $provider);
93 93
 			}
94 94
 		);
@@ -109,10 +109,10 @@  discard block
 block discarded – undo
109 109
 	 * Create instances of all the registered search providers
110 110
 	 */
111 111
 	private function initProviders() {
112
-		if(! empty($this->providers)) {
112
+		if (!empty($this->providers)) {
113 113
 			return;
114 114
 		}
115
-		foreach($this->registeredProviders as $provider) {
115
+		foreach ($this->registeredProviders as $provider) {
116 116
 			$class = $provider['class'];
117 117
 			$options = $provider['options'];
118 118
 			$this->providers[] = new $class($options);
Please login to merge, or discard this patch.
lib/private/Group/Database.php 2 patches
Indentation   +412 added lines, -412 removed lines patch added patch discarded remove patch
@@ -61,417 +61,417 @@
 block discarded – undo
61 61
  * Class for group management in a SQL Database (e.g. MySQL, SQLite)
62 62
  */
63 63
 class Database extends ABackend
64
-	implements IAddToGroupBackend,
65
-			   ICountDisabledInGroup,
66
-			   ICountUsersBackend,
67
-			   ICreateGroupBackend,
68
-			   IDeleteGroupBackend,
69
-			   IGetDisplayNameBackend,
70
-			   IGroupDetailsBackend,
71
-			   IRemoveFromGroupBackend,
72
-			   ISetDisplayNameBackend {
73
-
74
-	/** @var string[] */
75
-	private $groupCache = [];
76
-
77
-	/** @var IDBConnection */
78
-	private $dbConn;
79
-
80
-	/**
81
-	 * \OC\Group\Database constructor.
82
-	 *
83
-	 * @param IDBConnection|null $dbConn
84
-	 */
85
-	public function __construct(IDBConnection $dbConn = null) {
86
-		$this->dbConn = $dbConn;
87
-	}
88
-
89
-	/**
90
-	 * FIXME: This function should not be required!
91
-	 */
92
-	private function fixDI() {
93
-		if ($this->dbConn === null) {
94
-			$this->dbConn = \OC::$server->getDatabaseConnection();
95
-		}
96
-	}
97
-
98
-	/**
99
-	 * Try to create a new group
100
-	 * @param string $gid The name of the group to create
101
-	 * @return bool
102
-	 *
103
-	 * Tries to create a new group. If the group name already exists, false will
104
-	 * be returned.
105
-	 */
106
-	public function createGroup(string $gid): bool {
107
-		$this->fixDI();
108
-
109
-		try {
110
-			// Add group
111
-			$builder = $this->dbConn->getQueryBuilder();
112
-			$result = $builder->insert('groups')
113
-				->setValue('gid', $builder->createNamedParameter($gid))
114
-				->setValue('displayname', $builder->createNamedParameter($gid))
115
-				->execute();
116
-		} catch(UniqueConstraintViolationException $e) {
117
-			$result = 0;
118
-		}
119
-
120
-		// Add to cache
121
-		$this->groupCache[$gid] = $gid;
122
-
123
-		return $result === 1;
124
-	}
125
-
126
-	/**
127
-	 * delete a group
128
-	 * @param string $gid gid of the group to delete
129
-	 * @return bool
130
-	 *
131
-	 * Deletes a group and removes it from the group_user-table
132
-	 */
133
-	public function deleteGroup(string $gid): bool {
134
-		$this->fixDI();
135
-
136
-		// Delete the group
137
-		$qb = $this->dbConn->getQueryBuilder();
138
-		$qb->delete('groups')
139
-			->where($qb->expr()->eq('gid', $qb->createNamedParameter($gid)))
140
-			->execute();
141
-
142
-		// Delete the group-user relation
143
-		$qb = $this->dbConn->getQueryBuilder();
144
-		$qb->delete('group_user')
145
-			->where($qb->expr()->eq('gid', $qb->createNamedParameter($gid)))
146
-			->execute();
147
-
148
-		// Delete the group-groupadmin relation
149
-		$qb = $this->dbConn->getQueryBuilder();
150
-		$qb->delete('group_admin')
151
-			->where($qb->expr()->eq('gid', $qb->createNamedParameter($gid)))
152
-			->execute();
153
-
154
-		// Delete from cache
155
-		unset($this->groupCache[$gid]);
156
-
157
-		return true;
158
-	}
159
-
160
-	/**
161
-	 * is user in group?
162
-	 * @param string $uid uid of the user
163
-	 * @param string $gid gid of the group
164
-	 * @return bool
165
-	 *
166
-	 * Checks whether the user is member of a group or not.
167
-	 */
168
-	public function inGroup($uid, $gid) {
169
-		$this->fixDI();
170
-
171
-		// check
172
-		$qb = $this->dbConn->getQueryBuilder();
173
-		$cursor = $qb->select('uid')
174
-			->from('group_user')
175
-			->where($qb->expr()->eq('gid', $qb->createNamedParameter($gid)))
176
-			->andWhere($qb->expr()->eq('uid', $qb->createNamedParameter($uid)))
177
-			->execute();
178
-
179
-		$result = $cursor->fetch();
180
-		$cursor->closeCursor();
181
-
182
-		return $result ? true : false;
183
-	}
184
-
185
-	/**
186
-	 * Add a user to a group
187
-	 * @param string $uid Name of the user to add to group
188
-	 * @param string $gid Name of the group in which add the user
189
-	 * @return bool
190
-	 *
191
-	 * Adds a user to a group.
192
-	 */
193
-	public function addToGroup(string $uid, string $gid): bool {
194
-		$this->fixDI();
195
-
196
-		// No duplicate entries!
197
-		if(!$this->inGroup($uid, $gid)) {
198
-			$qb = $this->dbConn->getQueryBuilder();
199
-			$qb->insert('group_user')
200
-				->setValue('uid', $qb->createNamedParameter($uid))
201
-				->setValue('gid', $qb->createNamedParameter($gid))
202
-				->execute();
203
-			return true;
204
-		}else{
205
-			return false;
206
-		}
207
-	}
208
-
209
-	/**
210
-	 * Removes a user from a group
211
-	 * @param string $uid Name of the user to remove from group
212
-	 * @param string $gid Name of the group from which remove the user
213
-	 * @return bool
214
-	 *
215
-	 * removes the user from a group.
216
-	 */
217
-	public function removeFromGroup(string $uid, string $gid): bool {
218
-		$this->fixDI();
219
-
220
-		$qb = $this->dbConn->getQueryBuilder();
221
-		$qb->delete('group_user')
222
-			->where($qb->expr()->eq('uid', $qb->createNamedParameter($uid)))
223
-			->andWhere($qb->expr()->eq('gid', $qb->createNamedParameter($gid)))
224
-			->execute();
225
-
226
-		return true;
227
-	}
228
-
229
-	/**
230
-	 * Get all groups a user belongs to
231
-	 * @param string $uid Name of the user
232
-	 * @return array an array of group names
233
-	 *
234
-	 * This function fetches all groups a user belongs to. It does not check
235
-	 * if the user exists at all.
236
-	 */
237
-	public function getUserGroups($uid) {
238
-		//guests has empty or null $uid
239
-		if ($uid === null || $uid === '') {
240
-			return [];
241
-		}
242
-
243
-		$this->fixDI();
244
-
245
-		// No magic!
246
-		$qb = $this->dbConn->getQueryBuilder();
247
-		$cursor = $qb->select('gid')
248
-			->from('group_user')
249
-			->where($qb->expr()->eq('uid', $qb->createNamedParameter($uid)))
250
-			->execute();
251
-
252
-		$groups = [];
253
-		while($row = $cursor->fetch()) {
254
-			$groups[] = $row['gid'];
255
-			$this->groupCache[$row['gid']] = $row['gid'];
256
-		}
257
-		$cursor->closeCursor();
258
-
259
-		return $groups;
260
-	}
261
-
262
-	/**
263
-	 * get a list of all groups
264
-	 * @param string $search
265
-	 * @param int $limit
266
-	 * @param int $offset
267
-	 * @return array an array of group names
268
-	 *
269
-	 * Returns a list with all groups
270
-	 */
271
-	public function getGroups($search = '', $limit = null, $offset = null) {
272
-		$this->fixDI();
273
-
274
-		$query = $this->dbConn->getQueryBuilder();
275
-		$query->select('gid')
276
-			->from('groups')
277
-			->orderBy('gid', 'ASC');
278
-
279
-		if ($search !== '') {
280
-			$query->where($query->expr()->iLike('gid', $query->createNamedParameter(
281
-				'%' . $this->dbConn->escapeLikeParameter($search) . '%'
282
-			)));
283
-		}
284
-
285
-		$query->setMaxResults($limit)
286
-			->setFirstResult($offset);
287
-		$result = $query->execute();
288
-
289
-		$groups = [];
290
-		while ($row = $result->fetch()) {
291
-			$groups[] = $row['gid'];
292
-		}
293
-		$result->closeCursor();
294
-
295
-		return $groups;
296
-	}
297
-
298
-	/**
299
-	 * check if a group exists
300
-	 * @param string $gid
301
-	 * @return bool
302
-	 */
303
-	public function groupExists($gid) {
304
-		$this->fixDI();
305
-
306
-		// Check cache first
307
-		if (isset($this->groupCache[$gid])) {
308
-			return true;
309
-		}
310
-
311
-		$qb = $this->dbConn->getQueryBuilder();
312
-		$cursor = $qb->select('gid')
313
-			->from('groups')
314
-			->where($qb->expr()->eq('gid', $qb->createNamedParameter($gid)))
315
-			->execute();
316
-		$result = $cursor->fetch();
317
-		$cursor->closeCursor();
318
-
319
-		if ($result !== false) {
320
-			$this->groupCache[$gid] = $gid;
321
-			return true;
322
-		}
323
-		return false;
324
-	}
325
-
326
-	/**
327
-	 * get a list of all users in a group
328
-	 * @param string $gid
329
-	 * @param string $search
330
-	 * @param int $limit
331
-	 * @param int $offset
332
-	 * @return array an array of user ids
333
-	 */
334
-	public function usersInGroup($gid, $search = '', $limit = -1, $offset = 0) {
335
-		$this->fixDI();
336
-
337
-		$query = $this->dbConn->getQueryBuilder();
338
-		$query->select('uid')
339
-			->from('group_user')
340
-			->where($query->expr()->eq('gid', $query->createNamedParameter($gid)))
341
-			->orderBy('uid', 'ASC');
342
-
343
-		if ($search !== '') {
344
-			$query->andWhere($query->expr()->like('uid', $query->createNamedParameter(
345
-				'%' . $this->dbConn->escapeLikeParameter($search) . '%'
346
-			)));
347
-		}
348
-
349
-		if ($limit !== -1) {
350
-			$query->setMaxResults($limit);
351
-		}
352
-		if ($offset !== 0) {
353
-			$query->setFirstResult($offset);
354
-		}
355
-
356
-		$result = $query->execute();
357
-
358
-		$users = [];
359
-		while ($row = $result->fetch()) {
360
-			$users[] = $row['uid'];
361
-		}
362
-		$result->closeCursor();
363
-
364
-		return $users;
365
-	}
366
-
367
-	/**
368
-	 * get the number of all users matching the search string in a group
369
-	 * @param string $gid
370
-	 * @param string $search
371
-	 * @return int
372
-	 */
373
-	public function countUsersInGroup(string $gid, string $search = ''): int {
374
-		$this->fixDI();
375
-
376
-		$query = $this->dbConn->getQueryBuilder();
377
-		$query->select($query->func()->count('*', 'num_users'))
378
-			->from('group_user')
379
-			->where($query->expr()->eq('gid', $query->createNamedParameter($gid)));
380
-
381
-		if ($search !== '') {
382
-			$query->andWhere($query->expr()->like('uid', $query->createNamedParameter(
383
-				'%' . $this->dbConn->escapeLikeParameter($search) . '%'
384
-			)));
385
-		}
386
-
387
-		$result = $query->execute();
388
-		$count = $result->fetchColumn();
389
-		$result->closeCursor();
390
-
391
-		if ($count !== false) {
392
-			$count = (int)$count;
393
-		} else {
394
-			$count = 0;
395
-		}
396
-
397
-		return $count;
398
-	}
399
-
400
-	/**
401
-	 * get the number of disabled users in a group
402
-	 *
403
-	 * @param string $search
404
-	 *
405
-	 * @return int
406
-	 */
407
-	public function countDisabledInGroup(string $gid): int {
408
-		$this->fixDI();
409
-
410
-		$query = $this->dbConn->getQueryBuilder();
411
-		$query->select($query->createFunction('COUNT(DISTINCT ' . $query->getColumnName('uid') . ')'))
412
-			->from('preferences', 'p')
413
-			->innerJoin('p', 'group_user', 'g', $query->expr()->eq('p.userid', 'g.uid'))
414
-			->where($query->expr()->eq('appid', $query->createNamedParameter('core')))
415
-			->andWhere($query->expr()->eq('configkey', $query->createNamedParameter('enabled')))
416
-			->andWhere($query->expr()->eq('configvalue', $query->createNamedParameter('false'), IQueryBuilder::PARAM_STR))
417
-			->andWhere($query->expr()->eq('gid', $query->createNamedParameter($gid), IQueryBuilder::PARAM_STR));
418
-
419
-		$result = $query->execute();
420
-		$count = $result->fetchColumn();
421
-		$result->closeCursor();
422
-
423
-		if ($count !== false) {
424
-			$count = (int)$count;
425
-		} else {
426
-			$count = 0;
427
-		}
428
-
429
-		return $count;
430
-	}
431
-
432
-	public function getDisplayName(string $gid): string {
433
-		$this->fixDI();
434
-
435
-		$query = $this->dbConn->getQueryBuilder();
436
-		$query->select('displayname')
437
-			->from('groups')
438
-			->where($query->expr()->eq('gid', $query->createNamedParameter($gid)));
439
-
440
-		$result = $query->execute();
441
-		$displayName = $result->fetchColumn();
442
-		$result->closeCursor();
443
-
444
-		return (string) $displayName;
445
-	}
446
-
447
-	public function getGroupDetails(string $gid): array {
448
-		$displayName = $this->getDisplayName($gid);
449
-		if ($displayName !== '') {
450
-			return ['displayName' => $displayName];
451
-		}
452
-
453
-		return [];
454
-	}
455
-
456
-	public function setDisplayName(string $gid, string $displayName): bool {
457
-		if (!$this->groupExists($gid)) {
458
-			return false;
459
-		}
460
-
461
-		$this->fixDI();
462
-
463
-		$displayName = trim($displayName);
464
-		if ($displayName === '') {
465
-			$displayName = $gid;
466
-		}
467
-
468
-		$query = $this->dbConn->getQueryBuilder();
469
-		$query->update('groups')
470
-			->set('displayname', $query->createNamedParameter($displayName))
471
-			->where($query->expr()->eq('gid', $query->createNamedParameter($gid)));
472
-		$query->execute();
473
-
474
-		return true;
475
-	}
64
+    implements IAddToGroupBackend,
65
+                ICountDisabledInGroup,
66
+                ICountUsersBackend,
67
+                ICreateGroupBackend,
68
+                IDeleteGroupBackend,
69
+                IGetDisplayNameBackend,
70
+                IGroupDetailsBackend,
71
+                IRemoveFromGroupBackend,
72
+                ISetDisplayNameBackend {
73
+
74
+    /** @var string[] */
75
+    private $groupCache = [];
76
+
77
+    /** @var IDBConnection */
78
+    private $dbConn;
79
+
80
+    /**
81
+     * \OC\Group\Database constructor.
82
+     *
83
+     * @param IDBConnection|null $dbConn
84
+     */
85
+    public function __construct(IDBConnection $dbConn = null) {
86
+        $this->dbConn = $dbConn;
87
+    }
88
+
89
+    /**
90
+     * FIXME: This function should not be required!
91
+     */
92
+    private function fixDI() {
93
+        if ($this->dbConn === null) {
94
+            $this->dbConn = \OC::$server->getDatabaseConnection();
95
+        }
96
+    }
97
+
98
+    /**
99
+     * Try to create a new group
100
+     * @param string $gid The name of the group to create
101
+     * @return bool
102
+     *
103
+     * Tries to create a new group. If the group name already exists, false will
104
+     * be returned.
105
+     */
106
+    public function createGroup(string $gid): bool {
107
+        $this->fixDI();
108
+
109
+        try {
110
+            // Add group
111
+            $builder = $this->dbConn->getQueryBuilder();
112
+            $result = $builder->insert('groups')
113
+                ->setValue('gid', $builder->createNamedParameter($gid))
114
+                ->setValue('displayname', $builder->createNamedParameter($gid))
115
+                ->execute();
116
+        } catch(UniqueConstraintViolationException $e) {
117
+            $result = 0;
118
+        }
119
+
120
+        // Add to cache
121
+        $this->groupCache[$gid] = $gid;
122
+
123
+        return $result === 1;
124
+    }
125
+
126
+    /**
127
+     * delete a group
128
+     * @param string $gid gid of the group to delete
129
+     * @return bool
130
+     *
131
+     * Deletes a group and removes it from the group_user-table
132
+     */
133
+    public function deleteGroup(string $gid): bool {
134
+        $this->fixDI();
135
+
136
+        // Delete the group
137
+        $qb = $this->dbConn->getQueryBuilder();
138
+        $qb->delete('groups')
139
+            ->where($qb->expr()->eq('gid', $qb->createNamedParameter($gid)))
140
+            ->execute();
141
+
142
+        // Delete the group-user relation
143
+        $qb = $this->dbConn->getQueryBuilder();
144
+        $qb->delete('group_user')
145
+            ->where($qb->expr()->eq('gid', $qb->createNamedParameter($gid)))
146
+            ->execute();
147
+
148
+        // Delete the group-groupadmin relation
149
+        $qb = $this->dbConn->getQueryBuilder();
150
+        $qb->delete('group_admin')
151
+            ->where($qb->expr()->eq('gid', $qb->createNamedParameter($gid)))
152
+            ->execute();
153
+
154
+        // Delete from cache
155
+        unset($this->groupCache[$gid]);
156
+
157
+        return true;
158
+    }
159
+
160
+    /**
161
+     * is user in group?
162
+     * @param string $uid uid of the user
163
+     * @param string $gid gid of the group
164
+     * @return bool
165
+     *
166
+     * Checks whether the user is member of a group or not.
167
+     */
168
+    public function inGroup($uid, $gid) {
169
+        $this->fixDI();
170
+
171
+        // check
172
+        $qb = $this->dbConn->getQueryBuilder();
173
+        $cursor = $qb->select('uid')
174
+            ->from('group_user')
175
+            ->where($qb->expr()->eq('gid', $qb->createNamedParameter($gid)))
176
+            ->andWhere($qb->expr()->eq('uid', $qb->createNamedParameter($uid)))
177
+            ->execute();
178
+
179
+        $result = $cursor->fetch();
180
+        $cursor->closeCursor();
181
+
182
+        return $result ? true : false;
183
+    }
184
+
185
+    /**
186
+     * Add a user to a group
187
+     * @param string $uid Name of the user to add to group
188
+     * @param string $gid Name of the group in which add the user
189
+     * @return bool
190
+     *
191
+     * Adds a user to a group.
192
+     */
193
+    public function addToGroup(string $uid, string $gid): bool {
194
+        $this->fixDI();
195
+
196
+        // No duplicate entries!
197
+        if(!$this->inGroup($uid, $gid)) {
198
+            $qb = $this->dbConn->getQueryBuilder();
199
+            $qb->insert('group_user')
200
+                ->setValue('uid', $qb->createNamedParameter($uid))
201
+                ->setValue('gid', $qb->createNamedParameter($gid))
202
+                ->execute();
203
+            return true;
204
+        }else{
205
+            return false;
206
+        }
207
+    }
208
+
209
+    /**
210
+     * Removes a user from a group
211
+     * @param string $uid Name of the user to remove from group
212
+     * @param string $gid Name of the group from which remove the user
213
+     * @return bool
214
+     *
215
+     * removes the user from a group.
216
+     */
217
+    public function removeFromGroup(string $uid, string $gid): bool {
218
+        $this->fixDI();
219
+
220
+        $qb = $this->dbConn->getQueryBuilder();
221
+        $qb->delete('group_user')
222
+            ->where($qb->expr()->eq('uid', $qb->createNamedParameter($uid)))
223
+            ->andWhere($qb->expr()->eq('gid', $qb->createNamedParameter($gid)))
224
+            ->execute();
225
+
226
+        return true;
227
+    }
228
+
229
+    /**
230
+     * Get all groups a user belongs to
231
+     * @param string $uid Name of the user
232
+     * @return array an array of group names
233
+     *
234
+     * This function fetches all groups a user belongs to. It does not check
235
+     * if the user exists at all.
236
+     */
237
+    public function getUserGroups($uid) {
238
+        //guests has empty or null $uid
239
+        if ($uid === null || $uid === '') {
240
+            return [];
241
+        }
242
+
243
+        $this->fixDI();
244
+
245
+        // No magic!
246
+        $qb = $this->dbConn->getQueryBuilder();
247
+        $cursor = $qb->select('gid')
248
+            ->from('group_user')
249
+            ->where($qb->expr()->eq('uid', $qb->createNamedParameter($uid)))
250
+            ->execute();
251
+
252
+        $groups = [];
253
+        while($row = $cursor->fetch()) {
254
+            $groups[] = $row['gid'];
255
+            $this->groupCache[$row['gid']] = $row['gid'];
256
+        }
257
+        $cursor->closeCursor();
258
+
259
+        return $groups;
260
+    }
261
+
262
+    /**
263
+     * get a list of all groups
264
+     * @param string $search
265
+     * @param int $limit
266
+     * @param int $offset
267
+     * @return array an array of group names
268
+     *
269
+     * Returns a list with all groups
270
+     */
271
+    public function getGroups($search = '', $limit = null, $offset = null) {
272
+        $this->fixDI();
273
+
274
+        $query = $this->dbConn->getQueryBuilder();
275
+        $query->select('gid')
276
+            ->from('groups')
277
+            ->orderBy('gid', 'ASC');
278
+
279
+        if ($search !== '') {
280
+            $query->where($query->expr()->iLike('gid', $query->createNamedParameter(
281
+                '%' . $this->dbConn->escapeLikeParameter($search) . '%'
282
+            )));
283
+        }
284
+
285
+        $query->setMaxResults($limit)
286
+            ->setFirstResult($offset);
287
+        $result = $query->execute();
288
+
289
+        $groups = [];
290
+        while ($row = $result->fetch()) {
291
+            $groups[] = $row['gid'];
292
+        }
293
+        $result->closeCursor();
294
+
295
+        return $groups;
296
+    }
297
+
298
+    /**
299
+     * check if a group exists
300
+     * @param string $gid
301
+     * @return bool
302
+     */
303
+    public function groupExists($gid) {
304
+        $this->fixDI();
305
+
306
+        // Check cache first
307
+        if (isset($this->groupCache[$gid])) {
308
+            return true;
309
+        }
310
+
311
+        $qb = $this->dbConn->getQueryBuilder();
312
+        $cursor = $qb->select('gid')
313
+            ->from('groups')
314
+            ->where($qb->expr()->eq('gid', $qb->createNamedParameter($gid)))
315
+            ->execute();
316
+        $result = $cursor->fetch();
317
+        $cursor->closeCursor();
318
+
319
+        if ($result !== false) {
320
+            $this->groupCache[$gid] = $gid;
321
+            return true;
322
+        }
323
+        return false;
324
+    }
325
+
326
+    /**
327
+     * get a list of all users in a group
328
+     * @param string $gid
329
+     * @param string $search
330
+     * @param int $limit
331
+     * @param int $offset
332
+     * @return array an array of user ids
333
+     */
334
+    public function usersInGroup($gid, $search = '', $limit = -1, $offset = 0) {
335
+        $this->fixDI();
336
+
337
+        $query = $this->dbConn->getQueryBuilder();
338
+        $query->select('uid')
339
+            ->from('group_user')
340
+            ->where($query->expr()->eq('gid', $query->createNamedParameter($gid)))
341
+            ->orderBy('uid', 'ASC');
342
+
343
+        if ($search !== '') {
344
+            $query->andWhere($query->expr()->like('uid', $query->createNamedParameter(
345
+                '%' . $this->dbConn->escapeLikeParameter($search) . '%'
346
+            )));
347
+        }
348
+
349
+        if ($limit !== -1) {
350
+            $query->setMaxResults($limit);
351
+        }
352
+        if ($offset !== 0) {
353
+            $query->setFirstResult($offset);
354
+        }
355
+
356
+        $result = $query->execute();
357
+
358
+        $users = [];
359
+        while ($row = $result->fetch()) {
360
+            $users[] = $row['uid'];
361
+        }
362
+        $result->closeCursor();
363
+
364
+        return $users;
365
+    }
366
+
367
+    /**
368
+     * get the number of all users matching the search string in a group
369
+     * @param string $gid
370
+     * @param string $search
371
+     * @return int
372
+     */
373
+    public function countUsersInGroup(string $gid, string $search = ''): int {
374
+        $this->fixDI();
375
+
376
+        $query = $this->dbConn->getQueryBuilder();
377
+        $query->select($query->func()->count('*', 'num_users'))
378
+            ->from('group_user')
379
+            ->where($query->expr()->eq('gid', $query->createNamedParameter($gid)));
380
+
381
+        if ($search !== '') {
382
+            $query->andWhere($query->expr()->like('uid', $query->createNamedParameter(
383
+                '%' . $this->dbConn->escapeLikeParameter($search) . '%'
384
+            )));
385
+        }
386
+
387
+        $result = $query->execute();
388
+        $count = $result->fetchColumn();
389
+        $result->closeCursor();
390
+
391
+        if ($count !== false) {
392
+            $count = (int)$count;
393
+        } else {
394
+            $count = 0;
395
+        }
396
+
397
+        return $count;
398
+    }
399
+
400
+    /**
401
+     * get the number of disabled users in a group
402
+     *
403
+     * @param string $search
404
+     *
405
+     * @return int
406
+     */
407
+    public function countDisabledInGroup(string $gid): int {
408
+        $this->fixDI();
409
+
410
+        $query = $this->dbConn->getQueryBuilder();
411
+        $query->select($query->createFunction('COUNT(DISTINCT ' . $query->getColumnName('uid') . ')'))
412
+            ->from('preferences', 'p')
413
+            ->innerJoin('p', 'group_user', 'g', $query->expr()->eq('p.userid', 'g.uid'))
414
+            ->where($query->expr()->eq('appid', $query->createNamedParameter('core')))
415
+            ->andWhere($query->expr()->eq('configkey', $query->createNamedParameter('enabled')))
416
+            ->andWhere($query->expr()->eq('configvalue', $query->createNamedParameter('false'), IQueryBuilder::PARAM_STR))
417
+            ->andWhere($query->expr()->eq('gid', $query->createNamedParameter($gid), IQueryBuilder::PARAM_STR));
418
+
419
+        $result = $query->execute();
420
+        $count = $result->fetchColumn();
421
+        $result->closeCursor();
422
+
423
+        if ($count !== false) {
424
+            $count = (int)$count;
425
+        } else {
426
+            $count = 0;
427
+        }
428
+
429
+        return $count;
430
+    }
431
+
432
+    public function getDisplayName(string $gid): string {
433
+        $this->fixDI();
434
+
435
+        $query = $this->dbConn->getQueryBuilder();
436
+        $query->select('displayname')
437
+            ->from('groups')
438
+            ->where($query->expr()->eq('gid', $query->createNamedParameter($gid)));
439
+
440
+        $result = $query->execute();
441
+        $displayName = $result->fetchColumn();
442
+        $result->closeCursor();
443
+
444
+        return (string) $displayName;
445
+    }
446
+
447
+    public function getGroupDetails(string $gid): array {
448
+        $displayName = $this->getDisplayName($gid);
449
+        if ($displayName !== '') {
450
+            return ['displayName' => $displayName];
451
+        }
452
+
453
+        return [];
454
+    }
455
+
456
+    public function setDisplayName(string $gid, string $displayName): bool {
457
+        if (!$this->groupExists($gid)) {
458
+            return false;
459
+        }
460
+
461
+        $this->fixDI();
462
+
463
+        $displayName = trim($displayName);
464
+        if ($displayName === '') {
465
+            $displayName = $gid;
466
+        }
467
+
468
+        $query = $this->dbConn->getQueryBuilder();
469
+        $query->update('groups')
470
+            ->set('displayname', $query->createNamedParameter($displayName))
471
+            ->where($query->expr()->eq('gid', $query->createNamedParameter($gid)));
472
+        $query->execute();
473
+
474
+        return true;
475
+    }
476 476
 
477 477
 }
Please login to merge, or discard this patch.
Spacing   +10 added lines, -10 removed lines patch added patch discarded remove patch
@@ -113,7 +113,7 @@  discard block
 block discarded – undo
113 113
 				->setValue('gid', $builder->createNamedParameter($gid))
114 114
 				->setValue('displayname', $builder->createNamedParameter($gid))
115 115
 				->execute();
116
-		} catch(UniqueConstraintViolationException $e) {
116
+		} catch (UniqueConstraintViolationException $e) {
117 117
 			$result = 0;
118 118
 		}
119 119
 
@@ -194,14 +194,14 @@  discard block
 block discarded – undo
194 194
 		$this->fixDI();
195 195
 
196 196
 		// No duplicate entries!
197
-		if(!$this->inGroup($uid, $gid)) {
197
+		if (!$this->inGroup($uid, $gid)) {
198 198
 			$qb = $this->dbConn->getQueryBuilder();
199 199
 			$qb->insert('group_user')
200 200
 				->setValue('uid', $qb->createNamedParameter($uid))
201 201
 				->setValue('gid', $qb->createNamedParameter($gid))
202 202
 				->execute();
203 203
 			return true;
204
-		}else{
204
+		} else {
205 205
 			return false;
206 206
 		}
207 207
 	}
@@ -250,7 +250,7 @@  discard block
 block discarded – undo
250 250
 			->execute();
251 251
 
252 252
 		$groups = [];
253
-		while($row = $cursor->fetch()) {
253
+		while ($row = $cursor->fetch()) {
254 254
 			$groups[] = $row['gid'];
255 255
 			$this->groupCache[$row['gid']] = $row['gid'];
256 256
 		}
@@ -278,7 +278,7 @@  discard block
 block discarded – undo
278 278
 
279 279
 		if ($search !== '') {
280 280
 			$query->where($query->expr()->iLike('gid', $query->createNamedParameter(
281
-				'%' . $this->dbConn->escapeLikeParameter($search) . '%'
281
+				'%'.$this->dbConn->escapeLikeParameter($search).'%'
282 282
 			)));
283 283
 		}
284 284
 
@@ -342,7 +342,7 @@  discard block
 block discarded – undo
342 342
 
343 343
 		if ($search !== '') {
344 344
 			$query->andWhere($query->expr()->like('uid', $query->createNamedParameter(
345
-				'%' . $this->dbConn->escapeLikeParameter($search) . '%'
345
+				'%'.$this->dbConn->escapeLikeParameter($search).'%'
346 346
 			)));
347 347
 		}
348 348
 
@@ -380,7 +380,7 @@  discard block
 block discarded – undo
380 380
 
381 381
 		if ($search !== '') {
382 382
 			$query->andWhere($query->expr()->like('uid', $query->createNamedParameter(
383
-				'%' . $this->dbConn->escapeLikeParameter($search) . '%'
383
+				'%'.$this->dbConn->escapeLikeParameter($search).'%'
384 384
 			)));
385 385
 		}
386 386
 
@@ -389,7 +389,7 @@  discard block
 block discarded – undo
389 389
 		$result->closeCursor();
390 390
 
391 391
 		if ($count !== false) {
392
-			$count = (int)$count;
392
+			$count = (int) $count;
393 393
 		} else {
394 394
 			$count = 0;
395 395
 		}
@@ -408,7 +408,7 @@  discard block
 block discarded – undo
408 408
 		$this->fixDI();
409 409
 
410 410
 		$query = $this->dbConn->getQueryBuilder();
411
-		$query->select($query->createFunction('COUNT(DISTINCT ' . $query->getColumnName('uid') . ')'))
411
+		$query->select($query->createFunction('COUNT(DISTINCT '.$query->getColumnName('uid').')'))
412 412
 			->from('preferences', 'p')
413 413
 			->innerJoin('p', 'group_user', 'g', $query->expr()->eq('p.userid', 'g.uid'))
414 414
 			->where($query->expr()->eq('appid', $query->createNamedParameter('core')))
@@ -421,7 +421,7 @@  discard block
 block discarded – undo
421 421
 		$result->closeCursor();
422 422
 
423 423
 		if ($count !== false) {
424
-			$count = (int)$count;
424
+			$count = (int) $count;
425 425
 		} else {
426 426
 			$count = 0;
427 427
 		}
Please login to merge, or discard this patch.
lib/private/Config.php 2 patches
Indentation   +199 added lines, -199 removed lines patch added patch discarded remove patch
@@ -43,229 +43,229 @@
 block discarded – undo
43 43
  */
44 44
 class Config {
45 45
 
46
-	const ENV_PREFIX = 'NC_';
46
+    const ENV_PREFIX = 'NC_';
47 47
 
48
-	/** @var array Associative array ($key => $value) */
49
-	protected $cache = [];
50
-	/** @var string */
51
-	protected $configDir;
52
-	/** @var string */
53
-	protected $configFilePath;
54
-	/** @var string */
55
-	protected $configFileName;
48
+    /** @var array Associative array ($key => $value) */
49
+    protected $cache = [];
50
+    /** @var string */
51
+    protected $configDir;
52
+    /** @var string */
53
+    protected $configFilePath;
54
+    /** @var string */
55
+    protected $configFileName;
56 56
 
57
-	/**
58
-	 * @param string $configDir Path to the config dir, needs to end with '/'
59
-	 * @param string $fileName (Optional) Name of the config file. Defaults to config.php
60
-	 */
61
-	public function __construct($configDir, $fileName = 'config.php') {
62
-		$this->configDir = $configDir;
63
-		$this->configFilePath = $this->configDir.$fileName;
64
-		$this->configFileName = $fileName;
65
-		$this->readData();
66
-	}
57
+    /**
58
+     * @param string $configDir Path to the config dir, needs to end with '/'
59
+     * @param string $fileName (Optional) Name of the config file. Defaults to config.php
60
+     */
61
+    public function __construct($configDir, $fileName = 'config.php') {
62
+        $this->configDir = $configDir;
63
+        $this->configFilePath = $this->configDir.$fileName;
64
+        $this->configFileName = $fileName;
65
+        $this->readData();
66
+    }
67 67
 
68
-	/**
69
-	 * Lists all available config keys
70
-	 *
71
-	 * Please note that it does not return the values.
72
-	 *
73
-	 * @return array an array of key names
74
-	 */
75
-	public function getKeys() {
76
-		return array_keys($this->cache);
77
-	}
68
+    /**
69
+     * Lists all available config keys
70
+     *
71
+     * Please note that it does not return the values.
72
+     *
73
+     * @return array an array of key names
74
+     */
75
+    public function getKeys() {
76
+        return array_keys($this->cache);
77
+    }
78 78
 
79
-	/**
80
-	 * Returns a config value
81
-	 *
82
-	 * gets its value from an `NC_` prefixed environment variable
83
-	 * if it doesn't exist from config.php
84
-	 * if this doesn't exist either, it will return the given `$default`
85
-	 *
86
-	 * @param string $key key
87
-	 * @param mixed $default = null default value
88
-	 * @return mixed the value or $default
89
-	 */
90
-	public function getValue($key, $default = null) {
91
-		$envValue = getenv(self::ENV_PREFIX . $key);
92
-		if ($envValue !== false) {
93
-			return $envValue;
94
-		}
79
+    /**
80
+     * Returns a config value
81
+     *
82
+     * gets its value from an `NC_` prefixed environment variable
83
+     * if it doesn't exist from config.php
84
+     * if this doesn't exist either, it will return the given `$default`
85
+     *
86
+     * @param string $key key
87
+     * @param mixed $default = null default value
88
+     * @return mixed the value or $default
89
+     */
90
+    public function getValue($key, $default = null) {
91
+        $envValue = getenv(self::ENV_PREFIX . $key);
92
+        if ($envValue !== false) {
93
+            return $envValue;
94
+        }
95 95
 
96
-		if (isset($this->cache[$key])) {
97
-			return $this->cache[$key];
98
-		}
96
+        if (isset($this->cache[$key])) {
97
+            return $this->cache[$key];
98
+        }
99 99
 
100
-		return $default;
101
-	}
100
+        return $default;
101
+    }
102 102
 
103
-	/**
104
-	 * Sets and deletes values and writes the config.php
105
-	 *
106
-	 * @param array $configs Associative array with `key => value` pairs
107
-	 *                       If value is null, the config key will be deleted
108
-	 */
109
-	public function setValues(array $configs) {
110
-		$needsUpdate = false;
111
-		foreach ($configs as $key => $value) {
112
-			if ($value !== null) {
113
-				$needsUpdate |= $this->set($key, $value);
114
-			} else {
115
-				$needsUpdate |= $this->delete($key);
116
-			}
117
-		}
103
+    /**
104
+     * Sets and deletes values and writes the config.php
105
+     *
106
+     * @param array $configs Associative array with `key => value` pairs
107
+     *                       If value is null, the config key will be deleted
108
+     */
109
+    public function setValues(array $configs) {
110
+        $needsUpdate = false;
111
+        foreach ($configs as $key => $value) {
112
+            if ($value !== null) {
113
+                $needsUpdate |= $this->set($key, $value);
114
+            } else {
115
+                $needsUpdate |= $this->delete($key);
116
+            }
117
+        }
118 118
 
119
-		if ($needsUpdate) {
120
-			// Write changes
121
-			$this->writeData();
122
-		}
123
-	}
119
+        if ($needsUpdate) {
120
+            // Write changes
121
+            $this->writeData();
122
+        }
123
+    }
124 124
 
125
-	/**
126
-	 * Sets the value and writes it to config.php if required
127
-	 *
128
-	 * @param string $key key
129
-	 * @param mixed $value value
130
-	 */
131
-	public function setValue($key, $value) {
132
-		if ($this->set($key, $value)) {
133
-			// Write changes
134
-			$this->writeData();
135
-		}
136
-	}
125
+    /**
126
+     * Sets the value and writes it to config.php if required
127
+     *
128
+     * @param string $key key
129
+     * @param mixed $value value
130
+     */
131
+    public function setValue($key, $value) {
132
+        if ($this->set($key, $value)) {
133
+            // Write changes
134
+            $this->writeData();
135
+        }
136
+    }
137 137
 
138
-	/**
139
-	 * This function sets the value
140
-	 *
141
-	 * @param string $key key
142
-	 * @param mixed $value value
143
-	 * @return bool True if the file needs to be updated, false otherwise
144
-	 */
145
-	protected function set($key, $value) {
146
-		if (!isset($this->cache[$key]) || $this->cache[$key] !== $value) {
147
-			// Add change
148
-			$this->cache[$key] = $value;
149
-			return true;
150
-		}
138
+    /**
139
+     * This function sets the value
140
+     *
141
+     * @param string $key key
142
+     * @param mixed $value value
143
+     * @return bool True if the file needs to be updated, false otherwise
144
+     */
145
+    protected function set($key, $value) {
146
+        if (!isset($this->cache[$key]) || $this->cache[$key] !== $value) {
147
+            // Add change
148
+            $this->cache[$key] = $value;
149
+            return true;
150
+        }
151 151
 
152
-		return false;
153
-	}
152
+        return false;
153
+    }
154 154
 
155
-	/**
156
-	 * Removes a key from the config and removes it from config.php if required
157
-	 * @param string $key
158
-	 */
159
-	public function deleteKey($key) {
160
-		if ($this->delete($key)) {
161
-			// Write changes
162
-			$this->writeData();
163
-		}
164
-	}
155
+    /**
156
+     * Removes a key from the config and removes it from config.php if required
157
+     * @param string $key
158
+     */
159
+    public function deleteKey($key) {
160
+        if ($this->delete($key)) {
161
+            // Write changes
162
+            $this->writeData();
163
+        }
164
+    }
165 165
 
166
-	/**
167
-	 * This function removes a key from the config
168
-	 *
169
-	 * @param string $key
170
-	 * @return bool True if the file needs to be updated, false otherwise
171
-	 */
172
-	protected function delete($key) {
173
-		if (isset($this->cache[$key])) {
174
-			// Delete key from cache
175
-			unset($this->cache[$key]);
176
-			return true;
177
-		}
178
-		return false;
179
-	}
166
+    /**
167
+     * This function removes a key from the config
168
+     *
169
+     * @param string $key
170
+     * @return bool True if the file needs to be updated, false otherwise
171
+     */
172
+    protected function delete($key) {
173
+        if (isset($this->cache[$key])) {
174
+            // Delete key from cache
175
+            unset($this->cache[$key]);
176
+            return true;
177
+        }
178
+        return false;
179
+    }
180 180
 
181
-	/**
182
-	 * Loads the config file
183
-	 *
184
-	 * Reads the config file and saves it to the cache
185
-	 *
186
-	 * @throws \Exception If no lock could be acquired or the config file has not been found
187
-	 */
188
-	private function readData() {
189
-		// Default config should always get loaded
190
-		$configFiles = [$this->configFilePath];
181
+    /**
182
+     * Loads the config file
183
+     *
184
+     * Reads the config file and saves it to the cache
185
+     *
186
+     * @throws \Exception If no lock could be acquired or the config file has not been found
187
+     */
188
+    private function readData() {
189
+        // Default config should always get loaded
190
+        $configFiles = [$this->configFilePath];
191 191
 
192
-		// Add all files in the config dir ending with the same file name
193
-		$extra = glob($this->configDir.'*.'.$this->configFileName);
194
-		if (is_array($extra)) {
195
-			natsort($extra);
196
-			$configFiles = array_merge($configFiles, $extra);
197
-		}
192
+        // Add all files in the config dir ending with the same file name
193
+        $extra = glob($this->configDir.'*.'.$this->configFileName);
194
+        if (is_array($extra)) {
195
+            natsort($extra);
196
+            $configFiles = array_merge($configFiles, $extra);
197
+        }
198 198
 
199
-		// Include file and merge config
200
-		foreach ($configFiles as $file) {
201
-			$fileExistsAndIsReadable = file_exists($file) && is_readable($file);
202
-			$filePointer = $fileExistsAndIsReadable ? fopen($file, 'r') : false;
203
-			if($file === $this->configFilePath &&
204
-				$filePointer === false) {
205
-				// Opening the main config might not be possible, e.g. if the wrong
206
-				// permissions are set (likely on a new installation)
207
-				continue;
208
-			}
199
+        // Include file and merge config
200
+        foreach ($configFiles as $file) {
201
+            $fileExistsAndIsReadable = file_exists($file) && is_readable($file);
202
+            $filePointer = $fileExistsAndIsReadable ? fopen($file, 'r') : false;
203
+            if($file === $this->configFilePath &&
204
+                $filePointer === false) {
205
+                // Opening the main config might not be possible, e.g. if the wrong
206
+                // permissions are set (likely on a new installation)
207
+                continue;
208
+            }
209 209
 
210
-			// Try to acquire a file lock
211
-			if(!flock($filePointer, LOCK_SH)) {
212
-				throw new \Exception(sprintf('Could not acquire a shared lock on the config file %s', $file));
213
-			}
210
+            // Try to acquire a file lock
211
+            if(!flock($filePointer, LOCK_SH)) {
212
+                throw new \Exception(sprintf('Could not acquire a shared lock on the config file %s', $file));
213
+            }
214 214
 
215
-			unset($CONFIG);
216
-			include $file;
217
-			if(isset($CONFIG) && is_array($CONFIG)) {
218
-				$this->cache = array_merge($this->cache, $CONFIG);
219
-			}
215
+            unset($CONFIG);
216
+            include $file;
217
+            if(isset($CONFIG) && is_array($CONFIG)) {
218
+                $this->cache = array_merge($this->cache, $CONFIG);
219
+            }
220 220
 
221
-			// Close the file pointer and release the lock
222
-			flock($filePointer, LOCK_UN);
223
-			fclose($filePointer);
224
-		}
225
-	}
221
+            // Close the file pointer and release the lock
222
+            flock($filePointer, LOCK_UN);
223
+            fclose($filePointer);
224
+        }
225
+    }
226 226
 
227
-	/**
228
-	 * Writes the config file
229
-	 *
230
-	 * Saves the config to the config file.
231
-	 *
232
-	 * @throws HintException If the config file cannot be written to
233
-	 * @throws \Exception If no file lock can be acquired
234
-	 */
235
-	private function writeData() {
236
-		// Create a php file ...
237
-		$content = "<?php\n";
238
-		$content .= '$CONFIG = ';
239
-		$content .= var_export($this->cache, true);
240
-		$content .= ";\n";
227
+    /**
228
+     * Writes the config file
229
+     *
230
+     * Saves the config to the config file.
231
+     *
232
+     * @throws HintException If the config file cannot be written to
233
+     * @throws \Exception If no file lock can be acquired
234
+     */
235
+    private function writeData() {
236
+        // Create a php file ...
237
+        $content = "<?php\n";
238
+        $content .= '$CONFIG = ';
239
+        $content .= var_export($this->cache, true);
240
+        $content .= ";\n";
241 241
 
242
-		touch($this->configFilePath);
243
-		$filePointer = fopen($this->configFilePath, 'r+');
242
+        touch($this->configFilePath);
243
+        $filePointer = fopen($this->configFilePath, 'r+');
244 244
 
245
-		// Prevent others not to read the config
246
-		chmod($this->configFilePath, 0640);
245
+        // Prevent others not to read the config
246
+        chmod($this->configFilePath, 0640);
247 247
 
248
-		// File does not exist, this can happen when doing a fresh install
249
-		if(!is_resource($filePointer)) {
250
-			throw new HintException(
251
-				"Can't write into config directory!",
252
-				'This can usually be fixed by giving the webserver write access to the config directory.');
253
-		}
248
+        // File does not exist, this can happen when doing a fresh install
249
+        if(!is_resource($filePointer)) {
250
+            throw new HintException(
251
+                "Can't write into config directory!",
252
+                'This can usually be fixed by giving the webserver write access to the config directory.');
253
+        }
254 254
 
255
-		// Try to acquire a file lock
256
-		if(!flock($filePointer, LOCK_EX)) {
257
-			throw new \Exception(sprintf('Could not acquire an exclusive lock on the config file %s', $this->configFilePath));
258
-		}
255
+        // Try to acquire a file lock
256
+        if(!flock($filePointer, LOCK_EX)) {
257
+            throw new \Exception(sprintf('Could not acquire an exclusive lock on the config file %s', $this->configFilePath));
258
+        }
259 259
 
260
-		// Write the config and release the lock
261
-		ftruncate($filePointer, 0);
262
-		fwrite($filePointer, $content);
263
-		fflush($filePointer);
264
-		flock($filePointer, LOCK_UN);
265
-		fclose($filePointer);
260
+        // Write the config and release the lock
261
+        ftruncate($filePointer, 0);
262
+        fwrite($filePointer, $content);
263
+        fflush($filePointer);
264
+        flock($filePointer, LOCK_UN);
265
+        fclose($filePointer);
266 266
 
267
-		if (function_exists('opcache_invalidate')) {
268
-			@opcache_invalidate($this->configFilePath, true);
269
-		}
270
-	}
267
+        if (function_exists('opcache_invalidate')) {
268
+            @opcache_invalidate($this->configFilePath, true);
269
+        }
270
+    }
271 271
 }
Please login to merge, or discard this patch.
Spacing   +6 added lines, -6 removed lines patch added patch discarded remove patch
@@ -88,7 +88,7 @@  discard block
 block discarded – undo
88 88
 	 * @return mixed the value or $default
89 89
 	 */
90 90
 	public function getValue($key, $default = null) {
91
-		$envValue = getenv(self::ENV_PREFIX . $key);
91
+		$envValue = getenv(self::ENV_PREFIX.$key);
92 92
 		if ($envValue !== false) {
93 93
 			return $envValue;
94 94
 		}
@@ -200,7 +200,7 @@  discard block
 block discarded – undo
200 200
 		foreach ($configFiles as $file) {
201 201
 			$fileExistsAndIsReadable = file_exists($file) && is_readable($file);
202 202
 			$filePointer = $fileExistsAndIsReadable ? fopen($file, 'r') : false;
203
-			if($file === $this->configFilePath &&
203
+			if ($file === $this->configFilePath &&
204 204
 				$filePointer === false) {
205 205
 				// Opening the main config might not be possible, e.g. if the wrong
206 206
 				// permissions are set (likely on a new installation)
@@ -208,13 +208,13 @@  discard block
 block discarded – undo
208 208
 			}
209 209
 
210 210
 			// Try to acquire a file lock
211
-			if(!flock($filePointer, LOCK_SH)) {
211
+			if (!flock($filePointer, LOCK_SH)) {
212 212
 				throw new \Exception(sprintf('Could not acquire a shared lock on the config file %s', $file));
213 213
 			}
214 214
 
215 215
 			unset($CONFIG);
216 216
 			include $file;
217
-			if(isset($CONFIG) && is_array($CONFIG)) {
217
+			if (isset($CONFIG) && is_array($CONFIG)) {
218 218
 				$this->cache = array_merge($this->cache, $CONFIG);
219 219
 			}
220 220
 
@@ -246,14 +246,14 @@  discard block
 block discarded – undo
246 246
 		chmod($this->configFilePath, 0640);
247 247
 
248 248
 		// File does not exist, this can happen when doing a fresh install
249
-		if(!is_resource($filePointer)) {
249
+		if (!is_resource($filePointer)) {
250 250
 			throw new HintException(
251 251
 				"Can't write into config directory!",
252 252
 				'This can usually be fixed by giving the webserver write access to the config directory.');
253 253
 		}
254 254
 
255 255
 		// Try to acquire a file lock
256
-		if(!flock($filePointer, LOCK_EX)) {
256
+		if (!flock($filePointer, LOCK_EX)) {
257 257
 			throw new \Exception(sprintf('Could not acquire an exclusive lock on the config file %s', $this->configFilePath));
258 258
 		}
259 259
 
Please login to merge, or discard this patch.
lib/private/Installer.php 2 patches
Indentation   +571 added lines, -571 removed lines patch added patch discarded remove patch
@@ -56,575 +56,575 @@
 block discarded – undo
56 56
  * This class provides the functionality needed to install, update and remove apps
57 57
  */
58 58
 class Installer {
59
-	/** @var AppFetcher */
60
-	private $appFetcher;
61
-	/** @var IClientService */
62
-	private $clientService;
63
-	/** @var ITempManager */
64
-	private $tempManager;
65
-	/** @var ILogger */
66
-	private $logger;
67
-	/** @var IConfig */
68
-	private $config;
69
-	/** @var array - for caching the result of app fetcher */
70
-	private $apps = null;
71
-	/** @var bool|null - for caching the result of the ready status */
72
-	private $isInstanceReadyForUpdates = null;
73
-	/** @var bool */
74
-	private $isCLI;
75
-
76
-	/**
77
-	 * @param AppFetcher $appFetcher
78
-	 * @param IClientService $clientService
79
-	 * @param ITempManager $tempManager
80
-	 * @param ILogger $logger
81
-	 * @param IConfig $config
82
-	 */
83
-	public function __construct(
84
-		AppFetcher $appFetcher,
85
-		IClientService $clientService,
86
-		ITempManager $tempManager,
87
-		ILogger $logger,
88
-		IConfig $config,
89
-		bool $isCLI
90
-	) {
91
-		$this->appFetcher = $appFetcher;
92
-		$this->clientService = $clientService;
93
-		$this->tempManager = $tempManager;
94
-		$this->logger = $logger;
95
-		$this->config = $config;
96
-		$this->isCLI = $isCLI;
97
-	}
98
-
99
-	/**
100
-	 * Installs an app that is located in one of the app folders already
101
-	 *
102
-	 * @param string $appId App to install
103
-	 * @param bool $forceEnable
104
-	 * @throws \Exception
105
-	 * @return string app ID
106
-	 */
107
-	public function installApp(string $appId, bool $forceEnable = false): string {
108
-		$app = \OC_App::findAppInDirectories($appId);
109
-		if($app === false) {
110
-			throw new \Exception('App not found in any app directory');
111
-		}
112
-
113
-		$basedir = $app['path'].'/'.$appId;
114
-		$info = OC_App::getAppInfo($basedir.'/appinfo/info.xml', true);
115
-
116
-		$l = \OC::$server->getL10N('core');
117
-
118
-		if(!is_array($info)) {
119
-			throw new \Exception(
120
-				$l->t('App "%s" cannot be installed because appinfo file cannot be read.',
121
-					[$appId]
122
-				)
123
-			);
124
-		}
125
-
126
-		$ignoreMaxApps = $this->config->getSystemValue('app_install_overwrite', []);
127
-		$ignoreMax = $forceEnable || in_array($appId, $ignoreMaxApps, true);
128
-
129
-		$version = implode('.', \OCP\Util::getVersion());
130
-		if (!\OC_App::isAppCompatible($version, $info, $ignoreMax)) {
131
-			throw new \Exception(
132
-				// TODO $l
133
-				$l->t('App "%s" cannot be installed because it is not compatible with this version of the server.',
134
-					[$info['name']]
135
-				)
136
-			);
137
-		}
138
-
139
-		// check for required dependencies
140
-		\OC_App::checkAppDependencies($this->config, $l, $info, $ignoreMax);
141
-		\OC_App::registerAutoloading($appId, $basedir);
142
-
143
-		$previousVersion = $this->config->getAppValue($info['id'], 'installed_version', false);
144
-		if ($previousVersion) {
145
-			OC_App::executeRepairSteps($appId, $info['repair-steps']['pre-migration']);
146
-		}
147
-
148
-		//install the database
149
-		if(is_file($basedir.'/appinfo/database.xml')) {
150
-			if (\OC::$server->getConfig()->getAppValue($info['id'], 'installed_version') === null) {
151
-				OC_DB::createDbFromStructure($basedir.'/appinfo/database.xml');
152
-			} else {
153
-				OC_DB::updateDbFromStructure($basedir.'/appinfo/database.xml');
154
-			}
155
-		} else {
156
-			$ms = new \OC\DB\MigrationService($info['id'], \OC::$server->getDatabaseConnection());
157
-			$ms->migrate();
158
-		}
159
-		if ($previousVersion) {
160
-			OC_App::executeRepairSteps($appId, $info['repair-steps']['post-migration']);
161
-		}
162
-
163
-		\OC_App::setupBackgroundJobs($info['background-jobs']);
164
-
165
-		//run appinfo/install.php
166
-		self::includeAppScript($basedir . '/appinfo/install.php');
167
-
168
-		$appData = OC_App::getAppInfo($appId);
169
-		OC_App::executeRepairSteps($appId, $appData['repair-steps']['install']);
170
-
171
-		//set the installed version
172
-		\OC::$server->getConfig()->setAppValue($info['id'], 'installed_version', OC_App::getAppVersion($info['id'], false));
173
-		\OC::$server->getConfig()->setAppValue($info['id'], 'enabled', 'no');
174
-
175
-		//set remote/public handlers
176
-		foreach($info['remote'] as $name=>$path) {
177
-			\OC::$server->getConfig()->setAppValue('core', 'remote_'.$name, $info['id'].'/'.$path);
178
-		}
179
-		foreach($info['public'] as $name=>$path) {
180
-			\OC::$server->getConfig()->setAppValue('core', 'public_'.$name, $info['id'].'/'.$path);
181
-		}
182
-
183
-		OC_App::setAppTypes($info['id']);
184
-
185
-		return $info['id'];
186
-	}
187
-
188
-	/**
189
-	 * Updates the specified app from the appstore
190
-	 *
191
-	 * @param string $appId
192
-	 * @return bool
193
-	 */
194
-	public function updateAppstoreApp($appId) {
195
-		if($this->isUpdateAvailable($appId)) {
196
-			try {
197
-				$this->downloadApp($appId);
198
-			} catch (\Exception $e) {
199
-				$this->logger->logException($e, [
200
-					'level' => ILogger::ERROR,
201
-					'app' => 'core',
202
-				]);
203
-				return false;
204
-			}
205
-			return OC_App::updateApp($appId);
206
-		}
207
-
208
-		return false;
209
-	}
210
-
211
-	/**
212
-	 * Downloads an app and puts it into the app directory
213
-	 *
214
-	 * @param string $appId
215
-	 *
216
-	 * @throws \Exception If the installation was not successful
217
-	 */
218
-	public function downloadApp($appId) {
219
-		$appId = strtolower($appId);
220
-
221
-		$apps = $this->appFetcher->get();
222
-		foreach($apps as $app) {
223
-			if($app['id'] === $appId) {
224
-				// Load the certificate
225
-				$certificate = new X509();
226
-				$certificate->loadCA(file_get_contents(__DIR__ . '/../../resources/codesigning/root.crt'));
227
-				$loadedCertificate = $certificate->loadX509($app['certificate']);
228
-
229
-				// Verify if the certificate has been revoked
230
-				$crl = new X509();
231
-				$crl->loadCA(file_get_contents(__DIR__ . '/../../resources/codesigning/root.crt'));
232
-				$crl->loadCRL(file_get_contents(__DIR__ . '/../../resources/codesigning/root.crl'));
233
-				if($crl->validateSignature() !== true) {
234
-					throw new \Exception('Could not validate CRL signature');
235
-				}
236
-				$csn = $loadedCertificate['tbsCertificate']['serialNumber']->toString();
237
-				$revoked = $crl->getRevoked($csn);
238
-				if ($revoked !== false) {
239
-					throw new \Exception(
240
-						sprintf(
241
-							'Certificate "%s" has been revoked',
242
-							$csn
243
-						)
244
-					);
245
-				}
246
-
247
-				// Verify if the certificate has been issued by the Nextcloud Code Authority CA
248
-				if($certificate->validateSignature() !== true) {
249
-					throw new \Exception(
250
-						sprintf(
251
-							'App with id %s has a certificate not issued by a trusted Code Signing Authority',
252
-							$appId
253
-						)
254
-					);
255
-				}
256
-
257
-				// Verify if the certificate is issued for the requested app id
258
-				$certInfo = openssl_x509_parse($app['certificate']);
259
-				if(!isset($certInfo['subject']['CN'])) {
260
-					throw new \Exception(
261
-						sprintf(
262
-							'App with id %s has a cert with no CN',
263
-							$appId
264
-						)
265
-					);
266
-				}
267
-				if($certInfo['subject']['CN'] !== $appId) {
268
-					throw new \Exception(
269
-						sprintf(
270
-							'App with id %s has a cert issued to %s',
271
-							$appId,
272
-							$certInfo['subject']['CN']
273
-						)
274
-					);
275
-				}
276
-
277
-				// Download the release
278
-				$tempFile = $this->tempManager->getTemporaryFile('.tar.gz');
279
-				$timeout = $this->isCLI ? 0 : 120;
280
-				$client = $this->clientService->newClient();
281
-				$client->get($app['releases'][0]['download'], ['save_to' => $tempFile, 'timeout' => $timeout]);
282
-
283
-				// Check if the signature actually matches the downloaded content
284
-				$certificate = openssl_get_publickey($app['certificate']);
285
-				$verified = (bool)openssl_verify(file_get_contents($tempFile), base64_decode($app['releases'][0]['signature']), $certificate, OPENSSL_ALGO_SHA512);
286
-				openssl_free_key($certificate);
287
-
288
-				if($verified === true) {
289
-					// Seems to match, let's proceed
290
-					$extractDir = $this->tempManager->getTemporaryFolder();
291
-					$archive = new TAR($tempFile);
292
-
293
-					if($archive) {
294
-						if (!$archive->extract($extractDir)) {
295
-							throw new \Exception(
296
-								sprintf(
297
-									'Could not extract app %s',
298
-									$appId
299
-								)
300
-							);
301
-						}
302
-						$allFiles = scandir($extractDir);
303
-						$folders = array_diff($allFiles, ['.', '..']);
304
-						$folders = array_values($folders);
305
-
306
-						if(count($folders) > 1) {
307
-							throw new \Exception(
308
-								sprintf(
309
-									'Extracted app %s has more than 1 folder',
310
-									$appId
311
-								)
312
-							);
313
-						}
314
-
315
-						// Check if appinfo/info.xml has the same app ID as well
316
-						$loadEntities = libxml_disable_entity_loader(false);
317
-						$xml = simplexml_load_file($extractDir . '/' . $folders[0] . '/appinfo/info.xml');
318
-						libxml_disable_entity_loader($loadEntities);
319
-						if((string)$xml->id !== $appId) {
320
-							throw new \Exception(
321
-								sprintf(
322
-									'App for id %s has a wrong app ID in info.xml: %s',
323
-									$appId,
324
-									(string)$xml->id
325
-								)
326
-							);
327
-						}
328
-
329
-						// Check if the version is lower than before
330
-						$currentVersion = OC_App::getAppVersion($appId);
331
-						$newVersion = (string)$xml->version;
332
-						if(version_compare($currentVersion, $newVersion) === 1) {
333
-							throw new \Exception(
334
-								sprintf(
335
-									'App for id %s has version %s and tried to update to lower version %s',
336
-									$appId,
337
-									$currentVersion,
338
-									$newVersion
339
-								)
340
-							);
341
-						}
342
-
343
-						$baseDir = OC_App::getInstallPath() . '/' . $appId;
344
-						// Remove old app with the ID if existent
345
-						OC_Helper::rmdirr($baseDir);
346
-						// Move to app folder
347
-						if(@mkdir($baseDir)) {
348
-							$extractDir .= '/' . $folders[0];
349
-							OC_Helper::copyr($extractDir, $baseDir);
350
-						}
351
-						OC_Helper::copyr($extractDir, $baseDir);
352
-						OC_Helper::rmdirr($extractDir);
353
-						return;
354
-					} else {
355
-						throw new \Exception(
356
-							sprintf(
357
-								'Could not extract app with ID %s to %s',
358
-								$appId,
359
-								$extractDir
360
-							)
361
-						);
362
-					}
363
-				} else {
364
-					// Signature does not match
365
-					throw new \Exception(
366
-						sprintf(
367
-							'App with id %s has invalid signature',
368
-							$appId
369
-						)
370
-					);
371
-				}
372
-			}
373
-		}
374
-
375
-		throw new \Exception(
376
-			sprintf(
377
-				'Could not download app %s',
378
-				$appId
379
-			)
380
-		);
381
-	}
382
-
383
-	/**
384
-	 * Check if an update for the app is available
385
-	 *
386
-	 * @param string $appId
387
-	 * @return string|false false or the version number of the update
388
-	 */
389
-	public function isUpdateAvailable($appId) {
390
-		if ($this->isInstanceReadyForUpdates === null) {
391
-			$installPath = OC_App::getInstallPath();
392
-			if ($installPath === false || $installPath === null) {
393
-				$this->isInstanceReadyForUpdates = false;
394
-			} else {
395
-				$this->isInstanceReadyForUpdates = true;
396
-			}
397
-		}
398
-
399
-		if ($this->isInstanceReadyForUpdates === false) {
400
-			return false;
401
-		}
402
-
403
-		if ($this->isInstalledFromGit($appId) === true) {
404
-			return false;
405
-		}
406
-
407
-		if ($this->apps === null) {
408
-			$this->apps = $this->appFetcher->get();
409
-		}
410
-
411
-		foreach($this->apps as $app) {
412
-			if($app['id'] === $appId) {
413
-				$currentVersion = OC_App::getAppVersion($appId);
414
-
415
-				if (!isset($app['releases'][0]['version'])) {
416
-					return false;
417
-				}
418
-				$newestVersion = $app['releases'][0]['version'];
419
-				if ($currentVersion !== '0' && version_compare($newestVersion, $currentVersion, '>')) {
420
-					return $newestVersion;
421
-				} else {
422
-					return false;
423
-				}
424
-			}
425
-		}
426
-
427
-		return false;
428
-	}
429
-
430
-	/**
431
-	 * Check if app has been installed from git
432
-	 * @param string $name name of the application to remove
433
-	 * @return boolean
434
-	 *
435
-	 * The function will check if the path contains a .git folder
436
-	 */
437
-	private function isInstalledFromGit($appId) {
438
-		$app = \OC_App::findAppInDirectories($appId);
439
-		if($app === false) {
440
-			return false;
441
-		}
442
-		$basedir = $app['path'].'/'.$appId;
443
-		return file_exists($basedir.'/.git/');
444
-	}
445
-
446
-	/**
447
-	 * Check if app is already downloaded
448
-	 * @param string $name name of the application to remove
449
-	 * @return boolean
450
-	 *
451
-	 * The function will check if the app is already downloaded in the apps repository
452
-	 */
453
-	public function isDownloaded($name) {
454
-		foreach(\OC::$APPSROOTS as $dir) {
455
-			$dirToTest  = $dir['path'];
456
-			$dirToTest .= '/';
457
-			$dirToTest .= $name;
458
-			$dirToTest .= '/';
459
-
460
-			if (is_dir($dirToTest)) {
461
-				return true;
462
-			}
463
-		}
464
-
465
-		return false;
466
-	}
467
-
468
-	/**
469
-	 * Removes an app
470
-	 * @param string $appId ID of the application to remove
471
-	 * @return boolean
472
-	 *
473
-	 *
474
-	 * This function works as follows
475
-	 *   -# call uninstall repair steps
476
-	 *   -# removing the files
477
-	 *
478
-	 * The function will not delete preferences, tables and the configuration,
479
-	 * this has to be done by the function oc_app_uninstall().
480
-	 */
481
-	public function removeApp($appId) {
482
-		if($this->isDownloaded($appId)) {
483
-			if (\OC::$server->getAppManager()->isShipped($appId)) {
484
-				return false;
485
-			}
486
-			$appDir = OC_App::getInstallPath() . '/' . $appId;
487
-			OC_Helper::rmdirr($appDir);
488
-			return true;
489
-		}else{
490
-			\OCP\Util::writeLog('core', 'can\'t remove app '.$appId.'. It is not installed.', ILogger::ERROR);
491
-
492
-			return false;
493
-		}
494
-
495
-	}
496
-
497
-	/**
498
-	 * Installs the app within the bundle and marks the bundle as installed
499
-	 *
500
-	 * @param Bundle $bundle
501
-	 * @throws \Exception If app could not get installed
502
-	 */
503
-	public function installAppBundle(Bundle $bundle) {
504
-		$appIds = $bundle->getAppIdentifiers();
505
-		foreach($appIds as $appId) {
506
-			if(!$this->isDownloaded($appId)) {
507
-				$this->downloadApp($appId);
508
-			}
509
-			$this->installApp($appId);
510
-			$app = new OC_App();
511
-			$app->enable($appId);
512
-		}
513
-		$bundles = json_decode($this->config->getAppValue('core', 'installed.bundles', json_encode([])), true);
514
-		$bundles[] = $bundle->getIdentifier();
515
-		$this->config->setAppValue('core', 'installed.bundles', json_encode($bundles));
516
-	}
517
-
518
-	/**
519
-	 * Installs shipped apps
520
-	 *
521
-	 * This function installs all apps found in the 'apps' directory that should be enabled by default;
522
-	 * @param bool $softErrors When updating we ignore errors and simply log them, better to have a
523
-	 *                         working ownCloud at the end instead of an aborted update.
524
-	 * @return array Array of error messages (appid => Exception)
525
-	 */
526
-	public static function installShippedApps($softErrors = false) {
527
-		$appManager = \OC::$server->getAppManager();
528
-		$config = \OC::$server->getConfig();
529
-		$errors = [];
530
-		foreach(\OC::$APPSROOTS as $app_dir) {
531
-			if($dir = opendir($app_dir['path'])) {
532
-				while(false !== ($filename = readdir($dir))) {
533
-					if($filename[0] !== '.' and is_dir($app_dir['path']."/$filename")) {
534
-						if(file_exists($app_dir['path']."/$filename/appinfo/info.xml")) {
535
-							if($config->getAppValue($filename, "installed_version", null) === null) {
536
-								$info=OC_App::getAppInfo($filename);
537
-								$enabled = isset($info['default_enable']);
538
-								if (($enabled || in_array($filename, $appManager->getAlwaysEnabledApps()))
539
-									  && $config->getAppValue($filename, 'enabled') !== 'no') {
540
-									if ($softErrors) {
541
-										try {
542
-											Installer::installShippedApp($filename);
543
-										} catch (HintException $e) {
544
-											if ($e->getPrevious() instanceof TableExistsException) {
545
-												$errors[$filename] = $e;
546
-												continue;
547
-											}
548
-											throw $e;
549
-										}
550
-									} else {
551
-										Installer::installShippedApp($filename);
552
-									}
553
-									$config->setAppValue($filename, 'enabled', 'yes');
554
-								}
555
-							}
556
-						}
557
-					}
558
-				}
559
-				closedir($dir);
560
-			}
561
-		}
562
-
563
-		return $errors;
564
-	}
565
-
566
-	/**
567
-	 * install an app already placed in the app folder
568
-	 * @param string $app id of the app to install
569
-	 * @return integer
570
-	 */
571
-	public static function installShippedApp($app) {
572
-		//install the database
573
-		$appPath = OC_App::getAppPath($app);
574
-		\OC_App::registerAutoloading($app, $appPath);
575
-
576
-		if(is_file("$appPath/appinfo/database.xml")) {
577
-			try {
578
-				OC_DB::createDbFromStructure("$appPath/appinfo/database.xml");
579
-			} catch (TableExistsException $e) {
580
-				throw new HintException(
581
-					'Failed to enable app ' . $app,
582
-					'Please ask for help via one of our <a href="https://nextcloud.com/support/" target="_blank" rel="noreferrer noopener">support channels</a>.',
583
-					0, $e
584
-				);
585
-			}
586
-		} else {
587
-			$ms = new \OC\DB\MigrationService($app, \OC::$server->getDatabaseConnection());
588
-			$ms->migrate();
589
-		}
590
-
591
-		//run appinfo/install.php
592
-		self::includeAppScript("$appPath/appinfo/install.php");
593
-
594
-		$info = OC_App::getAppInfo($app);
595
-		if (is_null($info)) {
596
-			return false;
597
-		}
598
-		\OC_App::setupBackgroundJobs($info['background-jobs']);
599
-
600
-		OC_App::executeRepairSteps($app, $info['repair-steps']['install']);
601
-
602
-		$config = \OC::$server->getConfig();
603
-
604
-		$config->setAppValue($app, 'installed_version', OC_App::getAppVersion($app));
605
-		if (array_key_exists('ocsid', $info)) {
606
-			$config->setAppValue($app, 'ocsid', $info['ocsid']);
607
-		}
608
-
609
-		//set remote/public handlers
610
-		foreach($info['remote'] as $name=>$path) {
611
-			$config->setAppValue('core', 'remote_'.$name, $app.'/'.$path);
612
-		}
613
-		foreach($info['public'] as $name=>$path) {
614
-			$config->setAppValue('core', 'public_'.$name, $app.'/'.$path);
615
-		}
616
-
617
-		OC_App::setAppTypes($info['id']);
618
-
619
-		return $info['id'];
620
-	}
621
-
622
-	/**
623
-	 * @param string $script
624
-	 */
625
-	private static function includeAppScript($script) {
626
-		if (file_exists($script)){
627
-			include $script;
628
-		}
629
-	}
59
+    /** @var AppFetcher */
60
+    private $appFetcher;
61
+    /** @var IClientService */
62
+    private $clientService;
63
+    /** @var ITempManager */
64
+    private $tempManager;
65
+    /** @var ILogger */
66
+    private $logger;
67
+    /** @var IConfig */
68
+    private $config;
69
+    /** @var array - for caching the result of app fetcher */
70
+    private $apps = null;
71
+    /** @var bool|null - for caching the result of the ready status */
72
+    private $isInstanceReadyForUpdates = null;
73
+    /** @var bool */
74
+    private $isCLI;
75
+
76
+    /**
77
+     * @param AppFetcher $appFetcher
78
+     * @param IClientService $clientService
79
+     * @param ITempManager $tempManager
80
+     * @param ILogger $logger
81
+     * @param IConfig $config
82
+     */
83
+    public function __construct(
84
+        AppFetcher $appFetcher,
85
+        IClientService $clientService,
86
+        ITempManager $tempManager,
87
+        ILogger $logger,
88
+        IConfig $config,
89
+        bool $isCLI
90
+    ) {
91
+        $this->appFetcher = $appFetcher;
92
+        $this->clientService = $clientService;
93
+        $this->tempManager = $tempManager;
94
+        $this->logger = $logger;
95
+        $this->config = $config;
96
+        $this->isCLI = $isCLI;
97
+    }
98
+
99
+    /**
100
+     * Installs an app that is located in one of the app folders already
101
+     *
102
+     * @param string $appId App to install
103
+     * @param bool $forceEnable
104
+     * @throws \Exception
105
+     * @return string app ID
106
+     */
107
+    public function installApp(string $appId, bool $forceEnable = false): string {
108
+        $app = \OC_App::findAppInDirectories($appId);
109
+        if($app === false) {
110
+            throw new \Exception('App not found in any app directory');
111
+        }
112
+
113
+        $basedir = $app['path'].'/'.$appId;
114
+        $info = OC_App::getAppInfo($basedir.'/appinfo/info.xml', true);
115
+
116
+        $l = \OC::$server->getL10N('core');
117
+
118
+        if(!is_array($info)) {
119
+            throw new \Exception(
120
+                $l->t('App "%s" cannot be installed because appinfo file cannot be read.',
121
+                    [$appId]
122
+                )
123
+            );
124
+        }
125
+
126
+        $ignoreMaxApps = $this->config->getSystemValue('app_install_overwrite', []);
127
+        $ignoreMax = $forceEnable || in_array($appId, $ignoreMaxApps, true);
128
+
129
+        $version = implode('.', \OCP\Util::getVersion());
130
+        if (!\OC_App::isAppCompatible($version, $info, $ignoreMax)) {
131
+            throw new \Exception(
132
+                // TODO $l
133
+                $l->t('App "%s" cannot be installed because it is not compatible with this version of the server.',
134
+                    [$info['name']]
135
+                )
136
+            );
137
+        }
138
+
139
+        // check for required dependencies
140
+        \OC_App::checkAppDependencies($this->config, $l, $info, $ignoreMax);
141
+        \OC_App::registerAutoloading($appId, $basedir);
142
+
143
+        $previousVersion = $this->config->getAppValue($info['id'], 'installed_version', false);
144
+        if ($previousVersion) {
145
+            OC_App::executeRepairSteps($appId, $info['repair-steps']['pre-migration']);
146
+        }
147
+
148
+        //install the database
149
+        if(is_file($basedir.'/appinfo/database.xml')) {
150
+            if (\OC::$server->getConfig()->getAppValue($info['id'], 'installed_version') === null) {
151
+                OC_DB::createDbFromStructure($basedir.'/appinfo/database.xml');
152
+            } else {
153
+                OC_DB::updateDbFromStructure($basedir.'/appinfo/database.xml');
154
+            }
155
+        } else {
156
+            $ms = new \OC\DB\MigrationService($info['id'], \OC::$server->getDatabaseConnection());
157
+            $ms->migrate();
158
+        }
159
+        if ($previousVersion) {
160
+            OC_App::executeRepairSteps($appId, $info['repair-steps']['post-migration']);
161
+        }
162
+
163
+        \OC_App::setupBackgroundJobs($info['background-jobs']);
164
+
165
+        //run appinfo/install.php
166
+        self::includeAppScript($basedir . '/appinfo/install.php');
167
+
168
+        $appData = OC_App::getAppInfo($appId);
169
+        OC_App::executeRepairSteps($appId, $appData['repair-steps']['install']);
170
+
171
+        //set the installed version
172
+        \OC::$server->getConfig()->setAppValue($info['id'], 'installed_version', OC_App::getAppVersion($info['id'], false));
173
+        \OC::$server->getConfig()->setAppValue($info['id'], 'enabled', 'no');
174
+
175
+        //set remote/public handlers
176
+        foreach($info['remote'] as $name=>$path) {
177
+            \OC::$server->getConfig()->setAppValue('core', 'remote_'.$name, $info['id'].'/'.$path);
178
+        }
179
+        foreach($info['public'] as $name=>$path) {
180
+            \OC::$server->getConfig()->setAppValue('core', 'public_'.$name, $info['id'].'/'.$path);
181
+        }
182
+
183
+        OC_App::setAppTypes($info['id']);
184
+
185
+        return $info['id'];
186
+    }
187
+
188
+    /**
189
+     * Updates the specified app from the appstore
190
+     *
191
+     * @param string $appId
192
+     * @return bool
193
+     */
194
+    public function updateAppstoreApp($appId) {
195
+        if($this->isUpdateAvailable($appId)) {
196
+            try {
197
+                $this->downloadApp($appId);
198
+            } catch (\Exception $e) {
199
+                $this->logger->logException($e, [
200
+                    'level' => ILogger::ERROR,
201
+                    'app' => 'core',
202
+                ]);
203
+                return false;
204
+            }
205
+            return OC_App::updateApp($appId);
206
+        }
207
+
208
+        return false;
209
+    }
210
+
211
+    /**
212
+     * Downloads an app and puts it into the app directory
213
+     *
214
+     * @param string $appId
215
+     *
216
+     * @throws \Exception If the installation was not successful
217
+     */
218
+    public function downloadApp($appId) {
219
+        $appId = strtolower($appId);
220
+
221
+        $apps = $this->appFetcher->get();
222
+        foreach($apps as $app) {
223
+            if($app['id'] === $appId) {
224
+                // Load the certificate
225
+                $certificate = new X509();
226
+                $certificate->loadCA(file_get_contents(__DIR__ . '/../../resources/codesigning/root.crt'));
227
+                $loadedCertificate = $certificate->loadX509($app['certificate']);
228
+
229
+                // Verify if the certificate has been revoked
230
+                $crl = new X509();
231
+                $crl->loadCA(file_get_contents(__DIR__ . '/../../resources/codesigning/root.crt'));
232
+                $crl->loadCRL(file_get_contents(__DIR__ . '/../../resources/codesigning/root.crl'));
233
+                if($crl->validateSignature() !== true) {
234
+                    throw new \Exception('Could not validate CRL signature');
235
+                }
236
+                $csn = $loadedCertificate['tbsCertificate']['serialNumber']->toString();
237
+                $revoked = $crl->getRevoked($csn);
238
+                if ($revoked !== false) {
239
+                    throw new \Exception(
240
+                        sprintf(
241
+                            'Certificate "%s" has been revoked',
242
+                            $csn
243
+                        )
244
+                    );
245
+                }
246
+
247
+                // Verify if the certificate has been issued by the Nextcloud Code Authority CA
248
+                if($certificate->validateSignature() !== true) {
249
+                    throw new \Exception(
250
+                        sprintf(
251
+                            'App with id %s has a certificate not issued by a trusted Code Signing Authority',
252
+                            $appId
253
+                        )
254
+                    );
255
+                }
256
+
257
+                // Verify if the certificate is issued for the requested app id
258
+                $certInfo = openssl_x509_parse($app['certificate']);
259
+                if(!isset($certInfo['subject']['CN'])) {
260
+                    throw new \Exception(
261
+                        sprintf(
262
+                            'App with id %s has a cert with no CN',
263
+                            $appId
264
+                        )
265
+                    );
266
+                }
267
+                if($certInfo['subject']['CN'] !== $appId) {
268
+                    throw new \Exception(
269
+                        sprintf(
270
+                            'App with id %s has a cert issued to %s',
271
+                            $appId,
272
+                            $certInfo['subject']['CN']
273
+                        )
274
+                    );
275
+                }
276
+
277
+                // Download the release
278
+                $tempFile = $this->tempManager->getTemporaryFile('.tar.gz');
279
+                $timeout = $this->isCLI ? 0 : 120;
280
+                $client = $this->clientService->newClient();
281
+                $client->get($app['releases'][0]['download'], ['save_to' => $tempFile, 'timeout' => $timeout]);
282
+
283
+                // Check if the signature actually matches the downloaded content
284
+                $certificate = openssl_get_publickey($app['certificate']);
285
+                $verified = (bool)openssl_verify(file_get_contents($tempFile), base64_decode($app['releases'][0]['signature']), $certificate, OPENSSL_ALGO_SHA512);
286
+                openssl_free_key($certificate);
287
+
288
+                if($verified === true) {
289
+                    // Seems to match, let's proceed
290
+                    $extractDir = $this->tempManager->getTemporaryFolder();
291
+                    $archive = new TAR($tempFile);
292
+
293
+                    if($archive) {
294
+                        if (!$archive->extract($extractDir)) {
295
+                            throw new \Exception(
296
+                                sprintf(
297
+                                    'Could not extract app %s',
298
+                                    $appId
299
+                                )
300
+                            );
301
+                        }
302
+                        $allFiles = scandir($extractDir);
303
+                        $folders = array_diff($allFiles, ['.', '..']);
304
+                        $folders = array_values($folders);
305
+
306
+                        if(count($folders) > 1) {
307
+                            throw new \Exception(
308
+                                sprintf(
309
+                                    'Extracted app %s has more than 1 folder',
310
+                                    $appId
311
+                                )
312
+                            );
313
+                        }
314
+
315
+                        // Check if appinfo/info.xml has the same app ID as well
316
+                        $loadEntities = libxml_disable_entity_loader(false);
317
+                        $xml = simplexml_load_file($extractDir . '/' . $folders[0] . '/appinfo/info.xml');
318
+                        libxml_disable_entity_loader($loadEntities);
319
+                        if((string)$xml->id !== $appId) {
320
+                            throw new \Exception(
321
+                                sprintf(
322
+                                    'App for id %s has a wrong app ID in info.xml: %s',
323
+                                    $appId,
324
+                                    (string)$xml->id
325
+                                )
326
+                            );
327
+                        }
328
+
329
+                        // Check if the version is lower than before
330
+                        $currentVersion = OC_App::getAppVersion($appId);
331
+                        $newVersion = (string)$xml->version;
332
+                        if(version_compare($currentVersion, $newVersion) === 1) {
333
+                            throw new \Exception(
334
+                                sprintf(
335
+                                    'App for id %s has version %s and tried to update to lower version %s',
336
+                                    $appId,
337
+                                    $currentVersion,
338
+                                    $newVersion
339
+                                )
340
+                            );
341
+                        }
342
+
343
+                        $baseDir = OC_App::getInstallPath() . '/' . $appId;
344
+                        // Remove old app with the ID if existent
345
+                        OC_Helper::rmdirr($baseDir);
346
+                        // Move to app folder
347
+                        if(@mkdir($baseDir)) {
348
+                            $extractDir .= '/' . $folders[0];
349
+                            OC_Helper::copyr($extractDir, $baseDir);
350
+                        }
351
+                        OC_Helper::copyr($extractDir, $baseDir);
352
+                        OC_Helper::rmdirr($extractDir);
353
+                        return;
354
+                    } else {
355
+                        throw new \Exception(
356
+                            sprintf(
357
+                                'Could not extract app with ID %s to %s',
358
+                                $appId,
359
+                                $extractDir
360
+                            )
361
+                        );
362
+                    }
363
+                } else {
364
+                    // Signature does not match
365
+                    throw new \Exception(
366
+                        sprintf(
367
+                            'App with id %s has invalid signature',
368
+                            $appId
369
+                        )
370
+                    );
371
+                }
372
+            }
373
+        }
374
+
375
+        throw new \Exception(
376
+            sprintf(
377
+                'Could not download app %s',
378
+                $appId
379
+            )
380
+        );
381
+    }
382
+
383
+    /**
384
+     * Check if an update for the app is available
385
+     *
386
+     * @param string $appId
387
+     * @return string|false false or the version number of the update
388
+     */
389
+    public function isUpdateAvailable($appId) {
390
+        if ($this->isInstanceReadyForUpdates === null) {
391
+            $installPath = OC_App::getInstallPath();
392
+            if ($installPath === false || $installPath === null) {
393
+                $this->isInstanceReadyForUpdates = false;
394
+            } else {
395
+                $this->isInstanceReadyForUpdates = true;
396
+            }
397
+        }
398
+
399
+        if ($this->isInstanceReadyForUpdates === false) {
400
+            return false;
401
+        }
402
+
403
+        if ($this->isInstalledFromGit($appId) === true) {
404
+            return false;
405
+        }
406
+
407
+        if ($this->apps === null) {
408
+            $this->apps = $this->appFetcher->get();
409
+        }
410
+
411
+        foreach($this->apps as $app) {
412
+            if($app['id'] === $appId) {
413
+                $currentVersion = OC_App::getAppVersion($appId);
414
+
415
+                if (!isset($app['releases'][0]['version'])) {
416
+                    return false;
417
+                }
418
+                $newestVersion = $app['releases'][0]['version'];
419
+                if ($currentVersion !== '0' && version_compare($newestVersion, $currentVersion, '>')) {
420
+                    return $newestVersion;
421
+                } else {
422
+                    return false;
423
+                }
424
+            }
425
+        }
426
+
427
+        return false;
428
+    }
429
+
430
+    /**
431
+     * Check if app has been installed from git
432
+     * @param string $name name of the application to remove
433
+     * @return boolean
434
+     *
435
+     * The function will check if the path contains a .git folder
436
+     */
437
+    private function isInstalledFromGit($appId) {
438
+        $app = \OC_App::findAppInDirectories($appId);
439
+        if($app === false) {
440
+            return false;
441
+        }
442
+        $basedir = $app['path'].'/'.$appId;
443
+        return file_exists($basedir.'/.git/');
444
+    }
445
+
446
+    /**
447
+     * Check if app is already downloaded
448
+     * @param string $name name of the application to remove
449
+     * @return boolean
450
+     *
451
+     * The function will check if the app is already downloaded in the apps repository
452
+     */
453
+    public function isDownloaded($name) {
454
+        foreach(\OC::$APPSROOTS as $dir) {
455
+            $dirToTest  = $dir['path'];
456
+            $dirToTest .= '/';
457
+            $dirToTest .= $name;
458
+            $dirToTest .= '/';
459
+
460
+            if (is_dir($dirToTest)) {
461
+                return true;
462
+            }
463
+        }
464
+
465
+        return false;
466
+    }
467
+
468
+    /**
469
+     * Removes an app
470
+     * @param string $appId ID of the application to remove
471
+     * @return boolean
472
+     *
473
+     *
474
+     * This function works as follows
475
+     *   -# call uninstall repair steps
476
+     *   -# removing the files
477
+     *
478
+     * The function will not delete preferences, tables and the configuration,
479
+     * this has to be done by the function oc_app_uninstall().
480
+     */
481
+    public function removeApp($appId) {
482
+        if($this->isDownloaded($appId)) {
483
+            if (\OC::$server->getAppManager()->isShipped($appId)) {
484
+                return false;
485
+            }
486
+            $appDir = OC_App::getInstallPath() . '/' . $appId;
487
+            OC_Helper::rmdirr($appDir);
488
+            return true;
489
+        }else{
490
+            \OCP\Util::writeLog('core', 'can\'t remove app '.$appId.'. It is not installed.', ILogger::ERROR);
491
+
492
+            return false;
493
+        }
494
+
495
+    }
496
+
497
+    /**
498
+     * Installs the app within the bundle and marks the bundle as installed
499
+     *
500
+     * @param Bundle $bundle
501
+     * @throws \Exception If app could not get installed
502
+     */
503
+    public function installAppBundle(Bundle $bundle) {
504
+        $appIds = $bundle->getAppIdentifiers();
505
+        foreach($appIds as $appId) {
506
+            if(!$this->isDownloaded($appId)) {
507
+                $this->downloadApp($appId);
508
+            }
509
+            $this->installApp($appId);
510
+            $app = new OC_App();
511
+            $app->enable($appId);
512
+        }
513
+        $bundles = json_decode($this->config->getAppValue('core', 'installed.bundles', json_encode([])), true);
514
+        $bundles[] = $bundle->getIdentifier();
515
+        $this->config->setAppValue('core', 'installed.bundles', json_encode($bundles));
516
+    }
517
+
518
+    /**
519
+     * Installs shipped apps
520
+     *
521
+     * This function installs all apps found in the 'apps' directory that should be enabled by default;
522
+     * @param bool $softErrors When updating we ignore errors and simply log them, better to have a
523
+     *                         working ownCloud at the end instead of an aborted update.
524
+     * @return array Array of error messages (appid => Exception)
525
+     */
526
+    public static function installShippedApps($softErrors = false) {
527
+        $appManager = \OC::$server->getAppManager();
528
+        $config = \OC::$server->getConfig();
529
+        $errors = [];
530
+        foreach(\OC::$APPSROOTS as $app_dir) {
531
+            if($dir = opendir($app_dir['path'])) {
532
+                while(false !== ($filename = readdir($dir))) {
533
+                    if($filename[0] !== '.' and is_dir($app_dir['path']."/$filename")) {
534
+                        if(file_exists($app_dir['path']."/$filename/appinfo/info.xml")) {
535
+                            if($config->getAppValue($filename, "installed_version", null) === null) {
536
+                                $info=OC_App::getAppInfo($filename);
537
+                                $enabled = isset($info['default_enable']);
538
+                                if (($enabled || in_array($filename, $appManager->getAlwaysEnabledApps()))
539
+                                      && $config->getAppValue($filename, 'enabled') !== 'no') {
540
+                                    if ($softErrors) {
541
+                                        try {
542
+                                            Installer::installShippedApp($filename);
543
+                                        } catch (HintException $e) {
544
+                                            if ($e->getPrevious() instanceof TableExistsException) {
545
+                                                $errors[$filename] = $e;
546
+                                                continue;
547
+                                            }
548
+                                            throw $e;
549
+                                        }
550
+                                    } else {
551
+                                        Installer::installShippedApp($filename);
552
+                                    }
553
+                                    $config->setAppValue($filename, 'enabled', 'yes');
554
+                                }
555
+                            }
556
+                        }
557
+                    }
558
+                }
559
+                closedir($dir);
560
+            }
561
+        }
562
+
563
+        return $errors;
564
+    }
565
+
566
+    /**
567
+     * install an app already placed in the app folder
568
+     * @param string $app id of the app to install
569
+     * @return integer
570
+     */
571
+    public static function installShippedApp($app) {
572
+        //install the database
573
+        $appPath = OC_App::getAppPath($app);
574
+        \OC_App::registerAutoloading($app, $appPath);
575
+
576
+        if(is_file("$appPath/appinfo/database.xml")) {
577
+            try {
578
+                OC_DB::createDbFromStructure("$appPath/appinfo/database.xml");
579
+            } catch (TableExistsException $e) {
580
+                throw new HintException(
581
+                    'Failed to enable app ' . $app,
582
+                    'Please ask for help via one of our <a href="https://nextcloud.com/support/" target="_blank" rel="noreferrer noopener">support channels</a>.',
583
+                    0, $e
584
+                );
585
+            }
586
+        } else {
587
+            $ms = new \OC\DB\MigrationService($app, \OC::$server->getDatabaseConnection());
588
+            $ms->migrate();
589
+        }
590
+
591
+        //run appinfo/install.php
592
+        self::includeAppScript("$appPath/appinfo/install.php");
593
+
594
+        $info = OC_App::getAppInfo($app);
595
+        if (is_null($info)) {
596
+            return false;
597
+        }
598
+        \OC_App::setupBackgroundJobs($info['background-jobs']);
599
+
600
+        OC_App::executeRepairSteps($app, $info['repair-steps']['install']);
601
+
602
+        $config = \OC::$server->getConfig();
603
+
604
+        $config->setAppValue($app, 'installed_version', OC_App::getAppVersion($app));
605
+        if (array_key_exists('ocsid', $info)) {
606
+            $config->setAppValue($app, 'ocsid', $info['ocsid']);
607
+        }
608
+
609
+        //set remote/public handlers
610
+        foreach($info['remote'] as $name=>$path) {
611
+            $config->setAppValue('core', 'remote_'.$name, $app.'/'.$path);
612
+        }
613
+        foreach($info['public'] as $name=>$path) {
614
+            $config->setAppValue('core', 'public_'.$name, $app.'/'.$path);
615
+        }
616
+
617
+        OC_App::setAppTypes($info['id']);
618
+
619
+        return $info['id'];
620
+    }
621
+
622
+    /**
623
+     * @param string $script
624
+     */
625
+    private static function includeAppScript($script) {
626
+        if (file_exists($script)){
627
+            include $script;
628
+        }
629
+    }
630 630
 }
Please login to merge, or discard this patch.
Spacing   +49 added lines, -49 removed lines patch added patch discarded remove patch
@@ -106,7 +106,7 @@  discard block
 block discarded – undo
106 106
 	 */
107 107
 	public function installApp(string $appId, bool $forceEnable = false): string {
108 108
 		$app = \OC_App::findAppInDirectories($appId);
109
-		if($app === false) {
109
+		if ($app === false) {
110 110
 			throw new \Exception('App not found in any app directory');
111 111
 		}
112 112
 
@@ -115,7 +115,7 @@  discard block
 block discarded – undo
115 115
 
116 116
 		$l = \OC::$server->getL10N('core');
117 117
 
118
-		if(!is_array($info)) {
118
+		if (!is_array($info)) {
119 119
 			throw new \Exception(
120 120
 				$l->t('App "%s" cannot be installed because appinfo file cannot be read.',
121 121
 					[$appId]
@@ -146,7 +146,7 @@  discard block
 block discarded – undo
146 146
 		}
147 147
 
148 148
 		//install the database
149
-		if(is_file($basedir.'/appinfo/database.xml')) {
149
+		if (is_file($basedir.'/appinfo/database.xml')) {
150 150
 			if (\OC::$server->getConfig()->getAppValue($info['id'], 'installed_version') === null) {
151 151
 				OC_DB::createDbFromStructure($basedir.'/appinfo/database.xml');
152 152
 			} else {
@@ -163,7 +163,7 @@  discard block
 block discarded – undo
163 163
 		\OC_App::setupBackgroundJobs($info['background-jobs']);
164 164
 
165 165
 		//run appinfo/install.php
166
-		self::includeAppScript($basedir . '/appinfo/install.php');
166
+		self::includeAppScript($basedir.'/appinfo/install.php');
167 167
 
168 168
 		$appData = OC_App::getAppInfo($appId);
169 169
 		OC_App::executeRepairSteps($appId, $appData['repair-steps']['install']);
@@ -173,10 +173,10 @@  discard block
 block discarded – undo
173 173
 		\OC::$server->getConfig()->setAppValue($info['id'], 'enabled', 'no');
174 174
 
175 175
 		//set remote/public handlers
176
-		foreach($info['remote'] as $name=>$path) {
176
+		foreach ($info['remote'] as $name=>$path) {
177 177
 			\OC::$server->getConfig()->setAppValue('core', 'remote_'.$name, $info['id'].'/'.$path);
178 178
 		}
179
-		foreach($info['public'] as $name=>$path) {
179
+		foreach ($info['public'] as $name=>$path) {
180 180
 			\OC::$server->getConfig()->setAppValue('core', 'public_'.$name, $info['id'].'/'.$path);
181 181
 		}
182 182
 
@@ -192,7 +192,7 @@  discard block
 block discarded – undo
192 192
 	 * @return bool
193 193
 	 */
194 194
 	public function updateAppstoreApp($appId) {
195
-		if($this->isUpdateAvailable($appId)) {
195
+		if ($this->isUpdateAvailable($appId)) {
196 196
 			try {
197 197
 				$this->downloadApp($appId);
198 198
 			} catch (\Exception $e) {
@@ -219,18 +219,18 @@  discard block
 block discarded – undo
219 219
 		$appId = strtolower($appId);
220 220
 
221 221
 		$apps = $this->appFetcher->get();
222
-		foreach($apps as $app) {
223
-			if($app['id'] === $appId) {
222
+		foreach ($apps as $app) {
223
+			if ($app['id'] === $appId) {
224 224
 				// Load the certificate
225 225
 				$certificate = new X509();
226
-				$certificate->loadCA(file_get_contents(__DIR__ . '/../../resources/codesigning/root.crt'));
226
+				$certificate->loadCA(file_get_contents(__DIR__.'/../../resources/codesigning/root.crt'));
227 227
 				$loadedCertificate = $certificate->loadX509($app['certificate']);
228 228
 
229 229
 				// Verify if the certificate has been revoked
230 230
 				$crl = new X509();
231
-				$crl->loadCA(file_get_contents(__DIR__ . '/../../resources/codesigning/root.crt'));
232
-				$crl->loadCRL(file_get_contents(__DIR__ . '/../../resources/codesigning/root.crl'));
233
-				if($crl->validateSignature() !== true) {
231
+				$crl->loadCA(file_get_contents(__DIR__.'/../../resources/codesigning/root.crt'));
232
+				$crl->loadCRL(file_get_contents(__DIR__.'/../../resources/codesigning/root.crl'));
233
+				if ($crl->validateSignature() !== true) {
234 234
 					throw new \Exception('Could not validate CRL signature');
235 235
 				}
236 236
 				$csn = $loadedCertificate['tbsCertificate']['serialNumber']->toString();
@@ -245,7 +245,7 @@  discard block
 block discarded – undo
245 245
 				}
246 246
 
247 247
 				// Verify if the certificate has been issued by the Nextcloud Code Authority CA
248
-				if($certificate->validateSignature() !== true) {
248
+				if ($certificate->validateSignature() !== true) {
249 249
 					throw new \Exception(
250 250
 						sprintf(
251 251
 							'App with id %s has a certificate not issued by a trusted Code Signing Authority',
@@ -256,7 +256,7 @@  discard block
 block discarded – undo
256 256
 
257 257
 				// Verify if the certificate is issued for the requested app id
258 258
 				$certInfo = openssl_x509_parse($app['certificate']);
259
-				if(!isset($certInfo['subject']['CN'])) {
259
+				if (!isset($certInfo['subject']['CN'])) {
260 260
 					throw new \Exception(
261 261
 						sprintf(
262 262
 							'App with id %s has a cert with no CN',
@@ -264,7 +264,7 @@  discard block
 block discarded – undo
264 264
 						)
265 265
 					);
266 266
 				}
267
-				if($certInfo['subject']['CN'] !== $appId) {
267
+				if ($certInfo['subject']['CN'] !== $appId) {
268 268
 					throw new \Exception(
269 269
 						sprintf(
270 270
 							'App with id %s has a cert issued to %s',
@@ -282,15 +282,15 @@  discard block
 block discarded – undo
282 282
 
283 283
 				// Check if the signature actually matches the downloaded content
284 284
 				$certificate = openssl_get_publickey($app['certificate']);
285
-				$verified = (bool)openssl_verify(file_get_contents($tempFile), base64_decode($app['releases'][0]['signature']), $certificate, OPENSSL_ALGO_SHA512);
285
+				$verified = (bool) openssl_verify(file_get_contents($tempFile), base64_decode($app['releases'][0]['signature']), $certificate, OPENSSL_ALGO_SHA512);
286 286
 				openssl_free_key($certificate);
287 287
 
288
-				if($verified === true) {
288
+				if ($verified === true) {
289 289
 					// Seems to match, let's proceed
290 290
 					$extractDir = $this->tempManager->getTemporaryFolder();
291 291
 					$archive = new TAR($tempFile);
292 292
 
293
-					if($archive) {
293
+					if ($archive) {
294 294
 						if (!$archive->extract($extractDir)) {
295 295
 							throw new \Exception(
296 296
 								sprintf(
@@ -303,7 +303,7 @@  discard block
 block discarded – undo
303 303
 						$folders = array_diff($allFiles, ['.', '..']);
304 304
 						$folders = array_values($folders);
305 305
 
306
-						if(count($folders) > 1) {
306
+						if (count($folders) > 1) {
307 307
 							throw new \Exception(
308 308
 								sprintf(
309 309
 									'Extracted app %s has more than 1 folder',
@@ -314,22 +314,22 @@  discard block
 block discarded – undo
314 314
 
315 315
 						// Check if appinfo/info.xml has the same app ID as well
316 316
 						$loadEntities = libxml_disable_entity_loader(false);
317
-						$xml = simplexml_load_file($extractDir . '/' . $folders[0] . '/appinfo/info.xml');
317
+						$xml = simplexml_load_file($extractDir.'/'.$folders[0].'/appinfo/info.xml');
318 318
 						libxml_disable_entity_loader($loadEntities);
319
-						if((string)$xml->id !== $appId) {
319
+						if ((string) $xml->id !== $appId) {
320 320
 							throw new \Exception(
321 321
 								sprintf(
322 322
 									'App for id %s has a wrong app ID in info.xml: %s',
323 323
 									$appId,
324
-									(string)$xml->id
324
+									(string) $xml->id
325 325
 								)
326 326
 							);
327 327
 						}
328 328
 
329 329
 						// Check if the version is lower than before
330 330
 						$currentVersion = OC_App::getAppVersion($appId);
331
-						$newVersion = (string)$xml->version;
332
-						if(version_compare($currentVersion, $newVersion) === 1) {
331
+						$newVersion = (string) $xml->version;
332
+						if (version_compare($currentVersion, $newVersion) === 1) {
333 333
 							throw new \Exception(
334 334
 								sprintf(
335 335
 									'App for id %s has version %s and tried to update to lower version %s',
@@ -340,12 +340,12 @@  discard block
 block discarded – undo
340 340
 							);
341 341
 						}
342 342
 
343
-						$baseDir = OC_App::getInstallPath() . '/' . $appId;
343
+						$baseDir = OC_App::getInstallPath().'/'.$appId;
344 344
 						// Remove old app with the ID if existent
345 345
 						OC_Helper::rmdirr($baseDir);
346 346
 						// Move to app folder
347
-						if(@mkdir($baseDir)) {
348
-							$extractDir .= '/' . $folders[0];
347
+						if (@mkdir($baseDir)) {
348
+							$extractDir .= '/'.$folders[0];
349 349
 							OC_Helper::copyr($extractDir, $baseDir);
350 350
 						}
351 351
 						OC_Helper::copyr($extractDir, $baseDir);
@@ -408,8 +408,8 @@  discard block
 block discarded – undo
408 408
 			$this->apps = $this->appFetcher->get();
409 409
 		}
410 410
 
411
-		foreach($this->apps as $app) {
412
-			if($app['id'] === $appId) {
411
+		foreach ($this->apps as $app) {
412
+			if ($app['id'] === $appId) {
413 413
 				$currentVersion = OC_App::getAppVersion($appId);
414 414
 
415 415
 				if (!isset($app['releases'][0]['version'])) {
@@ -436,7 +436,7 @@  discard block
 block discarded – undo
436 436
 	 */
437 437
 	private function isInstalledFromGit($appId) {
438 438
 		$app = \OC_App::findAppInDirectories($appId);
439
-		if($app === false) {
439
+		if ($app === false) {
440 440
 			return false;
441 441
 		}
442 442
 		$basedir = $app['path'].'/'.$appId;
@@ -451,7 +451,7 @@  discard block
 block discarded – undo
451 451
 	 * The function will check if the app is already downloaded in the apps repository
452 452
 	 */
453 453
 	public function isDownloaded($name) {
454
-		foreach(\OC::$APPSROOTS as $dir) {
454
+		foreach (\OC::$APPSROOTS as $dir) {
455 455
 			$dirToTest  = $dir['path'];
456 456
 			$dirToTest .= '/';
457 457
 			$dirToTest .= $name;
@@ -479,14 +479,14 @@  discard block
 block discarded – undo
479 479
 	 * this has to be done by the function oc_app_uninstall().
480 480
 	 */
481 481
 	public function removeApp($appId) {
482
-		if($this->isDownloaded($appId)) {
482
+		if ($this->isDownloaded($appId)) {
483 483
 			if (\OC::$server->getAppManager()->isShipped($appId)) {
484 484
 				return false;
485 485
 			}
486
-			$appDir = OC_App::getInstallPath() . '/' . $appId;
486
+			$appDir = OC_App::getInstallPath().'/'.$appId;
487 487
 			OC_Helper::rmdirr($appDir);
488 488
 			return true;
489
-		}else{
489
+		} else {
490 490
 			\OCP\Util::writeLog('core', 'can\'t remove app '.$appId.'. It is not installed.', ILogger::ERROR);
491 491
 
492 492
 			return false;
@@ -502,8 +502,8 @@  discard block
 block discarded – undo
502 502
 	 */
503 503
 	public function installAppBundle(Bundle $bundle) {
504 504
 		$appIds = $bundle->getAppIdentifiers();
505
-		foreach($appIds as $appId) {
506
-			if(!$this->isDownloaded($appId)) {
505
+		foreach ($appIds as $appId) {
506
+			if (!$this->isDownloaded($appId)) {
507 507
 				$this->downloadApp($appId);
508 508
 			}
509 509
 			$this->installApp($appId);
@@ -527,13 +527,13 @@  discard block
 block discarded – undo
527 527
 		$appManager = \OC::$server->getAppManager();
528 528
 		$config = \OC::$server->getConfig();
529 529
 		$errors = [];
530
-		foreach(\OC::$APPSROOTS as $app_dir) {
531
-			if($dir = opendir($app_dir['path'])) {
532
-				while(false !== ($filename = readdir($dir))) {
533
-					if($filename[0] !== '.' and is_dir($app_dir['path']."/$filename")) {
534
-						if(file_exists($app_dir['path']."/$filename/appinfo/info.xml")) {
535
-							if($config->getAppValue($filename, "installed_version", null) === null) {
536
-								$info=OC_App::getAppInfo($filename);
530
+		foreach (\OC::$APPSROOTS as $app_dir) {
531
+			if ($dir = opendir($app_dir['path'])) {
532
+				while (false !== ($filename = readdir($dir))) {
533
+					if ($filename[0] !== '.' and is_dir($app_dir['path']."/$filename")) {
534
+						if (file_exists($app_dir['path']."/$filename/appinfo/info.xml")) {
535
+							if ($config->getAppValue($filename, "installed_version", null) === null) {
536
+								$info = OC_App::getAppInfo($filename);
537 537
 								$enabled = isset($info['default_enable']);
538 538
 								if (($enabled || in_array($filename, $appManager->getAlwaysEnabledApps()))
539 539
 									  && $config->getAppValue($filename, 'enabled') !== 'no') {
@@ -573,12 +573,12 @@  discard block
 block discarded – undo
573 573
 		$appPath = OC_App::getAppPath($app);
574 574
 		\OC_App::registerAutoloading($app, $appPath);
575 575
 
576
-		if(is_file("$appPath/appinfo/database.xml")) {
576
+		if (is_file("$appPath/appinfo/database.xml")) {
577 577
 			try {
578 578
 				OC_DB::createDbFromStructure("$appPath/appinfo/database.xml");
579 579
 			} catch (TableExistsException $e) {
580 580
 				throw new HintException(
581
-					'Failed to enable app ' . $app,
581
+					'Failed to enable app '.$app,
582 582
 					'Please ask for help via one of our <a href="https://nextcloud.com/support/" target="_blank" rel="noreferrer noopener">support channels</a>.',
583 583
 					0, $e
584 584
 				);
@@ -607,10 +607,10 @@  discard block
 block discarded – undo
607 607
 		}
608 608
 
609 609
 		//set remote/public handlers
610
-		foreach($info['remote'] as $name=>$path) {
610
+		foreach ($info['remote'] as $name=>$path) {
611 611
 			$config->setAppValue('core', 'remote_'.$name, $app.'/'.$path);
612 612
 		}
613
-		foreach($info['public'] as $name=>$path) {
613
+		foreach ($info['public'] as $name=>$path) {
614 614
 			$config->setAppValue('core', 'public_'.$name, $app.'/'.$path);
615 615
 		}
616 616
 
@@ -623,7 +623,7 @@  discard block
 block discarded – undo
623 623
 	 * @param string $script
624 624
 	 */
625 625
 	private static function includeAppScript($script) {
626
-		if (file_exists($script)){
626
+		if (file_exists($script)) {
627 627
 			include $script;
628 628
 		}
629 629
 	}
Please login to merge, or discard this patch.