SyncService.php 9.8 KB

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