Completed
Pull Request — master (#2834)
by Joas
14:28
created
lib/private/AppFramework/DependencyInjection/DIContainer.php 2 patches
Indentation   +353 added lines, -353 removed lines patch added patch discarded remove patch
@@ -62,357 +62,357 @@
 block discarded – undo
62 62
 
63 63
 class DIContainer extends SimpleContainer implements IAppContainer {
64 64
 
65
-	/**
66
-	 * @var array
67
-	 */
68
-	private $middleWares = array();
69
-
70
-	/** @var ServerContainer */
71
-	private $server;
72
-
73
-	/**
74
-	 * Put your class dependencies in here
75
-	 * @param string $appName the name of the app
76
-	 * @param array $urlParams
77
-	 * @param ServerContainer $server
78
-	 */
79
-	public function __construct($appName, $urlParams = array(), ServerContainer $server = null){
80
-		parent::__construct();
81
-		$this['AppName'] = $appName;
82
-		$this['urlParams'] = $urlParams;
83
-
84
-		/** @var \OC\ServerContainer $server */
85
-		if ($server === null) {
86
-			$server = \OC::$server;
87
-		}
88
-		$this->server = $server;
89
-		$this->server->registerAppContainer($appName, $this);
90
-
91
-		// aliases
92
-		$this->registerAlias('appName', 'AppName');
93
-		$this->registerAlias('webRoot', 'WebRoot');
94
-		$this->registerAlias('userId', 'UserId');
95
-
96
-		/**
97
-		 * Core services
98
-		 */
99
-		$this->registerService(IOutput::class, function($c){
100
-			return new Output($this->getServer()->getWebRoot());
101
-		});
102
-
103
-		$this->registerService(Folder::class, function() {
104
-			return $this->getServer()->getUserFolder();
105
-		});
106
-
107
-		$this->registerService(IAppData::class, function (SimpleContainer $c) {
108
-			return $this->getServer()->getAppDataDir($c->query('AppName'));
109
-		});
110
-
111
-		$this->registerService(IL10N::class, function($c) {
112
-			return $this->getServer()->getL10N($c->query('AppName'));
113
-		});
114
-
115
-		$this->registerAlias(\OCP\AppFramework\Utility\IControllerMethodReflector::class, \OC\AppFramework\Utility\ControllerMethodReflector::class);
116
-		$this->registerAlias('ControllerMethodReflector', \OCP\AppFramework\Utility\IControllerMethodReflector::class);
117
-
118
-		$this->registerService(IRequest::class, function() {
119
-			return $this->getServer()->query(IRequest::class);
120
-		});
121
-		$this->registerAlias('Request', IRequest::class);
122
-
123
-		$this->registerAlias(\OCP\AppFramework\Utility\ITimeFactory::class, \OC\AppFramework\Utility\TimeFactory::class);
124
-		$this->registerAlias('TimeFactory', \OCP\AppFramework\Utility\ITimeFactory::class);
125
-
126
-		$this->registerAlias(\OC\User\Session::class, \OCP\IUserSession::class);
127
-
128
-		$this->registerService(IServerContainer::class, function ($c) {
129
-			return $this->getServer();
130
-		});
131
-		$this->registerAlias('ServerContainer', IServerContainer::class);
132
-
133
-		$this->registerService(\OCP\WorkflowEngine\IManager::class, function ($c) {
134
-			return $c->query('OCA\WorkflowEngine\Manager');
135
-		});
136
-
137
-		$this->registerService(\OCP\AppFramework\IAppContainer::class, function ($c) {
138
-			return $c;
139
-		});
140
-
141
-		// commonly used attributes
142
-		$this->registerService('UserId', function ($c) {
143
-			return $c->query('OCP\\IUserSession')->getSession()->get('user_id');
144
-		});
145
-
146
-		$this->registerService('WebRoot', function ($c) {
147
-			return $c->query('ServerContainer')->getWebRoot();
148
-		});
149
-
150
-		$this->registerService('fromMailAddress', function() {
151
-			return Util::getDefaultEmailAddress('no-reply');
152
-		});
153
-
154
-		$this->registerService('OC_Defaults', function ($c) {
155
-			return $c->getServer()->getThemingDefaults();
156
-		});
157
-
158
-		$this->registerService('OCP\Encryption\IManager', function ($c) {
159
-			return $this->getServer()->getEncryptionManager();
160
-		});
161
-
162
-		$this->registerService(IValidator::class, function($c) {
163
-			return $c->query(Validator::class);
164
-		});
165
-
166
-		$this->registerService(\OC\Security\IdentityProof\Manager::class, function ($c) {
167
-			return new \OC\Security\IdentityProof\Manager(
168
-				$this->getServer()->getAppDataDir('identityproof'),
169
-				$this->getServer()->getCrypto()
170
-			);
171
-		});
172
-
173
-		$this->registerService(IShareHelper::class, function (SimpleContainer $c) {
174
-			return $c->query(IShareHelper::class);
175
-		});
176
-
177
-
178
-		/**
179
-		 * App Framework APIs
180
-		 */
181
-		$this->registerService('API', function($c){
182
-			$c->query('OCP\\ILogger')->debug(
183
-				'Accessing the API class is deprecated! Use the appropriate ' .
184
-				'services instead!'
185
-			);
186
-			return new API($c['AppName']);
187
-		});
188
-
189
-		$this->registerService('Protocol', function($c){
190
-			/** @var \OC\Server $server */
191
-			$server = $c->query('ServerContainer');
192
-			$protocol = $server->getRequest()->getHttpProtocol();
193
-			return new Http($_SERVER, $protocol);
194
-		});
195
-
196
-		$this->registerService('Dispatcher', function($c) {
197
-			return new Dispatcher(
198
-				$c['Protocol'],
199
-				$c['MiddlewareDispatcher'],
200
-				$c['ControllerMethodReflector'],
201
-				$c['Request']
202
-			);
203
-		});
204
-
205
-		/**
206
-		 * App Framework default arguments
207
-		 */
208
-		$this->registerParameter('corsMethods', 'PUT, POST, GET, DELETE, PATCH');
209
-		$this->registerParameter('corsAllowedHeaders', 'Authorization, Content-Type, Accept');
210
-		$this->registerParameter('corsMaxAge', 1728000);
211
-
212
-		/**
213
-		 * Middleware
214
-		 */
215
-		$app = $this;
216
-		$this->registerService('SecurityMiddleware', function($c) use ($app){
217
-			/** @var \OC\Server $server */
218
-			$server = $app->getServer();
219
-
220
-			return new SecurityMiddleware(
221
-				$c['Request'],
222
-				$c['ControllerMethodReflector'],
223
-				$server->getNavigationManager(),
224
-				$server->getURLGenerator(),
225
-				$server->getLogger(),
226
-				$server->getSession(),
227
-				$c['AppName'],
228
-				$app->isLoggedIn(),
229
-				$app->isAdminUser(),
230
-				$server->getContentSecurityPolicyManager(),
231
-				$server->getCsrfTokenManager(),
232
-				$server->getContentSecurityPolicyNonceManager(),
233
-				$server->getBruteForceThrottler()
234
-			);
235
-
236
-		});
237
-
238
-		$this->registerService('CORSMiddleware', function($c) {
239
-			return new CORSMiddleware(
240
-				$c['Request'],
241
-				$c['ControllerMethodReflector'],
242
-				$c->query(IUserSession::class),
243
-				$c->getServer()->getBruteForceThrottler()
244
-			);
245
-		});
246
-
247
-		$this->registerService('SessionMiddleware', function($c) use ($app) {
248
-			return new SessionMiddleware(
249
-				$c['Request'],
250
-				$c['ControllerMethodReflector'],
251
-				$app->getServer()->getSession()
252
-			);
253
-		});
254
-
255
-		$this->registerService('TwoFactorMiddleware', function (SimpleContainer $c) use ($app) {
256
-			$twoFactorManager = $c->getServer()->getTwoFactorAuthManager();
257
-			$userSession = $app->getServer()->getUserSession();
258
-			$session = $app->getServer()->getSession();
259
-			$urlGenerator = $app->getServer()->getURLGenerator();
260
-			$reflector = $c['ControllerMethodReflector'];
261
-			$request = $app->getServer()->getRequest();
262
-			return new TwoFactorMiddleware($twoFactorManager, $userSession, $session, $urlGenerator, $reflector, $request);
263
-		});
264
-
265
-		$this->registerService('OCSMiddleware', function (SimpleContainer $c) {
266
-			return new OCSMiddleware(
267
-				$c['Request']
268
-			);
269
-		});
270
-
271
-		$middleWares = &$this->middleWares;
272
-		$this->registerService('MiddlewareDispatcher', function($c) use (&$middleWares) {
273
-			$dispatcher = new MiddlewareDispatcher();
274
-			$dispatcher->registerMiddleware($c['CORSMiddleware']);
275
-			$dispatcher->registerMiddleware($c['OCSMiddleware']);
276
-			$dispatcher->registerMiddleware($c['SecurityMiddleware']);
277
-			$dispatcher->registerMiddleWare($c['TwoFactorMiddleware']);
278
-
279
-			foreach($middleWares as $middleWare) {
280
-				$dispatcher->registerMiddleware($c[$middleWare]);
281
-			}
282
-
283
-			$dispatcher->registerMiddleware($c['SessionMiddleware']);
284
-			return $dispatcher;
285
-		});
286
-
287
-	}
288
-
289
-
290
-	/**
291
-	 * @deprecated implements only deprecated methods
292
-	 * @return IApi
293
-	 */
294
-	function getCoreApi()
295
-	{
296
-		return $this->query('API');
297
-	}
298
-
299
-	/**
300
-	 * @return \OCP\IServerContainer
301
-	 */
302
-	function getServer()
303
-	{
304
-		return $this->server;
305
-	}
306
-
307
-	/**
308
-	 * @param string $middleWare
309
-	 * @return boolean|null
310
-	 */
311
-	function registerMiddleWare($middleWare) {
312
-		array_push($this->middleWares, $middleWare);
313
-	}
314
-
315
-	/**
316
-	 * used to return the appname of the set application
317
-	 * @return string the name of your application
318
-	 */
319
-	function getAppName() {
320
-		return $this->query('AppName');
321
-	}
322
-
323
-	/**
324
-	 * @deprecated use IUserSession->isLoggedIn()
325
-	 * @return boolean
326
-	 */
327
-	function isLoggedIn() {
328
-		return \OC::$server->getUserSession()->isLoggedIn();
329
-	}
330
-
331
-	/**
332
-	 * @deprecated use IGroupManager->isAdmin($userId)
333
-	 * @return boolean
334
-	 */
335
-	function isAdminUser() {
336
-		$uid = $this->getUserId();
337
-		return \OC_User::isAdminUser($uid);
338
-	}
339
-
340
-	private function getUserId() {
341
-		return $this->getServer()->getSession()->get('user_id');
342
-	}
343
-
344
-	/**
345
-	 * @deprecated use the ILogger instead
346
-	 * @param string $message
347
-	 * @param string $level
348
-	 * @return mixed
349
-	 */
350
-	function log($message, $level) {
351
-		switch($level){
352
-			case 'debug':
353
-				$level = \OCP\Util::DEBUG;
354
-				break;
355
-			case 'info':
356
-				$level = \OCP\Util::INFO;
357
-				break;
358
-			case 'warn':
359
-				$level = \OCP\Util::WARN;
360
-				break;
361
-			case 'fatal':
362
-				$level = \OCP\Util::FATAL;
363
-				break;
364
-			default:
365
-				$level = \OCP\Util::ERROR;
366
-				break;
367
-		}
368
-		\OCP\Util::writeLog($this->getAppName(), $message, $level);
369
-	}
370
-
371
-	/**
372
-	 * Register a capability
373
-	 *
374
-	 * @param string $serviceName e.g. 'OCA\Files\Capabilities'
375
-	 */
376
-	public function registerCapability($serviceName) {
377
-		$this->query('OC\CapabilitiesManager')->registerCapability(function() use ($serviceName) {
378
-			return $this->query($serviceName);
379
-		});
380
-	}
381
-
382
-	/**
383
-	 * @param string $name
384
-	 * @return mixed
385
-	 * @throws QueryException if the query could not be resolved
386
-	 */
387
-	public function query($name) {
388
-		try {
389
-			return $this->queryNoFallback($name);
390
-		} catch (QueryException $e) {
391
-			return $this->getServer()->query($name);
392
-		}
393
-	}
394
-
395
-	/**
396
-	 * @param string $name
397
-	 * @return mixed
398
-	 * @throws QueryException if the query could not be resolved
399
-	 */
400
-	public function queryNoFallback($name) {
401
-		$name = $this->sanitizeName($name);
402
-
403
-		if ($this->offsetExists($name)) {
404
-			return parent::query($name);
405
-		} else {
406
-			if ($this['AppName'] === 'settings' && strpos($name, 'OC\\Settings\\') === 0) {
407
-				return parent::query($name);
408
-			} else if ($this['AppName'] === 'core' && strpos($name, 'OC\\Core\\') === 0) {
409
-				return parent::query($name);
410
-			} else if (strpos($name, \OC\AppFramework\App::buildAppNamespace($this['AppName']) . '\\') === 0) {
411
-				return parent::query($name);
412
-			}
413
-		}
414
-
415
-		throw new QueryException('Could not resolve ' . $name . '!' .
416
-			' Class can not be instantiated');
417
-	}
65
+    /**
66
+     * @var array
67
+     */
68
+    private $middleWares = array();
69
+
70
+    /** @var ServerContainer */
71
+    private $server;
72
+
73
+    /**
74
+     * Put your class dependencies in here
75
+     * @param string $appName the name of the app
76
+     * @param array $urlParams
77
+     * @param ServerContainer $server
78
+     */
79
+    public function __construct($appName, $urlParams = array(), ServerContainer $server = null){
80
+        parent::__construct();
81
+        $this['AppName'] = $appName;
82
+        $this['urlParams'] = $urlParams;
83
+
84
+        /** @var \OC\ServerContainer $server */
85
+        if ($server === null) {
86
+            $server = \OC::$server;
87
+        }
88
+        $this->server = $server;
89
+        $this->server->registerAppContainer($appName, $this);
90
+
91
+        // aliases
92
+        $this->registerAlias('appName', 'AppName');
93
+        $this->registerAlias('webRoot', 'WebRoot');
94
+        $this->registerAlias('userId', 'UserId');
95
+
96
+        /**
97
+         * Core services
98
+         */
99
+        $this->registerService(IOutput::class, function($c){
100
+            return new Output($this->getServer()->getWebRoot());
101
+        });
102
+
103
+        $this->registerService(Folder::class, function() {
104
+            return $this->getServer()->getUserFolder();
105
+        });
106
+
107
+        $this->registerService(IAppData::class, function (SimpleContainer $c) {
108
+            return $this->getServer()->getAppDataDir($c->query('AppName'));
109
+        });
110
+
111
+        $this->registerService(IL10N::class, function($c) {
112
+            return $this->getServer()->getL10N($c->query('AppName'));
113
+        });
114
+
115
+        $this->registerAlias(\OCP\AppFramework\Utility\IControllerMethodReflector::class, \OC\AppFramework\Utility\ControllerMethodReflector::class);
116
+        $this->registerAlias('ControllerMethodReflector', \OCP\AppFramework\Utility\IControllerMethodReflector::class);
117
+
118
+        $this->registerService(IRequest::class, function() {
119
+            return $this->getServer()->query(IRequest::class);
120
+        });
121
+        $this->registerAlias('Request', IRequest::class);
122
+
123
+        $this->registerAlias(\OCP\AppFramework\Utility\ITimeFactory::class, \OC\AppFramework\Utility\TimeFactory::class);
124
+        $this->registerAlias('TimeFactory', \OCP\AppFramework\Utility\ITimeFactory::class);
125
+
126
+        $this->registerAlias(\OC\User\Session::class, \OCP\IUserSession::class);
127
+
128
+        $this->registerService(IServerContainer::class, function ($c) {
129
+            return $this->getServer();
130
+        });
131
+        $this->registerAlias('ServerContainer', IServerContainer::class);
132
+
133
+        $this->registerService(\OCP\WorkflowEngine\IManager::class, function ($c) {
134
+            return $c->query('OCA\WorkflowEngine\Manager');
135
+        });
136
+
137
+        $this->registerService(\OCP\AppFramework\IAppContainer::class, function ($c) {
138
+            return $c;
139
+        });
140
+
141
+        // commonly used attributes
142
+        $this->registerService('UserId', function ($c) {
143
+            return $c->query('OCP\\IUserSession')->getSession()->get('user_id');
144
+        });
145
+
146
+        $this->registerService('WebRoot', function ($c) {
147
+            return $c->query('ServerContainer')->getWebRoot();
148
+        });
149
+
150
+        $this->registerService('fromMailAddress', function() {
151
+            return Util::getDefaultEmailAddress('no-reply');
152
+        });
153
+
154
+        $this->registerService('OC_Defaults', function ($c) {
155
+            return $c->getServer()->getThemingDefaults();
156
+        });
157
+
158
+        $this->registerService('OCP\Encryption\IManager', function ($c) {
159
+            return $this->getServer()->getEncryptionManager();
160
+        });
161
+
162
+        $this->registerService(IValidator::class, function($c) {
163
+            return $c->query(Validator::class);
164
+        });
165
+
166
+        $this->registerService(\OC\Security\IdentityProof\Manager::class, function ($c) {
167
+            return new \OC\Security\IdentityProof\Manager(
168
+                $this->getServer()->getAppDataDir('identityproof'),
169
+                $this->getServer()->getCrypto()
170
+            );
171
+        });
172
+
173
+        $this->registerService(IShareHelper::class, function (SimpleContainer $c) {
174
+            return $c->query(IShareHelper::class);
175
+        });
176
+
177
+
178
+        /**
179
+         * App Framework APIs
180
+         */
181
+        $this->registerService('API', function($c){
182
+            $c->query('OCP\\ILogger')->debug(
183
+                'Accessing the API class is deprecated! Use the appropriate ' .
184
+                'services instead!'
185
+            );
186
+            return new API($c['AppName']);
187
+        });
188
+
189
+        $this->registerService('Protocol', function($c){
190
+            /** @var \OC\Server $server */
191
+            $server = $c->query('ServerContainer');
192
+            $protocol = $server->getRequest()->getHttpProtocol();
193
+            return new Http($_SERVER, $protocol);
194
+        });
195
+
196
+        $this->registerService('Dispatcher', function($c) {
197
+            return new Dispatcher(
198
+                $c['Protocol'],
199
+                $c['MiddlewareDispatcher'],
200
+                $c['ControllerMethodReflector'],
201
+                $c['Request']
202
+            );
203
+        });
204
+
205
+        /**
206
+         * App Framework default arguments
207
+         */
208
+        $this->registerParameter('corsMethods', 'PUT, POST, GET, DELETE, PATCH');
209
+        $this->registerParameter('corsAllowedHeaders', 'Authorization, Content-Type, Accept');
210
+        $this->registerParameter('corsMaxAge', 1728000);
211
+
212
+        /**
213
+         * Middleware
214
+         */
215
+        $app = $this;
216
+        $this->registerService('SecurityMiddleware', function($c) use ($app){
217
+            /** @var \OC\Server $server */
218
+            $server = $app->getServer();
219
+
220
+            return new SecurityMiddleware(
221
+                $c['Request'],
222
+                $c['ControllerMethodReflector'],
223
+                $server->getNavigationManager(),
224
+                $server->getURLGenerator(),
225
+                $server->getLogger(),
226
+                $server->getSession(),
227
+                $c['AppName'],
228
+                $app->isLoggedIn(),
229
+                $app->isAdminUser(),
230
+                $server->getContentSecurityPolicyManager(),
231
+                $server->getCsrfTokenManager(),
232
+                $server->getContentSecurityPolicyNonceManager(),
233
+                $server->getBruteForceThrottler()
234
+            );
235
+
236
+        });
237
+
238
+        $this->registerService('CORSMiddleware', function($c) {
239
+            return new CORSMiddleware(
240
+                $c['Request'],
241
+                $c['ControllerMethodReflector'],
242
+                $c->query(IUserSession::class),
243
+                $c->getServer()->getBruteForceThrottler()
244
+            );
245
+        });
246
+
247
+        $this->registerService('SessionMiddleware', function($c) use ($app) {
248
+            return new SessionMiddleware(
249
+                $c['Request'],
250
+                $c['ControllerMethodReflector'],
251
+                $app->getServer()->getSession()
252
+            );
253
+        });
254
+
255
+        $this->registerService('TwoFactorMiddleware', function (SimpleContainer $c) use ($app) {
256
+            $twoFactorManager = $c->getServer()->getTwoFactorAuthManager();
257
+            $userSession = $app->getServer()->getUserSession();
258
+            $session = $app->getServer()->getSession();
259
+            $urlGenerator = $app->getServer()->getURLGenerator();
260
+            $reflector = $c['ControllerMethodReflector'];
261
+            $request = $app->getServer()->getRequest();
262
+            return new TwoFactorMiddleware($twoFactorManager, $userSession, $session, $urlGenerator, $reflector, $request);
263
+        });
264
+
265
+        $this->registerService('OCSMiddleware', function (SimpleContainer $c) {
266
+            return new OCSMiddleware(
267
+                $c['Request']
268
+            );
269
+        });
270
+
271
+        $middleWares = &$this->middleWares;
272
+        $this->registerService('MiddlewareDispatcher', function($c) use (&$middleWares) {
273
+            $dispatcher = new MiddlewareDispatcher();
274
+            $dispatcher->registerMiddleware($c['CORSMiddleware']);
275
+            $dispatcher->registerMiddleware($c['OCSMiddleware']);
276
+            $dispatcher->registerMiddleware($c['SecurityMiddleware']);
277
+            $dispatcher->registerMiddleWare($c['TwoFactorMiddleware']);
278
+
279
+            foreach($middleWares as $middleWare) {
280
+                $dispatcher->registerMiddleware($c[$middleWare]);
281
+            }
282
+
283
+            $dispatcher->registerMiddleware($c['SessionMiddleware']);
284
+            return $dispatcher;
285
+        });
286
+
287
+    }
288
+
289
+
290
+    /**
291
+     * @deprecated implements only deprecated methods
292
+     * @return IApi
293
+     */
294
+    function getCoreApi()
295
+    {
296
+        return $this->query('API');
297
+    }
298
+
299
+    /**
300
+     * @return \OCP\IServerContainer
301
+     */
302
+    function getServer()
303
+    {
304
+        return $this->server;
305
+    }
306
+
307
+    /**
308
+     * @param string $middleWare
309
+     * @return boolean|null
310
+     */
311
+    function registerMiddleWare($middleWare) {
312
+        array_push($this->middleWares, $middleWare);
313
+    }
314
+
315
+    /**
316
+     * used to return the appname of the set application
317
+     * @return string the name of your application
318
+     */
319
+    function getAppName() {
320
+        return $this->query('AppName');
321
+    }
322
+
323
+    /**
324
+     * @deprecated use IUserSession->isLoggedIn()
325
+     * @return boolean
326
+     */
327
+    function isLoggedIn() {
328
+        return \OC::$server->getUserSession()->isLoggedIn();
329
+    }
330
+
331
+    /**
332
+     * @deprecated use IGroupManager->isAdmin($userId)
333
+     * @return boolean
334
+     */
335
+    function isAdminUser() {
336
+        $uid = $this->getUserId();
337
+        return \OC_User::isAdminUser($uid);
338
+    }
339
+
340
+    private function getUserId() {
341
+        return $this->getServer()->getSession()->get('user_id');
342
+    }
343
+
344
+    /**
345
+     * @deprecated use the ILogger instead
346
+     * @param string $message
347
+     * @param string $level
348
+     * @return mixed
349
+     */
350
+    function log($message, $level) {
351
+        switch($level){
352
+            case 'debug':
353
+                $level = \OCP\Util::DEBUG;
354
+                break;
355
+            case 'info':
356
+                $level = \OCP\Util::INFO;
357
+                break;
358
+            case 'warn':
359
+                $level = \OCP\Util::WARN;
360
+                break;
361
+            case 'fatal':
362
+                $level = \OCP\Util::FATAL;
363
+                break;
364
+            default:
365
+                $level = \OCP\Util::ERROR;
366
+                break;
367
+        }
368
+        \OCP\Util::writeLog($this->getAppName(), $message, $level);
369
+    }
370
+
371
+    /**
372
+     * Register a capability
373
+     *
374
+     * @param string $serviceName e.g. 'OCA\Files\Capabilities'
375
+     */
376
+    public function registerCapability($serviceName) {
377
+        $this->query('OC\CapabilitiesManager')->registerCapability(function() use ($serviceName) {
378
+            return $this->query($serviceName);
379
+        });
380
+    }
381
+
382
+    /**
383
+     * @param string $name
384
+     * @return mixed
385
+     * @throws QueryException if the query could not be resolved
386
+     */
387
+    public function query($name) {
388
+        try {
389
+            return $this->queryNoFallback($name);
390
+        } catch (QueryException $e) {
391
+            return $this->getServer()->query($name);
392
+        }
393
+    }
394
+
395
+    /**
396
+     * @param string $name
397
+     * @return mixed
398
+     * @throws QueryException if the query could not be resolved
399
+     */
400
+    public function queryNoFallback($name) {
401
+        $name = $this->sanitizeName($name);
402
+
403
+        if ($this->offsetExists($name)) {
404
+            return parent::query($name);
405
+        } else {
406
+            if ($this['AppName'] === 'settings' && strpos($name, 'OC\\Settings\\') === 0) {
407
+                return parent::query($name);
408
+            } else if ($this['AppName'] === 'core' && strpos($name, 'OC\\Core\\') === 0) {
409
+                return parent::query($name);
410
+            } else if (strpos($name, \OC\AppFramework\App::buildAppNamespace($this['AppName']) . '\\') === 0) {
411
+                return parent::query($name);
412
+            }
413
+        }
414
+
415
+        throw new QueryException('Could not resolve ' . $name . '!' .
416
+            ' Class can not be instantiated');
417
+    }
418 418
 }
Please login to merge, or discard this patch.
Spacing   +21 added lines, -21 removed lines patch added patch discarded remove patch
@@ -76,7 +76,7 @@  discard block
 block discarded – undo
76 76
 	 * @param array $urlParams
77 77
 	 * @param ServerContainer $server
78 78
 	 */
79
-	public function __construct($appName, $urlParams = array(), ServerContainer $server = null){
79
+	public function __construct($appName, $urlParams = array(), ServerContainer $server = null) {
80 80
 		parent::__construct();
81 81
 		$this['AppName'] = $appName;
82 82
 		$this['urlParams'] = $urlParams;
@@ -96,7 +96,7 @@  discard block
 block discarded – undo
96 96
 		/**
97 97
 		 * Core services
98 98
 		 */
99
-		$this->registerService(IOutput::class, function($c){
99
+		$this->registerService(IOutput::class, function($c) {
100 100
 			return new Output($this->getServer()->getWebRoot());
101 101
 		});
102 102
 
@@ -104,7 +104,7 @@  discard block
 block discarded – undo
104 104
 			return $this->getServer()->getUserFolder();
105 105
 		});
106 106
 
107
-		$this->registerService(IAppData::class, function (SimpleContainer $c) {
107
+		$this->registerService(IAppData::class, function(SimpleContainer $c) {
108 108
 			return $this->getServer()->getAppDataDir($c->query('AppName'));
109 109
 		});
110 110
 
@@ -125,25 +125,25 @@  discard block
 block discarded – undo
125 125
 
126 126
 		$this->registerAlias(\OC\User\Session::class, \OCP\IUserSession::class);
127 127
 
128
-		$this->registerService(IServerContainer::class, function ($c) {
128
+		$this->registerService(IServerContainer::class, function($c) {
129 129
 			return $this->getServer();
130 130
 		});
131 131
 		$this->registerAlias('ServerContainer', IServerContainer::class);
132 132
 
133
-		$this->registerService(\OCP\WorkflowEngine\IManager::class, function ($c) {
133
+		$this->registerService(\OCP\WorkflowEngine\IManager::class, function($c) {
134 134
 			return $c->query('OCA\WorkflowEngine\Manager');
135 135
 		});
136 136
 
137
-		$this->registerService(\OCP\AppFramework\IAppContainer::class, function ($c) {
137
+		$this->registerService(\OCP\AppFramework\IAppContainer::class, function($c) {
138 138
 			return $c;
139 139
 		});
140 140
 
141 141
 		// commonly used attributes
142
-		$this->registerService('UserId', function ($c) {
142
+		$this->registerService('UserId', function($c) {
143 143
 			return $c->query('OCP\\IUserSession')->getSession()->get('user_id');
144 144
 		});
145 145
 
146
-		$this->registerService('WebRoot', function ($c) {
146
+		$this->registerService('WebRoot', function($c) {
147 147
 			return $c->query('ServerContainer')->getWebRoot();
148 148
 		});
149 149
 
@@ -151,11 +151,11 @@  discard block
 block discarded – undo
151 151
 			return Util::getDefaultEmailAddress('no-reply');
152 152
 		});
153 153
 
154
-		$this->registerService('OC_Defaults', function ($c) {
154
+		$this->registerService('OC_Defaults', function($c) {
155 155
 			return $c->getServer()->getThemingDefaults();
156 156
 		});
157 157
 
158
-		$this->registerService('OCP\Encryption\IManager', function ($c) {
158
+		$this->registerService('OCP\Encryption\IManager', function($c) {
159 159
 			return $this->getServer()->getEncryptionManager();
160 160
 		});
161 161
 
@@ -163,14 +163,14 @@  discard block
 block discarded – undo
163 163
 			return $c->query(Validator::class);
164 164
 		});
165 165
 
166
-		$this->registerService(\OC\Security\IdentityProof\Manager::class, function ($c) {
166
+		$this->registerService(\OC\Security\IdentityProof\Manager::class, function($c) {
167 167
 			return new \OC\Security\IdentityProof\Manager(
168 168
 				$this->getServer()->getAppDataDir('identityproof'),
169 169
 				$this->getServer()->getCrypto()
170 170
 			);
171 171
 		});
172 172
 
173
-		$this->registerService(IShareHelper::class, function (SimpleContainer $c) {
173
+		$this->registerService(IShareHelper::class, function(SimpleContainer $c) {
174 174
 			return $c->query(IShareHelper::class);
175 175
 		});
176 176
 
@@ -178,15 +178,15 @@  discard block
 block discarded – undo
178 178
 		/**
179 179
 		 * App Framework APIs
180 180
 		 */
181
-		$this->registerService('API', function($c){
181
+		$this->registerService('API', function($c) {
182 182
 			$c->query('OCP\\ILogger')->debug(
183
-				'Accessing the API class is deprecated! Use the appropriate ' .
183
+				'Accessing the API class is deprecated! Use the appropriate '.
184 184
 				'services instead!'
185 185
 			);
186 186
 			return new API($c['AppName']);
187 187
 		});
188 188
 
189
-		$this->registerService('Protocol', function($c){
189
+		$this->registerService('Protocol', function($c) {
190 190
 			/** @var \OC\Server $server */
191 191
 			$server = $c->query('ServerContainer');
192 192
 			$protocol = $server->getRequest()->getHttpProtocol();
@@ -252,7 +252,7 @@  discard block
 block discarded – undo
252 252
 			);
253 253
 		});
254 254
 
255
-		$this->registerService('TwoFactorMiddleware', function (SimpleContainer $c) use ($app) {
255
+		$this->registerService('TwoFactorMiddleware', function(SimpleContainer $c) use ($app) {
256 256
 			$twoFactorManager = $c->getServer()->getTwoFactorAuthManager();
257 257
 			$userSession = $app->getServer()->getUserSession();
258 258
 			$session = $app->getServer()->getSession();
@@ -262,7 +262,7 @@  discard block
 block discarded – undo
262 262
 			return new TwoFactorMiddleware($twoFactorManager, $userSession, $session, $urlGenerator, $reflector, $request);
263 263
 		});
264 264
 
265
-		$this->registerService('OCSMiddleware', function (SimpleContainer $c) {
265
+		$this->registerService('OCSMiddleware', function(SimpleContainer $c) {
266 266
 			return new OCSMiddleware(
267 267
 				$c['Request']
268 268
 			);
@@ -276,7 +276,7 @@  discard block
 block discarded – undo
276 276
 			$dispatcher->registerMiddleware($c['SecurityMiddleware']);
277 277
 			$dispatcher->registerMiddleWare($c['TwoFactorMiddleware']);
278 278
 
279
-			foreach($middleWares as $middleWare) {
279
+			foreach ($middleWares as $middleWare) {
280 280
 				$dispatcher->registerMiddleware($c[$middleWare]);
281 281
 			}
282 282
 
@@ -348,7 +348,7 @@  discard block
 block discarded – undo
348 348
 	 * @return mixed
349 349
 	 */
350 350
 	function log($message, $level) {
351
-		switch($level){
351
+		switch ($level) {
352 352
 			case 'debug':
353 353
 				$level = \OCP\Util::DEBUG;
354 354
 				break;
@@ -407,12 +407,12 @@  discard block
 block discarded – undo
407 407
 				return parent::query($name);
408 408
 			} else if ($this['AppName'] === 'core' && strpos($name, 'OC\\Core\\') === 0) {
409 409
 				return parent::query($name);
410
-			} else if (strpos($name, \OC\AppFramework\App::buildAppNamespace($this['AppName']) . '\\') === 0) {
410
+			} else if (strpos($name, \OC\AppFramework\App::buildAppNamespace($this['AppName']).'\\') === 0) {
411 411
 				return parent::query($name);
412 412
 			}
413 413
 		}
414 414
 
415
-		throw new QueryException('Could not resolve ' . $name . '!' .
415
+		throw new QueryException('Could not resolve '.$name.'!'.
416 416
 			' Class can not be instantiated');
417 417
 	}
418 418
 }
Please login to merge, or discard this patch.
lib/private/Share20/Manager.php 3 patches
Doc Comments   +3 added lines patch added patch discarded remove patch
@@ -1101,6 +1101,9 @@
 block discarded – undo
1101 1101
 		return $share;
1102 1102
 	}
1103 1103
 
1104
+	/**
1105
+	 * @param IShare $share
1106
+	 */
1104 1107
 	protected function checkExpireDate($share) {
1105 1108
 		if ($share->getExpirationDate() !== null &&
1106 1109
 			$share->getExpirationDate() <= new \DateTime()) {
Please login to merge, or discard this patch.
Spacing   +15 added lines, -15 removed lines patch added patch discarded remove patch
@@ -321,7 +321,7 @@  discard block
 block discarded – undo
321 321
 
322 322
 		if ($fullId === null && $expirationDate === null && $this->shareApiLinkDefaultExpireDate()) {
323 323
 			$expirationDate = new \DateTime();
324
-			$expirationDate->setTime(0,0,0);
324
+			$expirationDate->setTime(0, 0, 0);
325 325
 			$expirationDate->add(new \DateInterval('P'.$this->shareApiLinkDefaultExpireDays().'D'));
326 326
 		}
327 327
 
@@ -333,7 +333,7 @@  discard block
 block discarded – undo
333 333
 
334 334
 			$date = new \DateTime();
335 335
 			$date->setTime(0, 0, 0);
336
-			$date->add(new \DateInterval('P' . $this->shareApiLinkDefaultExpireDays() . 'D'));
336
+			$date->add(new \DateInterval('P'.$this->shareApiLinkDefaultExpireDays().'D'));
337 337
 			if ($date < $expirationDate) {
338 338
 				$message = $this->l->t('Cannot set expiration date more than %s days in the future', [$this->shareApiLinkDefaultExpireDays()]);
339 339
 				throw new GenericShareException($message, $message, 404);
@@ -386,7 +386,7 @@  discard block
 block discarded – undo
386 386
 		 */
387 387
 		$provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_USER);
388 388
 		$existingShares = $provider->getSharesByPath($share->getNode());
389
-		foreach($existingShares as $existingShare) {
389
+		foreach ($existingShares as $existingShare) {
390 390
 			// Ignore if it is the same share
391 391
 			try {
392 392
 				if ($existingShare->getFullId() === $share->getFullId()) {
@@ -443,7 +443,7 @@  discard block
 block discarded – undo
443 443
 		 */
444 444
 		$provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_GROUP);
445 445
 		$existingShares = $provider->getSharesByPath($share->getNode());
446
-		foreach($existingShares as $existingShare) {
446
+		foreach ($existingShares as $existingShare) {
447 447
 			try {
448 448
 				if ($existingShare->getFullId() === $share->getFullId()) {
449 449
 					continue;
@@ -512,7 +512,7 @@  discard block
 block discarded – undo
512 512
 		// Make sure that we do not share a path that contains a shared mountpoint
513 513
 		if ($path instanceof \OCP\Files\Folder) {
514 514
 			$mounts = $this->mountManager->findIn($path->getPath());
515
-			foreach($mounts as $mount) {
515
+			foreach ($mounts as $mount) {
516 516
 				if ($mount->getStorage()->instanceOfStorage('\OCA\Files_Sharing\ISharedStorage')) {
517 517
 					throw new \InvalidArgumentException('Path contains files shared with you');
518 518
 				}
@@ -560,7 +560,7 @@  discard block
 block discarded – undo
560 560
 		$storage = $share->getNode()->getStorage();
561 561
 		if ($storage->instanceOfStorage('OCA\Files_Sharing\External\Storage')) {
562 562
 			$parent = $share->getNode()->getParent();
563
-			while($parent->getStorage()->instanceOfStorage('OCA\Files_Sharing\External\Storage')) {
563
+			while ($parent->getStorage()->instanceOfStorage('OCA\Files_Sharing\External\Storage')) {
564 564
 				$parent = $parent->getParent();
565 565
 			}
566 566
 			$share->setShareOwner($parent->getOwner()->getUID());
@@ -617,7 +617,7 @@  discard block
 block discarded – undo
617 617
 		}
618 618
 
619 619
 		// Generate the target
620
-		$target = $this->config->getSystemValue('share_folder', '/') .'/'. $share->getNode()->getName();
620
+		$target = $this->config->getSystemValue('share_folder', '/').'/'.$share->getNode()->getName();
621 621
 		$target = \OC\Files\Filesystem::normalizePath($target);
622 622
 		$share->setTarget($target);
623 623
 
@@ -864,7 +864,7 @@  discard block
 block discarded – undo
864 864
 	 * @param string $recipientId
865 865
 	 */
866 866
 	public function deleteFromSelf(\OCP\Share\IShare $share, $recipientId) {
867
-		list($providerId, ) = $this->splitFullId($share->getFullId());
867
+		list($providerId,) = $this->splitFullId($share->getFullId());
868 868
 		$provider = $this->factory->getProvider($providerId);
869 869
 
870 870
 		$provider->deleteFromSelf($share, $recipientId);
@@ -885,7 +885,7 @@  discard block
 block discarded – undo
885 885
 		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
886 886
 			$sharedWith = $this->groupManager->get($share->getSharedWith());
887 887
 			if (is_null($sharedWith)) {
888
-				throw new \InvalidArgumentException('Group "' . $share->getSharedWith() . '" does not exist');
888
+				throw new \InvalidArgumentException('Group "'.$share->getSharedWith().'" does not exist');
889 889
 			}
890 890
 			$recipient = $this->userManager->get($recipientId);
891 891
 			if (!$sharedWith->inGroup($recipient)) {
@@ -893,7 +893,7 @@  discard block
 block discarded – undo
893 893
 			}
894 894
 		}
895 895
 
896
-		list($providerId, ) = $this->splitFullId($share->getFullId());
896
+		list($providerId,) = $this->splitFullId($share->getFullId());
897 897
 		$provider = $this->factory->getProvider($providerId);
898 898
 
899 899
 		$provider->move($share, $recipientId);
@@ -940,7 +940,7 @@  discard block
 block discarded – undo
940 940
 
941 941
 		$shares2 = [];
942 942
 
943
-		while(true) {
943
+		while (true) {
944 944
 			$added = 0;
945 945
 			foreach ($shares as $share) {
946 946
 
@@ -1040,7 +1040,7 @@  discard block
 block discarded – undo
1040 1040
 	 *
1041 1041
 	 * @return Share[]
1042 1042
 	 */
1043
-	public function getSharesByPath(\OCP\Files\Node $path, $page=0, $perPage=50) {
1043
+	public function getSharesByPath(\OCP\Files\Node $path, $page = 0, $perPage = 50) {
1044 1044
 		return [];
1045 1045
 	}
1046 1046
 
@@ -1055,7 +1055,7 @@  discard block
 block discarded – undo
1055 1055
 	public function getShareByToken($token) {
1056 1056
 		$share = null;
1057 1057
 		try {
1058
-			if($this->shareApiAllowLinks()) {
1058
+			if ($this->shareApiAllowLinks()) {
1059 1059
 				$provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_LINK);
1060 1060
 				$share = $provider->getShareByToken($token);
1061 1061
 			}
@@ -1227,7 +1227,7 @@  discard block
 block discarded – undo
1227 1227
 		list(,,,$ownerPath) = explode('/', $ownerPath, 4);
1228 1228
 		$al['users'][$owner] = [
1229 1229
 			'node_id' => $path->getId(),
1230
-			'node_path' => '/' . $ownerPath,
1230
+			'node_path' => '/'.$ownerPath,
1231 1231
 		];
1232 1232
 
1233 1233
 		// Collect all the shares
@@ -1318,7 +1318,7 @@  discard block
 block discarded – undo
1318 1318
 	 * @return int
1319 1319
 	 */
1320 1320
 	public function shareApiLinkDefaultExpireDays() {
1321
-		return (int)$this->config->getAppValue('core', 'shareapi_expire_after_n_days', '7');
1321
+		return (int) $this->config->getAppValue('core', 'shareapi_expire_after_n_days', '7');
1322 1322
 	}
1323 1323
 
1324 1324
 	/**
Please login to merge, or discard this patch.
Indentation   +1345 added lines, -1345 removed lines patch added patch discarded remove patch
@@ -58,1373 +58,1373 @@
 block discarded – undo
58 58
  */
59 59
 class Manager implements IManager {
60 60
 
61
-	/** @var IProviderFactory */
62
-	private $factory;
63
-	/** @var ILogger */
64
-	private $logger;
65
-	/** @var IConfig */
66
-	private $config;
67
-	/** @var ISecureRandom */
68
-	private $secureRandom;
69
-	/** @var IHasher */
70
-	private $hasher;
71
-	/** @var IMountManager */
72
-	private $mountManager;
73
-	/** @var IGroupManager */
74
-	private $groupManager;
75
-	/** @var IL10N */
76
-	private $l;
77
-	/** @var IUserManager */
78
-	private $userManager;
79
-	/** @var IRootFolder */
80
-	private $rootFolder;
81
-	/** @var CappedMemoryCache */
82
-	private $sharingDisabledForUsersCache;
83
-	/** @var EventDispatcher */
84
-	private $eventDispatcher;
85
-	/** @var LegacyHooks */
86
-	private $legacyHooks;
87
-
88
-
89
-	/**
90
-	 * Manager constructor.
91
-	 *
92
-	 * @param ILogger $logger
93
-	 * @param IConfig $config
94
-	 * @param ISecureRandom $secureRandom
95
-	 * @param IHasher $hasher
96
-	 * @param IMountManager $mountManager
97
-	 * @param IGroupManager $groupManager
98
-	 * @param IL10N $l
99
-	 * @param IProviderFactory $factory
100
-	 * @param IUserManager $userManager
101
-	 * @param IRootFolder $rootFolder
102
-	 * @param EventDispatcher $eventDispatcher
103
-	 */
104
-	public function __construct(
105
-			ILogger $logger,
106
-			IConfig $config,
107
-			ISecureRandom $secureRandom,
108
-			IHasher $hasher,
109
-			IMountManager $mountManager,
110
-			IGroupManager $groupManager,
111
-			IL10N $l,
112
-			IProviderFactory $factory,
113
-			IUserManager $userManager,
114
-			IRootFolder $rootFolder,
115
-			EventDispatcher $eventDispatcher
116
-	) {
117
-		$this->logger = $logger;
118
-		$this->config = $config;
119
-		$this->secureRandom = $secureRandom;
120
-		$this->hasher = $hasher;
121
-		$this->mountManager = $mountManager;
122
-		$this->groupManager = $groupManager;
123
-		$this->l = $l;
124
-		$this->factory = $factory;
125
-		$this->userManager = $userManager;
126
-		$this->rootFolder = $rootFolder;
127
-		$this->eventDispatcher = $eventDispatcher;
128
-		$this->sharingDisabledForUsersCache = new CappedMemoryCache();
129
-		$this->legacyHooks = new LegacyHooks($this->eventDispatcher);
130
-	}
131
-
132
-	/**
133
-	 * Convert from a full share id to a tuple (providerId, shareId)
134
-	 *
135
-	 * @param string $id
136
-	 * @return string[]
137
-	 */
138
-	private function splitFullId($id) {
139
-		return explode(':', $id, 2);
140
-	}
141
-
142
-	/**
143
-	 * Verify if a password meets all requirements
144
-	 *
145
-	 * @param string $password
146
-	 * @throws \Exception
147
-	 */
148
-	protected function verifyPassword($password) {
149
-		if ($password === null) {
150
-			// No password is set, check if this is allowed.
151
-			if ($this->shareApiLinkEnforcePassword()) {
152
-				throw new \InvalidArgumentException('Passwords are enforced for link shares');
153
-			}
154
-
155
-			return;
156
-		}
157
-
158
-		// Let others verify the password
159
-		try {
160
-			$event = new GenericEvent($password);
161
-			$this->eventDispatcher->dispatch('OCP\PasswordPolicy::validate', $event);
162
-		} catch (HintException $e) {
163
-			throw new \Exception($e->getHint());
164
-		}
165
-	}
166
-
167
-	/**
168
-	 * Check for generic requirements before creating a share
169
-	 *
170
-	 * @param \OCP\Share\IShare $share
171
-	 * @throws \InvalidArgumentException
172
-	 * @throws GenericShareException
173
-	 */
174
-	protected function generalCreateChecks(\OCP\Share\IShare $share) {
175
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
176
-			// We expect a valid user as sharedWith for user shares
177
-			if (!$this->userManager->userExists($share->getSharedWith())) {
178
-				throw new \InvalidArgumentException('SharedWith is not a valid user');
179
-			}
180
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
181
-			// We expect a valid group as sharedWith for group shares
182
-			if (!$this->groupManager->groupExists($share->getSharedWith())) {
183
-				throw new \InvalidArgumentException('SharedWith is not a valid group');
184
-			}
185
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
186
-			if ($share->getSharedWith() !== null) {
187
-				throw new \InvalidArgumentException('SharedWith should be empty');
188
-			}
189
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_REMOTE) {
190
-			if ($share->getSharedWith() === null) {
191
-				throw new \InvalidArgumentException('SharedWith should not be empty');
192
-			}
193
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_EMAIL) {
194
-			if ($share->getSharedWith() === null) {
195
-				throw new \InvalidArgumentException('SharedWith should not be empty');
196
-			}
197
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_CIRCLE) {
198
-			$circle = \OCA\Circles\Api\Circles::detailsCircle($share->getSharedWith());
199
-			if ($circle === null) {
200
-				throw new \InvalidArgumentException('SharedWith is not a valid circle');
201
-			}
202
-		} else {
203
-			// We can't handle other types yet
204
-			throw new \InvalidArgumentException('unknown share type');
205
-		}
206
-
207
-		// Verify the initiator of the share is set
208
-		if ($share->getSharedBy() === null) {
209
-			throw new \InvalidArgumentException('SharedBy should be set');
210
-		}
211
-
212
-		// Cannot share with yourself
213
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER &&
214
-			$share->getSharedWith() === $share->getSharedBy()) {
215
-			throw new \InvalidArgumentException('Can\'t share with yourself');
216
-		}
217
-
218
-		// The path should be set
219
-		if ($share->getNode() === null) {
220
-			throw new \InvalidArgumentException('Path should be set');
221
-		}
222
-
223
-		// And it should be a file or a folder
224
-		if (!($share->getNode() instanceof \OCP\Files\File) &&
225
-				!($share->getNode() instanceof \OCP\Files\Folder)) {
226
-			throw new \InvalidArgumentException('Path should be either a file or a folder');
227
-		}
228
-
229
-		// And you can't share your rootfolder
230
-		if ($this->userManager->userExists($share->getSharedBy())) {
231
-			$sharedPath = $this->rootFolder->getUserFolder($share->getSharedBy())->getPath();
232
-		} else {
233
-			$sharedPath = $this->rootFolder->getUserFolder($share->getShareOwner())->getPath();
234
-		}
235
-		if ($sharedPath === $share->getNode()->getPath()) {
236
-			throw new \InvalidArgumentException('You can\'t share your root folder');
237
-		}
238
-
239
-		// Check if we actually have share permissions
240
-		if (!$share->getNode()->isShareable()) {
241
-			$message_t = $this->l->t('You are not allowed to share %s', [$share->getNode()->getPath()]);
242
-			throw new GenericShareException($message_t, $message_t, 404);
243
-		}
244
-
245
-		// Permissions should be set
246
-		if ($share->getPermissions() === null) {
247
-			throw new \InvalidArgumentException('A share requires permissions');
248
-		}
249
-
250
-		/*
61
+    /** @var IProviderFactory */
62
+    private $factory;
63
+    /** @var ILogger */
64
+    private $logger;
65
+    /** @var IConfig */
66
+    private $config;
67
+    /** @var ISecureRandom */
68
+    private $secureRandom;
69
+    /** @var IHasher */
70
+    private $hasher;
71
+    /** @var IMountManager */
72
+    private $mountManager;
73
+    /** @var IGroupManager */
74
+    private $groupManager;
75
+    /** @var IL10N */
76
+    private $l;
77
+    /** @var IUserManager */
78
+    private $userManager;
79
+    /** @var IRootFolder */
80
+    private $rootFolder;
81
+    /** @var CappedMemoryCache */
82
+    private $sharingDisabledForUsersCache;
83
+    /** @var EventDispatcher */
84
+    private $eventDispatcher;
85
+    /** @var LegacyHooks */
86
+    private $legacyHooks;
87
+
88
+
89
+    /**
90
+     * Manager constructor.
91
+     *
92
+     * @param ILogger $logger
93
+     * @param IConfig $config
94
+     * @param ISecureRandom $secureRandom
95
+     * @param IHasher $hasher
96
+     * @param IMountManager $mountManager
97
+     * @param IGroupManager $groupManager
98
+     * @param IL10N $l
99
+     * @param IProviderFactory $factory
100
+     * @param IUserManager $userManager
101
+     * @param IRootFolder $rootFolder
102
+     * @param EventDispatcher $eventDispatcher
103
+     */
104
+    public function __construct(
105
+            ILogger $logger,
106
+            IConfig $config,
107
+            ISecureRandom $secureRandom,
108
+            IHasher $hasher,
109
+            IMountManager $mountManager,
110
+            IGroupManager $groupManager,
111
+            IL10N $l,
112
+            IProviderFactory $factory,
113
+            IUserManager $userManager,
114
+            IRootFolder $rootFolder,
115
+            EventDispatcher $eventDispatcher
116
+    ) {
117
+        $this->logger = $logger;
118
+        $this->config = $config;
119
+        $this->secureRandom = $secureRandom;
120
+        $this->hasher = $hasher;
121
+        $this->mountManager = $mountManager;
122
+        $this->groupManager = $groupManager;
123
+        $this->l = $l;
124
+        $this->factory = $factory;
125
+        $this->userManager = $userManager;
126
+        $this->rootFolder = $rootFolder;
127
+        $this->eventDispatcher = $eventDispatcher;
128
+        $this->sharingDisabledForUsersCache = new CappedMemoryCache();
129
+        $this->legacyHooks = new LegacyHooks($this->eventDispatcher);
130
+    }
131
+
132
+    /**
133
+     * Convert from a full share id to a tuple (providerId, shareId)
134
+     *
135
+     * @param string $id
136
+     * @return string[]
137
+     */
138
+    private function splitFullId($id) {
139
+        return explode(':', $id, 2);
140
+    }
141
+
142
+    /**
143
+     * Verify if a password meets all requirements
144
+     *
145
+     * @param string $password
146
+     * @throws \Exception
147
+     */
148
+    protected function verifyPassword($password) {
149
+        if ($password === null) {
150
+            // No password is set, check if this is allowed.
151
+            if ($this->shareApiLinkEnforcePassword()) {
152
+                throw new \InvalidArgumentException('Passwords are enforced for link shares');
153
+            }
154
+
155
+            return;
156
+        }
157
+
158
+        // Let others verify the password
159
+        try {
160
+            $event = new GenericEvent($password);
161
+            $this->eventDispatcher->dispatch('OCP\PasswordPolicy::validate', $event);
162
+        } catch (HintException $e) {
163
+            throw new \Exception($e->getHint());
164
+        }
165
+    }
166
+
167
+    /**
168
+     * Check for generic requirements before creating a share
169
+     *
170
+     * @param \OCP\Share\IShare $share
171
+     * @throws \InvalidArgumentException
172
+     * @throws GenericShareException
173
+     */
174
+    protected function generalCreateChecks(\OCP\Share\IShare $share) {
175
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
176
+            // We expect a valid user as sharedWith for user shares
177
+            if (!$this->userManager->userExists($share->getSharedWith())) {
178
+                throw new \InvalidArgumentException('SharedWith is not a valid user');
179
+            }
180
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
181
+            // We expect a valid group as sharedWith for group shares
182
+            if (!$this->groupManager->groupExists($share->getSharedWith())) {
183
+                throw new \InvalidArgumentException('SharedWith is not a valid group');
184
+            }
185
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
186
+            if ($share->getSharedWith() !== null) {
187
+                throw new \InvalidArgumentException('SharedWith should be empty');
188
+            }
189
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_REMOTE) {
190
+            if ($share->getSharedWith() === null) {
191
+                throw new \InvalidArgumentException('SharedWith should not be empty');
192
+            }
193
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_EMAIL) {
194
+            if ($share->getSharedWith() === null) {
195
+                throw new \InvalidArgumentException('SharedWith should not be empty');
196
+            }
197
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_CIRCLE) {
198
+            $circle = \OCA\Circles\Api\Circles::detailsCircle($share->getSharedWith());
199
+            if ($circle === null) {
200
+                throw new \InvalidArgumentException('SharedWith is not a valid circle');
201
+            }
202
+        } else {
203
+            // We can't handle other types yet
204
+            throw new \InvalidArgumentException('unknown share type');
205
+        }
206
+
207
+        // Verify the initiator of the share is set
208
+        if ($share->getSharedBy() === null) {
209
+            throw new \InvalidArgumentException('SharedBy should be set');
210
+        }
211
+
212
+        // Cannot share with yourself
213
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER &&
214
+            $share->getSharedWith() === $share->getSharedBy()) {
215
+            throw new \InvalidArgumentException('Can\'t share with yourself');
216
+        }
217
+
218
+        // The path should be set
219
+        if ($share->getNode() === null) {
220
+            throw new \InvalidArgumentException('Path should be set');
221
+        }
222
+
223
+        // And it should be a file or a folder
224
+        if (!($share->getNode() instanceof \OCP\Files\File) &&
225
+                !($share->getNode() instanceof \OCP\Files\Folder)) {
226
+            throw new \InvalidArgumentException('Path should be either a file or a folder');
227
+        }
228
+
229
+        // And you can't share your rootfolder
230
+        if ($this->userManager->userExists($share->getSharedBy())) {
231
+            $sharedPath = $this->rootFolder->getUserFolder($share->getSharedBy())->getPath();
232
+        } else {
233
+            $sharedPath = $this->rootFolder->getUserFolder($share->getShareOwner())->getPath();
234
+        }
235
+        if ($sharedPath === $share->getNode()->getPath()) {
236
+            throw new \InvalidArgumentException('You can\'t share your root folder');
237
+        }
238
+
239
+        // Check if we actually have share permissions
240
+        if (!$share->getNode()->isShareable()) {
241
+            $message_t = $this->l->t('You are not allowed to share %s', [$share->getNode()->getPath()]);
242
+            throw new GenericShareException($message_t, $message_t, 404);
243
+        }
244
+
245
+        // Permissions should be set
246
+        if ($share->getPermissions() === null) {
247
+            throw new \InvalidArgumentException('A share requires permissions');
248
+        }
249
+
250
+        /*
251 251
 		 * Quick fix for #23536
252 252
 		 * Non moveable mount points do not have update and delete permissions
253 253
 		 * while we 'most likely' do have that on the storage.
254 254
 		 */
255
-		$permissions = $share->getNode()->getPermissions();
256
-		$mount = $share->getNode()->getMountPoint();
257
-		if (!($mount instanceof MoveableMount)) {
258
-			$permissions |= \OCP\Constants::PERMISSION_DELETE | \OCP\Constants::PERMISSION_UPDATE;
259
-		}
260
-
261
-		// Check that we do not share with more permissions than we have
262
-		if ($share->getPermissions() & ~$permissions) {
263
-			$message_t = $this->l->t('Cannot increase permissions of %s', [$share->getNode()->getPath()]);
264
-			throw new GenericShareException($message_t, $message_t, 404);
265
-		}
266
-
267
-
268
-		// Check that read permissions are always set
269
-		// Link shares are allowed to have no read permissions to allow upload to hidden folders
270
-		$noReadPermissionRequired = $share->getShareType() === \OCP\Share::SHARE_TYPE_LINK
271
-			|| $share->getShareType() === \OCP\Share::SHARE_TYPE_EMAIL;
272
-		if (!$noReadPermissionRequired &&
273
-			($share->getPermissions() & \OCP\Constants::PERMISSION_READ) === 0) {
274
-			throw new \InvalidArgumentException('Shares need at least read permissions');
275
-		}
276
-
277
-		if ($share->getNode() instanceof \OCP\Files\File) {
278
-			if ($share->getPermissions() & \OCP\Constants::PERMISSION_DELETE) {
279
-				$message_t = $this->l->t('Files can\'t be shared with delete permissions');
280
-				throw new GenericShareException($message_t);
281
-			}
282
-			if ($share->getPermissions() & \OCP\Constants::PERMISSION_CREATE) {
283
-				$message_t = $this->l->t('Files can\'t be shared with create permissions');
284
-				throw new GenericShareException($message_t);
285
-			}
286
-		}
287
-	}
288
-
289
-	/**
290
-	 * Validate if the expiration date fits the system settings
291
-	 *
292
-	 * @param \OCP\Share\IShare $share The share to validate the expiration date of
293
-	 * @return \OCP\Share\IShare The modified share object
294
-	 * @throws GenericShareException
295
-	 * @throws \InvalidArgumentException
296
-	 * @throws \Exception
297
-	 */
298
-	protected function validateExpirationDate(\OCP\Share\IShare $share) {
299
-
300
-		$expirationDate = $share->getExpirationDate();
301
-
302
-		if ($expirationDate !== null) {
303
-			//Make sure the expiration date is a date
304
-			$expirationDate->setTime(0, 0, 0);
305
-
306
-			$date = new \DateTime();
307
-			$date->setTime(0, 0, 0);
308
-			if ($date >= $expirationDate) {
309
-				$message = $this->l->t('Expiration date is in the past');
310
-				throw new GenericShareException($message, $message, 404);
311
-			}
312
-		}
313
-
314
-		// If expiredate is empty set a default one if there is a default
315
-		$fullId = null;
316
-		try {
317
-			$fullId = $share->getFullId();
318
-		} catch (\UnexpectedValueException $e) {
319
-			// This is a new share
320
-		}
321
-
322
-		if ($fullId === null && $expirationDate === null && $this->shareApiLinkDefaultExpireDate()) {
323
-			$expirationDate = new \DateTime();
324
-			$expirationDate->setTime(0,0,0);
325
-			$expirationDate->add(new \DateInterval('P'.$this->shareApiLinkDefaultExpireDays().'D'));
326
-		}
327
-
328
-		// If we enforce the expiration date check that is does not exceed
329
-		if ($this->shareApiLinkDefaultExpireDateEnforced()) {
330
-			if ($expirationDate === null) {
331
-				throw new \InvalidArgumentException('Expiration date is enforced');
332
-			}
333
-
334
-			$date = new \DateTime();
335
-			$date->setTime(0, 0, 0);
336
-			$date->add(new \DateInterval('P' . $this->shareApiLinkDefaultExpireDays() . 'D'));
337
-			if ($date < $expirationDate) {
338
-				$message = $this->l->t('Cannot set expiration date more than %s days in the future', [$this->shareApiLinkDefaultExpireDays()]);
339
-				throw new GenericShareException($message, $message, 404);
340
-			}
341
-		}
342
-
343
-		$accepted = true;
344
-		$message = '';
345
-		\OCP\Util::emitHook('\OC\Share', 'verifyExpirationDate', [
346
-			'expirationDate' => &$expirationDate,
347
-			'accepted' => &$accepted,
348
-			'message' => &$message,
349
-			'passwordSet' => $share->getPassword() !== null,
350
-		]);
351
-
352
-		if (!$accepted) {
353
-			throw new \Exception($message);
354
-		}
355
-
356
-		$share->setExpirationDate($expirationDate);
357
-
358
-		return $share;
359
-	}
360
-
361
-	/**
362
-	 * Check for pre share requirements for user shares
363
-	 *
364
-	 * @param \OCP\Share\IShare $share
365
-	 * @throws \Exception
366
-	 */
367
-	protected function userCreateChecks(\OCP\Share\IShare $share) {
368
-		// Check if we can share with group members only
369
-		if ($this->shareWithGroupMembersOnly()) {
370
-			$sharedBy = $this->userManager->get($share->getSharedBy());
371
-			$sharedWith = $this->userManager->get($share->getSharedWith());
372
-			// Verify we can share with this user
373
-			$groups = array_intersect(
374
-					$this->groupManager->getUserGroupIds($sharedBy),
375
-					$this->groupManager->getUserGroupIds($sharedWith)
376
-			);
377
-			if (empty($groups)) {
378
-				throw new \Exception('Only sharing with group members is allowed');
379
-			}
380
-		}
381
-
382
-		/*
255
+        $permissions = $share->getNode()->getPermissions();
256
+        $mount = $share->getNode()->getMountPoint();
257
+        if (!($mount instanceof MoveableMount)) {
258
+            $permissions |= \OCP\Constants::PERMISSION_DELETE | \OCP\Constants::PERMISSION_UPDATE;
259
+        }
260
+
261
+        // Check that we do not share with more permissions than we have
262
+        if ($share->getPermissions() & ~$permissions) {
263
+            $message_t = $this->l->t('Cannot increase permissions of %s', [$share->getNode()->getPath()]);
264
+            throw new GenericShareException($message_t, $message_t, 404);
265
+        }
266
+
267
+
268
+        // Check that read permissions are always set
269
+        // Link shares are allowed to have no read permissions to allow upload to hidden folders
270
+        $noReadPermissionRequired = $share->getShareType() === \OCP\Share::SHARE_TYPE_LINK
271
+            || $share->getShareType() === \OCP\Share::SHARE_TYPE_EMAIL;
272
+        if (!$noReadPermissionRequired &&
273
+            ($share->getPermissions() & \OCP\Constants::PERMISSION_READ) === 0) {
274
+            throw new \InvalidArgumentException('Shares need at least read permissions');
275
+        }
276
+
277
+        if ($share->getNode() instanceof \OCP\Files\File) {
278
+            if ($share->getPermissions() & \OCP\Constants::PERMISSION_DELETE) {
279
+                $message_t = $this->l->t('Files can\'t be shared with delete permissions');
280
+                throw new GenericShareException($message_t);
281
+            }
282
+            if ($share->getPermissions() & \OCP\Constants::PERMISSION_CREATE) {
283
+                $message_t = $this->l->t('Files can\'t be shared with create permissions');
284
+                throw new GenericShareException($message_t);
285
+            }
286
+        }
287
+    }
288
+
289
+    /**
290
+     * Validate if the expiration date fits the system settings
291
+     *
292
+     * @param \OCP\Share\IShare $share The share to validate the expiration date of
293
+     * @return \OCP\Share\IShare The modified share object
294
+     * @throws GenericShareException
295
+     * @throws \InvalidArgumentException
296
+     * @throws \Exception
297
+     */
298
+    protected function validateExpirationDate(\OCP\Share\IShare $share) {
299
+
300
+        $expirationDate = $share->getExpirationDate();
301
+
302
+        if ($expirationDate !== null) {
303
+            //Make sure the expiration date is a date
304
+            $expirationDate->setTime(0, 0, 0);
305
+
306
+            $date = new \DateTime();
307
+            $date->setTime(0, 0, 0);
308
+            if ($date >= $expirationDate) {
309
+                $message = $this->l->t('Expiration date is in the past');
310
+                throw new GenericShareException($message, $message, 404);
311
+            }
312
+        }
313
+
314
+        // If expiredate is empty set a default one if there is a default
315
+        $fullId = null;
316
+        try {
317
+            $fullId = $share->getFullId();
318
+        } catch (\UnexpectedValueException $e) {
319
+            // This is a new share
320
+        }
321
+
322
+        if ($fullId === null && $expirationDate === null && $this->shareApiLinkDefaultExpireDate()) {
323
+            $expirationDate = new \DateTime();
324
+            $expirationDate->setTime(0,0,0);
325
+            $expirationDate->add(new \DateInterval('P'.$this->shareApiLinkDefaultExpireDays().'D'));
326
+        }
327
+
328
+        // If we enforce the expiration date check that is does not exceed
329
+        if ($this->shareApiLinkDefaultExpireDateEnforced()) {
330
+            if ($expirationDate === null) {
331
+                throw new \InvalidArgumentException('Expiration date is enforced');
332
+            }
333
+
334
+            $date = new \DateTime();
335
+            $date->setTime(0, 0, 0);
336
+            $date->add(new \DateInterval('P' . $this->shareApiLinkDefaultExpireDays() . 'D'));
337
+            if ($date < $expirationDate) {
338
+                $message = $this->l->t('Cannot set expiration date more than %s days in the future', [$this->shareApiLinkDefaultExpireDays()]);
339
+                throw new GenericShareException($message, $message, 404);
340
+            }
341
+        }
342
+
343
+        $accepted = true;
344
+        $message = '';
345
+        \OCP\Util::emitHook('\OC\Share', 'verifyExpirationDate', [
346
+            'expirationDate' => &$expirationDate,
347
+            'accepted' => &$accepted,
348
+            'message' => &$message,
349
+            'passwordSet' => $share->getPassword() !== null,
350
+        ]);
351
+
352
+        if (!$accepted) {
353
+            throw new \Exception($message);
354
+        }
355
+
356
+        $share->setExpirationDate($expirationDate);
357
+
358
+        return $share;
359
+    }
360
+
361
+    /**
362
+     * Check for pre share requirements for user shares
363
+     *
364
+     * @param \OCP\Share\IShare $share
365
+     * @throws \Exception
366
+     */
367
+    protected function userCreateChecks(\OCP\Share\IShare $share) {
368
+        // Check if we can share with group members only
369
+        if ($this->shareWithGroupMembersOnly()) {
370
+            $sharedBy = $this->userManager->get($share->getSharedBy());
371
+            $sharedWith = $this->userManager->get($share->getSharedWith());
372
+            // Verify we can share with this user
373
+            $groups = array_intersect(
374
+                    $this->groupManager->getUserGroupIds($sharedBy),
375
+                    $this->groupManager->getUserGroupIds($sharedWith)
376
+            );
377
+            if (empty($groups)) {
378
+                throw new \Exception('Only sharing with group members is allowed');
379
+            }
380
+        }
381
+
382
+        /*
383 383
 		 * TODO: Could be costly, fix
384 384
 		 *
385 385
 		 * Also this is not what we want in the future.. then we want to squash identical shares.
386 386
 		 */
387
-		$provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_USER);
388
-		$existingShares = $provider->getSharesByPath($share->getNode());
389
-		foreach($existingShares as $existingShare) {
390
-			// Ignore if it is the same share
391
-			try {
392
-				if ($existingShare->getFullId() === $share->getFullId()) {
393
-					continue;
394
-				}
395
-			} catch (\UnexpectedValueException $e) {
396
-				//Shares are not identical
397
-			}
398
-
399
-			// Identical share already existst
400
-			if ($existingShare->getSharedWith() === $share->getSharedWith()) {
401
-				throw new \Exception('Path already shared with this user');
402
-			}
403
-
404
-			// The share is already shared with this user via a group share
405
-			if ($existingShare->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
406
-				$group = $this->groupManager->get($existingShare->getSharedWith());
407
-				if (!is_null($group)) {
408
-					$user = $this->userManager->get($share->getSharedWith());
409
-
410
-					if ($group->inGroup($user) && $existingShare->getShareOwner() !== $share->getShareOwner()) {
411
-						throw new \Exception('Path already shared with this user');
412
-					}
413
-				}
414
-			}
415
-		}
416
-	}
417
-
418
-	/**
419
-	 * Check for pre share requirements for group shares
420
-	 *
421
-	 * @param \OCP\Share\IShare $share
422
-	 * @throws \Exception
423
-	 */
424
-	protected function groupCreateChecks(\OCP\Share\IShare $share) {
425
-		// Verify group shares are allowed
426
-		if (!$this->allowGroupSharing()) {
427
-			throw new \Exception('Group sharing is now allowed');
428
-		}
429
-
430
-		// Verify if the user can share with this group
431
-		if ($this->shareWithGroupMembersOnly()) {
432
-			$sharedBy = $this->userManager->get($share->getSharedBy());
433
-			$sharedWith = $this->groupManager->get($share->getSharedWith());
434
-			if (is_null($sharedWith) || !$sharedWith->inGroup($sharedBy)) {
435
-				throw new \Exception('Only sharing within your own groups is allowed');
436
-			}
437
-		}
438
-
439
-		/*
387
+        $provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_USER);
388
+        $existingShares = $provider->getSharesByPath($share->getNode());
389
+        foreach($existingShares as $existingShare) {
390
+            // Ignore if it is the same share
391
+            try {
392
+                if ($existingShare->getFullId() === $share->getFullId()) {
393
+                    continue;
394
+                }
395
+            } catch (\UnexpectedValueException $e) {
396
+                //Shares are not identical
397
+            }
398
+
399
+            // Identical share already existst
400
+            if ($existingShare->getSharedWith() === $share->getSharedWith()) {
401
+                throw new \Exception('Path already shared with this user');
402
+            }
403
+
404
+            // The share is already shared with this user via a group share
405
+            if ($existingShare->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
406
+                $group = $this->groupManager->get($existingShare->getSharedWith());
407
+                if (!is_null($group)) {
408
+                    $user = $this->userManager->get($share->getSharedWith());
409
+
410
+                    if ($group->inGroup($user) && $existingShare->getShareOwner() !== $share->getShareOwner()) {
411
+                        throw new \Exception('Path already shared with this user');
412
+                    }
413
+                }
414
+            }
415
+        }
416
+    }
417
+
418
+    /**
419
+     * Check for pre share requirements for group shares
420
+     *
421
+     * @param \OCP\Share\IShare $share
422
+     * @throws \Exception
423
+     */
424
+    protected function groupCreateChecks(\OCP\Share\IShare $share) {
425
+        // Verify group shares are allowed
426
+        if (!$this->allowGroupSharing()) {
427
+            throw new \Exception('Group sharing is now allowed');
428
+        }
429
+
430
+        // Verify if the user can share with this group
431
+        if ($this->shareWithGroupMembersOnly()) {
432
+            $sharedBy = $this->userManager->get($share->getSharedBy());
433
+            $sharedWith = $this->groupManager->get($share->getSharedWith());
434
+            if (is_null($sharedWith) || !$sharedWith->inGroup($sharedBy)) {
435
+                throw new \Exception('Only sharing within your own groups is allowed');
436
+            }
437
+        }
438
+
439
+        /*
440 440
 		 * TODO: Could be costly, fix
441 441
 		 *
442 442
 		 * Also this is not what we want in the future.. then we want to squash identical shares.
443 443
 		 */
444
-		$provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_GROUP);
445
-		$existingShares = $provider->getSharesByPath($share->getNode());
446
-		foreach($existingShares as $existingShare) {
447
-			try {
448
-				if ($existingShare->getFullId() === $share->getFullId()) {
449
-					continue;
450
-				}
451
-			} catch (\UnexpectedValueException $e) {
452
-				//It is a new share so just continue
453
-			}
454
-
455
-			if ($existingShare->getSharedWith() === $share->getSharedWith()) {
456
-				throw new \Exception('Path already shared with this group');
457
-			}
458
-		}
459
-	}
460
-
461
-	/**
462
-	 * Check for pre share requirements for link shares
463
-	 *
464
-	 * @param \OCP\Share\IShare $share
465
-	 * @throws \Exception
466
-	 */
467
-	protected function linkCreateChecks(\OCP\Share\IShare $share) {
468
-		// Are link shares allowed?
469
-		if (!$this->shareApiAllowLinks()) {
470
-			throw new \Exception('Link sharing not allowed');
471
-		}
472
-
473
-		// Link shares by definition can't have share permissions
474
-		if ($share->getPermissions() & \OCP\Constants::PERMISSION_SHARE) {
475
-			throw new \InvalidArgumentException('Link shares can\'t have reshare permissions');
476
-		}
477
-
478
-		// Check if public upload is allowed
479
-		if (!$this->shareApiLinkAllowPublicUpload() &&
480
-			($share->getPermissions() & (\OCP\Constants::PERMISSION_CREATE | \OCP\Constants::PERMISSION_UPDATE | \OCP\Constants::PERMISSION_DELETE))) {
481
-			throw new \InvalidArgumentException('Public upload not allowed');
482
-		}
483
-	}
484
-
485
-	/**
486
-	 * To make sure we don't get invisible link shares we set the parent
487
-	 * of a link if it is a reshare. This is a quick word around
488
-	 * until we can properly display multiple link shares in the UI
489
-	 *
490
-	 * See: https://github.com/owncloud/core/issues/22295
491
-	 *
492
-	 * FIXME: Remove once multiple link shares can be properly displayed
493
-	 *
494
-	 * @param \OCP\Share\IShare $share
495
-	 */
496
-	protected function setLinkParent(\OCP\Share\IShare $share) {
497
-
498
-		// No sense in checking if the method is not there.
499
-		if (method_exists($share, 'setParent')) {
500
-			$storage = $share->getNode()->getStorage();
501
-			if ($storage->instanceOfStorage('\OCA\Files_Sharing\ISharedStorage')) {
502
-				/** @var \OCA\Files_Sharing\SharedStorage $storage */
503
-				$share->setParent($storage->getShareId());
504
-			}
505
-		};
506
-	}
507
-
508
-	/**
509
-	 * @param File|Folder $path
510
-	 */
511
-	protected function pathCreateChecks($path) {
512
-		// Make sure that we do not share a path that contains a shared mountpoint
513
-		if ($path instanceof \OCP\Files\Folder) {
514
-			$mounts = $this->mountManager->findIn($path->getPath());
515
-			foreach($mounts as $mount) {
516
-				if ($mount->getStorage()->instanceOfStorage('\OCA\Files_Sharing\ISharedStorage')) {
517
-					throw new \InvalidArgumentException('Path contains files shared with you');
518
-				}
519
-			}
520
-		}
521
-	}
522
-
523
-	/**
524
-	 * Check if the user that is sharing can actually share
525
-	 *
526
-	 * @param \OCP\Share\IShare $share
527
-	 * @throws \Exception
528
-	 */
529
-	protected function canShare(\OCP\Share\IShare $share) {
530
-		if (!$this->shareApiEnabled()) {
531
-			throw new \Exception('The share API is disabled');
532
-		}
533
-
534
-		if ($this->sharingDisabledForUser($share->getSharedBy())) {
535
-			throw new \Exception('You are not allowed to share');
536
-		}
537
-	}
538
-
539
-	/**
540
-	 * Share a path
541
-	 *
542
-	 * @param \OCP\Share\IShare $share
543
-	 * @return Share The share object
544
-	 * @throws \Exception
545
-	 *
546
-	 * TODO: handle link share permissions or check them
547
-	 */
548
-	public function createShare(\OCP\Share\IShare $share) {
549
-		$this->canShare($share);
550
-
551
-		$this->generalCreateChecks($share);
552
-
553
-		// Verify if there are any issues with the path
554
-		$this->pathCreateChecks($share->getNode());
555
-
556
-		/*
444
+        $provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_GROUP);
445
+        $existingShares = $provider->getSharesByPath($share->getNode());
446
+        foreach($existingShares as $existingShare) {
447
+            try {
448
+                if ($existingShare->getFullId() === $share->getFullId()) {
449
+                    continue;
450
+                }
451
+            } catch (\UnexpectedValueException $e) {
452
+                //It is a new share so just continue
453
+            }
454
+
455
+            if ($existingShare->getSharedWith() === $share->getSharedWith()) {
456
+                throw new \Exception('Path already shared with this group');
457
+            }
458
+        }
459
+    }
460
+
461
+    /**
462
+     * Check for pre share requirements for link shares
463
+     *
464
+     * @param \OCP\Share\IShare $share
465
+     * @throws \Exception
466
+     */
467
+    protected function linkCreateChecks(\OCP\Share\IShare $share) {
468
+        // Are link shares allowed?
469
+        if (!$this->shareApiAllowLinks()) {
470
+            throw new \Exception('Link sharing not allowed');
471
+        }
472
+
473
+        // Link shares by definition can't have share permissions
474
+        if ($share->getPermissions() & \OCP\Constants::PERMISSION_SHARE) {
475
+            throw new \InvalidArgumentException('Link shares can\'t have reshare permissions');
476
+        }
477
+
478
+        // Check if public upload is allowed
479
+        if (!$this->shareApiLinkAllowPublicUpload() &&
480
+            ($share->getPermissions() & (\OCP\Constants::PERMISSION_CREATE | \OCP\Constants::PERMISSION_UPDATE | \OCP\Constants::PERMISSION_DELETE))) {
481
+            throw new \InvalidArgumentException('Public upload not allowed');
482
+        }
483
+    }
484
+
485
+    /**
486
+     * To make sure we don't get invisible link shares we set the parent
487
+     * of a link if it is a reshare. This is a quick word around
488
+     * until we can properly display multiple link shares in the UI
489
+     *
490
+     * See: https://github.com/owncloud/core/issues/22295
491
+     *
492
+     * FIXME: Remove once multiple link shares can be properly displayed
493
+     *
494
+     * @param \OCP\Share\IShare $share
495
+     */
496
+    protected function setLinkParent(\OCP\Share\IShare $share) {
497
+
498
+        // No sense in checking if the method is not there.
499
+        if (method_exists($share, 'setParent')) {
500
+            $storage = $share->getNode()->getStorage();
501
+            if ($storage->instanceOfStorage('\OCA\Files_Sharing\ISharedStorage')) {
502
+                /** @var \OCA\Files_Sharing\SharedStorage $storage */
503
+                $share->setParent($storage->getShareId());
504
+            }
505
+        };
506
+    }
507
+
508
+    /**
509
+     * @param File|Folder $path
510
+     */
511
+    protected function pathCreateChecks($path) {
512
+        // Make sure that we do not share a path that contains a shared mountpoint
513
+        if ($path instanceof \OCP\Files\Folder) {
514
+            $mounts = $this->mountManager->findIn($path->getPath());
515
+            foreach($mounts as $mount) {
516
+                if ($mount->getStorage()->instanceOfStorage('\OCA\Files_Sharing\ISharedStorage')) {
517
+                    throw new \InvalidArgumentException('Path contains files shared with you');
518
+                }
519
+            }
520
+        }
521
+    }
522
+
523
+    /**
524
+     * Check if the user that is sharing can actually share
525
+     *
526
+     * @param \OCP\Share\IShare $share
527
+     * @throws \Exception
528
+     */
529
+    protected function canShare(\OCP\Share\IShare $share) {
530
+        if (!$this->shareApiEnabled()) {
531
+            throw new \Exception('The share API is disabled');
532
+        }
533
+
534
+        if ($this->sharingDisabledForUser($share->getSharedBy())) {
535
+            throw new \Exception('You are not allowed to share');
536
+        }
537
+    }
538
+
539
+    /**
540
+     * Share a path
541
+     *
542
+     * @param \OCP\Share\IShare $share
543
+     * @return Share The share object
544
+     * @throws \Exception
545
+     *
546
+     * TODO: handle link share permissions or check them
547
+     */
548
+    public function createShare(\OCP\Share\IShare $share) {
549
+        $this->canShare($share);
550
+
551
+        $this->generalCreateChecks($share);
552
+
553
+        // Verify if there are any issues with the path
554
+        $this->pathCreateChecks($share->getNode());
555
+
556
+        /*
557 557
 		 * On creation of a share the owner is always the owner of the path
558 558
 		 * Except for mounted federated shares.
559 559
 		 */
560
-		$storage = $share->getNode()->getStorage();
561
-		if ($storage->instanceOfStorage('OCA\Files_Sharing\External\Storage')) {
562
-			$parent = $share->getNode()->getParent();
563
-			while($parent->getStorage()->instanceOfStorage('OCA\Files_Sharing\External\Storage')) {
564
-				$parent = $parent->getParent();
565
-			}
566
-			$share->setShareOwner($parent->getOwner()->getUID());
567
-		} else {
568
-			$share->setShareOwner($share->getNode()->getOwner()->getUID());
569
-		}
570
-
571
-		//Verify share type
572
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
573
-			$this->userCreateChecks($share);
574
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
575
-			$this->groupCreateChecks($share);
576
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
577
-			$this->linkCreateChecks($share);
578
-			$this->setLinkParent($share);
579
-
580
-			/*
560
+        $storage = $share->getNode()->getStorage();
561
+        if ($storage->instanceOfStorage('OCA\Files_Sharing\External\Storage')) {
562
+            $parent = $share->getNode()->getParent();
563
+            while($parent->getStorage()->instanceOfStorage('OCA\Files_Sharing\External\Storage')) {
564
+                $parent = $parent->getParent();
565
+            }
566
+            $share->setShareOwner($parent->getOwner()->getUID());
567
+        } else {
568
+            $share->setShareOwner($share->getNode()->getOwner()->getUID());
569
+        }
570
+
571
+        //Verify share type
572
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
573
+            $this->userCreateChecks($share);
574
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
575
+            $this->groupCreateChecks($share);
576
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
577
+            $this->linkCreateChecks($share);
578
+            $this->setLinkParent($share);
579
+
580
+            /*
581 581
 			 * For now ignore a set token.
582 582
 			 */
583
-			$share->setToken(
584
-				$this->secureRandom->generate(
585
-					\OC\Share\Constants::TOKEN_LENGTH,
586
-					\OCP\Security\ISecureRandom::CHAR_LOWER.
587
-					\OCP\Security\ISecureRandom::CHAR_UPPER.
588
-					\OCP\Security\ISecureRandom::CHAR_DIGITS
589
-				)
590
-			);
591
-
592
-			//Verify the expiration date
593
-			$this->validateExpirationDate($share);
594
-
595
-			//Verify the password
596
-			$this->verifyPassword($share->getPassword());
597
-
598
-			// If a password is set. Hash it!
599
-			if ($share->getPassword() !== null) {
600
-				$share->setPassword($this->hasher->hash($share->getPassword()));
601
-			}
602
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_EMAIL) {
603
-			$share->setToken(
604
-				$this->secureRandom->generate(
605
-					\OC\Share\Constants::TOKEN_LENGTH,
606
-					\OCP\Security\ISecureRandom::CHAR_LOWER.
607
-					\OCP\Security\ISecureRandom::CHAR_UPPER.
608
-					\OCP\Security\ISecureRandom::CHAR_DIGITS
609
-				)
610
-			);
611
-		}
612
-
613
-		// Cannot share with the owner
614
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER &&
615
-			$share->getSharedWith() === $share->getShareOwner()) {
616
-			throw new \InvalidArgumentException('Can\'t share with the share owner');
617
-		}
618
-
619
-		// Generate the target
620
-		$target = $this->config->getSystemValue('share_folder', '/') .'/'. $share->getNode()->getName();
621
-		$target = \OC\Files\Filesystem::normalizePath($target);
622
-		$share->setTarget($target);
623
-
624
-		// Pre share hook
625
-		$run = true;
626
-		$error = '';
627
-		$preHookData = [
628
-			'itemType' => $share->getNode() instanceof \OCP\Files\File ? 'file' : 'folder',
629
-			'itemSource' => $share->getNode()->getId(),
630
-			'shareType' => $share->getShareType(),
631
-			'uidOwner' => $share->getSharedBy(),
632
-			'permissions' => $share->getPermissions(),
633
-			'fileSource' => $share->getNode()->getId(),
634
-			'expiration' => $share->getExpirationDate(),
635
-			'token' => $share->getToken(),
636
-			'itemTarget' => $share->getTarget(),
637
-			'shareWith' => $share->getSharedWith(),
638
-			'run' => &$run,
639
-			'error' => &$error,
640
-		];
641
-		\OC_Hook::emit('OCP\Share', 'pre_shared', $preHookData);
642
-
643
-		if ($run === false) {
644
-			throw new \Exception($error);
645
-		}
646
-
647
-		$oldShare = $share;
648
-		$provider = $this->factory->getProviderForType($share->getShareType());
649
-		$share = $provider->create($share);
650
-		//reuse the node we already have
651
-		$share->setNode($oldShare->getNode());
652
-
653
-		// Post share hook
654
-		$postHookData = [
655
-			'itemType' => $share->getNode() instanceof \OCP\Files\File ? 'file' : 'folder',
656
-			'itemSource' => $share->getNode()->getId(),
657
-			'shareType' => $share->getShareType(),
658
-			'uidOwner' => $share->getSharedBy(),
659
-			'permissions' => $share->getPermissions(),
660
-			'fileSource' => $share->getNode()->getId(),
661
-			'expiration' => $share->getExpirationDate(),
662
-			'token' => $share->getToken(),
663
-			'id' => $share->getId(),
664
-			'shareWith' => $share->getSharedWith(),
665
-			'itemTarget' => $share->getTarget(),
666
-			'fileTarget' => $share->getTarget(),
667
-		];
668
-
669
-		\OC_Hook::emit('OCP\Share', 'post_shared', $postHookData);
670
-
671
-		return $share;
672
-	}
673
-
674
-	/**
675
-	 * Update a share
676
-	 *
677
-	 * @param \OCP\Share\IShare $share
678
-	 * @return \OCP\Share\IShare The share object
679
-	 * @throws \InvalidArgumentException
680
-	 */
681
-	public function updateShare(\OCP\Share\IShare $share) {
682
-		$expirationDateUpdated = false;
683
-
684
-		$this->canShare($share);
685
-
686
-		try {
687
-			$originalShare = $this->getShareById($share->getFullId());
688
-		} catch (\UnexpectedValueException $e) {
689
-			throw new \InvalidArgumentException('Share does not have a full id');
690
-		}
691
-
692
-		// We can't change the share type!
693
-		if ($share->getShareType() !== $originalShare->getShareType()) {
694
-			throw new \InvalidArgumentException('Can\'t change share type');
695
-		}
696
-
697
-		// We can only change the recipient on user shares
698
-		if ($share->getSharedWith() !== $originalShare->getSharedWith() &&
699
-		    $share->getShareType() !== \OCP\Share::SHARE_TYPE_USER) {
700
-			throw new \InvalidArgumentException('Can only update recipient on user shares');
701
-		}
702
-
703
-		// Cannot share with the owner
704
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER &&
705
-			$share->getSharedWith() === $share->getShareOwner()) {
706
-			throw new \InvalidArgumentException('Can\'t share with the share owner');
707
-		}
708
-
709
-		$this->generalCreateChecks($share);
710
-
711
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
712
-			$this->userCreateChecks($share);
713
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
714
-			$this->groupCreateChecks($share);
715
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
716
-			$this->linkCreateChecks($share);
717
-
718
-			// Password updated.
719
-			if ($share->getPassword() !== $originalShare->getPassword()) {
720
-				//Verify the password
721
-				$this->verifyPassword($share->getPassword());
722
-
723
-				// If a password is set. Hash it!
724
-				if ($share->getPassword() !== null) {
725
-					$share->setPassword($this->hasher->hash($share->getPassword()));
726
-				}
727
-			}
728
-
729
-			if ($share->getExpirationDate() != $originalShare->getExpirationDate()) {
730
-				//Verify the expiration date
731
-				$this->validateExpirationDate($share);
732
-				$expirationDateUpdated = true;
733
-			}
734
-		}
735
-
736
-		$plainTextPassword = null;
737
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK || $share->getShareType() === \OCP\Share::SHARE_TYPE_EMAIL) {
738
-			// Password updated.
739
-			if ($share->getPassword() !== $originalShare->getPassword()) {
740
-				//Verify the password
741
-				$this->verifyPassword($share->getPassword());
742
-
743
-				// If a password is set. Hash it!
744
-				if ($share->getPassword() !== null) {
745
-					$plainTextPassword = $share->getPassword();
746
-					$share->setPassword($this->hasher->hash($plainTextPassword));
747
-				}
748
-			}
749
-		}
750
-
751
-		$this->pathCreateChecks($share->getNode());
752
-
753
-		// Now update the share!
754
-		$provider = $this->factory->getProviderForType($share->getShareType());
755
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_EMAIL) {
756
-			$share = $provider->update($share, $plainTextPassword);
757
-		} else {
758
-			$share = $provider->update($share);
759
-		}
760
-
761
-		if ($expirationDateUpdated === true) {
762
-			\OC_Hook::emit('OCP\Share', 'post_set_expiration_date', [
763
-				'itemType' => $share->getNode() instanceof \OCP\Files\File ? 'file' : 'folder',
764
-				'itemSource' => $share->getNode()->getId(),
765
-				'date' => $share->getExpirationDate(),
766
-				'uidOwner' => $share->getSharedBy(),
767
-			]);
768
-		}
769
-
770
-		if ($share->getPassword() !== $originalShare->getPassword()) {
771
-			\OC_Hook::emit('OCP\Share', 'post_update_password', [
772
-				'itemType' => $share->getNode() instanceof \OCP\Files\File ? 'file' : 'folder',
773
-				'itemSource' => $share->getNode()->getId(),
774
-				'uidOwner' => $share->getSharedBy(),
775
-				'token' => $share->getToken(),
776
-				'disabled' => is_null($share->getPassword()),
777
-			]);
778
-		}
779
-
780
-		if ($share->getPermissions() !== $originalShare->getPermissions()) {
781
-			if ($this->userManager->userExists($share->getShareOwner())) {
782
-				$userFolder = $this->rootFolder->getUserFolder($share->getShareOwner());
783
-			} else {
784
-				$userFolder = $this->rootFolder->getUserFolder($share->getSharedBy());
785
-			}
786
-			\OC_Hook::emit('OCP\Share', 'post_update_permissions', array(
787
-				'itemType' => $share->getNode() instanceof \OCP\Files\File ? 'file' : 'folder',
788
-				'itemSource' => $share->getNode()->getId(),
789
-				'shareType' => $share->getShareType(),
790
-				'shareWith' => $share->getSharedWith(),
791
-				'uidOwner' => $share->getSharedBy(),
792
-				'permissions' => $share->getPermissions(),
793
-				'path' => $userFolder->getRelativePath($share->getNode()->getPath()),
794
-			));
795
-		}
796
-
797
-		return $share;
798
-	}
799
-
800
-	/**
801
-	 * Delete all the children of this share
802
-	 * FIXME: remove once https://github.com/owncloud/core/pull/21660 is in
803
-	 *
804
-	 * @param \OCP\Share\IShare $share
805
-	 * @return \OCP\Share\IShare[] List of deleted shares
806
-	 */
807
-	protected function deleteChildren(\OCP\Share\IShare $share) {
808
-		$deletedShares = [];
809
-
810
-		$provider = $this->factory->getProviderForType($share->getShareType());
811
-
812
-		foreach ($provider->getChildren($share) as $child) {
813
-			$deletedChildren = $this->deleteChildren($child);
814
-			$deletedShares = array_merge($deletedShares, $deletedChildren);
815
-
816
-			$provider->delete($child);
817
-			$deletedShares[] = $child;
818
-		}
819
-
820
-		return $deletedShares;
821
-	}
822
-
823
-	/**
824
-	 * Delete a share
825
-	 *
826
-	 * @param \OCP\Share\IShare $share
827
-	 * @throws ShareNotFound
828
-	 * @throws \InvalidArgumentException
829
-	 */
830
-	public function deleteShare(\OCP\Share\IShare $share) {
831
-
832
-		try {
833
-			$share->getFullId();
834
-		} catch (\UnexpectedValueException $e) {
835
-			throw new \InvalidArgumentException('Share does not have a full id');
836
-		}
837
-
838
-		$event = new GenericEvent($share);
839
-		$this->eventDispatcher->dispatch('OCP\Share::preUnshare', $event);
840
-
841
-		// Get all children and delete them as well
842
-		$deletedShares = $this->deleteChildren($share);
843
-
844
-		// Do the actual delete
845
-		$provider = $this->factory->getProviderForType($share->getShareType());
846
-		$provider->delete($share);
847
-
848
-		// All the deleted shares caused by this delete
849
-		$deletedShares[] = $share;
850
-
851
-		// Emit post hook
852
-		$event->setArgument('deletedShares', $deletedShares);
853
-		$this->eventDispatcher->dispatch('OCP\Share::postUnshare', $event);
854
-	}
855
-
856
-
857
-	/**
858
-	 * Unshare a file as the recipient.
859
-	 * This can be different from a regular delete for example when one of
860
-	 * the users in a groups deletes that share. But the provider should
861
-	 * handle this.
862
-	 *
863
-	 * @param \OCP\Share\IShare $share
864
-	 * @param string $recipientId
865
-	 */
866
-	public function deleteFromSelf(\OCP\Share\IShare $share, $recipientId) {
867
-		list($providerId, ) = $this->splitFullId($share->getFullId());
868
-		$provider = $this->factory->getProvider($providerId);
869
-
870
-		$provider->deleteFromSelf($share, $recipientId);
871
-	}
872
-
873
-	/**
874
-	 * @inheritdoc
875
-	 */
876
-	public function moveShare(\OCP\Share\IShare $share, $recipientId) {
877
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
878
-			throw new \InvalidArgumentException('Can\'t change target of link share');
879
-		}
880
-
881
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER && $share->getSharedWith() !== $recipientId) {
882
-			throw new \InvalidArgumentException('Invalid recipient');
883
-		}
884
-
885
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
886
-			$sharedWith = $this->groupManager->get($share->getSharedWith());
887
-			if (is_null($sharedWith)) {
888
-				throw new \InvalidArgumentException('Group "' . $share->getSharedWith() . '" does not exist');
889
-			}
890
-			$recipient = $this->userManager->get($recipientId);
891
-			if (!$sharedWith->inGroup($recipient)) {
892
-				throw new \InvalidArgumentException('Invalid recipient');
893
-			}
894
-		}
895
-
896
-		list($providerId, ) = $this->splitFullId($share->getFullId());
897
-		$provider = $this->factory->getProvider($providerId);
898
-
899
-		$provider->move($share, $recipientId);
900
-	}
901
-
902
-	public function getSharesInFolder($userId, Folder $node, $reshares = false) {
903
-		$providers = $this->factory->getAllProviders();
904
-
905
-		return array_reduce($providers, function($shares, IShareProvider $provider) use ($userId, $node, $reshares) {
906
-			$newShares = $provider->getSharesInFolder($userId, $node, $reshares);
907
-			foreach ($newShares as $fid => $data) {
908
-				if (!isset($shares[$fid])) {
909
-					$shares[$fid] = [];
910
-				}
911
-
912
-				$shares[$fid] = array_merge($shares[$fid], $data);
913
-			}
914
-			return $shares;
915
-		}, []);
916
-	}
917
-
918
-	/**
919
-	 * @inheritdoc
920
-	 */
921
-	public function getSharesBy($userId, $shareType, $path = null, $reshares = false, $limit = 50, $offset = 0) {
922
-		if ($path !== null &&
923
-				!($path instanceof \OCP\Files\File) &&
924
-				!($path instanceof \OCP\Files\Folder)) {
925
-			throw new \InvalidArgumentException('invalid path');
926
-		}
927
-
928
-		try {
929
-			$provider = $this->factory->getProviderForType($shareType);
930
-		} catch (ProviderException $e) {
931
-			return [];
932
-		}
933
-
934
-		$shares = $provider->getSharesBy($userId, $shareType, $path, $reshares, $limit, $offset);
935
-
936
-		/*
583
+            $share->setToken(
584
+                $this->secureRandom->generate(
585
+                    \OC\Share\Constants::TOKEN_LENGTH,
586
+                    \OCP\Security\ISecureRandom::CHAR_LOWER.
587
+                    \OCP\Security\ISecureRandom::CHAR_UPPER.
588
+                    \OCP\Security\ISecureRandom::CHAR_DIGITS
589
+                )
590
+            );
591
+
592
+            //Verify the expiration date
593
+            $this->validateExpirationDate($share);
594
+
595
+            //Verify the password
596
+            $this->verifyPassword($share->getPassword());
597
+
598
+            // If a password is set. Hash it!
599
+            if ($share->getPassword() !== null) {
600
+                $share->setPassword($this->hasher->hash($share->getPassword()));
601
+            }
602
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_EMAIL) {
603
+            $share->setToken(
604
+                $this->secureRandom->generate(
605
+                    \OC\Share\Constants::TOKEN_LENGTH,
606
+                    \OCP\Security\ISecureRandom::CHAR_LOWER.
607
+                    \OCP\Security\ISecureRandom::CHAR_UPPER.
608
+                    \OCP\Security\ISecureRandom::CHAR_DIGITS
609
+                )
610
+            );
611
+        }
612
+
613
+        // Cannot share with the owner
614
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER &&
615
+            $share->getSharedWith() === $share->getShareOwner()) {
616
+            throw new \InvalidArgumentException('Can\'t share with the share owner');
617
+        }
618
+
619
+        // Generate the target
620
+        $target = $this->config->getSystemValue('share_folder', '/') .'/'. $share->getNode()->getName();
621
+        $target = \OC\Files\Filesystem::normalizePath($target);
622
+        $share->setTarget($target);
623
+
624
+        // Pre share hook
625
+        $run = true;
626
+        $error = '';
627
+        $preHookData = [
628
+            'itemType' => $share->getNode() instanceof \OCP\Files\File ? 'file' : 'folder',
629
+            'itemSource' => $share->getNode()->getId(),
630
+            'shareType' => $share->getShareType(),
631
+            'uidOwner' => $share->getSharedBy(),
632
+            'permissions' => $share->getPermissions(),
633
+            'fileSource' => $share->getNode()->getId(),
634
+            'expiration' => $share->getExpirationDate(),
635
+            'token' => $share->getToken(),
636
+            'itemTarget' => $share->getTarget(),
637
+            'shareWith' => $share->getSharedWith(),
638
+            'run' => &$run,
639
+            'error' => &$error,
640
+        ];
641
+        \OC_Hook::emit('OCP\Share', 'pre_shared', $preHookData);
642
+
643
+        if ($run === false) {
644
+            throw new \Exception($error);
645
+        }
646
+
647
+        $oldShare = $share;
648
+        $provider = $this->factory->getProviderForType($share->getShareType());
649
+        $share = $provider->create($share);
650
+        //reuse the node we already have
651
+        $share->setNode($oldShare->getNode());
652
+
653
+        // Post share hook
654
+        $postHookData = [
655
+            'itemType' => $share->getNode() instanceof \OCP\Files\File ? 'file' : 'folder',
656
+            'itemSource' => $share->getNode()->getId(),
657
+            'shareType' => $share->getShareType(),
658
+            'uidOwner' => $share->getSharedBy(),
659
+            'permissions' => $share->getPermissions(),
660
+            'fileSource' => $share->getNode()->getId(),
661
+            'expiration' => $share->getExpirationDate(),
662
+            'token' => $share->getToken(),
663
+            'id' => $share->getId(),
664
+            'shareWith' => $share->getSharedWith(),
665
+            'itemTarget' => $share->getTarget(),
666
+            'fileTarget' => $share->getTarget(),
667
+        ];
668
+
669
+        \OC_Hook::emit('OCP\Share', 'post_shared', $postHookData);
670
+
671
+        return $share;
672
+    }
673
+
674
+    /**
675
+     * Update a share
676
+     *
677
+     * @param \OCP\Share\IShare $share
678
+     * @return \OCP\Share\IShare The share object
679
+     * @throws \InvalidArgumentException
680
+     */
681
+    public function updateShare(\OCP\Share\IShare $share) {
682
+        $expirationDateUpdated = false;
683
+
684
+        $this->canShare($share);
685
+
686
+        try {
687
+            $originalShare = $this->getShareById($share->getFullId());
688
+        } catch (\UnexpectedValueException $e) {
689
+            throw new \InvalidArgumentException('Share does not have a full id');
690
+        }
691
+
692
+        // We can't change the share type!
693
+        if ($share->getShareType() !== $originalShare->getShareType()) {
694
+            throw new \InvalidArgumentException('Can\'t change share type');
695
+        }
696
+
697
+        // We can only change the recipient on user shares
698
+        if ($share->getSharedWith() !== $originalShare->getSharedWith() &&
699
+            $share->getShareType() !== \OCP\Share::SHARE_TYPE_USER) {
700
+            throw new \InvalidArgumentException('Can only update recipient on user shares');
701
+        }
702
+
703
+        // Cannot share with the owner
704
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER &&
705
+            $share->getSharedWith() === $share->getShareOwner()) {
706
+            throw new \InvalidArgumentException('Can\'t share with the share owner');
707
+        }
708
+
709
+        $this->generalCreateChecks($share);
710
+
711
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
712
+            $this->userCreateChecks($share);
713
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
714
+            $this->groupCreateChecks($share);
715
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
716
+            $this->linkCreateChecks($share);
717
+
718
+            // Password updated.
719
+            if ($share->getPassword() !== $originalShare->getPassword()) {
720
+                //Verify the password
721
+                $this->verifyPassword($share->getPassword());
722
+
723
+                // If a password is set. Hash it!
724
+                if ($share->getPassword() !== null) {
725
+                    $share->setPassword($this->hasher->hash($share->getPassword()));
726
+                }
727
+            }
728
+
729
+            if ($share->getExpirationDate() != $originalShare->getExpirationDate()) {
730
+                //Verify the expiration date
731
+                $this->validateExpirationDate($share);
732
+                $expirationDateUpdated = true;
733
+            }
734
+        }
735
+
736
+        $plainTextPassword = null;
737
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK || $share->getShareType() === \OCP\Share::SHARE_TYPE_EMAIL) {
738
+            // Password updated.
739
+            if ($share->getPassword() !== $originalShare->getPassword()) {
740
+                //Verify the password
741
+                $this->verifyPassword($share->getPassword());
742
+
743
+                // If a password is set. Hash it!
744
+                if ($share->getPassword() !== null) {
745
+                    $plainTextPassword = $share->getPassword();
746
+                    $share->setPassword($this->hasher->hash($plainTextPassword));
747
+                }
748
+            }
749
+        }
750
+
751
+        $this->pathCreateChecks($share->getNode());
752
+
753
+        // Now update the share!
754
+        $provider = $this->factory->getProviderForType($share->getShareType());
755
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_EMAIL) {
756
+            $share = $provider->update($share, $plainTextPassword);
757
+        } else {
758
+            $share = $provider->update($share);
759
+        }
760
+
761
+        if ($expirationDateUpdated === true) {
762
+            \OC_Hook::emit('OCP\Share', 'post_set_expiration_date', [
763
+                'itemType' => $share->getNode() instanceof \OCP\Files\File ? 'file' : 'folder',
764
+                'itemSource' => $share->getNode()->getId(),
765
+                'date' => $share->getExpirationDate(),
766
+                'uidOwner' => $share->getSharedBy(),
767
+            ]);
768
+        }
769
+
770
+        if ($share->getPassword() !== $originalShare->getPassword()) {
771
+            \OC_Hook::emit('OCP\Share', 'post_update_password', [
772
+                'itemType' => $share->getNode() instanceof \OCP\Files\File ? 'file' : 'folder',
773
+                'itemSource' => $share->getNode()->getId(),
774
+                'uidOwner' => $share->getSharedBy(),
775
+                'token' => $share->getToken(),
776
+                'disabled' => is_null($share->getPassword()),
777
+            ]);
778
+        }
779
+
780
+        if ($share->getPermissions() !== $originalShare->getPermissions()) {
781
+            if ($this->userManager->userExists($share->getShareOwner())) {
782
+                $userFolder = $this->rootFolder->getUserFolder($share->getShareOwner());
783
+            } else {
784
+                $userFolder = $this->rootFolder->getUserFolder($share->getSharedBy());
785
+            }
786
+            \OC_Hook::emit('OCP\Share', 'post_update_permissions', array(
787
+                'itemType' => $share->getNode() instanceof \OCP\Files\File ? 'file' : 'folder',
788
+                'itemSource' => $share->getNode()->getId(),
789
+                'shareType' => $share->getShareType(),
790
+                'shareWith' => $share->getSharedWith(),
791
+                'uidOwner' => $share->getSharedBy(),
792
+                'permissions' => $share->getPermissions(),
793
+                'path' => $userFolder->getRelativePath($share->getNode()->getPath()),
794
+            ));
795
+        }
796
+
797
+        return $share;
798
+    }
799
+
800
+    /**
801
+     * Delete all the children of this share
802
+     * FIXME: remove once https://github.com/owncloud/core/pull/21660 is in
803
+     *
804
+     * @param \OCP\Share\IShare $share
805
+     * @return \OCP\Share\IShare[] List of deleted shares
806
+     */
807
+    protected function deleteChildren(\OCP\Share\IShare $share) {
808
+        $deletedShares = [];
809
+
810
+        $provider = $this->factory->getProviderForType($share->getShareType());
811
+
812
+        foreach ($provider->getChildren($share) as $child) {
813
+            $deletedChildren = $this->deleteChildren($child);
814
+            $deletedShares = array_merge($deletedShares, $deletedChildren);
815
+
816
+            $provider->delete($child);
817
+            $deletedShares[] = $child;
818
+        }
819
+
820
+        return $deletedShares;
821
+    }
822
+
823
+    /**
824
+     * Delete a share
825
+     *
826
+     * @param \OCP\Share\IShare $share
827
+     * @throws ShareNotFound
828
+     * @throws \InvalidArgumentException
829
+     */
830
+    public function deleteShare(\OCP\Share\IShare $share) {
831
+
832
+        try {
833
+            $share->getFullId();
834
+        } catch (\UnexpectedValueException $e) {
835
+            throw new \InvalidArgumentException('Share does not have a full id');
836
+        }
837
+
838
+        $event = new GenericEvent($share);
839
+        $this->eventDispatcher->dispatch('OCP\Share::preUnshare', $event);
840
+
841
+        // Get all children and delete them as well
842
+        $deletedShares = $this->deleteChildren($share);
843
+
844
+        // Do the actual delete
845
+        $provider = $this->factory->getProviderForType($share->getShareType());
846
+        $provider->delete($share);
847
+
848
+        // All the deleted shares caused by this delete
849
+        $deletedShares[] = $share;
850
+
851
+        // Emit post hook
852
+        $event->setArgument('deletedShares', $deletedShares);
853
+        $this->eventDispatcher->dispatch('OCP\Share::postUnshare', $event);
854
+    }
855
+
856
+
857
+    /**
858
+     * Unshare a file as the recipient.
859
+     * This can be different from a regular delete for example when one of
860
+     * the users in a groups deletes that share. But the provider should
861
+     * handle this.
862
+     *
863
+     * @param \OCP\Share\IShare $share
864
+     * @param string $recipientId
865
+     */
866
+    public function deleteFromSelf(\OCP\Share\IShare $share, $recipientId) {
867
+        list($providerId, ) = $this->splitFullId($share->getFullId());
868
+        $provider = $this->factory->getProvider($providerId);
869
+
870
+        $provider->deleteFromSelf($share, $recipientId);
871
+    }
872
+
873
+    /**
874
+     * @inheritdoc
875
+     */
876
+    public function moveShare(\OCP\Share\IShare $share, $recipientId) {
877
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
878
+            throw new \InvalidArgumentException('Can\'t change target of link share');
879
+        }
880
+
881
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER && $share->getSharedWith() !== $recipientId) {
882
+            throw new \InvalidArgumentException('Invalid recipient');
883
+        }
884
+
885
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
886
+            $sharedWith = $this->groupManager->get($share->getSharedWith());
887
+            if (is_null($sharedWith)) {
888
+                throw new \InvalidArgumentException('Group "' . $share->getSharedWith() . '" does not exist');
889
+            }
890
+            $recipient = $this->userManager->get($recipientId);
891
+            if (!$sharedWith->inGroup($recipient)) {
892
+                throw new \InvalidArgumentException('Invalid recipient');
893
+            }
894
+        }
895
+
896
+        list($providerId, ) = $this->splitFullId($share->getFullId());
897
+        $provider = $this->factory->getProvider($providerId);
898
+
899
+        $provider->move($share, $recipientId);
900
+    }
901
+
902
+    public function getSharesInFolder($userId, Folder $node, $reshares = false) {
903
+        $providers = $this->factory->getAllProviders();
904
+
905
+        return array_reduce($providers, function($shares, IShareProvider $provider) use ($userId, $node, $reshares) {
906
+            $newShares = $provider->getSharesInFolder($userId, $node, $reshares);
907
+            foreach ($newShares as $fid => $data) {
908
+                if (!isset($shares[$fid])) {
909
+                    $shares[$fid] = [];
910
+                }
911
+
912
+                $shares[$fid] = array_merge($shares[$fid], $data);
913
+            }
914
+            return $shares;
915
+        }, []);
916
+    }
917
+
918
+    /**
919
+     * @inheritdoc
920
+     */
921
+    public function getSharesBy($userId, $shareType, $path = null, $reshares = false, $limit = 50, $offset = 0) {
922
+        if ($path !== null &&
923
+                !($path instanceof \OCP\Files\File) &&
924
+                !($path instanceof \OCP\Files\Folder)) {
925
+            throw new \InvalidArgumentException('invalid path');
926
+        }
927
+
928
+        try {
929
+            $provider = $this->factory->getProviderForType($shareType);
930
+        } catch (ProviderException $e) {
931
+            return [];
932
+        }
933
+
934
+        $shares = $provider->getSharesBy($userId, $shareType, $path, $reshares, $limit, $offset);
935
+
936
+        /*
937 937
 		 * Work around so we don't return expired shares but still follow
938 938
 		 * proper pagination.
939 939
 		 */
940 940
 
941
-		$shares2 = [];
942
-
943
-		while(true) {
944
-			$added = 0;
945
-			foreach ($shares as $share) {
946
-
947
-				try {
948
-					$this->checkExpireDate($share);
949
-				} catch (ShareNotFound $e) {
950
-					//Ignore since this basically means the share is deleted
951
-					continue;
952
-				}
953
-
954
-				$added++;
955
-				$shares2[] = $share;
956
-
957
-				if (count($shares2) === $limit) {
958
-					break;
959
-				}
960
-			}
961
-
962
-			if (count($shares2) === $limit) {
963
-				break;
964
-			}
965
-
966
-			// If there was no limit on the select we are done
967
-			if ($limit === -1) {
968
-				break;
969
-			}
970
-
971
-			$offset += $added;
972
-
973
-			// Fetch again $limit shares
974
-			$shares = $provider->getSharesBy($userId, $shareType, $path, $reshares, $limit, $offset);
975
-
976
-			// No more shares means we are done
977
-			if (empty($shares)) {
978
-				break;
979
-			}
980
-		}
981
-
982
-		$shares = $shares2;
983
-
984
-		return $shares;
985
-	}
986
-
987
-	/**
988
-	 * @inheritdoc
989
-	 */
990
-	public function getSharedWith($userId, $shareType, $node = null, $limit = 50, $offset = 0) {
991
-		try {
992
-			$provider = $this->factory->getProviderForType($shareType);
993
-		} catch (ProviderException $e) {
994
-			return [];
995
-		}
996
-
997
-		$shares = $provider->getSharedWith($userId, $shareType, $node, $limit, $offset);
998
-
999
-		// remove all shares which are already expired
1000
-		foreach ($shares as $key => $share) {
1001
-			try {
1002
-				$this->checkExpireDate($share);
1003
-			} catch (ShareNotFound $e) {
1004
-				unset($shares[$key]);
1005
-			}
1006
-		}
1007
-
1008
-		return $shares;
1009
-	}
1010
-
1011
-	/**
1012
-	 * @inheritdoc
1013
-	 */
1014
-	public function getShareById($id, $recipient = null) {
1015
-		if ($id === null) {
1016
-			throw new ShareNotFound();
1017
-		}
1018
-
1019
-		list($providerId, $id) = $this->splitFullId($id);
1020
-
1021
-		try {
1022
-			$provider = $this->factory->getProvider($providerId);
1023
-		} catch (ProviderException $e) {
1024
-			throw new ShareNotFound();
1025
-		}
1026
-
1027
-		$share = $provider->getShareById($id, $recipient);
1028
-
1029
-		$this->checkExpireDate($share);
1030
-
1031
-		return $share;
1032
-	}
1033
-
1034
-	/**
1035
-	 * Get all the shares for a given path
1036
-	 *
1037
-	 * @param \OCP\Files\Node $path
1038
-	 * @param int $page
1039
-	 * @param int $perPage
1040
-	 *
1041
-	 * @return Share[]
1042
-	 */
1043
-	public function getSharesByPath(\OCP\Files\Node $path, $page=0, $perPage=50) {
1044
-		return [];
1045
-	}
1046
-
1047
-	/**
1048
-	 * Get the share by token possible with password
1049
-	 *
1050
-	 * @param string $token
1051
-	 * @return Share
1052
-	 *
1053
-	 * @throws ShareNotFound
1054
-	 */
1055
-	public function getShareByToken($token) {
1056
-		$share = null;
1057
-		try {
1058
-			if($this->shareApiAllowLinks()) {
1059
-				$provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_LINK);
1060
-				$share = $provider->getShareByToken($token);
1061
-			}
1062
-		} catch (ProviderException $e) {
1063
-		} catch (ShareNotFound $e) {
1064
-		}
1065
-
1066
-
1067
-		// If it is not a link share try to fetch a federated share by token
1068
-		if ($share === null) {
1069
-			try {
1070
-				$provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_REMOTE);
1071
-				$share = $provider->getShareByToken($token);
1072
-			} catch (ProviderException $e) {
1073
-			} catch (ShareNotFound $e) {
1074
-			}
1075
-		}
1076
-
1077
-		// If it is not a link share try to fetch a mail share by token
1078
-		if ($share === null && $this->shareProviderExists(\OCP\Share::SHARE_TYPE_EMAIL)) {
1079
-			try {
1080
-				$provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_EMAIL);
1081
-				$share = $provider->getShareByToken($token);
1082
-			} catch (ProviderException $e) {
1083
-			} catch (ShareNotFound $e) {
1084
-			}
1085
-		}
1086
-
1087
-		if ($share === null) {
1088
-			throw new ShareNotFound();
1089
-		}
1090
-
1091
-		$this->checkExpireDate($share);
1092
-
1093
-		/*
941
+        $shares2 = [];
942
+
943
+        while(true) {
944
+            $added = 0;
945
+            foreach ($shares as $share) {
946
+
947
+                try {
948
+                    $this->checkExpireDate($share);
949
+                } catch (ShareNotFound $e) {
950
+                    //Ignore since this basically means the share is deleted
951
+                    continue;
952
+                }
953
+
954
+                $added++;
955
+                $shares2[] = $share;
956
+
957
+                if (count($shares2) === $limit) {
958
+                    break;
959
+                }
960
+            }
961
+
962
+            if (count($shares2) === $limit) {
963
+                break;
964
+            }
965
+
966
+            // If there was no limit on the select we are done
967
+            if ($limit === -1) {
968
+                break;
969
+            }
970
+
971
+            $offset += $added;
972
+
973
+            // Fetch again $limit shares
974
+            $shares = $provider->getSharesBy($userId, $shareType, $path, $reshares, $limit, $offset);
975
+
976
+            // No more shares means we are done
977
+            if (empty($shares)) {
978
+                break;
979
+            }
980
+        }
981
+
982
+        $shares = $shares2;
983
+
984
+        return $shares;
985
+    }
986
+
987
+    /**
988
+     * @inheritdoc
989
+     */
990
+    public function getSharedWith($userId, $shareType, $node = null, $limit = 50, $offset = 0) {
991
+        try {
992
+            $provider = $this->factory->getProviderForType($shareType);
993
+        } catch (ProviderException $e) {
994
+            return [];
995
+        }
996
+
997
+        $shares = $provider->getSharedWith($userId, $shareType, $node, $limit, $offset);
998
+
999
+        // remove all shares which are already expired
1000
+        foreach ($shares as $key => $share) {
1001
+            try {
1002
+                $this->checkExpireDate($share);
1003
+            } catch (ShareNotFound $e) {
1004
+                unset($shares[$key]);
1005
+            }
1006
+        }
1007
+
1008
+        return $shares;
1009
+    }
1010
+
1011
+    /**
1012
+     * @inheritdoc
1013
+     */
1014
+    public function getShareById($id, $recipient = null) {
1015
+        if ($id === null) {
1016
+            throw new ShareNotFound();
1017
+        }
1018
+
1019
+        list($providerId, $id) = $this->splitFullId($id);
1020
+
1021
+        try {
1022
+            $provider = $this->factory->getProvider($providerId);
1023
+        } catch (ProviderException $e) {
1024
+            throw new ShareNotFound();
1025
+        }
1026
+
1027
+        $share = $provider->getShareById($id, $recipient);
1028
+
1029
+        $this->checkExpireDate($share);
1030
+
1031
+        return $share;
1032
+    }
1033
+
1034
+    /**
1035
+     * Get all the shares for a given path
1036
+     *
1037
+     * @param \OCP\Files\Node $path
1038
+     * @param int $page
1039
+     * @param int $perPage
1040
+     *
1041
+     * @return Share[]
1042
+     */
1043
+    public function getSharesByPath(\OCP\Files\Node $path, $page=0, $perPage=50) {
1044
+        return [];
1045
+    }
1046
+
1047
+    /**
1048
+     * Get the share by token possible with password
1049
+     *
1050
+     * @param string $token
1051
+     * @return Share
1052
+     *
1053
+     * @throws ShareNotFound
1054
+     */
1055
+    public function getShareByToken($token) {
1056
+        $share = null;
1057
+        try {
1058
+            if($this->shareApiAllowLinks()) {
1059
+                $provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_LINK);
1060
+                $share = $provider->getShareByToken($token);
1061
+            }
1062
+        } catch (ProviderException $e) {
1063
+        } catch (ShareNotFound $e) {
1064
+        }
1065
+
1066
+
1067
+        // If it is not a link share try to fetch a federated share by token
1068
+        if ($share === null) {
1069
+            try {
1070
+                $provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_REMOTE);
1071
+                $share = $provider->getShareByToken($token);
1072
+            } catch (ProviderException $e) {
1073
+            } catch (ShareNotFound $e) {
1074
+            }
1075
+        }
1076
+
1077
+        // If it is not a link share try to fetch a mail share by token
1078
+        if ($share === null && $this->shareProviderExists(\OCP\Share::SHARE_TYPE_EMAIL)) {
1079
+            try {
1080
+                $provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_EMAIL);
1081
+                $share = $provider->getShareByToken($token);
1082
+            } catch (ProviderException $e) {
1083
+            } catch (ShareNotFound $e) {
1084
+            }
1085
+        }
1086
+
1087
+        if ($share === null) {
1088
+            throw new ShareNotFound();
1089
+        }
1090
+
1091
+        $this->checkExpireDate($share);
1092
+
1093
+        /*
1094 1094
 		 * Reduce the permissions for link shares if public upload is not enabled
1095 1095
 		 */
1096
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK &&
1097
-			!$this->shareApiLinkAllowPublicUpload()) {
1098
-			$share->setPermissions($share->getPermissions() & ~(\OCP\Constants::PERMISSION_CREATE | \OCP\Constants::PERMISSION_UPDATE));
1099
-		}
1100
-
1101
-		return $share;
1102
-	}
1103
-
1104
-	protected function checkExpireDate($share) {
1105
-		if ($share->getExpirationDate() !== null &&
1106
-			$share->getExpirationDate() <= new \DateTime()) {
1107
-			$this->deleteShare($share);
1108
-			throw new ShareNotFound();
1109
-		}
1110
-
1111
-	}
1112
-
1113
-	/**
1114
-	 * Verify the password of a public share
1115
-	 *
1116
-	 * @param \OCP\Share\IShare $share
1117
-	 * @param string $password
1118
-	 * @return bool
1119
-	 */
1120
-	public function checkPassword(\OCP\Share\IShare $share, $password) {
1121
-		$passwordProtected = $share->getShareType() !== \OCP\Share::SHARE_TYPE_LINK
1122
-			|| $share->getShareType() !== \OCP\Share::SHARE_TYPE_EMAIL;
1123
-		if (!$passwordProtected) {
1124
-			//TODO maybe exception?
1125
-			return false;
1126
-		}
1127
-
1128
-		if ($password === null || $share->getPassword() === null) {
1129
-			return false;
1130
-		}
1131
-
1132
-		$newHash = '';
1133
-		if (!$this->hasher->verify($password, $share->getPassword(), $newHash)) {
1134
-			return false;
1135
-		}
1136
-
1137
-		if (!empty($newHash)) {
1138
-			$share->setPassword($newHash);
1139
-			$provider = $this->factory->getProviderForType($share->getShareType());
1140
-			$provider->update($share);
1141
-		}
1142
-
1143
-		return true;
1144
-	}
1145
-
1146
-	/**
1147
-	 * @inheritdoc
1148
-	 */
1149
-	public function userDeleted($uid) {
1150
-		$types = [\OCP\Share::SHARE_TYPE_USER, \OCP\Share::SHARE_TYPE_GROUP, \OCP\Share::SHARE_TYPE_LINK, \OCP\Share::SHARE_TYPE_REMOTE, \OCP\Share::SHARE_TYPE_EMAIL];
1151
-
1152
-		foreach ($types as $type) {
1153
-			try {
1154
-				$provider = $this->factory->getProviderForType($type);
1155
-			} catch (ProviderException $e) {
1156
-				continue;
1157
-			}
1158
-			$provider->userDeleted($uid, $type);
1159
-		}
1160
-	}
1161
-
1162
-	/**
1163
-	 * @inheritdoc
1164
-	 */
1165
-	public function groupDeleted($gid) {
1166
-		$provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_GROUP);
1167
-		$provider->groupDeleted($gid);
1168
-	}
1169
-
1170
-	/**
1171
-	 * @inheritdoc
1172
-	 */
1173
-	public function userDeletedFromGroup($uid, $gid) {
1174
-		$provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_GROUP);
1175
-		$provider->userDeletedFromGroup($uid, $gid);
1176
-	}
1177
-
1178
-	/**
1179
-	 * Get access list to a path. This means
1180
-	 * all the users that can access a given path.
1181
-	 *
1182
-	 * Consider:
1183
-	 * -root
1184
-	 * |-folder1 (23)
1185
-	 *  |-folder2 (32)
1186
-	 *   |-fileA (42)
1187
-	 *
1188
-	 * fileA is shared with user1 and user1@server1
1189
-	 * folder2 is shared with group2 (user4 is a member of group2)
1190
-	 * folder1 is shared with user2 (renamed to "folder (1)") and user2@server2
1191
-	 *
1192
-	 * Then the access list to '/folder1/folder2/fileA' with $currentAccess is:
1193
-	 * [
1194
-	 *  users  => [
1195
-	 *      'user1' => ['node_id' => 42, 'node_path' => '/fileA'],
1196
-	 *      'user4' => ['node_id' => 32, 'node_path' => '/folder2'],
1197
-	 *      'user2' => ['node_id' => 23, 'node_path' => '/folder (1)'],
1198
-	 *  ],
1199
-	 *  remote => [
1200
-	 *      'user1@server1' => ['node_id' => 42, 'token' => 'SeCr3t'],
1201
-	 *      'user2@server2' => ['node_id' => 23, 'token' => 'FooBaR'],
1202
-	 *  ],
1203
-	 *  public => bool
1204
-	 *  mail => bool
1205
-	 * ]
1206
-	 *
1207
-	 * The access list to '/folder1/folder2/fileA' **without** $currentAccess is:
1208
-	 * [
1209
-	 *  users  => ['user1', 'user2', 'user4'],
1210
-	 *  remote => bool,
1211
-	 *  public => bool
1212
-	 *  mail => bool
1213
-	 * ]
1214
-	 *
1215
-	 * This is required for encryption/activity
1216
-	 *
1217
-	 * @param \OCP\Files\Node $path
1218
-	 * @param bool $recursive Should we check all parent folders as well
1219
-	 * @param bool $currentAccess Should the user have currently access to the file
1220
-	 * @return array
1221
-	 */
1222
-	public function getAccessList(\OCP\Files\Node $path, $recursive = true, $currentAccess = false) {
1223
-		$owner = $path->getOwner()->getUID();
1224
-
1225
-		if ($currentAccess) {
1226
-			$al = ['users' => [], 'remote' => [], 'public' => false];
1227
-		} else {
1228
-			$al = ['users' => [], 'remote' => false, 'public' => false];
1229
-		}
1230
-		if (!$this->userManager->userExists($owner)) {
1231
-			return $al;
1232
-		}
1233
-
1234
-		//Get node for the owner
1235
-		$userFolder = $this->rootFolder->getUserFolder($owner);
1236
-		if (!$userFolder->isSubNode($path)) {
1237
-			$path = $userFolder->getById($path->getId())[0];
1238
-		}
1239
-
1240
-		$providers = $this->factory->getAllProviders();
1241
-
1242
-		/** @var Node[] $nodes */
1243
-		$nodes = [];
1244
-
1245
-		$ownerPath = $path->getPath();
1246
-		list(,,,$ownerPath) = explode('/', $ownerPath, 4);
1247
-		$al['users'][$owner] = [
1248
-			'node_id' => $path->getId(),
1249
-			'node_path' => '/' . $ownerPath,
1250
-		];
1251
-
1252
-		// Collect all the shares
1253
-		while ($path->getPath() !== $userFolder->getPath()) {
1254
-			$nodes[] = $path;
1255
-			if (!$recursive) {
1256
-				break;
1257
-			}
1258
-			$path = $path->getParent();
1259
-		}
1260
-
1261
-		foreach ($providers as $provider) {
1262
-			$tmp = $provider->getAccessList($nodes, $currentAccess);
1263
-
1264
-			foreach ($tmp as $k => $v) {
1265
-				if (isset($al[$k])) {
1266
-					if (is_array($al[$k])) {
1267
-						$al[$k] = array_merge($al[$k], $v);
1268
-					} else {
1269
-						$al[$k] = $al[$k] || $v;
1270
-					}
1271
-				} else {
1272
-					$al[$k] = $v;
1273
-				}
1274
-			}
1275
-		}
1276
-
1277
-		return $al;
1278
-	}
1279
-
1280
-	/**
1281
-	 * Create a new share
1282
-	 * @return \OCP\Share\IShare;
1283
-	 */
1284
-	public function newShare() {
1285
-		return new \OC\Share20\Share($this->rootFolder, $this->userManager);
1286
-	}
1287
-
1288
-	/**
1289
-	 * Is the share API enabled
1290
-	 *
1291
-	 * @return bool
1292
-	 */
1293
-	public function shareApiEnabled() {
1294
-		return $this->config->getAppValue('core', 'shareapi_enabled', 'yes') === 'yes';
1295
-	}
1296
-
1297
-	/**
1298
-	 * Is public link sharing enabled
1299
-	 *
1300
-	 * @return bool
1301
-	 */
1302
-	public function shareApiAllowLinks() {
1303
-		return $this->config->getAppValue('core', 'shareapi_allow_links', 'yes') === 'yes';
1304
-	}
1305
-
1306
-	/**
1307
-	 * Is password on public link requires
1308
-	 *
1309
-	 * @return bool
1310
-	 */
1311
-	public function shareApiLinkEnforcePassword() {
1312
-		return $this->config->getAppValue('core', 'shareapi_enforce_links_password', 'no') === 'yes';
1313
-	}
1314
-
1315
-	/**
1316
-	 * Is default expire date enabled
1317
-	 *
1318
-	 * @return bool
1319
-	 */
1320
-	public function shareApiLinkDefaultExpireDate() {
1321
-		return $this->config->getAppValue('core', 'shareapi_default_expire_date', 'no') === 'yes';
1322
-	}
1323
-
1324
-	/**
1325
-	 * Is default expire date enforced
1326
-	 *`
1327
-	 * @return bool
1328
-	 */
1329
-	public function shareApiLinkDefaultExpireDateEnforced() {
1330
-		return $this->shareApiLinkDefaultExpireDate() &&
1331
-			$this->config->getAppValue('core', 'shareapi_enforce_expire_date', 'no') === 'yes';
1332
-	}
1333
-
1334
-	/**
1335
-	 * Number of default expire days
1336
-	 *shareApiLinkAllowPublicUpload
1337
-	 * @return int
1338
-	 */
1339
-	public function shareApiLinkDefaultExpireDays() {
1340
-		return (int)$this->config->getAppValue('core', 'shareapi_expire_after_n_days', '7');
1341
-	}
1342
-
1343
-	/**
1344
-	 * Allow public upload on link shares
1345
-	 *
1346
-	 * @return bool
1347
-	 */
1348
-	public function shareApiLinkAllowPublicUpload() {
1349
-		return $this->config->getAppValue('core', 'shareapi_allow_public_upload', 'yes') === 'yes';
1350
-	}
1351
-
1352
-	/**
1353
-	 * check if user can only share with group members
1354
-	 * @return bool
1355
-	 */
1356
-	public function shareWithGroupMembersOnly() {
1357
-		return $this->config->getAppValue('core', 'shareapi_only_share_with_group_members', 'no') === 'yes';
1358
-	}
1359
-
1360
-	/**
1361
-	 * Check if users can share with groups
1362
-	 * @return bool
1363
-	 */
1364
-	public function allowGroupSharing() {
1365
-		return $this->config->getAppValue('core', 'shareapi_allow_group_sharing', 'yes') === 'yes';
1366
-	}
1367
-
1368
-	/**
1369
-	 * Copied from \OC_Util::isSharingDisabledForUser
1370
-	 *
1371
-	 * TODO: Deprecate fuction from OC_Util
1372
-	 *
1373
-	 * @param string $userId
1374
-	 * @return bool
1375
-	 */
1376
-	public function sharingDisabledForUser($userId) {
1377
-		if ($userId === null) {
1378
-			return false;
1379
-		}
1380
-
1381
-		if (isset($this->sharingDisabledForUsersCache[$userId])) {
1382
-			return $this->sharingDisabledForUsersCache[$userId];
1383
-		}
1384
-
1385
-		if ($this->config->getAppValue('core', 'shareapi_exclude_groups', 'no') === 'yes') {
1386
-			$groupsList = $this->config->getAppValue('core', 'shareapi_exclude_groups_list', '');
1387
-			$excludedGroups = json_decode($groupsList);
1388
-			if (is_null($excludedGroups)) {
1389
-				$excludedGroups = explode(',', $groupsList);
1390
-				$newValue = json_encode($excludedGroups);
1391
-				$this->config->setAppValue('core', 'shareapi_exclude_groups_list', $newValue);
1392
-			}
1393
-			$user = $this->userManager->get($userId);
1394
-			$usersGroups = $this->groupManager->getUserGroupIds($user);
1395
-			if (!empty($usersGroups)) {
1396
-				$remainingGroups = array_diff($usersGroups, $excludedGroups);
1397
-				// if the user is only in groups which are disabled for sharing then
1398
-				// sharing is also disabled for the user
1399
-				if (empty($remainingGroups)) {
1400
-					$this->sharingDisabledForUsersCache[$userId] = true;
1401
-					return true;
1402
-				}
1403
-			}
1404
-		}
1405
-
1406
-		$this->sharingDisabledForUsersCache[$userId] = false;
1407
-		return false;
1408
-	}
1409
-
1410
-	/**
1411
-	 * @inheritdoc
1412
-	 */
1413
-	public function outgoingServer2ServerSharesAllowed() {
1414
-		return $this->config->getAppValue('files_sharing', 'outgoing_server2server_share_enabled', 'yes') === 'yes';
1415
-	}
1416
-
1417
-	/**
1418
-	 * @inheritdoc
1419
-	 */
1420
-	public function shareProviderExists($shareType) {
1421
-		try {
1422
-			$this->factory->getProviderForType($shareType);
1423
-		} catch (ProviderException $e) {
1424
-			return false;
1425
-		}
1426
-
1427
-		return true;
1428
-	}
1096
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK &&
1097
+            !$this->shareApiLinkAllowPublicUpload()) {
1098
+            $share->setPermissions($share->getPermissions() & ~(\OCP\Constants::PERMISSION_CREATE | \OCP\Constants::PERMISSION_UPDATE));
1099
+        }
1100
+
1101
+        return $share;
1102
+    }
1103
+
1104
+    protected function checkExpireDate($share) {
1105
+        if ($share->getExpirationDate() !== null &&
1106
+            $share->getExpirationDate() <= new \DateTime()) {
1107
+            $this->deleteShare($share);
1108
+            throw new ShareNotFound();
1109
+        }
1110
+
1111
+    }
1112
+
1113
+    /**
1114
+     * Verify the password of a public share
1115
+     *
1116
+     * @param \OCP\Share\IShare $share
1117
+     * @param string $password
1118
+     * @return bool
1119
+     */
1120
+    public function checkPassword(\OCP\Share\IShare $share, $password) {
1121
+        $passwordProtected = $share->getShareType() !== \OCP\Share::SHARE_TYPE_LINK
1122
+            || $share->getShareType() !== \OCP\Share::SHARE_TYPE_EMAIL;
1123
+        if (!$passwordProtected) {
1124
+            //TODO maybe exception?
1125
+            return false;
1126
+        }
1127
+
1128
+        if ($password === null || $share->getPassword() === null) {
1129
+            return false;
1130
+        }
1131
+
1132
+        $newHash = '';
1133
+        if (!$this->hasher->verify($password, $share->getPassword(), $newHash)) {
1134
+            return false;
1135
+        }
1136
+
1137
+        if (!empty($newHash)) {
1138
+            $share->setPassword($newHash);
1139
+            $provider = $this->factory->getProviderForType($share->getShareType());
1140
+            $provider->update($share);
1141
+        }
1142
+
1143
+        return true;
1144
+    }
1145
+
1146
+    /**
1147
+     * @inheritdoc
1148
+     */
1149
+    public function userDeleted($uid) {
1150
+        $types = [\OCP\Share::SHARE_TYPE_USER, \OCP\Share::SHARE_TYPE_GROUP, \OCP\Share::SHARE_TYPE_LINK, \OCP\Share::SHARE_TYPE_REMOTE, \OCP\Share::SHARE_TYPE_EMAIL];
1151
+
1152
+        foreach ($types as $type) {
1153
+            try {
1154
+                $provider = $this->factory->getProviderForType($type);
1155
+            } catch (ProviderException $e) {
1156
+                continue;
1157
+            }
1158
+            $provider->userDeleted($uid, $type);
1159
+        }
1160
+    }
1161
+
1162
+    /**
1163
+     * @inheritdoc
1164
+     */
1165
+    public function groupDeleted($gid) {
1166
+        $provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_GROUP);
1167
+        $provider->groupDeleted($gid);
1168
+    }
1169
+
1170
+    /**
1171
+     * @inheritdoc
1172
+     */
1173
+    public function userDeletedFromGroup($uid, $gid) {
1174
+        $provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_GROUP);
1175
+        $provider->userDeletedFromGroup($uid, $gid);
1176
+    }
1177
+
1178
+    /**
1179
+     * Get access list to a path. This means
1180
+     * all the users that can access a given path.
1181
+     *
1182
+     * Consider:
1183
+     * -root
1184
+     * |-folder1 (23)
1185
+     *  |-folder2 (32)
1186
+     *   |-fileA (42)
1187
+     *
1188
+     * fileA is shared with user1 and user1@server1
1189
+     * folder2 is shared with group2 (user4 is a member of group2)
1190
+     * folder1 is shared with user2 (renamed to "folder (1)") and user2@server2
1191
+     *
1192
+     * Then the access list to '/folder1/folder2/fileA' with $currentAccess is:
1193
+     * [
1194
+     *  users  => [
1195
+     *      'user1' => ['node_id' => 42, 'node_path' => '/fileA'],
1196
+     *      'user4' => ['node_id' => 32, 'node_path' => '/folder2'],
1197
+     *      'user2' => ['node_id' => 23, 'node_path' => '/folder (1)'],
1198
+     *  ],
1199
+     *  remote => [
1200
+     *      'user1@server1' => ['node_id' => 42, 'token' => 'SeCr3t'],
1201
+     *      'user2@server2' => ['node_id' => 23, 'token' => 'FooBaR'],
1202
+     *  ],
1203
+     *  public => bool
1204
+     *  mail => bool
1205
+     * ]
1206
+     *
1207
+     * The access list to '/folder1/folder2/fileA' **without** $currentAccess is:
1208
+     * [
1209
+     *  users  => ['user1', 'user2', 'user4'],
1210
+     *  remote => bool,
1211
+     *  public => bool
1212
+     *  mail => bool
1213
+     * ]
1214
+     *
1215
+     * This is required for encryption/activity
1216
+     *
1217
+     * @param \OCP\Files\Node $path
1218
+     * @param bool $recursive Should we check all parent folders as well
1219
+     * @param bool $currentAccess Should the user have currently access to the file
1220
+     * @return array
1221
+     */
1222
+    public function getAccessList(\OCP\Files\Node $path, $recursive = true, $currentAccess = false) {
1223
+        $owner = $path->getOwner()->getUID();
1224
+
1225
+        if ($currentAccess) {
1226
+            $al = ['users' => [], 'remote' => [], 'public' => false];
1227
+        } else {
1228
+            $al = ['users' => [], 'remote' => false, 'public' => false];
1229
+        }
1230
+        if (!$this->userManager->userExists($owner)) {
1231
+            return $al;
1232
+        }
1233
+
1234
+        //Get node for the owner
1235
+        $userFolder = $this->rootFolder->getUserFolder($owner);
1236
+        if (!$userFolder->isSubNode($path)) {
1237
+            $path = $userFolder->getById($path->getId())[0];
1238
+        }
1239
+
1240
+        $providers = $this->factory->getAllProviders();
1241
+
1242
+        /** @var Node[] $nodes */
1243
+        $nodes = [];
1244
+
1245
+        $ownerPath = $path->getPath();
1246
+        list(,,,$ownerPath) = explode('/', $ownerPath, 4);
1247
+        $al['users'][$owner] = [
1248
+            'node_id' => $path->getId(),
1249
+            'node_path' => '/' . $ownerPath,
1250
+        ];
1251
+
1252
+        // Collect all the shares
1253
+        while ($path->getPath() !== $userFolder->getPath()) {
1254
+            $nodes[] = $path;
1255
+            if (!$recursive) {
1256
+                break;
1257
+            }
1258
+            $path = $path->getParent();
1259
+        }
1260
+
1261
+        foreach ($providers as $provider) {
1262
+            $tmp = $provider->getAccessList($nodes, $currentAccess);
1263
+
1264
+            foreach ($tmp as $k => $v) {
1265
+                if (isset($al[$k])) {
1266
+                    if (is_array($al[$k])) {
1267
+                        $al[$k] = array_merge($al[$k], $v);
1268
+                    } else {
1269
+                        $al[$k] = $al[$k] || $v;
1270
+                    }
1271
+                } else {
1272
+                    $al[$k] = $v;
1273
+                }
1274
+            }
1275
+        }
1276
+
1277
+        return $al;
1278
+    }
1279
+
1280
+    /**
1281
+     * Create a new share
1282
+     * @return \OCP\Share\IShare;
1283
+     */
1284
+    public function newShare() {
1285
+        return new \OC\Share20\Share($this->rootFolder, $this->userManager);
1286
+    }
1287
+
1288
+    /**
1289
+     * Is the share API enabled
1290
+     *
1291
+     * @return bool
1292
+     */
1293
+    public function shareApiEnabled() {
1294
+        return $this->config->getAppValue('core', 'shareapi_enabled', 'yes') === 'yes';
1295
+    }
1296
+
1297
+    /**
1298
+     * Is public link sharing enabled
1299
+     *
1300
+     * @return bool
1301
+     */
1302
+    public function shareApiAllowLinks() {
1303
+        return $this->config->getAppValue('core', 'shareapi_allow_links', 'yes') === 'yes';
1304
+    }
1305
+
1306
+    /**
1307
+     * Is password on public link requires
1308
+     *
1309
+     * @return bool
1310
+     */
1311
+    public function shareApiLinkEnforcePassword() {
1312
+        return $this->config->getAppValue('core', 'shareapi_enforce_links_password', 'no') === 'yes';
1313
+    }
1314
+
1315
+    /**
1316
+     * Is default expire date enabled
1317
+     *
1318
+     * @return bool
1319
+     */
1320
+    public function shareApiLinkDefaultExpireDate() {
1321
+        return $this->config->getAppValue('core', 'shareapi_default_expire_date', 'no') === 'yes';
1322
+    }
1323
+
1324
+    /**
1325
+     * Is default expire date enforced
1326
+     *`
1327
+     * @return bool
1328
+     */
1329
+    public function shareApiLinkDefaultExpireDateEnforced() {
1330
+        return $this->shareApiLinkDefaultExpireDate() &&
1331
+            $this->config->getAppValue('core', 'shareapi_enforce_expire_date', 'no') === 'yes';
1332
+    }
1333
+
1334
+    /**
1335
+     * Number of default expire days
1336
+     *shareApiLinkAllowPublicUpload
1337
+     * @return int
1338
+     */
1339
+    public function shareApiLinkDefaultExpireDays() {
1340
+        return (int)$this->config->getAppValue('core', 'shareapi_expire_after_n_days', '7');
1341
+    }
1342
+
1343
+    /**
1344
+     * Allow public upload on link shares
1345
+     *
1346
+     * @return bool
1347
+     */
1348
+    public function shareApiLinkAllowPublicUpload() {
1349
+        return $this->config->getAppValue('core', 'shareapi_allow_public_upload', 'yes') === 'yes';
1350
+    }
1351
+
1352
+    /**
1353
+     * check if user can only share with group members
1354
+     * @return bool
1355
+     */
1356
+    public function shareWithGroupMembersOnly() {
1357
+        return $this->config->getAppValue('core', 'shareapi_only_share_with_group_members', 'no') === 'yes';
1358
+    }
1359
+
1360
+    /**
1361
+     * Check if users can share with groups
1362
+     * @return bool
1363
+     */
1364
+    public function allowGroupSharing() {
1365
+        return $this->config->getAppValue('core', 'shareapi_allow_group_sharing', 'yes') === 'yes';
1366
+    }
1367
+
1368
+    /**
1369
+     * Copied from \OC_Util::isSharingDisabledForUser
1370
+     *
1371
+     * TODO: Deprecate fuction from OC_Util
1372
+     *
1373
+     * @param string $userId
1374
+     * @return bool
1375
+     */
1376
+    public function sharingDisabledForUser($userId) {
1377
+        if ($userId === null) {
1378
+            return false;
1379
+        }
1380
+
1381
+        if (isset($this->sharingDisabledForUsersCache[$userId])) {
1382
+            return $this->sharingDisabledForUsersCache[$userId];
1383
+        }
1384
+
1385
+        if ($this->config->getAppValue('core', 'shareapi_exclude_groups', 'no') === 'yes') {
1386
+            $groupsList = $this->config->getAppValue('core', 'shareapi_exclude_groups_list', '');
1387
+            $excludedGroups = json_decode($groupsList);
1388
+            if (is_null($excludedGroups)) {
1389
+                $excludedGroups = explode(',', $groupsList);
1390
+                $newValue = json_encode($excludedGroups);
1391
+                $this->config->setAppValue('core', 'shareapi_exclude_groups_list', $newValue);
1392
+            }
1393
+            $user = $this->userManager->get($userId);
1394
+            $usersGroups = $this->groupManager->getUserGroupIds($user);
1395
+            if (!empty($usersGroups)) {
1396
+                $remainingGroups = array_diff($usersGroups, $excludedGroups);
1397
+                // if the user is only in groups which are disabled for sharing then
1398
+                // sharing is also disabled for the user
1399
+                if (empty($remainingGroups)) {
1400
+                    $this->sharingDisabledForUsersCache[$userId] = true;
1401
+                    return true;
1402
+                }
1403
+            }
1404
+        }
1405
+
1406
+        $this->sharingDisabledForUsersCache[$userId] = false;
1407
+        return false;
1408
+    }
1409
+
1410
+    /**
1411
+     * @inheritdoc
1412
+     */
1413
+    public function outgoingServer2ServerSharesAllowed() {
1414
+        return $this->config->getAppValue('files_sharing', 'outgoing_server2server_share_enabled', 'yes') === 'yes';
1415
+    }
1416
+
1417
+    /**
1418
+     * @inheritdoc
1419
+     */
1420
+    public function shareProviderExists($shareType) {
1421
+        try {
1422
+            $this->factory->getProviderForType($shareType);
1423
+        } catch (ProviderException $e) {
1424
+            return false;
1425
+        }
1426
+
1427
+        return true;
1428
+    }
1429 1429
 
1430 1430
 }
Please login to merge, or discard this patch.
lib/public/Share/IShareHelper.php 1 patch
Indentation   +6 added lines, -6 removed lines patch added patch discarded remove patch
@@ -32,10 +32,10 @@
 block discarded – undo
32 32
  */
33 33
 interface IShareHelper {
34 34
 
35
-	/**
36
-	 * @param Node $node
37
-	 * @return array [ users => [Mapping $uid => $pathForUser], remotes => [Mapping $cloudId => $pathToMountRoot]]
38
-	 * @since 12
39
-	 */
40
-	public function getPathsForAccessList(Node $node);
35
+    /**
36
+     * @param Node $node
37
+     * @return array [ users => [Mapping $uid => $pathForUser], remotes => [Mapping $cloudId => $pathToMountRoot]]
38
+     * @since 12
39
+     */
40
+    public function getPathsForAccessList(Node $node);
41 41
 }
Please login to merge, or discard this patch.
lib/private/Server.php 2 patches
Indentation   +1591 added lines, -1591 removed lines patch added patch discarded remove patch
@@ -117,1600 +117,1600 @@
 block discarded – undo
117 117
  * TODO: hookup all manager classes
118 118
  */
119 119
 class Server extends ServerContainer implements IServerContainer {
120
-	/** @var string */
121
-	private $webRoot;
122
-
123
-	/**
124
-	 * @param string $webRoot
125
-	 * @param \OC\Config $config
126
-	 */
127
-	public function __construct($webRoot, \OC\Config $config) {
128
-		parent::__construct();
129
-		$this->webRoot = $webRoot;
130
-
131
-		$this->registerAlias(\OCP\Contacts\IManager::class, \OC\ContactsManager::class);
132
-		$this->registerAlias('ContactsManager', \OCP\Contacts\IManager::class);
133
-
134
-		$this->registerService(\OCP\IPreview::class, function (Server $c) {
135
-			return new PreviewManager(
136
-				$c->getConfig(),
137
-				$c->getRootFolder(),
138
-				$c->getAppDataDir('preview'),
139
-				$c->getEventDispatcher(),
140
-				$c->getSession()->get('user_id')
141
-			);
142
-		});
143
-		$this->registerAlias('PreviewManager', \OCP\IPreview::class);
144
-
145
-		$this->registerService(\OC\Preview\Watcher::class, function (Server $c) {
146
-			return new \OC\Preview\Watcher(
147
-				$c->getAppDataDir('preview')
148
-			);
149
-		});
150
-
151
-		$this->registerService('EncryptionManager', function (Server $c) {
152
-			$view = new View();
153
-			$util = new Encryption\Util(
154
-				$view,
155
-				$c->getUserManager(),
156
-				$c->getGroupManager(),
157
-				$c->getConfig()
158
-			);
159
-			return new Encryption\Manager(
160
-				$c->getConfig(),
161
-				$c->getLogger(),
162
-				$c->getL10N('core'),
163
-				new View(),
164
-				$util,
165
-				new ArrayCache()
166
-			);
167
-		});
168
-
169
-		$this->registerService('EncryptionFileHelper', function (Server $c) {
170
-			$util = new Encryption\Util(
171
-				new View(),
172
-				$c->getUserManager(),
173
-				$c->getGroupManager(),
174
-				$c->getConfig()
175
-			);
176
-			return new Encryption\File(
177
-				$util,
178
-				$c->getRootFolder(),
179
-				$c->getShareManager()
180
-			);
181
-		});
182
-
183
-		$this->registerService('EncryptionKeyStorage', function (Server $c) {
184
-			$view = new View();
185
-			$util = new Encryption\Util(
186
-				$view,
187
-				$c->getUserManager(),
188
-				$c->getGroupManager(),
189
-				$c->getConfig()
190
-			);
191
-
192
-			return new Encryption\Keys\Storage($view, $util);
193
-		});
194
-		$this->registerService('TagMapper', function (Server $c) {
195
-			return new TagMapper($c->getDatabaseConnection());
196
-		});
197
-
198
-		$this->registerService(\OCP\ITagManager::class, function (Server $c) {
199
-			$tagMapper = $c->query('TagMapper');
200
-			return new TagManager($tagMapper, $c->getUserSession());
201
-		});
202
-		$this->registerAlias('TagManager', \OCP\ITagManager::class);
203
-
204
-		$this->registerService('SystemTagManagerFactory', function (Server $c) {
205
-			$config = $c->getConfig();
206
-			$factoryClass = $config->getSystemValue('systemtags.managerFactory', '\OC\SystemTag\ManagerFactory');
207
-			/** @var \OC\SystemTag\ManagerFactory $factory */
208
-			$factory = new $factoryClass($this);
209
-			return $factory;
210
-		});
211
-		$this->registerService(\OCP\SystemTag\ISystemTagManager::class, function (Server $c) {
212
-			return $c->query('SystemTagManagerFactory')->getManager();
213
-		});
214
-		$this->registerAlias('SystemTagManager', \OCP\SystemTag\ISystemTagManager::class);
215
-
216
-		$this->registerService(\OCP\SystemTag\ISystemTagObjectMapper::class, function (Server $c) {
217
-			return $c->query('SystemTagManagerFactory')->getObjectMapper();
218
-		});
219
-		$this->registerService('RootFolder', function (Server $c) {
220
-			$manager = \OC\Files\Filesystem::getMountManager(null);
221
-			$view = new View();
222
-			$root = new Root(
223
-				$manager,
224
-				$view,
225
-				null,
226
-				$c->getUserMountCache(),
227
-				$this->getLogger(),
228
-				$this->getUserManager()
229
-			);
230
-			$connector = new HookConnector($root, $view);
231
-			$connector->viewToNode();
232
-
233
-			$previewConnector = new \OC\Preview\WatcherConnector($root, $c->getSystemConfig());
234
-			$previewConnector->connectWatcher();
235
-
236
-			return $root;
237
-		});
238
-		$this->registerAlias('SystemTagObjectMapper', \OCP\SystemTag\ISystemTagObjectMapper::class);
239
-
240
-		$this->registerService(\OCP\Files\IRootFolder::class, function(Server $c) {
241
-			return new LazyRoot(function() use ($c) {
242
-				return $c->query('RootFolder');
243
-			});
244
-		});
245
-		$this->registerAlias('LazyRootFolder', \OCP\Files\IRootFolder::class);
246
-
247
-		$this->registerService(\OCP\IUserManager::class, function (Server $c) {
248
-			$config = $c->getConfig();
249
-			return new \OC\User\Manager($config);
250
-		});
251
-		$this->registerAlias('UserManager', \OCP\IUserManager::class);
252
-
253
-		$this->registerService(\OCP\IGroupManager::class, function (Server $c) {
254
-			$groupManager = new \OC\Group\Manager($this->getUserManager(), $this->getLogger());
255
-			$groupManager->listen('\OC\Group', 'preCreate', function ($gid) {
256
-				\OC_Hook::emit('OC_Group', 'pre_createGroup', array('run' => true, 'gid' => $gid));
257
-			});
258
-			$groupManager->listen('\OC\Group', 'postCreate', function (\OC\Group\Group $gid) {
259
-				\OC_Hook::emit('OC_User', 'post_createGroup', array('gid' => $gid->getGID()));
260
-			});
261
-			$groupManager->listen('\OC\Group', 'preDelete', function (\OC\Group\Group $group) {
262
-				\OC_Hook::emit('OC_Group', 'pre_deleteGroup', array('run' => true, 'gid' => $group->getGID()));
263
-			});
264
-			$groupManager->listen('\OC\Group', 'postDelete', function (\OC\Group\Group $group) {
265
-				\OC_Hook::emit('OC_User', 'post_deleteGroup', array('gid' => $group->getGID()));
266
-			});
267
-			$groupManager->listen('\OC\Group', 'preAddUser', function (\OC\Group\Group $group, \OC\User\User $user) {
268
-				\OC_Hook::emit('OC_Group', 'pre_addToGroup', array('run' => true, 'uid' => $user->getUID(), 'gid' => $group->getGID()));
269
-			});
270
-			$groupManager->listen('\OC\Group', 'postAddUser', function (\OC\Group\Group $group, \OC\User\User $user) {
271
-				\OC_Hook::emit('OC_Group', 'post_addToGroup', array('uid' => $user->getUID(), 'gid' => $group->getGID()));
272
-				//Minimal fix to keep it backward compatible TODO: clean up all the GroupManager hooks
273
-				\OC_Hook::emit('OC_User', 'post_addToGroup', array('uid' => $user->getUID(), 'gid' => $group->getGID()));
274
-			});
275
-			return $groupManager;
276
-		});
277
-		$this->registerAlias('GroupManager', \OCP\IGroupManager::class);
278
-
279
-		$this->registerService(Store::class, function(Server $c) {
280
-			$session = $c->getSession();
281
-			if (\OC::$server->getSystemConfig()->getValue('installed', false)) {
282
-				$tokenProvider = $c->query('OC\Authentication\Token\IProvider');
283
-			} else {
284
-				$tokenProvider = null;
285
-			}
286
-			$logger = $c->getLogger();
287
-			return new Store($session, $logger, $tokenProvider);
288
-		});
289
-		$this->registerAlias(IStore::class, Store::class);
290
-		$this->registerService('OC\Authentication\Token\DefaultTokenMapper', function (Server $c) {
291
-			$dbConnection = $c->getDatabaseConnection();
292
-			return new Authentication\Token\DefaultTokenMapper($dbConnection);
293
-		});
294
-		$this->registerService('OC\Authentication\Token\DefaultTokenProvider', function (Server $c) {
295
-			$mapper = $c->query('OC\Authentication\Token\DefaultTokenMapper');
296
-			$crypto = $c->getCrypto();
297
-			$config = $c->getConfig();
298
-			$logger = $c->getLogger();
299
-			$timeFactory = new TimeFactory();
300
-			return new \OC\Authentication\Token\DefaultTokenProvider($mapper, $crypto, $config, $logger, $timeFactory);
301
-		});
302
-		$this->registerAlias('OC\Authentication\Token\IProvider', 'OC\Authentication\Token\DefaultTokenProvider');
303
-
304
-		$this->registerService(\OCP\IUserSession::class, function (Server $c) {
305
-			$manager = $c->getUserManager();
306
-			$session = new \OC\Session\Memory('');
307
-			$timeFactory = new TimeFactory();
308
-			// Token providers might require a working database. This code
309
-			// might however be called when ownCloud is not yet setup.
310
-			if (\OC::$server->getSystemConfig()->getValue('installed', false)) {
311
-				$defaultTokenProvider = $c->query('OC\Authentication\Token\IProvider');
312
-			} else {
313
-				$defaultTokenProvider = null;
314
-			}
315
-
316
-			$userSession = new \OC\User\Session($manager, $session, $timeFactory, $defaultTokenProvider, $c->getConfig(), $c->getSecureRandom(), $c->getLockdownManager());
317
-			$userSession->listen('\OC\User', 'preCreateUser', function ($uid, $password) {
318
-				\OC_Hook::emit('OC_User', 'pre_createUser', array('run' => true, 'uid' => $uid, 'password' => $password));
319
-			});
320
-			$userSession->listen('\OC\User', 'postCreateUser', function ($user, $password) {
321
-				/** @var $user \OC\User\User */
322
-				\OC_Hook::emit('OC_User', 'post_createUser', array('uid' => $user->getUID(), 'password' => $password));
323
-			});
324
-			$userSession->listen('\OC\User', 'preDelete', function ($user) {
325
-				/** @var $user \OC\User\User */
326
-				\OC_Hook::emit('OC_User', 'pre_deleteUser', array('run' => true, 'uid' => $user->getUID()));
327
-			});
328
-			$userSession->listen('\OC\User', 'postDelete', function ($user) {
329
-				/** @var $user \OC\User\User */
330
-				\OC_Hook::emit('OC_User', 'post_deleteUser', array('uid' => $user->getUID()));
331
-			});
332
-			$userSession->listen('\OC\User', 'preSetPassword', function ($user, $password, $recoveryPassword) {
333
-				/** @var $user \OC\User\User */
334
-				\OC_Hook::emit('OC_User', 'pre_setPassword', array('run' => true, 'uid' => $user->getUID(), 'password' => $password, 'recoveryPassword' => $recoveryPassword));
335
-			});
336
-			$userSession->listen('\OC\User', 'postSetPassword', function ($user, $password, $recoveryPassword) {
337
-				/** @var $user \OC\User\User */
338
-				\OC_Hook::emit('OC_User', 'post_setPassword', array('run' => true, 'uid' => $user->getUID(), 'password' => $password, 'recoveryPassword' => $recoveryPassword));
339
-			});
340
-			$userSession->listen('\OC\User', 'preLogin', function ($uid, $password) {
341
-				\OC_Hook::emit('OC_User', 'pre_login', array('run' => true, 'uid' => $uid, 'password' => $password));
342
-			});
343
-			$userSession->listen('\OC\User', 'postLogin', function ($user, $password) {
344
-				/** @var $user \OC\User\User */
345
-				\OC_Hook::emit('OC_User', 'post_login', array('run' => true, 'uid' => $user->getUID(), 'password' => $password));
346
-			});
347
-			$userSession->listen('\OC\User', 'logout', function () {
348
-				\OC_Hook::emit('OC_User', 'logout', array());
349
-			});
350
-			$userSession->listen('\OC\User', 'changeUser', function ($user, $feature, $value) {
351
-				/** @var $user \OC\User\User */
352
-				\OC_Hook::emit('OC_User', 'changeUser', array('run' => true, 'user' => $user, 'feature' => $feature, 'value' => $value));
353
-			});
354
-			return $userSession;
355
-		});
356
-		$this->registerAlias('UserSession', \OCP\IUserSession::class);
357
-
358
-		$this->registerService(\OC\Authentication\TwoFactorAuth\Manager::class, function (Server $c) {
359
-			return new \OC\Authentication\TwoFactorAuth\Manager($c->getAppManager(), $c->getSession(), $c->getConfig(), $c->getActivityManager(), $c->getLogger());
360
-		});
361
-
362
-		$this->registerAlias(\OCP\INavigationManager::class, \OC\NavigationManager::class);
363
-		$this->registerAlias('NavigationManager', \OCP\INavigationManager::class);
364
-
365
-		$this->registerService(\OC\AllConfig::class, function (Server $c) {
366
-			return new \OC\AllConfig(
367
-				$c->getSystemConfig()
368
-			);
369
-		});
370
-		$this->registerAlias('AllConfig', \OC\AllConfig::class);
371
-		$this->registerAlias(\OCP\IConfig::class, \OC\AllConfig::class);
372
-
373
-		$this->registerService('SystemConfig', function ($c) use ($config) {
374
-			return new \OC\SystemConfig($config);
375
-		});
376
-
377
-		$this->registerService(\OC\AppConfig::class, function (Server $c) {
378
-			return new \OC\AppConfig($c->getDatabaseConnection());
379
-		});
380
-		$this->registerAlias('AppConfig', \OC\AppConfig::class);
381
-		$this->registerAlias(\OCP\IAppConfig::class, \OC\AppConfig::class);
382
-
383
-		$this->registerService(\OCP\L10N\IFactory::class, function (Server $c) {
384
-			return new \OC\L10N\Factory(
385
-				$c->getConfig(),
386
-				$c->getRequest(),
387
-				$c->getUserSession(),
388
-				\OC::$SERVERROOT
389
-			);
390
-		});
391
-		$this->registerAlias('L10NFactory', \OCP\L10N\IFactory::class);
392
-
393
-		$this->registerService(\OCP\IURLGenerator::class, function (Server $c) {
394
-			$config = $c->getConfig();
395
-			$cacheFactory = $c->getMemCacheFactory();
396
-			return new \OC\URLGenerator(
397
-				$config,
398
-				$cacheFactory
399
-			);
400
-		});
401
-		$this->registerAlias('URLGenerator', \OCP\IURLGenerator::class);
402
-
403
-		$this->registerService('AppHelper', function ($c) {
404
-			return new \OC\AppHelper();
405
-		});
406
-		$this->registerService('AppFetcher', function ($c) {
407
-			return new AppFetcher(
408
-				$this->getAppDataDir('appstore'),
409
-				$this->getHTTPClientService(),
410
-				$this->query(TimeFactory::class),
411
-				$this->getConfig()
412
-			);
413
-		});
414
-		$this->registerService('CategoryFetcher', function ($c) {
415
-			return new CategoryFetcher(
416
-				$this->getAppDataDir('appstore'),
417
-				$this->getHTTPClientService(),
418
-				$this->query(TimeFactory::class),
419
-				$this->getConfig()
420
-			);
421
-		});
422
-
423
-		$this->registerService(\OCP\ICache::class, function ($c) {
424
-			return new Cache\File();
425
-		});
426
-		$this->registerAlias('UserCache', \OCP\ICache::class);
427
-
428
-		$this->registerService(Factory::class, function (Server $c) {
429
-			$config = $c->getConfig();
430
-
431
-			if ($config->getSystemValue('installed', false) && !(defined('PHPUNIT_RUN') && PHPUNIT_RUN)) {
432
-				$v = \OC_App::getAppVersions();
433
-				$v['core'] = md5(file_get_contents(\OC::$SERVERROOT . '/version.php'));
434
-				$version = implode(',', $v);
435
-				$instanceId = \OC_Util::getInstanceId();
436
-				$path = \OC::$SERVERROOT;
437
-				$prefix = md5($instanceId . '-' . $version . '-' . $path . '-' . \OC::$WEBROOT);
438
-				return new \OC\Memcache\Factory($prefix, $c->getLogger(),
439
-					$config->getSystemValue('memcache.local', null),
440
-					$config->getSystemValue('memcache.distributed', null),
441
-					$config->getSystemValue('memcache.locking', null)
442
-				);
443
-			}
444
-
445
-			return new \OC\Memcache\Factory('', $c->getLogger(),
446
-				'\\OC\\Memcache\\ArrayCache',
447
-				'\\OC\\Memcache\\ArrayCache',
448
-				'\\OC\\Memcache\\ArrayCache'
449
-			);
450
-		});
451
-		$this->registerAlias('MemCacheFactory', Factory::class);
452
-		$this->registerAlias(ICacheFactory::class, Factory::class);
453
-
454
-		$this->registerService('RedisFactory', function (Server $c) {
455
-			$systemConfig = $c->getSystemConfig();
456
-			return new RedisFactory($systemConfig);
457
-		});
458
-
459
-		$this->registerService(\OCP\Activity\IManager::class, function (Server $c) {
460
-			return new \OC\Activity\Manager(
461
-				$c->getRequest(),
462
-				$c->getUserSession(),
463
-				$c->getConfig(),
464
-				$c->query(IValidator::class)
465
-			);
466
-		});
467
-		$this->registerAlias('ActivityManager', \OCP\Activity\IManager::class);
468
-
469
-		$this->registerService(\OCP\Activity\IEventMerger::class, function (Server $c) {
470
-			return new \OC\Activity\EventMerger(
471
-				$c->getL10N('lib')
472
-			);
473
-		});
474
-		$this->registerAlias(IValidator::class, Validator::class);
475
-
476
-		$this->registerService(\OCP\IAvatarManager::class, function (Server $c) {
477
-			return new AvatarManager(
478
-				$c->getUserManager(),
479
-				$c->getAppDataDir('avatar'),
480
-				$c->getL10N('lib'),
481
-				$c->getLogger(),
482
-				$c->getConfig()
483
-			);
484
-		});
485
-		$this->registerAlias('AvatarManager', \OCP\IAvatarManager::class);
486
-
487
-		$this->registerService(\OCP\ILogger::class, function (Server $c) {
488
-			$logType = $c->query('AllConfig')->getSystemValue('log_type', 'file');
489
-			$logger = Log::getLogClass($logType);
490
-			call_user_func(array($logger, 'init'));
491
-
492
-			return new Log($logger);
493
-		});
494
-		$this->registerAlias('Logger', \OCP\ILogger::class);
495
-
496
-		$this->registerService(\OCP\BackgroundJob\IJobList::class, function (Server $c) {
497
-			$config = $c->getConfig();
498
-			return new \OC\BackgroundJob\JobList(
499
-				$c->getDatabaseConnection(),
500
-				$config,
501
-				new TimeFactory()
502
-			);
503
-		});
504
-		$this->registerAlias('JobList', \OCP\BackgroundJob\IJobList::class);
505
-
506
-		$this->registerService(\OCP\Route\IRouter::class, function (Server $c) {
507
-			$cacheFactory = $c->getMemCacheFactory();
508
-			$logger = $c->getLogger();
509
-			if ($cacheFactory->isAvailable()) {
510
-				$router = new \OC\Route\CachingRouter($cacheFactory->create('route'), $logger);
511
-			} else {
512
-				$router = new \OC\Route\Router($logger);
513
-			}
514
-			return $router;
515
-		});
516
-		$this->registerAlias('Router', \OCP\Route\IRouter::class);
517
-
518
-		$this->registerService(\OCP\ISearch::class, function ($c) {
519
-			return new Search();
520
-		});
521
-		$this->registerAlias('Search', \OCP\ISearch::class);
522
-
523
-		$this->registerService(\OCP\Security\ISecureRandom::class, function ($c) {
524
-			return new SecureRandom();
525
-		});
526
-		$this->registerAlias('SecureRandom', \OCP\Security\ISecureRandom::class);
527
-
528
-		$this->registerService(\OCP\Security\ICrypto::class, function (Server $c) {
529
-			return new Crypto($c->getConfig(), $c->getSecureRandom());
530
-		});
531
-		$this->registerAlias('Crypto', \OCP\Security\ICrypto::class);
532
-
533
-		$this->registerService(\OCP\Security\IHasher::class, function (Server $c) {
534
-			return new Hasher($c->getConfig());
535
-		});
536
-		$this->registerAlias('Hasher', \OCP\Security\IHasher::class);
537
-
538
-		$this->registerService(\OCP\Security\ICredentialsManager::class, function (Server $c) {
539
-			return new CredentialsManager($c->getCrypto(), $c->getDatabaseConnection());
540
-		});
541
-		$this->registerAlias('CredentialsManager', \OCP\Security\ICredentialsManager::class);
542
-
543
-		$this->registerService(IDBConnection::class, function (Server $c) {
544
-			$systemConfig = $c->getSystemConfig();
545
-			$factory = new \OC\DB\ConnectionFactory($systemConfig);
546
-			$type = $systemConfig->getValue('dbtype', 'sqlite');
547
-			if (!$factory->isValidType($type)) {
548
-				throw new \OC\DatabaseException('Invalid database type');
549
-			}
550
-			$connectionParams = $factory->createConnectionParams();
551
-			$connection = $factory->getConnection($type, $connectionParams);
552
-			$connection->getConfiguration()->setSQLLogger($c->getQueryLogger());
553
-			return $connection;
554
-		});
555
-		$this->registerAlias('DatabaseConnection', IDBConnection::class);
556
-
557
-		$this->registerService('HTTPHelper', function (Server $c) {
558
-			$config = $c->getConfig();
559
-			return new HTTPHelper(
560
-				$config,
561
-				$c->getHTTPClientService()
562
-			);
563
-		});
564
-
565
-		$this->registerService(\OCP\Http\Client\IClientService::class, function (Server $c) {
566
-			$user = \OC_User::getUser();
567
-			$uid = $user ? $user : null;
568
-			return new ClientService(
569
-				$c->getConfig(),
570
-				new \OC\Security\CertificateManager($uid, new View(), $c->getConfig(), $c->getLogger())
571
-			);
572
-		});
573
-		$this->registerAlias('HttpClientService', \OCP\Http\Client\IClientService::class);
574
-
575
-		$this->registerService(\OCP\Diagnostics\IEventLogger::class, function (Server $c) {
576
-			if ($c->getSystemConfig()->getValue('debug', false)) {
577
-				return new EventLogger();
578
-			} else {
579
-				return new NullEventLogger();
580
-			}
581
-		});
582
-		$this->registerAlias('EventLogger', \OCP\Diagnostics\IEventLogger::class);
583
-
584
-		$this->registerService(\OCP\Diagnostics\IQueryLogger::class, function (Server $c) {
585
-			if ($c->getSystemConfig()->getValue('debug', false)) {
586
-				return new QueryLogger();
587
-			} else {
588
-				return new NullQueryLogger();
589
-			}
590
-		});
591
-		$this->registerAlias('QueryLogger', \OCP\Diagnostics\IQueryLogger::class);
592
-
593
-		$this->registerService(TempManager::class, function (Server $c) {
594
-			return new TempManager(
595
-				$c->getLogger(),
596
-				$c->getConfig()
597
-			);
598
-		});
599
-		$this->registerAlias('TempManager', TempManager::class);
600
-		$this->registerAlias(ITempManager::class, TempManager::class);
601
-
602
-		$this->registerService(AppManager::class, function (Server $c) {
603
-			return new \OC\App\AppManager(
604
-				$c->getUserSession(),
605
-				$c->getAppConfig(),
606
-				$c->getGroupManager(),
607
-				$c->getMemCacheFactory(),
608
-				$c->getEventDispatcher()
609
-			);
610
-		});
611
-		$this->registerAlias('AppManager', AppManager::class);
612
-		$this->registerAlias(IAppManager::class, AppManager::class);
613
-
614
-		$this->registerService(\OCP\IDateTimeZone::class, function (Server $c) {
615
-			return new DateTimeZone(
616
-				$c->getConfig(),
617
-				$c->getSession()
618
-			);
619
-		});
620
-		$this->registerAlias('DateTimeZone', \OCP\IDateTimeZone::class);
621
-
622
-		$this->registerService(\OCP\IDateTimeFormatter::class, function (Server $c) {
623
-			$language = $c->getConfig()->getUserValue($c->getSession()->get('user_id'), 'core', 'lang', null);
624
-
625
-			return new DateTimeFormatter(
626
-				$c->getDateTimeZone()->getTimeZone(),
627
-				$c->getL10N('lib', $language)
628
-			);
629
-		});
630
-		$this->registerAlias('DateTimeFormatter', \OCP\IDateTimeFormatter::class);
631
-
632
-		$this->registerService(\OCP\Files\Config\IUserMountCache::class, function (Server $c) {
633
-			$mountCache = new UserMountCache($c->getDatabaseConnection(), $c->getUserManager(), $c->getLogger());
634
-			$listener = new UserMountCacheListener($mountCache);
635
-			$listener->listen($c->getUserManager());
636
-			return $mountCache;
637
-		});
638
-		$this->registerAlias('UserMountCache', \OCP\Files\Config\IUserMountCache::class);
639
-
640
-		$this->registerService(\OCP\Files\Config\IMountProviderCollection::class, function (Server $c) {
641
-			$loader = \OC\Files\Filesystem::getLoader();
642
-			$mountCache = $c->query('UserMountCache');
643
-			$manager =  new \OC\Files\Config\MountProviderCollection($loader, $mountCache);
644
-
645
-			// builtin providers
646
-
647
-			$config = $c->getConfig();
648
-			$manager->registerProvider(new CacheMountProvider($config));
649
-			$manager->registerHomeProvider(new LocalHomeMountProvider());
650
-			$manager->registerHomeProvider(new ObjectHomeMountProvider($config));
651
-
652
-			return $manager;
653
-		});
654
-		$this->registerAlias('MountConfigManager', \OCP\Files\Config\IMountProviderCollection::class);
655
-
656
-		$this->registerService('IniWrapper', function ($c) {
657
-			return new IniGetWrapper();
658
-		});
659
-		$this->registerService('AsyncCommandBus', function (Server $c) {
660
-			$jobList = $c->getJobList();
661
-			return new AsyncBus($jobList);
662
-		});
663
-		$this->registerService('TrustedDomainHelper', function ($c) {
664
-			return new TrustedDomainHelper($this->getConfig());
665
-		});
666
-		$this->registerService('Throttler', function(Server $c) {
667
-			return new Throttler(
668
-				$c->getDatabaseConnection(),
669
-				new TimeFactory(),
670
-				$c->getLogger(),
671
-				$c->getConfig()
672
-			);
673
-		});
674
-		$this->registerService('IntegrityCodeChecker', function (Server $c) {
675
-			// IConfig and IAppManager requires a working database. This code
676
-			// might however be called when ownCloud is not yet setup.
677
-			if(\OC::$server->getSystemConfig()->getValue('installed', false)) {
678
-				$config = $c->getConfig();
679
-				$appManager = $c->getAppManager();
680
-			} else {
681
-				$config = null;
682
-				$appManager = null;
683
-			}
684
-
685
-			return new Checker(
686
-					new EnvironmentHelper(),
687
-					new FileAccessHelper(),
688
-					new AppLocator(),
689
-					$config,
690
-					$c->getMemCacheFactory(),
691
-					$appManager,
692
-					$c->getTempManager()
693
-			);
694
-		});
695
-		$this->registerService(\OCP\IRequest::class, function ($c) {
696
-			if (isset($this['urlParams'])) {
697
-				$urlParams = $this['urlParams'];
698
-			} else {
699
-				$urlParams = [];
700
-			}
701
-
702
-			if (defined('PHPUNIT_RUN') && PHPUNIT_RUN
703
-				&& in_array('fakeinput', stream_get_wrappers())
704
-			) {
705
-				$stream = 'fakeinput://data';
706
-			} else {
707
-				$stream = 'php://input';
708
-			}
709
-
710
-			return new Request(
711
-				[
712
-					'get' => $_GET,
713
-					'post' => $_POST,
714
-					'files' => $_FILES,
715
-					'server' => $_SERVER,
716
-					'env' => $_ENV,
717
-					'cookies' => $_COOKIE,
718
-					'method' => (isset($_SERVER) && isset($_SERVER['REQUEST_METHOD']))
719
-						? $_SERVER['REQUEST_METHOD']
720
-						: null,
721
-					'urlParams' => $urlParams,
722
-				],
723
-				$this->getSecureRandom(),
724
-				$this->getConfig(),
725
-				$this->getCsrfTokenManager(),
726
-				$stream
727
-			);
728
-		});
729
-		$this->registerAlias('Request', \OCP\IRequest::class);
730
-
731
-		$this->registerService(\OCP\Mail\IMailer::class, function (Server $c) {
732
-			return new Mailer(
733
-				$c->getConfig(),
734
-				$c->getLogger(),
735
-				$c->getThemingDefaults()
736
-			);
737
-		});
738
-		$this->registerAlias('Mailer', \OCP\Mail\IMailer::class);
739
-
740
-		$this->registerService('LDAPProvider', function(Server $c) {
741
-			$config = $c->getConfig();
742
-			$factoryClass = $config->getSystemValue('ldapProviderFactory', null);
743
-			if(is_null($factoryClass)) {
744
-				throw new \Exception('ldapProviderFactory not set');
745
-			}
746
-			/** @var \OCP\LDAP\ILDAPProviderFactory $factory */
747
-			$factory = new $factoryClass($this);
748
-			return $factory->getLDAPProvider();
749
-		});
750
-		$this->registerService('LockingProvider', function (Server $c) {
751
-			$ini = $c->getIniWrapper();
752
-			$config = $c->getConfig();
753
-			$ttl = $config->getSystemValue('filelocking.ttl', max(3600, $ini->getNumeric('max_execution_time')));
754
-			if ($config->getSystemValue('filelocking.enabled', true) or (defined('PHPUNIT_RUN') && PHPUNIT_RUN)) {
755
-				/** @var \OC\Memcache\Factory $memcacheFactory */
756
-				$memcacheFactory = $c->getMemCacheFactory();
757
-				$memcache = $memcacheFactory->createLocking('lock');
758
-				if (!($memcache instanceof \OC\Memcache\NullCache)) {
759
-					return new MemcacheLockingProvider($memcache, $ttl);
760
-				}
761
-				return new DBLockingProvider($c->getDatabaseConnection(), $c->getLogger(), new TimeFactory(), $ttl);
762
-			}
763
-			return new NoopLockingProvider();
764
-		});
765
-
766
-		$this->registerService(\OCP\Files\Mount\IMountManager::class, function () {
767
-			return new \OC\Files\Mount\Manager();
768
-		});
769
-		$this->registerAlias('MountManager', \OCP\Files\Mount\IMountManager::class);
770
-
771
-		$this->registerService(\OCP\Files\IMimeTypeDetector::class, function (Server $c) {
772
-			return new \OC\Files\Type\Detection(
773
-				$c->getURLGenerator(),
774
-				\OC::$configDir,
775
-				\OC::$SERVERROOT . '/resources/config/'
776
-			);
777
-		});
778
-		$this->registerAlias('MimeTypeDetector', \OCP\Files\IMimeTypeDetector::class);
779
-
780
-		$this->registerService(\OCP\Files\IMimeTypeLoader::class, function (Server $c) {
781
-			return new \OC\Files\Type\Loader(
782
-				$c->getDatabaseConnection()
783
-			);
784
-		});
785
-		$this->registerAlias('MimeTypeLoader', \OCP\Files\IMimeTypeLoader::class);
786
-
787
-		$this->registerService(\OCP\Notification\IManager::class, function (Server $c) {
788
-			return new Manager(
789
-				$c->query(IValidator::class)
790
-			);
791
-		});
792
-		$this->registerAlias('NotificationManager', \OCP\Notification\IManager::class);
793
-
794
-		$this->registerService(\OC\CapabilitiesManager::class, function (Server $c) {
795
-			$manager = new \OC\CapabilitiesManager($c->getLogger());
796
-			$manager->registerCapability(function () use ($c) {
797
-				return new \OC\OCS\CoreCapabilities($c->getConfig());
798
-			});
799
-			return $manager;
800
-		});
801
-		$this->registerAlias('CapabilitiesManager', \OC\CapabilitiesManager::class);
802
-
803
-		$this->registerService(\OCP\Comments\ICommentsManager::class, function(Server $c) {
804
-			$config = $c->getConfig();
805
-			$factoryClass = $config->getSystemValue('comments.managerFactory', '\OC\Comments\ManagerFactory');
806
-			/** @var \OCP\Comments\ICommentsManagerFactory $factory */
807
-			$factory = new $factoryClass($this);
808
-			return $factory->getManager();
809
-		});
810
-		$this->registerAlias('CommentsManager', \OCP\Comments\ICommentsManager::class);
811
-
812
-		$this->registerService('ThemingDefaults', function(Server $c) {
813
-			/*
120
+    /** @var string */
121
+    private $webRoot;
122
+
123
+    /**
124
+     * @param string $webRoot
125
+     * @param \OC\Config $config
126
+     */
127
+    public function __construct($webRoot, \OC\Config $config) {
128
+        parent::__construct();
129
+        $this->webRoot = $webRoot;
130
+
131
+        $this->registerAlias(\OCP\Contacts\IManager::class, \OC\ContactsManager::class);
132
+        $this->registerAlias('ContactsManager', \OCP\Contacts\IManager::class);
133
+
134
+        $this->registerService(\OCP\IPreview::class, function (Server $c) {
135
+            return new PreviewManager(
136
+                $c->getConfig(),
137
+                $c->getRootFolder(),
138
+                $c->getAppDataDir('preview'),
139
+                $c->getEventDispatcher(),
140
+                $c->getSession()->get('user_id')
141
+            );
142
+        });
143
+        $this->registerAlias('PreviewManager', \OCP\IPreview::class);
144
+
145
+        $this->registerService(\OC\Preview\Watcher::class, function (Server $c) {
146
+            return new \OC\Preview\Watcher(
147
+                $c->getAppDataDir('preview')
148
+            );
149
+        });
150
+
151
+        $this->registerService('EncryptionManager', function (Server $c) {
152
+            $view = new View();
153
+            $util = new Encryption\Util(
154
+                $view,
155
+                $c->getUserManager(),
156
+                $c->getGroupManager(),
157
+                $c->getConfig()
158
+            );
159
+            return new Encryption\Manager(
160
+                $c->getConfig(),
161
+                $c->getLogger(),
162
+                $c->getL10N('core'),
163
+                new View(),
164
+                $util,
165
+                new ArrayCache()
166
+            );
167
+        });
168
+
169
+        $this->registerService('EncryptionFileHelper', function (Server $c) {
170
+            $util = new Encryption\Util(
171
+                new View(),
172
+                $c->getUserManager(),
173
+                $c->getGroupManager(),
174
+                $c->getConfig()
175
+            );
176
+            return new Encryption\File(
177
+                $util,
178
+                $c->getRootFolder(),
179
+                $c->getShareManager()
180
+            );
181
+        });
182
+
183
+        $this->registerService('EncryptionKeyStorage', function (Server $c) {
184
+            $view = new View();
185
+            $util = new Encryption\Util(
186
+                $view,
187
+                $c->getUserManager(),
188
+                $c->getGroupManager(),
189
+                $c->getConfig()
190
+            );
191
+
192
+            return new Encryption\Keys\Storage($view, $util);
193
+        });
194
+        $this->registerService('TagMapper', function (Server $c) {
195
+            return new TagMapper($c->getDatabaseConnection());
196
+        });
197
+
198
+        $this->registerService(\OCP\ITagManager::class, function (Server $c) {
199
+            $tagMapper = $c->query('TagMapper');
200
+            return new TagManager($tagMapper, $c->getUserSession());
201
+        });
202
+        $this->registerAlias('TagManager', \OCP\ITagManager::class);
203
+
204
+        $this->registerService('SystemTagManagerFactory', function (Server $c) {
205
+            $config = $c->getConfig();
206
+            $factoryClass = $config->getSystemValue('systemtags.managerFactory', '\OC\SystemTag\ManagerFactory');
207
+            /** @var \OC\SystemTag\ManagerFactory $factory */
208
+            $factory = new $factoryClass($this);
209
+            return $factory;
210
+        });
211
+        $this->registerService(\OCP\SystemTag\ISystemTagManager::class, function (Server $c) {
212
+            return $c->query('SystemTagManagerFactory')->getManager();
213
+        });
214
+        $this->registerAlias('SystemTagManager', \OCP\SystemTag\ISystemTagManager::class);
215
+
216
+        $this->registerService(\OCP\SystemTag\ISystemTagObjectMapper::class, function (Server $c) {
217
+            return $c->query('SystemTagManagerFactory')->getObjectMapper();
218
+        });
219
+        $this->registerService('RootFolder', function (Server $c) {
220
+            $manager = \OC\Files\Filesystem::getMountManager(null);
221
+            $view = new View();
222
+            $root = new Root(
223
+                $manager,
224
+                $view,
225
+                null,
226
+                $c->getUserMountCache(),
227
+                $this->getLogger(),
228
+                $this->getUserManager()
229
+            );
230
+            $connector = new HookConnector($root, $view);
231
+            $connector->viewToNode();
232
+
233
+            $previewConnector = new \OC\Preview\WatcherConnector($root, $c->getSystemConfig());
234
+            $previewConnector->connectWatcher();
235
+
236
+            return $root;
237
+        });
238
+        $this->registerAlias('SystemTagObjectMapper', \OCP\SystemTag\ISystemTagObjectMapper::class);
239
+
240
+        $this->registerService(\OCP\Files\IRootFolder::class, function(Server $c) {
241
+            return new LazyRoot(function() use ($c) {
242
+                return $c->query('RootFolder');
243
+            });
244
+        });
245
+        $this->registerAlias('LazyRootFolder', \OCP\Files\IRootFolder::class);
246
+
247
+        $this->registerService(\OCP\IUserManager::class, function (Server $c) {
248
+            $config = $c->getConfig();
249
+            return new \OC\User\Manager($config);
250
+        });
251
+        $this->registerAlias('UserManager', \OCP\IUserManager::class);
252
+
253
+        $this->registerService(\OCP\IGroupManager::class, function (Server $c) {
254
+            $groupManager = new \OC\Group\Manager($this->getUserManager(), $this->getLogger());
255
+            $groupManager->listen('\OC\Group', 'preCreate', function ($gid) {
256
+                \OC_Hook::emit('OC_Group', 'pre_createGroup', array('run' => true, 'gid' => $gid));
257
+            });
258
+            $groupManager->listen('\OC\Group', 'postCreate', function (\OC\Group\Group $gid) {
259
+                \OC_Hook::emit('OC_User', 'post_createGroup', array('gid' => $gid->getGID()));
260
+            });
261
+            $groupManager->listen('\OC\Group', 'preDelete', function (\OC\Group\Group $group) {
262
+                \OC_Hook::emit('OC_Group', 'pre_deleteGroup', array('run' => true, 'gid' => $group->getGID()));
263
+            });
264
+            $groupManager->listen('\OC\Group', 'postDelete', function (\OC\Group\Group $group) {
265
+                \OC_Hook::emit('OC_User', 'post_deleteGroup', array('gid' => $group->getGID()));
266
+            });
267
+            $groupManager->listen('\OC\Group', 'preAddUser', function (\OC\Group\Group $group, \OC\User\User $user) {
268
+                \OC_Hook::emit('OC_Group', 'pre_addToGroup', array('run' => true, 'uid' => $user->getUID(), 'gid' => $group->getGID()));
269
+            });
270
+            $groupManager->listen('\OC\Group', 'postAddUser', function (\OC\Group\Group $group, \OC\User\User $user) {
271
+                \OC_Hook::emit('OC_Group', 'post_addToGroup', array('uid' => $user->getUID(), 'gid' => $group->getGID()));
272
+                //Minimal fix to keep it backward compatible TODO: clean up all the GroupManager hooks
273
+                \OC_Hook::emit('OC_User', 'post_addToGroup', array('uid' => $user->getUID(), 'gid' => $group->getGID()));
274
+            });
275
+            return $groupManager;
276
+        });
277
+        $this->registerAlias('GroupManager', \OCP\IGroupManager::class);
278
+
279
+        $this->registerService(Store::class, function(Server $c) {
280
+            $session = $c->getSession();
281
+            if (\OC::$server->getSystemConfig()->getValue('installed', false)) {
282
+                $tokenProvider = $c->query('OC\Authentication\Token\IProvider');
283
+            } else {
284
+                $tokenProvider = null;
285
+            }
286
+            $logger = $c->getLogger();
287
+            return new Store($session, $logger, $tokenProvider);
288
+        });
289
+        $this->registerAlias(IStore::class, Store::class);
290
+        $this->registerService('OC\Authentication\Token\DefaultTokenMapper', function (Server $c) {
291
+            $dbConnection = $c->getDatabaseConnection();
292
+            return new Authentication\Token\DefaultTokenMapper($dbConnection);
293
+        });
294
+        $this->registerService('OC\Authentication\Token\DefaultTokenProvider', function (Server $c) {
295
+            $mapper = $c->query('OC\Authentication\Token\DefaultTokenMapper');
296
+            $crypto = $c->getCrypto();
297
+            $config = $c->getConfig();
298
+            $logger = $c->getLogger();
299
+            $timeFactory = new TimeFactory();
300
+            return new \OC\Authentication\Token\DefaultTokenProvider($mapper, $crypto, $config, $logger, $timeFactory);
301
+        });
302
+        $this->registerAlias('OC\Authentication\Token\IProvider', 'OC\Authentication\Token\DefaultTokenProvider');
303
+
304
+        $this->registerService(\OCP\IUserSession::class, function (Server $c) {
305
+            $manager = $c->getUserManager();
306
+            $session = new \OC\Session\Memory('');
307
+            $timeFactory = new TimeFactory();
308
+            // Token providers might require a working database. This code
309
+            // might however be called when ownCloud is not yet setup.
310
+            if (\OC::$server->getSystemConfig()->getValue('installed', false)) {
311
+                $defaultTokenProvider = $c->query('OC\Authentication\Token\IProvider');
312
+            } else {
313
+                $defaultTokenProvider = null;
314
+            }
315
+
316
+            $userSession = new \OC\User\Session($manager, $session, $timeFactory, $defaultTokenProvider, $c->getConfig(), $c->getSecureRandom(), $c->getLockdownManager());
317
+            $userSession->listen('\OC\User', 'preCreateUser', function ($uid, $password) {
318
+                \OC_Hook::emit('OC_User', 'pre_createUser', array('run' => true, 'uid' => $uid, 'password' => $password));
319
+            });
320
+            $userSession->listen('\OC\User', 'postCreateUser', function ($user, $password) {
321
+                /** @var $user \OC\User\User */
322
+                \OC_Hook::emit('OC_User', 'post_createUser', array('uid' => $user->getUID(), 'password' => $password));
323
+            });
324
+            $userSession->listen('\OC\User', 'preDelete', function ($user) {
325
+                /** @var $user \OC\User\User */
326
+                \OC_Hook::emit('OC_User', 'pre_deleteUser', array('run' => true, 'uid' => $user->getUID()));
327
+            });
328
+            $userSession->listen('\OC\User', 'postDelete', function ($user) {
329
+                /** @var $user \OC\User\User */
330
+                \OC_Hook::emit('OC_User', 'post_deleteUser', array('uid' => $user->getUID()));
331
+            });
332
+            $userSession->listen('\OC\User', 'preSetPassword', function ($user, $password, $recoveryPassword) {
333
+                /** @var $user \OC\User\User */
334
+                \OC_Hook::emit('OC_User', 'pre_setPassword', array('run' => true, 'uid' => $user->getUID(), 'password' => $password, 'recoveryPassword' => $recoveryPassword));
335
+            });
336
+            $userSession->listen('\OC\User', 'postSetPassword', function ($user, $password, $recoveryPassword) {
337
+                /** @var $user \OC\User\User */
338
+                \OC_Hook::emit('OC_User', 'post_setPassword', array('run' => true, 'uid' => $user->getUID(), 'password' => $password, 'recoveryPassword' => $recoveryPassword));
339
+            });
340
+            $userSession->listen('\OC\User', 'preLogin', function ($uid, $password) {
341
+                \OC_Hook::emit('OC_User', 'pre_login', array('run' => true, 'uid' => $uid, 'password' => $password));
342
+            });
343
+            $userSession->listen('\OC\User', 'postLogin', function ($user, $password) {
344
+                /** @var $user \OC\User\User */
345
+                \OC_Hook::emit('OC_User', 'post_login', array('run' => true, 'uid' => $user->getUID(), 'password' => $password));
346
+            });
347
+            $userSession->listen('\OC\User', 'logout', function () {
348
+                \OC_Hook::emit('OC_User', 'logout', array());
349
+            });
350
+            $userSession->listen('\OC\User', 'changeUser', function ($user, $feature, $value) {
351
+                /** @var $user \OC\User\User */
352
+                \OC_Hook::emit('OC_User', 'changeUser', array('run' => true, 'user' => $user, 'feature' => $feature, 'value' => $value));
353
+            });
354
+            return $userSession;
355
+        });
356
+        $this->registerAlias('UserSession', \OCP\IUserSession::class);
357
+
358
+        $this->registerService(\OC\Authentication\TwoFactorAuth\Manager::class, function (Server $c) {
359
+            return new \OC\Authentication\TwoFactorAuth\Manager($c->getAppManager(), $c->getSession(), $c->getConfig(), $c->getActivityManager(), $c->getLogger());
360
+        });
361
+
362
+        $this->registerAlias(\OCP\INavigationManager::class, \OC\NavigationManager::class);
363
+        $this->registerAlias('NavigationManager', \OCP\INavigationManager::class);
364
+
365
+        $this->registerService(\OC\AllConfig::class, function (Server $c) {
366
+            return new \OC\AllConfig(
367
+                $c->getSystemConfig()
368
+            );
369
+        });
370
+        $this->registerAlias('AllConfig', \OC\AllConfig::class);
371
+        $this->registerAlias(\OCP\IConfig::class, \OC\AllConfig::class);
372
+
373
+        $this->registerService('SystemConfig', function ($c) use ($config) {
374
+            return new \OC\SystemConfig($config);
375
+        });
376
+
377
+        $this->registerService(\OC\AppConfig::class, function (Server $c) {
378
+            return new \OC\AppConfig($c->getDatabaseConnection());
379
+        });
380
+        $this->registerAlias('AppConfig', \OC\AppConfig::class);
381
+        $this->registerAlias(\OCP\IAppConfig::class, \OC\AppConfig::class);
382
+
383
+        $this->registerService(\OCP\L10N\IFactory::class, function (Server $c) {
384
+            return new \OC\L10N\Factory(
385
+                $c->getConfig(),
386
+                $c->getRequest(),
387
+                $c->getUserSession(),
388
+                \OC::$SERVERROOT
389
+            );
390
+        });
391
+        $this->registerAlias('L10NFactory', \OCP\L10N\IFactory::class);
392
+
393
+        $this->registerService(\OCP\IURLGenerator::class, function (Server $c) {
394
+            $config = $c->getConfig();
395
+            $cacheFactory = $c->getMemCacheFactory();
396
+            return new \OC\URLGenerator(
397
+                $config,
398
+                $cacheFactory
399
+            );
400
+        });
401
+        $this->registerAlias('URLGenerator', \OCP\IURLGenerator::class);
402
+
403
+        $this->registerService('AppHelper', function ($c) {
404
+            return new \OC\AppHelper();
405
+        });
406
+        $this->registerService('AppFetcher', function ($c) {
407
+            return new AppFetcher(
408
+                $this->getAppDataDir('appstore'),
409
+                $this->getHTTPClientService(),
410
+                $this->query(TimeFactory::class),
411
+                $this->getConfig()
412
+            );
413
+        });
414
+        $this->registerService('CategoryFetcher', function ($c) {
415
+            return new CategoryFetcher(
416
+                $this->getAppDataDir('appstore'),
417
+                $this->getHTTPClientService(),
418
+                $this->query(TimeFactory::class),
419
+                $this->getConfig()
420
+            );
421
+        });
422
+
423
+        $this->registerService(\OCP\ICache::class, function ($c) {
424
+            return new Cache\File();
425
+        });
426
+        $this->registerAlias('UserCache', \OCP\ICache::class);
427
+
428
+        $this->registerService(Factory::class, function (Server $c) {
429
+            $config = $c->getConfig();
430
+
431
+            if ($config->getSystemValue('installed', false) && !(defined('PHPUNIT_RUN') && PHPUNIT_RUN)) {
432
+                $v = \OC_App::getAppVersions();
433
+                $v['core'] = md5(file_get_contents(\OC::$SERVERROOT . '/version.php'));
434
+                $version = implode(',', $v);
435
+                $instanceId = \OC_Util::getInstanceId();
436
+                $path = \OC::$SERVERROOT;
437
+                $prefix = md5($instanceId . '-' . $version . '-' . $path . '-' . \OC::$WEBROOT);
438
+                return new \OC\Memcache\Factory($prefix, $c->getLogger(),
439
+                    $config->getSystemValue('memcache.local', null),
440
+                    $config->getSystemValue('memcache.distributed', null),
441
+                    $config->getSystemValue('memcache.locking', null)
442
+                );
443
+            }
444
+
445
+            return new \OC\Memcache\Factory('', $c->getLogger(),
446
+                '\\OC\\Memcache\\ArrayCache',
447
+                '\\OC\\Memcache\\ArrayCache',
448
+                '\\OC\\Memcache\\ArrayCache'
449
+            );
450
+        });
451
+        $this->registerAlias('MemCacheFactory', Factory::class);
452
+        $this->registerAlias(ICacheFactory::class, Factory::class);
453
+
454
+        $this->registerService('RedisFactory', function (Server $c) {
455
+            $systemConfig = $c->getSystemConfig();
456
+            return new RedisFactory($systemConfig);
457
+        });
458
+
459
+        $this->registerService(\OCP\Activity\IManager::class, function (Server $c) {
460
+            return new \OC\Activity\Manager(
461
+                $c->getRequest(),
462
+                $c->getUserSession(),
463
+                $c->getConfig(),
464
+                $c->query(IValidator::class)
465
+            );
466
+        });
467
+        $this->registerAlias('ActivityManager', \OCP\Activity\IManager::class);
468
+
469
+        $this->registerService(\OCP\Activity\IEventMerger::class, function (Server $c) {
470
+            return new \OC\Activity\EventMerger(
471
+                $c->getL10N('lib')
472
+            );
473
+        });
474
+        $this->registerAlias(IValidator::class, Validator::class);
475
+
476
+        $this->registerService(\OCP\IAvatarManager::class, function (Server $c) {
477
+            return new AvatarManager(
478
+                $c->getUserManager(),
479
+                $c->getAppDataDir('avatar'),
480
+                $c->getL10N('lib'),
481
+                $c->getLogger(),
482
+                $c->getConfig()
483
+            );
484
+        });
485
+        $this->registerAlias('AvatarManager', \OCP\IAvatarManager::class);
486
+
487
+        $this->registerService(\OCP\ILogger::class, function (Server $c) {
488
+            $logType = $c->query('AllConfig')->getSystemValue('log_type', 'file');
489
+            $logger = Log::getLogClass($logType);
490
+            call_user_func(array($logger, 'init'));
491
+
492
+            return new Log($logger);
493
+        });
494
+        $this->registerAlias('Logger', \OCP\ILogger::class);
495
+
496
+        $this->registerService(\OCP\BackgroundJob\IJobList::class, function (Server $c) {
497
+            $config = $c->getConfig();
498
+            return new \OC\BackgroundJob\JobList(
499
+                $c->getDatabaseConnection(),
500
+                $config,
501
+                new TimeFactory()
502
+            );
503
+        });
504
+        $this->registerAlias('JobList', \OCP\BackgroundJob\IJobList::class);
505
+
506
+        $this->registerService(\OCP\Route\IRouter::class, function (Server $c) {
507
+            $cacheFactory = $c->getMemCacheFactory();
508
+            $logger = $c->getLogger();
509
+            if ($cacheFactory->isAvailable()) {
510
+                $router = new \OC\Route\CachingRouter($cacheFactory->create('route'), $logger);
511
+            } else {
512
+                $router = new \OC\Route\Router($logger);
513
+            }
514
+            return $router;
515
+        });
516
+        $this->registerAlias('Router', \OCP\Route\IRouter::class);
517
+
518
+        $this->registerService(\OCP\ISearch::class, function ($c) {
519
+            return new Search();
520
+        });
521
+        $this->registerAlias('Search', \OCP\ISearch::class);
522
+
523
+        $this->registerService(\OCP\Security\ISecureRandom::class, function ($c) {
524
+            return new SecureRandom();
525
+        });
526
+        $this->registerAlias('SecureRandom', \OCP\Security\ISecureRandom::class);
527
+
528
+        $this->registerService(\OCP\Security\ICrypto::class, function (Server $c) {
529
+            return new Crypto($c->getConfig(), $c->getSecureRandom());
530
+        });
531
+        $this->registerAlias('Crypto', \OCP\Security\ICrypto::class);
532
+
533
+        $this->registerService(\OCP\Security\IHasher::class, function (Server $c) {
534
+            return new Hasher($c->getConfig());
535
+        });
536
+        $this->registerAlias('Hasher', \OCP\Security\IHasher::class);
537
+
538
+        $this->registerService(\OCP\Security\ICredentialsManager::class, function (Server $c) {
539
+            return new CredentialsManager($c->getCrypto(), $c->getDatabaseConnection());
540
+        });
541
+        $this->registerAlias('CredentialsManager', \OCP\Security\ICredentialsManager::class);
542
+
543
+        $this->registerService(IDBConnection::class, function (Server $c) {
544
+            $systemConfig = $c->getSystemConfig();
545
+            $factory = new \OC\DB\ConnectionFactory($systemConfig);
546
+            $type = $systemConfig->getValue('dbtype', 'sqlite');
547
+            if (!$factory->isValidType($type)) {
548
+                throw new \OC\DatabaseException('Invalid database type');
549
+            }
550
+            $connectionParams = $factory->createConnectionParams();
551
+            $connection = $factory->getConnection($type, $connectionParams);
552
+            $connection->getConfiguration()->setSQLLogger($c->getQueryLogger());
553
+            return $connection;
554
+        });
555
+        $this->registerAlias('DatabaseConnection', IDBConnection::class);
556
+
557
+        $this->registerService('HTTPHelper', function (Server $c) {
558
+            $config = $c->getConfig();
559
+            return new HTTPHelper(
560
+                $config,
561
+                $c->getHTTPClientService()
562
+            );
563
+        });
564
+
565
+        $this->registerService(\OCP\Http\Client\IClientService::class, function (Server $c) {
566
+            $user = \OC_User::getUser();
567
+            $uid = $user ? $user : null;
568
+            return new ClientService(
569
+                $c->getConfig(),
570
+                new \OC\Security\CertificateManager($uid, new View(), $c->getConfig(), $c->getLogger())
571
+            );
572
+        });
573
+        $this->registerAlias('HttpClientService', \OCP\Http\Client\IClientService::class);
574
+
575
+        $this->registerService(\OCP\Diagnostics\IEventLogger::class, function (Server $c) {
576
+            if ($c->getSystemConfig()->getValue('debug', false)) {
577
+                return new EventLogger();
578
+            } else {
579
+                return new NullEventLogger();
580
+            }
581
+        });
582
+        $this->registerAlias('EventLogger', \OCP\Diagnostics\IEventLogger::class);
583
+
584
+        $this->registerService(\OCP\Diagnostics\IQueryLogger::class, function (Server $c) {
585
+            if ($c->getSystemConfig()->getValue('debug', false)) {
586
+                return new QueryLogger();
587
+            } else {
588
+                return new NullQueryLogger();
589
+            }
590
+        });
591
+        $this->registerAlias('QueryLogger', \OCP\Diagnostics\IQueryLogger::class);
592
+
593
+        $this->registerService(TempManager::class, function (Server $c) {
594
+            return new TempManager(
595
+                $c->getLogger(),
596
+                $c->getConfig()
597
+            );
598
+        });
599
+        $this->registerAlias('TempManager', TempManager::class);
600
+        $this->registerAlias(ITempManager::class, TempManager::class);
601
+
602
+        $this->registerService(AppManager::class, function (Server $c) {
603
+            return new \OC\App\AppManager(
604
+                $c->getUserSession(),
605
+                $c->getAppConfig(),
606
+                $c->getGroupManager(),
607
+                $c->getMemCacheFactory(),
608
+                $c->getEventDispatcher()
609
+            );
610
+        });
611
+        $this->registerAlias('AppManager', AppManager::class);
612
+        $this->registerAlias(IAppManager::class, AppManager::class);
613
+
614
+        $this->registerService(\OCP\IDateTimeZone::class, function (Server $c) {
615
+            return new DateTimeZone(
616
+                $c->getConfig(),
617
+                $c->getSession()
618
+            );
619
+        });
620
+        $this->registerAlias('DateTimeZone', \OCP\IDateTimeZone::class);
621
+
622
+        $this->registerService(\OCP\IDateTimeFormatter::class, function (Server $c) {
623
+            $language = $c->getConfig()->getUserValue($c->getSession()->get('user_id'), 'core', 'lang', null);
624
+
625
+            return new DateTimeFormatter(
626
+                $c->getDateTimeZone()->getTimeZone(),
627
+                $c->getL10N('lib', $language)
628
+            );
629
+        });
630
+        $this->registerAlias('DateTimeFormatter', \OCP\IDateTimeFormatter::class);
631
+
632
+        $this->registerService(\OCP\Files\Config\IUserMountCache::class, function (Server $c) {
633
+            $mountCache = new UserMountCache($c->getDatabaseConnection(), $c->getUserManager(), $c->getLogger());
634
+            $listener = new UserMountCacheListener($mountCache);
635
+            $listener->listen($c->getUserManager());
636
+            return $mountCache;
637
+        });
638
+        $this->registerAlias('UserMountCache', \OCP\Files\Config\IUserMountCache::class);
639
+
640
+        $this->registerService(\OCP\Files\Config\IMountProviderCollection::class, function (Server $c) {
641
+            $loader = \OC\Files\Filesystem::getLoader();
642
+            $mountCache = $c->query('UserMountCache');
643
+            $manager =  new \OC\Files\Config\MountProviderCollection($loader, $mountCache);
644
+
645
+            // builtin providers
646
+
647
+            $config = $c->getConfig();
648
+            $manager->registerProvider(new CacheMountProvider($config));
649
+            $manager->registerHomeProvider(new LocalHomeMountProvider());
650
+            $manager->registerHomeProvider(new ObjectHomeMountProvider($config));
651
+
652
+            return $manager;
653
+        });
654
+        $this->registerAlias('MountConfigManager', \OCP\Files\Config\IMountProviderCollection::class);
655
+
656
+        $this->registerService('IniWrapper', function ($c) {
657
+            return new IniGetWrapper();
658
+        });
659
+        $this->registerService('AsyncCommandBus', function (Server $c) {
660
+            $jobList = $c->getJobList();
661
+            return new AsyncBus($jobList);
662
+        });
663
+        $this->registerService('TrustedDomainHelper', function ($c) {
664
+            return new TrustedDomainHelper($this->getConfig());
665
+        });
666
+        $this->registerService('Throttler', function(Server $c) {
667
+            return new Throttler(
668
+                $c->getDatabaseConnection(),
669
+                new TimeFactory(),
670
+                $c->getLogger(),
671
+                $c->getConfig()
672
+            );
673
+        });
674
+        $this->registerService('IntegrityCodeChecker', function (Server $c) {
675
+            // IConfig and IAppManager requires a working database. This code
676
+            // might however be called when ownCloud is not yet setup.
677
+            if(\OC::$server->getSystemConfig()->getValue('installed', false)) {
678
+                $config = $c->getConfig();
679
+                $appManager = $c->getAppManager();
680
+            } else {
681
+                $config = null;
682
+                $appManager = null;
683
+            }
684
+
685
+            return new Checker(
686
+                    new EnvironmentHelper(),
687
+                    new FileAccessHelper(),
688
+                    new AppLocator(),
689
+                    $config,
690
+                    $c->getMemCacheFactory(),
691
+                    $appManager,
692
+                    $c->getTempManager()
693
+            );
694
+        });
695
+        $this->registerService(\OCP\IRequest::class, function ($c) {
696
+            if (isset($this['urlParams'])) {
697
+                $urlParams = $this['urlParams'];
698
+            } else {
699
+                $urlParams = [];
700
+            }
701
+
702
+            if (defined('PHPUNIT_RUN') && PHPUNIT_RUN
703
+                && in_array('fakeinput', stream_get_wrappers())
704
+            ) {
705
+                $stream = 'fakeinput://data';
706
+            } else {
707
+                $stream = 'php://input';
708
+            }
709
+
710
+            return new Request(
711
+                [
712
+                    'get' => $_GET,
713
+                    'post' => $_POST,
714
+                    'files' => $_FILES,
715
+                    'server' => $_SERVER,
716
+                    'env' => $_ENV,
717
+                    'cookies' => $_COOKIE,
718
+                    'method' => (isset($_SERVER) && isset($_SERVER['REQUEST_METHOD']))
719
+                        ? $_SERVER['REQUEST_METHOD']
720
+                        : null,
721
+                    'urlParams' => $urlParams,
722
+                ],
723
+                $this->getSecureRandom(),
724
+                $this->getConfig(),
725
+                $this->getCsrfTokenManager(),
726
+                $stream
727
+            );
728
+        });
729
+        $this->registerAlias('Request', \OCP\IRequest::class);
730
+
731
+        $this->registerService(\OCP\Mail\IMailer::class, function (Server $c) {
732
+            return new Mailer(
733
+                $c->getConfig(),
734
+                $c->getLogger(),
735
+                $c->getThemingDefaults()
736
+            );
737
+        });
738
+        $this->registerAlias('Mailer', \OCP\Mail\IMailer::class);
739
+
740
+        $this->registerService('LDAPProvider', function(Server $c) {
741
+            $config = $c->getConfig();
742
+            $factoryClass = $config->getSystemValue('ldapProviderFactory', null);
743
+            if(is_null($factoryClass)) {
744
+                throw new \Exception('ldapProviderFactory not set');
745
+            }
746
+            /** @var \OCP\LDAP\ILDAPProviderFactory $factory */
747
+            $factory = new $factoryClass($this);
748
+            return $factory->getLDAPProvider();
749
+        });
750
+        $this->registerService('LockingProvider', function (Server $c) {
751
+            $ini = $c->getIniWrapper();
752
+            $config = $c->getConfig();
753
+            $ttl = $config->getSystemValue('filelocking.ttl', max(3600, $ini->getNumeric('max_execution_time')));
754
+            if ($config->getSystemValue('filelocking.enabled', true) or (defined('PHPUNIT_RUN') && PHPUNIT_RUN)) {
755
+                /** @var \OC\Memcache\Factory $memcacheFactory */
756
+                $memcacheFactory = $c->getMemCacheFactory();
757
+                $memcache = $memcacheFactory->createLocking('lock');
758
+                if (!($memcache instanceof \OC\Memcache\NullCache)) {
759
+                    return new MemcacheLockingProvider($memcache, $ttl);
760
+                }
761
+                return new DBLockingProvider($c->getDatabaseConnection(), $c->getLogger(), new TimeFactory(), $ttl);
762
+            }
763
+            return new NoopLockingProvider();
764
+        });
765
+
766
+        $this->registerService(\OCP\Files\Mount\IMountManager::class, function () {
767
+            return new \OC\Files\Mount\Manager();
768
+        });
769
+        $this->registerAlias('MountManager', \OCP\Files\Mount\IMountManager::class);
770
+
771
+        $this->registerService(\OCP\Files\IMimeTypeDetector::class, function (Server $c) {
772
+            return new \OC\Files\Type\Detection(
773
+                $c->getURLGenerator(),
774
+                \OC::$configDir,
775
+                \OC::$SERVERROOT . '/resources/config/'
776
+            );
777
+        });
778
+        $this->registerAlias('MimeTypeDetector', \OCP\Files\IMimeTypeDetector::class);
779
+
780
+        $this->registerService(\OCP\Files\IMimeTypeLoader::class, function (Server $c) {
781
+            return new \OC\Files\Type\Loader(
782
+                $c->getDatabaseConnection()
783
+            );
784
+        });
785
+        $this->registerAlias('MimeTypeLoader', \OCP\Files\IMimeTypeLoader::class);
786
+
787
+        $this->registerService(\OCP\Notification\IManager::class, function (Server $c) {
788
+            return new Manager(
789
+                $c->query(IValidator::class)
790
+            );
791
+        });
792
+        $this->registerAlias('NotificationManager', \OCP\Notification\IManager::class);
793
+
794
+        $this->registerService(\OC\CapabilitiesManager::class, function (Server $c) {
795
+            $manager = new \OC\CapabilitiesManager($c->getLogger());
796
+            $manager->registerCapability(function () use ($c) {
797
+                return new \OC\OCS\CoreCapabilities($c->getConfig());
798
+            });
799
+            return $manager;
800
+        });
801
+        $this->registerAlias('CapabilitiesManager', \OC\CapabilitiesManager::class);
802
+
803
+        $this->registerService(\OCP\Comments\ICommentsManager::class, function(Server $c) {
804
+            $config = $c->getConfig();
805
+            $factoryClass = $config->getSystemValue('comments.managerFactory', '\OC\Comments\ManagerFactory');
806
+            /** @var \OCP\Comments\ICommentsManagerFactory $factory */
807
+            $factory = new $factoryClass($this);
808
+            return $factory->getManager();
809
+        });
810
+        $this->registerAlias('CommentsManager', \OCP\Comments\ICommentsManager::class);
811
+
812
+        $this->registerService('ThemingDefaults', function(Server $c) {
813
+            /*
814 814
 			 * Dark magic for autoloader.
815 815
 			 * If we do a class_exists it will try to load the class which will
816 816
 			 * make composer cache the result. Resulting in errors when enabling
817 817
 			 * the theming app.
818 818
 			 */
819
-			$prefixes = \OC::$composerAutoloader->getPrefixesPsr4();
820
-			if (isset($prefixes['OCA\\Theming\\'])) {
821
-				$classExists = true;
822
-			} else {
823
-				$classExists = false;
824
-			}
825
-
826
-			if ($classExists && $c->getConfig()->getSystemValue('installed', false) && $c->getAppManager()->isInstalled('theming')) {
827
-				return new ThemingDefaults(
828
-					$c->getConfig(),
829
-					$c->getL10N('theming'),
830
-					$c->getURLGenerator(),
831
-					new \OC_Defaults(),
832
-					$c->getAppDataDir('theming'),
833
-					$c->getMemCacheFactory()
834
-				);
835
-			}
836
-			return new \OC_Defaults();
837
-		});
838
-		$this->registerService(EventDispatcher::class, function () {
839
-			return new EventDispatcher();
840
-		});
841
-		$this->registerAlias('EventDispatcher', EventDispatcher::class);
842
-		$this->registerAlias(EventDispatcherInterface::class, EventDispatcher::class);
843
-
844
-		$this->registerService('CryptoWrapper', function (Server $c) {
845
-			// FIXME: Instantiiated here due to cyclic dependency
846
-			$request = new Request(
847
-				[
848
-					'get' => $_GET,
849
-					'post' => $_POST,
850
-					'files' => $_FILES,
851
-					'server' => $_SERVER,
852
-					'env' => $_ENV,
853
-					'cookies' => $_COOKIE,
854
-					'method' => (isset($_SERVER) && isset($_SERVER['REQUEST_METHOD']))
855
-						? $_SERVER['REQUEST_METHOD']
856
-						: null,
857
-				],
858
-				$c->getSecureRandom(),
859
-				$c->getConfig()
860
-			);
861
-
862
-			return new CryptoWrapper(
863
-				$c->getConfig(),
864
-				$c->getCrypto(),
865
-				$c->getSecureRandom(),
866
-				$request
867
-			);
868
-		});
869
-		$this->registerService('CsrfTokenManager', function (Server $c) {
870
-			$tokenGenerator = new CsrfTokenGenerator($c->getSecureRandom());
871
-
872
-			return new CsrfTokenManager(
873
-				$tokenGenerator,
874
-				$c->query(SessionStorage::class)
875
-			);
876
-		});
877
-		$this->registerService(SessionStorage::class, function (Server $c) {
878
-			return new SessionStorage($c->getSession());
879
-		});
880
-		$this->registerService(\OCP\Security\IContentSecurityPolicyManager::class, function (Server $c) {
881
-			return new ContentSecurityPolicyManager();
882
-		});
883
-		$this->registerAlias('ContentSecurityPolicyManager', \OCP\Security\IContentSecurityPolicyManager::class);
884
-
885
-		$this->registerService('ContentSecurityPolicyNonceManager', function(Server $c) {
886
-			return new ContentSecurityPolicyNonceManager(
887
-				$c->getCsrfTokenManager(),
888
-				$c->getRequest()
889
-			);
890
-		});
891
-
892
-		$this->registerService(\OCP\Share\IManager::class, function(Server $c) {
893
-			$config = $c->getConfig();
894
-			$factoryClass = $config->getSystemValue('sharing.managerFactory', '\OC\Share20\ProviderFactory');
895
-			/** @var \OCP\Share\IProviderFactory $factory */
896
-			$factory = new $factoryClass($this);
897
-
898
-			$manager = new \OC\Share20\Manager(
899
-				$c->getLogger(),
900
-				$c->getConfig(),
901
-				$c->getSecureRandom(),
902
-				$c->getHasher(),
903
-				$c->getMountManager(),
904
-				$c->getGroupManager(),
905
-				$c->getL10N('core'),
906
-				$factory,
907
-				$c->getUserManager(),
908
-				$c->getLazyRootFolder(),
909
-				$c->getEventDispatcher()
910
-			);
911
-
912
-			return $manager;
913
-		});
914
-		$this->registerAlias('ShareManager', \OCP\Share\IManager::class);
915
-
916
-		$this->registerService('SettingsManager', function(Server $c) {
917
-			$manager = new \OC\Settings\Manager(
918
-				$c->getLogger(),
919
-				$c->getDatabaseConnection(),
920
-				$c->getL10N('lib'),
921
-				$c->getConfig(),
922
-				$c->getEncryptionManager(),
923
-				$c->getUserManager(),
924
-				$c->getLockingProvider(),
925
-				$c->getRequest(),
926
-				new \OC\Settings\Mapper($c->getDatabaseConnection()),
927
-				$c->getURLGenerator()
928
-			);
929
-			return $manager;
930
-		});
931
-		$this->registerService(\OC\Files\AppData\Factory::class, function (Server $c) {
932
-			return new \OC\Files\AppData\Factory(
933
-				$c->getRootFolder(),
934
-				$c->getSystemConfig()
935
-			);
936
-		});
937
-
938
-		$this->registerService('LockdownManager', function (Server $c) {
939
-			return new LockdownManager(function() use ($c) {
940
-				return $c->getSession();
941
-			});
942
-		});
943
-
944
-		$this->registerService(ICloudIdManager::class, function (Server $c) {
945
-			return new CloudIdManager();
946
-		});
947
-
948
-		/* To trick DI since we don't extend the DIContainer here */
949
-		$this->registerService(CleanPreviewsBackgroundJob::class, function (Server $c) {
950
-			return new CleanPreviewsBackgroundJob(
951
-				$c->getRootFolder(),
952
-				$c->getLogger(),
953
-				$c->getJobList(),
954
-				new TimeFactory()
955
-			);
956
-		});
957
-
958
-		$this->registerAlias(\OCP\AppFramework\Utility\IControllerMethodReflector::class, \OC\AppFramework\Utility\ControllerMethodReflector::class);
959
-		$this->registerAlias('ControllerMethodReflector', \OCP\AppFramework\Utility\IControllerMethodReflector::class);
960
-
961
-		$this->registerAlias(\OCP\AppFramework\Utility\ITimeFactory::class, \OC\AppFramework\Utility\TimeFactory::class);
962
-		$this->registerAlias('TimeFactory', \OCP\AppFramework\Utility\ITimeFactory::class);
963
-
964
-		$this->registerService(\OCP\ISession::class, function(SimpleContainer $c) {
965
-			return $c->query(\OCP\IUserSession::class)->getSession();
966
-		});
967
-
968
-		$this->registerService(IShareHelper::class, function(Server $c) {
969
-			return new ShareHelper(
970
-				$c->getLazyRootFolder()
971
-			);
972
-		});
973
-	}
974
-
975
-	/**
976
-	 * @return \OCP\Contacts\IManager
977
-	 */
978
-	public function getContactsManager() {
979
-		return $this->query('ContactsManager');
980
-	}
981
-
982
-	/**
983
-	 * @return \OC\Encryption\Manager
984
-	 */
985
-	public function getEncryptionManager() {
986
-		return $this->query('EncryptionManager');
987
-	}
988
-
989
-	/**
990
-	 * @return \OC\Encryption\File
991
-	 */
992
-	public function getEncryptionFilesHelper() {
993
-		return $this->query('EncryptionFileHelper');
994
-	}
995
-
996
-	/**
997
-	 * @return \OCP\Encryption\Keys\IStorage
998
-	 */
999
-	public function getEncryptionKeyStorage() {
1000
-		return $this->query('EncryptionKeyStorage');
1001
-	}
1002
-
1003
-	/**
1004
-	 * The current request object holding all information about the request
1005
-	 * currently being processed is returned from this method.
1006
-	 * In case the current execution was not initiated by a web request null is returned
1007
-	 *
1008
-	 * @return \OCP\IRequest
1009
-	 */
1010
-	public function getRequest() {
1011
-		return $this->query('Request');
1012
-	}
1013
-
1014
-	/**
1015
-	 * Returns the preview manager which can create preview images for a given file
1016
-	 *
1017
-	 * @return \OCP\IPreview
1018
-	 */
1019
-	public function getPreviewManager() {
1020
-		return $this->query('PreviewManager');
1021
-	}
1022
-
1023
-	/**
1024
-	 * Returns the tag manager which can get and set tags for different object types
1025
-	 *
1026
-	 * @see \OCP\ITagManager::load()
1027
-	 * @return \OCP\ITagManager
1028
-	 */
1029
-	public function getTagManager() {
1030
-		return $this->query('TagManager');
1031
-	}
1032
-
1033
-	/**
1034
-	 * Returns the system-tag manager
1035
-	 *
1036
-	 * @return \OCP\SystemTag\ISystemTagManager
1037
-	 *
1038
-	 * @since 9.0.0
1039
-	 */
1040
-	public function getSystemTagManager() {
1041
-		return $this->query('SystemTagManager');
1042
-	}
1043
-
1044
-	/**
1045
-	 * Returns the system-tag object mapper
1046
-	 *
1047
-	 * @return \OCP\SystemTag\ISystemTagObjectMapper
1048
-	 *
1049
-	 * @since 9.0.0
1050
-	 */
1051
-	public function getSystemTagObjectMapper() {
1052
-		return $this->query('SystemTagObjectMapper');
1053
-	}
1054
-
1055
-	/**
1056
-	 * Returns the avatar manager, used for avatar functionality
1057
-	 *
1058
-	 * @return \OCP\IAvatarManager
1059
-	 */
1060
-	public function getAvatarManager() {
1061
-		return $this->query('AvatarManager');
1062
-	}
1063
-
1064
-	/**
1065
-	 * Returns the root folder of ownCloud's data directory
1066
-	 *
1067
-	 * @return \OCP\Files\IRootFolder
1068
-	 */
1069
-	public function getRootFolder() {
1070
-		return $this->query('LazyRootFolder');
1071
-	}
1072
-
1073
-	/**
1074
-	 * Returns the root folder of ownCloud's data directory
1075
-	 * This is the lazy variant so this gets only initialized once it
1076
-	 * is actually used.
1077
-	 *
1078
-	 * @return \OCP\Files\IRootFolder
1079
-	 */
1080
-	public function getLazyRootFolder() {
1081
-		return $this->query('LazyRootFolder');
1082
-	}
1083
-
1084
-	/**
1085
-	 * Returns a view to ownCloud's files folder
1086
-	 *
1087
-	 * @param string $userId user ID
1088
-	 * @return \OCP\Files\Folder|null
1089
-	 */
1090
-	public function getUserFolder($userId = null) {
1091
-		if ($userId === null) {
1092
-			$user = $this->getUserSession()->getUser();
1093
-			if (!$user) {
1094
-				return null;
1095
-			}
1096
-			$userId = $user->getUID();
1097
-		}
1098
-		$root = $this->getRootFolder();
1099
-		return $root->getUserFolder($userId);
1100
-	}
1101
-
1102
-	/**
1103
-	 * Returns an app-specific view in ownClouds data directory
1104
-	 *
1105
-	 * @return \OCP\Files\Folder
1106
-	 * @deprecated since 9.2.0 use IAppData
1107
-	 */
1108
-	public function getAppFolder() {
1109
-		$dir = '/' . \OC_App::getCurrentApp();
1110
-		$root = $this->getRootFolder();
1111
-		if (!$root->nodeExists($dir)) {
1112
-			$folder = $root->newFolder($dir);
1113
-		} else {
1114
-			$folder = $root->get($dir);
1115
-		}
1116
-		return $folder;
1117
-	}
1118
-
1119
-	/**
1120
-	 * @return \OC\User\Manager
1121
-	 */
1122
-	public function getUserManager() {
1123
-		return $this->query('UserManager');
1124
-	}
1125
-
1126
-	/**
1127
-	 * @return \OC\Group\Manager
1128
-	 */
1129
-	public function getGroupManager() {
1130
-		return $this->query('GroupManager');
1131
-	}
1132
-
1133
-	/**
1134
-	 * @return \OC\User\Session
1135
-	 */
1136
-	public function getUserSession() {
1137
-		return $this->query('UserSession');
1138
-	}
1139
-
1140
-	/**
1141
-	 * @return \OCP\ISession
1142
-	 */
1143
-	public function getSession() {
1144
-		return $this->query('UserSession')->getSession();
1145
-	}
1146
-
1147
-	/**
1148
-	 * @param \OCP\ISession $session
1149
-	 */
1150
-	public function setSession(\OCP\ISession $session) {
1151
-		$this->query(SessionStorage::class)->setSession($session);
1152
-		$this->query('UserSession')->setSession($session);
1153
-		$this->query(Store::class)->setSession($session);
1154
-	}
1155
-
1156
-	/**
1157
-	 * @return \OC\Authentication\TwoFactorAuth\Manager
1158
-	 */
1159
-	public function getTwoFactorAuthManager() {
1160
-		return $this->query('\OC\Authentication\TwoFactorAuth\Manager');
1161
-	}
1162
-
1163
-	/**
1164
-	 * @return \OC\NavigationManager
1165
-	 */
1166
-	public function getNavigationManager() {
1167
-		return $this->query('NavigationManager');
1168
-	}
1169
-
1170
-	/**
1171
-	 * @return \OCP\IConfig
1172
-	 */
1173
-	public function getConfig() {
1174
-		return $this->query('AllConfig');
1175
-	}
1176
-
1177
-	/**
1178
-	 * @internal For internal use only
1179
-	 * @return \OC\SystemConfig
1180
-	 */
1181
-	public function getSystemConfig() {
1182
-		return $this->query('SystemConfig');
1183
-	}
1184
-
1185
-	/**
1186
-	 * Returns the app config manager
1187
-	 *
1188
-	 * @return \OCP\IAppConfig
1189
-	 */
1190
-	public function getAppConfig() {
1191
-		return $this->query('AppConfig');
1192
-	}
1193
-
1194
-	/**
1195
-	 * @return \OCP\L10N\IFactory
1196
-	 */
1197
-	public function getL10NFactory() {
1198
-		return $this->query('L10NFactory');
1199
-	}
1200
-
1201
-	/**
1202
-	 * get an L10N instance
1203
-	 *
1204
-	 * @param string $app appid
1205
-	 * @param string $lang
1206
-	 * @return IL10N
1207
-	 */
1208
-	public function getL10N($app, $lang = null) {
1209
-		return $this->getL10NFactory()->get($app, $lang);
1210
-	}
1211
-
1212
-	/**
1213
-	 * @return \OCP\IURLGenerator
1214
-	 */
1215
-	public function getURLGenerator() {
1216
-		return $this->query('URLGenerator');
1217
-	}
1218
-
1219
-	/**
1220
-	 * @return \OCP\IHelper
1221
-	 */
1222
-	public function getHelper() {
1223
-		return $this->query('AppHelper');
1224
-	}
1225
-
1226
-	/**
1227
-	 * @return AppFetcher
1228
-	 */
1229
-	public function getAppFetcher() {
1230
-		return $this->query('AppFetcher');
1231
-	}
1232
-
1233
-	/**
1234
-	 * Returns an ICache instance. Since 8.1.0 it returns a fake cache. Use
1235
-	 * getMemCacheFactory() instead.
1236
-	 *
1237
-	 * @return \OCP\ICache
1238
-	 * @deprecated 8.1.0 use getMemCacheFactory to obtain a proper cache
1239
-	 */
1240
-	public function getCache() {
1241
-		return $this->query('UserCache');
1242
-	}
1243
-
1244
-	/**
1245
-	 * Returns an \OCP\CacheFactory instance
1246
-	 *
1247
-	 * @return \OCP\ICacheFactory
1248
-	 */
1249
-	public function getMemCacheFactory() {
1250
-		return $this->query('MemCacheFactory');
1251
-	}
1252
-
1253
-	/**
1254
-	 * Returns an \OC\RedisFactory instance
1255
-	 *
1256
-	 * @return \OC\RedisFactory
1257
-	 */
1258
-	public function getGetRedisFactory() {
1259
-		return $this->query('RedisFactory');
1260
-	}
1261
-
1262
-
1263
-	/**
1264
-	 * Returns the current session
1265
-	 *
1266
-	 * @return \OCP\IDBConnection
1267
-	 */
1268
-	public function getDatabaseConnection() {
1269
-		return $this->query('DatabaseConnection');
1270
-	}
1271
-
1272
-	/**
1273
-	 * Returns the activity manager
1274
-	 *
1275
-	 * @return \OCP\Activity\IManager
1276
-	 */
1277
-	public function getActivityManager() {
1278
-		return $this->query('ActivityManager');
1279
-	}
1280
-
1281
-	/**
1282
-	 * Returns an job list for controlling background jobs
1283
-	 *
1284
-	 * @return \OCP\BackgroundJob\IJobList
1285
-	 */
1286
-	public function getJobList() {
1287
-		return $this->query('JobList');
1288
-	}
1289
-
1290
-	/**
1291
-	 * Returns a logger instance
1292
-	 *
1293
-	 * @return \OCP\ILogger
1294
-	 */
1295
-	public function getLogger() {
1296
-		return $this->query('Logger');
1297
-	}
1298
-
1299
-	/**
1300
-	 * Returns a router for generating and matching urls
1301
-	 *
1302
-	 * @return \OCP\Route\IRouter
1303
-	 */
1304
-	public function getRouter() {
1305
-		return $this->query('Router');
1306
-	}
1307
-
1308
-	/**
1309
-	 * Returns a search instance
1310
-	 *
1311
-	 * @return \OCP\ISearch
1312
-	 */
1313
-	public function getSearch() {
1314
-		return $this->query('Search');
1315
-	}
1316
-
1317
-	/**
1318
-	 * Returns a SecureRandom instance
1319
-	 *
1320
-	 * @return \OCP\Security\ISecureRandom
1321
-	 */
1322
-	public function getSecureRandom() {
1323
-		return $this->query('SecureRandom');
1324
-	}
1325
-
1326
-	/**
1327
-	 * Returns a Crypto instance
1328
-	 *
1329
-	 * @return \OCP\Security\ICrypto
1330
-	 */
1331
-	public function getCrypto() {
1332
-		return $this->query('Crypto');
1333
-	}
1334
-
1335
-	/**
1336
-	 * Returns a Hasher instance
1337
-	 *
1338
-	 * @return \OCP\Security\IHasher
1339
-	 */
1340
-	public function getHasher() {
1341
-		return $this->query('Hasher');
1342
-	}
1343
-
1344
-	/**
1345
-	 * Returns a CredentialsManager instance
1346
-	 *
1347
-	 * @return \OCP\Security\ICredentialsManager
1348
-	 */
1349
-	public function getCredentialsManager() {
1350
-		return $this->query('CredentialsManager');
1351
-	}
1352
-
1353
-	/**
1354
-	 * Returns an instance of the HTTP helper class
1355
-	 *
1356
-	 * @deprecated Use getHTTPClientService()
1357
-	 * @return \OC\HTTPHelper
1358
-	 */
1359
-	public function getHTTPHelper() {
1360
-		return $this->query('HTTPHelper');
1361
-	}
1362
-
1363
-	/**
1364
-	 * Get the certificate manager for the user
1365
-	 *
1366
-	 * @param string $userId (optional) if not specified the current loggedin user is used, use null to get the system certificate manager
1367
-	 * @return \OCP\ICertificateManager | null if $uid is null and no user is logged in
1368
-	 */
1369
-	public function getCertificateManager($userId = '') {
1370
-		if ($userId === '') {
1371
-			$userSession = $this->getUserSession();
1372
-			$user = $userSession->getUser();
1373
-			if (is_null($user)) {
1374
-				return null;
1375
-			}
1376
-			$userId = $user->getUID();
1377
-		}
1378
-		return new CertificateManager($userId, new View(), $this->getConfig(), $this->getLogger());
1379
-	}
1380
-
1381
-	/**
1382
-	 * Returns an instance of the HTTP client service
1383
-	 *
1384
-	 * @return \OCP\Http\Client\IClientService
1385
-	 */
1386
-	public function getHTTPClientService() {
1387
-		return $this->query('HttpClientService');
1388
-	}
1389
-
1390
-	/**
1391
-	 * Create a new event source
1392
-	 *
1393
-	 * @return \OCP\IEventSource
1394
-	 */
1395
-	public function createEventSource() {
1396
-		return new \OC_EventSource();
1397
-	}
1398
-
1399
-	/**
1400
-	 * Get the active event logger
1401
-	 *
1402
-	 * The returned logger only logs data when debug mode is enabled
1403
-	 *
1404
-	 * @return \OCP\Diagnostics\IEventLogger
1405
-	 */
1406
-	public function getEventLogger() {
1407
-		return $this->query('EventLogger');
1408
-	}
1409
-
1410
-	/**
1411
-	 * Get the active query logger
1412
-	 *
1413
-	 * The returned logger only logs data when debug mode is enabled
1414
-	 *
1415
-	 * @return \OCP\Diagnostics\IQueryLogger
1416
-	 */
1417
-	public function getQueryLogger() {
1418
-		return $this->query('QueryLogger');
1419
-	}
1420
-
1421
-	/**
1422
-	 * Get the manager for temporary files and folders
1423
-	 *
1424
-	 * @return \OCP\ITempManager
1425
-	 */
1426
-	public function getTempManager() {
1427
-		return $this->query('TempManager');
1428
-	}
1429
-
1430
-	/**
1431
-	 * Get the app manager
1432
-	 *
1433
-	 * @return \OCP\App\IAppManager
1434
-	 */
1435
-	public function getAppManager() {
1436
-		return $this->query('AppManager');
1437
-	}
1438
-
1439
-	/**
1440
-	 * Creates a new mailer
1441
-	 *
1442
-	 * @return \OCP\Mail\IMailer
1443
-	 */
1444
-	public function getMailer() {
1445
-		return $this->query('Mailer');
1446
-	}
1447
-
1448
-	/**
1449
-	 * Get the webroot
1450
-	 *
1451
-	 * @return string
1452
-	 */
1453
-	public function getWebRoot() {
1454
-		return $this->webRoot;
1455
-	}
1456
-
1457
-	/**
1458
-	 * @return \OC\OCSClient
1459
-	 */
1460
-	public function getOcsClient() {
1461
-		return $this->query('OcsClient');
1462
-	}
1463
-
1464
-	/**
1465
-	 * @return \OCP\IDateTimeZone
1466
-	 */
1467
-	public function getDateTimeZone() {
1468
-		return $this->query('DateTimeZone');
1469
-	}
1470
-
1471
-	/**
1472
-	 * @return \OCP\IDateTimeFormatter
1473
-	 */
1474
-	public function getDateTimeFormatter() {
1475
-		return $this->query('DateTimeFormatter');
1476
-	}
1477
-
1478
-	/**
1479
-	 * @return \OCP\Files\Config\IMountProviderCollection
1480
-	 */
1481
-	public function getMountProviderCollection() {
1482
-		return $this->query('MountConfigManager');
1483
-	}
1484
-
1485
-	/**
1486
-	 * Get the IniWrapper
1487
-	 *
1488
-	 * @return IniGetWrapper
1489
-	 */
1490
-	public function getIniWrapper() {
1491
-		return $this->query('IniWrapper');
1492
-	}
1493
-
1494
-	/**
1495
-	 * @return \OCP\Command\IBus
1496
-	 */
1497
-	public function getCommandBus() {
1498
-		return $this->query('AsyncCommandBus');
1499
-	}
1500
-
1501
-	/**
1502
-	 * Get the trusted domain helper
1503
-	 *
1504
-	 * @return TrustedDomainHelper
1505
-	 */
1506
-	public function getTrustedDomainHelper() {
1507
-		return $this->query('TrustedDomainHelper');
1508
-	}
1509
-
1510
-	/**
1511
-	 * Get the locking provider
1512
-	 *
1513
-	 * @return \OCP\Lock\ILockingProvider
1514
-	 * @since 8.1.0
1515
-	 */
1516
-	public function getLockingProvider() {
1517
-		return $this->query('LockingProvider');
1518
-	}
1519
-
1520
-	/**
1521
-	 * @return \OCP\Files\Mount\IMountManager
1522
-	 **/
1523
-	function getMountManager() {
1524
-		return $this->query('MountManager');
1525
-	}
1526
-
1527
-	/** @return \OCP\Files\Config\IUserMountCache */
1528
-	function getUserMountCache() {
1529
-		return $this->query('UserMountCache');
1530
-	}
1531
-
1532
-	/**
1533
-	 * Get the MimeTypeDetector
1534
-	 *
1535
-	 * @return \OCP\Files\IMimeTypeDetector
1536
-	 */
1537
-	public function getMimeTypeDetector() {
1538
-		return $this->query('MimeTypeDetector');
1539
-	}
1540
-
1541
-	/**
1542
-	 * Get the MimeTypeLoader
1543
-	 *
1544
-	 * @return \OCP\Files\IMimeTypeLoader
1545
-	 */
1546
-	public function getMimeTypeLoader() {
1547
-		return $this->query('MimeTypeLoader');
1548
-	}
1549
-
1550
-	/**
1551
-	 * Get the manager of all the capabilities
1552
-	 *
1553
-	 * @return \OC\CapabilitiesManager
1554
-	 */
1555
-	public function getCapabilitiesManager() {
1556
-		return $this->query('CapabilitiesManager');
1557
-	}
1558
-
1559
-	/**
1560
-	 * Get the EventDispatcher
1561
-	 *
1562
-	 * @return EventDispatcherInterface
1563
-	 * @since 8.2.0
1564
-	 */
1565
-	public function getEventDispatcher() {
1566
-		return $this->query('EventDispatcher');
1567
-	}
1568
-
1569
-	/**
1570
-	 * Get the Notification Manager
1571
-	 *
1572
-	 * @return \OCP\Notification\IManager
1573
-	 * @since 8.2.0
1574
-	 */
1575
-	public function getNotificationManager() {
1576
-		return $this->query('NotificationManager');
1577
-	}
1578
-
1579
-	/**
1580
-	 * @return \OCP\Comments\ICommentsManager
1581
-	 */
1582
-	public function getCommentsManager() {
1583
-		return $this->query('CommentsManager');
1584
-	}
1585
-
1586
-	/**
1587
-	 * @return \OCA\Theming\ThemingDefaults
1588
-	 */
1589
-	public function getThemingDefaults() {
1590
-		return $this->query('ThemingDefaults');
1591
-	}
1592
-
1593
-	/**
1594
-	 * @return \OC\IntegrityCheck\Checker
1595
-	 */
1596
-	public function getIntegrityCodeChecker() {
1597
-		return $this->query('IntegrityCodeChecker');
1598
-	}
1599
-
1600
-	/**
1601
-	 * @return \OC\Session\CryptoWrapper
1602
-	 */
1603
-	public function getSessionCryptoWrapper() {
1604
-		return $this->query('CryptoWrapper');
1605
-	}
1606
-
1607
-	/**
1608
-	 * @return CsrfTokenManager
1609
-	 */
1610
-	public function getCsrfTokenManager() {
1611
-		return $this->query('CsrfTokenManager');
1612
-	}
1613
-
1614
-	/**
1615
-	 * @return Throttler
1616
-	 */
1617
-	public function getBruteForceThrottler() {
1618
-		return $this->query('Throttler');
1619
-	}
1620
-
1621
-	/**
1622
-	 * @return IContentSecurityPolicyManager
1623
-	 */
1624
-	public function getContentSecurityPolicyManager() {
1625
-		return $this->query('ContentSecurityPolicyManager');
1626
-	}
1627
-
1628
-	/**
1629
-	 * @return ContentSecurityPolicyNonceManager
1630
-	 */
1631
-	public function getContentSecurityPolicyNonceManager() {
1632
-		return $this->query('ContentSecurityPolicyNonceManager');
1633
-	}
1634
-
1635
-	/**
1636
-	 * Not a public API as of 8.2, wait for 9.0
1637
-	 *
1638
-	 * @return \OCA\Files_External\Service\BackendService
1639
-	 */
1640
-	public function getStoragesBackendService() {
1641
-		return $this->query('OCA\\Files_External\\Service\\BackendService');
1642
-	}
1643
-
1644
-	/**
1645
-	 * Not a public API as of 8.2, wait for 9.0
1646
-	 *
1647
-	 * @return \OCA\Files_External\Service\GlobalStoragesService
1648
-	 */
1649
-	public function getGlobalStoragesService() {
1650
-		return $this->query('OCA\\Files_External\\Service\\GlobalStoragesService');
1651
-	}
1652
-
1653
-	/**
1654
-	 * Not a public API as of 8.2, wait for 9.0
1655
-	 *
1656
-	 * @return \OCA\Files_External\Service\UserGlobalStoragesService
1657
-	 */
1658
-	public function getUserGlobalStoragesService() {
1659
-		return $this->query('OCA\\Files_External\\Service\\UserGlobalStoragesService');
1660
-	}
1661
-
1662
-	/**
1663
-	 * Not a public API as of 8.2, wait for 9.0
1664
-	 *
1665
-	 * @return \OCA\Files_External\Service\UserStoragesService
1666
-	 */
1667
-	public function getUserStoragesService() {
1668
-		return $this->query('OCA\\Files_External\\Service\\UserStoragesService');
1669
-	}
1670
-
1671
-	/**
1672
-	 * @return \OCP\Share\IManager
1673
-	 */
1674
-	public function getShareManager() {
1675
-		return $this->query('ShareManager');
1676
-	}
1677
-
1678
-	/**
1679
-	 * Returns the LDAP Provider
1680
-	 *
1681
-	 * @return \OCP\LDAP\ILDAPProvider
1682
-	 */
1683
-	public function getLDAPProvider() {
1684
-		return $this->query('LDAPProvider');
1685
-	}
1686
-
1687
-	/**
1688
-	 * @return \OCP\Settings\IManager
1689
-	 */
1690
-	public function getSettingsManager() {
1691
-		return $this->query('SettingsManager');
1692
-	}
1693
-
1694
-	/**
1695
-	 * @return \OCP\Files\IAppData
1696
-	 */
1697
-	public function getAppDataDir($app) {
1698
-		/** @var \OC\Files\AppData\Factory $factory */
1699
-		$factory = $this->query(\OC\Files\AppData\Factory::class);
1700
-		return $factory->get($app);
1701
-	}
1702
-
1703
-	/**
1704
-	 * @return \OCP\Lockdown\ILockdownManager
1705
-	 */
1706
-	public function getLockdownManager() {
1707
-		return $this->query('LockdownManager');
1708
-	}
1709
-
1710
-	/**
1711
-	 * @return \OCP\Federation\ICloudIdManager
1712
-	 */
1713
-	public function getCloudIdManager() {
1714
-		return $this->query(ICloudIdManager::class);
1715
-	}
819
+            $prefixes = \OC::$composerAutoloader->getPrefixesPsr4();
820
+            if (isset($prefixes['OCA\\Theming\\'])) {
821
+                $classExists = true;
822
+            } else {
823
+                $classExists = false;
824
+            }
825
+
826
+            if ($classExists && $c->getConfig()->getSystemValue('installed', false) && $c->getAppManager()->isInstalled('theming')) {
827
+                return new ThemingDefaults(
828
+                    $c->getConfig(),
829
+                    $c->getL10N('theming'),
830
+                    $c->getURLGenerator(),
831
+                    new \OC_Defaults(),
832
+                    $c->getAppDataDir('theming'),
833
+                    $c->getMemCacheFactory()
834
+                );
835
+            }
836
+            return new \OC_Defaults();
837
+        });
838
+        $this->registerService(EventDispatcher::class, function () {
839
+            return new EventDispatcher();
840
+        });
841
+        $this->registerAlias('EventDispatcher', EventDispatcher::class);
842
+        $this->registerAlias(EventDispatcherInterface::class, EventDispatcher::class);
843
+
844
+        $this->registerService('CryptoWrapper', function (Server $c) {
845
+            // FIXME: Instantiiated here due to cyclic dependency
846
+            $request = new Request(
847
+                [
848
+                    'get' => $_GET,
849
+                    'post' => $_POST,
850
+                    'files' => $_FILES,
851
+                    'server' => $_SERVER,
852
+                    'env' => $_ENV,
853
+                    'cookies' => $_COOKIE,
854
+                    'method' => (isset($_SERVER) && isset($_SERVER['REQUEST_METHOD']))
855
+                        ? $_SERVER['REQUEST_METHOD']
856
+                        : null,
857
+                ],
858
+                $c->getSecureRandom(),
859
+                $c->getConfig()
860
+            );
861
+
862
+            return new CryptoWrapper(
863
+                $c->getConfig(),
864
+                $c->getCrypto(),
865
+                $c->getSecureRandom(),
866
+                $request
867
+            );
868
+        });
869
+        $this->registerService('CsrfTokenManager', function (Server $c) {
870
+            $tokenGenerator = new CsrfTokenGenerator($c->getSecureRandom());
871
+
872
+            return new CsrfTokenManager(
873
+                $tokenGenerator,
874
+                $c->query(SessionStorage::class)
875
+            );
876
+        });
877
+        $this->registerService(SessionStorage::class, function (Server $c) {
878
+            return new SessionStorage($c->getSession());
879
+        });
880
+        $this->registerService(\OCP\Security\IContentSecurityPolicyManager::class, function (Server $c) {
881
+            return new ContentSecurityPolicyManager();
882
+        });
883
+        $this->registerAlias('ContentSecurityPolicyManager', \OCP\Security\IContentSecurityPolicyManager::class);
884
+
885
+        $this->registerService('ContentSecurityPolicyNonceManager', function(Server $c) {
886
+            return new ContentSecurityPolicyNonceManager(
887
+                $c->getCsrfTokenManager(),
888
+                $c->getRequest()
889
+            );
890
+        });
891
+
892
+        $this->registerService(\OCP\Share\IManager::class, function(Server $c) {
893
+            $config = $c->getConfig();
894
+            $factoryClass = $config->getSystemValue('sharing.managerFactory', '\OC\Share20\ProviderFactory');
895
+            /** @var \OCP\Share\IProviderFactory $factory */
896
+            $factory = new $factoryClass($this);
897
+
898
+            $manager = new \OC\Share20\Manager(
899
+                $c->getLogger(),
900
+                $c->getConfig(),
901
+                $c->getSecureRandom(),
902
+                $c->getHasher(),
903
+                $c->getMountManager(),
904
+                $c->getGroupManager(),
905
+                $c->getL10N('core'),
906
+                $factory,
907
+                $c->getUserManager(),
908
+                $c->getLazyRootFolder(),
909
+                $c->getEventDispatcher()
910
+            );
911
+
912
+            return $manager;
913
+        });
914
+        $this->registerAlias('ShareManager', \OCP\Share\IManager::class);
915
+
916
+        $this->registerService('SettingsManager', function(Server $c) {
917
+            $manager = new \OC\Settings\Manager(
918
+                $c->getLogger(),
919
+                $c->getDatabaseConnection(),
920
+                $c->getL10N('lib'),
921
+                $c->getConfig(),
922
+                $c->getEncryptionManager(),
923
+                $c->getUserManager(),
924
+                $c->getLockingProvider(),
925
+                $c->getRequest(),
926
+                new \OC\Settings\Mapper($c->getDatabaseConnection()),
927
+                $c->getURLGenerator()
928
+            );
929
+            return $manager;
930
+        });
931
+        $this->registerService(\OC\Files\AppData\Factory::class, function (Server $c) {
932
+            return new \OC\Files\AppData\Factory(
933
+                $c->getRootFolder(),
934
+                $c->getSystemConfig()
935
+            );
936
+        });
937
+
938
+        $this->registerService('LockdownManager', function (Server $c) {
939
+            return new LockdownManager(function() use ($c) {
940
+                return $c->getSession();
941
+            });
942
+        });
943
+
944
+        $this->registerService(ICloudIdManager::class, function (Server $c) {
945
+            return new CloudIdManager();
946
+        });
947
+
948
+        /* To trick DI since we don't extend the DIContainer here */
949
+        $this->registerService(CleanPreviewsBackgroundJob::class, function (Server $c) {
950
+            return new CleanPreviewsBackgroundJob(
951
+                $c->getRootFolder(),
952
+                $c->getLogger(),
953
+                $c->getJobList(),
954
+                new TimeFactory()
955
+            );
956
+        });
957
+
958
+        $this->registerAlias(\OCP\AppFramework\Utility\IControllerMethodReflector::class, \OC\AppFramework\Utility\ControllerMethodReflector::class);
959
+        $this->registerAlias('ControllerMethodReflector', \OCP\AppFramework\Utility\IControllerMethodReflector::class);
960
+
961
+        $this->registerAlias(\OCP\AppFramework\Utility\ITimeFactory::class, \OC\AppFramework\Utility\TimeFactory::class);
962
+        $this->registerAlias('TimeFactory', \OCP\AppFramework\Utility\ITimeFactory::class);
963
+
964
+        $this->registerService(\OCP\ISession::class, function(SimpleContainer $c) {
965
+            return $c->query(\OCP\IUserSession::class)->getSession();
966
+        });
967
+
968
+        $this->registerService(IShareHelper::class, function(Server $c) {
969
+            return new ShareHelper(
970
+                $c->getLazyRootFolder()
971
+            );
972
+        });
973
+    }
974
+
975
+    /**
976
+     * @return \OCP\Contacts\IManager
977
+     */
978
+    public function getContactsManager() {
979
+        return $this->query('ContactsManager');
980
+    }
981
+
982
+    /**
983
+     * @return \OC\Encryption\Manager
984
+     */
985
+    public function getEncryptionManager() {
986
+        return $this->query('EncryptionManager');
987
+    }
988
+
989
+    /**
990
+     * @return \OC\Encryption\File
991
+     */
992
+    public function getEncryptionFilesHelper() {
993
+        return $this->query('EncryptionFileHelper');
994
+    }
995
+
996
+    /**
997
+     * @return \OCP\Encryption\Keys\IStorage
998
+     */
999
+    public function getEncryptionKeyStorage() {
1000
+        return $this->query('EncryptionKeyStorage');
1001
+    }
1002
+
1003
+    /**
1004
+     * The current request object holding all information about the request
1005
+     * currently being processed is returned from this method.
1006
+     * In case the current execution was not initiated by a web request null is returned
1007
+     *
1008
+     * @return \OCP\IRequest
1009
+     */
1010
+    public function getRequest() {
1011
+        return $this->query('Request');
1012
+    }
1013
+
1014
+    /**
1015
+     * Returns the preview manager which can create preview images for a given file
1016
+     *
1017
+     * @return \OCP\IPreview
1018
+     */
1019
+    public function getPreviewManager() {
1020
+        return $this->query('PreviewManager');
1021
+    }
1022
+
1023
+    /**
1024
+     * Returns the tag manager which can get and set tags for different object types
1025
+     *
1026
+     * @see \OCP\ITagManager::load()
1027
+     * @return \OCP\ITagManager
1028
+     */
1029
+    public function getTagManager() {
1030
+        return $this->query('TagManager');
1031
+    }
1032
+
1033
+    /**
1034
+     * Returns the system-tag manager
1035
+     *
1036
+     * @return \OCP\SystemTag\ISystemTagManager
1037
+     *
1038
+     * @since 9.0.0
1039
+     */
1040
+    public function getSystemTagManager() {
1041
+        return $this->query('SystemTagManager');
1042
+    }
1043
+
1044
+    /**
1045
+     * Returns the system-tag object mapper
1046
+     *
1047
+     * @return \OCP\SystemTag\ISystemTagObjectMapper
1048
+     *
1049
+     * @since 9.0.0
1050
+     */
1051
+    public function getSystemTagObjectMapper() {
1052
+        return $this->query('SystemTagObjectMapper');
1053
+    }
1054
+
1055
+    /**
1056
+     * Returns the avatar manager, used for avatar functionality
1057
+     *
1058
+     * @return \OCP\IAvatarManager
1059
+     */
1060
+    public function getAvatarManager() {
1061
+        return $this->query('AvatarManager');
1062
+    }
1063
+
1064
+    /**
1065
+     * Returns the root folder of ownCloud's data directory
1066
+     *
1067
+     * @return \OCP\Files\IRootFolder
1068
+     */
1069
+    public function getRootFolder() {
1070
+        return $this->query('LazyRootFolder');
1071
+    }
1072
+
1073
+    /**
1074
+     * Returns the root folder of ownCloud's data directory
1075
+     * This is the lazy variant so this gets only initialized once it
1076
+     * is actually used.
1077
+     *
1078
+     * @return \OCP\Files\IRootFolder
1079
+     */
1080
+    public function getLazyRootFolder() {
1081
+        return $this->query('LazyRootFolder');
1082
+    }
1083
+
1084
+    /**
1085
+     * Returns a view to ownCloud's files folder
1086
+     *
1087
+     * @param string $userId user ID
1088
+     * @return \OCP\Files\Folder|null
1089
+     */
1090
+    public function getUserFolder($userId = null) {
1091
+        if ($userId === null) {
1092
+            $user = $this->getUserSession()->getUser();
1093
+            if (!$user) {
1094
+                return null;
1095
+            }
1096
+            $userId = $user->getUID();
1097
+        }
1098
+        $root = $this->getRootFolder();
1099
+        return $root->getUserFolder($userId);
1100
+    }
1101
+
1102
+    /**
1103
+     * Returns an app-specific view in ownClouds data directory
1104
+     *
1105
+     * @return \OCP\Files\Folder
1106
+     * @deprecated since 9.2.0 use IAppData
1107
+     */
1108
+    public function getAppFolder() {
1109
+        $dir = '/' . \OC_App::getCurrentApp();
1110
+        $root = $this->getRootFolder();
1111
+        if (!$root->nodeExists($dir)) {
1112
+            $folder = $root->newFolder($dir);
1113
+        } else {
1114
+            $folder = $root->get($dir);
1115
+        }
1116
+        return $folder;
1117
+    }
1118
+
1119
+    /**
1120
+     * @return \OC\User\Manager
1121
+     */
1122
+    public function getUserManager() {
1123
+        return $this->query('UserManager');
1124
+    }
1125
+
1126
+    /**
1127
+     * @return \OC\Group\Manager
1128
+     */
1129
+    public function getGroupManager() {
1130
+        return $this->query('GroupManager');
1131
+    }
1132
+
1133
+    /**
1134
+     * @return \OC\User\Session
1135
+     */
1136
+    public function getUserSession() {
1137
+        return $this->query('UserSession');
1138
+    }
1139
+
1140
+    /**
1141
+     * @return \OCP\ISession
1142
+     */
1143
+    public function getSession() {
1144
+        return $this->query('UserSession')->getSession();
1145
+    }
1146
+
1147
+    /**
1148
+     * @param \OCP\ISession $session
1149
+     */
1150
+    public function setSession(\OCP\ISession $session) {
1151
+        $this->query(SessionStorage::class)->setSession($session);
1152
+        $this->query('UserSession')->setSession($session);
1153
+        $this->query(Store::class)->setSession($session);
1154
+    }
1155
+
1156
+    /**
1157
+     * @return \OC\Authentication\TwoFactorAuth\Manager
1158
+     */
1159
+    public function getTwoFactorAuthManager() {
1160
+        return $this->query('\OC\Authentication\TwoFactorAuth\Manager');
1161
+    }
1162
+
1163
+    /**
1164
+     * @return \OC\NavigationManager
1165
+     */
1166
+    public function getNavigationManager() {
1167
+        return $this->query('NavigationManager');
1168
+    }
1169
+
1170
+    /**
1171
+     * @return \OCP\IConfig
1172
+     */
1173
+    public function getConfig() {
1174
+        return $this->query('AllConfig');
1175
+    }
1176
+
1177
+    /**
1178
+     * @internal For internal use only
1179
+     * @return \OC\SystemConfig
1180
+     */
1181
+    public function getSystemConfig() {
1182
+        return $this->query('SystemConfig');
1183
+    }
1184
+
1185
+    /**
1186
+     * Returns the app config manager
1187
+     *
1188
+     * @return \OCP\IAppConfig
1189
+     */
1190
+    public function getAppConfig() {
1191
+        return $this->query('AppConfig');
1192
+    }
1193
+
1194
+    /**
1195
+     * @return \OCP\L10N\IFactory
1196
+     */
1197
+    public function getL10NFactory() {
1198
+        return $this->query('L10NFactory');
1199
+    }
1200
+
1201
+    /**
1202
+     * get an L10N instance
1203
+     *
1204
+     * @param string $app appid
1205
+     * @param string $lang
1206
+     * @return IL10N
1207
+     */
1208
+    public function getL10N($app, $lang = null) {
1209
+        return $this->getL10NFactory()->get($app, $lang);
1210
+    }
1211
+
1212
+    /**
1213
+     * @return \OCP\IURLGenerator
1214
+     */
1215
+    public function getURLGenerator() {
1216
+        return $this->query('URLGenerator');
1217
+    }
1218
+
1219
+    /**
1220
+     * @return \OCP\IHelper
1221
+     */
1222
+    public function getHelper() {
1223
+        return $this->query('AppHelper');
1224
+    }
1225
+
1226
+    /**
1227
+     * @return AppFetcher
1228
+     */
1229
+    public function getAppFetcher() {
1230
+        return $this->query('AppFetcher');
1231
+    }
1232
+
1233
+    /**
1234
+     * Returns an ICache instance. Since 8.1.0 it returns a fake cache. Use
1235
+     * getMemCacheFactory() instead.
1236
+     *
1237
+     * @return \OCP\ICache
1238
+     * @deprecated 8.1.0 use getMemCacheFactory to obtain a proper cache
1239
+     */
1240
+    public function getCache() {
1241
+        return $this->query('UserCache');
1242
+    }
1243
+
1244
+    /**
1245
+     * Returns an \OCP\CacheFactory instance
1246
+     *
1247
+     * @return \OCP\ICacheFactory
1248
+     */
1249
+    public function getMemCacheFactory() {
1250
+        return $this->query('MemCacheFactory');
1251
+    }
1252
+
1253
+    /**
1254
+     * Returns an \OC\RedisFactory instance
1255
+     *
1256
+     * @return \OC\RedisFactory
1257
+     */
1258
+    public function getGetRedisFactory() {
1259
+        return $this->query('RedisFactory');
1260
+    }
1261
+
1262
+
1263
+    /**
1264
+     * Returns the current session
1265
+     *
1266
+     * @return \OCP\IDBConnection
1267
+     */
1268
+    public function getDatabaseConnection() {
1269
+        return $this->query('DatabaseConnection');
1270
+    }
1271
+
1272
+    /**
1273
+     * Returns the activity manager
1274
+     *
1275
+     * @return \OCP\Activity\IManager
1276
+     */
1277
+    public function getActivityManager() {
1278
+        return $this->query('ActivityManager');
1279
+    }
1280
+
1281
+    /**
1282
+     * Returns an job list for controlling background jobs
1283
+     *
1284
+     * @return \OCP\BackgroundJob\IJobList
1285
+     */
1286
+    public function getJobList() {
1287
+        return $this->query('JobList');
1288
+    }
1289
+
1290
+    /**
1291
+     * Returns a logger instance
1292
+     *
1293
+     * @return \OCP\ILogger
1294
+     */
1295
+    public function getLogger() {
1296
+        return $this->query('Logger');
1297
+    }
1298
+
1299
+    /**
1300
+     * Returns a router for generating and matching urls
1301
+     *
1302
+     * @return \OCP\Route\IRouter
1303
+     */
1304
+    public function getRouter() {
1305
+        return $this->query('Router');
1306
+    }
1307
+
1308
+    /**
1309
+     * Returns a search instance
1310
+     *
1311
+     * @return \OCP\ISearch
1312
+     */
1313
+    public function getSearch() {
1314
+        return $this->query('Search');
1315
+    }
1316
+
1317
+    /**
1318
+     * Returns a SecureRandom instance
1319
+     *
1320
+     * @return \OCP\Security\ISecureRandom
1321
+     */
1322
+    public function getSecureRandom() {
1323
+        return $this->query('SecureRandom');
1324
+    }
1325
+
1326
+    /**
1327
+     * Returns a Crypto instance
1328
+     *
1329
+     * @return \OCP\Security\ICrypto
1330
+     */
1331
+    public function getCrypto() {
1332
+        return $this->query('Crypto');
1333
+    }
1334
+
1335
+    /**
1336
+     * Returns a Hasher instance
1337
+     *
1338
+     * @return \OCP\Security\IHasher
1339
+     */
1340
+    public function getHasher() {
1341
+        return $this->query('Hasher');
1342
+    }
1343
+
1344
+    /**
1345
+     * Returns a CredentialsManager instance
1346
+     *
1347
+     * @return \OCP\Security\ICredentialsManager
1348
+     */
1349
+    public function getCredentialsManager() {
1350
+        return $this->query('CredentialsManager');
1351
+    }
1352
+
1353
+    /**
1354
+     * Returns an instance of the HTTP helper class
1355
+     *
1356
+     * @deprecated Use getHTTPClientService()
1357
+     * @return \OC\HTTPHelper
1358
+     */
1359
+    public function getHTTPHelper() {
1360
+        return $this->query('HTTPHelper');
1361
+    }
1362
+
1363
+    /**
1364
+     * Get the certificate manager for the user
1365
+     *
1366
+     * @param string $userId (optional) if not specified the current loggedin user is used, use null to get the system certificate manager
1367
+     * @return \OCP\ICertificateManager | null if $uid is null and no user is logged in
1368
+     */
1369
+    public function getCertificateManager($userId = '') {
1370
+        if ($userId === '') {
1371
+            $userSession = $this->getUserSession();
1372
+            $user = $userSession->getUser();
1373
+            if (is_null($user)) {
1374
+                return null;
1375
+            }
1376
+            $userId = $user->getUID();
1377
+        }
1378
+        return new CertificateManager($userId, new View(), $this->getConfig(), $this->getLogger());
1379
+    }
1380
+
1381
+    /**
1382
+     * Returns an instance of the HTTP client service
1383
+     *
1384
+     * @return \OCP\Http\Client\IClientService
1385
+     */
1386
+    public function getHTTPClientService() {
1387
+        return $this->query('HttpClientService');
1388
+    }
1389
+
1390
+    /**
1391
+     * Create a new event source
1392
+     *
1393
+     * @return \OCP\IEventSource
1394
+     */
1395
+    public function createEventSource() {
1396
+        return new \OC_EventSource();
1397
+    }
1398
+
1399
+    /**
1400
+     * Get the active event logger
1401
+     *
1402
+     * The returned logger only logs data when debug mode is enabled
1403
+     *
1404
+     * @return \OCP\Diagnostics\IEventLogger
1405
+     */
1406
+    public function getEventLogger() {
1407
+        return $this->query('EventLogger');
1408
+    }
1409
+
1410
+    /**
1411
+     * Get the active query logger
1412
+     *
1413
+     * The returned logger only logs data when debug mode is enabled
1414
+     *
1415
+     * @return \OCP\Diagnostics\IQueryLogger
1416
+     */
1417
+    public function getQueryLogger() {
1418
+        return $this->query('QueryLogger');
1419
+    }
1420
+
1421
+    /**
1422
+     * Get the manager for temporary files and folders
1423
+     *
1424
+     * @return \OCP\ITempManager
1425
+     */
1426
+    public function getTempManager() {
1427
+        return $this->query('TempManager');
1428
+    }
1429
+
1430
+    /**
1431
+     * Get the app manager
1432
+     *
1433
+     * @return \OCP\App\IAppManager
1434
+     */
1435
+    public function getAppManager() {
1436
+        return $this->query('AppManager');
1437
+    }
1438
+
1439
+    /**
1440
+     * Creates a new mailer
1441
+     *
1442
+     * @return \OCP\Mail\IMailer
1443
+     */
1444
+    public function getMailer() {
1445
+        return $this->query('Mailer');
1446
+    }
1447
+
1448
+    /**
1449
+     * Get the webroot
1450
+     *
1451
+     * @return string
1452
+     */
1453
+    public function getWebRoot() {
1454
+        return $this->webRoot;
1455
+    }
1456
+
1457
+    /**
1458
+     * @return \OC\OCSClient
1459
+     */
1460
+    public function getOcsClient() {
1461
+        return $this->query('OcsClient');
1462
+    }
1463
+
1464
+    /**
1465
+     * @return \OCP\IDateTimeZone
1466
+     */
1467
+    public function getDateTimeZone() {
1468
+        return $this->query('DateTimeZone');
1469
+    }
1470
+
1471
+    /**
1472
+     * @return \OCP\IDateTimeFormatter
1473
+     */
1474
+    public function getDateTimeFormatter() {
1475
+        return $this->query('DateTimeFormatter');
1476
+    }
1477
+
1478
+    /**
1479
+     * @return \OCP\Files\Config\IMountProviderCollection
1480
+     */
1481
+    public function getMountProviderCollection() {
1482
+        return $this->query('MountConfigManager');
1483
+    }
1484
+
1485
+    /**
1486
+     * Get the IniWrapper
1487
+     *
1488
+     * @return IniGetWrapper
1489
+     */
1490
+    public function getIniWrapper() {
1491
+        return $this->query('IniWrapper');
1492
+    }
1493
+
1494
+    /**
1495
+     * @return \OCP\Command\IBus
1496
+     */
1497
+    public function getCommandBus() {
1498
+        return $this->query('AsyncCommandBus');
1499
+    }
1500
+
1501
+    /**
1502
+     * Get the trusted domain helper
1503
+     *
1504
+     * @return TrustedDomainHelper
1505
+     */
1506
+    public function getTrustedDomainHelper() {
1507
+        return $this->query('TrustedDomainHelper');
1508
+    }
1509
+
1510
+    /**
1511
+     * Get the locking provider
1512
+     *
1513
+     * @return \OCP\Lock\ILockingProvider
1514
+     * @since 8.1.0
1515
+     */
1516
+    public function getLockingProvider() {
1517
+        return $this->query('LockingProvider');
1518
+    }
1519
+
1520
+    /**
1521
+     * @return \OCP\Files\Mount\IMountManager
1522
+     **/
1523
+    function getMountManager() {
1524
+        return $this->query('MountManager');
1525
+    }
1526
+
1527
+    /** @return \OCP\Files\Config\IUserMountCache */
1528
+    function getUserMountCache() {
1529
+        return $this->query('UserMountCache');
1530
+    }
1531
+
1532
+    /**
1533
+     * Get the MimeTypeDetector
1534
+     *
1535
+     * @return \OCP\Files\IMimeTypeDetector
1536
+     */
1537
+    public function getMimeTypeDetector() {
1538
+        return $this->query('MimeTypeDetector');
1539
+    }
1540
+
1541
+    /**
1542
+     * Get the MimeTypeLoader
1543
+     *
1544
+     * @return \OCP\Files\IMimeTypeLoader
1545
+     */
1546
+    public function getMimeTypeLoader() {
1547
+        return $this->query('MimeTypeLoader');
1548
+    }
1549
+
1550
+    /**
1551
+     * Get the manager of all the capabilities
1552
+     *
1553
+     * @return \OC\CapabilitiesManager
1554
+     */
1555
+    public function getCapabilitiesManager() {
1556
+        return $this->query('CapabilitiesManager');
1557
+    }
1558
+
1559
+    /**
1560
+     * Get the EventDispatcher
1561
+     *
1562
+     * @return EventDispatcherInterface
1563
+     * @since 8.2.0
1564
+     */
1565
+    public function getEventDispatcher() {
1566
+        return $this->query('EventDispatcher');
1567
+    }
1568
+
1569
+    /**
1570
+     * Get the Notification Manager
1571
+     *
1572
+     * @return \OCP\Notification\IManager
1573
+     * @since 8.2.0
1574
+     */
1575
+    public function getNotificationManager() {
1576
+        return $this->query('NotificationManager');
1577
+    }
1578
+
1579
+    /**
1580
+     * @return \OCP\Comments\ICommentsManager
1581
+     */
1582
+    public function getCommentsManager() {
1583
+        return $this->query('CommentsManager');
1584
+    }
1585
+
1586
+    /**
1587
+     * @return \OCA\Theming\ThemingDefaults
1588
+     */
1589
+    public function getThemingDefaults() {
1590
+        return $this->query('ThemingDefaults');
1591
+    }
1592
+
1593
+    /**
1594
+     * @return \OC\IntegrityCheck\Checker
1595
+     */
1596
+    public function getIntegrityCodeChecker() {
1597
+        return $this->query('IntegrityCodeChecker');
1598
+    }
1599
+
1600
+    /**
1601
+     * @return \OC\Session\CryptoWrapper
1602
+     */
1603
+    public function getSessionCryptoWrapper() {
1604
+        return $this->query('CryptoWrapper');
1605
+    }
1606
+
1607
+    /**
1608
+     * @return CsrfTokenManager
1609
+     */
1610
+    public function getCsrfTokenManager() {
1611
+        return $this->query('CsrfTokenManager');
1612
+    }
1613
+
1614
+    /**
1615
+     * @return Throttler
1616
+     */
1617
+    public function getBruteForceThrottler() {
1618
+        return $this->query('Throttler');
1619
+    }
1620
+
1621
+    /**
1622
+     * @return IContentSecurityPolicyManager
1623
+     */
1624
+    public function getContentSecurityPolicyManager() {
1625
+        return $this->query('ContentSecurityPolicyManager');
1626
+    }
1627
+
1628
+    /**
1629
+     * @return ContentSecurityPolicyNonceManager
1630
+     */
1631
+    public function getContentSecurityPolicyNonceManager() {
1632
+        return $this->query('ContentSecurityPolicyNonceManager');
1633
+    }
1634
+
1635
+    /**
1636
+     * Not a public API as of 8.2, wait for 9.0
1637
+     *
1638
+     * @return \OCA\Files_External\Service\BackendService
1639
+     */
1640
+    public function getStoragesBackendService() {
1641
+        return $this->query('OCA\\Files_External\\Service\\BackendService');
1642
+    }
1643
+
1644
+    /**
1645
+     * Not a public API as of 8.2, wait for 9.0
1646
+     *
1647
+     * @return \OCA\Files_External\Service\GlobalStoragesService
1648
+     */
1649
+    public function getGlobalStoragesService() {
1650
+        return $this->query('OCA\\Files_External\\Service\\GlobalStoragesService');
1651
+    }
1652
+
1653
+    /**
1654
+     * Not a public API as of 8.2, wait for 9.0
1655
+     *
1656
+     * @return \OCA\Files_External\Service\UserGlobalStoragesService
1657
+     */
1658
+    public function getUserGlobalStoragesService() {
1659
+        return $this->query('OCA\\Files_External\\Service\\UserGlobalStoragesService');
1660
+    }
1661
+
1662
+    /**
1663
+     * Not a public API as of 8.2, wait for 9.0
1664
+     *
1665
+     * @return \OCA\Files_External\Service\UserStoragesService
1666
+     */
1667
+    public function getUserStoragesService() {
1668
+        return $this->query('OCA\\Files_External\\Service\\UserStoragesService');
1669
+    }
1670
+
1671
+    /**
1672
+     * @return \OCP\Share\IManager
1673
+     */
1674
+    public function getShareManager() {
1675
+        return $this->query('ShareManager');
1676
+    }
1677
+
1678
+    /**
1679
+     * Returns the LDAP Provider
1680
+     *
1681
+     * @return \OCP\LDAP\ILDAPProvider
1682
+     */
1683
+    public function getLDAPProvider() {
1684
+        return $this->query('LDAPProvider');
1685
+    }
1686
+
1687
+    /**
1688
+     * @return \OCP\Settings\IManager
1689
+     */
1690
+    public function getSettingsManager() {
1691
+        return $this->query('SettingsManager');
1692
+    }
1693
+
1694
+    /**
1695
+     * @return \OCP\Files\IAppData
1696
+     */
1697
+    public function getAppDataDir($app) {
1698
+        /** @var \OC\Files\AppData\Factory $factory */
1699
+        $factory = $this->query(\OC\Files\AppData\Factory::class);
1700
+        return $factory->get($app);
1701
+    }
1702
+
1703
+    /**
1704
+     * @return \OCP\Lockdown\ILockdownManager
1705
+     */
1706
+    public function getLockdownManager() {
1707
+        return $this->query('LockdownManager');
1708
+    }
1709
+
1710
+    /**
1711
+     * @return \OCP\Federation\ICloudIdManager
1712
+     */
1713
+    public function getCloudIdManager() {
1714
+        return $this->query(ICloudIdManager::class);
1715
+    }
1716 1716
 }
Please login to merge, or discard this patch.
Spacing   +95 added lines, -95 removed lines patch added patch discarded remove patch
@@ -131,7 +131,7 @@  discard block
 block discarded – undo
131 131
 		$this->registerAlias(\OCP\Contacts\IManager::class, \OC\ContactsManager::class);
132 132
 		$this->registerAlias('ContactsManager', \OCP\Contacts\IManager::class);
133 133
 
134
-		$this->registerService(\OCP\IPreview::class, function (Server $c) {
134
+		$this->registerService(\OCP\IPreview::class, function(Server $c) {
135 135
 			return new PreviewManager(
136 136
 				$c->getConfig(),
137 137
 				$c->getRootFolder(),
@@ -142,13 +142,13 @@  discard block
 block discarded – undo
142 142
 		});
143 143
 		$this->registerAlias('PreviewManager', \OCP\IPreview::class);
144 144
 
145
-		$this->registerService(\OC\Preview\Watcher::class, function (Server $c) {
145
+		$this->registerService(\OC\Preview\Watcher::class, function(Server $c) {
146 146
 			return new \OC\Preview\Watcher(
147 147
 				$c->getAppDataDir('preview')
148 148
 			);
149 149
 		});
150 150
 
151
-		$this->registerService('EncryptionManager', function (Server $c) {
151
+		$this->registerService('EncryptionManager', function(Server $c) {
152 152
 			$view = new View();
153 153
 			$util = new Encryption\Util(
154 154
 				$view,
@@ -166,7 +166,7 @@  discard block
 block discarded – undo
166 166
 			);
167 167
 		});
168 168
 
169
-		$this->registerService('EncryptionFileHelper', function (Server $c) {
169
+		$this->registerService('EncryptionFileHelper', function(Server $c) {
170 170
 			$util = new Encryption\Util(
171 171
 				new View(),
172 172
 				$c->getUserManager(),
@@ -180,7 +180,7 @@  discard block
 block discarded – undo
180 180
 			);
181 181
 		});
182 182
 
183
-		$this->registerService('EncryptionKeyStorage', function (Server $c) {
183
+		$this->registerService('EncryptionKeyStorage', function(Server $c) {
184 184
 			$view = new View();
185 185
 			$util = new Encryption\Util(
186 186
 				$view,
@@ -191,32 +191,32 @@  discard block
 block discarded – undo
191 191
 
192 192
 			return new Encryption\Keys\Storage($view, $util);
193 193
 		});
194
-		$this->registerService('TagMapper', function (Server $c) {
194
+		$this->registerService('TagMapper', function(Server $c) {
195 195
 			return new TagMapper($c->getDatabaseConnection());
196 196
 		});
197 197
 
198
-		$this->registerService(\OCP\ITagManager::class, function (Server $c) {
198
+		$this->registerService(\OCP\ITagManager::class, function(Server $c) {
199 199
 			$tagMapper = $c->query('TagMapper');
200 200
 			return new TagManager($tagMapper, $c->getUserSession());
201 201
 		});
202 202
 		$this->registerAlias('TagManager', \OCP\ITagManager::class);
203 203
 
204
-		$this->registerService('SystemTagManagerFactory', function (Server $c) {
204
+		$this->registerService('SystemTagManagerFactory', function(Server $c) {
205 205
 			$config = $c->getConfig();
206 206
 			$factoryClass = $config->getSystemValue('systemtags.managerFactory', '\OC\SystemTag\ManagerFactory');
207 207
 			/** @var \OC\SystemTag\ManagerFactory $factory */
208 208
 			$factory = new $factoryClass($this);
209 209
 			return $factory;
210 210
 		});
211
-		$this->registerService(\OCP\SystemTag\ISystemTagManager::class, function (Server $c) {
211
+		$this->registerService(\OCP\SystemTag\ISystemTagManager::class, function(Server $c) {
212 212
 			return $c->query('SystemTagManagerFactory')->getManager();
213 213
 		});
214 214
 		$this->registerAlias('SystemTagManager', \OCP\SystemTag\ISystemTagManager::class);
215 215
 
216
-		$this->registerService(\OCP\SystemTag\ISystemTagObjectMapper::class, function (Server $c) {
216
+		$this->registerService(\OCP\SystemTag\ISystemTagObjectMapper::class, function(Server $c) {
217 217
 			return $c->query('SystemTagManagerFactory')->getObjectMapper();
218 218
 		});
219
-		$this->registerService('RootFolder', function (Server $c) {
219
+		$this->registerService('RootFolder', function(Server $c) {
220 220
 			$manager = \OC\Files\Filesystem::getMountManager(null);
221 221
 			$view = new View();
222 222
 			$root = new Root(
@@ -244,30 +244,30 @@  discard block
 block discarded – undo
244 244
 		});
245 245
 		$this->registerAlias('LazyRootFolder', \OCP\Files\IRootFolder::class);
246 246
 
247
-		$this->registerService(\OCP\IUserManager::class, function (Server $c) {
247
+		$this->registerService(\OCP\IUserManager::class, function(Server $c) {
248 248
 			$config = $c->getConfig();
249 249
 			return new \OC\User\Manager($config);
250 250
 		});
251 251
 		$this->registerAlias('UserManager', \OCP\IUserManager::class);
252 252
 
253
-		$this->registerService(\OCP\IGroupManager::class, function (Server $c) {
253
+		$this->registerService(\OCP\IGroupManager::class, function(Server $c) {
254 254
 			$groupManager = new \OC\Group\Manager($this->getUserManager(), $this->getLogger());
255
-			$groupManager->listen('\OC\Group', 'preCreate', function ($gid) {
255
+			$groupManager->listen('\OC\Group', 'preCreate', function($gid) {
256 256
 				\OC_Hook::emit('OC_Group', 'pre_createGroup', array('run' => true, 'gid' => $gid));
257 257
 			});
258
-			$groupManager->listen('\OC\Group', 'postCreate', function (\OC\Group\Group $gid) {
258
+			$groupManager->listen('\OC\Group', 'postCreate', function(\OC\Group\Group $gid) {
259 259
 				\OC_Hook::emit('OC_User', 'post_createGroup', array('gid' => $gid->getGID()));
260 260
 			});
261
-			$groupManager->listen('\OC\Group', 'preDelete', function (\OC\Group\Group $group) {
261
+			$groupManager->listen('\OC\Group', 'preDelete', function(\OC\Group\Group $group) {
262 262
 				\OC_Hook::emit('OC_Group', 'pre_deleteGroup', array('run' => true, 'gid' => $group->getGID()));
263 263
 			});
264
-			$groupManager->listen('\OC\Group', 'postDelete', function (\OC\Group\Group $group) {
264
+			$groupManager->listen('\OC\Group', 'postDelete', function(\OC\Group\Group $group) {
265 265
 				\OC_Hook::emit('OC_User', 'post_deleteGroup', array('gid' => $group->getGID()));
266 266
 			});
267
-			$groupManager->listen('\OC\Group', 'preAddUser', function (\OC\Group\Group $group, \OC\User\User $user) {
267
+			$groupManager->listen('\OC\Group', 'preAddUser', function(\OC\Group\Group $group, \OC\User\User $user) {
268 268
 				\OC_Hook::emit('OC_Group', 'pre_addToGroup', array('run' => true, 'uid' => $user->getUID(), 'gid' => $group->getGID()));
269 269
 			});
270
-			$groupManager->listen('\OC\Group', 'postAddUser', function (\OC\Group\Group $group, \OC\User\User $user) {
270
+			$groupManager->listen('\OC\Group', 'postAddUser', function(\OC\Group\Group $group, \OC\User\User $user) {
271 271
 				\OC_Hook::emit('OC_Group', 'post_addToGroup', array('uid' => $user->getUID(), 'gid' => $group->getGID()));
272 272
 				//Minimal fix to keep it backward compatible TODO: clean up all the GroupManager hooks
273 273
 				\OC_Hook::emit('OC_User', 'post_addToGroup', array('uid' => $user->getUID(), 'gid' => $group->getGID()));
@@ -287,11 +287,11 @@  discard block
 block discarded – undo
287 287
 			return new Store($session, $logger, $tokenProvider);
288 288
 		});
289 289
 		$this->registerAlias(IStore::class, Store::class);
290
-		$this->registerService('OC\Authentication\Token\DefaultTokenMapper', function (Server $c) {
290
+		$this->registerService('OC\Authentication\Token\DefaultTokenMapper', function(Server $c) {
291 291
 			$dbConnection = $c->getDatabaseConnection();
292 292
 			return new Authentication\Token\DefaultTokenMapper($dbConnection);
293 293
 		});
294
-		$this->registerService('OC\Authentication\Token\DefaultTokenProvider', function (Server $c) {
294
+		$this->registerService('OC\Authentication\Token\DefaultTokenProvider', function(Server $c) {
295 295
 			$mapper = $c->query('OC\Authentication\Token\DefaultTokenMapper');
296 296
 			$crypto = $c->getCrypto();
297 297
 			$config = $c->getConfig();
@@ -301,7 +301,7 @@  discard block
 block discarded – undo
301 301
 		});
302 302
 		$this->registerAlias('OC\Authentication\Token\IProvider', 'OC\Authentication\Token\DefaultTokenProvider');
303 303
 
304
-		$this->registerService(\OCP\IUserSession::class, function (Server $c) {
304
+		$this->registerService(\OCP\IUserSession::class, function(Server $c) {
305 305
 			$manager = $c->getUserManager();
306 306
 			$session = new \OC\Session\Memory('');
307 307
 			$timeFactory = new TimeFactory();
@@ -314,40 +314,40 @@  discard block
 block discarded – undo
314 314
 			}
315 315
 
316 316
 			$userSession = new \OC\User\Session($manager, $session, $timeFactory, $defaultTokenProvider, $c->getConfig(), $c->getSecureRandom(), $c->getLockdownManager());
317
-			$userSession->listen('\OC\User', 'preCreateUser', function ($uid, $password) {
317
+			$userSession->listen('\OC\User', 'preCreateUser', function($uid, $password) {
318 318
 				\OC_Hook::emit('OC_User', 'pre_createUser', array('run' => true, 'uid' => $uid, 'password' => $password));
319 319
 			});
320
-			$userSession->listen('\OC\User', 'postCreateUser', function ($user, $password) {
320
+			$userSession->listen('\OC\User', 'postCreateUser', function($user, $password) {
321 321
 				/** @var $user \OC\User\User */
322 322
 				\OC_Hook::emit('OC_User', 'post_createUser', array('uid' => $user->getUID(), 'password' => $password));
323 323
 			});
324
-			$userSession->listen('\OC\User', 'preDelete', function ($user) {
324
+			$userSession->listen('\OC\User', 'preDelete', function($user) {
325 325
 				/** @var $user \OC\User\User */
326 326
 				\OC_Hook::emit('OC_User', 'pre_deleteUser', array('run' => true, 'uid' => $user->getUID()));
327 327
 			});
328
-			$userSession->listen('\OC\User', 'postDelete', function ($user) {
328
+			$userSession->listen('\OC\User', 'postDelete', function($user) {
329 329
 				/** @var $user \OC\User\User */
330 330
 				\OC_Hook::emit('OC_User', 'post_deleteUser', array('uid' => $user->getUID()));
331 331
 			});
332
-			$userSession->listen('\OC\User', 'preSetPassword', function ($user, $password, $recoveryPassword) {
332
+			$userSession->listen('\OC\User', 'preSetPassword', function($user, $password, $recoveryPassword) {
333 333
 				/** @var $user \OC\User\User */
334 334
 				\OC_Hook::emit('OC_User', 'pre_setPassword', array('run' => true, 'uid' => $user->getUID(), 'password' => $password, 'recoveryPassword' => $recoveryPassword));
335 335
 			});
336
-			$userSession->listen('\OC\User', 'postSetPassword', function ($user, $password, $recoveryPassword) {
336
+			$userSession->listen('\OC\User', 'postSetPassword', function($user, $password, $recoveryPassword) {
337 337
 				/** @var $user \OC\User\User */
338 338
 				\OC_Hook::emit('OC_User', 'post_setPassword', array('run' => true, 'uid' => $user->getUID(), 'password' => $password, 'recoveryPassword' => $recoveryPassword));
339 339
 			});
340
-			$userSession->listen('\OC\User', 'preLogin', function ($uid, $password) {
340
+			$userSession->listen('\OC\User', 'preLogin', function($uid, $password) {
341 341
 				\OC_Hook::emit('OC_User', 'pre_login', array('run' => true, 'uid' => $uid, 'password' => $password));
342 342
 			});
343
-			$userSession->listen('\OC\User', 'postLogin', function ($user, $password) {
343
+			$userSession->listen('\OC\User', 'postLogin', function($user, $password) {
344 344
 				/** @var $user \OC\User\User */
345 345
 				\OC_Hook::emit('OC_User', 'post_login', array('run' => true, 'uid' => $user->getUID(), 'password' => $password));
346 346
 			});
347
-			$userSession->listen('\OC\User', 'logout', function () {
347
+			$userSession->listen('\OC\User', 'logout', function() {
348 348
 				\OC_Hook::emit('OC_User', 'logout', array());
349 349
 			});
350
-			$userSession->listen('\OC\User', 'changeUser', function ($user, $feature, $value) {
350
+			$userSession->listen('\OC\User', 'changeUser', function($user, $feature, $value) {
351 351
 				/** @var $user \OC\User\User */
352 352
 				\OC_Hook::emit('OC_User', 'changeUser', array('run' => true, 'user' => $user, 'feature' => $feature, 'value' => $value));
353 353
 			});
@@ -355,14 +355,14 @@  discard block
 block discarded – undo
355 355
 		});
356 356
 		$this->registerAlias('UserSession', \OCP\IUserSession::class);
357 357
 
358
-		$this->registerService(\OC\Authentication\TwoFactorAuth\Manager::class, function (Server $c) {
358
+		$this->registerService(\OC\Authentication\TwoFactorAuth\Manager::class, function(Server $c) {
359 359
 			return new \OC\Authentication\TwoFactorAuth\Manager($c->getAppManager(), $c->getSession(), $c->getConfig(), $c->getActivityManager(), $c->getLogger());
360 360
 		});
361 361
 
362 362
 		$this->registerAlias(\OCP\INavigationManager::class, \OC\NavigationManager::class);
363 363
 		$this->registerAlias('NavigationManager', \OCP\INavigationManager::class);
364 364
 
365
-		$this->registerService(\OC\AllConfig::class, function (Server $c) {
365
+		$this->registerService(\OC\AllConfig::class, function(Server $c) {
366 366
 			return new \OC\AllConfig(
367 367
 				$c->getSystemConfig()
368 368
 			);
@@ -370,17 +370,17 @@  discard block
 block discarded – undo
370 370
 		$this->registerAlias('AllConfig', \OC\AllConfig::class);
371 371
 		$this->registerAlias(\OCP\IConfig::class, \OC\AllConfig::class);
372 372
 
373
-		$this->registerService('SystemConfig', function ($c) use ($config) {
373
+		$this->registerService('SystemConfig', function($c) use ($config) {
374 374
 			return new \OC\SystemConfig($config);
375 375
 		});
376 376
 
377
-		$this->registerService(\OC\AppConfig::class, function (Server $c) {
377
+		$this->registerService(\OC\AppConfig::class, function(Server $c) {
378 378
 			return new \OC\AppConfig($c->getDatabaseConnection());
379 379
 		});
380 380
 		$this->registerAlias('AppConfig', \OC\AppConfig::class);
381 381
 		$this->registerAlias(\OCP\IAppConfig::class, \OC\AppConfig::class);
382 382
 
383
-		$this->registerService(\OCP\L10N\IFactory::class, function (Server $c) {
383
+		$this->registerService(\OCP\L10N\IFactory::class, function(Server $c) {
384 384
 			return new \OC\L10N\Factory(
385 385
 				$c->getConfig(),
386 386
 				$c->getRequest(),
@@ -390,7 +390,7 @@  discard block
 block discarded – undo
390 390
 		});
391 391
 		$this->registerAlias('L10NFactory', \OCP\L10N\IFactory::class);
392 392
 
393
-		$this->registerService(\OCP\IURLGenerator::class, function (Server $c) {
393
+		$this->registerService(\OCP\IURLGenerator::class, function(Server $c) {
394 394
 			$config = $c->getConfig();
395 395
 			$cacheFactory = $c->getMemCacheFactory();
396 396
 			return new \OC\URLGenerator(
@@ -400,10 +400,10 @@  discard block
 block discarded – undo
400 400
 		});
401 401
 		$this->registerAlias('URLGenerator', \OCP\IURLGenerator::class);
402 402
 
403
-		$this->registerService('AppHelper', function ($c) {
403
+		$this->registerService('AppHelper', function($c) {
404 404
 			return new \OC\AppHelper();
405 405
 		});
406
-		$this->registerService('AppFetcher', function ($c) {
406
+		$this->registerService('AppFetcher', function($c) {
407 407
 			return new AppFetcher(
408 408
 				$this->getAppDataDir('appstore'),
409 409
 				$this->getHTTPClientService(),
@@ -411,7 +411,7 @@  discard block
 block discarded – undo
411 411
 				$this->getConfig()
412 412
 			);
413 413
 		});
414
-		$this->registerService('CategoryFetcher', function ($c) {
414
+		$this->registerService('CategoryFetcher', function($c) {
415 415
 			return new CategoryFetcher(
416 416
 				$this->getAppDataDir('appstore'),
417 417
 				$this->getHTTPClientService(),
@@ -420,21 +420,21 @@  discard block
 block discarded – undo
420 420
 			);
421 421
 		});
422 422
 
423
-		$this->registerService(\OCP\ICache::class, function ($c) {
423
+		$this->registerService(\OCP\ICache::class, function($c) {
424 424
 			return new Cache\File();
425 425
 		});
426 426
 		$this->registerAlias('UserCache', \OCP\ICache::class);
427 427
 
428
-		$this->registerService(Factory::class, function (Server $c) {
428
+		$this->registerService(Factory::class, function(Server $c) {
429 429
 			$config = $c->getConfig();
430 430
 
431 431
 			if ($config->getSystemValue('installed', false) && !(defined('PHPUNIT_RUN') && PHPUNIT_RUN)) {
432 432
 				$v = \OC_App::getAppVersions();
433
-				$v['core'] = md5(file_get_contents(\OC::$SERVERROOT . '/version.php'));
433
+				$v['core'] = md5(file_get_contents(\OC::$SERVERROOT.'/version.php'));
434 434
 				$version = implode(',', $v);
435 435
 				$instanceId = \OC_Util::getInstanceId();
436 436
 				$path = \OC::$SERVERROOT;
437
-				$prefix = md5($instanceId . '-' . $version . '-' . $path . '-' . \OC::$WEBROOT);
437
+				$prefix = md5($instanceId.'-'.$version.'-'.$path.'-'.\OC::$WEBROOT);
438 438
 				return new \OC\Memcache\Factory($prefix, $c->getLogger(),
439 439
 					$config->getSystemValue('memcache.local', null),
440 440
 					$config->getSystemValue('memcache.distributed', null),
@@ -451,12 +451,12 @@  discard block
 block discarded – undo
451 451
 		$this->registerAlias('MemCacheFactory', Factory::class);
452 452
 		$this->registerAlias(ICacheFactory::class, Factory::class);
453 453
 
454
-		$this->registerService('RedisFactory', function (Server $c) {
454
+		$this->registerService('RedisFactory', function(Server $c) {
455 455
 			$systemConfig = $c->getSystemConfig();
456 456
 			return new RedisFactory($systemConfig);
457 457
 		});
458 458
 
459
-		$this->registerService(\OCP\Activity\IManager::class, function (Server $c) {
459
+		$this->registerService(\OCP\Activity\IManager::class, function(Server $c) {
460 460
 			return new \OC\Activity\Manager(
461 461
 				$c->getRequest(),
462 462
 				$c->getUserSession(),
@@ -466,14 +466,14 @@  discard block
 block discarded – undo
466 466
 		});
467 467
 		$this->registerAlias('ActivityManager', \OCP\Activity\IManager::class);
468 468
 
469
-		$this->registerService(\OCP\Activity\IEventMerger::class, function (Server $c) {
469
+		$this->registerService(\OCP\Activity\IEventMerger::class, function(Server $c) {
470 470
 			return new \OC\Activity\EventMerger(
471 471
 				$c->getL10N('lib')
472 472
 			);
473 473
 		});
474 474
 		$this->registerAlias(IValidator::class, Validator::class);
475 475
 
476
-		$this->registerService(\OCP\IAvatarManager::class, function (Server $c) {
476
+		$this->registerService(\OCP\IAvatarManager::class, function(Server $c) {
477 477
 			return new AvatarManager(
478 478
 				$c->getUserManager(),
479 479
 				$c->getAppDataDir('avatar'),
@@ -484,7 +484,7 @@  discard block
 block discarded – undo
484 484
 		});
485 485
 		$this->registerAlias('AvatarManager', \OCP\IAvatarManager::class);
486 486
 
487
-		$this->registerService(\OCP\ILogger::class, function (Server $c) {
487
+		$this->registerService(\OCP\ILogger::class, function(Server $c) {
488 488
 			$logType = $c->query('AllConfig')->getSystemValue('log_type', 'file');
489 489
 			$logger = Log::getLogClass($logType);
490 490
 			call_user_func(array($logger, 'init'));
@@ -493,7 +493,7 @@  discard block
 block discarded – undo
493 493
 		});
494 494
 		$this->registerAlias('Logger', \OCP\ILogger::class);
495 495
 
496
-		$this->registerService(\OCP\BackgroundJob\IJobList::class, function (Server $c) {
496
+		$this->registerService(\OCP\BackgroundJob\IJobList::class, function(Server $c) {
497 497
 			$config = $c->getConfig();
498 498
 			return new \OC\BackgroundJob\JobList(
499 499
 				$c->getDatabaseConnection(),
@@ -503,7 +503,7 @@  discard block
 block discarded – undo
503 503
 		});
504 504
 		$this->registerAlias('JobList', \OCP\BackgroundJob\IJobList::class);
505 505
 
506
-		$this->registerService(\OCP\Route\IRouter::class, function (Server $c) {
506
+		$this->registerService(\OCP\Route\IRouter::class, function(Server $c) {
507 507
 			$cacheFactory = $c->getMemCacheFactory();
508 508
 			$logger = $c->getLogger();
509 509
 			if ($cacheFactory->isAvailable()) {
@@ -515,32 +515,32 @@  discard block
 block discarded – undo
515 515
 		});
516 516
 		$this->registerAlias('Router', \OCP\Route\IRouter::class);
517 517
 
518
-		$this->registerService(\OCP\ISearch::class, function ($c) {
518
+		$this->registerService(\OCP\ISearch::class, function($c) {
519 519
 			return new Search();
520 520
 		});
521 521
 		$this->registerAlias('Search', \OCP\ISearch::class);
522 522
 
523
-		$this->registerService(\OCP\Security\ISecureRandom::class, function ($c) {
523
+		$this->registerService(\OCP\Security\ISecureRandom::class, function($c) {
524 524
 			return new SecureRandom();
525 525
 		});
526 526
 		$this->registerAlias('SecureRandom', \OCP\Security\ISecureRandom::class);
527 527
 
528
-		$this->registerService(\OCP\Security\ICrypto::class, function (Server $c) {
528
+		$this->registerService(\OCP\Security\ICrypto::class, function(Server $c) {
529 529
 			return new Crypto($c->getConfig(), $c->getSecureRandom());
530 530
 		});
531 531
 		$this->registerAlias('Crypto', \OCP\Security\ICrypto::class);
532 532
 
533
-		$this->registerService(\OCP\Security\IHasher::class, function (Server $c) {
533
+		$this->registerService(\OCP\Security\IHasher::class, function(Server $c) {
534 534
 			return new Hasher($c->getConfig());
535 535
 		});
536 536
 		$this->registerAlias('Hasher', \OCP\Security\IHasher::class);
537 537
 
538
-		$this->registerService(\OCP\Security\ICredentialsManager::class, function (Server $c) {
538
+		$this->registerService(\OCP\Security\ICredentialsManager::class, function(Server $c) {
539 539
 			return new CredentialsManager($c->getCrypto(), $c->getDatabaseConnection());
540 540
 		});
541 541
 		$this->registerAlias('CredentialsManager', \OCP\Security\ICredentialsManager::class);
542 542
 
543
-		$this->registerService(IDBConnection::class, function (Server $c) {
543
+		$this->registerService(IDBConnection::class, function(Server $c) {
544 544
 			$systemConfig = $c->getSystemConfig();
545 545
 			$factory = new \OC\DB\ConnectionFactory($systemConfig);
546 546
 			$type = $systemConfig->getValue('dbtype', 'sqlite');
@@ -554,7 +554,7 @@  discard block
 block discarded – undo
554 554
 		});
555 555
 		$this->registerAlias('DatabaseConnection', IDBConnection::class);
556 556
 
557
-		$this->registerService('HTTPHelper', function (Server $c) {
557
+		$this->registerService('HTTPHelper', function(Server $c) {
558 558
 			$config = $c->getConfig();
559 559
 			return new HTTPHelper(
560 560
 				$config,
@@ -562,7 +562,7 @@  discard block
 block discarded – undo
562 562
 			);
563 563
 		});
564 564
 
565
-		$this->registerService(\OCP\Http\Client\IClientService::class, function (Server $c) {
565
+		$this->registerService(\OCP\Http\Client\IClientService::class, function(Server $c) {
566 566
 			$user = \OC_User::getUser();
567 567
 			$uid = $user ? $user : null;
568 568
 			return new ClientService(
@@ -572,7 +572,7 @@  discard block
 block discarded – undo
572 572
 		});
573 573
 		$this->registerAlias('HttpClientService', \OCP\Http\Client\IClientService::class);
574 574
 
575
-		$this->registerService(\OCP\Diagnostics\IEventLogger::class, function (Server $c) {
575
+		$this->registerService(\OCP\Diagnostics\IEventLogger::class, function(Server $c) {
576 576
 			if ($c->getSystemConfig()->getValue('debug', false)) {
577 577
 				return new EventLogger();
578 578
 			} else {
@@ -581,7 +581,7 @@  discard block
 block discarded – undo
581 581
 		});
582 582
 		$this->registerAlias('EventLogger', \OCP\Diagnostics\IEventLogger::class);
583 583
 
584
-		$this->registerService(\OCP\Diagnostics\IQueryLogger::class, function (Server $c) {
584
+		$this->registerService(\OCP\Diagnostics\IQueryLogger::class, function(Server $c) {
585 585
 			if ($c->getSystemConfig()->getValue('debug', false)) {
586 586
 				return new QueryLogger();
587 587
 			} else {
@@ -590,7 +590,7 @@  discard block
 block discarded – undo
590 590
 		});
591 591
 		$this->registerAlias('QueryLogger', \OCP\Diagnostics\IQueryLogger::class);
592 592
 
593
-		$this->registerService(TempManager::class, function (Server $c) {
593
+		$this->registerService(TempManager::class, function(Server $c) {
594 594
 			return new TempManager(
595 595
 				$c->getLogger(),
596 596
 				$c->getConfig()
@@ -599,7 +599,7 @@  discard block
 block discarded – undo
599 599
 		$this->registerAlias('TempManager', TempManager::class);
600 600
 		$this->registerAlias(ITempManager::class, TempManager::class);
601 601
 
602
-		$this->registerService(AppManager::class, function (Server $c) {
602
+		$this->registerService(AppManager::class, function(Server $c) {
603 603
 			return new \OC\App\AppManager(
604 604
 				$c->getUserSession(),
605 605
 				$c->getAppConfig(),
@@ -611,7 +611,7 @@  discard block
 block discarded – undo
611 611
 		$this->registerAlias('AppManager', AppManager::class);
612 612
 		$this->registerAlias(IAppManager::class, AppManager::class);
613 613
 
614
-		$this->registerService(\OCP\IDateTimeZone::class, function (Server $c) {
614
+		$this->registerService(\OCP\IDateTimeZone::class, function(Server $c) {
615 615
 			return new DateTimeZone(
616 616
 				$c->getConfig(),
617 617
 				$c->getSession()
@@ -619,7 +619,7 @@  discard block
 block discarded – undo
619 619
 		});
620 620
 		$this->registerAlias('DateTimeZone', \OCP\IDateTimeZone::class);
621 621
 
622
-		$this->registerService(\OCP\IDateTimeFormatter::class, function (Server $c) {
622
+		$this->registerService(\OCP\IDateTimeFormatter::class, function(Server $c) {
623 623
 			$language = $c->getConfig()->getUserValue($c->getSession()->get('user_id'), 'core', 'lang', null);
624 624
 
625 625
 			return new DateTimeFormatter(
@@ -629,7 +629,7 @@  discard block
 block discarded – undo
629 629
 		});
630 630
 		$this->registerAlias('DateTimeFormatter', \OCP\IDateTimeFormatter::class);
631 631
 
632
-		$this->registerService(\OCP\Files\Config\IUserMountCache::class, function (Server $c) {
632
+		$this->registerService(\OCP\Files\Config\IUserMountCache::class, function(Server $c) {
633 633
 			$mountCache = new UserMountCache($c->getDatabaseConnection(), $c->getUserManager(), $c->getLogger());
634 634
 			$listener = new UserMountCacheListener($mountCache);
635 635
 			$listener->listen($c->getUserManager());
@@ -637,10 +637,10 @@  discard block
 block discarded – undo
637 637
 		});
638 638
 		$this->registerAlias('UserMountCache', \OCP\Files\Config\IUserMountCache::class);
639 639
 
640
-		$this->registerService(\OCP\Files\Config\IMountProviderCollection::class, function (Server $c) {
640
+		$this->registerService(\OCP\Files\Config\IMountProviderCollection::class, function(Server $c) {
641 641
 			$loader = \OC\Files\Filesystem::getLoader();
642 642
 			$mountCache = $c->query('UserMountCache');
643
-			$manager =  new \OC\Files\Config\MountProviderCollection($loader, $mountCache);
643
+			$manager = new \OC\Files\Config\MountProviderCollection($loader, $mountCache);
644 644
 
645 645
 			// builtin providers
646 646
 
@@ -653,14 +653,14 @@  discard block
 block discarded – undo
653 653
 		});
654 654
 		$this->registerAlias('MountConfigManager', \OCP\Files\Config\IMountProviderCollection::class);
655 655
 
656
-		$this->registerService('IniWrapper', function ($c) {
656
+		$this->registerService('IniWrapper', function($c) {
657 657
 			return new IniGetWrapper();
658 658
 		});
659
-		$this->registerService('AsyncCommandBus', function (Server $c) {
659
+		$this->registerService('AsyncCommandBus', function(Server $c) {
660 660
 			$jobList = $c->getJobList();
661 661
 			return new AsyncBus($jobList);
662 662
 		});
663
-		$this->registerService('TrustedDomainHelper', function ($c) {
663
+		$this->registerService('TrustedDomainHelper', function($c) {
664 664
 			return new TrustedDomainHelper($this->getConfig());
665 665
 		});
666 666
 		$this->registerService('Throttler', function(Server $c) {
@@ -671,10 +671,10 @@  discard block
 block discarded – undo
671 671
 				$c->getConfig()
672 672
 			);
673 673
 		});
674
-		$this->registerService('IntegrityCodeChecker', function (Server $c) {
674
+		$this->registerService('IntegrityCodeChecker', function(Server $c) {
675 675
 			// IConfig and IAppManager requires a working database. This code
676 676
 			// might however be called when ownCloud is not yet setup.
677
-			if(\OC::$server->getSystemConfig()->getValue('installed', false)) {
677
+			if (\OC::$server->getSystemConfig()->getValue('installed', false)) {
678 678
 				$config = $c->getConfig();
679 679
 				$appManager = $c->getAppManager();
680 680
 			} else {
@@ -692,7 +692,7 @@  discard block
 block discarded – undo
692 692
 					$c->getTempManager()
693 693
 			);
694 694
 		});
695
-		$this->registerService(\OCP\IRequest::class, function ($c) {
695
+		$this->registerService(\OCP\IRequest::class, function($c) {
696 696
 			if (isset($this['urlParams'])) {
697 697
 				$urlParams = $this['urlParams'];
698 698
 			} else {
@@ -728,7 +728,7 @@  discard block
 block discarded – undo
728 728
 		});
729 729
 		$this->registerAlias('Request', \OCP\IRequest::class);
730 730
 
731
-		$this->registerService(\OCP\Mail\IMailer::class, function (Server $c) {
731
+		$this->registerService(\OCP\Mail\IMailer::class, function(Server $c) {
732 732
 			return new Mailer(
733 733
 				$c->getConfig(),
734 734
 				$c->getLogger(),
@@ -740,14 +740,14 @@  discard block
 block discarded – undo
740 740
 		$this->registerService('LDAPProvider', function(Server $c) {
741 741
 			$config = $c->getConfig();
742 742
 			$factoryClass = $config->getSystemValue('ldapProviderFactory', null);
743
-			if(is_null($factoryClass)) {
743
+			if (is_null($factoryClass)) {
744 744
 				throw new \Exception('ldapProviderFactory not set');
745 745
 			}
746 746
 			/** @var \OCP\LDAP\ILDAPProviderFactory $factory */
747 747
 			$factory = new $factoryClass($this);
748 748
 			return $factory->getLDAPProvider();
749 749
 		});
750
-		$this->registerService('LockingProvider', function (Server $c) {
750
+		$this->registerService('LockingProvider', function(Server $c) {
751 751
 			$ini = $c->getIniWrapper();
752 752
 			$config = $c->getConfig();
753 753
 			$ttl = $config->getSystemValue('filelocking.ttl', max(3600, $ini->getNumeric('max_execution_time')));
@@ -763,37 +763,37 @@  discard block
 block discarded – undo
763 763
 			return new NoopLockingProvider();
764 764
 		});
765 765
 
766
-		$this->registerService(\OCP\Files\Mount\IMountManager::class, function () {
766
+		$this->registerService(\OCP\Files\Mount\IMountManager::class, function() {
767 767
 			return new \OC\Files\Mount\Manager();
768 768
 		});
769 769
 		$this->registerAlias('MountManager', \OCP\Files\Mount\IMountManager::class);
770 770
 
771
-		$this->registerService(\OCP\Files\IMimeTypeDetector::class, function (Server $c) {
771
+		$this->registerService(\OCP\Files\IMimeTypeDetector::class, function(Server $c) {
772 772
 			return new \OC\Files\Type\Detection(
773 773
 				$c->getURLGenerator(),
774 774
 				\OC::$configDir,
775
-				\OC::$SERVERROOT . '/resources/config/'
775
+				\OC::$SERVERROOT.'/resources/config/'
776 776
 			);
777 777
 		});
778 778
 		$this->registerAlias('MimeTypeDetector', \OCP\Files\IMimeTypeDetector::class);
779 779
 
780
-		$this->registerService(\OCP\Files\IMimeTypeLoader::class, function (Server $c) {
780
+		$this->registerService(\OCP\Files\IMimeTypeLoader::class, function(Server $c) {
781 781
 			return new \OC\Files\Type\Loader(
782 782
 				$c->getDatabaseConnection()
783 783
 			);
784 784
 		});
785 785
 		$this->registerAlias('MimeTypeLoader', \OCP\Files\IMimeTypeLoader::class);
786 786
 
787
-		$this->registerService(\OCP\Notification\IManager::class, function (Server $c) {
787
+		$this->registerService(\OCP\Notification\IManager::class, function(Server $c) {
788 788
 			return new Manager(
789 789
 				$c->query(IValidator::class)
790 790
 			);
791 791
 		});
792 792
 		$this->registerAlias('NotificationManager', \OCP\Notification\IManager::class);
793 793
 
794
-		$this->registerService(\OC\CapabilitiesManager::class, function (Server $c) {
794
+		$this->registerService(\OC\CapabilitiesManager::class, function(Server $c) {
795 795
 			$manager = new \OC\CapabilitiesManager($c->getLogger());
796
-			$manager->registerCapability(function () use ($c) {
796
+			$manager->registerCapability(function() use ($c) {
797 797
 				return new \OC\OCS\CoreCapabilities($c->getConfig());
798 798
 			});
799 799
 			return $manager;
@@ -835,13 +835,13 @@  discard block
 block discarded – undo
835 835
 			}
836 836
 			return new \OC_Defaults();
837 837
 		});
838
-		$this->registerService(EventDispatcher::class, function () {
838
+		$this->registerService(EventDispatcher::class, function() {
839 839
 			return new EventDispatcher();
840 840
 		});
841 841
 		$this->registerAlias('EventDispatcher', EventDispatcher::class);
842 842
 		$this->registerAlias(EventDispatcherInterface::class, EventDispatcher::class);
843 843
 
844
-		$this->registerService('CryptoWrapper', function (Server $c) {
844
+		$this->registerService('CryptoWrapper', function(Server $c) {
845 845
 			// FIXME: Instantiiated here due to cyclic dependency
846 846
 			$request = new Request(
847 847
 				[
@@ -866,7 +866,7 @@  discard block
 block discarded – undo
866 866
 				$request
867 867
 			);
868 868
 		});
869
-		$this->registerService('CsrfTokenManager', function (Server $c) {
869
+		$this->registerService('CsrfTokenManager', function(Server $c) {
870 870
 			$tokenGenerator = new CsrfTokenGenerator($c->getSecureRandom());
871 871
 
872 872
 			return new CsrfTokenManager(
@@ -874,10 +874,10 @@  discard block
 block discarded – undo
874 874
 				$c->query(SessionStorage::class)
875 875
 			);
876 876
 		});
877
-		$this->registerService(SessionStorage::class, function (Server $c) {
877
+		$this->registerService(SessionStorage::class, function(Server $c) {
878 878
 			return new SessionStorage($c->getSession());
879 879
 		});
880
-		$this->registerService(\OCP\Security\IContentSecurityPolicyManager::class, function (Server $c) {
880
+		$this->registerService(\OCP\Security\IContentSecurityPolicyManager::class, function(Server $c) {
881 881
 			return new ContentSecurityPolicyManager();
882 882
 		});
883 883
 		$this->registerAlias('ContentSecurityPolicyManager', \OCP\Security\IContentSecurityPolicyManager::class);
@@ -928,25 +928,25 @@  discard block
 block discarded – undo
928 928
 			);
929 929
 			return $manager;
930 930
 		});
931
-		$this->registerService(\OC\Files\AppData\Factory::class, function (Server $c) {
931
+		$this->registerService(\OC\Files\AppData\Factory::class, function(Server $c) {
932 932
 			return new \OC\Files\AppData\Factory(
933 933
 				$c->getRootFolder(),
934 934
 				$c->getSystemConfig()
935 935
 			);
936 936
 		});
937 937
 
938
-		$this->registerService('LockdownManager', function (Server $c) {
938
+		$this->registerService('LockdownManager', function(Server $c) {
939 939
 			return new LockdownManager(function() use ($c) {
940 940
 				return $c->getSession();
941 941
 			});
942 942
 		});
943 943
 
944
-		$this->registerService(ICloudIdManager::class, function (Server $c) {
944
+		$this->registerService(ICloudIdManager::class, function(Server $c) {
945 945
 			return new CloudIdManager();
946 946
 		});
947 947
 
948 948
 		/* To trick DI since we don't extend the DIContainer here */
949
-		$this->registerService(CleanPreviewsBackgroundJob::class, function (Server $c) {
949
+		$this->registerService(CleanPreviewsBackgroundJob::class, function(Server $c) {
950 950
 			return new CleanPreviewsBackgroundJob(
951 951
 				$c->getRootFolder(),
952 952
 				$c->getLogger(),
@@ -1106,7 +1106,7 @@  discard block
 block discarded – undo
1106 1106
 	 * @deprecated since 9.2.0 use IAppData
1107 1107
 	 */
1108 1108
 	public function getAppFolder() {
1109
-		$dir = '/' . \OC_App::getCurrentApp();
1109
+		$dir = '/'.\OC_App::getCurrentApp();
1110 1110
 		$root = $this->getRootFolder();
1111 1111
 		if (!$root->nodeExists($dir)) {
1112 1112
 			$folder = $root->newFolder($dir);
Please login to merge, or discard this patch.
lib/private/Share20/ShareHelper.php 2 patches
Indentation   +113 added lines, -113 removed lines patch added patch discarded remove patch
@@ -28,117 +28,117 @@
 block discarded – undo
28 28
 
29 29
 class ShareHelper implements IShareHelper {
30 30
 
31
-	/** @var IManager */
32
-	private $shareManager;
33
-
34
-	public function __construct(IManager $shareManager) {
35
-		$this->shareManager = $shareManager;
36
-	}
37
-
38
-	/**
39
-	 * @param Node $node
40
-	 * @return array [ users => [Mapping $uid => $pathForUser], remotes => [Mapping $cloudId => $pathToMountRoot]]
41
-	 */
42
-	public function getPathsForAccessList(Node $node) {
43
-		$result = [
44
-			'users' => [],
45
-			'remotes' => [],
46
-		];
47
-
48
-		$accessList = $this->shareManager->getAccessList($node, true, true);
49
-		if (!empty($accessList['users'])) {
50
-			$result['users'] = $this->getPathsForUsers($node, $accessList['users']);
51
-		}
52
-		if (!empty($accessList['remote'])) {
53
-			$result['remotes'] = $this->getPathsForRemotes($node, $accessList['remote']);
54
-		}
55
-
56
-		return $result;
57
-	}
58
-
59
-	/**
60
-	 * @param Node $node
61
-	 * @param array[] $users
62
-	 * @return array
63
-	 */
64
-	protected function getPathsForUsers(Node $node, array $users) {
65
-		$byId = $results = [];
66
-		foreach ($users as $uid => $info) {
67
-			if (!isset($byId[$info['node_id']])) {
68
-				$byId[$info['node_id']] = [];
69
-			}
70
-			$byId[$info['node_id']][$uid] = $info['node_path'];
71
-		}
72
-
73
-		if (isset($byId[$node->getId()])) {
74
-			foreach ($byId[$node->getId()] as $uid => $path) {
75
-				$results[$uid] = $path;
76
-			}
77
-			unset($byId[$node->getId()]);
78
-		}
79
-
80
-		if (empty($byId)) {
81
-			return $results;
82
-		}
83
-
84
-		$item = $node;
85
-		$appendix = '/' . $node->getName();
86
-		while (!empty($byId)) {
87
-			/** @var Node $item */
88
-			$item = $item->getParent();
89
-
90
-			if (!empty($byId[$item->getId()])) {
91
-				foreach ($byId[$item->getId()] as $uid => $path) {
92
-					$results[$uid] = $path . $appendix;
93
-				}
94
-				unset($byId[$item->getId()]);
95
-			}
96
-
97
-			$appendix = '/' . $item->getName() . $appendix;
98
-		}
99
-
100
-		return $results;
101
-	}
102
-
103
-	/**
104
-	 * @param Node $node
105
-	 * @param array[] $remotes
106
-	 * @return array
107
-	 */
108
-	protected function getPathsForRemotes(Node $node, array $remotes) {
109
-		$byId = $results = [];
110
-		foreach ($remotes as $cloudId => $info) {
111
-			if (!isset($byId[$info['node_id']])) {
112
-				$byId[$info['node_id']] = [];
113
-			}
114
-			$byId[$info['node_id']][$cloudId] = $info['token'];
115
-		}
116
-
117
-		$item = $node;
118
-		while (!empty($byId)) {
119
-			if (!empty($byId[$item->getId()])) {
120
-				$path = $this->getMountedPath($item);
121
-				foreach ($byId[$item->getId()] as $uid => $token) {
122
-					$results[$uid] = [
123
-						'node_path' => $path,
124
-						'token' => $token,
125
-					];
126
-				}
127
-				unset($byId[$item->getId()]);
128
-			}
129
-			$item = $item->getParent();
130
-		}
131
-
132
-		return $results;
133
-	}
134
-
135
-	/**
136
-	 * @param Node $node
137
-	 * @return string
138
-	 */
139
-	protected function getMountedPath(Node $node) {
140
-		$path = $node->getPath();
141
-		$sections = explode('/', $path, 4);
142
-		return '/' . $sections[3];
143
-	}
31
+    /** @var IManager */
32
+    private $shareManager;
33
+
34
+    public function __construct(IManager $shareManager) {
35
+        $this->shareManager = $shareManager;
36
+    }
37
+
38
+    /**
39
+     * @param Node $node
40
+     * @return array [ users => [Mapping $uid => $pathForUser], remotes => [Mapping $cloudId => $pathToMountRoot]]
41
+     */
42
+    public function getPathsForAccessList(Node $node) {
43
+        $result = [
44
+            'users' => [],
45
+            'remotes' => [],
46
+        ];
47
+
48
+        $accessList = $this->shareManager->getAccessList($node, true, true);
49
+        if (!empty($accessList['users'])) {
50
+            $result['users'] = $this->getPathsForUsers($node, $accessList['users']);
51
+        }
52
+        if (!empty($accessList['remote'])) {
53
+            $result['remotes'] = $this->getPathsForRemotes($node, $accessList['remote']);
54
+        }
55
+
56
+        return $result;
57
+    }
58
+
59
+    /**
60
+     * @param Node $node
61
+     * @param array[] $users
62
+     * @return array
63
+     */
64
+    protected function getPathsForUsers(Node $node, array $users) {
65
+        $byId = $results = [];
66
+        foreach ($users as $uid => $info) {
67
+            if (!isset($byId[$info['node_id']])) {
68
+                $byId[$info['node_id']] = [];
69
+            }
70
+            $byId[$info['node_id']][$uid] = $info['node_path'];
71
+        }
72
+
73
+        if (isset($byId[$node->getId()])) {
74
+            foreach ($byId[$node->getId()] as $uid => $path) {
75
+                $results[$uid] = $path;
76
+            }
77
+            unset($byId[$node->getId()]);
78
+        }
79
+
80
+        if (empty($byId)) {
81
+            return $results;
82
+        }
83
+
84
+        $item = $node;
85
+        $appendix = '/' . $node->getName();
86
+        while (!empty($byId)) {
87
+            /** @var Node $item */
88
+            $item = $item->getParent();
89
+
90
+            if (!empty($byId[$item->getId()])) {
91
+                foreach ($byId[$item->getId()] as $uid => $path) {
92
+                    $results[$uid] = $path . $appendix;
93
+                }
94
+                unset($byId[$item->getId()]);
95
+            }
96
+
97
+            $appendix = '/' . $item->getName() . $appendix;
98
+        }
99
+
100
+        return $results;
101
+    }
102
+
103
+    /**
104
+     * @param Node $node
105
+     * @param array[] $remotes
106
+     * @return array
107
+     */
108
+    protected function getPathsForRemotes(Node $node, array $remotes) {
109
+        $byId = $results = [];
110
+        foreach ($remotes as $cloudId => $info) {
111
+            if (!isset($byId[$info['node_id']])) {
112
+                $byId[$info['node_id']] = [];
113
+            }
114
+            $byId[$info['node_id']][$cloudId] = $info['token'];
115
+        }
116
+
117
+        $item = $node;
118
+        while (!empty($byId)) {
119
+            if (!empty($byId[$item->getId()])) {
120
+                $path = $this->getMountedPath($item);
121
+                foreach ($byId[$item->getId()] as $uid => $token) {
122
+                    $results[$uid] = [
123
+                        'node_path' => $path,
124
+                        'token' => $token,
125
+                    ];
126
+                }
127
+                unset($byId[$item->getId()]);
128
+            }
129
+            $item = $item->getParent();
130
+        }
131
+
132
+        return $results;
133
+    }
134
+
135
+    /**
136
+     * @param Node $node
137
+     * @return string
138
+     */
139
+    protected function getMountedPath(Node $node) {
140
+        $path = $node->getPath();
141
+        $sections = explode('/', $path, 4);
142
+        return '/' . $sections[3];
143
+    }
144 144
 }
Please login to merge, or discard this patch.
Spacing   +4 added lines, -4 removed lines patch added patch discarded remove patch
@@ -82,19 +82,19 @@  discard block
 block discarded – undo
82 82
 		}
83 83
 
84 84
 		$item = $node;
85
-		$appendix = '/' . $node->getName();
85
+		$appendix = '/'.$node->getName();
86 86
 		while (!empty($byId)) {
87 87
 			/** @var Node $item */
88 88
 			$item = $item->getParent();
89 89
 
90 90
 			if (!empty($byId[$item->getId()])) {
91 91
 				foreach ($byId[$item->getId()] as $uid => $path) {
92
-					$results[$uid] = $path . $appendix;
92
+					$results[$uid] = $path.$appendix;
93 93
 				}
94 94
 				unset($byId[$item->getId()]);
95 95
 			}
96 96
 
97
-			$appendix = '/' . $item->getName() . $appendix;
97
+			$appendix = '/'.$item->getName().$appendix;
98 98
 		}
99 99
 
100 100
 		return $results;
@@ -139,6 +139,6 @@  discard block
 block discarded – undo
139 139
 	protected function getMountedPath(Node $node) {
140 140
 		$path = $node->getPath();
141 141
 		$sections = explode('/', $path, 4);
142
-		return '/' . $sections[3];
142
+		return '/'.$sections[3];
143 143
 	}
144 144
 }
Please login to merge, or discard this patch.
apps/federatedfilesharing/lib/FederatedShareProvider.php 1 patch
Indentation   +954 added lines, -954 removed lines patch added patch discarded remove patch
@@ -50,968 +50,968 @@
 block discarded – undo
50 50
  */
51 51
 class FederatedShareProvider implements IShareProvider {
52 52
 
53
-	const SHARE_TYPE_REMOTE = 6;
54
-
55
-	/** @var IDBConnection */
56
-	private $dbConnection;
57
-
58
-	/** @var AddressHandler */
59
-	private $addressHandler;
60
-
61
-	/** @var Notifications */
62
-	private $notifications;
63
-
64
-	/** @var TokenHandler */
65
-	private $tokenHandler;
66
-
67
-	/** @var IL10N */
68
-	private $l;
69
-
70
-	/** @var ILogger */
71
-	private $logger;
72
-
73
-	/** @var IRootFolder */
74
-	private $rootFolder;
75
-
76
-	/** @var IConfig */
77
-	private $config;
78
-
79
-	/** @var string */
80
-	private $externalShareTable = 'share_external';
81
-
82
-	/** @var IUserManager */
83
-	private $userManager;
84
-
85
-	/** @var ICloudIdManager */
86
-	private $cloudIdManager;
87
-
88
-	/**
89
-	 * DefaultShareProvider constructor.
90
-	 *
91
-	 * @param IDBConnection $connection
92
-	 * @param AddressHandler $addressHandler
93
-	 * @param Notifications $notifications
94
-	 * @param TokenHandler $tokenHandler
95
-	 * @param IL10N $l10n
96
-	 * @param ILogger $logger
97
-	 * @param IRootFolder $rootFolder
98
-	 * @param IConfig $config
99
-	 * @param IUserManager $userManager
100
-	 * @param ICloudIdManager $cloudIdManager
101
-	 */
102
-	public function __construct(
103
-			IDBConnection $connection,
104
-			AddressHandler $addressHandler,
105
-			Notifications $notifications,
106
-			TokenHandler $tokenHandler,
107
-			IL10N $l10n,
108
-			ILogger $logger,
109
-			IRootFolder $rootFolder,
110
-			IConfig $config,
111
-			IUserManager $userManager,
112
-			ICloudIdManager $cloudIdManager
113
-	) {
114
-		$this->dbConnection = $connection;
115
-		$this->addressHandler = $addressHandler;
116
-		$this->notifications = $notifications;
117
-		$this->tokenHandler = $tokenHandler;
118
-		$this->l = $l10n;
119
-		$this->logger = $logger;
120
-		$this->rootFolder = $rootFolder;
121
-		$this->config = $config;
122
-		$this->userManager = $userManager;
123
-		$this->cloudIdManager = $cloudIdManager;
124
-	}
125
-
126
-	/**
127
-	 * Return the identifier of this provider.
128
-	 *
129
-	 * @return string Containing only [a-zA-Z0-9]
130
-	 */
131
-	public function identifier() {
132
-		return 'ocFederatedSharing';
133
-	}
134
-
135
-	/**
136
-	 * Share a path
137
-	 *
138
-	 * @param IShare $share
139
-	 * @return IShare The share object
140
-	 * @throws ShareNotFound
141
-	 * @throws \Exception
142
-	 */
143
-	public function create(IShare $share) {
144
-
145
-		$shareWith = $share->getSharedWith();
146
-		$itemSource = $share->getNodeId();
147
-		$itemType = $share->getNodeType();
148
-		$permissions = $share->getPermissions();
149
-		$sharedBy = $share->getSharedBy();
150
-
151
-		/*
53
+    const SHARE_TYPE_REMOTE = 6;
54
+
55
+    /** @var IDBConnection */
56
+    private $dbConnection;
57
+
58
+    /** @var AddressHandler */
59
+    private $addressHandler;
60
+
61
+    /** @var Notifications */
62
+    private $notifications;
63
+
64
+    /** @var TokenHandler */
65
+    private $tokenHandler;
66
+
67
+    /** @var IL10N */
68
+    private $l;
69
+
70
+    /** @var ILogger */
71
+    private $logger;
72
+
73
+    /** @var IRootFolder */
74
+    private $rootFolder;
75
+
76
+    /** @var IConfig */
77
+    private $config;
78
+
79
+    /** @var string */
80
+    private $externalShareTable = 'share_external';
81
+
82
+    /** @var IUserManager */
83
+    private $userManager;
84
+
85
+    /** @var ICloudIdManager */
86
+    private $cloudIdManager;
87
+
88
+    /**
89
+     * DefaultShareProvider constructor.
90
+     *
91
+     * @param IDBConnection $connection
92
+     * @param AddressHandler $addressHandler
93
+     * @param Notifications $notifications
94
+     * @param TokenHandler $tokenHandler
95
+     * @param IL10N $l10n
96
+     * @param ILogger $logger
97
+     * @param IRootFolder $rootFolder
98
+     * @param IConfig $config
99
+     * @param IUserManager $userManager
100
+     * @param ICloudIdManager $cloudIdManager
101
+     */
102
+    public function __construct(
103
+            IDBConnection $connection,
104
+            AddressHandler $addressHandler,
105
+            Notifications $notifications,
106
+            TokenHandler $tokenHandler,
107
+            IL10N $l10n,
108
+            ILogger $logger,
109
+            IRootFolder $rootFolder,
110
+            IConfig $config,
111
+            IUserManager $userManager,
112
+            ICloudIdManager $cloudIdManager
113
+    ) {
114
+        $this->dbConnection = $connection;
115
+        $this->addressHandler = $addressHandler;
116
+        $this->notifications = $notifications;
117
+        $this->tokenHandler = $tokenHandler;
118
+        $this->l = $l10n;
119
+        $this->logger = $logger;
120
+        $this->rootFolder = $rootFolder;
121
+        $this->config = $config;
122
+        $this->userManager = $userManager;
123
+        $this->cloudIdManager = $cloudIdManager;
124
+    }
125
+
126
+    /**
127
+     * Return the identifier of this provider.
128
+     *
129
+     * @return string Containing only [a-zA-Z0-9]
130
+     */
131
+    public function identifier() {
132
+        return 'ocFederatedSharing';
133
+    }
134
+
135
+    /**
136
+     * Share a path
137
+     *
138
+     * @param IShare $share
139
+     * @return IShare The share object
140
+     * @throws ShareNotFound
141
+     * @throws \Exception
142
+     */
143
+    public function create(IShare $share) {
144
+
145
+        $shareWith = $share->getSharedWith();
146
+        $itemSource = $share->getNodeId();
147
+        $itemType = $share->getNodeType();
148
+        $permissions = $share->getPermissions();
149
+        $sharedBy = $share->getSharedBy();
150
+
151
+        /*
152 152
 		 * Check if file is not already shared with the remote user
153 153
 		 */
154
-		$alreadyShared = $this->getSharedWith($shareWith, self::SHARE_TYPE_REMOTE, $share->getNode(), 1, 0);
155
-		if (!empty($alreadyShared)) {
156
-			$message = 'Sharing %s failed, because this item is already shared with %s';
157
-			$message_t = $this->l->t('Sharing %s failed, because this item is already shared with %s', array($share->getNode()->getName(), $shareWith));
158
-			$this->logger->debug(sprintf($message, $share->getNode()->getName(), $shareWith), ['app' => 'Federated File Sharing']);
159
-			throw new \Exception($message_t);
160
-		}
161
-
162
-
163
-		// don't allow federated shares if source and target server are the same
164
-		$cloudId = $this->cloudIdManager->resolveCloudId($shareWith);
165
-		$currentServer = $this->addressHandler->generateRemoteURL();
166
-		$currentUser = $sharedBy;
167
-		if ($this->addressHandler->compareAddresses($cloudId->getUser(), $cloudId->getRemote(), $currentUser, $currentServer)) {
168
-			$message = 'Not allowed to create a federated share with the same user.';
169
-			$message_t = $this->l->t('Not allowed to create a federated share with the same user');
170
-			$this->logger->debug($message, ['app' => 'Federated File Sharing']);
171
-			throw new \Exception($message_t);
172
-		}
173
-
174
-
175
-		$share->setSharedWith($cloudId->getId());
176
-
177
-		try {
178
-			$remoteShare = $this->getShareFromExternalShareTable($share);
179
-		} catch (ShareNotFound $e) {
180
-			$remoteShare = null;
181
-		}
182
-
183
-		if ($remoteShare) {
184
-			try {
185
-				$ownerCloudId = $this->cloudIdManager->getCloudId($remoteShare['owner'], $remoteShare['remote']);
186
-				$shareId = $this->addShareToDB($itemSource, $itemType, $shareWith, $sharedBy, $ownerCloudId->getId(), $permissions, 'tmp_token_' . time());
187
-				$share->setId($shareId);
188
-				list($token, $remoteId) = $this->askOwnerToReShare($shareWith, $share, $shareId);
189
-				// remote share was create successfully if we get a valid token as return
190
-				$send = is_string($token) && $token !== '';
191
-			} catch (\Exception $e) {
192
-				// fall back to old re-share behavior if the remote server
193
-				// doesn't support flat re-shares (was introduced with Nextcloud 9.1)
194
-				$this->removeShareFromTable($share);
195
-				$shareId = $this->createFederatedShare($share);
196
-			}
197
-			if ($send) {
198
-				$this->updateSuccessfulReshare($shareId, $token);
199
-				$this->storeRemoteId($shareId, $remoteId);
200
-			} else {
201
-				$this->removeShareFromTable($share);
202
-				$message_t = $this->l->t('File is already shared with %s', [$shareWith]);
203
-				throw new \Exception($message_t);
204
-			}
205
-
206
-		} else {
207
-			$shareId = $this->createFederatedShare($share);
208
-		}
209
-
210
-		$data = $this->getRawShare($shareId);
211
-		return $this->createShareObject($data);
212
-	}
213
-
214
-	/**
215
-	 * create federated share and inform the recipient
216
-	 *
217
-	 * @param IShare $share
218
-	 * @return int
219
-	 * @throws ShareNotFound
220
-	 * @throws \Exception
221
-	 */
222
-	protected function createFederatedShare(IShare $share) {
223
-		$token = $this->tokenHandler->generateToken();
224
-		$shareId = $this->addShareToDB(
225
-			$share->getNodeId(),
226
-			$share->getNodeType(),
227
-			$share->getSharedWith(),
228
-			$share->getSharedBy(),
229
-			$share->getShareOwner(),
230
-			$share->getPermissions(),
231
-			$token
232
-		);
233
-
234
-		$failure = false;
235
-
236
-		try {
237
-			$sharedByFederatedId = $share->getSharedBy();
238
-			if ($this->userManager->userExists($sharedByFederatedId)) {
239
-				$cloudId = $this->cloudIdManager->getCloudId($sharedByFederatedId, $this->addressHandler->generateRemoteURL());
240
-				$sharedByFederatedId = $cloudId->getId();
241
-			}
242
-			$ownerCloudId = $this->cloudIdManager->getCloudId($share->getShareOwner(), $this->addressHandler->generateRemoteURL());
243
-			$send = $this->notifications->sendRemoteShare(
244
-				$token,
245
-				$share->getSharedWith(),
246
-				$share->getNode()->getName(),
247
-				$shareId,
248
-				$share->getShareOwner(),
249
-				$ownerCloudId->getId(),
250
-				$share->getSharedBy(),
251
-				$sharedByFederatedId
252
-			);
253
-
254
-			if ($send === false) {
255
-				$failure = true;
256
-			}
257
-		} catch (\Exception $e) {
258
-			$this->logger->error('Failed to notify remote server of federated share, removing share (' . $e->getMessage() . ')');
259
-			$failure = true;
260
-		}
261
-
262
-		if($failure) {
263
-			$this->removeShareFromTableById($shareId);
264
-			$message_t = $this->l->t('Sharing %s failed, could not find %s, maybe the server is currently unreachable or uses a self-signed certificate.',
265
-				[$share->getNode()->getName(), $share->getSharedWith()]);
266
-			throw new \Exception($message_t);
267
-		}
268
-
269
-		return $shareId;
270
-
271
-	}
272
-
273
-	/**
274
-	 * @param string $shareWith
275
-	 * @param IShare $share
276
-	 * @param string $shareId internal share Id
277
-	 * @return array
278
-	 * @throws \Exception
279
-	 */
280
-	protected function askOwnerToReShare($shareWith, IShare $share, $shareId) {
281
-
282
-		$remoteShare = $this->getShareFromExternalShareTable($share);
283
-		$token = $remoteShare['share_token'];
284
-		$remoteId = $remoteShare['remote_id'];
285
-		$remote = $remoteShare['remote'];
286
-
287
-		list($token, $remoteId) = $this->notifications->requestReShare(
288
-			$token,
289
-			$remoteId,
290
-			$shareId,
291
-			$remote,
292
-			$shareWith,
293
-			$share->getPermissions()
294
-		);
295
-
296
-		return [$token, $remoteId];
297
-	}
298
-
299
-	/**
300
-	 * get federated share from the share_external table but exclude mounted link shares
301
-	 *
302
-	 * @param IShare $share
303
-	 * @return array
304
-	 * @throws ShareNotFound
305
-	 */
306
-	protected function getShareFromExternalShareTable(IShare $share) {
307
-		$query = $this->dbConnection->getQueryBuilder();
308
-		$query->select('*')->from($this->externalShareTable)
309
-			->where($query->expr()->eq('user', $query->createNamedParameter($share->getShareOwner())))
310
-			->andWhere($query->expr()->eq('mountpoint', $query->createNamedParameter($share->getTarget())));
311
-		$result = $query->execute()->fetchAll();
312
-
313
-		if (isset($result[0]) && (int)$result[0]['remote_id'] > 0) {
314
-			return $result[0];
315
-		}
316
-
317
-		throw new ShareNotFound('share not found in share_external table');
318
-	}
319
-
320
-	/**
321
-	 * add share to the database and return the ID
322
-	 *
323
-	 * @param int $itemSource
324
-	 * @param string $itemType
325
-	 * @param string $shareWith
326
-	 * @param string $sharedBy
327
-	 * @param string $uidOwner
328
-	 * @param int $permissions
329
-	 * @param string $token
330
-	 * @return int
331
-	 */
332
-	private function addShareToDB($itemSource, $itemType, $shareWith, $sharedBy, $uidOwner, $permissions, $token) {
333
-		$qb = $this->dbConnection->getQueryBuilder();
334
-		$qb->insert('share')
335
-			->setValue('share_type', $qb->createNamedParameter(self::SHARE_TYPE_REMOTE))
336
-			->setValue('item_type', $qb->createNamedParameter($itemType))
337
-			->setValue('item_source', $qb->createNamedParameter($itemSource))
338
-			->setValue('file_source', $qb->createNamedParameter($itemSource))
339
-			->setValue('share_with', $qb->createNamedParameter($shareWith))
340
-			->setValue('uid_owner', $qb->createNamedParameter($uidOwner))
341
-			->setValue('uid_initiator', $qb->createNamedParameter($sharedBy))
342
-			->setValue('permissions', $qb->createNamedParameter($permissions))
343
-			->setValue('token', $qb->createNamedParameter($token))
344
-			->setValue('stime', $qb->createNamedParameter(time()));
345
-
346
-		/*
154
+        $alreadyShared = $this->getSharedWith($shareWith, self::SHARE_TYPE_REMOTE, $share->getNode(), 1, 0);
155
+        if (!empty($alreadyShared)) {
156
+            $message = 'Sharing %s failed, because this item is already shared with %s';
157
+            $message_t = $this->l->t('Sharing %s failed, because this item is already shared with %s', array($share->getNode()->getName(), $shareWith));
158
+            $this->logger->debug(sprintf($message, $share->getNode()->getName(), $shareWith), ['app' => 'Federated File Sharing']);
159
+            throw new \Exception($message_t);
160
+        }
161
+
162
+
163
+        // don't allow federated shares if source and target server are the same
164
+        $cloudId = $this->cloudIdManager->resolveCloudId($shareWith);
165
+        $currentServer = $this->addressHandler->generateRemoteURL();
166
+        $currentUser = $sharedBy;
167
+        if ($this->addressHandler->compareAddresses($cloudId->getUser(), $cloudId->getRemote(), $currentUser, $currentServer)) {
168
+            $message = 'Not allowed to create a federated share with the same user.';
169
+            $message_t = $this->l->t('Not allowed to create a federated share with the same user');
170
+            $this->logger->debug($message, ['app' => 'Federated File Sharing']);
171
+            throw new \Exception($message_t);
172
+        }
173
+
174
+
175
+        $share->setSharedWith($cloudId->getId());
176
+
177
+        try {
178
+            $remoteShare = $this->getShareFromExternalShareTable($share);
179
+        } catch (ShareNotFound $e) {
180
+            $remoteShare = null;
181
+        }
182
+
183
+        if ($remoteShare) {
184
+            try {
185
+                $ownerCloudId = $this->cloudIdManager->getCloudId($remoteShare['owner'], $remoteShare['remote']);
186
+                $shareId = $this->addShareToDB($itemSource, $itemType, $shareWith, $sharedBy, $ownerCloudId->getId(), $permissions, 'tmp_token_' . time());
187
+                $share->setId($shareId);
188
+                list($token, $remoteId) = $this->askOwnerToReShare($shareWith, $share, $shareId);
189
+                // remote share was create successfully if we get a valid token as return
190
+                $send = is_string($token) && $token !== '';
191
+            } catch (\Exception $e) {
192
+                // fall back to old re-share behavior if the remote server
193
+                // doesn't support flat re-shares (was introduced with Nextcloud 9.1)
194
+                $this->removeShareFromTable($share);
195
+                $shareId = $this->createFederatedShare($share);
196
+            }
197
+            if ($send) {
198
+                $this->updateSuccessfulReshare($shareId, $token);
199
+                $this->storeRemoteId($shareId, $remoteId);
200
+            } else {
201
+                $this->removeShareFromTable($share);
202
+                $message_t = $this->l->t('File is already shared with %s', [$shareWith]);
203
+                throw new \Exception($message_t);
204
+            }
205
+
206
+        } else {
207
+            $shareId = $this->createFederatedShare($share);
208
+        }
209
+
210
+        $data = $this->getRawShare($shareId);
211
+        return $this->createShareObject($data);
212
+    }
213
+
214
+    /**
215
+     * create federated share and inform the recipient
216
+     *
217
+     * @param IShare $share
218
+     * @return int
219
+     * @throws ShareNotFound
220
+     * @throws \Exception
221
+     */
222
+    protected function createFederatedShare(IShare $share) {
223
+        $token = $this->tokenHandler->generateToken();
224
+        $shareId = $this->addShareToDB(
225
+            $share->getNodeId(),
226
+            $share->getNodeType(),
227
+            $share->getSharedWith(),
228
+            $share->getSharedBy(),
229
+            $share->getShareOwner(),
230
+            $share->getPermissions(),
231
+            $token
232
+        );
233
+
234
+        $failure = false;
235
+
236
+        try {
237
+            $sharedByFederatedId = $share->getSharedBy();
238
+            if ($this->userManager->userExists($sharedByFederatedId)) {
239
+                $cloudId = $this->cloudIdManager->getCloudId($sharedByFederatedId, $this->addressHandler->generateRemoteURL());
240
+                $sharedByFederatedId = $cloudId->getId();
241
+            }
242
+            $ownerCloudId = $this->cloudIdManager->getCloudId($share->getShareOwner(), $this->addressHandler->generateRemoteURL());
243
+            $send = $this->notifications->sendRemoteShare(
244
+                $token,
245
+                $share->getSharedWith(),
246
+                $share->getNode()->getName(),
247
+                $shareId,
248
+                $share->getShareOwner(),
249
+                $ownerCloudId->getId(),
250
+                $share->getSharedBy(),
251
+                $sharedByFederatedId
252
+            );
253
+
254
+            if ($send === false) {
255
+                $failure = true;
256
+            }
257
+        } catch (\Exception $e) {
258
+            $this->logger->error('Failed to notify remote server of federated share, removing share (' . $e->getMessage() . ')');
259
+            $failure = true;
260
+        }
261
+
262
+        if($failure) {
263
+            $this->removeShareFromTableById($shareId);
264
+            $message_t = $this->l->t('Sharing %s failed, could not find %s, maybe the server is currently unreachable or uses a self-signed certificate.',
265
+                [$share->getNode()->getName(), $share->getSharedWith()]);
266
+            throw new \Exception($message_t);
267
+        }
268
+
269
+        return $shareId;
270
+
271
+    }
272
+
273
+    /**
274
+     * @param string $shareWith
275
+     * @param IShare $share
276
+     * @param string $shareId internal share Id
277
+     * @return array
278
+     * @throws \Exception
279
+     */
280
+    protected function askOwnerToReShare($shareWith, IShare $share, $shareId) {
281
+
282
+        $remoteShare = $this->getShareFromExternalShareTable($share);
283
+        $token = $remoteShare['share_token'];
284
+        $remoteId = $remoteShare['remote_id'];
285
+        $remote = $remoteShare['remote'];
286
+
287
+        list($token, $remoteId) = $this->notifications->requestReShare(
288
+            $token,
289
+            $remoteId,
290
+            $shareId,
291
+            $remote,
292
+            $shareWith,
293
+            $share->getPermissions()
294
+        );
295
+
296
+        return [$token, $remoteId];
297
+    }
298
+
299
+    /**
300
+     * get federated share from the share_external table but exclude mounted link shares
301
+     *
302
+     * @param IShare $share
303
+     * @return array
304
+     * @throws ShareNotFound
305
+     */
306
+    protected function getShareFromExternalShareTable(IShare $share) {
307
+        $query = $this->dbConnection->getQueryBuilder();
308
+        $query->select('*')->from($this->externalShareTable)
309
+            ->where($query->expr()->eq('user', $query->createNamedParameter($share->getShareOwner())))
310
+            ->andWhere($query->expr()->eq('mountpoint', $query->createNamedParameter($share->getTarget())));
311
+        $result = $query->execute()->fetchAll();
312
+
313
+        if (isset($result[0]) && (int)$result[0]['remote_id'] > 0) {
314
+            return $result[0];
315
+        }
316
+
317
+        throw new ShareNotFound('share not found in share_external table');
318
+    }
319
+
320
+    /**
321
+     * add share to the database and return the ID
322
+     *
323
+     * @param int $itemSource
324
+     * @param string $itemType
325
+     * @param string $shareWith
326
+     * @param string $sharedBy
327
+     * @param string $uidOwner
328
+     * @param int $permissions
329
+     * @param string $token
330
+     * @return int
331
+     */
332
+    private function addShareToDB($itemSource, $itemType, $shareWith, $sharedBy, $uidOwner, $permissions, $token) {
333
+        $qb = $this->dbConnection->getQueryBuilder();
334
+        $qb->insert('share')
335
+            ->setValue('share_type', $qb->createNamedParameter(self::SHARE_TYPE_REMOTE))
336
+            ->setValue('item_type', $qb->createNamedParameter($itemType))
337
+            ->setValue('item_source', $qb->createNamedParameter($itemSource))
338
+            ->setValue('file_source', $qb->createNamedParameter($itemSource))
339
+            ->setValue('share_with', $qb->createNamedParameter($shareWith))
340
+            ->setValue('uid_owner', $qb->createNamedParameter($uidOwner))
341
+            ->setValue('uid_initiator', $qb->createNamedParameter($sharedBy))
342
+            ->setValue('permissions', $qb->createNamedParameter($permissions))
343
+            ->setValue('token', $qb->createNamedParameter($token))
344
+            ->setValue('stime', $qb->createNamedParameter(time()));
345
+
346
+        /*
347 347
 		 * Added to fix https://github.com/owncloud/core/issues/22215
348 348
 		 * Can be removed once we get rid of ajax/share.php
349 349
 		 */
350
-		$qb->setValue('file_target', $qb->createNamedParameter(''));
351
-
352
-		$qb->execute();
353
-		$id = $qb->getLastInsertId();
354
-
355
-		return (int)$id;
356
-	}
357
-
358
-	/**
359
-	 * Update a share
360
-	 *
361
-	 * @param IShare $share
362
-	 * @return IShare The share object
363
-	 */
364
-	public function update(IShare $share) {
365
-		/*
350
+        $qb->setValue('file_target', $qb->createNamedParameter(''));
351
+
352
+        $qb->execute();
353
+        $id = $qb->getLastInsertId();
354
+
355
+        return (int)$id;
356
+    }
357
+
358
+    /**
359
+     * Update a share
360
+     *
361
+     * @param IShare $share
362
+     * @return IShare The share object
363
+     */
364
+    public function update(IShare $share) {
365
+        /*
366 366
 		 * We allow updating the permissions of federated shares
367 367
 		 */
368
-		$qb = $this->dbConnection->getQueryBuilder();
369
-			$qb->update('share')
370
-				->where($qb->expr()->eq('id', $qb->createNamedParameter($share->getId())))
371
-				->set('permissions', $qb->createNamedParameter($share->getPermissions()))
372
-				->set('uid_owner', $qb->createNamedParameter($share->getShareOwner()))
373
-				->set('uid_initiator', $qb->createNamedParameter($share->getSharedBy()))
374
-				->execute();
375
-
376
-		// send the updated permission to the owner/initiator, if they are not the same
377
-		if ($share->getShareOwner() !== $share->getSharedBy()) {
378
-			$this->sendPermissionUpdate($share);
379
-		}
380
-
381
-		return $share;
382
-	}
383
-
384
-	/**
385
-	 * send the updated permission to the owner/initiator, if they are not the same
386
-	 *
387
-	 * @param IShare $share
388
-	 * @throws ShareNotFound
389
-	 * @throws \OC\HintException
390
-	 */
391
-	protected function sendPermissionUpdate(IShare $share) {
392
-		$remoteId = $this->getRemoteId($share);
393
-		// if the local user is the owner we send the permission change to the initiator
394
-		if ($this->userManager->userExists($share->getShareOwner())) {
395
-			list(, $remote) = $this->addressHandler->splitUserRemote($share->getSharedBy());
396
-		} else { // ... if not we send the permission change to the owner
397
-			list(, $remote) = $this->addressHandler->splitUserRemote($share->getShareOwner());
398
-		}
399
-		$this->notifications->sendPermissionChange($remote, $remoteId, $share->getToken(), $share->getPermissions());
400
-	}
401
-
402
-
403
-	/**
404
-	 * update successful reShare with the correct token
405
-	 *
406
-	 * @param int $shareId
407
-	 * @param string $token
408
-	 */
409
-	protected function updateSuccessfulReShare($shareId, $token) {
410
-		$query = $this->dbConnection->getQueryBuilder();
411
-		$query->update('share')
412
-			->where($query->expr()->eq('id', $query->createNamedParameter($shareId)))
413
-			->set('token', $query->createNamedParameter($token))
414
-			->execute();
415
-	}
416
-
417
-	/**
418
-	 * store remote ID in federated reShare table
419
-	 *
420
-	 * @param $shareId
421
-	 * @param $remoteId
422
-	 */
423
-	public function storeRemoteId($shareId, $remoteId) {
424
-		$query = $this->dbConnection->getQueryBuilder();
425
-		$query->insert('federated_reshares')
426
-			->values(
427
-				[
428
-					'share_id' =>  $query->createNamedParameter($shareId),
429
-					'remote_id' => $query->createNamedParameter($remoteId),
430
-				]
431
-			);
432
-		$query->execute();
433
-	}
434
-
435
-	/**
436
-	 * get share ID on remote server for federated re-shares
437
-	 *
438
-	 * @param IShare $share
439
-	 * @return int
440
-	 * @throws ShareNotFound
441
-	 */
442
-	public function getRemoteId(IShare $share) {
443
-		$query = $this->dbConnection->getQueryBuilder();
444
-		$query->select('remote_id')->from('federated_reshares')
445
-			->where($query->expr()->eq('share_id', $query->createNamedParameter((int)$share->getId())));
446
-		$data = $query->execute()->fetch();
447
-
448
-		if (!is_array($data) || !isset($data['remote_id'])) {
449
-			throw new ShareNotFound();
450
-		}
451
-
452
-		return (int)$data['remote_id'];
453
-	}
454
-
455
-	/**
456
-	 * @inheritdoc
457
-	 */
458
-	public function move(IShare $share, $recipient) {
459
-		/*
368
+        $qb = $this->dbConnection->getQueryBuilder();
369
+            $qb->update('share')
370
+                ->where($qb->expr()->eq('id', $qb->createNamedParameter($share->getId())))
371
+                ->set('permissions', $qb->createNamedParameter($share->getPermissions()))
372
+                ->set('uid_owner', $qb->createNamedParameter($share->getShareOwner()))
373
+                ->set('uid_initiator', $qb->createNamedParameter($share->getSharedBy()))
374
+                ->execute();
375
+
376
+        // send the updated permission to the owner/initiator, if they are not the same
377
+        if ($share->getShareOwner() !== $share->getSharedBy()) {
378
+            $this->sendPermissionUpdate($share);
379
+        }
380
+
381
+        return $share;
382
+    }
383
+
384
+    /**
385
+     * send the updated permission to the owner/initiator, if they are not the same
386
+     *
387
+     * @param IShare $share
388
+     * @throws ShareNotFound
389
+     * @throws \OC\HintException
390
+     */
391
+    protected function sendPermissionUpdate(IShare $share) {
392
+        $remoteId = $this->getRemoteId($share);
393
+        // if the local user is the owner we send the permission change to the initiator
394
+        if ($this->userManager->userExists($share->getShareOwner())) {
395
+            list(, $remote) = $this->addressHandler->splitUserRemote($share->getSharedBy());
396
+        } else { // ... if not we send the permission change to the owner
397
+            list(, $remote) = $this->addressHandler->splitUserRemote($share->getShareOwner());
398
+        }
399
+        $this->notifications->sendPermissionChange($remote, $remoteId, $share->getToken(), $share->getPermissions());
400
+    }
401
+
402
+
403
+    /**
404
+     * update successful reShare with the correct token
405
+     *
406
+     * @param int $shareId
407
+     * @param string $token
408
+     */
409
+    protected function updateSuccessfulReShare($shareId, $token) {
410
+        $query = $this->dbConnection->getQueryBuilder();
411
+        $query->update('share')
412
+            ->where($query->expr()->eq('id', $query->createNamedParameter($shareId)))
413
+            ->set('token', $query->createNamedParameter($token))
414
+            ->execute();
415
+    }
416
+
417
+    /**
418
+     * store remote ID in federated reShare table
419
+     *
420
+     * @param $shareId
421
+     * @param $remoteId
422
+     */
423
+    public function storeRemoteId($shareId, $remoteId) {
424
+        $query = $this->dbConnection->getQueryBuilder();
425
+        $query->insert('federated_reshares')
426
+            ->values(
427
+                [
428
+                    'share_id' =>  $query->createNamedParameter($shareId),
429
+                    'remote_id' => $query->createNamedParameter($remoteId),
430
+                ]
431
+            );
432
+        $query->execute();
433
+    }
434
+
435
+    /**
436
+     * get share ID on remote server for federated re-shares
437
+     *
438
+     * @param IShare $share
439
+     * @return int
440
+     * @throws ShareNotFound
441
+     */
442
+    public function getRemoteId(IShare $share) {
443
+        $query = $this->dbConnection->getQueryBuilder();
444
+        $query->select('remote_id')->from('federated_reshares')
445
+            ->where($query->expr()->eq('share_id', $query->createNamedParameter((int)$share->getId())));
446
+        $data = $query->execute()->fetch();
447
+
448
+        if (!is_array($data) || !isset($data['remote_id'])) {
449
+            throw new ShareNotFound();
450
+        }
451
+
452
+        return (int)$data['remote_id'];
453
+    }
454
+
455
+    /**
456
+     * @inheritdoc
457
+     */
458
+    public function move(IShare $share, $recipient) {
459
+        /*
460 460
 		 * This function does nothing yet as it is just for outgoing
461 461
 		 * federated shares.
462 462
 		 */
463
-		return $share;
464
-	}
465
-
466
-	/**
467
-	 * Get all children of this share
468
-	 *
469
-	 * @param IShare $parent
470
-	 * @return IShare[]
471
-	 */
472
-	public function getChildren(IShare $parent) {
473
-		$children = [];
474
-
475
-		$qb = $this->dbConnection->getQueryBuilder();
476
-		$qb->select('*')
477
-			->from('share')
478
-			->where($qb->expr()->eq('parent', $qb->createNamedParameter($parent->getId())))
479
-			->andWhere($qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_REMOTE)))
480
-			->orderBy('id');
481
-
482
-		$cursor = $qb->execute();
483
-		while($data = $cursor->fetch()) {
484
-			$children[] = $this->createShareObject($data);
485
-		}
486
-		$cursor->closeCursor();
487
-
488
-		return $children;
489
-	}
490
-
491
-	/**
492
-	 * Delete a share (owner unShares the file)
493
-	 *
494
-	 * @param IShare $share
495
-	 */
496
-	public function delete(IShare $share) {
497
-
498
-		list(, $remote) = $this->addressHandler->splitUserRemote($share->getSharedWith());
499
-
500
-		$isOwner = false;
501
-
502
-		$this->removeShareFromTable($share);
503
-
504
-		// if the local user is the owner we can send the unShare request directly...
505
-		if ($this->userManager->userExists($share->getShareOwner())) {
506
-			$this->notifications->sendRemoteUnShare($remote, $share->getId(), $share->getToken());
507
-			$this->revokeShare($share, true);
508
-			$isOwner = true;
509
-		} else { // ... if not we need to correct ID for the unShare request
510
-			$remoteId = $this->getRemoteId($share);
511
-			$this->notifications->sendRemoteUnShare($remote, $remoteId, $share->getToken());
512
-			$this->revokeShare($share, false);
513
-		}
514
-
515
-		// send revoke notification to the other user, if initiator and owner are not the same user
516
-		if ($share->getShareOwner() !== $share->getSharedBy()) {
517
-			$remoteId = $this->getRemoteId($share);
518
-			if ($isOwner) {
519
-				list(, $remote) = $this->addressHandler->splitUserRemote($share->getSharedBy());
520
-			} else {
521
-				list(, $remote) = $this->addressHandler->splitUserRemote($share->getShareOwner());
522
-			}
523
-			$this->notifications->sendRevokeShare($remote, $remoteId, $share->getToken());
524
-		}
525
-	}
526
-
527
-	/**
528
-	 * in case of a re-share we need to send the other use (initiator or owner)
529
-	 * a message that the file was unshared
530
-	 *
531
-	 * @param IShare $share
532
-	 * @param bool $isOwner the user can either be the owner or the user who re-sahred it
533
-	 * @throws ShareNotFound
534
-	 * @throws \OC\HintException
535
-	 */
536
-	protected function revokeShare($share, $isOwner) {
537
-		// also send a unShare request to the initiator, if this is a different user than the owner
538
-		if ($share->getShareOwner() !== $share->getSharedBy()) {
539
-			if ($isOwner) {
540
-				list(, $remote) = $this->addressHandler->splitUserRemote($share->getSharedBy());
541
-			} else {
542
-				list(, $remote) = $this->addressHandler->splitUserRemote($share->getShareOwner());
543
-			}
544
-			$remoteId = $this->getRemoteId($share);
545
-			$this->notifications->sendRevokeShare($remote, $remoteId, $share->getToken());
546
-		}
547
-	}
548
-
549
-	/**
550
-	 * remove share from table
551
-	 *
552
-	 * @param IShare $share
553
-	 */
554
-	public function removeShareFromTable(IShare $share) {
555
-		$this->removeShareFromTableById($share->getId());
556
-	}
557
-
558
-	/**
559
-	 * remove share from table
560
-	 *
561
-	 * @param string $shareId
562
-	 */
563
-	private function removeShareFromTableById($shareId) {
564
-		$qb = $this->dbConnection->getQueryBuilder();
565
-		$qb->delete('share')
566
-			->where($qb->expr()->eq('id', $qb->createNamedParameter($shareId)));
567
-		$qb->execute();
568
-
569
-		$qb->delete('federated_reshares')
570
-			->where($qb->expr()->eq('share_id', $qb->createNamedParameter($shareId)));
571
-		$qb->execute();
572
-	}
573
-
574
-	/**
575
-	 * @inheritdoc
576
-	 */
577
-	public function deleteFromSelf(IShare $share, $recipient) {
578
-		// nothing to do here. Technically deleteFromSelf in the context of federated
579
-		// shares is a umount of a external storage. This is handled here
580
-		// apps/files_sharing/lib/external/manager.php
581
-		// TODO move this code over to this app
582
-		return;
583
-	}
584
-
585
-
586
-	public function getSharesInFolder($userId, Folder $node, $reshares) {
587
-		$qb = $this->dbConnection->getQueryBuilder();
588
-		$qb->select('*')
589
-			->from('share', 's')
590
-			->andWhere($qb->expr()->orX(
591
-				$qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
592
-				$qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
593
-			))
594
-			->andWhere(
595
-				$qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_REMOTE))
596
-			);
597
-
598
-		/**
599
-		 * Reshares for this user are shares where they are the owner.
600
-		 */
601
-		if ($reshares === false) {
602
-			$qb->andWhere($qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId)));
603
-		} else {
604
-			$qb->andWhere(
605
-				$qb->expr()->orX(
606
-					$qb->expr()->eq('uid_owner', $qb->createNamedParameter($userId)),
607
-					$qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId))
608
-				)
609
-			);
610
-		}
611
-
612
-		$qb->innerJoin('s', 'filecache' ,'f', $qb->expr()->eq('s.file_source', 'f.fileid'));
613
-		$qb->andWhere($qb->expr()->eq('f.parent', $qb->createNamedParameter($node->getId())));
614
-
615
-		$qb->orderBy('id');
616
-
617
-		$cursor = $qb->execute();
618
-		$shares = [];
619
-		while ($data = $cursor->fetch()) {
620
-			$shares[$data['fileid']][] = $this->createShareObject($data);
621
-		}
622
-		$cursor->closeCursor();
623
-
624
-		return $shares;
625
-	}
626
-
627
-	/**
628
-	 * @inheritdoc
629
-	 */
630
-	public function getSharesBy($userId, $shareType, $node, $reshares, $limit, $offset) {
631
-		$qb = $this->dbConnection->getQueryBuilder();
632
-		$qb->select('*')
633
-			->from('share');
634
-
635
-		$qb->andWhere($qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_REMOTE)));
636
-
637
-		/**
638
-		 * Reshares for this user are shares where they are the owner.
639
-		 */
640
-		if ($reshares === false) {
641
-			//Special case for old shares created via the web UI
642
-			$or1 = $qb->expr()->andX(
643
-				$qb->expr()->eq('uid_owner', $qb->createNamedParameter($userId)),
644
-				$qb->expr()->isNull('uid_initiator')
645
-			);
646
-
647
-			$qb->andWhere(
648
-				$qb->expr()->orX(
649
-					$qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId)),
650
-					$or1
651
-				)
652
-			);
653
-		} else {
654
-			$qb->andWhere(
655
-				$qb->expr()->orX(
656
-					$qb->expr()->eq('uid_owner', $qb->createNamedParameter($userId)),
657
-					$qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId))
658
-				)
659
-			);
660
-		}
661
-
662
-		if ($node !== null) {
663
-			$qb->andWhere($qb->expr()->eq('file_source', $qb->createNamedParameter($node->getId())));
664
-		}
665
-
666
-		if ($limit !== -1) {
667
-			$qb->setMaxResults($limit);
668
-		}
669
-
670
-		$qb->setFirstResult($offset);
671
-		$qb->orderBy('id');
672
-
673
-		$cursor = $qb->execute();
674
-		$shares = [];
675
-		while($data = $cursor->fetch()) {
676
-			$shares[] = $this->createShareObject($data);
677
-		}
678
-		$cursor->closeCursor();
679
-
680
-		return $shares;
681
-	}
682
-
683
-	/**
684
-	 * @inheritdoc
685
-	 */
686
-	public function getShareById($id, $recipientId = null) {
687
-		$qb = $this->dbConnection->getQueryBuilder();
688
-
689
-		$qb->select('*')
690
-			->from('share')
691
-			->where($qb->expr()->eq('id', $qb->createNamedParameter($id)))
692
-			->andWhere($qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_REMOTE)));
693
-
694
-		$cursor = $qb->execute();
695
-		$data = $cursor->fetch();
696
-		$cursor->closeCursor();
697
-
698
-		if ($data === false) {
699
-			throw new ShareNotFound();
700
-		}
701
-
702
-		try {
703
-			$share = $this->createShareObject($data);
704
-		} catch (InvalidShare $e) {
705
-			throw new ShareNotFound();
706
-		}
707
-
708
-		return $share;
709
-	}
710
-
711
-	/**
712
-	 * Get shares for a given path
713
-	 *
714
-	 * @param \OCP\Files\Node $path
715
-	 * @return IShare[]
716
-	 */
717
-	public function getSharesByPath(Node $path) {
718
-		$qb = $this->dbConnection->getQueryBuilder();
719
-
720
-		$cursor = $qb->select('*')
721
-			->from('share')
722
-			->andWhere($qb->expr()->eq('file_source', $qb->createNamedParameter($path->getId())))
723
-			->andWhere($qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_REMOTE)))
724
-			->execute();
725
-
726
-		$shares = [];
727
-		while($data = $cursor->fetch()) {
728
-			$shares[] = $this->createShareObject($data);
729
-		}
730
-		$cursor->closeCursor();
731
-
732
-		return $shares;
733
-	}
734
-
735
-	/**
736
-	 * @inheritdoc
737
-	 */
738
-	public function getSharedWith($userId, $shareType, $node, $limit, $offset) {
739
-		/** @var IShare[] $shares */
740
-		$shares = [];
741
-
742
-		//Get shares directly with this user
743
-		$qb = $this->dbConnection->getQueryBuilder();
744
-		$qb->select('*')
745
-			->from('share');
746
-
747
-		// Order by id
748
-		$qb->orderBy('id');
749
-
750
-		// Set limit and offset
751
-		if ($limit !== -1) {
752
-			$qb->setMaxResults($limit);
753
-		}
754
-		$qb->setFirstResult($offset);
755
-
756
-		$qb->where($qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_REMOTE)));
757
-		$qb->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($userId)));
758
-
759
-		// Filter by node if provided
760
-		if ($node !== null) {
761
-			$qb->andWhere($qb->expr()->eq('file_source', $qb->createNamedParameter($node->getId())));
762
-		}
763
-
764
-		$cursor = $qb->execute();
765
-
766
-		while($data = $cursor->fetch()) {
767
-			$shares[] = $this->createShareObject($data);
768
-		}
769
-		$cursor->closeCursor();
770
-
771
-
772
-		return $shares;
773
-	}
774
-
775
-	/**
776
-	 * Get a share by token
777
-	 *
778
-	 * @param string $token
779
-	 * @return IShare
780
-	 * @throws ShareNotFound
781
-	 */
782
-	public function getShareByToken($token) {
783
-		$qb = $this->dbConnection->getQueryBuilder();
784
-
785
-		$cursor = $qb->select('*')
786
-			->from('share')
787
-			->where($qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_REMOTE)))
788
-			->andWhere($qb->expr()->eq('token', $qb->createNamedParameter($token)))
789
-			->execute();
790
-
791
-		$data = $cursor->fetch();
792
-
793
-		if ($data === false) {
794
-			throw new ShareNotFound('Share not found', $this->l->t('Could not find share'));
795
-		}
796
-
797
-		try {
798
-			$share = $this->createShareObject($data);
799
-		} catch (InvalidShare $e) {
800
-			throw new ShareNotFound('Share not found', $this->l->t('Could not find share'));
801
-		}
802
-
803
-		return $share;
804
-	}
805
-
806
-	/**
807
-	 * get database row of a give share
808
-	 *
809
-	 * @param $id
810
-	 * @return array
811
-	 * @throws ShareNotFound
812
-	 */
813
-	private function getRawShare($id) {
814
-
815
-		// Now fetch the inserted share and create a complete share object
816
-		$qb = $this->dbConnection->getQueryBuilder();
817
-		$qb->select('*')
818
-			->from('share')
819
-			->where($qb->expr()->eq('id', $qb->createNamedParameter($id)));
820
-
821
-		$cursor = $qb->execute();
822
-		$data = $cursor->fetch();
823
-		$cursor->closeCursor();
824
-
825
-		if ($data === false) {
826
-			throw new ShareNotFound;
827
-		}
828
-
829
-		return $data;
830
-	}
831
-
832
-	/**
833
-	 * Create a share object from an database row
834
-	 *
835
-	 * @param array $data
836
-	 * @return IShare
837
-	 * @throws InvalidShare
838
-	 * @throws ShareNotFound
839
-	 */
840
-	private function createShareObject($data) {
841
-
842
-		$share = new Share($this->rootFolder, $this->userManager);
843
-		$share->setId((int)$data['id'])
844
-			->setShareType((int)$data['share_type'])
845
-			->setPermissions((int)$data['permissions'])
846
-			->setTarget($data['file_target'])
847
-			->setMailSend((bool)$data['mail_send'])
848
-			->setToken($data['token']);
849
-
850
-		$shareTime = new \DateTime();
851
-		$shareTime->setTimestamp((int)$data['stime']);
852
-		$share->setShareTime($shareTime);
853
-		$share->setSharedWith($data['share_with']);
854
-
855
-		if ($data['uid_initiator'] !== null) {
856
-			$share->setShareOwner($data['uid_owner']);
857
-			$share->setSharedBy($data['uid_initiator']);
858
-		} else {
859
-			//OLD SHARE
860
-			$share->setSharedBy($data['uid_owner']);
861
-			$path = $this->getNode($share->getSharedBy(), (int)$data['file_source']);
862
-
863
-			$owner = $path->getOwner();
864
-			$share->setShareOwner($owner->getUID());
865
-		}
866
-
867
-		$share->setNodeId((int)$data['file_source']);
868
-		$share->setNodeType($data['item_type']);
869
-
870
-		$share->setProviderId($this->identifier());
871
-
872
-		return $share;
873
-	}
874
-
875
-	/**
876
-	 * Get the node with file $id for $user
877
-	 *
878
-	 * @param string $userId
879
-	 * @param int $id
880
-	 * @return \OCP\Files\File|\OCP\Files\Folder
881
-	 * @throws InvalidShare
882
-	 */
883
-	private function getNode($userId, $id) {
884
-		try {
885
-			$userFolder = $this->rootFolder->getUserFolder($userId);
886
-		} catch (NotFoundException $e) {
887
-			throw new InvalidShare();
888
-		}
889
-
890
-		$nodes = $userFolder->getById($id);
891
-
892
-		if (empty($nodes)) {
893
-			throw new InvalidShare();
894
-		}
895
-
896
-		return $nodes[0];
897
-	}
898
-
899
-	/**
900
-	 * A user is deleted from the system
901
-	 * So clean up the relevant shares.
902
-	 *
903
-	 * @param string $uid
904
-	 * @param int $shareType
905
-	 */
906
-	public function userDeleted($uid, $shareType) {
907
-		//TODO: probabaly a good idea to send unshare info to remote servers
908
-
909
-		$qb = $this->dbConnection->getQueryBuilder();
910
-
911
-		$qb->delete('share')
912
-			->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_REMOTE)))
913
-			->andWhere($qb->expr()->eq('uid_owner', $qb->createNamedParameter($uid)))
914
-			->execute();
915
-	}
916
-
917
-	/**
918
-	 * This provider does not handle groups
919
-	 *
920
-	 * @param string $gid
921
-	 */
922
-	public function groupDeleted($gid) {
923
-		// We don't handle groups here
924
-		return;
925
-	}
926
-
927
-	/**
928
-	 * This provider does not handle groups
929
-	 *
930
-	 * @param string $uid
931
-	 * @param string $gid
932
-	 */
933
-	public function userDeletedFromGroup($uid, $gid) {
934
-		// We don't handle groups here
935
-		return;
936
-	}
937
-
938
-	/**
939
-	 * check if users from other Nextcloud instances are allowed to mount public links share by this instance
940
-	 *
941
-	 * @return bool
942
-	 */
943
-	public function isOutgoingServer2serverShareEnabled() {
944
-		$result = $this->config->getAppValue('files_sharing', 'outgoing_server2server_share_enabled', 'yes');
945
-		return ($result === 'yes');
946
-	}
947
-
948
-	/**
949
-	 * check if users are allowed to mount public links from other ownClouds
950
-	 *
951
-	 * @return bool
952
-	 */
953
-	public function isIncomingServer2serverShareEnabled() {
954
-		$result = $this->config->getAppValue('files_sharing', 'incoming_server2server_share_enabled', 'yes');
955
-		return ($result === 'yes');
956
-	}
957
-
958
-	/**
959
-	 * Check if querying sharees on the lookup server is enabled
960
-	 *
961
-	 * @return bool
962
-	 */
963
-	public function isLookupServerQueriesEnabled() {
964
-		$result = $this->config->getAppValue('files_sharing', 'lookupServerEnabled', 'no');
965
-		return ($result === 'yes');
966
-	}
967
-
968
-
969
-	/**
970
-	 * Check if it is allowed to publish user specific data to the lookup server
971
-	 *
972
-	 * @return bool
973
-	 */
974
-	public function isLookupServerUploadEnabled() {
975
-		$result = $this->config->getAppValue('files_sharing', 'lookupServerUploadEnabled', 'yes');
976
-		return ($result === 'yes');
977
-	}
978
-
979
-	/**
980
-	 * @inheritdoc
981
-	 */
982
-	public function getAccessList($nodes, $currentAccess) {
983
-		$ids = [];
984
-		foreach ($nodes as $node) {
985
-			$ids[] = $node->getId();
986
-		}
987
-
988
-		$qb = $this->dbConnection->getQueryBuilder();
989
-		$qb->select('share_with', 'token', 'file_source')
990
-			->from('share')
991
-			->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_REMOTE)))
992
-			->andWhere($qb->expr()->in('file_source', $qb->createNamedParameter($ids, IQueryBuilder::PARAM_INT_ARRAY)))
993
-			->andWhere($qb->expr()->orX(
994
-				$qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
995
-				$qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
996
-			));
997
-		$cursor = $qb->execute();
998
-
999
-		if ($currentAccess === false) {
1000
-			$remote = $cursor->fetch() !== false;
1001
-			$cursor->closeCursor();
1002
-
1003
-			return ['remote' => $remote];
1004
-		}
1005
-
1006
-		$remote = [];
1007
-		while ($row = $cursor->fetch()) {
1008
-			$remote[$row['share_with']] = [
1009
-				'node_id' => $row['file_source'],
1010
-				'token' => $row['token'],
1011
-			];
1012
-		}
1013
-		$cursor->closeCursor();
1014
-
1015
-		return ['remote' => $remote];
1016
-	}
463
+        return $share;
464
+    }
465
+
466
+    /**
467
+     * Get all children of this share
468
+     *
469
+     * @param IShare $parent
470
+     * @return IShare[]
471
+     */
472
+    public function getChildren(IShare $parent) {
473
+        $children = [];
474
+
475
+        $qb = $this->dbConnection->getQueryBuilder();
476
+        $qb->select('*')
477
+            ->from('share')
478
+            ->where($qb->expr()->eq('parent', $qb->createNamedParameter($parent->getId())))
479
+            ->andWhere($qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_REMOTE)))
480
+            ->orderBy('id');
481
+
482
+        $cursor = $qb->execute();
483
+        while($data = $cursor->fetch()) {
484
+            $children[] = $this->createShareObject($data);
485
+        }
486
+        $cursor->closeCursor();
487
+
488
+        return $children;
489
+    }
490
+
491
+    /**
492
+     * Delete a share (owner unShares the file)
493
+     *
494
+     * @param IShare $share
495
+     */
496
+    public function delete(IShare $share) {
497
+
498
+        list(, $remote) = $this->addressHandler->splitUserRemote($share->getSharedWith());
499
+
500
+        $isOwner = false;
501
+
502
+        $this->removeShareFromTable($share);
503
+
504
+        // if the local user is the owner we can send the unShare request directly...
505
+        if ($this->userManager->userExists($share->getShareOwner())) {
506
+            $this->notifications->sendRemoteUnShare($remote, $share->getId(), $share->getToken());
507
+            $this->revokeShare($share, true);
508
+            $isOwner = true;
509
+        } else { // ... if not we need to correct ID for the unShare request
510
+            $remoteId = $this->getRemoteId($share);
511
+            $this->notifications->sendRemoteUnShare($remote, $remoteId, $share->getToken());
512
+            $this->revokeShare($share, false);
513
+        }
514
+
515
+        // send revoke notification to the other user, if initiator and owner are not the same user
516
+        if ($share->getShareOwner() !== $share->getSharedBy()) {
517
+            $remoteId = $this->getRemoteId($share);
518
+            if ($isOwner) {
519
+                list(, $remote) = $this->addressHandler->splitUserRemote($share->getSharedBy());
520
+            } else {
521
+                list(, $remote) = $this->addressHandler->splitUserRemote($share->getShareOwner());
522
+            }
523
+            $this->notifications->sendRevokeShare($remote, $remoteId, $share->getToken());
524
+        }
525
+    }
526
+
527
+    /**
528
+     * in case of a re-share we need to send the other use (initiator or owner)
529
+     * a message that the file was unshared
530
+     *
531
+     * @param IShare $share
532
+     * @param bool $isOwner the user can either be the owner or the user who re-sahred it
533
+     * @throws ShareNotFound
534
+     * @throws \OC\HintException
535
+     */
536
+    protected function revokeShare($share, $isOwner) {
537
+        // also send a unShare request to the initiator, if this is a different user than the owner
538
+        if ($share->getShareOwner() !== $share->getSharedBy()) {
539
+            if ($isOwner) {
540
+                list(, $remote) = $this->addressHandler->splitUserRemote($share->getSharedBy());
541
+            } else {
542
+                list(, $remote) = $this->addressHandler->splitUserRemote($share->getShareOwner());
543
+            }
544
+            $remoteId = $this->getRemoteId($share);
545
+            $this->notifications->sendRevokeShare($remote, $remoteId, $share->getToken());
546
+        }
547
+    }
548
+
549
+    /**
550
+     * remove share from table
551
+     *
552
+     * @param IShare $share
553
+     */
554
+    public function removeShareFromTable(IShare $share) {
555
+        $this->removeShareFromTableById($share->getId());
556
+    }
557
+
558
+    /**
559
+     * remove share from table
560
+     *
561
+     * @param string $shareId
562
+     */
563
+    private function removeShareFromTableById($shareId) {
564
+        $qb = $this->dbConnection->getQueryBuilder();
565
+        $qb->delete('share')
566
+            ->where($qb->expr()->eq('id', $qb->createNamedParameter($shareId)));
567
+        $qb->execute();
568
+
569
+        $qb->delete('federated_reshares')
570
+            ->where($qb->expr()->eq('share_id', $qb->createNamedParameter($shareId)));
571
+        $qb->execute();
572
+    }
573
+
574
+    /**
575
+     * @inheritdoc
576
+     */
577
+    public function deleteFromSelf(IShare $share, $recipient) {
578
+        // nothing to do here. Technically deleteFromSelf in the context of federated
579
+        // shares is a umount of a external storage. This is handled here
580
+        // apps/files_sharing/lib/external/manager.php
581
+        // TODO move this code over to this app
582
+        return;
583
+    }
584
+
585
+
586
+    public function getSharesInFolder($userId, Folder $node, $reshares) {
587
+        $qb = $this->dbConnection->getQueryBuilder();
588
+        $qb->select('*')
589
+            ->from('share', 's')
590
+            ->andWhere($qb->expr()->orX(
591
+                $qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
592
+                $qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
593
+            ))
594
+            ->andWhere(
595
+                $qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_REMOTE))
596
+            );
597
+
598
+        /**
599
+         * Reshares for this user are shares where they are the owner.
600
+         */
601
+        if ($reshares === false) {
602
+            $qb->andWhere($qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId)));
603
+        } else {
604
+            $qb->andWhere(
605
+                $qb->expr()->orX(
606
+                    $qb->expr()->eq('uid_owner', $qb->createNamedParameter($userId)),
607
+                    $qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId))
608
+                )
609
+            );
610
+        }
611
+
612
+        $qb->innerJoin('s', 'filecache' ,'f', $qb->expr()->eq('s.file_source', 'f.fileid'));
613
+        $qb->andWhere($qb->expr()->eq('f.parent', $qb->createNamedParameter($node->getId())));
614
+
615
+        $qb->orderBy('id');
616
+
617
+        $cursor = $qb->execute();
618
+        $shares = [];
619
+        while ($data = $cursor->fetch()) {
620
+            $shares[$data['fileid']][] = $this->createShareObject($data);
621
+        }
622
+        $cursor->closeCursor();
623
+
624
+        return $shares;
625
+    }
626
+
627
+    /**
628
+     * @inheritdoc
629
+     */
630
+    public function getSharesBy($userId, $shareType, $node, $reshares, $limit, $offset) {
631
+        $qb = $this->dbConnection->getQueryBuilder();
632
+        $qb->select('*')
633
+            ->from('share');
634
+
635
+        $qb->andWhere($qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_REMOTE)));
636
+
637
+        /**
638
+         * Reshares for this user are shares where they are the owner.
639
+         */
640
+        if ($reshares === false) {
641
+            //Special case for old shares created via the web UI
642
+            $or1 = $qb->expr()->andX(
643
+                $qb->expr()->eq('uid_owner', $qb->createNamedParameter($userId)),
644
+                $qb->expr()->isNull('uid_initiator')
645
+            );
646
+
647
+            $qb->andWhere(
648
+                $qb->expr()->orX(
649
+                    $qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId)),
650
+                    $or1
651
+                )
652
+            );
653
+        } else {
654
+            $qb->andWhere(
655
+                $qb->expr()->orX(
656
+                    $qb->expr()->eq('uid_owner', $qb->createNamedParameter($userId)),
657
+                    $qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId))
658
+                )
659
+            );
660
+        }
661
+
662
+        if ($node !== null) {
663
+            $qb->andWhere($qb->expr()->eq('file_source', $qb->createNamedParameter($node->getId())));
664
+        }
665
+
666
+        if ($limit !== -1) {
667
+            $qb->setMaxResults($limit);
668
+        }
669
+
670
+        $qb->setFirstResult($offset);
671
+        $qb->orderBy('id');
672
+
673
+        $cursor = $qb->execute();
674
+        $shares = [];
675
+        while($data = $cursor->fetch()) {
676
+            $shares[] = $this->createShareObject($data);
677
+        }
678
+        $cursor->closeCursor();
679
+
680
+        return $shares;
681
+    }
682
+
683
+    /**
684
+     * @inheritdoc
685
+     */
686
+    public function getShareById($id, $recipientId = null) {
687
+        $qb = $this->dbConnection->getQueryBuilder();
688
+
689
+        $qb->select('*')
690
+            ->from('share')
691
+            ->where($qb->expr()->eq('id', $qb->createNamedParameter($id)))
692
+            ->andWhere($qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_REMOTE)));
693
+
694
+        $cursor = $qb->execute();
695
+        $data = $cursor->fetch();
696
+        $cursor->closeCursor();
697
+
698
+        if ($data === false) {
699
+            throw new ShareNotFound();
700
+        }
701
+
702
+        try {
703
+            $share = $this->createShareObject($data);
704
+        } catch (InvalidShare $e) {
705
+            throw new ShareNotFound();
706
+        }
707
+
708
+        return $share;
709
+    }
710
+
711
+    /**
712
+     * Get shares for a given path
713
+     *
714
+     * @param \OCP\Files\Node $path
715
+     * @return IShare[]
716
+     */
717
+    public function getSharesByPath(Node $path) {
718
+        $qb = $this->dbConnection->getQueryBuilder();
719
+
720
+        $cursor = $qb->select('*')
721
+            ->from('share')
722
+            ->andWhere($qb->expr()->eq('file_source', $qb->createNamedParameter($path->getId())))
723
+            ->andWhere($qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_REMOTE)))
724
+            ->execute();
725
+
726
+        $shares = [];
727
+        while($data = $cursor->fetch()) {
728
+            $shares[] = $this->createShareObject($data);
729
+        }
730
+        $cursor->closeCursor();
731
+
732
+        return $shares;
733
+    }
734
+
735
+    /**
736
+     * @inheritdoc
737
+     */
738
+    public function getSharedWith($userId, $shareType, $node, $limit, $offset) {
739
+        /** @var IShare[] $shares */
740
+        $shares = [];
741
+
742
+        //Get shares directly with this user
743
+        $qb = $this->dbConnection->getQueryBuilder();
744
+        $qb->select('*')
745
+            ->from('share');
746
+
747
+        // Order by id
748
+        $qb->orderBy('id');
749
+
750
+        // Set limit and offset
751
+        if ($limit !== -1) {
752
+            $qb->setMaxResults($limit);
753
+        }
754
+        $qb->setFirstResult($offset);
755
+
756
+        $qb->where($qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_REMOTE)));
757
+        $qb->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($userId)));
758
+
759
+        // Filter by node if provided
760
+        if ($node !== null) {
761
+            $qb->andWhere($qb->expr()->eq('file_source', $qb->createNamedParameter($node->getId())));
762
+        }
763
+
764
+        $cursor = $qb->execute();
765
+
766
+        while($data = $cursor->fetch()) {
767
+            $shares[] = $this->createShareObject($data);
768
+        }
769
+        $cursor->closeCursor();
770
+
771
+
772
+        return $shares;
773
+    }
774
+
775
+    /**
776
+     * Get a share by token
777
+     *
778
+     * @param string $token
779
+     * @return IShare
780
+     * @throws ShareNotFound
781
+     */
782
+    public function getShareByToken($token) {
783
+        $qb = $this->dbConnection->getQueryBuilder();
784
+
785
+        $cursor = $qb->select('*')
786
+            ->from('share')
787
+            ->where($qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_REMOTE)))
788
+            ->andWhere($qb->expr()->eq('token', $qb->createNamedParameter($token)))
789
+            ->execute();
790
+
791
+        $data = $cursor->fetch();
792
+
793
+        if ($data === false) {
794
+            throw new ShareNotFound('Share not found', $this->l->t('Could not find share'));
795
+        }
796
+
797
+        try {
798
+            $share = $this->createShareObject($data);
799
+        } catch (InvalidShare $e) {
800
+            throw new ShareNotFound('Share not found', $this->l->t('Could not find share'));
801
+        }
802
+
803
+        return $share;
804
+    }
805
+
806
+    /**
807
+     * get database row of a give share
808
+     *
809
+     * @param $id
810
+     * @return array
811
+     * @throws ShareNotFound
812
+     */
813
+    private function getRawShare($id) {
814
+
815
+        // Now fetch the inserted share and create a complete share object
816
+        $qb = $this->dbConnection->getQueryBuilder();
817
+        $qb->select('*')
818
+            ->from('share')
819
+            ->where($qb->expr()->eq('id', $qb->createNamedParameter($id)));
820
+
821
+        $cursor = $qb->execute();
822
+        $data = $cursor->fetch();
823
+        $cursor->closeCursor();
824
+
825
+        if ($data === false) {
826
+            throw new ShareNotFound;
827
+        }
828
+
829
+        return $data;
830
+    }
831
+
832
+    /**
833
+     * Create a share object from an database row
834
+     *
835
+     * @param array $data
836
+     * @return IShare
837
+     * @throws InvalidShare
838
+     * @throws ShareNotFound
839
+     */
840
+    private function createShareObject($data) {
841
+
842
+        $share = new Share($this->rootFolder, $this->userManager);
843
+        $share->setId((int)$data['id'])
844
+            ->setShareType((int)$data['share_type'])
845
+            ->setPermissions((int)$data['permissions'])
846
+            ->setTarget($data['file_target'])
847
+            ->setMailSend((bool)$data['mail_send'])
848
+            ->setToken($data['token']);
849
+
850
+        $shareTime = new \DateTime();
851
+        $shareTime->setTimestamp((int)$data['stime']);
852
+        $share->setShareTime($shareTime);
853
+        $share->setSharedWith($data['share_with']);
854
+
855
+        if ($data['uid_initiator'] !== null) {
856
+            $share->setShareOwner($data['uid_owner']);
857
+            $share->setSharedBy($data['uid_initiator']);
858
+        } else {
859
+            //OLD SHARE
860
+            $share->setSharedBy($data['uid_owner']);
861
+            $path = $this->getNode($share->getSharedBy(), (int)$data['file_source']);
862
+
863
+            $owner = $path->getOwner();
864
+            $share->setShareOwner($owner->getUID());
865
+        }
866
+
867
+        $share->setNodeId((int)$data['file_source']);
868
+        $share->setNodeType($data['item_type']);
869
+
870
+        $share->setProviderId($this->identifier());
871
+
872
+        return $share;
873
+    }
874
+
875
+    /**
876
+     * Get the node with file $id for $user
877
+     *
878
+     * @param string $userId
879
+     * @param int $id
880
+     * @return \OCP\Files\File|\OCP\Files\Folder
881
+     * @throws InvalidShare
882
+     */
883
+    private function getNode($userId, $id) {
884
+        try {
885
+            $userFolder = $this->rootFolder->getUserFolder($userId);
886
+        } catch (NotFoundException $e) {
887
+            throw new InvalidShare();
888
+        }
889
+
890
+        $nodes = $userFolder->getById($id);
891
+
892
+        if (empty($nodes)) {
893
+            throw new InvalidShare();
894
+        }
895
+
896
+        return $nodes[0];
897
+    }
898
+
899
+    /**
900
+     * A user is deleted from the system
901
+     * So clean up the relevant shares.
902
+     *
903
+     * @param string $uid
904
+     * @param int $shareType
905
+     */
906
+    public function userDeleted($uid, $shareType) {
907
+        //TODO: probabaly a good idea to send unshare info to remote servers
908
+
909
+        $qb = $this->dbConnection->getQueryBuilder();
910
+
911
+        $qb->delete('share')
912
+            ->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_REMOTE)))
913
+            ->andWhere($qb->expr()->eq('uid_owner', $qb->createNamedParameter($uid)))
914
+            ->execute();
915
+    }
916
+
917
+    /**
918
+     * This provider does not handle groups
919
+     *
920
+     * @param string $gid
921
+     */
922
+    public function groupDeleted($gid) {
923
+        // We don't handle groups here
924
+        return;
925
+    }
926
+
927
+    /**
928
+     * This provider does not handle groups
929
+     *
930
+     * @param string $uid
931
+     * @param string $gid
932
+     */
933
+    public function userDeletedFromGroup($uid, $gid) {
934
+        // We don't handle groups here
935
+        return;
936
+    }
937
+
938
+    /**
939
+     * check if users from other Nextcloud instances are allowed to mount public links share by this instance
940
+     *
941
+     * @return bool
942
+     */
943
+    public function isOutgoingServer2serverShareEnabled() {
944
+        $result = $this->config->getAppValue('files_sharing', 'outgoing_server2server_share_enabled', 'yes');
945
+        return ($result === 'yes');
946
+    }
947
+
948
+    /**
949
+     * check if users are allowed to mount public links from other ownClouds
950
+     *
951
+     * @return bool
952
+     */
953
+    public function isIncomingServer2serverShareEnabled() {
954
+        $result = $this->config->getAppValue('files_sharing', 'incoming_server2server_share_enabled', 'yes');
955
+        return ($result === 'yes');
956
+    }
957
+
958
+    /**
959
+     * Check if querying sharees on the lookup server is enabled
960
+     *
961
+     * @return bool
962
+     */
963
+    public function isLookupServerQueriesEnabled() {
964
+        $result = $this->config->getAppValue('files_sharing', 'lookupServerEnabled', 'no');
965
+        return ($result === 'yes');
966
+    }
967
+
968
+
969
+    /**
970
+     * Check if it is allowed to publish user specific data to the lookup server
971
+     *
972
+     * @return bool
973
+     */
974
+    public function isLookupServerUploadEnabled() {
975
+        $result = $this->config->getAppValue('files_sharing', 'lookupServerUploadEnabled', 'yes');
976
+        return ($result === 'yes');
977
+    }
978
+
979
+    /**
980
+     * @inheritdoc
981
+     */
982
+    public function getAccessList($nodes, $currentAccess) {
983
+        $ids = [];
984
+        foreach ($nodes as $node) {
985
+            $ids[] = $node->getId();
986
+        }
987
+
988
+        $qb = $this->dbConnection->getQueryBuilder();
989
+        $qb->select('share_with', 'token', 'file_source')
990
+            ->from('share')
991
+            ->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_REMOTE)))
992
+            ->andWhere($qb->expr()->in('file_source', $qb->createNamedParameter($ids, IQueryBuilder::PARAM_INT_ARRAY)))
993
+            ->andWhere($qb->expr()->orX(
994
+                $qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
995
+                $qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
996
+            ));
997
+        $cursor = $qb->execute();
998
+
999
+        if ($currentAccess === false) {
1000
+            $remote = $cursor->fetch() !== false;
1001
+            $cursor->closeCursor();
1002
+
1003
+            return ['remote' => $remote];
1004
+        }
1005
+
1006
+        $remote = [];
1007
+        while ($row = $cursor->fetch()) {
1008
+            $remote[$row['share_with']] = [
1009
+                'node_id' => $row['file_source'],
1010
+                'token' => $row['token'],
1011
+            ];
1012
+        }
1013
+        $cursor->closeCursor();
1014
+
1015
+        return ['remote' => $remote];
1016
+    }
1017 1017
 }
Please login to merge, or discard this patch.
apps/sharebymail/lib/ShareByMailProvider.php 1 patch
Indentation   +817 added lines, -817 removed lines patch added patch discarded remove patch
@@ -50,835 +50,835 @@
 block discarded – undo
50 50
  */
51 51
 class ShareByMailProvider implements IShareProvider {
52 52
 
53
-	/** @var  IDBConnection */
54
-	private $dbConnection;
55
-
56
-	/** @var ILogger */
57
-	private $logger;
58
-
59
-	/** @var ISecureRandom */
60
-	private $secureRandom;
61
-
62
-	/** @var IUserManager */
63
-	private $userManager;
64
-
65
-	/** @var IRootFolder */
66
-	private $rootFolder;
67
-
68
-	/** @var IL10N */
69
-	private $l;
70
-
71
-	/** @var IMailer */
72
-	private $mailer;
73
-
74
-	/** @var IURLGenerator */
75
-	private $urlGenerator;
76
-
77
-	/** @var IManager  */
78
-	private $activityManager;
79
-
80
-	/** @var SettingsManager */
81
-	private $settingsManager;
82
-
83
-	/**
84
-	 * Return the identifier of this provider.
85
-	 *
86
-	 * @return string Containing only [a-zA-Z0-9]
87
-	 */
88
-	public function identifier() {
89
-		return 'ocMailShare';
90
-	}
91
-
92
-	/**
93
-	 * DefaultShareProvider constructor.
94
-	 *
95
-	 * @param IDBConnection $connection
96
-	 * @param ISecureRandom $secureRandom
97
-	 * @param IUserManager $userManager
98
-	 * @param IRootFolder $rootFolder
99
-	 * @param IL10N $l
100
-	 * @param ILogger $logger
101
-	 * @param IMailer $mailer
102
-	 * @param IURLGenerator $urlGenerator
103
-	 * @param IManager $activityManager
104
-	 * @param SettingsManager $settingsManager
105
-	 */
106
-	public function __construct(
107
-		IDBConnection $connection,
108
-		ISecureRandom $secureRandom,
109
-		IUserManager $userManager,
110
-		IRootFolder $rootFolder,
111
-		IL10N $l,
112
-		ILogger $logger,
113
-		IMailer $mailer,
114
-		IURLGenerator $urlGenerator,
115
-		IManager $activityManager,
116
-		SettingsManager $settingsManager
117
-	) {
118
-		$this->dbConnection = $connection;
119
-		$this->secureRandom = $secureRandom;
120
-		$this->userManager = $userManager;
121
-		$this->rootFolder = $rootFolder;
122
-		$this->l = $l;
123
-		$this->logger = $logger;
124
-		$this->mailer = $mailer;
125
-		$this->urlGenerator = $urlGenerator;
126
-		$this->activityManager = $activityManager;
127
-		$this->settingsManager = $settingsManager;
128
-	}
129
-
130
-	/**
131
-	 * Share a path
132
-	 *
133
-	 * @param IShare $share
134
-	 * @return IShare The share object
135
-	 * @throws ShareNotFound
136
-	 * @throws \Exception
137
-	 */
138
-	public function create(IShare $share) {
139
-
140
-		$shareWith = $share->getSharedWith();
141
-		/*
53
+    /** @var  IDBConnection */
54
+    private $dbConnection;
55
+
56
+    /** @var ILogger */
57
+    private $logger;
58
+
59
+    /** @var ISecureRandom */
60
+    private $secureRandom;
61
+
62
+    /** @var IUserManager */
63
+    private $userManager;
64
+
65
+    /** @var IRootFolder */
66
+    private $rootFolder;
67
+
68
+    /** @var IL10N */
69
+    private $l;
70
+
71
+    /** @var IMailer */
72
+    private $mailer;
73
+
74
+    /** @var IURLGenerator */
75
+    private $urlGenerator;
76
+
77
+    /** @var IManager  */
78
+    private $activityManager;
79
+
80
+    /** @var SettingsManager */
81
+    private $settingsManager;
82
+
83
+    /**
84
+     * Return the identifier of this provider.
85
+     *
86
+     * @return string Containing only [a-zA-Z0-9]
87
+     */
88
+    public function identifier() {
89
+        return 'ocMailShare';
90
+    }
91
+
92
+    /**
93
+     * DefaultShareProvider constructor.
94
+     *
95
+     * @param IDBConnection $connection
96
+     * @param ISecureRandom $secureRandom
97
+     * @param IUserManager $userManager
98
+     * @param IRootFolder $rootFolder
99
+     * @param IL10N $l
100
+     * @param ILogger $logger
101
+     * @param IMailer $mailer
102
+     * @param IURLGenerator $urlGenerator
103
+     * @param IManager $activityManager
104
+     * @param SettingsManager $settingsManager
105
+     */
106
+    public function __construct(
107
+        IDBConnection $connection,
108
+        ISecureRandom $secureRandom,
109
+        IUserManager $userManager,
110
+        IRootFolder $rootFolder,
111
+        IL10N $l,
112
+        ILogger $logger,
113
+        IMailer $mailer,
114
+        IURLGenerator $urlGenerator,
115
+        IManager $activityManager,
116
+        SettingsManager $settingsManager
117
+    ) {
118
+        $this->dbConnection = $connection;
119
+        $this->secureRandom = $secureRandom;
120
+        $this->userManager = $userManager;
121
+        $this->rootFolder = $rootFolder;
122
+        $this->l = $l;
123
+        $this->logger = $logger;
124
+        $this->mailer = $mailer;
125
+        $this->urlGenerator = $urlGenerator;
126
+        $this->activityManager = $activityManager;
127
+        $this->settingsManager = $settingsManager;
128
+    }
129
+
130
+    /**
131
+     * Share a path
132
+     *
133
+     * @param IShare $share
134
+     * @return IShare The share object
135
+     * @throws ShareNotFound
136
+     * @throws \Exception
137
+     */
138
+    public function create(IShare $share) {
139
+
140
+        $shareWith = $share->getSharedWith();
141
+        /*
142 142
 		 * Check if file is not already shared with the remote user
143 143
 		 */
144
-		$alreadyShared = $this->getSharedWith($shareWith, \OCP\Share::SHARE_TYPE_EMAIL, $share->getNode(), 1, 0);
145
-		if (!empty($alreadyShared)) {
146
-			$message = 'Sharing %s failed, this item is already shared with %s';
147
-			$message_t = $this->l->t('Sharing %s failed, this item is already shared with %s', array($share->getNode()->getName(), $shareWith));
148
-			$this->logger->debug(sprintf($message, $share->getNode()->getName(), $shareWith), ['app' => 'Federated File Sharing']);
149
-			throw new \Exception($message_t);
150
-		}
151
-
152
-		$shareId = $this->createMailShare($share);
153
-		$this->createActivity($share);
154
-		$data = $this->getRawShare($shareId);
155
-		return $this->createShareObject($data);
156
-
157
-	}
158
-
159
-	/**
160
-	 * create activity if a file/folder was shared by mail
161
-	 *
162
-	 * @param IShare $share
163
-	 */
164
-	protected function createActivity(IShare $share) {
165
-
166
-		$userFolder = $this->rootFolder->getUserFolder($share->getSharedBy());
167
-
168
-		$this->publishActivity(
169
-			Activity::SUBJECT_SHARED_EMAIL_SELF,
170
-			[$userFolder->getRelativePath($share->getNode()->getPath()), $share->getSharedWith()],
171
-			$share->getSharedBy(),
172
-			$share->getNode()->getId(),
173
-			$userFolder->getRelativePath($share->getNode()->getPath())
174
-		);
175
-
176
-		if ($share->getShareOwner() !== $share->getSharedBy()) {
177
-			$ownerFolder = $this->rootFolder->getUserFolder($share->getShareOwner());
178
-			$fileId = $share->getNode()->getId();
179
-			$nodes = $ownerFolder->getById($fileId);
180
-			$ownerPath = $nodes[0]->getPath();
181
-			$this->publishActivity(
182
-				Activity::SUBJECT_SHARED_EMAIL_BY,
183
-				[$ownerFolder->getRelativePath($ownerPath), $share->getSharedWith(), $share->getSharedBy()],
184
-				$share->getShareOwner(),
185
-				$fileId,
186
-				$ownerFolder->getRelativePath($ownerPath)
187
-			);
188
-		}
189
-
190
-	}
191
-
192
-	/**
193
-	 * publish activity if a file/folder was shared by mail
194
-	 *
195
-	 * @param $subject
196
-	 * @param $parameters
197
-	 * @param $affectedUser
198
-	 * @param $fileId
199
-	 * @param $filePath
200
-	 */
201
-	protected function publishActivity($subject, $parameters, $affectedUser, $fileId, $filePath) {
202
-		$event = $this->activityManager->generateEvent();
203
-		$event->setApp('sharebymail')
204
-			->setType('shared')
205
-			->setSubject($subject, $parameters)
206
-			->setAffectedUser($affectedUser)
207
-			->setObject('files', $fileId, $filePath);
208
-		$this->activityManager->publish($event);
209
-
210
-	}
211
-
212
-	/**
213
-	 * @param IShare $share
214
-	 * @return int
215
-	 * @throws \Exception
216
-	 */
217
-	protected function createMailShare(IShare $share) {
218
-		$share->setToken($this->generateToken());
219
-		$shareId = $this->addShareToDB(
220
-			$share->getNodeId(),
221
-			$share->getNodeType(),
222
-			$share->getSharedWith(),
223
-			$share->getSharedBy(),
224
-			$share->getShareOwner(),
225
-			$share->getPermissions(),
226
-			$share->getToken()
227
-		);
228
-
229
-		try {
230
-			$link = $this->urlGenerator->linkToRouteAbsolute('files_sharing.sharecontroller.showShare',
231
-				['token' => $share->getToken()]);
232
-			$this->sendMailNotification($share->getNode()->getName(),
233
-				$link,
234
-				$share->getShareOwner(),
235
-				$share->getSharedBy(), $share->getSharedWith());
236
-		} catch (HintException $hintException) {
237
-			$this->logger->error('Failed to send share by mail: ' . $hintException->getMessage());
238
-			$this->removeShareFromTable($shareId);
239
-			throw $hintException;
240
-		} catch (\Exception $e) {
241
-			$this->logger->error('Failed to send share by mail: ' . $e->getMessage());
242
-			$this->removeShareFromTable($shareId);
243
-			throw new HintException('Failed to send share by mail',
244
-				$this->l->t('Failed to send share by E-mail'));
245
-		}
246
-
247
-		return $shareId;
248
-
249
-	}
250
-
251
-	protected function sendMailNotification($filename, $link, $owner, $initiator, $shareWith) {
252
-		$ownerUser = $this->userManager->get($owner);
253
-		$initiatorUser = $this->userManager->get($initiator);
254
-		$ownerDisplayName = ($ownerUser instanceof IUser) ? $ownerUser->getDisplayName() : $owner;
255
-		$initiatorDisplayName = ($initiatorUser instanceof IUser) ? $initiatorUser->getDisplayName() : $initiator;
256
-		if ($owner === $initiator) {
257
-			$subject = (string)$this->l->t('%s shared »%s« with you', array($ownerDisplayName, $filename));
258
-		} else {
259
-			$subject = (string)$this->l->t('%s shared »%s« with you on behalf of %s', array($ownerDisplayName, $filename, $initiatorDisplayName));
260
-		}
261
-
262
-		$message = $this->mailer->createMessage();
263
-		$htmlBody = $this->createMailBody('mail', $filename, $link, $ownerDisplayName, $initiatorDisplayName);
264
-		$textBody = $this->createMailBody('altmail', $filename, $link, $ownerDisplayName, $initiatorDisplayName);
265
-		$message->setTo([$shareWith]);
266
-		$message->setSubject($subject);
267
-		$message->setBody($textBody, 'text/plain');
268
-		$message->setHtmlBody($htmlBody);
269
-		$this->mailer->send($message);
270
-
271
-	}
272
-
273
-	/**
274
-	 * create mail body
275
-	 *
276
-	 * @param $filename
277
-	 * @param $link
278
-	 * @param $owner
279
-	 * @param $initiator
280
-	 * @return string plain text mail
281
-	 * @throws HintException
282
-	 */
283
-	protected function createMailBody($template, $filename, $link, $owner, $initiator) {
284
-
285
-		$mailBodyTemplate = new Template('sharebymail', $template, '');
286
-		$mailBodyTemplate->assign ('filename', \OCP\Util::sanitizeHTML($filename));
287
-		$mailBodyTemplate->assign ('link', $link);
288
-		$mailBodyTemplate->assign ('owner', \OCP\Util::sanitizeHTML($owner));
289
-		$mailBodyTemplate->assign ('initiator', \OCP\Util::sanitizeHTML($initiator));
290
-		$mailBodyTemplate->assign ('onBehalfOf', $initiator !== $owner);
291
-		$mailBody = $mailBodyTemplate->fetchPage();
292
-
293
-		if (is_string($mailBody)) {
294
-			return $mailBody;
295
-		}
296
-
297
-		throw new HintException('Failed to create the E-mail',
298
-			$this->l->t('Failed to create the E-mail'));
299
-	}
300
-
301
-	/**
302
-	 * send password to recipient of a mail share
303
-	 *
304
-	 * @param string $filename
305
-	 * @param string $initiator
306
-	 * @param string $shareWith
307
-	 */
308
-	protected function sendPassword($filename, $initiator, $shareWith, $password) {
309
-
310
-		if ($this->settingsManager->sendPasswordByMail() === false) {
311
-			return;
312
-		}
313
-
314
-		$initiatorUser = $this->userManager->get($initiator);
315
-		$initiatorDisplayName = ($initiatorUser instanceof IUser) ? $initiatorUser->getDisplayName() : $initiator;
316
-		$subject = (string)$this->l->t('Password to access »%s« shared to you by %s', [$filename, $initiatorDisplayName]);
317
-
318
-		$message = $this->mailer->createMessage();
319
-		$htmlBody = $this->createMailBodyToSendPassword('mailpassword', $filename, $initiatorDisplayName, $password);
320
-		$textBody = $this->createMailBodyToSendPassword('altmailpassword', $filename,$initiatorDisplayName, $password);
321
-		$message->setTo([$shareWith]);
322
-		$message->setSubject($subject);
323
-		$message->setBody($textBody, 'text/plain');
324
-		$message->setHtmlBody($htmlBody);
325
-		$this->mailer->send($message);
326
-
327
-	}
328
-
329
-	/**
330
-	 * create mail body to send password to recipient
331
-	 *
332
-	 * @param string $filename
333
-	 * @param string $initiator
334
-	 * @param string $password
335
-	 * @return string plain text mail
336
-	 * @throws HintException
337
-	 */
338
-	protected function createMailBodyToSendPassword($template, $filename, $initiator, $password) {
339
-
340
-		$mailBodyTemplate = new Template('sharebymail', $template, '');
341
-		$mailBodyTemplate->assign ('filename', \OCP\Util::sanitizeHTML($filename));
342
-		$mailBodyTemplate->assign ('password', \OCP\Util::sanitizeHTML($password));
343
-		$mailBodyTemplate->assign ('initiator', \OCP\Util::sanitizeHTML($initiator));
344
-		$mailBody = $mailBodyTemplate->fetchPage();
345
-
346
-		if (is_string($mailBody)) {
347
-			return $mailBody;
348
-		}
349
-
350
-		throw new HintException('Failed to create the E-mail',
351
-			$this->l->t('Failed to create the E-mail'));
352
-	}
353
-
354
-
355
-	/**
356
-	 * generate share token
357
-	 *
358
-	 * @return string
359
-	 */
360
-	protected function generateToken() {
361
-		$token = $this->secureRandom->generate(
362
-			15, ISecureRandom::CHAR_LOWER . ISecureRandom::CHAR_UPPER . ISecureRandom::CHAR_DIGITS);
363
-		return $token;
364
-	}
365
-
366
-	/**
367
-	 * Get all children of this share
368
-	 *
369
-	 * @param IShare $parent
370
-	 * @return IShare[]
371
-	 */
372
-	public function getChildren(IShare $parent) {
373
-		$children = [];
374
-
375
-		$qb = $this->dbConnection->getQueryBuilder();
376
-		$qb->select('*')
377
-			->from('share')
378
-			->where($qb->expr()->eq('parent', $qb->createNamedParameter($parent->getId())))
379
-			->andWhere($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_EMAIL)))
380
-			->orderBy('id');
381
-
382
-		$cursor = $qb->execute();
383
-		while($data = $cursor->fetch()) {
384
-			$children[] = $this->createShareObject($data);
385
-		}
386
-		$cursor->closeCursor();
387
-
388
-		return $children;
389
-	}
390
-
391
-	/**
392
-	 * add share to the database and return the ID
393
-	 *
394
-	 * @param int $itemSource
395
-	 * @param string $itemType
396
-	 * @param string $shareWith
397
-	 * @param string $sharedBy
398
-	 * @param string $uidOwner
399
-	 * @param int $permissions
400
-	 * @param string $token
401
-	 * @return int
402
-	 */
403
-	protected function addShareToDB($itemSource, $itemType, $shareWith, $sharedBy, $uidOwner, $permissions, $token) {
404
-		$qb = $this->dbConnection->getQueryBuilder();
405
-		$qb->insert('share')
406
-			->setValue('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_EMAIL))
407
-			->setValue('item_type', $qb->createNamedParameter($itemType))
408
-			->setValue('item_source', $qb->createNamedParameter($itemSource))
409
-			->setValue('file_source', $qb->createNamedParameter($itemSource))
410
-			->setValue('share_with', $qb->createNamedParameter($shareWith))
411
-			->setValue('uid_owner', $qb->createNamedParameter($uidOwner))
412
-			->setValue('uid_initiator', $qb->createNamedParameter($sharedBy))
413
-			->setValue('permissions', $qb->createNamedParameter($permissions))
414
-			->setValue('token', $qb->createNamedParameter($token))
415
-			->setValue('stime', $qb->createNamedParameter(time()));
416
-
417
-		/*
144
+        $alreadyShared = $this->getSharedWith($shareWith, \OCP\Share::SHARE_TYPE_EMAIL, $share->getNode(), 1, 0);
145
+        if (!empty($alreadyShared)) {
146
+            $message = 'Sharing %s failed, this item is already shared with %s';
147
+            $message_t = $this->l->t('Sharing %s failed, this item is already shared with %s', array($share->getNode()->getName(), $shareWith));
148
+            $this->logger->debug(sprintf($message, $share->getNode()->getName(), $shareWith), ['app' => 'Federated File Sharing']);
149
+            throw new \Exception($message_t);
150
+        }
151
+
152
+        $shareId = $this->createMailShare($share);
153
+        $this->createActivity($share);
154
+        $data = $this->getRawShare($shareId);
155
+        return $this->createShareObject($data);
156
+
157
+    }
158
+
159
+    /**
160
+     * create activity if a file/folder was shared by mail
161
+     *
162
+     * @param IShare $share
163
+     */
164
+    protected function createActivity(IShare $share) {
165
+
166
+        $userFolder = $this->rootFolder->getUserFolder($share->getSharedBy());
167
+
168
+        $this->publishActivity(
169
+            Activity::SUBJECT_SHARED_EMAIL_SELF,
170
+            [$userFolder->getRelativePath($share->getNode()->getPath()), $share->getSharedWith()],
171
+            $share->getSharedBy(),
172
+            $share->getNode()->getId(),
173
+            $userFolder->getRelativePath($share->getNode()->getPath())
174
+        );
175
+
176
+        if ($share->getShareOwner() !== $share->getSharedBy()) {
177
+            $ownerFolder = $this->rootFolder->getUserFolder($share->getShareOwner());
178
+            $fileId = $share->getNode()->getId();
179
+            $nodes = $ownerFolder->getById($fileId);
180
+            $ownerPath = $nodes[0]->getPath();
181
+            $this->publishActivity(
182
+                Activity::SUBJECT_SHARED_EMAIL_BY,
183
+                [$ownerFolder->getRelativePath($ownerPath), $share->getSharedWith(), $share->getSharedBy()],
184
+                $share->getShareOwner(),
185
+                $fileId,
186
+                $ownerFolder->getRelativePath($ownerPath)
187
+            );
188
+        }
189
+
190
+    }
191
+
192
+    /**
193
+     * publish activity if a file/folder was shared by mail
194
+     *
195
+     * @param $subject
196
+     * @param $parameters
197
+     * @param $affectedUser
198
+     * @param $fileId
199
+     * @param $filePath
200
+     */
201
+    protected function publishActivity($subject, $parameters, $affectedUser, $fileId, $filePath) {
202
+        $event = $this->activityManager->generateEvent();
203
+        $event->setApp('sharebymail')
204
+            ->setType('shared')
205
+            ->setSubject($subject, $parameters)
206
+            ->setAffectedUser($affectedUser)
207
+            ->setObject('files', $fileId, $filePath);
208
+        $this->activityManager->publish($event);
209
+
210
+    }
211
+
212
+    /**
213
+     * @param IShare $share
214
+     * @return int
215
+     * @throws \Exception
216
+     */
217
+    protected function createMailShare(IShare $share) {
218
+        $share->setToken($this->generateToken());
219
+        $shareId = $this->addShareToDB(
220
+            $share->getNodeId(),
221
+            $share->getNodeType(),
222
+            $share->getSharedWith(),
223
+            $share->getSharedBy(),
224
+            $share->getShareOwner(),
225
+            $share->getPermissions(),
226
+            $share->getToken()
227
+        );
228
+
229
+        try {
230
+            $link = $this->urlGenerator->linkToRouteAbsolute('files_sharing.sharecontroller.showShare',
231
+                ['token' => $share->getToken()]);
232
+            $this->sendMailNotification($share->getNode()->getName(),
233
+                $link,
234
+                $share->getShareOwner(),
235
+                $share->getSharedBy(), $share->getSharedWith());
236
+        } catch (HintException $hintException) {
237
+            $this->logger->error('Failed to send share by mail: ' . $hintException->getMessage());
238
+            $this->removeShareFromTable($shareId);
239
+            throw $hintException;
240
+        } catch (\Exception $e) {
241
+            $this->logger->error('Failed to send share by mail: ' . $e->getMessage());
242
+            $this->removeShareFromTable($shareId);
243
+            throw new HintException('Failed to send share by mail',
244
+                $this->l->t('Failed to send share by E-mail'));
245
+        }
246
+
247
+        return $shareId;
248
+
249
+    }
250
+
251
+    protected function sendMailNotification($filename, $link, $owner, $initiator, $shareWith) {
252
+        $ownerUser = $this->userManager->get($owner);
253
+        $initiatorUser = $this->userManager->get($initiator);
254
+        $ownerDisplayName = ($ownerUser instanceof IUser) ? $ownerUser->getDisplayName() : $owner;
255
+        $initiatorDisplayName = ($initiatorUser instanceof IUser) ? $initiatorUser->getDisplayName() : $initiator;
256
+        if ($owner === $initiator) {
257
+            $subject = (string)$this->l->t('%s shared »%s« with you', array($ownerDisplayName, $filename));
258
+        } else {
259
+            $subject = (string)$this->l->t('%s shared »%s« with you on behalf of %s', array($ownerDisplayName, $filename, $initiatorDisplayName));
260
+        }
261
+
262
+        $message = $this->mailer->createMessage();
263
+        $htmlBody = $this->createMailBody('mail', $filename, $link, $ownerDisplayName, $initiatorDisplayName);
264
+        $textBody = $this->createMailBody('altmail', $filename, $link, $ownerDisplayName, $initiatorDisplayName);
265
+        $message->setTo([$shareWith]);
266
+        $message->setSubject($subject);
267
+        $message->setBody($textBody, 'text/plain');
268
+        $message->setHtmlBody($htmlBody);
269
+        $this->mailer->send($message);
270
+
271
+    }
272
+
273
+    /**
274
+     * create mail body
275
+     *
276
+     * @param $filename
277
+     * @param $link
278
+     * @param $owner
279
+     * @param $initiator
280
+     * @return string plain text mail
281
+     * @throws HintException
282
+     */
283
+    protected function createMailBody($template, $filename, $link, $owner, $initiator) {
284
+
285
+        $mailBodyTemplate = new Template('sharebymail', $template, '');
286
+        $mailBodyTemplate->assign ('filename', \OCP\Util::sanitizeHTML($filename));
287
+        $mailBodyTemplate->assign ('link', $link);
288
+        $mailBodyTemplate->assign ('owner', \OCP\Util::sanitizeHTML($owner));
289
+        $mailBodyTemplate->assign ('initiator', \OCP\Util::sanitizeHTML($initiator));
290
+        $mailBodyTemplate->assign ('onBehalfOf', $initiator !== $owner);
291
+        $mailBody = $mailBodyTemplate->fetchPage();
292
+
293
+        if (is_string($mailBody)) {
294
+            return $mailBody;
295
+        }
296
+
297
+        throw new HintException('Failed to create the E-mail',
298
+            $this->l->t('Failed to create the E-mail'));
299
+    }
300
+
301
+    /**
302
+     * send password to recipient of a mail share
303
+     *
304
+     * @param string $filename
305
+     * @param string $initiator
306
+     * @param string $shareWith
307
+     */
308
+    protected function sendPassword($filename, $initiator, $shareWith, $password) {
309
+
310
+        if ($this->settingsManager->sendPasswordByMail() === false) {
311
+            return;
312
+        }
313
+
314
+        $initiatorUser = $this->userManager->get($initiator);
315
+        $initiatorDisplayName = ($initiatorUser instanceof IUser) ? $initiatorUser->getDisplayName() : $initiator;
316
+        $subject = (string)$this->l->t('Password to access »%s« shared to you by %s', [$filename, $initiatorDisplayName]);
317
+
318
+        $message = $this->mailer->createMessage();
319
+        $htmlBody = $this->createMailBodyToSendPassword('mailpassword', $filename, $initiatorDisplayName, $password);
320
+        $textBody = $this->createMailBodyToSendPassword('altmailpassword', $filename,$initiatorDisplayName, $password);
321
+        $message->setTo([$shareWith]);
322
+        $message->setSubject($subject);
323
+        $message->setBody($textBody, 'text/plain');
324
+        $message->setHtmlBody($htmlBody);
325
+        $this->mailer->send($message);
326
+
327
+    }
328
+
329
+    /**
330
+     * create mail body to send password to recipient
331
+     *
332
+     * @param string $filename
333
+     * @param string $initiator
334
+     * @param string $password
335
+     * @return string plain text mail
336
+     * @throws HintException
337
+     */
338
+    protected function createMailBodyToSendPassword($template, $filename, $initiator, $password) {
339
+
340
+        $mailBodyTemplate = new Template('sharebymail', $template, '');
341
+        $mailBodyTemplate->assign ('filename', \OCP\Util::sanitizeHTML($filename));
342
+        $mailBodyTemplate->assign ('password', \OCP\Util::sanitizeHTML($password));
343
+        $mailBodyTemplate->assign ('initiator', \OCP\Util::sanitizeHTML($initiator));
344
+        $mailBody = $mailBodyTemplate->fetchPage();
345
+
346
+        if (is_string($mailBody)) {
347
+            return $mailBody;
348
+        }
349
+
350
+        throw new HintException('Failed to create the E-mail',
351
+            $this->l->t('Failed to create the E-mail'));
352
+    }
353
+
354
+
355
+    /**
356
+     * generate share token
357
+     *
358
+     * @return string
359
+     */
360
+    protected function generateToken() {
361
+        $token = $this->secureRandom->generate(
362
+            15, ISecureRandom::CHAR_LOWER . ISecureRandom::CHAR_UPPER . ISecureRandom::CHAR_DIGITS);
363
+        return $token;
364
+    }
365
+
366
+    /**
367
+     * Get all children of this share
368
+     *
369
+     * @param IShare $parent
370
+     * @return IShare[]
371
+     */
372
+    public function getChildren(IShare $parent) {
373
+        $children = [];
374
+
375
+        $qb = $this->dbConnection->getQueryBuilder();
376
+        $qb->select('*')
377
+            ->from('share')
378
+            ->where($qb->expr()->eq('parent', $qb->createNamedParameter($parent->getId())))
379
+            ->andWhere($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_EMAIL)))
380
+            ->orderBy('id');
381
+
382
+        $cursor = $qb->execute();
383
+        while($data = $cursor->fetch()) {
384
+            $children[] = $this->createShareObject($data);
385
+        }
386
+        $cursor->closeCursor();
387
+
388
+        return $children;
389
+    }
390
+
391
+    /**
392
+     * add share to the database and return the ID
393
+     *
394
+     * @param int $itemSource
395
+     * @param string $itemType
396
+     * @param string $shareWith
397
+     * @param string $sharedBy
398
+     * @param string $uidOwner
399
+     * @param int $permissions
400
+     * @param string $token
401
+     * @return int
402
+     */
403
+    protected function addShareToDB($itemSource, $itemType, $shareWith, $sharedBy, $uidOwner, $permissions, $token) {
404
+        $qb = $this->dbConnection->getQueryBuilder();
405
+        $qb->insert('share')
406
+            ->setValue('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_EMAIL))
407
+            ->setValue('item_type', $qb->createNamedParameter($itemType))
408
+            ->setValue('item_source', $qb->createNamedParameter($itemSource))
409
+            ->setValue('file_source', $qb->createNamedParameter($itemSource))
410
+            ->setValue('share_with', $qb->createNamedParameter($shareWith))
411
+            ->setValue('uid_owner', $qb->createNamedParameter($uidOwner))
412
+            ->setValue('uid_initiator', $qb->createNamedParameter($sharedBy))
413
+            ->setValue('permissions', $qb->createNamedParameter($permissions))
414
+            ->setValue('token', $qb->createNamedParameter($token))
415
+            ->setValue('stime', $qb->createNamedParameter(time()));
416
+
417
+        /*
418 418
 		 * Added to fix https://github.com/owncloud/core/issues/22215
419 419
 		 * Can be removed once we get rid of ajax/share.php
420 420
 		 */
421
-		$qb->setValue('file_target', $qb->createNamedParameter(''));
421
+        $qb->setValue('file_target', $qb->createNamedParameter(''));
422 422
 
423
-		$qb->execute();
424
-		$id = $qb->getLastInsertId();
423
+        $qb->execute();
424
+        $id = $qb->getLastInsertId();
425 425
 
426
-		return (int)$id;
427
-	}
426
+        return (int)$id;
427
+    }
428 428
 
429
-	/**
430
-	 * Update a share
431
-	 *
432
-	 * @param IShare $share
433
-	 * @param string|null $plainTextPassword
434
-	 * @return IShare The share object
435
-	 */
436
-	public function update(IShare $share, $plainTextPassword = null) {
429
+    /**
430
+     * Update a share
431
+     *
432
+     * @param IShare $share
433
+     * @param string|null $plainTextPassword
434
+     * @return IShare The share object
435
+     */
436
+    public function update(IShare $share, $plainTextPassword = null) {
437 437
 
438
-		$originalShare = $this->getShareById($share->getId());
438
+        $originalShare = $this->getShareById($share->getId());
439 439
 
440
-		// a real password was given
441
-		$validPassword = $plainTextPassword !== null && $plainTextPassword !== '';
440
+        // a real password was given
441
+        $validPassword = $plainTextPassword !== null && $plainTextPassword !== '';
442 442
 
443
-		if($validPassword && $originalShare->getPassword() !== $share->getPassword()) {
444
-			$this->sendPassword($share->getNode()->getName(), $share->getSharedBy(), $share->getSharedWith(), $plainTextPassword);
445
-		}
446
-		/*
443
+        if($validPassword && $originalShare->getPassword() !== $share->getPassword()) {
444
+            $this->sendPassword($share->getNode()->getName(), $share->getSharedBy(), $share->getSharedWith(), $plainTextPassword);
445
+        }
446
+        /*
447 447
 		 * We allow updating the permissions and password of mail shares
448 448
 		 */
449
-		$qb = $this->dbConnection->getQueryBuilder();
450
-		$qb->update('share')
451
-			->where($qb->expr()->eq('id', $qb->createNamedParameter($share->getId())))
452
-			->set('permissions', $qb->createNamedParameter($share->getPermissions()))
453
-			->set('uid_owner', $qb->createNamedParameter($share->getShareOwner()))
454
-			->set('uid_initiator', $qb->createNamedParameter($share->getSharedBy()))
455
-			->set('password', $qb->createNamedParameter($share->getPassword()))
456
-			->set('expiration', $qb->createNamedParameter($share->getExpirationDate(), IQueryBuilder::PARAM_DATE))
457
-			->execute();
458
-
459
-		return $share;
460
-	}
461
-
462
-	/**
463
-	 * @inheritdoc
464
-	 */
465
-	public function move(IShare $share, $recipient) {
466
-		/**
467
-		 * nothing to do here, mail shares are only outgoing shares
468
-		 */
469
-		return $share;
470
-	}
471
-
472
-	/**
473
-	 * Delete a share (owner unShares the file)
474
-	 *
475
-	 * @param IShare $share
476
-	 */
477
-	public function delete(IShare $share) {
478
-		$this->removeShareFromTable($share->getId());
479
-	}
480
-
481
-	/**
482
-	 * @inheritdoc
483
-	 */
484
-	public function deleteFromSelf(IShare $share, $recipient) {
485
-		// nothing to do here, mail shares are only outgoing shares
486
-		return;
487
-	}
488
-
489
-	/**
490
-	 * @inheritdoc
491
-	 */
492
-	public function getSharesBy($userId, $shareType, $node, $reshares, $limit, $offset) {
493
-		$qb = $this->dbConnection->getQueryBuilder();
494
-		$qb->select('*')
495
-			->from('share');
496
-
497
-		$qb->andWhere($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_EMAIL)));
498
-
499
-		/**
500
-		 * Reshares for this user are shares where they are the owner.
501
-		 */
502
-		if ($reshares === false) {
503
-			//Special case for old shares created via the web UI
504
-			$or1 = $qb->expr()->andX(
505
-				$qb->expr()->eq('uid_owner', $qb->createNamedParameter($userId)),
506
-				$qb->expr()->isNull('uid_initiator')
507
-			);
508
-
509
-			$qb->andWhere(
510
-				$qb->expr()->orX(
511
-					$qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId)),
512
-					$or1
513
-				)
514
-			);
515
-		} else {
516
-			$qb->andWhere(
517
-				$qb->expr()->orX(
518
-					$qb->expr()->eq('uid_owner', $qb->createNamedParameter($userId)),
519
-					$qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId))
520
-				)
521
-			);
522
-		}
523
-
524
-		if ($node !== null) {
525
-			$qb->andWhere($qb->expr()->eq('file_source', $qb->createNamedParameter($node->getId())));
526
-		}
527
-
528
-		if ($limit !== -1) {
529
-			$qb->setMaxResults($limit);
530
-		}
531
-
532
-		$qb->setFirstResult($offset);
533
-		$qb->orderBy('id');
534
-
535
-		$cursor = $qb->execute();
536
-		$shares = [];
537
-		while($data = $cursor->fetch()) {
538
-			$shares[] = $this->createShareObject($data);
539
-		}
540
-		$cursor->closeCursor();
541
-
542
-		return $shares;
543
-	}
544
-
545
-	/**
546
-	 * @inheritdoc
547
-	 */
548
-	public function getShareById($id, $recipientId = null) {
549
-		$qb = $this->dbConnection->getQueryBuilder();
550
-
551
-		$qb->select('*')
552
-			->from('share')
553
-			->where($qb->expr()->eq('id', $qb->createNamedParameter($id)))
554
-			->andWhere($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_EMAIL)));
555
-
556
-		$cursor = $qb->execute();
557
-		$data = $cursor->fetch();
558
-		$cursor->closeCursor();
559
-
560
-		if ($data === false) {
561
-			throw new ShareNotFound();
562
-		}
563
-
564
-		try {
565
-			$share = $this->createShareObject($data);
566
-		} catch (InvalidShare $e) {
567
-			throw new ShareNotFound();
568
-		}
569
-
570
-		return $share;
571
-	}
572
-
573
-	/**
574
-	 * Get shares for a given path
575
-	 *
576
-	 * @param \OCP\Files\Node $path
577
-	 * @return IShare[]
578
-	 */
579
-	public function getSharesByPath(Node $path) {
580
-		$qb = $this->dbConnection->getQueryBuilder();
581
-
582
-		$cursor = $qb->select('*')
583
-			->from('share')
584
-			->andWhere($qb->expr()->eq('file_source', $qb->createNamedParameter($path->getId())))
585
-			->andWhere($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_EMAIL)))
586
-			->execute();
587
-
588
-		$shares = [];
589
-		while($data = $cursor->fetch()) {
590
-			$shares[] = $this->createShareObject($data);
591
-		}
592
-		$cursor->closeCursor();
593
-
594
-		return $shares;
595
-	}
596
-
597
-	/**
598
-	 * @inheritdoc
599
-	 */
600
-	public function getSharedWith($userId, $shareType, $node, $limit, $offset) {
601
-		/** @var IShare[] $shares */
602
-		$shares = [];
603
-
604
-		//Get shares directly with this user
605
-		$qb = $this->dbConnection->getQueryBuilder();
606
-		$qb->select('*')
607
-			->from('share');
608
-
609
-		// Order by id
610
-		$qb->orderBy('id');
611
-
612
-		// Set limit and offset
613
-		if ($limit !== -1) {
614
-			$qb->setMaxResults($limit);
615
-		}
616
-		$qb->setFirstResult($offset);
617
-
618
-		$qb->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_EMAIL)));
619
-		$qb->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($userId)));
620
-
621
-		// Filter by node if provided
622
-		if ($node !== null) {
623
-			$qb->andWhere($qb->expr()->eq('file_source', $qb->createNamedParameter($node->getId())));
624
-		}
625
-
626
-		$cursor = $qb->execute();
627
-
628
-		while($data = $cursor->fetch()) {
629
-			$shares[] = $this->createShareObject($data);
630
-		}
631
-		$cursor->closeCursor();
632
-
633
-
634
-		return $shares;
635
-	}
636
-
637
-	/**
638
-	 * Get a share by token
639
-	 *
640
-	 * @param string $token
641
-	 * @return IShare
642
-	 * @throws ShareNotFound
643
-	 */
644
-	public function getShareByToken($token) {
645
-		$qb = $this->dbConnection->getQueryBuilder();
646
-
647
-		$cursor = $qb->select('*')
648
-			->from('share')
649
-			->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_EMAIL)))
650
-			->andWhere($qb->expr()->eq('token', $qb->createNamedParameter($token)))
651
-			->execute();
652
-
653
-		$data = $cursor->fetch();
654
-
655
-		if ($data === false) {
656
-			throw new ShareNotFound('Share not found', $this->l->t('Could not find share'));
657
-		}
658
-
659
-		try {
660
-			$share = $this->createShareObject($data);
661
-		} catch (InvalidShare $e) {
662
-			throw new ShareNotFound('Share not found', $this->l->t('Could not find share'));
663
-		}
664
-
665
-		return $share;
666
-	}
667
-
668
-	/**
669
-	 * remove share from table
670
-	 *
671
-	 * @param string $shareId
672
-	 */
673
-	protected function removeShareFromTable($shareId) {
674
-		$qb = $this->dbConnection->getQueryBuilder();
675
-		$qb->delete('share')
676
-			->where($qb->expr()->eq('id', $qb->createNamedParameter($shareId)));
677
-		$qb->execute();
678
-	}
679
-
680
-	/**
681
-	 * Create a share object from an database row
682
-	 *
683
-	 * @param array $data
684
-	 * @return IShare
685
-	 * @throws InvalidShare
686
-	 * @throws ShareNotFound
687
-	 */
688
-	protected function createShareObject($data) {
689
-
690
-		$share = new Share($this->rootFolder, $this->userManager);
691
-		$share->setId((int)$data['id'])
692
-			->setShareType((int)$data['share_type'])
693
-			->setPermissions((int)$data['permissions'])
694
-			->setTarget($data['file_target'])
695
-			->setMailSend((bool)$data['mail_send'])
696
-			->setToken($data['token']);
697
-
698
-		$shareTime = new \DateTime();
699
-		$shareTime->setTimestamp((int)$data['stime']);
700
-		$share->setShareTime($shareTime);
701
-		$share->setSharedWith($data['share_with']);
702
-		$share->setPassword($data['password']);
703
-
704
-		if ($data['uid_initiator'] !== null) {
705
-			$share->setShareOwner($data['uid_owner']);
706
-			$share->setSharedBy($data['uid_initiator']);
707
-		} else {
708
-			//OLD SHARE
709
-			$share->setSharedBy($data['uid_owner']);
710
-			$path = $this->getNode($share->getSharedBy(), (int)$data['file_source']);
711
-
712
-			$owner = $path->getOwner();
713
-			$share->setShareOwner($owner->getUID());
714
-		}
715
-
716
-		if ($data['expiration'] !== null) {
717
-			$expiration = \DateTime::createFromFormat('Y-m-d H:i:s', $data['expiration']);
718
-			if ($expiration !== false) {
719
-				$share->setExpirationDate($expiration);
720
-			}
721
-		}
722
-
723
-		$share->setNodeId((int)$data['file_source']);
724
-		$share->setNodeType($data['item_type']);
725
-
726
-		$share->setProviderId($this->identifier());
727
-
728
-		return $share;
729
-	}
730
-
731
-	/**
732
-	 * Get the node with file $id for $user
733
-	 *
734
-	 * @param string $userId
735
-	 * @param int $id
736
-	 * @return \OCP\Files\File|\OCP\Files\Folder
737
-	 * @throws InvalidShare
738
-	 */
739
-	private function getNode($userId, $id) {
740
-		try {
741
-			$userFolder = $this->rootFolder->getUserFolder($userId);
742
-		} catch (NotFoundException $e) {
743
-			throw new InvalidShare();
744
-		}
745
-
746
-		$nodes = $userFolder->getById($id);
747
-
748
-		if (empty($nodes)) {
749
-			throw new InvalidShare();
750
-		}
751
-
752
-		return $nodes[0];
753
-	}
754
-
755
-	/**
756
-	 * A user is deleted from the system
757
-	 * So clean up the relevant shares.
758
-	 *
759
-	 * @param string $uid
760
-	 * @param int $shareType
761
-	 */
762
-	public function userDeleted($uid, $shareType) {
763
-		$qb = $this->dbConnection->getQueryBuilder();
764
-
765
-		$qb->delete('share')
766
-			->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_EMAIL)))
767
-			->andWhere($qb->expr()->eq('uid_owner', $qb->createNamedParameter($uid)))
768
-			->execute();
769
-	}
770
-
771
-	/**
772
-	 * This provider does not support group shares
773
-	 *
774
-	 * @param string $gid
775
-	 */
776
-	public function groupDeleted($gid) {
777
-		return;
778
-	}
779
-
780
-	/**
781
-	 * This provider does not support group shares
782
-	 *
783
-	 * @param string $uid
784
-	 * @param string $gid
785
-	 */
786
-	public function userDeletedFromGroup($uid, $gid) {
787
-		return;
788
-	}
789
-
790
-	/**
791
-	 * get database row of a give share
792
-	 *
793
-	 * @param $id
794
-	 * @return array
795
-	 * @throws ShareNotFound
796
-	 */
797
-	protected function getRawShare($id) {
798
-
799
-		// Now fetch the inserted share and create a complete share object
800
-		$qb = $this->dbConnection->getQueryBuilder();
801
-		$qb->select('*')
802
-			->from('share')
803
-			->where($qb->expr()->eq('id', $qb->createNamedParameter($id)));
804
-
805
-		$cursor = $qb->execute();
806
-		$data = $cursor->fetch();
807
-		$cursor->closeCursor();
808
-
809
-		if ($data === false) {
810
-			throw new ShareNotFound;
811
-		}
812
-
813
-		return $data;
814
-	}
815
-
816
-	public function getSharesInFolder($userId, Folder $node, $reshares) {
817
-		$qb = $this->dbConnection->getQueryBuilder();
818
-		$qb->select('*')
819
-			->from('share', 's')
820
-			->andWhere($qb->expr()->orX(
821
-				$qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
822
-				$qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
823
-			))
824
-			->andWhere(
825
-				$qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_EMAIL))
826
-			);
827
-
828
-		/**
829
-		 * Reshares for this user are shares where they are the owner.
830
-		 */
831
-		if ($reshares === false) {
832
-			$qb->andWhere($qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId)));
833
-		} else {
834
-			$qb->andWhere(
835
-				$qb->expr()->orX(
836
-					$qb->expr()->eq('uid_owner', $qb->createNamedParameter($userId)),
837
-					$qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId))
838
-				)
839
-			);
840
-		}
841
-
842
-		$qb->innerJoin('s', 'filecache' ,'f', $qb->expr()->eq('s.file_source', 'f.fileid'));
843
-		$qb->andWhere($qb->expr()->eq('f.parent', $qb->createNamedParameter($node->getId())));
844
-
845
-		$qb->orderBy('id');
846
-
847
-		$cursor = $qb->execute();
848
-		$shares = [];
849
-		while ($data = $cursor->fetch()) {
850
-			$shares[$data['fileid']][] = $this->createShareObject($data);
851
-		}
852
-		$cursor->closeCursor();
853
-
854
-		return $shares;
855
-	}
856
-
857
-	/**
858
-	 * @inheritdoc
859
-	 */
860
-	public function getAccessList($nodes, $currentAccess) {
861
-		$ids = [];
862
-		foreach ($nodes as $node) {
863
-			$ids[] = $node->getId();
864
-		}
865
-
866
-		$qb = $this->dbConnection->getQueryBuilder();
867
-		$qb->select('share_with')
868
-			->from('share')
869
-			->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_EMAIL)))
870
-			->andWhere($qb->expr()->in('file_source', $qb->createNamedParameter($ids, IQueryBuilder::PARAM_INT_ARRAY)))
871
-			->andWhere($qb->expr()->orX(
872
-				$qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
873
-				$qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
874
-			))
875
-			->setMaxResults(1);
876
-		$cursor = $qb->execute();
877
-
878
-		$mail = $cursor->fetch() !== false;
879
-		$cursor->closeCursor();
880
-
881
-		return ['mail' => $mail];
882
-	}
449
+        $qb = $this->dbConnection->getQueryBuilder();
450
+        $qb->update('share')
451
+            ->where($qb->expr()->eq('id', $qb->createNamedParameter($share->getId())))
452
+            ->set('permissions', $qb->createNamedParameter($share->getPermissions()))
453
+            ->set('uid_owner', $qb->createNamedParameter($share->getShareOwner()))
454
+            ->set('uid_initiator', $qb->createNamedParameter($share->getSharedBy()))
455
+            ->set('password', $qb->createNamedParameter($share->getPassword()))
456
+            ->set('expiration', $qb->createNamedParameter($share->getExpirationDate(), IQueryBuilder::PARAM_DATE))
457
+            ->execute();
458
+
459
+        return $share;
460
+    }
461
+
462
+    /**
463
+     * @inheritdoc
464
+     */
465
+    public function move(IShare $share, $recipient) {
466
+        /**
467
+         * nothing to do here, mail shares are only outgoing shares
468
+         */
469
+        return $share;
470
+    }
471
+
472
+    /**
473
+     * Delete a share (owner unShares the file)
474
+     *
475
+     * @param IShare $share
476
+     */
477
+    public function delete(IShare $share) {
478
+        $this->removeShareFromTable($share->getId());
479
+    }
480
+
481
+    /**
482
+     * @inheritdoc
483
+     */
484
+    public function deleteFromSelf(IShare $share, $recipient) {
485
+        // nothing to do here, mail shares are only outgoing shares
486
+        return;
487
+    }
488
+
489
+    /**
490
+     * @inheritdoc
491
+     */
492
+    public function getSharesBy($userId, $shareType, $node, $reshares, $limit, $offset) {
493
+        $qb = $this->dbConnection->getQueryBuilder();
494
+        $qb->select('*')
495
+            ->from('share');
496
+
497
+        $qb->andWhere($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_EMAIL)));
498
+
499
+        /**
500
+         * Reshares for this user are shares where they are the owner.
501
+         */
502
+        if ($reshares === false) {
503
+            //Special case for old shares created via the web UI
504
+            $or1 = $qb->expr()->andX(
505
+                $qb->expr()->eq('uid_owner', $qb->createNamedParameter($userId)),
506
+                $qb->expr()->isNull('uid_initiator')
507
+            );
508
+
509
+            $qb->andWhere(
510
+                $qb->expr()->orX(
511
+                    $qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId)),
512
+                    $or1
513
+                )
514
+            );
515
+        } else {
516
+            $qb->andWhere(
517
+                $qb->expr()->orX(
518
+                    $qb->expr()->eq('uid_owner', $qb->createNamedParameter($userId)),
519
+                    $qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId))
520
+                )
521
+            );
522
+        }
523
+
524
+        if ($node !== null) {
525
+            $qb->andWhere($qb->expr()->eq('file_source', $qb->createNamedParameter($node->getId())));
526
+        }
527
+
528
+        if ($limit !== -1) {
529
+            $qb->setMaxResults($limit);
530
+        }
531
+
532
+        $qb->setFirstResult($offset);
533
+        $qb->orderBy('id');
534
+
535
+        $cursor = $qb->execute();
536
+        $shares = [];
537
+        while($data = $cursor->fetch()) {
538
+            $shares[] = $this->createShareObject($data);
539
+        }
540
+        $cursor->closeCursor();
541
+
542
+        return $shares;
543
+    }
544
+
545
+    /**
546
+     * @inheritdoc
547
+     */
548
+    public function getShareById($id, $recipientId = null) {
549
+        $qb = $this->dbConnection->getQueryBuilder();
550
+
551
+        $qb->select('*')
552
+            ->from('share')
553
+            ->where($qb->expr()->eq('id', $qb->createNamedParameter($id)))
554
+            ->andWhere($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_EMAIL)));
555
+
556
+        $cursor = $qb->execute();
557
+        $data = $cursor->fetch();
558
+        $cursor->closeCursor();
559
+
560
+        if ($data === false) {
561
+            throw new ShareNotFound();
562
+        }
563
+
564
+        try {
565
+            $share = $this->createShareObject($data);
566
+        } catch (InvalidShare $e) {
567
+            throw new ShareNotFound();
568
+        }
569
+
570
+        return $share;
571
+    }
572
+
573
+    /**
574
+     * Get shares for a given path
575
+     *
576
+     * @param \OCP\Files\Node $path
577
+     * @return IShare[]
578
+     */
579
+    public function getSharesByPath(Node $path) {
580
+        $qb = $this->dbConnection->getQueryBuilder();
581
+
582
+        $cursor = $qb->select('*')
583
+            ->from('share')
584
+            ->andWhere($qb->expr()->eq('file_source', $qb->createNamedParameter($path->getId())))
585
+            ->andWhere($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_EMAIL)))
586
+            ->execute();
587
+
588
+        $shares = [];
589
+        while($data = $cursor->fetch()) {
590
+            $shares[] = $this->createShareObject($data);
591
+        }
592
+        $cursor->closeCursor();
593
+
594
+        return $shares;
595
+    }
596
+
597
+    /**
598
+     * @inheritdoc
599
+     */
600
+    public function getSharedWith($userId, $shareType, $node, $limit, $offset) {
601
+        /** @var IShare[] $shares */
602
+        $shares = [];
603
+
604
+        //Get shares directly with this user
605
+        $qb = $this->dbConnection->getQueryBuilder();
606
+        $qb->select('*')
607
+            ->from('share');
608
+
609
+        // Order by id
610
+        $qb->orderBy('id');
611
+
612
+        // Set limit and offset
613
+        if ($limit !== -1) {
614
+            $qb->setMaxResults($limit);
615
+        }
616
+        $qb->setFirstResult($offset);
617
+
618
+        $qb->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_EMAIL)));
619
+        $qb->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($userId)));
620
+
621
+        // Filter by node if provided
622
+        if ($node !== null) {
623
+            $qb->andWhere($qb->expr()->eq('file_source', $qb->createNamedParameter($node->getId())));
624
+        }
625
+
626
+        $cursor = $qb->execute();
627
+
628
+        while($data = $cursor->fetch()) {
629
+            $shares[] = $this->createShareObject($data);
630
+        }
631
+        $cursor->closeCursor();
632
+
633
+
634
+        return $shares;
635
+    }
636
+
637
+    /**
638
+     * Get a share by token
639
+     *
640
+     * @param string $token
641
+     * @return IShare
642
+     * @throws ShareNotFound
643
+     */
644
+    public function getShareByToken($token) {
645
+        $qb = $this->dbConnection->getQueryBuilder();
646
+
647
+        $cursor = $qb->select('*')
648
+            ->from('share')
649
+            ->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_EMAIL)))
650
+            ->andWhere($qb->expr()->eq('token', $qb->createNamedParameter($token)))
651
+            ->execute();
652
+
653
+        $data = $cursor->fetch();
654
+
655
+        if ($data === false) {
656
+            throw new ShareNotFound('Share not found', $this->l->t('Could not find share'));
657
+        }
658
+
659
+        try {
660
+            $share = $this->createShareObject($data);
661
+        } catch (InvalidShare $e) {
662
+            throw new ShareNotFound('Share not found', $this->l->t('Could not find share'));
663
+        }
664
+
665
+        return $share;
666
+    }
667
+
668
+    /**
669
+     * remove share from table
670
+     *
671
+     * @param string $shareId
672
+     */
673
+    protected function removeShareFromTable($shareId) {
674
+        $qb = $this->dbConnection->getQueryBuilder();
675
+        $qb->delete('share')
676
+            ->where($qb->expr()->eq('id', $qb->createNamedParameter($shareId)));
677
+        $qb->execute();
678
+    }
679
+
680
+    /**
681
+     * Create a share object from an database row
682
+     *
683
+     * @param array $data
684
+     * @return IShare
685
+     * @throws InvalidShare
686
+     * @throws ShareNotFound
687
+     */
688
+    protected function createShareObject($data) {
689
+
690
+        $share = new Share($this->rootFolder, $this->userManager);
691
+        $share->setId((int)$data['id'])
692
+            ->setShareType((int)$data['share_type'])
693
+            ->setPermissions((int)$data['permissions'])
694
+            ->setTarget($data['file_target'])
695
+            ->setMailSend((bool)$data['mail_send'])
696
+            ->setToken($data['token']);
697
+
698
+        $shareTime = new \DateTime();
699
+        $shareTime->setTimestamp((int)$data['stime']);
700
+        $share->setShareTime($shareTime);
701
+        $share->setSharedWith($data['share_with']);
702
+        $share->setPassword($data['password']);
703
+
704
+        if ($data['uid_initiator'] !== null) {
705
+            $share->setShareOwner($data['uid_owner']);
706
+            $share->setSharedBy($data['uid_initiator']);
707
+        } else {
708
+            //OLD SHARE
709
+            $share->setSharedBy($data['uid_owner']);
710
+            $path = $this->getNode($share->getSharedBy(), (int)$data['file_source']);
711
+
712
+            $owner = $path->getOwner();
713
+            $share->setShareOwner($owner->getUID());
714
+        }
715
+
716
+        if ($data['expiration'] !== null) {
717
+            $expiration = \DateTime::createFromFormat('Y-m-d H:i:s', $data['expiration']);
718
+            if ($expiration !== false) {
719
+                $share->setExpirationDate($expiration);
720
+            }
721
+        }
722
+
723
+        $share->setNodeId((int)$data['file_source']);
724
+        $share->setNodeType($data['item_type']);
725
+
726
+        $share->setProviderId($this->identifier());
727
+
728
+        return $share;
729
+    }
730
+
731
+    /**
732
+     * Get the node with file $id for $user
733
+     *
734
+     * @param string $userId
735
+     * @param int $id
736
+     * @return \OCP\Files\File|\OCP\Files\Folder
737
+     * @throws InvalidShare
738
+     */
739
+    private function getNode($userId, $id) {
740
+        try {
741
+            $userFolder = $this->rootFolder->getUserFolder($userId);
742
+        } catch (NotFoundException $e) {
743
+            throw new InvalidShare();
744
+        }
745
+
746
+        $nodes = $userFolder->getById($id);
747
+
748
+        if (empty($nodes)) {
749
+            throw new InvalidShare();
750
+        }
751
+
752
+        return $nodes[0];
753
+    }
754
+
755
+    /**
756
+     * A user is deleted from the system
757
+     * So clean up the relevant shares.
758
+     *
759
+     * @param string $uid
760
+     * @param int $shareType
761
+     */
762
+    public function userDeleted($uid, $shareType) {
763
+        $qb = $this->dbConnection->getQueryBuilder();
764
+
765
+        $qb->delete('share')
766
+            ->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_EMAIL)))
767
+            ->andWhere($qb->expr()->eq('uid_owner', $qb->createNamedParameter($uid)))
768
+            ->execute();
769
+    }
770
+
771
+    /**
772
+     * This provider does not support group shares
773
+     *
774
+     * @param string $gid
775
+     */
776
+    public function groupDeleted($gid) {
777
+        return;
778
+    }
779
+
780
+    /**
781
+     * This provider does not support group shares
782
+     *
783
+     * @param string $uid
784
+     * @param string $gid
785
+     */
786
+    public function userDeletedFromGroup($uid, $gid) {
787
+        return;
788
+    }
789
+
790
+    /**
791
+     * get database row of a give share
792
+     *
793
+     * @param $id
794
+     * @return array
795
+     * @throws ShareNotFound
796
+     */
797
+    protected function getRawShare($id) {
798
+
799
+        // Now fetch the inserted share and create a complete share object
800
+        $qb = $this->dbConnection->getQueryBuilder();
801
+        $qb->select('*')
802
+            ->from('share')
803
+            ->where($qb->expr()->eq('id', $qb->createNamedParameter($id)));
804
+
805
+        $cursor = $qb->execute();
806
+        $data = $cursor->fetch();
807
+        $cursor->closeCursor();
808
+
809
+        if ($data === false) {
810
+            throw new ShareNotFound;
811
+        }
812
+
813
+        return $data;
814
+    }
815
+
816
+    public function getSharesInFolder($userId, Folder $node, $reshares) {
817
+        $qb = $this->dbConnection->getQueryBuilder();
818
+        $qb->select('*')
819
+            ->from('share', 's')
820
+            ->andWhere($qb->expr()->orX(
821
+                $qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
822
+                $qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
823
+            ))
824
+            ->andWhere(
825
+                $qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_EMAIL))
826
+            );
827
+
828
+        /**
829
+         * Reshares for this user are shares where they are the owner.
830
+         */
831
+        if ($reshares === false) {
832
+            $qb->andWhere($qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId)));
833
+        } else {
834
+            $qb->andWhere(
835
+                $qb->expr()->orX(
836
+                    $qb->expr()->eq('uid_owner', $qb->createNamedParameter($userId)),
837
+                    $qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId))
838
+                )
839
+            );
840
+        }
841
+
842
+        $qb->innerJoin('s', 'filecache' ,'f', $qb->expr()->eq('s.file_source', 'f.fileid'));
843
+        $qb->andWhere($qb->expr()->eq('f.parent', $qb->createNamedParameter($node->getId())));
844
+
845
+        $qb->orderBy('id');
846
+
847
+        $cursor = $qb->execute();
848
+        $shares = [];
849
+        while ($data = $cursor->fetch()) {
850
+            $shares[$data['fileid']][] = $this->createShareObject($data);
851
+        }
852
+        $cursor->closeCursor();
853
+
854
+        return $shares;
855
+    }
856
+
857
+    /**
858
+     * @inheritdoc
859
+     */
860
+    public function getAccessList($nodes, $currentAccess) {
861
+        $ids = [];
862
+        foreach ($nodes as $node) {
863
+            $ids[] = $node->getId();
864
+        }
865
+
866
+        $qb = $this->dbConnection->getQueryBuilder();
867
+        $qb->select('share_with')
868
+            ->from('share')
869
+            ->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_EMAIL)))
870
+            ->andWhere($qb->expr()->in('file_source', $qb->createNamedParameter($ids, IQueryBuilder::PARAM_INT_ARRAY)))
871
+            ->andWhere($qb->expr()->orX(
872
+                $qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
873
+                $qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
874
+            ))
875
+            ->setMaxResults(1);
876
+        $cursor = $qb->execute();
877
+
878
+        $mail = $cursor->fetch() !== false;
879
+        $cursor->closeCursor();
880
+
881
+        return ['mail' => $mail];
882
+    }
883 883
 
884 884
 }
Please login to merge, or discard this patch.
lib/private/Encryption/File.php 1 patch
Indentation   +90 added lines, -90 removed lines patch added patch discarded remove patch
@@ -31,95 +31,95 @@
 block discarded – undo
31 31
 
32 32
 class File implements \OCP\Encryption\IFile {
33 33
 
34
-	/** @var Util */
35
-	protected $util;
36
-
37
-	/** @var IRootFolder */
38
-	private $rootFolder;
39
-
40
-	/** @var IManager */
41
-	private $shareManager;
42
-
43
-	/**
44
-	 * cache results of already checked folders
45
-	 *
46
-	 * @var array
47
-	 */
48
-	protected $cache;
49
-
50
-	public function __construct(Util $util,
51
-								IRootFolder $rootFolder,
52
-								IManager $shareManager) {
53
-		$this->util = $util;
54
-		$this->cache = new CappedMemoryCache();
55
-		$this->rootFolder = $rootFolder;
56
-		$this->shareManager = $shareManager;
57
-	}
58
-
59
-
60
-	/**
61
-	 * get list of users with access to the file
62
-	 *
63
-	 * @param string $path to the file
64
-	 * @return array  ['users' => $uniqueUserIds, 'public' => $public]
65
-	 */
66
-	public function getAccessList($path) {
67
-
68
-		// Make sure that a share key is generated for the owner too
69
-		list($owner, $ownerPath) = $this->util->getUidAndFilename($path);
70
-
71
-		// always add owner to the list of users with access to the file
72
-		$userIds = array($owner);
73
-
74
-		if (!$this->util->isFile($owner . '/' . $ownerPath)) {
75
-			return array('users' => $userIds, 'public' => false);
76
-		}
77
-
78
-		$ownerPath = substr($ownerPath, strlen('/files'));
79
-		$userFolder = $this->rootFolder->getUserFolder($owner);
80
-		try {
81
-			$file = $userFolder->get($ownerPath);
82
-		} catch (NotFoundException $e) {
83
-			$file = null;
84
-		}
85
-		$ownerPath = $this->util->stripPartialFileExtension($ownerPath);
86
-
87
-		// first get the shares for the parent and cache the result so that we don't
88
-		// need to check all parents for every file
89
-		$parent = dirname($ownerPath);
90
-		$parentNode = $userFolder->get($parent);
91
-		if (isset($this->cache[$parent])) {
92
-			$resultForParents = $this->cache[$parent];
93
-		} else {
94
-			$resultForParents = $this->shareManager->getAccessList($parentNode);
95
-			$this->cache[$parent] = $resultForParents;
96
-		}
97
-		$userIds = array_merge($userIds, $resultForParents['users']);
98
-		$public = $resultForParents['public'] || $resultForParents['remote'];
99
-
100
-
101
-		// Find out who, if anyone, is sharing the file
102
-		if ($file !== null) {
103
-			$resultForFile = $this->shareManager->getAccessList($file, false);
104
-			$userIds = array_merge($userIds, $resultForFile['users']);
105
-			$public = $resultForFile['public'] || $resultForFile['remote'] || $public;
106
-		}
107
-
108
-		// check if it is a group mount
109
-		if (\OCP\App::isEnabled("files_external")) {
110
-			$mounts = \OC_Mount_Config::getSystemMountPoints();
111
-			foreach ($mounts as $mount) {
112
-				if ($mount['mountpoint'] == substr($ownerPath, 1, strlen($mount['mountpoint']))) {
113
-					$mountedFor = $this->util->getUserWithAccessToMountPoint($mount['applicable']['users'], $mount['applicable']['groups']);
114
-					$userIds = array_merge($userIds, $mountedFor);
115
-				}
116
-			}
117
-		}
118
-
119
-		// Remove duplicate UIDs
120
-		$uniqueUserIds = array_unique($userIds);
121
-
122
-		return array('users' => $uniqueUserIds, 'public' => $public);
123
-	}
34
+    /** @var Util */
35
+    protected $util;
36
+
37
+    /** @var IRootFolder */
38
+    private $rootFolder;
39
+
40
+    /** @var IManager */
41
+    private $shareManager;
42
+
43
+    /**
44
+     * cache results of already checked folders
45
+     *
46
+     * @var array
47
+     */
48
+    protected $cache;
49
+
50
+    public function __construct(Util $util,
51
+                                IRootFolder $rootFolder,
52
+                                IManager $shareManager) {
53
+        $this->util = $util;
54
+        $this->cache = new CappedMemoryCache();
55
+        $this->rootFolder = $rootFolder;
56
+        $this->shareManager = $shareManager;
57
+    }
58
+
59
+
60
+    /**
61
+     * get list of users with access to the file
62
+     *
63
+     * @param string $path to the file
64
+     * @return array  ['users' => $uniqueUserIds, 'public' => $public]
65
+     */
66
+    public function getAccessList($path) {
67
+
68
+        // Make sure that a share key is generated for the owner too
69
+        list($owner, $ownerPath) = $this->util->getUidAndFilename($path);
70
+
71
+        // always add owner to the list of users with access to the file
72
+        $userIds = array($owner);
73
+
74
+        if (!$this->util->isFile($owner . '/' . $ownerPath)) {
75
+            return array('users' => $userIds, 'public' => false);
76
+        }
77
+
78
+        $ownerPath = substr($ownerPath, strlen('/files'));
79
+        $userFolder = $this->rootFolder->getUserFolder($owner);
80
+        try {
81
+            $file = $userFolder->get($ownerPath);
82
+        } catch (NotFoundException $e) {
83
+            $file = null;
84
+        }
85
+        $ownerPath = $this->util->stripPartialFileExtension($ownerPath);
86
+
87
+        // first get the shares for the parent and cache the result so that we don't
88
+        // need to check all parents for every file
89
+        $parent = dirname($ownerPath);
90
+        $parentNode = $userFolder->get($parent);
91
+        if (isset($this->cache[$parent])) {
92
+            $resultForParents = $this->cache[$parent];
93
+        } else {
94
+            $resultForParents = $this->shareManager->getAccessList($parentNode);
95
+            $this->cache[$parent] = $resultForParents;
96
+        }
97
+        $userIds = array_merge($userIds, $resultForParents['users']);
98
+        $public = $resultForParents['public'] || $resultForParents['remote'];
99
+
100
+
101
+        // Find out who, if anyone, is sharing the file
102
+        if ($file !== null) {
103
+            $resultForFile = $this->shareManager->getAccessList($file, false);
104
+            $userIds = array_merge($userIds, $resultForFile['users']);
105
+            $public = $resultForFile['public'] || $resultForFile['remote'] || $public;
106
+        }
107
+
108
+        // check if it is a group mount
109
+        if (\OCP\App::isEnabled("files_external")) {
110
+            $mounts = \OC_Mount_Config::getSystemMountPoints();
111
+            foreach ($mounts as $mount) {
112
+                if ($mount['mountpoint'] == substr($ownerPath, 1, strlen($mount['mountpoint']))) {
113
+                    $mountedFor = $this->util->getUserWithAccessToMountPoint($mount['applicable']['users'], $mount['applicable']['groups']);
114
+                    $userIds = array_merge($userIds, $mountedFor);
115
+                }
116
+            }
117
+        }
118
+
119
+        // Remove duplicate UIDs
120
+        $uniqueUserIds = array_unique($userIds);
121
+
122
+        return array('users' => $uniqueUserIds, 'public' => $public);
123
+    }
124 124
 
125 125
 }
Please login to merge, or discard this patch.
lib/private/Share20/DefaultShareProvider.php 2 patches
Indentation   +1101 added lines, -1101 removed lines patch added patch discarded remove patch
@@ -47,1138 +47,1138 @@
 block discarded – undo
47 47
  */
48 48
 class DefaultShareProvider implements IShareProvider {
49 49
 
50
-	// Special share type for user modified group shares
51
-	const SHARE_TYPE_USERGROUP = 2;
52
-
53
-	/** @var IDBConnection */
54
-	private $dbConn;
55
-
56
-	/** @var IUserManager */
57
-	private $userManager;
58
-
59
-	/** @var IGroupManager */
60
-	private $groupManager;
61
-
62
-	/** @var IRootFolder */
63
-	private $rootFolder;
64
-
65
-	/**
66
-	 * DefaultShareProvider constructor.
67
-	 *
68
-	 * @param IDBConnection $connection
69
-	 * @param IUserManager $userManager
70
-	 * @param IGroupManager $groupManager
71
-	 * @param IRootFolder $rootFolder
72
-	 */
73
-	public function __construct(
74
-			IDBConnection $connection,
75
-			IUserManager $userManager,
76
-			IGroupManager $groupManager,
77
-			IRootFolder $rootFolder) {
78
-		$this->dbConn = $connection;
79
-		$this->userManager = $userManager;
80
-		$this->groupManager = $groupManager;
81
-		$this->rootFolder = $rootFolder;
82
-	}
83
-
84
-	/**
85
-	 * Return the identifier of this provider.
86
-	 *
87
-	 * @return string Containing only [a-zA-Z0-9]
88
-	 */
89
-	public function identifier() {
90
-		return 'ocinternal';
91
-	}
92
-
93
-	/**
94
-	 * Share a path
95
-	 *
96
-	 * @param \OCP\Share\IShare $share
97
-	 * @return \OCP\Share\IShare The share object
98
-	 * @throws ShareNotFound
99
-	 * @throws \Exception
100
-	 */
101
-	public function create(\OCP\Share\IShare $share) {
102
-		$qb = $this->dbConn->getQueryBuilder();
103
-
104
-		$qb->insert('share');
105
-		$qb->setValue('share_type', $qb->createNamedParameter($share->getShareType()));
106
-
107
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
108
-			//Set the UID of the user we share with
109
-			$qb->setValue('share_with', $qb->createNamedParameter($share->getSharedWith()));
110
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
111
-			//Set the GID of the group we share with
112
-			$qb->setValue('share_with', $qb->createNamedParameter($share->getSharedWith()));
113
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
114
-			//Set the token of the share
115
-			$qb->setValue('token', $qb->createNamedParameter($share->getToken()));
116
-
117
-			//If a password is set store it
118
-			if ($share->getPassword() !== null) {
119
-				$qb->setValue('password', $qb->createNamedParameter($share->getPassword()));
120
-			}
121
-
122
-			//If an expiration date is set store it
123
-			if ($share->getExpirationDate() !== null) {
124
-				$qb->setValue('expiration', $qb->createNamedParameter($share->getExpirationDate(), 'datetime'));
125
-			}
126
-
127
-			if (method_exists($share, 'getParent')) {
128
-				$qb->setValue('parent', $qb->createNamedParameter($share->getParent()));
129
-			}
130
-		} else {
131
-			throw new \Exception('invalid share type!');
132
-		}
133
-
134
-		// Set what is shares
135
-		$qb->setValue('item_type', $qb->createParameter('itemType'));
136
-		if ($share->getNode() instanceof \OCP\Files\File) {
137
-			$qb->setParameter('itemType', 'file');
138
-		} else {
139
-			$qb->setParameter('itemType', 'folder');
140
-		}
141
-
142
-		// Set the file id
143
-		$qb->setValue('item_source', $qb->createNamedParameter($share->getNode()->getId()));
144
-		$qb->setValue('file_source', $qb->createNamedParameter($share->getNode()->getId()));
145
-
146
-		// set the permissions
147
-		$qb->setValue('permissions', $qb->createNamedParameter($share->getPermissions()));
148
-
149
-		// Set who created this share
150
-		$qb->setValue('uid_initiator', $qb->createNamedParameter($share->getSharedBy()));
151
-
152
-		// Set who is the owner of this file/folder (and this the owner of the share)
153
-		$qb->setValue('uid_owner', $qb->createNamedParameter($share->getShareOwner()));
154
-
155
-		// Set the file target
156
-		$qb->setValue('file_target', $qb->createNamedParameter($share->getTarget()));
157
-
158
-		// Set the time this share was created
159
-		$qb->setValue('stime', $qb->createNamedParameter(time()));
160
-
161
-		// insert the data and fetch the id of the share
162
-		$this->dbConn->beginTransaction();
163
-		$qb->execute();
164
-		$id = $this->dbConn->lastInsertId('*PREFIX*share');
165
-
166
-		// Now fetch the inserted share and create a complete share object
167
-		$qb = $this->dbConn->getQueryBuilder();
168
-		$qb->select('*')
169
-			->from('share')
170
-			->where($qb->expr()->eq('id', $qb->createNamedParameter($id)));
171
-
172
-		$cursor = $qb->execute();
173
-		$data = $cursor->fetch();
174
-		$this->dbConn->commit();
175
-		$cursor->closeCursor();
176
-
177
-		if ($data === false) {
178
-			throw new ShareNotFound();
179
-		}
180
-
181
-		$share = $this->createShare($data);
182
-		return $share;
183
-	}
184
-
185
-	/**
186
-	 * Update a share
187
-	 *
188
-	 * @param \OCP\Share\IShare $share
189
-	 * @return \OCP\Share\IShare The share object
190
-	 */
191
-	public function update(\OCP\Share\IShare $share) {
192
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
193
-			/*
50
+    // Special share type for user modified group shares
51
+    const SHARE_TYPE_USERGROUP = 2;
52
+
53
+    /** @var IDBConnection */
54
+    private $dbConn;
55
+
56
+    /** @var IUserManager */
57
+    private $userManager;
58
+
59
+    /** @var IGroupManager */
60
+    private $groupManager;
61
+
62
+    /** @var IRootFolder */
63
+    private $rootFolder;
64
+
65
+    /**
66
+     * DefaultShareProvider constructor.
67
+     *
68
+     * @param IDBConnection $connection
69
+     * @param IUserManager $userManager
70
+     * @param IGroupManager $groupManager
71
+     * @param IRootFolder $rootFolder
72
+     */
73
+    public function __construct(
74
+            IDBConnection $connection,
75
+            IUserManager $userManager,
76
+            IGroupManager $groupManager,
77
+            IRootFolder $rootFolder) {
78
+        $this->dbConn = $connection;
79
+        $this->userManager = $userManager;
80
+        $this->groupManager = $groupManager;
81
+        $this->rootFolder = $rootFolder;
82
+    }
83
+
84
+    /**
85
+     * Return the identifier of this provider.
86
+     *
87
+     * @return string Containing only [a-zA-Z0-9]
88
+     */
89
+    public function identifier() {
90
+        return 'ocinternal';
91
+    }
92
+
93
+    /**
94
+     * Share a path
95
+     *
96
+     * @param \OCP\Share\IShare $share
97
+     * @return \OCP\Share\IShare The share object
98
+     * @throws ShareNotFound
99
+     * @throws \Exception
100
+     */
101
+    public function create(\OCP\Share\IShare $share) {
102
+        $qb = $this->dbConn->getQueryBuilder();
103
+
104
+        $qb->insert('share');
105
+        $qb->setValue('share_type', $qb->createNamedParameter($share->getShareType()));
106
+
107
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
108
+            //Set the UID of the user we share with
109
+            $qb->setValue('share_with', $qb->createNamedParameter($share->getSharedWith()));
110
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
111
+            //Set the GID of the group we share with
112
+            $qb->setValue('share_with', $qb->createNamedParameter($share->getSharedWith()));
113
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
114
+            //Set the token of the share
115
+            $qb->setValue('token', $qb->createNamedParameter($share->getToken()));
116
+
117
+            //If a password is set store it
118
+            if ($share->getPassword() !== null) {
119
+                $qb->setValue('password', $qb->createNamedParameter($share->getPassword()));
120
+            }
121
+
122
+            //If an expiration date is set store it
123
+            if ($share->getExpirationDate() !== null) {
124
+                $qb->setValue('expiration', $qb->createNamedParameter($share->getExpirationDate(), 'datetime'));
125
+            }
126
+
127
+            if (method_exists($share, 'getParent')) {
128
+                $qb->setValue('parent', $qb->createNamedParameter($share->getParent()));
129
+            }
130
+        } else {
131
+            throw new \Exception('invalid share type!');
132
+        }
133
+
134
+        // Set what is shares
135
+        $qb->setValue('item_type', $qb->createParameter('itemType'));
136
+        if ($share->getNode() instanceof \OCP\Files\File) {
137
+            $qb->setParameter('itemType', 'file');
138
+        } else {
139
+            $qb->setParameter('itemType', 'folder');
140
+        }
141
+
142
+        // Set the file id
143
+        $qb->setValue('item_source', $qb->createNamedParameter($share->getNode()->getId()));
144
+        $qb->setValue('file_source', $qb->createNamedParameter($share->getNode()->getId()));
145
+
146
+        // set the permissions
147
+        $qb->setValue('permissions', $qb->createNamedParameter($share->getPermissions()));
148
+
149
+        // Set who created this share
150
+        $qb->setValue('uid_initiator', $qb->createNamedParameter($share->getSharedBy()));
151
+
152
+        // Set who is the owner of this file/folder (and this the owner of the share)
153
+        $qb->setValue('uid_owner', $qb->createNamedParameter($share->getShareOwner()));
154
+
155
+        // Set the file target
156
+        $qb->setValue('file_target', $qb->createNamedParameter($share->getTarget()));
157
+
158
+        // Set the time this share was created
159
+        $qb->setValue('stime', $qb->createNamedParameter(time()));
160
+
161
+        // insert the data and fetch the id of the share
162
+        $this->dbConn->beginTransaction();
163
+        $qb->execute();
164
+        $id = $this->dbConn->lastInsertId('*PREFIX*share');
165
+
166
+        // Now fetch the inserted share and create a complete share object
167
+        $qb = $this->dbConn->getQueryBuilder();
168
+        $qb->select('*')
169
+            ->from('share')
170
+            ->where($qb->expr()->eq('id', $qb->createNamedParameter($id)));
171
+
172
+        $cursor = $qb->execute();
173
+        $data = $cursor->fetch();
174
+        $this->dbConn->commit();
175
+        $cursor->closeCursor();
176
+
177
+        if ($data === false) {
178
+            throw new ShareNotFound();
179
+        }
180
+
181
+        $share = $this->createShare($data);
182
+        return $share;
183
+    }
184
+
185
+    /**
186
+     * Update a share
187
+     *
188
+     * @param \OCP\Share\IShare $share
189
+     * @return \OCP\Share\IShare The share object
190
+     */
191
+    public function update(\OCP\Share\IShare $share) {
192
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
193
+            /*
194 194
 			 * We allow updating the recipient on user shares.
195 195
 			 */
196
-			$qb = $this->dbConn->getQueryBuilder();
197
-			$qb->update('share')
198
-				->where($qb->expr()->eq('id', $qb->createNamedParameter($share->getId())))
199
-				->set('share_with', $qb->createNamedParameter($share->getSharedWith()))
200
-				->set('uid_owner', $qb->createNamedParameter($share->getShareOwner()))
201
-				->set('uid_initiator', $qb->createNamedParameter($share->getSharedBy()))
202
-				->set('permissions', $qb->createNamedParameter($share->getPermissions()))
203
-				->set('item_source', $qb->createNamedParameter($share->getNode()->getId()))
204
-				->set('file_source', $qb->createNamedParameter($share->getNode()->getId()))
205
-				->set('expiration', $qb->createNamedParameter($share->getExpirationDate(), IQueryBuilder::PARAM_DATE))
206
-				->execute();
207
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
208
-			$qb = $this->dbConn->getQueryBuilder();
209
-			$qb->update('share')
210
-				->where($qb->expr()->eq('id', $qb->createNamedParameter($share->getId())))
211
-				->set('uid_owner', $qb->createNamedParameter($share->getShareOwner()))
212
-				->set('uid_initiator', $qb->createNamedParameter($share->getSharedBy()))
213
-				->set('permissions', $qb->createNamedParameter($share->getPermissions()))
214
-				->set('item_source', $qb->createNamedParameter($share->getNode()->getId()))
215
-				->set('file_source', $qb->createNamedParameter($share->getNode()->getId()))
216
-				->set('expiration', $qb->createNamedParameter($share->getExpirationDate(), IQueryBuilder::PARAM_DATE))
217
-				->execute();
218
-
219
-			/*
196
+            $qb = $this->dbConn->getQueryBuilder();
197
+            $qb->update('share')
198
+                ->where($qb->expr()->eq('id', $qb->createNamedParameter($share->getId())))
199
+                ->set('share_with', $qb->createNamedParameter($share->getSharedWith()))
200
+                ->set('uid_owner', $qb->createNamedParameter($share->getShareOwner()))
201
+                ->set('uid_initiator', $qb->createNamedParameter($share->getSharedBy()))
202
+                ->set('permissions', $qb->createNamedParameter($share->getPermissions()))
203
+                ->set('item_source', $qb->createNamedParameter($share->getNode()->getId()))
204
+                ->set('file_source', $qb->createNamedParameter($share->getNode()->getId()))
205
+                ->set('expiration', $qb->createNamedParameter($share->getExpirationDate(), IQueryBuilder::PARAM_DATE))
206
+                ->execute();
207
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
208
+            $qb = $this->dbConn->getQueryBuilder();
209
+            $qb->update('share')
210
+                ->where($qb->expr()->eq('id', $qb->createNamedParameter($share->getId())))
211
+                ->set('uid_owner', $qb->createNamedParameter($share->getShareOwner()))
212
+                ->set('uid_initiator', $qb->createNamedParameter($share->getSharedBy()))
213
+                ->set('permissions', $qb->createNamedParameter($share->getPermissions()))
214
+                ->set('item_source', $qb->createNamedParameter($share->getNode()->getId()))
215
+                ->set('file_source', $qb->createNamedParameter($share->getNode()->getId()))
216
+                ->set('expiration', $qb->createNamedParameter($share->getExpirationDate(), IQueryBuilder::PARAM_DATE))
217
+                ->execute();
218
+
219
+            /*
220 220
 			 * Update all user defined group shares
221 221
 			 */
222
-			$qb = $this->dbConn->getQueryBuilder();
223
-			$qb->update('share')
224
-				->where($qb->expr()->eq('parent', $qb->createNamedParameter($share->getId())))
225
-				->set('uid_owner', $qb->createNamedParameter($share->getShareOwner()))
226
-				->set('uid_initiator', $qb->createNamedParameter($share->getSharedBy()))
227
-				->set('item_source', $qb->createNamedParameter($share->getNode()->getId()))
228
-				->set('file_source', $qb->createNamedParameter($share->getNode()->getId()))
229
-				->set('expiration', $qb->createNamedParameter($share->getExpirationDate(), IQueryBuilder::PARAM_DATE))
230
-				->execute();
231
-
232
-			/*
222
+            $qb = $this->dbConn->getQueryBuilder();
223
+            $qb->update('share')
224
+                ->where($qb->expr()->eq('parent', $qb->createNamedParameter($share->getId())))
225
+                ->set('uid_owner', $qb->createNamedParameter($share->getShareOwner()))
226
+                ->set('uid_initiator', $qb->createNamedParameter($share->getSharedBy()))
227
+                ->set('item_source', $qb->createNamedParameter($share->getNode()->getId()))
228
+                ->set('file_source', $qb->createNamedParameter($share->getNode()->getId()))
229
+                ->set('expiration', $qb->createNamedParameter($share->getExpirationDate(), IQueryBuilder::PARAM_DATE))
230
+                ->execute();
231
+
232
+            /*
233 233
 			 * Now update the permissions for all children that have not set it to 0
234 234
 			 */
235
-			$qb = $this->dbConn->getQueryBuilder();
236
-			$qb->update('share')
237
-				->where($qb->expr()->eq('parent', $qb->createNamedParameter($share->getId())))
238
-				->andWhere($qb->expr()->neq('permissions', $qb->createNamedParameter(0)))
239
-				->set('permissions', $qb->createNamedParameter($share->getPermissions()))
240
-				->execute();
241
-
242
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
243
-			$qb = $this->dbConn->getQueryBuilder();
244
-			$qb->update('share')
245
-				->where($qb->expr()->eq('id', $qb->createNamedParameter($share->getId())))
246
-				->set('password', $qb->createNamedParameter($share->getPassword()))
247
-				->set('uid_owner', $qb->createNamedParameter($share->getShareOwner()))
248
-				->set('uid_initiator', $qb->createNamedParameter($share->getSharedBy()))
249
-				->set('permissions', $qb->createNamedParameter($share->getPermissions()))
250
-				->set('item_source', $qb->createNamedParameter($share->getNode()->getId()))
251
-				->set('file_source', $qb->createNamedParameter($share->getNode()->getId()))
252
-				->set('token', $qb->createNamedParameter($share->getToken()))
253
-				->set('expiration', $qb->createNamedParameter($share->getExpirationDate(), IQueryBuilder::PARAM_DATE))
254
-				->execute();
255
-		}
256
-
257
-		return $share;
258
-	}
259
-
260
-	/**
261
-	 * Get all children of this share
262
-	 * FIXME: remove once https://github.com/owncloud/core/pull/21660 is in
263
-	 *
264
-	 * @param \OCP\Share\IShare $parent
265
-	 * @return \OCP\Share\IShare[]
266
-	 */
267
-	public function getChildren(\OCP\Share\IShare $parent) {
268
-		$children = [];
269
-
270
-		$qb = $this->dbConn->getQueryBuilder();
271
-		$qb->select('*')
272
-			->from('share')
273
-			->where($qb->expr()->eq('parent', $qb->createNamedParameter($parent->getId())))
274
-			->andWhere(
275
-				$qb->expr()->in(
276
-					'share_type',
277
-					$qb->createNamedParameter([
278
-						\OCP\Share::SHARE_TYPE_USER,
279
-						\OCP\Share::SHARE_TYPE_GROUP,
280
-						\OCP\Share::SHARE_TYPE_LINK,
281
-					], IQueryBuilder::PARAM_INT_ARRAY)
282
-				)
283
-			)
284
-			->andWhere($qb->expr()->orX(
285
-				$qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
286
-				$qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
287
-			))
288
-			->orderBy('id');
289
-
290
-		$cursor = $qb->execute();
291
-		while($data = $cursor->fetch()) {
292
-			$children[] = $this->createShare($data);
293
-		}
294
-		$cursor->closeCursor();
295
-
296
-		return $children;
297
-	}
298
-
299
-	/**
300
-	 * Delete a share
301
-	 *
302
-	 * @param \OCP\Share\IShare $share
303
-	 */
304
-	public function delete(\OCP\Share\IShare $share) {
305
-		$qb = $this->dbConn->getQueryBuilder();
306
-		$qb->delete('share')
307
-			->where($qb->expr()->eq('id', $qb->createNamedParameter($share->getId())));
308
-
309
-		/*
235
+            $qb = $this->dbConn->getQueryBuilder();
236
+            $qb->update('share')
237
+                ->where($qb->expr()->eq('parent', $qb->createNamedParameter($share->getId())))
238
+                ->andWhere($qb->expr()->neq('permissions', $qb->createNamedParameter(0)))
239
+                ->set('permissions', $qb->createNamedParameter($share->getPermissions()))
240
+                ->execute();
241
+
242
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
243
+            $qb = $this->dbConn->getQueryBuilder();
244
+            $qb->update('share')
245
+                ->where($qb->expr()->eq('id', $qb->createNamedParameter($share->getId())))
246
+                ->set('password', $qb->createNamedParameter($share->getPassword()))
247
+                ->set('uid_owner', $qb->createNamedParameter($share->getShareOwner()))
248
+                ->set('uid_initiator', $qb->createNamedParameter($share->getSharedBy()))
249
+                ->set('permissions', $qb->createNamedParameter($share->getPermissions()))
250
+                ->set('item_source', $qb->createNamedParameter($share->getNode()->getId()))
251
+                ->set('file_source', $qb->createNamedParameter($share->getNode()->getId()))
252
+                ->set('token', $qb->createNamedParameter($share->getToken()))
253
+                ->set('expiration', $qb->createNamedParameter($share->getExpirationDate(), IQueryBuilder::PARAM_DATE))
254
+                ->execute();
255
+        }
256
+
257
+        return $share;
258
+    }
259
+
260
+    /**
261
+     * Get all children of this share
262
+     * FIXME: remove once https://github.com/owncloud/core/pull/21660 is in
263
+     *
264
+     * @param \OCP\Share\IShare $parent
265
+     * @return \OCP\Share\IShare[]
266
+     */
267
+    public function getChildren(\OCP\Share\IShare $parent) {
268
+        $children = [];
269
+
270
+        $qb = $this->dbConn->getQueryBuilder();
271
+        $qb->select('*')
272
+            ->from('share')
273
+            ->where($qb->expr()->eq('parent', $qb->createNamedParameter($parent->getId())))
274
+            ->andWhere(
275
+                $qb->expr()->in(
276
+                    'share_type',
277
+                    $qb->createNamedParameter([
278
+                        \OCP\Share::SHARE_TYPE_USER,
279
+                        \OCP\Share::SHARE_TYPE_GROUP,
280
+                        \OCP\Share::SHARE_TYPE_LINK,
281
+                    ], IQueryBuilder::PARAM_INT_ARRAY)
282
+                )
283
+            )
284
+            ->andWhere($qb->expr()->orX(
285
+                $qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
286
+                $qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
287
+            ))
288
+            ->orderBy('id');
289
+
290
+        $cursor = $qb->execute();
291
+        while($data = $cursor->fetch()) {
292
+            $children[] = $this->createShare($data);
293
+        }
294
+        $cursor->closeCursor();
295
+
296
+        return $children;
297
+    }
298
+
299
+    /**
300
+     * Delete a share
301
+     *
302
+     * @param \OCP\Share\IShare $share
303
+     */
304
+    public function delete(\OCP\Share\IShare $share) {
305
+        $qb = $this->dbConn->getQueryBuilder();
306
+        $qb->delete('share')
307
+            ->where($qb->expr()->eq('id', $qb->createNamedParameter($share->getId())));
308
+
309
+        /*
310 310
 		 * If the share is a group share delete all possible
311 311
 		 * user defined groups shares.
312 312
 		 */
313
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
314
-			$qb->orWhere($qb->expr()->eq('parent', $qb->createNamedParameter($share->getId())));
315
-		}
316
-
317
-		$qb->execute();
318
-	}
319
-
320
-	/**
321
-	 * Unshare a share from the recipient. If this is a group share
322
-	 * this means we need a special entry in the share db.
323
-	 *
324
-	 * @param \OCP\Share\IShare $share
325
-	 * @param string $recipient UserId of recipient
326
-	 * @throws BackendError
327
-	 * @throws ProviderException
328
-	 */
329
-	public function deleteFromSelf(\OCP\Share\IShare $share, $recipient) {
330
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
331
-
332
-			$group = $this->groupManager->get($share->getSharedWith());
333
-			$user = $this->userManager->get($recipient);
334
-
335
-			if (is_null($group)) {
336
-				throw new ProviderException('Group "' . $share->getSharedWith() . '" does not exist');
337
-			}
338
-
339
-			if (!$group->inGroup($user)) {
340
-				throw new ProviderException('Recipient not in receiving group');
341
-			}
342
-
343
-			// Try to fetch user specific share
344
-			$qb = $this->dbConn->getQueryBuilder();
345
-			$stmt = $qb->select('*')
346
-				->from('share')
347
-				->where($qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP)))
348
-				->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($recipient)))
349
-				->andWhere($qb->expr()->eq('parent', $qb->createNamedParameter($share->getId())))
350
-				->andWhere($qb->expr()->orX(
351
-					$qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
352
-					$qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
353
-				))
354
-				->execute();
355
-
356
-			$data = $stmt->fetch();
357
-
358
-			/*
313
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
314
+            $qb->orWhere($qb->expr()->eq('parent', $qb->createNamedParameter($share->getId())));
315
+        }
316
+
317
+        $qb->execute();
318
+    }
319
+
320
+    /**
321
+     * Unshare a share from the recipient. If this is a group share
322
+     * this means we need a special entry in the share db.
323
+     *
324
+     * @param \OCP\Share\IShare $share
325
+     * @param string $recipient UserId of recipient
326
+     * @throws BackendError
327
+     * @throws ProviderException
328
+     */
329
+    public function deleteFromSelf(\OCP\Share\IShare $share, $recipient) {
330
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
331
+
332
+            $group = $this->groupManager->get($share->getSharedWith());
333
+            $user = $this->userManager->get($recipient);
334
+
335
+            if (is_null($group)) {
336
+                throw new ProviderException('Group "' . $share->getSharedWith() . '" does not exist');
337
+            }
338
+
339
+            if (!$group->inGroup($user)) {
340
+                throw new ProviderException('Recipient not in receiving group');
341
+            }
342
+
343
+            // Try to fetch user specific share
344
+            $qb = $this->dbConn->getQueryBuilder();
345
+            $stmt = $qb->select('*')
346
+                ->from('share')
347
+                ->where($qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP)))
348
+                ->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($recipient)))
349
+                ->andWhere($qb->expr()->eq('parent', $qb->createNamedParameter($share->getId())))
350
+                ->andWhere($qb->expr()->orX(
351
+                    $qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
352
+                    $qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
353
+                ))
354
+                ->execute();
355
+
356
+            $data = $stmt->fetch();
357
+
358
+            /*
359 359
 			 * Check if there already is a user specific group share.
360 360
 			 * If there is update it (if required).
361 361
 			 */
362
-			if ($data === false) {
363
-				$qb = $this->dbConn->getQueryBuilder();
364
-
365
-				$type = $share->getNodeType();
366
-
367
-				//Insert new share
368
-				$qb->insert('share')
369
-					->values([
370
-						'share_type' => $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP),
371
-						'share_with' => $qb->createNamedParameter($recipient),
372
-						'uid_owner' => $qb->createNamedParameter($share->getShareOwner()),
373
-						'uid_initiator' => $qb->createNamedParameter($share->getSharedBy()),
374
-						'parent' => $qb->createNamedParameter($share->getId()),
375
-						'item_type' => $qb->createNamedParameter($type),
376
-						'item_source' => $qb->createNamedParameter($share->getNodeId()),
377
-						'file_source' => $qb->createNamedParameter($share->getNodeId()),
378
-						'file_target' => $qb->createNamedParameter($share->getTarget()),
379
-						'permissions' => $qb->createNamedParameter(0),
380
-						'stime' => $qb->createNamedParameter($share->getShareTime()->getTimestamp()),
381
-					])->execute();
382
-
383
-			} else if ($data['permissions'] !== 0) {
384
-
385
-				// Update existing usergroup share
386
-				$qb = $this->dbConn->getQueryBuilder();
387
-				$qb->update('share')
388
-					->set('permissions', $qb->createNamedParameter(0))
389
-					->where($qb->expr()->eq('id', $qb->createNamedParameter($data['id'])))
390
-					->execute();
391
-			}
392
-
393
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
394
-
395
-			if ($share->getSharedWith() !== $recipient) {
396
-				throw new ProviderException('Recipient does not match');
397
-			}
398
-
399
-			// We can just delete user and link shares
400
-			$this->delete($share);
401
-		} else {
402
-			throw new ProviderException('Invalid shareType');
403
-		}
404
-	}
405
-
406
-	/**
407
-	 * @inheritdoc
408
-	 */
409
-	public function move(\OCP\Share\IShare $share, $recipient) {
410
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
411
-			// Just update the target
412
-			$qb = $this->dbConn->getQueryBuilder();
413
-			$qb->update('share')
414
-				->set('file_target', $qb->createNamedParameter($share->getTarget()))
415
-				->where($qb->expr()->eq('id', $qb->createNamedParameter($share->getId())))
416
-				->execute();
417
-
418
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
419
-
420
-			// Check if there is a usergroup share
421
-			$qb = $this->dbConn->getQueryBuilder();
422
-			$stmt = $qb->select('id')
423
-				->from('share')
424
-				->where($qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP)))
425
-				->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($recipient)))
426
-				->andWhere($qb->expr()->eq('parent', $qb->createNamedParameter($share->getId())))
427
-				->andWhere($qb->expr()->orX(
428
-					$qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
429
-					$qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
430
-				))
431
-				->setMaxResults(1)
432
-				->execute();
433
-
434
-			$data = $stmt->fetch();
435
-			$stmt->closeCursor();
436
-
437
-			if ($data === false) {
438
-				// No usergroup share yet. Create one.
439
-				$qb = $this->dbConn->getQueryBuilder();
440
-				$qb->insert('share')
441
-					->values([
442
-						'share_type' => $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP),
443
-						'share_with' => $qb->createNamedParameter($recipient),
444
-						'uid_owner' => $qb->createNamedParameter($share->getShareOwner()),
445
-						'uid_initiator' => $qb->createNamedParameter($share->getSharedBy()),
446
-						'parent' => $qb->createNamedParameter($share->getId()),
447
-						'item_type' => $qb->createNamedParameter($share->getNode() instanceof File ? 'file' : 'folder'),
448
-						'item_source' => $qb->createNamedParameter($share->getNode()->getId()),
449
-						'file_source' => $qb->createNamedParameter($share->getNode()->getId()),
450
-						'file_target' => $qb->createNamedParameter($share->getTarget()),
451
-						'permissions' => $qb->createNamedParameter($share->getPermissions()),
452
-						'stime' => $qb->createNamedParameter($share->getShareTime()->getTimestamp()),
453
-					])->execute();
454
-			} else {
455
-				// Already a usergroup share. Update it.
456
-				$qb = $this->dbConn->getQueryBuilder();
457
-				$qb->update('share')
458
-					->set('file_target', $qb->createNamedParameter($share->getTarget()))
459
-					->where($qb->expr()->eq('id', $qb->createNamedParameter($data['id'])))
460
-					->execute();
461
-			}
462
-		}
463
-
464
-		return $share;
465
-	}
466
-
467
-	public function getSharesInFolder($userId, Folder $node, $reshares) {
468
-		$qb = $this->dbConn->getQueryBuilder();
469
-		$qb->select('*')
470
-			->from('share', 's')
471
-			->andWhere($qb->expr()->orX(
472
-				$qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
473
-				$qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
474
-			));
475
-
476
-		$qb->andWhere($qb->expr()->orX(
477
-			$qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_USER)),
478
-			$qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_GROUP)),
479
-			$qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_LINK))
480
-		));
481
-
482
-		/**
483
-		 * Reshares for this user are shares where they are the owner.
484
-		 */
485
-		if ($reshares === false) {
486
-			$qb->andWhere($qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId)));
487
-		} else {
488
-			$qb->andWhere(
489
-				$qb->expr()->orX(
490
-					$qb->expr()->eq('uid_owner', $qb->createNamedParameter($userId)),
491
-					$qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId))
492
-				)
493
-			);
494
-		}
495
-
496
-		$qb->innerJoin('s', 'filecache' ,'f', $qb->expr()->eq('s.file_source', 'f.fileid'));
497
-		$qb->andWhere($qb->expr()->eq('f.parent', $qb->createNamedParameter($node->getId())));
498
-
499
-		$qb->orderBy('id');
500
-
501
-		$cursor = $qb->execute();
502
-		$shares = [];
503
-		while ($data = $cursor->fetch()) {
504
-			$shares[$data['fileid']][] = $this->createShare($data);
505
-		}
506
-		$cursor->closeCursor();
507
-
508
-		return $shares;
509
-	}
510
-
511
-	/**
512
-	 * @inheritdoc
513
-	 */
514
-	public function getSharesBy($userId, $shareType, $node, $reshares, $limit, $offset) {
515
-		$qb = $this->dbConn->getQueryBuilder();
516
-		$qb->select('*')
517
-			->from('share')
518
-			->andWhere($qb->expr()->orX(
519
-				$qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
520
-				$qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
521
-			));
522
-
523
-		$qb->andWhere($qb->expr()->eq('share_type', $qb->createNamedParameter($shareType)));
524
-
525
-		/**
526
-		 * Reshares for this user are shares where they are the owner.
527
-		 */
528
-		if ($reshares === false) {
529
-			$qb->andWhere($qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId)));
530
-		} else {
531
-			$qb->andWhere(
532
-				$qb->expr()->orX(
533
-					$qb->expr()->eq('uid_owner', $qb->createNamedParameter($userId)),
534
-					$qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId))
535
-				)
536
-			);
537
-		}
538
-
539
-		if ($node !== null) {
540
-			$qb->andWhere($qb->expr()->eq('file_source', $qb->createNamedParameter($node->getId())));
541
-		}
542
-
543
-		if ($limit !== -1) {
544
-			$qb->setMaxResults($limit);
545
-		}
546
-
547
-		$qb->setFirstResult($offset);
548
-		$qb->orderBy('id');
549
-
550
-		$cursor = $qb->execute();
551
-		$shares = [];
552
-		while($data = $cursor->fetch()) {
553
-			$shares[] = $this->createShare($data);
554
-		}
555
-		$cursor->closeCursor();
556
-
557
-		return $shares;
558
-	}
559
-
560
-	/**
561
-	 * @inheritdoc
562
-	 */
563
-	public function getShareById($id, $recipientId = null) {
564
-		$qb = $this->dbConn->getQueryBuilder();
565
-
566
-		$qb->select('*')
567
-			->from('share')
568
-			->where($qb->expr()->eq('id', $qb->createNamedParameter($id)))
569
-			->andWhere(
570
-				$qb->expr()->in(
571
-					'share_type',
572
-					$qb->createNamedParameter([
573
-						\OCP\Share::SHARE_TYPE_USER,
574
-						\OCP\Share::SHARE_TYPE_GROUP,
575
-						\OCP\Share::SHARE_TYPE_LINK,
576
-					], IQueryBuilder::PARAM_INT_ARRAY)
577
-				)
578
-			)
579
-			->andWhere($qb->expr()->orX(
580
-				$qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
581
-				$qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
582
-			));
583
-
584
-		$cursor = $qb->execute();
585
-		$data = $cursor->fetch();
586
-		$cursor->closeCursor();
587
-
588
-		if ($data === false) {
589
-			throw new ShareNotFound();
590
-		}
591
-
592
-		try {
593
-			$share = $this->createShare($data);
594
-		} catch (InvalidShare $e) {
595
-			throw new ShareNotFound();
596
-		}
597
-
598
-		// If the recipient is set for a group share resolve to that user
599
-		if ($recipientId !== null && $share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
600
-			$share = $this->resolveGroupShares([$share], $recipientId)[0];
601
-		}
602
-
603
-		return $share;
604
-	}
605
-
606
-	/**
607
-	 * Get shares for a given path
608
-	 *
609
-	 * @param \OCP\Files\Node $path
610
-	 * @return \OCP\Share\IShare[]
611
-	 */
612
-	public function getSharesByPath(Node $path) {
613
-		$qb = $this->dbConn->getQueryBuilder();
614
-
615
-		$cursor = $qb->select('*')
616
-			->from('share')
617
-			->andWhere($qb->expr()->eq('file_source', $qb->createNamedParameter($path->getId())))
618
-			->andWhere(
619
-				$qb->expr()->orX(
620
-					$qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_USER)),
621
-					$qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_GROUP))
622
-				)
623
-			)
624
-			->andWhere($qb->expr()->orX(
625
-				$qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
626
-				$qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
627
-			))
628
-			->execute();
629
-
630
-		$shares = [];
631
-		while($data = $cursor->fetch()) {
632
-			$shares[] = $this->createShare($data);
633
-		}
634
-		$cursor->closeCursor();
635
-
636
-		return $shares;
637
-	}
638
-
639
-	/**
640
-	 * Returns whether the given database result can be interpreted as
641
-	 * a share with accessible file (not trashed, not deleted)
642
-	 */
643
-	private function isAccessibleResult($data) {
644
-		// exclude shares leading to deleted file entries
645
-		if ($data['fileid'] === null) {
646
-			return false;
647
-		}
648
-
649
-		// exclude shares leading to trashbin on home storages
650
-		$pathSections = explode('/', $data['path'], 2);
651
-		// FIXME: would not detect rare md5'd home storage case properly
652
-		if ($pathSections[0] !== 'files'
653
-		    	&& in_array(explode(':', $data['storage_string_id'], 2)[0], array('home', 'object'))) {
654
-			return false;
655
-		}
656
-		return true;
657
-	}
658
-
659
-	/**
660
-	 * @inheritdoc
661
-	 */
662
-	public function getSharedWith($userId, $shareType, $node, $limit, $offset) {
663
-		/** @var Share[] $shares */
664
-		$shares = [];
665
-
666
-		if ($shareType === \OCP\Share::SHARE_TYPE_USER) {
667
-			//Get shares directly with this user
668
-			$qb = $this->dbConn->getQueryBuilder();
669
-			$qb->select('s.*',
670
-				'f.fileid', 'f.path', 'f.permissions AS f_permissions', 'f.storage', 'f.path_hash',
671
-				'f.parent AS f_parent', 'f.name', 'f.mimetype', 'f.mimepart', 'f.size', 'f.mtime', 'f.storage_mtime',
672
-				'f.encrypted', 'f.unencrypted_size', 'f.etag', 'f.checksum'
673
-			)
674
-				->selectAlias('st.id', 'storage_string_id')
675
-				->from('share', 's')
676
-				->leftJoin('s', 'filecache', 'f', $qb->expr()->eq('s.file_source', 'f.fileid'))
677
-				->leftJoin('f', 'storages', 'st', $qb->expr()->eq('f.storage', 'st.numeric_id'));
678
-
679
-			// Order by id
680
-			$qb->orderBy('s.id');
681
-
682
-			// Set limit and offset
683
-			if ($limit !== -1) {
684
-				$qb->setMaxResults($limit);
685
-			}
686
-			$qb->setFirstResult($offset);
687
-
688
-			$qb->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_USER)))
689
-				->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($userId)))
690
-				->andWhere($qb->expr()->orX(
691
-					$qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
692
-					$qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
693
-				));
694
-
695
-			// Filter by node if provided
696
-			if ($node !== null) {
697
-				$qb->andWhere($qb->expr()->eq('file_source', $qb->createNamedParameter($node->getId())));
698
-			}
699
-
700
-			$cursor = $qb->execute();
701
-
702
-			while($data = $cursor->fetch()) {
703
-				if ($this->isAccessibleResult($data)) {
704
-					$shares[] = $this->createShare($data);
705
-				}
706
-			}
707
-			$cursor->closeCursor();
708
-
709
-		} else if ($shareType === \OCP\Share::SHARE_TYPE_GROUP) {
710
-			$user = $this->userManager->get($userId);
711
-			$allGroups = $this->groupManager->getUserGroups($user);
712
-
713
-			/** @var Share[] $shares2 */
714
-			$shares2 = [];
715
-
716
-			$start = 0;
717
-			while(true) {
718
-				$groups = array_slice($allGroups, $start, 100);
719
-				$start += 100;
720
-
721
-				if ($groups === []) {
722
-					break;
723
-				}
724
-
725
-				$qb = $this->dbConn->getQueryBuilder();
726
-				$qb->select('s.*',
727
-					'f.fileid', 'f.path', 'f.permissions AS f_permissions', 'f.storage', 'f.path_hash',
728
-					'f.parent AS f_parent', 'f.name', 'f.mimetype', 'f.mimepart', 'f.size', 'f.mtime', 'f.storage_mtime',
729
-					'f.encrypted', 'f.unencrypted_size', 'f.etag', 'f.checksum'
730
-				)
731
-					->selectAlias('st.id', 'storage_string_id')
732
-					->from('share', 's')
733
-					->leftJoin('s', 'filecache', 'f', $qb->expr()->eq('s.file_source', 'f.fileid'))
734
-					->leftJoin('f', 'storages', 'st', $qb->expr()->eq('f.storage', 'st.numeric_id'))
735
-					->orderBy('s.id')
736
-					->setFirstResult(0);
737
-
738
-				if ($limit !== -1) {
739
-					$qb->setMaxResults($limit - count($shares));
740
-				}
741
-
742
-				// Filter by node if provided
743
-				if ($node !== null) {
744
-					$qb->andWhere($qb->expr()->eq('file_source', $qb->createNamedParameter($node->getId())));
745
-				}
746
-
747
-				$groups = array_map(function(IGroup $group) { return $group->getGID(); }, $groups);
748
-
749
-				$qb->andWhere($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_GROUP)))
750
-					->andWhere($qb->expr()->in('share_with', $qb->createNamedParameter(
751
-						$groups,
752
-						IQueryBuilder::PARAM_STR_ARRAY
753
-					)))
754
-					->andWhere($qb->expr()->orX(
755
-						$qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
756
-						$qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
757
-					));
758
-
759
-				$cursor = $qb->execute();
760
-				while($data = $cursor->fetch()) {
761
-					if ($offset > 0) {
762
-						$offset--;
763
-						continue;
764
-					}
765
-
766
-					if ($this->isAccessibleResult($data)) {
767
-						$shares2[] = $this->createShare($data);
768
-					}
769
-				}
770
-				$cursor->closeCursor();
771
-			}
772
-
773
-			/*
362
+            if ($data === false) {
363
+                $qb = $this->dbConn->getQueryBuilder();
364
+
365
+                $type = $share->getNodeType();
366
+
367
+                //Insert new share
368
+                $qb->insert('share')
369
+                    ->values([
370
+                        'share_type' => $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP),
371
+                        'share_with' => $qb->createNamedParameter($recipient),
372
+                        'uid_owner' => $qb->createNamedParameter($share->getShareOwner()),
373
+                        'uid_initiator' => $qb->createNamedParameter($share->getSharedBy()),
374
+                        'parent' => $qb->createNamedParameter($share->getId()),
375
+                        'item_type' => $qb->createNamedParameter($type),
376
+                        'item_source' => $qb->createNamedParameter($share->getNodeId()),
377
+                        'file_source' => $qb->createNamedParameter($share->getNodeId()),
378
+                        'file_target' => $qb->createNamedParameter($share->getTarget()),
379
+                        'permissions' => $qb->createNamedParameter(0),
380
+                        'stime' => $qb->createNamedParameter($share->getShareTime()->getTimestamp()),
381
+                    ])->execute();
382
+
383
+            } else if ($data['permissions'] !== 0) {
384
+
385
+                // Update existing usergroup share
386
+                $qb = $this->dbConn->getQueryBuilder();
387
+                $qb->update('share')
388
+                    ->set('permissions', $qb->createNamedParameter(0))
389
+                    ->where($qb->expr()->eq('id', $qb->createNamedParameter($data['id'])))
390
+                    ->execute();
391
+            }
392
+
393
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
394
+
395
+            if ($share->getSharedWith() !== $recipient) {
396
+                throw new ProviderException('Recipient does not match');
397
+            }
398
+
399
+            // We can just delete user and link shares
400
+            $this->delete($share);
401
+        } else {
402
+            throw new ProviderException('Invalid shareType');
403
+        }
404
+    }
405
+
406
+    /**
407
+     * @inheritdoc
408
+     */
409
+    public function move(\OCP\Share\IShare $share, $recipient) {
410
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
411
+            // Just update the target
412
+            $qb = $this->dbConn->getQueryBuilder();
413
+            $qb->update('share')
414
+                ->set('file_target', $qb->createNamedParameter($share->getTarget()))
415
+                ->where($qb->expr()->eq('id', $qb->createNamedParameter($share->getId())))
416
+                ->execute();
417
+
418
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
419
+
420
+            // Check if there is a usergroup share
421
+            $qb = $this->dbConn->getQueryBuilder();
422
+            $stmt = $qb->select('id')
423
+                ->from('share')
424
+                ->where($qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP)))
425
+                ->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($recipient)))
426
+                ->andWhere($qb->expr()->eq('parent', $qb->createNamedParameter($share->getId())))
427
+                ->andWhere($qb->expr()->orX(
428
+                    $qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
429
+                    $qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
430
+                ))
431
+                ->setMaxResults(1)
432
+                ->execute();
433
+
434
+            $data = $stmt->fetch();
435
+            $stmt->closeCursor();
436
+
437
+            if ($data === false) {
438
+                // No usergroup share yet. Create one.
439
+                $qb = $this->dbConn->getQueryBuilder();
440
+                $qb->insert('share')
441
+                    ->values([
442
+                        'share_type' => $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP),
443
+                        'share_with' => $qb->createNamedParameter($recipient),
444
+                        'uid_owner' => $qb->createNamedParameter($share->getShareOwner()),
445
+                        'uid_initiator' => $qb->createNamedParameter($share->getSharedBy()),
446
+                        'parent' => $qb->createNamedParameter($share->getId()),
447
+                        'item_type' => $qb->createNamedParameter($share->getNode() instanceof File ? 'file' : 'folder'),
448
+                        'item_source' => $qb->createNamedParameter($share->getNode()->getId()),
449
+                        'file_source' => $qb->createNamedParameter($share->getNode()->getId()),
450
+                        'file_target' => $qb->createNamedParameter($share->getTarget()),
451
+                        'permissions' => $qb->createNamedParameter($share->getPermissions()),
452
+                        'stime' => $qb->createNamedParameter($share->getShareTime()->getTimestamp()),
453
+                    ])->execute();
454
+            } else {
455
+                // Already a usergroup share. Update it.
456
+                $qb = $this->dbConn->getQueryBuilder();
457
+                $qb->update('share')
458
+                    ->set('file_target', $qb->createNamedParameter($share->getTarget()))
459
+                    ->where($qb->expr()->eq('id', $qb->createNamedParameter($data['id'])))
460
+                    ->execute();
461
+            }
462
+        }
463
+
464
+        return $share;
465
+    }
466
+
467
+    public function getSharesInFolder($userId, Folder $node, $reshares) {
468
+        $qb = $this->dbConn->getQueryBuilder();
469
+        $qb->select('*')
470
+            ->from('share', 's')
471
+            ->andWhere($qb->expr()->orX(
472
+                $qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
473
+                $qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
474
+            ));
475
+
476
+        $qb->andWhere($qb->expr()->orX(
477
+            $qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_USER)),
478
+            $qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_GROUP)),
479
+            $qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_LINK))
480
+        ));
481
+
482
+        /**
483
+         * Reshares for this user are shares where they are the owner.
484
+         */
485
+        if ($reshares === false) {
486
+            $qb->andWhere($qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId)));
487
+        } else {
488
+            $qb->andWhere(
489
+                $qb->expr()->orX(
490
+                    $qb->expr()->eq('uid_owner', $qb->createNamedParameter($userId)),
491
+                    $qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId))
492
+                )
493
+            );
494
+        }
495
+
496
+        $qb->innerJoin('s', 'filecache' ,'f', $qb->expr()->eq('s.file_source', 'f.fileid'));
497
+        $qb->andWhere($qb->expr()->eq('f.parent', $qb->createNamedParameter($node->getId())));
498
+
499
+        $qb->orderBy('id');
500
+
501
+        $cursor = $qb->execute();
502
+        $shares = [];
503
+        while ($data = $cursor->fetch()) {
504
+            $shares[$data['fileid']][] = $this->createShare($data);
505
+        }
506
+        $cursor->closeCursor();
507
+
508
+        return $shares;
509
+    }
510
+
511
+    /**
512
+     * @inheritdoc
513
+     */
514
+    public function getSharesBy($userId, $shareType, $node, $reshares, $limit, $offset) {
515
+        $qb = $this->dbConn->getQueryBuilder();
516
+        $qb->select('*')
517
+            ->from('share')
518
+            ->andWhere($qb->expr()->orX(
519
+                $qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
520
+                $qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
521
+            ));
522
+
523
+        $qb->andWhere($qb->expr()->eq('share_type', $qb->createNamedParameter($shareType)));
524
+
525
+        /**
526
+         * Reshares for this user are shares where they are the owner.
527
+         */
528
+        if ($reshares === false) {
529
+            $qb->andWhere($qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId)));
530
+        } else {
531
+            $qb->andWhere(
532
+                $qb->expr()->orX(
533
+                    $qb->expr()->eq('uid_owner', $qb->createNamedParameter($userId)),
534
+                    $qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId))
535
+                )
536
+            );
537
+        }
538
+
539
+        if ($node !== null) {
540
+            $qb->andWhere($qb->expr()->eq('file_source', $qb->createNamedParameter($node->getId())));
541
+        }
542
+
543
+        if ($limit !== -1) {
544
+            $qb->setMaxResults($limit);
545
+        }
546
+
547
+        $qb->setFirstResult($offset);
548
+        $qb->orderBy('id');
549
+
550
+        $cursor = $qb->execute();
551
+        $shares = [];
552
+        while($data = $cursor->fetch()) {
553
+            $shares[] = $this->createShare($data);
554
+        }
555
+        $cursor->closeCursor();
556
+
557
+        return $shares;
558
+    }
559
+
560
+    /**
561
+     * @inheritdoc
562
+     */
563
+    public function getShareById($id, $recipientId = null) {
564
+        $qb = $this->dbConn->getQueryBuilder();
565
+
566
+        $qb->select('*')
567
+            ->from('share')
568
+            ->where($qb->expr()->eq('id', $qb->createNamedParameter($id)))
569
+            ->andWhere(
570
+                $qb->expr()->in(
571
+                    'share_type',
572
+                    $qb->createNamedParameter([
573
+                        \OCP\Share::SHARE_TYPE_USER,
574
+                        \OCP\Share::SHARE_TYPE_GROUP,
575
+                        \OCP\Share::SHARE_TYPE_LINK,
576
+                    ], IQueryBuilder::PARAM_INT_ARRAY)
577
+                )
578
+            )
579
+            ->andWhere($qb->expr()->orX(
580
+                $qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
581
+                $qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
582
+            ));
583
+
584
+        $cursor = $qb->execute();
585
+        $data = $cursor->fetch();
586
+        $cursor->closeCursor();
587
+
588
+        if ($data === false) {
589
+            throw new ShareNotFound();
590
+        }
591
+
592
+        try {
593
+            $share = $this->createShare($data);
594
+        } catch (InvalidShare $e) {
595
+            throw new ShareNotFound();
596
+        }
597
+
598
+        // If the recipient is set for a group share resolve to that user
599
+        if ($recipientId !== null && $share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
600
+            $share = $this->resolveGroupShares([$share], $recipientId)[0];
601
+        }
602
+
603
+        return $share;
604
+    }
605
+
606
+    /**
607
+     * Get shares for a given path
608
+     *
609
+     * @param \OCP\Files\Node $path
610
+     * @return \OCP\Share\IShare[]
611
+     */
612
+    public function getSharesByPath(Node $path) {
613
+        $qb = $this->dbConn->getQueryBuilder();
614
+
615
+        $cursor = $qb->select('*')
616
+            ->from('share')
617
+            ->andWhere($qb->expr()->eq('file_source', $qb->createNamedParameter($path->getId())))
618
+            ->andWhere(
619
+                $qb->expr()->orX(
620
+                    $qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_USER)),
621
+                    $qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_GROUP))
622
+                )
623
+            )
624
+            ->andWhere($qb->expr()->orX(
625
+                $qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
626
+                $qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
627
+            ))
628
+            ->execute();
629
+
630
+        $shares = [];
631
+        while($data = $cursor->fetch()) {
632
+            $shares[] = $this->createShare($data);
633
+        }
634
+        $cursor->closeCursor();
635
+
636
+        return $shares;
637
+    }
638
+
639
+    /**
640
+     * Returns whether the given database result can be interpreted as
641
+     * a share with accessible file (not trashed, not deleted)
642
+     */
643
+    private function isAccessibleResult($data) {
644
+        // exclude shares leading to deleted file entries
645
+        if ($data['fileid'] === null) {
646
+            return false;
647
+        }
648
+
649
+        // exclude shares leading to trashbin on home storages
650
+        $pathSections = explode('/', $data['path'], 2);
651
+        // FIXME: would not detect rare md5'd home storage case properly
652
+        if ($pathSections[0] !== 'files'
653
+                && in_array(explode(':', $data['storage_string_id'], 2)[0], array('home', 'object'))) {
654
+            return false;
655
+        }
656
+        return true;
657
+    }
658
+
659
+    /**
660
+     * @inheritdoc
661
+     */
662
+    public function getSharedWith($userId, $shareType, $node, $limit, $offset) {
663
+        /** @var Share[] $shares */
664
+        $shares = [];
665
+
666
+        if ($shareType === \OCP\Share::SHARE_TYPE_USER) {
667
+            //Get shares directly with this user
668
+            $qb = $this->dbConn->getQueryBuilder();
669
+            $qb->select('s.*',
670
+                'f.fileid', 'f.path', 'f.permissions AS f_permissions', 'f.storage', 'f.path_hash',
671
+                'f.parent AS f_parent', 'f.name', 'f.mimetype', 'f.mimepart', 'f.size', 'f.mtime', 'f.storage_mtime',
672
+                'f.encrypted', 'f.unencrypted_size', 'f.etag', 'f.checksum'
673
+            )
674
+                ->selectAlias('st.id', 'storage_string_id')
675
+                ->from('share', 's')
676
+                ->leftJoin('s', 'filecache', 'f', $qb->expr()->eq('s.file_source', 'f.fileid'))
677
+                ->leftJoin('f', 'storages', 'st', $qb->expr()->eq('f.storage', 'st.numeric_id'));
678
+
679
+            // Order by id
680
+            $qb->orderBy('s.id');
681
+
682
+            // Set limit and offset
683
+            if ($limit !== -1) {
684
+                $qb->setMaxResults($limit);
685
+            }
686
+            $qb->setFirstResult($offset);
687
+
688
+            $qb->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_USER)))
689
+                ->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($userId)))
690
+                ->andWhere($qb->expr()->orX(
691
+                    $qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
692
+                    $qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
693
+                ));
694
+
695
+            // Filter by node if provided
696
+            if ($node !== null) {
697
+                $qb->andWhere($qb->expr()->eq('file_source', $qb->createNamedParameter($node->getId())));
698
+            }
699
+
700
+            $cursor = $qb->execute();
701
+
702
+            while($data = $cursor->fetch()) {
703
+                if ($this->isAccessibleResult($data)) {
704
+                    $shares[] = $this->createShare($data);
705
+                }
706
+            }
707
+            $cursor->closeCursor();
708
+
709
+        } else if ($shareType === \OCP\Share::SHARE_TYPE_GROUP) {
710
+            $user = $this->userManager->get($userId);
711
+            $allGroups = $this->groupManager->getUserGroups($user);
712
+
713
+            /** @var Share[] $shares2 */
714
+            $shares2 = [];
715
+
716
+            $start = 0;
717
+            while(true) {
718
+                $groups = array_slice($allGroups, $start, 100);
719
+                $start += 100;
720
+
721
+                if ($groups === []) {
722
+                    break;
723
+                }
724
+
725
+                $qb = $this->dbConn->getQueryBuilder();
726
+                $qb->select('s.*',
727
+                    'f.fileid', 'f.path', 'f.permissions AS f_permissions', 'f.storage', 'f.path_hash',
728
+                    'f.parent AS f_parent', 'f.name', 'f.mimetype', 'f.mimepart', 'f.size', 'f.mtime', 'f.storage_mtime',
729
+                    'f.encrypted', 'f.unencrypted_size', 'f.etag', 'f.checksum'
730
+                )
731
+                    ->selectAlias('st.id', 'storage_string_id')
732
+                    ->from('share', 's')
733
+                    ->leftJoin('s', 'filecache', 'f', $qb->expr()->eq('s.file_source', 'f.fileid'))
734
+                    ->leftJoin('f', 'storages', 'st', $qb->expr()->eq('f.storage', 'st.numeric_id'))
735
+                    ->orderBy('s.id')
736
+                    ->setFirstResult(0);
737
+
738
+                if ($limit !== -1) {
739
+                    $qb->setMaxResults($limit - count($shares));
740
+                }
741
+
742
+                // Filter by node if provided
743
+                if ($node !== null) {
744
+                    $qb->andWhere($qb->expr()->eq('file_source', $qb->createNamedParameter($node->getId())));
745
+                }
746
+
747
+                $groups = array_map(function(IGroup $group) { return $group->getGID(); }, $groups);
748
+
749
+                $qb->andWhere($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_GROUP)))
750
+                    ->andWhere($qb->expr()->in('share_with', $qb->createNamedParameter(
751
+                        $groups,
752
+                        IQueryBuilder::PARAM_STR_ARRAY
753
+                    )))
754
+                    ->andWhere($qb->expr()->orX(
755
+                        $qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
756
+                        $qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
757
+                    ));
758
+
759
+                $cursor = $qb->execute();
760
+                while($data = $cursor->fetch()) {
761
+                    if ($offset > 0) {
762
+                        $offset--;
763
+                        continue;
764
+                    }
765
+
766
+                    if ($this->isAccessibleResult($data)) {
767
+                        $shares2[] = $this->createShare($data);
768
+                    }
769
+                }
770
+                $cursor->closeCursor();
771
+            }
772
+
773
+            /*
774 774
  			 * Resolve all group shares to user specific shares
775 775
  			 */
776
-			$shares = $this->resolveGroupShares($shares2, $userId);
777
-		} else {
778
-			throw new BackendError('Invalid backend');
779
-		}
780
-
781
-
782
-		return $shares;
783
-	}
784
-
785
-	/**
786
-	 * Get a share by token
787
-	 *
788
-	 * @param string $token
789
-	 * @return \OCP\Share\IShare
790
-	 * @throws ShareNotFound
791
-	 */
792
-	public function getShareByToken($token) {
793
-		$qb = $this->dbConn->getQueryBuilder();
794
-
795
-		$cursor = $qb->select('*')
796
-			->from('share')
797
-			->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_LINK)))
798
-			->andWhere($qb->expr()->eq('token', $qb->createNamedParameter($token)))
799
-			->andWhere($qb->expr()->orX(
800
-				$qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
801
-				$qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
802
-			))
803
-			->execute();
804
-
805
-		$data = $cursor->fetch();
806
-
807
-		if ($data === false) {
808
-			throw new ShareNotFound();
809
-		}
810
-
811
-		try {
812
-			$share = $this->createShare($data);
813
-		} catch (InvalidShare $e) {
814
-			throw new ShareNotFound();
815
-		}
816
-
817
-		return $share;
818
-	}
819
-
820
-	/**
821
-	 * Create a share object from an database row
822
-	 *
823
-	 * @param mixed[] $data
824
-	 * @return \OCP\Share\IShare
825
-	 * @throws InvalidShare
826
-	 */
827
-	private function createShare($data) {
828
-		$share = new Share($this->rootFolder, $this->userManager);
829
-		$share->setId((int)$data['id'])
830
-			->setShareType((int)$data['share_type'])
831
-			->setPermissions((int)$data['permissions'])
832
-			->setTarget($data['file_target'])
833
-			->setMailSend((bool)$data['mail_send']);
834
-
835
-		$shareTime = new \DateTime();
836
-		$shareTime->setTimestamp((int)$data['stime']);
837
-		$share->setShareTime($shareTime);
838
-
839
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
840
-			$share->setSharedWith($data['share_with']);
841
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
842
-			$share->setSharedWith($data['share_with']);
843
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
844
-			$share->setPassword($data['password']);
845
-			$share->setToken($data['token']);
846
-		}
847
-
848
-		$share->setSharedBy($data['uid_initiator']);
849
-		$share->setShareOwner($data['uid_owner']);
850
-
851
-		$share->setNodeId((int)$data['file_source']);
852
-		$share->setNodeType($data['item_type']);
853
-
854
-		if ($data['expiration'] !== null) {
855
-			$expiration = \DateTime::createFromFormat('Y-m-d H:i:s', $data['expiration']);
856
-			$share->setExpirationDate($expiration);
857
-		}
858
-
859
-		if (isset($data['f_permissions'])) {
860
-			$entryData = $data;
861
-			$entryData['permissions'] = $entryData['f_permissions'];
862
-			$entryData['parent'] = $entryData['f_parent'];;
863
-			$share->setNodeCacheEntry(Cache::cacheEntryFromData($entryData,
864
-				\OC::$server->getMimeTypeLoader()));
865
-		}
866
-
867
-		$share->setProviderId($this->identifier());
868
-
869
-		return $share;
870
-	}
871
-
872
-	/**
873
-	 * @param Share[] $shares
874
-	 * @param $userId
875
-	 * @return Share[] The updates shares if no update is found for a share return the original
876
-	 */
877
-	private function resolveGroupShares($shares, $userId) {
878
-		$result = [];
879
-
880
-		$start = 0;
881
-		while(true) {
882
-			/** @var Share[] $shareSlice */
883
-			$shareSlice = array_slice($shares, $start, 100);
884
-			$start += 100;
885
-
886
-			if ($shareSlice === []) {
887
-				break;
888
-			}
889
-
890
-			/** @var int[] $ids */
891
-			$ids = [];
892
-			/** @var Share[] $shareMap */
893
-			$shareMap = [];
894
-
895
-			foreach ($shareSlice as $share) {
896
-				$ids[] = (int)$share->getId();
897
-				$shareMap[$share->getId()] = $share;
898
-			}
899
-
900
-			$qb = $this->dbConn->getQueryBuilder();
901
-
902
-			$query = $qb->select('*')
903
-				->from('share')
904
-				->where($qb->expr()->in('parent', $qb->createNamedParameter($ids, IQueryBuilder::PARAM_INT_ARRAY)))
905
-				->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($userId)))
906
-				->andWhere($qb->expr()->orX(
907
-					$qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
908
-					$qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
909
-				));
910
-
911
-			$stmt = $query->execute();
912
-
913
-			while($data = $stmt->fetch()) {
914
-				$shareMap[$data['parent']]->setPermissions((int)$data['permissions']);
915
-				$shareMap[$data['parent']]->setTarget($data['file_target']);
916
-			}
917
-
918
-			$stmt->closeCursor();
919
-
920
-			foreach ($shareMap as $share) {
921
-				$result[] = $share;
922
-			}
923
-		}
924
-
925
-		return $result;
926
-	}
927
-
928
-	/**
929
-	 * A user is deleted from the system
930
-	 * So clean up the relevant shares.
931
-	 *
932
-	 * @param string $uid
933
-	 * @param int $shareType
934
-	 */
935
-	public function userDeleted($uid, $shareType) {
936
-		$qb = $this->dbConn->getQueryBuilder();
937
-
938
-		$qb->delete('share');
939
-
940
-		if ($shareType === \OCP\Share::SHARE_TYPE_USER) {
941
-			/*
776
+            $shares = $this->resolveGroupShares($shares2, $userId);
777
+        } else {
778
+            throw new BackendError('Invalid backend');
779
+        }
780
+
781
+
782
+        return $shares;
783
+    }
784
+
785
+    /**
786
+     * Get a share by token
787
+     *
788
+     * @param string $token
789
+     * @return \OCP\Share\IShare
790
+     * @throws ShareNotFound
791
+     */
792
+    public function getShareByToken($token) {
793
+        $qb = $this->dbConn->getQueryBuilder();
794
+
795
+        $cursor = $qb->select('*')
796
+            ->from('share')
797
+            ->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_LINK)))
798
+            ->andWhere($qb->expr()->eq('token', $qb->createNamedParameter($token)))
799
+            ->andWhere($qb->expr()->orX(
800
+                $qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
801
+                $qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
802
+            ))
803
+            ->execute();
804
+
805
+        $data = $cursor->fetch();
806
+
807
+        if ($data === false) {
808
+            throw new ShareNotFound();
809
+        }
810
+
811
+        try {
812
+            $share = $this->createShare($data);
813
+        } catch (InvalidShare $e) {
814
+            throw new ShareNotFound();
815
+        }
816
+
817
+        return $share;
818
+    }
819
+
820
+    /**
821
+     * Create a share object from an database row
822
+     *
823
+     * @param mixed[] $data
824
+     * @return \OCP\Share\IShare
825
+     * @throws InvalidShare
826
+     */
827
+    private function createShare($data) {
828
+        $share = new Share($this->rootFolder, $this->userManager);
829
+        $share->setId((int)$data['id'])
830
+            ->setShareType((int)$data['share_type'])
831
+            ->setPermissions((int)$data['permissions'])
832
+            ->setTarget($data['file_target'])
833
+            ->setMailSend((bool)$data['mail_send']);
834
+
835
+        $shareTime = new \DateTime();
836
+        $shareTime->setTimestamp((int)$data['stime']);
837
+        $share->setShareTime($shareTime);
838
+
839
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
840
+            $share->setSharedWith($data['share_with']);
841
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
842
+            $share->setSharedWith($data['share_with']);
843
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
844
+            $share->setPassword($data['password']);
845
+            $share->setToken($data['token']);
846
+        }
847
+
848
+        $share->setSharedBy($data['uid_initiator']);
849
+        $share->setShareOwner($data['uid_owner']);
850
+
851
+        $share->setNodeId((int)$data['file_source']);
852
+        $share->setNodeType($data['item_type']);
853
+
854
+        if ($data['expiration'] !== null) {
855
+            $expiration = \DateTime::createFromFormat('Y-m-d H:i:s', $data['expiration']);
856
+            $share->setExpirationDate($expiration);
857
+        }
858
+
859
+        if (isset($data['f_permissions'])) {
860
+            $entryData = $data;
861
+            $entryData['permissions'] = $entryData['f_permissions'];
862
+            $entryData['parent'] = $entryData['f_parent'];;
863
+            $share->setNodeCacheEntry(Cache::cacheEntryFromData($entryData,
864
+                \OC::$server->getMimeTypeLoader()));
865
+        }
866
+
867
+        $share->setProviderId($this->identifier());
868
+
869
+        return $share;
870
+    }
871
+
872
+    /**
873
+     * @param Share[] $shares
874
+     * @param $userId
875
+     * @return Share[] The updates shares if no update is found for a share return the original
876
+     */
877
+    private function resolveGroupShares($shares, $userId) {
878
+        $result = [];
879
+
880
+        $start = 0;
881
+        while(true) {
882
+            /** @var Share[] $shareSlice */
883
+            $shareSlice = array_slice($shares, $start, 100);
884
+            $start += 100;
885
+
886
+            if ($shareSlice === []) {
887
+                break;
888
+            }
889
+
890
+            /** @var int[] $ids */
891
+            $ids = [];
892
+            /** @var Share[] $shareMap */
893
+            $shareMap = [];
894
+
895
+            foreach ($shareSlice as $share) {
896
+                $ids[] = (int)$share->getId();
897
+                $shareMap[$share->getId()] = $share;
898
+            }
899
+
900
+            $qb = $this->dbConn->getQueryBuilder();
901
+
902
+            $query = $qb->select('*')
903
+                ->from('share')
904
+                ->where($qb->expr()->in('parent', $qb->createNamedParameter($ids, IQueryBuilder::PARAM_INT_ARRAY)))
905
+                ->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($userId)))
906
+                ->andWhere($qb->expr()->orX(
907
+                    $qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
908
+                    $qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
909
+                ));
910
+
911
+            $stmt = $query->execute();
912
+
913
+            while($data = $stmt->fetch()) {
914
+                $shareMap[$data['parent']]->setPermissions((int)$data['permissions']);
915
+                $shareMap[$data['parent']]->setTarget($data['file_target']);
916
+            }
917
+
918
+            $stmt->closeCursor();
919
+
920
+            foreach ($shareMap as $share) {
921
+                $result[] = $share;
922
+            }
923
+        }
924
+
925
+        return $result;
926
+    }
927
+
928
+    /**
929
+     * A user is deleted from the system
930
+     * So clean up the relevant shares.
931
+     *
932
+     * @param string $uid
933
+     * @param int $shareType
934
+     */
935
+    public function userDeleted($uid, $shareType) {
936
+        $qb = $this->dbConn->getQueryBuilder();
937
+
938
+        $qb->delete('share');
939
+
940
+        if ($shareType === \OCP\Share::SHARE_TYPE_USER) {
941
+            /*
942 942
 			 * Delete all user shares that are owned by this user
943 943
 			 * or that are received by this user
944 944
 			 */
945 945
 
946
-			$qb->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_USER)));
946
+            $qb->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_USER)));
947 947
 
948
-			$qb->andWhere(
949
-				$qb->expr()->orX(
950
-					$qb->expr()->eq('uid_owner', $qb->createNamedParameter($uid)),
951
-					$qb->expr()->eq('share_with', $qb->createNamedParameter($uid))
952
-				)
953
-			);
954
-		} else if ($shareType === \OCP\Share::SHARE_TYPE_GROUP) {
955
-			/*
948
+            $qb->andWhere(
949
+                $qb->expr()->orX(
950
+                    $qb->expr()->eq('uid_owner', $qb->createNamedParameter($uid)),
951
+                    $qb->expr()->eq('share_with', $qb->createNamedParameter($uid))
952
+                )
953
+            );
954
+        } else if ($shareType === \OCP\Share::SHARE_TYPE_GROUP) {
955
+            /*
956 956
 			 * Delete all group shares that are owned by this user
957 957
 			 * Or special user group shares that are received by this user
958 958
 			 */
959
-			$qb->where(
960
-				$qb->expr()->andX(
961
-					$qb->expr()->orX(
962
-						$qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_GROUP)),
963
-						$qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP))
964
-					),
965
-					$qb->expr()->eq('uid_owner', $qb->createNamedParameter($uid))
966
-				)
967
-			);
968
-
969
-			$qb->orWhere(
970
-				$qb->expr()->andX(
971
-					$qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP)),
972
-					$qb->expr()->eq('share_with', $qb->createNamedParameter($uid))
973
-				)
974
-			);
975
-		} else if ($shareType === \OCP\Share::SHARE_TYPE_LINK) {
976
-			/*
959
+            $qb->where(
960
+                $qb->expr()->andX(
961
+                    $qb->expr()->orX(
962
+                        $qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_GROUP)),
963
+                        $qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP))
964
+                    ),
965
+                    $qb->expr()->eq('uid_owner', $qb->createNamedParameter($uid))
966
+                )
967
+            );
968
+
969
+            $qb->orWhere(
970
+                $qb->expr()->andX(
971
+                    $qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP)),
972
+                    $qb->expr()->eq('share_with', $qb->createNamedParameter($uid))
973
+                )
974
+            );
975
+        } else if ($shareType === \OCP\Share::SHARE_TYPE_LINK) {
976
+            /*
977 977
 			 * Delete all link shares owned by this user.
978 978
 			 * And all link shares initiated by this user (until #22327 is in)
979 979
 			 */
980
-			$qb->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_LINK)));
981
-
982
-			$qb->andWhere(
983
-				$qb->expr()->orX(
984
-					$qb->expr()->eq('uid_owner', $qb->createNamedParameter($uid)),
985
-					$qb->expr()->eq('uid_initiator', $qb->createNamedParameter($uid))
986
-				)
987
-			);
988
-		}
989
-
990
-		$qb->execute();
991
-	}
992
-
993
-	/**
994
-	 * Delete all shares received by this group. As well as any custom group
995
-	 * shares for group members.
996
-	 *
997
-	 * @param string $gid
998
-	 */
999
-	public function groupDeleted($gid) {
1000
-		/*
980
+            $qb->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_LINK)));
981
+
982
+            $qb->andWhere(
983
+                $qb->expr()->orX(
984
+                    $qb->expr()->eq('uid_owner', $qb->createNamedParameter($uid)),
985
+                    $qb->expr()->eq('uid_initiator', $qb->createNamedParameter($uid))
986
+                )
987
+            );
988
+        }
989
+
990
+        $qb->execute();
991
+    }
992
+
993
+    /**
994
+     * Delete all shares received by this group. As well as any custom group
995
+     * shares for group members.
996
+     *
997
+     * @param string $gid
998
+     */
999
+    public function groupDeleted($gid) {
1000
+        /*
1001 1001
 		 * First delete all custom group shares for group members
1002 1002
 		 */
1003
-		$qb = $this->dbConn->getQueryBuilder();
1004
-		$qb->select('id')
1005
-			->from('share')
1006
-			->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_GROUP)))
1007
-			->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($gid)));
1008
-
1009
-		$cursor = $qb->execute();
1010
-		$ids = [];
1011
-		while($row = $cursor->fetch()) {
1012
-			$ids[] = (int)$row['id'];
1013
-		}
1014
-		$cursor->closeCursor();
1015
-
1016
-		if (!empty($ids)) {
1017
-			$chunks = array_chunk($ids, 100);
1018
-			foreach ($chunks as $chunk) {
1019
-				$qb->delete('share')
1020
-					->where($qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP)))
1021
-					->andWhere($qb->expr()->in('parent', $qb->createNamedParameter($chunk, IQueryBuilder::PARAM_INT_ARRAY)));
1022
-				$qb->execute();
1023
-			}
1024
-		}
1025
-
1026
-		/*
1003
+        $qb = $this->dbConn->getQueryBuilder();
1004
+        $qb->select('id')
1005
+            ->from('share')
1006
+            ->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_GROUP)))
1007
+            ->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($gid)));
1008
+
1009
+        $cursor = $qb->execute();
1010
+        $ids = [];
1011
+        while($row = $cursor->fetch()) {
1012
+            $ids[] = (int)$row['id'];
1013
+        }
1014
+        $cursor->closeCursor();
1015
+
1016
+        if (!empty($ids)) {
1017
+            $chunks = array_chunk($ids, 100);
1018
+            foreach ($chunks as $chunk) {
1019
+                $qb->delete('share')
1020
+                    ->where($qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP)))
1021
+                    ->andWhere($qb->expr()->in('parent', $qb->createNamedParameter($chunk, IQueryBuilder::PARAM_INT_ARRAY)));
1022
+                $qb->execute();
1023
+            }
1024
+        }
1025
+
1026
+        /*
1027 1027
 		 * Now delete all the group shares
1028 1028
 		 */
1029
-		$qb = $this->dbConn->getQueryBuilder();
1030
-		$qb->delete('share')
1031
-			->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_GROUP)))
1032
-			->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($gid)));
1033
-		$qb->execute();
1034
-	}
1035
-
1036
-	/**
1037
-	 * Delete custom group shares to this group for this user
1038
-	 *
1039
-	 * @param string $uid
1040
-	 * @param string $gid
1041
-	 */
1042
-	public function userDeletedFromGroup($uid, $gid) {
1043
-		/*
1029
+        $qb = $this->dbConn->getQueryBuilder();
1030
+        $qb->delete('share')
1031
+            ->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_GROUP)))
1032
+            ->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($gid)));
1033
+        $qb->execute();
1034
+    }
1035
+
1036
+    /**
1037
+     * Delete custom group shares to this group for this user
1038
+     *
1039
+     * @param string $uid
1040
+     * @param string $gid
1041
+     */
1042
+    public function userDeletedFromGroup($uid, $gid) {
1043
+        /*
1044 1044
 		 * Get all group shares
1045 1045
 		 */
1046
-		$qb = $this->dbConn->getQueryBuilder();
1047
-		$qb->select('id')
1048
-			->from('share')
1049
-			->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_GROUP)))
1050
-			->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($gid)));
1051
-
1052
-		$cursor = $qb->execute();
1053
-		$ids = [];
1054
-		while($row = $cursor->fetch()) {
1055
-			$ids[] = (int)$row['id'];
1056
-		}
1057
-		$cursor->closeCursor();
1058
-
1059
-		if (!empty($ids)) {
1060
-			$chunks = array_chunk($ids, 100);
1061
-			foreach ($chunks as $chunk) {
1062
-				/*
1046
+        $qb = $this->dbConn->getQueryBuilder();
1047
+        $qb->select('id')
1048
+            ->from('share')
1049
+            ->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_GROUP)))
1050
+            ->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($gid)));
1051
+
1052
+        $cursor = $qb->execute();
1053
+        $ids = [];
1054
+        while($row = $cursor->fetch()) {
1055
+            $ids[] = (int)$row['id'];
1056
+        }
1057
+        $cursor->closeCursor();
1058
+
1059
+        if (!empty($ids)) {
1060
+            $chunks = array_chunk($ids, 100);
1061
+            foreach ($chunks as $chunk) {
1062
+                /*
1063 1063
 				 * Delete all special shares wit this users for the found group shares
1064 1064
 				 */
1065
-				$qb->delete('share')
1066
-					->where($qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP)))
1067
-					->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($uid)))
1068
-					->andWhere($qb->expr()->in('parent', $qb->createNamedParameter($chunk, IQueryBuilder::PARAM_INT_ARRAY)));
1069
-				$qb->execute();
1070
-			}
1071
-		}
1072
-	}
1073
-
1074
-	/**
1075
-	 * @inheritdoc
1076
-	 */
1077
-	public function getAccessList($nodes, $currentAccess) {
1078
-		$ids = [];
1079
-		foreach ($nodes as $node) {
1080
-			$ids[] = $node->getId();
1081
-		}
1082
-
1083
-		$qb = $this->dbConn->getQueryBuilder();
1084
-
1085
-		$or = $qb->expr()->orX(
1086
-			$qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_USER)),
1087
-			$qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_GROUP)),
1088
-			$qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_LINK))
1089
-		);
1090
-
1091
-		if ($currentAccess) {
1092
-			$or->add($qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP)));
1093
-		}
1094
-
1095
-		$qb->select('id', 'parent', 'share_type', 'share_with', 'file_source', 'file_target', 'permissions')
1096
-			->from('share')
1097
-			->where(
1098
-				$or
1099
-			)
1100
-			->andWhere($qb->expr()->in('file_source', $qb->createNamedParameter($ids, IQueryBuilder::PARAM_INT_ARRAY)))
1101
-			->andWhere($qb->expr()->orX(
1102
-				$qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
1103
-				$qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
1104
-			));
1105
-		$cursor = $qb->execute();
1106
-
1107
-		$users = [];
1108
-		$link = false;
1109
-		while($row = $cursor->fetch()) {
1110
-			$type = (int)$row['share_type'];
1111
-			if ($type === \OCP\Share::SHARE_TYPE_USER) {
1112
-				$uid = $row['share_with'];
1113
-				$users[$uid] = isset($users[$uid]) ? $users[$uid] : [];
1114
-				$users[$uid][$row['id']] = $row;
1115
-			} else if ($type === \OCP\Share::SHARE_TYPE_GROUP) {
1116
-				$gid = $row['share_with'];
1117
-				$group = $this->groupManager->get($gid);
1118
-
1119
-				if ($gid === null) {
1120
-					continue;
1121
-				}
1122
-
1123
-				$userList = $group->getUsers();
1124
-				foreach ($userList as $user) {
1125
-					$uid = $user->getUID();
1126
-					$users[$uid] = isset($users[$uid]) ? $users[$uid] : [];
1127
-					$users[$uid][$row['id']] = $row;
1128
-				}
1129
-			} else if ($type === \OCP\Share::SHARE_TYPE_LINK) {
1130
-				$link = true;
1131
-			} else if ($type === self::SHARE_TYPE_USERGROUP && $currentAccess === true) {
1132
-				$uid = $row['share_with'];
1133
-				$users[$uid] = isset($users[$uid]) ? $users[$uid] : [];
1134
-				$users[$uid][$row['id']] = $row;
1135
-			}
1136
-		}
1137
-		$cursor->closeCursor();
1138
-
1139
-		if ($currentAccess === true) {
1140
-			$users = array_map([$this, 'filterSharesOfUser'], $users);
1141
-			$users = array_filter($users);
1142
-		} else {
1143
-			$users = array_keys($users);
1144
-		}
1145
-
1146
-		return ['users' => $users, 'public' => $link];
1147
-	}
1148
-
1149
-	/**
1150
-	 * For each user the path with the fewest slashes is returned
1151
-	 * @param array $shares
1152
-	 * @return array
1153
-	 */
1154
-	protected function filterSharesOfUser(array $shares) {
1155
-		// Group shares when the user has a share exception
1156
-		foreach ($shares as $id => $share) {
1157
-			$type = (int) $share['share_type'];
1158
-			$permissions = (int) $share['permissions'];
1159
-
1160
-			if ($type === self::SHARE_TYPE_USERGROUP) {
1161
-				unset($shares[$share['parent']]);
1162
-
1163
-				if ($permissions === 0) {
1164
-					unset($shares[$id]);
1165
-				}
1166
-			}
1167
-		}
1168
-
1169
-		$best = [];
1170
-		$bestDepth = 0;
1171
-		foreach ($shares as $id => $share) {
1172
-			$depth = substr_count($share['file_target'], '/');
1173
-			if (empty($best) || $depth < $bestDepth) {
1174
-				$bestDepth = $depth;
1175
-				$best = [
1176
-					'node_id' => $share['file_source'],
1177
-					'node_path' => $share['file_target'],
1178
-				];
1179
-			}
1180
-		}
1181
-
1182
-		return $best;
1183
-	}
1065
+                $qb->delete('share')
1066
+                    ->where($qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP)))
1067
+                    ->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($uid)))
1068
+                    ->andWhere($qb->expr()->in('parent', $qb->createNamedParameter($chunk, IQueryBuilder::PARAM_INT_ARRAY)));
1069
+                $qb->execute();
1070
+            }
1071
+        }
1072
+    }
1073
+
1074
+    /**
1075
+     * @inheritdoc
1076
+     */
1077
+    public function getAccessList($nodes, $currentAccess) {
1078
+        $ids = [];
1079
+        foreach ($nodes as $node) {
1080
+            $ids[] = $node->getId();
1081
+        }
1082
+
1083
+        $qb = $this->dbConn->getQueryBuilder();
1084
+
1085
+        $or = $qb->expr()->orX(
1086
+            $qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_USER)),
1087
+            $qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_GROUP)),
1088
+            $qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_LINK))
1089
+        );
1090
+
1091
+        if ($currentAccess) {
1092
+            $or->add($qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP)));
1093
+        }
1094
+
1095
+        $qb->select('id', 'parent', 'share_type', 'share_with', 'file_source', 'file_target', 'permissions')
1096
+            ->from('share')
1097
+            ->where(
1098
+                $or
1099
+            )
1100
+            ->andWhere($qb->expr()->in('file_source', $qb->createNamedParameter($ids, IQueryBuilder::PARAM_INT_ARRAY)))
1101
+            ->andWhere($qb->expr()->orX(
1102
+                $qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
1103
+                $qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
1104
+            ));
1105
+        $cursor = $qb->execute();
1106
+
1107
+        $users = [];
1108
+        $link = false;
1109
+        while($row = $cursor->fetch()) {
1110
+            $type = (int)$row['share_type'];
1111
+            if ($type === \OCP\Share::SHARE_TYPE_USER) {
1112
+                $uid = $row['share_with'];
1113
+                $users[$uid] = isset($users[$uid]) ? $users[$uid] : [];
1114
+                $users[$uid][$row['id']] = $row;
1115
+            } else if ($type === \OCP\Share::SHARE_TYPE_GROUP) {
1116
+                $gid = $row['share_with'];
1117
+                $group = $this->groupManager->get($gid);
1118
+
1119
+                if ($gid === null) {
1120
+                    continue;
1121
+                }
1122
+
1123
+                $userList = $group->getUsers();
1124
+                foreach ($userList as $user) {
1125
+                    $uid = $user->getUID();
1126
+                    $users[$uid] = isset($users[$uid]) ? $users[$uid] : [];
1127
+                    $users[$uid][$row['id']] = $row;
1128
+                }
1129
+            } else if ($type === \OCP\Share::SHARE_TYPE_LINK) {
1130
+                $link = true;
1131
+            } else if ($type === self::SHARE_TYPE_USERGROUP && $currentAccess === true) {
1132
+                $uid = $row['share_with'];
1133
+                $users[$uid] = isset($users[$uid]) ? $users[$uid] : [];
1134
+                $users[$uid][$row['id']] = $row;
1135
+            }
1136
+        }
1137
+        $cursor->closeCursor();
1138
+
1139
+        if ($currentAccess === true) {
1140
+            $users = array_map([$this, 'filterSharesOfUser'], $users);
1141
+            $users = array_filter($users);
1142
+        } else {
1143
+            $users = array_keys($users);
1144
+        }
1145
+
1146
+        return ['users' => $users, 'public' => $link];
1147
+    }
1148
+
1149
+    /**
1150
+     * For each user the path with the fewest slashes is returned
1151
+     * @param array $shares
1152
+     * @return array
1153
+     */
1154
+    protected function filterSharesOfUser(array $shares) {
1155
+        // Group shares when the user has a share exception
1156
+        foreach ($shares as $id => $share) {
1157
+            $type = (int) $share['share_type'];
1158
+            $permissions = (int) $share['permissions'];
1159
+
1160
+            if ($type === self::SHARE_TYPE_USERGROUP) {
1161
+                unset($shares[$share['parent']]);
1162
+
1163
+                if ($permissions === 0) {
1164
+                    unset($shares[$id]);
1165
+                }
1166
+            }
1167
+        }
1168
+
1169
+        $best = [];
1170
+        $bestDepth = 0;
1171
+        foreach ($shares as $id => $share) {
1172
+            $depth = substr_count($share['file_target'], '/');
1173
+            if (empty($best) || $depth < $bestDepth) {
1174
+                $bestDepth = $depth;
1175
+                $best = [
1176
+                    'node_id' => $share['file_source'],
1177
+                    'node_path' => $share['file_target'],
1178
+                ];
1179
+            }
1180
+        }
1181
+
1182
+        return $best;
1183
+    }
1184 1184
 }
Please login to merge, or discard this patch.
Spacing   +25 added lines, -25 removed lines patch added patch discarded remove patch
@@ -288,7 +288,7 @@  discard block
 block discarded – undo
288 288
 			->orderBy('id');
289 289
 
290 290
 		$cursor = $qb->execute();
291
-		while($data = $cursor->fetch()) {
291
+		while ($data = $cursor->fetch()) {
292 292
 			$children[] = $this->createShare($data);
293 293
 		}
294 294
 		$cursor->closeCursor();
@@ -333,7 +333,7 @@  discard block
 block discarded – undo
333 333
 			$user = $this->userManager->get($recipient);
334 334
 
335 335
 			if (is_null($group)) {
336
-				throw new ProviderException('Group "' . $share->getSharedWith() . '" does not exist');
336
+				throw new ProviderException('Group "'.$share->getSharedWith().'" does not exist');
337 337
 			}
338 338
 
339 339
 			if (!$group->inGroup($user)) {
@@ -493,7 +493,7 @@  discard block
 block discarded – undo
493 493
 			);
494 494
 		}
495 495
 
496
-		$qb->innerJoin('s', 'filecache' ,'f', $qb->expr()->eq('s.file_source', 'f.fileid'));
496
+		$qb->innerJoin('s', 'filecache', 'f', $qb->expr()->eq('s.file_source', 'f.fileid'));
497 497
 		$qb->andWhere($qb->expr()->eq('f.parent', $qb->createNamedParameter($node->getId())));
498 498
 
499 499
 		$qb->orderBy('id');
@@ -549,7 +549,7 @@  discard block
 block discarded – undo
549 549
 
550 550
 		$cursor = $qb->execute();
551 551
 		$shares = [];
552
-		while($data = $cursor->fetch()) {
552
+		while ($data = $cursor->fetch()) {
553 553
 			$shares[] = $this->createShare($data);
554 554
 		}
555 555
 		$cursor->closeCursor();
@@ -628,7 +628,7 @@  discard block
 block discarded – undo
628 628
 			->execute();
629 629
 
630 630
 		$shares = [];
631
-		while($data = $cursor->fetch()) {
631
+		while ($data = $cursor->fetch()) {
632 632
 			$shares[] = $this->createShare($data);
633 633
 		}
634 634
 		$cursor->closeCursor();
@@ -699,7 +699,7 @@  discard block
 block discarded – undo
699 699
 
700 700
 			$cursor = $qb->execute();
701 701
 
702
-			while($data = $cursor->fetch()) {
702
+			while ($data = $cursor->fetch()) {
703 703
 				if ($this->isAccessibleResult($data)) {
704 704
 					$shares[] = $this->createShare($data);
705 705
 				}
@@ -714,7 +714,7 @@  discard block
 block discarded – undo
714 714
 			$shares2 = [];
715 715
 
716 716
 			$start = 0;
717
-			while(true) {
717
+			while (true) {
718 718
 				$groups = array_slice($allGroups, $start, 100);
719 719
 				$start += 100;
720 720
 
@@ -757,7 +757,7 @@  discard block
 block discarded – undo
757 757
 					));
758 758
 
759 759
 				$cursor = $qb->execute();
760
-				while($data = $cursor->fetch()) {
760
+				while ($data = $cursor->fetch()) {
761 761
 					if ($offset > 0) {
762 762
 						$offset--;
763 763
 						continue;
@@ -826,14 +826,14 @@  discard block
 block discarded – undo
826 826
 	 */
827 827
 	private function createShare($data) {
828 828
 		$share = new Share($this->rootFolder, $this->userManager);
829
-		$share->setId((int)$data['id'])
830
-			->setShareType((int)$data['share_type'])
831
-			->setPermissions((int)$data['permissions'])
829
+		$share->setId((int) $data['id'])
830
+			->setShareType((int) $data['share_type'])
831
+			->setPermissions((int) $data['permissions'])
832 832
 			->setTarget($data['file_target'])
833
-			->setMailSend((bool)$data['mail_send']);
833
+			->setMailSend((bool) $data['mail_send']);
834 834
 
835 835
 		$shareTime = new \DateTime();
836
-		$shareTime->setTimestamp((int)$data['stime']);
836
+		$shareTime->setTimestamp((int) $data['stime']);
837 837
 		$share->setShareTime($shareTime);
838 838
 
839 839
 		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
@@ -848,7 +848,7 @@  discard block
 block discarded – undo
848 848
 		$share->setSharedBy($data['uid_initiator']);
849 849
 		$share->setShareOwner($data['uid_owner']);
850 850
 
851
-		$share->setNodeId((int)$data['file_source']);
851
+		$share->setNodeId((int) $data['file_source']);
852 852
 		$share->setNodeType($data['item_type']);
853 853
 
854 854
 		if ($data['expiration'] !== null) {
@@ -859,7 +859,7 @@  discard block
 block discarded – undo
859 859
 		if (isset($data['f_permissions'])) {
860 860
 			$entryData = $data;
861 861
 			$entryData['permissions'] = $entryData['f_permissions'];
862
-			$entryData['parent'] = $entryData['f_parent'];;
862
+			$entryData['parent'] = $entryData['f_parent']; ;
863 863
 			$share->setNodeCacheEntry(Cache::cacheEntryFromData($entryData,
864 864
 				\OC::$server->getMimeTypeLoader()));
865 865
 		}
@@ -878,7 +878,7 @@  discard block
 block discarded – undo
878 878
 		$result = [];
879 879
 
880 880
 		$start = 0;
881
-		while(true) {
881
+		while (true) {
882 882
 			/** @var Share[] $shareSlice */
883 883
 			$shareSlice = array_slice($shares, $start, 100);
884 884
 			$start += 100;
@@ -893,7 +893,7 @@  discard block
 block discarded – undo
893 893
 			$shareMap = [];
894 894
 
895 895
 			foreach ($shareSlice as $share) {
896
-				$ids[] = (int)$share->getId();
896
+				$ids[] = (int) $share->getId();
897 897
 				$shareMap[$share->getId()] = $share;
898 898
 			}
899 899
 
@@ -910,8 +910,8 @@  discard block
 block discarded – undo
910 910
 
911 911
 			$stmt = $query->execute();
912 912
 
913
-			while($data = $stmt->fetch()) {
914
-				$shareMap[$data['parent']]->setPermissions((int)$data['permissions']);
913
+			while ($data = $stmt->fetch()) {
914
+				$shareMap[$data['parent']]->setPermissions((int) $data['permissions']);
915 915
 				$shareMap[$data['parent']]->setTarget($data['file_target']);
916 916
 			}
917 917
 
@@ -1008,8 +1008,8 @@  discard block
 block discarded – undo
1008 1008
 
1009 1009
 		$cursor = $qb->execute();
1010 1010
 		$ids = [];
1011
-		while($row = $cursor->fetch()) {
1012
-			$ids[] = (int)$row['id'];
1011
+		while ($row = $cursor->fetch()) {
1012
+			$ids[] = (int) $row['id'];
1013 1013
 		}
1014 1014
 		$cursor->closeCursor();
1015 1015
 
@@ -1051,8 +1051,8 @@  discard block
 block discarded – undo
1051 1051
 
1052 1052
 		$cursor = $qb->execute();
1053 1053
 		$ids = [];
1054
-		while($row = $cursor->fetch()) {
1055
-			$ids[] = (int)$row['id'];
1054
+		while ($row = $cursor->fetch()) {
1055
+			$ids[] = (int) $row['id'];
1056 1056
 		}
1057 1057
 		$cursor->closeCursor();
1058 1058
 
@@ -1106,8 +1106,8 @@  discard block
 block discarded – undo
1106 1106
 
1107 1107
 		$users = [];
1108 1108
 		$link = false;
1109
-		while($row = $cursor->fetch()) {
1110
-			$type = (int)$row['share_type'];
1109
+		while ($row = $cursor->fetch()) {
1110
+			$type = (int) $row['share_type'];
1111 1111
 			if ($type === \OCP\Share::SHARE_TYPE_USER) {
1112 1112
 				$uid = $row['share_with'];
1113 1113
 				$users[$uid] = isset($users[$uid]) ? $users[$uid] : [];
Please login to merge, or discard this patch.