Passed
Push — master ( 09a284...339466 )
by Roeland
39:23 queued 10:37
created
apps/dav/lib/Command/SyncBirthdayCalendar.php 1 patch
Indentation   +82 added lines, -82 removed lines patch added patch discarded remove patch
@@ -34,86 +34,86 @@
 block discarded – undo
34 34
 
35 35
 class SyncBirthdayCalendar extends Command {
36 36
 
37
-	/** @var BirthdayService */
38
-	private $birthdayService;
39
-
40
-	/** @var IConfig */
41
-	private $config;
42
-
43
-	/** @var IUserManager */
44
-	private $userManager;
45
-
46
-	/**
47
-	 * @param IUserManager $userManager
48
-	 * @param IConfig $config
49
-	 * @param BirthdayService $birthdayService
50
-	 */
51
-	function __construct(IUserManager $userManager, IConfig $config,
52
-						 BirthdayService $birthdayService) {
53
-		parent::__construct();
54
-		$this->birthdayService = $birthdayService;
55
-		$this->config = $config;
56
-		$this->userManager = $userManager;
57
-	}
58
-
59
-	protected function configure() {
60
-		$this
61
-			->setName('dav:sync-birthday-calendar')
62
-			->setDescription('Synchronizes the birthday calendar')
63
-			->addArgument('user',
64
-				InputArgument::OPTIONAL,
65
-				'User for whom the birthday calendar will be synchronized');
66
-	}
67
-
68
-	/**
69
-	 * @param InputInterface $input
70
-	 * @param OutputInterface $output
71
-	 */
72
-	protected function execute(InputInterface $input, OutputInterface $output) {
73
-		$this->verifyEnabled();
74
-
75
-		$user = $input->getArgument('user');
76
-		if (!is_null($user)) {
77
-			if (!$this->userManager->userExists($user)) {
78
-				throw new \InvalidArgumentException("User <$user> in unknown.");
79
-			}
80
-
81
-			// re-enable the birthday calendar in case it's called directly with a user name
82
-			$isEnabled = $this->config->getUserValue($user, 'dav', 'generateBirthdayCalendar', 'yes');
83
-			if ($isEnabled !== 'yes') {
84
-				$this->config->setUserValue($user, 'dav', 'generateBirthdayCalendar', 'yes');
85
-				$output->writeln("Re-enabling birthday calendar for $user");
86
-			}
87
-
88
-			$output->writeln("Start birthday calendar sync for $user");
89
-			$this->birthdayService->syncUser($user);
90
-			return;
91
-		}
92
-		$output->writeln("Start birthday calendar sync for all users ...");
93
-		$p = new ProgressBar($output);
94
-		$p->start();
95
-		$this->userManager->callForSeenUsers(function($user) use ($p)  {
96
-			$p->advance();
97
-
98
-			$userId = $user->getUID();
99
-			$isEnabled = $this->config->getUserValue($userId, 'dav', 'generateBirthdayCalendar', 'yes');
100
-			if ($isEnabled !== 'yes') {
101
-				return;
102
-			}
103
-
104
-			/** @var IUser $user */
105
-			$this->birthdayService->syncUser($user->getUID());
106
-		});
107
-
108
-		$p->finish();
109
-		$output->writeln('');
110
-	}
111
-
112
-	protected function verifyEnabled () {
113
-		$isEnabled = $this->config->getAppValue('dav', 'generateBirthdayCalendar', 'yes');
114
-
115
-		if ($isEnabled !== 'yes') {
116
-			throw new \InvalidArgumentException('Birthday calendars are disabled');
117
-		}
118
-	}
37
+    /** @var BirthdayService */
38
+    private $birthdayService;
39
+
40
+    /** @var IConfig */
41
+    private $config;
42
+
43
+    /** @var IUserManager */
44
+    private $userManager;
45
+
46
+    /**
47
+     * @param IUserManager $userManager
48
+     * @param IConfig $config
49
+     * @param BirthdayService $birthdayService
50
+     */
51
+    function __construct(IUserManager $userManager, IConfig $config,
52
+                            BirthdayService $birthdayService) {
53
+        parent::__construct();
54
+        $this->birthdayService = $birthdayService;
55
+        $this->config = $config;
56
+        $this->userManager = $userManager;
57
+    }
58
+
59
+    protected function configure() {
60
+        $this
61
+            ->setName('dav:sync-birthday-calendar')
62
+            ->setDescription('Synchronizes the birthday calendar')
63
+            ->addArgument('user',
64
+                InputArgument::OPTIONAL,
65
+                'User for whom the birthday calendar will be synchronized');
66
+    }
67
+
68
+    /**
69
+     * @param InputInterface $input
70
+     * @param OutputInterface $output
71
+     */
72
+    protected function execute(InputInterface $input, OutputInterface $output) {
73
+        $this->verifyEnabled();
74
+
75
+        $user = $input->getArgument('user');
76
+        if (!is_null($user)) {
77
+            if (!$this->userManager->userExists($user)) {
78
+                throw new \InvalidArgumentException("User <$user> in unknown.");
79
+            }
80
+
81
+            // re-enable the birthday calendar in case it's called directly with a user name
82
+            $isEnabled = $this->config->getUserValue($user, 'dav', 'generateBirthdayCalendar', 'yes');
83
+            if ($isEnabled !== 'yes') {
84
+                $this->config->setUserValue($user, 'dav', 'generateBirthdayCalendar', 'yes');
85
+                $output->writeln("Re-enabling birthday calendar for $user");
86
+            }
87
+
88
+            $output->writeln("Start birthday calendar sync for $user");
89
+            $this->birthdayService->syncUser($user);
90
+            return;
91
+        }
92
+        $output->writeln("Start birthday calendar sync for all users ...");
93
+        $p = new ProgressBar($output);
94
+        $p->start();
95
+        $this->userManager->callForSeenUsers(function($user) use ($p)  {
96
+            $p->advance();
97
+
98
+            $userId = $user->getUID();
99
+            $isEnabled = $this->config->getUserValue($userId, 'dav', 'generateBirthdayCalendar', 'yes');
100
+            if ($isEnabled !== 'yes') {
101
+                return;
102
+            }
103
+
104
+            /** @var IUser $user */
105
+            $this->birthdayService->syncUser($user->getUID());
106
+        });
107
+
108
+        $p->finish();
109
+        $output->writeln('');
110
+    }
111
+
112
+    protected function verifyEnabled () {
113
+        $isEnabled = $this->config->getAppValue('dav', 'generateBirthdayCalendar', 'yes');
114
+
115
+        if ($isEnabled !== 'yes') {
116
+            throw new \InvalidArgumentException('Birthday calendars are disabled');
117
+        }
118
+    }
119 119
 }
