CardDavBackend.php 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086
  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 Georg Ehrke <georg@owncloud.com>
  9. * @author Joas Schilling <coding@schilljs.com>
  10. * @author Stefan Weil <sw@weilnetz.de>
  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 OCA\DAV\Connector\Sabre\Principal;
  30. use OCP\DB\QueryBuilder\IQueryBuilder;
  31. use OCA\DAV\DAV\Sharing\Backend;
  32. use OCA\DAV\DAV\Sharing\IShareable;
  33. use OCP\IDBConnection;
  34. use OCP\IUser;
  35. use OCP\IUserManager;
  36. use PDO;
  37. use Sabre\CardDAV\Backend\BackendInterface;
  38. use Sabre\CardDAV\Backend\SyncSupport;
  39. use Sabre\CardDAV\Plugin;
  40. use Sabre\DAV\Exception\BadRequest;
  41. use Sabre\HTTP\URLUtil;
  42. use Sabre\VObject\Component\VCard;
  43. use Sabre\VObject\Reader;
  44. use Symfony\Component\EventDispatcher\EventDispatcherInterface;
  45. use Symfony\Component\EventDispatcher\GenericEvent;
  46. class CardDavBackend implements BackendInterface, SyncSupport {
  47. const PERSONAL_ADDRESSBOOK_URI = 'contacts';
  48. const PERSONAL_ADDRESSBOOK_NAME = 'Contacts';
  49. /** @var Principal */
  50. private $principalBackend;
  51. /** @var string */
  52. private $dbCardsTable = 'cards';
  53. /** @var string */
  54. private $dbCardsPropertiesTable = 'cards_properties';
  55. /** @var IDBConnection */
  56. private $db;
  57. /** @var Backend */
  58. private $sharingBackend;
  59. /** @var array properties to index */
  60. public static $indexProperties = array(
  61. 'BDAY', 'UID', 'N', 'FN', 'TITLE', 'ROLE', 'NOTE', 'NICKNAME',
  62. 'ORG', 'CATEGORIES', 'EMAIL', 'TEL', 'IMPP', 'ADR', 'URL', 'GEO', 'CLOUD');
  63. /**
  64. * @var string[] Map of uid => display name
  65. */
  66. protected $userDisplayNames;
  67. /** @var IUserManager */
  68. private $userManager;
  69. /** @var EventDispatcherInterface */
  70. private $dispatcher;
  71. /**
  72. * CardDavBackend constructor.
  73. *
  74. * @param IDBConnection $db
  75. * @param Principal $principalBackend
  76. * @param IUserManager $userManager
  77. * @param EventDispatcherInterface $dispatcher
  78. */
  79. public function __construct(IDBConnection $db,
  80. Principal $principalBackend,
  81. IUserManager $userManager,
  82. EventDispatcherInterface $dispatcher = null) {
  83. $this->db = $db;
  84. $this->principalBackend = $principalBackend;
  85. $this->userManager = $userManager;
  86. $this->dispatcher = $dispatcher;
  87. $this->sharingBackend = new Backend($this->db, $principalBackend, 'addressbook');
  88. }
  89. /**
  90. * Return the number of address books for a principal
  91. *
  92. * @param $principalUri
  93. * @return int
  94. */
  95. public function getAddressBooksForUserCount($principalUri) {
  96. $principalUri = $this->convertPrincipal($principalUri, true);
  97. $query = $this->db->getQueryBuilder();
  98. $query->select($query->createFunction('COUNT(*)'))
  99. ->from('addressbooks')
  100. ->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)));
  101. return (int)$query->execute()->fetchColumn();
  102. }
  103. /**
  104. * Returns the list of address books for a specific user.
  105. *
  106. * Every addressbook should have the following properties:
  107. * id - an arbitrary unique id
  108. * uri - the 'basename' part of the url
  109. * principaluri - Same as the passed parameter
  110. *
  111. * Any additional clark-notation property may be passed besides this. Some
  112. * common ones are :
  113. * {DAV:}displayname
  114. * {urn:ietf:params:xml:ns:carddav}addressbook-description
  115. * {http://calendarserver.org/ns/}getctag
  116. *
  117. * @param string $principalUri
  118. * @return array
  119. */
  120. function getAddressBooksForUser($principalUri) {
  121. $principalUriOriginal = $principalUri;
  122. $principalUri = $this->convertPrincipal($principalUri, true);
  123. $query = $this->db->getQueryBuilder();
  124. $query->select(['id', 'uri', 'displayname', 'principaluri', 'description', 'synctoken'])
  125. ->from('addressbooks')
  126. ->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)));
  127. $addressBooks = [];
  128. $result = $query->execute();
  129. while($row = $result->fetch()) {
  130. $addressBooks[$row['id']] = [
  131. 'id' => $row['id'],
  132. 'uri' => $row['uri'],
  133. 'principaluri' => $this->convertPrincipal($row['principaluri'], false),
  134. '{DAV:}displayname' => $row['displayname'],
  135. '{' . Plugin::NS_CARDDAV . '}addressbook-description' => $row['description'],
  136. '{http://calendarserver.org/ns/}getctag' => $row['synctoken'],
  137. '{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
  138. ];
  139. }
  140. $result->closeCursor();
  141. // query for shared calendars
  142. $principals = $this->principalBackend->getGroupMembership($principalUriOriginal, true);
  143. $principals[]= $principalUri;
  144. $query = $this->db->getQueryBuilder();
  145. $result = $query->select(['a.id', 'a.uri', 'a.displayname', 'a.principaluri', 'a.description', 'a.synctoken', 's.access'])
  146. ->from('dav_shares', 's')
  147. ->join('s', 'addressbooks', 'a', $query->expr()->eq('s.resourceid', 'a.id'))
  148. ->where($query->expr()->in('s.principaluri', $query->createParameter('principaluri')))
  149. ->andWhere($query->expr()->eq('s.type', $query->createParameter('type')))
  150. ->setParameter('type', 'addressbook')
  151. ->setParameter('principaluri', $principals, IQueryBuilder::PARAM_STR_ARRAY)
  152. ->execute();
  153. $readOnlyPropertyName = '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}read-only';
  154. while($row = $result->fetch()) {
  155. $readOnly = (int) $row['access'] === Backend::ACCESS_READ;
  156. if (isset($addressBooks[$row['id']])) {
  157. if ($readOnly) {
  158. // New share can not have more permissions then the old one.
  159. continue;
  160. }
  161. if (isset($addressBooks[$row['id']][$readOnlyPropertyName]) &&
  162. $addressBooks[$row['id']][$readOnlyPropertyName] === 0) {
  163. // Old share is already read-write, no more permissions can be gained
  164. continue;
  165. }
  166. }
  167. list(, $name) = URLUtil::splitPath($row['principaluri']);
  168. $uri = $row['uri'] . '_shared_by_' . $name;
  169. $displayName = $row['displayname'] . ' (' . $this->getUserDisplayName($name) . ')';
  170. $addressBooks[$row['id']] = [
  171. 'id' => $row['id'],
  172. 'uri' => $uri,
  173. 'principaluri' => $principalUriOriginal,
  174. '{DAV:}displayname' => $displayName,
  175. '{' . Plugin::NS_CARDDAV . '}addressbook-description' => $row['description'],
  176. '{http://calendarserver.org/ns/}getctag' => $row['synctoken'],
  177. '{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
  178. '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $row['principaluri'],
  179. $readOnlyPropertyName => $readOnly,
  180. ];
  181. }
  182. $result->closeCursor();
  183. return array_values($addressBooks);
  184. }
  185. public function getUsersOwnAddressBooks($principalUri) {
  186. $principalUriOriginal = $principalUri;
  187. $principalUri = $this->convertPrincipal($principalUri, true);
  188. $query = $this->db->getQueryBuilder();
  189. $query->select(['id', 'uri', 'displayname', 'principaluri', 'description', 'synctoken'])
  190. ->from('addressbooks')
  191. ->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)));
  192. $addressBooks = [];
  193. $result = $query->execute();
  194. while($row = $result->fetch()) {
  195. $addressBooks[$row['id']] = [
  196. 'id' => $row['id'],
  197. 'uri' => $row['uri'],
  198. 'principaluri' => $this->convertPrincipal($row['principaluri'], false),
  199. '{DAV:}displayname' => $row['displayname'],
  200. '{' . Plugin::NS_CARDDAV . '}addressbook-description' => $row['description'],
  201. '{http://calendarserver.org/ns/}getctag' => $row['synctoken'],
  202. '{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
  203. ];
  204. }
  205. $result->closeCursor();
  206. return array_values($addressBooks);
  207. }
  208. private function getUserDisplayName($uid) {
  209. if (!isset($this->userDisplayNames[$uid])) {
  210. $user = $this->userManager->get($uid);
  211. if ($user instanceof IUser) {
  212. $this->userDisplayNames[$uid] = $user->getDisplayName();
  213. } else {
  214. $this->userDisplayNames[$uid] = $uid;
  215. }
  216. }
  217. return $this->userDisplayNames[$uid];
  218. }
  219. /**
  220. * @param int $addressBookId
  221. */
  222. public function getAddressBookById($addressBookId) {
  223. $query = $this->db->getQueryBuilder();
  224. $result = $query->select(['id', 'uri', 'displayname', 'principaluri', 'description', 'synctoken'])
  225. ->from('addressbooks')
  226. ->where($query->expr()->eq('id', $query->createNamedParameter($addressBookId)))
  227. ->execute();
  228. $row = $result->fetch();
  229. $result->closeCursor();
  230. if ($row === false) {
  231. return null;
  232. }
  233. return [
  234. 'id' => $row['id'],
  235. 'uri' => $row['uri'],
  236. 'principaluri' => $row['principaluri'],
  237. '{DAV:}displayname' => $row['displayname'],
  238. '{' . Plugin::NS_CARDDAV . '}addressbook-description' => $row['description'],
  239. '{http://calendarserver.org/ns/}getctag' => $row['synctoken'],
  240. '{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
  241. ];
  242. }
  243. /**
  244. * @param $addressBookUri
  245. * @return array|null
  246. */
  247. public function getAddressBooksByUri($principal, $addressBookUri) {
  248. $query = $this->db->getQueryBuilder();
  249. $result = $query->select(['id', 'uri', 'displayname', 'principaluri', 'description', 'synctoken'])
  250. ->from('addressbooks')
  251. ->where($query->expr()->eq('uri', $query->createNamedParameter($addressBookUri)))
  252. ->andWhere($query->expr()->eq('principaluri', $query->createNamedParameter($principal)))
  253. ->setMaxResults(1)
  254. ->execute();
  255. $row = $result->fetch();
  256. $result->closeCursor();
  257. if ($row === false) {
  258. return null;
  259. }
  260. return [
  261. 'id' => $row['id'],
  262. 'uri' => $row['uri'],
  263. 'principaluri' => $row['principaluri'],
  264. '{DAV:}displayname' => $row['displayname'],
  265. '{' . Plugin::NS_CARDDAV . '}addressbook-description' => $row['description'],
  266. '{http://calendarserver.org/ns/}getctag' => $row['synctoken'],
  267. '{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
  268. ];
  269. }
  270. /**
  271. * Updates properties for an address book.
  272. *
  273. * The list of mutations is stored in a Sabre\DAV\PropPatch object.
  274. * To do the actual updates, you must tell this object which properties
  275. * you're going to process with the handle() method.
  276. *
  277. * Calling the handle method is like telling the PropPatch object "I
  278. * promise I can handle updating this property".
  279. *
  280. * Read the PropPatch documentation for more info and examples.
  281. *
  282. * @param string $addressBookId
  283. * @param \Sabre\DAV\PropPatch $propPatch
  284. * @return void
  285. */
  286. function updateAddressBook($addressBookId, \Sabre\DAV\PropPatch $propPatch) {
  287. $supportedProperties = [
  288. '{DAV:}displayname',
  289. '{' . Plugin::NS_CARDDAV . '}addressbook-description',
  290. ];
  291. $propPatch->handle($supportedProperties, function($mutations) use ($addressBookId) {
  292. $updates = [];
  293. foreach($mutations as $property=>$newValue) {
  294. switch($property) {
  295. case '{DAV:}displayname' :
  296. $updates['displayname'] = $newValue;
  297. break;
  298. case '{' . Plugin::NS_CARDDAV . '}addressbook-description' :
  299. $updates['description'] = $newValue;
  300. break;
  301. }
  302. }
  303. $query = $this->db->getQueryBuilder();
  304. $query->update('addressbooks');
  305. foreach($updates as $key=>$value) {
  306. $query->set($key, $query->createNamedParameter($value));
  307. }
  308. $query->where($query->expr()->eq('id', $query->createNamedParameter($addressBookId)))
  309. ->execute();
  310. $this->addChange($addressBookId, "", 2);
  311. return true;
  312. });
  313. }
  314. /**
  315. * Creates a new address book
  316. *
  317. * @param string $principalUri
  318. * @param string $url Just the 'basename' of the url.
  319. * @param array $properties
  320. * @return int
  321. * @throws BadRequest
  322. */
  323. function createAddressBook($principalUri, $url, array $properties) {
  324. $values = [
  325. 'displayname' => null,
  326. 'description' => null,
  327. 'principaluri' => $principalUri,
  328. 'uri' => $url,
  329. 'synctoken' => 1
  330. ];
  331. foreach($properties as $property=>$newValue) {
  332. switch($property) {
  333. case '{DAV:}displayname' :
  334. $values['displayname'] = $newValue;
  335. break;
  336. case '{' . Plugin::NS_CARDDAV . '}addressbook-description' :
  337. $values['description'] = $newValue;
  338. break;
  339. default :
  340. throw new BadRequest('Unknown property: ' . $property);
  341. }
  342. }
  343. // Fallback to make sure the displayname is set. Some clients may refuse
  344. // to work with addressbooks not having a displayname.
  345. if(is_null($values['displayname'])) {
  346. $values['displayname'] = $url;
  347. }
  348. $query = $this->db->getQueryBuilder();
  349. $query->insert('addressbooks')
  350. ->values([
  351. 'uri' => $query->createParameter('uri'),
  352. 'displayname' => $query->createParameter('displayname'),
  353. 'description' => $query->createParameter('description'),
  354. 'principaluri' => $query->createParameter('principaluri'),
  355. 'synctoken' => $query->createParameter('synctoken'),
  356. ])
  357. ->setParameters($values)
  358. ->execute();
  359. return $query->getLastInsertId();
  360. }
  361. /**
  362. * Deletes an entire addressbook and all its contents
  363. *
  364. * @param mixed $addressBookId
  365. * @return void
  366. */
  367. function deleteAddressBook($addressBookId) {
  368. $query = $this->db->getQueryBuilder();
  369. $query->delete('cards')
  370. ->where($query->expr()->eq('addressbookid', $query->createParameter('addressbookid')))
  371. ->setParameter('addressbookid', $addressBookId)
  372. ->execute();
  373. $query->delete('addressbookchanges')
  374. ->where($query->expr()->eq('addressbookid', $query->createParameter('addressbookid')))
  375. ->setParameter('addressbookid', $addressBookId)
  376. ->execute();
  377. $query->delete('addressbooks')
  378. ->where($query->expr()->eq('id', $query->createParameter('id')))
  379. ->setParameter('id', $addressBookId)
  380. ->execute();
  381. $this->sharingBackend->deleteAllShares($addressBookId);
  382. $query->delete($this->dbCardsPropertiesTable)
  383. ->where($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId)))
  384. ->execute();
  385. }
  386. /**
  387. * Returns all cards for a specific addressbook id.
  388. *
  389. * This method should return the following properties for each card:
  390. * * carddata - raw vcard data
  391. * * uri - Some unique url
  392. * * lastmodified - A unix timestamp
  393. *
  394. * It's recommended to also return the following properties:
  395. * * etag - A unique etag. This must change every time the card changes.
  396. * * size - The size of the card in bytes.
  397. *
  398. * If these last two properties are provided, less time will be spent
  399. * calculating them. If they are specified, you can also ommit carddata.
  400. * This may speed up certain requests, especially with large cards.
  401. *
  402. * @param mixed $addressBookId
  403. * @return array
  404. */
  405. function getCards($addressBookId) {
  406. $query = $this->db->getQueryBuilder();
  407. $query->select(['id', 'uri', 'lastmodified', 'etag', 'size', 'carddata'])
  408. ->from('cards')
  409. ->where($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId)));
  410. $cards = [];
  411. $result = $query->execute();
  412. while($row = $result->fetch()) {
  413. $row['etag'] = '"' . $row['etag'] . '"';
  414. $row['carddata'] = $this->readBlob($row['carddata']);
  415. $cards[] = $row;
  416. }
  417. $result->closeCursor();
  418. return $cards;
  419. }
  420. /**
  421. * Returns a specific card.
  422. *
  423. * The same set of properties must be returned as with getCards. The only
  424. * exception is that 'carddata' is absolutely required.
  425. *
  426. * If the card does not exist, you must return false.
  427. *
  428. * @param mixed $addressBookId
  429. * @param string $cardUri
  430. * @return array
  431. */
  432. function getCard($addressBookId, $cardUri) {
  433. $query = $this->db->getQueryBuilder();
  434. $query->select(['id', 'uri', 'lastmodified', 'etag', 'size', 'carddata'])
  435. ->from('cards')
  436. ->where($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId)))
  437. ->andWhere($query->expr()->eq('uri', $query->createNamedParameter($cardUri)))
  438. ->setMaxResults(1);
  439. $result = $query->execute();
  440. $row = $result->fetch();
  441. if (!$row) {
  442. return false;
  443. }
  444. $row['etag'] = '"' . $row['etag'] . '"';
  445. $row['carddata'] = $this->readBlob($row['carddata']);
  446. return $row;
  447. }
  448. /**
  449. * Returns a list of cards.
  450. *
  451. * This method should work identical to getCard, but instead return all the
  452. * cards in the list as an array.
  453. *
  454. * If the backend supports this, it may allow for some speed-ups.
  455. *
  456. * @param mixed $addressBookId
  457. * @param string[] $uris
  458. * @return array
  459. */
  460. function getMultipleCards($addressBookId, array $uris) {
  461. if (empty($uris)) {
  462. return [];
  463. }
  464. $chunks = array_chunk($uris, 100);
  465. $cards = [];
  466. $query = $this->db->getQueryBuilder();
  467. $query->select(['id', 'uri', 'lastmodified', 'etag', 'size', 'carddata'])
  468. ->from('cards')
  469. ->where($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId)))
  470. ->andWhere($query->expr()->in('uri', $query->createParameter('uri')));
  471. foreach ($chunks as $uris) {
  472. $query->setParameter('uri', $uris, IQueryBuilder::PARAM_STR_ARRAY);
  473. $result = $query->execute();
  474. while ($row = $result->fetch()) {
  475. $row['etag'] = '"' . $row['etag'] . '"';
  476. $row['carddata'] = $this->readBlob($row['carddata']);
  477. $cards[] = $row;
  478. }
  479. $result->closeCursor();
  480. }
  481. return $cards;
  482. }
  483. /**
  484. * Creates a new card.
  485. *
  486. * The addressbook id will be passed as the first argument. This is the
  487. * same id as it is returned from the getAddressBooksForUser method.
  488. *
  489. * The cardUri is a base uri, and doesn't include the full path. The
  490. * cardData argument is the vcard body, and is passed as a string.
  491. *
  492. * It is possible to return an ETag from this method. This ETag is for the
  493. * newly created resource, and must be enclosed with double quotes (that
  494. * is, the string itself must contain the double quotes).
  495. *
  496. * You should only return the ETag if you store the carddata as-is. If a
  497. * subsequent GET request on the same card does not have the same body,
  498. * byte-by-byte and you did return an ETag here, clients tend to get
  499. * confused.
  500. *
  501. * If you don't return an ETag, you can just return null.
  502. *
  503. * @param mixed $addressBookId
  504. * @param string $cardUri
  505. * @param string $cardData
  506. * @return string
  507. */
  508. function createCard($addressBookId, $cardUri, $cardData) {
  509. $etag = md5($cardData);
  510. $query = $this->db->getQueryBuilder();
  511. $query->insert('cards')
  512. ->values([
  513. 'carddata' => $query->createNamedParameter($cardData, IQueryBuilder::PARAM_LOB),
  514. 'uri' => $query->createNamedParameter($cardUri),
  515. 'lastmodified' => $query->createNamedParameter(time()),
  516. 'addressbookid' => $query->createNamedParameter($addressBookId),
  517. 'size' => $query->createNamedParameter(strlen($cardData)),
  518. 'etag' => $query->createNamedParameter($etag),
  519. ])
  520. ->execute();
  521. $this->addChange($addressBookId, $cardUri, 1);
  522. $this->updateProperties($addressBookId, $cardUri, $cardData);
  523. if (!is_null($this->dispatcher)) {
  524. $this->dispatcher->dispatch('\OCA\DAV\CardDAV\CardDavBackend::createCard',
  525. new GenericEvent(null, [
  526. 'addressBookId' => $addressBookId,
  527. 'cardUri' => $cardUri,
  528. 'cardData' => $cardData]));
  529. }
  530. return '"' . $etag . '"';
  531. }
  532. /**
  533. * Updates a card.
  534. *
  535. * The addressbook id will be passed as the first argument. This is the
  536. * same id as it is returned from the getAddressBooksForUser method.
  537. *
  538. * The cardUri is a base uri, and doesn't include the full path. The
  539. * cardData argument is the vcard body, and is passed as a string.
  540. *
  541. * It is possible to return an ETag from this method. This ETag should
  542. * match that of the updated resource, and must be enclosed with double
  543. * quotes (that is: the string itself must contain the actual quotes).
  544. *
  545. * You should only return the ETag if you store the carddata as-is. If a
  546. * subsequent GET request on the same card does not have the same body,
  547. * byte-by-byte and you did return an ETag here, clients tend to get
  548. * confused.
  549. *
  550. * If you don't return an ETag, you can just return null.
  551. *
  552. * @param mixed $addressBookId
  553. * @param string $cardUri
  554. * @param string $cardData
  555. * @return string
  556. */
  557. function updateCard($addressBookId, $cardUri, $cardData) {
  558. $etag = md5($cardData);
  559. $query = $this->db->getQueryBuilder();
  560. $query->update('cards')
  561. ->set('carddata', $query->createNamedParameter($cardData, IQueryBuilder::PARAM_LOB))
  562. ->set('lastmodified', $query->createNamedParameter(time()))
  563. ->set('size', $query->createNamedParameter(strlen($cardData)))
  564. ->set('etag', $query->createNamedParameter($etag))
  565. ->where($query->expr()->eq('uri', $query->createNamedParameter($cardUri)))
  566. ->andWhere($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId)))
  567. ->execute();
  568. $this->addChange($addressBookId, $cardUri, 2);
  569. $this->updateProperties($addressBookId, $cardUri, $cardData);
  570. if (!is_null($this->dispatcher)) {
  571. $this->dispatcher->dispatch('\OCA\DAV\CardDAV\CardDavBackend::updateCard',
  572. new GenericEvent(null, [
  573. 'addressBookId' => $addressBookId,
  574. 'cardUri' => $cardUri,
  575. 'cardData' => $cardData]));
  576. }
  577. return '"' . $etag . '"';
  578. }
  579. /**
  580. * Deletes a card
  581. *
  582. * @param mixed $addressBookId
  583. * @param string $cardUri
  584. * @return bool
  585. */
  586. function deleteCard($addressBookId, $cardUri) {
  587. try {
  588. $cardId = $this->getCardId($addressBookId, $cardUri);
  589. } catch (\InvalidArgumentException $e) {
  590. $cardId = null;
  591. }
  592. $query = $this->db->getQueryBuilder();
  593. $ret = $query->delete('cards')
  594. ->where($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId)))
  595. ->andWhere($query->expr()->eq('uri', $query->createNamedParameter($cardUri)))
  596. ->execute();
  597. $this->addChange($addressBookId, $cardUri, 3);
  598. if (!is_null($this->dispatcher)) {
  599. $this->dispatcher->dispatch('\OCA\DAV\CardDAV\CardDavBackend::deleteCard',
  600. new GenericEvent(null, [
  601. 'addressBookId' => $addressBookId,
  602. 'cardUri' => $cardUri]));
  603. }
  604. if ($ret === 1) {
  605. if ($cardId !== null) {
  606. $this->purgeProperties($addressBookId, $cardId);
  607. }
  608. return true;
  609. }
  610. return false;
  611. }
  612. /**
  613. * The getChanges method returns all the changes that have happened, since
  614. * the specified syncToken in the specified address book.
  615. *
  616. * This function should return an array, such as the following:
  617. *
  618. * [
  619. * 'syncToken' => 'The current synctoken',
  620. * 'added' => [
  621. * 'new.txt',
  622. * ],
  623. * 'modified' => [
  624. * 'modified.txt',
  625. * ],
  626. * 'deleted' => [
  627. * 'foo.php.bak',
  628. * 'old.txt'
  629. * ]
  630. * ];
  631. *
  632. * The returned syncToken property should reflect the *current* syncToken
  633. * of the calendar, as reported in the {http://sabredav.org/ns}sync-token
  634. * property. This is needed here too, to ensure the operation is atomic.
  635. *
  636. * If the $syncToken argument is specified as null, this is an initial
  637. * sync, and all members should be reported.
  638. *
  639. * The modified property is an array of nodenames that have changed since
  640. * the last token.
  641. *
  642. * The deleted property is an array with nodenames, that have been deleted
  643. * from collection.
  644. *
  645. * The $syncLevel argument is basically the 'depth' of the report. If it's
  646. * 1, you only have to report changes that happened only directly in
  647. * immediate descendants. If it's 2, it should also include changes from
  648. * the nodes below the child collections. (grandchildren)
  649. *
  650. * The $limit argument allows a client to specify how many results should
  651. * be returned at most. If the limit is not specified, it should be treated
  652. * as infinite.
  653. *
  654. * If the limit (infinite or not) is higher than you're willing to return,
  655. * you should throw a Sabre\DAV\Exception\TooMuchMatches() exception.
  656. *
  657. * If the syncToken is expired (due to data cleanup) or unknown, you must
  658. * return null.
  659. *
  660. * The limit is 'suggestive'. You are free to ignore it.
  661. *
  662. * @param string $addressBookId
  663. * @param string $syncToken
  664. * @param int $syncLevel
  665. * @param int $limit
  666. * @return array
  667. */
  668. function getChangesForAddressBook($addressBookId, $syncToken, $syncLevel, $limit = null) {
  669. // Current synctoken
  670. $stmt = $this->db->prepare('SELECT `synctoken` FROM `*PREFIX*addressbooks` WHERE `id` = ?');
  671. $stmt->execute([ $addressBookId ]);
  672. $currentToken = $stmt->fetchColumn(0);
  673. if (is_null($currentToken)) return null;
  674. $result = [
  675. 'syncToken' => $currentToken,
  676. 'added' => [],
  677. 'modified' => [],
  678. 'deleted' => [],
  679. ];
  680. if ($syncToken) {
  681. $query = "SELECT `uri`, `operation` FROM `*PREFIX*addressbookchanges` WHERE `synctoken` >= ? AND `synctoken` < ? AND `addressbookid` = ? ORDER BY `synctoken`";
  682. if ($limit>0) {
  683. $query .= " `LIMIT` " . (int)$limit;
  684. }
  685. // Fetching all changes
  686. $stmt = $this->db->prepare($query);
  687. $stmt->execute([$syncToken, $currentToken, $addressBookId]);
  688. $changes = [];
  689. // This loop ensures that any duplicates are overwritten, only the
  690. // last change on a node is relevant.
  691. while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
  692. $changes[$row['uri']] = $row['operation'];
  693. }
  694. foreach($changes as $uri => $operation) {
  695. switch($operation) {
  696. case 1:
  697. $result['added'][] = $uri;
  698. break;
  699. case 2:
  700. $result['modified'][] = $uri;
  701. break;
  702. case 3:
  703. $result['deleted'][] = $uri;
  704. break;
  705. }
  706. }
  707. } else {
  708. // No synctoken supplied, this is the initial sync.
  709. $query = "SELECT `uri` FROM `*PREFIX*cards` WHERE `addressbookid` = ?";
  710. $stmt = $this->db->prepare($query);
  711. $stmt->execute([$addressBookId]);
  712. $result['added'] = $stmt->fetchAll(\PDO::FETCH_COLUMN);
  713. }
  714. return $result;
  715. }
  716. /**
  717. * Adds a change record to the addressbookchanges table.
  718. *
  719. * @param mixed $addressBookId
  720. * @param string $objectUri
  721. * @param int $operation 1 = add, 2 = modify, 3 = delete
  722. * @return void
  723. */
  724. protected function addChange($addressBookId, $objectUri, $operation) {
  725. $sql = 'INSERT INTO `*PREFIX*addressbookchanges`(`uri`, `synctoken`, `addressbookid`, `operation`) SELECT ?, `synctoken`, ?, ? FROM `*PREFIX*addressbooks` WHERE `id` = ?';
  726. $stmt = $this->db->prepare($sql);
  727. $stmt->execute([
  728. $objectUri,
  729. $addressBookId,
  730. $operation,
  731. $addressBookId
  732. ]);
  733. $stmt = $this->db->prepare('UPDATE `*PREFIX*addressbooks` SET `synctoken` = `synctoken` + 1 WHERE `id` = ?');
  734. $stmt->execute([
  735. $addressBookId
  736. ]);
  737. }
  738. private function readBlob($cardData) {
  739. if (is_resource($cardData)) {
  740. return stream_get_contents($cardData);
  741. }
  742. return $cardData;
  743. }
  744. /**
  745. * @param IShareable $shareable
  746. * @param string[] $add
  747. * @param string[] $remove
  748. */
  749. public function updateShares(IShareable $shareable, $add, $remove) {
  750. $this->sharingBackend->updateShares($shareable, $add, $remove);
  751. }
  752. /**
  753. * search contact
  754. *
  755. * @param int $addressBookId
  756. * @param string $pattern which should match within the $searchProperties
  757. * @param array $searchProperties defines the properties within the query pattern should match
  758. * @return array an array of contacts which are arrays of key-value-pairs
  759. */
  760. public function search($addressBookId, $pattern, $searchProperties) {
  761. $query = $this->db->getQueryBuilder();
  762. $query2 = $this->db->getQueryBuilder();
  763. $query2->selectDistinct('cp.cardid')->from($this->dbCardsPropertiesTable, 'cp');
  764. foreach ($searchProperties as $property) {
  765. $query2->orWhere(
  766. $query2->expr()->andX(
  767. $query2->expr()->eq('cp.name', $query->createNamedParameter($property)),
  768. $query2->expr()->ilike('cp.value', $query->createNamedParameter('%' . $this->db->escapeLikeParameter($pattern) . '%'))
  769. )
  770. );
  771. }
  772. $query2->andWhere($query2->expr()->eq('cp.addressbookid', $query->createNamedParameter($addressBookId)));
  773. $query->select('c.carddata', 'c.uri')->from($this->dbCardsTable, 'c')
  774. ->where($query->expr()->in('c.id', $query->createFunction($query2->getSQL())));
  775. $result = $query->execute();
  776. $cards = $result->fetchAll();
  777. $result->closeCursor();
  778. return array_map(function($array) {
  779. $array['carddata'] = $this->readBlob($array['carddata']);
  780. return $array;
  781. }, $cards);
  782. }
  783. /**
  784. * @param int $bookId
  785. * @param string $name
  786. * @return array
  787. */
  788. public function collectCardProperties($bookId, $name) {
  789. $query = $this->db->getQueryBuilder();
  790. $result = $query->selectDistinct('value')
  791. ->from($this->dbCardsPropertiesTable)
  792. ->where($query->expr()->eq('name', $query->createNamedParameter($name)))
  793. ->andWhere($query->expr()->eq('addressbookid', $query->createNamedParameter($bookId)))
  794. ->execute();
  795. $all = $result->fetchAll(PDO::FETCH_COLUMN);
  796. $result->closeCursor();
  797. return $all;
  798. }
  799. /**
  800. * get URI from a given contact
  801. *
  802. * @param int $id
  803. * @return string
  804. */
  805. public function getCardUri($id) {
  806. $query = $this->db->getQueryBuilder();
  807. $query->select('uri')->from($this->dbCardsTable)
  808. ->where($query->expr()->eq('id', $query->createParameter('id')))
  809. ->setParameter('id', $id);
  810. $result = $query->execute();
  811. $uri = $result->fetch();
  812. $result->closeCursor();
  813. if (!isset($uri['uri'])) {
  814. throw new \InvalidArgumentException('Card does not exists: ' . $id);
  815. }
  816. return $uri['uri'];
  817. }
  818. /**
  819. * return contact with the given URI
  820. *
  821. * @param int $addressBookId
  822. * @param string $uri
  823. * @returns array
  824. */
  825. public function getContact($addressBookId, $uri) {
  826. $result = [];
  827. $query = $this->db->getQueryBuilder();
  828. $query->select('*')->from($this->dbCardsTable)
  829. ->where($query->expr()->eq('uri', $query->createNamedParameter($uri)))
  830. ->andWhere($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId)));
  831. $queryResult = $query->execute();
  832. $contact = $queryResult->fetch();
  833. $queryResult->closeCursor();
  834. if (is_array($contact)) {
  835. $result = $contact;
  836. }
  837. return $result;
  838. }
  839. /**
  840. * Returns the list of people whom this address book is shared with.
  841. *
  842. * Every element in this array should have the following properties:
  843. * * href - Often a mailto: address
  844. * * commonName - Optional, for example a first + last name
  845. * * status - See the Sabre\CalDAV\SharingPlugin::STATUS_ constants.
  846. * * readOnly - boolean
  847. * * summary - Optional, a description for the share
  848. *
  849. * @return array
  850. */
  851. public function getShares($addressBookId) {
  852. return $this->sharingBackend->getShares($addressBookId);
  853. }
  854. /**
  855. * update properties table
  856. *
  857. * @param int $addressBookId
  858. * @param string $cardUri
  859. * @param string $vCardSerialized
  860. */
  861. protected function updateProperties($addressBookId, $cardUri, $vCardSerialized) {
  862. $cardId = $this->getCardId($addressBookId, $cardUri);
  863. $vCard = $this->readCard($vCardSerialized);
  864. $this->purgeProperties($addressBookId, $cardId);
  865. $query = $this->db->getQueryBuilder();
  866. $query->insert($this->dbCardsPropertiesTable)
  867. ->values(
  868. [
  869. 'addressbookid' => $query->createNamedParameter($addressBookId),
  870. 'cardid' => $query->createNamedParameter($cardId),
  871. 'name' => $query->createParameter('name'),
  872. 'value' => $query->createParameter('value'),
  873. 'preferred' => $query->createParameter('preferred')
  874. ]
  875. );
  876. foreach ($vCard->children() as $property) {
  877. if(!in_array($property->name, self::$indexProperties)) {
  878. continue;
  879. }
  880. $preferred = 0;
  881. foreach($property->parameters as $parameter) {
  882. if ($parameter->name == 'TYPE' && strtoupper($parameter->getValue()) == 'PREF') {
  883. $preferred = 1;
  884. break;
  885. }
  886. }
  887. $query->setParameter('name', $property->name);
  888. $query->setParameter('value', substr($property->getValue(), 0, 254));
  889. $query->setParameter('preferred', $preferred);
  890. $query->execute();
  891. }
  892. }
  893. /**
  894. * read vCard data into a vCard object
  895. *
  896. * @param string $cardData
  897. * @return VCard
  898. */
  899. protected function readCard($cardData) {
  900. return Reader::read($cardData);
  901. }
  902. /**
  903. * delete all properties from a given card
  904. *
  905. * @param int $addressBookId
  906. * @param int $cardId
  907. */
  908. protected function purgeProperties($addressBookId, $cardId) {
  909. $query = $this->db->getQueryBuilder();
  910. $query->delete($this->dbCardsPropertiesTable)
  911. ->where($query->expr()->eq('cardid', $query->createNamedParameter($cardId)))
  912. ->andWhere($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId)));
  913. $query->execute();
  914. }
  915. /**
  916. * get ID from a given contact
  917. *
  918. * @param int $addressBookId
  919. * @param string $uri
  920. * @return int
  921. */
  922. protected function getCardId($addressBookId, $uri) {
  923. $query = $this->db->getQueryBuilder();
  924. $query->select('id')->from($this->dbCardsTable)
  925. ->where($query->expr()->eq('uri', $query->createNamedParameter($uri)))
  926. ->andWhere($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId)));
  927. $result = $query->execute();
  928. $cardIds = $result->fetch();
  929. $result->closeCursor();
  930. if (!isset($cardIds['id'])) {
  931. throw new \InvalidArgumentException('Card does not exists: ' . $uri);
  932. }
  933. return (int)$cardIds['id'];
  934. }
  935. /**
  936. * For shared address books the sharee is set in the ACL of the address book
  937. * @param $addressBookId
  938. * @param $acl
  939. * @return array
  940. */
  941. public function applyShareAcl($addressBookId, $acl) {
  942. return $this->sharingBackend->applyShareAcl($addressBookId, $acl);
  943. }
  944. private function convertPrincipal($principalUri, $toV2) {
  945. if ($this->principalBackend->getPrincipalPrefix() === 'principals') {
  946. list(, $name) = URLUtil::splitPath($principalUri);
  947. if ($toV2 === true) {
  948. return "principals/users/$name";
  949. }
  950. return "principals/$name";
  951. }
  952. return $principalUri;
  953. }
  954. }