You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

SyncService.php 9.5KB

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