Please login to merge, or discard this patch.
apps/dav/lib/CardDAV/SyncService.php 1 patch
Indentation   +298 added lines, -298 removed lines patch added patch discarded remove patch
@@ -39,304 +39,304 @@
 block discarded – undo
39 39
 
40 40
 class SyncService {
41 41
 
42
-	/** @var CardDavBackend */
43
-	private $backend;
44
-
45
-	/** @var IUserManager */
46
-	private $userManager;
47
-
48
-	/** @var ILogger */
49
-	private $logger;
50
-
51
-	/** @var array */
52
-	private $localSystemAddressBook;
53
-
54
-	/** @var AccountManager */
55
-	private $accountManager;
56
-
57
-	/** @var string */
58
-	protected $certPath;
59
-
60
-	/**
61
-	 * SyncService constructor.
62
-	 *
63
-	 * @param CardDavBackend $backend
64
-	 * @param IUserManager $userManager
65
-	 * @param ILogger $logger
66
-	 * @param AccountManager $accountManager
67
-	 */
68
-	public function __construct(CardDavBackend $backend, IUserManager $userManager, ILogger $logger, AccountManager $accountManager) {
69
-		$this->backend = $backend;
70
-		$this->userManager = $userManager;
71
-		$this->logger = $logger;
72
-		$this->accountManager = $accountManager;
73
-		$this->certPath = '';
74
-	}
75
-
76
-	/**
77
-	 * @param string $url
78
-	 * @param string $userName
79
-	 * @param string $addressBookUrl
80
-	 * @param string $sharedSecret
81
-	 * @param string $syncToken
82
-	 * @param int $targetBookId
83
-	 * @param string $targetPrincipal
84
-	 * @param array $targetProperties
85
-	 * @return string
86
-	 * @throws \Exception
87
-	 */
88
-	public function syncRemoteAddressBook($url, $userName, $addressBookUrl, $sharedSecret, $syncToken, $targetBookId, $targetPrincipal, $targetProperties) {
89
-		// 1. create addressbook
90
-		$book = $this->ensureSystemAddressBookExists($targetPrincipal, $targetBookId, $targetProperties);
91
-		$addressBookId = $book['id'];
92
-
93
-		// 2. query changes
94
-		try {
95
-			$response = $this->requestSyncReport($url, $userName, $addressBookUrl, $sharedSecret, $syncToken);
96
-		} catch (ClientHttpException $ex) {
97
-			if ($ex->getCode() === Http::STATUS_UNAUTHORIZED) {
98
-				// remote server revoked access to the address book, remove it
99
-				$this->backend->deleteAddressBook($addressBookId);
100
-				$this->logger->info('Authorization failed, remove address book: ' . $url, ['app' => 'dav']);
101
-				throw $ex;
102
-			}
103
-		}
104
-
105
-		// 3. apply changes
106
-		// TODO: use multi-get for download
107
-		foreach ($response['response'] as $resource => $status) {
108
-			$cardUri = basename($resource);
109
-			if (isset($status[200])) {
110
-				$vCard = $this->download($url, $userName, $sharedSecret, $resource);
111
-				$existingCard = $this->backend->getCard($addressBookId, $cardUri);
112
-				if ($existingCard === false) {
113
-					$this->backend->createCard($addressBookId, $cardUri, $vCard['body']);
114
-				} else {
115
-					$this->backend->updateCard($addressBookId, $cardUri, $vCard['body']);
116
-				}
117
-			} else {
118
-				$this->backend->deleteCard($addressBookId, $cardUri);
119
-			}
120
-		}
121
-
122
-		return $response['token'];
123
-	}
124
-
125
-	/**
126
-	 * @param string $principal
127
-	 * @param string $id
128
-	 * @param array $properties
129
-	 * @return array|null
130
-	 * @throws \Sabre\DAV\Exception\BadRequest
131
-	 */
132
-	public function ensureSystemAddressBookExists($principal, $id, $properties) {
133
-		$book = $this->backend->getAddressBooksByUri($principal, $id);
134
-		if (!is_null($book)) {
135
-			return $book;
136
-		}
137
-		$this->backend->createAddressBook($principal, $id, $properties);
138
-
139
-		return $this->backend->getAddressBooksByUri($principal, $id);
140
-	}
141
-
142
-	/**
143
-	 * Check if there is a valid certPath we should use
144
-	 *
145
-	 * @return string
146
-	 */
147
-	protected function getCertPath() {
148
-
149
-		// we already have a valid certPath
150
-		if ($this->certPath !== '') {
151
-			return $this->certPath;
152
-		}
153
-
154
-		/** @var ICertificateManager $certManager */
155
-		$certManager = \OC::$server->getCertificateManager(null);
156
-		$certPath = $certManager->getAbsoluteBundlePath();
157
-		if (file_exists($certPath)) {
158
-			$this->certPath = $certPath;
159
-		}
160
-
161
-		return $this->certPath;
162
-	}
163
-
164
-	/**
165
-	 * @param string $url
166
-	 * @param string $userName
167
-	 * @param string $addressBookUrl
168
-	 * @param string $sharedSecret
169
-	 * @return Client
170
-	 */
171
-	protected function getClient($url, $userName, $sharedSecret) {
172
-		$settings = [
173
-			'baseUri' => $url . '/',
174
-			'userName' => $userName,
175
-			'password' => $sharedSecret,
176
-		];
177
-		$client = new Client($settings);
178
-		$certPath = $this->getCertPath();
179
-		$client->setThrowExceptions(true);
180
-
181
-		if ($certPath !== '' && strpos($url, 'http://') !== 0) {
182
-			$client->addCurlSetting(CURLOPT_CAINFO, $this->certPath);
183
-		}
184
-
185
-		return $client;
186
-	}
187
-
188
-	/**
189
-	 * @param string $url
190
-	 * @param string $userName
191
-	 * @param string $addressBookUrl
192
-	 * @param string $sharedSecret
193
-	 * @param string $syncToken
194
-	 * @return array
195
-	 */
196
-	 protected function requestSyncReport($url, $userName, $addressBookUrl, $sharedSecret, $syncToken) {
197
-		 $client = $this->getClient($url, $userName, $sharedSecret);
198
-
199
-		 $body = $this->buildSyncCollectionRequestBody($syncToken);
200
-
201
-		 $response = $client->request('REPORT', $addressBookUrl, $body, [
202
-			 'Content-Type' => 'application/xml'
203
-		 ]);
204
-
205
-		 return $this->parseMultiStatus($response['body']);
206
-	 }
207
-
208
-	/**
209
-	 * @param string $url
210
-	 * @param string $userName
211
-	 * @param string $sharedSecret
212
-	 * @param string $resourcePath
213
-	 * @return array
214
-	 */
215
-	protected function download($url, $userName, $sharedSecret, $resourcePath) {
216
-		$client = $this->getClient($url, $userName, $sharedSecret);
217
-		return $client->request('GET', $resourcePath);
218
-	}
219
-
220
-	/**
221
-	 * @param string|null $syncToken
222
-	 * @return string
223
-	 */
224
-	private function buildSyncCollectionRequestBody($syncToken) {
225
-
226
-		$dom = new \DOMDocument('1.0', 'UTF-8');
227
-		$dom->formatOutput = true;
228
-		$root = $dom->createElementNS('DAV:', 'd:sync-collection');
229
-		$sync = $dom->createElement('d:sync-token', $syncToken);
230
-		$prop = $dom->createElement('d:prop');
231
-		$cont = $dom->createElement('d:getcontenttype');
232
-		$etag = $dom->createElement('d:getetag');
233
-
234
-		$prop->appendChild($cont);
235
-		$prop->appendChild($etag);
236
-		$root->appendChild($sync);
237
-		$root->appendChild($prop);
238
-		$dom->appendChild($root);
239
-		return $dom->saveXML();
240
-	}
241
-
242
-	/**
243
-	 * @param string $body
244
-	 * @return array
245
-	 * @throws \Sabre\Xml\ParseException
246
-	 */
247
-	private function parseMultiStatus($body) {
248
-		$xml = new Service();
249
-
250
-		/** @var MultiStatus $multiStatus */
251
-		$multiStatus = $xml->expect('{DAV:}multistatus', $body);
252
-
253
-		$result = [];
254
-		foreach ($multiStatus->getResponses() as $response) {
255
-			$result[$response->getHref()] = $response->getResponseProperties();
256
-		}
257
-
258
-		return ['response' => $result, 'token' => $multiStatus->getSyncToken()];
259
-	}
260
-
261
-	/**
262
-	 * @param IUser $user
263
-	 */
264
-	public function updateUser(IUser $user) {
265
-		$systemAddressBook = $this->getLocalSystemAddressBook();
266
-		$addressBookId = $systemAddressBook['id'];
267
-		$converter = new Converter($this->accountManager);
268
-		$name = $user->getBackendClassName();
269
-		$userId = $user->getUID();
270
-
271
-		$cardId = "$name:$userId.vcf";
272
-		$card = $this->backend->getCard($addressBookId, $cardId);
273
-		if ($user->isEnabled()) {
274
-			if ($card === false) {
275
-				$vCard = $converter->createCardFromUser($user);
276
-				if ($vCard !== null) {
277
-					$this->backend->createCard($addressBookId, $cardId, $vCard->serialize());
278
-				}
279
-			} else {
280
-				$vCard = $converter->createCardFromUser($user);
281
-				if (is_null($vCard)) {
282
-					$this->backend->deleteCard($addressBookId, $cardId);
283
-				} else {
284
-					$this->backend->updateCard($addressBookId, $cardId, $vCard->serialize());
285
-				}
286
-			}
287
-		} else {
288
-			$this->backend->deleteCard($addressBookId, $cardId);
289
-		}
290
-	}
291
-
292
-	/**
293
-	 * @param IUser|string $userOrCardId
294
-	 */
295
-	public function deleteUser($userOrCardId) {
296
-		$systemAddressBook = $this->getLocalSystemAddressBook();
297
-		if ($userOrCardId instanceof IUser){
298
-			$name = $userOrCardId->getBackendClassName();
299
-			$userId = $userOrCardId->getUID();
300
-
301
-			$userOrCardId = "$name:$userId.vcf";
302
-		}
303
-		$this->backend->deleteCard($systemAddressBook['id'], $userOrCardId);
304
-	}
305
-
306
-	/**
307
-	 * @return array|null
308
-	 */
309
-	public function getLocalSystemAddressBook() {
310
-		if (is_null($this->localSystemAddressBook)) {
311
-			$systemPrincipal = "principals/system/system";
312
-			$this->localSystemAddressBook = $this->ensureSystemAddressBookExists($systemPrincipal, 'system', [
313
-				'{' . Plugin::NS_CARDDAV . '}addressbook-description' => 'System addressbook which holds all users of this instance'
314
-			]);
315
-		}
316
-
317
-		return $this->localSystemAddressBook;
318
-	}
319
-
320
-	public function syncInstance(\Closure $progressCallback = null) {
321
-		$systemAddressBook = $this->getLocalSystemAddressBook();
322
-		$this->userManager->callForSeenUsers(function($user) use ($systemAddressBook, $progressCallback) {
323
-			$this->updateUser($user);
324
-			if (!is_null($progressCallback)) {
325
-				$progressCallback();
326
-			}
327
-		});
328
-
329
-		// remove no longer existing
330
-		$allCards = $this->backend->getCards($systemAddressBook['id']);
331
-		foreach($allCards as $card) {
332
-			$vCard = Reader::read($card['carddata']);
333
-			$uid = $vCard->UID->getValue();
334
-			// load backend and see if user exists
335
-			if (!$this->userManager->userExists($uid)) {
336
-				$this->deleteUser($card['uri']);
337
-			}
338
-		}
339
-	}
42
+    /** @var CardDavBackend */
43
+    private $backend;
44
+
45
+    /** @var IUserManager */
46
+    private $userManager;
47
+
48
+    /** @var ILogger */
49
+    private $logger;
50
+
51
+    /** @var array */
52
+    private $localSystemAddressBook;
53
+
54
+    /** @var AccountManager */
55
+    private $accountManager;
56
+
57
+    /** @var string */
58
+    protected $certPath;
59
+
60
+    /**
61
+     * SyncService constructor.
62
+     *
63
+     * @param CardDavBackend $backend
64
+     * @param IUserManager $userManager
65
+     * @param ILogger $logger
66
+     * @param AccountManager $accountManager
67
+     */
68
+    public function __construct(CardDavBackend $backend, IUserManager $userManager, ILogger $logger, AccountManager $accountManager) {
69
+        $this->backend = $backend;
70
+        $this->userManager = $userManager;
71
+        $this->logger = $logger;
72
+        $this->accountManager = $accountManager;
73
+        $this->certPath = '';
74
+    }
75
+
76
+    /**
77
+     * @param string $url
78
+     * @param string $userName
79
+     * @param string $addressBookUrl
80
+     * @param string $sharedSecret
81
+     * @param string $syncToken
82
+     * @param int $targetBookId
83
+     * @param string $targetPrincipal
84
+     * @param array $targetProperties
85
+     * @return string
86
+     * @throws \Exception
87
+     */
88
+    public function syncRemoteAddressBook($url, $userName, $addressBookUrl, $sharedSecret, $syncToken, $targetBookId, $targetPrincipal, $targetProperties) {
89
+        // 1. create addressbook
90
+        $book = $this->ensureSystemAddressBookExists($targetPrincipal, $targetBookId, $targetProperties);
91
+        $addressBookId = $book['id'];
92
+
93
+        // 2. query changes
94
+        try {
95
+            $response = $this->requestSyncReport($url, $userName, $addressBookUrl, $sharedSecret, $syncToken);
96
+        } catch (ClientHttpException $ex) {
97
+            if ($ex->getCode() === Http::STATUS_UNAUTHORIZED) {
98
+                // remote server revoked access to the address book, remove it
99
+                $this->backend->deleteAddressBook($addressBookId);
100
+                $this->logger->info('Authorization failed, remove address book: ' . $url, ['app' => 'dav']);
101
+                throw $ex;
102
+            }
103
+        }
104
+
105
+        // 3. apply changes
106
+        // TODO: use multi-get for download
107
+        foreach ($response['response'] as $resource => $status) {
108
+            $cardUri = basename($resource);
109
+            if (isset($status[200])) {
110
+                $vCard = $this->download($url, $userName, $sharedSecret, $resource);
111
+                $existingCard = $this->backend->getCard($addressBookId, $cardUri);
112
+                if ($existingCard === false) {
113
+                    $this->backend->createCard($addressBookId, $cardUri, $vCard['body']);
114
+                } else {
115
+                    $this->backend->updateCard($addressBookId, $cardUri, $vCard['body']);
116
+                }
117
+            } else {
118
+                $this->backend->deleteCard($addressBookId, $cardUri);
119
+            }
120
+        }
121
+
122
+        return $response['token'];
123
+    }
124
+
125
+    /**
126
+     * @param string $principal
127
+     * @param string $id
128
+     * @param array $properties
129
+     * @return array|null
130
+     * @throws \Sabre\DAV\Exception\BadRequest
131
+     */
132
+    public function ensureSystemAddressBookExists($principal, $id, $properties) {
133
+        $book = $this->backend->getAddressBooksByUri($principal, $id);
134
+        if (!is_null($book)) {
135
+            return $book;
136
+        }
137
+        $this->backend->createAddressBook($principal, $id, $properties);
138
+
139
+        return $this->backend->getAddressBooksByUri($principal, $id);
140
+    }
141
+
142
+    /**
143
+     * Check if there is a valid certPath we should use
144
+     *
145
+     * @return string
146
+     */
147
+    protected function getCertPath() {
148
+
149
+        // we already have a valid certPath
150
+        if ($this->certPath !== '') {
151
+            return $this->certPath;
152
+        }
153
+
154
+        /** @var ICertificateManager $certManager */
155
+        $certManager = \OC::$server->getCertificateManager(null);
156
+        $certPath = $certManager->getAbsoluteBundlePath();
157
+        if (file_exists($certPath)) {
158
+            $this->certPath = $certPath;
159
+        }
160
+
161
+        return $this->certPath;
162
+    }
163
+
164
+    /**
165
+     * @param string $url
166
+     * @param string $userName
167
+     * @param string $addressBookUrl
168
+     * @param string $sharedSecret
169
+     * @return Client
170
+     */
171
+    protected function getClient($url, $userName, $sharedSecret) {
172
+        $settings = [
173
+            'baseUri' => $url . '/',
174
+            'userName' => $userName,
175
+            'password' => $sharedSecret,
176
+        ];
177
+        $client = new Client($settings);
178
+        $certPath = $this->getCertPath();
179
+        $client->setThrowExceptions(true);
180
+
181
+        if ($certPath !== '' && strpos($url, 'http://') !== 0) {
182
+            $client->addCurlSetting(CURLOPT_CAINFO, $this->certPath);
183
+        }
184
+
185
+        return $client;
186
+    }
187
+
188
+    /**
189
+     * @param string $url
190
+     * @param string $userName
191
+     * @param string $addressBookUrl
192
+     * @param string $sharedSecret
193
+     * @param string $syncToken
194
+     * @return array
195
+     */
196
+        protected function requestSyncReport($url, $userName, $addressBookUrl, $sharedSecret, $syncToken) {
197
+            $client = $this->getClient($url, $userName, $sharedSecret);
198
+
199
+            $body = $this->buildSyncCollectionRequestBody($syncToken);
200
+
201
+            $response = $client->request('REPORT', $addressBookUrl, $body, [
202
+                'Content-Type' => 'application/xml'
203
+            ]);
204
+
205
+            return $this->parseMultiStatus($response['body']);
206
+        }
207
+
208
+    /**
209
+     * @param string $url
210
+     * @param string $userName
211
+     * @param string $sharedSecret
212
+     * @param string $resourcePath
213
+     * @return array
214
+     */
215
+    protected function download($url, $userName, $sharedSecret, $resourcePath) {
216
+        $client = $this->getClient($url, $userName, $sharedSecret);
217
+        return $client->request('GET', $resourcePath);
218
+    }
219
+
220
+    /**
221
+     * @param string|null $syncToken
222
+     * @return string
223
+     */
224
+    private function buildSyncCollectionRequestBody($syncToken) {
225
+
226
+        $dom = new \DOMDocument('1.0', 'UTF-8');
227
+        $dom->formatOutput = true;
228
+        $root = $dom->createElementNS('DAV:', 'd:sync-collection');
229
+        $sync = $dom->createElement('d:sync-token', $syncToken);
230
+        $prop = $dom->createElement('d:prop');
231
+        $cont = $dom->createElement('d:getcontenttype');
232
+        $etag = $dom->createElement('d:getetag');
233
+
234
+        $prop->appendChild($cont);
235
+        $prop->appendChild($etag);
236
+        $root->appendChild($sync);
237
+        $root->appendChild($prop);
238
+        $dom->appendChild($root);
239
+        return $dom->saveXML();
240
+    }
241
+
242
+    /**
243
+     * @param string $body
244
+     * @return array
245
+     * @throws \Sabre\Xml\ParseException
246
+     */
247
+    private function parseMultiStatus($body) {
248
+        $xml = new Service();
249
+
250
+        /** @var MultiStatus $multiStatus */
251
+        $multiStatus = $xml->expect('{DAV:}multistatus', $body);
252
+
253
+        $result = [];
254
+        foreach ($multiStatus->getResponses() as $response) {
255
+            $result[$response->getHref()] = $response->getResponseProperties();
256
+        }
257
+
258
+        return ['response' => $result, 'token' => $multiStatus->getSyncToken()];
259
+    }
260
+
261
+    /**
262
+     * @param IUser $user
263
+     */
264
+    public function updateUser(IUser $user) {
265
+        $systemAddressBook = $this->getLocalSystemAddressBook();
266
+        $addressBookId = $systemAddressBook['id'];
267
+        $converter = new Converter($this->accountManager);
268
+        $name = $user->getBackendClassName();
269
+        $userId = $user->getUID();
270
+
271
+        $cardId = "$name:$userId.vcf";
272
+        $card = $this->backend->getCard($addressBookId, $cardId);
273
+        if ($user->isEnabled()) {
274
+            if ($card === false) {
275
+                $vCard = $converter->createCardFromUser($user);
276
+                if ($vCard !== null) {
277
+                    $this->backend->createCard($addressBookId, $cardId, $vCard->serialize());
278
+                }
279
+            } else {
280
+                $vCard = $converter->createCardFromUser($user);
281
+                if (is_null($vCard)) {
282
+                    $this->backend->deleteCard($addressBookId, $cardId);
283
+                } else {
284
+                    $this->backend->updateCard($addressBookId, $cardId, $vCard->serialize());
285
+                }
286
+            }
287
+        } else {
288
+            $this->backend->deleteCard($addressBookId, $cardId);
289
+        }
290
+    }
291
+
292
+    /**
293
+     * @param IUser|string $userOrCardId
294
+     */
295
+    public function deleteUser($userOrCardId) {
296
+        $systemAddressBook = $this->getLocalSystemAddressBook();
297
+        if ($userOrCardId instanceof IUser){
298
+            $name = $userOrCardId->getBackendClassName();
299
+            $userId = $userOrCardId->getUID();
300
+
301
+            $userOrCardId = "$name:$userId.vcf";
302
+        }
303
+        $this->backend->deleteCard($systemAddressBook['id'], $userOrCardId);
304
+    }
305
+
306
+    /**
307
+     * @return array|null
308
+     */
309
+    public function getLocalSystemAddressBook() {
310
+        if (is_null($this->localSystemAddressBook)) {
311
+            $systemPrincipal = "principals/system/system";
312
+            $this->localSystemAddressBook = $this->ensureSystemAddressBookExists($systemPrincipal, 'system', [
313
+                '{' . Plugin::NS_CARDDAV . '}addressbook-description' => 'System addressbook which holds all users of this instance'
314
+            ]);
315
+        }
316
+
317
+        return $this->localSystemAddressBook;
318
+    }
319
+
320
+    public function syncInstance(\Closure $progressCallback = null) {
321
+        $systemAddressBook = $this->getLocalSystemAddressBook();
322
+        $this->userManager->callForSeenUsers(function($user) use ($systemAddressBook, $progressCallback) {
323
+            $this->updateUser($user);
324
+            if (!is_null($progressCallback)) {
325
+                $progressCallback();
326
+            }
327
+        });
328
+
329
+        // remove no longer existing
330
+        $allCards = $this->backend->getCards($systemAddressBook['id']);
331
+        foreach($allCards as $card) {
332
+            $vCard = Reader::read($card['carddata']);
333
+            $uid = $vCard->UID->getValue();
334
+            // load backend and see if user exists
335
+            if (!$this->userManager->userExists($uid)) {
336
+                $this->deleteUser($card['uri']);
337
+            }
338
+        }
339
+    }
340 340
 
341 341
 
342 342
 }
