CardDavBackend.php 44 KB

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