1
0

SyncService.php 9.4 KB

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