Please login to merge, or discard this patch.
apps/dav/lib/Controller/BirthdayCalendarController.php 1 patch
Indentation   +65 added lines, -65 removed lines patch added patch discarded remove patch
@@ -37,80 +37,80 @@
 block discarded – undo
37 37
 
38 38
 class BirthdayCalendarController extends Controller {
39 39
 
40
-	/**
41
-	 * @var IDBConnection
42
-	 */
43
-	protected $db;
40
+    /**
41
+     * @var IDBConnection
42
+     */
43
+    protected $db;
44 44
 
45
-	/**
46
-	 * @var IConfig
47
-	 */
48
-	protected $config;
45
+    /**
46
+     * @var IConfig
47
+     */
48
+    protected $config;
49 49
 
50
-	/**
51
-	 * @var IUserManager
52
-	 */
53
-	protected $userManager;
50
+    /**
51
+     * @var IUserManager
52
+     */
53
+    protected $userManager;
54 54
 
55
-	/**
56
-	 * @var CalDavBackend
57
-	 */
58
-	protected $caldavBackend;
55
+    /**
56
+     * @var CalDavBackend
57
+     */
58
+    protected $caldavBackend;
59 59
 
60
-	/**
61
-	 * @var IJobList
62
-	 */
63
-	protected $jobList;
60
+    /**
61
+     * @var IJobList
62
+     */
63
+    protected $jobList;
64 64
 
65
-	/**
66
-	 * BirthdayCalendar constructor.
67
-	 *
68
-	 * @param string $appName
69
-	 * @param IRequest $request
70
-	 * @param IDBConnection $db
71
-	 * @param IConfig $config
72
-	 * @param IJobList $jobList
73
-	 * @param IUserManager $userManager
74
-	 * @param CalDavBackend $calDavBackend
75
-	 */
76
-	public function __construct($appName, IRequest $request,
77
-								IDBConnection $db, IConfig $config,
78
-								IJobList $jobList,
79
-								IUserManager $userManager,
80
-								CalDavBackend $calDavBackend){
81
-		parent::__construct($appName, $request);
82
-		$this->db = $db;
83
-		$this->config = $config;
84
-		$this->userManager = $userManager;
85
-		$this->jobList = $jobList;
86
-		$this->caldavBackend = $calDavBackend;
87
-	}
65
+    /**
66
+     * BirthdayCalendar constructor.
67
+     *
68
+     * @param string $appName
69
+     * @param IRequest $request
70
+     * @param IDBConnection $db
71
+     * @param IConfig $config
72
+     * @param IJobList $jobList
73
+     * @param IUserManager $userManager
74
+     * @param CalDavBackend $calDavBackend
75
+     */
76
+    public function __construct($appName, IRequest $request,
77
+                                IDBConnection $db, IConfig $config,
78
+                                IJobList $jobList,
79
+                                IUserManager $userManager,
80
+                                CalDavBackend $calDavBackend){
81
+        parent::__construct($appName, $request);
82
+        $this->db = $db;
83
+        $this->config = $config;
84
+        $this->userManager = $userManager;
85
+        $this->jobList = $jobList;
86
+        $this->caldavBackend = $calDavBackend;
87
+    }
88 88
 
89
-	/**
90
-	 * @return Response
91
-	 */
92
-	public function enable() {
93
-		$this->config->setAppValue($this->appName, 'generateBirthdayCalendar', 'yes');
89
+    /**
90
+     * @return Response
91
+     */
92
+    public function enable() {
93
+        $this->config->setAppValue($this->appName, 'generateBirthdayCalendar', 'yes');
94 94
 
95
-		// add background job for each user
96
-		$this->userManager->callForSeenUsers(function(IUser $user) {
97
-			$this->jobList->add(GenerateBirthdayCalendarBackgroundJob::class, [
98
-				'userId' => $user->getUID(),
99
-			]);
100
-		});
95
+        // add background job for each user
96
+        $this->userManager->callForSeenUsers(function(IUser $user) {
97
+            $this->jobList->add(GenerateBirthdayCalendarBackgroundJob::class, [
98
+                'userId' => $user->getUID(),
99
+            ]);
100
+        });
101 101
 
102
-		return new JSONResponse([]);
103
-	}
102
+        return new JSONResponse([]);
103
+    }
104 104
 
105
-	/**
106
-	 * @return Response
107
-	 */
108
-	public function disable() {
109
-		$this->config->setAppValue($this->appName, 'generateBirthdayCalendar', 'no');
105
+    /**
106
+     * @return Response
107
+     */
108
+    public function disable() {
109
+        $this->config->setAppValue($this->appName, 'generateBirthdayCalendar', 'no');
110 110
 
111
-		$this->jobList->remove(GenerateBirthdayCalendarBackgroundJob::class);
112
-		$this->caldavBackend->deleteAllBirthdayCalendars();
111
+        $this->jobList->remove(GenerateBirthdayCalendarBackgroundJob::class);
112
+        $this->caldavBackend->deleteAllBirthdayCalendars();
113 113
 
114
-		return new JSONResponse([]);
115
-	}
114
+        return new JSONResponse([]);
115
+    }
116 116
 }
