PDO.php 55 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487
  1. <?php
  2. declare(strict_types=1);
  3. namespace Sabre\CalDAV\Backend;
  4. use Sabre\CalDAV;
  5. use Sabre\DAV;
  6. use Sabre\DAV\Exception\Forbidden;
  7. use Sabre\DAV\PropPatch;
  8. use Sabre\DAV\Xml\Element\Sharee;
  9. use Sabre\VObject;
  10. /**
  11. * PDO CalDAV backend.
  12. *
  13. * This backend is used to store calendar-data in a PDO database, such as
  14. * sqlite or MySQL
  15. *
  16. * @copyright Copyright (C) fruux GmbH (https://fruux.com/)
  17. * @author Evert Pot (http://evertpot.com/)
  18. * @license http://sabre.io/license/ Modified BSD License
  19. */
  20. class PDO extends AbstractBackend implements SyncSupport, SubscriptionSupport, SchedulingSupport, SharingSupport
  21. {
  22. /**
  23. * We need to specify a max date, because we need to stop *somewhere*.
  24. *
  25. * On 32 bit system the maximum for a signed integer is 2147483647, so
  26. * MAX_DATE cannot be higher than date('Y-m-d', 2147483647) which results
  27. * in 2038-01-19 to avoid problems when the date is converted
  28. * to a unix timestamp.
  29. */
  30. const MAX_DATE = '2038-01-01';
  31. /**
  32. * pdo.
  33. *
  34. * @var \PDO
  35. */
  36. protected $pdo;
  37. /**
  38. * The table name that will be used for calendars.
  39. *
  40. * @var string
  41. */
  42. public $calendarTableName = 'calendars';
  43. /**
  44. * The table name that will be used for calendars instances.
  45. *
  46. * A single calendar can have multiple instances, if the calendar is
  47. * shared.
  48. *
  49. * @var string
  50. */
  51. public $calendarInstancesTableName = 'calendarinstances';
  52. /**
  53. * The table name that will be used for calendar objects.
  54. *
  55. * @var string
  56. */
  57. public $calendarObjectTableName = 'calendarobjects';
  58. /**
  59. * The table name that will be used for tracking changes in calendars.
  60. *
  61. * @var string
  62. */
  63. public $calendarChangesTableName = 'calendarchanges';
  64. /**
  65. * The table name that will be used inbox items.
  66. *
  67. * @var string
  68. */
  69. public $schedulingObjectTableName = 'schedulingobjects';
  70. /**
  71. * The table name that will be used for calendar subscriptions.
  72. *
  73. * @var string
  74. */
  75. public $calendarSubscriptionsTableName = 'calendarsubscriptions';
  76. /**
  77. * List of CalDAV properties, and how they map to database fieldnames
  78. * Add your own properties by simply adding on to this array.
  79. *
  80. * Note that only string-based properties are supported here.
  81. *
  82. * @var array
  83. */
  84. public $propertyMap = [
  85. '{DAV:}displayname' => 'displayname',
  86. '{urn:ietf:params:xml:ns:caldav}calendar-description' => 'description',
  87. '{urn:ietf:params:xml:ns:caldav}calendar-timezone' => 'timezone',
  88. '{http://apple.com/ns/ical/}calendar-order' => 'calendarorder',
  89. '{http://apple.com/ns/ical/}calendar-color' => 'calendarcolor',
  90. ];
  91. /**
  92. * List of subscription properties, and how they map to database fieldnames.
  93. *
  94. * @var array
  95. */
  96. public $subscriptionPropertyMap = [
  97. '{DAV:}displayname' => 'displayname',
  98. '{http://apple.com/ns/ical/}refreshrate' => 'refreshrate',
  99. '{http://apple.com/ns/ical/}calendar-order' => 'calendarorder',
  100. '{http://apple.com/ns/ical/}calendar-color' => 'calendarcolor',
  101. '{http://calendarserver.org/ns/}subscribed-strip-todos' => 'striptodos',
  102. '{http://calendarserver.org/ns/}subscribed-strip-alarms' => 'stripalarms',
  103. '{http://calendarserver.org/ns/}subscribed-strip-attachments' => 'stripattachments',
  104. ];
  105. /**
  106. * Creates the backend.
  107. */
  108. public function __construct(\PDO $pdo)
  109. {
  110. $this->pdo = $pdo;
  111. }
  112. /**
  113. * Returns a list of calendars for a principal.
  114. *
  115. * Every project is an array with the following keys:
  116. * * id, a unique id that will be used by other functions to modify the
  117. * calendar. This can be the same as the uri or a database key.
  118. * * uri. This is just the 'base uri' or 'filename' of the calendar.
  119. * * principaluri. The owner of the calendar. Almost always the same as
  120. * principalUri passed to this method.
  121. *
  122. * Furthermore it can contain webdav properties in clark notation. A very
  123. * common one is '{DAV:}displayname'.
  124. *
  125. * Many clients also require:
  126. * {urn:ietf:params:xml:ns:caldav}supported-calendar-component-set
  127. * For this property, you can just return an instance of
  128. * Sabre\CalDAV\Xml\Property\SupportedCalendarComponentSet.
  129. *
  130. * If you return {http://sabredav.org/ns}read-only and set the value to 1,
  131. * ACL will automatically be put in read-only mode.
  132. *
  133. * @param string $principalUri
  134. *
  135. * @return array
  136. */
  137. public function getCalendarsForUser($principalUri)
  138. {
  139. $fields = array_values($this->propertyMap);
  140. $fields[] = 'calendarid';
  141. $fields[] = 'uri';
  142. $fields[] = 'synctoken';
  143. $fields[] = 'components';
  144. $fields[] = 'principaluri';
  145. $fields[] = 'transparent';
  146. $fields[] = 'access';
  147. // Making fields a comma-delimited list
  148. $fields = implode(', ', $fields);
  149. $stmt = $this->pdo->prepare(<<<SQL
  150. SELECT {$this->calendarInstancesTableName}.id as id, $fields FROM {$this->calendarInstancesTableName}
  151. LEFT JOIN {$this->calendarTableName} ON
  152. {$this->calendarInstancesTableName}.calendarid = {$this->calendarTableName}.id
  153. WHERE principaluri = ? ORDER BY calendarorder ASC
  154. SQL
  155. );
  156. $stmt->execute([$principalUri]);
  157. $calendars = [];
  158. while ($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
  159. $components = [];
  160. if ($row['components']) {
  161. $components = explode(',', $row['components']);
  162. }
  163. $calendar = [
  164. 'id' => [(int) $row['calendarid'], (int) $row['id']],
  165. 'uri' => $row['uri'],
  166. 'principaluri' => $row['principaluri'],
  167. '{'.CalDAV\Plugin::NS_CALENDARSERVER.'}getctag' => 'http://sabre.io/ns/sync/'.($row['synctoken'] ? $row['synctoken'] : '0'),
  168. '{http://sabredav.org/ns}sync-token' => $row['synctoken'] ? $row['synctoken'] : '0',
  169. '{'.CalDAV\Plugin::NS_CALDAV.'}supported-calendar-component-set' => new CalDAV\Xml\Property\SupportedCalendarComponentSet($components),
  170. '{'.CalDAV\Plugin::NS_CALDAV.'}schedule-calendar-transp' => new CalDAV\Xml\Property\ScheduleCalendarTransp($row['transparent'] ? 'transparent' : 'opaque'),
  171. 'share-resource-uri' => '/ns/share/'.$row['calendarid'],
  172. ];
  173. $calendar['share-access'] = (int) $row['access'];
  174. // 1 = owner, 2 = readonly, 3 = readwrite
  175. if ($row['access'] > 1) {
  176. // We need to find more information about the original owner.
  177. //$stmt2 = $this->pdo->prepare('SELECT principaluri FROM ' . $this->calendarInstancesTableName . ' WHERE access = 1 AND id = ?');
  178. //$stmt2->execute([$row['id']]);
  179. // read-only is for backwards compatbility. Might go away in
  180. // the future.
  181. $calendar['read-only'] = \Sabre\DAV\Sharing\Plugin::ACCESS_READ === (int) $row['access'];
  182. }
  183. foreach ($this->propertyMap as $xmlName => $dbName) {
  184. $calendar[$xmlName] = $row[$dbName];
  185. }
  186. $calendars[] = $calendar;
  187. }
  188. return $calendars;
  189. }
  190. /**
  191. * Creates a new calendar for a principal.
  192. *
  193. * If the creation was a success, an id must be returned that can be used
  194. * to reference this calendar in other methods, such as updateCalendar.
  195. *
  196. * @param string $principalUri
  197. * @param string $calendarUri
  198. *
  199. * @return string
  200. */
  201. public function createCalendar($principalUri, $calendarUri, array $properties)
  202. {
  203. $fieldNames = [
  204. 'principaluri',
  205. 'uri',
  206. 'transparent',
  207. 'calendarid',
  208. ];
  209. $values = [
  210. ':principaluri' => $principalUri,
  211. ':uri' => $calendarUri,
  212. ':transparent' => 0,
  213. ];
  214. $sccs = '{urn:ietf:params:xml:ns:caldav}supported-calendar-component-set';
  215. if (!isset($properties[$sccs])) {
  216. // Default value
  217. $components = 'VEVENT,VTODO';
  218. } else {
  219. if (!($properties[$sccs] instanceof CalDAV\Xml\Property\SupportedCalendarComponentSet)) {
  220. throw new DAV\Exception('The '.$sccs.' property must be of type: \Sabre\CalDAV\Xml\Property\SupportedCalendarComponentSet');
  221. }
  222. $components = implode(',', $properties[$sccs]->getValue());
  223. }
  224. $transp = '{'.CalDAV\Plugin::NS_CALDAV.'}schedule-calendar-transp';
  225. if (isset($properties[$transp])) {
  226. $values[':transparent'] = 'transparent' === $properties[$transp]->getValue() ? 1 : 0;
  227. }
  228. $stmt = $this->pdo->prepare('INSERT INTO '.$this->calendarTableName.' (synctoken, components) VALUES (1, ?)');
  229. $stmt->execute([$components]);
  230. $calendarId = $this->pdo->lastInsertId(
  231. $this->calendarTableName.'_id_seq'
  232. );
  233. $values[':calendarid'] = $calendarId;
  234. foreach ($this->propertyMap as $xmlName => $dbName) {
  235. if (isset($properties[$xmlName])) {
  236. $values[':'.$dbName] = $properties[$xmlName];
  237. $fieldNames[] = $dbName;
  238. }
  239. }
  240. $stmt = $this->pdo->prepare('INSERT INTO '.$this->calendarInstancesTableName.' ('.implode(', ', $fieldNames).') VALUES ('.implode(', ', array_keys($values)).')');
  241. $stmt->execute($values);
  242. return [
  243. $calendarId,
  244. $this->pdo->lastInsertId($this->calendarInstancesTableName.'_id_seq'),
  245. ];
  246. }
  247. /**
  248. * Updates properties for a calendar.
  249. *
  250. * The list of mutations is stored in a Sabre\DAV\PropPatch object.
  251. * To do the actual updates, you must tell this object which properties
  252. * you're going to process with the handle() method.
  253. *
  254. * Calling the handle method is like telling the PropPatch object "I
  255. * promise I can handle updating this property".
  256. *
  257. * Read the PropPatch documentation for more info and examples.
  258. *
  259. * @param mixed $calendarId
  260. */
  261. public function updateCalendar($calendarId, PropPatch $propPatch)
  262. {
  263. if (!is_array($calendarId)) {
  264. throw new \InvalidArgumentException('The value passed to $calendarId is expected to be an array with a calendarId and an instanceId');
  265. }
  266. list($calendarId, $instanceId) = $calendarId;
  267. $supportedProperties = array_keys($this->propertyMap);
  268. $supportedProperties[] = '{'.CalDAV\Plugin::NS_CALDAV.'}schedule-calendar-transp';
  269. $propPatch->handle($supportedProperties, function ($mutations) use ($calendarId, $instanceId) {
  270. $newValues = [];
  271. foreach ($mutations as $propertyName => $propertyValue) {
  272. switch ($propertyName) {
  273. case '{'.CalDAV\Plugin::NS_CALDAV.'}schedule-calendar-transp':
  274. $fieldName = 'transparent';
  275. $newValues[$fieldName] = 'transparent' === $propertyValue->getValue();
  276. break;
  277. default:
  278. $fieldName = $this->propertyMap[$propertyName];
  279. $newValues[$fieldName] = $propertyValue;
  280. break;
  281. }
  282. }
  283. $valuesSql = [];
  284. foreach ($newValues as $fieldName => $value) {
  285. $valuesSql[] = $fieldName.' = ?';
  286. }
  287. $stmt = $this->pdo->prepare('UPDATE '.$this->calendarInstancesTableName.' SET '.implode(', ', $valuesSql).' WHERE id = ?');
  288. $newValues['id'] = $instanceId;
  289. $stmt->execute(array_values($newValues));
  290. $this->addChange($calendarId, '', 2);
  291. return true;
  292. });
  293. }
  294. /**
  295. * Delete a calendar and all it's objects.
  296. *
  297. * @param mixed $calendarId
  298. */
  299. public function deleteCalendar($calendarId)
  300. {
  301. if (!is_array($calendarId)) {
  302. throw new \InvalidArgumentException('The value passed to $calendarId is expected to be an array with a calendarId and an instanceId');
  303. }
  304. list($calendarId, $instanceId) = $calendarId;
  305. $stmt = $this->pdo->prepare('SELECT access FROM '.$this->calendarInstancesTableName.' where id = ?');
  306. $stmt->execute([$instanceId]);
  307. $access = (int) $stmt->fetchColumn();
  308. if (\Sabre\DAV\Sharing\Plugin::ACCESS_SHAREDOWNER === $access) {
  309. /**
  310. * If the user is the owner of the calendar, we delete all data and all
  311. * instances.
  312. **/
  313. $stmt = $this->pdo->prepare('DELETE FROM '.$this->calendarObjectTableName.' WHERE calendarid = ?');
  314. $stmt->execute([$calendarId]);
  315. $stmt = $this->pdo->prepare('DELETE FROM '.$this->calendarChangesTableName.' WHERE calendarid = ?');
  316. $stmt->execute([$calendarId]);
  317. $stmt = $this->pdo->prepare('DELETE FROM '.$this->calendarInstancesTableName.' WHERE calendarid = ?');
  318. $stmt->execute([$calendarId]);
  319. $stmt = $this->pdo->prepare('DELETE FROM '.$this->calendarTableName.' WHERE id = ?');
  320. $stmt->execute([$calendarId]);
  321. } else {
  322. /**
  323. * If it was an instance of a shared calendar, we only delete that
  324. * instance.
  325. */
  326. $stmt = $this->pdo->prepare('DELETE FROM '.$this->calendarInstancesTableName.' WHERE id = ?');
  327. $stmt->execute([$instanceId]);
  328. }
  329. }
  330. /**
  331. * Returns all calendar objects within a calendar.
  332. *
  333. * Every item contains an array with the following keys:
  334. * * calendardata - The iCalendar-compatible calendar data
  335. * * uri - a unique key which will be used to construct the uri. This can
  336. * be any arbitrary string, but making sure it ends with '.ics' is a
  337. * good idea. This is only the basename, or filename, not the full
  338. * path.
  339. * * lastmodified - a timestamp of the last modification time
  340. * * etag - An arbitrary string, surrounded by double-quotes. (e.g.:
  341. * ' "abcdef"')
  342. * * size - The size of the calendar objects, in bytes.
  343. * * component - optional, a string containing the type of object, such
  344. * as 'vevent' or 'vtodo'. If specified, this will be used to populate
  345. * the Content-Type header.
  346. *
  347. * Note that the etag is optional, but it's highly encouraged to return for
  348. * speed reasons.
  349. *
  350. * The calendardata is also optional. If it's not returned
  351. * 'getCalendarObject' will be called later, which *is* expected to return
  352. * calendardata.
  353. *
  354. * If neither etag or size are specified, the calendardata will be
  355. * used/fetched to determine these numbers. If both are specified the
  356. * amount of times this is needed is reduced by a great degree.
  357. *
  358. * @param mixed $calendarId
  359. *
  360. * @return array
  361. */
  362. public function getCalendarObjects($calendarId)
  363. {
  364. if (!is_array($calendarId)) {
  365. throw new \InvalidArgumentException('The value passed to $calendarId is expected to be an array with a calendarId and an instanceId');
  366. }
  367. list($calendarId, $instanceId) = $calendarId;
  368. $stmt = $this->pdo->prepare('SELECT id, uri, lastmodified, etag, calendarid, size, componenttype FROM '.$this->calendarObjectTableName.' WHERE calendarid = ?');
  369. $stmt->execute([$calendarId]);
  370. $result = [];
  371. foreach ($stmt->fetchAll(\PDO::FETCH_ASSOC) as $row) {
  372. $result[] = [
  373. 'id' => $row['id'],
  374. 'uri' => $row['uri'],
  375. 'lastmodified' => (int) $row['lastmodified'],
  376. 'etag' => '"'.$row['etag'].'"',
  377. 'size' => (int) $row['size'],
  378. 'component' => strtolower($row['componenttype']),
  379. ];
  380. }
  381. return $result;
  382. }
  383. /**
  384. * Returns information from a single calendar object, based on it's object
  385. * uri.
  386. *
  387. * The object uri is only the basename, or filename and not a full path.
  388. *
  389. * The returned array must have the same keys as getCalendarObjects. The
  390. * 'calendardata' object is required here though, while it's not required
  391. * for getCalendarObjects.
  392. *
  393. * This method must return null if the object did not exist.
  394. *
  395. * @param mixed $calendarId
  396. * @param string $objectUri
  397. *
  398. * @return array|null
  399. */
  400. public function getCalendarObject($calendarId, $objectUri)
  401. {
  402. if (!is_array($calendarId)) {
  403. throw new \InvalidArgumentException('The value passed to $calendarId is expected to be an array with a calendarId and an instanceId');
  404. }
  405. list($calendarId, $instanceId) = $calendarId;
  406. $stmt = $this->pdo->prepare('SELECT id, uri, lastmodified, etag, calendarid, size, calendardata, componenttype FROM '.$this->calendarObjectTableName.' WHERE calendarid = ? AND uri = ?');
  407. $stmt->execute([$calendarId, $objectUri]);
  408. $row = $stmt->fetch(\PDO::FETCH_ASSOC);
  409. if (!$row) {
  410. return null;
  411. }
  412. return [
  413. 'id' => $row['id'],
  414. 'uri' => $row['uri'],
  415. 'lastmodified' => (int) $row['lastmodified'],
  416. 'etag' => '"'.$row['etag'].'"',
  417. 'size' => (int) $row['size'],
  418. 'calendardata' => $row['calendardata'],
  419. 'component' => strtolower($row['componenttype']),
  420. ];
  421. }
  422. /**
  423. * Returns a list of calendar objects.
  424. *
  425. * This method should work identical to getCalendarObject, but instead
  426. * return all the calendar objects in the list as an array.
  427. *
  428. * If the backend supports this, it may allow for some speed-ups.
  429. *
  430. * @param mixed $calendarId
  431. *
  432. * @return array
  433. */
  434. public function getMultipleCalendarObjects($calendarId, array $uris)
  435. {
  436. if (!is_array($calendarId)) {
  437. throw new \InvalidArgumentException('The value passed to $calendarId is expected to be an array with a calendarId and an instanceId');
  438. }
  439. list($calendarId, $instanceId) = $calendarId;
  440. $result = [];
  441. foreach (array_chunk($uris, 900) as $chunk) {
  442. $query = 'SELECT id, uri, lastmodified, etag, calendarid, size, calendardata, componenttype FROM '.$this->calendarObjectTableName.' WHERE calendarid = ? AND uri IN (';
  443. // Inserting a whole bunch of question marks
  444. $query .= implode(',', array_fill(0, count($chunk), '?'));
  445. $query .= ')';
  446. $stmt = $this->pdo->prepare($query);
  447. $stmt->execute(array_merge([$calendarId], $chunk));
  448. while ($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
  449. $result[] = [
  450. 'id' => $row['id'],
  451. 'uri' => $row['uri'],
  452. 'lastmodified' => (int) $row['lastmodified'],
  453. 'etag' => '"'.$row['etag'].'"',
  454. 'size' => (int) $row['size'],
  455. 'calendardata' => $row['calendardata'],
  456. 'component' => strtolower($row['componenttype']),
  457. ];
  458. }
  459. }
  460. return $result;
  461. }
  462. /**
  463. * Creates a new calendar object.
  464. *
  465. * The object uri is only the basename, or filename and not a full path.
  466. *
  467. * It is possible return an etag from this function, which will be used in
  468. * the response to this PUT request. Note that the ETag must be surrounded
  469. * by double-quotes.
  470. *
  471. * However, you should only really return this ETag if you don't mangle the
  472. * calendar-data. If the result of a subsequent GET to this object is not
  473. * the exact same as this request body, you should omit the ETag.
  474. *
  475. * @param mixed $calendarId
  476. * @param string $objectUri
  477. * @param string $calendarData
  478. *
  479. * @return string|null
  480. */
  481. public function createCalendarObject($calendarId, $objectUri, $calendarData)
  482. {
  483. if (!is_array($calendarId)) {
  484. throw new \InvalidArgumentException('The value passed to $calendarId is expected to be an array with a calendarId and an instanceId');
  485. }
  486. list($calendarId, $instanceId) = $calendarId;
  487. $extraData = $this->getDenormalizedData($calendarData);
  488. $stmt = $this->pdo->prepare('INSERT INTO '.$this->calendarObjectTableName.' (calendarid, uri, calendardata, lastmodified, etag, size, componenttype, firstoccurence, lastoccurence, uid) VALUES (?,?,?,?,?,?,?,?,?,?)');
  489. $stmt->execute([
  490. $calendarId,
  491. $objectUri,
  492. $calendarData,
  493. time(),
  494. $extraData['etag'],
  495. $extraData['size'],
  496. $extraData['componentType'],
  497. $extraData['firstOccurence'],
  498. $extraData['lastOccurence'],
  499. $extraData['uid'],
  500. ]);
  501. $this->addChange($calendarId, $objectUri, 1);
  502. return '"'.$extraData['etag'].'"';
  503. }
  504. /**
  505. * Updates an existing calendarobject, based on it's uri.
  506. *
  507. * The object uri is only the basename, or filename and not a full path.
  508. *
  509. * It is possible return an etag from this function, which will be used in
  510. * the response to this PUT request. Note that the ETag must be surrounded
  511. * by double-quotes.
  512. *
  513. * However, you should only really return this ETag if you don't mangle the
  514. * calendar-data. If the result of a subsequent GET to this object is not
  515. * the exact same as this request body, you should omit the ETag.
  516. *
  517. * @param mixed $calendarId
  518. * @param string $objectUri
  519. * @param string $calendarData
  520. *
  521. * @return string|null
  522. */
  523. public function updateCalendarObject($calendarId, $objectUri, $calendarData)
  524. {
  525. if (!is_array($calendarId)) {
  526. throw new \InvalidArgumentException('The value passed to $calendarId is expected to be an array with a calendarId and an instanceId');
  527. }
  528. list($calendarId, $instanceId) = $calendarId;
  529. $extraData = $this->getDenormalizedData($calendarData);
  530. $stmt = $this->pdo->prepare('UPDATE '.$this->calendarObjectTableName.' SET calendardata = ?, lastmodified = ?, etag = ?, size = ?, componenttype = ?, firstoccurence = ?, lastoccurence = ?, uid = ? WHERE calendarid = ? AND uri = ?');
  531. $stmt->execute([$calendarData, time(), $extraData['etag'], $extraData['size'], $extraData['componentType'], $extraData['firstOccurence'], $extraData['lastOccurence'], $extraData['uid'], $calendarId, $objectUri]);
  532. $this->addChange($calendarId, $objectUri, 2);
  533. return '"'.$extraData['etag'].'"';
  534. }
  535. /**
  536. * Parses some information from calendar objects, used for optimized
  537. * calendar-queries.
  538. *
  539. * Returns an array with the following keys:
  540. * * etag - An md5 checksum of the object without the quotes.
  541. * * size - Size of the object in bytes
  542. * * componentType - VEVENT, VTODO or VJOURNAL
  543. * * firstOccurence
  544. * * lastOccurence
  545. * * uid - value of the UID property
  546. *
  547. * @param string $calendarData
  548. *
  549. * @return array
  550. */
  551. protected function getDenormalizedData($calendarData)
  552. {
  553. $vObject = VObject\Reader::read($calendarData);
  554. $componentType = null;
  555. $component = null;
  556. $firstOccurence = null;
  557. $lastOccurence = null;
  558. $uid = null;
  559. foreach ($vObject->getComponents() as $component) {
  560. if ('VTIMEZONE' !== $component->name) {
  561. $componentType = $component->name;
  562. $uid = (string) $component->UID;
  563. break;
  564. }
  565. }
  566. if (!$componentType) {
  567. throw new \Sabre\DAV\Exception\BadRequest('Calendar objects must have a VJOURNAL, VEVENT or VTODO component');
  568. }
  569. if ('VEVENT' === $componentType) {
  570. $firstOccurence = $component->DTSTART->getDateTime()->getTimeStamp();
  571. // Finding the last occurence is a bit harder
  572. if (!isset($component->RRULE)) {
  573. if (isset($component->DTEND)) {
  574. $lastOccurence = $component->DTEND->getDateTime()->getTimeStamp();
  575. } elseif (isset($component->DURATION)) {
  576. $endDate = clone $component->DTSTART->getDateTime();
  577. $endDate = $endDate->add(VObject\DateTimeParser::parse($component->DURATION->getValue()));
  578. $lastOccurence = $endDate->getTimeStamp();
  579. } elseif (!$component->DTSTART->hasTime()) {
  580. $endDate = clone $component->DTSTART->getDateTime();
  581. $endDate = $endDate->modify('+1 day');
  582. $lastOccurence = $endDate->getTimeStamp();
  583. } else {
  584. $lastOccurence = $firstOccurence;
  585. }
  586. } else {
  587. $it = new VObject\Recur\EventIterator($vObject, (string) $component->UID);
  588. $maxDate = new \DateTime(self::MAX_DATE);
  589. if ($it->isInfinite()) {
  590. $lastOccurence = $maxDate->getTimeStamp();
  591. } else {
  592. $end = $it->getDtEnd();
  593. while ($it->valid() && $end < $maxDate) {
  594. $end = $it->getDtEnd();
  595. $it->next();
  596. }
  597. $lastOccurence = $end->getTimeStamp();
  598. }
  599. }
  600. // Ensure Occurence values are positive
  601. if ($firstOccurence < 0) {
  602. $firstOccurence = 0;
  603. }
  604. if ($lastOccurence < 0) {
  605. $lastOccurence = 0;
  606. }
  607. }
  608. // Destroy circular references to PHP will GC the object.
  609. $vObject->destroy();
  610. return [
  611. 'etag' => md5($calendarData),
  612. 'size' => strlen($calendarData),
  613. 'componentType' => $componentType,
  614. 'firstOccurence' => $firstOccurence,
  615. 'lastOccurence' => $lastOccurence,
  616. 'uid' => $uid,
  617. ];
  618. }
  619. /**
  620. * Deletes an existing calendar object.
  621. *
  622. * The object uri is only the basename, or filename and not a full path.
  623. *
  624. * @param mixed $calendarId
  625. * @param string $objectUri
  626. */
  627. public function deleteCalendarObject($calendarId, $objectUri)
  628. {
  629. if (!is_array($calendarId)) {
  630. throw new \InvalidArgumentException('The value passed to $calendarId is expected to be an array with a calendarId and an instanceId');
  631. }
  632. list($calendarId, $instanceId) = $calendarId;
  633. $stmt = $this->pdo->prepare('DELETE FROM '.$this->calendarObjectTableName.' WHERE calendarid = ? AND uri = ?');
  634. $stmt->execute([$calendarId, $objectUri]);
  635. $this->addChange($calendarId, $objectUri, 3);
  636. }
  637. /**
  638. * Performs a calendar-query on the contents of this calendar.
  639. *
  640. * The calendar-query is defined in RFC4791 : CalDAV. Using the
  641. * calendar-query it is possible for a client to request a specific set of
  642. * object, based on contents of iCalendar properties, date-ranges and
  643. * iCalendar component types (VTODO, VEVENT).
  644. *
  645. * This method should just return a list of (relative) urls that match this
  646. * query.
  647. *
  648. * The list of filters are specified as an array. The exact array is
  649. * documented by \Sabre\CalDAV\CalendarQueryParser.
  650. *
  651. * Note that it is extremely likely that getCalendarObject for every path
  652. * returned from this method will be called almost immediately after. You
  653. * may want to anticipate this to speed up these requests.
  654. *
  655. * This method provides a default implementation, which parses *all* the
  656. * iCalendar objects in the specified calendar.
  657. *
  658. * This default may well be good enough for personal use, and calendars
  659. * that aren't very large. But if you anticipate high usage, big calendars
  660. * or high loads, you are strongly adviced to optimize certain paths.
  661. *
  662. * The best way to do so is override this method and to optimize
  663. * specifically for 'common filters'.
  664. *
  665. * Requests that are extremely common are:
  666. * * requests for just VEVENTS
  667. * * requests for just VTODO
  668. * * requests with a time-range-filter on a VEVENT.
  669. *
  670. * ..and combinations of these requests. It may not be worth it to try to
  671. * handle every possible situation and just rely on the (relatively
  672. * easy to use) CalendarQueryValidator to handle the rest.
  673. *
  674. * Note that especially time-range-filters may be difficult to parse. A
  675. * time-range filter specified on a VEVENT must for instance also handle
  676. * recurrence rules correctly.
  677. * A good example of how to interpret all these filters can also simply
  678. * be found in \Sabre\CalDAV\CalendarQueryFilter. This class is as correct
  679. * as possible, so it gives you a good idea on what type of stuff you need
  680. * to think of.
  681. *
  682. * This specific implementation (for the PDO) backend optimizes filters on
  683. * specific components, and VEVENT time-ranges.
  684. *
  685. * @param mixed $calendarId
  686. *
  687. * @return array
  688. */
  689. public function calendarQuery($calendarId, array $filters)
  690. {
  691. if (!is_array($calendarId)) {
  692. throw new \InvalidArgumentException('The value passed to $calendarId is expected to be an array with a calendarId and an instanceId');
  693. }
  694. list($calendarId, $instanceId) = $calendarId;
  695. $componentType = null;
  696. $requirePostFilter = true;
  697. $timeRange = null;
  698. // if no filters were specified, we don't need to filter after a query
  699. if (!$filters['prop-filters'] && !$filters['comp-filters']) {
  700. $requirePostFilter = false;
  701. }
  702. // Figuring out if there's a component filter
  703. if (count($filters['comp-filters']) > 0 && !$filters['comp-filters'][0]['is-not-defined']) {
  704. $componentType = $filters['comp-filters'][0]['name'];
  705. // Checking if we need post-filters
  706. $has_time_range = array_key_exists('time-range', $filters['comp-filters'][0]) && $filters['comp-filters'][0]['time-range'];
  707. if (!$filters['prop-filters'] && !$filters['comp-filters'][0]['comp-filters'] && !$has_time_range && !$filters['comp-filters'][0]['prop-filters']) {
  708. $requirePostFilter = false;
  709. }
  710. // There was a time-range filter
  711. if ('VEVENT' == $componentType && $has_time_range) {
  712. $timeRange = $filters['comp-filters'][0]['time-range'];
  713. // If start time OR the end time is not specified, we can do a
  714. // 100% accurate mysql query.
  715. if (!$filters['prop-filters'] && !$filters['comp-filters'][0]['comp-filters'] && !$filters['comp-filters'][0]['prop-filters'] && $timeRange) {
  716. if ((array_key_exists('start', $timeRange) && !$timeRange['start']) || (array_key_exists('end', $timeRange) && !$timeRange['end'])) {
  717. $requirePostFilter = false;
  718. }
  719. }
  720. }
  721. }
  722. if ($requirePostFilter) {
  723. $query = 'SELECT uri, calendardata FROM '.$this->calendarObjectTableName.' WHERE calendarid = :calendarid';
  724. } else {
  725. $query = 'SELECT uri FROM '.$this->calendarObjectTableName.' WHERE calendarid = :calendarid';
  726. }
  727. $values = [
  728. 'calendarid' => $calendarId,
  729. ];
  730. if ($componentType) {
  731. $query .= ' AND componenttype = :componenttype';
  732. $values['componenttype'] = $componentType;
  733. }
  734. if ($timeRange && array_key_exists('start', $timeRange) && $timeRange['start']) {
  735. $query .= ' AND lastoccurence > :startdate';
  736. $values['startdate'] = $timeRange['start']->getTimeStamp();
  737. }
  738. if ($timeRange && array_key_exists('end', $timeRange) && $timeRange['end']) {
  739. $query .= ' AND firstoccurence < :enddate';
  740. $values['enddate'] = $timeRange['end']->getTimeStamp();
  741. }
  742. $stmt = $this->pdo->prepare($query);
  743. $stmt->execute($values);
  744. $result = [];
  745. while ($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
  746. if ($requirePostFilter) {
  747. if (!$this->validateFilterForObject($row, $filters)) {
  748. continue;
  749. }
  750. }
  751. $result[] = $row['uri'];
  752. }
  753. return $result;
  754. }
  755. /**
  756. * Searches through all of a users calendars and calendar objects to find
  757. * an object with a specific UID.
  758. *
  759. * This method should return the path to this object, relative to the
  760. * calendar home, so this path usually only contains two parts:
  761. *
  762. * calendarpath/objectpath.ics
  763. *
  764. * If the uid is not found, return null.
  765. *
  766. * This method should only consider * objects that the principal owns, so
  767. * any calendars owned by other principals that also appear in this
  768. * collection should be ignored.
  769. *
  770. * @param string $principalUri
  771. * @param string $uid
  772. *
  773. * @return string|null
  774. */
  775. public function getCalendarObjectByUID($principalUri, $uid)
  776. {
  777. $query = <<<SQL
  778. SELECT
  779. calendar_instances.uri AS calendaruri, calendarobjects.uri as objecturi
  780. FROM
  781. $this->calendarObjectTableName AS calendarobjects
  782. LEFT JOIN
  783. $this->calendarInstancesTableName AS calendar_instances
  784. ON calendarobjects.calendarid = calendar_instances.calendarid
  785. WHERE
  786. calendar_instances.principaluri = ?
  787. AND
  788. calendarobjects.uid = ?
  789. AND
  790. calendar_instances.access = 1
  791. SQL;
  792. $stmt = $this->pdo->prepare($query);
  793. $stmt->execute([$principalUri, $uid]);
  794. if ($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
  795. return $row['calendaruri'].'/'.$row['objecturi'];
  796. }
  797. }
  798. /**
  799. * The getChanges method returns all the changes that have happened, since
  800. * the specified syncToken in the specified calendar.
  801. *
  802. * This function should return an array, such as the following:
  803. *
  804. * [
  805. * 'syncToken' => 'The current synctoken',
  806. * 'added' => [
  807. * 'new.txt',
  808. * ],
  809. * 'modified' => [
  810. * 'modified.txt',
  811. * ],
  812. * 'deleted' => [
  813. * 'foo.php.bak',
  814. * 'old.txt'
  815. * ]
  816. * ];
  817. *
  818. * The returned syncToken property should reflect the *current* syncToken
  819. * of the calendar, as reported in the {http://sabredav.org/ns}sync-token
  820. * property this is needed here too, to ensure the operation is atomic.
  821. *
  822. * If the $syncToken argument is specified as null, this is an initial
  823. * sync, and all members should be reported.
  824. *
  825. * The modified property is an array of nodenames that have changed since
  826. * the last token.
  827. *
  828. * The deleted property is an array with nodenames, that have been deleted
  829. * from collection.
  830. *
  831. * The $syncLevel argument is basically the 'depth' of the report. If it's
  832. * 1, you only have to report changes that happened only directly in
  833. * immediate descendants. If it's 2, it should also include changes from
  834. * the nodes below the child collections. (grandchildren)
  835. *
  836. * The $limit argument allows a client to specify how many results should
  837. * be returned at most. If the limit is not specified, it should be treated
  838. * as infinite.
  839. *
  840. * If the limit (infinite or not) is higher than you're willing to return,
  841. * you should throw a Sabre\DAV\Exception\TooMuchMatches() exception.
  842. *
  843. * If the syncToken is expired (due to data cleanup) or unknown, you must
  844. * return null.
  845. *
  846. * The limit is 'suggestive'. You are free to ignore it.
  847. *
  848. * @param mixed $calendarId
  849. * @param string $syncToken
  850. * @param int $syncLevel
  851. * @param int $limit
  852. *
  853. * @return array|null
  854. */
  855. public function getChangesForCalendar($calendarId, $syncToken, $syncLevel, $limit = null)
  856. {
  857. if (!is_array($calendarId)) {
  858. throw new \InvalidArgumentException('The value passed to $calendarId is expected to be an array with a calendarId and an instanceId');
  859. }
  860. list($calendarId, $instanceId) = $calendarId;
  861. $result = [
  862. 'added' => [],
  863. 'modified' => [],
  864. 'deleted' => [],
  865. ];
  866. if ($syncToken) {
  867. $query = 'SELECT uri, operation, synctoken FROM '.$this->calendarChangesTableName.' WHERE synctoken >= ? AND calendarid = ? ORDER BY synctoken';
  868. if ($limit > 0) {
  869. // Fetch one more raw to detect result truncation
  870. $query .= ' LIMIT '.((int) $limit + 1);
  871. }
  872. // Fetching all changes
  873. $stmt = $this->pdo->prepare($query);
  874. $stmt->execute([$syncToken, $calendarId]);
  875. $changes = [];
  876. // This loop ensures that any duplicates are overwritten, only the
  877. // last change on a node is relevant.
  878. while ($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
  879. $changes[$row['uri']] = $row;
  880. }
  881. $currentToken = null;
  882. $result_count = 0;
  883. foreach ($changes as $uri => $operation) {
  884. if (!is_null($limit) && $result_count >= $limit) {
  885. $result['result_truncated'] = true;
  886. break;
  887. }
  888. if (null === $currentToken || $currentToken < $operation['synctoken'] + 1) {
  889. // SyncToken in CalDAV perspective is consistently the next number of the last synced change event in this class.
  890. $currentToken = $operation['synctoken'] + 1;
  891. }
  892. ++$result_count;
  893. switch ($operation['operation']) {
  894. case 1:
  895. $result['added'][] = $uri;
  896. break;
  897. case 2:
  898. $result['modified'][] = $uri;
  899. break;
  900. case 3:
  901. $result['deleted'][] = $uri;
  902. break;
  903. }
  904. }
  905. if (!is_null($currentToken)) {
  906. $result['syncToken'] = $currentToken;
  907. } else {
  908. // This means returned value is equivalent to syncToken
  909. $result['syncToken'] = $syncToken;
  910. }
  911. } else {
  912. // Current synctoken
  913. $stmt = $this->pdo->prepare('SELECT synctoken FROM '.$this->calendarTableName.' WHERE id = ?');
  914. $stmt->execute([$calendarId]);
  915. $currentToken = $stmt->fetchColumn(0);
  916. if (is_null($currentToken)) {
  917. return null;
  918. }
  919. $result['syncToken'] = $currentToken;
  920. // No synctoken supplied, this is the initial sync.
  921. $query = 'SELECT uri FROM '.$this->calendarObjectTableName.' WHERE calendarid = ?';
  922. $stmt = $this->pdo->prepare($query);
  923. $stmt->execute([$calendarId]);
  924. $result['added'] = $stmt->fetchAll(\PDO::FETCH_COLUMN);
  925. }
  926. return $result;
  927. }
  928. /**
  929. * Adds a change record to the calendarchanges table.
  930. *
  931. * @param mixed $calendarId
  932. * @param string $objectUri
  933. * @param int $operation 1 = add, 2 = modify, 3 = delete
  934. */
  935. protected function addChange($calendarId, $objectUri, $operation)
  936. {
  937. $stmt = $this->pdo->prepare('INSERT INTO '.$this->calendarChangesTableName.' (uri, synctoken, calendarid, operation) SELECT ?, synctoken, ?, ? FROM '.$this->calendarTableName.' WHERE id = ?');
  938. $stmt->execute([
  939. $objectUri,
  940. $calendarId,
  941. $operation,
  942. $calendarId,
  943. ]);
  944. $stmt = $this->pdo->prepare('UPDATE '.$this->calendarTableName.' SET synctoken = synctoken + 1 WHERE id = ?');
  945. $stmt->execute([
  946. $calendarId,
  947. ]);
  948. }
  949. /**
  950. * Returns a list of subscriptions for a principal.
  951. *
  952. * Every subscription is an array with the following keys:
  953. * * id, a unique id that will be used by other functions to modify the
  954. * subscription. This can be the same as the uri or a database key.
  955. * * uri. This is just the 'base uri' or 'filename' of the subscription.
  956. * * principaluri. The owner of the subscription. Almost always the same as
  957. * principalUri passed to this method.
  958. * * source. Url to the actual feed
  959. *
  960. * Furthermore, all the subscription info must be returned too:
  961. *
  962. * 1. {DAV:}displayname
  963. * 2. {http://apple.com/ns/ical/}refreshrate
  964. * 3. {http://calendarserver.org/ns/}subscribed-strip-todos (omit if todos
  965. * should not be stripped).
  966. * 4. {http://calendarserver.org/ns/}subscribed-strip-alarms (omit if alarms
  967. * should not be stripped).
  968. * 5. {http://calendarserver.org/ns/}subscribed-strip-attachments (omit if
  969. * attachments should not be stripped).
  970. * 7. {http://apple.com/ns/ical/}calendar-color
  971. * 8. {http://apple.com/ns/ical/}calendar-order
  972. * 9. {urn:ietf:params:xml:ns:caldav}supported-calendar-component-set
  973. * (should just be an instance of
  974. * Sabre\CalDAV\Property\SupportedCalendarComponentSet, with a bunch of
  975. * default components).
  976. *
  977. * @param string $principalUri
  978. *
  979. * @return array
  980. */
  981. public function getSubscriptionsForUser($principalUri)
  982. {
  983. $fields = array_values($this->subscriptionPropertyMap);
  984. $fields[] = 'id';
  985. $fields[] = 'uri';
  986. $fields[] = 'source';
  987. $fields[] = 'principaluri';
  988. $fields[] = 'lastmodified';
  989. // Making fields a comma-delimited list
  990. $fields = implode(', ', $fields);
  991. $stmt = $this->pdo->prepare('SELECT '.$fields.' FROM '.$this->calendarSubscriptionsTableName.' WHERE principaluri = ? ORDER BY calendarorder ASC');
  992. $stmt->execute([$principalUri]);
  993. $subscriptions = [];
  994. while ($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
  995. $subscription = [
  996. 'id' => $row['id'],
  997. 'uri' => $row['uri'],
  998. 'principaluri' => $row['principaluri'],
  999. 'source' => $row['source'],
  1000. 'lastmodified' => $row['lastmodified'],
  1001. '{'.CalDAV\Plugin::NS_CALDAV.'}supported-calendar-component-set' => new CalDAV\Xml\Property\SupportedCalendarComponentSet(['VTODO', 'VEVENT']),
  1002. ];
  1003. foreach ($this->subscriptionPropertyMap as $xmlName => $dbName) {
  1004. if (!is_null($row[$dbName])) {
  1005. $subscription[$xmlName] = $row[$dbName];
  1006. }
  1007. }
  1008. $subscriptions[] = $subscription;
  1009. }
  1010. return $subscriptions;
  1011. }
  1012. /**
  1013. * Creates a new subscription for a principal.
  1014. *
  1015. * If the creation was a success, an id must be returned that can be used to reference
  1016. * this subscription in other methods, such as updateSubscription.
  1017. *
  1018. * @param string $principalUri
  1019. * @param string $uri
  1020. *
  1021. * @return mixed
  1022. */
  1023. public function createSubscription($principalUri, $uri, array $properties)
  1024. {
  1025. $fieldNames = [
  1026. 'principaluri',
  1027. 'uri',
  1028. 'source',
  1029. 'lastmodified',
  1030. ];
  1031. if (!isset($properties['{http://calendarserver.org/ns/}source'])) {
  1032. throw new Forbidden('The {http://calendarserver.org/ns/}source property is required when creating subscriptions');
  1033. }
  1034. $values = [
  1035. ':principaluri' => $principalUri,
  1036. ':uri' => $uri,
  1037. ':source' => $properties['{http://calendarserver.org/ns/}source']->getHref(),
  1038. ':lastmodified' => time(),
  1039. ];
  1040. foreach ($this->subscriptionPropertyMap as $xmlName => $dbName) {
  1041. if (isset($properties[$xmlName])) {
  1042. $values[':'.$dbName] = $properties[$xmlName];
  1043. $fieldNames[] = $dbName;
  1044. }
  1045. }
  1046. $stmt = $this->pdo->prepare('INSERT INTO '.$this->calendarSubscriptionsTableName.' ('.implode(', ', $fieldNames).') VALUES ('.implode(', ', array_keys($values)).')');
  1047. $stmt->execute($values);
  1048. return $this->pdo->lastInsertId(
  1049. $this->calendarSubscriptionsTableName.'_id_seq'
  1050. );
  1051. }
  1052. /**
  1053. * Updates a subscription.
  1054. *
  1055. * The list of mutations is stored in a Sabre\DAV\PropPatch object.
  1056. * To do the actual updates, you must tell this object which properties
  1057. * you're going to process with the handle() method.
  1058. *
  1059. * Calling the handle method is like telling the PropPatch object "I
  1060. * promise I can handle updating this property".
  1061. *
  1062. * Read the PropPatch documentation for more info and examples.
  1063. *
  1064. * @param mixed $subscriptionId
  1065. */
  1066. public function updateSubscription($subscriptionId, PropPatch $propPatch)
  1067. {
  1068. $supportedProperties = array_keys($this->subscriptionPropertyMap);
  1069. $supportedProperties[] = '{http://calendarserver.org/ns/}source';
  1070. $propPatch->handle($supportedProperties, function ($mutations) use ($subscriptionId) {
  1071. $newValues = [];
  1072. foreach ($mutations as $propertyName => $propertyValue) {
  1073. if ('{http://calendarserver.org/ns/}source' === $propertyName) {
  1074. $newValues['source'] = $propertyValue->getHref();
  1075. } else {
  1076. $fieldName = $this->subscriptionPropertyMap[$propertyName];
  1077. $newValues[$fieldName] = $propertyValue;
  1078. }
  1079. }
  1080. // Now we're generating the sql query.
  1081. $valuesSql = [];
  1082. foreach ($newValues as $fieldName => $value) {
  1083. $valuesSql[] = $fieldName.' = ?';
  1084. }
  1085. $stmt = $this->pdo->prepare('UPDATE '.$this->calendarSubscriptionsTableName.' SET '.implode(', ', $valuesSql).', lastmodified = ? WHERE id = ?');
  1086. $newValues['lastmodified'] = time();
  1087. $newValues['id'] = $subscriptionId;
  1088. $stmt->execute(array_values($newValues));
  1089. return true;
  1090. });
  1091. }
  1092. /**
  1093. * Deletes a subscription.
  1094. *
  1095. * @param mixed $subscriptionId
  1096. */
  1097. public function deleteSubscription($subscriptionId)
  1098. {
  1099. $stmt = $this->pdo->prepare('DELETE FROM '.$this->calendarSubscriptionsTableName.' WHERE id = ?');
  1100. $stmt->execute([$subscriptionId]);
  1101. }
  1102. /**
  1103. * Returns a single scheduling object.
  1104. *
  1105. * The returned array should contain the following elements:
  1106. * * uri - A unique basename for the object. This will be used to
  1107. * construct a full uri.
  1108. * * calendardata - The iCalendar object
  1109. * * lastmodified - The last modification date. Can be an int for a unix
  1110. * timestamp, or a PHP DateTime object.
  1111. * * etag - A unique token that must change if the object changed.
  1112. * * size - The size of the object, in bytes.
  1113. *
  1114. * @param string $principalUri
  1115. * @param string $objectUri
  1116. *
  1117. * @return array
  1118. */
  1119. public function getSchedulingObject($principalUri, $objectUri)
  1120. {
  1121. $stmt = $this->pdo->prepare('SELECT uri, calendardata, lastmodified, etag, size FROM '.$this->schedulingObjectTableName.' WHERE principaluri = ? AND uri = ?');
  1122. $stmt->execute([$principalUri, $objectUri]);
  1123. $row = $stmt->fetch(\PDO::FETCH_ASSOC);
  1124. if (!$row) {
  1125. return null;
  1126. }
  1127. return [
  1128. 'uri' => $row['uri'],
  1129. 'calendardata' => $row['calendardata'],
  1130. 'lastmodified' => $row['lastmodified'],
  1131. 'etag' => '"'.$row['etag'].'"',
  1132. 'size' => (int) $row['size'],
  1133. ];
  1134. }
  1135. /**
  1136. * Returns all scheduling objects for the inbox collection.
  1137. *
  1138. * These objects should be returned as an array. Every item in the array
  1139. * should follow the same structure as returned from getSchedulingObject.
  1140. *
  1141. * The main difference is that 'calendardata' is optional.
  1142. *
  1143. * @param string $principalUri
  1144. *
  1145. * @return array
  1146. */
  1147. public function getSchedulingObjects($principalUri)
  1148. {
  1149. $stmt = $this->pdo->prepare('SELECT id, calendardata, uri, lastmodified, etag, size FROM '.$this->schedulingObjectTableName.' WHERE principaluri = ?');
  1150. $stmt->execute([$principalUri]);
  1151. $result = [];
  1152. foreach ($stmt->fetchAll(\PDO::FETCH_ASSOC) as $row) {
  1153. $result[] = [
  1154. 'calendardata' => $row['calendardata'],
  1155. 'uri' => $row['uri'],
  1156. 'lastmodified' => $row['lastmodified'],
  1157. 'etag' => '"'.$row['etag'].'"',
  1158. 'size' => (int) $row['size'],
  1159. ];
  1160. }
  1161. return $result;
  1162. }
  1163. /**
  1164. * Deletes a scheduling object.
  1165. *
  1166. * @param string $principalUri
  1167. * @param string $objectUri
  1168. */
  1169. public function deleteSchedulingObject($principalUri, $objectUri)
  1170. {
  1171. $stmt = $this->pdo->prepare('DELETE FROM '.$this->schedulingObjectTableName.' WHERE principaluri = ? AND uri = ?');
  1172. $stmt->execute([$principalUri, $objectUri]);
  1173. }
  1174. /**
  1175. * Creates a new scheduling object. This should land in a users' inbox.
  1176. *
  1177. * @param string $principalUri
  1178. * @param string $objectUri
  1179. * @param string|resource $objectData
  1180. */
  1181. public function createSchedulingObject($principalUri, $objectUri, $objectData)
  1182. {
  1183. $stmt = $this->pdo->prepare('INSERT INTO '.$this->schedulingObjectTableName.' (principaluri, calendardata, uri, lastmodified, etag, size) VALUES (?, ?, ?, ?, ?, ?)');
  1184. if (is_resource($objectData)) {
  1185. $objectData = stream_get_contents($objectData);
  1186. }
  1187. $stmt->execute([$principalUri, $objectData, $objectUri, time(), md5($objectData), strlen($objectData)]);
  1188. }
  1189. /**
  1190. * Updates the list of shares.
  1191. *
  1192. * @param mixed $calendarId
  1193. * @param \Sabre\DAV\Xml\Element\Sharee[] $sharees
  1194. */
  1195. public function updateInvites($calendarId, array $sharees)
  1196. {
  1197. if (!is_array($calendarId)) {
  1198. throw new \InvalidArgumentException('The value passed to $calendarId is expected to be an array with a calendarId and an instanceId');
  1199. }
  1200. $currentInvites = $this->getInvites($calendarId);
  1201. list($calendarId, $instanceId) = $calendarId;
  1202. $removeStmt = $this->pdo->prepare('DELETE FROM '.$this->calendarInstancesTableName.' WHERE calendarid = ? AND share_href = ? AND access IN (2,3)');
  1203. $updateStmt = $this->pdo->prepare('UPDATE '.$this->calendarInstancesTableName.' SET access = ?, share_displayname = ?, share_invitestatus = ? WHERE calendarid = ? AND share_href = ?');
  1204. $insertStmt = $this->pdo->prepare('
  1205. INSERT INTO '.$this->calendarInstancesTableName.'
  1206. (
  1207. calendarid,
  1208. principaluri,
  1209. access,
  1210. displayname,
  1211. uri,
  1212. description,
  1213. calendarorder,
  1214. calendarcolor,
  1215. timezone,
  1216. transparent,
  1217. share_href,
  1218. share_displayname,
  1219. share_invitestatus
  1220. )
  1221. SELECT
  1222. ?,
  1223. ?,
  1224. ?,
  1225. displayname,
  1226. ?,
  1227. description,
  1228. calendarorder,
  1229. calendarcolor,
  1230. timezone,
  1231. 1,
  1232. ?,
  1233. ?,
  1234. ?
  1235. FROM '.$this->calendarInstancesTableName.' WHERE id = ?');
  1236. foreach ($sharees as $sharee) {
  1237. if (\Sabre\DAV\Sharing\Plugin::ACCESS_NOACCESS === $sharee->access) {
  1238. // if access was set no NOACCESS, it means access for an
  1239. // existing sharee was removed.
  1240. $removeStmt->execute([$calendarId, $sharee->href]);
  1241. continue;
  1242. }
  1243. if (is_null($sharee->principal)) {
  1244. // If the server could not determine the principal automatically,
  1245. // we will mark the invite status as invalid.
  1246. $sharee->inviteStatus = \Sabre\DAV\Sharing\Plugin::INVITE_INVALID;
  1247. } else {
  1248. // Because sabre/dav does not yet have an invitation system,
  1249. // every invite is automatically accepted for now.
  1250. $sharee->inviteStatus = \Sabre\DAV\Sharing\Plugin::INVITE_ACCEPTED;
  1251. }
  1252. foreach ($currentInvites as $oldSharee) {
  1253. if ($oldSharee->href === $sharee->href) {
  1254. // This is an update
  1255. $sharee->properties = array_merge(
  1256. $oldSharee->properties,
  1257. $sharee->properties
  1258. );
  1259. $updateStmt->execute([
  1260. $sharee->access,
  1261. isset($sharee->properties['{DAV:}displayname']) ? $sharee->properties['{DAV:}displayname'] : null,
  1262. $sharee->inviteStatus ?: $oldSharee->inviteStatus,
  1263. $calendarId,
  1264. $sharee->href,
  1265. ]);
  1266. continue 2;
  1267. }
  1268. }
  1269. // If we got here, it means it was a new sharee
  1270. $insertStmt->execute([
  1271. $calendarId,
  1272. $sharee->principal,
  1273. $sharee->access,
  1274. \Sabre\DAV\UUIDUtil::getUUID(),
  1275. $sharee->href,
  1276. isset($sharee->properties['{DAV:}displayname']) ? $sharee->properties['{DAV:}displayname'] : null,
  1277. $sharee->inviteStatus ?: \Sabre\DAV\Sharing\Plugin::INVITE_NORESPONSE,
  1278. $instanceId,
  1279. ]);
  1280. }
  1281. }
  1282. /**
  1283. * Returns the list of people whom a calendar is shared with.
  1284. *
  1285. * Every item in the returned list must be a Sharee object with at
  1286. * least the following properties set:
  1287. * $href
  1288. * $shareAccess
  1289. * $inviteStatus
  1290. *
  1291. * and optionally:
  1292. * $properties
  1293. *
  1294. * @param mixed $calendarId
  1295. *
  1296. * @return \Sabre\DAV\Xml\Element\Sharee[]
  1297. */
  1298. public function getInvites($calendarId)
  1299. {
  1300. if (!is_array($calendarId)) {
  1301. throw new \InvalidArgumentException('The value passed to getInvites() is expected to be an array with a calendarId and an instanceId');
  1302. }
  1303. list($calendarId, $instanceId) = $calendarId;
  1304. $query = <<<SQL
  1305. SELECT
  1306. principaluri,
  1307. access,
  1308. share_href,
  1309. share_displayname,
  1310. share_invitestatus
  1311. FROM {$this->calendarInstancesTableName}
  1312. WHERE
  1313. calendarid = ?
  1314. SQL;
  1315. $stmt = $this->pdo->prepare($query);
  1316. $stmt->execute([$calendarId]);
  1317. $result = [];
  1318. while ($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
  1319. $result[] = new Sharee([
  1320. 'href' => isset($row['share_href']) ? $row['share_href'] : \Sabre\HTTP\encodePath($row['principaluri']),
  1321. 'access' => (int) $row['access'],
  1322. /// Everyone is always immediately accepted, for now.
  1323. 'inviteStatus' => (int) $row['share_invitestatus'],
  1324. 'properties' => !empty($row['share_displayname'])
  1325. ? ['{DAV:}displayname' => $row['share_displayname']]
  1326. : [],
  1327. 'principal' => $row['principaluri'],
  1328. ]);
  1329. }
  1330. return $result;
  1331. }
  1332. /**
  1333. * Publishes a calendar.
  1334. *
  1335. * @param mixed $calendarId
  1336. * @param bool $value
  1337. */
  1338. public function setPublishStatus($calendarId, $value)
  1339. {
  1340. throw new DAV\Exception\NotImplemented('Not implemented');
  1341. }
  1342. }