CardDavBackend.php 36 KB

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