SyncService.php 8.0 KB

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