Completed
Pull Request — master (#4303)
by Björn
25:54 queued 20s
created
lib/private/AppFramework/Routing/RouteConfig.php 1 patch
Indentation   +236 added lines, -236 removed lines patch added patch discarded remove patch
@@ -36,242 +36,242 @@
 block discarded – undo
36 36
  * @package OC\AppFramework\routing
37 37
  */
38 38
 class RouteConfig {
39
-	/** @var DIContainer */
40
-	private $container;
41
-
42
-	/** @var IRouter */
43
-	private $router;
44
-
45
-	/** @var array */
46
-	private $routes;
47
-
48
-	/** @var string */
49
-	private $appName;
50
-
51
-	/** @var string[] */
52
-	private $controllerNameCache = [];
53
-
54
-	/**
55
-	 * @param \OC\AppFramework\DependencyInjection\DIContainer $container
56
-	 * @param \OCP\Route\IRouter $router
57
-	 * @param array $routes
58
-	 * @internal param $appName
59
-	 */
60
-	public function __construct(DIContainer $container, IRouter $router, $routes) {
61
-		$this->routes = $routes;
62
-		$this->container = $container;
63
-		$this->router = $router;
64
-		$this->appName = $container['AppName'];
65
-	}
66
-
67
-	/**
68
-	 * The routes and resource will be registered to the \OCP\Route\IRouter
69
-	 */
70
-	public function register() {
71
-
72
-		// parse simple
73
-		$this->processSimpleRoutes($this->routes);
74
-
75
-		// parse resources
76
-		$this->processResources($this->routes);
77
-
78
-		/*
39
+    /** @var DIContainer */
40
+    private $container;
41
+
42
+    /** @var IRouter */
43
+    private $router;
44
+
45
+    /** @var array */
46
+    private $routes;
47
+
48
+    /** @var string */
49
+    private $appName;
50
+
51
+    /** @var string[] */
52
+    private $controllerNameCache = [];
53
+
54
+    /**
55
+     * @param \OC\AppFramework\DependencyInjection\DIContainer $container
56
+     * @param \OCP\Route\IRouter $router
57
+     * @param array $routes
58
+     * @internal param $appName
59
+     */
60
+    public function __construct(DIContainer $container, IRouter $router, $routes) {
61
+        $this->routes = $routes;
62
+        $this->container = $container;
63
+        $this->router = $router;
64
+        $this->appName = $container['AppName'];
65
+    }
66
+
67
+    /**
68
+     * The routes and resource will be registered to the \OCP\Route\IRouter
69
+     */
70
+    public function register() {
71
+
72
+        // parse simple
73
+        $this->processSimpleRoutes($this->routes);
74
+
75
+        // parse resources
76
+        $this->processResources($this->routes);
77
+
78
+        /*
79 79
 		 * OCS routes go into a different collection
80 80
 		 */
81
-		$oldCollection = $this->router->getCurrentCollection();
82
-		$this->router->useCollection($oldCollection.'.ocs');
83
-
84
-		// parse ocs simple routes
85
-		$this->processOCS($this->routes);
86
-
87
-		$this->router->useCollection($oldCollection);
88
-	}
89
-
90
-	private function processOCS(array $routes) {
91
-		$ocsRoutes = isset($routes['ocs']) ? $routes['ocs'] : [];
92
-		foreach ($ocsRoutes as $ocsRoute) {
93
-			$name = $ocsRoute['name'];
94
-			$postfix = '';
95
-
96
-			if (isset($ocsRoute['postfix'])) {
97
-				$postfix = $ocsRoute['postfix'];
98
-			}
99
-
100
-			if (isset($ocsRoute['root'])) {
101
-				$root = $ocsRoute['root'];
102
-			} else {
103
-				$root = '/apps/'.$this->appName;
104
-			}
105
-
106
-			$url = $root . $ocsRoute['url'];
107
-			$verb = isset($ocsRoute['verb']) ? strtoupper($ocsRoute['verb']) : 'GET';
108
-
109
-			$split = explode('#', $name, 2);
110
-			if (count($split) != 2) {
111
-				throw new \UnexpectedValueException('Invalid route name');
112
-			}
113
-			$controller = $split[0];
114
-			$action = $split[1];
115
-
116
-			$controllerName = $this->buildControllerName($controller);
117
-			$actionName = $this->buildActionName($action);
118
-
119
-			// register the route
120
-			$handler = new RouteActionHandler($this->container, $controllerName, $actionName);
121
-
122
-			$router = $this->router->create('ocs.'.$this->appName.'.'.$controller.'.'.$action . $postfix, $url)
123
-				->method($verb)
124
-				->action($handler);
125
-
126
-			// optionally register requirements for route. This is used to
127
-			// tell the route parser how url parameters should be matched
128
-			if(array_key_exists('requirements', $ocsRoute)) {
129
-				$router->requirements($ocsRoute['requirements']);
130
-			}
131
-
132
-			// optionally register defaults for route. This is used to
133
-			// tell the route parser how url parameters should be default valued
134
-			if(array_key_exists('defaults', $ocsRoute)) {
135
-				$router->defaults($ocsRoute['defaults']);
136
-			}
137
-		}
138
-	}
139
-
140
-	/**
141
-	 * Creates one route base on the give configuration
142
-	 * @param array $routes
143
-	 * @throws \UnexpectedValueException
144
-	 */
145
-	private function processSimpleRoutes($routes)
146
-	{
147
-		$simpleRoutes = isset($routes['routes']) ? $routes['routes'] : array();
148
-		foreach ($simpleRoutes as $simpleRoute) {
149
-			$name = $simpleRoute['name'];
150
-			$postfix = '';
151
-
152
-			if (isset($simpleRoute['postfix'])) {
153
-				$postfix = $simpleRoute['postfix'];
154
-			}
155
-
156
-			$url = $simpleRoute['url'];
157
-			$verb = isset($simpleRoute['verb']) ? strtoupper($simpleRoute['verb']) : 'GET';
158
-
159
-			$split = explode('#', $name, 2);
160
-			if (count($split) != 2) {
161
-				throw new \UnexpectedValueException('Invalid route name');
162
-			}
163
-			$controller = $split[0];
164
-			$action = $split[1];
165
-
166
-			$controllerName = $this->buildControllerName($controller);
167
-			$actionName = $this->buildActionName($action);
168
-
169
-			// register the route
170
-			$handler = new RouteActionHandler($this->container, $controllerName, $actionName);
171
-			$router = $this->router->create($this->appName.'.'.$controller.'.'.$action . $postfix, $url)
172
-							->method($verb)
173
-							->action($handler);
174
-
175
-			// optionally register requirements for route. This is used to
176
-			// tell the route parser how url parameters should be matched
177
-			if(array_key_exists('requirements', $simpleRoute)) {
178
-				$router->requirements($simpleRoute['requirements']);
179
-			}
180
-
181
-			// optionally register defaults for route. This is used to
182
-			// tell the route parser how url parameters should be default valued
183
-			if(array_key_exists('defaults', $simpleRoute)) {
184
-				$router->defaults($simpleRoute['defaults']);
185
-			}
186
-		}
187
-	}
188
-
189
-	/**
190
-	 * For a given name and url restful routes are created:
191
-	 *  - index
192
-	 *  - show
193
-	 *  - new
194
-	 *  - create
195
-	 *  - update
196
-	 *  - destroy
197
-	 *
198
-	 * @param array $routes
199
-	 */
200
-	private function processResources($routes)
201
-	{
202
-		// declaration of all restful actions
203
-		$actions = array(
204
-			array('name' => 'index', 'verb' => 'GET', 'on-collection' => true),
205
-			array('name' => 'show', 'verb' => 'GET'),
206
-			array('name' => 'create', 'verb' => 'POST', 'on-collection' => true),
207
-			array('name' => 'update', 'verb' => 'PUT'),
208
-			array('name' => 'destroy', 'verb' => 'DELETE'),
209
-		);
210
-
211
-		$resources = isset($routes['resources']) ? $routes['resources'] : array();
212
-		foreach ($resources as $resource => $config) {
213
-
214
-			// the url parameter used as id to the resource
215
-			foreach($actions as $action) {
216
-				$url = $config['url'];
217
-				$method = $action['name'];
218
-				$verb = isset($action['verb']) ? strtoupper($action['verb']) : 'GET';
219
-				$collectionAction = isset($action['on-collection']) ? $action['on-collection'] : false;
220
-				if (!$collectionAction) {
221
-					$url = $url . '/{id}';
222
-				}
223
-				if (isset($action['url-postfix'])) {
224
-					$url = $url . '/' . $action['url-postfix'];
225
-				}
226
-
227
-				$controller = $resource;
228
-
229
-				$controllerName = $this->buildControllerName($controller);
230
-				$actionName = $this->buildActionName($method);
231
-
232
-				$routeName = $this->appName . '.' . strtolower($resource) . '.' . strtolower($method);
233
-
234
-				$this->router->create($routeName, $url)->method($verb)->action(
235
-					new RouteActionHandler($this->container, $controllerName, $actionName)
236
-				);
237
-			}
238
-		}
239
-	}
240
-
241
-	/**
242
-	 * Based on a given route name the controller name is generated
243
-	 * @param string $controller
244
-	 * @return string
245
-	 */
246
-	private function buildControllerName($controller)
247
-	{
248
-		if (!isset($this->controllerNameCache[$controller])) {
249
-			$this->controllerNameCache[$controller] = $this->underScoreToCamelCase(ucfirst($controller)) . 'Controller';
250
-		}
251
-		return $this->controllerNameCache[$controller];
252
-	}
253
-
254
-	/**
255
-	 * Based on the action part of the route name the controller method name is generated
256
-	 * @param string $action
257
-	 * @return string
258
-	 */
259
-	private function buildActionName($action) {
260
-		return $this->underScoreToCamelCase($action);
261
-	}
262
-
263
-	/**
264
-	 * Underscored strings are converted to camel case strings
265
-	 * @param string $str
266
-	 * @return string
267
-	 */
268
-	private function underScoreToCamelCase($str) {
269
-		$pattern = "/_[a-z]?/";
270
-		return preg_replace_callback(
271
-			$pattern,
272
-			function ($matches) {
273
-				return strtoupper(ltrim($matches[0], "_"));
274
-			},
275
-			$str);
276
-	}
81
+        $oldCollection = $this->router->getCurrentCollection();
82
+        $this->router->useCollection($oldCollection.'.ocs');
83
+
84
+        // parse ocs simple routes
85
+        $this->processOCS($this->routes);
86
+
87
+        $this->router->useCollection($oldCollection);
88
+    }
89
+
90
+    private function processOCS(array $routes) {
91
+        $ocsRoutes = isset($routes['ocs']) ? $routes['ocs'] : [];
92
+        foreach ($ocsRoutes as $ocsRoute) {
93
+            $name = $ocsRoute['name'];
94
+            $postfix = '';
95
+
96
+            if (isset($ocsRoute['postfix'])) {
97
+                $postfix = $ocsRoute['postfix'];
98
+            }
99
+
100
+            if (isset($ocsRoute['root'])) {
101
+                $root = $ocsRoute['root'];
102
+            } else {
103
+                $root = '/apps/'.$this->appName;
104
+            }
105
+
106
+            $url = $root . $ocsRoute['url'];
107
+            $verb = isset($ocsRoute['verb']) ? strtoupper($ocsRoute['verb']) : 'GET';
108
+
109
+            $split = explode('#', $name, 2);
110
+            if (count($split) != 2) {
111
+                throw new \UnexpectedValueException('Invalid route name');
112
+            }
113
+            $controller = $split[0];
114
+            $action = $split[1];
115
+
116
+            $controllerName = $this->buildControllerName($controller);
117
+            $actionName = $this->buildActionName($action);
118
+
119
+            // register the route
120
+            $handler = new RouteActionHandler($this->container, $controllerName, $actionName);
121
+
122
+            $router = $this->router->create('ocs.'.$this->appName.'.'.$controller.'.'.$action . $postfix, $url)
123
+                ->method($verb)
124
+                ->action($handler);
125
+
126
+            // optionally register requirements for route. This is used to
127
+            // tell the route parser how url parameters should be matched
128
+            if(array_key_exists('requirements', $ocsRoute)) {
129
+                $router->requirements($ocsRoute['requirements']);
130
+            }
131
+
132
+            // optionally register defaults for route. This is used to
133
+            // tell the route parser how url parameters should be default valued
134
+            if(array_key_exists('defaults', $ocsRoute)) {
135
+                $router->defaults($ocsRoute['defaults']);
136
+            }
137
+        }
138
+    }
139
+
140
+    /**
141
+     * Creates one route base on the give configuration
142
+     * @param array $routes
143
+     * @throws \UnexpectedValueException
144
+     */
145
+    private function processSimpleRoutes($routes)
146
+    {
147
+        $simpleRoutes = isset($routes['routes']) ? $routes['routes'] : array();
148
+        foreach ($simpleRoutes as $simpleRoute) {
149
+            $name = $simpleRoute['name'];
150
+            $postfix = '';
151
+
152
+            if (isset($simpleRoute['postfix'])) {
153
+                $postfix = $simpleRoute['postfix'];
154
+            }
155
+
156
+            $url = $simpleRoute['url'];
157
+            $verb = isset($simpleRoute['verb']) ? strtoupper($simpleRoute['verb']) : 'GET';
158
+
159
+            $split = explode('#', $name, 2);
160
+            if (count($split) != 2) {
161
+                throw new \UnexpectedValueException('Invalid route name');
162
+            }
163
+            $controller = $split[0];
164
+            $action = $split[1];
165
+
166
+            $controllerName = $this->buildControllerName($controller);
167
+            $actionName = $this->buildActionName($action);
168
+
169
+            // register the route
170
+            $handler = new RouteActionHandler($this->container, $controllerName, $actionName);
171
+            $router = $this->router->create($this->appName.'.'.$controller.'.'.$action . $postfix, $url)
172
+                            ->method($verb)
173
+                            ->action($handler);
174
+
175
+            // optionally register requirements for route. This is used to
176
+            // tell the route parser how url parameters should be matched
177
+            if(array_key_exists('requirements', $simpleRoute)) {
178
+                $router->requirements($simpleRoute['requirements']);
179
+            }
180
+
181
+            // optionally register defaults for route. This is used to
182
+            // tell the route parser how url parameters should be default valued
183
+            if(array_key_exists('defaults', $simpleRoute)) {
184
+                $router->defaults($simpleRoute['defaults']);
185
+            }
186
+        }
187
+    }
188
+
189
+    /**
190
+     * For a given name and url restful routes are created:
191
+     *  - index
192
+     *  - show
193
+     *  - new
194
+     *  - create
195
+     *  - update
196
+     *  - destroy
197
+     *
198
+     * @param array $routes
199
+     */
200
+    private function processResources($routes)
201
+    {
202
+        // declaration of all restful actions
203
+        $actions = array(
204
+            array('name' => 'index', 'verb' => 'GET', 'on-collection' => true),
205
+            array('name' => 'show', 'verb' => 'GET'),
206
+            array('name' => 'create', 'verb' => 'POST', 'on-collection' => true),
207
+            array('name' => 'update', 'verb' => 'PUT'),
208
+            array('name' => 'destroy', 'verb' => 'DELETE'),
209
+        );
210
+
211
+        $resources = isset($routes['resources']) ? $routes['resources'] : array();
212
+        foreach ($resources as $resource => $config) {
213
+
214
+            // the url parameter used as id to the resource
215
+            foreach($actions as $action) {
216
+                $url = $config['url'];
217
+                $method = $action['name'];
218
+                $verb = isset($action['verb']) ? strtoupper($action['verb']) : 'GET';
219
+                $collectionAction = isset($action['on-collection']) ? $action['on-collection'] : false;
220
+                if (!$collectionAction) {
221
+                    $url = $url . '/{id}';
222
+                }
223
+                if (isset($action['url-postfix'])) {
224
+                    $url = $url . '/' . $action['url-postfix'];
225
+                }
226
+
227
+                $controller = $resource;
228
+
229
+                $controllerName = $this->buildControllerName($controller);
230
+                $actionName = $this->buildActionName($method);
231
+
232
+                $routeName = $this->appName . '.' . strtolower($resource) . '.' . strtolower($method);
233
+
234
+                $this->router->create($routeName, $url)->method($verb)->action(
235
+                    new RouteActionHandler($this->container, $controllerName, $actionName)
236
+                );
237
+            }
238
+        }
239
+    }
240
+
241
+    /**
242
+     * Based on a given route name the controller name is generated
243
+     * @param string $controller
244
+     * @return string
245
+     */
246
+    private function buildControllerName($controller)
247
+    {
248
+        if (!isset($this->controllerNameCache[$controller])) {
249
+            $this->controllerNameCache[$controller] = $this->underScoreToCamelCase(ucfirst($controller)) . 'Controller';
250
+        }
251
+        return $this->controllerNameCache[$controller];
252
+    }
253
+
254
+    /**
255
+     * Based on the action part of the route name the controller method name is generated
256
+     * @param string $action
257
+     * @return string
258
+     */
259
+    private function buildActionName($action) {
260
+        return $this->underScoreToCamelCase($action);
261
+    }
262
+
263
+    /**
264
+     * Underscored strings are converted to camel case strings
265
+     * @param string $str
266
+     * @return string
267
+     */
268
+    private function underScoreToCamelCase($str) {
269
+        $pattern = "/_[a-z]?/";
270
+        return preg_replace_callback(
271
+            $pattern,
272
+            function ($matches) {
273
+                return strtoupper(ltrim($matches[0], "_"));
274
+            },
275
+            $str);
276
+    }
277 277
 }
Please login to merge, or discard this patch.
apps/sharebymail/lib/Settings/SettingsManager.php 1 patch
Indentation   +30 added lines, -30 removed lines patch added patch discarded remove patch
@@ -27,35 +27,35 @@
 block discarded – undo
27 27
 
28 28
 class SettingsManager {
29 29
 
30
-	/** @var IConfig */
31
-	private $config;
32
-
33
-	private $sendPasswordByMailDefault = 'yes';
34
-
35
-	private $enforcePasswordProtectionDefault = 'no';
36
-
37
-	public function __construct(IConfig $config) {
38
-		$this->config = $config;
39
-	}
40
-
41
-	/**
42
-	 * should the password for a mail share be send to the recipient
43
-	 *
44
-	 * @return bool
45
-	 */
46
-	public function sendPasswordByMail() {
47
-		$sendPasswordByMail = $this->config->getAppValue('sharebymail', 'sendpasswordmail', $this->sendPasswordByMailDefault);
48
-		return $sendPasswordByMail === 'yes';
49
-	}
50
-
51
-	/**
52
-	 * do we require a share by mail to be password protected
53
-	 *
54
-	 * @return bool
55
-	 */
56
-	public function enforcePasswordProtection() {
57
-		$enforcePassword = $this->config->getAppValue('sharebymail', 'enforcePasswordProtection', $this->enforcePasswordProtectionDefault);
58
-		return $enforcePassword === 'yes';
59
-	}
30
+    /** @var IConfig */
31
+    private $config;
32
+
33
+    private $sendPasswordByMailDefault = 'yes';
34
+
35
+    private $enforcePasswordProtectionDefault = 'no';
36
+
37
+    public function __construct(IConfig $config) {
38
+        $this->config = $config;
39
+    }
40
+
41
+    /**
42
+     * should the password for a mail share be send to the recipient
43
+     *
44
+     * @return bool
45
+     */
46
+    public function sendPasswordByMail() {
47
+        $sendPasswordByMail = $this->config->getAppValue('sharebymail', 'sendpasswordmail', $this->sendPasswordByMailDefault);
48
+        return $sendPasswordByMail === 'yes';
49
+    }
50
+
51
+    /**
52
+     * do we require a share by mail to be password protected
53
+     *
54
+     * @return bool
55
+     */
56
+    public function enforcePasswordProtection() {
57
+        $enforcePassword = $this->config->getAppValue('sharebymail', 'enforcePasswordProtection', $this->enforcePasswordProtectionDefault);
58
+        return $enforcePassword === 'yes';
59
+    }
60 60
 
61 61
 }
Please login to merge, or discard this patch.
apps/sharebymail/lib/Settings/Admin.php 1 patch
Indentation   +31 added lines, -31 removed lines patch added patch discarded remove patch
@@ -27,42 +27,42 @@
 block discarded – undo
27 27
 
28 28
 class Admin implements ISettings {
29 29
 
30
-	/** @var SettingsManager */
31
-	private $settingsManager;
30
+    /** @var SettingsManager */
31
+    private $settingsManager;
32 32
 
33
-	public function __construct(SettingsManager $settingsManager) {
34
-		$this->settingsManager = $settingsManager;
35
-	}
33
+    public function __construct(SettingsManager $settingsManager) {
34
+        $this->settingsManager = $settingsManager;
35
+    }
36 36
 
37
-	/**
38
-	 * @return TemplateResponse
39
-	 */
40
-	public function getForm() {
37
+    /**
38
+     * @return TemplateResponse
39
+     */
40
+    public function getForm() {
41 41
 
42
-		$parameters = [
43
-			'sendPasswordMail' => $this->settingsManager->sendPasswordByMail(),
44
-			'enforcePasswordProtection' => $this->settingsManager->enforcePasswordProtection()
45
-		];
42
+        $parameters = [
43
+            'sendPasswordMail' => $this->settingsManager->sendPasswordByMail(),
44
+            'enforcePasswordProtection' => $this->settingsManager->enforcePasswordProtection()
45
+        ];
46 46
 
47
-		return new TemplateResponse('sharebymail', 'settings-admin', $parameters, '');
48
-	}
47
+        return new TemplateResponse('sharebymail', 'settings-admin', $parameters, '');
48
+    }
49 49
 
50
-	/**
51
-	 * @return string the section ID, e.g. 'sharing'
52
-	 */
53
-	public function getSection() {
54
-		return 'sharing';
55
-	}
50
+    /**
51
+     * @return string the section ID, e.g. 'sharing'
52
+     */
53
+    public function getSection() {
54
+        return 'sharing';
55
+    }
56 56
 
57
-	/**
58
-	 * @return int whether the form should be rather on the top or bottom of
59
-	 * the admin section. The forms are arranged in ascending order of the
60
-	 * priority values. It is required to return a value between 0 and 100.
61
-	 *
62
-	 * E.g.: 70
63
-	 */
64
-	public function getPriority() {
65
-		return 40;
66
-	}
57
+    /**
58
+     * @return int whether the form should be rather on the top or bottom of
59
+     * the admin section. The forms are arranged in ascending order of the
60
+     * priority values. It is required to return a value between 0 and 100.
61
+     *
62
+     * E.g.: 70
63
+     */
64
+    public function getPriority() {
65
+        return 40;
66
+    }
67 67
 
68 68
 }
Please login to merge, or discard this patch.
apps/sharebymail/lib/Settings.php 1 patch
Indentation   +23 added lines, -23 removed lines patch added patch discarded remove patch
@@ -27,27 +27,27 @@
 block discarded – undo
27 27
 
28 28
 class Settings {
29 29
 
30
-	/** @var SettingsManager */
31
-	private $settingsManager;
32
-
33
-	public function __construct(SettingsManager $settingsManager) {
34
-		$this->settingsManager = $settingsManager;
35
-	}
36
-
37
-	/**
38
-	 * announce that the share-by-mail share provider is enabled
39
-	 *
40
-	 * @param array $settings
41
-	 */
42
-	public function announceShareProvider(array $settings) {
43
-		$array = json_decode($settings['array']['oc_appconfig'], true);
44
-		$array['shareByMailEnabled'] = true;
45
-		$settings['array']['oc_appconfig'] = json_encode($array);
46
-	}
47
-
48
-	public function announceShareByMailSettings(array $settings) {
49
-		$array = json_decode($settings['array']['oc_appconfig'], true);
50
-		$array['shareByMail']['enforcePasswordProtection'] = $this->settingsManager->enforcePasswordProtection();
51
-		$settings['array']['oc_appconfig'] = json_encode($array);
52
-	}
30
+    /** @var SettingsManager */
31
+    private $settingsManager;
32
+
33
+    public function __construct(SettingsManager $settingsManager) {
34
+        $this->settingsManager = $settingsManager;
35
+    }
36
+
37
+    /**
38
+     * announce that the share-by-mail share provider is enabled
39
+     *
40
+     * @param array $settings
41
+     */
42
+    public function announceShareProvider(array $settings) {
43
+        $array = json_decode($settings['array']['oc_appconfig'], true);
44
+        $array['shareByMailEnabled'] = true;
45
+        $settings['array']['oc_appconfig'] = json_encode($array);
46
+    }
47
+
48
+    public function announceShareByMailSettings(array $settings) {
49
+        $array = json_decode($settings['array']['oc_appconfig'], true);
50
+        $array['shareByMail']['enforcePasswordProtection'] = $this->settingsManager->enforcePasswordProtection();
51
+        $settings['array']['oc_appconfig'] = json_encode($array);
52
+    }
53 53
 }
Please login to merge, or discard this patch.
apps/sharebymail/lib/AppInfo/Application.php 1 patch
Indentation   +11 added lines, -11 removed lines patch added patch discarded remove patch
@@ -29,19 +29,19 @@
 block discarded – undo
29 29
 
30 30
 class Application extends App {
31 31
 
32
-	public function __construct(array $urlParams = array()) {
33
-		parent::__construct('sharebymail', $urlParams);
32
+    public function __construct(array $urlParams = array()) {
33
+        parent::__construct('sharebymail', $urlParams);
34 34
 
35
-		$settingsManager = \OC::$server->query(Settings\SettingsManager::class);
36
-		$settings = new Settings($settingsManager);
35
+        $settingsManager = \OC::$server->query(Settings\SettingsManager::class);
36
+        $settings = new Settings($settingsManager);
37 37
 
38
-		/** register capabilities */
39
-		$container = $this->getContainer();
40
-		$container->registerCapability('OCA\ShareByMail\Capabilities');
38
+        /** register capabilities */
39
+        $container = $this->getContainer();
40
+        $container->registerCapability('OCA\ShareByMail\Capabilities');
41 41
 
42
-		/** register hooks */
43
-		Util::connectHook('\OCP\Config', 'js', $settings, 'announceShareProvider');
44
-		Util::connectHook('\OCP\Config', 'js', $settings, 'announceShareByMailSettings');
45
-	}
42
+        /** register hooks */
43
+        Util::connectHook('\OCP\Config', 'js', $settings, 'announceShareProvider');
44
+        Util::connectHook('\OCP\Config', 'js', $settings, 'announceShareByMailSettings');
45
+    }
46 46
 
47 47
 }
Please login to merge, or discard this patch.
settings/routes.php 1 patch
Indentation   +51 added lines, -51 removed lines patch added patch discarded remove patch
@@ -36,76 +36,76 @@
 block discarded – undo
36 36
 
37 37
 $application = new Application();
38 38
 $application->registerRoutes($this, [
39
-	'resources' => [
40
-		'users' => ['url' => '/settings/users/users'],
41
-		'AuthSettings' => ['url' => '/settings/personal/authtokens'],
42
-	],
43
-	'routes' => [
44
-		['name' => 'MailSettings#setMailSettings', 'url' => '/settings/admin/mailsettings', 'verb' => 'POST'],
45
-		['name' => 'MailSettings#storeCredentials', 'url' => '/settings/admin/mailsettings/credentials', 'verb' => 'POST'],
46
-		['name' => 'MailSettings#sendTestMail', 'url' => '/settings/admin/mailtest', 'verb' => 'POST'],
47
-		['name' => 'Encryption#startMigration', 'url' => '/settings/admin/startmigration', 'verb' => 'POST'],
48
-		['name' => 'AppSettings#listCategories', 'url' => '/settings/apps/categories', 'verb' => 'GET'],
49
-		['name' => 'AppSettings#viewApps', 'url' => '/settings/apps', 'verb' => 'GET'],
50
-		['name' => 'AppSettings#listApps', 'url' => '/settings/apps/list', 'verb' => 'GET'],
51
-		['name' => 'SecuritySettings#trustedDomains', 'url' => '/settings/admin/security/trustedDomains', 'verb' => 'POST'],
52
-		['name' => 'Users#setDisplayName', 'url' => '/settings/users/{username}/displayName', 'verb' => 'POST'],
53
-		['name' => 'Users#setEMailAddress', 'url' => '/settings/users/{id}/mailAddress', 'verb' => 'PUT'],
54
-		['name' => 'Users#setUserSettings', 'url' => '/settings/users/{username}/settings', 'verb' => 'PUT'],
55
-		['name' => 'Users#stats', 'url' => '/settings/users/stats', 'verb' => 'GET'],
56
-		['name' => 'LogSettings#setLogLevel', 'url' => '/settings/admin/log/level', 'verb' => 'POST'],
57
-		['name' => 'LogSettings#getEntries', 'url' => '/settings/admin/log/entries', 'verb' => 'GET'],
58
-		['name' => 'LogSettings#download', 'url' => '/settings/admin/log/download', 'verb' => 'GET'],
59
-		['name' => 'CheckSetup#check', 'url' => '/settings/ajax/checksetup', 'verb' => 'GET'],
60
-		['name' => 'CheckSetup#getFailedIntegrityCheckFiles', 'url' => '/settings/integrity/failed', 'verb' => 'GET'],
61
-		['name' => 'CheckSetup#rescanFailedIntegrityCheck', 'url' => '/settings/integrity/rescan', 'verb' => 'GET'],
62
-		['name' => 'Certificate#addPersonalRootCertificate', 'url' => '/settings/personal/certificate', 'verb' => 'POST'],
63
-		['name' => 'Certificate#removePersonalRootCertificate', 'url' => '/settings/personal/certificate/{certificateIdentifier}', 'verb' => 'DELETE'],
64
-		['name' => 'Certificate#addSystemRootCertificate', 'url' => '/settings/admin/certificate', 'verb' => 'POST'],
65
-		['name' => 'Certificate#removeSystemRootCertificate', 'url' => '/settings/admin/certificate/{certificateIdentifier}', 'verb' => 'DELETE'],
66
-		['name' => 'AdminSettings#index', 'url' => '/settings/admin/{section}', 'verb' => 'GET', 'defaults' => ['section' => 'server']],
67
-		['name' => 'AdminSettings#form', 'url' => '/settings/admin/{section}', 'verb' => 'GET'],
68
-		['name' => 'ChangePassword#changePersonalPassword', 'url' => '/settings/personal/changepassword', 'verb' => 'POST'],
69
-		['name' => 'ChangePassword#changeUserPassword', 'url' => '/settings/users/changepassword', 'verb' => 'POST'],
70
-		['name' => 'Personal#setLanguage', 'url' => '/settings/ajax/setlanguage.php', 'verb' => 'POST'],
71
-		['name' => 'Groups#index', 'url' => '/settings/users/groups', 'verb' => 'GET'],
72
-		['name' => 'Groups#show', 'url' => '/settings/users/groups/{id}', 'requirements' => ['id' => '[^?]*'], 'verb' => 'GET'],
73
-		['name' => 'Groups#create', 'url' => '/settings/users/groups', 'verb' => 'POST'],
74
-		['name' => 'Groups#update', 'url' => '/settings/users/groups/{id}', 'requirements' => ['id' => '[^?]*'], 'verb' => 'PUT'],
75
-		['name' => 'Groups#destroy', 'url' => '/settings/users/groups/{id}', 'requirements' => ['id' => '[^?]*'], 'verb' => 'DELETE'],
76
-	]
39
+    'resources' => [
40
+        'users' => ['url' => '/settings/users/users'],
41
+        'AuthSettings' => ['url' => '/settings/personal/authtokens'],
42
+    ],
43
+    'routes' => [
44
+        ['name' => 'MailSettings#setMailSettings', 'url' => '/settings/admin/mailsettings', 'verb' => 'POST'],
45
+        ['name' => 'MailSettings#storeCredentials', 'url' => '/settings/admin/mailsettings/credentials', 'verb' => 'POST'],
46
+        ['name' => 'MailSettings#sendTestMail', 'url' => '/settings/admin/mailtest', 'verb' => 'POST'],
47
+        ['name' => 'Encryption#startMigration', 'url' => '/settings/admin/startmigration', 'verb' => 'POST'],
48
+        ['name' => 'AppSettings#listCategories', 'url' => '/settings/apps/categories', 'verb' => 'GET'],
49
+        ['name' => 'AppSettings#viewApps', 'url' => '/settings/apps', 'verb' => 'GET'],
50
+        ['name' => 'AppSettings#listApps', 'url' => '/settings/apps/list', 'verb' => 'GET'],
51
+        ['name' => 'SecuritySettings#trustedDomains', 'url' => '/settings/admin/security/trustedDomains', 'verb' => 'POST'],
52
+        ['name' => 'Users#setDisplayName', 'url' => '/settings/users/{username}/displayName', 'verb' => 'POST'],
53
+        ['name' => 'Users#setEMailAddress', 'url' => '/settings/users/{id}/mailAddress', 'verb' => 'PUT'],
54
+        ['name' => 'Users#setUserSettings', 'url' => '/settings/users/{username}/settings', 'verb' => 'PUT'],
55
+        ['name' => 'Users#stats', 'url' => '/settings/users/stats', 'verb' => 'GET'],
56
+        ['name' => 'LogSettings#setLogLevel', 'url' => '/settings/admin/log/level', 'verb' => 'POST'],
57
+        ['name' => 'LogSettings#getEntries', 'url' => '/settings/admin/log/entries', 'verb' => 'GET'],
58
+        ['name' => 'LogSettings#download', 'url' => '/settings/admin/log/download', 'verb' => 'GET'],
59
+        ['name' => 'CheckSetup#check', 'url' => '/settings/ajax/checksetup', 'verb' => 'GET'],
60
+        ['name' => 'CheckSetup#getFailedIntegrityCheckFiles', 'url' => '/settings/integrity/failed', 'verb' => 'GET'],
61
+        ['name' => 'CheckSetup#rescanFailedIntegrityCheck', 'url' => '/settings/integrity/rescan', 'verb' => 'GET'],
62
+        ['name' => 'Certificate#addPersonalRootCertificate', 'url' => '/settings/personal/certificate', 'verb' => 'POST'],
63
+        ['name' => 'Certificate#removePersonalRootCertificate', 'url' => '/settings/personal/certificate/{certificateIdentifier}', 'verb' => 'DELETE'],
64
+        ['name' => 'Certificate#addSystemRootCertificate', 'url' => '/settings/admin/certificate', 'verb' => 'POST'],
65
+        ['name' => 'Certificate#removeSystemRootCertificate', 'url' => '/settings/admin/certificate/{certificateIdentifier}', 'verb' => 'DELETE'],
66
+        ['name' => 'AdminSettings#index', 'url' => '/settings/admin/{section}', 'verb' => 'GET', 'defaults' => ['section' => 'server']],
67
+        ['name' => 'AdminSettings#form', 'url' => '/settings/admin/{section}', 'verb' => 'GET'],
68
+        ['name' => 'ChangePassword#changePersonalPassword', 'url' => '/settings/personal/changepassword', 'verb' => 'POST'],
69
+        ['name' => 'ChangePassword#changeUserPassword', 'url' => '/settings/users/changepassword', 'verb' => 'POST'],
70
+        ['name' => 'Personal#setLanguage', 'url' => '/settings/ajax/setlanguage.php', 'verb' => 'POST'],
71
+        ['name' => 'Groups#index', 'url' => '/settings/users/groups', 'verb' => 'GET'],
72
+        ['name' => 'Groups#show', 'url' => '/settings/users/groups/{id}', 'requirements' => ['id' => '[^?]*'], 'verb' => 'GET'],
73
+        ['name' => 'Groups#create', 'url' => '/settings/users/groups', 'verb' => 'POST'],
74
+        ['name' => 'Groups#update', 'url' => '/settings/users/groups/{id}', 'requirements' => ['id' => '[^?]*'], 'verb' => 'PUT'],
75
+        ['name' => 'Groups#destroy', 'url' => '/settings/users/groups/{id}', 'requirements' => ['id' => '[^?]*'], 'verb' => 'DELETE'],
76
+    ]
77 77
 ]);
78 78
 
79 79
 /** @var $this \OCP\Route\IRouter */
80 80
 
81 81
 // Settings pages
82 82
 $this->create('settings_help', '/settings/help')
83
-	->actionInclude('settings/help.php');
83
+    ->actionInclude('settings/help.php');
84 84
 $this->create('settings_personal', '/settings/personal')
85
-	->actionInclude('settings/personal.php');
85
+    ->actionInclude('settings/personal.php');
86 86
 $this->create('settings_users', '/settings/users')
87
-	->actionInclude('settings/users.php');
87
+    ->actionInclude('settings/users.php');
88 88
 // Settings ajax actions
89 89
 // users
90 90
 $this->create('settings_ajax_setquota', '/settings/ajax/setquota.php')
91
-	->actionInclude('settings/ajax/setquota.php');
91
+    ->actionInclude('settings/ajax/setquota.php');
92 92
 $this->create('settings_ajax_togglegroups', '/settings/ajax/togglegroups.php')
93
-	->actionInclude('settings/ajax/togglegroups.php');
93
+    ->actionInclude('settings/ajax/togglegroups.php');
94 94
 $this->create('settings_ajax_togglesubadmins', '/settings/ajax/togglesubadmins.php')
95
-	->actionInclude('settings/ajax/togglesubadmins.php');
95
+    ->actionInclude('settings/ajax/togglesubadmins.php');
96 96
 $this->create('settings_ajax_changegorupname', '/settings/ajax/changegroupname.php')
97
-	->actionInclude('settings/ajax/changegroupname.php');
97
+    ->actionInclude('settings/ajax/changegroupname.php');
98 98
 // apps
99 99
 $this->create('settings_ajax_enableapp', '/settings/ajax/enableapp.php')
100
-	->actionInclude('settings/ajax/enableapp.php');
100
+    ->actionInclude('settings/ajax/enableapp.php');
101 101
 $this->create('settings_ajax_disableapp', '/settings/ajax/disableapp.php')
102
-	->actionInclude('settings/ajax/disableapp.php');
102
+    ->actionInclude('settings/ajax/disableapp.php');
103 103
 $this->create('settings_ajax_updateapp', '/settings/ajax/updateapp.php')
104
-	->actionInclude('settings/ajax/updateapp.php');
104
+    ->actionInclude('settings/ajax/updateapp.php');
105 105
 $this->create('settings_ajax_uninstallapp', '/settings/ajax/uninstallapp.php')
106
-	->actionInclude('settings/ajax/uninstallapp.php');
106
+    ->actionInclude('settings/ajax/uninstallapp.php');
107 107
 $this->create('settings_ajax_navigationdetect', '/settings/ajax/navigationdetect.php')
108
-	->actionInclude('settings/ajax/navigationdetect.php');
108
+    ->actionInclude('settings/ajax/navigationdetect.php');
109 109
 // admin
110 110
 $this->create('settings_ajax_excludegroups', '/settings/ajax/excludegroups.php')
111
-	->actionInclude('settings/ajax/excludegroups.php');
111
+    ->actionInclude('settings/ajax/excludegroups.php');
Please login to merge, or discard this patch.
lib/private/Share20/Manager.php 1 patch
Indentation   +1355 added lines, -1355 removed lines patch added patch discarded remove patch
@@ -58,1383 +58,1383 @@
 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 ($path->getId() !== $userFolder->getId() && !$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
-
1246
-		if ($currentAccess) {
1247
-			$ownerPath = $path->getPath();
1248
-			$ownerPath = explode('/', $ownerPath, 4);
1249
-			if (count($ownerPath) < 4) {
1250
-				$ownerPath = '';
1251
-			} else {
1252
-				$ownerPath = $ownerPath[3];
1253
-			}
1254
-			$al['users'][$owner] = [
1255
-				'node_id' => $path->getId(),
1256
-				'node_path' => '/' . $ownerPath,
1257
-			];
1258
-		} else {
1259
-			$al['users'][] = $owner;
1260
-		}
1261
-
1262
-		// Collect all the shares
1263
-		while ($path->getPath() !== $userFolder->getPath()) {
1264
-			$nodes[] = $path;
1265
-			if (!$recursive) {
1266
-				break;
1267
-			}
1268
-			$path = $path->getParent();
1269
-		}
1270
-
1271
-		foreach ($providers as $provider) {
1272
-			$tmp = $provider->getAccessList($nodes, $currentAccess);
1273
-
1274
-			foreach ($tmp as $k => $v) {
1275
-				if (isset($al[$k])) {
1276
-					if (is_array($al[$k])) {
1277
-						$al[$k] = array_merge($al[$k], $v);
1278
-					} else {
1279
-						$al[$k] = $al[$k] || $v;
1280
-					}
1281
-				} else {
1282
-					$al[$k] = $v;
1283
-				}
1284
-			}
1285
-		}
1286
-
1287
-		return $al;
1288
-	}
1289
-
1290
-	/**
1291
-	 * Create a new share
1292
-	 * @return \OCP\Share\IShare;
1293
-	 */
1294
-	public function newShare() {
1295
-		return new \OC\Share20\Share($this->rootFolder, $this->userManager);
1296
-	}
1297
-
1298
-	/**
1299
-	 * Is the share API enabled
1300
-	 *
1301
-	 * @return bool
1302
-	 */
1303
-	public function shareApiEnabled() {
1304
-		return $this->config->getAppValue('core', 'shareapi_enabled', 'yes') === 'yes';
1305
-	}
1306
-
1307
-	/**
1308
-	 * Is public link sharing enabled
1309
-	 *
1310
-	 * @return bool
1311
-	 */
1312
-	public function shareApiAllowLinks() {
1313
-		return $this->config->getAppValue('core', 'shareapi_allow_links', 'yes') === 'yes';
1314
-	}
1315
-
1316
-	/**
1317
-	 * Is password on public link requires
1318
-	 *
1319
-	 * @return bool
1320
-	 */
1321
-	public function shareApiLinkEnforcePassword() {
1322
-		return $this->config->getAppValue('core', 'shareapi_enforce_links_password', 'no') === 'yes';
1323
-	}
1324
-
1325
-	/**
1326
-	 * Is default expire date enabled
1327
-	 *
1328
-	 * @return bool
1329
-	 */
1330
-	public function shareApiLinkDefaultExpireDate() {
1331
-		return $this->config->getAppValue('core', 'shareapi_default_expire_date', 'no') === 'yes';
1332
-	}
1333
-
1334
-	/**
1335
-	 * Is default expire date enforced
1336
-	 *`
1337
-	 * @return bool
1338
-	 */
1339
-	public function shareApiLinkDefaultExpireDateEnforced() {
1340
-		return $this->shareApiLinkDefaultExpireDate() &&
1341
-			$this->config->getAppValue('core', 'shareapi_enforce_expire_date', 'no') === 'yes';
1342
-	}
1343
-
1344
-	/**
1345
-	 * Number of default expire days
1346
-	 *shareApiLinkAllowPublicUpload
1347
-	 * @return int
1348
-	 */
1349
-	public function shareApiLinkDefaultExpireDays() {
1350
-		return (int)$this->config->getAppValue('core', 'shareapi_expire_after_n_days', '7');
1351
-	}
1352
-
1353
-	/**
1354
-	 * Allow public upload on link shares
1355
-	 *
1356
-	 * @return bool
1357
-	 */
1358
-	public function shareApiLinkAllowPublicUpload() {
1359
-		return $this->config->getAppValue('core', 'shareapi_allow_public_upload', 'yes') === 'yes';
1360
-	}
1361
-
1362
-	/**
1363
-	 * check if user can only share with group members
1364
-	 * @return bool
1365
-	 */
1366
-	public function shareWithGroupMembersOnly() {
1367
-		return $this->config->getAppValue('core', 'shareapi_only_share_with_group_members', 'no') === 'yes';
1368
-	}
1369
-
1370
-	/**
1371
-	 * Check if users can share with groups
1372
-	 * @return bool
1373
-	 */
1374
-	public function allowGroupSharing() {
1375
-		return $this->config->getAppValue('core', 'shareapi_allow_group_sharing', 'yes') === 'yes';
1376
-	}
1377
-
1378
-	/**
1379
-	 * Copied from \OC_Util::isSharingDisabledForUser
1380
-	 *
1381
-	 * TODO: Deprecate fuction from OC_Util
1382
-	 *
1383
-	 * @param string $userId
1384
-	 * @return bool
1385
-	 */
1386
-	public function sharingDisabledForUser($userId) {
1387
-		if ($userId === null) {
1388
-			return false;
1389
-		}
1390
-
1391
-		if (isset($this->sharingDisabledForUsersCache[$userId])) {
1392
-			return $this->sharingDisabledForUsersCache[$userId];
1393
-		}
1394
-
1395
-		if ($this->config->getAppValue('core', 'shareapi_exclude_groups', 'no') === 'yes') {
1396
-			$groupsList = $this->config->getAppValue('core', 'shareapi_exclude_groups_list', '');
1397
-			$excludedGroups = json_decode($groupsList);
1398
-			if (is_null($excludedGroups)) {
1399
-				$excludedGroups = explode(',', $groupsList);
1400
-				$newValue = json_encode($excludedGroups);
1401
-				$this->config->setAppValue('core', 'shareapi_exclude_groups_list', $newValue);
1402
-			}
1403
-			$user = $this->userManager->get($userId);
1404
-			$usersGroups = $this->groupManager->getUserGroupIds($user);
1405
-			if (!empty($usersGroups)) {
1406
-				$remainingGroups = array_diff($usersGroups, $excludedGroups);
1407
-				// if the user is only in groups which are disabled for sharing then
1408
-				// sharing is also disabled for the user
1409
-				if (empty($remainingGroups)) {
1410
-					$this->sharingDisabledForUsersCache[$userId] = true;
1411
-					return true;
1412
-				}
1413
-			}
1414
-		}
1415
-
1416
-		$this->sharingDisabledForUsersCache[$userId] = false;
1417
-		return false;
1418
-	}
1419
-
1420
-	/**
1421
-	 * @inheritdoc
1422
-	 */
1423
-	public function outgoingServer2ServerSharesAllowed() {
1424
-		return $this->config->getAppValue('files_sharing', 'outgoing_server2server_share_enabled', 'yes') === 'yes';
1425
-	}
1426
-
1427
-	/**
1428
-	 * @inheritdoc
1429
-	 */
1430
-	public function shareProviderExists($shareType) {
1431
-		try {
1432
-			$this->factory->getProviderForType($shareType);
1433
-		} catch (ProviderException $e) {
1434
-			return false;
1435
-		}
1436
-
1437
-		return true;
1438
-	}
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 ($path->getId() !== $userFolder->getId() && !$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
+
1246
+        if ($currentAccess) {
1247
+            $ownerPath = $path->getPath();
1248
+            $ownerPath = explode('/', $ownerPath, 4);
1249
+            if (count($ownerPath) < 4) {
1250
+                $ownerPath = '';
1251
+            } else {
1252
+                $ownerPath = $ownerPath[3];
1253
+            }
1254
+            $al['users'][$owner] = [
1255
+                'node_id' => $path->getId(),
1256
+                'node_path' => '/' . $ownerPath,
1257
+            ];
1258
+        } else {
1259
+            $al['users'][] = $owner;
1260
+        }
1261
+
1262
+        // Collect all the shares
1263
+        while ($path->getPath() !== $userFolder->getPath()) {
1264
+            $nodes[] = $path;
1265
+            if (!$recursive) {
1266
+                break;
1267
+            }
1268
+            $path = $path->getParent();
1269
+        }
1270
+
1271
+        foreach ($providers as $provider) {
1272
+            $tmp = $provider->getAccessList($nodes, $currentAccess);
1273
+
1274
+            foreach ($tmp as $k => $v) {
1275
+                if (isset($al[$k])) {
1276
+                    if (is_array($al[$k])) {
1277
+                        $al[$k] = array_merge($al[$k], $v);
1278
+                    } else {
1279
+                        $al[$k] = $al[$k] || $v;
1280
+                    }
1281
+                } else {
1282
+                    $al[$k] = $v;
1283
+                }
1284
+            }
1285
+        }
1286
+
1287
+        return $al;
1288
+    }
1289
+
1290
+    /**
1291
+     * Create a new share
1292
+     * @return \OCP\Share\IShare;
1293
+     */
1294
+    public function newShare() {
1295
+        return new \OC\Share20\Share($this->rootFolder, $this->userManager);
1296
+    }
1297
+
1298
+    /**
1299
+     * Is the share API enabled
1300
+     *
1301
+     * @return bool
1302
+     */
1303
+    public function shareApiEnabled() {
1304
+        return $this->config->getAppValue('core', 'shareapi_enabled', 'yes') === 'yes';
1305
+    }
1306
+
1307
+    /**
1308
+     * Is public link sharing enabled
1309
+     *
1310
+     * @return bool
1311
+     */
1312
+    public function shareApiAllowLinks() {
1313
+        return $this->config->getAppValue('core', 'shareapi_allow_links', 'yes') === 'yes';
1314
+    }
1315
+
1316
+    /**
1317
+     * Is password on public link requires
1318
+     *
1319
+     * @return bool
1320
+     */
1321
+    public function shareApiLinkEnforcePassword() {
1322
+        return $this->config->getAppValue('core', 'shareapi_enforce_links_password', 'no') === 'yes';
1323
+    }
1324
+
1325
+    /**
1326
+     * Is default expire date enabled
1327
+     *
1328
+     * @return bool
1329
+     */
1330
+    public function shareApiLinkDefaultExpireDate() {
1331
+        return $this->config->getAppValue('core', 'shareapi_default_expire_date', 'no') === 'yes';
1332
+    }
1333
+
1334
+    /**
1335
+     * Is default expire date enforced
1336
+     *`
1337
+     * @return bool
1338
+     */
1339
+    public function shareApiLinkDefaultExpireDateEnforced() {
1340
+        return $this->shareApiLinkDefaultExpireDate() &&
1341
+            $this->config->getAppValue('core', 'shareapi_enforce_expire_date', 'no') === 'yes';
1342
+    }
1343
+
1344
+    /**
1345
+     * Number of default expire days
1346
+     *shareApiLinkAllowPublicUpload
1347
+     * @return int
1348
+     */
1349
+    public function shareApiLinkDefaultExpireDays() {
1350
+        return (int)$this->config->getAppValue('core', 'shareapi_expire_after_n_days', '7');
1351
+    }
1352
+
1353
+    /**
1354
+     * Allow public upload on link shares
1355
+     *
1356
+     * @return bool
1357
+     */
1358
+    public function shareApiLinkAllowPublicUpload() {
1359
+        return $this->config->getAppValue('core', 'shareapi_allow_public_upload', 'yes') === 'yes';
1360
+    }
1361
+
1362
+    /**
1363
+     * check if user can only share with group members
1364
+     * @return bool
1365
+     */
1366
+    public function shareWithGroupMembersOnly() {
1367
+        return $this->config->getAppValue('core', 'shareapi_only_share_with_group_members', 'no') === 'yes';
1368
+    }
1369
+
1370
+    /**
1371
+     * Check if users can share with groups
1372
+     * @return bool
1373
+     */
1374
+    public function allowGroupSharing() {
1375
+        return $this->config->getAppValue('core', 'shareapi_allow_group_sharing', 'yes') === 'yes';
1376
+    }
1377
+
1378
+    /**
1379
+     * Copied from \OC_Util::isSharingDisabledForUser
1380
+     *
1381
+     * TODO: Deprecate fuction from OC_Util
1382
+     *
1383
+     * @param string $userId
1384
+     * @return bool
1385
+     */
1386
+    public function sharingDisabledForUser($userId) {
1387
+        if ($userId === null) {
1388
+            return false;
1389
+        }
1390
+
1391
+        if (isset($this->sharingDisabledForUsersCache[$userId])) {
1392
+            return $this->sharingDisabledForUsersCache[$userId];
1393
+        }
1394
+
1395
+        if ($this->config->getAppValue('core', 'shareapi_exclude_groups', 'no') === 'yes') {
1396
+            $groupsList = $this->config->getAppValue('core', 'shareapi_exclude_groups_list', '');
1397
+            $excludedGroups = json_decode($groupsList);
1398
+            if (is_null($excludedGroups)) {
1399
+                $excludedGroups = explode(',', $groupsList);
1400
+                $newValue = json_encode($excludedGroups);
1401
+                $this->config->setAppValue('core', 'shareapi_exclude_groups_list', $newValue);
1402
+            }
1403
+            $user = $this->userManager->get($userId);
1404
+            $usersGroups = $this->groupManager->getUserGroupIds($user);
1405
+            if (!empty($usersGroups)) {
1406
+                $remainingGroups = array_diff($usersGroups, $excludedGroups);
1407
+                // if the user is only in groups which are disabled for sharing then
1408
+                // sharing is also disabled for the user
1409
+                if (empty($remainingGroups)) {
1410
+                    $this->sharingDisabledForUsersCache[$userId] = true;
1411
+                    return true;
1412
+                }
1413
+            }
1414
+        }
1415
+
1416
+        $this->sharingDisabledForUsersCache[$userId] = false;
1417
+        return false;
1418
+    }
1419
+
1420
+    /**
1421
+     * @inheritdoc
1422
+     */
1423
+    public function outgoingServer2ServerSharesAllowed() {
1424
+        return $this->config->getAppValue('files_sharing', 'outgoing_server2server_share_enabled', 'yes') === 'yes';
1425
+    }
1426
+
1427
+    /**
1428
+     * @inheritdoc
1429
+     */
1430
+    public function shareProviderExists($shareType) {
1431
+        try {
1432
+            $this->factory->getProviderForType($shareType);
1433
+        } catch (ProviderException $e) {
1434
+            return false;
1435
+        }
1436
+
1437
+        return true;
1438
+    }
1439 1439
 
1440 1440
 }
