carddavbackend.php 29 KB

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