Please login to merge, or discard this patch.
apps/dav/lib/Migration/RegenerateBirthdayCalendars.php 1 patch
Indentation   +43 added lines, -43 removed lines patch added patch discarded remove patch
@@ -32,54 +32,54 @@
 block discarded – undo
32 32
 
33 33
 class RegenerateBirthdayCalendars implements IRepairStep {
34 34
 
35
-	/** @var IUserManager */
36
-	private $userManager;
35
+    /** @var IUserManager */
36
+    private $userManager;
37 37
 
38
-	/** @var IJobList */
39
-	private $jobList;
38
+    /** @var IJobList */
39
+    private $jobList;
40 40
 
41
-	/** @var IConfig */
42
-	private $config;
41
+    /** @var IConfig */
42
+    private $config;
43 43
 
44
-	/**
45
-	 * @param IUserManager $userManager,
46
-	 * @param IJobList $jobList
47
-	 * @param IConfig $config
48
-	 */
49
-	public function __construct(IUserManager $userManager,
50
-								IJobList $jobList,
51
-								IConfig $config) {
52
-		$this->userManager = $userManager;
53
-		$this->jobList = $jobList;
54
-		$this->config = $config;
55
-	}
44
+    /**
45
+     * @param IUserManager $userManager,
46
+     * @param IJobList $jobList
47
+     * @param IConfig $config
48
+     */
49
+    public function __construct(IUserManager $userManager,
50
+                                IJobList $jobList,
51
+                                IConfig $config) {
52
+        $this->userManager = $userManager;
53
+        $this->jobList = $jobList;
54
+        $this->config = $config;
55
+    }
56 56
 
57
-	/**
58
-	 * @return string
59
-	 */
60
-	public function getName() {
61
-		return 'Regenerating birthday calendars to use new icons and fix old birthday events without year';
62
-	}
57
+    /**
58
+     * @return string
59
+     */
60
+    public function getName() {
61
+        return 'Regenerating birthday calendars to use new icons and fix old birthday events without year';
62
+    }
63 63
 
64
-	/**
65
-	 * @param IOutput $output
66
-	 */
67
-	public function run(IOutput $output) {
68
-		// only run once
69
-		if ($this->config->getAppValue('dav', 'regeneratedBirthdayCalendarsForYearFix') === 'yes') {
70
-			$output->info('Repair step already executed');
71
-			return;
72
-		}
64
+    /**
65
+     * @param IOutput $output
66
+     */
67
+    public function run(IOutput $output) {
68
+        // only run once
69
+        if ($this->config->getAppValue('dav', 'regeneratedBirthdayCalendarsForYearFix') === 'yes') {
70
+            $output->info('Repair step already executed');
71
+            return;
72
+        }
73 73
 
74
-		$output->info('Adding background jobs to regenerate birthday calendar');
75
-		$this->userManager->callForSeenUsers(function(IUser $user) {
76
-			$this->jobList->add(GenerateBirthdayCalendarBackgroundJob::class, [
77
-				'userId' => $user->getUID(),
78
-				'purgeBeforeGenerating' => true
79
-			]);
80
-		});
74
+        $output->info('Adding background jobs to regenerate birthday calendar');
75
+        $this->userManager->callForSeenUsers(function(IUser $user) {
76
+            $this->jobList->add(GenerateBirthdayCalendarBackgroundJob::class, [
77
+                'userId' => $user->getUID(),
78
+                'purgeBeforeGenerating' => true
79
+            ]);
80
+        });
81 81
 
82
-		// if all were done, no need to redo the repair during next upgrade
83
-		$this->config->setAppValue('dav', 'regeneratedBirthdayCalendarsForYearFix', 'yes');
84
-	}
82
+        // if all were done, no need to redo the repair during next upgrade
83
+        $this->config->setAppValue('dav', 'regeneratedBirthdayCalendarsForYearFix', 'yes');
84
+    }
85 85
 }
Please login to merge, or discard this patch.