SyncService.php 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345
  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 Joas Schilling <coding@schilljs.com>
  9. * @author Morris Jobke <hey@morrisjobke.de>
  10. * @author Thomas Citharel <nextcloud@tcit.fr>
  11. * @author Thomas Müller <thomas.mueller@tmit.eu>
  12. *
  13. * @license AGPL-3.0
  14. *
  15. * This code is free software: you can redistribute it and/or modify
  16. * it under the terms of the GNU Affero General Public License, version 3,
  17. * as published by the Free Software Foundation.
  18. *
  19. * This program is distributed in the hope that it will be useful,
  20. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  21. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  22. * GNU Affero General Public License for more details.
  23. *
  24. * You should have received a copy of the GNU Affero General Public License, version 3,
  25. * along with this program. If not, see <http://www.gnu.org/licenses/>
  26. *
  27. */
  28. namespace OCA\DAV\CardDAV;
  29. use OC\Accounts\AccountManager;
  30. use OCP\AppFramework\Http;
  31. use OCP\ICertificateManager;
  32. use OCP\ILogger;
  33. use OCP\IUser;
  34. use OCP\IUserManager;
  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. /** @var ILogger */
  46. private $logger;
  47. /** @var array */
  48. private $localSystemAddressBook;
  49. /** @var AccountManager */
  50. private $accountManager;
  51. /** @var string */
  52. protected $certPath;
  53. /**
  54. * SyncService constructor.
  55. *
  56. * @param CardDavBackend $backend
  57. * @param IUserManager $userManager
  58. * @param ILogger $logger
  59. * @param AccountManager $accountManager
  60. */
  61. public function __construct(CardDavBackend $backend, IUserManager $userManager, ILogger $logger, AccountManager $accountManager) {
  62. $this->backend = $backend;
  63. $this->userManager = $userManager;
  64. $this->logger = $logger;
  65. $this->accountManager = $accountManager;
  66. $this->certPath = '';
  67. }
  68. /**
  69. * @param string $url
  70. * @param string $userName
  71. * @param string $addressBookUrl
  72. * @param string $sharedSecret
  73. * @param string $syncToken
  74. * @param int $targetBookId
  75. * @param string $targetPrincipal
  76. * @param array $targetProperties
  77. * @return string
  78. * @throws \Exception
  79. */
  80. public function syncRemoteAddressBook($url, $userName, $addressBookUrl, $sharedSecret, $syncToken, $targetBookId, $targetPrincipal, $targetProperties) {
  81. // 1. create addressbook
  82. $book = $this->ensureSystemAddressBookExists($targetPrincipal, $targetBookId, $targetProperties);
  83. $addressBookId = $book['id'];
  84. // 2. query changes
  85. try {
  86. $response = $this->requestSyncReport($url, $userName, $addressBookUrl, $sharedSecret, $syncToken);
  87. } catch (ClientHttpException $ex) {
  88. if ($ex->getCode() === Http::STATUS_UNAUTHORIZED) {
  89. // remote server revoked access to the address book, remove it
  90. $this->backend->deleteAddressBook($addressBookId);
  91. $this->logger->info('Authorization failed, remove address book: ' . $url, ['app' => 'dav']);
  92. throw $ex;
  93. }
  94. }
  95. // 3. apply changes
  96. // TODO: use multi-get for download
  97. foreach ($response['response'] as $resource => $status) {
  98. $cardUri = basename($resource);
  99. if (isset($status[200])) {
  100. $vCard = $this->download($url, $userName, $sharedSecret, $resource);
  101. $existingCard = $this->backend->getCard($addressBookId, $cardUri);
  102. if ($existingCard === false) {
  103. $this->backend->createCard($addressBookId, $cardUri, $vCard['body']);
  104. } else {
  105. $this->backend->updateCard($addressBookId, $cardUri, $vCard['body']);
  106. }
  107. } else {
  108. $this->backend->deleteCard($addressBookId, $cardUri);
  109. }
  110. }
  111. return $response['token'];
  112. }
  113. /**
  114. * @param string $principal
  115. * @param string $id
  116. * @param array $properties
  117. * @return array|null
  118. * @throws \Sabre\DAV\Exception\BadRequest
  119. */
  120. public function ensureSystemAddressBookExists($principal, $id, $properties) {
  121. $book = $this->backend->getAddressBooksByUri($principal, $id);
  122. if (!is_null($book)) {
  123. return $book;
  124. }
  125. $this->backend->createAddressBook($principal, $id, $properties);
  126. return $this->backend->getAddressBooksByUri($principal, $id);
  127. }
  128. /**
  129. * Check if there is a valid certPath we should use
  130. *
  131. * @return string
  132. */
  133. protected function getCertPath() {
  134. // we already have a valid certPath
  135. if ($this->certPath !== '') {
  136. return $this->certPath;
  137. }
  138. /** @var ICertificateManager $certManager */
  139. $certManager = \OC::$server->getCertificateManager(null);
  140. $certPath = $certManager->getAbsoluteBundlePath();
  141. if (file_exists($certPath)) {
  142. $this->certPath = $certPath;
  143. }
  144. return $this->certPath;
  145. }
  146. /**
  147. * @param string $url
  148. * @param string $userName
  149. * @param string $addressBookUrl
  150. * @param string $sharedSecret
  151. * @return Client
  152. */
  153. protected function getClient($url, $userName, $sharedSecret) {
  154. $settings = [
  155. 'baseUri' => $url . '/',
  156. 'userName' => $userName,
  157. 'password' => $sharedSecret,
  158. ];
  159. $client = new Client($settings);
  160. $certPath = $this->getCertPath();
  161. $client->setThrowExceptions(true);
  162. if ($certPath !== '' && strpos($url, 'http://') !== 0) {
  163. $client->addCurlSetting(CURLOPT_CAINFO, $this->certPath);
  164. }
  165. return $client;
  166. }
  167. /**
  168. * @param string $url
  169. * @param string $userName
  170. * @param string $addressBookUrl
  171. * @param string $sharedSecret
  172. * @param string $syncToken
  173. * @return array
  174. */
  175. protected function requestSyncReport($url, $userName, $addressBookUrl, $sharedSecret, $syncToken) {
  176. $client = $this->getClient($url, $userName, $sharedSecret);
  177. $body = $this->buildSyncCollectionRequestBody($syncToken);
  178. $response = $client->request('REPORT', $addressBookUrl, $body, [
  179. 'Content-Type' => 'application/xml'
  180. ]);
  181. return $this->parseMultiStatus($response['body']);
  182. }
  183. /**
  184. * @param string $url
  185. * @param string $userName
  186. * @param string $sharedSecret
  187. * @param string $resourcePath
  188. * @return array
  189. */
  190. protected function download($url, $userName, $sharedSecret, $resourcePath) {
  191. $client = $this->getClient($url, $userName, $sharedSecret);
  192. return $client->request('GET', $resourcePath);
  193. }
  194. /**
  195. * @param string|null $syncToken
  196. * @return string
  197. */
  198. private function buildSyncCollectionRequestBody($syncToken) {
  199. $dom = new \DOMDocument('1.0', 'UTF-8');
  200. $dom->formatOutput = true;
  201. $root = $dom->createElementNS('DAV:', 'd:sync-collection');
  202. $sync = $dom->createElement('d:sync-token', $syncToken);
  203. $prop = $dom->createElement('d:prop');
  204. $cont = $dom->createElement('d:getcontenttype');
  205. $etag = $dom->createElement('d:getetag');
  206. $prop->appendChild($cont);
  207. $prop->appendChild($etag);
  208. $root->appendChild($sync);
  209. $root->appendChild($prop);
  210. $dom->appendChild($root);
  211. return $dom->saveXML();
  212. }
  213. /**
  214. * @param string $body
  215. * @return array
  216. * @throws \Sabre\Xml\ParseException
  217. */
  218. private function parseMultiStatus($body) {
  219. $xml = new Service();
  220. /** @var MultiStatus $multiStatus */
  221. $multiStatus = $xml->expect('{DAV:}multistatus', $body);
  222. $result = [];
  223. foreach ($multiStatus->getResponses() as $response) {
  224. $result[$response->getHref()] = $response->getResponseProperties();
  225. }
  226. return ['response' => $result, 'token' => $multiStatus->getSyncToken()];
  227. }
  228. /**
  229. * @param IUser $user
  230. */
  231. public function updateUser(IUser $user) {
  232. $systemAddressBook = $this->getLocalSystemAddressBook();
  233. $addressBookId = $systemAddressBook['id'];
  234. $converter = new Converter($this->accountManager);
  235. $name = $user->getBackendClassName();
  236. $userId = $user->getUID();
  237. $cardId = "$name:$userId.vcf";
  238. $card = $this->backend->getCard($addressBookId, $cardId);
  239. if ($user->isEnabled()) {
  240. if ($card === false) {
  241. $vCard = $converter->createCardFromUser($user);
  242. if ($vCard !== null) {
  243. $this->backend->createCard($addressBookId, $cardId, $vCard->serialize());
  244. }
  245. } else {
  246. $vCard = $converter->createCardFromUser($user);
  247. if (is_null($vCard)) {
  248. $this->backend->deleteCard($addressBookId, $cardId);
  249. } else {
  250. $this->backend->updateCard($addressBookId, $cardId, $vCard->serialize());
  251. }
  252. }
  253. } else {
  254. $this->backend->deleteCard($addressBookId, $cardId);
  255. }
  256. }
  257. /**
  258. * @param IUser|string $userOrCardId
  259. */
  260. public function deleteUser($userOrCardId) {
  261. $systemAddressBook = $this->getLocalSystemAddressBook();
  262. if ($userOrCardId instanceof IUser){
  263. $name = $userOrCardId->getBackendClassName();
  264. $userId = $userOrCardId->getUID();
  265. $userOrCardId = "$name:$userId.vcf";
  266. }
  267. $this->backend->deleteCard($systemAddressBook['id'], $userOrCardId);
  268. }
  269. /**
  270. * @return array|null
  271. */
  272. public function getLocalSystemAddressBook() {
  273. if (is_null($this->localSystemAddressBook)) {
  274. $systemPrincipal = "principals/system/system";
  275. $this->localSystemAddressBook = $this->ensureSystemAddressBookExists($systemPrincipal, 'system', [
  276. '{' . Plugin::NS_CARDDAV . '}addressbook-description' => 'System addressbook which holds all users of this instance'
  277. ]);
  278. }
  279. return $this->localSystemAddressBook;
  280. }
  281. public function syncInstance(\Closure $progressCallback = null) {
  282. $systemAddressBook = $this->getLocalSystemAddressBook();
  283. $this->userManager->callForSeenUsers(function($user) use ($systemAddressBook, $progressCallback) {
  284. $this->updateUser($user);
  285. if (!is_null($progressCallback)) {
  286. $progressCallback();
  287. }
  288. });
  289. // remove no longer existing
  290. $allCards = $this->backend->getCards($systemAddressBook['id']);
  291. foreach($allCards as $card) {
  292. $vCard = Reader::read($card['carddata']);
  293. $uid = $vCard->UID->getValue();
  294. // load backend and see if user exists
  295. if (!$this->userManager->userExists($uid)) {
  296. $this->deleteUser($card['uri']);
  297. }
  298. }
  299. }
  300. }