Completed
Pull Request — master (#4212)
by Individual IT
13:52
created
apps/federation/lib/BackgroundJob/RequestSharedSecret.php 1 patch
Indentation   +136 added lines, -136 removed lines patch added patch discarded remove patch
@@ -47,140 +47,140 @@
 block discarded – undo
47 47
  */
48 48
 class RequestSharedSecret extends Job {
49 49
 
50
-	/** @var IClient */
51
-	private $httpClient;
52
-
53
-	/** @var IJobList */
54
-	private $jobList;
55
-
56
-	/** @var IURLGenerator */
57
-	private $urlGenerator;
58
-
59
-	/** @var DbHandler */
60
-	private $dbHandler;
61
-
62
-	/** @var TrustedServers */
63
-	private $trustedServers;
64
-
65
-	private $endPoint = '/ocs/v2.php/apps/federation/api/v1/request-shared-secret?format=json';
66
-
67
-	/** @var ILogger */
68
-	private $logger;
69
-
70
-	/** @var bool */
71
-	protected $retainJob = false;
72
-
73
-	/**
74
-	 * RequestSharedSecret constructor.
75
-	 *
76
-	 * @param IClient $httpClient
77
-	 * @param IURLGenerator $urlGenerator
78
-	 * @param IJobList $jobList
79
-	 * @param TrustedServers $trustedServers
80
-	 * @param DbHandler $dbHandler
81
-	 */
82
-	public function __construct(
83
-		IClient $httpClient = null,
84
-		IURLGenerator $urlGenerator = null,
85
-		IJobList $jobList = null,
86
-		TrustedServers $trustedServers = null,
87
-		DbHandler $dbHandler = null
88
-	) {
89
-		$this->httpClient = $httpClient ? $httpClient : \OC::$server->getHTTPClientService()->newClient();
90
-		$this->jobList = $jobList ? $jobList : \OC::$server->getJobList();
91
-		$this->urlGenerator = $urlGenerator ? $urlGenerator : \OC::$server->getURLGenerator();
92
-		$this->dbHandler = $dbHandler ? $dbHandler : new DbHandler(\OC::$server->getDatabaseConnection(), \OC::$server->getL10N('federation'));
93
-		$this->logger = \OC::$server->getLogger();
94
-		if ($trustedServers) {
95
-			$this->trustedServers = $trustedServers;
96
-		} else {
97
-			$this->trustedServers = new TrustedServers(
98
-				$this->dbHandler,
99
-				\OC::$server->getHTTPClientService(),
100
-				$this->logger,
101
-				$this->jobList,
102
-				\OC::$server->getSecureRandom(),
103
-				\OC::$server->getConfig(),
104
-				\OC::$server->getEventDispatcher()
105
-			);
106
-		}
107
-	}
108
-
109
-
110
-	/**
111
-	 * run the job, then remove it from the joblist
112
-	 *
113
-	 * @param JobList $jobList
114
-	 * @param ILogger $logger
115
-	 */
116
-	public function execute($jobList, ILogger $logger = null) {
117
-		$target = $this->argument['url'];
118
-		// only execute if target is still in the list of trusted domains
119
-		if ($this->trustedServers->isTrustedServer($target)) {
120
-			$this->parentExecute($jobList, $logger);
121
-		}
122
-
123
-		if (!$this->retainJob) {
124
-			$jobList->remove($this, $this->argument);
125
-		}
126
-	}
127
-
128
-	/**
129
-	 * call execute() method of parent
130
-	 *
131
-	 * @param JobList $jobList
132
-	 * @param ILogger $logger
133
-	 */
134
-	protected function parentExecute($jobList, $logger) {
135
-		parent::execute($jobList, $logger);
136
-	}
137
-
138
-	protected function run($argument) {
139
-
140
-		$target = $argument['url'];
141
-		$source = $this->urlGenerator->getAbsoluteURL('/');
142
-		$source = rtrim($source, '/');
143
-		$token = $argument['token'];
144
-
145
-		try {
146
-			$result = $this->httpClient->post(
147
-				$target . $this->endPoint,
148
-				[
149
-					'body' => [
150
-						'url' => $source,
151
-						'token' => $token,
152
-					],
153
-					'timeout' => 3,
154
-					'connect_timeout' => 3,
155
-				]
156
-			);
157
-
158
-			$status = $result->getStatusCode();
159
-
160
-		} catch (ClientException $e) {
161
-			$status = $e->getCode();
162
-			if ($status === Http::STATUS_FORBIDDEN) {
163
-				$this->logger->info($target . ' refused to ask for a shared secret.', ['app' => 'federation']);
164
-			} else {
165
-				$this->logger->logException($e, ['app' => 'federation']);
166
-			}
167
-		} catch (\Exception $e) {
168
-			$status = Http::STATUS_INTERNAL_SERVER_ERROR;
169
-			$this->logger->logException($e, ['app' => 'federation']);
170
-		}
171
-
172
-		// if we received a unexpected response we try again later
173
-		if (
174
-			$status !== Http::STATUS_OK
175
-			&& $status !== Http::STATUS_FORBIDDEN
176
-		) {
177
-			$this->retainJob = true;
178
-		}
179
-
180
-		if ($status === Http::STATUS_FORBIDDEN) {
181
-			// clear token if remote server refuses to ask for shared secret
182
-			$this->dbHandler->addToken($target, '');
183
-		}
184
-
185
-	}
50
+    /** @var IClient */
51
+    private $httpClient;
52
+
53
+    /** @var IJobList */
54
+    private $jobList;
55
+
56
+    /** @var IURLGenerator */
57
+    private $urlGenerator;
58
+
59
+    /** @var DbHandler */
60
+    private $dbHandler;
61
+
62
+    /** @var TrustedServers */
63
+    private $trustedServers;
64
+
65
+    private $endPoint = '/ocs/v2.php/apps/federation/api/v1/request-shared-secret?format=json';
66
+
67
+    /** @var ILogger */
68
+    private $logger;
69
+
70
+    /** @var bool */
71
+    protected $retainJob = false;
72
+
73
+    /**
74
+     * RequestSharedSecret constructor.
75
+     *
76
+     * @param IClient $httpClient
77
+     * @param IURLGenerator $urlGenerator
78
+     * @param IJobList $jobList
79
+     * @param TrustedServers $trustedServers
80
+     * @param DbHandler $dbHandler
81
+     */
82
+    public function __construct(
83
+        IClient $httpClient = null,
84
+        IURLGenerator $urlGenerator = null,
85
+        IJobList $jobList = null,
86
+        TrustedServers $trustedServers = null,
87
+        DbHandler $dbHandler = null
88
+    ) {
89
+        $this->httpClient = $httpClient ? $httpClient : \OC::$server->getHTTPClientService()->newClient();
90
+        $this->jobList = $jobList ? $jobList : \OC::$server->getJobList();
91
+        $this->urlGenerator = $urlGenerator ? $urlGenerator : \OC::$server->getURLGenerator();
92
+        $this->dbHandler = $dbHandler ? $dbHandler : new DbHandler(\OC::$server->getDatabaseConnection(), \OC::$server->getL10N('federation'));
93
+        $this->logger = \OC::$server->getLogger();
94
+        if ($trustedServers) {
95
+            $this->trustedServers = $trustedServers;
96
+        } else {
97
+            $this->trustedServers = new TrustedServers(
98
+                $this->dbHandler,
99
+                \OC::$server->getHTTPClientService(),
100
+                $this->logger,
101
+                $this->jobList,
102
+                \OC::$server->getSecureRandom(),
103
+                \OC::$server->getConfig(),
104
+                \OC::$server->getEventDispatcher()
105
+            );
106
+        }
107
+    }
108
+
109
+
110
+    /**
111
+     * run the job, then remove it from the joblist
112
+     *
113
+     * @param JobList $jobList
114
+     * @param ILogger $logger
115
+     */
116
+    public function execute($jobList, ILogger $logger = null) {
117
+        $target = $this->argument['url'];
118
+        // only execute if target is still in the list of trusted domains
119
+        if ($this->trustedServers->isTrustedServer($target)) {
120
+            $this->parentExecute($jobList, $logger);
121
+        }
122
+
123
+        if (!$this->retainJob) {
124
+            $jobList->remove($this, $this->argument);
125
+        }
126
+    }
127
+
128
+    /**
129
+     * call execute() method of parent
130
+     *
131
+     * @param JobList $jobList
132
+     * @param ILogger $logger
133
+     */
134
+    protected function parentExecute($jobList, $logger) {
135
+        parent::execute($jobList, $logger);
136
+    }
137
+
138
+    protected function run($argument) {
139
+
140
+        $target = $argument['url'];
141
+        $source = $this->urlGenerator->getAbsoluteURL('/');
142
+        $source = rtrim($source, '/');
143
+        $token = $argument['token'];
144
+
145
+        try {
146
+            $result = $this->httpClient->post(
147
+                $target . $this->endPoint,
148
+                [
149
+                    'body' => [
150
+                        'url' => $source,
151
+                        'token' => $token,
152
+                    ],
153
+                    'timeout' => 3,
154
+                    'connect_timeout' => 3,
155
+                ]
156
+            );
157
+
158
+            $status = $result->getStatusCode();
159
+
160
+        } catch (ClientException $e) {
161
+            $status = $e->getCode();
162
+            if ($status === Http::STATUS_FORBIDDEN) {
163
+                $this->logger->info($target . ' refused to ask for a shared secret.', ['app' => 'federation']);
164
+            } else {
165
+                $this->logger->logException($e, ['app' => 'federation']);
166
+            }
167
+        } catch (\Exception $e) {
168
+            $status = Http::STATUS_INTERNAL_SERVER_ERROR;
169
+            $this->logger->logException($e, ['app' => 'federation']);
170
+        }
171
+
172
+        // if we received a unexpected response we try again later
173
+        if (
174
+            $status !== Http::STATUS_OK
175
+            && $status !== Http::STATUS_FORBIDDEN
176
+        ) {
177
+            $this->retainJob = true;
178
+        }
179
+
180
+        if ($status === Http::STATUS_FORBIDDEN) {
181
+            // clear token if remote server refuses to ask for shared secret
182
+            $this->dbHandler->addToken($target, '');
183
+        }
184
+
185
+    }
186 186
 }
Please login to merge, or discard this patch.
apps/federation/lib/Settings/Admin.php 1 patch
Indentation   +31 added lines, -31 removed lines patch added patch discarded remove patch
@@ -29,41 +29,41 @@
 block discarded – undo
29 29
 
30 30
 class Admin implements ISettings {
31 31
 
32
-	/** @var TrustedServers */
33
-	private $trustedServers;
32
+    /** @var TrustedServers */
33
+    private $trustedServers;
34 34
 
35
-	public function __construct(TrustedServers $trustedServers) {
36
-		$this->trustedServers = $trustedServers;
37
-	}
35
+    public function __construct(TrustedServers $trustedServers) {
36
+        $this->trustedServers = $trustedServers;
37
+    }
38 38
 
39
-	/**
40
-	 * @return TemplateResponse
41
-	 */
42
-	public function getForm() {
43
-		$parameters = [
44
-			'trustedServers' => $this->trustedServers->getServers(),
45
-			'autoAddServers' => $this->trustedServers->getAutoAddServers(),
46
-		];
39
+    /**
40
+     * @return TemplateResponse
41
+     */
42
+    public function getForm() {
43
+        $parameters = [
44
+            'trustedServers' => $this->trustedServers->getServers(),
45
+            'autoAddServers' => $this->trustedServers->getAutoAddServers(),
46
+        ];
47 47
 
48
-		return new TemplateResponse('federation', 'settings-admin', $parameters, '');
49
-	}
48
+        return new TemplateResponse('federation', 'settings-admin', $parameters, '');
49
+    }
50 50
 
51
-	/**
52
-	 * @return string the section ID, e.g. 'sharing'
53
-	 */
54
-	public function getSection() {
55
-		return 'sharing';
56
-	}
51
+    /**
52
+     * @return string the section ID, e.g. 'sharing'
53
+     */
54
+    public function getSection() {
55
+        return 'sharing';
56
+    }
57 57
 
58
-	/**
59
-	 * @return int whether the form should be rather on the top or bottom of
60
-	 * the admin section. The forms are arranged in ascending order of the
61
-	 * priority values. It is required to return a value between 0 and 100.
62
-	 *
63
-	 * E.g.: 70
64
-	 */
65
-	public function getPriority() {
66
-		return 30;
67
-	}
58
+    /**
59
+     * @return int whether the form should be rather on the top or bottom of
60
+     * the admin section. The forms are arranged in ascending order of the
61
+     * priority values. It is required to return a value between 0 and 100.
62
+     *
63
+     * E.g.: 70
64
+     */
65
+    public function getPriority() {
66
+        return 30;
67
+    }
68 68
 
69 69
 }
Please login to merge, or discard this patch.
apps/federation/lib/Hooks.php 1 patch
Indentation   +20 added lines, -20 removed lines patch added patch discarded remove patch
@@ -27,25 +27,25 @@
 block discarded – undo
27 27
 
28 28
 class Hooks {
29 29
 
30
-	/** @var TrustedServers */
31
-	private $trustedServers;
32
-
33
-	public function __construct(TrustedServers $trustedServers) {
34
-		$this->trustedServers = $trustedServers;
35
-	}
36
-
37
-	/**
38
-	 * add servers to the list of trusted servers once a federated share was established
39
-	 *
40
-	 * @param array $params
41
-	 */
42
-	public function addServerHook($params) {
43
-		if (
44
-			$this->trustedServers->getAutoAddServers() === true &&
45
-			$this->trustedServers->isTrustedServer($params['server']) === false
46
-		) {
47
-			$this->trustedServers->addServer($params['server']);
48
-		}
49
-	}
30
+    /** @var TrustedServers */
31
+    private $trustedServers;
32
+
33
+    public function __construct(TrustedServers $trustedServers) {
34
+        $this->trustedServers = $trustedServers;
35
+    }
36
+
37
+    /**
38
+     * add servers to the list of trusted servers once a federated share was established
39
+     *
40
+     * @param array $params
41
+     */
42
+    public function addServerHook($params) {
43
+        if (
44
+            $this->trustedServers->getAutoAddServers() === true &&
45
+            $this->trustedServers->isTrustedServer($params['server']) === false
46
+        ) {
47
+            $this->trustedServers->addServer($params['server']);
48
+        }
49
+    }
50 50
 
51 51
 }
Please login to merge, or discard this patch.
apps/federation/lib/DbHandler.php 1 patch
Indentation   +275 added lines, -275 removed lines patch added patch discarded remove patch
@@ -42,280 +42,280 @@
 block discarded – undo
42 42
  */
43 43
 class DbHandler {
44 44
 
45
-	/** @var  IDBConnection */
46
-	private $connection;
47
-
48
-	/** @var  IL10N */
49
-	private $IL10N;
50
-
51
-	/** @var string  */
52
-	private $dbTable = 'trusted_servers';
53
-
54
-	/**
55
-	 * @param IDBConnection $connection
56
-	 * @param IL10N $il10n
57
-	 */
58
-	public function __construct(
59
-		IDBConnection $connection,
60
-		IL10N $il10n
61
-	) {
62
-		$this->connection = $connection;
63
-		$this->IL10N = $il10n;
64
-	}
65
-
66
-	/**
67
-	 * add server to the list of trusted servers
68
-	 *
69
-	 * @param string $url
70
-	 * @return int
71
-	 * @throws HintException
72
-	 */
73
-	public function addServer($url) {
74
-		$hash = $this->hash($url);
75
-		$url = rtrim($url, '/');
76
-		$query = $this->connection->getQueryBuilder();
77
-		$query->insert($this->dbTable)
78
-			->values(
79
-				[
80
-					'url' =>  $query->createParameter('url'),
81
-					'url_hash' => $query->createParameter('url_hash'),
82
-				]
83
-			)
84
-			->setParameter('url', $url)
85
-			->setParameter('url_hash', $hash);
86
-
87
-		$result = $query->execute();
88
-
89
-		if ($result) {
90
-			return (int)$this->connection->lastInsertId('*PREFIX*'.$this->dbTable);
91
-		} else {
92
-			$message = 'Internal failure, Could not add trusted server: ' . $url;
93
-			$message_t = $this->IL10N->t('Could not add server');
94
-			throw new HintException($message, $message_t);
95
-		}
96
-	}
97
-
98
-	/**
99
-	 * remove server from the list of trusted servers
100
-	 *
101
-	 * @param int $id
102
-	 */
103
-	public function removeServer($id) {
104
-		$query = $this->connection->getQueryBuilder();
105
-		$query->delete($this->dbTable)
106
-			->where($query->expr()->eq('id', $query->createParameter('id')))
107
-			->setParameter('id', $id);
108
-		$query->execute();
109
-	}
110
-
111
-	/**
112
-	 * get trusted server with given ID
113
-	 *
114
-	 * @param int $id
115
-	 * @return array
116
-	 * @throws \Exception
117
-	 */
118
-	public function getServerById($id) {
119
-		$query = $this->connection->getQueryBuilder();
120
-		$query->select('*')->from($this->dbTable)
121
-			->where($query->expr()->eq('id', $query->createParameter('id')))
122
-			->setParameter('id', $id);
123
-		$query->execute();
124
-		$result = $query->execute()->fetchAll();
125
-
126
-		if (empty($result)) {
127
-			throw new \Exception('No Server found with ID: ' . $id);
128
-		}
129
-
130
-		return $result[0];
131
-	}
132
-
133
-	/**
134
-	 * get all trusted servers
135
-	 *
136
-	 * @return array
137
-	 */
138
-	public function getAllServer() {
139
-		$query = $this->connection->getQueryBuilder();
140
-		$query->select(['url', 'url_hash', 'id', 'status', 'shared_secret', 'sync_token'])->from($this->dbTable);
141
-		$result = $query->execute()->fetchAll();
142
-		return $result;
143
-	}
144
-
145
-	/**
146
-	 * check if server already exists in the database table
147
-	 *
148
-	 * @param string $url
149
-	 * @return bool
150
-	 */
151
-	public function serverExists($url) {
152
-		$hash = $this->hash($url);
153
-		$query = $this->connection->getQueryBuilder();
154
-		$query->select('url')->from($this->dbTable)
155
-			->where($query->expr()->eq('url_hash', $query->createParameter('url_hash')))
156
-			->setParameter('url_hash', $hash);
157
-		$result = $query->execute()->fetchAll();
158
-
159
-		return !empty($result);
160
-	}
161
-
162
-	/**
163
-	 * write token to database. Token is used to exchange the secret
164
-	 *
165
-	 * @param string $url
166
-	 * @param string $token
167
-	 */
168
-	public function addToken($url, $token) {
169
-		$hash = $this->hash($url);
170
-		$query = $this->connection->getQueryBuilder();
171
-		$query->update($this->dbTable)
172
-			->set('token', $query->createParameter('token'))
173
-			->where($query->expr()->eq('url_hash', $query->createParameter('url_hash')))
174
-			->setParameter('url_hash', $hash)
175
-			->setParameter('token', $token);
176
-		$query->execute();
177
-	}
178
-
179
-	/**
180
-	 * get token stored in database
181
-	 *
182
-	 * @param string $url
183
-	 * @return string
184
-	 * @throws \Exception
185
-	 */
186
-	public function getToken($url) {
187
-		$hash = $this->hash($url);
188
-		$query = $this->connection->getQueryBuilder();
189
-		$query->select('token')->from($this->dbTable)
190
-			->where($query->expr()->eq('url_hash', $query->createParameter('url_hash')))
191
-			->setParameter('url_hash', $hash);
192
-
193
-		$result = $query->execute()->fetch();
194
-
195
-		if (!isset($result['token'])) {
196
-			throw new \Exception('No token found for: ' . $url);
197
-		}
198
-
199
-		return $result['token'];
200
-	}
201
-
202
-	/**
203
-	 * add shared Secret to database
204
-	 *
205
-	 * @param string $url
206
-	 * @param string $sharedSecret
207
-	 */
208
-	public function addSharedSecret($url, $sharedSecret) {
209
-		$hash = $this->hash($url);
210
-		$query = $this->connection->getQueryBuilder();
211
-		$query->update($this->dbTable)
212
-			->set('shared_secret', $query->createParameter('sharedSecret'))
213
-			->where($query->expr()->eq('url_hash', $query->createParameter('url_hash')))
214
-			->setParameter('url_hash', $hash)
215
-			->setParameter('sharedSecret', $sharedSecret);
216
-		$query->execute();
217
-	}
218
-
219
-	/**
220
-	 * get shared secret from database
221
-	 *
222
-	 * @param string $url
223
-	 * @return string
224
-	 */
225
-	public function getSharedSecret($url) {
226
-		$hash = $this->hash($url);
227
-		$query = $this->connection->getQueryBuilder();
228
-		$query->select('shared_secret')->from($this->dbTable)
229
-			->where($query->expr()->eq('url_hash', $query->createParameter('url_hash')))
230
-			->setParameter('url_hash', $hash);
231
-
232
-		$result = $query->execute()->fetch();
233
-		return $result['shared_secret'];
234
-	}
235
-
236
-	/**
237
-	 * set server status
238
-	 *
239
-	 * @param string $url
240
-	 * @param int $status
241
-	 * @param string|null $token
242
-	 */
243
-	public function setServerStatus($url, $status, $token = null) {
244
-		$hash = $this->hash($url);
245
-		$query = $this->connection->getQueryBuilder();
246
-		$query->update($this->dbTable)
247
-				->set('status', $query->createNamedParameter($status))
248
-				->where($query->expr()->eq('url_hash', $query->createNamedParameter($hash)));
249
-		if (!is_null($token)) {
250
-			$query->set('sync_token', $query->createNamedParameter($token));
251
-		}
252
-		$query->execute();
253
-	}
254
-
255
-	/**
256
-	 * get server status
257
-	 *
258
-	 * @param string $url
259
-	 * @return int
260
-	 */
261
-	public function getServerStatus($url) {
262
-		$hash = $this->hash($url);
263
-		$query = $this->connection->getQueryBuilder();
264
-		$query->select('status')->from($this->dbTable)
265
-				->where($query->expr()->eq('url_hash', $query->createParameter('url_hash')))
266
-				->setParameter('url_hash', $hash);
267
-
268
-		$result = $query->execute()->fetch();
269
-		return (int)$result['status'];
270
-	}
271
-
272
-	/**
273
-	 * create hash from URL
274
-	 *
275
-	 * @param string $url
276
-	 * @return string
277
-	 */
278
-	protected function hash($url) {
279
-		$normalized = $this->normalizeUrl($url);
280
-		return sha1($normalized);
281
-	}
282
-
283
-	/**
284
-	 * normalize URL, used to create the sha1 hash
285
-	 *
286
-	 * @param string $url
287
-	 * @return string
288
-	 */
289
-	protected function normalizeUrl($url) {
290
-		$normalized = $url;
291
-
292
-		if (strpos($url, 'https://') === 0) {
293
-			$normalized = substr($url, strlen('https://'));
294
-		} else if (strpos($url, 'http://') === 0) {
295
-			$normalized = substr($url, strlen('http://'));
296
-		}
297
-
298
-		$normalized = Filesystem::normalizePath($normalized);
299
-		$normalized = trim($normalized, '/');
300
-
301
-		return $normalized;
302
-	}
303
-
304
-	/**
305
-	 * @param $username
306
-	 * @param $password
307
-	 * @return bool
308
-	 */
309
-	public function auth($username, $password) {
310
-		if ($username !== 'system') {
311
-			return false;
312
-		}
313
-		$query = $this->connection->getQueryBuilder();
314
-		$query->select('url')->from($this->dbTable)
315
-				->where($query->expr()->eq('shared_secret', $query->createNamedParameter($password)));
316
-
317
-		$result = $query->execute()->fetch();
318
-		return !empty($result);
319
-	}
45
+    /** @var  IDBConnection */
46
+    private $connection;
47
+
48
+    /** @var  IL10N */
49
+    private $IL10N;
50
+
51
+    /** @var string  */
52
+    private $dbTable = 'trusted_servers';
53
+
54
+    /**
55
+     * @param IDBConnection $connection
56
+     * @param IL10N $il10n
57
+     */
58
+    public function __construct(
59
+        IDBConnection $connection,
60
+        IL10N $il10n
61
+    ) {
62
+        $this->connection = $connection;
63
+        $this->IL10N = $il10n;
64
+    }
65
+
66
+    /**
67
+     * add server to the list of trusted servers
68
+     *
69
+     * @param string $url
70
+     * @return int
71
+     * @throws HintException
72
+     */
73
+    public function addServer($url) {
74
+        $hash = $this->hash($url);
75
+        $url = rtrim($url, '/');
76
+        $query = $this->connection->getQueryBuilder();
77
+        $query->insert($this->dbTable)
78
+            ->values(
79
+                [
80
+                    'url' =>  $query->createParameter('url'),
81
+                    'url_hash' => $query->createParameter('url_hash'),
82
+                ]
83
+            )
84
+            ->setParameter('url', $url)
85
+            ->setParameter('url_hash', $hash);
86
+
87
+        $result = $query->execute();
88
+
89
+        if ($result) {
90
+            return (int)$this->connection->lastInsertId('*PREFIX*'.$this->dbTable);
91
+        } else {
92
+            $message = 'Internal failure, Could not add trusted server: ' . $url;
93
+            $message_t = $this->IL10N->t('Could not add server');
94
+            throw new HintException($message, $message_t);
95
+        }
96
+    }
97
+
98
+    /**
99
+     * remove server from the list of trusted servers
100
+     *
101
+     * @param int $id
102
+     */
103
+    public function removeServer($id) {
104
+        $query = $this->connection->getQueryBuilder();
105
+        $query->delete($this->dbTable)
106
+            ->where($query->expr()->eq('id', $query->createParameter('id')))
107
+            ->setParameter('id', $id);
108
+        $query->execute();
109
+    }
110
+
111
+    /**
112
+     * get trusted server with given ID
113
+     *
114
+     * @param int $id
115
+     * @return array
116
+     * @throws \Exception
117
+     */
118
+    public function getServerById($id) {
119
+        $query = $this->connection->getQueryBuilder();
120
+        $query->select('*')->from($this->dbTable)
121
+            ->where($query->expr()->eq('id', $query->createParameter('id')))
122
+            ->setParameter('id', $id);
123
+        $query->execute();
124
+        $result = $query->execute()->fetchAll();
125
+
126
+        if (empty($result)) {
127
+            throw new \Exception('No Server found with ID: ' . $id);
128
+        }
129
+
130
+        return $result[0];
131
+    }
132
+
133
+    /**
134
+     * get all trusted servers
135
+     *
136
+     * @return array
137
+     */
138
+    public function getAllServer() {
139
+        $query = $this->connection->getQueryBuilder();
140
+        $query->select(['url', 'url_hash', 'id', 'status', 'shared_secret', 'sync_token'])->from($this->dbTable);
141
+        $result = $query->execute()->fetchAll();
142
+        return $result;
143
+    }
144
+
145
+    /**
146
+     * check if server already exists in the database table
147
+     *
148
+     * @param string $url
149
+     * @return bool
150
+     */
151
+    public function serverExists($url) {
152
+        $hash = $this->hash($url);
153
+        $query = $this->connection->getQueryBuilder();
154
+        $query->select('url')->from($this->dbTable)
155
+            ->where($query->expr()->eq('url_hash', $query->createParameter('url_hash')))
156
+            ->setParameter('url_hash', $hash);
157
+        $result = $query->execute()->fetchAll();
158
+
159
+        return !empty($result);
160
+    }
161
+
162
+    /**
163
+     * write token to database. Token is used to exchange the secret
164
+     *
165
+     * @param string $url
166
+     * @param string $token
167
+     */
168
+    public function addToken($url, $token) {
169
+        $hash = $this->hash($url);
170
+        $query = $this->connection->getQueryBuilder();
171
+        $query->update($this->dbTable)
172
+            ->set('token', $query->createParameter('token'))
173
+            ->where($query->expr()->eq('url_hash', $query->createParameter('url_hash')))
174
+            ->setParameter('url_hash', $hash)
175
+            ->setParameter('token', $token);
176
+        $query->execute();
177
+    }
178
+
179
+    /**
180
+     * get token stored in database
181
+     *
182
+     * @param string $url
183
+     * @return string
184
+     * @throws \Exception
185
+     */
186
+    public function getToken($url) {
187
+        $hash = $this->hash($url);
188
+        $query = $this->connection->getQueryBuilder();
189
+        $query->select('token')->from($this->dbTable)
190
+            ->where($query->expr()->eq('url_hash', $query->createParameter('url_hash')))
191
+            ->setParameter('url_hash', $hash);
192
+
193
+        $result = $query->execute()->fetch();
194
+
195
+        if (!isset($result['token'])) {
196
+            throw new \Exception('No token found for: ' . $url);
197
+        }
198
+
199
+        return $result['token'];
200
+    }
201
+
202
+    /**
203
+     * add shared Secret to database
204
+     *
205
+     * @param string $url
206
+     * @param string $sharedSecret
207
+     */
208
+    public function addSharedSecret($url, $sharedSecret) {
209
+        $hash = $this->hash($url);
210
+        $query = $this->connection->getQueryBuilder();
211
+        $query->update($this->dbTable)
212
+            ->set('shared_secret', $query->createParameter('sharedSecret'))
213
+            ->where($query->expr()->eq('url_hash', $query->createParameter('url_hash')))
214
+            ->setParameter('url_hash', $hash)
215
+            ->setParameter('sharedSecret', $sharedSecret);
216
+        $query->execute();
217
+    }
218
+
219
+    /**
220
+     * get shared secret from database
221
+     *
222
+     * @param string $url
223
+     * @return string
224
+     */
225
+    public function getSharedSecret($url) {
226
+        $hash = $this->hash($url);
227
+        $query = $this->connection->getQueryBuilder();
228
+        $query->select('shared_secret')->from($this->dbTable)
229
+            ->where($query->expr()->eq('url_hash', $query->createParameter('url_hash')))
230
+            ->setParameter('url_hash', $hash);
231
+
232
+        $result = $query->execute()->fetch();
233
+        return $result['shared_secret'];
234
+    }
235
+
236
+    /**
237
+     * set server status
238
+     *
239
+     * @param string $url
240
+     * @param int $status
241
+     * @param string|null $token
242
+     */
243
+    public function setServerStatus($url, $status, $token = null) {
244
+        $hash = $this->hash($url);
245
+        $query = $this->connection->getQueryBuilder();
246
+        $query->update($this->dbTable)
247
+                ->set('status', $query->createNamedParameter($status))
248
+                ->where($query->expr()->eq('url_hash', $query->createNamedParameter($hash)));
249
+        if (!is_null($token)) {
250
+            $query->set('sync_token', $query->createNamedParameter($token));
251
+        }
252
+        $query->execute();
253
+    }
254
+
255
+    /**
256
+     * get server status
257
+     *
258
+     * @param string $url
259
+     * @return int
260
+     */
261
+    public function getServerStatus($url) {
262
+        $hash = $this->hash($url);
263
+        $query = $this->connection->getQueryBuilder();
264
+        $query->select('status')->from($this->dbTable)
265
+                ->where($query->expr()->eq('url_hash', $query->createParameter('url_hash')))
266
+                ->setParameter('url_hash', $hash);
267
+
268
+        $result = $query->execute()->fetch();
269
+        return (int)$result['status'];
270
+    }
271
+
272
+    /**
273
+     * create hash from URL
274
+     *
275
+     * @param string $url
276
+     * @return string
277
+     */
278
+    protected function hash($url) {
279
+        $normalized = $this->normalizeUrl($url);
280
+        return sha1($normalized);
281
+    }
282
+
283
+    /**
284
+     * normalize URL, used to create the sha1 hash
285
+     *
286
+     * @param string $url
287
+     * @return string
288
+     */
289
+    protected function normalizeUrl($url) {
290
+        $normalized = $url;
291
+
292
+        if (strpos($url, 'https://') === 0) {
293
+            $normalized = substr($url, strlen('https://'));
294
+        } else if (strpos($url, 'http://') === 0) {
295
+            $normalized = substr($url, strlen('http://'));
296
+        }
297
+
298
+        $normalized = Filesystem::normalizePath($normalized);
299
+        $normalized = trim($normalized, '/');
300
+
301
+        return $normalized;
302
+    }
303
+
304
+    /**
305
+     * @param $username
306
+     * @param $password
307
+     * @return bool
308
+     */
309
+    public function auth($username, $password) {
310
+        if ($username !== 'system') {
311
+            return false;
312
+        }
313
+        $query = $this->connection->getQueryBuilder();
314
+        $query->select('url')->from($this->dbTable)
315
+                ->where($query->expr()->eq('shared_secret', $query->createNamedParameter($password)));
316
+
317
+        $result = $query->execute()->fetch();
318
+        return !empty($result);
319
+    }
320 320
 
321 321
 }
Please login to merge, or discard this patch.
apps/federation/lib/SyncJob.php 1 patch
Indentation   +13 added lines, -13 removed lines patch added patch discarded remove patch
@@ -27,18 +27,18 @@
 block discarded – undo
27 27
 
28 28
 class SyncJob extends TimedJob {
29 29
 
30
-	public function __construct() {
31
-		// Run once a day
32
-		$this->setInterval(24 * 60 * 60);
33
-	}
30
+    public function __construct() {
31
+        // Run once a day
32
+        $this->setInterval(24 * 60 * 60);
33
+    }
34 34
 
35
-	protected function run($argument) {
36
-		$app = new Application();
37
-		$ss = $app->getSyncService();
38
-		$ss->syncThemAll(function($url, $ex) {
39
-			if ($ex instanceof \Exception) {
40
-				\OC::$server->getLogger()->error("Error while syncing $url : " . $ex->getMessage(), ['app' => 'fed-sync']);
41
-			}
42
-		});
43
-	}
35
+    protected function run($argument) {
36
+        $app = new Application();
37
+        $ss = $app->getSyncService();
38
+        $ss->syncThemAll(function($url, $ex) {
39
+            if ($ex instanceof \Exception) {
40
+                \OC::$server->getLogger()->error("Error while syncing $url : " . $ex->getMessage(), ['app' => 'fed-sync']);
41
+            }
42
+        });
43
+    }
44 44
 }
Please login to merge, or discard this patch.
apps/dav/lib/DAV/PublicAuth.php 1 patch
Indentation   +58 added lines, -58 removed lines patch added patch discarded remove patch
@@ -26,67 +26,67 @@
 block discarded – undo
26 26
 
27 27
 class PublicAuth implements BackendInterface {
28 28
 
29
-	/** @var string[] */
30
-	private $publicURLs;
29
+    /** @var string[] */
30
+    private $publicURLs;
31 31
 
32
-	public function __construct() {
33
-		$this->publicURLs = [
34
-			'public-calendars',
35
-			'principals/system/public'
36
-		];
37
-	}
32
+    public function __construct() {
33
+        $this->publicURLs = [
34
+            'public-calendars',
35
+            'principals/system/public'
36
+        ];
37
+    }
38 38
 
39
-	/**
40
-	 * When this method is called, the backend must check if authentication was
41
-	 * successful.
42
-	 *
43
-	 * The returned value must be one of the following
44
-	 *
45
-	 * [true, "principals/username"]
46
-	 * [false, "reason for failure"]
47
-	 *
48
-	 * If authentication was successful, it's expected that the authentication
49
-	 * backend returns a so-called principal url.
50
-	 *
51
-	 * Examples of a principal url:
52
-	 *
53
-	 * principals/admin
54
-	 * principals/user1
55
-	 * principals/users/joe
56
-	 * principals/uid/123457
57
-	 *
58
-	 * If you don't use WebDAV ACL (RFC3744) we recommend that you simply
59
-	 * return a string such as:
60
-	 *
61
-	 * principals/users/[username]
62
-	 *
63
-	 * @param RequestInterface $request
64
-	 * @param ResponseInterface $response
65
-	 * @return array
66
-	 */
67
-	function check(RequestInterface $request, ResponseInterface $response) {
39
+    /**
40
+     * When this method is called, the backend must check if authentication was
41
+     * successful.
42
+     *
43
+     * The returned value must be one of the following
44
+     *
45
+     * [true, "principals/username"]
46
+     * [false, "reason for failure"]
47
+     *
48
+     * If authentication was successful, it's expected that the authentication
49
+     * backend returns a so-called principal url.
50
+     *
51
+     * Examples of a principal url:
52
+     *
53
+     * principals/admin
54
+     * principals/user1
55
+     * principals/users/joe
56
+     * principals/uid/123457
57
+     *
58
+     * If you don't use WebDAV ACL (RFC3744) we recommend that you simply
59
+     * return a string such as:
60
+     *
61
+     * principals/users/[username]
62
+     *
63
+     * @param RequestInterface $request
64
+     * @param ResponseInterface $response
65
+     * @return array
66
+     */
67
+    function check(RequestInterface $request, ResponseInterface $response) {
68 68
 
69
-		if ($this->isRequestPublic($request)) {
70
-			return [true, "principals/system/public"];
71
-		}
72
-		return [false, "No public access to this resource."];
73
-	}
69
+        if ($this->isRequestPublic($request)) {
70
+            return [true, "principals/system/public"];
71
+        }
72
+        return [false, "No public access to this resource."];
73
+    }
74 74
 
75
-	/**
76
-	 * @inheritdoc
77
-	 */
78
-	function challenge(RequestInterface $request, ResponseInterface $response) {
79
-	}
75
+    /**
76
+     * @inheritdoc
77
+     */
78
+    function challenge(RequestInterface $request, ResponseInterface $response) {
79
+    }
80 80
 
81
-	/**
82
-	 * @param RequestInterface $request
83
-	 * @return bool
84
-	 */
85
-	private function isRequestPublic(RequestInterface $request) {
86
-		$url = $request->getPath();
87
-		$matchingUrls = array_filter($this->publicURLs, function ($publicUrl) use ($url) {
88
-			return strpos($url, $publicUrl, 0) === 0;
89
-		});
90
-		return !empty($matchingUrls);
91
-	}
81
+    /**
82
+     * @param RequestInterface $request
83
+     * @return bool
84
+     */
85
+    private function isRequestPublic(RequestInterface $request) {
86
+        $url = $request->getPath();
87
+        $matchingUrls = array_filter($this->publicURLs, function ($publicUrl) use ($url) {
88
+            return strpos($url, $publicUrl, 0) === 0;
89
+        });
90
+        return !empty($matchingUrls);
91
+    }
92 92
 }
Please login to merge, or discard this patch.
apps/dav/lib/DAV/SystemPrincipalBackend.php 1 patch
Indentation   +161 added lines, -161 removed lines patch added patch discarded remove patch
@@ -27,165 +27,165 @@
 block discarded – undo
27 27
 
28 28
 class SystemPrincipalBackend extends AbstractBackend {
29 29
 
30
-	/**
31
-	 * Returns a list of principals based on a prefix.
32
-	 *
33
-	 * This prefix will often contain something like 'principals'. You are only
34
-	 * expected to return principals that are in this base path.
35
-	 *
36
-	 * You are expected to return at least a 'uri' for every user, you can
37
-	 * return any additional properties if you wish so. Common properties are:
38
-	 *   {DAV:}displayname
39
-	 *   {http://sabredav.org/ns}email-address - This is a custom SabreDAV
40
-	 *     field that's actually injected in a number of other properties. If
41
-	 *     you have an email address, use this property.
42
-	 *
43
-	 * @param string $prefixPath
44
-	 * @return array
45
-	 */
46
-	function getPrincipalsByPrefix($prefixPath) {
47
-		$principals = [];
48
-
49
-		if ($prefixPath === 'principals/system') {
50
-			$principals[] = [
51
-				'uri' => 'principals/system/system',
52
-				'{DAV:}displayname' => 'system',
53
-			];
54
-			$principals[] = [
55
-				'uri' => 'principals/system/public',
56
-				'{DAV:}displayname' => 'public',
57
-			];
58
-		}
59
-
60
-		return $principals;
61
-	}
62
-
63
-	/**
64
-	 * Returns a specific principal, specified by it's path.
65
-	 * The returned structure should be the exact same as from
66
-	 * getPrincipalsByPrefix.
67
-	 *
68
-	 * @param string $path
69
-	 * @return array
70
-	 */
71
-	function getPrincipalByPath($path) {
72
-
73
-		if ($path === 'principals/system/system') {
74
-			$principal = [
75
-				'uri' => 'principals/system/system',
76
-				'{DAV:}displayname' => 'system',
77
-			];
78
-			return $principal;
79
-		}
80
-		if ($path === 'principals/system/public') {
81
-			$principal = [
82
-				'uri' => 'principals/system/public',
83
-				'{DAV:}displayname' => 'public',
84
-			];
85
-			return $principal;
86
-		}
87
-
88
-		return null;
89
-	}
90
-
91
-	/**
92
-	 * Updates one ore more webdav properties on a principal.
93
-	 *
94
-	 * The list of mutations is stored in a Sabre\DAV\PropPatch object.
95
-	 * To do the actual updates, you must tell this object which properties
96
-	 * you're going to process with the handle() method.
97
-	 *
98
-	 * Calling the handle method is like telling the PropPatch object "I
99
-	 * promise I can handle updating this property".
100
-	 *
101
-	 * Read the PropPatch documentation for more info and examples.
102
-	 *
103
-	 * @param string $path
104
-	 * @param \Sabre\DAV\PropPatch $propPatch
105
-	 * @return void
106
-	 */
107
-	function updatePrincipal($path, \Sabre\DAV\PropPatch $propPatch) {
108
-	}
109
-
110
-	/**
111
-	 * This method is used to search for principals matching a set of
112
-	 * properties.
113
-	 *
114
-	 * This search is specifically used by RFC3744's principal-property-search
115
-	 * REPORT.
116
-	 *
117
-	 * The actual search should be a unicode-non-case-sensitive search. The
118
-	 * keys in searchProperties are the WebDAV property names, while the values
119
-	 * are the property values to search on.
120
-	 *
121
-	 * By default, if multiple properties are submitted to this method, the
122
-	 * various properties should be combined with 'AND'. If $test is set to
123
-	 * 'anyof', it should be combined using 'OR'.
124
-	 *
125
-	 * This method should simply return an array with full principal uri's.
126
-	 *
127
-	 * If somebody attempted to search on a property the backend does not
128
-	 * support, you should simply return 0 results.
129
-	 *
130
-	 * You can also just return 0 results if you choose to not support
131
-	 * searching at all, but keep in mind that this may stop certain features
132
-	 * from working.
133
-	 *
134
-	 * @param string $prefixPath
135
-	 * @param array $searchProperties
136
-	 * @param string $test
137
-	 * @return array
138
-	 */
139
-	function searchPrincipals($prefixPath, array $searchProperties, $test = 'allof') {
140
-		return [];
141
-	}
142
-
143
-	/**
144
-	 * Returns the list of members for a group-principal
145
-	 *
146
-	 * @param string $principal
147
-	 * @return array
148
-	 */
149
-	function getGroupMemberSet($principal) {
150
-		// TODO: for now the group principal has only one member, the user itself
151
-		$principal = $this->getPrincipalByPath($principal);
152
-		if (!$principal) {
153
-			throw new \Sabre\DAV\Exception('Principal not found');
154
-		}
155
-
156
-		return [$principal['uri']];
157
-	}
158
-
159
-	/**
160
-	 * Returns the list of groups a principal is a member of
161
-	 *
162
-	 * @param string $principal
163
-	 * @return array
164
-	 */
165
-	function getGroupMembership($principal) {
166
-		list($prefix, $name) = URLUtil::splitPath($principal);
167
-
168
-		if ($prefix === 'principals/system') {
169
-			$principal = $this->getPrincipalByPath($principal);
170
-			if (!$principal) {
171
-				throw new \Sabre\DAV\Exception('Principal not found');
172
-			}
173
-
174
-			return [];
175
-		}
176
-		return [];
177
-	}
178
-
179
-	/**
180
-	 * Updates the list of group members for a group principal.
181
-	 *
182
-	 * The principals should be passed as a list of uri's.
183
-	 *
184
-	 * @param string $principal
185
-	 * @param array $members
186
-	 * @return void
187
-	 */
188
-	function setGroupMemberSet($principal, array $members) {
189
-		throw new \Sabre\DAV\Exception('Setting members of the group is not supported yet');
190
-	}
30
+    /**
31
+     * Returns a list of principals based on a prefix.
32
+     *
33
+     * This prefix will often contain something like 'principals'. You are only
34
+     * expected to return principals that are in this base path.
35
+     *
36
+     * You are expected to return at least a 'uri' for every user, you can
37
+     * return any additional properties if you wish so. Common properties are:
38
+     *   {DAV:}displayname
39
+     *   {http://sabredav.org/ns}email-address - This is a custom SabreDAV
40
+     *     field that's actually injected in a number of other properties. If
41
+     *     you have an email address, use this property.
42
+     *
43
+     * @param string $prefixPath
44
+     * @return array
45
+     */
46
+    function getPrincipalsByPrefix($prefixPath) {
47
+        $principals = [];
48
+
49
+        if ($prefixPath === 'principals/system') {
50
+            $principals[] = [
51
+                'uri' => 'principals/system/system',
52
+                '{DAV:}displayname' => 'system',
53
+            ];
54
+            $principals[] = [
55
+                'uri' => 'principals/system/public',
56
+                '{DAV:}displayname' => 'public',
57
+            ];
58
+        }
59
+
60
+        return $principals;
61
+    }
62
+
63
+    /**
64
+     * Returns a specific principal, specified by it's path.
65
+     * The returned structure should be the exact same as from
66
+     * getPrincipalsByPrefix.
67
+     *
68
+     * @param string $path
69
+     * @return array
70
+     */
71
+    function getPrincipalByPath($path) {
72
+
73
+        if ($path === 'principals/system/system') {
74
+            $principal = [
75
+                'uri' => 'principals/system/system',
76
+                '{DAV:}displayname' => 'system',
77
+            ];
78
+            return $principal;
79
+        }
80
+        if ($path === 'principals/system/public') {
81
+            $principal = [
82
+                'uri' => 'principals/system/public',
83
+                '{DAV:}displayname' => 'public',
84
+            ];
85
+            return $principal;
86
+        }
87
+
88
+        return null;
89
+    }
90
+
91
+    /**
92
+     * Updates one ore more webdav properties on a principal.
93
+     *
94
+     * The list of mutations is stored in a Sabre\DAV\PropPatch object.
95
+     * To do the actual updates, you must tell this object which properties
96
+     * you're going to process with the handle() method.
97
+     *
98
+     * Calling the handle method is like telling the PropPatch object "I
99
+     * promise I can handle updating this property".
100
+     *
101
+     * Read the PropPatch documentation for more info and examples.
102
+     *
103
+     * @param string $path
104
+     * @param \Sabre\DAV\PropPatch $propPatch
105
+     * @return void
106
+     */
107
+    function updatePrincipal($path, \Sabre\DAV\PropPatch $propPatch) {
108
+    }
109
+
110
+    /**
111
+     * This method is used to search for principals matching a set of
112
+     * properties.
113
+     *
114
+     * This search is specifically used by RFC3744's principal-property-search
115
+     * REPORT.
116
+     *
117
+     * The actual search should be a unicode-non-case-sensitive search. The
118
+     * keys in searchProperties are the WebDAV property names, while the values
119
+     * are the property values to search on.
120
+     *
121
+     * By default, if multiple properties are submitted to this method, the
122
+     * various properties should be combined with 'AND'. If $test is set to
123
+     * 'anyof', it should be combined using 'OR'.
124
+     *
125
+     * This method should simply return an array with full principal uri's.
126
+     *
127
+     * If somebody attempted to search on a property the backend does not
128
+     * support, you should simply return 0 results.
129
+     *
130
+     * You can also just return 0 results if you choose to not support
131
+     * searching at all, but keep in mind that this may stop certain features
132
+     * from working.
133
+     *
134
+     * @param string $prefixPath
135
+     * @param array $searchProperties
136
+     * @param string $test
137
+     * @return array
138
+     */
139
+    function searchPrincipals($prefixPath, array $searchProperties, $test = 'allof') {
140
+        return [];
141
+    }
142
+
143
+    /**
144
+     * Returns the list of members for a group-principal
145
+     *
146
+     * @param string $principal
147
+     * @return array
148
+     */
149
+    function getGroupMemberSet($principal) {
150
+        // TODO: for now the group principal has only one member, the user itself
151
+        $principal = $this->getPrincipalByPath($principal);
152
+        if (!$principal) {
153
+            throw new \Sabre\DAV\Exception('Principal not found');
154
+        }
155
+
156
+        return [$principal['uri']];
157
+    }
158
+
159
+    /**
160
+     * Returns the list of groups a principal is a member of
161
+     *
162
+     * @param string $principal
163
+     * @return array
164
+     */
165
+    function getGroupMembership($principal) {
166
+        list($prefix, $name) = URLUtil::splitPath($principal);
167
+
168
+        if ($prefix === 'principals/system') {
169
+            $principal = $this->getPrincipalByPath($principal);
170
+            if (!$principal) {
171
+                throw new \Sabre\DAV\Exception('Principal not found');
172
+            }
173
+
174
+            return [];
175
+        }
176
+        return [];
177
+    }
178
+
179
+    /**
180
+     * Updates the list of group members for a group principal.
181
+     *
182
+     * The principals should be passed as a list of uri's.
183
+     *
184
+     * @param string $principal
185
+     * @param array $members
186
+     * @return void
187
+     */
188
+    function setGroupMemberSet($principal, array $members) {
189
+        throw new \Sabre\DAV\Exception('Setting members of the group is not supported yet');
190
+    }
191 191
 }
Please login to merge, or discard this patch.
apps/dav/lib/DAV/Sharing/Xml/Invite.php 1 patch
Indentation   +126 added lines, -126 removed lines patch added patch discarded remove patch
@@ -41,130 +41,130 @@
 block discarded – undo
41 41
  */
42 42
 class Invite implements XmlSerializable {
43 43
 
44
-	/**
45
-	 * The list of users a calendar has been shared to.
46
-	 *
47
-	 * @var array
48
-	 */
49
-	protected $users;
50
-
51
-	/**
52
-	 * The organizer contains information about the person who shared the
53
-	 * object.
54
-	 *
55
-	 * @var array|null
56
-	 */
57
-	protected $organizer;
58
-
59
-	/**
60
-	 * Creates the property.
61
-	 *
62
-	 * Users is an array. Each element of the array has the following
63
-	 * properties:
64
-	 *
65
-	 *   * href - Often a mailto: address
66
-	 *   * commonName - Optional, for example a first and lastname for a user.
67
-	 *   * status - One of the SharingPlugin::STATUS_* constants.
68
-	 *   * readOnly - true or false
69
-	 *   * summary - Optional, description of the share
70
-	 *
71
-	 * The organizer key is optional to specify. It's only useful when a
72
-	 * 'sharee' requests the sharing information.
73
-	 *
74
-	 * The organizer may have the following properties:
75
-	 *   * href - Often a mailto: address.
76
-	 *   * commonName - Optional human-readable name.
77
-	 *   * firstName - Optional first name.
78
-	 *   * lastName - Optional last name.
79
-	 *
80
-	 * If you wonder why these two structures are so different, I guess a
81
-	 * valid answer is that the current spec is still a draft.
82
-	 *
83
-	 * @param array $users
84
-	 */
85
-	function __construct(array $users, array $organizer = null) {
86
-
87
-		$this->users = $users;
88
-		$this->organizer = $organizer;
89
-
90
-	}
91
-
92
-	/**
93
-	 * Returns the list of users, as it was passed to the constructor.
94
-	 *
95
-	 * @return array
96
-	 */
97
-	function getValue() {
98
-
99
-		return $this->users;
100
-
101
-	}
102
-
103
-	/**
104
-	 * The xmlSerialize metod is called during xml writing.
105
-	 *
106
-	 * Use the $writer argument to write its own xml serialization.
107
-	 *
108
-	 * An important note: do _not_ create a parent element. Any element
109
-	 * implementing XmlSerializble should only ever write what's considered
110
-	 * its 'inner xml'.
111
-	 *
112
-	 * The parent of the current element is responsible for writing a
113
-	 * containing element.
114
-	 *
115
-	 * This allows serializers to be re-used for different element names.
116
-	 *
117
-	 * If you are opening new elements, you must also close them again.
118
-	 *
119
-	 * @param Writer $writer
120
-	 * @return void
121
-	 */
122
-	function xmlSerialize(Writer $writer) {
123
-
124
-		$cs = '{' . Plugin::NS_OWNCLOUD . '}';
125
-
126
-		if (!is_null($this->organizer)) {
127
-
128
-			$writer->startElement($cs . 'organizer');
129
-			$writer->writeElement('{DAV:}href', $this->organizer['href']);
130
-
131
-			if (isset($this->organizer['commonName']) && $this->organizer['commonName']) {
132
-				$writer->writeElement($cs . 'common-name', $this->organizer['commonName']);
133
-			}
134
-			if (isset($this->organizer['firstName']) && $this->organizer['firstName']) {
135
-				$writer->writeElement($cs . 'first-name', $this->organizer['firstName']);
136
-			}
137
-			if (isset($this->organizer['lastName']) && $this->organizer['lastName']) {
138
-				$writer->writeElement($cs . 'last-name', $this->organizer['lastName']);
139
-			}
140
-			$writer->endElement(); // organizer
141
-
142
-		}
143
-
144
-		foreach ($this->users as $user) {
145
-
146
-			$writer->startElement($cs . 'user');
147
-			$writer->writeElement('{DAV:}href', $user['href']);
148
-			if (isset($user['commonName']) && $user['commonName']) {
149
-				$writer->writeElement($cs . 'common-name', $user['commonName']);
150
-			}
151
-			$writer->writeElement($cs . 'invite-accepted');
152
-
153
-			$writer->startElement($cs . 'access');
154
-			if ($user['readOnly']) {
155
-				$writer->writeElement($cs . 'read');
156
-			} else {
157
-				$writer->writeElement($cs . 'read-write');
158
-			}
159
-			$writer->endElement(); // access
160
-
161
-			if (isset($user['summary']) && $user['summary']) {
162
-				$writer->writeElement($cs . 'summary', $user['summary']);
163
-			}
164
-
165
-			$writer->endElement(); //user
166
-
167
-		}
168
-
169
-	}
44
+    /**
45
+     * The list of users a calendar has been shared to.
46
+     *
47
+     * @var array
48
+     */
49
+    protected $users;
50
+
51
+    /**
52
+     * The organizer contains information about the person who shared the
53
+     * object.
54
+     *
55
+     * @var array|null
56
+     */
57
+    protected $organizer;
58
+
59
+    /**
60
+     * Creates the property.
61
+     *
62
+     * Users is an array. Each element of the array has the following
63
+     * properties:
64
+     *
65
+     *   * href - Often a mailto: address
66
+     *   * commonName - Optional, for example a first and lastname for a user.
67
+     *   * status - One of the SharingPlugin::STATUS_* constants.
68
+     *   * readOnly - true or false
69
+     *   * summary - Optional, description of the share
70
+     *
71
+     * The organizer key is optional to specify. It's only useful when a
72
+     * 'sharee' requests the sharing information.
73
+     *
74
+     * The organizer may have the following properties:
75
+     *   * href - Often a mailto: address.
76
+     *   * commonName - Optional human-readable name.
77
+     *   * firstName - Optional first name.
78
+     *   * lastName - Optional last name.
79
+     *
80
+     * If you wonder why these two structures are so different, I guess a
81
+     * valid answer is that the current spec is still a draft.
82
+     *
83
+     * @param array $users
84
+     */
85
+    function __construct(array $users, array $organizer = null) {
86
+
87
+        $this->users = $users;
88
+        $this->organizer = $organizer;
89
+
90
+    }
91
+
92
+    /**
93
+     * Returns the list of users, as it was passed to the constructor.
94
+     *
95
+     * @return array
96
+     */
97
+    function getValue() {
98
+
99
+        return $this->users;
100
+
101
+    }
102
+
103
+    /**
104
+     * The xmlSerialize metod is called during xml writing.
105
+     *
106
+     * Use the $writer argument to write its own xml serialization.
107
+     *
108
+     * An important note: do _not_ create a parent element. Any element
109
+     * implementing XmlSerializble should only ever write what's considered
110
+     * its 'inner xml'.
111
+     *
112
+     * The parent of the current element is responsible for writing a
113
+     * containing element.
114
+     *
115
+     * This allows serializers to be re-used for different element names.
116
+     *
117
+     * If you are opening new elements, you must also close them again.
118
+     *
119
+     * @param Writer $writer
120
+     * @return void
121
+     */
122
+    function xmlSerialize(Writer $writer) {
123
+
124
+        $cs = '{' . Plugin::NS_OWNCLOUD . '}';
125
+
126
+        if (!is_null($this->organizer)) {
127
+
128
+            $writer->startElement($cs . 'organizer');
129
+            $writer->writeElement('{DAV:}href', $this->organizer['href']);
130
+
131
+            if (isset($this->organizer['commonName']) && $this->organizer['commonName']) {
132
+                $writer->writeElement($cs . 'common-name', $this->organizer['commonName']);
133
+            }
134
+            if (isset($this->organizer['firstName']) && $this->organizer['firstName']) {
135
+                $writer->writeElement($cs . 'first-name', $this->organizer['firstName']);
136
+            }
137
+            if (isset($this->organizer['lastName']) && $this->organizer['lastName']) {
138
+                $writer->writeElement($cs . 'last-name', $this->organizer['lastName']);
139
+            }
140
+            $writer->endElement(); // organizer
141
+
142
+        }
143
+
144
+        foreach ($this->users as $user) {
145
+
146
+            $writer->startElement($cs . 'user');
147
+            $writer->writeElement('{DAV:}href', $user['href']);
148
+            if (isset($user['commonName']) && $user['commonName']) {
149
+                $writer->writeElement($cs . 'common-name', $user['commonName']);
150
+            }
151
+            $writer->writeElement($cs . 'invite-accepted');
152
+
153
+            $writer->startElement($cs . 'access');
154
+            if ($user['readOnly']) {
155
+                $writer->writeElement($cs . 'read');
156
+            } else {
157
+                $writer->writeElement($cs . 'read-write');
158
+            }
159
+            $writer->endElement(); // access
160
+
161
+            if (isset($user['summary']) && $user['summary']) {
162
+                $writer->writeElement($cs . 'summary', $user['summary']);
163
+            }
164
+
165
+            $writer->endElement(); //user
166
+
167
+        }
168
+
169
+    }
170 170
 }
Please login to merge, or discard this patch.
apps/dav/lib/DAV/Sharing/Plugin.php 1 patch
Indentation   +161 added lines, -161 removed lines patch added patch discarded remove patch
@@ -36,166 +36,166 @@
 block discarded – undo
36 36
 
37 37
 class Plugin extends ServerPlugin {
38 38
 
39
-	const NS_OWNCLOUD = 'http://owncloud.org/ns';
40
-
41
-	/** @var Auth */
42
-	private $auth;
43
-
44
-	/** @var IRequest */
45
-	private $request;
46
-
47
-	/**
48
-	 * Plugin constructor.
49
-	 *
50
-	 * @param Auth $authBackEnd
51
-	 * @param IRequest $request
52
-	 */
53
-	public function __construct(Auth $authBackEnd, IRequest $request) {
54
-		$this->auth = $authBackEnd;
55
-		$this->request = $request;
56
-	}
57
-
58
-	/**
59
-	 * Reference to SabreDAV server object.
60
-	 *
61
-	 * @var \Sabre\DAV\Server
62
-	 */
63
-	protected $server;
64
-
65
-	/**
66
-	 * This method should return a list of server-features.
67
-	 *
68
-	 * This is for example 'versioning' and is added to the DAV: header
69
-	 * in an OPTIONS response.
70
-	 *
71
-	 * @return string[]
72
-	 */
73
-	function getFeatures() {
74
-		return ['oc-resource-sharing'];
75
-	}
76
-
77
-	/**
78
-	 * Returns a plugin name.
79
-	 *
80
-	 * Using this name other plugins will be able to access other plugins
81
-	 * using Sabre\DAV\Server::getPlugin
82
-	 *
83
-	 * @return string
84
-	 */
85
-	function getPluginName() {
86
-		return 'oc-resource-sharing';
87
-	}
88
-
89
-	/**
90
-	 * This initializes the plugin.
91
-	 *
92
-	 * This function is called by Sabre\DAV\Server, after
93
-	 * addPlugin is called.
94
-	 *
95
-	 * This method should set up the required event subscriptions.
96
-	 *
97
-	 * @param Server $server
98
-	 * @return void
99
-	 */
100
-	function initialize(Server $server) {
101
-		$this->server = $server;
102
-		$this->server->xml->elementMap['{' . Plugin::NS_OWNCLOUD . '}share'] = 'OCA\\DAV\\DAV\\Sharing\\Xml\\ShareRequest';
103
-		$this->server->xml->elementMap['{' . Plugin::NS_OWNCLOUD . '}invite'] = 'OCA\\DAV\\DAV\\Sharing\\Xml\\Invite';
104
-
105
-		$this->server->on('method:POST', [$this, 'httpPost']);
106
-		$this->server->on('propFind',    [$this, 'propFind']);
107
-	}
108
-
109
-	/**
110
-	 * We intercept this to handle POST requests on a dav resource.
111
-	 *
112
-	 * @param RequestInterface $request
113
-	 * @param ResponseInterface $response
114
-	 * @return null|false
115
-	 */
116
-	function httpPost(RequestInterface $request, ResponseInterface $response) {
117
-
118
-		$path = $request->getPath();
119
-
120
-		// Only handling xml
121
-		$contentType = $request->getHeader('Content-Type');
122
-		if (strpos($contentType, 'application/xml') === false && strpos($contentType, 'text/xml') === false)
123
-			return;
124
-
125
-		// Making sure the node exists
126
-		try {
127
-			$node = $this->server->tree->getNodeForPath($path);
128
-		} catch (NotFound $e) {
129
-			return;
130
-		}
131
-
132
-		$requestBody = $request->getBodyAsString();
133
-
134
-		// If this request handler could not deal with this POST request, it
135
-		// will return 'null' and other plugins get a chance to handle the
136
-		// request.
137
-		//
138
-		// However, we already requested the full body. This is a problem,
139
-		// because a body can only be read once. This is why we preemptively
140
-		// re-populated the request body with the existing data.
141
-		$request->setBody($requestBody);
142
-
143
-		$message = $this->server->xml->parse($requestBody, $request->getUrl(), $documentType);
144
-
145
-		switch ($documentType) {
146
-
147
-			// Dealing with the 'share' document, which modified invitees on a
148
-			// calendar.
149
-			case '{' . self::NS_OWNCLOUD . '}share' :
150
-
151
-				// We can only deal with IShareableCalendar objects
152
-				if (!$node instanceof IShareable) {
153
-					return;
154
-				}
155
-
156
-				$this->server->transactionType = 'post-oc-resource-share';
157
-
158
-				// Getting ACL info
159
-				$acl = $this->server->getPlugin('acl');
160
-
161
-				// If there's no ACL support, we allow everything
162
-				if ($acl) {
163
-					/** @var \Sabre\DAVACL\Plugin $acl */
164
-					$acl->checkPrivileges($path, '{DAV:}write');
165
-				}
166
-
167
-				$node->updateShares($message->set, $message->remove);
168
-
169
-				$response->setStatus(200);
170
-				// Adding this because sending a response body may cause issues,
171
-				// and I wanted some type of indicator the response was handled.
172
-				$response->setHeader('X-Sabre-Status', 'everything-went-well');
173
-
174
-				// Breaking the event chain
175
-				return false;
176
-		}
177
-	}
178
-
179
-	/**
180
-	 * This event is triggered when properties are requested for a certain
181
-	 * node.
182
-	 *
183
-	 * This allows us to inject any properties early.
184
-	 *
185
-	 * @param PropFind $propFind
186
-	 * @param INode $node
187
-	 * @return void
188
-	 */
189
-	function propFind(PropFind $propFind, INode $node) {
190
-		if ($node instanceof IShareable) {
191
-
192
-			$propFind->handle('{' . Plugin::NS_OWNCLOUD . '}invite', function() use ($node) {
193
-				return new Invite(
194
-					$node->getShares()
195
-				);
196
-			});
197
-
198
-		}
199
-	}
39
+    const NS_OWNCLOUD = 'http://owncloud.org/ns';
40
+
41
+    /** @var Auth */
42
+    private $auth;
43
+
44
+    /** @var IRequest */
45
+    private $request;
46
+
47
+    /**
48
+     * Plugin constructor.
49
+     *
50
+     * @param Auth $authBackEnd
51
+     * @param IRequest $request
52
+     */
53
+    public function __construct(Auth $authBackEnd, IRequest $request) {
54
+        $this->auth = $authBackEnd;
55
+        $this->request = $request;
56
+    }
57
+
58
+    /**
59
+     * Reference to SabreDAV server object.
60
+     *
61
+     * @var \Sabre\DAV\Server
62
+     */
63
+    protected $server;
64
+
65
+    /**
66
+     * This method should return a list of server-features.
67
+     *
68
+     * This is for example 'versioning' and is added to the DAV: header
69
+     * in an OPTIONS response.
70
+     *
71
+     * @return string[]
72
+     */
73
+    function getFeatures() {
74
+        return ['oc-resource-sharing'];
75
+    }
76
+
77
+    /**
78
+     * Returns a plugin name.
79
+     *
80
+     * Using this name other plugins will be able to access other plugins
81
+     * using Sabre\DAV\Server::getPlugin
82
+     *
83
+     * @return string
84
+     */
85
+    function getPluginName() {
86
+        return 'oc-resource-sharing';
87
+    }
88
+
89
+    /**
90
+     * This initializes the plugin.
91
+     *
92
+     * This function is called by Sabre\DAV\Server, after
93
+     * addPlugin is called.
94
+     *
95
+     * This method should set up the required event subscriptions.
96
+     *
97
+     * @param Server $server
98
+     * @return void
99
+     */
100
+    function initialize(Server $server) {
101
+        $this->server = $server;
102
+        $this->server->xml->elementMap['{' . Plugin::NS_OWNCLOUD . '}share'] = 'OCA\\DAV\\DAV\\Sharing\\Xml\\ShareRequest';
103
+        $this->server->xml->elementMap['{' . Plugin::NS_OWNCLOUD . '}invite'] = 'OCA\\DAV\\DAV\\Sharing\\Xml\\Invite';
104
+
105
+        $this->server->on('method:POST', [$this, 'httpPost']);
106
+        $this->server->on('propFind',    [$this, 'propFind']);
107
+    }
108
+
109
+    /**
110
+     * We intercept this to handle POST requests on a dav resource.
111
+     *
112
+     * @param RequestInterface $request
113
+     * @param ResponseInterface $response
114
+     * @return null|false
115
+     */
116
+    function httpPost(RequestInterface $request, ResponseInterface $response) {
117
+
118
+        $path = $request->getPath();
119
+
120
+        // Only handling xml
121
+        $contentType = $request->getHeader('Content-Type');
122
+        if (strpos($contentType, 'application/xml') === false && strpos($contentType, 'text/xml') === false)
123
+            return;
124
+
125
+        // Making sure the node exists
126
+        try {
127
+            $node = $this->server->tree->getNodeForPath($path);
128
+        } catch (NotFound $e) {
129
+            return;
130
+        }
131
+
132
+        $requestBody = $request->getBodyAsString();
133
+
134
+        // If this request handler could not deal with this POST request, it
135
+        // will return 'null' and other plugins get a chance to handle the
136
+        // request.
137
+        //
138
+        // However, we already requested the full body. This is a problem,
139
+        // because a body can only be read once. This is why we preemptively
140
+        // re-populated the request body with the existing data.
141
+        $request->setBody($requestBody);
142
+
143
+        $message = $this->server->xml->parse($requestBody, $request->getUrl(), $documentType);
144
+
145
+        switch ($documentType) {
146
+
147
+            // Dealing with the 'share' document, which modified invitees on a
148
+            // calendar.
149
+            case '{' . self::NS_OWNCLOUD . '}share' :
150
+
151
+                // We can only deal with IShareableCalendar objects
152
+                if (!$node instanceof IShareable) {
153
+                    return;
154
+                }
155
+
156
+                $this->server->transactionType = 'post-oc-resource-share';
157
+
158
+                // Getting ACL info
159
+                $acl = $this->server->getPlugin('acl');
160
+
161
+                // If there's no ACL support, we allow everything
162
+                if ($acl) {
163
+                    /** @var \Sabre\DAVACL\Plugin $acl */
164
+                    $acl->checkPrivileges($path, '{DAV:}write');
165
+                }
166
+
167
+                $node->updateShares($message->set, $message->remove);
168
+
169
+                $response->setStatus(200);
170
+                // Adding this because sending a response body may cause issues,
171
+                // and I wanted some type of indicator the response was handled.
172
+                $response->setHeader('X-Sabre-Status', 'everything-went-well');
173
+
174
+                // Breaking the event chain
175
+                return false;
176
+        }
177
+    }
178
+
179
+    /**
180
+     * This event is triggered when properties are requested for a certain
181
+     * node.
182
+     *
183
+     * This allows us to inject any properties early.
184
+     *
185
+     * @param PropFind $propFind
186
+     * @param INode $node
187
+     * @return void
188
+     */
189
+    function propFind(PropFind $propFind, INode $node) {
190
+        if ($node instanceof IShareable) {
191
+
192
+            $propFind->handle('{' . Plugin::NS_OWNCLOUD . '}invite', function() use ($node) {
193
+                return new Invite(
194
+                    $node->getShares()
195
+                );
196
+            });
197
+
198
+        }
199
+    }
200 200
 
201 201
 }
Please login to merge, or discard this patch.