Please login to merge, or discard this patch.
apps/sharebymail/lib/Activity.php 1 patch
Indentation   +268 added lines, -268 removed lines patch added patch discarded remove patch
@@ -33,272 +33,272 @@
 block discarded – undo
33 33
 
34 34
 class Activity implements IProvider {
35 35
 
36
-	/** @var IFactory */
37
-	protected $languageFactory;
38
-
39
-	/** @var IL10N */
40
-	protected $l;
41
-
42
-	/** @var IURLGenerator */
43
-	protected $url;
44
-
45
-	/** @var IManager */
46
-	protected $activityManager;
47
-
48
-	/** @var IUserManager */
49
-	protected $userManager;
50
-	/** @var IContactsManager */
51
-	protected $contactsManager;
52
-
53
-	/** @var array */
54
-	protected $displayNames = [];
55
-
56
-	/** @var array */
57
-	protected $contactNames = [];
58
-
59
-	const SUBJECT_SHARED_EMAIL_SELF = 'shared_with_email_self';
60
-	const SUBJECT_SHARED_EMAIL_BY = 'shared_with_email_by';
61
-	const SUBJECT_SHARED_EMAIL_PASSWORD_SEND = 'shared_with_email_password_send';
62
-	const SUBJECT_SHARED_EMAIL_PASSWORD_SEND_SELF = 'shared_with_email_password_send_self';
63
-
64
-	/**
65
-	 * @param IFactory $languageFactory
66
-	 * @param IURLGenerator $url
67
-	 * @param IManager $activityManager
68
-	 * @param IUserManager $userManager
69
-	 * @param IContactsManager $contactsManager
70
-	 */
71
-	public function __construct(IFactory $languageFactory, IURLGenerator $url, IManager $activityManager, IUserManager $userManager, IContactsManager $contactsManager) {
72
-		$this->languageFactory = $languageFactory;
73
-		$this->url = $url;
74
-		$this->activityManager = $activityManager;
75
-		$this->userManager = $userManager;
76
-		$this->contactsManager = $contactsManager;
77
-	}
78
-
79
-	/**
80
-	 * @param string $language
81
-	 * @param IEvent $event
82
-	 * @param IEvent|null $previousEvent
83
-	 * @return IEvent
84
-	 * @throws \InvalidArgumentException
85
-	 * @since 11.0.0
86
-	 */
87
-	public function parse($language, IEvent $event, IEvent $previousEvent = null) {
88
-		if ($event->getApp() !== 'sharebymail') {
89
-			throw new \InvalidArgumentException();
90
-		}
91
-
92
-		$this->l = $this->languageFactory->get('sharebymail', $language);
93
-
94
-		if ($this->activityManager->isFormattingFilteredObject()) {
95
-			try {
96
-				return $this->parseShortVersion($event);
97
-			} catch (\InvalidArgumentException $e) {
98
-				// Ignore and simply use the long version...
99
-			}
100
-		}
101
-
102
-		return $this->parseLongVersion($event);
103
-	}
104
-
105
-	/**
106
-	 * @param IEvent $event
107
-	 * @return IEvent
108
-	 * @throws \InvalidArgumentException
109
-	 * @since 11.0.0
110
-	 */
111
-	public function parseShortVersion(IEvent $event) {
112
-		$parsedParameters = $this->getParsedParameters($event);
113
-
114
-		if ($event->getSubject() === self::SUBJECT_SHARED_EMAIL_SELF) {
115
-			$event->setParsedSubject($this->l->t('Shared with %1$s', [
116
-					$parsedParameters['email']['name'],
117
-				]))
118
-				->setRichSubject($this->l->t('Shared with {email}'), [
119
-					'email' => $parsedParameters['email'],
120
-				])
121
-				->setIcon($this->url->getAbsoluteURL($this->url->imagePath('core', 'actions/share.svg')));
122
-		} else if ($event->getSubject() === self::SUBJECT_SHARED_EMAIL_BY) {
123
-			$event->setParsedSubject($this->l->t('Shared with %1$s by %2$s', [
124
-				$parsedParameters['email']['name'],
125
-				$parsedParameters['actor']['name'],
126
-			]))
127
-				->setRichSubject($this->l->t('Shared with {email} by {actor}'), [
128
-					'email' => $parsedParameters['email'],
129
-					'actor' => $parsedParameters['actor'],
130
-				])
131
-				->setIcon($this->url->getAbsoluteURL($this->url->imagePath('core', 'actions/share.svg')));
132
-		} else if ($event->getSubject() === self::SUBJECT_SHARED_EMAIL_PASSWORD_SEND) {
133
-			$event->setParsedSubject($this->l->t('Password for mail share send to %1$s', [
134
-				$parsedParameters['email']['name']
135
-			]))
136
-				->setRichSubject($this->l->t('Password for mail share send to {email}'), [
137
-					'email' => $parsedParameters['email']
138
-				])
139
-				->setIcon($this->url->getAbsoluteURL($this->url->imagePath('core', 'actions/share.svg')));
140
-		} else if ($event->getSubject() === self::SUBJECT_SHARED_EMAIL_PASSWORD_SEND_SELF) {
141
-			$event->setParsedSubject($this->l->t('Password for mail share send to you'))
142
-				->setRichSubject($this->l->t('Password for mail share send to you'))
143
-				->setIcon($this->url->getAbsoluteURL($this->url->imagePath('core', 'actions/share.svg')));
144
-		} else {
145
-			throw new \InvalidArgumentException();
146
-		}
147
-
148
-		return $event;
149
-	}
150
-
151
-	/**
152
-	 * @param IEvent $event
153
-	 * @return IEvent
154
-	 * @throws \InvalidArgumentException
155
-	 * @since 11.0.0
156
-	 */
157
-	public function parseLongVersion(IEvent $event) {
158
-		$parsedParameters = $this->getParsedParameters($event);
159
-
160
-		if ($event->getSubject() === self::SUBJECT_SHARED_EMAIL_SELF) {
161
-			$event->setParsedSubject($this->l->t('You shared %1$s with %2$s by mail', [
162
-					$parsedParameters['file']['path'],
163
-					$parsedParameters['email']['name'],
164
-				]))
165
-				->setRichSubject($this->l->t('You shared {file} with {email} by mail'), $parsedParameters)
166
-				->setIcon($this->url->getAbsoluteURL($this->url->imagePath('core', 'actions/share.svg')));
167
-		} else if ($event->getSubject() === self::SUBJECT_SHARED_EMAIL_BY) {
168
-			$event->setParsedSubject($this->l->t('%3$s shared %1$s with %2$s by mail', [
169
-				$parsedParameters['file']['path'],
170
-				$parsedParameters['email']['name'],
171
-				$parsedParameters['actor']['name'],
172
-			]))
173
-				->setRichSubject($this->l->t('{actor} shared {file} with {email} by mail'), $parsedParameters)
174
-				->setIcon($this->url->getAbsoluteURL($this->url->imagePath('core', 'actions/share.svg')));
175
-		} else if ($event->getSubject() === self::SUBJECT_SHARED_EMAIL_PASSWORD_SEND) {
176
-			$event->setParsedSubject($this->l->t('Password to access %1$s was send to %2s', [
177
-				$parsedParameters['file']['path'],
178
-				$parsedParameters['email']['name']
179
-			]))
180
-				->setRichSubject($this->l->t('Password to access {file} was send to {email}'), $parsedParameters)
181
-				->setIcon($this->url->getAbsoluteURL($this->url->imagePath('core', 'actions/share.svg')));
182
-		} else if ($event->getSubject() === self::SUBJECT_SHARED_EMAIL_PASSWORD_SEND_SELF) {
183
-			$event->setParsedSubject(
184
-				$this->l->t('Password to access %1$s was send to you',
185
-					[$parsedParameters['file']['path']]))
186
-				->setRichSubject($this->l->t('Password to access {file} was send to you'), $parsedParameters)
187
-				->setIcon($this->url->getAbsoluteURL($this->url->imagePath('core', 'actions/share.svg')));
188
-
189
-		} else {
190
-			throw new \InvalidArgumentException();
191
-		}
192
-
193
-		return $event;
194
-	}
195
-
196
-	protected function getParsedParameters(IEvent $event) {
197
-		$subject = $event->getSubject();
198
-		$parameters = $event->getSubjectParameters();
199
-
200
-		switch ($subject) {
201
-			case self::SUBJECT_SHARED_EMAIL_SELF:
202
-				return [
203
-					'file' => $this->generateFileParameter((int) $event->getObjectId(), $parameters[0]),
204
-					'email' => $this->generateEmailParameter($parameters[1]),
205
-				];
206
-			case self::SUBJECT_SHARED_EMAIL_BY:
207
-				return [
208
-					'file' => $this->generateFileParameter((int) $event->getObjectId(), $parameters[0]),
209
-					'email' => $this->generateEmailParameter($parameters[1]),
210
-					'actor' => $this->generateUserParameter($parameters[2]),
211
-				];
212
-			case self::SUBJECT_SHARED_EMAIL_PASSWORD_SEND:
213
-				return [
214
-					'file' => $this->generateFileParameter((int) $event->getObjectId(), $parameters[0]),
215
-					'email' => $this->generateEmailParameter($parameters[1]),
216
-				];
217
-			case self::SUBJECT_SHARED_EMAIL_PASSWORD_SEND_SELF:
218
-				return [
219
-					'file' => $this->generateFileParameter((int) $event->getObjectId(), $parameters[0]),
220
-				];
221
-		}
222
-		throw new \InvalidArgumentException();
223
-	}
224
-
225
-	/**
226
-	 * @param int $id
227
-	 * @param string $path
228
-	 * @return array
229
-	 */
230
-	protected function generateFileParameter($id, $path) {
231
-		return [
232
-			'type' => 'file',
233
-			'id' => $id,
234
-			'name' => basename($path),
235
-			'path' => trim($path, '/'),
236
-			'link' => $this->url->linkToRouteAbsolute('files.viewcontroller.showFile', ['fileid' => $id]),
237
-		];
238
-	}
239
-
240
-	/**
241
-	 * @param string $email
242
-	 * @return array
243
-	 */
244
-	protected function generateEmailParameter($email) {
245
-		if (!isset($this->contactNames[$email])) {
246
-			$this->contactNames[$email] = $this->getContactName($email);
247
-		}
248
-
249
-		return [
250
-			'type' => 'email',
251
-			'id' => $email,
252
-			'name' => $this->contactNames[$email],
253
-		];
254
-	}
255
-
256
-	/**
257
-	 * @param string $uid
258
-	 * @return array
259
-	 */
260
-	protected function generateUserParameter($uid) {
261
-		if (!isset($this->displayNames[$uid])) {
262
-			$this->displayNames[$uid] = $this->getDisplayName($uid);
263
-		}
264
-
265
-		return [
266
-			'type' => 'user',
267
-			'id' => $uid,
268
-			'name' => $this->displayNames[$uid],
269
-		];
270
-	}
271
-
272
-	/**
273
-	 * @param string $email
274
-	 * @return string
275
-	 */
276
-	protected function getContactName($email) {
277
-		$addressBookContacts = $this->contactsManager->search($email, ['EMAIL']);
278
-
279
-		foreach ($addressBookContacts as $contact) {
280
-			if (isset($contact['isLocalSystemBook'])) {
281
-				continue;
282
-			}
283
-
284
-			if (in_array($email, $contact['EMAIL'])) {
285
-				return $contact['FN'];
286
-			}
287
-		}
288
-
289
-		return $email;
290
-	}
291
-
292
-	/**
293
-	 * @param string $uid
294
-	 * @return string
295
-	 */
296
-	protected function getDisplayName($uid) {
297
-		$user = $this->userManager->get($uid);
298
-		if ($user instanceof IUser) {
299
-			return $user->getDisplayName();
300
-		} else {
301
-			return $uid;
302
-		}
303
-	}
36
+    /** @var IFactory */
37
+    protected $languageFactory;
38
+
39
+    /** @var IL10N */
40
+    protected $l;
41
+
42
+    /** @var IURLGenerator */
43
+    protected $url;
44
+
45
+    /** @var IManager */
46
+    protected $activityManager;
47
+
48
+    /** @var IUserManager */
49
+    protected $userManager;
50
+    /** @var IContactsManager */
51
+    protected $contactsManager;
52
+
53
+    /** @var array */
54
+    protected $displayNames = [];
55
+
56
+    /** @var array */
57
+    protected $contactNames = [];
58
+
59
+    const SUBJECT_SHARED_EMAIL_SELF = 'shared_with_email_self';
60
+    const SUBJECT_SHARED_EMAIL_BY = 'shared_with_email_by';
61
+    const SUBJECT_SHARED_EMAIL_PASSWORD_SEND = 'shared_with_email_password_send';
62
+    const SUBJECT_SHARED_EMAIL_PASSWORD_SEND_SELF = 'shared_with_email_password_send_self';
63
+
64
+    /**
65
+     * @param IFactory $languageFactory
66
+     * @param IURLGenerator $url
67
+     * @param IManager $activityManager
68
+     * @param IUserManager $userManager
69
+     * @param IContactsManager $contactsManager
70
+     */
71
+    public function __construct(IFactory $languageFactory, IURLGenerator $url, IManager $activityManager, IUserManager $userManager, IContactsManager $contactsManager) {
72
+        $this->languageFactory = $languageFactory;
73
+        $this->url = $url;
74
+        $this->activityManager = $activityManager;
75
+        $this->userManager = $userManager;
76
+        $this->contactsManager = $contactsManager;
77
+    }
78
+
79
+    /**
80
+     * @param string $language
81
+     * @param IEvent $event
82
+     * @param IEvent|null $previousEvent
83
+     * @return IEvent
84
+     * @throws \InvalidArgumentException
85
+     * @since 11.0.0
86
+     */
87
+    public function parse($language, IEvent $event, IEvent $previousEvent = null) {
88
+        if ($event->getApp() !== 'sharebymail') {
89
+            throw new \InvalidArgumentException();
90
+        }
91
+
92
+        $this->l = $this->languageFactory->get('sharebymail', $language);
93
+
94
+        if ($this->activityManager->isFormattingFilteredObject()) {
95
+            try {
96
+                return $this->parseShortVersion($event);
97
+            } catch (\InvalidArgumentException $e) {
98
+                // Ignore and simply use the long version...
99
+            }
100
+        }
101
+
102
+        return $this->parseLongVersion($event);
103
+    }
104
+
105
+    /**
106
+     * @param IEvent $event
107
+     * @return IEvent
108
+     * @throws \InvalidArgumentException
109
+     * @since 11.0.0
110
+     */
111
+    public function parseShortVersion(IEvent $event) {
112
+        $parsedParameters = $this->getParsedParameters($event);
113
+
114
+        if ($event->getSubject() === self::SUBJECT_SHARED_EMAIL_SELF) {
115
+            $event->setParsedSubject($this->l->t('Shared with %1$s', [
116
+                    $parsedParameters['email']['name'],
117
+                ]))
118
+                ->setRichSubject($this->l->t('Shared with {email}'), [
119
+                    'email' => $parsedParameters['email'],
120
+                ])
121
+                ->setIcon($this->url->getAbsoluteURL($this->url->imagePath('core', 'actions/share.svg')));
122
+        } else if ($event->getSubject() === self::SUBJECT_SHARED_EMAIL_BY) {
123
+            $event->setParsedSubject($this->l->t('Shared with %1$s by %2$s', [
124
+                $parsedParameters['email']['name'],
125
+                $parsedParameters['actor']['name'],
126
+            ]))
127
+                ->setRichSubject($this->l->t('Shared with {email} by {actor}'), [
128
+                    'email' => $parsedParameters['email'],
129
+                    'actor' => $parsedParameters['actor'],
130
+                ])
131
+                ->setIcon($this->url->getAbsoluteURL($this->url->imagePath('core', 'actions/share.svg')));
132
+        } else if ($event->getSubject() === self::SUBJECT_SHARED_EMAIL_PASSWORD_SEND) {
133
+            $event->setParsedSubject($this->l->t('Password for mail share send to %1$s', [
134
+                $parsedParameters['email']['name']
135
+            ]))
136
+                ->setRichSubject($this->l->t('Password for mail share send to {email}'), [
137
+                    'email' => $parsedParameters['email']
138
+                ])
139
+                ->setIcon($this->url->getAbsoluteURL($this->url->imagePath('core', 'actions/share.svg')));
140
+        } else if ($event->getSubject() === self::SUBJECT_SHARED_EMAIL_PASSWORD_SEND_SELF) {
141
+            $event->setParsedSubject($this->l->t('Password for mail share send to you'))
142
+                ->setRichSubject($this->l->t('Password for mail share send to you'))
143
+                ->setIcon($this->url->getAbsoluteURL($this->url->imagePath('core', 'actions/share.svg')));
144
+        } else {
145
+            throw new \InvalidArgumentException();
146
+        }
147
+
148
+        return $event;
149
+    }
150
+
151
+    /**
152
+     * @param IEvent $event
153
+     * @return IEvent
154
+     * @throws \InvalidArgumentException
155
+     * @since 11.0.0
156
+     */
157
+    public function parseLongVersion(IEvent $event) {
158
+        $parsedParameters = $this->getParsedParameters($event);
159
+
160
+        if ($event->getSubject() === self::SUBJECT_SHARED_EMAIL_SELF) {
161
+            $event->setParsedSubject($this->l->t('You shared %1$s with %2$s by mail', [
162
+                    $parsedParameters['file']['path'],
163
+                    $parsedParameters['email']['name'],
164
+                ]))
165
+                ->setRichSubject($this->l->t('You shared {file} with {email} by mail'), $parsedParameters)
166
+                ->setIcon($this->url->getAbsoluteURL($this->url->imagePath('core', 'actions/share.svg')));
167
+        } else if ($event->getSubject() === self::SUBJECT_SHARED_EMAIL_BY) {
168
+            $event->setParsedSubject($this->l->t('%3$s shared %1$s with %2$s by mail', [
169
+                $parsedParameters['file']['path'],
170
+                $parsedParameters['email']['name'],
171
+                $parsedParameters['actor']['name'],
172
+            ]))
173
+                ->setRichSubject($this->l->t('{actor} shared {file} with {email} by mail'), $parsedParameters)
174
+                ->setIcon($this->url->getAbsoluteURL($this->url->imagePath('core', 'actions/share.svg')));
175
+        } else if ($event->getSubject() === self::SUBJECT_SHARED_EMAIL_PASSWORD_SEND) {
176
+            $event->setParsedSubject($this->l->t('Password to access %1$s was send to %2s', [
177
+                $parsedParameters['file']['path'],
178
+                $parsedParameters['email']['name']
179
+            ]))
180
+                ->setRichSubject($this->l->t('Password to access {file} was send to {email}'), $parsedParameters)
181
+                ->setIcon($this->url->getAbsoluteURL($this->url->imagePath('core', 'actions/share.svg')));
182
+        } else if ($event->getSubject() === self::SUBJECT_SHARED_EMAIL_PASSWORD_SEND_SELF) {
183
+            $event->setParsedSubject(
184
+                $this->l->t('Password to access %1$s was send to you',
185
+                    [$parsedParameters['file']['path']]))
186
+                ->setRichSubject($this->l->t('Password to access {file} was send to you'), $parsedParameters)
187
+                ->setIcon($this->url->getAbsoluteURL($this->url->imagePath('core', 'actions/share.svg')));
188
+
189
+        } else {
190
+            throw new \InvalidArgumentException();
191
+        }
192
+
193
+        return $event;
194
+    }
195
+
196
+    protected function getParsedParameters(IEvent $event) {
197
+        $subject = $event->getSubject();
198
+        $parameters = $event->getSubjectParameters();
199
+
200
+        switch ($subject) {
201
+            case self::SUBJECT_SHARED_EMAIL_SELF:
202
+                return [
203
+                    'file' => $this->generateFileParameter((int) $event->getObjectId(), $parameters[0]),
204
+                    'email' => $this->generateEmailParameter($parameters[1]),
205
+                ];
206
+            case self::SUBJECT_SHARED_EMAIL_BY:
207
+                return [
208
+                    'file' => $this->generateFileParameter((int) $event->getObjectId(), $parameters[0]),
209
+                    'email' => $this->generateEmailParameter($parameters[1]),
210
+                    'actor' => $this->generateUserParameter($parameters[2]),
211
+                ];
212
+            case self::SUBJECT_SHARED_EMAIL_PASSWORD_SEND:
213
+                return [
214
+                    'file' => $this->generateFileParameter((int) $event->getObjectId(), $parameters[0]),
215
+                    'email' => $this->generateEmailParameter($parameters[1]),
216
+                ];
217
+            case self::SUBJECT_SHARED_EMAIL_PASSWORD_SEND_SELF:
218
+                return [
219
+                    'file' => $this->generateFileParameter((int) $event->getObjectId(), $parameters[0]),
220
+                ];
221
+        }
222
+        throw new \InvalidArgumentException();
223
+    }
224
+
225
+    /**
226
+     * @param int $id
227
+     * @param string $path
228
+     * @return array
229
+     */
230
+    protected function generateFileParameter($id, $path) {
231
+        return [
232
+            'type' => 'file',
233
+            'id' => $id,
234
+            'name' => basename($path),
235
+            'path' => trim($path, '/'),
236
+            'link' => $this->url->linkToRouteAbsolute('files.viewcontroller.showFile', ['fileid' => $id]),
237
+        ];
238
+    }
239
+
240
+    /**
241
+     * @param string $email
242
+     * @return array
243
+     */
244
+    protected function generateEmailParameter($email) {
245
+        if (!isset($this->contactNames[$email])) {
246
+            $this->contactNames[$email] = $this->getContactName($email);
247
+        }
248
+
249
+        return [
250
+            'type' => 'email',
251
+            'id' => $email,
252
+            'name' => $this->contactNames[$email],
253
+        ];
254
+    }
255
+
256
+    /**
257
+     * @param string $uid
258
+     * @return array
259
+     */
260
+    protected function generateUserParameter($uid) {
261
+        if (!isset($this->displayNames[$uid])) {
262
+            $this->displayNames[$uid] = $this->getDisplayName($uid);
263
+        }
264
+
265
+        return [
266
+            'type' => 'user',
267
+            'id' => $uid,
268
+            'name' => $this->displayNames[$uid],
269
+        ];
270
+    }
271
+
272
+    /**
273
+     * @param string $email
274
+     * @return string
275
+     */
276
+    protected function getContactName($email) {
277
+        $addressBookContacts = $this->contactsManager->search($email, ['EMAIL']);
278
+
279
+        foreach ($addressBookContacts as $contact) {
280
+            if (isset($contact['isLocalSystemBook'])) {
281
+                continue;
282
+            }
283
+
284
+            if (in_array($email, $contact['EMAIL'])) {
285
+                return $contact['FN'];
286
+            }
287
+        }
288
+
289
+        return $email;
290
+    }
291
+
292
+    /**
293
+     * @param string $uid
294
+     * @return string
295
+     */
296
+    protected function getDisplayName($uid) {
297
+        $user = $this->userManager->get($uid);
298
+        if ($user instanceof IUser) {
299
+            return $user->getDisplayName();
300
+        } else {
301
+            return $uid;
302
+        }
303
+    }
304 304
 }
