CalDavBackend.php 128 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545
  1. <?php
  2. /**
  3. * SPDX-FileCopyrightText: 2018 Nextcloud GmbH and Nextcloud contributors
  4. * SPDX-FileCopyrightText: 2016 ownCloud, Inc.
  5. * SPDX-License-Identifier: AGPL-3.0-only
  6. */
  7. namespace OCA\DAV\CalDAV;
  8. use DateTime;
  9. use DateTimeImmutable;
  10. use DateTimeInterface;
  11. use OCA\DAV\AppInfo\Application;
  12. use OCA\DAV\CalDAV\Sharing\Backend;
  13. use OCA\DAV\Connector\Sabre\Principal;
  14. use OCA\DAV\DAV\Sharing\IShareable;
  15. use OCA\DAV\Events\CachedCalendarObjectCreatedEvent;
  16. use OCA\DAV\Events\CachedCalendarObjectDeletedEvent;
  17. use OCA\DAV\Events\CachedCalendarObjectUpdatedEvent;
  18. use OCA\DAV\Events\CalendarCreatedEvent;
  19. use OCA\DAV\Events\CalendarDeletedEvent;
  20. use OCA\DAV\Events\CalendarMovedToTrashEvent;
  21. use OCA\DAV\Events\CalendarObjectCreatedEvent;
  22. use OCA\DAV\Events\CalendarObjectDeletedEvent;
  23. use OCA\DAV\Events\CalendarObjectMovedEvent;
  24. use OCA\DAV\Events\CalendarObjectMovedToTrashEvent;
  25. use OCA\DAV\Events\CalendarObjectRestoredEvent;
  26. use OCA\DAV\Events\CalendarObjectUpdatedEvent;
  27. use OCA\DAV\Events\CalendarPublishedEvent;
  28. use OCA\DAV\Events\CalendarRestoredEvent;
  29. use OCA\DAV\Events\CalendarShareUpdatedEvent;
  30. use OCA\DAV\Events\CalendarUnpublishedEvent;
  31. use OCA\DAV\Events\CalendarUpdatedEvent;
  32. use OCA\DAV\Events\SubscriptionCreatedEvent;
  33. use OCA\DAV\Events\SubscriptionDeletedEvent;
  34. use OCA\DAV\Events\SubscriptionUpdatedEvent;
  35. use OCP\AppFramework\Db\TTransactional;
  36. use OCP\Calendar\Exceptions\CalendarException;
  37. use OCP\DB\Exception;
  38. use OCP\DB\QueryBuilder\IQueryBuilder;
  39. use OCP\EventDispatcher\IEventDispatcher;
  40. use OCP\IConfig;
  41. use OCP\IDBConnection;
  42. use OCP\IUserManager;
  43. use OCP\Security\ISecureRandom;
  44. use Psr\Log\LoggerInterface;
  45. use RuntimeException;
  46. use Sabre\CalDAV\Backend\AbstractBackend;
  47. use Sabre\CalDAV\Backend\SchedulingSupport;
  48. use Sabre\CalDAV\Backend\SubscriptionSupport;
  49. use Sabre\CalDAV\Backend\SyncSupport;
  50. use Sabre\CalDAV\Xml\Property\ScheduleCalendarTransp;
  51. use Sabre\CalDAV\Xml\Property\SupportedCalendarComponentSet;
  52. use Sabre\DAV;
  53. use Sabre\DAV\Exception\BadRequest;
  54. use Sabre\DAV\Exception\Forbidden;
  55. use Sabre\DAV\Exception\NotFound;
  56. use Sabre\DAV\PropPatch;
  57. use Sabre\Uri;
  58. use Sabre\VObject\Component;
  59. use Sabre\VObject\Component\VCalendar;
  60. use Sabre\VObject\Component\VTimeZone;
  61. use Sabre\VObject\DateTimeParser;
  62. use Sabre\VObject\InvalidDataException;
  63. use Sabre\VObject\ParseException;
  64. use Sabre\VObject\Property;
  65. use Sabre\VObject\Reader;
  66. use Sabre\VObject\Recur\EventIterator;
  67. use Sabre\VObject\Recur\MaxInstancesExceededException;
  68. use Sabre\VObject\Recur\NoInstancesException;
  69. use function array_column;
  70. use function array_map;
  71. use function array_merge;
  72. use function array_values;
  73. use function explode;
  74. use function is_array;
  75. use function is_resource;
  76. use function pathinfo;
  77. use function rewind;
  78. use function settype;
  79. use function sprintf;
  80. use function str_replace;
  81. use function strtolower;
  82. use function time;
  83. /**
  84. * Class CalDavBackend
  85. *
  86. * Code is heavily inspired by https://github.com/fruux/sabre-dav/blob/master/lib/CalDAV/Backend/PDO.php
  87. *
  88. * @package OCA\DAV\CalDAV
  89. */
  90. class CalDavBackend extends AbstractBackend implements SyncSupport, SubscriptionSupport, SchedulingSupport {
  91. use TTransactional;
  92. public const CALENDAR_TYPE_CALENDAR = 0;
  93. public const CALENDAR_TYPE_SUBSCRIPTION = 1;
  94. public const PERSONAL_CALENDAR_URI = 'personal';
  95. public const PERSONAL_CALENDAR_NAME = 'Personal';
  96. public const RESOURCE_BOOKING_CALENDAR_URI = 'calendar';
  97. public const RESOURCE_BOOKING_CALENDAR_NAME = 'Calendar';
  98. /**
  99. * We need to specify a max date, because we need to stop *somewhere*
  100. *
  101. * On 32 bit system the maximum for a signed integer is 2147483647, so
  102. * MAX_DATE cannot be higher than date('Y-m-d', 2147483647) which results
  103. * in 2038-01-19 to avoid problems when the date is converted
  104. * to a unix timestamp.
  105. */
  106. public const MAX_DATE = '2038-01-01';
  107. public const ACCESS_PUBLIC = 4;
  108. public const CLASSIFICATION_PUBLIC = 0;
  109. public const CLASSIFICATION_PRIVATE = 1;
  110. public const CLASSIFICATION_CONFIDENTIAL = 2;
  111. /**
  112. * List of CalDAV properties, and how they map to database field names and their type
  113. * Add your own properties by simply adding on to this array.
  114. *
  115. * @var array
  116. * @psalm-var array<string, string[]>
  117. */
  118. public array $propertyMap = [
  119. '{DAV:}displayname' => ['displayname', 'string'],
  120. '{urn:ietf:params:xml:ns:caldav}calendar-description' => ['description', 'string'],
  121. '{urn:ietf:params:xml:ns:caldav}calendar-timezone' => ['timezone', 'string'],
  122. '{http://apple.com/ns/ical/}calendar-order' => ['calendarorder', 'int'],
  123. '{http://apple.com/ns/ical/}calendar-color' => ['calendarcolor', 'string'],
  124. '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_NEXTCLOUD . '}deleted-at' => ['deleted_at', 'int'],
  125. ];
  126. /**
  127. * List of subscription properties, and how they map to database field names.
  128. *
  129. * @var array
  130. */
  131. public array $subscriptionPropertyMap = [
  132. '{DAV:}displayname' => ['displayname', 'string'],
  133. '{http://apple.com/ns/ical/}refreshrate' => ['refreshrate', 'string'],
  134. '{http://apple.com/ns/ical/}calendar-order' => ['calendarorder', 'int'],
  135. '{http://apple.com/ns/ical/}calendar-color' => ['calendarcolor', 'string'],
  136. '{http://calendarserver.org/ns/}subscribed-strip-todos' => ['striptodos', 'bool'],
  137. '{http://calendarserver.org/ns/}subscribed-strip-alarms' => ['stripalarms', 'string'],
  138. '{http://calendarserver.org/ns/}subscribed-strip-attachments' => ['stripattachments', 'string'],
  139. ];
  140. /**
  141. * properties to index
  142. *
  143. * This list has to be kept in sync with ICalendarQuery::SEARCH_PROPERTY_*
  144. *
  145. * @see \OCP\Calendar\ICalendarQuery
  146. */
  147. private const INDEXED_PROPERTIES = [
  148. 'CATEGORIES',
  149. 'COMMENT',
  150. 'DESCRIPTION',
  151. 'LOCATION',
  152. 'RESOURCES',
  153. 'STATUS',
  154. 'SUMMARY',
  155. 'ATTENDEE',
  156. 'CONTACT',
  157. 'ORGANIZER'
  158. ];
  159. /** @var array parameters to index */
  160. public static array $indexParameters = [
  161. 'ATTENDEE' => ['CN'],
  162. 'ORGANIZER' => ['CN'],
  163. ];
  164. /**
  165. * @var string[] Map of uid => display name
  166. */
  167. protected array $userDisplayNames;
  168. private string $dbObjectPropertiesTable = 'calendarobjects_props';
  169. private array $cachedObjects = [];
  170. public function __construct(
  171. private IDBConnection $db,
  172. private Principal $principalBackend,
  173. private IUserManager $userManager,
  174. private ISecureRandom $random,
  175. private LoggerInterface $logger,
  176. private IEventDispatcher $dispatcher,
  177. private IConfig $config,
  178. private Sharing\Backend $calendarSharingBackend,
  179. private bool $legacyEndpoint = false,
  180. ) {
  181. }
  182. /**
  183. * Return the number of calendars for a principal
  184. *
  185. * By default this excludes the automatically generated birthday calendar
  186. *
  187. * @param $principalUri
  188. * @param bool $excludeBirthday
  189. * @return int
  190. */
  191. public function getCalendarsForUserCount($principalUri, $excludeBirthday = true) {
  192. $principalUri = $this->convertPrincipal($principalUri, true);
  193. $query = $this->db->getQueryBuilder();
  194. $query->select($query->func()->count('*'))
  195. ->from('calendars');
  196. if ($principalUri === '') {
  197. $query->where($query->expr()->emptyString('principaluri'));
  198. } else {
  199. $query->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)));
  200. }
  201. if ($excludeBirthday) {
  202. $query->andWhere($query->expr()->neq('uri', $query->createNamedParameter(BirthdayService::BIRTHDAY_CALENDAR_URI)));
  203. }
  204. $result = $query->executeQuery();
  205. $column = (int)$result->fetchOne();
  206. $result->closeCursor();
  207. return $column;
  208. }
  209. /**
  210. * Return the number of subscriptions for a principal
  211. */
  212. public function getSubscriptionsForUserCount(string $principalUri): int {
  213. $principalUri = $this->convertPrincipal($principalUri, true);
  214. $query = $this->db->getQueryBuilder();
  215. $query->select($query->func()->count('*'))
  216. ->from('calendarsubscriptions');
  217. if ($principalUri === '') {
  218. $query->where($query->expr()->emptyString('principaluri'));
  219. } else {
  220. $query->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)));
  221. }
  222. $result = $query->executeQuery();
  223. $column = (int)$result->fetchOne();
  224. $result->closeCursor();
  225. return $column;
  226. }
  227. /**
  228. * @return array{id: int, deleted_at: int}[]
  229. */
  230. public function getDeletedCalendars(int $deletedBefore): array {
  231. $qb = $this->db->getQueryBuilder();
  232. $qb->select(['id', 'deleted_at'])
  233. ->from('calendars')
  234. ->where($qb->expr()->isNotNull('deleted_at'))
  235. ->andWhere($qb->expr()->lt('deleted_at', $qb->createNamedParameter($deletedBefore)));
  236. $result = $qb->executeQuery();
  237. $calendars = [];
  238. while (($row = $result->fetch()) !== false) {
  239. $calendars[] = [
  240. 'id' => (int) $row['id'],
  241. 'deleted_at' => (int) $row['deleted_at'],
  242. ];
  243. }
  244. $result->closeCursor();
  245. return $calendars;
  246. }
  247. /**
  248. * Returns a list of calendars for a principal.
  249. *
  250. * Every project is an array with the following keys:
  251. * * id, a unique id that will be used by other functions to modify the
  252. * calendar. This can be the same as the uri or a database key.
  253. * * uri, which the basename of the uri with which the calendar is
  254. * accessed.
  255. * * principaluri. The owner of the calendar. Almost always the same as
  256. * principalUri passed to this method.
  257. *
  258. * Furthermore it can contain webdav properties in clark notation. A very
  259. * common one is '{DAV:}displayname'.
  260. *
  261. * Many clients also require:
  262. * {urn:ietf:params:xml:ns:caldav}supported-calendar-component-set
  263. * For this property, you can just return an instance of
  264. * Sabre\CalDAV\Property\SupportedCalendarComponentSet.
  265. *
  266. * If you return {http://sabredav.org/ns}read-only and set the value to 1,
  267. * ACL will automatically be put in read-only mode.
  268. *
  269. * @param string $principalUri
  270. * @return array
  271. */
  272. public function getCalendarsForUser($principalUri) {
  273. return $this->atomic(function () use ($principalUri) {
  274. $principalUriOriginal = $principalUri;
  275. $principalUri = $this->convertPrincipal($principalUri, true);
  276. $fields = array_column($this->propertyMap, 0);
  277. $fields[] = 'id';
  278. $fields[] = 'uri';
  279. $fields[] = 'synctoken';
  280. $fields[] = 'components';
  281. $fields[] = 'principaluri';
  282. $fields[] = 'transparent';
  283. // Making fields a comma-delimited list
  284. $query = $this->db->getQueryBuilder();
  285. $query->select($fields)
  286. ->from('calendars')
  287. ->orderBy('calendarorder', 'ASC');
  288. if ($principalUri === '') {
  289. $query->where($query->expr()->emptyString('principaluri'));
  290. } else {
  291. $query->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)));
  292. }
  293. $result = $query->executeQuery();
  294. $calendars = [];
  295. while ($row = $result->fetch()) {
  296. $row['principaluri'] = (string) $row['principaluri'];
  297. $components = [];
  298. if ($row['components']) {
  299. $components = explode(',', $row['components']);
  300. }
  301. $calendar = [
  302. 'id' => $row['id'],
  303. 'uri' => $row['uri'],
  304. 'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
  305. '{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
  306. '{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
  307. '{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
  308. '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
  309. '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($principalUri, !$this->legacyEndpoint),
  310. ];
  311. $calendar = $this->rowToCalendar($row, $calendar);
  312. $calendar = $this->addOwnerPrincipalToCalendar($calendar);
  313. $calendar = $this->addResourceTypeToCalendar($row, $calendar);
  314. if (!isset($calendars[$calendar['id']])) {
  315. $calendars[$calendar['id']] = $calendar;
  316. }
  317. }
  318. $result->closeCursor();
  319. // query for shared calendars
  320. $principals = $this->principalBackend->getGroupMembership($principalUriOriginal, true);
  321. $principals = array_merge($principals, $this->principalBackend->getCircleMembership($principalUriOriginal));
  322. $principals[] = $principalUri;
  323. $fields = array_column($this->propertyMap, 0);
  324. $fields = array_map(function (string $field) {
  325. return 'a.'.$field;
  326. }, $fields);
  327. $fields[] = 'a.id';
  328. $fields[] = 'a.uri';
  329. $fields[] = 'a.synctoken';
  330. $fields[] = 'a.components';
  331. $fields[] = 'a.principaluri';
  332. $fields[] = 'a.transparent';
  333. $fields[] = 's.access';
  334. $select = $this->db->getQueryBuilder();
  335. $subSelect = $this->db->getQueryBuilder();
  336. $subSelect->select('resourceid')
  337. ->from('dav_shares', 'd')
  338. ->where($subSelect->expr()->eq('d.access', $select->createNamedParameter(Backend::ACCESS_UNSHARED, IQueryBuilder::PARAM_INT), IQueryBuilder::PARAM_INT))
  339. ->andWhere($subSelect->expr()->in('d.principaluri', $select->createNamedParameter($principals, IQueryBuilder::PARAM_STR_ARRAY), IQueryBuilder::PARAM_STR_ARRAY));
  340. $select->select($fields)
  341. ->from('dav_shares', 's')
  342. ->join('s', 'calendars', 'a', $select->expr()->eq('s.resourceid', 'a.id', IQueryBuilder::PARAM_INT))
  343. ->where($select->expr()->in('s.principaluri', $select->createNamedParameter($principals, IQueryBuilder::PARAM_STR_ARRAY), IQueryBuilder::PARAM_STR_ARRAY))
  344. ->andWhere($select->expr()->eq('s.type', $select->createNamedParameter('calendar', IQueryBuilder::PARAM_STR), IQueryBuilder::PARAM_STR))
  345. ->andWhere($select->expr()->notIn('a.id', $select->createFunction($subSelect->getSQL()), IQueryBuilder::PARAM_INT_ARRAY));
  346. $results = $select->executeQuery();
  347. $readOnlyPropertyName = '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}read-only';
  348. while ($row = $results->fetch()) {
  349. $row['principaluri'] = (string) $row['principaluri'];
  350. if ($row['principaluri'] === $principalUri) {
  351. continue;
  352. }
  353. $readOnly = (int) $row['access'] === Backend::ACCESS_READ;
  354. if (isset($calendars[$row['id']])) {
  355. if ($readOnly) {
  356. // New share can not have more permissions than the old one.
  357. continue;
  358. }
  359. if (isset($calendars[$row['id']][$readOnlyPropertyName]) &&
  360. $calendars[$row['id']][$readOnlyPropertyName] === 0) {
  361. // Old share is already read-write, no more permissions can be gained
  362. continue;
  363. }
  364. }
  365. [, $name] = Uri\split($row['principaluri']);
  366. $uri = $row['uri'] . '_shared_by_' . $name;
  367. $row['displayname'] = $row['displayname'] . ' (' . ($this->userManager->getDisplayName($name) ?? ($name ?? '')) . ')';
  368. $components = [];
  369. if ($row['components']) {
  370. $components = explode(',', $row['components']);
  371. }
  372. $calendar = [
  373. 'id' => $row['id'],
  374. 'uri' => $uri,
  375. 'principaluri' => $this->convertPrincipal($principalUri, !$this->legacyEndpoint),
  376. '{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
  377. '{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
  378. '{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
  379. '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp('transparent'),
  380. '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
  381. $readOnlyPropertyName => $readOnly,
  382. ];
  383. $calendar = $this->rowToCalendar($row, $calendar);
  384. $calendar = $this->addOwnerPrincipalToCalendar($calendar);
  385. $calendar = $this->addResourceTypeToCalendar($row, $calendar);
  386. $calendars[$calendar['id']] = $calendar;
  387. }
  388. $result->closeCursor();
  389. return array_values($calendars);
  390. }, $this->db);
  391. }
  392. /**
  393. * @param $principalUri
  394. * @return array
  395. */
  396. public function getUsersOwnCalendars($principalUri) {
  397. $principalUri = $this->convertPrincipal($principalUri, true);
  398. $fields = array_column($this->propertyMap, 0);
  399. $fields[] = 'id';
  400. $fields[] = 'uri';
  401. $fields[] = 'synctoken';
  402. $fields[] = 'components';
  403. $fields[] = 'principaluri';
  404. $fields[] = 'transparent';
  405. // Making fields a comma-delimited list
  406. $query = $this->db->getQueryBuilder();
  407. $query->select($fields)->from('calendars')
  408. ->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
  409. ->orderBy('calendarorder', 'ASC');
  410. $stmt = $query->executeQuery();
  411. $calendars = [];
  412. while ($row = $stmt->fetch()) {
  413. $row['principaluri'] = (string) $row['principaluri'];
  414. $components = [];
  415. if ($row['components']) {
  416. $components = explode(',', $row['components']);
  417. }
  418. $calendar = [
  419. 'id' => $row['id'],
  420. 'uri' => $row['uri'],
  421. 'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
  422. '{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
  423. '{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
  424. '{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
  425. '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
  426. ];
  427. $calendar = $this->rowToCalendar($row, $calendar);
  428. $calendar = $this->addOwnerPrincipalToCalendar($calendar);
  429. $calendar = $this->addResourceTypeToCalendar($row, $calendar);
  430. if (!isset($calendars[$calendar['id']])) {
  431. $calendars[$calendar['id']] = $calendar;
  432. }
  433. }
  434. $stmt->closeCursor();
  435. return array_values($calendars);
  436. }
  437. /**
  438. * @return array
  439. */
  440. public function getPublicCalendars() {
  441. $fields = array_column($this->propertyMap, 0);
  442. $fields[] = 'a.id';
  443. $fields[] = 'a.uri';
  444. $fields[] = 'a.synctoken';
  445. $fields[] = 'a.components';
  446. $fields[] = 'a.principaluri';
  447. $fields[] = 'a.transparent';
  448. $fields[] = 's.access';
  449. $fields[] = 's.publicuri';
  450. $calendars = [];
  451. $query = $this->db->getQueryBuilder();
  452. $result = $query->select($fields)
  453. ->from('dav_shares', 's')
  454. ->join('s', 'calendars', 'a', $query->expr()->eq('s.resourceid', 'a.id'))
  455. ->where($query->expr()->in('s.access', $query->createNamedParameter(self::ACCESS_PUBLIC)))
  456. ->andWhere($query->expr()->eq('s.type', $query->createNamedParameter('calendar')))
  457. ->executeQuery();
  458. while ($row = $result->fetch()) {
  459. $row['principaluri'] = (string) $row['principaluri'];
  460. [, $name] = Uri\split($row['principaluri']);
  461. $row['displayname'] = $row['displayname'] . "($name)";
  462. $components = [];
  463. if ($row['components']) {
  464. $components = explode(',', $row['components']);
  465. }
  466. $calendar = [
  467. 'id' => $row['id'],
  468. 'uri' => $row['publicuri'],
  469. 'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
  470. '{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
  471. '{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
  472. '{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
  473. '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
  474. '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($row['principaluri'], $this->legacyEndpoint),
  475. '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}read-only' => (int)$row['access'] === Backend::ACCESS_READ,
  476. '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}public' => (int)$row['access'] === self::ACCESS_PUBLIC,
  477. ];
  478. $calendar = $this->rowToCalendar($row, $calendar);
  479. $calendar = $this->addOwnerPrincipalToCalendar($calendar);
  480. $calendar = $this->addResourceTypeToCalendar($row, $calendar);
  481. if (!isset($calendars[$calendar['id']])) {
  482. $calendars[$calendar['id']] = $calendar;
  483. }
  484. }
  485. $result->closeCursor();
  486. return array_values($calendars);
  487. }
  488. /**
  489. * @param string $uri
  490. * @return array
  491. * @throws NotFound
  492. */
  493. public function getPublicCalendar($uri) {
  494. $fields = array_column($this->propertyMap, 0);
  495. $fields[] = 'a.id';
  496. $fields[] = 'a.uri';
  497. $fields[] = 'a.synctoken';
  498. $fields[] = 'a.components';
  499. $fields[] = 'a.principaluri';
  500. $fields[] = 'a.transparent';
  501. $fields[] = 's.access';
  502. $fields[] = 's.publicuri';
  503. $query = $this->db->getQueryBuilder();
  504. $result = $query->select($fields)
  505. ->from('dav_shares', 's')
  506. ->join('s', 'calendars', 'a', $query->expr()->eq('s.resourceid', 'a.id'))
  507. ->where($query->expr()->in('s.access', $query->createNamedParameter(self::ACCESS_PUBLIC)))
  508. ->andWhere($query->expr()->eq('s.type', $query->createNamedParameter('calendar')))
  509. ->andWhere($query->expr()->eq('s.publicuri', $query->createNamedParameter($uri)))
  510. ->executeQuery();
  511. $row = $result->fetch();
  512. $result->closeCursor();
  513. if ($row === false) {
  514. throw new NotFound('Node with name \'' . $uri . '\' could not be found');
  515. }
  516. $row['principaluri'] = (string) $row['principaluri'];
  517. [, $name] = Uri\split($row['principaluri']);
  518. $row['displayname'] = $row['displayname'] . ' ' . "($name)";
  519. $components = [];
  520. if ($row['components']) {
  521. $components = explode(',', $row['components']);
  522. }
  523. $calendar = [
  524. 'id' => $row['id'],
  525. 'uri' => $row['publicuri'],
  526. 'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
  527. '{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
  528. '{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
  529. '{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
  530. '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
  531. '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
  532. '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}read-only' => (int)$row['access'] === Backend::ACCESS_READ,
  533. '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}public' => (int)$row['access'] === self::ACCESS_PUBLIC,
  534. ];
  535. $calendar = $this->rowToCalendar($row, $calendar);
  536. $calendar = $this->addOwnerPrincipalToCalendar($calendar);
  537. $calendar = $this->addResourceTypeToCalendar($row, $calendar);
  538. return $calendar;
  539. }
  540. /**
  541. * @param string $principal
  542. * @param string $uri
  543. * @return array|null
  544. */
  545. public function getCalendarByUri($principal, $uri) {
  546. $fields = array_column($this->propertyMap, 0);
  547. $fields[] = 'id';
  548. $fields[] = 'uri';
  549. $fields[] = 'synctoken';
  550. $fields[] = 'components';
  551. $fields[] = 'principaluri';
  552. $fields[] = 'transparent';
  553. // Making fields a comma-delimited list
  554. $query = $this->db->getQueryBuilder();
  555. $query->select($fields)->from('calendars')
  556. ->where($query->expr()->eq('uri', $query->createNamedParameter($uri)))
  557. ->andWhere($query->expr()->eq('principaluri', $query->createNamedParameter($principal)))
  558. ->setMaxResults(1);
  559. $stmt = $query->executeQuery();
  560. $row = $stmt->fetch();
  561. $stmt->closeCursor();
  562. if ($row === false) {
  563. return null;
  564. }
  565. $row['principaluri'] = (string) $row['principaluri'];
  566. $components = [];
  567. if ($row['components']) {
  568. $components = explode(',', $row['components']);
  569. }
  570. $calendar = [
  571. 'id' => $row['id'],
  572. 'uri' => $row['uri'],
  573. 'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
  574. '{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
  575. '{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
  576. '{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
  577. '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
  578. ];
  579. $calendar = $this->rowToCalendar($row, $calendar);
  580. $calendar = $this->addOwnerPrincipalToCalendar($calendar);
  581. $calendar = $this->addResourceTypeToCalendar($row, $calendar);
  582. return $calendar;
  583. }
  584. /**
  585. * @return array{id: int, uri: string, '{http://calendarserver.org/ns/}getctag': string, '{http://sabredav.org/ns}sync-token': int, '{urn:ietf:params:xml:ns:caldav}supported-calendar-component-set': SupportedCalendarComponentSet, '{urn:ietf:params:xml:ns:caldav}schedule-calendar-transp': ScheduleCalendarTransp, '{urn:ietf:params:xml:ns:caldav}calendar-timezone': ?string }|null
  586. */
  587. public function getCalendarById(int $calendarId): ?array {
  588. $fields = array_column($this->propertyMap, 0);
  589. $fields[] = 'id';
  590. $fields[] = 'uri';
  591. $fields[] = 'synctoken';
  592. $fields[] = 'components';
  593. $fields[] = 'principaluri';
  594. $fields[] = 'transparent';
  595. // Making fields a comma-delimited list
  596. $query = $this->db->getQueryBuilder();
  597. $query->select($fields)->from('calendars')
  598. ->where($query->expr()->eq('id', $query->createNamedParameter($calendarId)))
  599. ->setMaxResults(1);
  600. $stmt = $query->executeQuery();
  601. $row = $stmt->fetch();
  602. $stmt->closeCursor();
  603. if ($row === false) {
  604. return null;
  605. }
  606. $row['principaluri'] = (string) $row['principaluri'];
  607. $components = [];
  608. if ($row['components']) {
  609. $components = explode(',', $row['components']);
  610. }
  611. $calendar = [
  612. 'id' => $row['id'],
  613. 'uri' => $row['uri'],
  614. 'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
  615. '{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
  616. '{http://sabredav.org/ns}sync-token' => $row['synctoken'] ?? 0,
  617. '{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
  618. '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
  619. ];
  620. $calendar = $this->rowToCalendar($row, $calendar);
  621. $calendar = $this->addOwnerPrincipalToCalendar($calendar);
  622. $calendar = $this->addResourceTypeToCalendar($row, $calendar);
  623. return $calendar;
  624. }
  625. /**
  626. * @param $subscriptionId
  627. */
  628. public function getSubscriptionById($subscriptionId) {
  629. $fields = array_column($this->subscriptionPropertyMap, 0);
  630. $fields[] = 'id';
  631. $fields[] = 'uri';
  632. $fields[] = 'source';
  633. $fields[] = 'synctoken';
  634. $fields[] = 'principaluri';
  635. $fields[] = 'lastmodified';
  636. $query = $this->db->getQueryBuilder();
  637. $query->select($fields)
  638. ->from('calendarsubscriptions')
  639. ->where($query->expr()->eq('id', $query->createNamedParameter($subscriptionId)))
  640. ->orderBy('calendarorder', 'asc');
  641. $stmt = $query->executeQuery();
  642. $row = $stmt->fetch();
  643. $stmt->closeCursor();
  644. if ($row === false) {
  645. return null;
  646. }
  647. $row['principaluri'] = (string) $row['principaluri'];
  648. $subscription = [
  649. 'id' => $row['id'],
  650. 'uri' => $row['uri'],
  651. 'principaluri' => $row['principaluri'],
  652. 'source' => $row['source'],
  653. 'lastmodified' => $row['lastmodified'],
  654. '{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet(['VTODO', 'VEVENT']),
  655. '{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
  656. ];
  657. return $this->rowToSubscription($row, $subscription);
  658. }
  659. /**
  660. * Creates a new calendar for a principal.
  661. *
  662. * If the creation was a success, an id must be returned that can be used to reference
  663. * this calendar in other methods, such as updateCalendar.
  664. *
  665. * @param string $principalUri
  666. * @param string $calendarUri
  667. * @param array $properties
  668. * @return int
  669. *
  670. * @throws CalendarException
  671. */
  672. public function createCalendar($principalUri, $calendarUri, array $properties) {
  673. if (strlen($calendarUri) > 255) {
  674. throw new CalendarException('URI too long. Calendar not created');
  675. }
  676. $values = [
  677. 'principaluri' => $this->convertPrincipal($principalUri, true),
  678. 'uri' => $calendarUri,
  679. 'synctoken' => 1,
  680. 'transparent' => 0,
  681. 'components' => 'VEVENT,VTODO,VJOURNAL',
  682. 'displayname' => $calendarUri
  683. ];
  684. // Default value
  685. $sccs = '{urn:ietf:params:xml:ns:caldav}supported-calendar-component-set';
  686. if (isset($properties[$sccs])) {
  687. if (!($properties[$sccs] instanceof SupportedCalendarComponentSet)) {
  688. throw new DAV\Exception('The ' . $sccs . ' property must be of type: \Sabre\CalDAV\Property\SupportedCalendarComponentSet');
  689. }
  690. $values['components'] = implode(',', $properties[$sccs]->getValue());
  691. } elseif (isset($properties['components'])) {
  692. // Allow to provide components internally without having
  693. // to create a SupportedCalendarComponentSet object
  694. $values['components'] = $properties['components'];
  695. }
  696. $transp = '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp';
  697. if (isset($properties[$transp])) {
  698. $values['transparent'] = (int) ($properties[$transp]->getValue() === 'transparent');
  699. }
  700. foreach ($this->propertyMap as $xmlName => [$dbName, $type]) {
  701. if (isset($properties[$xmlName])) {
  702. $values[$dbName] = $properties[$xmlName];
  703. }
  704. }
  705. [$calendarId, $calendarData] = $this->atomic(function () use ($values) {
  706. $query = $this->db->getQueryBuilder();
  707. $query->insert('calendars');
  708. foreach ($values as $column => $value) {
  709. $query->setValue($column, $query->createNamedParameter($value));
  710. }
  711. $query->executeStatement();
  712. $calendarId = $query->getLastInsertId();
  713. $calendarData = $this->getCalendarById($calendarId);
  714. return [$calendarId, $calendarData];
  715. }, $this->db);
  716. $this->dispatcher->dispatchTyped(new CalendarCreatedEvent((int)$calendarId, $calendarData));
  717. return $calendarId;
  718. }
  719. /**
  720. * Updates properties for a calendar.
  721. *
  722. * The list of mutations is stored in a Sabre\DAV\PropPatch object.
  723. * To do the actual updates, you must tell this object which properties
  724. * you're going to process with the handle() method.
  725. *
  726. * Calling the handle method is like telling the PropPatch object "I
  727. * promise I can handle updating this property".
  728. *
  729. * Read the PropPatch documentation for more info and examples.
  730. *
  731. * @param mixed $calendarId
  732. * @param PropPatch $propPatch
  733. * @return void
  734. */
  735. public function updateCalendar($calendarId, PropPatch $propPatch) {
  736. $supportedProperties = array_keys($this->propertyMap);
  737. $supportedProperties[] = '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp';
  738. $propPatch->handle($supportedProperties, function ($mutations) use ($calendarId) {
  739. $newValues = [];
  740. foreach ($mutations as $propertyName => $propertyValue) {
  741. switch ($propertyName) {
  742. case '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp':
  743. $fieldName = 'transparent';
  744. $newValues[$fieldName] = (int) ($propertyValue->getValue() === 'transparent');
  745. break;
  746. default:
  747. $fieldName = $this->propertyMap[$propertyName][0];
  748. $newValues[$fieldName] = $propertyValue;
  749. break;
  750. }
  751. }
  752. [$calendarData, $shares] = $this->atomic(function () use ($calendarId, $newValues) {
  753. $query = $this->db->getQueryBuilder();
  754. $query->update('calendars');
  755. foreach ($newValues as $fieldName => $value) {
  756. $query->set($fieldName, $query->createNamedParameter($value));
  757. }
  758. $query->where($query->expr()->eq('id', $query->createNamedParameter($calendarId)));
  759. $query->executeStatement();
  760. $this->addChanges($calendarId, [""], 2);
  761. $calendarData = $this->getCalendarById($calendarId);
  762. $shares = $this->getShares($calendarId);
  763. return [$calendarData, $shares];
  764. }, $this->db);
  765. $this->dispatcher->dispatchTyped(new CalendarUpdatedEvent($calendarId, $calendarData, $shares, $mutations));
  766. return true;
  767. });
  768. }
  769. /**
  770. * Delete a calendar and all it's objects
  771. *
  772. * @param mixed $calendarId
  773. * @return void
  774. */
  775. public function deleteCalendar($calendarId, bool $forceDeletePermanently = false) {
  776. $this->atomic(function () use ($calendarId, $forceDeletePermanently) {
  777. // The calendar is deleted right away if this is either enforced by the caller
  778. // or the special contacts birthday calendar or when the preference of an empty
  779. // retention (0 seconds) is set, which signals a disabled trashbin.
  780. $calendarData = $this->getCalendarById($calendarId);
  781. $isBirthdayCalendar = isset($calendarData['uri']) && $calendarData['uri'] === BirthdayService::BIRTHDAY_CALENDAR_URI;
  782. $trashbinDisabled = $this->config->getAppValue(Application::APP_ID, RetentionService::RETENTION_CONFIG_KEY) === '0';
  783. if ($forceDeletePermanently || $isBirthdayCalendar || $trashbinDisabled) {
  784. $calendarData = $this->getCalendarById($calendarId);
  785. $shares = $this->getShares($calendarId);
  786. $qbDeleteCalendarObjectProps = $this->db->getQueryBuilder();
  787. $qbDeleteCalendarObjectProps->delete($this->dbObjectPropertiesTable)
  788. ->where($qbDeleteCalendarObjectProps->expr()->eq('calendarid', $qbDeleteCalendarObjectProps->createNamedParameter($calendarId)))
  789. ->andWhere($qbDeleteCalendarObjectProps->expr()->eq('calendartype', $qbDeleteCalendarObjectProps->createNamedParameter(self::CALENDAR_TYPE_CALENDAR)))
  790. ->executeStatement();
  791. $qbDeleteCalendarObjects = $this->db->getQueryBuilder();
  792. $qbDeleteCalendarObjects->delete('calendarobjects')
  793. ->where($qbDeleteCalendarObjects->expr()->eq('calendarid', $qbDeleteCalendarObjects->createNamedParameter($calendarId)))
  794. ->andWhere($qbDeleteCalendarObjects->expr()->eq('calendartype', $qbDeleteCalendarObjects->createNamedParameter(self::CALENDAR_TYPE_CALENDAR)))
  795. ->executeStatement();
  796. $qbDeleteCalendarChanges = $this->db->getQueryBuilder();
  797. $qbDeleteCalendarChanges->delete('calendarchanges')
  798. ->where($qbDeleteCalendarChanges->expr()->eq('calendarid', $qbDeleteCalendarChanges->createNamedParameter($calendarId)))
  799. ->andWhere($qbDeleteCalendarChanges->expr()->eq('calendartype', $qbDeleteCalendarChanges->createNamedParameter(self::CALENDAR_TYPE_CALENDAR)))
  800. ->executeStatement();
  801. $this->calendarSharingBackend->deleteAllShares($calendarId);
  802. $qbDeleteCalendar = $this->db->getQueryBuilder();
  803. $qbDeleteCalendar->delete('calendars')
  804. ->where($qbDeleteCalendar->expr()->eq('id', $qbDeleteCalendar->createNamedParameter($calendarId)))
  805. ->executeStatement();
  806. // Only dispatch if we actually deleted anything
  807. if ($calendarData) {
  808. $this->dispatcher->dispatchTyped(new CalendarDeletedEvent($calendarId, $calendarData, $shares));
  809. }
  810. } else {
  811. $qbMarkCalendarDeleted = $this->db->getQueryBuilder();
  812. $qbMarkCalendarDeleted->update('calendars')
  813. ->set('deleted_at', $qbMarkCalendarDeleted->createNamedParameter(time()))
  814. ->where($qbMarkCalendarDeleted->expr()->eq('id', $qbMarkCalendarDeleted->createNamedParameter($calendarId)))
  815. ->executeStatement();
  816. $calendarData = $this->getCalendarById($calendarId);
  817. $shares = $this->getShares($calendarId);
  818. if ($calendarData) {
  819. $this->dispatcher->dispatchTyped(new CalendarMovedToTrashEvent(
  820. $calendarId,
  821. $calendarData,
  822. $shares
  823. ));
  824. }
  825. }
  826. }, $this->db);
  827. }
  828. public function restoreCalendar(int $id): void {
  829. $this->atomic(function () use ($id) {
  830. $qb = $this->db->getQueryBuilder();
  831. $update = $qb->update('calendars')
  832. ->set('deleted_at', $qb->createNamedParameter(null))
  833. ->where($qb->expr()->eq('id', $qb->createNamedParameter($id, IQueryBuilder::PARAM_INT), IQueryBuilder::PARAM_INT));
  834. $update->executeStatement();
  835. $calendarData = $this->getCalendarById($id);
  836. $shares = $this->getShares($id);
  837. if ($calendarData === null) {
  838. throw new RuntimeException('Calendar data that was just written can\'t be read back. Check your database configuration.');
  839. }
  840. $this->dispatcher->dispatchTyped(new CalendarRestoredEvent(
  841. $id,
  842. $calendarData,
  843. $shares
  844. ));
  845. }, $this->db);
  846. }
  847. /**
  848. * Returns all calendar objects with limited metadata for a calendar
  849. *
  850. * Every item contains an array with the following keys:
  851. * * id - the table row id
  852. * * etag - An arbitrary string
  853. * * uri - a unique key which will be used to construct the uri. This can
  854. * be any arbitrary string.
  855. * * calendardata - The iCalendar-compatible calendar data
  856. *
  857. * @param mixed $calendarId
  858. * @param int $calendarType
  859. * @return array
  860. */
  861. public function getLimitedCalendarObjects(int $calendarId, int $calendarType = self::CALENDAR_TYPE_CALENDAR):array {
  862. $query = $this->db->getQueryBuilder();
  863. $query->select(['id','uid', 'etag', 'uri', 'calendardata'])
  864. ->from('calendarobjects')
  865. ->where($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)))
  866. ->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter($calendarType)))
  867. ->andWhere($query->expr()->isNull('deleted_at'));
  868. $stmt = $query->executeQuery();
  869. $result = [];
  870. while (($row = $stmt->fetch()) !== false) {
  871. $result[$row['uid']] = [
  872. 'id' => $row['id'],
  873. 'etag' => $row['etag'],
  874. 'uri' => $row['uri'],
  875. 'calendardata' => $row['calendardata'],
  876. ];
  877. }
  878. $stmt->closeCursor();
  879. return $result;
  880. }
  881. /**
  882. * Delete all of an user's shares
  883. *
  884. * @param string $principaluri
  885. * @return void
  886. */
  887. public function deleteAllSharesByUser($principaluri) {
  888. $this->calendarSharingBackend->deleteAllSharesByUser($principaluri);
  889. }
  890. /**
  891. * Returns all calendar objects within a calendar.
  892. *
  893. * Every item contains an array with the following keys:
  894. * * calendardata - The iCalendar-compatible calendar data
  895. * * uri - a unique key which will be used to construct the uri. This can
  896. * be any arbitrary string, but making sure it ends with '.ics' is a
  897. * good idea. This is only the basename, or filename, not the full
  898. * path.
  899. * * lastmodified - a timestamp of the last modification time
  900. * * etag - An arbitrary string, surrounded by double-quotes. (e.g.:
  901. * '"abcdef"')
  902. * * size - The size of the calendar objects, in bytes.
  903. * * component - optional, a string containing the type of object, such
  904. * as 'vevent' or 'vtodo'. If specified, this will be used to populate
  905. * the Content-Type header.
  906. *
  907. * Note that the etag is optional, but it's highly encouraged to return for
  908. * speed reasons.
  909. *
  910. * The calendardata is also optional. If it's not returned
  911. * 'getCalendarObject' will be called later, which *is* expected to return
  912. * calendardata.
  913. *
  914. * If neither etag or size are specified, the calendardata will be
  915. * used/fetched to determine these numbers. If both are specified the
  916. * amount of times this is needed is reduced by a great degree.
  917. *
  918. * @param mixed $calendarId
  919. * @param int $calendarType
  920. * @return array
  921. */
  922. public function getCalendarObjects($calendarId, $calendarType = self::CALENDAR_TYPE_CALENDAR):array {
  923. $query = $this->db->getQueryBuilder();
  924. $query->select(['id', 'uri', 'lastmodified', 'etag', 'calendarid', 'size', 'componenttype', 'classification'])
  925. ->from('calendarobjects')
  926. ->where($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)))
  927. ->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter($calendarType)))
  928. ->andWhere($query->expr()->isNull('deleted_at'));
  929. $stmt = $query->executeQuery();
  930. $result = [];
  931. while (($row = $stmt->fetch()) !== false) {
  932. $result[] = [
  933. 'id' => $row['id'],
  934. 'uri' => $row['uri'],
  935. 'lastmodified' => $row['lastmodified'],
  936. 'etag' => '"' . $row['etag'] . '"',
  937. 'calendarid' => $row['calendarid'],
  938. 'size' => (int)$row['size'],
  939. 'component' => strtolower($row['componenttype']),
  940. 'classification' => (int)$row['classification']
  941. ];
  942. }
  943. $stmt->closeCursor();
  944. return $result;
  945. }
  946. public function getDeletedCalendarObjects(int $deletedBefore): array {
  947. $query = $this->db->getQueryBuilder();
  948. $query->select(['co.id', 'co.uri', 'co.lastmodified', 'co.etag', 'co.calendarid', 'co.calendartype', 'co.size', 'co.componenttype', 'co.classification', 'co.deleted_at'])
  949. ->from('calendarobjects', 'co')
  950. ->join('co', 'calendars', 'c', $query->expr()->eq('c.id', 'co.calendarid', IQueryBuilder::PARAM_INT))
  951. ->where($query->expr()->isNotNull('co.deleted_at'))
  952. ->andWhere($query->expr()->lt('co.deleted_at', $query->createNamedParameter($deletedBefore)));
  953. $stmt = $query->executeQuery();
  954. $result = [];
  955. while (($row = $stmt->fetch()) !== false) {
  956. $result[] = [
  957. 'id' => $row['id'],
  958. 'uri' => $row['uri'],
  959. 'lastmodified' => $row['lastmodified'],
  960. 'etag' => '"' . $row['etag'] . '"',
  961. 'calendarid' => (int) $row['calendarid'],
  962. 'calendartype' => (int) $row['calendartype'],
  963. 'size' => (int) $row['size'],
  964. 'component' => strtolower($row['componenttype']),
  965. 'classification' => (int) $row['classification'],
  966. '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_NEXTCLOUD . '}deleted-at' => $row['deleted_at'] === null ? $row['deleted_at'] : (int) $row['deleted_at'],
  967. ];
  968. }
  969. $stmt->closeCursor();
  970. return $result;
  971. }
  972. /**
  973. * Return all deleted calendar objects by the given principal that are not
  974. * in deleted calendars.
  975. *
  976. * @param string $principalUri
  977. * @return array
  978. * @throws Exception
  979. */
  980. public function getDeletedCalendarObjectsByPrincipal(string $principalUri): array {
  981. $query = $this->db->getQueryBuilder();
  982. $query->select(['co.id', 'co.uri', 'co.lastmodified', 'co.etag', 'co.calendarid', 'co.size', 'co.componenttype', 'co.classification', 'co.deleted_at'])
  983. ->selectAlias('c.uri', 'calendaruri')
  984. ->from('calendarobjects', 'co')
  985. ->join('co', 'calendars', 'c', $query->expr()->eq('c.id', 'co.calendarid', IQueryBuilder::PARAM_INT))
  986. ->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
  987. ->andWhere($query->expr()->isNotNull('co.deleted_at'))
  988. ->andWhere($query->expr()->isNull('c.deleted_at'));
  989. $stmt = $query->executeQuery();
  990. $result = [];
  991. while ($row = $stmt->fetch()) {
  992. $result[] = [
  993. 'id' => $row['id'],
  994. 'uri' => $row['uri'],
  995. 'lastmodified' => $row['lastmodified'],
  996. 'etag' => '"' . $row['etag'] . '"',
  997. 'calendarid' => $row['calendarid'],
  998. 'calendaruri' => $row['calendaruri'],
  999. 'size' => (int)$row['size'],
  1000. 'component' => strtolower($row['componenttype']),
  1001. 'classification' => (int)$row['classification'],
  1002. '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_NEXTCLOUD . '}deleted-at' => $row['deleted_at'] === null ? $row['deleted_at'] : (int) $row['deleted_at'],
  1003. ];
  1004. }
  1005. $stmt->closeCursor();
  1006. return $result;
  1007. }
  1008. /**
  1009. * Returns information from a single calendar object, based on it's object
  1010. * uri.
  1011. *
  1012. * The object uri is only the basename, or filename and not a full path.
  1013. *
  1014. * The returned array must have the same keys as getCalendarObjects. The
  1015. * 'calendardata' object is required here though, while it's not required
  1016. * for getCalendarObjects.
  1017. *
  1018. * This method must return null if the object did not exist.
  1019. *
  1020. * @param mixed $calendarId
  1021. * @param string $objectUri
  1022. * @param int $calendarType
  1023. * @return array|null
  1024. */
  1025. public function getCalendarObject($calendarId, $objectUri, int $calendarType = self::CALENDAR_TYPE_CALENDAR) {
  1026. $key = $calendarId . '::' . $objectUri . '::' . $calendarType;
  1027. if (isset($this->cachedObjects[$key])) {
  1028. return $this->cachedObjects[$key];
  1029. }
  1030. $query = $this->db->getQueryBuilder();
  1031. $query->select(['id', 'uri', 'lastmodified', 'etag', 'calendarid', 'size', 'calendardata', 'componenttype', 'classification', 'deleted_at'])
  1032. ->from('calendarobjects')
  1033. ->where($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)))
  1034. ->andWhere($query->expr()->eq('uri', $query->createNamedParameter($objectUri)))
  1035. ->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter($calendarType)));
  1036. $stmt = $query->executeQuery();
  1037. $row = $stmt->fetch();
  1038. $stmt->closeCursor();
  1039. if (!$row) {
  1040. return null;
  1041. }
  1042. $object = $this->rowToCalendarObject($row);
  1043. $this->cachedObjects[$key] = $object;
  1044. return $object;
  1045. }
  1046. private function rowToCalendarObject(array $row): array {
  1047. return [
  1048. 'id' => $row['id'],
  1049. 'uri' => $row['uri'],
  1050. 'lastmodified' => $row['lastmodified'],
  1051. 'etag' => '"' . $row['etag'] . '"',
  1052. 'calendarid' => $row['calendarid'],
  1053. 'size' => (int)$row['size'],
  1054. 'calendardata' => $this->readBlob($row['calendardata']),
  1055. 'component' => strtolower($row['componenttype']),
  1056. 'classification' => (int)$row['classification'],
  1057. '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_NEXTCLOUD . '}deleted-at' => $row['deleted_at'] === null ? $row['deleted_at'] : (int) $row['deleted_at'],
  1058. ];
  1059. }
  1060. /**
  1061. * Returns a list of calendar objects.
  1062. *
  1063. * This method should work identical to getCalendarObject, but instead
  1064. * return all the calendar objects in the list as an array.
  1065. *
  1066. * If the backend supports this, it may allow for some speed-ups.
  1067. *
  1068. * @param mixed $calendarId
  1069. * @param string[] $uris
  1070. * @param int $calendarType
  1071. * @return array
  1072. */
  1073. public function getMultipleCalendarObjects($calendarId, array $uris, $calendarType = self::CALENDAR_TYPE_CALENDAR):array {
  1074. if (empty($uris)) {
  1075. return [];
  1076. }
  1077. $chunks = array_chunk($uris, 100);
  1078. $objects = [];
  1079. $query = $this->db->getQueryBuilder();
  1080. $query->select(['id', 'uri', 'lastmodified', 'etag', 'calendarid', 'size', 'calendardata', 'componenttype', 'classification'])
  1081. ->from('calendarobjects')
  1082. ->where($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)))
  1083. ->andWhere($query->expr()->in('uri', $query->createParameter('uri')))
  1084. ->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter($calendarType)))
  1085. ->andWhere($query->expr()->isNull('deleted_at'));
  1086. foreach ($chunks as $uris) {
  1087. $query->setParameter('uri', $uris, IQueryBuilder::PARAM_STR_ARRAY);
  1088. $result = $query->executeQuery();
  1089. while ($row = $result->fetch()) {
  1090. $objects[] = [
  1091. 'id' => $row['id'],
  1092. 'uri' => $row['uri'],
  1093. 'lastmodified' => $row['lastmodified'],
  1094. 'etag' => '"' . $row['etag'] . '"',
  1095. 'calendarid' => $row['calendarid'],
  1096. 'size' => (int)$row['size'],
  1097. 'calendardata' => $this->readBlob($row['calendardata']),
  1098. 'component' => strtolower($row['componenttype']),
  1099. 'classification' => (int)$row['classification']
  1100. ];
  1101. }
  1102. $result->closeCursor();
  1103. }
  1104. return $objects;
  1105. }
  1106. /**
  1107. * Creates a new calendar object.
  1108. *
  1109. * The object uri is only the basename, or filename and not a full path.
  1110. *
  1111. * It is possible return an etag from this function, which will be used in
  1112. * the response to this PUT request. Note that the ETag must be surrounded
  1113. * by double-quotes.
  1114. *
  1115. * However, you should only really return this ETag if you don't mangle the
  1116. * calendar-data. If the result of a subsequent GET to this object is not
  1117. * the exact same as this request body, you should omit the ETag.
  1118. *
  1119. * @param mixed $calendarId
  1120. * @param string $objectUri
  1121. * @param string $calendarData
  1122. * @param int $calendarType
  1123. * @return string
  1124. */
  1125. public function createCalendarObject($calendarId, $objectUri, $calendarData, $calendarType = self::CALENDAR_TYPE_CALENDAR) {
  1126. $this->cachedObjects = [];
  1127. $extraData = $this->getDenormalizedData($calendarData);
  1128. return $this->atomic(function () use ($calendarId, $objectUri, $calendarData, $extraData, $calendarType) {
  1129. // Try to detect duplicates
  1130. $qb = $this->db->getQueryBuilder();
  1131. $qb->select($qb->func()->count('*'))
  1132. ->from('calendarobjects')
  1133. ->where($qb->expr()->eq('calendarid', $qb->createNamedParameter($calendarId)))
  1134. ->andWhere($qb->expr()->eq('uid', $qb->createNamedParameter($extraData['uid'])))
  1135. ->andWhere($qb->expr()->eq('calendartype', $qb->createNamedParameter($calendarType)))
  1136. ->andWhere($qb->expr()->isNull('deleted_at'));
  1137. $result = $qb->executeQuery();
  1138. $count = (int) $result->fetchOne();
  1139. $result->closeCursor();
  1140. if ($count !== 0) {
  1141. throw new BadRequest('Calendar object with uid already exists in this calendar collection.');
  1142. }
  1143. // For a more specific error message we also try to explicitly look up the UID but as a deleted entry
  1144. $qbDel = $this->db->getQueryBuilder();
  1145. $qbDel->select('*')
  1146. ->from('calendarobjects')
  1147. ->where($qbDel->expr()->eq('calendarid', $qbDel->createNamedParameter($calendarId)))
  1148. ->andWhere($qbDel->expr()->eq('uid', $qbDel->createNamedParameter($extraData['uid'])))
  1149. ->andWhere($qbDel->expr()->eq('calendartype', $qbDel->createNamedParameter($calendarType)))
  1150. ->andWhere($qbDel->expr()->isNotNull('deleted_at'));
  1151. $result = $qbDel->executeQuery();
  1152. $found = $result->fetch();
  1153. $result->closeCursor();
  1154. if ($found !== false) {
  1155. // the object existed previously but has been deleted
  1156. // remove the trashbin entry and continue as if it was a new object
  1157. $this->deleteCalendarObject($calendarId, $found['uri']);
  1158. }
  1159. $query = $this->db->getQueryBuilder();
  1160. $query->insert('calendarobjects')
  1161. ->values([
  1162. 'calendarid' => $query->createNamedParameter($calendarId),
  1163. 'uri' => $query->createNamedParameter($objectUri),
  1164. 'calendardata' => $query->createNamedParameter($calendarData, IQueryBuilder::PARAM_LOB),
  1165. 'lastmodified' => $query->createNamedParameter(time()),
  1166. 'etag' => $query->createNamedParameter($extraData['etag']),
  1167. 'size' => $query->createNamedParameter($extraData['size']),
  1168. 'componenttype' => $query->createNamedParameter($extraData['componentType']),
  1169. 'firstoccurence' => $query->createNamedParameter($extraData['firstOccurence']),
  1170. 'lastoccurence' => $query->createNamedParameter($extraData['lastOccurence']),
  1171. 'classification' => $query->createNamedParameter($extraData['classification']),
  1172. 'uid' => $query->createNamedParameter($extraData['uid']),
  1173. 'calendartype' => $query->createNamedParameter($calendarType),
  1174. ])
  1175. ->executeStatement();
  1176. $this->updateProperties($calendarId, $objectUri, $calendarData, $calendarType);
  1177. $this->addChanges($calendarId, [$objectUri], 1, $calendarType);
  1178. $objectRow = $this->getCalendarObject($calendarId, $objectUri, $calendarType);
  1179. assert($objectRow !== null);
  1180. if ($calendarType === self::CALENDAR_TYPE_CALENDAR) {
  1181. $calendarRow = $this->getCalendarById($calendarId);
  1182. $shares = $this->getShares($calendarId);
  1183. $this->dispatcher->dispatchTyped(new CalendarObjectCreatedEvent($calendarId, $calendarRow, $shares, $objectRow));
  1184. } else {
  1185. $subscriptionRow = $this->getSubscriptionById($calendarId);
  1186. $this->dispatcher->dispatchTyped(new CachedCalendarObjectCreatedEvent($calendarId, $subscriptionRow, [], $objectRow));
  1187. }
  1188. return '"' . $extraData['etag'] . '"';
  1189. }, $this->db);
  1190. }
  1191. /**
  1192. * Updates an existing calendarobject, based on it's uri.
  1193. *
  1194. * The object uri is only the basename, or filename and not a full path.
  1195. *
  1196. * It is possible return an etag from this function, which will be used in
  1197. * the response to this PUT request. Note that the ETag must be surrounded
  1198. * by double-quotes.
  1199. *
  1200. * However, you should only really return this ETag if you don't mangle the
  1201. * calendar-data. If the result of a subsequent GET to this object is not
  1202. * the exact same as this request body, you should omit the ETag.
  1203. *
  1204. * @param mixed $calendarId
  1205. * @param string $objectUri
  1206. * @param string $calendarData
  1207. * @param int $calendarType
  1208. * @return string
  1209. */
  1210. public function updateCalendarObject($calendarId, $objectUri, $calendarData, $calendarType = self::CALENDAR_TYPE_CALENDAR) {
  1211. $this->cachedObjects = [];
  1212. $extraData = $this->getDenormalizedData($calendarData);
  1213. return $this->atomic(function () use ($calendarId, $objectUri, $calendarData, $extraData, $calendarType) {
  1214. $query = $this->db->getQueryBuilder();
  1215. $query->update('calendarobjects')
  1216. ->set('calendardata', $query->createNamedParameter($calendarData, IQueryBuilder::PARAM_LOB))
  1217. ->set('lastmodified', $query->createNamedParameter(time()))
  1218. ->set('etag', $query->createNamedParameter($extraData['etag']))
  1219. ->set('size', $query->createNamedParameter($extraData['size']))
  1220. ->set('componenttype', $query->createNamedParameter($extraData['componentType']))
  1221. ->set('firstoccurence', $query->createNamedParameter($extraData['firstOccurence']))
  1222. ->set('lastoccurence', $query->createNamedParameter($extraData['lastOccurence']))
  1223. ->set('classification', $query->createNamedParameter($extraData['classification']))
  1224. ->set('uid', $query->createNamedParameter($extraData['uid']))
  1225. ->where($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)))
  1226. ->andWhere($query->expr()->eq('uri', $query->createNamedParameter($objectUri)))
  1227. ->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter($calendarType)))
  1228. ->executeStatement();
  1229. $this->updateProperties($calendarId, $objectUri, $calendarData, $calendarType);
  1230. $this->addChanges($calendarId, [$objectUri], 2, $calendarType);
  1231. $objectRow = $this->getCalendarObject($calendarId, $objectUri, $calendarType);
  1232. if (is_array($objectRow)) {
  1233. if ($calendarType === self::CALENDAR_TYPE_CALENDAR) {
  1234. $calendarRow = $this->getCalendarById($calendarId);
  1235. $shares = $this->getShares($calendarId);
  1236. $this->dispatcher->dispatchTyped(new CalendarObjectUpdatedEvent($calendarId, $calendarRow, $shares, $objectRow));
  1237. } else {
  1238. $subscriptionRow = $this->getSubscriptionById($calendarId);
  1239. $this->dispatcher->dispatchTyped(new CachedCalendarObjectUpdatedEvent($calendarId, $subscriptionRow, [], $objectRow));
  1240. }
  1241. }
  1242. return '"' . $extraData['etag'] . '"';
  1243. }, $this->db);
  1244. }
  1245. /**
  1246. * Moves a calendar object from calendar to calendar.
  1247. *
  1248. * @param int $sourceCalendarId
  1249. * @param int $targetCalendarId
  1250. * @param int $objectId
  1251. * @param string $oldPrincipalUri
  1252. * @param string $newPrincipalUri
  1253. * @param int $calendarType
  1254. * @return bool
  1255. * @throws Exception
  1256. */
  1257. public function moveCalendarObject(int $sourceCalendarId, int $targetCalendarId, int $objectId, string $oldPrincipalUri, string $newPrincipalUri, int $calendarType = self::CALENDAR_TYPE_CALENDAR): bool {
  1258. $this->cachedObjects = [];
  1259. return $this->atomic(function () use ($sourceCalendarId, $targetCalendarId, $objectId, $oldPrincipalUri, $newPrincipalUri, $calendarType) {
  1260. $object = $this->getCalendarObjectById($oldPrincipalUri, $objectId);
  1261. if (empty($object)) {
  1262. return false;
  1263. }
  1264. $query = $this->db->getQueryBuilder();
  1265. $query->update('calendarobjects')
  1266. ->set('calendarid', $query->createNamedParameter($targetCalendarId, IQueryBuilder::PARAM_INT))
  1267. ->where($query->expr()->eq('id', $query->createNamedParameter($objectId, IQueryBuilder::PARAM_INT), IQueryBuilder::PARAM_INT))
  1268. ->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter($calendarType, IQueryBuilder::PARAM_INT), IQueryBuilder::PARAM_INT))
  1269. ->executeStatement();
  1270. $this->purgeProperties($sourceCalendarId, $objectId);
  1271. $this->updateProperties($targetCalendarId, $object['uri'], $object['calendardata'], $calendarType);
  1272. $this->addChanges($sourceCalendarId, [$object['uri']], 3, $calendarType);
  1273. $this->addChanges($targetCalendarId, [$object['uri']], 1, $calendarType);
  1274. $object = $this->getCalendarObjectById($newPrincipalUri, $objectId);
  1275. // Calendar Object wasn't found - possibly because it was deleted in the meantime by a different client
  1276. if (empty($object)) {
  1277. return false;
  1278. }
  1279. $targetCalendarRow = $this->getCalendarById($targetCalendarId);
  1280. // the calendar this event is being moved to does not exist any longer
  1281. if (empty($targetCalendarRow)) {
  1282. return false;
  1283. }
  1284. if ($calendarType === self::CALENDAR_TYPE_CALENDAR) {
  1285. $sourceShares = $this->getShares($sourceCalendarId);
  1286. $targetShares = $this->getShares($targetCalendarId);
  1287. $sourceCalendarRow = $this->getCalendarById($sourceCalendarId);
  1288. $this->dispatcher->dispatchTyped(new CalendarObjectMovedEvent($sourceCalendarId, $sourceCalendarRow, $targetCalendarId, $targetCalendarRow, $sourceShares, $targetShares, $object));
  1289. }
  1290. return true;
  1291. }, $this->db);
  1292. }
  1293. /**
  1294. * @param int $calendarObjectId
  1295. * @param int $classification
  1296. */
  1297. public function setClassification($calendarObjectId, $classification) {
  1298. $this->cachedObjects = [];
  1299. if (!in_array($classification, [
  1300. self::CLASSIFICATION_PUBLIC, self::CLASSIFICATION_PRIVATE, self::CLASSIFICATION_CONFIDENTIAL
  1301. ])) {
  1302. throw new \InvalidArgumentException();
  1303. }
  1304. $query = $this->db->getQueryBuilder();
  1305. $query->update('calendarobjects')
  1306. ->set('classification', $query->createNamedParameter($classification))
  1307. ->where($query->expr()->eq('id', $query->createNamedParameter($calendarObjectId)))
  1308. ->executeStatement();
  1309. }
  1310. /**
  1311. * Deletes an existing calendar object.
  1312. *
  1313. * The object uri is only the basename, or filename and not a full path.
  1314. *
  1315. * @param mixed $calendarId
  1316. * @param string $objectUri
  1317. * @param int $calendarType
  1318. * @param bool $forceDeletePermanently
  1319. * @return void
  1320. */
  1321. public function deleteCalendarObject($calendarId, $objectUri, $calendarType = self::CALENDAR_TYPE_CALENDAR, bool $forceDeletePermanently = false) {
  1322. $this->cachedObjects = [];
  1323. $this->atomic(function () use ($calendarId, $objectUri, $calendarType, $forceDeletePermanently) {
  1324. $data = $this->getCalendarObject($calendarId, $objectUri, $calendarType);
  1325. if ($data === null) {
  1326. // Nothing to delete
  1327. return;
  1328. }
  1329. if ($forceDeletePermanently || $this->config->getAppValue(Application::APP_ID, RetentionService::RETENTION_CONFIG_KEY) === '0') {
  1330. $stmt = $this->db->prepare('DELETE FROM `*PREFIX*calendarobjects` WHERE `calendarid` = ? AND `uri` = ? AND `calendartype` = ?');
  1331. $stmt->execute([$calendarId, $objectUri, $calendarType]);
  1332. $this->purgeProperties($calendarId, $data['id']);
  1333. if ($calendarType === self::CALENDAR_TYPE_CALENDAR) {
  1334. $calendarRow = $this->getCalendarById($calendarId);
  1335. $shares = $this->getShares($calendarId);
  1336. $this->dispatcher->dispatchTyped(new CalendarObjectDeletedEvent($calendarId, $calendarRow, $shares, $data));
  1337. } else {
  1338. $subscriptionRow = $this->getSubscriptionById($calendarId);
  1339. $this->dispatcher->dispatchTyped(new CachedCalendarObjectDeletedEvent($calendarId, $subscriptionRow, [], $data));
  1340. }
  1341. } else {
  1342. $pathInfo = pathinfo($data['uri']);
  1343. if (!empty($pathInfo['extension'])) {
  1344. // Append a suffix to "free" the old URI for recreation
  1345. $newUri = sprintf(
  1346. "%s-deleted.%s",
  1347. $pathInfo['filename'],
  1348. $pathInfo['extension']
  1349. );
  1350. } else {
  1351. $newUri = sprintf(
  1352. "%s-deleted",
  1353. $pathInfo['filename']
  1354. );
  1355. }
  1356. // Try to detect conflicts before the DB does
  1357. // As unlikely as it seems, this can happen when the user imports, then deletes, imports and deletes again
  1358. $newObject = $this->getCalendarObject($calendarId, $newUri, $calendarType);
  1359. if ($newObject !== null) {
  1360. throw new Forbidden("A calendar object with URI $newUri already exists in calendar $calendarId, therefore this object can't be moved into the trashbin");
  1361. }
  1362. $qb = $this->db->getQueryBuilder();
  1363. $markObjectDeletedQuery = $qb->update('calendarobjects')
  1364. ->set('deleted_at', $qb->createNamedParameter(time(), IQueryBuilder::PARAM_INT))
  1365. ->set('uri', $qb->createNamedParameter($newUri))
  1366. ->where(
  1367. $qb->expr()->eq('calendarid', $qb->createNamedParameter($calendarId)),
  1368. $qb->expr()->eq('calendartype', $qb->createNamedParameter($calendarType, IQueryBuilder::PARAM_INT), IQueryBuilder::PARAM_INT),
  1369. $qb->expr()->eq('uri', $qb->createNamedParameter($objectUri))
  1370. );
  1371. $markObjectDeletedQuery->executeStatement();
  1372. $calendarData = $this->getCalendarById($calendarId);
  1373. if ($calendarData !== null) {
  1374. $this->dispatcher->dispatchTyped(
  1375. new CalendarObjectMovedToTrashEvent(
  1376. $calendarId,
  1377. $calendarData,
  1378. $this->getShares($calendarId),
  1379. $data
  1380. )
  1381. );
  1382. }
  1383. }
  1384. $this->addChanges($calendarId, [$objectUri], 3, $calendarType);
  1385. }, $this->db);
  1386. }
  1387. /**
  1388. * @param mixed $objectData
  1389. *
  1390. * @throws Forbidden
  1391. */
  1392. public function restoreCalendarObject(array $objectData): void {
  1393. $this->cachedObjects = [];
  1394. $this->atomic(function () use ($objectData) {
  1395. $id = (int) $objectData['id'];
  1396. $restoreUri = str_replace("-deleted.ics", ".ics", $objectData['uri']);
  1397. $targetObject = $this->getCalendarObject(
  1398. $objectData['calendarid'],
  1399. $restoreUri
  1400. );
  1401. if ($targetObject !== null) {
  1402. throw new Forbidden("Can not restore calendar $id because a calendar object with the URI $restoreUri already exists");
  1403. }
  1404. $qb = $this->db->getQueryBuilder();
  1405. $update = $qb->update('calendarobjects')
  1406. ->set('uri', $qb->createNamedParameter($restoreUri))
  1407. ->set('deleted_at', $qb->createNamedParameter(null))
  1408. ->where($qb->expr()->eq('id', $qb->createNamedParameter($id, IQueryBuilder::PARAM_INT), IQueryBuilder::PARAM_INT));
  1409. $update->executeStatement();
  1410. // Make sure this change is tracked in the changes table
  1411. $qb2 = $this->db->getQueryBuilder();
  1412. $selectObject = $qb2->select('calendardata', 'uri', 'calendarid', 'calendartype')
  1413. ->selectAlias('componenttype', 'component')
  1414. ->from('calendarobjects')
  1415. ->where($qb2->expr()->eq('id', $qb2->createNamedParameter($id, IQueryBuilder::PARAM_INT), IQueryBuilder::PARAM_INT));
  1416. $result = $selectObject->executeQuery();
  1417. $row = $result->fetch();
  1418. $result->closeCursor();
  1419. if ($row === false) {
  1420. // Welp, this should possibly not have happened, but let's ignore
  1421. return;
  1422. }
  1423. $this->addChanges($row['calendarid'], [$row['uri']], 1, (int) $row['calendartype']);
  1424. $calendarRow = $this->getCalendarById((int) $row['calendarid']);
  1425. if ($calendarRow === null) {
  1426. throw new RuntimeException('Calendar object data that was just written can\'t be read back. Check your database configuration.');
  1427. }
  1428. $this->dispatcher->dispatchTyped(
  1429. new CalendarObjectRestoredEvent(
  1430. (int) $objectData['calendarid'],
  1431. $calendarRow,
  1432. $this->getShares((int) $row['calendarid']),
  1433. $row
  1434. )
  1435. );
  1436. }, $this->db);
  1437. }
  1438. /**
  1439. * Performs a calendar-query on the contents of this calendar.
  1440. *
  1441. * The calendar-query is defined in RFC4791 : CalDAV. Using the
  1442. * calendar-query it is possible for a client to request a specific set of
  1443. * object, based on contents of iCalendar properties, date-ranges and
  1444. * iCalendar component types (VTODO, VEVENT).
  1445. *
  1446. * This method should just return a list of (relative) urls that match this
  1447. * query.
  1448. *
  1449. * The list of filters are specified as an array. The exact array is
  1450. * documented by Sabre\CalDAV\CalendarQueryParser.
  1451. *
  1452. * Note that it is extremely likely that getCalendarObject for every path
  1453. * returned from this method will be called almost immediately after. You
  1454. * may want to anticipate this to speed up these requests.
  1455. *
  1456. * This method provides a default implementation, which parses *all* the
  1457. * iCalendar objects in the specified calendar.
  1458. *
  1459. * This default may well be good enough for personal use, and calendars
  1460. * that aren't very large. But if you anticipate high usage, big calendars
  1461. * or high loads, you are strongly advised to optimize certain paths.
  1462. *
  1463. * The best way to do so is override this method and to optimize
  1464. * specifically for 'common filters'.
  1465. *
  1466. * Requests that are extremely common are:
  1467. * * requests for just VEVENTS
  1468. * * requests for just VTODO
  1469. * * requests with a time-range-filter on either VEVENT or VTODO.
  1470. *
  1471. * ..and combinations of these requests. It may not be worth it to try to
  1472. * handle every possible situation and just rely on the (relatively
  1473. * easy to use) CalendarQueryValidator to handle the rest.
  1474. *
  1475. * Note that especially time-range-filters may be difficult to parse. A
  1476. * time-range filter specified on a VEVENT must for instance also handle
  1477. * recurrence rules correctly.
  1478. * A good example of how to interpret all these filters can also simply
  1479. * be found in Sabre\CalDAV\CalendarQueryFilter. This class is as correct
  1480. * as possible, so it gives you a good idea on what type of stuff you need
  1481. * to think of.
  1482. *
  1483. * @param mixed $calendarId
  1484. * @param array $filters
  1485. * @param int $calendarType
  1486. * @return array
  1487. */
  1488. public function calendarQuery($calendarId, array $filters, $calendarType = self::CALENDAR_TYPE_CALENDAR):array {
  1489. $componentType = null;
  1490. $requirePostFilter = true;
  1491. $timeRange = null;
  1492. // if no filters were specified, we don't need to filter after a query
  1493. if (!$filters['prop-filters'] && !$filters['comp-filters']) {
  1494. $requirePostFilter = false;
  1495. }
  1496. // Figuring out if there's a component filter
  1497. if (count($filters['comp-filters']) > 0 && !$filters['comp-filters'][0]['is-not-defined']) {
  1498. $componentType = $filters['comp-filters'][0]['name'];
  1499. // Checking if we need post-filters
  1500. if (!$filters['prop-filters'] && !$filters['comp-filters'][0]['comp-filters'] && !$filters['comp-filters'][0]['time-range'] && !$filters['comp-filters'][0]['prop-filters']) {
  1501. $requirePostFilter = false;
  1502. }
  1503. // There was a time-range filter
  1504. if ($componentType === 'VEVENT' && isset($filters['comp-filters'][0]['time-range']) && is_array($filters['comp-filters'][0]['time-range'])) {
  1505. $timeRange = $filters['comp-filters'][0]['time-range'];
  1506. // If start time OR the end time is not specified, we can do a
  1507. // 100% accurate mysql query.
  1508. if (!$filters['prop-filters'] && !$filters['comp-filters'][0]['comp-filters'] && !$filters['comp-filters'][0]['prop-filters'] && (!$timeRange['start'] || !$timeRange['end'])) {
  1509. $requirePostFilter = false;
  1510. }
  1511. }
  1512. }
  1513. $query = $this->db->getQueryBuilder();
  1514. $query->select(['id', 'uri', 'lastmodified', 'etag', 'calendarid', 'size', 'calendardata', 'componenttype', 'classification', 'deleted_at'])
  1515. ->from('calendarobjects')
  1516. ->where($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)))
  1517. ->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter($calendarType)))
  1518. ->andWhere($query->expr()->isNull('deleted_at'));
  1519. if ($componentType) {
  1520. $query->andWhere($query->expr()->eq('componenttype', $query->createNamedParameter($componentType)));
  1521. }
  1522. if ($timeRange && $timeRange['start']) {
  1523. $query->andWhere($query->expr()->gt('lastoccurence', $query->createNamedParameter($timeRange['start']->getTimeStamp())));
  1524. }
  1525. if ($timeRange && $timeRange['end']) {
  1526. $query->andWhere($query->expr()->lt('firstoccurence', $query->createNamedParameter($timeRange['end']->getTimeStamp())));
  1527. }
  1528. $stmt = $query->executeQuery();
  1529. $result = [];
  1530. while ($row = $stmt->fetch()) {
  1531. // if we leave it as a blob we can't read it both from the post filter and the rowToCalendarObject
  1532. if (isset($row['calendardata'])) {
  1533. $row['calendardata'] = $this->readBlob($row['calendardata']);
  1534. }
  1535. if ($requirePostFilter) {
  1536. // validateFilterForObject will parse the calendar data
  1537. // catch parsing errors
  1538. try {
  1539. $matches = $this->validateFilterForObject($row, $filters);
  1540. } catch (ParseException $ex) {
  1541. $this->logger->error('Caught parsing exception for calendar data. This usually indicates invalid calendar data. calendar-id:'.$calendarId.' uri:'.$row['uri'], [
  1542. 'app' => 'dav',
  1543. 'exception' => $ex,
  1544. ]);
  1545. continue;
  1546. } catch (InvalidDataException $ex) {
  1547. $this->logger->error('Caught invalid data exception for calendar data. This usually indicates invalid calendar data. calendar-id:'.$calendarId.' uri:'.$row['uri'], [
  1548. 'app' => 'dav',
  1549. 'exception' => $ex,
  1550. ]);
  1551. continue;
  1552. } catch (MaxInstancesExceededException $ex) {
  1553. $this->logger->warning('Caught max instances exceeded exception for calendar data. This usually indicates too much recurring (more than 3500) event in calendar data. Object uri: '.$row['uri'], [
  1554. 'app' => 'dav',
  1555. 'exception' => $ex,
  1556. ]);
  1557. continue;
  1558. }
  1559. if (!$matches) {
  1560. continue;
  1561. }
  1562. }
  1563. $result[] = $row['uri'];
  1564. $key = $calendarId . '::' . $row['uri'] . '::' . $calendarType;
  1565. $this->cachedObjects[$key] = $this->rowToCalendarObject($row);
  1566. }
  1567. return $result;
  1568. }
  1569. /**
  1570. * custom Nextcloud search extension for CalDAV
  1571. *
  1572. * TODO - this should optionally cover cached calendar objects as well
  1573. *
  1574. * @param string $principalUri
  1575. * @param array $filters
  1576. * @param integer|null $limit
  1577. * @param integer|null $offset
  1578. * @return array
  1579. */
  1580. public function calendarSearch($principalUri, array $filters, $limit = null, $offset = null) {
  1581. return $this->atomic(function () use ($principalUri, $filters, $limit, $offset) {
  1582. $calendars = $this->getCalendarsForUser($principalUri);
  1583. $ownCalendars = [];
  1584. $sharedCalendars = [];
  1585. $uriMapper = [];
  1586. foreach ($calendars as $calendar) {
  1587. if ($calendar['{http://owncloud.org/ns}owner-principal'] === $principalUri) {
  1588. $ownCalendars[] = $calendar['id'];
  1589. } else {
  1590. $sharedCalendars[] = $calendar['id'];
  1591. }
  1592. $uriMapper[$calendar['id']] = $calendar['uri'];
  1593. }
  1594. if (count($ownCalendars) === 0 && count($sharedCalendars) === 0) {
  1595. return [];
  1596. }
  1597. $query = $this->db->getQueryBuilder();
  1598. // Calendar id expressions
  1599. $calendarExpressions = [];
  1600. foreach ($ownCalendars as $id) {
  1601. $calendarExpressions[] = $query->expr()->andX(
  1602. $query->expr()->eq('c.calendarid',
  1603. $query->createNamedParameter($id)),
  1604. $query->expr()->eq('c.calendartype',
  1605. $query->createNamedParameter(self::CALENDAR_TYPE_CALENDAR)));
  1606. }
  1607. foreach ($sharedCalendars as $id) {
  1608. $calendarExpressions[] = $query->expr()->andX(
  1609. $query->expr()->eq('c.calendarid',
  1610. $query->createNamedParameter($id)),
  1611. $query->expr()->eq('c.classification',
  1612. $query->createNamedParameter(self::CLASSIFICATION_PUBLIC)),
  1613. $query->expr()->eq('c.calendartype',
  1614. $query->createNamedParameter(self::CALENDAR_TYPE_CALENDAR)));
  1615. }
  1616. if (count($calendarExpressions) === 1) {
  1617. $calExpr = $calendarExpressions[0];
  1618. } else {
  1619. $calExpr = call_user_func_array([$query->expr(), 'orX'], $calendarExpressions);
  1620. }
  1621. // Component expressions
  1622. $compExpressions = [];
  1623. foreach ($filters['comps'] as $comp) {
  1624. $compExpressions[] = $query->expr()
  1625. ->eq('c.componenttype', $query->createNamedParameter($comp));
  1626. }
  1627. if (count($compExpressions) === 1) {
  1628. $compExpr = $compExpressions[0];
  1629. } else {
  1630. $compExpr = call_user_func_array([$query->expr(), 'orX'], $compExpressions);
  1631. }
  1632. if (!isset($filters['props'])) {
  1633. $filters['props'] = [];
  1634. }
  1635. if (!isset($filters['params'])) {
  1636. $filters['params'] = [];
  1637. }
  1638. $propParamExpressions = [];
  1639. foreach ($filters['props'] as $prop) {
  1640. $propParamExpressions[] = $query->expr()->andX(
  1641. $query->expr()->eq('i.name', $query->createNamedParameter($prop)),
  1642. $query->expr()->isNull('i.parameter')
  1643. );
  1644. }
  1645. foreach ($filters['params'] as $param) {
  1646. $propParamExpressions[] = $query->expr()->andX(
  1647. $query->expr()->eq('i.name', $query->createNamedParameter($param['property'])),
  1648. $query->expr()->eq('i.parameter', $query->createNamedParameter($param['parameter']))
  1649. );
  1650. }
  1651. if (count($propParamExpressions) === 1) {
  1652. $propParamExpr = $propParamExpressions[0];
  1653. } else {
  1654. $propParamExpr = call_user_func_array([$query->expr(), 'orX'], $propParamExpressions);
  1655. }
  1656. $query->select(['c.calendarid', 'c.uri'])
  1657. ->from($this->dbObjectPropertiesTable, 'i')
  1658. ->join('i', 'calendarobjects', 'c', $query->expr()->eq('i.objectid', 'c.id'))
  1659. ->where($calExpr)
  1660. ->andWhere($compExpr)
  1661. ->andWhere($propParamExpr)
  1662. ->andWhere($query->expr()->iLike('i.value',
  1663. $query->createNamedParameter('%'.$this->db->escapeLikeParameter($filters['search-term']).'%')))
  1664. ->andWhere($query->expr()->isNull('deleted_at'));
  1665. if ($offset) {
  1666. $query->setFirstResult($offset);
  1667. }
  1668. if ($limit) {
  1669. $query->setMaxResults($limit);
  1670. }
  1671. $stmt = $query->executeQuery();
  1672. $result = [];
  1673. while ($row = $stmt->fetch()) {
  1674. $path = $uriMapper[$row['calendarid']] . '/' . $row['uri'];
  1675. if (!in_array($path, $result)) {
  1676. $result[] = $path;
  1677. }
  1678. }
  1679. return $result;
  1680. }, $this->db);
  1681. }
  1682. /**
  1683. * used for Nextcloud's calendar API
  1684. *
  1685. * @param array $calendarInfo
  1686. * @param string $pattern
  1687. * @param array $searchProperties
  1688. * @param array $options
  1689. * @param integer|null $limit
  1690. * @param integer|null $offset
  1691. *
  1692. * @return array
  1693. */
  1694. public function search(
  1695. array $calendarInfo,
  1696. $pattern,
  1697. array $searchProperties,
  1698. array $options,
  1699. $limit,
  1700. $offset
  1701. ) {
  1702. $outerQuery = $this->db->getQueryBuilder();
  1703. $innerQuery = $this->db->getQueryBuilder();
  1704. if (isset($calendarInfo['source'])) {
  1705. $calendarType = self::CALENDAR_TYPE_SUBSCRIPTION;
  1706. } else {
  1707. $calendarType = self::CALENDAR_TYPE_CALENDAR;
  1708. }
  1709. $innerQuery->selectDistinct('op.objectid')
  1710. ->from($this->dbObjectPropertiesTable, 'op')
  1711. ->andWhere($innerQuery->expr()->eq('op.calendarid',
  1712. $outerQuery->createNamedParameter($calendarInfo['id'])))
  1713. ->andWhere($innerQuery->expr()->eq('op.calendartype',
  1714. $outerQuery->createNamedParameter($calendarType)));
  1715. $outerQuery->select('c.id', 'c.calendardata', 'c.componenttype', 'c.uid', 'c.uri')
  1716. ->from('calendarobjects', 'c')
  1717. ->where($outerQuery->expr()->isNull('deleted_at'));
  1718. // only return public items for shared calendars for now
  1719. if (isset($calendarInfo['{http://owncloud.org/ns}owner-principal']) === false || $calendarInfo['principaluri'] !== $calendarInfo['{http://owncloud.org/ns}owner-principal']) {
  1720. $outerQuery->andWhere($outerQuery->expr()->eq('c.classification',
  1721. $outerQuery->createNamedParameter(self::CLASSIFICATION_PUBLIC)));
  1722. }
  1723. if (!empty($searchProperties)) {
  1724. $or = [];
  1725. foreach ($searchProperties as $searchProperty) {
  1726. $or[] = $innerQuery->expr()->eq('op.name',
  1727. $outerQuery->createNamedParameter($searchProperty));
  1728. }
  1729. $innerQuery->andWhere($innerQuery->expr()->orX(...$or));
  1730. }
  1731. if ($pattern !== '') {
  1732. $innerQuery->andWhere($innerQuery->expr()->iLike('op.value',
  1733. $outerQuery->createNamedParameter('%' .
  1734. $this->db->escapeLikeParameter($pattern) . '%')));
  1735. }
  1736. $start = null;
  1737. $end = null;
  1738. $hasLimit = is_int($limit);
  1739. $hasTimeRange = false;
  1740. if (isset($options['timerange']['start']) && $options['timerange']['start'] instanceof DateTimeInterface) {
  1741. /** @var DateTimeInterface $start */
  1742. $start = $options['timerange']['start'];
  1743. $outerQuery->andWhere(
  1744. $outerQuery->expr()->gt(
  1745. 'lastoccurence',
  1746. $outerQuery->createNamedParameter($start->getTimestamp())
  1747. )
  1748. );
  1749. $hasTimeRange = true;
  1750. }
  1751. if (isset($options['timerange']['end']) && $options['timerange']['end'] instanceof DateTimeInterface) {
  1752. /** @var DateTimeInterface $end */
  1753. $end = $options['timerange']['end'];
  1754. $outerQuery->andWhere(
  1755. $outerQuery->expr()->lt(
  1756. 'firstoccurence',
  1757. $outerQuery->createNamedParameter($end->getTimestamp())
  1758. )
  1759. );
  1760. $hasTimeRange = true;
  1761. }
  1762. if (isset($options['uid'])) {
  1763. $outerQuery->andWhere($outerQuery->expr()->eq('uid', $outerQuery->createNamedParameter($options['uid'])));
  1764. }
  1765. if (!empty($options['types'])) {
  1766. $or = [];
  1767. foreach ($options['types'] as $type) {
  1768. $or[] = $outerQuery->expr()->eq('componenttype',
  1769. $outerQuery->createNamedParameter($type));
  1770. }
  1771. $outerQuery->andWhere($outerQuery->expr()->orX(...$or));
  1772. }
  1773. $outerQuery->andWhere($outerQuery->expr()->in('c.id', $outerQuery->createFunction($innerQuery->getSQL())));
  1774. // Without explicit order by its undefined in which order the SQL server returns the events.
  1775. // For the pagination with hasLimit and hasTimeRange, a stable ordering is helpful.
  1776. $outerQuery->addOrderBy('id');
  1777. $offset = (int)$offset;
  1778. $outerQuery->setFirstResult($offset);
  1779. $calendarObjects = [];
  1780. if ($hasLimit && $hasTimeRange) {
  1781. /**
  1782. * Event recurrences are evaluated at runtime because the database only knows the first and last occurrence.
  1783. *
  1784. * Given, a user created 8 events with a yearly reoccurrence and two for events tomorrow.
  1785. * The upcoming event widget asks the CalDAV backend for 7 events within the next 14 days.
  1786. *
  1787. * If limit 7 is applied to the SQL query, we find the 7 events with a yearly reoccurrence
  1788. * and discard the events after evaluating the reoccurrence rules because they are not due within
  1789. * the next 14 days and end up with an empty result even if there are two events to show.
  1790. *
  1791. * The workaround for search requests with a limit and time range is asking for more row than requested
  1792. * and retrying if we have not reached the limit.
  1793. *
  1794. * 25 rows and 3 retries is entirely arbitrary.
  1795. */
  1796. $maxResults = (int)max($limit, 25);
  1797. $outerQuery->setMaxResults($maxResults);
  1798. for ($attempt = $objectsCount = 0; $attempt < 3 && $objectsCount < $limit; $attempt++) {
  1799. $objectsCount = array_push($calendarObjects, ...$this->searchCalendarObjects($outerQuery, $start, $end));
  1800. $outerQuery->setFirstResult($offset += $maxResults);
  1801. }
  1802. $calendarObjects = array_slice($calendarObjects, 0, $limit, false);
  1803. } else {
  1804. $outerQuery->setMaxResults($limit);
  1805. $calendarObjects = $this->searchCalendarObjects($outerQuery, $start, $end);
  1806. }
  1807. $calendarObjects = array_map(function ($o) use ($options) {
  1808. $calendarData = Reader::read($o['calendardata']);
  1809. // Expand recurrences if an explicit time range is requested
  1810. if ($calendarData instanceof VCalendar
  1811. && isset($options['timerange']['start'], $options['timerange']['end'])) {
  1812. $calendarData = $calendarData->expand(
  1813. $options['timerange']['start'],
  1814. $options['timerange']['end'],
  1815. );
  1816. }
  1817. $comps = $calendarData->getComponents();
  1818. $objects = [];
  1819. $timezones = [];
  1820. foreach ($comps as $comp) {
  1821. if ($comp instanceof VTimeZone) {
  1822. $timezones[] = $comp;
  1823. } else {
  1824. $objects[] = $comp;
  1825. }
  1826. }
  1827. return [
  1828. 'id' => $o['id'],
  1829. 'type' => $o['componenttype'],
  1830. 'uid' => $o['uid'],
  1831. 'uri' => $o['uri'],
  1832. 'objects' => array_map(function ($c) {
  1833. return $this->transformSearchData($c);
  1834. }, $objects),
  1835. 'timezones' => array_map(function ($c) {
  1836. return $this->transformSearchData($c);
  1837. }, $timezones),
  1838. ];
  1839. }, $calendarObjects);
  1840. usort($calendarObjects, function (array $a, array $b) {
  1841. /** @var DateTimeImmutable $startA */
  1842. $startA = $a['objects'][0]['DTSTART'][0] ?? new DateTimeImmutable(self::MAX_DATE);
  1843. /** @var DateTimeImmutable $startB */
  1844. $startB = $b['objects'][0]['DTSTART'][0] ?? new DateTimeImmutable(self::MAX_DATE);
  1845. return $startA->getTimestamp() <=> $startB->getTimestamp();
  1846. });
  1847. return $calendarObjects;
  1848. }
  1849. private function searchCalendarObjects(IQueryBuilder $query, DateTimeInterface|null $start, DateTimeInterface|null $end): array {
  1850. $calendarObjects = [];
  1851. $filterByTimeRange = ($start instanceof DateTimeInterface) || ($end instanceof DateTimeInterface);
  1852. $result = $query->executeQuery();
  1853. while (($row = $result->fetch()) !== false) {
  1854. if ($filterByTimeRange === false) {
  1855. // No filter required
  1856. $calendarObjects[] = $row;
  1857. continue;
  1858. }
  1859. try {
  1860. $isValid = $this->validateFilterForObject($row, [
  1861. 'name' => 'VCALENDAR',
  1862. 'comp-filters' => [
  1863. [
  1864. 'name' => 'VEVENT',
  1865. 'comp-filters' => [],
  1866. 'prop-filters' => [],
  1867. 'is-not-defined' => false,
  1868. 'time-range' => [
  1869. 'start' => $start,
  1870. 'end' => $end,
  1871. ],
  1872. ],
  1873. ],
  1874. 'prop-filters' => [],
  1875. 'is-not-defined' => false,
  1876. 'time-range' => null,
  1877. ]);
  1878. } catch (MaxInstancesExceededException $ex) {
  1879. $this->logger->warning('Caught max instances exceeded exception for calendar data. This usually indicates too much recurring (more than 3500) event in calendar data. Object uri: '.$row['uri'], [
  1880. 'app' => 'dav',
  1881. 'exception' => $ex,
  1882. ]);
  1883. continue;
  1884. }
  1885. if (is_resource($row['calendardata'])) {
  1886. // Put the stream back to the beginning so it can be read another time
  1887. rewind($row['calendardata']);
  1888. }
  1889. if ($isValid) {
  1890. $calendarObjects[] = $row;
  1891. }
  1892. }
  1893. $result->closeCursor();
  1894. return $calendarObjects;
  1895. }
  1896. /**
  1897. * @param Component $comp
  1898. * @return array
  1899. */
  1900. private function transformSearchData(Component $comp) {
  1901. $data = [];
  1902. /** @var Component[] $subComponents */
  1903. $subComponents = $comp->getComponents();
  1904. /** @var Property[] $properties */
  1905. $properties = array_filter($comp->children(), function ($c) {
  1906. return $c instanceof Property;
  1907. });
  1908. $validationRules = $comp->getValidationRules();
  1909. foreach ($subComponents as $subComponent) {
  1910. $name = $subComponent->name;
  1911. if (!isset($data[$name])) {
  1912. $data[$name] = [];
  1913. }
  1914. $data[$name][] = $this->transformSearchData($subComponent);
  1915. }
  1916. foreach ($properties as $property) {
  1917. $name = $property->name;
  1918. if (!isset($validationRules[$name])) {
  1919. $validationRules[$name] = '*';
  1920. }
  1921. $rule = $validationRules[$property->name];
  1922. if ($rule === '+' || $rule === '*') { // multiple
  1923. if (!isset($data[$name])) {
  1924. $data[$name] = [];
  1925. }
  1926. $data[$name][] = $this->transformSearchProperty($property);
  1927. } else { // once
  1928. $data[$name] = $this->transformSearchProperty($property);
  1929. }
  1930. }
  1931. return $data;
  1932. }
  1933. /**
  1934. * @param Property $prop
  1935. * @return array
  1936. */
  1937. private function transformSearchProperty(Property $prop) {
  1938. // No need to check Date, as it extends DateTime
  1939. if ($prop instanceof Property\ICalendar\DateTime) {
  1940. $value = $prop->getDateTime();
  1941. } else {
  1942. $value = $prop->getValue();
  1943. }
  1944. return [
  1945. $value,
  1946. $prop->parameters()
  1947. ];
  1948. }
  1949. /**
  1950. * @param string $principalUri
  1951. * @param string $pattern
  1952. * @param array $componentTypes
  1953. * @param array $searchProperties
  1954. * @param array $searchParameters
  1955. * @param array $options
  1956. * @return array
  1957. */
  1958. public function searchPrincipalUri(string $principalUri,
  1959. string $pattern,
  1960. array $componentTypes,
  1961. array $searchProperties,
  1962. array $searchParameters,
  1963. array $options = []
  1964. ): array {
  1965. return $this->atomic(function () use ($principalUri, $pattern, $componentTypes, $searchProperties, $searchParameters, $options) {
  1966. $escapePattern = !\array_key_exists('escape_like_param', $options) || $options['escape_like_param'] !== false;
  1967. $calendarObjectIdQuery = $this->db->getQueryBuilder();
  1968. $calendarOr = [];
  1969. $searchOr = [];
  1970. // Fetch calendars and subscription
  1971. $calendars = $this->getCalendarsForUser($principalUri);
  1972. $subscriptions = $this->getSubscriptionsForUser($principalUri);
  1973. foreach ($calendars as $calendar) {
  1974. $calendarAnd = $calendarObjectIdQuery->expr()->andX(
  1975. $calendarObjectIdQuery->expr()->eq('cob.calendarid', $calendarObjectIdQuery->createNamedParameter((int)$calendar['id'])),
  1976. $calendarObjectIdQuery->expr()->eq('cob.calendartype', $calendarObjectIdQuery->createNamedParameter(self::CALENDAR_TYPE_CALENDAR)),
  1977. );
  1978. // If it's shared, limit search to public events
  1979. if (isset($calendar['{http://owncloud.org/ns}owner-principal'])
  1980. && $calendar['principaluri'] !== $calendar['{http://owncloud.org/ns}owner-principal']) {
  1981. $calendarAnd->add($calendarObjectIdQuery->expr()->eq('co.classification', $calendarObjectIdQuery->createNamedParameter(self::CLASSIFICATION_PUBLIC)));
  1982. }
  1983. $calendarOr[] = $calendarAnd;
  1984. }
  1985. foreach ($subscriptions as $subscription) {
  1986. $subscriptionAnd = $calendarObjectIdQuery->expr()->andX(
  1987. $calendarObjectIdQuery->expr()->eq('cob.calendarid', $calendarObjectIdQuery->createNamedParameter((int)$subscription['id'])),
  1988. $calendarObjectIdQuery->expr()->eq('cob.calendartype', $calendarObjectIdQuery->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)),
  1989. );
  1990. // If it's shared, limit search to public events
  1991. if (isset($subscription['{http://owncloud.org/ns}owner-principal'])
  1992. && $subscription['principaluri'] !== $subscription['{http://owncloud.org/ns}owner-principal']) {
  1993. $subscriptionAnd->add($calendarObjectIdQuery->expr()->eq('co.classification', $calendarObjectIdQuery->createNamedParameter(self::CLASSIFICATION_PUBLIC)));
  1994. }
  1995. $calendarOr[] = $subscriptionAnd;
  1996. }
  1997. foreach ($searchProperties as $property) {
  1998. $propertyAnd = $calendarObjectIdQuery->expr()->andX(
  1999. $calendarObjectIdQuery->expr()->eq('cob.name', $calendarObjectIdQuery->createNamedParameter($property, IQueryBuilder::PARAM_STR)),
  2000. $calendarObjectIdQuery->expr()->isNull('cob.parameter'),
  2001. );
  2002. $searchOr[] = $propertyAnd;
  2003. }
  2004. foreach ($searchParameters as $property => $parameter) {
  2005. $parameterAnd = $calendarObjectIdQuery->expr()->andX(
  2006. $calendarObjectIdQuery->expr()->eq('cob.name', $calendarObjectIdQuery->createNamedParameter($property, IQueryBuilder::PARAM_STR)),
  2007. $calendarObjectIdQuery->expr()->eq('cob.parameter', $calendarObjectIdQuery->createNamedParameter($parameter, IQueryBuilder::PARAM_STR_ARRAY)),
  2008. );
  2009. $searchOr[] = $parameterAnd;
  2010. }
  2011. if (empty($calendarOr)) {
  2012. return [];
  2013. }
  2014. if (empty($searchOr)) {
  2015. return [];
  2016. }
  2017. $calendarObjectIdQuery->selectDistinct('cob.objectid')
  2018. ->from($this->dbObjectPropertiesTable, 'cob')
  2019. ->leftJoin('cob', 'calendarobjects', 'co', $calendarObjectIdQuery->expr()->eq('co.id', 'cob.objectid'))
  2020. ->andWhere($calendarObjectIdQuery->expr()->in('co.componenttype', $calendarObjectIdQuery->createNamedParameter($componentTypes, IQueryBuilder::PARAM_STR_ARRAY)))
  2021. ->andWhere($calendarObjectIdQuery->expr()->orX(...$calendarOr))
  2022. ->andWhere($calendarObjectIdQuery->expr()->orX(...$searchOr))
  2023. ->andWhere($calendarObjectIdQuery->expr()->isNull('deleted_at'));
  2024. if ($pattern !== '') {
  2025. if (!$escapePattern) {
  2026. $calendarObjectIdQuery->andWhere($calendarObjectIdQuery->expr()->ilike('cob.value', $calendarObjectIdQuery->createNamedParameter($pattern)));
  2027. } else {
  2028. $calendarObjectIdQuery->andWhere($calendarObjectIdQuery->expr()->ilike('cob.value', $calendarObjectIdQuery->createNamedParameter('%' . $this->db->escapeLikeParameter($pattern) . '%')));
  2029. }
  2030. }
  2031. if (isset($options['limit'])) {
  2032. $calendarObjectIdQuery->setMaxResults($options['limit']);
  2033. }
  2034. if (isset($options['offset'])) {
  2035. $calendarObjectIdQuery->setFirstResult($options['offset']);
  2036. }
  2037. if (isset($options['timerange'])) {
  2038. if (isset($options['timerange']['start']) && $options['timerange']['start'] instanceof DateTimeInterface) {
  2039. $calendarObjectIdQuery->andWhere($calendarObjectIdQuery->expr()->gt(
  2040. 'lastoccurence',
  2041. $calendarObjectIdQuery->createNamedParameter($options['timerange']['start']->getTimeStamp()),
  2042. ));
  2043. }
  2044. if (isset($options['timerange']['end']) && $options['timerange']['end'] instanceof DateTimeInterface) {
  2045. $calendarObjectIdQuery->andWhere($calendarObjectIdQuery->expr()->lt(
  2046. 'firstoccurence',
  2047. $calendarObjectIdQuery->createNamedParameter($options['timerange']['end']->getTimeStamp()),
  2048. ));
  2049. }
  2050. }
  2051. $result = $calendarObjectIdQuery->executeQuery();
  2052. $matches = [];
  2053. while (($row = $result->fetch()) !== false) {
  2054. $matches[] = (int) $row['objectid'];
  2055. }
  2056. $result->closeCursor();
  2057. $query = $this->db->getQueryBuilder();
  2058. $query->select('calendardata', 'uri', 'calendarid', 'calendartype')
  2059. ->from('calendarobjects')
  2060. ->where($query->expr()->in('id', $query->createNamedParameter($matches, IQueryBuilder::PARAM_INT_ARRAY)));
  2061. $result = $query->executeQuery();
  2062. $calendarObjects = [];
  2063. while (($array = $result->fetch()) !== false) {
  2064. $array['calendarid'] = (int)$array['calendarid'];
  2065. $array['calendartype'] = (int)$array['calendartype'];
  2066. $array['calendardata'] = $this->readBlob($array['calendardata']);
  2067. $calendarObjects[] = $array;
  2068. }
  2069. $result->closeCursor();
  2070. return $calendarObjects;
  2071. }, $this->db);
  2072. }
  2073. /**
  2074. * Searches through all of a users calendars and calendar objects to find
  2075. * an object with a specific UID.
  2076. *
  2077. * This method should return the path to this object, relative to the
  2078. * calendar home, so this path usually only contains two parts:
  2079. *
  2080. * calendarpath/objectpath.ics
  2081. *
  2082. * If the uid is not found, return null.
  2083. *
  2084. * This method should only consider * objects that the principal owns, so
  2085. * any calendars owned by other principals that also appear in this
  2086. * collection should be ignored.
  2087. *
  2088. * @param string $principalUri
  2089. * @param string $uid
  2090. * @return string|null
  2091. */
  2092. public function getCalendarObjectByUID($principalUri, $uid) {
  2093. $query = $this->db->getQueryBuilder();
  2094. $query->selectAlias('c.uri', 'calendaruri')->selectAlias('co.uri', 'objecturi')
  2095. ->from('calendarobjects', 'co')
  2096. ->leftJoin('co', 'calendars', 'c', $query->expr()->eq('co.calendarid', 'c.id'))
  2097. ->where($query->expr()->eq('c.principaluri', $query->createNamedParameter($principalUri)))
  2098. ->andWhere($query->expr()->eq('co.uid', $query->createNamedParameter($uid)))
  2099. ->andWhere($query->expr()->isNull('co.deleted_at'));
  2100. $stmt = $query->executeQuery();
  2101. $row = $stmt->fetch();
  2102. $stmt->closeCursor();
  2103. if ($row) {
  2104. return $row['calendaruri'] . '/' . $row['objecturi'];
  2105. }
  2106. return null;
  2107. }
  2108. public function getCalendarObjectById(string $principalUri, int $id): ?array {
  2109. $query = $this->db->getQueryBuilder();
  2110. $query->select(['co.id', 'co.uri', 'co.lastmodified', 'co.etag', 'co.calendarid', 'co.size', 'co.calendardata', 'co.componenttype', 'co.classification', 'co.deleted_at'])
  2111. ->selectAlias('c.uri', 'calendaruri')
  2112. ->from('calendarobjects', 'co')
  2113. ->join('co', 'calendars', 'c', $query->expr()->eq('c.id', 'co.calendarid', IQueryBuilder::PARAM_INT))
  2114. ->where($query->expr()->eq('c.principaluri', $query->createNamedParameter($principalUri)))
  2115. ->andWhere($query->expr()->eq('co.id', $query->createNamedParameter($id, IQueryBuilder::PARAM_INT), IQueryBuilder::PARAM_INT));
  2116. $stmt = $query->executeQuery();
  2117. $row = $stmt->fetch();
  2118. $stmt->closeCursor();
  2119. if (!$row) {
  2120. return null;
  2121. }
  2122. return [
  2123. 'id' => $row['id'],
  2124. 'uri' => $row['uri'],
  2125. 'lastmodified' => $row['lastmodified'],
  2126. 'etag' => '"' . $row['etag'] . '"',
  2127. 'calendarid' => $row['calendarid'],
  2128. 'calendaruri' => $row['calendaruri'],
  2129. 'size' => (int)$row['size'],
  2130. 'calendardata' => $this->readBlob($row['calendardata']),
  2131. 'component' => strtolower($row['componenttype']),
  2132. 'classification' => (int)$row['classification'],
  2133. 'deleted_at' => isset($row['deleted_at']) ? ((int) $row['deleted_at']) : null,
  2134. ];
  2135. }
  2136. /**
  2137. * The getChanges method returns all the changes that have happened, since
  2138. * the specified syncToken in the specified calendar.
  2139. *
  2140. * This function should return an array, such as the following:
  2141. *
  2142. * [
  2143. * 'syncToken' => 'The current synctoken',
  2144. * 'added' => [
  2145. * 'new.txt',
  2146. * ],
  2147. * 'modified' => [
  2148. * 'modified.txt',
  2149. * ],
  2150. * 'deleted' => [
  2151. * 'foo.php.bak',
  2152. * 'old.txt'
  2153. * ]
  2154. * );
  2155. *
  2156. * The returned syncToken property should reflect the *current* syncToken
  2157. * of the calendar, as reported in the {http://sabredav.org/ns}sync-token
  2158. * property This is * needed here too, to ensure the operation is atomic.
  2159. *
  2160. * If the $syncToken argument is specified as null, this is an initial
  2161. * sync, and all members should be reported.
  2162. *
  2163. * The modified property is an array of nodenames that have changed since
  2164. * the last token.
  2165. *
  2166. * The deleted property is an array with nodenames, that have been deleted
  2167. * from collection.
  2168. *
  2169. * The $syncLevel argument is basically the 'depth' of the report. If it's
  2170. * 1, you only have to report changes that happened only directly in
  2171. * immediate descendants. If it's 2, it should also include changes from
  2172. * the nodes below the child collections. (grandchildren)
  2173. *
  2174. * The $limit argument allows a client to specify how many results should
  2175. * be returned at most. If the limit is not specified, it should be treated
  2176. * as infinite.
  2177. *
  2178. * If the limit (infinite or not) is higher than you're willing to return,
  2179. * you should throw a Sabre\DAV\Exception\TooMuchMatches() exception.
  2180. *
  2181. * If the syncToken is expired (due to data cleanup) or unknown, you must
  2182. * return null.
  2183. *
  2184. * The limit is 'suggestive'. You are free to ignore it.
  2185. *
  2186. * @param string $calendarId
  2187. * @param string $syncToken
  2188. * @param int $syncLevel
  2189. * @param int|null $limit
  2190. * @param int $calendarType
  2191. * @return ?array
  2192. */
  2193. public function getChangesForCalendar($calendarId, $syncToken, $syncLevel, $limit = null, $calendarType = self::CALENDAR_TYPE_CALENDAR) {
  2194. $table = $calendarType === self::CALENDAR_TYPE_CALENDAR ? 'calendars': 'calendarsubscriptions';
  2195. return $this->atomic(function () use ($calendarId, $syncToken, $syncLevel, $limit, $calendarType, $table) {
  2196. // Current synctoken
  2197. $qb = $this->db->getQueryBuilder();
  2198. $qb->select('synctoken')
  2199. ->from($table)
  2200. ->where(
  2201. $qb->expr()->eq('id', $qb->createNamedParameter($calendarId))
  2202. );
  2203. $stmt = $qb->executeQuery();
  2204. $currentToken = $stmt->fetchOne();
  2205. $initialSync = !is_numeric($syncToken);
  2206. if ($currentToken === false) {
  2207. return null;
  2208. }
  2209. // evaluate if this is a initial sync and construct appropriate command
  2210. if ($initialSync) {
  2211. $qb = $this->db->getQueryBuilder();
  2212. $qb->select('uri')
  2213. ->from('calendarobjects')
  2214. ->where($qb->expr()->eq('calendarid', $qb->createNamedParameter($calendarId)))
  2215. ->andWhere($qb->expr()->eq('calendartype', $qb->createNamedParameter($calendarType)))
  2216. ->andWhere($qb->expr()->isNull('deleted_at'));
  2217. } else {
  2218. $qb = $this->db->getQueryBuilder();
  2219. $qb->select('uri', $qb->func()->max('operation'))
  2220. ->from('calendarchanges')
  2221. ->where($qb->expr()->eq('calendarid', $qb->createNamedParameter($calendarId)))
  2222. ->andWhere($qb->expr()->eq('calendartype', $qb->createNamedParameter($calendarType)))
  2223. ->andWhere($qb->expr()->gte('synctoken', $qb->createNamedParameter($syncToken)))
  2224. ->andWhere($qb->expr()->lt('synctoken', $qb->createNamedParameter($currentToken)))
  2225. ->groupBy('uri');
  2226. }
  2227. // evaluate if limit exists
  2228. if (is_numeric($limit)) {
  2229. $qb->setMaxResults($limit);
  2230. }
  2231. // execute command
  2232. $stmt = $qb->executeQuery();
  2233. // build results
  2234. $result = ['syncToken' => $currentToken, 'added' => [], 'modified' => [], 'deleted' => []];
  2235. // retrieve results
  2236. if ($initialSync) {
  2237. $result['added'] = $stmt->fetchAll(\PDO::FETCH_COLUMN);
  2238. } else {
  2239. // \PDO::FETCH_NUM is needed due to the inconsistent field names
  2240. // produced by doctrine for MAX() with different databases
  2241. while ($entry = $stmt->fetch(\PDO::FETCH_NUM)) {
  2242. // assign uri (column 0) to appropriate mutation based on operation (column 1)
  2243. // forced (int) is needed as doctrine with OCI returns the operation field as string not integer
  2244. match ((int)$entry[1]) {
  2245. 1 => $result['added'][] = $entry[0],
  2246. 2 => $result['modified'][] = $entry[0],
  2247. 3 => $result['deleted'][] = $entry[0],
  2248. default => $this->logger->debug('Unknown calendar change operation detected')
  2249. };
  2250. }
  2251. }
  2252. $stmt->closeCursor();
  2253. return $result;
  2254. }, $this->db);
  2255. }
  2256. /**
  2257. * Returns a list of subscriptions for a principal.
  2258. *
  2259. * Every subscription is an array with the following keys:
  2260. * * id, a unique id that will be used by other functions to modify the
  2261. * subscription. This can be the same as the uri or a database key.
  2262. * * uri. This is just the 'base uri' or 'filename' of the subscription.
  2263. * * principaluri. The owner of the subscription. Almost always the same as
  2264. * principalUri passed to this method.
  2265. *
  2266. * Furthermore, all the subscription info must be returned too:
  2267. *
  2268. * 1. {DAV:}displayname
  2269. * 2. {http://apple.com/ns/ical/}refreshrate
  2270. * 3. {http://calendarserver.org/ns/}subscribed-strip-todos (omit if todos
  2271. * should not be stripped).
  2272. * 4. {http://calendarserver.org/ns/}subscribed-strip-alarms (omit if alarms
  2273. * should not be stripped).
  2274. * 5. {http://calendarserver.org/ns/}subscribed-strip-attachments (omit if
  2275. * attachments should not be stripped).
  2276. * 6. {http://calendarserver.org/ns/}source (Must be a
  2277. * Sabre\DAV\Property\Href).
  2278. * 7. {http://apple.com/ns/ical/}calendar-color
  2279. * 8. {http://apple.com/ns/ical/}calendar-order
  2280. * 9. {urn:ietf:params:xml:ns:caldav}supported-calendar-component-set
  2281. * (should just be an instance of
  2282. * Sabre\CalDAV\Property\SupportedCalendarComponentSet, with a bunch of
  2283. * default components).
  2284. *
  2285. * @param string $principalUri
  2286. * @return array
  2287. */
  2288. public function getSubscriptionsForUser($principalUri) {
  2289. $fields = array_column($this->subscriptionPropertyMap, 0);
  2290. $fields[] = 'id';
  2291. $fields[] = 'uri';
  2292. $fields[] = 'source';
  2293. $fields[] = 'principaluri';
  2294. $fields[] = 'lastmodified';
  2295. $fields[] = 'synctoken';
  2296. $query = $this->db->getQueryBuilder();
  2297. $query->select($fields)
  2298. ->from('calendarsubscriptions')
  2299. ->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
  2300. ->orderBy('calendarorder', 'asc');
  2301. $stmt = $query->executeQuery();
  2302. $subscriptions = [];
  2303. while ($row = $stmt->fetch()) {
  2304. $subscription = [
  2305. 'id' => $row['id'],
  2306. 'uri' => $row['uri'],
  2307. 'principaluri' => $row['principaluri'],
  2308. 'source' => $row['source'],
  2309. 'lastmodified' => $row['lastmodified'],
  2310. '{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet(['VTODO', 'VEVENT']),
  2311. '{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
  2312. ];
  2313. $subscriptions[] = $this->rowToSubscription($row, $subscription);
  2314. }
  2315. return $subscriptions;
  2316. }
  2317. /**
  2318. * Creates a new subscription for a principal.
  2319. *
  2320. * If the creation was a success, an id must be returned that can be used to reference
  2321. * this subscription in other methods, such as updateSubscription.
  2322. *
  2323. * @param string $principalUri
  2324. * @param string $uri
  2325. * @param array $properties
  2326. * @return mixed
  2327. */
  2328. public function createSubscription($principalUri, $uri, array $properties) {
  2329. if (!isset($properties['{http://calendarserver.org/ns/}source'])) {
  2330. throw new Forbidden('The {http://calendarserver.org/ns/}source property is required when creating subscriptions');
  2331. }
  2332. $values = [
  2333. 'principaluri' => $principalUri,
  2334. 'uri' => $uri,
  2335. 'source' => $properties['{http://calendarserver.org/ns/}source']->getHref(),
  2336. 'lastmodified' => time(),
  2337. ];
  2338. $propertiesBoolean = ['striptodos', 'stripalarms', 'stripattachments'];
  2339. foreach ($this->subscriptionPropertyMap as $xmlName => [$dbName, $type]) {
  2340. if (array_key_exists($xmlName, $properties)) {
  2341. $values[$dbName] = $properties[$xmlName];
  2342. if (in_array($dbName, $propertiesBoolean)) {
  2343. $values[$dbName] = true;
  2344. }
  2345. }
  2346. }
  2347. [$subscriptionId, $subscriptionRow] = $this->atomic(function () use ($values) {
  2348. $valuesToInsert = [];
  2349. $query = $this->db->getQueryBuilder();
  2350. foreach (array_keys($values) as $name) {
  2351. $valuesToInsert[$name] = $query->createNamedParameter($values[$name]);
  2352. }
  2353. $query->insert('calendarsubscriptions')
  2354. ->values($valuesToInsert)
  2355. ->executeStatement();
  2356. $subscriptionId = $query->getLastInsertId();
  2357. $subscriptionRow = $this->getSubscriptionById($subscriptionId);
  2358. return [$subscriptionId, $subscriptionRow];
  2359. }, $this->db);
  2360. $this->dispatcher->dispatchTyped(new SubscriptionCreatedEvent($subscriptionId, $subscriptionRow));
  2361. return $subscriptionId;
  2362. }
  2363. /**
  2364. * Updates a subscription
  2365. *
  2366. * The list of mutations is stored in a Sabre\DAV\PropPatch object.
  2367. * To do the actual updates, you must tell this object which properties
  2368. * you're going to process with the handle() method.
  2369. *
  2370. * Calling the handle method is like telling the PropPatch object "I
  2371. * promise I can handle updating this property".
  2372. *
  2373. * Read the PropPatch documentation for more info and examples.
  2374. *
  2375. * @param mixed $subscriptionId
  2376. * @param PropPatch $propPatch
  2377. * @return void
  2378. */
  2379. public function updateSubscription($subscriptionId, PropPatch $propPatch) {
  2380. $supportedProperties = array_keys($this->subscriptionPropertyMap);
  2381. $supportedProperties[] = '{http://calendarserver.org/ns/}source';
  2382. $propPatch->handle($supportedProperties, function ($mutations) use ($subscriptionId) {
  2383. $newValues = [];
  2384. foreach ($mutations as $propertyName => $propertyValue) {
  2385. if ($propertyName === '{http://calendarserver.org/ns/}source') {
  2386. $newValues['source'] = $propertyValue->getHref();
  2387. } else {
  2388. $fieldName = $this->subscriptionPropertyMap[$propertyName][0];
  2389. $newValues[$fieldName] = $propertyValue;
  2390. }
  2391. }
  2392. $subscriptionRow = $this->atomic(function () use ($subscriptionId, $newValues) {
  2393. $query = $this->db->getQueryBuilder();
  2394. $query->update('calendarsubscriptions')
  2395. ->set('lastmodified', $query->createNamedParameter(time()));
  2396. foreach ($newValues as $fieldName => $value) {
  2397. $query->set($fieldName, $query->createNamedParameter($value));
  2398. }
  2399. $query->where($query->expr()->eq('id', $query->createNamedParameter($subscriptionId)))
  2400. ->executeStatement();
  2401. return $this->getSubscriptionById($subscriptionId);
  2402. }, $this->db);
  2403. $this->dispatcher->dispatchTyped(new SubscriptionUpdatedEvent((int)$subscriptionId, $subscriptionRow, [], $mutations));
  2404. return true;
  2405. });
  2406. }
  2407. /**
  2408. * Deletes a subscription.
  2409. *
  2410. * @param mixed $subscriptionId
  2411. * @return void
  2412. */
  2413. public function deleteSubscription($subscriptionId) {
  2414. $this->atomic(function () use ($subscriptionId) {
  2415. $subscriptionRow = $this->getSubscriptionById($subscriptionId);
  2416. $query = $this->db->getQueryBuilder();
  2417. $query->delete('calendarsubscriptions')
  2418. ->where($query->expr()->eq('id', $query->createNamedParameter($subscriptionId)))
  2419. ->executeStatement();
  2420. $query = $this->db->getQueryBuilder();
  2421. $query->delete('calendarobjects')
  2422. ->where($query->expr()->eq('calendarid', $query->createNamedParameter($subscriptionId)))
  2423. ->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)))
  2424. ->executeStatement();
  2425. $query->delete('calendarchanges')
  2426. ->where($query->expr()->eq('calendarid', $query->createNamedParameter($subscriptionId)))
  2427. ->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)))
  2428. ->executeStatement();
  2429. $query->delete($this->dbObjectPropertiesTable)
  2430. ->where($query->expr()->eq('calendarid', $query->createNamedParameter($subscriptionId)))
  2431. ->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)))
  2432. ->executeStatement();
  2433. if ($subscriptionRow) {
  2434. $this->dispatcher->dispatchTyped(new SubscriptionDeletedEvent((int)$subscriptionId, $subscriptionRow, []));
  2435. }
  2436. }, $this->db);
  2437. }
  2438. /**
  2439. * Returns a single scheduling object for the inbox collection.
  2440. *
  2441. * The returned array should contain the following elements:
  2442. * * uri - A unique basename for the object. This will be used to
  2443. * construct a full uri.
  2444. * * calendardata - The iCalendar object
  2445. * * lastmodified - The last modification date. Can be an int for a unix
  2446. * timestamp, or a PHP DateTime object.
  2447. * * etag - A unique token that must change if the object changed.
  2448. * * size - The size of the object, in bytes.
  2449. *
  2450. * @param string $principalUri
  2451. * @param string $objectUri
  2452. * @return array
  2453. */
  2454. public function getSchedulingObject($principalUri, $objectUri) {
  2455. $query = $this->db->getQueryBuilder();
  2456. $stmt = $query->select(['uri', 'calendardata', 'lastmodified', 'etag', 'size'])
  2457. ->from('schedulingobjects')
  2458. ->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
  2459. ->andWhere($query->expr()->eq('uri', $query->createNamedParameter($objectUri)))
  2460. ->executeQuery();
  2461. $row = $stmt->fetch();
  2462. if (!$row) {
  2463. return null;
  2464. }
  2465. return [
  2466. 'uri' => $row['uri'],
  2467. 'calendardata' => $row['calendardata'],
  2468. 'lastmodified' => $row['lastmodified'],
  2469. 'etag' => '"' . $row['etag'] . '"',
  2470. 'size' => (int)$row['size'],
  2471. ];
  2472. }
  2473. /**
  2474. * Returns all scheduling objects for the inbox collection.
  2475. *
  2476. * These objects should be returned as an array. Every item in the array
  2477. * should follow the same structure as returned from getSchedulingObject.
  2478. *
  2479. * The main difference is that 'calendardata' is optional.
  2480. *
  2481. * @param string $principalUri
  2482. * @return array
  2483. */
  2484. public function getSchedulingObjects($principalUri) {
  2485. $query = $this->db->getQueryBuilder();
  2486. $stmt = $query->select(['uri', 'calendardata', 'lastmodified', 'etag', 'size'])
  2487. ->from('schedulingobjects')
  2488. ->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
  2489. ->executeQuery();
  2490. $results = [];
  2491. while (($row = $stmt->fetch()) !== false) {
  2492. $results[] = [
  2493. 'calendardata' => $row['calendardata'],
  2494. 'uri' => $row['uri'],
  2495. 'lastmodified' => $row['lastmodified'],
  2496. 'etag' => '"' . $row['etag'] . '"',
  2497. 'size' => (int)$row['size'],
  2498. ];
  2499. }
  2500. $stmt->closeCursor();
  2501. return $results;
  2502. }
  2503. /**
  2504. * Deletes a scheduling object from the inbox collection.
  2505. *
  2506. * @param string $principalUri
  2507. * @param string $objectUri
  2508. * @return void
  2509. */
  2510. public function deleteSchedulingObject($principalUri, $objectUri) {
  2511. $this->cachedObjects = [];
  2512. $query = $this->db->getQueryBuilder();
  2513. $query->delete('schedulingobjects')
  2514. ->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
  2515. ->andWhere($query->expr()->eq('uri', $query->createNamedParameter($objectUri)))
  2516. ->executeStatement();
  2517. }
  2518. /**
  2519. * Deletes all scheduling objects last modified before $modifiedBefore from the inbox collection.
  2520. *
  2521. * @param int $modifiedBefore
  2522. * @param int $limit
  2523. * @return void
  2524. */
  2525. public function deleteOutdatedSchedulingObjects(int $modifiedBefore, int $limit): void {
  2526. $query = $this->db->getQueryBuilder();
  2527. $query->select('id')
  2528. ->from('schedulingobjects')
  2529. ->where($query->expr()->lt('lastmodified', $query->createNamedParameter($modifiedBefore)))
  2530. ->setMaxResults($limit);
  2531. $result = $query->executeQuery();
  2532. $count = $result->rowCount();
  2533. if($count === 0) {
  2534. return;
  2535. }
  2536. $ids = array_map(static function (array $id) {
  2537. return (int)$id[0];
  2538. }, $result->fetchAll(\PDO::FETCH_NUM));
  2539. $result->closeCursor();
  2540. $numDeleted = 0;
  2541. $deleteQuery = $this->db->getQueryBuilder();
  2542. $deleteQuery->delete('schedulingobjects')
  2543. ->where($deleteQuery->expr()->in('id', $deleteQuery->createParameter('ids'), IQueryBuilder::PARAM_INT_ARRAY));
  2544. foreach(array_chunk($ids, 1000) as $chunk) {
  2545. $deleteQuery->setParameter('ids', $chunk, IQueryBuilder::PARAM_INT_ARRAY);
  2546. $numDeleted += $deleteQuery->executeStatement();
  2547. }
  2548. if($numDeleted === $limit) {
  2549. $this->logger->info("Deleted $limit scheduling objects, continuing with next batch");
  2550. $this->deleteOutdatedSchedulingObjects($modifiedBefore, $limit);
  2551. }
  2552. }
  2553. /**
  2554. * Creates a new scheduling object. This should land in a users' inbox.
  2555. *
  2556. * @param string $principalUri
  2557. * @param string $objectUri
  2558. * @param string $objectData
  2559. * @return void
  2560. */
  2561. public function createSchedulingObject($principalUri, $objectUri, $objectData) {
  2562. $this->cachedObjects = [];
  2563. $query = $this->db->getQueryBuilder();
  2564. $query->insert('schedulingobjects')
  2565. ->values([
  2566. 'principaluri' => $query->createNamedParameter($principalUri),
  2567. 'calendardata' => $query->createNamedParameter($objectData, IQueryBuilder::PARAM_LOB),
  2568. 'uri' => $query->createNamedParameter($objectUri),
  2569. 'lastmodified' => $query->createNamedParameter(time()),
  2570. 'etag' => $query->createNamedParameter(md5($objectData)),
  2571. 'size' => $query->createNamedParameter(strlen($objectData))
  2572. ])
  2573. ->executeStatement();
  2574. }
  2575. /**
  2576. * Adds a change record to the calendarchanges table.
  2577. *
  2578. * @param mixed $calendarId
  2579. * @param string[] $objectUris
  2580. * @param int $operation 1 = add, 2 = modify, 3 = delete.
  2581. * @param int $calendarType
  2582. * @return void
  2583. */
  2584. protected function addChanges(int $calendarId, array $objectUris, int $operation, int $calendarType = self::CALENDAR_TYPE_CALENDAR): void {
  2585. $this->cachedObjects = [];
  2586. $table = $calendarType === self::CALENDAR_TYPE_CALENDAR ? 'calendars': 'calendarsubscriptions';
  2587. $this->atomic(function () use ($calendarId, $objectUris, $operation, $calendarType, $table) {
  2588. $query = $this->db->getQueryBuilder();
  2589. $query->select('synctoken')
  2590. ->from($table)
  2591. ->where($query->expr()->eq('id', $query->createNamedParameter($calendarId)));
  2592. $result = $query->executeQuery();
  2593. $syncToken = (int)$result->fetchOne();
  2594. $result->closeCursor();
  2595. $query = $this->db->getQueryBuilder();
  2596. $query->insert('calendarchanges')
  2597. ->values([
  2598. 'uri' => $query->createParameter('uri'),
  2599. 'synctoken' => $query->createNamedParameter($syncToken),
  2600. 'calendarid' => $query->createNamedParameter($calendarId),
  2601. 'operation' => $query->createNamedParameter($operation),
  2602. 'calendartype' => $query->createNamedParameter($calendarType),
  2603. 'created_at' => time(),
  2604. ]);
  2605. foreach ($objectUris as $uri) {
  2606. $query->setParameter('uri', $uri);
  2607. $query->executeStatement();
  2608. }
  2609. $query = $this->db->getQueryBuilder();
  2610. $query->update($table)
  2611. ->set('synctoken', $query->createNamedParameter($syncToken + 1, IQueryBuilder::PARAM_INT))
  2612. ->where($query->expr()->eq('id', $query->createNamedParameter($calendarId)))
  2613. ->executeStatement();
  2614. }, $this->db);
  2615. }
  2616. public function restoreChanges(int $calendarId, int $calendarType = self::CALENDAR_TYPE_CALENDAR): void {
  2617. $this->cachedObjects = [];
  2618. $this->atomic(function () use ($calendarId, $calendarType) {
  2619. $qbAdded = $this->db->getQueryBuilder();
  2620. $qbAdded->select('uri')
  2621. ->from('calendarobjects')
  2622. ->where(
  2623. $qbAdded->expr()->andX(
  2624. $qbAdded->expr()->eq('calendarid', $qbAdded->createNamedParameter($calendarId)),
  2625. $qbAdded->expr()->eq('calendartype', $qbAdded->createNamedParameter($calendarType)),
  2626. $qbAdded->expr()->isNull('deleted_at'),
  2627. )
  2628. );
  2629. $resultAdded = $qbAdded->executeQuery();
  2630. $addedUris = $resultAdded->fetchAll(\PDO::FETCH_COLUMN);
  2631. $resultAdded->closeCursor();
  2632. // Track everything as changed
  2633. // Tracking the creation is not necessary because \OCA\DAV\CalDAV\CalDavBackend::getChangesForCalendar
  2634. // only returns the last change per object.
  2635. $this->addChanges($calendarId, $addedUris, 2, $calendarType);
  2636. $qbDeleted = $this->db->getQueryBuilder();
  2637. $qbDeleted->select('uri')
  2638. ->from('calendarobjects')
  2639. ->where(
  2640. $qbDeleted->expr()->andX(
  2641. $qbDeleted->expr()->eq('calendarid', $qbDeleted->createNamedParameter($calendarId)),
  2642. $qbDeleted->expr()->eq('calendartype', $qbDeleted->createNamedParameter($calendarType)),
  2643. $qbDeleted->expr()->isNotNull('deleted_at'),
  2644. )
  2645. );
  2646. $resultDeleted = $qbDeleted->executeQuery();
  2647. $deletedUris = array_map(function (string $uri) {
  2648. return str_replace("-deleted.ics", ".ics", $uri);
  2649. }, $resultDeleted->fetchAll(\PDO::FETCH_COLUMN));
  2650. $resultDeleted->closeCursor();
  2651. $this->addChanges($calendarId, $deletedUris, 3, $calendarType);
  2652. }, $this->db);
  2653. }
  2654. /**
  2655. * Parses some information from calendar objects, used for optimized
  2656. * calendar-queries.
  2657. *
  2658. * Returns an array with the following keys:
  2659. * * etag - An md5 checksum of the object without the quotes.
  2660. * * size - Size of the object in bytes
  2661. * * componentType - VEVENT, VTODO or VJOURNAL
  2662. * * firstOccurence
  2663. * * lastOccurence
  2664. * * uid - value of the UID property
  2665. *
  2666. * @param string $calendarData
  2667. * @return array
  2668. */
  2669. public function getDenormalizedData(string $calendarData): array {
  2670. $vObject = Reader::read($calendarData);
  2671. $vEvents = [];
  2672. $componentType = null;
  2673. $component = null;
  2674. $firstOccurrence = null;
  2675. $lastOccurrence = null;
  2676. $uid = null;
  2677. $classification = self::CLASSIFICATION_PUBLIC;
  2678. $hasDTSTART = false;
  2679. foreach ($vObject->getComponents() as $component) {
  2680. if ($component->name !== 'VTIMEZONE') {
  2681. // Finding all VEVENTs, and track them
  2682. if ($component->name === 'VEVENT') {
  2683. $vEvents[] = $component;
  2684. if ($component->DTSTART) {
  2685. $hasDTSTART = true;
  2686. }
  2687. }
  2688. // Track first component type and uid
  2689. if ($uid === null) {
  2690. $componentType = $component->name;
  2691. $uid = (string)$component->UID;
  2692. }
  2693. }
  2694. }
  2695. if (!$componentType) {
  2696. throw new BadRequest('Calendar objects must have a VJOURNAL, VEVENT or VTODO component');
  2697. }
  2698. if ($hasDTSTART) {
  2699. $component = $vEvents[0];
  2700. // Finding the last occurrence is a bit harder
  2701. if (!isset($component->RRULE) && count($vEvents) === 1) {
  2702. $firstOccurrence = $component->DTSTART->getDateTime()->getTimeStamp();
  2703. if (isset($component->DTEND)) {
  2704. $lastOccurrence = $component->DTEND->getDateTime()->getTimeStamp();
  2705. } elseif (isset($component->DURATION)) {
  2706. $endDate = clone $component->DTSTART->getDateTime();
  2707. $endDate->add(DateTimeParser::parse($component->DURATION->getValue()));
  2708. $lastOccurrence = $endDate->getTimeStamp();
  2709. } elseif (!$component->DTSTART->hasTime()) {
  2710. $endDate = clone $component->DTSTART->getDateTime();
  2711. $endDate->modify('+1 day');
  2712. $lastOccurrence = $endDate->getTimeStamp();
  2713. } else {
  2714. $lastOccurrence = $firstOccurrence;
  2715. }
  2716. } else {
  2717. try {
  2718. $it = new EventIterator($vEvents);
  2719. } catch (NoInstancesException $e) {
  2720. $this->logger->debug('Caught no instance exception for calendar data. This usually indicates invalid calendar data.', [
  2721. 'app' => 'dav',
  2722. 'exception' => $e,
  2723. ]);
  2724. throw new Forbidden($e->getMessage());
  2725. }
  2726. $maxDate = new DateTime(self::MAX_DATE);
  2727. $firstOccurrence = $it->getDtStart()->getTimestamp();
  2728. if ($it->isInfinite()) {
  2729. $lastOccurrence = $maxDate->getTimestamp();
  2730. } else {
  2731. $end = $it->getDtEnd();
  2732. while ($it->valid() && $end < $maxDate) {
  2733. $end = $it->getDtEnd();
  2734. $it->next();
  2735. }
  2736. $lastOccurrence = $end->getTimestamp();
  2737. }
  2738. }
  2739. }
  2740. if ($component->CLASS) {
  2741. $classification = CalDavBackend::CLASSIFICATION_PRIVATE;
  2742. switch ($component->CLASS->getValue()) {
  2743. case 'PUBLIC':
  2744. $classification = CalDavBackend::CLASSIFICATION_PUBLIC;
  2745. break;
  2746. case 'CONFIDENTIAL':
  2747. $classification = CalDavBackend::CLASSIFICATION_CONFIDENTIAL;
  2748. break;
  2749. }
  2750. }
  2751. return [
  2752. 'etag' => md5($calendarData),
  2753. 'size' => strlen($calendarData),
  2754. 'componentType' => $componentType,
  2755. 'firstOccurence' => is_null($firstOccurrence) ? null : max(0, $firstOccurrence),
  2756. 'lastOccurence' => is_null($lastOccurrence) ? null : max(0, $lastOccurrence),
  2757. 'uid' => $uid,
  2758. 'classification' => $classification
  2759. ];
  2760. }
  2761. /**
  2762. * @param $cardData
  2763. * @return bool|string
  2764. */
  2765. private function readBlob($cardData) {
  2766. if (is_resource($cardData)) {
  2767. return stream_get_contents($cardData);
  2768. }
  2769. return $cardData;
  2770. }
  2771. /**
  2772. * @param list<array{href: string, commonName: string, readOnly: bool}> $add
  2773. * @param list<string> $remove
  2774. */
  2775. public function updateShares(IShareable $shareable, array $add, array $remove): void {
  2776. $this->atomic(function () use ($shareable, $add, $remove) {
  2777. $calendarId = $shareable->getResourceId();
  2778. $calendarRow = $this->getCalendarById($calendarId);
  2779. if ($calendarRow === null) {
  2780. throw new \RuntimeException('Trying to update shares for non-existing calendar: ' . $calendarId);
  2781. }
  2782. $oldShares = $this->getShares($calendarId);
  2783. $this->calendarSharingBackend->updateShares($shareable, $add, $remove, $oldShares);
  2784. $this->dispatcher->dispatchTyped(new CalendarShareUpdatedEvent($calendarId, $calendarRow, $oldShares, $add, $remove));
  2785. }, $this->db);
  2786. }
  2787. /**
  2788. * @return list<array{href: string, commonName: string, status: int, readOnly: bool, '{http://owncloud.org/ns}principal': string, '{http://owncloud.org/ns}group-share': bool}>
  2789. */
  2790. public function getShares(int $resourceId): array {
  2791. return $this->calendarSharingBackend->getShares($resourceId);
  2792. }
  2793. public function preloadShares(array $resourceIds): void {
  2794. $this->calendarSharingBackend->preloadShares($resourceIds);
  2795. }
  2796. /**
  2797. * @param boolean $value
  2798. * @param \OCA\DAV\CalDAV\Calendar $calendar
  2799. * @return string|null
  2800. */
  2801. public function setPublishStatus($value, $calendar) {
  2802. return $this->atomic(function () use ($value, $calendar) {
  2803. $calendarId = $calendar->getResourceId();
  2804. $calendarData = $this->getCalendarById($calendarId);
  2805. $query = $this->db->getQueryBuilder();
  2806. if ($value) {
  2807. $publicUri = $this->random->generate(16, ISecureRandom::CHAR_HUMAN_READABLE);
  2808. $query->insert('dav_shares')
  2809. ->values([
  2810. 'principaluri' => $query->createNamedParameter($calendar->getPrincipalURI()),
  2811. 'type' => $query->createNamedParameter('calendar'),
  2812. 'access' => $query->createNamedParameter(self::ACCESS_PUBLIC),
  2813. 'resourceid' => $query->createNamedParameter($calendar->getResourceId()),
  2814. 'publicuri' => $query->createNamedParameter($publicUri)
  2815. ]);
  2816. $query->executeStatement();
  2817. $this->dispatcher->dispatchTyped(new CalendarPublishedEvent($calendarId, $calendarData, $publicUri));
  2818. return $publicUri;
  2819. }
  2820. $query->delete('dav_shares')
  2821. ->where($query->expr()->eq('resourceid', $query->createNamedParameter($calendar->getResourceId())))
  2822. ->andWhere($query->expr()->eq('access', $query->createNamedParameter(self::ACCESS_PUBLIC)));
  2823. $query->executeStatement();
  2824. $this->dispatcher->dispatchTyped(new CalendarUnpublishedEvent($calendarId, $calendarData));
  2825. return null;
  2826. }, $this->db);
  2827. }
  2828. /**
  2829. * @param \OCA\DAV\CalDAV\Calendar $calendar
  2830. * @return mixed
  2831. */
  2832. public function getPublishStatus($calendar) {
  2833. $query = $this->db->getQueryBuilder();
  2834. $result = $query->select('publicuri')
  2835. ->from('dav_shares')
  2836. ->where($query->expr()->eq('resourceid', $query->createNamedParameter($calendar->getResourceId())))
  2837. ->andWhere($query->expr()->eq('access', $query->createNamedParameter(self::ACCESS_PUBLIC)))
  2838. ->executeQuery();
  2839. $row = $result->fetch();
  2840. $result->closeCursor();
  2841. return $row ? reset($row) : false;
  2842. }
  2843. /**
  2844. * @param int $resourceId
  2845. * @param list<array{privilege: string, principal: string, protected: bool}> $acl
  2846. * @return list<array{privilege: string, principal: string, protected: bool}>
  2847. */
  2848. public function applyShareAcl(int $resourceId, array $acl): array {
  2849. $shares = $this->calendarSharingBackend->getShares($resourceId);
  2850. return $this->calendarSharingBackend->applyShareAcl($shares, $acl);
  2851. }
  2852. /**
  2853. * update properties table
  2854. *
  2855. * @param int $calendarId
  2856. * @param string $objectUri
  2857. * @param string $calendarData
  2858. * @param int $calendarType
  2859. */
  2860. public function updateProperties($calendarId, $objectUri, $calendarData, $calendarType = self::CALENDAR_TYPE_CALENDAR) {
  2861. $this->cachedObjects = [];
  2862. $this->atomic(function () use ($calendarId, $objectUri, $calendarData, $calendarType) {
  2863. $objectId = $this->getCalendarObjectId($calendarId, $objectUri, $calendarType);
  2864. try {
  2865. $vCalendar = $this->readCalendarData($calendarData);
  2866. } catch (\Exception $ex) {
  2867. return;
  2868. }
  2869. $this->purgeProperties($calendarId, $objectId);
  2870. $query = $this->db->getQueryBuilder();
  2871. $query->insert($this->dbObjectPropertiesTable)
  2872. ->values(
  2873. [
  2874. 'calendarid' => $query->createNamedParameter($calendarId),
  2875. 'calendartype' => $query->createNamedParameter($calendarType),
  2876. 'objectid' => $query->createNamedParameter($objectId),
  2877. 'name' => $query->createParameter('name'),
  2878. 'parameter' => $query->createParameter('parameter'),
  2879. 'value' => $query->createParameter('value'),
  2880. ]
  2881. );
  2882. $indexComponents = ['VEVENT', 'VJOURNAL', 'VTODO'];
  2883. foreach ($vCalendar->getComponents() as $component) {
  2884. if (!in_array($component->name, $indexComponents)) {
  2885. continue;
  2886. }
  2887. foreach ($component->children() as $property) {
  2888. if (in_array($property->name, self::INDEXED_PROPERTIES, true)) {
  2889. $value = $property->getValue();
  2890. // is this a shitty db?
  2891. if (!$this->db->supports4ByteText()) {
  2892. $value = preg_replace('/[\x{10000}-\x{10FFFF}]/u', "\xEF\xBF\xBD", $value);
  2893. }
  2894. $value = mb_strcut($value, 0, 254);
  2895. $query->setParameter('name', $property->name);
  2896. $query->setParameter('parameter', null);
  2897. $query->setParameter('value', mb_strcut($value, 0, 254));
  2898. $query->executeStatement();
  2899. }
  2900. if (array_key_exists($property->name, self::$indexParameters)) {
  2901. $parameters = $property->parameters();
  2902. $indexedParametersForProperty = self::$indexParameters[$property->name];
  2903. foreach ($parameters as $key => $value) {
  2904. if (in_array($key, $indexedParametersForProperty)) {
  2905. // is this a shitty db?
  2906. if ($this->db->supports4ByteText()) {
  2907. $value = preg_replace('/[\x{10000}-\x{10FFFF}]/u', "\xEF\xBF\xBD", $value);
  2908. }
  2909. $query->setParameter('name', $property->name);
  2910. $query->setParameter('parameter', mb_strcut($key, 0, 254));
  2911. $query->setParameter('value', mb_strcut($value, 0, 254));
  2912. $query->executeStatement();
  2913. }
  2914. }
  2915. }
  2916. }
  2917. }
  2918. }, $this->db);
  2919. }
  2920. /**
  2921. * deletes all birthday calendars
  2922. */
  2923. public function deleteAllBirthdayCalendars() {
  2924. $this->atomic(function () {
  2925. $query = $this->db->getQueryBuilder();
  2926. $result = $query->select(['id'])->from('calendars')
  2927. ->where($query->expr()->eq('uri', $query->createNamedParameter(BirthdayService::BIRTHDAY_CALENDAR_URI)))
  2928. ->executeQuery();
  2929. while (($row = $result->fetch()) !== false) {
  2930. $this->deleteCalendar(
  2931. $row['id'],
  2932. true // No data to keep in the trashbin, if the user re-enables then we regenerate
  2933. );
  2934. }
  2935. $result->closeCursor();
  2936. }, $this->db);
  2937. }
  2938. /**
  2939. * @param $subscriptionId
  2940. */
  2941. public function purgeAllCachedEventsForSubscription($subscriptionId) {
  2942. $this->atomic(function () use ($subscriptionId) {
  2943. $query = $this->db->getQueryBuilder();
  2944. $query->select('uri')
  2945. ->from('calendarobjects')
  2946. ->where($query->expr()->eq('calendarid', $query->createNamedParameter($subscriptionId)))
  2947. ->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)));
  2948. $stmt = $query->executeQuery();
  2949. $uris = [];
  2950. while (($row = $stmt->fetch()) !== false) {
  2951. $uris[] = $row['uri'];
  2952. }
  2953. $stmt->closeCursor();
  2954. $query = $this->db->getQueryBuilder();
  2955. $query->delete('calendarobjects')
  2956. ->where($query->expr()->eq('calendarid', $query->createNamedParameter($subscriptionId)))
  2957. ->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)))
  2958. ->executeStatement();
  2959. $query = $this->db->getQueryBuilder();
  2960. $query->delete('calendarchanges')
  2961. ->where($query->expr()->eq('calendarid', $query->createNamedParameter($subscriptionId)))
  2962. ->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)))
  2963. ->executeStatement();
  2964. $query = $this->db->getQueryBuilder();
  2965. $query->delete($this->dbObjectPropertiesTable)
  2966. ->where($query->expr()->eq('calendarid', $query->createNamedParameter($subscriptionId)))
  2967. ->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)))
  2968. ->executeStatement();
  2969. $this->addChanges($subscriptionId, $uris, 3, self::CALENDAR_TYPE_SUBSCRIPTION);
  2970. }, $this->db);
  2971. }
  2972. /**
  2973. * @param int $subscriptionId
  2974. * @param array<int> $calendarObjectIds
  2975. * @param array<string> $calendarObjectUris
  2976. */
  2977. public function purgeCachedEventsForSubscription(int $subscriptionId, array $calendarObjectIds, array $calendarObjectUris): void {
  2978. if(empty($calendarObjectUris)) {
  2979. return;
  2980. }
  2981. $this->atomic(function () use ($subscriptionId, $calendarObjectIds, $calendarObjectUris) {
  2982. foreach (array_chunk($calendarObjectIds, 1000) as $chunk) {
  2983. $query = $this->db->getQueryBuilder();
  2984. $query->delete($this->dbObjectPropertiesTable)
  2985. ->where($query->expr()->eq('calendarid', $query->createNamedParameter($subscriptionId)))
  2986. ->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)))
  2987. ->andWhere($query->expr()->in('id', $query->createNamedParameter($chunk, IQueryBuilder::PARAM_INT_ARRAY), IQueryBuilder::PARAM_INT_ARRAY))
  2988. ->executeStatement();
  2989. $query = $this->db->getQueryBuilder();
  2990. $query->delete('calendarobjects')
  2991. ->where($query->expr()->eq('calendarid', $query->createNamedParameter($subscriptionId)))
  2992. ->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)))
  2993. ->andWhere($query->expr()->in('id', $query->createNamedParameter($chunk, IQueryBuilder::PARAM_INT_ARRAY), IQueryBuilder::PARAM_INT_ARRAY))
  2994. ->executeStatement();
  2995. }
  2996. foreach (array_chunk($calendarObjectUris, 1000) as $chunk) {
  2997. $query = $this->db->getQueryBuilder();
  2998. $query->delete('calendarchanges')
  2999. ->where($query->expr()->eq('calendarid', $query->createNamedParameter($subscriptionId)))
  3000. ->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)))
  3001. ->andWhere($query->expr()->in('uri', $query->createNamedParameter($chunk, IQueryBuilder::PARAM_STR_ARRAY), IQueryBuilder::PARAM_STR_ARRAY))
  3002. ->executeStatement();
  3003. }
  3004. $this->addChanges($subscriptionId, $calendarObjectUris, 3, self::CALENDAR_TYPE_SUBSCRIPTION);
  3005. }, $this->db);
  3006. }
  3007. /**
  3008. * Move a calendar from one user to another
  3009. *
  3010. * @param string $uriName
  3011. * @param string $uriOrigin
  3012. * @param string $uriDestination
  3013. * @param string $newUriName (optional) the new uriName
  3014. */
  3015. public function moveCalendar($uriName, $uriOrigin, $uriDestination, $newUriName = null) {
  3016. $query = $this->db->getQueryBuilder();
  3017. $query->update('calendars')
  3018. ->set('principaluri', $query->createNamedParameter($uriDestination))
  3019. ->set('uri', $query->createNamedParameter($newUriName ?: $uriName))
  3020. ->where($query->expr()->eq('principaluri', $query->createNamedParameter($uriOrigin)))
  3021. ->andWhere($query->expr()->eq('uri', $query->createNamedParameter($uriName)))
  3022. ->executeStatement();
  3023. }
  3024. /**
  3025. * read VCalendar data into a VCalendar object
  3026. *
  3027. * @param string $objectData
  3028. * @return VCalendar
  3029. */
  3030. protected function readCalendarData($objectData) {
  3031. return Reader::read($objectData);
  3032. }
  3033. /**
  3034. * delete all properties from a given calendar object
  3035. *
  3036. * @param int $calendarId
  3037. * @param int $objectId
  3038. */
  3039. protected function purgeProperties($calendarId, $objectId) {
  3040. $this->cachedObjects = [];
  3041. $query = $this->db->getQueryBuilder();
  3042. $query->delete($this->dbObjectPropertiesTable)
  3043. ->where($query->expr()->eq('objectid', $query->createNamedParameter($objectId)))
  3044. ->andWhere($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)));
  3045. $query->executeStatement();
  3046. }
  3047. /**
  3048. * get ID from a given calendar object
  3049. *
  3050. * @param int $calendarId
  3051. * @param string $uri
  3052. * @param int $calendarType
  3053. * @return int
  3054. */
  3055. protected function getCalendarObjectId($calendarId, $uri, $calendarType):int {
  3056. $query = $this->db->getQueryBuilder();
  3057. $query->select('id')
  3058. ->from('calendarobjects')
  3059. ->where($query->expr()->eq('uri', $query->createNamedParameter($uri)))
  3060. ->andWhere($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)))
  3061. ->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter($calendarType)));
  3062. $result = $query->executeQuery();
  3063. $objectIds = $result->fetch();
  3064. $result->closeCursor();
  3065. if (!isset($objectIds['id'])) {
  3066. throw new \InvalidArgumentException('Calendarobject does not exists: ' . $uri);
  3067. }
  3068. return (int)$objectIds['id'];
  3069. }
  3070. /**
  3071. * @throws \InvalidArgumentException
  3072. */
  3073. public function pruneOutdatedSyncTokens(int $keep, int $retention): int {
  3074. if ($keep < 0) {
  3075. throw new \InvalidArgumentException();
  3076. }
  3077. $query = $this->db->getQueryBuilder();
  3078. $query->select($query->func()->max('id'))
  3079. ->from('calendarchanges');
  3080. $result = $query->executeQuery();
  3081. $maxId = (int) $result->fetchOne();
  3082. $result->closeCursor();
  3083. if (!$maxId || $maxId < $keep) {
  3084. return 0;
  3085. }
  3086. $query = $this->db->getQueryBuilder();
  3087. $query->delete('calendarchanges')
  3088. ->where(
  3089. $query->expr()->lte('id', $query->createNamedParameter($maxId - $keep, IQueryBuilder::PARAM_INT), IQueryBuilder::PARAM_INT),
  3090. $query->expr()->lte('created_at', $query->createNamedParameter($retention)),
  3091. );
  3092. return $query->executeStatement();
  3093. }
  3094. /**
  3095. * return legacy endpoint principal name to new principal name
  3096. *
  3097. * @param $principalUri
  3098. * @param $toV2
  3099. * @return string
  3100. */
  3101. private function convertPrincipal($principalUri, $toV2) {
  3102. if ($this->principalBackend->getPrincipalPrefix() === 'principals') {
  3103. [, $name] = Uri\split($principalUri);
  3104. if ($toV2 === true) {
  3105. return "principals/users/$name";
  3106. }
  3107. return "principals/$name";
  3108. }
  3109. return $principalUri;
  3110. }
  3111. /**
  3112. * adds information about an owner to the calendar data
  3113. *
  3114. */
  3115. private function addOwnerPrincipalToCalendar(array $calendarInfo): array {
  3116. $ownerPrincipalKey = '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal';
  3117. $displaynameKey = '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_NEXTCLOUD . '}owner-displayname';
  3118. if (isset($calendarInfo[$ownerPrincipalKey])) {
  3119. $uri = $calendarInfo[$ownerPrincipalKey];
  3120. } else {
  3121. $uri = $calendarInfo['principaluri'];
  3122. }
  3123. $principalInformation = $this->principalBackend->getPrincipalByPath($uri);
  3124. if (isset($principalInformation['{DAV:}displayname'])) {
  3125. $calendarInfo[$displaynameKey] = $principalInformation['{DAV:}displayname'];
  3126. }
  3127. return $calendarInfo;
  3128. }
  3129. private function addResourceTypeToCalendar(array $row, array $calendar): array {
  3130. if (isset($row['deleted_at'])) {
  3131. // Columns is set and not null -> this is a deleted calendar
  3132. // we send a custom resourcetype to hide the deleted calendar
  3133. // from ordinary DAV clients, but the Calendar app will know
  3134. // how to handle this special resource.
  3135. $calendar['{DAV:}resourcetype'] = new DAV\Xml\Property\ResourceType([
  3136. '{DAV:}collection',
  3137. sprintf('{%s}deleted-calendar', \OCA\DAV\DAV\Sharing\Plugin::NS_NEXTCLOUD),
  3138. ]);
  3139. }
  3140. return $calendar;
  3141. }
  3142. /**
  3143. * Amend the calendar info with database row data
  3144. *
  3145. * @param array $row
  3146. * @param array $calendar
  3147. *
  3148. * @return array
  3149. */
  3150. private function rowToCalendar($row, array $calendar): array {
  3151. foreach ($this->propertyMap as $xmlName => [$dbName, $type]) {
  3152. $value = $row[$dbName];
  3153. if ($value !== null) {
  3154. settype($value, $type);
  3155. }
  3156. $calendar[$xmlName] = $value;
  3157. }
  3158. return $calendar;
  3159. }
  3160. /**
  3161. * Amend the subscription info with database row data
  3162. *
  3163. * @param array $row
  3164. * @param array $subscription
  3165. *
  3166. * @return array
  3167. */
  3168. private function rowToSubscription($row, array $subscription): array {
  3169. foreach ($this->subscriptionPropertyMap as $xmlName => [$dbName, $type]) {
  3170. $value = $row[$dbName];
  3171. if ($value !== null) {
  3172. settype($value, $type);
  3173. }
  3174. $subscription[$xmlName] = $value;
  3175. }
  3176. return $subscription;
  3177. }
  3178. }