SyncService.php 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284
  1. <?php
  2. /**
  3. * @copyright Copyright (c) 2016, ownCloud, Inc.
  4. *
  5. * @author Arthur Schiwon <blizzz@arthur-schiwon.de>
  6. * @author Bjoern Schiessle <bjoern@schiessle.org>
  7. * @author Björn Schießle <bjoern@schiessle.org>
  8. * @author Christoph Wurst <christoph@winzerhof-wurst.at>
  9. * @author Joas Schilling <coding@schilljs.com>
  10. * @author Morris Jobke <hey@morrisjobke.de>
  11. * @author Thomas Citharel <nextcloud@tcit.fr>
  12. * @author Thomas Müller <thomas.mueller@tmit.eu>
  13. *
  14. * @license AGPL-3.0
  15. *
  16. * This code is free software: you can redistribute it and/or modify
  17. * it under the terms of the GNU Affero General Public License, version 3,
  18. * as published by the Free Software Foundation.
  19. *
  20. * This program is distributed in the hope that it will be useful,
  21. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  22. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  23. * GNU Affero General Public License for more details.
  24. *
  25. * You should have received a copy of the GNU Affero General Public License, version 3,
  26. * along with this program. If not, see <http://www.gnu.org/licenses/>
  27. *
  28. */
  29. namespace OCA\DAV\CardDAV;
  30. use OC\Accounts\AccountManager;
  31. use OCP\AppFramework\Http;
  32. use OCP\IUser;
  33. use OCP\IUserManager;
  34. use Psr\Log\LoggerInterface;
  35. use Sabre\DAV\Client;
  36. use Sabre\DAV\Xml\Response\MultiStatus;
  37. use Sabre\DAV\Xml\Service;
  38. use Sabre\HTTP\ClientHttpException;
  39. use Sabre\VObject\Reader;
  40. class SyncService {
  41. private CardDavBackend $backend;
  42. private IUserManager $userManager;
  43. private LoggerInterface $logger;
  44. private ?array $localSystemAddressBook = null;
  45. private Converter $converter;
  46. protected string $certPath;
  47. public function __construct(CardDavBackend $backend,
  48. IUserManager $userManager,
  49. LoggerInterface $logger,
  50. Converter $converter) {
  51. $this->backend = $backend;
  52. $this->userManager = $userManager;
  53. $this->logger = $logger;
  54. $this->converter = $converter;
  55. $this->certPath = '';
  56. }
  57. /**
  58. * @throws \Exception
  59. */
  60. public function syncRemoteAddressBook(string $url, string $userName, string $addressBookUrl, string $sharedSecret, ?string $syncToken, string $targetBookHash, string $targetPrincipal, array $targetProperties): string {
  61. // 1. create addressbook
  62. $book = $this->ensureSystemAddressBookExists($targetPrincipal, $targetBookHash, $targetProperties);
  63. $addressBookId = $book['id'];
  64. // 2. query changes
  65. try {
  66. $response = $this->requestSyncReport($url, $userName, $addressBookUrl, $sharedSecret, $syncToken);
  67. } catch (ClientHttpException $ex) {
  68. if ($ex->getCode() === Http::STATUS_UNAUTHORIZED) {
  69. // remote server revoked access to the address book, remove it
  70. $this->backend->deleteAddressBook($addressBookId);
  71. $this->logger->error('Authorization failed, remove address book: ' . $url, ['app' => 'dav']);
  72. throw $ex;
  73. }
  74. $this->logger->error('Client exception:', ['app' => 'dav', 'exception' => $ex]);
  75. throw $ex;
  76. }
  77. // 3. apply changes
  78. // TODO: use multi-get for download
  79. foreach ($response['response'] as $resource => $status) {
  80. $cardUri = basename($resource);
  81. if (isset($status[200])) {
  82. $vCard = $this->download($url, $userName, $sharedSecret, $resource);
  83. $existingCard = $this->backend->getCard($addressBookId, $cardUri);
  84. if ($existingCard === false) {
  85. $this->backend->createCard($addressBookId, $cardUri, $vCard['body']);
  86. } else {
  87. $this->backend->updateCard($addressBookId, $cardUri, $vCard['body']);
  88. }
  89. } else {
  90. $this->backend->deleteCard($addressBookId, $cardUri);
  91. }
  92. }
  93. return $response['token'];
  94. }
  95. /**
  96. * @throws \Sabre\DAV\Exception\BadRequest
  97. */
  98. public function ensureSystemAddressBookExists(string $principal, string $uri, array $properties): ?array {
  99. $book = $this->backend->getAddressBooksByUri($principal, $uri);
  100. if (!is_null($book)) {
  101. return $book;
  102. }
  103. // FIXME This might break in clustered DB setup
  104. $this->backend->createAddressBook($principal, $uri, $properties);
  105. return $this->backend->getAddressBooksByUri($principal, $uri);
  106. }
  107. /**
  108. * Check if there is a valid certPath we should use
  109. */
  110. protected function getCertPath(): string {
  111. // we already have a valid certPath
  112. if ($this->certPath !== '') {
  113. return $this->certPath;
  114. }
  115. $certManager = \OC::$server->getCertificateManager();
  116. $certPath = $certManager->getAbsoluteBundlePath();
  117. if (file_exists($certPath)) {
  118. $this->certPath = $certPath;
  119. }
  120. return $this->certPath;
  121. }
  122. protected function getClient(string $url, string $userName, string $sharedSecret): Client {
  123. $settings = [
  124. 'baseUri' => $url . '/',
  125. 'userName' => $userName,
  126. 'password' => $sharedSecret,
  127. ];
  128. $client = new Client($settings);
  129. $certPath = $this->getCertPath();
  130. $client->setThrowExceptions(true);
  131. if ($certPath !== '' && strpos($url, 'http://') !== 0) {
  132. $client->addCurlSetting(CURLOPT_CAINFO, $this->certPath);
  133. }
  134. return $client;
  135. }
  136. protected function requestSyncReport(string $url, string $userName, string $addressBookUrl, string $sharedSecret, ?string $syncToken): array {
  137. $client = $this->getClient($url, $userName, $sharedSecret);
  138. $body = $this->buildSyncCollectionRequestBody($syncToken);
  139. $response = $client->request('REPORT', $addressBookUrl, $body, [
  140. 'Content-Type' => 'application/xml'
  141. ]);
  142. return $this->parseMultiStatus($response['body']);
  143. }
  144. protected function download(string $url, string $userName, string $sharedSecret, string $resourcePath): array {
  145. $client = $this->getClient($url, $userName, $sharedSecret);
  146. return $client->request('GET', $resourcePath);
  147. }
  148. private function buildSyncCollectionRequestBody(?string $syncToken): string {
  149. $dom = new \DOMDocument('1.0', 'UTF-8');
  150. $dom->formatOutput = true;
  151. $root = $dom->createElementNS('DAV:', 'd:sync-collection');
  152. $sync = $dom->createElement('d:sync-token', $syncToken);
  153. $prop = $dom->createElement('d:prop');
  154. $cont = $dom->createElement('d:getcontenttype');
  155. $etag = $dom->createElement('d:getetag');
  156. $prop->appendChild($cont);
  157. $prop->appendChild($etag);
  158. $root->appendChild($sync);
  159. $root->appendChild($prop);
  160. $dom->appendChild($root);
  161. return $dom->saveXML();
  162. }
  163. /**
  164. * @param string $body
  165. * @return array
  166. * @throws \Sabre\Xml\ParseException
  167. */
  168. private function parseMultiStatus($body) {
  169. $xml = new Service();
  170. /** @var MultiStatus $multiStatus */
  171. $multiStatus = $xml->expect('{DAV:}multistatus', $body);
  172. $result = [];
  173. foreach ($multiStatus->getResponses() as $response) {
  174. $result[$response->getHref()] = $response->getResponseProperties();
  175. }
  176. return ['response' => $result, 'token' => $multiStatus->getSyncToken()];
  177. }
  178. /**
  179. * @param IUser $user
  180. */
  181. public function updateUser(IUser $user) {
  182. $systemAddressBook = $this->getLocalSystemAddressBook();
  183. $addressBookId = $systemAddressBook['id'];
  184. $name = $user->getBackendClassName();
  185. $userId = $user->getUID();
  186. $cardId = "$name:$userId.vcf";
  187. if ($user->isEnabled()) {
  188. $card = $this->backend->getCard($addressBookId, $cardId);
  189. if ($card === false) {
  190. $vCard = $this->converter->createCardFromUser($user);
  191. if ($vCard !== null) {
  192. $this->backend->createCard($addressBookId, $cardId, $vCard->serialize(), false);
  193. }
  194. } else {
  195. $vCard = $this->converter->createCardFromUser($user);
  196. if (is_null($vCard)) {
  197. $this->backend->deleteCard($addressBookId, $cardId);
  198. } else {
  199. $this->backend->updateCard($addressBookId, $cardId, $vCard->serialize());
  200. }
  201. }
  202. } else {
  203. $this->backend->deleteCard($addressBookId, $cardId);
  204. }
  205. }
  206. /**
  207. * @param IUser|string $userOrCardId
  208. */
  209. public function deleteUser($userOrCardId) {
  210. $systemAddressBook = $this->getLocalSystemAddressBook();
  211. if ($userOrCardId instanceof IUser) {
  212. $name = $userOrCardId->getBackendClassName();
  213. $userId = $userOrCardId->getUID();
  214. $userOrCardId = "$name:$userId.vcf";
  215. }
  216. $this->backend->deleteCard($systemAddressBook['id'], $userOrCardId);
  217. }
  218. /**
  219. * @return array|null
  220. */
  221. public function getLocalSystemAddressBook() {
  222. if (is_null($this->localSystemAddressBook)) {
  223. $systemPrincipal = "principals/system/system";
  224. $this->localSystemAddressBook = $this->ensureSystemAddressBookExists($systemPrincipal, 'system', [
  225. '{' . Plugin::NS_CARDDAV . '}addressbook-description' => 'System addressbook which holds all users of this instance'
  226. ]);
  227. }
  228. return $this->localSystemAddressBook;
  229. }
  230. public function syncInstance(\Closure $progressCallback = null) {
  231. $systemAddressBook = $this->getLocalSystemAddressBook();
  232. $this->userManager->callForAllUsers(function ($user) use ($systemAddressBook, $progressCallback) {
  233. $this->updateUser($user);
  234. if (!is_null($progressCallback)) {
  235. $progressCallback();
  236. }
  237. });
  238. // remove no longer existing
  239. $allCards = $this->backend->getCards($systemAddressBook['id']);
  240. foreach ($allCards as $card) {
  241. $vCard = Reader::read($card['carddata']);
  242. $uid = $vCard->UID->getValue();
  243. // load backend and see if user exists
  244. if (!$this->userManager->userExists($uid)) {
  245. $this->deleteUser($card['uri']);
  246. }
  247. }
  248. }
  249. }