CalDavBackend.php 124 KB

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