CardDavBackend.php 50 KB

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