Completed
Pull Request — master (#3825)
by Björn
15:00
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
Indentation   +275 added lines, -275 removed lines patch added patch discarded remove patch
@@ -37,281 +37,281 @@
 block discarded – undo
37 37
 
38 38
 class SyncService {
39 39
 
40
-	/** @var CardDavBackend */
41
-	private $backend;
42
-
43
-	/** @var IUserManager */
44
-	private $userManager;
45
-
46
-	/** @var ILogger */
47
-	private $logger;
48
-
49
-	/** @var array */
50
-	private $localSystemAddressBook;
51
-
52
-	/** @var AccountManager */
53
-	private $accountManager;
54
-
55
-	/** @var string */
56
-	protected $certPath;
57
-
58
-	/**
59
-	 * SyncService constructor.
60
-	 *
61
-	 * @param CardDavBackend $backend
62
-	 * @param IUserManager $userManager
63
-	 * @param ILogger $logger
64
-	 * @param AccountManager $accountManager
65
-	 */
66
-	public function __construct(CardDavBackend $backend, IUserManager $userManager, ILogger $logger, AccountManager $accountManager) {
67
-		$this->backend = $backend;
68
-		$this->userManager = $userManager;
69
-		$this->logger = $logger;
70
-		$this->accountManager = $accountManager;
71
-
72
-		$certManager = \OC::$server->getCertificateManager(null);
73
-		$certPath = $certManager->getAbsoluteBundlePath();
74
-		if (file_exists($certPath)) {
75
-			$this->certPath = $certPath;
76
-		}
77
-	}
78
-
79
-	/**
80
-	 * @param string $url
81
-	 * @param string $userName
82
-	 * @param string $sharedSecret
83
-	 * @param string $syncToken
84
-	 * @param int $targetBookId
85
-	 * @param string $targetPrincipal
86
-	 * @param array $targetProperties
87
-	 * @return string
88
-	 * @throws \Exception
89
-	 */
90
-	public function syncRemoteAddressBook($url, $userName, $sharedSecret, $syncToken, $targetBookId, $targetPrincipal, $targetProperties) {
91
-		// 1. create addressbook
92
-		$book = $this->ensureSystemAddressBookExists($targetPrincipal, $targetBookId, $targetProperties);
93
-		$addressBookId = $book['id'];
94
-
95
-		// 2. query changes
96
-		try {
97
-			$response = $this->requestSyncReport($url, $userName, $sharedSecret, $syncToken);
98
-		} catch (ClientHttpException $ex) {
99
-			if ($ex->getCode() === Http::STATUS_UNAUTHORIZED) {
100
-				// remote server revoked access to the address book, remove it
101
-				$this->backend->deleteAddressBook($addressBookId);
102
-				$this->logger->info('Authorization failed, remove address book: ' . $url, ['app' => 'dav']);
103
-				throw $ex;
104
-			}
105
-		}
106
-
107
-		// 3. apply changes
108
-		// TODO: use multi-get for download
109
-		foreach ($response['response'] as $resource => $status) {
110
-			$cardUri = basename($resource);
111
-			if (isset($status[200])) {
112
-				$vCard = $this->download($url, $sharedSecret, $resource);
113
-				$existingCard = $this->backend->getCard($addressBookId, $cardUri);
114
-				if ($existingCard === false) {
115
-					$this->backend->createCard($addressBookId, $cardUri, $vCard['body']);
116
-				} else {
117
-					$this->backend->updateCard($addressBookId, $cardUri, $vCard['body']);
118
-				}
119
-			} else {
120
-				$this->backend->deleteCard($addressBookId, $cardUri);
121
-			}
122
-		}
123
-
124
-		return $response['token'];
125
-	}
126
-
127
-	/**
128
-	 * @param string $principal
129
-	 * @param string $id
130
-	 * @param array $properties
131
-	 * @return array|null
132
-	 * @throws \Sabre\DAV\Exception\BadRequest
133
-	 */
134
-	public function ensureSystemAddressBookExists($principal, $id, $properties) {
135
-		$book = $this->backend->getAddressBooksByUri($principal, $id);
136
-		if (!is_null($book)) {
137
-			return $book;
138
-		}
139
-		$this->backend->createAddressBook($principal, $id, $properties);
140
-
141
-		return $this->backend->getAddressBooksByUri($principal, $id);
142
-	}
143
-
144
-	/**
145
-	 * @param string $url
146
-	 * @param string $userName
147
-	 * @param string $sharedSecret
148
-	 * @return Client
149
-	 */
150
-	protected function getClient($url, $userName, $sharedSecret) {
151
-		$settings = [
152
-			'baseUri' => $url . '/',
153
-			'userName' => $userName,
154
-			'password' => $sharedSecret,
155
-		];
156
-		$client = new Client($settings);
157
-		$client->setThrowExceptions(true);
158
-
159
-		if (strpos($url, 'http://') !== 0 && $this->certPath) {
160
-			$client->addCurlSetting(CURLOPT_CAINFO, $this->certPath);
161
-		}
162
-
163
-		return $client;
164
-	}
165
-
166
-	/**
167
-	 * @param string $url
168
-	 * @param string $userName
169
-	 * @param string $sharedSecret
170
-	 * @param string $syncToken
171
-	 * @return array
172
-	 */
173
-	protected function requestSyncReport($url, $userName, $sharedSecret, $syncToken) {
174
-		$client = $this->getClient($url, $userName, $sharedSecret);
175
-
176
-		$addressBookUrl = "remote.php/dav/addressbooks/system/system/system";
177
-		$body = $this->buildSyncCollectionRequestBody($syncToken);
178
-
179
-		$response = $client->request('REPORT', $addressBookUrl, $body, [
180
-			'Content-Type' => 'application/xml'
181
-		]);
182
-
183
-		return $this->parseMultiStatus($response['body']);
184
-	}
185
-
186
-	/**
187
-	 * @param string $url
188
-	 * @param string $sharedSecret
189
-	 * @param string $resourcePath
190
-	 * @return array
191
-	 */
192
-	protected function download($url, $sharedSecret, $resourcePath) {
193
-		$client = $this->getClient($url, 'system', $sharedSecret);
194
-		return $client->request('GET', $resourcePath);
195
-	}
196
-
197
-	/**
198
-	 * @param string|null $syncToken
199
-	 * @return string
200
-	 */
201
-	private function buildSyncCollectionRequestBody($syncToken) {
202
-
203
-		$dom = new \DOMDocument('1.0', 'UTF-8');
204
-		$dom->formatOutput = true;
205
-		$root = $dom->createElementNS('DAV:', 'd:sync-collection');
206
-		$sync = $dom->createElement('d:sync-token', $syncToken);
207
-		$prop = $dom->createElement('d:prop');
208
-		$cont = $dom->createElement('d:getcontenttype');
209
-		$etag = $dom->createElement('d:getetag');
210
-
211
-		$prop->appendChild($cont);
212
-		$prop->appendChild($etag);
213
-		$root->appendChild($sync);
214
-		$root->appendChild($prop);
215
-		$dom->appendChild($root);
216
-		$body = $dom->saveXML();
217
-
218
-		return $body;
219
-	}
220
-
221
-	/**
222
-	 * @param string $body
223
-	 * @return array
224
-	 * @throws \Sabre\Xml\ParseException
225
-	 */
226
-	private function parseMultiStatus($body) {
227
-		$xml = new Service();
228
-
229
-		/** @var MultiStatus $multiStatus */
230
-		$multiStatus = $xml->expect('{DAV:}multistatus', $body);
231
-
232
-		$result = [];
233
-		foreach ($multiStatus->getResponses() as $response) {
234
-			$result[$response->getHref()] = $response->getResponseProperties();
235
-		}
236
-
237
-		return ['response' => $result, 'token' => $multiStatus->getSyncToken()];
238
-	}
239
-
240
-	/**
241
-	 * @param IUser $user
242
-	 */
243
-	public function updateUser($user) {
244
-		$systemAddressBook = $this->getLocalSystemAddressBook();
245
-		$addressBookId = $systemAddressBook['id'];
246
-		$converter = new Converter($this->accountManager);
247
-		$name = $user->getBackendClassName();
248
-		$userId = $user->getUID();
249
-
250
-		$cardId = "$name:$userId.vcf";
251
-		$card = $this->backend->getCard($addressBookId, $cardId);
252
-		if ($card === false) {
253
-			$vCard = $converter->createCardFromUser($user);
254
-			if ($vCard !== null) {
255
-				$this->backend->createCard($addressBookId, $cardId, $vCard->serialize());
256
-			}
257
-		} else {
258
-			$vCard = $converter->createCardFromUser($user);
259
-			if (is_null($vCard)) {
260
-				$this->backend->deleteCard($addressBookId, $cardId);
261
-			} else {
262
-				$this->backend->updateCard($addressBookId, $cardId, $vCard->serialize());
263
-			}
264
-		}
265
-	}
266
-
267
-	/**
268
-	 * @param IUser|string $userOrCardId
269
-	 */
270
-	public function deleteUser($userOrCardId) {
271
-		$systemAddressBook = $this->getLocalSystemAddressBook();
272
-		if ($userOrCardId instanceof IUser){
273
-			$name = $userOrCardId->getBackendClassName();
274
-			$userId = $userOrCardId->getUID();
275
-
276
-			$userOrCardId = "$name:$userId.vcf";
277
-		}
278
-		$this->backend->deleteCard($systemAddressBook['id'], $userOrCardId);
279
-	}
280
-
281
-	/**
282
-	 * @return array|null
283
-	 */
284
-	public function getLocalSystemAddressBook() {
285
-		if (is_null($this->localSystemAddressBook)) {
286
-			$systemPrincipal = "principals/system/system";
287
-			$this->localSystemAddressBook = $this->ensureSystemAddressBookExists($systemPrincipal, 'system', [
288
-				'{' . Plugin::NS_CARDDAV . '}addressbook-description' => 'System addressbook which holds all users of this instance'
289
-			]);
290
-		}
291
-
292
-		return $this->localSystemAddressBook;
293
-	}
294
-
295
-	public function syncInstance(\Closure $progressCallback = null) {
296
-		$systemAddressBook = $this->getLocalSystemAddressBook();
297
-		$this->userManager->callForAllUsers(function($user) use ($systemAddressBook, $progressCallback) {
298
-			$this->updateUser($user);
299
-			if (!is_null($progressCallback)) {
300
-				$progressCallback();
301
-			}
302
-		});
303
-
304
-		// remove no longer existing
305
-		$allCards = $this->backend->getCards($systemAddressBook['id']);
306
-		foreach($allCards as $card) {
307
-			$vCard = Reader::read($card['carddata']);
308
-			$uid = $vCard->UID->getValue();
309
-			// load backend and see if user exists
310
-			if (!$this->userManager->userExists($uid)) {
311
-				$this->deleteUser($card['uri']);
312
-			}
313
-		}
314
-	}
40
+    /** @var CardDavBackend */
41
+    private $backend;
42
+
43
+    /** @var IUserManager */
44
+    private $userManager;
45
+
46
+    /** @var ILogger */
47
+    private $logger;
48
+
49
+    /** @var array */
50
+    private $localSystemAddressBook;
51
+
52
+    /** @var AccountManager */
53
+    private $accountManager;
54
+
55
+    /** @var string */
56
+    protected $certPath;
57
+
58
+    /**
59
+     * SyncService constructor.
60
+     *
61
+     * @param CardDavBackend $backend
62
+     * @param IUserManager $userManager
63
+     * @param ILogger $logger
64
+     * @param AccountManager $accountManager
65
+     */
66
+    public function __construct(CardDavBackend $backend, IUserManager $userManager, ILogger $logger, AccountManager $accountManager) {
67
+        $this->backend = $backend;
68
+        $this->userManager = $userManager;
69
+        $this->logger = $logger;
70
+        $this->accountManager = $accountManager;
71
+
72
+        $certManager = \OC::$server->getCertificateManager(null);
73
+        $certPath = $certManager->getAbsoluteBundlePath();
74
+        if (file_exists($certPath)) {
75
+            $this->certPath = $certPath;
76
+        }
77
+    }
78
+
79
+    /**
80
+     * @param string $url
81
+     * @param string $userName
82
+     * @param string $sharedSecret
83
+     * @param string $syncToken
84
+     * @param int $targetBookId
85
+     * @param string $targetPrincipal
86
+     * @param array $targetProperties
87
+     * @return string
88
+     * @throws \Exception
89
+     */
90
+    public function syncRemoteAddressBook($url, $userName, $sharedSecret, $syncToken, $targetBookId, $targetPrincipal, $targetProperties) {
91
+        // 1. create addressbook
92
+        $book = $this->ensureSystemAddressBookExists($targetPrincipal, $targetBookId, $targetProperties);
93
+        $addressBookId = $book['id'];
94
+
95
+        // 2. query changes
96
+        try {
97
+            $response = $this->requestSyncReport($url, $userName, $sharedSecret, $syncToken);
98
+        } catch (ClientHttpException $ex) {
99
+            if ($ex->getCode() === Http::STATUS_UNAUTHORIZED) {
100
+                // remote server revoked access to the address book, remove it
101
+                $this->backend->deleteAddressBook($addressBookId);
102
+                $this->logger->info('Authorization failed, remove address book: ' . $url, ['app' => 'dav']);
103
+                throw $ex;
104
+            }
105
+        }
106
+
107
+        // 3. apply changes
108
+        // TODO: use multi-get for download
109
+        foreach ($response['response'] as $resource => $status) {
110
+            $cardUri = basename($resource);
111
+            if (isset($status[200])) {
112
+                $vCard = $this->download($url, $sharedSecret, $resource);
113
+                $existingCard = $this->backend->getCard($addressBookId, $cardUri);
114
+                if ($existingCard === false) {
115
+                    $this->backend->createCard($addressBookId, $cardUri, $vCard['body']);
116
+                } else {
117
+                    $this->backend->updateCard($addressBookId, $cardUri, $vCard['body']);
118
+                }
119
+            } else {
120
+                $this->backend->deleteCard($addressBookId, $cardUri);
121
+            }
122
+        }
123
+
124
+        return $response['token'];
125
+    }
126
+
127
+    /**
128
+     * @param string $principal
129
+     * @param string $id
130
+     * @param array $properties
131
+     * @return array|null
132
+     * @throws \Sabre\DAV\Exception\BadRequest
133
+     */
134
+    public function ensureSystemAddressBookExists($principal, $id, $properties) {
135
+        $book = $this->backend->getAddressBooksByUri($principal, $id);
136
+        if (!is_null($book)) {
137
+            return $book;
138
+        }
139
+        $this->backend->createAddressBook($principal, $id, $properties);
140
+
141
+        return $this->backend->getAddressBooksByUri($principal, $id);
142
+    }
143
+
144
+    /**
145
+     * @param string $url
146
+     * @param string $userName
147
+     * @param string $sharedSecret
148
+     * @return Client
149
+     */
150
+    protected function getClient($url, $userName, $sharedSecret) {
151
+        $settings = [
152
+            'baseUri' => $url . '/',
153
+            'userName' => $userName,
154
+            'password' => $sharedSecret,
155
+        ];
156
+        $client = new Client($settings);
157
+        $client->setThrowExceptions(true);
158
+
159
+        if (strpos($url, 'http://') !== 0 && $this->certPath) {
160
+            $client->addCurlSetting(CURLOPT_CAINFO, $this->certPath);
161
+        }
162
+
163
+        return $client;
164
+    }
165
+
166
+    /**
167
+     * @param string $url
168
+     * @param string $userName
169
+     * @param string $sharedSecret
170
+     * @param string $syncToken
171
+     * @return array
172
+     */
173
+    protected function requestSyncReport($url, $userName, $sharedSecret, $syncToken) {
174
+        $client = $this->getClient($url, $userName, $sharedSecret);
175
+
176
+        $addressBookUrl = "remote.php/dav/addressbooks/system/system/system";
177
+        $body = $this->buildSyncCollectionRequestBody($syncToken);
178
+
179
+        $response = $client->request('REPORT', $addressBookUrl, $body, [
180
+            'Content-Type' => 'application/xml'
181
+        ]);
182
+
183
+        return $this->parseMultiStatus($response['body']);
184
+    }
185
+
186
+    /**
187
+     * @param string $url
188
+     * @param string $sharedSecret
189
+     * @param string $resourcePath
190
+     * @return array
191
+     */
192
+    protected function download($url, $sharedSecret, $resourcePath) {
193
+        $client = $this->getClient($url, 'system', $sharedSecret);
194
+        return $client->request('GET', $resourcePath);
195
+    }
196
+
197
+    /**
198
+     * @param string|null $syncToken
199
+     * @return string
200
+     */
201
+    private function buildSyncCollectionRequestBody($syncToken) {
202
+
203
+        $dom = new \DOMDocument('1.0', 'UTF-8');
204
+        $dom->formatOutput = true;
205
+        $root = $dom->createElementNS('DAV:', 'd:sync-collection');
206
+        $sync = $dom->createElement('d:sync-token', $syncToken);
207
+        $prop = $dom->createElement('d:prop');
208
+        $cont = $dom->createElement('d:getcontenttype');
209
+        $etag = $dom->createElement('d:getetag');
210
+
211
+        $prop->appendChild($cont);
212
+        $prop->appendChild($etag);
213
+        $root->appendChild($sync);
214
+        $root->appendChild($prop);
215
+        $dom->appendChild($root);
216
+        $body = $dom->saveXML();
217
+
218
+        return $body;
219
+    }
220
+
221
+    /**
222
+     * @param string $body
223
+     * @return array
224
+     * @throws \Sabre\Xml\ParseException
225
+     */
226
+    private function parseMultiStatus($body) {
227
+        $xml = new Service();
228
+
229
+        /** @var MultiStatus $multiStatus */
230
+        $multiStatus = $xml->expect('{DAV:}multistatus', $body);
231
+
232
+        $result = [];
233
+        foreach ($multiStatus->getResponses() as $response) {
234
+            $result[$response->getHref()] = $response->getResponseProperties();
235
+        }
236
+
237
+        return ['response' => $result, 'token' => $multiStatus->getSyncToken()];
238
+    }
239
+
240
+    /**
241
+     * @param IUser $user
242
+     */
243
+    public function updateUser($user) {
244
+        $systemAddressBook = $this->getLocalSystemAddressBook();
245
+        $addressBookId = $systemAddressBook['id'];
246
+        $converter = new Converter($this->accountManager);
247
+        $name = $user->getBackendClassName();
248
+        $userId = $user->getUID();
249
+
250
+        $cardId = "$name:$userId.vcf";
251
+        $card = $this->backend->getCard($addressBookId, $cardId);
252
+        if ($card === false) {
253
+            $vCard = $converter->createCardFromUser($user);
254
+            if ($vCard !== null) {
255
+                $this->backend->createCard($addressBookId, $cardId, $vCard->serialize());
256
+            }
257
+        } else {
258
+            $vCard = $converter->createCardFromUser($user);
259
+            if (is_null($vCard)) {
260
+                $this->backend->deleteCard($addressBookId, $cardId);
261
+            } else {
262
+                $this->backend->updateCard($addressBookId, $cardId, $vCard->serialize());
263
+            }
264
+        }
265
+    }
266
+
267
+    /**
268
+     * @param IUser|string $userOrCardId
269
+     */
270
+    public function deleteUser($userOrCardId) {
271
+        $systemAddressBook = $this->getLocalSystemAddressBook();
272
+        if ($userOrCardId instanceof IUser){
273
+            $name = $userOrCardId->getBackendClassName();
274
+            $userId = $userOrCardId->getUID();
275
+
276
+            $userOrCardId = "$name:$userId.vcf";
277
+        }
278
+        $this->backend->deleteCard($systemAddressBook['id'], $userOrCardId);
279
+    }
280
+
281
+    /**
282
+     * @return array|null
283
+     */
284
+    public function getLocalSystemAddressBook() {
285
+        if (is_null($this->localSystemAddressBook)) {
286
+            $systemPrincipal = "principals/system/system";
287
+            $this->localSystemAddressBook = $this->ensureSystemAddressBookExists($systemPrincipal, 'system', [
288
+                '{' . Plugin::NS_CARDDAV . '}addressbook-description' => 'System addressbook which holds all users of this instance'
289
+            ]);
290
+        }
291
+
292
+        return $this->localSystemAddressBook;
293
+    }
294
+
295
+    public function syncInstance(\Closure $progressCallback = null) {
296
+        $systemAddressBook = $this->getLocalSystemAddressBook();
297
+        $this->userManager->callForAllUsers(function($user) use ($systemAddressBook, $progressCallback) {
298
+            $this->updateUser($user);
299
+            if (!is_null($progressCallback)) {
300
+                $progressCallback();
301
+            }
302
+        });
303
+
304
+        // remove no longer existing
305
+        $allCards = $this->backend->getCards($systemAddressBook['id']);
306
+        foreach($allCards as $card) {
307
+            $vCard = Reader::read($card['carddata']);
308
+            $uid = $vCard->UID->getValue();
309
+            // load backend and see if user exists
310
+            if (!$this->userManager->userExists($uid)) {
311
+                $this->deleteUser($card['uri']);
312
+            }
313
+        }
314
+    }
315 315
 
316 316
 
317 317
 }
Please login to merge, or discard this patch.
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.