Completed
Pull Request — master (#3614)
by Björn
12:05
created
apps/federation/lib/BackgroundJob/GetSharedSecret.php 2 patches
Spacing   +5 added lines, -5 removed lines patch added patch discarded remove patch
@@ -46,7 +46,7 @@  discard block
 block discarded – undo
46 46
  *
47 47
  * @package OCA\Federation\Backgroundjob
48 48
  */
49
-class GetSharedSecret extends Job{
49
+class GetSharedSecret extends Job {
50 50
 
51 51
 	/** @var IClient */
52 52
 	private $httpClient;
@@ -155,7 +155,7 @@  discard block
 block discarded – undo
155 155
 		$endPoint = isset($endPoints['shared-secret']) ? $endPoints['shared-secret'] : $this->defaultEndPoint;
156 156
 
157 157
 		// make sure that we have a well formated url
158
-		$url = rtrim($target, '/') . '/' . trim($endPoint, '/') . $this->format;
158
+		$url = rtrim($target, '/').'/'.trim($endPoint, '/').$this->format;
159 159
 
160 160
 		$result = null;
161 161
 		try {
@@ -177,7 +177,7 @@  discard block
 block discarded – undo
177 177
 		} catch (ClientException $e) {
178 178
 			$status = $e->getCode();
179 179
 			if ($status === Http::STATUS_FORBIDDEN) {
180
-				$this->logger->info($target . ' refused to exchange a shared secret with you.', ['app' => 'federation']);
180
+				$this->logger->info($target.' refused to exchange a shared secret with you.', ['app' => 'federation']);
181 181
 			} else {
182 182
 				$this->logger->logException($e, ['app' => 'federation']);
183 183
 			}
@@ -192,7 +192,7 @@  discard block
 block discarded – undo
192 192
 			&& $status !== Http::STATUS_FORBIDDEN
193 193
 		) {
194 194
 			$this->retainJob = true;
195
-		}  else {
195
+		} else {
196 196
 			// reset token if we received a valid response
197 197
 			$this->dbHandler->addToken($target, '');
198 198
 		}
@@ -207,7 +207,7 @@  discard block
 block discarded – undo
207 207
 				);
208 208
 			} else {
209 209
 				$this->logger->error(
210
-						'remote server "' . $target . '"" does not return a valid shared secret',
210
+						'remote server "'.$target.'"" does not return a valid shared secret',
211 211
 						['app' => 'federation']
212 212
 				);
213 213
 				$this->trustedServers->setServerStatus($target, TrustedServers::STATUS_FAILURE);
Please login to merge, or discard this patch.
Indentation   +167 added lines, -167 removed lines patch added patch discarded remove patch
@@ -48,171 +48,171 @@
 block discarded – undo
48 48
  */
49 49
 class GetSharedSecret extends Job{
50 50
 
51
-	/** @var IClient */
52
-	private $httpClient;
53
-
54
-	/** @var IJobList */
55
-	private $jobList;
56
-
57
-	/** @var IURLGenerator */
58
-	private $urlGenerator;
59
-
60
-	/** @var TrustedServers  */
61
-	private $trustedServers;
62
-
63
-	/** @var DbHandler */
64
-	private $dbHandler;
65
-
66
-	/** @var IDiscoveryService  */
67
-	private $ocsDiscoveryService;
68
-
69
-	/** @var ILogger */
70
-	private $logger;
71
-
72
-	/** @var bool */
73
-	protected $retainJob = false;
74
-
75
-	private $format = '?format=json';
76
-
77
-	private $defaultEndPoint = '/ocs/v2.php/apps/federation/api/v1/shared-secret';
78
-
79
-	/**
80
-	 * RequestSharedSecret constructor.
81
-	 *
82
-	 * @param IClient $httpClient
83
-	 * @param IURLGenerator $urlGenerator
84
-	 * @param IJobList $jobList
85
-	 * @param TrustedServers $trustedServers
86
-	 * @param ILogger $logger
87
-	 * @param DbHandler $dbHandler
88
-	 * @param IDiscoveryService $ocsDiscoveryService
89
-	 */
90
-	public function __construct(
91
-		IClient $httpClient = null,
92
-		IURLGenerator $urlGenerator = null,
93
-		IJobList $jobList = null,
94
-		TrustedServers $trustedServers = null,
95
-		ILogger $logger = null,
96
-		DbHandler $dbHandler = null,
97
-		IDiscoveryService $ocsDiscoveryService = null
98
-	) {
99
-		$this->logger = $logger ? $logger : \OC::$server->getLogger();
100
-		$this->httpClient = $httpClient ? $httpClient : \OC::$server->getHTTPClientService()->newClient();
101
-		$this->jobList = $jobList ? $jobList : \OC::$server->getJobList();
102
-		$this->urlGenerator = $urlGenerator ? $urlGenerator : \OC::$server->getURLGenerator();
103
-		$this->dbHandler = $dbHandler ? $dbHandler : new DbHandler(\OC::$server->getDatabaseConnection(), \OC::$server->getL10N('federation'));
104
-		$this->ocsDiscoveryService = $ocsDiscoveryService ? $ocsDiscoveryService : \OC::$server->getOCSDiscoveryService();
105
-		if ($trustedServers) {
106
-			$this->trustedServers = $trustedServers;
107
-		} else {
108
-			$this->trustedServers = new TrustedServers(
109
-				$this->dbHandler,
110
-				\OC::$server->getHTTPClientService(),
111
-				$this->logger,
112
-				$this->jobList,
113
-				\OC::$server->getSecureRandom(),
114
-				\OC::$server->getConfig(),
115
-				\OC::$server->getEventDispatcher()
116
-			);
117
-		}
118
-	}
119
-
120
-	/**
121
-	 * run the job, then remove it from the joblist
122
-	 *
123
-	 * @param JobList $jobList
124
-	 * @param ILogger $logger
125
-	 */
126
-	public function execute($jobList, ILogger $logger = null) {
127
-		$target = $this->argument['url'];
128
-		// only execute if target is still in the list of trusted domains
129
-		if ($this->trustedServers->isTrustedServer($target)) {
130
-			$this->parentExecute($jobList, $logger);
131
-		}
132
-
133
-		if (!$this->retainJob) {
134
-			$jobList->remove($this, $this->argument);
135
-		}
136
-	}
137
-
138
-	/**
139
-	 * call execute() method of parent
140
-	 *
141
-	 * @param JobList $jobList
142
-	 * @param ILogger $logger
143
-	 */
144
-	protected function parentExecute($jobList, $logger = null) {
145
-		parent::execute($jobList, $logger);
146
-	}
147
-
148
-	protected function run($argument) {
149
-		$target = $argument['url'];
150
-		$source = $this->urlGenerator->getAbsoluteURL('/');
151
-		$source = rtrim($source, '/');
152
-		$token = $argument['token'];
153
-
154
-		$endPoints = $this->ocsDiscoveryService->discover($target, 'FEDERATED_SHARING');
155
-		$endPoint = isset($endPoints['shared-secret']) ? $endPoints['shared-secret'] : $this->defaultEndPoint;
156
-
157
-		// make sure that we have a well formated url
158
-		$url = rtrim($target, '/') . '/' . trim($endPoint, '/') . $this->format;
159
-
160
-		$result = null;
161
-		try {
162
-			$result = $this->httpClient->get(
163
-				$url,
164
-				[
165
-					'query' =>
166
-						[
167
-							'url' => $source,
168
-							'token' => $token
169
-						],
170
-					'timeout' => 3,
171
-					'connect_timeout' => 3,
172
-				]
173
-			);
174
-
175
-			$status = $result->getStatusCode();
176
-
177
-		} catch (ClientException $e) {
178
-			$status = $e->getCode();
179
-			if ($status === Http::STATUS_FORBIDDEN) {
180
-				$this->logger->info($target . ' refused to exchange a shared secret with you.', ['app' => 'federation']);
181
-			} else {
182
-				$this->logger->logException($e, ['app' => 'federation']);
183
-			}
184
-		} catch (\Exception $e) {
185
-			$status = Http::STATUS_INTERNAL_SERVER_ERROR;
186
-			$this->logger->logException($e, ['app' => 'federation']);
187
-		}
188
-
189
-		// if we received a unexpected response we try again later
190
-		if (
191
-			$status !== Http::STATUS_OK
192
-			&& $status !== Http::STATUS_FORBIDDEN
193
-		) {
194
-			$this->retainJob = true;
195
-		}  else {
196
-			// reset token if we received a valid response
197
-			$this->dbHandler->addToken($target, '');
198
-		}
199
-
200
-		if ($status === Http::STATUS_OK && $result instanceof IResponse) {
201
-			$body = $result->getBody();
202
-			$result = json_decode($body, true);
203
-			if (isset($result['ocs']['data']['sharedSecret'])) {
204
-				$this->trustedServers->addSharedSecret(
205
-						$target,
206
-						$result['ocs']['data']['sharedSecret']
207
-				);
208
-			} else {
209
-				$this->logger->error(
210
-						'remote server "' . $target . '"" does not return a valid shared secret',
211
-						['app' => 'federation']
212
-				);
213
-				$this->trustedServers->setServerStatus($target, TrustedServers::STATUS_FAILURE);
214
-			}
215
-		}
216
-
217
-	}
51
+    /** @var IClient */
52
+    private $httpClient;
53
+
54
+    /** @var IJobList */
55
+    private $jobList;
56
+
57
+    /** @var IURLGenerator */
58
+    private $urlGenerator;
59
+
60
+    /** @var TrustedServers  */
61
+    private $trustedServers;
62
+
63
+    /** @var DbHandler */
64
+    private $dbHandler;
65
+
66
+    /** @var IDiscoveryService  */
67
+    private $ocsDiscoveryService;
68
+
69
+    /** @var ILogger */
70
+    private $logger;
71
+
72
+    /** @var bool */
73
+    protected $retainJob = false;
74
+
75
+    private $format = '?format=json';
76
+
77
+    private $defaultEndPoint = '/ocs/v2.php/apps/federation/api/v1/shared-secret';
78
+
79
+    /**
80
+     * RequestSharedSecret constructor.
81
+     *
82
+     * @param IClient $httpClient
83
+     * @param IURLGenerator $urlGenerator
84
+     * @param IJobList $jobList
85
+     * @param TrustedServers $trustedServers
86
+     * @param ILogger $logger
87
+     * @param DbHandler $dbHandler
88
+     * @param IDiscoveryService $ocsDiscoveryService
89
+     */
90
+    public function __construct(
91
+        IClient $httpClient = null,
92
+        IURLGenerator $urlGenerator = null,
93
+        IJobList $jobList = null,
94
+        TrustedServers $trustedServers = null,
95
+        ILogger $logger = null,
96
+        DbHandler $dbHandler = null,
97
+        IDiscoveryService $ocsDiscoveryService = null
98
+    ) {
99
+        $this->logger = $logger ? $logger : \OC::$server->getLogger();
100
+        $this->httpClient = $httpClient ? $httpClient : \OC::$server->getHTTPClientService()->newClient();
101
+        $this->jobList = $jobList ? $jobList : \OC::$server->getJobList();
102
+        $this->urlGenerator = $urlGenerator ? $urlGenerator : \OC::$server->getURLGenerator();
103
+        $this->dbHandler = $dbHandler ? $dbHandler : new DbHandler(\OC::$server->getDatabaseConnection(), \OC::$server->getL10N('federation'));
104
+        $this->ocsDiscoveryService = $ocsDiscoveryService ? $ocsDiscoveryService : \OC::$server->getOCSDiscoveryService();
105
+        if ($trustedServers) {
106
+            $this->trustedServers = $trustedServers;
107
+        } else {
108
+            $this->trustedServers = new TrustedServers(
109
+                $this->dbHandler,
110
+                \OC::$server->getHTTPClientService(),
111
+                $this->logger,
112
+                $this->jobList,
113
+                \OC::$server->getSecureRandom(),
114
+                \OC::$server->getConfig(),
115
+                \OC::$server->getEventDispatcher()
116
+            );
117
+        }
118
+    }
119
+
120
+    /**
121
+     * run the job, then remove it from the joblist
122
+     *
123
+     * @param JobList $jobList
124
+     * @param ILogger $logger
125
+     */
126
+    public function execute($jobList, ILogger $logger = null) {
127
+        $target = $this->argument['url'];
128
+        // only execute if target is still in the list of trusted domains
129
+        if ($this->trustedServers->isTrustedServer($target)) {
130
+            $this->parentExecute($jobList, $logger);
131
+        }
132
+
133
+        if (!$this->retainJob) {
134
+            $jobList->remove($this, $this->argument);
135
+        }
136
+    }
137
+
138
+    /**
139
+     * call execute() method of parent
140
+     *
141
+     * @param JobList $jobList
142
+     * @param ILogger $logger
143
+     */
144
+    protected function parentExecute($jobList, $logger = null) {
145
+        parent::execute($jobList, $logger);
146
+    }
147
+
148
+    protected function run($argument) {
149
+        $target = $argument['url'];
150
+        $source = $this->urlGenerator->getAbsoluteURL('/');
151
+        $source = rtrim($source, '/');
152
+        $token = $argument['token'];
153
+
154
+        $endPoints = $this->ocsDiscoveryService->discover($target, 'FEDERATED_SHARING');
155
+        $endPoint = isset($endPoints['shared-secret']) ? $endPoints['shared-secret'] : $this->defaultEndPoint;
156
+
157
+        // make sure that we have a well formated url
158
+        $url = rtrim($target, '/') . '/' . trim($endPoint, '/') . $this->format;
159
+
160
+        $result = null;
161
+        try {
162
+            $result = $this->httpClient->get(
163
+                $url,
164
+                [
165
+                    'query' =>
166
+                        [
167
+                            'url' => $source,
168
+                            'token' => $token
169
+                        ],
170
+                    'timeout' => 3,
171
+                    'connect_timeout' => 3,
172
+                ]
173
+            );
174
+
175
+            $status = $result->getStatusCode();
176
+
177
+        } catch (ClientException $e) {
178
+            $status = $e->getCode();
179
+            if ($status === Http::STATUS_FORBIDDEN) {
180
+                $this->logger->info($target . ' refused to exchange a shared secret with you.', ['app' => 'federation']);
181
+            } else {
182
+                $this->logger->logException($e, ['app' => 'federation']);
183
+            }
184
+        } catch (\Exception $e) {
185
+            $status = Http::STATUS_INTERNAL_SERVER_ERROR;
186
+            $this->logger->logException($e, ['app' => 'federation']);
187
+        }
188
+
189
+        // if we received a unexpected response we try again later
190
+        if (
191
+            $status !== Http::STATUS_OK
192
+            && $status !== Http::STATUS_FORBIDDEN
193
+        ) {
194
+            $this->retainJob = true;
195
+        }  else {
196
+            // reset token if we received a valid response
197
+            $this->dbHandler->addToken($target, '');
198
+        }
199
+
200
+        if ($status === Http::STATUS_OK && $result instanceof IResponse) {
201
+            $body = $result->getBody();
202
+            $result = json_decode($body, true);
203
+            if (isset($result['ocs']['data']['sharedSecret'])) {
204
+                $this->trustedServers->addSharedSecret(
205
+                        $target,
206
+                        $result['ocs']['data']['sharedSecret']
207
+                );
208
+            } else {
209
+                $this->logger->error(
210
+                        'remote server "' . $target . '"" does not return a valid shared secret',
211
+                        ['app' => 'federation']
212
+                );
213
+                $this->trustedServers->setServerStatus($target, TrustedServers::STATUS_FAILURE);
214
+            }
215
+        }
216
+
217
+    }
218 218
 }
Please login to merge, or discard this patch.
apps/federation/lib/BackgroundJob/RequestSharedSecret.php 2 patches
Spacing   +2 added lines, -2 removed lines patch added patch discarded remove patch
@@ -155,7 +155,7 @@  discard block
 block discarded – undo
155 155
 		$endPoint = isset($endPoints['shared-secret']) ? $endPoints['shared-secret'] : $this->defaultEndPoint;
156 156
 
157 157
 		// make sure that we have a well formated url
158
-		$url = rtrim($target, '/') . '/' . trim($endPoint, '/') . $this->format;
158
+		$url = rtrim($target, '/').'/'.trim($endPoint, '/').$this->format;
159 159
 
160 160
 		try {
161 161
 			$result = $this->httpClient->post(
@@ -175,7 +175,7 @@  discard block
 block discarded – undo
175 175
 		} catch (ClientException $e) {
176 176
 			$status = $e->getCode();
177 177
 			if ($status === Http::STATUS_FORBIDDEN) {
178
-				$this->logger->info($target . ' refused to ask for a shared secret.', ['app' => 'federation']);
178
+				$this->logger->info($target.' refused to ask for a shared secret.', ['app' => 'federation']);
179 179
 			} else {
180 180
 				$this->logger->logException($e, ['app' => 'federation']);
181 181
 			}
Please login to merge, or discard this patch.
Indentation   +150 added lines, -150 removed lines patch added patch discarded remove patch
@@ -48,154 +48,154 @@
 block discarded – undo
48 48
  */
49 49
 class RequestSharedSecret extends Job {
50 50
 
51
-	/** @var IClient */
52
-	private $httpClient;
53
-
54
-	/** @var IJobList */
55
-	private $jobList;
56
-
57
-	/** @var IURLGenerator */
58
-	private $urlGenerator;
59
-
60
-	/** @var DbHandler */
61
-	private $dbHandler;
62
-
63
-	/** @var TrustedServers */
64
-	private $trustedServers;
65
-
66
-	/** @var IDiscoveryService  */
67
-	private $ocsDiscoveryService;
68
-
69
-	/** @var ILogger */
70
-	private $logger;
71
-
72
-	/** @var bool */
73
-	protected $retainJob = false;
74
-
75
-	private $format = '?format=json';
76
-
77
-	private $defaultEndPoint = '/ocs/v2.php/apps/federation/api/v1/request-shared-secret';
78
-
79
-	/**
80
-	 * RequestSharedSecret constructor.
81
-	 *
82
-	 * @param IClient $httpClient
83
-	 * @param IURLGenerator $urlGenerator
84
-	 * @param IJobList $jobList
85
-	 * @param TrustedServers $trustedServers
86
-	 * @param DbHandler $dbHandler
87
-	 * @param IDiscoveryService $ocsDiscoveryService
88
-	 */
89
-	public function __construct(
90
-		IClient $httpClient = null,
91
-		IURLGenerator $urlGenerator = null,
92
-		IJobList $jobList = null,
93
-		TrustedServers $trustedServers = null,
94
-		DbHandler $dbHandler = null,
95
-		IDiscoveryService $ocsDiscoveryService = null
96
-	) {
97
-		$this->httpClient = $httpClient ? $httpClient : \OC::$server->getHTTPClientService()->newClient();
98
-		$this->jobList = $jobList ? $jobList : \OC::$server->getJobList();
99
-		$this->urlGenerator = $urlGenerator ? $urlGenerator : \OC::$server->getURLGenerator();
100
-		$this->dbHandler = $dbHandler ? $dbHandler : new DbHandler(\OC::$server->getDatabaseConnection(), \OC::$server->getL10N('federation'));
101
-		$this->logger = \OC::$server->getLogger();
102
-		$this->ocsDiscoveryService = $ocsDiscoveryService ? $ocsDiscoveryService : \OC::$server->getOCSDiscoveryService();
103
-		if ($trustedServers) {
104
-			$this->trustedServers = $trustedServers;
105
-		} else {
106
-			$this->trustedServers = new TrustedServers(
107
-				$this->dbHandler,
108
-				\OC::$server->getHTTPClientService(),
109
-				$this->logger,
110
-				$this->jobList,
111
-				\OC::$server->getSecureRandom(),
112
-				\OC::$server->getConfig(),
113
-				\OC::$server->getEventDispatcher()
114
-			);
115
-		}
116
-	}
117
-
118
-
119
-	/**
120
-	 * run the job, then remove it from the joblist
121
-	 *
122
-	 * @param JobList $jobList
123
-	 * @param ILogger $logger
124
-	 */
125
-	public function execute($jobList, ILogger $logger = null) {
126
-		$target = $this->argument['url'];
127
-		// only execute if target is still in the list of trusted domains
128
-		if ($this->trustedServers->isTrustedServer($target)) {
129
-			$this->parentExecute($jobList, $logger);
130
-		}
131
-
132
-		if (!$this->retainJob) {
133
-			$jobList->remove($this, $this->argument);
134
-		}
135
-	}
136
-
137
-	/**
138
-	 * call execute() method of parent
139
-	 *
140
-	 * @param JobList $jobList
141
-	 * @param ILogger $logger
142
-	 */
143
-	protected function parentExecute($jobList, $logger) {
144
-		parent::execute($jobList, $logger);
145
-	}
146
-
147
-	protected function run($argument) {
148
-
149
-		$target = $argument['url'];
150
-		$source = $this->urlGenerator->getAbsoluteURL('/');
151
-		$source = rtrim($source, '/');
152
-		$token = $argument['token'];
153
-
154
-		$endPoints = $this->ocsDiscoveryService->discover($target, 'FEDERATED_SHARING');
155
-		$endPoint = isset($endPoints['shared-secret']) ? $endPoints['shared-secret'] : $this->defaultEndPoint;
156
-
157
-		// make sure that we have a well formated url
158
-		$url = rtrim($target, '/') . '/' . trim($endPoint, '/') . $this->format;
159
-
160
-		try {
161
-			$result = $this->httpClient->post(
162
-				$url,
163
-				[
164
-					'body' => [
165
-						'url' => $source,
166
-						'token' => $token,
167
-					],
168
-					'timeout' => 3,
169
-					'connect_timeout' => 3,
170
-				]
171
-			);
172
-
173
-			$status = $result->getStatusCode();
174
-
175
-		} catch (ClientException $e) {
176
-			$status = $e->getCode();
177
-			if ($status === Http::STATUS_FORBIDDEN) {
178
-				$this->logger->info($target . ' refused to ask for a shared secret.', ['app' => 'federation']);
179
-			} else {
180
-				$this->logger->logException($e, ['app' => 'federation']);
181
-			}
182
-		} catch (\Exception $e) {
183
-			$status = Http::STATUS_INTERNAL_SERVER_ERROR;
184
-			$this->logger->logException($e, ['app' => 'federation']);
185
-		}
186
-
187
-		// if we received a unexpected response we try again later
188
-		if (
189
-			$status !== Http::STATUS_OK
190
-			&& $status !== Http::STATUS_FORBIDDEN
191
-		) {
192
-			$this->retainJob = true;
193
-		}
194
-
195
-		if ($status === Http::STATUS_FORBIDDEN) {
196
-			// clear token if remote server refuses to ask for shared secret
197
-			$this->dbHandler->addToken($target, '');
198
-		}
199
-
200
-	}
51
+    /** @var IClient */
52
+    private $httpClient;
53
+
54
+    /** @var IJobList */
55
+    private $jobList;
56
+
57
+    /** @var IURLGenerator */
58
+    private $urlGenerator;
59
+
60
+    /** @var DbHandler */
61
+    private $dbHandler;
62
+
63
+    /** @var TrustedServers */
64
+    private $trustedServers;
65
+
66
+    /** @var IDiscoveryService  */
67
+    private $ocsDiscoveryService;
68
+
69
+    /** @var ILogger */
70
+    private $logger;
71
+
72
+    /** @var bool */
73
+    protected $retainJob = false;
74
+
75
+    private $format = '?format=json';
76
+
77
+    private $defaultEndPoint = '/ocs/v2.php/apps/federation/api/v1/request-shared-secret';
78
+
79
+    /**
80
+     * RequestSharedSecret constructor.
81
+     *
82
+     * @param IClient $httpClient
83
+     * @param IURLGenerator $urlGenerator
84
+     * @param IJobList $jobList
85
+     * @param TrustedServers $trustedServers
86
+     * @param DbHandler $dbHandler
87
+     * @param IDiscoveryService $ocsDiscoveryService
88
+     */
89
+    public function __construct(
90
+        IClient $httpClient = null,
91
+        IURLGenerator $urlGenerator = null,
92
+        IJobList $jobList = null,
93
+        TrustedServers $trustedServers = null,
94
+        DbHandler $dbHandler = null,
95
+        IDiscoveryService $ocsDiscoveryService = null
96
+    ) {
97
+        $this->httpClient = $httpClient ? $httpClient : \OC::$server->getHTTPClientService()->newClient();
98
+        $this->jobList = $jobList ? $jobList : \OC::$server->getJobList();
99
+        $this->urlGenerator = $urlGenerator ? $urlGenerator : \OC::$server->getURLGenerator();
100
+        $this->dbHandler = $dbHandler ? $dbHandler : new DbHandler(\OC::$server->getDatabaseConnection(), \OC::$server->getL10N('federation'));
101
+        $this->logger = \OC::$server->getLogger();
102
+        $this->ocsDiscoveryService = $ocsDiscoveryService ? $ocsDiscoveryService : \OC::$server->getOCSDiscoveryService();
103
+        if ($trustedServers) {
104
+            $this->trustedServers = $trustedServers;
105
+        } else {
106
+            $this->trustedServers = new TrustedServers(
107
+                $this->dbHandler,
108
+                \OC::$server->getHTTPClientService(),
109
+                $this->logger,
110
+                $this->jobList,
111
+                \OC::$server->getSecureRandom(),
112
+                \OC::$server->getConfig(),
113
+                \OC::$server->getEventDispatcher()
114
+            );
115
+        }
116
+    }
117
+
118
+
119
+    /**
120
+     * run the job, then remove it from the joblist
121
+     *
122
+     * @param JobList $jobList
123
+     * @param ILogger $logger
124
+     */
125
+    public function execute($jobList, ILogger $logger = null) {
126
+        $target = $this->argument['url'];
127
+        // only execute if target is still in the list of trusted domains
128
+        if ($this->trustedServers->isTrustedServer($target)) {
129
+            $this->parentExecute($jobList, $logger);
130
+        }
131
+
132
+        if (!$this->retainJob) {
133
+            $jobList->remove($this, $this->argument);
134
+        }
135
+    }
136
+
137
+    /**
138
+     * call execute() method of parent
139
+     *
140
+     * @param JobList $jobList
141
+     * @param ILogger $logger
142
+     */
143
+    protected function parentExecute($jobList, $logger) {
144
+        parent::execute($jobList, $logger);
145
+    }
146
+
147
+    protected function run($argument) {
148
+
149
+        $target = $argument['url'];
150
+        $source = $this->urlGenerator->getAbsoluteURL('/');
151
+        $source = rtrim($source, '/');
152
+        $token = $argument['token'];
153
+
154
+        $endPoints = $this->ocsDiscoveryService->discover($target, 'FEDERATED_SHARING');
155
+        $endPoint = isset($endPoints['shared-secret']) ? $endPoints['shared-secret'] : $this->defaultEndPoint;
156
+
157
+        // make sure that we have a well formated url
158
+        $url = rtrim($target, '/') . '/' . trim($endPoint, '/') . $this->format;
159
+
160
+        try {
161
+            $result = $this->httpClient->post(
162
+                $url,
163
+                [
164
+                    'body' => [
165
+                        'url' => $source,
166
+                        'token' => $token,
167
+                    ],
168
+                    'timeout' => 3,
169
+                    'connect_timeout' => 3,
170
+                ]
171
+            );
172
+
173
+            $status = $result->getStatusCode();
174
+
175
+        } catch (ClientException $e) {
176
+            $status = $e->getCode();
177
+            if ($status === Http::STATUS_FORBIDDEN) {
178
+                $this->logger->info($target . ' refused to ask for a shared secret.', ['app' => 'federation']);
179
+            } else {
180
+                $this->logger->logException($e, ['app' => 'federation']);
181
+            }
182
+        } catch (\Exception $e) {
183
+            $status = Http::STATUS_INTERNAL_SERVER_ERROR;
184
+            $this->logger->logException($e, ['app' => 'federation']);
185
+        }
186
+
187
+        // if we received a unexpected response we try again later
188
+        if (
189
+            $status !== Http::STATUS_OK
190
+            && $status !== Http::STATUS_FORBIDDEN
191
+        ) {
192
+            $this->retainJob = true;
193
+        }
194
+
195
+        if ($status === Http::STATUS_FORBIDDEN) {
196
+            // clear token if remote server refuses to ask for shared secret
197
+            $this->dbHandler->addToken($target, '');
198
+        }
199
+
200
+    }
201 201
 }
Please login to merge, or discard this patch.
lib/public/OCS/IDiscoveryService.php 1 patch
Indentation   +12 added lines, -12 removed lines patch added patch discarded remove patch
@@ -32,17 +32,17 @@
 block discarded – undo
32 32
  */
33 33
 interface IDiscoveryService {
34 34
 
35
-	/**
36
-	 * Discover OCS end-points
37
-	 *
38
-	 * If no valid discovery data is found the defaults are returned
39
-	 *
40
-	 * @since 12.0.0
41
-	 *
42
-	 * @param string $remote
43
-	 * @param string $service the service you want to discover
44
-	 * @return array
45
-	 */
46
-	public function discover($remote, $service);
35
+    /**
36
+     * Discover OCS end-points
37
+     *
38
+     * If no valid discovery data is found the defaults are returned
39
+     *
40
+     * @since 12.0.0
41
+     *
42
+     * @param string $remote
43
+     * @param string $service the service you want to discover
44
+     * @return array
45
+     */
46
+    public function discover($remote, $service);
47 47
 
48 48
 }
Please login to merge, or discard this patch.
apps/federation/lib/AppInfo/Application.php 1 patch
Indentation   +96 added lines, -96 removed lines patch added patch discarded remove patch
@@ -42,101 +42,101 @@
 block discarded – undo
42 42
 
43 43
 class Application extends \OCP\AppFramework\App {
44 44
 
45
-	/**
46
-	 * @param array $urlParams
47
-	 */
48
-	public function __construct($urlParams = array()) {
49
-		parent::__construct('federation', $urlParams);
50
-		$this->registerService();
51
-		$this->registerMiddleware();
52
-	}
53
-
54
-	private function registerService() {
55
-		$container = $this->getContainer();
56
-
57
-		$container->registerService('addServerMiddleware', function(IAppContainer $c) {
58
-			return new AddServerMiddleware(
59
-				$c->getAppName(),
60
-				\OC::$server->getL10N($c->getAppName()),
61
-				\OC::$server->getLogger()
62
-			);
63
-		});
64
-
65
-		$container->registerService('DbHandler', function(IAppContainer $c) {
66
-			return new DbHandler(
67
-				\OC::$server->getDatabaseConnection(),
68
-				\OC::$server->getL10N($c->getAppName())
69
-			);
70
-		});
71
-
72
-		$container->registerService('TrustedServers', function(IAppContainer $c) {
73
-			$server = $c->getServer();
74
-			return new TrustedServers(
75
-				$c->query('DbHandler'),
76
-				$server->getHTTPClientService(),
77
-				$server->getLogger(),
78
-				$server->getJobList(),
79
-				$server->getSecureRandom(),
80
-				$server->getConfig(),
81
-				$server->getEventDispatcher()
82
-			);
83
-		});
84
-
85
-		$container->registerService('SettingsController', function (IAppContainer $c) {
86
-			$server = $c->getServer();
87
-			return new SettingsController(
88
-				$c->getAppName(),
89
-				$server->getRequest(),
90
-				$server->getL10N($c->getAppName()),
91
-				$c->query('TrustedServers')
92
-			);
93
-		});
94
-
95
-	}
96
-
97
-	private function registerMiddleware() {
98
-		$container = $this->getContainer();
99
-		$container->registerMiddleware('addServerMiddleware');
100
-	}
101
-
102
-	/**
103
-	 * listen to federated_share_added hooks to auto-add new servers to the
104
-	 * list of trusted servers.
105
-	 */
106
-	public function registerHooks() {
107
-
108
-		$container = $this->getContainer();
109
-		$hooksManager = new Hooks($container->query('TrustedServers'));
110
-
111
-		Util::connectHook(
112
-				'OCP\Share',
113
-				'federated_share_added',
114
-				$hooksManager,
115
-				'addServerHook'
116
-		);
117
-
118
-		$dispatcher = $this->getContainer()->getServer()->getEventDispatcher();
119
-		$dispatcher->addListener('OCA\DAV\Connector\Sabre::authInit', function($event) use($container) {
120
-			if ($event instanceof SabrePluginEvent) {
121
-				$authPlugin = $event->getServer()->getPlugin('auth');
122
-				if ($authPlugin instanceof Plugin) {
123
-					$h = new DbHandler($container->getServer()->getDatabaseConnection(),
124
-							$container->getServer()->getL10N('federation')
125
-					);
126
-					$authPlugin->addBackend(new FedAuth($h));
127
-				}
128
-			}
129
-		});
130
-	}
131
-
132
-	/**
133
-	 * @return SyncFederationAddressBooks
134
-	 */
135
-	public function getSyncService() {
136
-		$syncService = \OC::$server->query('CardDAVSyncService');
137
-		$dbHandler = $this->getContainer()->query('DbHandler');
138
-		$discoveryService = \OC::$server->getOCSDiscoveryService();
139
-		return new SyncFederationAddressBooks($dbHandler, $syncService, $discoveryService);
140
-	}
45
+    /**
46
+     * @param array $urlParams
47
+     */
48
+    public function __construct($urlParams = array()) {
49
+        parent::__construct('federation', $urlParams);
50
+        $this->registerService();
51
+        $this->registerMiddleware();
52
+    }
53
+
54
+    private function registerService() {
55
+        $container = $this->getContainer();
56
+
57
+        $container->registerService('addServerMiddleware', function(IAppContainer $c) {
58
+            return new AddServerMiddleware(
59
+                $c->getAppName(),
60
+                \OC::$server->getL10N($c->getAppName()),
61
+                \OC::$server->getLogger()
62
+            );
63
+        });
64
+
65
+        $container->registerService('DbHandler', function(IAppContainer $c) {
66
+            return new DbHandler(
67
+                \OC::$server->getDatabaseConnection(),
68
+                \OC::$server->getL10N($c->getAppName())
69
+            );
70
+        });
71
+
72
+        $container->registerService('TrustedServers', function(IAppContainer $c) {
73
+            $server = $c->getServer();
74
+            return new TrustedServers(
75
+                $c->query('DbHandler'),
76
+                $server->getHTTPClientService(),
77
+                $server->getLogger(),
78
+                $server->getJobList(),
79
+                $server->getSecureRandom(),
80
+                $server->getConfig(),
81
+                $server->getEventDispatcher()
82
+            );
83
+        });
84
+
85
+        $container->registerService('SettingsController', function (IAppContainer $c) {
86
+            $server = $c->getServer();
87
+            return new SettingsController(
88
+                $c->getAppName(),
89
+                $server->getRequest(),
90
+                $server->getL10N($c->getAppName()),
91
+                $c->query('TrustedServers')
92
+            );
93
+        });
94
+
95
+    }
96
+
97
+    private function registerMiddleware() {
98
+        $container = $this->getContainer();
99
+        $container->registerMiddleware('addServerMiddleware');
100
+    }
101
+
102
+    /**
103
+     * listen to federated_share_added hooks to auto-add new servers to the
104
+     * list of trusted servers.
105
+     */
106
+    public function registerHooks() {
107
+
108
+        $container = $this->getContainer();
109
+        $hooksManager = new Hooks($container->query('TrustedServers'));
110
+
111
+        Util::connectHook(
112
+                'OCP\Share',
113
+                'federated_share_added',
114
+                $hooksManager,
115
+                'addServerHook'
116
+        );
117
+
118
+        $dispatcher = $this->getContainer()->getServer()->getEventDispatcher();
119
+        $dispatcher->addListener('OCA\DAV\Connector\Sabre::authInit', function($event) use($container) {
120
+            if ($event instanceof SabrePluginEvent) {
121
+                $authPlugin = $event->getServer()->getPlugin('auth');
122
+                if ($authPlugin instanceof Plugin) {
123
+                    $h = new DbHandler($container->getServer()->getDatabaseConnection(),
124
+                            $container->getServer()->getL10N('federation')
125
+                    );
126
+                    $authPlugin->addBackend(new FedAuth($h));
127
+                }
128
+            }
129
+        });
130
+    }
131
+
132
+    /**
133
+     * @return SyncFederationAddressBooks
134
+     */
135
+    public function getSyncService() {
136
+        $syncService = \OC::$server->query('CardDAVSyncService');
137
+        $dbHandler = $this->getContainer()->query('DbHandler');
138
+        $discoveryService = \OC::$server->getOCSDiscoveryService();
139
+        return new SyncFederationAddressBooks($dbHandler, $syncService, $discoveryService);
140
+    }
141 141
 
142 142
 }
Please login to merge, or discard this patch.
apps/federatedfilesharing/lib/Controller/MountPublicLinkController.php 2 patches
Unused Use Statements   -1 removed lines patch added patch discarded remove patch
@@ -29,7 +29,6 @@
 block discarded – undo
29 29
 use OC\HintException;
30 30
 use OC\Share\Helper;
31 31
 use OCA\FederatedFileSharing\AddressHandler;
32
-use OCA\FederatedFileSharing\DiscoveryManager;
33 32
 use OCA\FederatedFileSharing\FederatedShareProvider;
34 33
 use OCA\Files_Sharing\External\Manager;
35 34
 use OCP\AppFramework\Controller;
Please login to merge, or discard this patch.
Indentation   +278 added lines, -278 removed lines patch added patch discarded remove patch
@@ -54,283 +54,283 @@
 block discarded – undo
54 54
  */
55 55
 class MountPublicLinkController extends Controller {
56 56
 
57
-	/** @var FederatedShareProvider */
58
-	private $federatedShareProvider;
59
-
60
-	/** @var AddressHandler */
61
-	private $addressHandler;
62
-
63
-	/** @var IManager  */
64
-	private $shareManager;
65
-
66
-	/** @var  ISession */
67
-	private $session;
68
-
69
-	/** @var IL10N */
70
-	private $l;
71
-
72
-	/** @var IUserSession */
73
-	private $userSession;
74
-
75
-	/** @var IClientService */
76
-	private $clientService;
77
-
78
-	/** @var ICloudIdManager  */
79
-	private $cloudIdManager;
80
-
81
-	/**
82
-	 * MountPublicLinkController constructor.
83
-	 *
84
-	 * @param string $appName
85
-	 * @param IRequest $request
86
-	 * @param FederatedShareProvider $federatedShareProvider
87
-	 * @param IManager $shareManager
88
-	 * @param AddressHandler $addressHandler
89
-	 * @param ISession $session
90
-	 * @param IL10N $l
91
-	 * @param IUserSession $userSession
92
-	 * @param IClientService $clientService
93
-	 * @param ICloudIdManager $cloudIdManager
94
-	 */
95
-	public function __construct($appName,
96
-								IRequest $request,
97
-								FederatedShareProvider $federatedShareProvider,
98
-								IManager $shareManager,
99
-								AddressHandler $addressHandler,
100
-								ISession $session,
101
-								IL10N $l,
102
-								IUserSession $userSession,
103
-								IClientService $clientService,
104
-								ICloudIdManager $cloudIdManager
105
-	) {
106
-		parent::__construct($appName, $request);
107
-
108
-		$this->federatedShareProvider = $federatedShareProvider;
109
-		$this->shareManager = $shareManager;
110
-		$this->addressHandler = $addressHandler;
111
-		$this->session = $session;
112
-		$this->l = $l;
113
-		$this->userSession = $userSession;
114
-		$this->clientService = $clientService;
115
-		$this->cloudIdManager = $cloudIdManager;
116
-	}
117
-
118
-	/**
119
-	 * send federated share to a user of a public link
120
-	 *
121
-	 * @NoCSRFRequired
122
-	 * @PublicPage
123
-	 * @BruteForceProtection publicLink2FederatedShare
124
-	 *
125
-	 * @param string $shareWith
126
-	 * @param string $token
127
-	 * @param string $password
128
-	 * @return JSONResponse
129
-	 */
130
-	public function createFederatedShare($shareWith, $token, $password = '') {
131
-
132
-		if (!$this->federatedShareProvider->isOutgoingServer2serverShareEnabled()) {
133
-			return new JSONResponse(
134
-				['message' => 'This server doesn\'t support outgoing federated shares'],
135
-				Http::STATUS_BAD_REQUEST
136
-			);
137
-		}
138
-
139
-		try {
140
-			list(, $server) = $this->addressHandler->splitUserRemote($shareWith);
141
-			$share = $this->shareManager->getShareByToken($token);
142
-		} catch (HintException $e) {
143
-			return new JSONResponse(['message' => $e->getHint()], Http::STATUS_BAD_REQUEST);
144
-		}
145
-
146
-		// make sure that user is authenticated in case of a password protected link
147
-		$storedPassword = $share->getPassword();
148
-		$authenticated = $this->session->get('public_link_authenticated') === $share->getId() ||
149
-			$this->shareManager->checkPassword($share, $password);
150
-		if (!empty($storedPassword) && !$authenticated ) {
151
-			return new JSONResponse(
152
-				['message' => 'No permission to access the share'],
153
-				Http::STATUS_BAD_REQUEST
154
-			);
155
-		}
156
-
157
-		$share->setSharedWith($shareWith);
158
-
159
-		try {
160
-			$this->federatedShareProvider->create($share);
161
-		} catch (\Exception $e) {
162
-			return new JSONResponse(['message' => $e->getMessage()], Http::STATUS_BAD_REQUEST);
163
-		}
164
-
165
-		return new JSONResponse(['remoteUrl' => $server]);
166
-	}
167
-
168
-	/**
169
-	 * ask other server to get a federated share
170
-	 *
171
-	 * @NoAdminRequired
172
-	 *
173
-	 * @param string $token
174
-	 * @param string $remote
175
-	 * @param string $password
176
-	 * @param string $owner (only for legacy reasons, can be removed with legacyMountPublicLink())
177
-	 * @param string $ownerDisplayName (only for legacy reasons, can be removed with legacyMountPublicLink())
178
-	 * @param string $name (only for legacy reasons, can be removed with legacyMountPublicLink())
179
-	 * @return JSONResponse
180
-	 */
181
-	public function askForFederatedShare($token, $remote, $password = '', $owner = '', $ownerDisplayName = '', $name = '') {
182
-		// check if server admin allows to mount public links from other servers
183
-		if ($this->federatedShareProvider->isIncomingServer2serverShareEnabled() === false) {
184
-			return new JSONResponse(['message' => $this->l->t('Server to server sharing is not enabled on this server')], Http::STATUS_BAD_REQUEST);
185
-		}
186
-
187
-		$cloudId = $this->cloudIdManager->getCloudId($this->userSession->getUser()->getUID(), $this->addressHandler->generateRemoteURL());
188
-
189
-		$httpClient = $this->clientService->newClient();
190
-
191
-		try {
192
-			$response = $httpClient->post($remote . '/index.php/apps/federatedfilesharing/createFederatedShare',
193
-				[
194
-					'body' =>
195
-						[
196
-							'token' => $token,
197
-							'shareWith' => rtrim($cloudId->getId(), '/'),
198
-							'password' => $password
199
-						],
200
-					'connect_timeout' => 10,
201
-				]
202
-			);
203
-		} catch (\Exception $e) {
204
-			if (empty($password)) {
205
-				$message = $this->l->t("Couldn't establish a federated share.");
206
-			} else {
207
-				$message = $this->l->t("Couldn't establish a federated share, maybe the password was wrong.");
208
-			}
209
-			return new JSONResponse(['message' => $message], Http::STATUS_BAD_REQUEST);
210
-		}
211
-
212
-		$body = $response->getBody();
213
-		$result = json_decode($body, true);
214
-
215
-		if (is_array($result) && isset($result['remoteUrl'])) {
216
-			return new JSONResponse(['message' => $this->l->t('Federated Share request was successful, you will receive a invitation. Check your notifications.')]);
217
-		}
218
-
219
-		// if we doesn't get the expected response we assume that we try to add
220
-		// a federated share from a Nextcloud <= 9 server
221
-		return $this->legacyMountPublicLink($token, $remote, $password, $name, $owner, $ownerDisplayName);
222
-	}
223
-
224
-	/**
225
-	 * Allow Nextcloud to mount a public link directly
226
-	 *
227
-	 * This code was copied from the apps/files_sharing/ajax/external.php with
228
-	 * minimal changes, just to guarantee backward compatibility
229
-	 *
230
-	 * ToDo: Remove this method once Nextcloud 9 reaches end of life
231
-	 *
232
-	 * @param string $token
233
-	 * @param string $remote
234
-	 * @param string $password
235
-	 * @param string $name
236
-	 * @param string $owner
237
-	 * @param string $ownerDisplayName
238
-	 * @return JSONResponse
239
-	 */
240
-	private function legacyMountPublicLink($token, $remote, $password, $name, $owner, $ownerDisplayName) {
241
-
242
-		// Check for invalid name
243
-		if (!Util::isValidFileName($name)) {
244
-			return new JSONResponse(['message' => $this->l->t('The mountpoint name contains invalid characters.')], Http::STATUS_BAD_REQUEST);
245
-		}
246
-		$currentUser = $this->userSession->getUser()->getUID();
247
-		$currentServer = $this->addressHandler->generateRemoteURL();
248
-		if (Helper::isSameUserOnSameServer($owner, $remote, $currentUser, $currentServer)) {
249
-			return new JSONResponse(['message' => $this->l->t('Not allowed to create a federated share with the owner.')], Http::STATUS_BAD_REQUEST);
250
-		}
251
-		$externalManager = new Manager(
252
-			\OC::$server->getDatabaseConnection(),
253
-			Filesystem::getMountManager(),
254
-			Filesystem::getLoader(),
255
-			\OC::$server->getHTTPClientService(),
256
-			\OC::$server->getNotificationManager(),
257
-			\OC::$server->getOCSDiscoveryService(),
258
-			\OC::$server->getUserSession()->getUser()->getUID()
259
-		);
260
-
261
-		// check for ssl cert
262
-
263
-		if (strpos($remote, 'https') === 0) {
264
-			try {
265
-				$client = $this->clientService->newClient();
266
-				$client->get($remote, [
267
-					'timeout' => 10,
268
-					'connect_timeout' => 10,
269
-				])->getBody();
270
-			} catch (\Exception $e) {
271
-				return new JSONResponse(['message' => $this->l->t('Invalid or untrusted SSL certificate')], Http::STATUS_BAD_REQUEST);
272
-			}
273
-		}
274
-		$mount = $externalManager->addShare($remote, $token, $password, $name, $ownerDisplayName, true);
275
-		/**
276
-		 * @var \OCA\Files_Sharing\External\Storage $storage
277
-		 */
278
-		$storage = $mount->getStorage();
279
-		try {
280
-			// check if storage exists
281
-			$storage->checkStorageAvailability();
282
-		} catch (StorageInvalidException $e) {
283
-			// note: checkStorageAvailability will already remove the invalid share
284
-			Util::writeLog(
285
-				'federatedfilesharing',
286
-				'Invalid remote storage: ' . get_class($e) . ': ' . $e->getMessage(),
287
-				Util::DEBUG
288
-			);
289
-			return new JSONResponse(['message' => $this->l->t('Could not authenticate to remote share, password might be wrong')], Http::STATUS_BAD_REQUEST);
290
-		} catch (\Exception $e) {
291
-			Util::writeLog(
292
-				'federatedfilesharing',
293
-				'Invalid remote storage: ' . get_class($e) . ': ' . $e->getMessage(),
294
-				Util::DEBUG
295
-			);
296
-			$externalManager->removeShare($mount->getMountPoint());
297
-			return new JSONResponse(['message' => $this->l->t('Storage not valid')], Http::STATUS_BAD_REQUEST);
298
-		}
299
-		$result = $storage->file_exists('');
300
-		if ($result) {
301
-			try {
302
-				$storage->getScanner()->scanAll();
303
-				return new JSONResponse(
304
-					[
305
-						'message' => $this->l->t('Federated Share successfully added'),
306
-						'legacyMount' => '1'
307
-					]
308
-				);
309
-			} catch (StorageInvalidException $e) {
310
-				Util::writeLog(
311
-					'federatedfilesharing',
312
-					'Invalid remote storage: ' . get_class($e) . ': ' . $e->getMessage(),
313
-					Util::DEBUG
314
-				);
315
-				return new JSONResponse(['message' => $this->l->t('Storage not valid')], Http::STATUS_BAD_REQUEST);
316
-			} catch (\Exception $e) {
317
-				Util::writeLog(
318
-					'federatedfilesharing',
319
-					'Invalid remote storage: ' . get_class($e) . ': ' . $e->getMessage(),
320
-					Util::DEBUG
321
-				);
322
-				return new JSONResponse(['message' => $this->l->t('Couldn\'t add remote share')], Http::STATUS_BAD_REQUEST);
323
-			}
324
-		} else {
325
-			$externalManager->removeShare($mount->getMountPoint());
326
-			Util::writeLog(
327
-				'federatedfilesharing',
328
-				'Couldn\'t add remote share',
329
-				Util::DEBUG
330
-			);
331
-			return new JSONResponse(['message' => $this->l->t('Couldn\'t add remote share')], Http::STATUS_BAD_REQUEST);
332
-		}
333
-
334
-	}
57
+    /** @var FederatedShareProvider */
58
+    private $federatedShareProvider;
59
+
60
+    /** @var AddressHandler */
61
+    private $addressHandler;
62
+
63
+    /** @var IManager  */
64
+    private $shareManager;
65
+
66
+    /** @var  ISession */
67
+    private $session;
68
+
69
+    /** @var IL10N */
70
+    private $l;
71
+
72
+    /** @var IUserSession */
73
+    private $userSession;
74
+
75
+    /** @var IClientService */
76
+    private $clientService;
77
+
78
+    /** @var ICloudIdManager  */
79
+    private $cloudIdManager;
80
+
81
+    /**
82
+     * MountPublicLinkController constructor.
83
+     *
84
+     * @param string $appName
85
+     * @param IRequest $request
86
+     * @param FederatedShareProvider $federatedShareProvider
87
+     * @param IManager $shareManager
88
+     * @param AddressHandler $addressHandler
89
+     * @param ISession $session
90
+     * @param IL10N $l
91
+     * @param IUserSession $userSession
92
+     * @param IClientService $clientService
93
+     * @param ICloudIdManager $cloudIdManager
94
+     */
95
+    public function __construct($appName,
96
+                                IRequest $request,
97
+                                FederatedShareProvider $federatedShareProvider,
98
+                                IManager $shareManager,
99
+                                AddressHandler $addressHandler,
100
+                                ISession $session,
101
+                                IL10N $l,
102
+                                IUserSession $userSession,
103
+                                IClientService $clientService,
104
+                                ICloudIdManager $cloudIdManager
105
+    ) {
106
+        parent::__construct($appName, $request);
107
+
108
+        $this->federatedShareProvider = $federatedShareProvider;
109
+        $this->shareManager = $shareManager;
110
+        $this->addressHandler = $addressHandler;
111
+        $this->session = $session;
112
+        $this->l = $l;
113
+        $this->userSession = $userSession;
114
+        $this->clientService = $clientService;
115
+        $this->cloudIdManager = $cloudIdManager;
116
+    }
117
+
118
+    /**
119
+     * send federated share to a user of a public link
120
+     *
121
+     * @NoCSRFRequired
122
+     * @PublicPage
123
+     * @BruteForceProtection publicLink2FederatedShare
124
+     *
125
+     * @param string $shareWith
126
+     * @param string $token
127
+     * @param string $password
128
+     * @return JSONResponse
129
+     */
130
+    public function createFederatedShare($shareWith, $token, $password = '') {
131
+
132
+        if (!$this->federatedShareProvider->isOutgoingServer2serverShareEnabled()) {
133
+            return new JSONResponse(
134
+                ['message' => 'This server doesn\'t support outgoing federated shares'],
135
+                Http::STATUS_BAD_REQUEST
136
+            );
137
+        }
138
+
139
+        try {
140
+            list(, $server) = $this->addressHandler->splitUserRemote($shareWith);
141
+            $share = $this->shareManager->getShareByToken($token);
142
+        } catch (HintException $e) {
143
+            return new JSONResponse(['message' => $e->getHint()], Http::STATUS_BAD_REQUEST);
144
+        }
145
+
146
+        // make sure that user is authenticated in case of a password protected link
147
+        $storedPassword = $share->getPassword();
148
+        $authenticated = $this->session->get('public_link_authenticated') === $share->getId() ||
149
+            $this->shareManager->checkPassword($share, $password);
150
+        if (!empty($storedPassword) && !$authenticated ) {
151
+            return new JSONResponse(
152
+                ['message' => 'No permission to access the share'],
153
+                Http::STATUS_BAD_REQUEST
154
+            );
155
+        }
156
+
157
+        $share->setSharedWith($shareWith);
158
+
159
+        try {
160
+            $this->federatedShareProvider->create($share);
161
+        } catch (\Exception $e) {
162
+            return new JSONResponse(['message' => $e->getMessage()], Http::STATUS_BAD_REQUEST);
163
+        }
164
+
165
+        return new JSONResponse(['remoteUrl' => $server]);
166
+    }
167
+
168
+    /**
169
+     * ask other server to get a federated share
170
+     *
171
+     * @NoAdminRequired
172
+     *
173
+     * @param string $token
174
+     * @param string $remote
175
+     * @param string $password
176
+     * @param string $owner (only for legacy reasons, can be removed with legacyMountPublicLink())
177
+     * @param string $ownerDisplayName (only for legacy reasons, can be removed with legacyMountPublicLink())
178
+     * @param string $name (only for legacy reasons, can be removed with legacyMountPublicLink())
179
+     * @return JSONResponse
180
+     */
181
+    public function askForFederatedShare($token, $remote, $password = '', $owner = '', $ownerDisplayName = '', $name = '') {
182
+        // check if server admin allows to mount public links from other servers
183
+        if ($this->federatedShareProvider->isIncomingServer2serverShareEnabled() === false) {
184
+            return new JSONResponse(['message' => $this->l->t('Server to server sharing is not enabled on this server')], Http::STATUS_BAD_REQUEST);
185
+        }
186
+
187
+        $cloudId = $this->cloudIdManager->getCloudId($this->userSession->getUser()->getUID(), $this->addressHandler->generateRemoteURL());
188
+
189
+        $httpClient = $this->clientService->newClient();
190
+
191
+        try {
192
+            $response = $httpClient->post($remote . '/index.php/apps/federatedfilesharing/createFederatedShare',
193
+                [
194
+                    'body' =>
195
+                        [
196
+                            'token' => $token,
197
+                            'shareWith' => rtrim($cloudId->getId(), '/'),
198
+                            'password' => $password
199
+                        ],
200
+                    'connect_timeout' => 10,
201
+                ]
202
+            );
203
+        } catch (\Exception $e) {
204
+            if (empty($password)) {
205
+                $message = $this->l->t("Couldn't establish a federated share.");
206
+            } else {
207
+                $message = $this->l->t("Couldn't establish a federated share, maybe the password was wrong.");
208
+            }
209
+            return new JSONResponse(['message' => $message], Http::STATUS_BAD_REQUEST);
210
+        }
211
+
212
+        $body = $response->getBody();
213
+        $result = json_decode($body, true);
214
+
215
+        if (is_array($result) && isset($result['remoteUrl'])) {
216
+            return new JSONResponse(['message' => $this->l->t('Federated Share request was successful, you will receive a invitation. Check your notifications.')]);
217
+        }
218
+
219
+        // if we doesn't get the expected response we assume that we try to add
220
+        // a federated share from a Nextcloud <= 9 server
221
+        return $this->legacyMountPublicLink($token, $remote, $password, $name, $owner, $ownerDisplayName);
222
+    }
223
+
224
+    /**
225
+     * Allow Nextcloud to mount a public link directly
226
+     *
227
+     * This code was copied from the apps/files_sharing/ajax/external.php with
228
+     * minimal changes, just to guarantee backward compatibility
229
+     *
230
+     * ToDo: Remove this method once Nextcloud 9 reaches end of life
231
+     *
232
+     * @param string $token
233
+     * @param string $remote
234
+     * @param string $password
235
+     * @param string $name
236
+     * @param string $owner
237
+     * @param string $ownerDisplayName
238
+     * @return JSONResponse
239
+     */
240
+    private function legacyMountPublicLink($token, $remote, $password, $name, $owner, $ownerDisplayName) {
241
+
242
+        // Check for invalid name
243
+        if (!Util::isValidFileName($name)) {
244
+            return new JSONResponse(['message' => $this->l->t('The mountpoint name contains invalid characters.')], Http::STATUS_BAD_REQUEST);
245
+        }
246
+        $currentUser = $this->userSession->getUser()->getUID();
247
+        $currentServer = $this->addressHandler->generateRemoteURL();
248
+        if (Helper::isSameUserOnSameServer($owner, $remote, $currentUser, $currentServer)) {
249
+            return new JSONResponse(['message' => $this->l->t('Not allowed to create a federated share with the owner.')], Http::STATUS_BAD_REQUEST);
250
+        }
251
+        $externalManager = new Manager(
252
+            \OC::$server->getDatabaseConnection(),
253
+            Filesystem::getMountManager(),
254
+            Filesystem::getLoader(),
255
+            \OC::$server->getHTTPClientService(),
256
+            \OC::$server->getNotificationManager(),
257
+            \OC::$server->getOCSDiscoveryService(),
258
+            \OC::$server->getUserSession()->getUser()->getUID()
259
+        );
260
+
261
+        // check for ssl cert
262
+
263
+        if (strpos($remote, 'https') === 0) {
264
+            try {
265
+                $client = $this->clientService->newClient();
266
+                $client->get($remote, [
267
+                    'timeout' => 10,
268
+                    'connect_timeout' => 10,
269
+                ])->getBody();
270
+            } catch (\Exception $e) {
271
+                return new JSONResponse(['message' => $this->l->t('Invalid or untrusted SSL certificate')], Http::STATUS_BAD_REQUEST);
272
+            }
273
+        }
274
+        $mount = $externalManager->addShare($remote, $token, $password, $name, $ownerDisplayName, true);
275
+        /**
276
+         * @var \OCA\Files_Sharing\External\Storage $storage
277
+         */
278
+        $storage = $mount->getStorage();
279
+        try {
280
+            // check if storage exists
281
+            $storage->checkStorageAvailability();
282
+        } catch (StorageInvalidException $e) {
283
+            // note: checkStorageAvailability will already remove the invalid share
284
+            Util::writeLog(
285
+                'federatedfilesharing',
286
+                'Invalid remote storage: ' . get_class($e) . ': ' . $e->getMessage(),
287
+                Util::DEBUG
288
+            );
289
+            return new JSONResponse(['message' => $this->l->t('Could not authenticate to remote share, password might be wrong')], Http::STATUS_BAD_REQUEST);
290
+        } catch (\Exception $e) {
291
+            Util::writeLog(
292
+                'federatedfilesharing',
293
+                'Invalid remote storage: ' . get_class($e) . ': ' . $e->getMessage(),
294
+                Util::DEBUG
295
+            );
296
+            $externalManager->removeShare($mount->getMountPoint());
297
+            return new JSONResponse(['message' => $this->l->t('Storage not valid')], Http::STATUS_BAD_REQUEST);
298
+        }
299
+        $result = $storage->file_exists('');
300
+        if ($result) {
301
+            try {
302
+                $storage->getScanner()->scanAll();
303
+                return new JSONResponse(
304
+                    [
305
+                        'message' => $this->l->t('Federated Share successfully added'),
306
+                        'legacyMount' => '1'
307
+                    ]
308
+                );
309
+            } catch (StorageInvalidException $e) {
310
+                Util::writeLog(
311
+                    'federatedfilesharing',
312
+                    'Invalid remote storage: ' . get_class($e) . ': ' . $e->getMessage(),
313
+                    Util::DEBUG
314
+                );
315
+                return new JSONResponse(['message' => $this->l->t('Storage not valid')], Http::STATUS_BAD_REQUEST);
316
+            } catch (\Exception $e) {
317
+                Util::writeLog(
318
+                    'federatedfilesharing',
319
+                    'Invalid remote storage: ' . get_class($e) . ': ' . $e->getMessage(),
320
+                    Util::DEBUG
321
+                );
322
+                return new JSONResponse(['message' => $this->l->t('Couldn\'t add remote share')], Http::STATUS_BAD_REQUEST);
323
+            }
324
+        } else {
325
+            $externalManager->removeShare($mount->getMountPoint());
326
+            Util::writeLog(
327
+                'federatedfilesharing',
328
+                'Couldn\'t add remote share',
329
+                Util::DEBUG
330
+            );
331
+            return new JSONResponse(['message' => $this->l->t('Couldn\'t add remote share')], Http::STATUS_BAD_REQUEST);
332
+        }
333
+
334
+    }
335 335
 
336 336
 }
Please login to merge, or discard this patch.
apps/federatedfilesharing/lib/Controller/RequestHandlerController.php 2 patches
Unused Use Statements   -1 removed lines patch added patch discarded remove patch
@@ -26,7 +26,6 @@
 block discarded – undo
26 26
 
27 27
 namespace OCA\FederatedFileSharing\Controller;
28 28
 
29
-use OCA\FederatedFileSharing\DiscoveryManager;
30 29
 use OCA\Files_Sharing\Activity\Providers\RemoteShares;
31 30
 use OCA\FederatedFileSharing\AddressHandler;
32 31
 use OCA\FederatedFileSharing\FederatedShareProvider;
Please login to merge, or discard this patch.
Indentation   +605 added lines, -605 removed lines patch added patch discarded remove patch
@@ -48,609 +48,609 @@
 block discarded – undo
48 48
 
49 49
 class RequestHandlerController extends OCSController {
50 50
 
51
-	/** @var FederatedShareProvider */
52
-	private $federatedShareProvider;
53
-
54
-	/** @var IDBConnection */
55
-	private $connection;
56
-
57
-	/** @var Share\IManager */
58
-	private $shareManager;
59
-
60
-	/** @var Notifications */
61
-	private $notifications;
62
-
63
-	/** @var AddressHandler */
64
-	private $addressHandler;
65
-
66
-	/** @var  IUserManager */
67
-	private $userManager;
68
-
69
-	/** @var string */
70
-	private $shareTable = 'share';
71
-
72
-	/** @var ICloudIdManager */
73
-	private $cloudIdManager;
74
-
75
-	/**
76
-	 * Server2Server constructor.
77
-	 *
78
-	 * @param string $appName
79
-	 * @param IRequest $request
80
-	 * @param FederatedShareProvider $federatedShareProvider
81
-	 * @param IDBConnection $connection
82
-	 * @param Share\IManager $shareManager
83
-	 * @param Notifications $notifications
84
-	 * @param AddressHandler $addressHandler
85
-	 * @param IUserManager $userManager
86
-	 * @param ICloudIdManager $cloudIdManager
87
-	 */
88
-	public function __construct($appName,
89
-								IRequest $request,
90
-								FederatedShareProvider $federatedShareProvider,
91
-								IDBConnection $connection,
92
-								Share\IManager $shareManager,
93
-								Notifications $notifications,
94
-								AddressHandler $addressHandler,
95
-								IUserManager $userManager,
96
-								ICloudIdManager $cloudIdManager
97
-	) {
98
-		parent::__construct($appName, $request);
99
-
100
-		$this->federatedShareProvider = $federatedShareProvider;
101
-		$this->connection = $connection;
102
-		$this->shareManager = $shareManager;
103
-		$this->notifications = $notifications;
104
-		$this->addressHandler = $addressHandler;
105
-		$this->userManager = $userManager;
106
-		$this->cloudIdManager = $cloudIdManager;
107
-	}
108
-
109
-	/**
110
-	 * @NoCSRFRequired
111
-	 * @PublicPage
112
-	 *
113
-	 * create a new share
114
-	 *
115
-	 * @return Http\DataResponse
116
-	 * @throws OCSException
117
-	 */
118
-	public function createShare() {
119
-
120
-		if (!$this->isS2SEnabled(true)) {
121
-			throw new OCSException('Server does not support federated cloud sharing', 503);
122
-		}
123
-
124
-		$remote = isset($_POST['remote']) ? $_POST['remote'] : null;
125
-		$token = isset($_POST['token']) ? $_POST['token'] : null;
126
-		$name = isset($_POST['name']) ? $_POST['name'] : null;
127
-		$owner = isset($_POST['owner']) ? $_POST['owner'] : null;
128
-		$sharedBy = isset($_POST['sharedBy']) ? $_POST['sharedBy'] : null;
129
-		$shareWith = isset($_POST['shareWith']) ? $_POST['shareWith'] : null;
130
-		$remoteId = isset($_POST['remoteId']) ? (int)$_POST['remoteId'] : null;
131
-		$sharedByFederatedId = isset($_POST['sharedByFederatedId']) ? $_POST['sharedByFederatedId'] : null;
132
-		$ownerFederatedId = isset($_POST['ownerFederatedId']) ? $_POST['ownerFederatedId'] : null;
133
-
134
-		if ($remote && $token && $name && $owner && $remoteId && $shareWith) {
135
-
136
-			if (!\OCP\Util::isValidFileName($name)) {
137
-				throw new OCSException('The mountpoint name contains invalid characters.', 400);
138
-			}
139
-
140
-			// FIXME this should be a method in the user management instead
141
-			\OCP\Util::writeLog('files_sharing', 'shareWith before, ' . $shareWith, \OCP\Util::DEBUG);
142
-			\OCP\Util::emitHook(
143
-				'\OCA\Files_Sharing\API\Server2Server',
144
-				'preLoginNameUsedAsUserName',
145
-				array('uid' => &$shareWith)
146
-			);
147
-			\OCP\Util::writeLog('files_sharing', 'shareWith after, ' . $shareWith, \OCP\Util::DEBUG);
148
-
149
-			if (!\OCP\User::userExists($shareWith)) {
150
-				throw new OCSException('User does not exists', 400);
151
-			}
152
-
153
-			\OC_Util::setupFS($shareWith);
154
-
155
-			$externalManager = new \OCA\Files_Sharing\External\Manager(
156
-					\OC::$server->getDatabaseConnection(),
157
-					\OC\Files\Filesystem::getMountManager(),
158
-					\OC\Files\Filesystem::getLoader(),
159
-					\OC::$server->getHTTPClientService(),
160
-					\OC::$server->getNotificationManager(),
161
-					\OC::$server->getOCSDiscoveryService(),
162
-					$shareWith
163
-				);
164
-
165
-			try {
166
-				$externalManager->addShare($remote, $token, '', $name, $owner, false, $shareWith, $remoteId);
167
-				$shareId = \OC::$server->getDatabaseConnection()->lastInsertId('*PREFIX*share_external');
168
-
169
-				if ($ownerFederatedId === null) {
170
-					$ownerFederatedId = $this->cloudIdManager->getCloudId($owner, $this->cleanupRemote($remote))->getId();
171
-				}
172
-				// if the owner of the share and the initiator are the same user
173
-				// we also complete the federated share ID for the initiator
174
-				if ($sharedByFederatedId === null && $owner === $sharedBy) {
175
-					$sharedByFederatedId = $ownerFederatedId;
176
-				}
177
-
178
-				$event = \OC::$server->getActivityManager()->generateEvent();
179
-				$event->setApp('files_sharing')
180
-					->setType('remote_share')
181
-					->setSubject(RemoteShares::SUBJECT_REMOTE_SHARE_RECEIVED, [$ownerFederatedId, trim($name, '/')])
182
-					->setAffectedUser($shareWith)
183
-					->setObject('remote_share', (int)$shareId, $name);
184
-				\OC::$server->getActivityManager()->publish($event);
185
-
186
-				$urlGenerator = \OC::$server->getURLGenerator();
187
-
188
-				$notificationManager = \OC::$server->getNotificationManager();
189
-				$notification = $notificationManager->createNotification();
190
-				$notification->setApp('files_sharing')
191
-					->setUser($shareWith)
192
-					->setDateTime(new \DateTime())
193
-					->setObject('remote_share', $shareId)
194
-					->setSubject('remote_share', [$ownerFederatedId, $sharedByFederatedId, trim($name, '/')]);
195
-
196
-				$declineAction = $notification->createAction();
197
-				$declineAction->setLabel('decline')
198
-					->setLink($urlGenerator->getAbsoluteURL($urlGenerator->linkTo('', 'ocs/v1.php/apps/files_sharing/api/v1/remote_shares/pending/' . $shareId)), 'DELETE');
199
-				$notification->addAction($declineAction);
200
-
201
-				$acceptAction = $notification->createAction();
202
-				$acceptAction->setLabel('accept')
203
-					->setLink($urlGenerator->getAbsoluteURL($urlGenerator->linkTo('', 'ocs/v1.php/apps/files_sharing/api/v1/remote_shares/pending/' . $shareId)), 'POST');
204
-				$notification->addAction($acceptAction);
205
-
206
-				$notificationManager->notify($notification);
207
-
208
-				return new Http\DataResponse();
209
-			} catch (\Exception $e) {
210
-				\OCP\Util::writeLog('files_sharing', 'server can not add remote share, ' . $e->getMessage(), \OCP\Util::ERROR);
211
-				throw new OCSException('internal server error, was not able to add share from ' . $remote, 500);
212
-			}
213
-		}
214
-
215
-		throw new OCSException('server can not add remote share, missing parameter', 400);
216
-	}
217
-
218
-	/**
219
-	 * @NoCSRFRequired
220
-	 * @PublicPage
221
-	 *
222
-	 * create re-share on behalf of another user
223
-	 *
224
-	 * @param int $id
225
-	 * @return Http\DataResponse
226
-	 * @throws OCSBadRequestException
227
-	 * @throws OCSForbiddenException
228
-	 * @throws OCSNotFoundException
229
-	 */
230
-	public function reShare($id) {
231
-
232
-		$token = $this->request->getParam('token', null);
233
-		$shareWith = $this->request->getParam('shareWith', null);
234
-		$permission = (int)$this->request->getParam('permission', null);
235
-		$remoteId = (int)$this->request->getParam('remoteId', null);
236
-
237
-		if ($id === null ||
238
-			$token === null ||
239
-			$shareWith === null ||
240
-			$permission === null ||
241
-			$remoteId === null
242
-		) {
243
-			throw new OCSBadRequestException();
244
-		}
245
-
246
-		try {
247
-			$share = $this->federatedShareProvider->getShareById($id);
248
-		} catch (Share\Exceptions\ShareNotFound $e) {
249
-			throw new OCSNotFoundException();
250
-		}
251
-
252
-		// don't allow to share a file back to the owner
253
-		list($user, $remote) = $this->addressHandler->splitUserRemote($shareWith);
254
-		$owner = $share->getShareOwner();
255
-		$currentServer = $this->addressHandler->generateRemoteURL();
256
-		if ($this->addressHandler->compareAddresses($user, $remote, $owner, $currentServer)) {
257
-			throw new OCSForbiddenException();
258
-		}
259
-
260
-		if ($this->verifyShare($share, $token)) {
261
-
262
-			// check if re-sharing is allowed
263
-			if ($share->getPermissions() | ~Constants::PERMISSION_SHARE) {
264
-				$share->setPermissions($share->getPermissions() & $permission);
265
-				// the recipient of the initial share is now the initiator for the re-share
266
-				$share->setSharedBy($share->getSharedWith());
267
-				$share->setSharedWith($shareWith);
268
-				try {
269
-					$result = $this->federatedShareProvider->create($share);
270
-					$this->federatedShareProvider->storeRemoteId((int)$result->getId(), $remoteId);
271
-					return new Http\DataResponse([
272
-						'token' => $result->getToken(),
273
-						'remoteId' => $result->getId()
274
-					]);
275
-				} catch (\Exception $e) {
276
-					throw new OCSBadRequestException();
277
-				}
278
-			} else {
279
-				throw new OCSForbiddenException();
280
-			}
281
-		}
282
-		throw new OCSBadRequestException();
283
-	}
284
-
285
-	/**
286
-	 * @NoCSRFRequired
287
-	 * @PublicPage
288
-	 *
289
-	 * accept server-to-server share
290
-	 *
291
-	 * @param int $id
292
-	 * @return Http\DataResponse
293
-	 * @throws OCSException
294
-	 */
295
-	public function acceptShare($id) {
296
-
297
-		if (!$this->isS2SEnabled()) {
298
-			throw new OCSException('Server does not support federated cloud sharing', 503);
299
-		}
300
-
301
-		$token = isset($_POST['token']) ? $_POST['token'] : null;
302
-
303
-		try {
304
-			$share = $this->federatedShareProvider->getShareById($id);
305
-		} catch (Share\Exceptions\ShareNotFound $e) {
306
-			return new Http\DataResponse();
307
-		}
308
-
309
-		if ($this->verifyShare($share, $token)) {
310
-			$this->executeAcceptShare($share);
311
-			if ($share->getShareOwner() !== $share->getSharedBy()) {
312
-				list(, $remote) = $this->addressHandler->splitUserRemote($share->getSharedBy());
313
-				$remoteId = $this->federatedShareProvider->getRemoteId($share);
314
-				$this->notifications->sendAcceptShare($remote, $remoteId, $share->getToken());
315
-			}
316
-		}
317
-
318
-		return new Http\DataResponse();
319
-	}
320
-
321
-	protected function executeAcceptShare(Share\IShare $share) {
322
-		list($file, $link) = $this->getFile($this->getCorrectUid($share), $share->getNode()->getId());
323
-
324
-		$event = \OC::$server->getActivityManager()->generateEvent();
325
-		$event->setApp('files_sharing')
326
-			->setType('remote_share')
327
-			->setAffectedUser($this->getCorrectUid($share))
328
-			->setSubject(RemoteShares::SUBJECT_REMOTE_SHARE_ACCEPTED, [$share->getSharedWith(), $file])
329
-			->setObject('files', (int)$share->getNode()->getId(), $file)
330
-			->setLink($link);
331
-		\OC::$server->getActivityManager()->publish($event);
332
-	}
333
-
334
-	/**
335
-	 * @NoCSRFRequired
336
-	 * @PublicPage
337
-	 *
338
-	 * decline server-to-server share
339
-	 *
340
-	 * @param int $id
341
-	 * @return Http\DataResponse
342
-	 * @throws OCSException
343
-	 */
344
-	public function declineShare($id) {
345
-
346
-		if (!$this->isS2SEnabled()) {
347
-			throw new OCSException('Server does not support federated cloud sharing', 503);
348
-		}
349
-
350
-		$token = isset($_POST['token']) ? $_POST['token'] : null;
351
-
352
-		try {
353
-			$share = $this->federatedShareProvider->getShareById($id);
354
-		} catch (Share\Exceptions\ShareNotFound $e) {
355
-			return new Http\DataResponse();
356
-		}
357
-
358
-		if ($this->verifyShare($share, $token)) {
359
-			if ($share->getShareOwner() !== $share->getSharedBy()) {
360
-				list(, $remote) = $this->addressHandler->splitUserRemote($share->getSharedBy());
361
-				$remoteId = $this->federatedShareProvider->getRemoteId($share);
362
-				$this->notifications->sendDeclineShare($remote, $remoteId, $share->getToken());
363
-			}
364
-			$this->executeDeclineShare($share);
365
-		}
366
-
367
-		return new Http\DataResponse();
368
-	}
369
-
370
-	/**
371
-	 * delete declined share and create a activity
372
-	 *
373
-	 * @param Share\IShare $share
374
-	 */
375
-	protected function executeDeclineShare(Share\IShare $share) {
376
-		$this->federatedShareProvider->removeShareFromTable($share);
377
-		list($file, $link) = $this->getFile($this->getCorrectUid($share), $share->getNode()->getId());
378
-
379
-		$event = \OC::$server->getActivityManager()->generateEvent();
380
-		$event->setApp('files_sharing')
381
-			->setType('remote_share')
382
-			->setAffectedUser($this->getCorrectUid($share))
383
-			->setSubject(RemoteShares::SUBJECT_REMOTE_SHARE_DECLINED, [$share->getSharedWith(), $file])
384
-			->setObject('files', (int)$share->getNode()->getId(), $file)
385
-			->setLink($link);
386
-		\OC::$server->getActivityManager()->publish($event);
387
-
388
-	}
389
-
390
-	/**
391
-	 * check if we are the initiator or the owner of a re-share and return the correct UID
392
-	 *
393
-	 * @param Share\IShare $share
394
-	 * @return string
395
-	 */
396
-	protected function getCorrectUid(Share\IShare $share) {
397
-		if ($this->userManager->userExists($share->getShareOwner())) {
398
-			return $share->getShareOwner();
399
-		}
400
-
401
-		return $share->getSharedBy();
402
-	}
403
-
404
-	/**
405
-	 * @NoCSRFRequired
406
-	 * @PublicPage
407
-	 *
408
-	 * remove server-to-server share if it was unshared by the owner
409
-	 *
410
-	 * @param int $id
411
-	 * @return Http\DataResponse
412
-	 * @throws OCSException
413
-	 */
414
-	public function unshare($id) {
415
-
416
-		if (!$this->isS2SEnabled()) {
417
-			throw new OCSException('Server does not support federated cloud sharing', 503);
418
-		}
419
-
420
-		$token = isset($_POST['token']) ? $_POST['token'] : null;
421
-
422
-		$query = \OCP\DB::prepare('SELECT * FROM `*PREFIX*share_external` WHERE `remote_id` = ? AND `share_token` = ?');
423
-		$query->execute(array($id, $token));
424
-		$share = $query->fetchRow();
425
-
426
-		if ($token && $id && !empty($share)) {
427
-
428
-			$remote = $this->cleanupRemote($share['remote']);
429
-
430
-			$owner = $this->cloudIdManager->getCloudId($share['owner'], $remote);
431
-			$mountpoint = $share['mountpoint'];
432
-			$user = $share['user'];
433
-
434
-			$query = \OCP\DB::prepare('DELETE FROM `*PREFIX*share_external` WHERE `remote_id` = ? AND `share_token` = ?');
435
-			$query->execute(array($id, $token));
436
-
437
-			if ($share['accepted']) {
438
-				$path = trim($mountpoint, '/');
439
-			} else {
440
-				$path = trim($share['name'], '/');
441
-			}
442
-
443
-			$notificationManager = \OC::$server->getNotificationManager();
444
-			$notification = $notificationManager->createNotification();
445
-			$notification->setApp('files_sharing')
446
-				->setUser($share['user'])
447
-				->setObject('remote_share', (int)$share['id']);
448
-			$notificationManager->markProcessed($notification);
449
-
450
-			$event = \OC::$server->getActivityManager()->generateEvent();
451
-			$event->setApp('files_sharing')
452
-				->setType('remote_share')
453
-				->setSubject(RemoteShares::SUBJECT_REMOTE_SHARE_UNSHARED, [$owner, $path])
454
-				->setAffectedUser($user)
455
-				->setObject('remote_share', (int)$share['id'], $path);
456
-			\OC::$server->getActivityManager()->publish($event);
457
-		}
458
-
459
-		return new Http\DataResponse();
460
-	}
461
-
462
-	private function cleanupRemote($remote) {
463
-		$remote = substr($remote, strpos($remote, '://') + 3);
464
-
465
-		return rtrim($remote, '/');
466
-	}
467
-
468
-
469
-	/**
470
-	 * @NoCSRFRequired
471
-	 * @PublicPage
472
-	 *
473
-	 * federated share was revoked, either by the owner or the re-sharer
474
-	 *
475
-	 * @param int $id
476
-	 * @return Http\DataResponse
477
-	 * @throws OCSBadRequestException
478
-	 */
479
-	public function revoke($id) {
480
-		$token = $this->request->getParam('token');
481
-
482
-		$share = $this->federatedShareProvider->getShareById($id);
483
-
484
-		if ($this->verifyShare($share, $token)) {
485
-			$this->federatedShareProvider->removeShareFromTable($share);
486
-			return new Http\DataResponse();
487
-		}
488
-
489
-		throw new OCSBadRequestException();
490
-	}
491
-
492
-	/**
493
-	 * get share
494
-	 *
495
-	 * @param int $id
496
-	 * @param string $token
497
-	 * @return array|bool
498
-	 */
499
-	protected function getShare($id, $token) {
500
-		$query = $this->connection->getQueryBuilder();
501
-		$query->select('*')->from($this->shareTable)
502
-			->where($query->expr()->eq('token', $query->createNamedParameter($token)))
503
-			->andWhere($query->expr()->eq('share_type', $query->createNamedParameter(FederatedShareProvider::SHARE_TYPE_REMOTE)))
504
-			->andWhere($query->expr()->eq('id', $query->createNamedParameter($id)));
505
-
506
-		$result = $query->execute()->fetchAll();
507
-
508
-		if (!empty($result) && isset($result[0])) {
509
-			return $result[0];
510
-		}
511
-
512
-		return false;
513
-	}
514
-
515
-	/**
516
-	 * get file
517
-	 *
518
-	 * @param string $user
519
-	 * @param int $fileSource
520
-	 * @return array with internal path of the file and a absolute link to it
521
-	 */
522
-	private function getFile($user, $fileSource) {
523
-		\OC_Util::setupFS($user);
524
-
525
-		try {
526
-			$file = \OC\Files\Filesystem::getPath($fileSource);
527
-		} catch (NotFoundException $e) {
528
-			$file = null;
529
-		}
530
-		$args = \OC\Files\Filesystem::is_dir($file) ? array('dir' => $file) : array('dir' => dirname($file), 'scrollto' => $file);
531
-		$link = \OCP\Util::linkToAbsolute('files', 'index.php', $args);
532
-
533
-		return array($file, $link);
534
-
535
-	}
536
-
537
-	/**
538
-	 * check if server-to-server sharing is enabled
539
-	 *
540
-	 * @param bool $incoming
541
-	 * @return bool
542
-	 */
543
-	private function isS2SEnabled($incoming = false) {
544
-
545
-		$result = \OCP\App::isEnabled('files_sharing');
546
-
547
-		if ($incoming) {
548
-			$result = $result && $this->federatedShareProvider->isIncomingServer2serverShareEnabled();
549
-		} else {
550
-			$result = $result && $this->federatedShareProvider->isOutgoingServer2serverShareEnabled();
551
-		}
552
-
553
-		return $result;
554
-	}
555
-
556
-	/**
557
-	 * check if we got the right share
558
-	 *
559
-	 * @param Share\IShare $share
560
-	 * @param string $token
561
-	 * @return bool
562
-	 */
563
-	protected function verifyShare(Share\IShare $share, $token) {
564
-		if (
565
-			$share->getShareType() === FederatedShareProvider::SHARE_TYPE_REMOTE &&
566
-			$share->getToken() === $token
567
-		) {
568
-			return true;
569
-		}
570
-
571
-		return false;
572
-	}
573
-
574
-	/**
575
-	 * @NoCSRFRequired
576
-	 * @PublicPage
577
-	 *
578
-	 * update share information to keep federated re-shares in sync
579
-	 *
580
-	 * @param int $id
581
-	 * @return Http\DataResponse
582
-	 * @throws OCSBadRequestException
583
-	 */
584
-	public function updatePermissions($id) {
585
-		$token = $this->request->getParam('token', null);
586
-		$permissions = $this->request->getParam('permissions', null);
587
-
588
-		try {
589
-			$share = $this->federatedShareProvider->getShareById($id);
590
-		} catch (Share\Exceptions\ShareNotFound $e) {
591
-			throw new OCSBadRequestException();
592
-		}
593
-
594
-		$validPermission = ctype_digit($permissions);
595
-		$validToken = $this->verifyShare($share, $token);
596
-		if ($validPermission && $validToken) {
597
-			$this->updatePermissionsInDatabase($share, (int)$permissions);
598
-		} else {
599
-			throw new OCSBadRequestException();
600
-		}
601
-
602
-		return new Http\DataResponse();
603
-	}
604
-
605
-	/**
606
-	 * update permissions in database
607
-	 *
608
-	 * @param IShare $share
609
-	 * @param int $permissions
610
-	 */
611
-	protected function updatePermissionsInDatabase(IShare $share, $permissions) {
612
-		$query = $this->connection->getQueryBuilder();
613
-		$query->update('share')
614
-			->where($query->expr()->eq('id', $query->createNamedParameter($share->getId())))
615
-			->set('permissions', $query->createNamedParameter($permissions))
616
-			->execute();
617
-	}
618
-
619
-	/**
620
-	 * @NoCSRFRequired
621
-	 * @PublicPage
622
-	 *
623
-	 * change the owner of a server-to-server share
624
-	 *
625
-	 * @param int $id
626
-	 * @return Http\DataResponse
627
-	 * @throws \InvalidArgumentException
628
-	 * @throws OCSException
629
-	 */
630
-	public function move($id) {
631
-
632
-		if (!$this->isS2SEnabled()) {
633
-			throw new OCSException('Server does not support federated cloud sharing', 503);
634
-		}
635
-
636
-		$token = $this->request->getParam('token');
637
-		$remote = $this->request->getParam('remote');
638
-		$newRemoteId = $this->request->getParam('remote_id', $id);
639
-		$cloudId = $this->cloudIdManager->resolveCloudId($remote);
640
-
641
-		$qb = $this->connection->getQueryBuilder();
642
-		$query = $qb->update('share_external')
643
-			->set('remote', $qb->createNamedParameter($cloudId->getRemote()))
644
-			->set('owner', $qb->createNamedParameter($cloudId->getUser()))
645
-			->set('remote_id', $qb->createNamedParameter($newRemoteId))
646
-			->where($qb->expr()->eq('remote_id', $qb->createNamedParameter($id)))
647
-			->andWhere($qb->expr()->eq('share_token', $qb->createNamedParameter($token)));
648
-		$affected = $query->execute();
649
-
650
-		if ($affected > 0) {
651
-			return new Http\DataResponse(['remote' => $cloudId->getRemote(), 'owner' => $cloudId->getUser()]);
652
-		} else {
653
-			throw new OCSBadRequestException('Share not found or token invalid');
654
-		}
655
-	}
51
+    /** @var FederatedShareProvider */
52
+    private $federatedShareProvider;
53
+
54
+    /** @var IDBConnection */
55
+    private $connection;
56
+
57
+    /** @var Share\IManager */
58
+    private $shareManager;
59
+
60
+    /** @var Notifications */
61
+    private $notifications;
62
+
63
+    /** @var AddressHandler */
64
+    private $addressHandler;
65
+
66
+    /** @var  IUserManager */
67
+    private $userManager;
68
+
69
+    /** @var string */
70
+    private $shareTable = 'share';
71
+
72
+    /** @var ICloudIdManager */
73
+    private $cloudIdManager;
74
+
75
+    /**
76
+     * Server2Server constructor.
77
+     *
78
+     * @param string $appName
79
+     * @param IRequest $request
80
+     * @param FederatedShareProvider $federatedShareProvider
81
+     * @param IDBConnection $connection
82
+     * @param Share\IManager $shareManager
83
+     * @param Notifications $notifications
84
+     * @param AddressHandler $addressHandler
85
+     * @param IUserManager $userManager
86
+     * @param ICloudIdManager $cloudIdManager
87
+     */
88
+    public function __construct($appName,
89
+                                IRequest $request,
90
+                                FederatedShareProvider $federatedShareProvider,
91
+                                IDBConnection $connection,
92
+                                Share\IManager $shareManager,
93
+                                Notifications $notifications,
94
+                                AddressHandler $addressHandler,
95
+                                IUserManager $userManager,
96
+                                ICloudIdManager $cloudIdManager
97
+    ) {
98
+        parent::__construct($appName, $request);
99
+
100
+        $this->federatedShareProvider = $federatedShareProvider;
101
+        $this->connection = $connection;
102
+        $this->shareManager = $shareManager;
103
+        $this->notifications = $notifications;
104
+        $this->addressHandler = $addressHandler;
105
+        $this->userManager = $userManager;
106
+        $this->cloudIdManager = $cloudIdManager;
107
+    }
108
+
109
+    /**
110
+     * @NoCSRFRequired
111
+     * @PublicPage
112
+     *
113
+     * create a new share
114
+     *
115
+     * @return Http\DataResponse
116
+     * @throws OCSException
117
+     */
118
+    public function createShare() {
119
+
120
+        if (!$this->isS2SEnabled(true)) {
121
+            throw new OCSException('Server does not support federated cloud sharing', 503);
122
+        }
123
+
124
+        $remote = isset($_POST['remote']) ? $_POST['remote'] : null;
125
+        $token = isset($_POST['token']) ? $_POST['token'] : null;
126
+        $name = isset($_POST['name']) ? $_POST['name'] : null;
127
+        $owner = isset($_POST['owner']) ? $_POST['owner'] : null;
128
+        $sharedBy = isset($_POST['sharedBy']) ? $_POST['sharedBy'] : null;
129
+        $shareWith = isset($_POST['shareWith']) ? $_POST['shareWith'] : null;
130
+        $remoteId = isset($_POST['remoteId']) ? (int)$_POST['remoteId'] : null;
131
+        $sharedByFederatedId = isset($_POST['sharedByFederatedId']) ? $_POST['sharedByFederatedId'] : null;
132
+        $ownerFederatedId = isset($_POST['ownerFederatedId']) ? $_POST['ownerFederatedId'] : null;
133
+
134
+        if ($remote && $token && $name && $owner && $remoteId && $shareWith) {
135
+
136
+            if (!\OCP\Util::isValidFileName($name)) {
137
+                throw new OCSException('The mountpoint name contains invalid characters.', 400);
138
+            }
139
+
140
+            // FIXME this should be a method in the user management instead
141
+            \OCP\Util::writeLog('files_sharing', 'shareWith before, ' . $shareWith, \OCP\Util::DEBUG);
142
+            \OCP\Util::emitHook(
143
+                '\OCA\Files_Sharing\API\Server2Server',
144
+                'preLoginNameUsedAsUserName',
145
+                array('uid' => &$shareWith)
146
+            );
147
+            \OCP\Util::writeLog('files_sharing', 'shareWith after, ' . $shareWith, \OCP\Util::DEBUG);
148
+
149
+            if (!\OCP\User::userExists($shareWith)) {
150
+                throw new OCSException('User does not exists', 400);
151
+            }
152
+
153
+            \OC_Util::setupFS($shareWith);
154
+
155
+            $externalManager = new \OCA\Files_Sharing\External\Manager(
156
+                    \OC::$server->getDatabaseConnection(),
157
+                    \OC\Files\Filesystem::getMountManager(),
158
+                    \OC\Files\Filesystem::getLoader(),
159
+                    \OC::$server->getHTTPClientService(),
160
+                    \OC::$server->getNotificationManager(),
161
+                    \OC::$server->getOCSDiscoveryService(),
162
+                    $shareWith
163
+                );
164
+
165
+            try {
166
+                $externalManager->addShare($remote, $token, '', $name, $owner, false, $shareWith, $remoteId);
167
+                $shareId = \OC::$server->getDatabaseConnection()->lastInsertId('*PREFIX*share_external');
168
+
169
+                if ($ownerFederatedId === null) {
170
+                    $ownerFederatedId = $this->cloudIdManager->getCloudId($owner, $this->cleanupRemote($remote))->getId();
171
+                }
172
+                // if the owner of the share and the initiator are the same user
173
+                // we also complete the federated share ID for the initiator
174
+                if ($sharedByFederatedId === null && $owner === $sharedBy) {
175
+                    $sharedByFederatedId = $ownerFederatedId;
176
+                }
177
+
178
+                $event = \OC::$server->getActivityManager()->generateEvent();
179
+                $event->setApp('files_sharing')
180
+                    ->setType('remote_share')
181
+                    ->setSubject(RemoteShares::SUBJECT_REMOTE_SHARE_RECEIVED, [$ownerFederatedId, trim($name, '/')])
182
+                    ->setAffectedUser($shareWith)
183
+                    ->setObject('remote_share', (int)$shareId, $name);
184
+                \OC::$server->getActivityManager()->publish($event);
185
+
186
+                $urlGenerator = \OC::$server->getURLGenerator();
187
+
188
+                $notificationManager = \OC::$server->getNotificationManager();
189
+                $notification = $notificationManager->createNotification();
190
+                $notification->setApp('files_sharing')
191
+                    ->setUser($shareWith)
192
+                    ->setDateTime(new \DateTime())
193
+                    ->setObject('remote_share', $shareId)
194
+                    ->setSubject('remote_share', [$ownerFederatedId, $sharedByFederatedId, trim($name, '/')]);
195
+
196
+                $declineAction = $notification->createAction();
197
+                $declineAction->setLabel('decline')
198
+                    ->setLink($urlGenerator->getAbsoluteURL($urlGenerator->linkTo('', 'ocs/v1.php/apps/files_sharing/api/v1/remote_shares/pending/' . $shareId)), 'DELETE');
199
+                $notification->addAction($declineAction);
200
+
201
+                $acceptAction = $notification->createAction();
202
+                $acceptAction->setLabel('accept')
203
+                    ->setLink($urlGenerator->getAbsoluteURL($urlGenerator->linkTo('', 'ocs/v1.php/apps/files_sharing/api/v1/remote_shares/pending/' . $shareId)), 'POST');
204
+                $notification->addAction($acceptAction);
205
+
206
+                $notificationManager->notify($notification);
207
+
208
+                return new Http\DataResponse();
209
+            } catch (\Exception $e) {
210
+                \OCP\Util::writeLog('files_sharing', 'server can not add remote share, ' . $e->getMessage(), \OCP\Util::ERROR);
211
+                throw new OCSException('internal server error, was not able to add share from ' . $remote, 500);
212
+            }
213
+        }
214
+
215
+        throw new OCSException('server can not add remote share, missing parameter', 400);
216
+    }
217
+
218
+    /**
219
+     * @NoCSRFRequired
220
+     * @PublicPage
221
+     *
222
+     * create re-share on behalf of another user
223
+     *
224
+     * @param int $id
225
+     * @return Http\DataResponse
226
+     * @throws OCSBadRequestException
227
+     * @throws OCSForbiddenException
228
+     * @throws OCSNotFoundException
229
+     */
230
+    public function reShare($id) {
231
+
232
+        $token = $this->request->getParam('token', null);
233
+        $shareWith = $this->request->getParam('shareWith', null);
234
+        $permission = (int)$this->request->getParam('permission', null);
235
+        $remoteId = (int)$this->request->getParam('remoteId', null);
236
+
237
+        if ($id === null ||
238
+            $token === null ||
239
+            $shareWith === null ||
240
+            $permission === null ||
241
+            $remoteId === null
242
+        ) {
243
+            throw new OCSBadRequestException();
244
+        }
245
+
246
+        try {
247
+            $share = $this->federatedShareProvider->getShareById($id);
248
+        } catch (Share\Exceptions\ShareNotFound $e) {
249
+            throw new OCSNotFoundException();
250
+        }
251
+
252
+        // don't allow to share a file back to the owner
253
+        list($user, $remote) = $this->addressHandler->splitUserRemote($shareWith);
254
+        $owner = $share->getShareOwner();
255
+        $currentServer = $this->addressHandler->generateRemoteURL();
256
+        if ($this->addressHandler->compareAddresses($user, $remote, $owner, $currentServer)) {
257
+            throw new OCSForbiddenException();
258
+        }
259
+
260
+        if ($this->verifyShare($share, $token)) {
261
+
262
+            // check if re-sharing is allowed
263
+            if ($share->getPermissions() | ~Constants::PERMISSION_SHARE) {
264
+                $share->setPermissions($share->getPermissions() & $permission);
265
+                // the recipient of the initial share is now the initiator for the re-share
266
+                $share->setSharedBy($share->getSharedWith());
267
+                $share->setSharedWith($shareWith);
268
+                try {
269
+                    $result = $this->federatedShareProvider->create($share);
270
+                    $this->federatedShareProvider->storeRemoteId((int)$result->getId(), $remoteId);
271
+                    return new Http\DataResponse([
272
+                        'token' => $result->getToken(),
273
+                        'remoteId' => $result->getId()
274
+                    ]);
275
+                } catch (\Exception $e) {
276
+                    throw new OCSBadRequestException();
277
+                }
278
+            } else {
279
+                throw new OCSForbiddenException();
280
+            }
281
+        }
282
+        throw new OCSBadRequestException();
283
+    }
284
+
285
+    /**
286
+     * @NoCSRFRequired
287
+     * @PublicPage
288
+     *
289
+     * accept server-to-server share
290
+     *
291
+     * @param int $id
292
+     * @return Http\DataResponse
293
+     * @throws OCSException
294
+     */
295
+    public function acceptShare($id) {
296
+
297
+        if (!$this->isS2SEnabled()) {
298
+            throw new OCSException('Server does not support federated cloud sharing', 503);
299
+        }
300
+
301
+        $token = isset($_POST['token']) ? $_POST['token'] : null;
302
+
303
+        try {
304
+            $share = $this->federatedShareProvider->getShareById($id);
305
+        } catch (Share\Exceptions\ShareNotFound $e) {
306
+            return new Http\DataResponse();
307
+        }
308
+
309
+        if ($this->verifyShare($share, $token)) {
310
+            $this->executeAcceptShare($share);
311
+            if ($share->getShareOwner() !== $share->getSharedBy()) {
312
+                list(, $remote) = $this->addressHandler->splitUserRemote($share->getSharedBy());
313
+                $remoteId = $this->federatedShareProvider->getRemoteId($share);
314
+                $this->notifications->sendAcceptShare($remote, $remoteId, $share->getToken());
315
+            }
316
+        }
317
+
318
+        return new Http\DataResponse();
319
+    }
320
+
321
+    protected function executeAcceptShare(Share\IShare $share) {
322
+        list($file, $link) = $this->getFile($this->getCorrectUid($share), $share->getNode()->getId());
323
+
324
+        $event = \OC::$server->getActivityManager()->generateEvent();
325
+        $event->setApp('files_sharing')
326
+            ->setType('remote_share')
327
+            ->setAffectedUser($this->getCorrectUid($share))
328
+            ->setSubject(RemoteShares::SUBJECT_REMOTE_SHARE_ACCEPTED, [$share->getSharedWith(), $file])
329
+            ->setObject('files', (int)$share->getNode()->getId(), $file)
330
+            ->setLink($link);
331
+        \OC::$server->getActivityManager()->publish($event);
332
+    }
333
+
334
+    /**
335
+     * @NoCSRFRequired
336
+     * @PublicPage
337
+     *
338
+     * decline server-to-server share
339
+     *
340
+     * @param int $id
341
+     * @return Http\DataResponse
342
+     * @throws OCSException
343
+     */
344
+    public function declineShare($id) {
345
+
346
+        if (!$this->isS2SEnabled()) {
347
+            throw new OCSException('Server does not support federated cloud sharing', 503);
348
+        }
349
+
350
+        $token = isset($_POST['token']) ? $_POST['token'] : null;
351
+
352
+        try {
353
+            $share = $this->federatedShareProvider->getShareById($id);
354
+        } catch (Share\Exceptions\ShareNotFound $e) {
355
+            return new Http\DataResponse();
356
+        }
357
+
358
+        if ($this->verifyShare($share, $token)) {
359
+            if ($share->getShareOwner() !== $share->getSharedBy()) {
360
+                list(, $remote) = $this->addressHandler->splitUserRemote($share->getSharedBy());
361
+                $remoteId = $this->federatedShareProvider->getRemoteId($share);
362
+                $this->notifications->sendDeclineShare($remote, $remoteId, $share->getToken());
363
+            }
364
+            $this->executeDeclineShare($share);
365
+        }
366
+
367
+        return new Http\DataResponse();
368
+    }
369
+
370
+    /**
371
+     * delete declined share and create a activity
372
+     *
373
+     * @param Share\IShare $share
374
+     */
375
+    protected function executeDeclineShare(Share\IShare $share) {
376
+        $this->federatedShareProvider->removeShareFromTable($share);
377
+        list($file, $link) = $this->getFile($this->getCorrectUid($share), $share->getNode()->getId());
378
+
379
+        $event = \OC::$server->getActivityManager()->generateEvent();
380
+        $event->setApp('files_sharing')
381
+            ->setType('remote_share')
382
+            ->setAffectedUser($this->getCorrectUid($share))
383
+            ->setSubject(RemoteShares::SUBJECT_REMOTE_SHARE_DECLINED, [$share->getSharedWith(), $file])
384
+            ->setObject('files', (int)$share->getNode()->getId(), $file)
385
+            ->setLink($link);
386
+        \OC::$server->getActivityManager()->publish($event);
387
+
388
+    }
389
+
390
+    /**
391
+     * check if we are the initiator or the owner of a re-share and return the correct UID
392
+     *
393
+     * @param Share\IShare $share
394
+     * @return string
395
+     */
396
+    protected function getCorrectUid(Share\IShare $share) {
397
+        if ($this->userManager->userExists($share->getShareOwner())) {
398
+            return $share->getShareOwner();
399
+        }
400
+
401
+        return $share->getSharedBy();
402
+    }
403
+
404
+    /**
405
+     * @NoCSRFRequired
406
+     * @PublicPage
407
+     *
408
+     * remove server-to-server share if it was unshared by the owner
409
+     *
410
+     * @param int $id
411
+     * @return Http\DataResponse
412
+     * @throws OCSException
413
+     */
414
+    public function unshare($id) {
415
+
416
+        if (!$this->isS2SEnabled()) {
417
+            throw new OCSException('Server does not support federated cloud sharing', 503);
418
+        }
419
+
420
+        $token = isset($_POST['token']) ? $_POST['token'] : null;
421
+
422
+        $query = \OCP\DB::prepare('SELECT * FROM `*PREFIX*share_external` WHERE `remote_id` = ? AND `share_token` = ?');
423
+        $query->execute(array($id, $token));
424
+        $share = $query->fetchRow();
425
+
426
+        if ($token && $id && !empty($share)) {
427
+
428
+            $remote = $this->cleanupRemote($share['remote']);
429
+
430
+            $owner = $this->cloudIdManager->getCloudId($share['owner'], $remote);
431
+            $mountpoint = $share['mountpoint'];
432
+            $user = $share['user'];
433
+
434
+            $query = \OCP\DB::prepare('DELETE FROM `*PREFIX*share_external` WHERE `remote_id` = ? AND `share_token` = ?');
435
+            $query->execute(array($id, $token));
436
+
437
+            if ($share['accepted']) {
438
+                $path = trim($mountpoint, '/');
439
+            } else {
440
+                $path = trim($share['name'], '/');
441
+            }
442
+
443
+            $notificationManager = \OC::$server->getNotificationManager();
444
+            $notification = $notificationManager->createNotification();
445
+            $notification->setApp('files_sharing')
446
+                ->setUser($share['user'])
447
+                ->setObject('remote_share', (int)$share['id']);
448
+            $notificationManager->markProcessed($notification);
449
+
450
+            $event = \OC::$server->getActivityManager()->generateEvent();
451
+            $event->setApp('files_sharing')
452
+                ->setType('remote_share')
453
+                ->setSubject(RemoteShares::SUBJECT_REMOTE_SHARE_UNSHARED, [$owner, $path])
454
+                ->setAffectedUser($user)
455
+                ->setObject('remote_share', (int)$share['id'], $path);
456
+            \OC::$server->getActivityManager()->publish($event);
457
+        }
458
+
459
+        return new Http\DataResponse();
460
+    }
461
+
462
+    private function cleanupRemote($remote) {
463
+        $remote = substr($remote, strpos($remote, '://') + 3);
464
+
465
+        return rtrim($remote, '/');
466
+    }
467
+
468
+
469
+    /**
470
+     * @NoCSRFRequired
471
+     * @PublicPage
472
+     *
473
+     * federated share was revoked, either by the owner or the re-sharer
474
+     *
475
+     * @param int $id
476
+     * @return Http\DataResponse
477
+     * @throws OCSBadRequestException
478
+     */
479
+    public function revoke($id) {
480
+        $token = $this->request->getParam('token');
481
+
482
+        $share = $this->federatedShareProvider->getShareById($id);
483
+
484
+        if ($this->verifyShare($share, $token)) {
485
+            $this->federatedShareProvider->removeShareFromTable($share);
486
+            return new Http\DataResponse();
487
+        }
488
+
489
+        throw new OCSBadRequestException();
490
+    }
491
+
492
+    /**
493
+     * get share
494
+     *
495
+     * @param int $id
496
+     * @param string $token
497
+     * @return array|bool
498
+     */
499
+    protected function getShare($id, $token) {
500
+        $query = $this->connection->getQueryBuilder();
501
+        $query->select('*')->from($this->shareTable)
502
+            ->where($query->expr()->eq('token', $query->createNamedParameter($token)))
503
+            ->andWhere($query->expr()->eq('share_type', $query->createNamedParameter(FederatedShareProvider::SHARE_TYPE_REMOTE)))
504
+            ->andWhere($query->expr()->eq('id', $query->createNamedParameter($id)));
505
+
506
+        $result = $query->execute()->fetchAll();
507
+
508
+        if (!empty($result) && isset($result[0])) {
509
+            return $result[0];
510
+        }
511
+
512
+        return false;
513
+    }
514
+
515
+    /**
516
+     * get file
517
+     *
518
+     * @param string $user
519
+     * @param int $fileSource
520
+     * @return array with internal path of the file and a absolute link to it
521
+     */
522
+    private function getFile($user, $fileSource) {
523
+        \OC_Util::setupFS($user);
524
+
525
+        try {
526
+            $file = \OC\Files\Filesystem::getPath($fileSource);
527
+        } catch (NotFoundException $e) {
528
+            $file = null;
529
+        }
530
+        $args = \OC\Files\Filesystem::is_dir($file) ? array('dir' => $file) : array('dir' => dirname($file), 'scrollto' => $file);
531
+        $link = \OCP\Util::linkToAbsolute('files', 'index.php', $args);
532
+
533
+        return array($file, $link);
534
+
535
+    }
536
+
537
+    /**
538
+     * check if server-to-server sharing is enabled
539
+     *
540
+     * @param bool $incoming
541
+     * @return bool
542
+     */
543
+    private function isS2SEnabled($incoming = false) {
544
+
545
+        $result = \OCP\App::isEnabled('files_sharing');
546
+
547
+        if ($incoming) {
548
+            $result = $result && $this->federatedShareProvider->isIncomingServer2serverShareEnabled();
549
+        } else {
550
+            $result = $result && $this->federatedShareProvider->isOutgoingServer2serverShareEnabled();
551
+        }
552
+
553
+        return $result;
554
+    }
555
+
556
+    /**
557
+     * check if we got the right share
558
+     *
559
+     * @param Share\IShare $share
560
+     * @param string $token
561
+     * @return bool
562
+     */
563
+    protected function verifyShare(Share\IShare $share, $token) {
564
+        if (
565
+            $share->getShareType() === FederatedShareProvider::SHARE_TYPE_REMOTE &&
566
+            $share->getToken() === $token
567
+        ) {
568
+            return true;
569
+        }
570
+
571
+        return false;
572
+    }
573
+
574
+    /**
575
+     * @NoCSRFRequired
576
+     * @PublicPage
577
+     *
578
+     * update share information to keep federated re-shares in sync
579
+     *
580
+     * @param int $id
581
+     * @return Http\DataResponse
582
+     * @throws OCSBadRequestException
583
+     */
584
+    public function updatePermissions($id) {
585
+        $token = $this->request->getParam('token', null);
586
+        $permissions = $this->request->getParam('permissions', null);
587
+
588
+        try {
589
+            $share = $this->federatedShareProvider->getShareById($id);
590
+        } catch (Share\Exceptions\ShareNotFound $e) {
591
+            throw new OCSBadRequestException();
592
+        }
593
+
594
+        $validPermission = ctype_digit($permissions);
595
+        $validToken = $this->verifyShare($share, $token);
596
+        if ($validPermission && $validToken) {
597
+            $this->updatePermissionsInDatabase($share, (int)$permissions);
598
+        } else {
599
+            throw new OCSBadRequestException();
600
+        }
601
+
602
+        return new Http\DataResponse();
603
+    }
604
+
605
+    /**
606
+     * update permissions in database
607
+     *
608
+     * @param IShare $share
609
+     * @param int $permissions
610
+     */
611
+    protected function updatePermissionsInDatabase(IShare $share, $permissions) {
612
+        $query = $this->connection->getQueryBuilder();
613
+        $query->update('share')
614
+            ->where($query->expr()->eq('id', $query->createNamedParameter($share->getId())))
615
+            ->set('permissions', $query->createNamedParameter($permissions))
616
+            ->execute();
617
+    }
618
+
619
+    /**
620
+     * @NoCSRFRequired
621
+     * @PublicPage
622
+     *
623
+     * change the owner of a server-to-server share
624
+     *
625
+     * @param int $id
626
+     * @return Http\DataResponse
627
+     * @throws \InvalidArgumentException
628
+     * @throws OCSException
629
+     */
630
+    public function move($id) {
631
+
632
+        if (!$this->isS2SEnabled()) {
633
+            throw new OCSException('Server does not support federated cloud sharing', 503);
634
+        }
635
+
636
+        $token = $this->request->getParam('token');
637
+        $remote = $this->request->getParam('remote');
638
+        $newRemoteId = $this->request->getParam('remote_id', $id);
639
+        $cloudId = $this->cloudIdManager->resolveCloudId($remote);
640
+
641
+        $qb = $this->connection->getQueryBuilder();
642
+        $query = $qb->update('share_external')
643
+            ->set('remote', $qb->createNamedParameter($cloudId->getRemote()))
644
+            ->set('owner', $qb->createNamedParameter($cloudId->getUser()))
645
+            ->set('remote_id', $qb->createNamedParameter($newRemoteId))
646
+            ->where($qb->expr()->eq('remote_id', $qb->createNamedParameter($id)))
647
+            ->andWhere($qb->expr()->eq('share_token', $qb->createNamedParameter($token)));
648
+        $affected = $query->execute();
649
+
650
+        if ($affected > 0) {
651
+            return new Http\DataResponse(['remote' => $cloudId->getRemote(), 'owner' => $cloudId->getUser()]);
652
+        } else {
653
+            throw new OCSBadRequestException('Share not found or token invalid');
654
+        }
655
+    }
656 656
 }
Please login to merge, or discard this patch.
apps/files_sharing/lib/AppInfo/Application.php 3 patches
Unused Use Statements   -1 removed lines patch added patch discarded remove patch
@@ -27,7 +27,6 @@
 block discarded – undo
27 27
 
28 28
 namespace OCA\Files_Sharing\AppInfo;
29 29
 
30
-use OCA\FederatedFileSharing\DiscoveryManager;
31 30
 use OCA\Files_Sharing\Middleware\OCSShareAPIMiddleware;
32 31
 use OCA\Files_Sharing\MountProvider;
33 32
 use OCP\AppFramework\App;
Please login to merge, or discard this patch.
Indentation   +111 added lines, -111 removed lines patch added patch discarded remove patch
@@ -40,127 +40,127 @@
 block discarded – undo
40 40
 use OCP\IServerContainer;
41 41
 
42 42
 class Application extends App {
43
-	public function __construct(array $urlParams = array()) {
44
-		parent::__construct('files_sharing', $urlParams);
43
+    public function __construct(array $urlParams = array()) {
44
+        parent::__construct('files_sharing', $urlParams);
45 45
 
46
-		$container = $this->getContainer();
47
-		/** @var IServerContainer $server */
48
-		$server = $container->getServer();
46
+        $container = $this->getContainer();
47
+        /** @var IServerContainer $server */
48
+        $server = $container->getServer();
49 49
 
50
-		/**
51
-		 * Controllers
52
-		 */
53
-		$container->registerService('ShareController', function (SimpleContainer $c) use ($server) {
54
-			$federatedSharingApp = new \OCA\FederatedFileSharing\AppInfo\Application();
55
-			return new ShareController(
56
-				$c->query('AppName'),
57
-				$c->query('Request'),
58
-				$server->getConfig(),
59
-				$server->getURLGenerator(),
60
-				$server->getUserManager(),
61
-				$server->getLogger(),
62
-				$server->getActivityManager(),
63
-				$server->getShareManager(),
64
-				$server->getSession(),
65
-				$server->getPreviewManager(),
66
-				$server->getRootFolder(),
67
-				$federatedSharingApp->getFederatedShareProvider(),
68
-				$server->getEventDispatcher(),
69
-				$server->getL10N($c->query('AppName')),
70
-				$server->getThemingDefaults()
71
-			);
72
-		});
73
-		$container->registerService('ExternalSharesController', function (SimpleContainer $c) {
74
-			return new ExternalSharesController(
75
-				$c->query('AppName'),
76
-				$c->query('Request'),
77
-				$c->query('ExternalManager'),
78
-				$c->query('HttpClientService')
79
-			);
80
-		});
50
+        /**
51
+         * Controllers
52
+         */
53
+        $container->registerService('ShareController', function (SimpleContainer $c) use ($server) {
54
+            $federatedSharingApp = new \OCA\FederatedFileSharing\AppInfo\Application();
55
+            return new ShareController(
56
+                $c->query('AppName'),
57
+                $c->query('Request'),
58
+                $server->getConfig(),
59
+                $server->getURLGenerator(),
60
+                $server->getUserManager(),
61
+                $server->getLogger(),
62
+                $server->getActivityManager(),
63
+                $server->getShareManager(),
64
+                $server->getSession(),
65
+                $server->getPreviewManager(),
66
+                $server->getRootFolder(),
67
+                $federatedSharingApp->getFederatedShareProvider(),
68
+                $server->getEventDispatcher(),
69
+                $server->getL10N($c->query('AppName')),
70
+                $server->getThemingDefaults()
71
+            );
72
+        });
73
+        $container->registerService('ExternalSharesController', function (SimpleContainer $c) {
74
+            return new ExternalSharesController(
75
+                $c->query('AppName'),
76
+                $c->query('Request'),
77
+                $c->query('ExternalManager'),
78
+                $c->query('HttpClientService')
79
+            );
80
+        });
81 81
 
82
-		/**
83
-		 * Core class wrappers
84
-		 */
85
-		$container->registerService('HttpClientService', function (SimpleContainer $c) use ($server) {
86
-			return $server->getHTTPClientService();
87
-		});
88
-		$container->registerService(ICloudIdManager::class, function (SimpleContainer $c) use ($server) {
89
-			return $server->getCloudIdManager();
90
-		});
91
-		$container->registerService('ExternalManager', function (SimpleContainer $c) use ($server) {
92
-			$user = $server->getUserSession()->getUser();
93
-			$uid = $user ? $user->getUID() : null;
94
-			return new \OCA\Files_Sharing\External\Manager(
95
-				$server->getDatabaseConnection(),
96
-				\OC\Files\Filesystem::getMountManager(),
97
-				\OC\Files\Filesystem::getLoader(),
98
-				$server->getHTTPClientService(),
99
-				$server->getNotificationManager(),
100
-				$server->getOCSDiscoveryService(),
101
-				$uid
102
-			);
103
-		});
104
-		$container->registerAlias('OCA\Files_Sharing\External\Manager', 'ExternalManager');
82
+        /**
83
+         * Core class wrappers
84
+         */
85
+        $container->registerService('HttpClientService', function (SimpleContainer $c) use ($server) {
86
+            return $server->getHTTPClientService();
87
+        });
88
+        $container->registerService(ICloudIdManager::class, function (SimpleContainer $c) use ($server) {
89
+            return $server->getCloudIdManager();
90
+        });
91
+        $container->registerService('ExternalManager', function (SimpleContainer $c) use ($server) {
92
+            $user = $server->getUserSession()->getUser();
93
+            $uid = $user ? $user->getUID() : null;
94
+            return new \OCA\Files_Sharing\External\Manager(
95
+                $server->getDatabaseConnection(),
96
+                \OC\Files\Filesystem::getMountManager(),
97
+                \OC\Files\Filesystem::getLoader(),
98
+                $server->getHTTPClientService(),
99
+                $server->getNotificationManager(),
100
+                $server->getOCSDiscoveryService(),
101
+                $uid
102
+            );
103
+        });
104
+        $container->registerAlias('OCA\Files_Sharing\External\Manager', 'ExternalManager');
105 105
 
106
-		/**
107
-		 * Middleware
108
-		 */
109
-		$container->registerService('SharingCheckMiddleware', function (SimpleContainer $c) use ($server) {
110
-			return new SharingCheckMiddleware(
111
-				$c->query('AppName'),
112
-				$server->getConfig(),
113
-				$server->getAppManager(),
114
-				$c['ControllerMethodReflector'],
115
-				$server->getShareManager(),
116
-				$server->getRequest()
117
-			);
118
-		});
106
+        /**
107
+         * Middleware
108
+         */
109
+        $container->registerService('SharingCheckMiddleware', function (SimpleContainer $c) use ($server) {
110
+            return new SharingCheckMiddleware(
111
+                $c->query('AppName'),
112
+                $server->getConfig(),
113
+                $server->getAppManager(),
114
+                $c['ControllerMethodReflector'],
115
+                $server->getShareManager(),
116
+                $server->getRequest()
117
+            );
118
+        });
119 119
 
120
-		$container->registerService('OCSShareAPIMiddleware', function (SimpleContainer $c) use ($server) {
121
-			return new OCSShareAPIMiddleware(
122
-				$server->getShareManager(),
123
-				$server->getL10N($c->query('AppName'))
124
-			);
125
-		});
120
+        $container->registerService('OCSShareAPIMiddleware', function (SimpleContainer $c) use ($server) {
121
+            return new OCSShareAPIMiddleware(
122
+                $server->getShareManager(),
123
+                $server->getL10N($c->query('AppName'))
124
+            );
125
+        });
126 126
 
127
-		// Execute middlewares
128
-		$container->registerMiddleWare('SharingCheckMiddleware');
129
-		$container->registerMiddleWare('OCSShareAPIMiddleware');
127
+        // Execute middlewares
128
+        $container->registerMiddleWare('SharingCheckMiddleware');
129
+        $container->registerMiddleWare('OCSShareAPIMiddleware');
130 130
 
131
-		$container->registerService('MountProvider', function (IContainer $c) {
132
-			/** @var \OCP\IServerContainer $server */
133
-			$server = $c->query('ServerContainer');
134
-			return new MountProvider(
135
-				$server->getConfig(),
136
-				$server->getShareManager(),
137
-				$server->getLogger()
138
-			);
139
-		});
131
+        $container->registerService('MountProvider', function (IContainer $c) {
132
+            /** @var \OCP\IServerContainer $server */
133
+            $server = $c->query('ServerContainer');
134
+            return new MountProvider(
135
+                $server->getConfig(),
136
+                $server->getShareManager(),
137
+                $server->getLogger()
138
+            );
139
+        });
140 140
 
141
-		$container->registerService('ExternalMountProvider', function (IContainer $c) {
142
-			/** @var \OCP\IServerContainer $server */
143
-			$server = $c->query('ServerContainer');
144
-			return new \OCA\Files_Sharing\External\MountProvider(
145
-				$server->getDatabaseConnection(),
146
-				function() use ($c) {
147
-					return $c->query('ExternalManager');
148
-				},
149
-				$server->getCloudIdManager()
150
-			);
151
-		});
141
+        $container->registerService('ExternalMountProvider', function (IContainer $c) {
142
+            /** @var \OCP\IServerContainer $server */
143
+            $server = $c->query('ServerContainer');
144
+            return new \OCA\Files_Sharing\External\MountProvider(
145
+                $server->getDatabaseConnection(),
146
+                function() use ($c) {
147
+                    return $c->query('ExternalManager');
148
+                },
149
+                $server->getCloudIdManager()
150
+            );
151
+        });
152 152
 
153
-		/*
153
+        /*
154 154
 		 * Register capabilities
155 155
 		 */
156
-		$container->registerCapability('OCA\Files_Sharing\Capabilities');
157
-	}
156
+        $container->registerCapability('OCA\Files_Sharing\Capabilities');
157
+    }
158 158
 
159
-	public function registerMountProviders() {
160
-		/** @var \OCP\IServerContainer $server */
161
-		$server = $this->getContainer()->query('ServerContainer');
162
-		$mountProviderCollection = $server->getMountProviderCollection();
163
-		$mountProviderCollection->registerProvider($this->getContainer()->query('MountProvider'));
164
-		$mountProviderCollection->registerProvider($this->getContainer()->query('ExternalMountProvider'));
165
-	}
159
+    public function registerMountProviders() {
160
+        /** @var \OCP\IServerContainer $server */
161
+        $server = $this->getContainer()->query('ServerContainer');
162
+        $mountProviderCollection = $server->getMountProviderCollection();
163
+        $mountProviderCollection->registerProvider($this->getContainer()->query('MountProvider'));
164
+        $mountProviderCollection->registerProvider($this->getContainer()->query('ExternalMountProvider'));
165
+    }
166 166
 }
Please login to merge, or discard this patch.
Spacing   +9 added lines, -9 removed lines patch added patch discarded remove patch
@@ -50,7 +50,7 @@  discard block
 block discarded – undo
50 50
 		/**
51 51
 		 * Controllers
52 52
 		 */
53
-		$container->registerService('ShareController', function (SimpleContainer $c) use ($server) {
53
+		$container->registerService('ShareController', function(SimpleContainer $c) use ($server) {
54 54
 			$federatedSharingApp = new \OCA\FederatedFileSharing\AppInfo\Application();
55 55
 			return new ShareController(
56 56
 				$c->query('AppName'),
@@ -70,7 +70,7 @@  discard block
 block discarded – undo
70 70
 				$server->getThemingDefaults()
71 71
 			);
72 72
 		});
73
-		$container->registerService('ExternalSharesController', function (SimpleContainer $c) {
73
+		$container->registerService('ExternalSharesController', function(SimpleContainer $c) {
74 74
 			return new ExternalSharesController(
75 75
 				$c->query('AppName'),
76 76
 				$c->query('Request'),
@@ -82,13 +82,13 @@  discard block
 block discarded – undo
82 82
 		/**
83 83
 		 * Core class wrappers
84 84
 		 */
85
-		$container->registerService('HttpClientService', function (SimpleContainer $c) use ($server) {
85
+		$container->registerService('HttpClientService', function(SimpleContainer $c) use ($server) {
86 86
 			return $server->getHTTPClientService();
87 87
 		});
88
-		$container->registerService(ICloudIdManager::class, function (SimpleContainer $c) use ($server) {
88
+		$container->registerService(ICloudIdManager::class, function(SimpleContainer $c) use ($server) {
89 89
 			return $server->getCloudIdManager();
90 90
 		});
91
-		$container->registerService('ExternalManager', function (SimpleContainer $c) use ($server) {
91
+		$container->registerService('ExternalManager', function(SimpleContainer $c) use ($server) {
92 92
 			$user = $server->getUserSession()->getUser();
93 93
 			$uid = $user ? $user->getUID() : null;
94 94
 			return new \OCA\Files_Sharing\External\Manager(
@@ -106,7 +106,7 @@  discard block
 block discarded – undo
106 106
 		/**
107 107
 		 * Middleware
108 108
 		 */
109
-		$container->registerService('SharingCheckMiddleware', function (SimpleContainer $c) use ($server) {
109
+		$container->registerService('SharingCheckMiddleware', function(SimpleContainer $c) use ($server) {
110 110
 			return new SharingCheckMiddleware(
111 111
 				$c->query('AppName'),
112 112
 				$server->getConfig(),
@@ -117,7 +117,7 @@  discard block
 block discarded – undo
117 117
 			);
118 118
 		});
119 119
 
120
-		$container->registerService('OCSShareAPIMiddleware', function (SimpleContainer $c) use ($server) {
120
+		$container->registerService('OCSShareAPIMiddleware', function(SimpleContainer $c) use ($server) {
121 121
 			return new OCSShareAPIMiddleware(
122 122
 				$server->getShareManager(),
123 123
 				$server->getL10N($c->query('AppName'))
@@ -128,7 +128,7 @@  discard block
 block discarded – undo
128 128
 		$container->registerMiddleWare('SharingCheckMiddleware');
129 129
 		$container->registerMiddleWare('OCSShareAPIMiddleware');
130 130
 
131
-		$container->registerService('MountProvider', function (IContainer $c) {
131
+		$container->registerService('MountProvider', function(IContainer $c) {
132 132
 			/** @var \OCP\IServerContainer $server */
133 133
 			$server = $c->query('ServerContainer');
134 134
 			return new MountProvider(
@@ -138,7 +138,7 @@  discard block
 block discarded – undo
138 138
 			);
139 139
 		});
140 140
 
141
-		$container->registerService('ExternalMountProvider', function (IContainer $c) {
141
+		$container->registerService('ExternalMountProvider', function(IContainer $c) {
142 142
 			/** @var \OCP\IServerContainer $server */
143 143
 			$server = $c->query('ServerContainer');
144 144
 			return new \OCA\Files_Sharing\External\MountProvider(
Please login to merge, or discard this patch.
apps/files_sharing/lib/External/Manager.php 3 patches
Unused Use Statements   -1 removed lines patch added patch discarded remove patch
@@ -30,7 +30,6 @@
 block discarded – undo
30 30
 namespace OCA\Files_Sharing\External;
31 31
 
32 32
 use OC\Files\Filesystem;
33
-use OCA\FederatedFileSharing\DiscoveryManager;
34 33
 use OCP\Files;
35 34
 use OCP\Files\Storage\IStorageFactory;
36 35
 use OCP\Http\Client\IClientService;
Please login to merge, or discard this patch.
Indentation   +383 added lines, -383 removed lines patch added patch discarded remove patch
@@ -39,440 +39,440 @@
 block discarded – undo
39 39
 use OCP\OCS\IDiscoveryService;
40 40
 
41 41
 class Manager {
42
-	const STORAGE = '\OCA\Files_Sharing\External\Storage';
43
-
44
-	/**
45
-	 * @var string
46
-	 */
47
-	private $uid;
48
-
49
-	/**
50
-	 * @var IDBConnection
51
-	 */
52
-	private $connection;
53
-
54
-	/**
55
-	 * @var \OC\Files\Mount\Manager
56
-	 */
57
-	private $mountManager;
58
-
59
-	/**
60
-	 * @var IStorageFactory
61
-	 */
62
-	private $storageLoader;
63
-
64
-	/**
65
-	 * @var IClientService
66
-	 */
67
-	private $clientService;
68
-
69
-	/**
70
-	 * @var IManager
71
-	 */
72
-	private $notificationManager;
73
-
74
-	/**
75
-	 * @var IDiscoveryService
76
-	 */
77
-	private $discoveryService;
78
-
79
-	/**
80
-	 * @param IDBConnection $connection
81
-	 * @param \OC\Files\Mount\Manager $mountManager
82
-	 * @param IStorageFactory $storageLoader
83
-	 * @param IClientService $clientService
84
-	 * @param IManager $notificationManager
85
-	 * @param IDiscoveryService $discoveryService
86
-	 * @param string $uid
87
-	 */
88
-	public function __construct(IDBConnection $connection,
89
-								\OC\Files\Mount\Manager $mountManager,
90
-								IStorageFactory $storageLoader,
91
-								IClientService $clientService,
92
-								IManager $notificationManager,
93
-								IDiscoveryService $discoveryService,
94
-								$uid) {
95
-		$this->connection = $connection;
96
-		$this->mountManager = $mountManager;
97
-		$this->storageLoader = $storageLoader;
98
-		$this->clientService = $clientService;
99
-		$this->uid = $uid;
100
-		$this->notificationManager = $notificationManager;
101
-		$this->discoveryService = $discoveryService;
102
-	}
103
-
104
-	/**
105
-	 * add new server-to-server share
106
-	 *
107
-	 * @param string $remote
108
-	 * @param string $token
109
-	 * @param string $password
110
-	 * @param string $name
111
-	 * @param string $owner
112
-	 * @param boolean $accepted
113
-	 * @param string $user
114
-	 * @param int $remoteId
115
-	 * @return Mount|null
116
-	 */
117
-	public function addShare($remote, $token, $password, $name, $owner, $accepted=false, $user = null, $remoteId = -1) {
118
-
119
-		$user = $user ? $user : $this->uid;
120
-		$accepted = $accepted ? 1 : 0;
121
-		$name = Filesystem::normalizePath('/' . $name);
122
-
123
-		if (!$accepted) {
124
-			// To avoid conflicts with the mount point generation later,
125
-			// we only use a temporary mount point name here. The real
126
-			// mount point name will be generated when accepting the share,
127
-			// using the original share item name.
128
-			$tmpMountPointName = '{{TemporaryMountPointName#' . $name . '}}';
129
-			$mountPoint = $tmpMountPointName;
130
-			$hash = md5($tmpMountPointName);
131
-			$data = [
132
-				'remote'		=> $remote,
133
-				'share_token'	=> $token,
134
-				'password'		=> $password,
135
-				'name'			=> $name,
136
-				'owner'			=> $owner,
137
-				'user'			=> $user,
138
-				'mountpoint'	=> $mountPoint,
139
-				'mountpoint_hash'	=> $hash,
140
-				'accepted'		=> $accepted,
141
-				'remote_id'		=> $remoteId,
142
-			];
143
-
144
-			$i = 1;
145
-			while (!$this->connection->insertIfNotExist('*PREFIX*share_external', $data, ['user', 'mountpoint_hash'])) {
146
-				// The external share already exists for the user
147
-				$data['mountpoint'] = $tmpMountPointName . '-' . $i;
148
-				$data['mountpoint_hash'] = md5($data['mountpoint']);
149
-				$i++;
150
-			}
151
-			return null;
152
-		}
153
-
154
-		$mountPoint = Files::buildNotExistingFileName('/', $name);
155
-		$mountPoint = Filesystem::normalizePath('/' . $mountPoint);
156
-		$hash = md5($mountPoint);
157
-
158
-		$query = $this->connection->prepare('
42
+    const STORAGE = '\OCA\Files_Sharing\External\Storage';
43
+
44
+    /**
45
+     * @var string
46
+     */
47
+    private $uid;
48
+
49
+    /**
50
+     * @var IDBConnection
51
+     */
52
+    private $connection;
53
+
54
+    /**
55
+     * @var \OC\Files\Mount\Manager
56
+     */
57
+    private $mountManager;
58
+
59
+    /**
60
+     * @var IStorageFactory
61
+     */
62
+    private $storageLoader;
63
+
64
+    /**
65
+     * @var IClientService
66
+     */
67
+    private $clientService;
68
+
69
+    /**
70
+     * @var IManager
71
+     */
72
+    private $notificationManager;
73
+
74
+    /**
75
+     * @var IDiscoveryService
76
+     */
77
+    private $discoveryService;
78
+
79
+    /**
80
+     * @param IDBConnection $connection
81
+     * @param \OC\Files\Mount\Manager $mountManager
82
+     * @param IStorageFactory $storageLoader
83
+     * @param IClientService $clientService
84
+     * @param IManager $notificationManager
85
+     * @param IDiscoveryService $discoveryService
86
+     * @param string $uid
87
+     */
88
+    public function __construct(IDBConnection $connection,
89
+                                \OC\Files\Mount\Manager $mountManager,
90
+                                IStorageFactory $storageLoader,
91
+                                IClientService $clientService,
92
+                                IManager $notificationManager,
93
+                                IDiscoveryService $discoveryService,
94
+                                $uid) {
95
+        $this->connection = $connection;
96
+        $this->mountManager = $mountManager;
97
+        $this->storageLoader = $storageLoader;
98
+        $this->clientService = $clientService;
99
+        $this->uid = $uid;
100
+        $this->notificationManager = $notificationManager;
101
+        $this->discoveryService = $discoveryService;
102
+    }
103
+
104
+    /**
105
+     * add new server-to-server share
106
+     *
107
+     * @param string $remote
108
+     * @param string $token
109
+     * @param string $password
110
+     * @param string $name
111
+     * @param string $owner
112
+     * @param boolean $accepted
113
+     * @param string $user
114
+     * @param int $remoteId
115
+     * @return Mount|null
116
+     */
117
+    public function addShare($remote, $token, $password, $name, $owner, $accepted=false, $user = null, $remoteId = -1) {
118
+
119
+        $user = $user ? $user : $this->uid;
120
+        $accepted = $accepted ? 1 : 0;
121
+        $name = Filesystem::normalizePath('/' . $name);
122
+
123
+        if (!$accepted) {
124
+            // To avoid conflicts with the mount point generation later,
125
+            // we only use a temporary mount point name here. The real
126
+            // mount point name will be generated when accepting the share,
127
+            // using the original share item name.
128
+            $tmpMountPointName = '{{TemporaryMountPointName#' . $name . '}}';
129
+            $mountPoint = $tmpMountPointName;
130
+            $hash = md5($tmpMountPointName);
131
+            $data = [
132
+                'remote'		=> $remote,
133
+                'share_token'	=> $token,
134
+                'password'		=> $password,
135
+                'name'			=> $name,
136
+                'owner'			=> $owner,
137
+                'user'			=> $user,
138
+                'mountpoint'	=> $mountPoint,
139
+                'mountpoint_hash'	=> $hash,
140
+                'accepted'		=> $accepted,
141
+                'remote_id'		=> $remoteId,
142
+            ];
143
+
144
+            $i = 1;
145
+            while (!$this->connection->insertIfNotExist('*PREFIX*share_external', $data, ['user', 'mountpoint_hash'])) {
146
+                // The external share already exists for the user
147
+                $data['mountpoint'] = $tmpMountPointName . '-' . $i;
148
+                $data['mountpoint_hash'] = md5($data['mountpoint']);
149
+                $i++;
150
+            }
151
+            return null;
152
+        }
153
+
154
+        $mountPoint = Files::buildNotExistingFileName('/', $name);
155
+        $mountPoint = Filesystem::normalizePath('/' . $mountPoint);
156
+        $hash = md5($mountPoint);
157
+
158
+        $query = $this->connection->prepare('
159 159
 				INSERT INTO `*PREFIX*share_external`
160 160
 					(`remote`, `share_token`, `password`, `name`, `owner`, `user`, `mountpoint`, `mountpoint_hash`, `accepted`, `remote_id`)
161 161
 				VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
162 162
 			');
163
-		$query->execute(array($remote, $token, $password, $name, $owner, $user, $mountPoint, $hash, $accepted, $remoteId));
164
-
165
-		$options = array(
166
-			'remote'	=> $remote,
167
-			'token'		=> $token,
168
-			'password'	=> $password,
169
-			'mountpoint'	=> $mountPoint,
170
-			'owner'		=> $owner
171
-		);
172
-		return $this->mountShare($options);
173
-	}
174
-
175
-	/**
176
-	 * get share
177
-	 *
178
-	 * @param int $id share id
179
-	 * @return mixed share of false
180
-	 */
181
-	public function getShare($id) {
182
-		$getShare = $this->connection->prepare('
163
+        $query->execute(array($remote, $token, $password, $name, $owner, $user, $mountPoint, $hash, $accepted, $remoteId));
164
+
165
+        $options = array(
166
+            'remote'	=> $remote,
167
+            'token'		=> $token,
168
+            'password'	=> $password,
169
+            'mountpoint'	=> $mountPoint,
170
+            'owner'		=> $owner
171
+        );
172
+        return $this->mountShare($options);
173
+    }
174
+
175
+    /**
176
+     * get share
177
+     *
178
+     * @param int $id share id
179
+     * @return mixed share of false
180
+     */
181
+    public function getShare($id) {
182
+        $getShare = $this->connection->prepare('
183 183
 			SELECT `id`, `remote`, `remote_id`, `share_token`, `name`, `owner`, `user`, `mountpoint`, `accepted`
184 184
 			FROM  `*PREFIX*share_external`
185 185
 			WHERE `id` = ? AND `user` = ?');
186
-		$result = $getShare->execute(array($id, $this->uid));
186
+        $result = $getShare->execute(array($id, $this->uid));
187 187
 
188
-		return $result ? $getShare->fetch() : false;
189
-	}
188
+        return $result ? $getShare->fetch() : false;
189
+    }
190 190
 
191
-	/**
192
-	 * accept server-to-server share
193
-	 *
194
-	 * @param int $id
195
-	 * @return bool True if the share could be accepted, false otherwise
196
-	 */
197
-	public function acceptShare($id) {
191
+    /**
192
+     * accept server-to-server share
193
+     *
194
+     * @param int $id
195
+     * @return bool True if the share could be accepted, false otherwise
196
+     */
197
+    public function acceptShare($id) {
198 198
 
199
-		$share = $this->getShare($id);
199
+        $share = $this->getShare($id);
200 200
 
201
-		if ($share) {
202
-			$mountPoint = Files::buildNotExistingFileName('/', $share['name']);
203
-			$mountPoint = Filesystem::normalizePath('/' . $mountPoint);
204
-			$hash = md5($mountPoint);
201
+        if ($share) {
202
+            $mountPoint = Files::buildNotExistingFileName('/', $share['name']);
203
+            $mountPoint = Filesystem::normalizePath('/' . $mountPoint);
204
+            $hash = md5($mountPoint);
205 205
 
206
-			$acceptShare = $this->connection->prepare('
206
+            $acceptShare = $this->connection->prepare('
207 207
 				UPDATE `*PREFIX*share_external`
208 208
 				SET `accepted` = ?,
209 209
 					`mountpoint` = ?,
210 210
 					`mountpoint_hash` = ?
211 211
 				WHERE `id` = ? AND `user` = ?');
212
-			$acceptShare->execute(array(1, $mountPoint, $hash, $id, $this->uid));
213
-			$this->sendFeedbackToRemote($share['remote'], $share['share_token'], $share['remote_id'], 'accept');
212
+            $acceptShare->execute(array(1, $mountPoint, $hash, $id, $this->uid));
213
+            $this->sendFeedbackToRemote($share['remote'], $share['share_token'], $share['remote_id'], 'accept');
214 214
 
215
-			\OC_Hook::emit('OCP\Share', 'federated_share_added', ['server' => $share['remote']]);
215
+            \OC_Hook::emit('OCP\Share', 'federated_share_added', ['server' => $share['remote']]);
216 216
 
217
-			$this->processNotification($id);
218
-			return true;
219
-		}
217
+            $this->processNotification($id);
218
+            return true;
219
+        }
220 220
 
221
-		return false;
222
-	}
221
+        return false;
222
+    }
223 223
 
224
-	/**
225
-	 * decline server-to-server share
226
-	 *
227
-	 * @param int $id
228
-	 * @return bool True if the share could be declined, false otherwise
229
-	 */
230
-	public function declineShare($id) {
224
+    /**
225
+     * decline server-to-server share
226
+     *
227
+     * @param int $id
228
+     * @return bool True if the share could be declined, false otherwise
229
+     */
230
+    public function declineShare($id) {
231 231
 
232
-		$share = $this->getShare($id);
232
+        $share = $this->getShare($id);
233 233
 
234
-		if ($share) {
235
-			$removeShare = $this->connection->prepare('
234
+        if ($share) {
235
+            $removeShare = $this->connection->prepare('
236 236
 				DELETE FROM `*PREFIX*share_external` WHERE `id` = ? AND `user` = ?');
237
-			$removeShare->execute(array($id, $this->uid));
238
-			$this->sendFeedbackToRemote($share['remote'], $share['share_token'], $share['remote_id'], 'decline');
239
-
240
-			$this->processNotification($id);
241
-			return true;
242
-		}
243
-
244
-		return false;
245
-	}
246
-
247
-	/**
248
-	 * @param int $remoteShare
249
-	 */
250
-	public function processNotification($remoteShare) {
251
-		$filter = $this->notificationManager->createNotification();
252
-		$filter->setApp('files_sharing')
253
-			->setUser($this->uid)
254
-			->setObject('remote_share', (int) $remoteShare);
255
-		$this->notificationManager->markProcessed($filter);
256
-	}
257
-
258
-	/**
259
-	 * inform remote server whether server-to-server share was accepted/declined
260
-	 *
261
-	 * @param string $remote
262
-	 * @param string $token
263
-	 * @param int $remoteId Share id on the remote host
264
-	 * @param string $feedback
265
-	 * @return boolean
266
-	 */
267
-	private function sendFeedbackToRemote($remote, $token, $remoteId, $feedback) {
268
-
269
-		$federationEndpoints = $this->discoveryService->discover($remote, 'FEDERATED_SHARING');
270
-		$endpoint = isset($federationEndpoints['share']) ? $federationEndpoints['share'] : '/ocs/v2.php/cloud/shares';
271
-
272
-		$url = rtrim($remote, '/') . $endpoint . '/' . $remoteId . '/' . $feedback . '?format=' . \OCP\Share::RESPONSE_FORMAT;
273
-		$fields = array('token' => $token);
274
-
275
-		$client = $this->clientService->newClient();
276
-
277
-		try {
278
-			$response = $client->post(
279
-				$url,
280
-				[
281
-					'body' => $fields,
282
-					'connect_timeout' => 10,
283
-				]
284
-			);
285
-		} catch (\Exception $e) {
286
-			return false;
287
-		}
288
-
289
-		$status = json_decode($response->getBody(), true);
290
-
291
-		return ($status['ocs']['meta']['statuscode'] === 100 || $status['ocs']['meta']['statuscode'] === 200);
292
-	}
293
-
294
-	/**
295
-	 * remove '/user/files' from the path and trailing slashes
296
-	 *
297
-	 * @param string $path
298
-	 * @return string
299
-	 */
300
-	protected function stripPath($path) {
301
-		$prefix = '/' . $this->uid . '/files';
302
-		return rtrim(substr($path, strlen($prefix)), '/');
303
-	}
304
-
305
-	public function getMount($data) {
306
-		$data['manager'] = $this;
307
-		$mountPoint = '/' . $this->uid . '/files' . $data['mountpoint'];
308
-		$data['mountpoint'] = $mountPoint;
309
-		$data['certificateManager'] = \OC::$server->getCertificateManager($this->uid);
310
-		return new Mount(self::STORAGE, $mountPoint, $data, $this, $this->storageLoader);
311
-	}
312
-
313
-	/**
314
-	 * @param array $data
315
-	 * @return Mount
316
-	 */
317
-	protected function mountShare($data) {
318
-		$mount = $this->getMount($data);
319
-		$this->mountManager->addMount($mount);
320
-		return $mount;
321
-	}
322
-
323
-	/**
324
-	 * @return \OC\Files\Mount\Manager
325
-	 */
326
-	public function getMountManager() {
327
-		return $this->mountManager;
328
-	}
329
-
330
-	/**
331
-	 * @param string $source
332
-	 * @param string $target
333
-	 * @return bool
334
-	 */
335
-	public function setMountPoint($source, $target) {
336
-		$source = $this->stripPath($source);
337
-		$target = $this->stripPath($target);
338
-		$sourceHash = md5($source);
339
-		$targetHash = md5($target);
340
-
341
-		$query = $this->connection->prepare('
237
+            $removeShare->execute(array($id, $this->uid));
238
+            $this->sendFeedbackToRemote($share['remote'], $share['share_token'], $share['remote_id'], 'decline');
239
+
240
+            $this->processNotification($id);
241
+            return true;
242
+        }
243
+
244
+        return false;
245
+    }
246
+
247
+    /**
248
+     * @param int $remoteShare
249
+     */
250
+    public function processNotification($remoteShare) {
251
+        $filter = $this->notificationManager->createNotification();
252
+        $filter->setApp('files_sharing')
253
+            ->setUser($this->uid)
254
+            ->setObject('remote_share', (int) $remoteShare);
255
+        $this->notificationManager->markProcessed($filter);
256
+    }
257
+
258
+    /**
259
+     * inform remote server whether server-to-server share was accepted/declined
260
+     *
261
+     * @param string $remote
262
+     * @param string $token
263
+     * @param int $remoteId Share id on the remote host
264
+     * @param string $feedback
265
+     * @return boolean
266
+     */
267
+    private function sendFeedbackToRemote($remote, $token, $remoteId, $feedback) {
268
+
269
+        $federationEndpoints = $this->discoveryService->discover($remote, 'FEDERATED_SHARING');
270
+        $endpoint = isset($federationEndpoints['share']) ? $federationEndpoints['share'] : '/ocs/v2.php/cloud/shares';
271
+
272
+        $url = rtrim($remote, '/') . $endpoint . '/' . $remoteId . '/' . $feedback . '?format=' . \OCP\Share::RESPONSE_FORMAT;
273
+        $fields = array('token' => $token);
274
+
275
+        $client = $this->clientService->newClient();
276
+
277
+        try {
278
+            $response = $client->post(
279
+                $url,
280
+                [
281
+                    'body' => $fields,
282
+                    'connect_timeout' => 10,
283
+                ]
284
+            );
285
+        } catch (\Exception $e) {
286
+            return false;
287
+        }
288
+
289
+        $status = json_decode($response->getBody(), true);
290
+
291
+        return ($status['ocs']['meta']['statuscode'] === 100 || $status['ocs']['meta']['statuscode'] === 200);
292
+    }
293
+
294
+    /**
295
+     * remove '/user/files' from the path and trailing slashes
296
+     *
297
+     * @param string $path
298
+     * @return string
299
+     */
300
+    protected function stripPath($path) {
301
+        $prefix = '/' . $this->uid . '/files';
302
+        return rtrim(substr($path, strlen($prefix)), '/');
303
+    }
304
+
305
+    public function getMount($data) {
306
+        $data['manager'] = $this;
307
+        $mountPoint = '/' . $this->uid . '/files' . $data['mountpoint'];
308
+        $data['mountpoint'] = $mountPoint;
309
+        $data['certificateManager'] = \OC::$server->getCertificateManager($this->uid);
310
+        return new Mount(self::STORAGE, $mountPoint, $data, $this, $this->storageLoader);
311
+    }
312
+
313
+    /**
314
+     * @param array $data
315
+     * @return Mount
316
+     */
317
+    protected function mountShare($data) {
318
+        $mount = $this->getMount($data);
319
+        $this->mountManager->addMount($mount);
320
+        return $mount;
321
+    }
322
+
323
+    /**
324
+     * @return \OC\Files\Mount\Manager
325
+     */
326
+    public function getMountManager() {
327
+        return $this->mountManager;
328
+    }
329
+
330
+    /**
331
+     * @param string $source
332
+     * @param string $target
333
+     * @return bool
334
+     */
335
+    public function setMountPoint($source, $target) {
336
+        $source = $this->stripPath($source);
337
+        $target = $this->stripPath($target);
338
+        $sourceHash = md5($source);
339
+        $targetHash = md5($target);
340
+
341
+        $query = $this->connection->prepare('
342 342
 			UPDATE `*PREFIX*share_external`
343 343
 			SET `mountpoint` = ?, `mountpoint_hash` = ?
344 344
 			WHERE `mountpoint_hash` = ?
345 345
 			AND `user` = ?
346 346
 		');
347
-		$result = (bool)$query->execute(array($target, $targetHash, $sourceHash, $this->uid));
347
+        $result = (bool)$query->execute(array($target, $targetHash, $sourceHash, $this->uid));
348 348
 
349
-		return $result;
350
-	}
349
+        return $result;
350
+    }
351 351
 
352
-	public function removeShare($mountPoint) {
352
+    public function removeShare($mountPoint) {
353 353
 
354
-		$mountPointObj = $this->mountManager->find($mountPoint);
355
-		$id = $mountPointObj->getStorage()->getCache()->getId('');
354
+        $mountPointObj = $this->mountManager->find($mountPoint);
355
+        $id = $mountPointObj->getStorage()->getCache()->getId('');
356 356
 
357
-		$mountPoint = $this->stripPath($mountPoint);
358
-		$hash = md5($mountPoint);
357
+        $mountPoint = $this->stripPath($mountPoint);
358
+        $hash = md5($mountPoint);
359 359
 
360
-		$getShare = $this->connection->prepare('
360
+        $getShare = $this->connection->prepare('
361 361
 			SELECT `remote`, `share_token`, `remote_id`
362 362
 			FROM  `*PREFIX*share_external`
363 363
 			WHERE `mountpoint_hash` = ? AND `user` = ?');
364
-		$result = $getShare->execute(array($hash, $this->uid));
364
+        $result = $getShare->execute(array($hash, $this->uid));
365 365
 
366
-		if ($result) {
367
-			$share = $getShare->fetch();
368
-			$this->sendFeedbackToRemote($share['remote'], $share['share_token'], $share['remote_id'], 'decline');
369
-		}
370
-		$getShare->closeCursor();
366
+        if ($result) {
367
+            $share = $getShare->fetch();
368
+            $this->sendFeedbackToRemote($share['remote'], $share['share_token'], $share['remote_id'], 'decline');
369
+        }
370
+        $getShare->closeCursor();
371 371
 
372
-		$query = $this->connection->prepare('
372
+        $query = $this->connection->prepare('
373 373
 			DELETE FROM `*PREFIX*share_external`
374 374
 			WHERE `mountpoint_hash` = ?
375 375
 			AND `user` = ?
376 376
 		');
377
-		$result = (bool)$query->execute(array($hash, $this->uid));
378
-
379
-		if($result) {
380
-			$this->removeReShares($id);
381
-		}
382
-
383
-		return $result;
384
-	}
385
-
386
-	/**
387
-	 * remove re-shares from share table and mapping in the federated_reshares table
388
-	 *
389
-	 * @param $mountPointId
390
-	 */
391
-	protected function removeReShares($mountPointId) {
392
-		$selectQuery = $this->connection->getQueryBuilder();
393
-		$query = $this->connection->getQueryBuilder();
394
-		$selectQuery->select('id')->from('share')
395
-			->where($selectQuery->expr()->eq('file_source', $query->createNamedParameter($mountPointId)));
396
-		$select = $selectQuery->getSQL();
397
-
398
-
399
-		$query->delete('federated_reshares')
400
-			->where($query->expr()->in('share_id', $query->createFunction('(' . $select . ')')));
401
-		$query->execute();
402
-
403
-		$deleteReShares = $this->connection->getQueryBuilder();
404
-		$deleteReShares->delete('share')
405
-			->where($deleteReShares->expr()->eq('file_source', $deleteReShares->createNamedParameter($mountPointId)));
406
-		$deleteReShares->execute();
407
-	}
408
-
409
-	/**
410
-	 * remove all shares for user $uid if the user was deleted
411
-	 *
412
-	 * @param string $uid
413
-	 * @return bool
414
-	 */
415
-	public function removeUserShares($uid) {
416
-		$getShare = $this->connection->prepare('
377
+        $result = (bool)$query->execute(array($hash, $this->uid));
378
+
379
+        if($result) {
380
+            $this->removeReShares($id);
381
+        }
382
+
383
+        return $result;
384
+    }
385
+
386
+    /**
387
+     * remove re-shares from share table and mapping in the federated_reshares table
388
+     *
389
+     * @param $mountPointId
390
+     */
391
+    protected function removeReShares($mountPointId) {
392
+        $selectQuery = $this->connection->getQueryBuilder();
393
+        $query = $this->connection->getQueryBuilder();
394
+        $selectQuery->select('id')->from('share')
395
+            ->where($selectQuery->expr()->eq('file_source', $query->createNamedParameter($mountPointId)));
396
+        $select = $selectQuery->getSQL();
397
+
398
+
399
+        $query->delete('federated_reshares')
400
+            ->where($query->expr()->in('share_id', $query->createFunction('(' . $select . ')')));
401
+        $query->execute();
402
+
403
+        $deleteReShares = $this->connection->getQueryBuilder();
404
+        $deleteReShares->delete('share')
405
+            ->where($deleteReShares->expr()->eq('file_source', $deleteReShares->createNamedParameter($mountPointId)));
406
+        $deleteReShares->execute();
407
+    }
408
+
409
+    /**
410
+     * remove all shares for user $uid if the user was deleted
411
+     *
412
+     * @param string $uid
413
+     * @return bool
414
+     */
415
+    public function removeUserShares($uid) {
416
+        $getShare = $this->connection->prepare('
417 417
 			SELECT `remote`, `share_token`, `remote_id`
418 418
 			FROM  `*PREFIX*share_external`
419 419
 			WHERE `user` = ?');
420
-		$result = $getShare->execute(array($uid));
420
+        $result = $getShare->execute(array($uid));
421 421
 
422
-		if ($result) {
423
-			$shares = $getShare->fetchAll();
424
-			foreach($shares as $share) {
425
-				$this->sendFeedbackToRemote($share['remote'], $share['share_token'], $share['remote_id'], 'decline');
426
-			}
427
-		}
422
+        if ($result) {
423
+            $shares = $getShare->fetchAll();
424
+            foreach($shares as $share) {
425
+                $this->sendFeedbackToRemote($share['remote'], $share['share_token'], $share['remote_id'], 'decline');
426
+            }
427
+        }
428 428
 
429
-		$query = $this->connection->prepare('
429
+        $query = $this->connection->prepare('
430 430
 			DELETE FROM `*PREFIX*share_external`
431 431
 			WHERE `user` = ?
432 432
 		');
433
-		return (bool)$query->execute(array($uid));
434
-	}
435
-
436
-	/**
437
-	 * return a list of shares which are not yet accepted by the user
438
-	 *
439
-	 * @return array list of open server-to-server shares
440
-	 */
441
-	public function getOpenShares() {
442
-		return $this->getShares(false);
443
-	}
444
-
445
-	/**
446
-	 * return a list of shares which are accepted by the user
447
-	 *
448
-	 * @return array list of accepted server-to-server shares
449
-	 */
450
-	public function getAcceptedShares() {
451
-		return $this->getShares(true);
452
-	}
453
-
454
-	/**
455
-	 * return a list of shares for the user
456
-	 *
457
-	 * @param bool|null $accepted True for accepted only,
458
-	 *                            false for not accepted,
459
-	 *                            null for all shares of the user
460
-	 * @return array list of open server-to-server shares
461
-	 */
462
-	private function getShares($accepted) {
463
-		$query = 'SELECT `id`, `remote`, `remote_id`, `share_token`, `name`, `owner`, `user`, `mountpoint`, `accepted`
433
+        return (bool)$query->execute(array($uid));
434
+    }
435
+
436
+    /**
437
+     * return a list of shares which are not yet accepted by the user
438
+     *
439
+     * @return array list of open server-to-server shares
440
+     */
441
+    public function getOpenShares() {
442
+        return $this->getShares(false);
443
+    }
444
+
445
+    /**
446
+     * return a list of shares which are accepted by the user
447
+     *
448
+     * @return array list of accepted server-to-server shares
449
+     */
450
+    public function getAcceptedShares() {
451
+        return $this->getShares(true);
452
+    }
453
+
454
+    /**
455
+     * return a list of shares for the user
456
+     *
457
+     * @param bool|null $accepted True for accepted only,
458
+     *                            false for not accepted,
459
+     *                            null for all shares of the user
460
+     * @return array list of open server-to-server shares
461
+     */
462
+    private function getShares($accepted) {
463
+        $query = 'SELECT `id`, `remote`, `remote_id`, `share_token`, `name`, `owner`, `user`, `mountpoint`, `accepted`
464 464
 		          FROM `*PREFIX*share_external` 
465 465
 				  WHERE `user` = ?';
466
-		$parameters = [$this->uid];
467
-		if (!is_null($accepted)) {
468
-			$query .= ' AND `accepted` = ?';
469
-			$parameters[] = (int) $accepted;
470
-		}
471
-		$query .= ' ORDER BY `id` ASC';
472
-
473
-		$shares = $this->connection->prepare($query);
474
-		$result = $shares->execute($parameters);
475
-
476
-		return $result ? $shares->fetchAll() : [];
477
-	}
466
+        $parameters = [$this->uid];
467
+        if (!is_null($accepted)) {
468
+            $query .= ' AND `accepted` = ?';
469
+            $parameters[] = (int) $accepted;
470
+        }
471
+        $query .= ' ORDER BY `id` ASC';
472
+
473
+        $shares = $this->connection->prepare($query);
474
+        $result = $shares->execute($parameters);
475
+
476
+        return $result ? $shares->fetchAll() : [];
477
+    }
478 478
 }
Please login to merge, or discard this patch.
Spacing   +15 added lines, -15 removed lines patch added patch discarded remove patch
@@ -114,18 +114,18 @@  discard block
 block discarded – undo
114 114
 	 * @param int $remoteId
115 115
 	 * @return Mount|null
116 116
 	 */
117
-	public function addShare($remote, $token, $password, $name, $owner, $accepted=false, $user = null, $remoteId = -1) {
117
+	public function addShare($remote, $token, $password, $name, $owner, $accepted = false, $user = null, $remoteId = -1) {
118 118
 
119 119
 		$user = $user ? $user : $this->uid;
120 120
 		$accepted = $accepted ? 1 : 0;
121
-		$name = Filesystem::normalizePath('/' . $name);
121
+		$name = Filesystem::normalizePath('/'.$name);
122 122
 
123 123
 		if (!$accepted) {
124 124
 			// To avoid conflicts with the mount point generation later,
125 125
 			// we only use a temporary mount point name here. The real
126 126
 			// mount point name will be generated when accepting the share,
127 127
 			// using the original share item name.
128
-			$tmpMountPointName = '{{TemporaryMountPointName#' . $name . '}}';
128
+			$tmpMountPointName = '{{TemporaryMountPointName#'.$name.'}}';
129 129
 			$mountPoint = $tmpMountPointName;
130 130
 			$hash = md5($tmpMountPointName);
131 131
 			$data = [
@@ -144,7 +144,7 @@  discard block
 block discarded – undo
144 144
 			$i = 1;
145 145
 			while (!$this->connection->insertIfNotExist('*PREFIX*share_external', $data, ['user', 'mountpoint_hash'])) {
146 146
 				// The external share already exists for the user
147
-				$data['mountpoint'] = $tmpMountPointName . '-' . $i;
147
+				$data['mountpoint'] = $tmpMountPointName.'-'.$i;
148 148
 				$data['mountpoint_hash'] = md5($data['mountpoint']);
149 149
 				$i++;
150 150
 			}
@@ -152,7 +152,7 @@  discard block
 block discarded – undo
152 152
 		}
153 153
 
154 154
 		$mountPoint = Files::buildNotExistingFileName('/', $name);
155
-		$mountPoint = Filesystem::normalizePath('/' . $mountPoint);
155
+		$mountPoint = Filesystem::normalizePath('/'.$mountPoint);
156 156
 		$hash = md5($mountPoint);
157 157
 
158 158
 		$query = $this->connection->prepare('
@@ -200,7 +200,7 @@  discard block
 block discarded – undo
200 200
 
201 201
 		if ($share) {
202 202
 			$mountPoint = Files::buildNotExistingFileName('/', $share['name']);
203
-			$mountPoint = Filesystem::normalizePath('/' . $mountPoint);
203
+			$mountPoint = Filesystem::normalizePath('/'.$mountPoint);
204 204
 			$hash = md5($mountPoint);
205 205
 
206 206
 			$acceptShare = $this->connection->prepare('
@@ -269,7 +269,7 @@  discard block
 block discarded – undo
269 269
 		$federationEndpoints = $this->discoveryService->discover($remote, 'FEDERATED_SHARING');
270 270
 		$endpoint = isset($federationEndpoints['share']) ? $federationEndpoints['share'] : '/ocs/v2.php/cloud/shares';
271 271
 
272
-		$url = rtrim($remote, '/') . $endpoint . '/' . $remoteId . '/' . $feedback . '?format=' . \OCP\Share::RESPONSE_FORMAT;
272
+		$url = rtrim($remote, '/').$endpoint.'/'.$remoteId.'/'.$feedback.'?format='.\OCP\Share::RESPONSE_FORMAT;
273 273
 		$fields = array('token' => $token);
274 274
 
275 275
 		$client = $this->clientService->newClient();
@@ -298,13 +298,13 @@  discard block
 block discarded – undo
298 298
 	 * @return string
299 299
 	 */
300 300
 	protected function stripPath($path) {
301
-		$prefix = '/' . $this->uid . '/files';
301
+		$prefix = '/'.$this->uid.'/files';
302 302
 		return rtrim(substr($path, strlen($prefix)), '/');
303 303
 	}
304 304
 
305 305
 	public function getMount($data) {
306 306
 		$data['manager'] = $this;
307
-		$mountPoint = '/' . $this->uid . '/files' . $data['mountpoint'];
307
+		$mountPoint = '/'.$this->uid.'/files'.$data['mountpoint'];
308 308
 		$data['mountpoint'] = $mountPoint;
309 309
 		$data['certificateManager'] = \OC::$server->getCertificateManager($this->uid);
310 310
 		return new Mount(self::STORAGE, $mountPoint, $data, $this, $this->storageLoader);
@@ -344,7 +344,7 @@  discard block
 block discarded – undo
344 344
 			WHERE `mountpoint_hash` = ?
345 345
 			AND `user` = ?
346 346
 		');
347
-		$result = (bool)$query->execute(array($target, $targetHash, $sourceHash, $this->uid));
347
+		$result = (bool) $query->execute(array($target, $targetHash, $sourceHash, $this->uid));
348 348
 
349 349
 		return $result;
350 350
 	}
@@ -374,9 +374,9 @@  discard block
 block discarded – undo
374 374
 			WHERE `mountpoint_hash` = ?
375 375
 			AND `user` = ?
376 376
 		');
377
-		$result = (bool)$query->execute(array($hash, $this->uid));
377
+		$result = (bool) $query->execute(array($hash, $this->uid));
378 378
 
379
-		if($result) {
379
+		if ($result) {
380 380
 			$this->removeReShares($id);
381 381
 		}
382 382
 
@@ -397,7 +397,7 @@  discard block
 block discarded – undo
397 397
 
398 398
 
399 399
 		$query->delete('federated_reshares')
400
-			->where($query->expr()->in('share_id', $query->createFunction('(' . $select . ')')));
400
+			->where($query->expr()->in('share_id', $query->createFunction('('.$select.')')));
401 401
 		$query->execute();
402 402
 
403 403
 		$deleteReShares = $this->connection->getQueryBuilder();
@@ -421,7 +421,7 @@  discard block
 block discarded – undo
421 421
 
422 422
 		if ($result) {
423 423
 			$shares = $getShare->fetchAll();
424
-			foreach($shares as $share) {
424
+			foreach ($shares as $share) {
425 425
 				$this->sendFeedbackToRemote($share['remote'], $share['share_token'], $share['remote_id'], 'decline');
426 426
 			}
427 427
 		}
@@ -430,7 +430,7 @@  discard block
 block discarded – undo
430 430
 			DELETE FROM `*PREFIX*share_external`
431 431
 			WHERE `user` = ?
432 432
 		');
433
-		return (bool)$query->execute(array($uid));
433
+		return (bool) $query->execute(array($uid));
434 434
 	}
435 435
 
436 436
 	/**
Please login to merge, or discard this patch.
apps/files_sharing/lib/External/Storage.php 3 patches
Unused Use Statements   -1 removed lines patch added patch discarded remove patch
@@ -32,7 +32,6 @@
 block discarded – undo
32 32
 use GuzzleHttp\Exception\ConnectException;
33 33
 use OC\Files\Storage\DAV;
34 34
 use OC\ForbiddenException;
35
-use OCA\FederatedFileSharing\DiscoveryManager;
36 35
 use OCA\Files_Sharing\ISharedStorage;
37 36
 use OCP\AppFramework\Http;
38 37
 use OCP\Federation\ICloudId;
Please login to merge, or discard this patch.
Indentation   +323 added lines, -323 removed lines patch added patch discarded remove patch
@@ -41,328 +41,328 @@
 block discarded – undo
41 41
 use OCP\Files\StorageNotAvailableException;
42 42
 
43 43
 class Storage extends DAV implements ISharedStorage {
44
-	/** @var ICloudId */
45
-	private $cloudId;
46
-	/** @var string */
47
-	private $mountPoint;
48
-	/** @var string */
49
-	private $token;
50
-	/** @var \OCP\ICacheFactory */
51
-	private $memcacheFactory;
52
-	/** @var \OCP\Http\Client\IClientService */
53
-	private $httpClient;
54
-	/** @var bool */
55
-	private $updateChecked = false;
56
-
57
-	/**
58
-	 * @var \OCA\Files_Sharing\External\Manager
59
-	 */
60
-	private $manager;
61
-
62
-	public function __construct($options) {
63
-		$this->memcacheFactory = \OC::$server->getMemCacheFactory();
64
-		$this->httpClient = $options['HttpClientService'];
65
-
66
-		$this->manager = $options['manager'];
67
-		$this->cloudId = $options['cloudId'];
68
-		$discoveryService = \OC::$server->getOCSDiscoveryService();
69
-
70
-		list($protocol, $remote) = explode('://', $this->cloudId->getRemote());
71
-		if (strpos($remote, '/')) {
72
-			list($host, $root) = explode('/', $remote, 2);
73
-		} else {
74
-			$host = $remote;
75
-			$root = '';
76
-		}
77
-		$secure = $protocol === 'https';
78
-		$federatedSharingEndpoints = $discoveryService->discover($this->cloudId->getRemote(), 'FEDERATED_SHARING');
79
-		$webDavEndpoint = isset($federatedSharingEndpoints['webdav']) ? $federatedSharingEndpoints['webdav'] : '/public.php/webdav';
80
-		$root = rtrim($root, '/') . $webDavEndpoint;
81
-		$this->mountPoint = $options['mountpoint'];
82
-		$this->token = $options['token'];
83
-
84
-		parent::__construct(array(
85
-			'secure' => $secure,
86
-			'host' => $host,
87
-			'root' => $root,
88
-			'user' => $options['token'],
89
-			'password' => (string)$options['password']
90
-		));
91
-	}
92
-
93
-	public function getWatcher($path = '', $storage = null) {
94
-		if (!$storage) {
95
-			$storage = $this;
96
-		}
97
-		if (!isset($this->watcher)) {
98
-			$this->watcher = new Watcher($storage);
99
-			$this->watcher->setPolicy(\OC\Files\Cache\Watcher::CHECK_ONCE);
100
-		}
101
-		return $this->watcher;
102
-	}
103
-
104
-	public function getRemoteUser() {
105
-		return $this->cloudId->getUser();
106
-	}
107
-
108
-	public function getRemote() {
109
-		return $this->cloudId->getRemote();
110
-	}
111
-
112
-	public function getMountPoint() {
113
-		return $this->mountPoint;
114
-	}
115
-
116
-	public function getToken() {
117
-		return $this->token;
118
-	}
119
-
120
-	public function getPassword() {
121
-		return $this->password;
122
-	}
123
-
124
-	/**
125
-	 * @brief get id of the mount point
126
-	 * @return string
127
-	 */
128
-	public function getId() {
129
-		return 'shared::' . md5($this->token . '@' . $this->getRemote());
130
-	}
131
-
132
-	public function getCache($path = '', $storage = null) {
133
-		if (is_null($this->cache)) {
134
-			$this->cache = new Cache($this, $this->cloudId);
135
-		}
136
-		return $this->cache;
137
-	}
138
-
139
-	/**
140
-	 * @param string $path
141
-	 * @param \OC\Files\Storage\Storage $storage
142
-	 * @return \OCA\Files_Sharing\External\Scanner
143
-	 */
144
-	public function getScanner($path = '', $storage = null) {
145
-		if (!$storage) {
146
-			$storage = $this;
147
-		}
148
-		if (!isset($this->scanner)) {
149
-			$this->scanner = new Scanner($storage);
150
-		}
151
-		return $this->scanner;
152
-	}
153
-
154
-	/**
155
-	 * check if a file or folder has been updated since $time
156
-	 *
157
-	 * @param string $path
158
-	 * @param int $time
159
-	 * @throws \OCP\Files\StorageNotAvailableException
160
-	 * @throws \OCP\Files\StorageInvalidException
161
-	 * @return bool
162
-	 */
163
-	public function hasUpdated($path, $time) {
164
-		// since for owncloud webdav servers we can rely on etag propagation we only need to check the root of the storage
165
-		// because of that we only do one check for the entire storage per request
166
-		if ($this->updateChecked) {
167
-			return false;
168
-		}
169
-		$this->updateChecked = true;
170
-		try {
171
-			return parent::hasUpdated('', $time);
172
-		} catch (StorageInvalidException $e) {
173
-			// check if it needs to be removed
174
-			$this->checkStorageAvailability();
175
-			throw $e;
176
-		} catch (StorageNotAvailableException $e) {
177
-			// check if it needs to be removed or just temp unavailable
178
-			$this->checkStorageAvailability();
179
-			throw $e;
180
-		}
181
-	}
182
-
183
-	public function test() {
184
-		try {
185
-			return parent::test();
186
-		} catch (StorageInvalidException $e) {
187
-			// check if it needs to be removed
188
-			$this->checkStorageAvailability();
189
-			throw $e;
190
-		} catch (StorageNotAvailableException $e) {
191
-			// check if it needs to be removed or just temp unavailable
192
-			$this->checkStorageAvailability();
193
-			throw $e;
194
-		}
195
-	}
196
-
197
-	/**
198
-	 * Check whether this storage is permanently or temporarily
199
-	 * unavailable
200
-	 *
201
-	 * @throws \OCP\Files\StorageNotAvailableException
202
-	 * @throws \OCP\Files\StorageInvalidException
203
-	 */
204
-	public function checkStorageAvailability() {
205
-		// see if we can find out why the share is unavailable
206
-		try {
207
-			$this->getShareInfo();
208
-		} catch (NotFoundException $e) {
209
-			// a 404 can either mean that the share no longer exists or there is no ownCloud on the remote
210
-			if ($this->testRemote()) {
211
-				// valid ownCloud instance means that the public share no longer exists
212
-				// since this is permanent (re-sharing the file will create a new token)
213
-				// we remove the invalid storage
214
-				$this->manager->removeShare($this->mountPoint);
215
-				$this->manager->getMountManager()->removeMount($this->mountPoint);
216
-				throw new StorageInvalidException();
217
-			} else {
218
-				// ownCloud instance is gone, likely to be a temporary server configuration error
219
-				throw new StorageNotAvailableException();
220
-			}
221
-		} catch (ForbiddenException $e) {
222
-			// auth error, remove share for now (provide a dialog in the future)
223
-			$this->manager->removeShare($this->mountPoint);
224
-			$this->manager->getMountManager()->removeMount($this->mountPoint);
225
-			throw new StorageInvalidException();
226
-		} catch (\GuzzleHttp\Exception\ConnectException $e) {
227
-			throw new StorageNotAvailableException();
228
-		} catch (\GuzzleHttp\Exception\RequestException $e) {
229
-			throw new StorageNotAvailableException();
230
-		} catch (\Exception $e) {
231
-			throw $e;
232
-		}
233
-	}
234
-
235
-	public function file_exists($path) {
236
-		if ($path === '') {
237
-			return true;
238
-		} else {
239
-			return parent::file_exists($path);
240
-		}
241
-	}
242
-
243
-	/**
244
-	 * check if the configured remote is a valid federated share provider
245
-	 *
246
-	 * @return bool
247
-	 */
248
-	protected function testRemote() {
249
-		try {
250
-			return $this->testRemoteUrl($this->getRemote() . '/ocs-provider/index.php')
251
-				|| $this->testRemoteUrl($this->getRemote() . '/ocs-provider/')
252
-				|| $this->testRemoteUrl($this->getRemote() . '/status.php');
253
-		} catch (\Exception $e) {
254
-			return false;
255
-		}
256
-	}
257
-
258
-	/**
259
-	 * @param string $url
260
-	 * @return bool
261
-	 */
262
-	private function testRemoteUrl($url) {
263
-		$cache = $this->memcacheFactory->create('files_sharing_remote_url');
264
-		if($cache->hasKey($url)) {
265
-			return (bool)$cache->get($url);
266
-		}
267
-
268
-		$client = $this->httpClient->newClient();
269
-		try {
270
-			$result = $client->get($url, [
271
-				'timeout' => 10,
272
-				'connect_timeout' => 10,
273
-			])->getBody();
274
-			$data = json_decode($result);
275
-			$returnValue = (is_object($data) && !empty($data->version));
276
-		} catch (ConnectException $e) {
277
-			$returnValue = false;
278
-		} catch (ClientException $e) {
279
-			$returnValue = false;
280
-		}
281
-
282
-		$cache->set($url, $returnValue);
283
-		return $returnValue;
284
-	}
285
-
286
-	/**
287
-	 * Whether the remote is an ownCloud, used since some sharing features are not
288
-	 * standardized. Let's use this to detect whether to use it.
289
-	 *
290
-	 * @return bool
291
-	 */
292
-	public function remoteIsOwnCloud() {
293
-		if(defined('PHPUNIT_RUN') || !$this->testRemoteUrl($this->getRemote() . '/status.php')) {
294
-			return false;
295
-		}
296
-		return true;
297
-	}
298
-
299
-	/**
300
-	 * @return mixed
301
-	 * @throws ForbiddenException
302
-	 * @throws NotFoundException
303
-	 * @throws \Exception
304
-	 */
305
-	public function getShareInfo() {
306
-		$remote = $this->getRemote();
307
-		$token = $this->getToken();
308
-		$password = $this->getPassword();
309
-
310
-		// If remote is not an ownCloud do not try to get any share info
311
-		if(!$this->remoteIsOwnCloud()) {
312
-			return ['status' => 'unsupported'];
313
-		}
314
-
315
-		$url = rtrim($remote, '/') . '/index.php/apps/files_sharing/shareinfo?t=' . $token;
316
-
317
-		// TODO: DI
318
-		$client = \OC::$server->getHTTPClientService()->newClient();
319
-		try {
320
-			$response = $client->post($url, [
321
-				'body' => ['password' => $password],
322
-				'timeout' => 10,
323
-				'connect_timeout' => 10,
324
-			]);
325
-		} catch (\GuzzleHttp\Exception\RequestException $e) {
326
-			if ($e->getCode() === Http::STATUS_UNAUTHORIZED || $e->getCode() === Http::STATUS_FORBIDDEN) {
327
-				throw new ForbiddenException();
328
-			}
329
-			if ($e->getCode() === Http::STATUS_NOT_FOUND) {
330
-				throw new NotFoundException();
331
-			}
332
-			// throw this to be on the safe side: the share will still be visible
333
-			// in the UI in case the failure is intermittent, and the user will
334
-			// be able to decide whether to remove it if it's really gone
335
-			throw new StorageNotAvailableException();
336
-		}
337
-
338
-		return json_decode($response->getBody(), true);
339
-	}
340
-
341
-	public function getOwner($path) {
342
-		return $this->cloudId->getDisplayId();
343
-	}
344
-
345
-	public function isSharable($path) {
346
-		if (\OCP\Util::isSharingDisabledForUser() || !\OC\Share\Share::isResharingAllowed()) {
347
-			return false;
348
-		}
349
-		return ($this->getPermissions($path) & \OCP\Constants::PERMISSION_SHARE);
350
-	}
351
-
352
-	public function getPermissions($path) {
353
-		$response = $this->propfind($path);
354
-		if (isset($response['{http://open-collaboration-services.org/ns}share-permissions'])) {
355
-			$permissions = $response['{http://open-collaboration-services.org/ns}share-permissions'];
356
-		} else {
357
-			// use default permission if remote server doesn't provide the share permissions
358
-			if ($this->is_dir($path)) {
359
-				$permissions = \OCP\Constants::PERMISSION_ALL;
360
-			} else {
361
-				$permissions = \OCP\Constants::PERMISSION_ALL & ~\OCP\Constants::PERMISSION_CREATE;
362
-			}
363
-		}
364
-
365
-		return $permissions;
366
-	}
44
+    /** @var ICloudId */
45
+    private $cloudId;
46
+    /** @var string */
47
+    private $mountPoint;
48
+    /** @var string */
49
+    private $token;
50
+    /** @var \OCP\ICacheFactory */
51
+    private $memcacheFactory;
52
+    /** @var \OCP\Http\Client\IClientService */
53
+    private $httpClient;
54
+    /** @var bool */
55
+    private $updateChecked = false;
56
+
57
+    /**
58
+     * @var \OCA\Files_Sharing\External\Manager
59
+     */
60
+    private $manager;
61
+
62
+    public function __construct($options) {
63
+        $this->memcacheFactory = \OC::$server->getMemCacheFactory();
64
+        $this->httpClient = $options['HttpClientService'];
65
+
66
+        $this->manager = $options['manager'];
67
+        $this->cloudId = $options['cloudId'];
68
+        $discoveryService = \OC::$server->getOCSDiscoveryService();
69
+
70
+        list($protocol, $remote) = explode('://', $this->cloudId->getRemote());
71
+        if (strpos($remote, '/')) {
72
+            list($host, $root) = explode('/', $remote, 2);
73
+        } else {
74
+            $host = $remote;
75
+            $root = '';
76
+        }
77
+        $secure = $protocol === 'https';
78
+        $federatedSharingEndpoints = $discoveryService->discover($this->cloudId->getRemote(), 'FEDERATED_SHARING');
79
+        $webDavEndpoint = isset($federatedSharingEndpoints['webdav']) ? $federatedSharingEndpoints['webdav'] : '/public.php/webdav';
80
+        $root = rtrim($root, '/') . $webDavEndpoint;
81
+        $this->mountPoint = $options['mountpoint'];
82
+        $this->token = $options['token'];
83
+
84
+        parent::__construct(array(
85
+            'secure' => $secure,
86
+            'host' => $host,
87
+            'root' => $root,
88
+            'user' => $options['token'],
89
+            'password' => (string)$options['password']
90
+        ));
91
+    }
92
+
93
+    public function getWatcher($path = '', $storage = null) {
94
+        if (!$storage) {
95
+            $storage = $this;
96
+        }
97
+        if (!isset($this->watcher)) {
98
+            $this->watcher = new Watcher($storage);
99
+            $this->watcher->setPolicy(\OC\Files\Cache\Watcher::CHECK_ONCE);
100
+        }
101
+        return $this->watcher;
102
+    }
103
+
104
+    public function getRemoteUser() {
105
+        return $this->cloudId->getUser();
106
+    }
107
+
108
+    public function getRemote() {
109
+        return $this->cloudId->getRemote();
110
+    }
111
+
112
+    public function getMountPoint() {
113
+        return $this->mountPoint;
114
+    }
115
+
116
+    public function getToken() {
117
+        return $this->token;
118
+    }
119
+
120
+    public function getPassword() {
121
+        return $this->password;
122
+    }
123
+
124
+    /**
125
+     * @brief get id of the mount point
126
+     * @return string
127
+     */
128
+    public function getId() {
129
+        return 'shared::' . md5($this->token . '@' . $this->getRemote());
130
+    }
131
+
132
+    public function getCache($path = '', $storage = null) {
133
+        if (is_null($this->cache)) {
134
+            $this->cache = new Cache($this, $this->cloudId);
135
+        }
136
+        return $this->cache;
137
+    }
138
+
139
+    /**
140
+     * @param string $path
141
+     * @param \OC\Files\Storage\Storage $storage
142
+     * @return \OCA\Files_Sharing\External\Scanner
143
+     */
144
+    public function getScanner($path = '', $storage = null) {
145
+        if (!$storage) {
146
+            $storage = $this;
147
+        }
148
+        if (!isset($this->scanner)) {
149
+            $this->scanner = new Scanner($storage);
150
+        }
151
+        return $this->scanner;
152
+    }
153
+
154
+    /**
155
+     * check if a file or folder has been updated since $time
156
+     *
157
+     * @param string $path
158
+     * @param int $time
159
+     * @throws \OCP\Files\StorageNotAvailableException
160
+     * @throws \OCP\Files\StorageInvalidException
161
+     * @return bool
162
+     */
163
+    public function hasUpdated($path, $time) {
164
+        // since for owncloud webdav servers we can rely on etag propagation we only need to check the root of the storage
165
+        // because of that we only do one check for the entire storage per request
166
+        if ($this->updateChecked) {
167
+            return false;
168
+        }
169
+        $this->updateChecked = true;
170
+        try {
171
+            return parent::hasUpdated('', $time);
172
+        } catch (StorageInvalidException $e) {
173
+            // check if it needs to be removed
174
+            $this->checkStorageAvailability();
175
+            throw $e;
176
+        } catch (StorageNotAvailableException $e) {
177
+            // check if it needs to be removed or just temp unavailable
178
+            $this->checkStorageAvailability();
179
+            throw $e;
180
+        }
181
+    }
182
+
183
+    public function test() {
184
+        try {
185
+            return parent::test();
186
+        } catch (StorageInvalidException $e) {
187
+            // check if it needs to be removed
188
+            $this->checkStorageAvailability();
189
+            throw $e;
190
+        } catch (StorageNotAvailableException $e) {
191
+            // check if it needs to be removed or just temp unavailable
192
+            $this->checkStorageAvailability();
193
+            throw $e;
194
+        }
195
+    }
196
+
197
+    /**
198
+     * Check whether this storage is permanently or temporarily
199
+     * unavailable
200
+     *
201
+     * @throws \OCP\Files\StorageNotAvailableException
202
+     * @throws \OCP\Files\StorageInvalidException
203
+     */
204
+    public function checkStorageAvailability() {
205
+        // see if we can find out why the share is unavailable
206
+        try {
207
+            $this->getShareInfo();
208
+        } catch (NotFoundException $e) {
209
+            // a 404 can either mean that the share no longer exists or there is no ownCloud on the remote
210
+            if ($this->testRemote()) {
211
+                // valid ownCloud instance means that the public share no longer exists
212
+                // since this is permanent (re-sharing the file will create a new token)
213
+                // we remove the invalid storage
214
+                $this->manager->removeShare($this->mountPoint);
215
+                $this->manager->getMountManager()->removeMount($this->mountPoint);
216
+                throw new StorageInvalidException();
217
+            } else {
218
+                // ownCloud instance is gone, likely to be a temporary server configuration error
219
+                throw new StorageNotAvailableException();
220
+            }
221
+        } catch (ForbiddenException $e) {
222
+            // auth error, remove share for now (provide a dialog in the future)
223
+            $this->manager->removeShare($this->mountPoint);
224
+            $this->manager->getMountManager()->removeMount($this->mountPoint);
225
+            throw new StorageInvalidException();
226
+        } catch (\GuzzleHttp\Exception\ConnectException $e) {
227
+            throw new StorageNotAvailableException();
228
+        } catch (\GuzzleHttp\Exception\RequestException $e) {
229
+            throw new StorageNotAvailableException();
230
+        } catch (\Exception $e) {
231
+            throw $e;
232
+        }
233
+    }
234
+
235
+    public function file_exists($path) {
236
+        if ($path === '') {
237
+            return true;
238
+        } else {
239
+            return parent::file_exists($path);
240
+        }
241
+    }
242
+
243
+    /**
244
+     * check if the configured remote is a valid federated share provider
245
+     *
246
+     * @return bool
247
+     */
248
+    protected function testRemote() {
249
+        try {
250
+            return $this->testRemoteUrl($this->getRemote() . '/ocs-provider/index.php')
251
+                || $this->testRemoteUrl($this->getRemote() . '/ocs-provider/')
252
+                || $this->testRemoteUrl($this->getRemote() . '/status.php');
253
+        } catch (\Exception $e) {
254
+            return false;
255
+        }
256
+    }
257
+
258
+    /**
259
+     * @param string $url
260
+     * @return bool
261
+     */
262
+    private function testRemoteUrl($url) {
263
+        $cache = $this->memcacheFactory->create('files_sharing_remote_url');
264
+        if($cache->hasKey($url)) {
265
+            return (bool)$cache->get($url);
266
+        }
267
+
268
+        $client = $this->httpClient->newClient();
269
+        try {
270
+            $result = $client->get($url, [
271
+                'timeout' => 10,
272
+                'connect_timeout' => 10,
273
+            ])->getBody();
274
+            $data = json_decode($result);
275
+            $returnValue = (is_object($data) && !empty($data->version));
276
+        } catch (ConnectException $e) {
277
+            $returnValue = false;
278
+        } catch (ClientException $e) {
279
+            $returnValue = false;
280
+        }
281
+
282
+        $cache->set($url, $returnValue);
283
+        return $returnValue;
284
+    }
285
+
286
+    /**
287
+     * Whether the remote is an ownCloud, used since some sharing features are not
288
+     * standardized. Let's use this to detect whether to use it.
289
+     *
290
+     * @return bool
291
+     */
292
+    public function remoteIsOwnCloud() {
293
+        if(defined('PHPUNIT_RUN') || !$this->testRemoteUrl($this->getRemote() . '/status.php')) {
294
+            return false;
295
+        }
296
+        return true;
297
+    }
298
+
299
+    /**
300
+     * @return mixed
301
+     * @throws ForbiddenException
302
+     * @throws NotFoundException
303
+     * @throws \Exception
304
+     */
305
+    public function getShareInfo() {
306
+        $remote = $this->getRemote();
307
+        $token = $this->getToken();
308
+        $password = $this->getPassword();
309
+
310
+        // If remote is not an ownCloud do not try to get any share info
311
+        if(!$this->remoteIsOwnCloud()) {
312
+            return ['status' => 'unsupported'];
313
+        }
314
+
315
+        $url = rtrim($remote, '/') . '/index.php/apps/files_sharing/shareinfo?t=' . $token;
316
+
317
+        // TODO: DI
318
+        $client = \OC::$server->getHTTPClientService()->newClient();
319
+        try {
320
+            $response = $client->post($url, [
321
+                'body' => ['password' => $password],
322
+                'timeout' => 10,
323
+                'connect_timeout' => 10,
324
+            ]);
325
+        } catch (\GuzzleHttp\Exception\RequestException $e) {
326
+            if ($e->getCode() === Http::STATUS_UNAUTHORIZED || $e->getCode() === Http::STATUS_FORBIDDEN) {
327
+                throw new ForbiddenException();
328
+            }
329
+            if ($e->getCode() === Http::STATUS_NOT_FOUND) {
330
+                throw new NotFoundException();
331
+            }
332
+            // throw this to be on the safe side: the share will still be visible
333
+            // in the UI in case the failure is intermittent, and the user will
334
+            // be able to decide whether to remove it if it's really gone
335
+            throw new StorageNotAvailableException();
336
+        }
337
+
338
+        return json_decode($response->getBody(), true);
339
+    }
340
+
341
+    public function getOwner($path) {
342
+        return $this->cloudId->getDisplayId();
343
+    }
344
+
345
+    public function isSharable($path) {
346
+        if (\OCP\Util::isSharingDisabledForUser() || !\OC\Share\Share::isResharingAllowed()) {
347
+            return false;
348
+        }
349
+        return ($this->getPermissions($path) & \OCP\Constants::PERMISSION_SHARE);
350
+    }
351
+
352
+    public function getPermissions($path) {
353
+        $response = $this->propfind($path);
354
+        if (isset($response['{http://open-collaboration-services.org/ns}share-permissions'])) {
355
+            $permissions = $response['{http://open-collaboration-services.org/ns}share-permissions'];
356
+        } else {
357
+            // use default permission if remote server doesn't provide the share permissions
358
+            if ($this->is_dir($path)) {
359
+                $permissions = \OCP\Constants::PERMISSION_ALL;
360
+            } else {
361
+                $permissions = \OCP\Constants::PERMISSION_ALL & ~\OCP\Constants::PERMISSION_CREATE;
362
+            }
363
+        }
364
+
365
+        return $permissions;
366
+    }
367 367
 
368 368
 }
Please login to merge, or discard this patch.
Spacing   +11 added lines, -11 removed lines patch added patch discarded remove patch
@@ -77,7 +77,7 @@  discard block
 block discarded – undo
77 77
 		$secure = $protocol === 'https';
78 78
 		$federatedSharingEndpoints = $discoveryService->discover($this->cloudId->getRemote(), 'FEDERATED_SHARING');
79 79
 		$webDavEndpoint = isset($federatedSharingEndpoints['webdav']) ? $federatedSharingEndpoints['webdav'] : '/public.php/webdav';
80
-		$root = rtrim($root, '/') . $webDavEndpoint;
80
+		$root = rtrim($root, '/').$webDavEndpoint;
81 81
 		$this->mountPoint = $options['mountpoint'];
82 82
 		$this->token = $options['token'];
83 83
 
@@ -86,7 +86,7 @@  discard block
 block discarded – undo
86 86
 			'host' => $host,
87 87
 			'root' => $root,
88 88
 			'user' => $options['token'],
89
-			'password' => (string)$options['password']
89
+			'password' => (string) $options['password']
90 90
 		));
91 91
 	}
92 92
 
@@ -126,7 +126,7 @@  discard block
 block discarded – undo
126 126
 	 * @return string
127 127
 	 */
128 128
 	public function getId() {
129
-		return 'shared::' . md5($this->token . '@' . $this->getRemote());
129
+		return 'shared::'.md5($this->token.'@'.$this->getRemote());
130 130
 	}
131 131
 
132 132
 	public function getCache($path = '', $storage = null) {
@@ -247,9 +247,9 @@  discard block
 block discarded – undo
247 247
 	 */
248 248
 	protected function testRemote() {
249 249
 		try {
250
-			return $this->testRemoteUrl($this->getRemote() . '/ocs-provider/index.php')
251
-				|| $this->testRemoteUrl($this->getRemote() . '/ocs-provider/')
252
-				|| $this->testRemoteUrl($this->getRemote() . '/status.php');
250
+			return $this->testRemoteUrl($this->getRemote().'/ocs-provider/index.php')
251
+				|| $this->testRemoteUrl($this->getRemote().'/ocs-provider/')
252
+				|| $this->testRemoteUrl($this->getRemote().'/status.php');
253 253
 		} catch (\Exception $e) {
254 254
 			return false;
255 255
 		}
@@ -261,8 +261,8 @@  discard block
 block discarded – undo
261 261
 	 */
262 262
 	private function testRemoteUrl($url) {
263 263
 		$cache = $this->memcacheFactory->create('files_sharing_remote_url');
264
-		if($cache->hasKey($url)) {
265
-			return (bool)$cache->get($url);
264
+		if ($cache->hasKey($url)) {
265
+			return (bool) $cache->get($url);
266 266
 		}
267 267
 
268 268
 		$client = $this->httpClient->newClient();
@@ -290,7 +290,7 @@  discard block
 block discarded – undo
290 290
 	 * @return bool
291 291
 	 */
292 292
 	public function remoteIsOwnCloud() {
293
-		if(defined('PHPUNIT_RUN') || !$this->testRemoteUrl($this->getRemote() . '/status.php')) {
293
+		if (defined('PHPUNIT_RUN') || !$this->testRemoteUrl($this->getRemote().'/status.php')) {
294 294
 			return false;
295 295
 		}
296 296
 		return true;
@@ -308,11 +308,11 @@  discard block
 block discarded – undo
308 308
 		$password = $this->getPassword();
309 309
 
310 310
 		// If remote is not an ownCloud do not try to get any share info
311
-		if(!$this->remoteIsOwnCloud()) {
311
+		if (!$this->remoteIsOwnCloud()) {
312 312
 			return ['status' => 'unsupported'];
313 313
 		}
314 314
 
315
-		$url = rtrim($remote, '/') . '/index.php/apps/files_sharing/shareinfo?t=' . $token;
315
+		$url = rtrim($remote, '/').'/index.php/apps/files_sharing/shareinfo?t='.$token;
316 316
 
317 317
 		// TODO: DI
318 318
 		$client = \OC::$server->getHTTPClientService()->newClient();
Please login to merge, or discard this patch.