Completed
Pull Request — master (#3825)
by Björn
15:58
created
apps/federation/lib/Middleware/AddServerMiddleware.php 1 patch
Indentation   +34 added lines, -34 removed lines patch added patch discarded remove patch
@@ -34,45 +34,45 @@
 block discarded – undo
34 34
 
35 35
 class AddServerMiddleware extends Middleware {
36 36
 
37
-	/** @var  string */
38
-	protected $appName;
37
+    /** @var  string */
38
+    protected $appName;
39 39
 
40
-	/** @var  IL10N */
41
-	protected $l;
40
+    /** @var  IL10N */
41
+    protected $l;
42 42
 
43
-	/** @var  ILogger */
44
-	protected $logger;
43
+    /** @var  ILogger */
44
+    protected $logger;
45 45
 
46
-	public function __construct($appName, IL10N $l, ILogger $logger) {
47
-		$this->appName = $appName;
48
-		$this->l = $l;
49
-		$this->logger = $logger;
50
-	}
46
+    public function __construct($appName, IL10N $l, ILogger $logger) {
47
+        $this->appName = $appName;
48
+        $this->l = $l;
49
+        $this->logger = $logger;
50
+    }
51 51
 
52
-	/**
53
-	 * Log error message and return a response which can be displayed to the user
54
-	 *
55
-	 * @param \OCP\AppFramework\Controller $controller
56
-	 * @param string $methodName
57
-	 * @param \Exception $exception
58
-	 * @return JSONResponse
59
-	 */
60
-	public function afterException($controller, $methodName, \Exception $exception) {
61
-		if (($controller instanceof SettingsController) === false) {
62
-			throw $exception;
63
-		}
64
-		$this->logger->error($exception->getMessage(), ['app' => $this->appName]);
65
-		if ($exception instanceof HintException) {
66
-			$message = $exception->getHint();
67
-		} else {
68
-			$message = $exception->getMessage();
69
-		}
52
+    /**
53
+     * Log error message and return a response which can be displayed to the user
54
+     *
55
+     * @param \OCP\AppFramework\Controller $controller
56
+     * @param string $methodName
57
+     * @param \Exception $exception
58
+     * @return JSONResponse
59
+     */
60
+    public function afterException($controller, $methodName, \Exception $exception) {
61
+        if (($controller instanceof SettingsController) === false) {
62
+            throw $exception;
63
+        }
64
+        $this->logger->error($exception->getMessage(), ['app' => $this->appName]);
65
+        if ($exception instanceof HintException) {
66
+            $message = $exception->getHint();
67
+        } else {
68
+            $message = $exception->getMessage();
69
+        }
70 70
 
71
-		return new JSONResponse(
72
-			['message' => $message],
73
-			Http::STATUS_BAD_REQUEST
74
-		);
71
+        return new JSONResponse(
72
+            ['message' => $message],
73
+            Http::STATUS_BAD_REQUEST
74
+        );
75 75
 
76
-	}
76
+    }
77 77
 
78 78
 }
Please login to merge, or discard this patch.
apps/dav/lib/CardDAV/Converter.php 2 patches
Spacing   +2 added lines, -2 removed lines patch added patch discarded remove patch
@@ -119,9 +119,9 @@
 block discarded – undo
119 119
 		$elements = explode(' ', $fullName);
120 120
 		$result = ['', '', '', '', ''];
121 121
 		if (count($elements) > 2) {
122
-			$result[0] = implode(' ', array_slice($elements, count($elements)-1));
122
+			$result[0] = implode(' ', array_slice($elements, count($elements) - 1));
123 123
 			$result[1] = $elements[0];
124
-			$result[2] = implode(' ', array_slice($elements, 1, count($elements)-2));
124
+			$result[2] = implode(' ', array_slice($elements, 1, count($elements) - 2));
125 125
 		} elseif (count($elements) === 2) {
126 126
 			$result[0] = $elements[1];
127 127
 			$result[1] = $elements[0];
Please login to merge, or discard this patch.
Indentation   +115 added lines, -115 removed lines patch added patch discarded remove patch
@@ -30,120 +30,120 @@
 block discarded – undo
30 30
 
31 31
 class Converter {
32 32
 
33
-	/** @var AccountManager */
34
-	private $accountManager;
35
-
36
-	/**
37
-	 * Converter constructor.
38
-	 *
39
-	 * @param AccountManager $accountManager
40
-	 */
41
-	public function __construct(AccountManager $accountManager) {
42
-		$this->accountManager = $accountManager;
43
-	}
44
-
45
-	/**
46
-	 * @param IUser $user
47
-	 * @return VCard|null
48
-	 */
49
-	public function createCardFromUser(IUser $user) {
50
-
51
-		$userData = $this->accountManager->getUser($user);
52
-
53
-		$uid = $user->getUID();
54
-		$cloudId = $user->getCloudId();
55
-		$image = $this->getAvatarImage($user);
56
-
57
-		$vCard = new VCard();
58
-		$vCard->VERSION = '3.0';
59
-		$vCard->UID = $uid;
60
-
61
-		$publish = false;
62
-
63
-		foreach ($userData as $property => $value) {
64
-
65
-			$shareWithTrustedServers =
66
-				$value['scope'] === AccountManager::VISIBILITY_CONTACTS_ONLY ||
67
-				$value['scope'] === AccountManager::VISIBILITY_PUBLIC;
68
-
69
-			$emptyValue = !isset($value['value']) || $value['value'] === '';
70
-			$noImage = $image === null;
71
-
72
-			if ($shareWithTrustedServers && (!$emptyValue || !$noImage)) {
73
-				$publish = true;
74
-				switch ($property) {
75
-					case AccountManager::PROPERTY_DISPLAYNAME:
76
-						$vCard->add(new Text($vCard, 'FN', $value['value']));
77
-						$vCard->add(new Text($vCard, 'N', $this->splitFullName($value['value'])));
78
-						break;
79
-					case AccountManager::PROPERTY_AVATAR:
80
-						if ($image !== null) {
81
-							$vCard->add('PHOTO', $image->data(), ['ENCODING' => 'b', 'TYPE' => $image->mimeType()]);
82
-						}
83
-						break;
84
-					case AccountManager::PROPERTY_EMAIL:
85
-						$vCard->add(new Text($vCard, 'EMAIL', $value['value'], ['TYPE' => 'OTHER']));
86
-						break;
87
-					case AccountManager::PROPERTY_WEBSITE:
88
-						$vCard->add(new Text($vCard, 'URL', $value['value']));
89
-						break;
90
-					case AccountManager::PROPERTY_PHONE:
91
-						$vCard->add(new Text($vCard, 'TEL', $value['value'], ['TYPE' => 'OTHER']));
92
-						break;
93
-					case AccountManager::PROPERTY_ADDRESS:
94
-						$vCard->add(new Text($vCard, 'ADR', $value['value'], ['TYPE' => 'OTHER']));
95
-						break;
96
-					case AccountManager::PROPERTY_TWITTER:
97
-						$vCard->add(new Text($vCard, 'X-SOCIALPROFILE', $value['value'], ['TYPE' => 'TWITTER']));
98
-						break;
99
-				}
100
-			}
101
-		}
102
-
103
-		if ($publish && !empty($cloudId)) {
104
-			$vCard->add(new Text($vCard, 'CLOUD', $cloudId));
105
-			$vCard->validate();
106
-			return $vCard;
107
-		}
108
-
109
-		return null;
110
-	}
111
-
112
-	/**
113
-	 * @param string $fullName
114
-	 * @return string[]
115
-	 */
116
-	public function splitFullName($fullName) {
117
-		// Very basic western style parsing. I'm not gonna implement
118
-		// https://github.com/android/platform_packages_providers_contactsprovider/blob/master/src/com/android/providers/contacts/NameSplitter.java ;)
119
-
120
-		$elements = explode(' ', $fullName);
121
-		$result = ['', '', '', '', ''];
122
-		if (count($elements) > 2) {
123
-			$result[0] = implode(' ', array_slice($elements, count($elements)-1));
124
-			$result[1] = $elements[0];
125
-			$result[2] = implode(' ', array_slice($elements, 1, count($elements)-2));
126
-		} elseif (count($elements) === 2) {
127
-			$result[0] = $elements[1];
128
-			$result[1] = $elements[0];
129
-		} else {
130
-			$result[0] = $elements[0];
131
-		}
132
-
133
-		return $result;
134
-	}
135
-
136
-	/**
137
-	 * @param IUser $user
138
-	 * @return null|IImage
139
-	 */
140
-	private function getAvatarImage(IUser $user) {
141
-		try {
142
-			$image = $user->getAvatarImage(-1);
143
-			return $image;
144
-		} catch (\Exception $ex) {
145
-			return null;
146
-		}
147
-	}
33
+    /** @var AccountManager */
34
+    private $accountManager;
35
+
36
+    /**
37
+     * Converter constructor.
38
+     *
39
+     * @param AccountManager $accountManager
40
+     */
41
+    public function __construct(AccountManager $accountManager) {
42
+        $this->accountManager = $accountManager;
43
+    }
44
+
45
+    /**
46
+     * @param IUser $user
47
+     * @return VCard|null
48
+     */
49
+    public function createCardFromUser(IUser $user) {
50
+
51
+        $userData = $this->accountManager->getUser($user);
52
+
53
+        $uid = $user->getUID();
54
+        $cloudId = $user->getCloudId();
55
+        $image = $this->getAvatarImage($user);
56
+
57
+        $vCard = new VCard();
58
+        $vCard->VERSION = '3.0';
59
+        $vCard->UID = $uid;
60
+
61
+        $publish = false;
62
+
63
+        foreach ($userData as $property => $value) {
64
+
65
+            $shareWithTrustedServers =
66
+                $value['scope'] === AccountManager::VISIBILITY_CONTACTS_ONLY ||
67
+                $value['scope'] === AccountManager::VISIBILITY_PUBLIC;
68
+
69
+            $emptyValue = !isset($value['value']) || $value['value'] === '';
70
+            $noImage = $image === null;
71
+
72
+            if ($shareWithTrustedServers && (!$emptyValue || !$noImage)) {
73
+                $publish = true;
74
+                switch ($property) {
75
+                    case AccountManager::PROPERTY_DISPLAYNAME:
76
+                        $vCard->add(new Text($vCard, 'FN', $value['value']));
77
+                        $vCard->add(new Text($vCard, 'N', $this->splitFullName($value['value'])));
78
+                        break;
79
+                    case AccountManager::PROPERTY_AVATAR:
80
+                        if ($image !== null) {
81
+                            $vCard->add('PHOTO', $image->data(), ['ENCODING' => 'b', 'TYPE' => $image->mimeType()]);
82
+                        }
83
+                        break;
84
+                    case AccountManager::PROPERTY_EMAIL:
85
+                        $vCard->add(new Text($vCard, 'EMAIL', $value['value'], ['TYPE' => 'OTHER']));
86
+                        break;
87
+                    case AccountManager::PROPERTY_WEBSITE:
88
+                        $vCard->add(new Text($vCard, 'URL', $value['value']));
89
+                        break;
90
+                    case AccountManager::PROPERTY_PHONE:
91
+                        $vCard->add(new Text($vCard, 'TEL', $value['value'], ['TYPE' => 'OTHER']));
92
+                        break;
93
+                    case AccountManager::PROPERTY_ADDRESS:
94
+                        $vCard->add(new Text($vCard, 'ADR', $value['value'], ['TYPE' => 'OTHER']));
95
+                        break;
96
+                    case AccountManager::PROPERTY_TWITTER:
97
+                        $vCard->add(new Text($vCard, 'X-SOCIALPROFILE', $value['value'], ['TYPE' => 'TWITTER']));
98
+                        break;
99
+                }
100
+            }
101
+        }
102
+
103
+        if ($publish && !empty($cloudId)) {
104
+            $vCard->add(new Text($vCard, 'CLOUD', $cloudId));
105
+            $vCard->validate();
106
+            return $vCard;
107
+        }
108
+
109
+        return null;
110
+    }
111
+
112
+    /**
113
+     * @param string $fullName
114
+     * @return string[]
115
+     */
116
+    public function splitFullName($fullName) {
117
+        // Very basic western style parsing. I'm not gonna implement
118
+        // https://github.com/android/platform_packages_providers_contactsprovider/blob/master/src/com/android/providers/contacts/NameSplitter.java ;)
119
+
120
+        $elements = explode(' ', $fullName);
121
+        $result = ['', '', '', '', ''];
122
+        if (count($elements) > 2) {
123
+            $result[0] = implode(' ', array_slice($elements, count($elements)-1));
124
+            $result[1] = $elements[0];
125
+            $result[2] = implode(' ', array_slice($elements, 1, count($elements)-2));
126
+        } elseif (count($elements) === 2) {
127
+            $result[0] = $elements[1];
128
+            $result[1] = $elements[0];
129
+        } else {
130
+            $result[0] = $elements[0];
131
+        }
132
+
133
+        return $result;
134
+    }
135
+
136
+    /**
137
+     * @param IUser $user
138
+     * @return null|IImage
139
+     */
140
+    private function getAvatarImage(IUser $user) {
141
+        try {
142
+            $image = $user->getAvatarImage(-1);
143
+            return $image;
144
+        } catch (\Exception $ex) {
145
+            return null;
146
+        }
147
+    }
148 148
 
149 149
 }
Please login to merge, or discard this patch.
apps/dav/lib/CardDAV/SyncService.php 2 patches
Spacing   +5 added lines, -5 removed lines patch added patch discarded remove patch
@@ -99,7 +99,7 @@  discard block
 block discarded – undo
99 99
 			if ($ex->getCode() === Http::STATUS_UNAUTHORIZED) {
100 100
 				// remote server revoked access to the address book, remove it
101 101
 				$this->backend->deleteAddressBook($addressBookId);
102
-				$this->logger->info('Authorization failed, remove address book: ' . $url, ['app' => 'dav']);
102
+				$this->logger->info('Authorization failed, remove address book: '.$url, ['app' => 'dav']);
103 103
 				throw $ex;
104 104
 			}
105 105
 		}
@@ -149,7 +149,7 @@  discard block
 block discarded – undo
149 149
 	 */
150 150
 	protected function getClient($url, $userName, $sharedSecret) {
151 151
 		$settings = [
152
-			'baseUri' => $url . '/',
152
+			'baseUri' => $url.'/',
153 153
 			'userName' => $userName,
154 154
 			'password' => $sharedSecret,
155 155
 		];
@@ -269,7 +269,7 @@  discard block
 block discarded – undo
269 269
 	 */
270 270
 	public function deleteUser($userOrCardId) {
271 271
 		$systemAddressBook = $this->getLocalSystemAddressBook();
272
-		if ($userOrCardId instanceof IUser){
272
+		if ($userOrCardId instanceof IUser) {
273 273
 			$name = $userOrCardId->getBackendClassName();
274 274
 			$userId = $userOrCardId->getUID();
275 275
 
@@ -285,7 +285,7 @@  discard block
 block discarded – undo
285 285
 		if (is_null($this->localSystemAddressBook)) {
286 286
 			$systemPrincipal = "principals/system/system";
287 287
 			$this->localSystemAddressBook = $this->ensureSystemAddressBookExists($systemPrincipal, 'system', [
288
-				'{' . Plugin::NS_CARDDAV . '}addressbook-description' => 'System addressbook which holds all users of this instance'
288
+				'{'.Plugin::NS_CARDDAV.'}addressbook-description' => 'System addressbook which holds all users of this instance'
289 289
 			]);
290 290
 		}
291 291
 
@@ -303,7 +303,7 @@  discard block
 block discarded – undo
303 303
 
304 304
 		// remove no longer existing
305 305
 		$allCards = $this->backend->getCards($systemAddressBook['id']);
306
-		foreach($allCards as $card) {
306
+		foreach ($allCards as $card) {
307 307
 			$vCard = Reader::read($card['carddata']);
308 308
 			$uid = $vCard->UID->getValue();
309 309
 			// load backend and see if user exists
Please login to merge, or discard this patch.
Indentation   +288 added lines, -288 removed lines patch added patch discarded remove patch
@@ -38,294 +38,294 @@
 block discarded – undo
38 38
 
39 39
 class SyncService {
40 40
 
41
-	/** @var CardDavBackend */
42
-	private $backend;
43
-
44
-	/** @var IUserManager */
45
-	private $userManager;
46
-
47
-	/** @var ILogger */
48
-	private $logger;
49
-
50
-	/** @var array */
51
-	private $localSystemAddressBook;
52
-
53
-	/** @var AccountManager */
54
-	private $accountManager;
55
-
56
-	/** @var string */
57
-	protected $certPath;
58
-
59
-	/**
60
-	 * SyncService constructor.
61
-	 *
62
-	 * @param CardDavBackend $backend
63
-	 * @param IUserManager $userManager
64
-	 * @param ILogger $logger
65
-	 * @param AccountManager $accountManager
66
-	 */
67
-	public function __construct(CardDavBackend $backend, IUserManager $userManager, ILogger $logger, AccountManager $accountManager) {
68
-		$this->backend = $backend;
69
-		$this->userManager = $userManager;
70
-		$this->logger = $logger;
71
-		$this->accountManager = $accountManager;
72
-	}
73
-
74
-	/**
75
-	 * @param string $url
76
-	 * @param string $userName
77
-	 * @param string $sharedSecret
78
-	 * @param string $syncToken
79
-	 * @param int $targetBookId
80
-	 * @param string $targetPrincipal
81
-	 * @param array $targetProperties
82
-	 * @return string
83
-	 * @throws \Exception
84
-	 */
85
-	public function syncRemoteAddressBook($url, $userName, $sharedSecret, $syncToken, $targetBookId, $targetPrincipal, $targetProperties) {
86
-		// 1. create addressbook
87
-		$book = $this->ensureSystemAddressBookExists($targetPrincipal, $targetBookId, $targetProperties);
88
-		$addressBookId = $book['id'];
89
-
90
-		// 2. query changes
91
-		try {
92
-			$response = $this->requestSyncReport($url, $userName, $sharedSecret, $syncToken);
93
-		} catch (ClientHttpException $ex) {
94
-			if ($ex->getCode() === Http::STATUS_UNAUTHORIZED) {
95
-				// remote server revoked access to the address book, remove it
96
-				$this->backend->deleteAddressBook($addressBookId);
97
-				$this->logger->info('Authorization failed, remove address book: ' . $url, ['app' => 'dav']);
98
-				throw $ex;
99
-			}
100
-		}
101
-
102
-		// 3. apply changes
103
-		// TODO: use multi-get for download
104
-		foreach ($response['response'] as $resource => $status) {
105
-			$cardUri = basename($resource);
106
-			if (isset($status[200])) {
107
-				$vCard = $this->download($url, $sharedSecret, $resource);
108
-				$existingCard = $this->backend->getCard($addressBookId, $cardUri);
109
-				if ($existingCard === false) {
110
-					$this->backend->createCard($addressBookId, $cardUri, $vCard['body']);
111
-				} else {
112
-					$this->backend->updateCard($addressBookId, $cardUri, $vCard['body']);
113
-				}
114
-			} else {
115
-				$this->backend->deleteCard($addressBookId, $cardUri);
116
-			}
117
-		}
118
-
119
-		return $response['token'];
120
-	}
121
-
122
-	/**
123
-	 * @param string $principal
124
-	 * @param string $id
125
-	 * @param array $properties
126
-	 * @return array|null
127
-	 * @throws \Sabre\DAV\Exception\BadRequest
128
-	 */
129
-	public function ensureSystemAddressBookExists($principal, $id, $properties) {
130
-		$book = $this->backend->getAddressBooksByUri($principal, $id);
131
-		if (!is_null($book)) {
132
-			return $book;
133
-		}
134
-		$this->backend->createAddressBook($principal, $id, $properties);
135
-
136
-		return $this->backend->getAddressBooksByUri($principal, $id);
137
-	}
138
-
139
-	/**
140
-	 * Check if there is a valid certPath we should use
141
-	 */
142
-	protected function getCertPath() {
143
-
144
-		// we already have a valid certPath
145
-		if ($this->certPath) {
146
-			return;
147
-		}
148
-
149
-		/** @var ICertificateManager $certManager */
150
-		$certManager = \OC::$server->getCertificateManager(null);
151
-		$certPath = $certManager->getAbsoluteBundlePath();
152
-		if (file_exists($certPath)) {
153
-			$this->certPath = $certPath;
154
-		}
155
-	}
156
-
157
-	/**
158
-	 * @param string $url
159
-	 * @param string $userName
160
-	 * @param string $sharedSecret
161
-	 * @return Client
162
-	 */
163
-	protected function getClient($url, $userName, $sharedSecret) {
164
-		$settings = [
165
-			'baseUri' => $url . '/',
166
-			'userName' => $userName,
167
-			'password' => $sharedSecret,
168
-		];
169
-		$client = new Client($settings);
170
-		$this->getCertPath();
171
-		$client->setThrowExceptions(true);
172
-
173
-		if (strpos($url, 'http://') !== 0 && $this->certPath) {
174
-			$client->addCurlSetting(CURLOPT_CAINFO, $this->certPath);
175
-		}
176
-
177
-		return $client;
178
-	}
179
-
180
-	/**
181
-	 * @param string $url
182
-	 * @param string $userName
183
-	 * @param string $sharedSecret
184
-	 * @param string $syncToken
185
-	 * @return array
186
-	 */
187
-	protected function requestSyncReport($url, $userName, $sharedSecret, $syncToken) {
188
-		$client = $this->getClient($url, $userName, $sharedSecret);
189
-
190
-		$addressBookUrl = "remote.php/dav/addressbooks/system/system/system";
191
-		$body = $this->buildSyncCollectionRequestBody($syncToken);
192
-
193
-		$response = $client->request('REPORT', $addressBookUrl, $body, [
194
-			'Content-Type' => 'application/xml'
195
-		]);
196
-
197
-		return $this->parseMultiStatus($response['body']);
198
-	}
199
-
200
-	/**
201
-	 * @param string $url
202
-	 * @param string $sharedSecret
203
-	 * @param string $resourcePath
204
-	 * @return array
205
-	 */
206
-	protected function download($url, $sharedSecret, $resourcePath) {
207
-		$client = $this->getClient($url, 'system', $sharedSecret);
208
-		return $client->request('GET', $resourcePath);
209
-	}
210
-
211
-	/**
212
-	 * @param string|null $syncToken
213
-	 * @return string
214
-	 */
215
-	private function buildSyncCollectionRequestBody($syncToken) {
216
-
217
-		$dom = new \DOMDocument('1.0', 'UTF-8');
218
-		$dom->formatOutput = true;
219
-		$root = $dom->createElementNS('DAV:', 'd:sync-collection');
220
-		$sync = $dom->createElement('d:sync-token', $syncToken);
221
-		$prop = $dom->createElement('d:prop');
222
-		$cont = $dom->createElement('d:getcontenttype');
223
-		$etag = $dom->createElement('d:getetag');
224
-
225
-		$prop->appendChild($cont);
226
-		$prop->appendChild($etag);
227
-		$root->appendChild($sync);
228
-		$root->appendChild($prop);
229
-		$dom->appendChild($root);
230
-		$body = $dom->saveXML();
231
-
232
-		return $body;
233
-	}
234
-
235
-	/**
236
-	 * @param string $body
237
-	 * @return array
238
-	 * @throws \Sabre\Xml\ParseException
239
-	 */
240
-	private function parseMultiStatus($body) {
241
-		$xml = new Service();
242
-
243
-		/** @var MultiStatus $multiStatus */
244
-		$multiStatus = $xml->expect('{DAV:}multistatus', $body);
245
-
246
-		$result = [];
247
-		foreach ($multiStatus->getResponses() as $response) {
248
-			$result[$response->getHref()] = $response->getResponseProperties();
249
-		}
250
-
251
-		return ['response' => $result, 'token' => $multiStatus->getSyncToken()];
252
-	}
253
-
254
-	/**
255
-	 * @param IUser $user
256
-	 */
257
-	public function updateUser($user) {
258
-		$systemAddressBook = $this->getLocalSystemAddressBook();
259
-		$addressBookId = $systemAddressBook['id'];
260
-		$converter = new Converter($this->accountManager);
261
-		$name = $user->getBackendClassName();
262
-		$userId = $user->getUID();
263
-
264
-		$cardId = "$name:$userId.vcf";
265
-		$card = $this->backend->getCard($addressBookId, $cardId);
266
-		if ($card === false) {
267
-			$vCard = $converter->createCardFromUser($user);
268
-			if ($vCard !== null) {
269
-				$this->backend->createCard($addressBookId, $cardId, $vCard->serialize());
270
-			}
271
-		} else {
272
-			$vCard = $converter->createCardFromUser($user);
273
-			if (is_null($vCard)) {
274
-				$this->backend->deleteCard($addressBookId, $cardId);
275
-			} else {
276
-				$this->backend->updateCard($addressBookId, $cardId, $vCard->serialize());
277
-			}
278
-		}
279
-	}
280
-
281
-	/**
282
-	 * @param IUser|string $userOrCardId
283
-	 */
284
-	public function deleteUser($userOrCardId) {
285
-		$systemAddressBook = $this->getLocalSystemAddressBook();
286
-		if ($userOrCardId instanceof IUser){
287
-			$name = $userOrCardId->getBackendClassName();
288
-			$userId = $userOrCardId->getUID();
289
-
290
-			$userOrCardId = "$name:$userId.vcf";
291
-		}
292
-		$this->backend->deleteCard($systemAddressBook['id'], $userOrCardId);
293
-	}
294
-
295
-	/**
296
-	 * @return array|null
297
-	 */
298
-	public function getLocalSystemAddressBook() {
299
-		if (is_null($this->localSystemAddressBook)) {
300
-			$systemPrincipal = "principals/system/system";
301
-			$this->localSystemAddressBook = $this->ensureSystemAddressBookExists($systemPrincipal, 'system', [
302
-				'{' . Plugin::NS_CARDDAV . '}addressbook-description' => 'System addressbook which holds all users of this instance'
303
-			]);
304
-		}
305
-
306
-		return $this->localSystemAddressBook;
307
-	}
308
-
309
-	public function syncInstance(\Closure $progressCallback = null) {
310
-		$systemAddressBook = $this->getLocalSystemAddressBook();
311
-		$this->userManager->callForAllUsers(function($user) use ($systemAddressBook, $progressCallback) {
312
-			$this->updateUser($user);
313
-			if (!is_null($progressCallback)) {
314
-				$progressCallback();
315
-			}
316
-		});
317
-
318
-		// remove no longer existing
319
-		$allCards = $this->backend->getCards($systemAddressBook['id']);
320
-		foreach($allCards as $card) {
321
-			$vCard = Reader::read($card['carddata']);
322
-			$uid = $vCard->UID->getValue();
323
-			// load backend and see if user exists
324
-			if (!$this->userManager->userExists($uid)) {
325
-				$this->deleteUser($card['uri']);
326
-			}
327
-		}
328
-	}
41
+    /** @var CardDavBackend */
42
+    private $backend;
43
+
44
+    /** @var IUserManager */
45
+    private $userManager;
46
+
47
+    /** @var ILogger */
48
+    private $logger;
49
+
50
+    /** @var array */
51
+    private $localSystemAddressBook;
52
+
53
+    /** @var AccountManager */
54
+    private $accountManager;
55
+
56
+    /** @var string */
57
+    protected $certPath;
58
+
59
+    /**
60
+     * SyncService constructor.
61
+     *
62
+     * @param CardDavBackend $backend
63
+     * @param IUserManager $userManager
64
+     * @param ILogger $logger
65
+     * @param AccountManager $accountManager
66
+     */
67
+    public function __construct(CardDavBackend $backend, IUserManager $userManager, ILogger $logger, AccountManager $accountManager) {
68
+        $this->backend = $backend;
69
+        $this->userManager = $userManager;
70
+        $this->logger = $logger;
71
+        $this->accountManager = $accountManager;
72
+    }
73
+
74
+    /**
75
+     * @param string $url
76
+     * @param string $userName
77
+     * @param string $sharedSecret
78
+     * @param string $syncToken
79
+     * @param int $targetBookId
80
+     * @param string $targetPrincipal
81
+     * @param array $targetProperties
82
+     * @return string
83
+     * @throws \Exception
84
+     */
85
+    public function syncRemoteAddressBook($url, $userName, $sharedSecret, $syncToken, $targetBookId, $targetPrincipal, $targetProperties) {
86
+        // 1. create addressbook
87
+        $book = $this->ensureSystemAddressBookExists($targetPrincipal, $targetBookId, $targetProperties);
88
+        $addressBookId = $book['id'];
89
+
90
+        // 2. query changes
91
+        try {
92
+            $response = $this->requestSyncReport($url, $userName, $sharedSecret, $syncToken);
93
+        } catch (ClientHttpException $ex) {
94
+            if ($ex->getCode() === Http::STATUS_UNAUTHORIZED) {
95
+                // remote server revoked access to the address book, remove it
96
+                $this->backend->deleteAddressBook($addressBookId);
97
+                $this->logger->info('Authorization failed, remove address book: ' . $url, ['app' => 'dav']);
98
+                throw $ex;
99
+            }
100
+        }
101
+
102
+        // 3. apply changes
103
+        // TODO: use multi-get for download
104
+        foreach ($response['response'] as $resource => $status) {
105
+            $cardUri = basename($resource);
106
+            if (isset($status[200])) {
107
+                $vCard = $this->download($url, $sharedSecret, $resource);
108
+                $existingCard = $this->backend->getCard($addressBookId, $cardUri);
109
+                if ($existingCard === false) {
110
+                    $this->backend->createCard($addressBookId, $cardUri, $vCard['body']);
111
+                } else {
112
+                    $this->backend->updateCard($addressBookId, $cardUri, $vCard['body']);
113
+                }
114
+            } else {
115
+                $this->backend->deleteCard($addressBookId, $cardUri);
116
+            }
117
+        }
118
+
119
+        return $response['token'];
120
+    }
121
+
122
+    /**
123
+     * @param string $principal
124
+     * @param string $id
125
+     * @param array $properties
126
+     * @return array|null
127
+     * @throws \Sabre\DAV\Exception\BadRequest
128
+     */
129
+    public function ensureSystemAddressBookExists($principal, $id, $properties) {
130
+        $book = $this->backend->getAddressBooksByUri($principal, $id);
131
+        if (!is_null($book)) {
132
+            return $book;
133
+        }
134
+        $this->backend->createAddressBook($principal, $id, $properties);
135
+
136
+        return $this->backend->getAddressBooksByUri($principal, $id);
137
+    }
138
+
139
+    /**
140
+     * Check if there is a valid certPath we should use
141
+     */
142
+    protected function getCertPath() {
143
+
144
+        // we already have a valid certPath
145
+        if ($this->certPath) {
146
+            return;
147
+        }
148
+
149
+        /** @var ICertificateManager $certManager */
150
+        $certManager = \OC::$server->getCertificateManager(null);
151
+        $certPath = $certManager->getAbsoluteBundlePath();
152
+        if (file_exists($certPath)) {
153
+            $this->certPath = $certPath;
154
+        }
155
+    }
156
+
157
+    /**
158
+     * @param string $url
159
+     * @param string $userName
160
+     * @param string $sharedSecret
161
+     * @return Client
162
+     */
163
+    protected function getClient($url, $userName, $sharedSecret) {
164
+        $settings = [
165
+            'baseUri' => $url . '/',
166
+            'userName' => $userName,
167
+            'password' => $sharedSecret,
168
+        ];
169
+        $client = new Client($settings);
170
+        $this->getCertPath();
171
+        $client->setThrowExceptions(true);
172
+
173
+        if (strpos($url, 'http://') !== 0 && $this->certPath) {
174
+            $client->addCurlSetting(CURLOPT_CAINFO, $this->certPath);
175
+        }
176
+
177
+        return $client;
178
+    }
179
+
180
+    /**
181
+     * @param string $url
182
+     * @param string $userName
183
+     * @param string $sharedSecret
184
+     * @param string $syncToken
185
+     * @return array
186
+     */
187
+    protected function requestSyncReport($url, $userName, $sharedSecret, $syncToken) {
188
+        $client = $this->getClient($url, $userName, $sharedSecret);
189
+
190
+        $addressBookUrl = "remote.php/dav/addressbooks/system/system/system";
191
+        $body = $this->buildSyncCollectionRequestBody($syncToken);
192
+
193
+        $response = $client->request('REPORT', $addressBookUrl, $body, [
194
+            'Content-Type' => 'application/xml'
195
+        ]);
196
+
197
+        return $this->parseMultiStatus($response['body']);
198
+    }
199
+
200
+    /**
201
+     * @param string $url
202
+     * @param string $sharedSecret
203
+     * @param string $resourcePath
204
+     * @return array
205
+     */
206
+    protected function download($url, $sharedSecret, $resourcePath) {
207
+        $client = $this->getClient($url, 'system', $sharedSecret);
208
+        return $client->request('GET', $resourcePath);
209
+    }
210
+
211
+    /**
212
+     * @param string|null $syncToken
213
+     * @return string
214
+     */
215
+    private function buildSyncCollectionRequestBody($syncToken) {
216
+
217
+        $dom = new \DOMDocument('1.0', 'UTF-8');
218
+        $dom->formatOutput = true;
219
+        $root = $dom->createElementNS('DAV:', 'd:sync-collection');
220
+        $sync = $dom->createElement('d:sync-token', $syncToken);
221
+        $prop = $dom->createElement('d:prop');
222
+        $cont = $dom->createElement('d:getcontenttype');
223
+        $etag = $dom->createElement('d:getetag');
224
+
225
+        $prop->appendChild($cont);
226
+        $prop->appendChild($etag);
227
+        $root->appendChild($sync);
228
+        $root->appendChild($prop);
229
+        $dom->appendChild($root);
230
+        $body = $dom->saveXML();
231
+
232
+        return $body;
233
+    }
234
+
235
+    /**
236
+     * @param string $body
237
+     * @return array
238
+     * @throws \Sabre\Xml\ParseException
239
+     */
240
+    private function parseMultiStatus($body) {
241
+        $xml = new Service();
242
+
243
+        /** @var MultiStatus $multiStatus */
244
+        $multiStatus = $xml->expect('{DAV:}multistatus', $body);
245
+
246
+        $result = [];
247
+        foreach ($multiStatus->getResponses() as $response) {
248
+            $result[$response->getHref()] = $response->getResponseProperties();
249
+        }
250
+
251
+        return ['response' => $result, 'token' => $multiStatus->getSyncToken()];
252
+    }
253
+
254
+    /**
255
+     * @param IUser $user
256
+     */
257
+    public function updateUser($user) {
258
+        $systemAddressBook = $this->getLocalSystemAddressBook();
259
+        $addressBookId = $systemAddressBook['id'];
260
+        $converter = new Converter($this->accountManager);
261
+        $name = $user->getBackendClassName();
262
+        $userId = $user->getUID();
263
+
264
+        $cardId = "$name:$userId.vcf";
265
+        $card = $this->backend->getCard($addressBookId, $cardId);
266
+        if ($card === false) {
267
+            $vCard = $converter->createCardFromUser($user);
268
+            if ($vCard !== null) {
269
+                $this->backend->createCard($addressBookId, $cardId, $vCard->serialize());
270
+            }
271
+        } else {
272
+            $vCard = $converter->createCardFromUser($user);
273
+            if (is_null($vCard)) {
274
+                $this->backend->deleteCard($addressBookId, $cardId);
275
+            } else {
276
+                $this->backend->updateCard($addressBookId, $cardId, $vCard->serialize());
277
+            }
278
+        }
279
+    }
280
+
281
+    /**
282
+     * @param IUser|string $userOrCardId
283
+     */
284
+    public function deleteUser($userOrCardId) {
285
+        $systemAddressBook = $this->getLocalSystemAddressBook();
286
+        if ($userOrCardId instanceof IUser){
287
+            $name = $userOrCardId->getBackendClassName();
288
+            $userId = $userOrCardId->getUID();
289
+
290
+            $userOrCardId = "$name:$userId.vcf";
291
+        }
292
+        $this->backend->deleteCard($systemAddressBook['id'], $userOrCardId);
293
+    }
294
+
295
+    /**
296
+     * @return array|null
297
+     */
298
+    public function getLocalSystemAddressBook() {
299
+        if (is_null($this->localSystemAddressBook)) {
300
+            $systemPrincipal = "principals/system/system";
301
+            $this->localSystemAddressBook = $this->ensureSystemAddressBookExists($systemPrincipal, 'system', [
302
+                '{' . Plugin::NS_CARDDAV . '}addressbook-description' => 'System addressbook which holds all users of this instance'
303
+            ]);
304
+        }
305
+
306
+        return $this->localSystemAddressBook;
307
+    }
308
+
309
+    public function syncInstance(\Closure $progressCallback = null) {
310
+        $systemAddressBook = $this->getLocalSystemAddressBook();
311
+        $this->userManager->callForAllUsers(function($user) use ($systemAddressBook, $progressCallback) {
312
+            $this->updateUser($user);
313
+            if (!is_null($progressCallback)) {
314
+                $progressCallback();
315
+            }
316
+        });
317
+
318
+        // remove no longer existing
319
+        $allCards = $this->backend->getCards($systemAddressBook['id']);
320
+        foreach($allCards as $card) {
321
+            $vCard = Reader::read($card['carddata']);
322
+            $uid = $vCard->UID->getValue();
323
+            // load backend and see if user exists
324
+            if (!$this->userManager->userExists($uid)) {
325
+                $this->deleteUser($card['uri']);
326
+            }
327
+        }
328
+    }
329 329
 
330 330
 
331 331
 }
Please login to merge, or discard this patch.