SyncService.php 8.5 KB

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