Please login to merge, or discard this patch.
lib/private/Share20/ProviderFactory.php 1 patch
Indentation   +213 added lines, -213 removed lines patch added patch discarded remove patch
@@ -43,224 +43,224 @@
 block discarded – undo
43 43
  */
44 44
 class ProviderFactory implements IProviderFactory {
45 45
 
46
-	/** @var IServerContainer */
47
-	private $serverContainer;
48
-	/** @var DefaultShareProvider */
49
-	private $defaultProvider = null;
50
-	/** @var FederatedShareProvider */
51
-	private $federatedProvider = null;
52
-	/** @var  ShareByMailProvider */
53
-	private $shareByMailProvider;
54
-	/** @var  \OCA\Circles\ShareByCircleProvider;
55
-	 * ShareByCircleProvider */
56
-	private $shareByCircleProvider;
57
-
58
-	/**
59
-	 * IProviderFactory constructor.
60
-	 *
61
-	 * @param IServerContainer $serverContainer
62
-	 */
63
-	public function __construct(IServerContainer $serverContainer) {
64
-		$this->serverContainer = $serverContainer;
65
-	}
66
-
67
-	/**
68
-	 * Create the default share provider.
69
-	 *
70
-	 * @return DefaultShareProvider
71
-	 */
72
-	protected function defaultShareProvider() {
73
-		if ($this->defaultProvider === null) {
74
-			$this->defaultProvider = new DefaultShareProvider(
75
-				$this->serverContainer->getDatabaseConnection(),
76
-				$this->serverContainer->getUserManager(),
77
-				$this->serverContainer->getGroupManager(),
78
-				$this->serverContainer->getLazyRootFolder()
79
-			);
80
-		}
81
-
82
-		return $this->defaultProvider;
83
-	}
84
-
85
-	/**
86
-	 * Create the federated share provider
87
-	 *
88
-	 * @return FederatedShareProvider
89
-	 */
90
-	protected function federatedShareProvider() {
91
-		if ($this->federatedProvider === null) {
92
-			/*
46
+    /** @var IServerContainer */
47
+    private $serverContainer;
48
+    /** @var DefaultShareProvider */
49
+    private $defaultProvider = null;
50
+    /** @var FederatedShareProvider */
51
+    private $federatedProvider = null;
52
+    /** @var  ShareByMailProvider */
53
+    private $shareByMailProvider;
54
+    /** @var  \OCA\Circles\ShareByCircleProvider;
55
+     * ShareByCircleProvider */
56
+    private $shareByCircleProvider;
57
+
58
+    /**
59
+     * IProviderFactory constructor.
60
+     *
61
+     * @param IServerContainer $serverContainer
62
+     */
63
+    public function __construct(IServerContainer $serverContainer) {
64
+        $this->serverContainer = $serverContainer;
65
+    }
66
+
67
+    /**
68
+     * Create the default share provider.
69
+     *
70
+     * @return DefaultShareProvider
71
+     */
72
+    protected function defaultShareProvider() {
73
+        if ($this->defaultProvider === null) {
74
+            $this->defaultProvider = new DefaultShareProvider(
75
+                $this->serverContainer->getDatabaseConnection(),
76
+                $this->serverContainer->getUserManager(),
77
+                $this->serverContainer->getGroupManager(),
78
+                $this->serverContainer->getLazyRootFolder()
79
+            );
80
+        }
81
+
82
+        return $this->defaultProvider;
83
+    }
84
+
85
+    /**
86
+     * Create the federated share provider
87
+     *
88
+     * @return FederatedShareProvider
89
+     */
90
+    protected function federatedShareProvider() {
91
+        if ($this->federatedProvider === null) {
92
+            /*
93 93
 			 * Check if the app is enabled
94 94
 			 */
95
-			$appManager = $this->serverContainer->getAppManager();
96
-			if (!$appManager->isEnabledForUser('federatedfilesharing')) {
97
-				return null;
98
-			}
95
+            $appManager = $this->serverContainer->getAppManager();
96
+            if (!$appManager->isEnabledForUser('federatedfilesharing')) {
97
+                return null;
98
+            }
99 99
 
100
-			/*
100
+            /*
101 101
 			 * TODO: add factory to federated sharing app
102 102
 			 */
103
-			$l = $this->serverContainer->getL10N('federatedfilessharing');
104
-			$addressHandler = new AddressHandler(
105
-				$this->serverContainer->getURLGenerator(),
106
-				$l,
107
-				$this->serverContainer->getCloudIdManager()
108
-			);
109
-			$notifications = new Notifications(
110
-				$addressHandler,
111
-				$this->serverContainer->getHTTPClientService(),
112
-				$this->serverContainer->query(\OCP\OCS\IDiscoveryService::class),
113
-				$this->serverContainer->getJobList()
114
-			);
115
-			$tokenHandler = new TokenHandler(
116
-				$this->serverContainer->getSecureRandom()
117
-			);
118
-
119
-			$this->federatedProvider = new FederatedShareProvider(
120
-				$this->serverContainer->getDatabaseConnection(),
121
-				$addressHandler,
122
-				$notifications,
123
-				$tokenHandler,
124
-				$l,
125
-				$this->serverContainer->getLogger(),
126
-				$this->serverContainer->getLazyRootFolder(),
127
-				$this->serverContainer->getConfig(),
128
-				$this->serverContainer->getUserManager(),
129
-				$this->serverContainer->getCloudIdManager()
130
-			);
131
-		}
132
-
133
-		return $this->federatedProvider;
134
-	}
135
-
136
-	/**
137
-	 * Create the federated share provider
138
-	 *
139
-	 * @return ShareByMailProvider
140
-	 */
141
-	protected function getShareByMailProvider() {
142
-		if ($this->shareByMailProvider === null) {
143
-			/*
103
+            $l = $this->serverContainer->getL10N('federatedfilessharing');
104
+            $addressHandler = new AddressHandler(
105
+                $this->serverContainer->getURLGenerator(),
106
+                $l,
107
+                $this->serverContainer->getCloudIdManager()
108
+            );
109
+            $notifications = new Notifications(
110
+                $addressHandler,
111
+                $this->serverContainer->getHTTPClientService(),
112
+                $this->serverContainer->query(\OCP\OCS\IDiscoveryService::class),
113
+                $this->serverContainer->getJobList()
114
+            );
115
+            $tokenHandler = new TokenHandler(
116
+                $this->serverContainer->getSecureRandom()
117
+            );
118
+
119
+            $this->federatedProvider = new FederatedShareProvider(
120
+                $this->serverContainer->getDatabaseConnection(),
121
+                $addressHandler,
122
+                $notifications,
123
+                $tokenHandler,
124
+                $l,
125
+                $this->serverContainer->getLogger(),
126
+                $this->serverContainer->getLazyRootFolder(),
127
+                $this->serverContainer->getConfig(),
128
+                $this->serverContainer->getUserManager(),
129
+                $this->serverContainer->getCloudIdManager()
130
+            );
131
+        }
132
+
133
+        return $this->federatedProvider;
134
+    }
135
+
136
+    /**
137
+     * Create the federated share provider
138
+     *
139
+     * @return ShareByMailProvider
140
+     */
141
+    protected function getShareByMailProvider() {
142
+        if ($this->shareByMailProvider === null) {
143
+            /*
144 144
 			 * Check if the app is enabled
145 145
 			 */
146
-			$appManager = $this->serverContainer->getAppManager();
147
-			if (!$appManager->isEnabledForUser('sharebymail')) {
148
-				return null;
149
-			}
150
-
151
-			$settingsManager = new SettingsManager($this->serverContainer->getConfig());
152
-
153
-			$this->shareByMailProvider = new ShareByMailProvider(
154
-				$this->serverContainer->getDatabaseConnection(),
155
-				$this->serverContainer->getSecureRandom(),
156
-				$this->serverContainer->getUserManager(),
157
-				$this->serverContainer->getLazyRootFolder(),
158
-				$this->serverContainer->getL10N('sharebymail'),
159
-				$this->serverContainer->getLogger(),
160
-				$this->serverContainer->getMailer(),
161
-				$this->serverContainer->getURLGenerator(),
162
-				$this->serverContainer->getActivityManager(),
163
-				$settingsManager,
164
-				$this->serverContainer->query(Defaults::class),
165
-				$this->serverContainer->getHasher(),
166
-				$this->serverContainer->query(CapabilitiesManager::class)
167
-			);
168
-		}
169
-
170
-		return $this->shareByMailProvider;
171
-	}
172
-
173
-
174
-	/**
175
-	 * Create the circle share provider
176
-	 *
177
-	 * @return FederatedShareProvider
178
-	 */
179
-	protected function getShareByCircleProvider() {
180
-
181
-		$appManager = $this->serverContainer->getAppManager();
182
-		if (!$appManager->isEnabledForUser('circles')) {
183
-			return null;
184
-		}
185
-
186
-
187
-		if ($this->shareByCircleProvider === null) {
188
-
189
-			$this->shareByCircleProvider = new \OCA\Circles\ShareByCircleProvider(
190
-				$this->serverContainer->getDatabaseConnection(),
191
-				$this->serverContainer->getSecureRandom(),
192
-				$this->serverContainer->getUserManager(),
193
-				$this->serverContainer->getLazyRootFolder(),
194
-				$this->serverContainer->getL10N('circles'),
195
-				$this->serverContainer->getLogger(),
196
-				$this->serverContainer->getURLGenerator()
197
-			);
198
-		}
199
-
200
-		return $this->shareByCircleProvider;
201
-	}
202
-
203
-
204
-	/**
205
-	 * @inheritdoc
206
-	 */
207
-	public function getProvider($id) {
208
-		$provider = null;
209
-		if ($id === 'ocinternal') {
210
-			$provider = $this->defaultShareProvider();
211
-		} else if ($id === 'ocFederatedSharing') {
212
-			$provider = $this->federatedShareProvider();
213
-		} else if ($id === 'ocMailShare') {
214
-			$provider = $this->getShareByMailProvider();
215
-		} else if ($id === 'ocCircleShare') {
216
-			$provider = $this->getShareByCircleProvider();
217
-		}
218
-
219
-		if ($provider === null) {
220
-			throw new ProviderException('No provider with id .' . $id . ' found.');
221
-		}
222
-
223
-		return $provider;
224
-	}
225
-
226
-	/**
227
-	 * @inheritdoc
228
-	 */
229
-	public function getProviderForType($shareType) {
230
-		$provider = null;
231
-
232
-		if ($shareType === \OCP\Share::SHARE_TYPE_USER ||
233
-			$shareType === \OCP\Share::SHARE_TYPE_GROUP ||
234
-			$shareType === \OCP\Share::SHARE_TYPE_LINK
235
-		) {
236
-			$provider = $this->defaultShareProvider();
237
-		} else if ($shareType === \OCP\Share::SHARE_TYPE_REMOTE) {
238
-			$provider = $this->federatedShareProvider();
239
-		} else if ($shareType === \OCP\Share::SHARE_TYPE_EMAIL) {
240
-			$provider = $this->getShareByMailProvider();
241
-		} else if ($shareType === \OCP\Share::SHARE_TYPE_CIRCLE) {
242
-			$provider = $this->getShareByCircleProvider();
243
-		}
244
-
245
-
246
-		if ($provider === null) {
247
-			throw new ProviderException('No share provider for share type ' . $shareType);
248
-		}
249
-
250
-		return $provider;
251
-	}
252
-
253
-	public function getAllProviders() {
254
-		$shares = [$this->defaultShareProvider(), $this->federatedShareProvider()];
255
-		$shareByMail = $this->getShareByMailProvider();
256
-		if ($shareByMail !== null) {
257
-			$shares[] = $shareByMail;
258
-		}
259
-		$shareByCircle = $this->getShareByCircleProvider();
260
-		if ($shareByCircle !== null) {
261
-			$shares[] = $shareByCircle;
262
-		}
263
-
264
-		return $shares;
265
-	}
146
+            $appManager = $this->serverContainer->getAppManager();
147
+            if (!$appManager->isEnabledForUser('sharebymail')) {
148
+                return null;
149
+            }
150
+
151
+            $settingsManager = new SettingsManager($this->serverContainer->getConfig());
152
+
153
+            $this->shareByMailProvider = new ShareByMailProvider(
154
+                $this->serverContainer->getDatabaseConnection(),
155
+                $this->serverContainer->getSecureRandom(),
156
+                $this->serverContainer->getUserManager(),
157
+                $this->serverContainer->getLazyRootFolder(),
158
+                $this->serverContainer->getL10N('sharebymail'),
159
+                $this->serverContainer->getLogger(),
160
+                $this->serverContainer->getMailer(),
161
+                $this->serverContainer->getURLGenerator(),
162
+                $this->serverContainer->getActivityManager(),
163
+                $settingsManager,
164
+                $this->serverContainer->query(Defaults::class),
165
+                $this->serverContainer->getHasher(),
166
+                $this->serverContainer->query(CapabilitiesManager::class)
167
+            );
168
+        }
169
+
170
+        return $this->shareByMailProvider;
171
+    }
172
+
173
+
174
+    /**
175
+     * Create the circle share provider
176
+     *
177
+     * @return FederatedShareProvider
178
+     */
179
+    protected function getShareByCircleProvider() {
180
+
181
+        $appManager = $this->serverContainer->getAppManager();
182
+        if (!$appManager->isEnabledForUser('circles')) {
183
+            return null;
184
+        }
185
+
186
+
187
+        if ($this->shareByCircleProvider === null) {
188
+
189
+            $this->shareByCircleProvider = new \OCA\Circles\ShareByCircleProvider(
190
+                $this->serverContainer->getDatabaseConnection(),
191
+                $this->serverContainer->getSecureRandom(),
192
+                $this->serverContainer->getUserManager(),
193
+                $this->serverContainer->getLazyRootFolder(),
194
+                $this->serverContainer->getL10N('circles'),
195
+                $this->serverContainer->getLogger(),
196
+                $this->serverContainer->getURLGenerator()
197
+            );
198
+        }
199
+
200
+        return $this->shareByCircleProvider;
201
+    }
202
+
203
+
204
+    /**
205
+     * @inheritdoc
206
+     */
207
+    public function getProvider($id) {
208
+        $provider = null;
209
+        if ($id === 'ocinternal') {
210
+            $provider = $this->defaultShareProvider();
211
+        } else if ($id === 'ocFederatedSharing') {
212
+            $provider = $this->federatedShareProvider();
213
+        } else if ($id === 'ocMailShare') {
214
+            $provider = $this->getShareByMailProvider();
215
+        } else if ($id === 'ocCircleShare') {
216
+            $provider = $this->getShareByCircleProvider();
217
+        }
218
+
219
+        if ($provider === null) {
220
+            throw new ProviderException('No provider with id .' . $id . ' found.');
221
+        }
222
+
223
+        return $provider;
224
+    }
225
+
226
+    /**
227
+     * @inheritdoc
228
+     */
229
+    public function getProviderForType($shareType) {
230
+        $provider = null;
231
+
232
+        if ($shareType === \OCP\Share::SHARE_TYPE_USER ||
233
+            $shareType === \OCP\Share::SHARE_TYPE_GROUP ||
234
+            $shareType === \OCP\Share::SHARE_TYPE_LINK
235
+        ) {
236
+            $provider = $this->defaultShareProvider();
237
+        } else if ($shareType === \OCP\Share::SHARE_TYPE_REMOTE) {
238
+            $provider = $this->federatedShareProvider();
239
+        } else if ($shareType === \OCP\Share::SHARE_TYPE_EMAIL) {
240
+            $provider = $this->getShareByMailProvider();
241
+        } else if ($shareType === \OCP\Share::SHARE_TYPE_CIRCLE) {
242
+            $provider = $this->getShareByCircleProvider();
243
+        }
244
+
245
+
246
+        if ($provider === null) {
247
+            throw new ProviderException('No share provider for share type ' . $shareType);
248
+        }
249
+
250
+        return $provider;
251
+    }
252
+
253
+    public function getAllProviders() {
254
+        $shares = [$this->defaultShareProvider(), $this->federatedShareProvider()];
255
+        $shareByMail = $this->getShareByMailProvider();
256
+        if ($shareByMail !== null) {
257
+            $shares[] = $shareByMail;
258
+        }
259
+        $shareByCircle = $this->getShareByCircleProvider();
260
+        if ($shareByCircle !== null) {
261
+            $shares[] = $shareByCircle;
262
+        }
263
+
264
+        return $shares;
265
+    }
266 266
 }
Please login to merge, or discard this patch.