SyncService.php 9.5 KB

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