CalDavBackend.php 128 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530
  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,VJOURNAL',
  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. * Returns all calendar objects with limited metadata for a calendar
  848. *
  849. * Every item contains an array with the following keys:
  850. * * id - the table row id
  851. * * etag - An arbitrary string
  852. * * uri - a unique key which will be used to construct the uri. This can
  853. * be any arbitrary string.
  854. * * calendardata - The iCalendar-compatible calendar data
  855. *
  856. * @param mixed $calendarId
  857. * @param int $calendarType
  858. * @return array
  859. */
  860. public function getLimitedCalendarObjects(int $calendarId, int $calendarType = self::CALENDAR_TYPE_CALENDAR):array {
  861. $query = $this->db->getQueryBuilder();
  862. $query->select(['id','uid', 'etag', 'uri', 'calendardata'])
  863. ->from('calendarobjects')
  864. ->where($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)))
  865. ->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter($calendarType)))
  866. ->andWhere($query->expr()->isNull('deleted_at'));
  867. $stmt = $query->executeQuery();
  868. $result = [];
  869. while (($row = $stmt->fetch()) !== false) {
  870. $result[$row['uid']] = [
  871. 'id' => $row['id'],
  872. 'etag' => $row['etag'],
  873. 'uri' => $row['uri'],
  874. 'calendardata' => $row['calendardata'],
  875. ];
  876. }
  877. $stmt->closeCursor();
  878. return $result;
  879. }
  880. /**
  881. * Delete all of an user's shares
  882. *
  883. * @param string $principaluri
  884. * @return void
  885. */
  886. public function deleteAllSharesByUser($principaluri) {
  887. $this->calendarSharingBackend->deleteAllSharesByUser($principaluri);
  888. }
  889. /**
  890. * Returns all calendar objects within a calendar.
  891. *
  892. * Every item contains an array with the following keys:
  893. * * calendardata - The iCalendar-compatible calendar data
  894. * * uri - a unique key which will be used to construct the uri. This can
  895. * be any arbitrary string, but making sure it ends with '.ics' is a
  896. * good idea. This is only the basename, or filename, not the full
  897. * path.
  898. * * lastmodified - a timestamp of the last modification time
  899. * * etag - An arbitrary string, surrounded by double-quotes. (e.g.:
  900. * '"abcdef"')
  901. * * size - The size of the calendar objects, in bytes.
  902. * * component - optional, a string containing the type of object, such
  903. * as 'vevent' or 'vtodo'. If specified, this will be used to populate
  904. * the Content-Type header.
  905. *
  906. * Note that the etag is optional, but it's highly encouraged to return for
  907. * speed reasons.
  908. *
  909. * The calendardata is also optional. If it's not returned
  910. * 'getCalendarObject' will be called later, which *is* expected to return
  911. * calendardata.
  912. *
  913. * If neither etag or size are specified, the calendardata will be
  914. * used/fetched to determine these numbers. If both are specified the
  915. * amount of times this is needed is reduced by a great degree.
  916. *
  917. * @param mixed $calendarId
  918. * @param int $calendarType
  919. * @return array
  920. */
  921. public function getCalendarObjects($calendarId, $calendarType = self::CALENDAR_TYPE_CALENDAR):array {
  922. $query = $this->db->getQueryBuilder();
  923. $query->select(['id', 'uri', 'lastmodified', 'etag', 'calendarid', 'size', 'componenttype', 'classification'])
  924. ->from('calendarobjects')
  925. ->where($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)))
  926. ->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter($calendarType)))
  927. ->andWhere($query->expr()->isNull('deleted_at'));
  928. $stmt = $query->executeQuery();
  929. $result = [];
  930. while (($row = $stmt->fetch()) !== false) {
  931. $result[] = [
  932. 'id' => $row['id'],
  933. 'uri' => $row['uri'],
  934. 'lastmodified' => $row['lastmodified'],
  935. 'etag' => '"' . $row['etag'] . '"',
  936. 'calendarid' => $row['calendarid'],
  937. 'size' => (int)$row['size'],
  938. 'component' => strtolower($row['componenttype']),
  939. 'classification' => (int)$row['classification']
  940. ];
  941. }
  942. $stmt->closeCursor();
  943. return $result;
  944. }
  945. public function getDeletedCalendarObjects(int $deletedBefore): array {
  946. $query = $this->db->getQueryBuilder();
  947. $query->select(['co.id', 'co.uri', 'co.lastmodified', 'co.etag', 'co.calendarid', 'co.calendartype', 'co.size', 'co.componenttype', 'co.classification', 'co.deleted_at'])
  948. ->from('calendarobjects', 'co')
  949. ->join('co', 'calendars', 'c', $query->expr()->eq('c.id', 'co.calendarid', IQueryBuilder::PARAM_INT))
  950. ->where($query->expr()->isNotNull('co.deleted_at'))
  951. ->andWhere($query->expr()->lt('co.deleted_at', $query->createNamedParameter($deletedBefore)));
  952. $stmt = $query->executeQuery();
  953. $result = [];
  954. while (($row = $stmt->fetch()) !== false) {
  955. $result[] = [
  956. 'id' => $row['id'],
  957. 'uri' => $row['uri'],
  958. 'lastmodified' => $row['lastmodified'],
  959. 'etag' => '"' . $row['etag'] . '"',
  960. 'calendarid' => (int)$row['calendarid'],
  961. 'calendartype' => (int)$row['calendartype'],
  962. 'size' => (int)$row['size'],
  963. 'component' => strtolower($row['componenttype']),
  964. 'classification' => (int)$row['classification'],
  965. '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_NEXTCLOUD . '}deleted-at' => $row['deleted_at'] === null ? $row['deleted_at'] : (int)$row['deleted_at'],
  966. ];
  967. }
  968. $stmt->closeCursor();
  969. return $result;
  970. }
  971. /**
  972. * Return all deleted calendar objects by the given principal that are not
  973. * in deleted calendars.
  974. *
  975. * @param string $principalUri
  976. * @return array
  977. * @throws Exception
  978. */
  979. public function getDeletedCalendarObjectsByPrincipal(string $principalUri): array {
  980. $query = $this->db->getQueryBuilder();
  981. $query->select(['co.id', 'co.uri', 'co.lastmodified', 'co.etag', 'co.calendarid', 'co.size', 'co.componenttype', 'co.classification', 'co.deleted_at'])
  982. ->selectAlias('c.uri', 'calendaruri')
  983. ->from('calendarobjects', 'co')
  984. ->join('co', 'calendars', 'c', $query->expr()->eq('c.id', 'co.calendarid', IQueryBuilder::PARAM_INT))
  985. ->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
  986. ->andWhere($query->expr()->isNotNull('co.deleted_at'))
  987. ->andWhere($query->expr()->isNull('c.deleted_at'));
  988. $stmt = $query->executeQuery();
  989. $result = [];
  990. while ($row = $stmt->fetch()) {
  991. $result[] = [
  992. 'id' => $row['id'],
  993. 'uri' => $row['uri'],
  994. 'lastmodified' => $row['lastmodified'],
  995. 'etag' => '"' . $row['etag'] . '"',
  996. 'calendarid' => $row['calendarid'],
  997. 'calendaruri' => $row['calendaruri'],
  998. 'size' => (int)$row['size'],
  999. 'component' => strtolower($row['componenttype']),
  1000. 'classification' => (int)$row['classification'],
  1001. '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_NEXTCLOUD . '}deleted-at' => $row['deleted_at'] === null ? $row['deleted_at'] : (int)$row['deleted_at'],
  1002. ];
  1003. }
  1004. $stmt->closeCursor();
  1005. return $result;
  1006. }
  1007. /**
  1008. * Returns information from a single calendar object, based on it's object
  1009. * uri.
  1010. *
  1011. * The object uri is only the basename, or filename and not a full path.
  1012. *
  1013. * The returned array must have the same keys as getCalendarObjects. The
  1014. * 'calendardata' object is required here though, while it's not required
  1015. * for getCalendarObjects.
  1016. *
  1017. * This method must return null if the object did not exist.
  1018. *
  1019. * @param mixed $calendarId
  1020. * @param string $objectUri
  1021. * @param int $calendarType
  1022. * @return array|null
  1023. */
  1024. public function getCalendarObject($calendarId, $objectUri, int $calendarType = self::CALENDAR_TYPE_CALENDAR) {
  1025. $key = $calendarId . '::' . $objectUri . '::' . $calendarType;
  1026. if (isset($this->cachedObjects[$key])) {
  1027. return $this->cachedObjects[$key];
  1028. }
  1029. $query = $this->db->getQueryBuilder();
  1030. $query->select(['id', 'uri', 'lastmodified', 'etag', 'calendarid', 'size', 'calendardata', 'componenttype', 'classification', 'deleted_at'])
  1031. ->from('calendarobjects')
  1032. ->where($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)))
  1033. ->andWhere($query->expr()->eq('uri', $query->createNamedParameter($objectUri)))
  1034. ->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter($calendarType)));
  1035. $stmt = $query->executeQuery();
  1036. $row = $stmt->fetch();
  1037. $stmt->closeCursor();
  1038. if (!$row) {
  1039. return null;
  1040. }
  1041. $object = $this->rowToCalendarObject($row);
  1042. $this->cachedObjects[$key] = $object;
  1043. return $object;
  1044. }
  1045. private function rowToCalendarObject(array $row): array {
  1046. return [
  1047. 'id' => $row['id'],
  1048. 'uri' => $row['uri'],
  1049. 'lastmodified' => $row['lastmodified'],
  1050. 'etag' => '"' . $row['etag'] . '"',
  1051. 'calendarid' => $row['calendarid'],
  1052. 'size' => (int)$row['size'],
  1053. 'calendardata' => $this->readBlob($row['calendardata']),
  1054. 'component' => strtolower($row['componenttype']),
  1055. 'classification' => (int)$row['classification'],
  1056. '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_NEXTCLOUD . '}deleted-at' => $row['deleted_at'] === null ? $row['deleted_at'] : (int)$row['deleted_at'],
  1057. ];
  1058. }
  1059. /**
  1060. * Returns a list of calendar objects.
  1061. *
  1062. * This method should work identical to getCalendarObject, but instead
  1063. * return all the calendar objects in the list as an array.
  1064. *
  1065. * If the backend supports this, it may allow for some speed-ups.
  1066. *
  1067. * @param mixed $calendarId
  1068. * @param string[] $uris
  1069. * @param int $calendarType
  1070. * @return array
  1071. */
  1072. public function getMultipleCalendarObjects($calendarId, array $uris, $calendarType = self::CALENDAR_TYPE_CALENDAR):array {
  1073. if (empty($uris)) {
  1074. return [];
  1075. }
  1076. $chunks = array_chunk($uris, 100);
  1077. $objects = [];
  1078. $query = $this->db->getQueryBuilder();
  1079. $query->select(['id', 'uri', 'lastmodified', 'etag', 'calendarid', 'size', 'calendardata', 'componenttype', 'classification'])
  1080. ->from('calendarobjects')
  1081. ->where($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)))
  1082. ->andWhere($query->expr()->in('uri', $query->createParameter('uri')))
  1083. ->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter($calendarType)))
  1084. ->andWhere($query->expr()->isNull('deleted_at'));
  1085. foreach ($chunks as $uris) {
  1086. $query->setParameter('uri', $uris, IQueryBuilder::PARAM_STR_ARRAY);
  1087. $result = $query->executeQuery();
  1088. while ($row = $result->fetch()) {
  1089. $objects[] = [
  1090. 'id' => $row['id'],
  1091. 'uri' => $row['uri'],
  1092. 'lastmodified' => $row['lastmodified'],
  1093. 'etag' => '"' . $row['etag'] . '"',
  1094. 'calendarid' => $row['calendarid'],
  1095. 'size' => (int)$row['size'],
  1096. 'calendardata' => $this->readBlob($row['calendardata']),
  1097. 'component' => strtolower($row['componenttype']),
  1098. 'classification' => (int)$row['classification']
  1099. ];
  1100. }
  1101. $result->closeCursor();
  1102. }
  1103. return $objects;
  1104. }
  1105. /**
  1106. * Creates a new calendar object.
  1107. *
  1108. * The object uri is only the basename, or filename and not a full path.
  1109. *
  1110. * It is possible return an etag from this function, which will be used in
  1111. * the response to this PUT request. Note that the ETag must be surrounded
  1112. * by double-quotes.
  1113. *
  1114. * However, you should only really return this ETag if you don't mangle the
  1115. * calendar-data. If the result of a subsequent GET to this object is not
  1116. * the exact same as this request body, you should omit the ETag.
  1117. *
  1118. * @param mixed $calendarId
  1119. * @param string $objectUri
  1120. * @param string $calendarData
  1121. * @param int $calendarType
  1122. * @return string
  1123. */
  1124. public function createCalendarObject($calendarId, $objectUri, $calendarData, $calendarType = self::CALENDAR_TYPE_CALENDAR) {
  1125. $this->cachedObjects = [];
  1126. $extraData = $this->getDenormalizedData($calendarData);
  1127. return $this->atomic(function () use ($calendarId, $objectUri, $calendarData, $extraData, $calendarType) {
  1128. // Try to detect duplicates
  1129. $qb = $this->db->getQueryBuilder();
  1130. $qb->select($qb->func()->count('*'))
  1131. ->from('calendarobjects')
  1132. ->where($qb->expr()->eq('calendarid', $qb->createNamedParameter($calendarId)))
  1133. ->andWhere($qb->expr()->eq('uid', $qb->createNamedParameter($extraData['uid'])))
  1134. ->andWhere($qb->expr()->eq('calendartype', $qb->createNamedParameter($calendarType)))
  1135. ->andWhere($qb->expr()->isNull('deleted_at'));
  1136. $result = $qb->executeQuery();
  1137. $count = (int)$result->fetchOne();
  1138. $result->closeCursor();
  1139. if ($count !== 0) {
  1140. throw new BadRequest('Calendar object with uid already exists in this calendar collection.');
  1141. }
  1142. // For a more specific error message we also try to explicitly look up the UID but as a deleted entry
  1143. $qbDel = $this->db->getQueryBuilder();
  1144. $qbDel->select('*')
  1145. ->from('calendarobjects')
  1146. ->where($qbDel->expr()->eq('calendarid', $qbDel->createNamedParameter($calendarId)))
  1147. ->andWhere($qbDel->expr()->eq('uid', $qbDel->createNamedParameter($extraData['uid'])))
  1148. ->andWhere($qbDel->expr()->eq('calendartype', $qbDel->createNamedParameter($calendarType)))
  1149. ->andWhere($qbDel->expr()->isNotNull('deleted_at'));
  1150. $result = $qbDel->executeQuery();
  1151. $found = $result->fetch();
  1152. $result->closeCursor();
  1153. if ($found !== false) {
  1154. // the object existed previously but has been deleted
  1155. // remove the trashbin entry and continue as if it was a new object
  1156. $this->deleteCalendarObject($calendarId, $found['uri']);
  1157. }
  1158. $query = $this->db->getQueryBuilder();
  1159. $query->insert('calendarobjects')
  1160. ->values([
  1161. 'calendarid' => $query->createNamedParameter($calendarId),
  1162. 'uri' => $query->createNamedParameter($objectUri),
  1163. 'calendardata' => $query->createNamedParameter($calendarData, IQueryBuilder::PARAM_LOB),
  1164. 'lastmodified' => $query->createNamedParameter(time()),
  1165. 'etag' => $query->createNamedParameter($extraData['etag']),
  1166. 'size' => $query->createNamedParameter($extraData['size']),
  1167. 'componenttype' => $query->createNamedParameter($extraData['componentType']),
  1168. 'firstoccurence' => $query->createNamedParameter($extraData['firstOccurence']),
  1169. 'lastoccurence' => $query->createNamedParameter($extraData['lastOccurence']),
  1170. 'classification' => $query->createNamedParameter($extraData['classification']),
  1171. 'uid' => $query->createNamedParameter($extraData['uid']),
  1172. 'calendartype' => $query->createNamedParameter($calendarType),
  1173. ])
  1174. ->executeStatement();
  1175. $this->updateProperties($calendarId, $objectUri, $calendarData, $calendarType);
  1176. $this->addChanges($calendarId, [$objectUri], 1, $calendarType);
  1177. $objectRow = $this->getCalendarObject($calendarId, $objectUri, $calendarType);
  1178. assert($objectRow !== null);
  1179. if ($calendarType === self::CALENDAR_TYPE_CALENDAR) {
  1180. $calendarRow = $this->getCalendarById($calendarId);
  1181. $shares = $this->getShares($calendarId);
  1182. $this->dispatcher->dispatchTyped(new CalendarObjectCreatedEvent($calendarId, $calendarRow, $shares, $objectRow));
  1183. } else {
  1184. $subscriptionRow = $this->getSubscriptionById($calendarId);
  1185. $this->dispatcher->dispatchTyped(new CachedCalendarObjectCreatedEvent($calendarId, $subscriptionRow, [], $objectRow));
  1186. }
  1187. return '"' . $extraData['etag'] . '"';
  1188. }, $this->db);
  1189. }
  1190. /**
  1191. * Updates an existing calendarobject, based on it's uri.
  1192. *
  1193. * The object uri is only the basename, or filename and not a full path.
  1194. *
  1195. * It is possible return an etag from this function, which will be used in
  1196. * the response to this PUT request. Note that the ETag must be surrounded
  1197. * by double-quotes.
  1198. *
  1199. * However, you should only really return this ETag if you don't mangle the
  1200. * calendar-data. If the result of a subsequent GET to this object is not
  1201. * the exact same as this request body, you should omit the ETag.
  1202. *
  1203. * @param mixed $calendarId
  1204. * @param string $objectUri
  1205. * @param string $calendarData
  1206. * @param int $calendarType
  1207. * @return string
  1208. */
  1209. public function updateCalendarObject($calendarId, $objectUri, $calendarData, $calendarType = self::CALENDAR_TYPE_CALENDAR) {
  1210. $this->cachedObjects = [];
  1211. $extraData = $this->getDenormalizedData($calendarData);
  1212. return $this->atomic(function () use ($calendarId, $objectUri, $calendarData, $extraData, $calendarType) {
  1213. $query = $this->db->getQueryBuilder();
  1214. $query->update('calendarobjects')
  1215. ->set('calendardata', $query->createNamedParameter($calendarData, IQueryBuilder::PARAM_LOB))
  1216. ->set('lastmodified', $query->createNamedParameter(time()))
  1217. ->set('etag', $query->createNamedParameter($extraData['etag']))
  1218. ->set('size', $query->createNamedParameter($extraData['size']))
  1219. ->set('componenttype', $query->createNamedParameter($extraData['componentType']))
  1220. ->set('firstoccurence', $query->createNamedParameter($extraData['firstOccurence']))
  1221. ->set('lastoccurence', $query->createNamedParameter($extraData['lastOccurence']))
  1222. ->set('classification', $query->createNamedParameter($extraData['classification']))
  1223. ->set('uid', $query->createNamedParameter($extraData['uid']))
  1224. ->where($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)))
  1225. ->andWhere($query->expr()->eq('uri', $query->createNamedParameter($objectUri)))
  1226. ->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter($calendarType)))
  1227. ->executeStatement();
  1228. $this->updateProperties($calendarId, $objectUri, $calendarData, $calendarType);
  1229. $this->addChanges($calendarId, [$objectUri], 2, $calendarType);
  1230. $objectRow = $this->getCalendarObject($calendarId, $objectUri, $calendarType);
  1231. if (is_array($objectRow)) {
  1232. if ($calendarType === self::CALENDAR_TYPE_CALENDAR) {
  1233. $calendarRow = $this->getCalendarById($calendarId);
  1234. $shares = $this->getShares($calendarId);
  1235. $this->dispatcher->dispatchTyped(new CalendarObjectUpdatedEvent($calendarId, $calendarRow, $shares, $objectRow));
  1236. } else {
  1237. $subscriptionRow = $this->getSubscriptionById($calendarId);
  1238. $this->dispatcher->dispatchTyped(new CachedCalendarObjectUpdatedEvent($calendarId, $subscriptionRow, [], $objectRow));
  1239. }
  1240. }
  1241. return '"' . $extraData['etag'] . '"';
  1242. }, $this->db);
  1243. }
  1244. /**
  1245. * Moves a calendar object from calendar to calendar.
  1246. *
  1247. * @param int $sourceCalendarId
  1248. * @param int $targetCalendarId
  1249. * @param int $objectId
  1250. * @param string $oldPrincipalUri
  1251. * @param string $newPrincipalUri
  1252. * @param int $calendarType
  1253. * @return bool
  1254. * @throws Exception
  1255. */
  1256. public function moveCalendarObject(int $sourceCalendarId, int $targetCalendarId, int $objectId, string $oldPrincipalUri, string $newPrincipalUri, int $calendarType = self::CALENDAR_TYPE_CALENDAR): bool {
  1257. $this->cachedObjects = [];
  1258. return $this->atomic(function () use ($sourceCalendarId, $targetCalendarId, $objectId, $oldPrincipalUri, $newPrincipalUri, $calendarType) {
  1259. $object = $this->getCalendarObjectById($oldPrincipalUri, $objectId);
  1260. if (empty($object)) {
  1261. return false;
  1262. }
  1263. $query = $this->db->getQueryBuilder();
  1264. $query->update('calendarobjects')
  1265. ->set('calendarid', $query->createNamedParameter($targetCalendarId, IQueryBuilder::PARAM_INT))
  1266. ->where($query->expr()->eq('id', $query->createNamedParameter($objectId, IQueryBuilder::PARAM_INT), IQueryBuilder::PARAM_INT))
  1267. ->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter($calendarType, IQueryBuilder::PARAM_INT), IQueryBuilder::PARAM_INT))
  1268. ->executeStatement();
  1269. $this->purgeProperties($sourceCalendarId, $objectId);
  1270. $this->updateProperties($targetCalendarId, $object['uri'], $object['calendardata'], $calendarType);
  1271. $this->addChanges($sourceCalendarId, [$object['uri']], 3, $calendarType);
  1272. $this->addChanges($targetCalendarId, [$object['uri']], 1, $calendarType);
  1273. $object = $this->getCalendarObjectById($newPrincipalUri, $objectId);
  1274. // Calendar Object wasn't found - possibly because it was deleted in the meantime by a different client
  1275. if (empty($object)) {
  1276. return false;
  1277. }
  1278. $targetCalendarRow = $this->getCalendarById($targetCalendarId);
  1279. // the calendar this event is being moved to does not exist any longer
  1280. if (empty($targetCalendarRow)) {
  1281. return false;
  1282. }
  1283. if ($calendarType === self::CALENDAR_TYPE_CALENDAR) {
  1284. $sourceShares = $this->getShares($sourceCalendarId);
  1285. $targetShares = $this->getShares($targetCalendarId);
  1286. $sourceCalendarRow = $this->getCalendarById($sourceCalendarId);
  1287. $this->dispatcher->dispatchTyped(new CalendarObjectMovedEvent($sourceCalendarId, $sourceCalendarRow, $targetCalendarId, $targetCalendarRow, $sourceShares, $targetShares, $object));
  1288. }
  1289. return true;
  1290. }, $this->db);
  1291. }
  1292. /**
  1293. * @param int $calendarObjectId
  1294. * @param int $classification
  1295. */
  1296. public function setClassification($calendarObjectId, $classification) {
  1297. $this->cachedObjects = [];
  1298. if (!in_array($classification, [
  1299. self::CLASSIFICATION_PUBLIC, self::CLASSIFICATION_PRIVATE, self::CLASSIFICATION_CONFIDENTIAL
  1300. ])) {
  1301. throw new \InvalidArgumentException();
  1302. }
  1303. $query = $this->db->getQueryBuilder();
  1304. $query->update('calendarobjects')
  1305. ->set('classification', $query->createNamedParameter($classification))
  1306. ->where($query->expr()->eq('id', $query->createNamedParameter($calendarObjectId)))
  1307. ->executeStatement();
  1308. }
  1309. /**
  1310. * Deletes an existing calendar object.
  1311. *
  1312. * The object uri is only the basename, or filename and not a full path.
  1313. *
  1314. * @param mixed $calendarId
  1315. * @param string $objectUri
  1316. * @param int $calendarType
  1317. * @param bool $forceDeletePermanently
  1318. * @return void
  1319. */
  1320. public function deleteCalendarObject($calendarId, $objectUri, $calendarType = self::CALENDAR_TYPE_CALENDAR, bool $forceDeletePermanently = false) {
  1321. $this->cachedObjects = [];
  1322. $this->atomic(function () use ($calendarId, $objectUri, $calendarType, $forceDeletePermanently) {
  1323. $data = $this->getCalendarObject($calendarId, $objectUri, $calendarType);
  1324. if ($data === null) {
  1325. // Nothing to delete
  1326. return;
  1327. }
  1328. if ($forceDeletePermanently || $this->config->getAppValue(Application::APP_ID, RetentionService::RETENTION_CONFIG_KEY) === '0') {
  1329. $stmt = $this->db->prepare('DELETE FROM `*PREFIX*calendarobjects` WHERE `calendarid` = ? AND `uri` = ? AND `calendartype` = ?');
  1330. $stmt->execute([$calendarId, $objectUri, $calendarType]);
  1331. $this->purgeProperties($calendarId, $data['id']);
  1332. if ($calendarType === self::CALENDAR_TYPE_CALENDAR) {
  1333. $calendarRow = $this->getCalendarById($calendarId);
  1334. $shares = $this->getShares($calendarId);
  1335. $this->dispatcher->dispatchTyped(new CalendarObjectDeletedEvent($calendarId, $calendarRow, $shares, $data));
  1336. } else {
  1337. $subscriptionRow = $this->getSubscriptionById($calendarId);
  1338. $this->dispatcher->dispatchTyped(new CachedCalendarObjectDeletedEvent($calendarId, $subscriptionRow, [], $data));
  1339. }
  1340. } else {
  1341. $pathInfo = pathinfo($data['uri']);
  1342. if (!empty($pathInfo['extension'])) {
  1343. // Append a suffix to "free" the old URI for recreation
  1344. $newUri = sprintf(
  1345. '%s-deleted.%s',
  1346. $pathInfo['filename'],
  1347. $pathInfo['extension']
  1348. );
  1349. } else {
  1350. $newUri = sprintf(
  1351. '%s-deleted',
  1352. $pathInfo['filename']
  1353. );
  1354. }
  1355. // Try to detect conflicts before the DB does
  1356. // As unlikely as it seems, this can happen when the user imports, then deletes, imports and deletes again
  1357. $newObject = $this->getCalendarObject($calendarId, $newUri, $calendarType);
  1358. if ($newObject !== null) {
  1359. throw new Forbidden("A calendar object with URI $newUri already exists in calendar $calendarId, therefore this object can't be moved into the trashbin");
  1360. }
  1361. $qb = $this->db->getQueryBuilder();
  1362. $markObjectDeletedQuery = $qb->update('calendarobjects')
  1363. ->set('deleted_at', $qb->createNamedParameter(time(), IQueryBuilder::PARAM_INT))
  1364. ->set('uri', $qb->createNamedParameter($newUri))
  1365. ->where(
  1366. $qb->expr()->eq('calendarid', $qb->createNamedParameter($calendarId)),
  1367. $qb->expr()->eq('calendartype', $qb->createNamedParameter($calendarType, IQueryBuilder::PARAM_INT), IQueryBuilder::PARAM_INT),
  1368. $qb->expr()->eq('uri', $qb->createNamedParameter($objectUri))
  1369. );
  1370. $markObjectDeletedQuery->executeStatement();
  1371. $calendarData = $this->getCalendarById($calendarId);
  1372. if ($calendarData !== null) {
  1373. $this->dispatcher->dispatchTyped(
  1374. new CalendarObjectMovedToTrashEvent(
  1375. $calendarId,
  1376. $calendarData,
  1377. $this->getShares($calendarId),
  1378. $data
  1379. )
  1380. );
  1381. }
  1382. }
  1383. $this->addChanges($calendarId, [$objectUri], 3, $calendarType);
  1384. }, $this->db);
  1385. }
  1386. /**
  1387. * @param mixed $objectData
  1388. *
  1389. * @throws Forbidden
  1390. */
  1391. public function restoreCalendarObject(array $objectData): void {
  1392. $this->cachedObjects = [];
  1393. $this->atomic(function () use ($objectData) {
  1394. $id = (int)$objectData['id'];
  1395. $restoreUri = str_replace('-deleted.ics', '.ics', $objectData['uri']);
  1396. $targetObject = $this->getCalendarObject(
  1397. $objectData['calendarid'],
  1398. $restoreUri
  1399. );
  1400. if ($targetObject !== null) {
  1401. throw new Forbidden("Can not restore calendar $id because a calendar object with the URI $restoreUri already exists");
  1402. }
  1403. $qb = $this->db->getQueryBuilder();
  1404. $update = $qb->update('calendarobjects')
  1405. ->set('uri', $qb->createNamedParameter($restoreUri))
  1406. ->set('deleted_at', $qb->createNamedParameter(null))
  1407. ->where($qb->expr()->eq('id', $qb->createNamedParameter($id, IQueryBuilder::PARAM_INT), IQueryBuilder::PARAM_INT));
  1408. $update->executeStatement();
  1409. // Make sure this change is tracked in the changes table
  1410. $qb2 = $this->db->getQueryBuilder();
  1411. $selectObject = $qb2->select('calendardata', 'uri', 'calendarid', 'calendartype')
  1412. ->selectAlias('componenttype', 'component')
  1413. ->from('calendarobjects')
  1414. ->where($qb2->expr()->eq('id', $qb2->createNamedParameter($id, IQueryBuilder::PARAM_INT), IQueryBuilder::PARAM_INT));
  1415. $result = $selectObject->executeQuery();
  1416. $row = $result->fetch();
  1417. $result->closeCursor();
  1418. if ($row === false) {
  1419. // Welp, this should possibly not have happened, but let's ignore
  1420. return;
  1421. }
  1422. $this->addChanges($row['calendarid'], [$row['uri']], 1, (int)$row['calendartype']);
  1423. $calendarRow = $this->getCalendarById((int)$row['calendarid']);
  1424. if ($calendarRow === null) {
  1425. throw new RuntimeException('Calendar object data that was just written can\'t be read back. Check your database configuration.');
  1426. }
  1427. $this->dispatcher->dispatchTyped(
  1428. new CalendarObjectRestoredEvent(
  1429. (int)$objectData['calendarid'],
  1430. $calendarRow,
  1431. $this->getShares((int)$row['calendarid']),
  1432. $row
  1433. )
  1434. );
  1435. }, $this->db);
  1436. }
  1437. /**
  1438. * Performs a calendar-query on the contents of this calendar.
  1439. *
  1440. * The calendar-query is defined in RFC4791 : CalDAV. Using the
  1441. * calendar-query it is possible for a client to request a specific set of
  1442. * object, based on contents of iCalendar properties, date-ranges and
  1443. * iCalendar component types (VTODO, VEVENT).
  1444. *
  1445. * This method should just return a list of (relative) urls that match this
  1446. * query.
  1447. *
  1448. * The list of filters are specified as an array. The exact array is
  1449. * documented by Sabre\CalDAV\CalendarQueryParser.
  1450. *
  1451. * Note that it is extremely likely that getCalendarObject for every path
  1452. * returned from this method will be called almost immediately after. You
  1453. * may want to anticipate this to speed up these requests.
  1454. *
  1455. * This method provides a default implementation, which parses *all* the
  1456. * iCalendar objects in the specified calendar.
  1457. *
  1458. * This default may well be good enough for personal use, and calendars
  1459. * that aren't very large. But if you anticipate high usage, big calendars
  1460. * or high loads, you are strongly advised to optimize certain paths.
  1461. *
  1462. * The best way to do so is override this method and to optimize
  1463. * specifically for 'common filters'.
  1464. *
  1465. * Requests that are extremely common are:
  1466. * * requests for just VEVENTS
  1467. * * requests for just VTODO
  1468. * * requests with a time-range-filter on either VEVENT or VTODO.
  1469. *
  1470. * ..and combinations of these requests. It may not be worth it to try to
  1471. * handle every possible situation and just rely on the (relatively
  1472. * easy to use) CalendarQueryValidator to handle the rest.
  1473. *
  1474. * Note that especially time-range-filters may be difficult to parse. A
  1475. * time-range filter specified on a VEVENT must for instance also handle
  1476. * recurrence rules correctly.
  1477. * A good example of how to interpret all these filters can also simply
  1478. * be found in Sabre\CalDAV\CalendarQueryFilter. This class is as correct
  1479. * as possible, so it gives you a good idea on what type of stuff you need
  1480. * to think of.
  1481. *
  1482. * @param mixed $calendarId
  1483. * @param array $filters
  1484. * @param int $calendarType
  1485. * @return array
  1486. */
  1487. public function calendarQuery($calendarId, array $filters, $calendarType = self::CALENDAR_TYPE_CALENDAR):array {
  1488. $componentType = null;
  1489. $requirePostFilter = true;
  1490. $timeRange = null;
  1491. // if no filters were specified, we don't need to filter after a query
  1492. if (!$filters['prop-filters'] && !$filters['comp-filters']) {
  1493. $requirePostFilter = false;
  1494. }
  1495. // Figuring out if there's a component filter
  1496. if (count($filters['comp-filters']) > 0 && !$filters['comp-filters'][0]['is-not-defined']) {
  1497. $componentType = $filters['comp-filters'][0]['name'];
  1498. // Checking if we need post-filters
  1499. if (!$filters['prop-filters'] && !$filters['comp-filters'][0]['comp-filters'] && !$filters['comp-filters'][0]['time-range'] && !$filters['comp-filters'][0]['prop-filters']) {
  1500. $requirePostFilter = false;
  1501. }
  1502. // There was a time-range filter
  1503. if ($componentType === 'VEVENT' && isset($filters['comp-filters'][0]['time-range']) && is_array($filters['comp-filters'][0]['time-range'])) {
  1504. $timeRange = $filters['comp-filters'][0]['time-range'];
  1505. // If start time OR the end time is not specified, we can do a
  1506. // 100% accurate mysql query.
  1507. if (!$filters['prop-filters'] && !$filters['comp-filters'][0]['comp-filters'] && !$filters['comp-filters'][0]['prop-filters'] && (!$timeRange['start'] || !$timeRange['end'])) {
  1508. $requirePostFilter = false;
  1509. }
  1510. }
  1511. }
  1512. $query = $this->db->getQueryBuilder();
  1513. $query->select(['id', 'uri', 'lastmodified', 'etag', 'calendarid', 'size', 'calendardata', 'componenttype', 'classification', 'deleted_at'])
  1514. ->from('calendarobjects')
  1515. ->where($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)))
  1516. ->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter($calendarType)))
  1517. ->andWhere($query->expr()->isNull('deleted_at'));
  1518. if ($componentType) {
  1519. $query->andWhere($query->expr()->eq('componenttype', $query->createNamedParameter($componentType)));
  1520. }
  1521. if ($timeRange && $timeRange['start']) {
  1522. $query->andWhere($query->expr()->gt('lastoccurence', $query->createNamedParameter($timeRange['start']->getTimeStamp())));
  1523. }
  1524. if ($timeRange && $timeRange['end']) {
  1525. $query->andWhere($query->expr()->lt('firstoccurence', $query->createNamedParameter($timeRange['end']->getTimeStamp())));
  1526. }
  1527. $stmt = $query->executeQuery();
  1528. $result = [];
  1529. while ($row = $stmt->fetch()) {
  1530. // if we leave it as a blob we can't read it both from the post filter and the rowToCalendarObject
  1531. if (isset($row['calendardata'])) {
  1532. $row['calendardata'] = $this->readBlob($row['calendardata']);
  1533. }
  1534. if ($requirePostFilter) {
  1535. // validateFilterForObject will parse the calendar data
  1536. // catch parsing errors
  1537. try {
  1538. $matches = $this->validateFilterForObject($row, $filters);
  1539. } catch (ParseException $ex) {
  1540. $this->logger->error('Caught parsing exception for calendar data. This usually indicates invalid calendar data. calendar-id:'.$calendarId.' uri:'.$row['uri'], [
  1541. 'app' => 'dav',
  1542. 'exception' => $ex,
  1543. ]);
  1544. continue;
  1545. } catch (InvalidDataException $ex) {
  1546. $this->logger->error('Caught invalid data exception for calendar data. This usually indicates invalid calendar data. calendar-id:'.$calendarId.' uri:'.$row['uri'], [
  1547. 'app' => 'dav',
  1548. 'exception' => $ex,
  1549. ]);
  1550. continue;
  1551. }
  1552. if (!$matches) {
  1553. continue;
  1554. }
  1555. }
  1556. $result[] = $row['uri'];
  1557. $key = $calendarId . '::' . $row['uri'] . '::' . $calendarType;
  1558. $this->cachedObjects[$key] = $this->rowToCalendarObject($row);
  1559. }
  1560. return $result;
  1561. }
  1562. /**
  1563. * custom Nextcloud search extension for CalDAV
  1564. *
  1565. * TODO - this should optionally cover cached calendar objects as well
  1566. *
  1567. * @param string $principalUri
  1568. * @param array $filters
  1569. * @param integer|null $limit
  1570. * @param integer|null $offset
  1571. * @return array
  1572. */
  1573. public function calendarSearch($principalUri, array $filters, $limit = null, $offset = null) {
  1574. return $this->atomic(function () use ($principalUri, $filters, $limit, $offset) {
  1575. $calendars = $this->getCalendarsForUser($principalUri);
  1576. $ownCalendars = [];
  1577. $sharedCalendars = [];
  1578. $uriMapper = [];
  1579. foreach ($calendars as $calendar) {
  1580. if ($calendar['{http://owncloud.org/ns}owner-principal'] === $principalUri) {
  1581. $ownCalendars[] = $calendar['id'];
  1582. } else {
  1583. $sharedCalendars[] = $calendar['id'];
  1584. }
  1585. $uriMapper[$calendar['id']] = $calendar['uri'];
  1586. }
  1587. if (count($ownCalendars) === 0 && count($sharedCalendars) === 0) {
  1588. return [];
  1589. }
  1590. $query = $this->db->getQueryBuilder();
  1591. // Calendar id expressions
  1592. $calendarExpressions = [];
  1593. foreach ($ownCalendars as $id) {
  1594. $calendarExpressions[] = $query->expr()->andX(
  1595. $query->expr()->eq('c.calendarid',
  1596. $query->createNamedParameter($id)),
  1597. $query->expr()->eq('c.calendartype',
  1598. $query->createNamedParameter(self::CALENDAR_TYPE_CALENDAR)));
  1599. }
  1600. foreach ($sharedCalendars as $id) {
  1601. $calendarExpressions[] = $query->expr()->andX(
  1602. $query->expr()->eq('c.calendarid',
  1603. $query->createNamedParameter($id)),
  1604. $query->expr()->eq('c.classification',
  1605. $query->createNamedParameter(self::CLASSIFICATION_PUBLIC)),
  1606. $query->expr()->eq('c.calendartype',
  1607. $query->createNamedParameter(self::CALENDAR_TYPE_CALENDAR)));
  1608. }
  1609. if (count($calendarExpressions) === 1) {
  1610. $calExpr = $calendarExpressions[0];
  1611. } else {
  1612. $calExpr = call_user_func_array([$query->expr(), 'orX'], $calendarExpressions);
  1613. }
  1614. // Component expressions
  1615. $compExpressions = [];
  1616. foreach ($filters['comps'] as $comp) {
  1617. $compExpressions[] = $query->expr()
  1618. ->eq('c.componenttype', $query->createNamedParameter($comp));
  1619. }
  1620. if (count($compExpressions) === 1) {
  1621. $compExpr = $compExpressions[0];
  1622. } else {
  1623. $compExpr = call_user_func_array([$query->expr(), 'orX'], $compExpressions);
  1624. }
  1625. if (!isset($filters['props'])) {
  1626. $filters['props'] = [];
  1627. }
  1628. if (!isset($filters['params'])) {
  1629. $filters['params'] = [];
  1630. }
  1631. $propParamExpressions = [];
  1632. foreach ($filters['props'] as $prop) {
  1633. $propParamExpressions[] = $query->expr()->andX(
  1634. $query->expr()->eq('i.name', $query->createNamedParameter($prop)),
  1635. $query->expr()->isNull('i.parameter')
  1636. );
  1637. }
  1638. foreach ($filters['params'] as $param) {
  1639. $propParamExpressions[] = $query->expr()->andX(
  1640. $query->expr()->eq('i.name', $query->createNamedParameter($param['property'])),
  1641. $query->expr()->eq('i.parameter', $query->createNamedParameter($param['parameter']))
  1642. );
  1643. }
  1644. if (count($propParamExpressions) === 1) {
  1645. $propParamExpr = $propParamExpressions[0];
  1646. } else {
  1647. $propParamExpr = call_user_func_array([$query->expr(), 'orX'], $propParamExpressions);
  1648. }
  1649. $query->select(['c.calendarid', 'c.uri'])
  1650. ->from($this->dbObjectPropertiesTable, 'i')
  1651. ->join('i', 'calendarobjects', 'c', $query->expr()->eq('i.objectid', 'c.id'))
  1652. ->where($calExpr)
  1653. ->andWhere($compExpr)
  1654. ->andWhere($propParamExpr)
  1655. ->andWhere($query->expr()->iLike('i.value',
  1656. $query->createNamedParameter('%'.$this->db->escapeLikeParameter($filters['search-term']).'%')))
  1657. ->andWhere($query->expr()->isNull('deleted_at'));
  1658. if ($offset) {
  1659. $query->setFirstResult($offset);
  1660. }
  1661. if ($limit) {
  1662. $query->setMaxResults($limit);
  1663. }
  1664. $stmt = $query->executeQuery();
  1665. $result = [];
  1666. while ($row = $stmt->fetch()) {
  1667. $path = $uriMapper[$row['calendarid']] . '/' . $row['uri'];
  1668. if (!in_array($path, $result)) {
  1669. $result[] = $path;
  1670. }
  1671. }
  1672. return $result;
  1673. }, $this->db);
  1674. }
  1675. /**
  1676. * used for Nextcloud's calendar API
  1677. *
  1678. * @param array $calendarInfo
  1679. * @param string $pattern
  1680. * @param array $searchProperties
  1681. * @param array $options
  1682. * @param integer|null $limit
  1683. * @param integer|null $offset
  1684. *
  1685. * @return array
  1686. */
  1687. public function search(
  1688. array $calendarInfo,
  1689. $pattern,
  1690. array $searchProperties,
  1691. array $options,
  1692. $limit,
  1693. $offset
  1694. ) {
  1695. $outerQuery = $this->db->getQueryBuilder();
  1696. $innerQuery = $this->db->getQueryBuilder();
  1697. if (isset($calendarInfo['source'])) {
  1698. $calendarType = self::CALENDAR_TYPE_SUBSCRIPTION;
  1699. } else {
  1700. $calendarType = self::CALENDAR_TYPE_CALENDAR;
  1701. }
  1702. $innerQuery->selectDistinct('op.objectid')
  1703. ->from($this->dbObjectPropertiesTable, 'op')
  1704. ->andWhere($innerQuery->expr()->eq('op.calendarid',
  1705. $outerQuery->createNamedParameter($calendarInfo['id'])))
  1706. ->andWhere($innerQuery->expr()->eq('op.calendartype',
  1707. $outerQuery->createNamedParameter($calendarType)));
  1708. $outerQuery->select('c.id', 'c.calendardata', 'c.componenttype', 'c.uid', 'c.uri')
  1709. ->from('calendarobjects', 'c')
  1710. ->where($outerQuery->expr()->isNull('deleted_at'));
  1711. // only return public items for shared calendars for now
  1712. if (isset($calendarInfo['{http://owncloud.org/ns}owner-principal']) === false || $calendarInfo['principaluri'] !== $calendarInfo['{http://owncloud.org/ns}owner-principal']) {
  1713. $outerQuery->andWhere($outerQuery->expr()->eq('c.classification',
  1714. $outerQuery->createNamedParameter(self::CLASSIFICATION_PUBLIC)));
  1715. }
  1716. if (!empty($searchProperties)) {
  1717. $or = [];
  1718. foreach ($searchProperties as $searchProperty) {
  1719. $or[] = $innerQuery->expr()->eq('op.name',
  1720. $outerQuery->createNamedParameter($searchProperty));
  1721. }
  1722. $innerQuery->andWhere($innerQuery->expr()->orX(...$or));
  1723. }
  1724. if ($pattern !== '') {
  1725. $innerQuery->andWhere($innerQuery->expr()->iLike('op.value',
  1726. $outerQuery->createNamedParameter('%' .
  1727. $this->db->escapeLikeParameter($pattern) . '%')));
  1728. }
  1729. $start = null;
  1730. $end = null;
  1731. $hasLimit = is_int($limit);
  1732. $hasTimeRange = false;
  1733. if (isset($options['timerange']['start']) && $options['timerange']['start'] instanceof DateTimeInterface) {
  1734. /** @var DateTimeInterface $start */
  1735. $start = $options['timerange']['start'];
  1736. $outerQuery->andWhere(
  1737. $outerQuery->expr()->gt(
  1738. 'lastoccurence',
  1739. $outerQuery->createNamedParameter($start->getTimestamp())
  1740. )
  1741. );
  1742. $hasTimeRange = true;
  1743. }
  1744. if (isset($options['timerange']['end']) && $options['timerange']['end'] instanceof DateTimeInterface) {
  1745. /** @var DateTimeInterface $end */
  1746. $end = $options['timerange']['end'];
  1747. $outerQuery->andWhere(
  1748. $outerQuery->expr()->lt(
  1749. 'firstoccurence',
  1750. $outerQuery->createNamedParameter($end->getTimestamp())
  1751. )
  1752. );
  1753. $hasTimeRange = true;
  1754. }
  1755. if (isset($options['uid'])) {
  1756. $outerQuery->andWhere($outerQuery->expr()->eq('uid', $outerQuery->createNamedParameter($options['uid'])));
  1757. }
  1758. if (!empty($options['types'])) {
  1759. $or = [];
  1760. foreach ($options['types'] as $type) {
  1761. $or[] = $outerQuery->expr()->eq('componenttype',
  1762. $outerQuery->createNamedParameter($type));
  1763. }
  1764. $outerQuery->andWhere($outerQuery->expr()->orX(...$or));
  1765. }
  1766. $outerQuery->andWhere($outerQuery->expr()->in('c.id', $outerQuery->createFunction($innerQuery->getSQL())));
  1767. // Without explicit order by its undefined in which order the SQL server returns the events.
  1768. // For the pagination with hasLimit and hasTimeRange, a stable ordering is helpful.
  1769. $outerQuery->addOrderBy('id');
  1770. $offset = (int)$offset;
  1771. $outerQuery->setFirstResult($offset);
  1772. $calendarObjects = [];
  1773. if ($hasLimit && $hasTimeRange) {
  1774. /**
  1775. * Event recurrences are evaluated at runtime because the database only knows the first and last occurrence.
  1776. *
  1777. * Given, a user created 8 events with a yearly reoccurrence and two for events tomorrow.
  1778. * The upcoming event widget asks the CalDAV backend for 7 events within the next 14 days.
  1779. *
  1780. * If limit 7 is applied to the SQL query, we find the 7 events with a yearly reoccurrence
  1781. * and discard the events after evaluating the reoccurrence rules because they are not due within
  1782. * the next 14 days and end up with an empty result even if there are two events to show.
  1783. *
  1784. * The workaround for search requests with a limit and time range is asking for more row than requested
  1785. * and retrying if we have not reached the limit.
  1786. *
  1787. * 25 rows and 3 retries is entirely arbitrary.
  1788. */
  1789. $maxResults = (int)max($limit, 25);
  1790. $outerQuery->setMaxResults($maxResults);
  1791. for ($attempt = $objectsCount = 0; $attempt < 3 && $objectsCount < $limit; $attempt++) {
  1792. $objectsCount = array_push($calendarObjects, ...$this->searchCalendarObjects($outerQuery, $start, $end));
  1793. $outerQuery->setFirstResult($offset += $maxResults);
  1794. }
  1795. $calendarObjects = array_slice($calendarObjects, 0, $limit, false);
  1796. } else {
  1797. $outerQuery->setMaxResults($limit);
  1798. $calendarObjects = $this->searchCalendarObjects($outerQuery, $start, $end);
  1799. }
  1800. $calendarObjects = array_map(function ($o) use ($options) {
  1801. $calendarData = Reader::read($o['calendardata']);
  1802. // Expand recurrences if an explicit time range is requested
  1803. if ($calendarData instanceof VCalendar
  1804. && isset($options['timerange']['start'], $options['timerange']['end'])) {
  1805. $calendarData = $calendarData->expand(
  1806. $options['timerange']['start'],
  1807. $options['timerange']['end'],
  1808. );
  1809. }
  1810. $comps = $calendarData->getComponents();
  1811. $objects = [];
  1812. $timezones = [];
  1813. foreach ($comps as $comp) {
  1814. if ($comp instanceof VTimeZone) {
  1815. $timezones[] = $comp;
  1816. } else {
  1817. $objects[] = $comp;
  1818. }
  1819. }
  1820. return [
  1821. 'id' => $o['id'],
  1822. 'type' => $o['componenttype'],
  1823. 'uid' => $o['uid'],
  1824. 'uri' => $o['uri'],
  1825. 'objects' => array_map(function ($c) {
  1826. return $this->transformSearchData($c);
  1827. }, $objects),
  1828. 'timezones' => array_map(function ($c) {
  1829. return $this->transformSearchData($c);
  1830. }, $timezones),
  1831. ];
  1832. }, $calendarObjects);
  1833. usort($calendarObjects, function (array $a, array $b) {
  1834. /** @var DateTimeImmutable $startA */
  1835. $startA = $a['objects'][0]['DTSTART'][0] ?? new DateTimeImmutable(self::MAX_DATE);
  1836. /** @var DateTimeImmutable $startB */
  1837. $startB = $b['objects'][0]['DTSTART'][0] ?? new DateTimeImmutable(self::MAX_DATE);
  1838. return $startA->getTimestamp() <=> $startB->getTimestamp();
  1839. });
  1840. return $calendarObjects;
  1841. }
  1842. private function searchCalendarObjects(IQueryBuilder $query, DateTimeInterface|null $start, DateTimeInterface|null $end): array {
  1843. $calendarObjects = [];
  1844. $filterByTimeRange = ($start instanceof DateTimeInterface) || ($end instanceof DateTimeInterface);
  1845. $result = $query->executeQuery();
  1846. while (($row = $result->fetch()) !== false) {
  1847. if ($filterByTimeRange === false) {
  1848. // No filter required
  1849. $calendarObjects[] = $row;
  1850. continue;
  1851. }
  1852. $isValid = $this->validateFilterForObject($row, [
  1853. 'name' => 'VCALENDAR',
  1854. 'comp-filters' => [
  1855. [
  1856. 'name' => 'VEVENT',
  1857. 'comp-filters' => [],
  1858. 'prop-filters' => [],
  1859. 'is-not-defined' => false,
  1860. 'time-range' => [
  1861. 'start' => $start,
  1862. 'end' => $end,
  1863. ],
  1864. ],
  1865. ],
  1866. 'prop-filters' => [],
  1867. 'is-not-defined' => false,
  1868. 'time-range' => null,
  1869. ]);
  1870. if (is_resource($row['calendardata'])) {
  1871. // Put the stream back to the beginning so it can be read another time
  1872. rewind($row['calendardata']);
  1873. }
  1874. if ($isValid) {
  1875. $calendarObjects[] = $row;
  1876. }
  1877. }
  1878. $result->closeCursor();
  1879. return $calendarObjects;
  1880. }
  1881. /**
  1882. * @param Component $comp
  1883. * @return array
  1884. */
  1885. private function transformSearchData(Component $comp) {
  1886. $data = [];
  1887. /** @var Component[] $subComponents */
  1888. $subComponents = $comp->getComponents();
  1889. /** @var Property[] $properties */
  1890. $properties = array_filter($comp->children(), function ($c) {
  1891. return $c instanceof Property;
  1892. });
  1893. $validationRules = $comp->getValidationRules();
  1894. foreach ($subComponents as $subComponent) {
  1895. $name = $subComponent->name;
  1896. if (!isset($data[$name])) {
  1897. $data[$name] = [];
  1898. }
  1899. $data[$name][] = $this->transformSearchData($subComponent);
  1900. }
  1901. foreach ($properties as $property) {
  1902. $name = $property->name;
  1903. if (!isset($validationRules[$name])) {
  1904. $validationRules[$name] = '*';
  1905. }
  1906. $rule = $validationRules[$property->name];
  1907. if ($rule === '+' || $rule === '*') { // multiple
  1908. if (!isset($data[$name])) {
  1909. $data[$name] = [];
  1910. }
  1911. $data[$name][] = $this->transformSearchProperty($property);
  1912. } else { // once
  1913. $data[$name] = $this->transformSearchProperty($property);
  1914. }
  1915. }
  1916. return $data;
  1917. }
  1918. /**
  1919. * @param Property $prop
  1920. * @return array
  1921. */
  1922. private function transformSearchProperty(Property $prop) {
  1923. // No need to check Date, as it extends DateTime
  1924. if ($prop instanceof Property\ICalendar\DateTime) {
  1925. $value = $prop->getDateTime();
  1926. } else {
  1927. $value = $prop->getValue();
  1928. }
  1929. return [
  1930. $value,
  1931. $prop->parameters()
  1932. ];
  1933. }
  1934. /**
  1935. * @param string $principalUri
  1936. * @param string $pattern
  1937. * @param array $componentTypes
  1938. * @param array $searchProperties
  1939. * @param array $searchParameters
  1940. * @param array $options
  1941. * @return array
  1942. */
  1943. public function searchPrincipalUri(string $principalUri,
  1944. string $pattern,
  1945. array $componentTypes,
  1946. array $searchProperties,
  1947. array $searchParameters,
  1948. array $options = []
  1949. ): array {
  1950. return $this->atomic(function () use ($principalUri, $pattern, $componentTypes, $searchProperties, $searchParameters, $options) {
  1951. $escapePattern = !\array_key_exists('escape_like_param', $options) || $options['escape_like_param'] !== false;
  1952. $calendarObjectIdQuery = $this->db->getQueryBuilder();
  1953. $calendarOr = [];
  1954. $searchOr = [];
  1955. // Fetch calendars and subscription
  1956. $calendars = $this->getCalendarsForUser($principalUri);
  1957. $subscriptions = $this->getSubscriptionsForUser($principalUri);
  1958. foreach ($calendars as $calendar) {
  1959. $calendarAnd = $calendarObjectIdQuery->expr()->andX(
  1960. $calendarObjectIdQuery->expr()->eq('cob.calendarid', $calendarObjectIdQuery->createNamedParameter((int)$calendar['id'])),
  1961. $calendarObjectIdQuery->expr()->eq('cob.calendartype', $calendarObjectIdQuery->createNamedParameter(self::CALENDAR_TYPE_CALENDAR)),
  1962. );
  1963. // If it's shared, limit search to public events
  1964. if (isset($calendar['{http://owncloud.org/ns}owner-principal'])
  1965. && $calendar['principaluri'] !== $calendar['{http://owncloud.org/ns}owner-principal']) {
  1966. $calendarAnd->add($calendarObjectIdQuery->expr()->eq('co.classification', $calendarObjectIdQuery->createNamedParameter(self::CLASSIFICATION_PUBLIC)));
  1967. }
  1968. $calendarOr[] = $calendarAnd;
  1969. }
  1970. foreach ($subscriptions as $subscription) {
  1971. $subscriptionAnd = $calendarObjectIdQuery->expr()->andX(
  1972. $calendarObjectIdQuery->expr()->eq('cob.calendarid', $calendarObjectIdQuery->createNamedParameter((int)$subscription['id'])),
  1973. $calendarObjectIdQuery->expr()->eq('cob.calendartype', $calendarObjectIdQuery->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)),
  1974. );
  1975. // If it's shared, limit search to public events
  1976. if (isset($subscription['{http://owncloud.org/ns}owner-principal'])
  1977. && $subscription['principaluri'] !== $subscription['{http://owncloud.org/ns}owner-principal']) {
  1978. $subscriptionAnd->add($calendarObjectIdQuery->expr()->eq('co.classification', $calendarObjectIdQuery->createNamedParameter(self::CLASSIFICATION_PUBLIC)));
  1979. }
  1980. $calendarOr[] = $subscriptionAnd;
  1981. }
  1982. foreach ($searchProperties as $property) {
  1983. $propertyAnd = $calendarObjectIdQuery->expr()->andX(
  1984. $calendarObjectIdQuery->expr()->eq('cob.name', $calendarObjectIdQuery->createNamedParameter($property, IQueryBuilder::PARAM_STR)),
  1985. $calendarObjectIdQuery->expr()->isNull('cob.parameter'),
  1986. );
  1987. $searchOr[] = $propertyAnd;
  1988. }
  1989. foreach ($searchParameters as $property => $parameter) {
  1990. $parameterAnd = $calendarObjectIdQuery->expr()->andX(
  1991. $calendarObjectIdQuery->expr()->eq('cob.name', $calendarObjectIdQuery->createNamedParameter($property, IQueryBuilder::PARAM_STR)),
  1992. $calendarObjectIdQuery->expr()->eq('cob.parameter', $calendarObjectIdQuery->createNamedParameter($parameter, IQueryBuilder::PARAM_STR_ARRAY)),
  1993. );
  1994. $searchOr[] = $parameterAnd;
  1995. }
  1996. if (empty($calendarOr)) {
  1997. return [];
  1998. }
  1999. if (empty($searchOr)) {
  2000. return [];
  2001. }
  2002. $calendarObjectIdQuery->selectDistinct('cob.objectid')
  2003. ->from($this->dbObjectPropertiesTable, 'cob')
  2004. ->leftJoin('cob', 'calendarobjects', 'co', $calendarObjectIdQuery->expr()->eq('co.id', 'cob.objectid'))
  2005. ->andWhere($calendarObjectIdQuery->expr()->in('co.componenttype', $calendarObjectIdQuery->createNamedParameter($componentTypes, IQueryBuilder::PARAM_STR_ARRAY)))
  2006. ->andWhere($calendarObjectIdQuery->expr()->orX(...$calendarOr))
  2007. ->andWhere($calendarObjectIdQuery->expr()->orX(...$searchOr))
  2008. ->andWhere($calendarObjectIdQuery->expr()->isNull('deleted_at'));
  2009. if ($pattern !== '') {
  2010. if (!$escapePattern) {
  2011. $calendarObjectIdQuery->andWhere($calendarObjectIdQuery->expr()->ilike('cob.value', $calendarObjectIdQuery->createNamedParameter($pattern)));
  2012. } else {
  2013. $calendarObjectIdQuery->andWhere($calendarObjectIdQuery->expr()->ilike('cob.value', $calendarObjectIdQuery->createNamedParameter('%' . $this->db->escapeLikeParameter($pattern) . '%')));
  2014. }
  2015. }
  2016. if (isset($options['limit'])) {
  2017. $calendarObjectIdQuery->setMaxResults($options['limit']);
  2018. }
  2019. if (isset($options['offset'])) {
  2020. $calendarObjectIdQuery->setFirstResult($options['offset']);
  2021. }
  2022. if (isset($options['timerange'])) {
  2023. if (isset($options['timerange']['start']) && $options['timerange']['start'] instanceof DateTimeInterface) {
  2024. $calendarObjectIdQuery->andWhere($calendarObjectIdQuery->expr()->gt(
  2025. 'lastoccurence',
  2026. $calendarObjectIdQuery->createNamedParameter($options['timerange']['start']->getTimeStamp()),
  2027. ));
  2028. }
  2029. if (isset($options['timerange']['end']) && $options['timerange']['end'] instanceof DateTimeInterface) {
  2030. $calendarObjectIdQuery->andWhere($calendarObjectIdQuery->expr()->lt(
  2031. 'firstoccurence',
  2032. $calendarObjectIdQuery->createNamedParameter($options['timerange']['end']->getTimeStamp()),
  2033. ));
  2034. }
  2035. }
  2036. $result = $calendarObjectIdQuery->executeQuery();
  2037. $matches = [];
  2038. while (($row = $result->fetch()) !== false) {
  2039. $matches[] = (int)$row['objectid'];
  2040. }
  2041. $result->closeCursor();
  2042. $query = $this->db->getQueryBuilder();
  2043. $query->select('calendardata', 'uri', 'calendarid', 'calendartype')
  2044. ->from('calendarobjects')
  2045. ->where($query->expr()->in('id', $query->createNamedParameter($matches, IQueryBuilder::PARAM_INT_ARRAY)));
  2046. $result = $query->executeQuery();
  2047. $calendarObjects = [];
  2048. while (($array = $result->fetch()) !== false) {
  2049. $array['calendarid'] = (int)$array['calendarid'];
  2050. $array['calendartype'] = (int)$array['calendartype'];
  2051. $array['calendardata'] = $this->readBlob($array['calendardata']);
  2052. $calendarObjects[] = $array;
  2053. }
  2054. $result->closeCursor();
  2055. return $calendarObjects;
  2056. }, $this->db);
  2057. }
  2058. /**
  2059. * Searches through all of a users calendars and calendar objects to find
  2060. * an object with a specific UID.
  2061. *
  2062. * This method should return the path to this object, relative to the
  2063. * calendar home, so this path usually only contains two parts:
  2064. *
  2065. * calendarpath/objectpath.ics
  2066. *
  2067. * If the uid is not found, return null.
  2068. *
  2069. * This method should only consider * objects that the principal owns, so
  2070. * any calendars owned by other principals that also appear in this
  2071. * collection should be ignored.
  2072. *
  2073. * @param string $principalUri
  2074. * @param string $uid
  2075. * @return string|null
  2076. */
  2077. public function getCalendarObjectByUID($principalUri, $uid) {
  2078. $query = $this->db->getQueryBuilder();
  2079. $query->selectAlias('c.uri', 'calendaruri')->selectAlias('co.uri', 'objecturi')
  2080. ->from('calendarobjects', 'co')
  2081. ->leftJoin('co', 'calendars', 'c', $query->expr()->eq('co.calendarid', 'c.id'))
  2082. ->where($query->expr()->eq('c.principaluri', $query->createNamedParameter($principalUri)))
  2083. ->andWhere($query->expr()->eq('co.uid', $query->createNamedParameter($uid)))
  2084. ->andWhere($query->expr()->isNull('co.deleted_at'));
  2085. $stmt = $query->executeQuery();
  2086. $row = $stmt->fetch();
  2087. $stmt->closeCursor();
  2088. if ($row) {
  2089. return $row['calendaruri'] . '/' . $row['objecturi'];
  2090. }
  2091. return null;
  2092. }
  2093. public function getCalendarObjectById(string $principalUri, int $id): ?array {
  2094. $query = $this->db->getQueryBuilder();
  2095. $query->select(['co.id', 'co.uri', 'co.lastmodified', 'co.etag', 'co.calendarid', 'co.size', 'co.calendardata', 'co.componenttype', 'co.classification', 'co.deleted_at'])
  2096. ->selectAlias('c.uri', 'calendaruri')
  2097. ->from('calendarobjects', 'co')
  2098. ->join('co', 'calendars', 'c', $query->expr()->eq('c.id', 'co.calendarid', IQueryBuilder::PARAM_INT))
  2099. ->where($query->expr()->eq('c.principaluri', $query->createNamedParameter($principalUri)))
  2100. ->andWhere($query->expr()->eq('co.id', $query->createNamedParameter($id, IQueryBuilder::PARAM_INT), IQueryBuilder::PARAM_INT));
  2101. $stmt = $query->executeQuery();
  2102. $row = $stmt->fetch();
  2103. $stmt->closeCursor();
  2104. if (!$row) {
  2105. return null;
  2106. }
  2107. return [
  2108. 'id' => $row['id'],
  2109. 'uri' => $row['uri'],
  2110. 'lastmodified' => $row['lastmodified'],
  2111. 'etag' => '"' . $row['etag'] . '"',
  2112. 'calendarid' => $row['calendarid'],
  2113. 'calendaruri' => $row['calendaruri'],
  2114. 'size' => (int)$row['size'],
  2115. 'calendardata' => $this->readBlob($row['calendardata']),
  2116. 'component' => strtolower($row['componenttype']),
  2117. 'classification' => (int)$row['classification'],
  2118. 'deleted_at' => isset($row['deleted_at']) ? ((int)$row['deleted_at']) : null,
  2119. ];
  2120. }
  2121. /**
  2122. * The getChanges method returns all the changes that have happened, since
  2123. * the specified syncToken in the specified calendar.
  2124. *
  2125. * This function should return an array, such as the following:
  2126. *
  2127. * [
  2128. * 'syncToken' => 'The current synctoken',
  2129. * 'added' => [
  2130. * 'new.txt',
  2131. * ],
  2132. * 'modified' => [
  2133. * 'modified.txt',
  2134. * ],
  2135. * 'deleted' => [
  2136. * 'foo.php.bak',
  2137. * 'old.txt'
  2138. * ]
  2139. * );
  2140. *
  2141. * The returned syncToken property should reflect the *current* syncToken
  2142. * of the calendar, as reported in the {http://sabredav.org/ns}sync-token
  2143. * property This is * needed here too, to ensure the operation is atomic.
  2144. *
  2145. * If the $syncToken argument is specified as null, this is an initial
  2146. * sync, and all members should be reported.
  2147. *
  2148. * The modified property is an array of nodenames that have changed since
  2149. * the last token.
  2150. *
  2151. * The deleted property is an array with nodenames, that have been deleted
  2152. * from collection.
  2153. *
  2154. * The $syncLevel argument is basically the 'depth' of the report. If it's
  2155. * 1, you only have to report changes that happened only directly in
  2156. * immediate descendants. If it's 2, it should also include changes from
  2157. * the nodes below the child collections. (grandchildren)
  2158. *
  2159. * The $limit argument allows a client to specify how many results should
  2160. * be returned at most. If the limit is not specified, it should be treated
  2161. * as infinite.
  2162. *
  2163. * If the limit (infinite or not) is higher than you're willing to return,
  2164. * you should throw a Sabre\DAV\Exception\TooMuchMatches() exception.
  2165. *
  2166. * If the syncToken is expired (due to data cleanup) or unknown, you must
  2167. * return null.
  2168. *
  2169. * The limit is 'suggestive'. You are free to ignore it.
  2170. *
  2171. * @param string $calendarId
  2172. * @param string $syncToken
  2173. * @param int $syncLevel
  2174. * @param int|null $limit
  2175. * @param int $calendarType
  2176. * @return ?array
  2177. */
  2178. public function getChangesForCalendar($calendarId, $syncToken, $syncLevel, $limit = null, $calendarType = self::CALENDAR_TYPE_CALENDAR) {
  2179. $table = $calendarType === self::CALENDAR_TYPE_CALENDAR ? 'calendars': 'calendarsubscriptions';
  2180. return $this->atomic(function () use ($calendarId, $syncToken, $syncLevel, $limit, $calendarType, $table) {
  2181. // Current synctoken
  2182. $qb = $this->db->getQueryBuilder();
  2183. $qb->select('synctoken')
  2184. ->from($table)
  2185. ->where(
  2186. $qb->expr()->eq('id', $qb->createNamedParameter($calendarId))
  2187. );
  2188. $stmt = $qb->executeQuery();
  2189. $currentToken = $stmt->fetchOne();
  2190. $initialSync = !is_numeric($syncToken);
  2191. if ($currentToken === false) {
  2192. return null;
  2193. }
  2194. // evaluate if this is a initial sync and construct appropriate command
  2195. if ($initialSync) {
  2196. $qb = $this->db->getQueryBuilder();
  2197. $qb->select('uri')
  2198. ->from('calendarobjects')
  2199. ->where($qb->expr()->eq('calendarid', $qb->createNamedParameter($calendarId)))
  2200. ->andWhere($qb->expr()->eq('calendartype', $qb->createNamedParameter($calendarType)))
  2201. ->andWhere($qb->expr()->isNull('deleted_at'));
  2202. } else {
  2203. $qb = $this->db->getQueryBuilder();
  2204. $qb->select('uri', $qb->func()->max('operation'))
  2205. ->from('calendarchanges')
  2206. ->where($qb->expr()->eq('calendarid', $qb->createNamedParameter($calendarId)))
  2207. ->andWhere($qb->expr()->eq('calendartype', $qb->createNamedParameter($calendarType)))
  2208. ->andWhere($qb->expr()->gte('synctoken', $qb->createNamedParameter($syncToken)))
  2209. ->andWhere($qb->expr()->lt('synctoken', $qb->createNamedParameter($currentToken)))
  2210. ->groupBy('uri');
  2211. }
  2212. // evaluate if limit exists
  2213. if (is_numeric($limit)) {
  2214. $qb->setMaxResults($limit);
  2215. }
  2216. // execute command
  2217. $stmt = $qb->executeQuery();
  2218. // build results
  2219. $result = ['syncToken' => $currentToken, 'added' => [], 'modified' => [], 'deleted' => []];
  2220. // retrieve results
  2221. if ($initialSync) {
  2222. $result['added'] = $stmt->fetchAll(\PDO::FETCH_COLUMN);
  2223. } else {
  2224. // \PDO::FETCH_NUM is needed due to the inconsistent field names
  2225. // produced by doctrine for MAX() with different databases
  2226. while ($entry = $stmt->fetch(\PDO::FETCH_NUM)) {
  2227. // assign uri (column 0) to appropriate mutation based on operation (column 1)
  2228. // forced (int) is needed as doctrine with OCI returns the operation field as string not integer
  2229. match ((int)$entry[1]) {
  2230. 1 => $result['added'][] = $entry[0],
  2231. 2 => $result['modified'][] = $entry[0],
  2232. 3 => $result['deleted'][] = $entry[0],
  2233. default => $this->logger->debug('Unknown calendar change operation detected')
  2234. };
  2235. }
  2236. }
  2237. $stmt->closeCursor();
  2238. return $result;
  2239. }, $this->db);
  2240. }
  2241. /**
  2242. * Returns a list of subscriptions for a principal.
  2243. *
  2244. * Every subscription is an array with the following keys:
  2245. * * id, a unique id that will be used by other functions to modify the
  2246. * subscription. This can be the same as the uri or a database key.
  2247. * * uri. This is just the 'base uri' or 'filename' of the subscription.
  2248. * * principaluri. The owner of the subscription. Almost always the same as
  2249. * principalUri passed to this method.
  2250. *
  2251. * Furthermore, all the subscription info must be returned too:
  2252. *
  2253. * 1. {DAV:}displayname
  2254. * 2. {http://apple.com/ns/ical/}refreshrate
  2255. * 3. {http://calendarserver.org/ns/}subscribed-strip-todos (omit if todos
  2256. * should not be stripped).
  2257. * 4. {http://calendarserver.org/ns/}subscribed-strip-alarms (omit if alarms
  2258. * should not be stripped).
  2259. * 5. {http://calendarserver.org/ns/}subscribed-strip-attachments (omit if
  2260. * attachments should not be stripped).
  2261. * 6. {http://calendarserver.org/ns/}source (Must be a
  2262. * Sabre\DAV\Property\Href).
  2263. * 7. {http://apple.com/ns/ical/}calendar-color
  2264. * 8. {http://apple.com/ns/ical/}calendar-order
  2265. * 9. {urn:ietf:params:xml:ns:caldav}supported-calendar-component-set
  2266. * (should just be an instance of
  2267. * Sabre\CalDAV\Property\SupportedCalendarComponentSet, with a bunch of
  2268. * default components).
  2269. *
  2270. * @param string $principalUri
  2271. * @return array
  2272. */
  2273. public function getSubscriptionsForUser($principalUri) {
  2274. $fields = array_column($this->subscriptionPropertyMap, 0);
  2275. $fields[] = 'id';
  2276. $fields[] = 'uri';
  2277. $fields[] = 'source';
  2278. $fields[] = 'principaluri';
  2279. $fields[] = 'lastmodified';
  2280. $fields[] = 'synctoken';
  2281. $query = $this->db->getQueryBuilder();
  2282. $query->select($fields)
  2283. ->from('calendarsubscriptions')
  2284. ->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
  2285. ->orderBy('calendarorder', 'asc');
  2286. $stmt = $query->executeQuery();
  2287. $subscriptions = [];
  2288. while ($row = $stmt->fetch()) {
  2289. $subscription = [
  2290. 'id' => $row['id'],
  2291. 'uri' => $row['uri'],
  2292. 'principaluri' => $row['principaluri'],
  2293. 'source' => $row['source'],
  2294. 'lastmodified' => $row['lastmodified'],
  2295. '{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet(['VTODO', 'VEVENT']),
  2296. '{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
  2297. ];
  2298. $subscriptions[] = $this->rowToSubscription($row, $subscription);
  2299. }
  2300. return $subscriptions;
  2301. }
  2302. /**
  2303. * Creates a new subscription for a principal.
  2304. *
  2305. * If the creation was a success, an id must be returned that can be used to reference
  2306. * this subscription in other methods, such as updateSubscription.
  2307. *
  2308. * @param string $principalUri
  2309. * @param string $uri
  2310. * @param array $properties
  2311. * @return mixed
  2312. */
  2313. public function createSubscription($principalUri, $uri, array $properties) {
  2314. if (!isset($properties['{http://calendarserver.org/ns/}source'])) {
  2315. throw new Forbidden('The {http://calendarserver.org/ns/}source property is required when creating subscriptions');
  2316. }
  2317. $values = [
  2318. 'principaluri' => $principalUri,
  2319. 'uri' => $uri,
  2320. 'source' => $properties['{http://calendarserver.org/ns/}source']->getHref(),
  2321. 'lastmodified' => time(),
  2322. ];
  2323. $propertiesBoolean = ['striptodos', 'stripalarms', 'stripattachments'];
  2324. foreach ($this->subscriptionPropertyMap as $xmlName => [$dbName, $type]) {
  2325. if (array_key_exists($xmlName, $properties)) {
  2326. $values[$dbName] = $properties[$xmlName];
  2327. if (in_array($dbName, $propertiesBoolean)) {
  2328. $values[$dbName] = true;
  2329. }
  2330. }
  2331. }
  2332. [$subscriptionId, $subscriptionRow] = $this->atomic(function () use ($values) {
  2333. $valuesToInsert = [];
  2334. $query = $this->db->getQueryBuilder();
  2335. foreach (array_keys($values) as $name) {
  2336. $valuesToInsert[$name] = $query->createNamedParameter($values[$name]);
  2337. }
  2338. $query->insert('calendarsubscriptions')
  2339. ->values($valuesToInsert)
  2340. ->executeStatement();
  2341. $subscriptionId = $query->getLastInsertId();
  2342. $subscriptionRow = $this->getSubscriptionById($subscriptionId);
  2343. return [$subscriptionId, $subscriptionRow];
  2344. }, $this->db);
  2345. $this->dispatcher->dispatchTyped(new SubscriptionCreatedEvent($subscriptionId, $subscriptionRow));
  2346. return $subscriptionId;
  2347. }
  2348. /**
  2349. * Updates a subscription
  2350. *
  2351. * The list of mutations is stored in a Sabre\DAV\PropPatch object.
  2352. * To do the actual updates, you must tell this object which properties
  2353. * you're going to process with the handle() method.
  2354. *
  2355. * Calling the handle method is like telling the PropPatch object "I
  2356. * promise I can handle updating this property".
  2357. *
  2358. * Read the PropPatch documentation for more info and examples.
  2359. *
  2360. * @param mixed $subscriptionId
  2361. * @param PropPatch $propPatch
  2362. * @return void
  2363. */
  2364. public function updateSubscription($subscriptionId, PropPatch $propPatch) {
  2365. $supportedProperties = array_keys($this->subscriptionPropertyMap);
  2366. $supportedProperties[] = '{http://calendarserver.org/ns/}source';
  2367. $propPatch->handle($supportedProperties, function ($mutations) use ($subscriptionId) {
  2368. $newValues = [];
  2369. foreach ($mutations as $propertyName => $propertyValue) {
  2370. if ($propertyName === '{http://calendarserver.org/ns/}source') {
  2371. $newValues['source'] = $propertyValue->getHref();
  2372. } else {
  2373. $fieldName = $this->subscriptionPropertyMap[$propertyName][0];
  2374. $newValues[$fieldName] = $propertyValue;
  2375. }
  2376. }
  2377. $subscriptionRow = $this->atomic(function () use ($subscriptionId, $newValues) {
  2378. $query = $this->db->getQueryBuilder();
  2379. $query->update('calendarsubscriptions')
  2380. ->set('lastmodified', $query->createNamedParameter(time()));
  2381. foreach ($newValues as $fieldName => $value) {
  2382. $query->set($fieldName, $query->createNamedParameter($value));
  2383. }
  2384. $query->where($query->expr()->eq('id', $query->createNamedParameter($subscriptionId)))
  2385. ->executeStatement();
  2386. return $this->getSubscriptionById($subscriptionId);
  2387. }, $this->db);
  2388. $this->dispatcher->dispatchTyped(new SubscriptionUpdatedEvent((int)$subscriptionId, $subscriptionRow, [], $mutations));
  2389. return true;
  2390. });
  2391. }
  2392. /**
  2393. * Deletes a subscription.
  2394. *
  2395. * @param mixed $subscriptionId
  2396. * @return void
  2397. */
  2398. public function deleteSubscription($subscriptionId) {
  2399. $this->atomic(function () use ($subscriptionId) {
  2400. $subscriptionRow = $this->getSubscriptionById($subscriptionId);
  2401. $query = $this->db->getQueryBuilder();
  2402. $query->delete('calendarsubscriptions')
  2403. ->where($query->expr()->eq('id', $query->createNamedParameter($subscriptionId)))
  2404. ->executeStatement();
  2405. $query = $this->db->getQueryBuilder();
  2406. $query->delete('calendarobjects')
  2407. ->where($query->expr()->eq('calendarid', $query->createNamedParameter($subscriptionId)))
  2408. ->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)))
  2409. ->executeStatement();
  2410. $query->delete('calendarchanges')
  2411. ->where($query->expr()->eq('calendarid', $query->createNamedParameter($subscriptionId)))
  2412. ->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)))
  2413. ->executeStatement();
  2414. $query->delete($this->dbObjectPropertiesTable)
  2415. ->where($query->expr()->eq('calendarid', $query->createNamedParameter($subscriptionId)))
  2416. ->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)))
  2417. ->executeStatement();
  2418. if ($subscriptionRow) {
  2419. $this->dispatcher->dispatchTyped(new SubscriptionDeletedEvent((int)$subscriptionId, $subscriptionRow, []));
  2420. }
  2421. }, $this->db);
  2422. }
  2423. /**
  2424. * Returns a single scheduling object for the inbox collection.
  2425. *
  2426. * The returned array should contain the following elements:
  2427. * * uri - A unique basename for the object. This will be used to
  2428. * construct a full uri.
  2429. * * calendardata - The iCalendar object
  2430. * * lastmodified - The last modification date. Can be an int for a unix
  2431. * timestamp, or a PHP DateTime object.
  2432. * * etag - A unique token that must change if the object changed.
  2433. * * size - The size of the object, in bytes.
  2434. *
  2435. * @param string $principalUri
  2436. * @param string $objectUri
  2437. * @return array
  2438. */
  2439. public function getSchedulingObject($principalUri, $objectUri) {
  2440. $query = $this->db->getQueryBuilder();
  2441. $stmt = $query->select(['uri', 'calendardata', 'lastmodified', 'etag', 'size'])
  2442. ->from('schedulingobjects')
  2443. ->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
  2444. ->andWhere($query->expr()->eq('uri', $query->createNamedParameter($objectUri)))
  2445. ->executeQuery();
  2446. $row = $stmt->fetch();
  2447. if (!$row) {
  2448. return null;
  2449. }
  2450. return [
  2451. 'uri' => $row['uri'],
  2452. 'calendardata' => $row['calendardata'],
  2453. 'lastmodified' => $row['lastmodified'],
  2454. 'etag' => '"' . $row['etag'] . '"',
  2455. 'size' => (int)$row['size'],
  2456. ];
  2457. }
  2458. /**
  2459. * Returns all scheduling objects for the inbox collection.
  2460. *
  2461. * These objects should be returned as an array. Every item in the array
  2462. * should follow the same structure as returned from getSchedulingObject.
  2463. *
  2464. * The main difference is that 'calendardata' is optional.
  2465. *
  2466. * @param string $principalUri
  2467. * @return array
  2468. */
  2469. public function getSchedulingObjects($principalUri) {
  2470. $query = $this->db->getQueryBuilder();
  2471. $stmt = $query->select(['uri', 'calendardata', 'lastmodified', 'etag', 'size'])
  2472. ->from('schedulingobjects')
  2473. ->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
  2474. ->executeQuery();
  2475. $results = [];
  2476. while (($row = $stmt->fetch()) !== false) {
  2477. $results[] = [
  2478. 'calendardata' => $row['calendardata'],
  2479. 'uri' => $row['uri'],
  2480. 'lastmodified' => $row['lastmodified'],
  2481. 'etag' => '"' . $row['etag'] . '"',
  2482. 'size' => (int)$row['size'],
  2483. ];
  2484. }
  2485. $stmt->closeCursor();
  2486. return $results;
  2487. }
  2488. /**
  2489. * Deletes a scheduling object from the inbox collection.
  2490. *
  2491. * @param string $principalUri
  2492. * @param string $objectUri
  2493. * @return void
  2494. */
  2495. public function deleteSchedulingObject($principalUri, $objectUri) {
  2496. $this->cachedObjects = [];
  2497. $query = $this->db->getQueryBuilder();
  2498. $query->delete('schedulingobjects')
  2499. ->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
  2500. ->andWhere($query->expr()->eq('uri', $query->createNamedParameter($objectUri)))
  2501. ->executeStatement();
  2502. }
  2503. /**
  2504. * Deletes all scheduling objects last modified before $modifiedBefore from the inbox collection.
  2505. *
  2506. * @param int $modifiedBefore
  2507. * @param int $limit
  2508. * @return void
  2509. */
  2510. public function deleteOutdatedSchedulingObjects(int $modifiedBefore, int $limit): void {
  2511. $query = $this->db->getQueryBuilder();
  2512. $query->select('id')
  2513. ->from('schedulingobjects')
  2514. ->where($query->expr()->lt('lastmodified', $query->createNamedParameter($modifiedBefore)))
  2515. ->setMaxResults($limit);
  2516. $result = $query->executeQuery();
  2517. $count = $result->rowCount();
  2518. if($count === 0) {
  2519. return;
  2520. }
  2521. $ids = array_map(static function (array $id) {
  2522. return (int)$id[0];
  2523. }, $result->fetchAll(\PDO::FETCH_NUM));
  2524. $result->closeCursor();
  2525. $numDeleted = 0;
  2526. $deleteQuery = $this->db->getQueryBuilder();
  2527. $deleteQuery->delete('schedulingobjects')
  2528. ->where($deleteQuery->expr()->in('id', $deleteQuery->createParameter('ids'), IQueryBuilder::PARAM_INT_ARRAY));
  2529. foreach(array_chunk($ids, 1000) as $chunk) {
  2530. $deleteQuery->setParameter('ids', $chunk, IQueryBuilder::PARAM_INT_ARRAY);
  2531. $numDeleted += $deleteQuery->executeStatement();
  2532. }
  2533. if($numDeleted === $limit) {
  2534. $this->logger->info("Deleted $limit scheduling objects, continuing with next batch");
  2535. $this->deleteOutdatedSchedulingObjects($modifiedBefore, $limit);
  2536. }
  2537. }
  2538. /**
  2539. * Creates a new scheduling object. This should land in a users' inbox.
  2540. *
  2541. * @param string $principalUri
  2542. * @param string $objectUri
  2543. * @param string $objectData
  2544. * @return void
  2545. */
  2546. public function createSchedulingObject($principalUri, $objectUri, $objectData) {
  2547. $this->cachedObjects = [];
  2548. $query = $this->db->getQueryBuilder();
  2549. $query->insert('schedulingobjects')
  2550. ->values([
  2551. 'principaluri' => $query->createNamedParameter($principalUri),
  2552. 'calendardata' => $query->createNamedParameter($objectData, IQueryBuilder::PARAM_LOB),
  2553. 'uri' => $query->createNamedParameter($objectUri),
  2554. 'lastmodified' => $query->createNamedParameter(time()),
  2555. 'etag' => $query->createNamedParameter(md5($objectData)),
  2556. 'size' => $query->createNamedParameter(strlen($objectData))
  2557. ])
  2558. ->executeStatement();
  2559. }
  2560. /**
  2561. * Adds a change record to the calendarchanges table.
  2562. *
  2563. * @param mixed $calendarId
  2564. * @param string[] $objectUris
  2565. * @param int $operation 1 = add, 2 = modify, 3 = delete.
  2566. * @param int $calendarType
  2567. * @return void
  2568. */
  2569. protected function addChanges(int $calendarId, array $objectUris, int $operation, int $calendarType = self::CALENDAR_TYPE_CALENDAR): void {
  2570. $this->cachedObjects = [];
  2571. $table = $calendarType === self::CALENDAR_TYPE_CALENDAR ? 'calendars': 'calendarsubscriptions';
  2572. $this->atomic(function () use ($calendarId, $objectUris, $operation, $calendarType, $table) {
  2573. $query = $this->db->getQueryBuilder();
  2574. $query->select('synctoken')
  2575. ->from($table)
  2576. ->where($query->expr()->eq('id', $query->createNamedParameter($calendarId)));
  2577. $result = $query->executeQuery();
  2578. $syncToken = (int)$result->fetchOne();
  2579. $result->closeCursor();
  2580. $query = $this->db->getQueryBuilder();
  2581. $query->insert('calendarchanges')
  2582. ->values([
  2583. 'uri' => $query->createParameter('uri'),
  2584. 'synctoken' => $query->createNamedParameter($syncToken),
  2585. 'calendarid' => $query->createNamedParameter($calendarId),
  2586. 'operation' => $query->createNamedParameter($operation),
  2587. 'calendartype' => $query->createNamedParameter($calendarType),
  2588. 'created_at' => time(),
  2589. ]);
  2590. foreach ($objectUris as $uri) {
  2591. $query->setParameter('uri', $uri);
  2592. $query->executeStatement();
  2593. }
  2594. $query = $this->db->getQueryBuilder();
  2595. $query->update($table)
  2596. ->set('synctoken', $query->createNamedParameter($syncToken + 1, IQueryBuilder::PARAM_INT))
  2597. ->where($query->expr()->eq('id', $query->createNamedParameter($calendarId)))
  2598. ->executeStatement();
  2599. }, $this->db);
  2600. }
  2601. public function restoreChanges(int $calendarId, int $calendarType = self::CALENDAR_TYPE_CALENDAR): void {
  2602. $this->cachedObjects = [];
  2603. $this->atomic(function () use ($calendarId, $calendarType) {
  2604. $qbAdded = $this->db->getQueryBuilder();
  2605. $qbAdded->select('uri')
  2606. ->from('calendarobjects')
  2607. ->where(
  2608. $qbAdded->expr()->andX(
  2609. $qbAdded->expr()->eq('calendarid', $qbAdded->createNamedParameter($calendarId)),
  2610. $qbAdded->expr()->eq('calendartype', $qbAdded->createNamedParameter($calendarType)),
  2611. $qbAdded->expr()->isNull('deleted_at'),
  2612. )
  2613. );
  2614. $resultAdded = $qbAdded->executeQuery();
  2615. $addedUris = $resultAdded->fetchAll(\PDO::FETCH_COLUMN);
  2616. $resultAdded->closeCursor();
  2617. // Track everything as changed
  2618. // Tracking the creation is not necessary because \OCA\DAV\CalDAV\CalDavBackend::getChangesForCalendar
  2619. // only returns the last change per object.
  2620. $this->addChanges($calendarId, $addedUris, 2, $calendarType);
  2621. $qbDeleted = $this->db->getQueryBuilder();
  2622. $qbDeleted->select('uri')
  2623. ->from('calendarobjects')
  2624. ->where(
  2625. $qbDeleted->expr()->andX(
  2626. $qbDeleted->expr()->eq('calendarid', $qbDeleted->createNamedParameter($calendarId)),
  2627. $qbDeleted->expr()->eq('calendartype', $qbDeleted->createNamedParameter($calendarType)),
  2628. $qbDeleted->expr()->isNotNull('deleted_at'),
  2629. )
  2630. );
  2631. $resultDeleted = $qbDeleted->executeQuery();
  2632. $deletedUris = array_map(function (string $uri) {
  2633. return str_replace('-deleted.ics', '.ics', $uri);
  2634. }, $resultDeleted->fetchAll(\PDO::FETCH_COLUMN));
  2635. $resultDeleted->closeCursor();
  2636. $this->addChanges($calendarId, $deletedUris, 3, $calendarType);
  2637. }, $this->db);
  2638. }
  2639. /**
  2640. * Parses some information from calendar objects, used for optimized
  2641. * calendar-queries.
  2642. *
  2643. * Returns an array with the following keys:
  2644. * * etag - An md5 checksum of the object without the quotes.
  2645. * * size - Size of the object in bytes
  2646. * * componentType - VEVENT, VTODO or VJOURNAL
  2647. * * firstOccurence
  2648. * * lastOccurence
  2649. * * uid - value of the UID property
  2650. *
  2651. * @param string $calendarData
  2652. * @return array
  2653. */
  2654. public function getDenormalizedData(string $calendarData): array {
  2655. $vObject = Reader::read($calendarData);
  2656. $vEvents = [];
  2657. $componentType = null;
  2658. $component = null;
  2659. $firstOccurrence = null;
  2660. $lastOccurrence = null;
  2661. $uid = null;
  2662. $classification = self::CLASSIFICATION_PUBLIC;
  2663. $hasDTSTART = false;
  2664. foreach ($vObject->getComponents() as $component) {
  2665. if ($component->name !== 'VTIMEZONE') {
  2666. // Finding all VEVENTs, and track them
  2667. if ($component->name === 'VEVENT') {
  2668. $vEvents[] = $component;
  2669. if ($component->DTSTART) {
  2670. $hasDTSTART = true;
  2671. }
  2672. }
  2673. // Track first component type and uid
  2674. if ($uid === null) {
  2675. $componentType = $component->name;
  2676. $uid = (string)$component->UID;
  2677. }
  2678. }
  2679. }
  2680. if (!$componentType) {
  2681. throw new BadRequest('Calendar objects must have a VJOURNAL, VEVENT or VTODO component');
  2682. }
  2683. if ($hasDTSTART) {
  2684. $component = $vEvents[0];
  2685. // Finding the last occurrence is a bit harder
  2686. if (!isset($component->RRULE) && count($vEvents) === 1) {
  2687. $firstOccurrence = $component->DTSTART->getDateTime()->getTimeStamp();
  2688. if (isset($component->DTEND)) {
  2689. $lastOccurrence = $component->DTEND->getDateTime()->getTimeStamp();
  2690. } elseif (isset($component->DURATION)) {
  2691. $endDate = clone $component->DTSTART->getDateTime();
  2692. $endDate->add(DateTimeParser::parse($component->DURATION->getValue()));
  2693. $lastOccurrence = $endDate->getTimeStamp();
  2694. } elseif (!$component->DTSTART->hasTime()) {
  2695. $endDate = clone $component->DTSTART->getDateTime();
  2696. $endDate->modify('+1 day');
  2697. $lastOccurrence = $endDate->getTimeStamp();
  2698. } else {
  2699. $lastOccurrence = $firstOccurrence;
  2700. }
  2701. } else {
  2702. try {
  2703. $it = new EventIterator($vEvents);
  2704. } catch (NoInstancesException $e) {
  2705. $this->logger->debug('Caught no instance exception for calendar data. This usually indicates invalid calendar data.', [
  2706. 'app' => 'dav',
  2707. 'exception' => $e,
  2708. ]);
  2709. throw new Forbidden($e->getMessage());
  2710. }
  2711. $maxDate = new DateTime(self::MAX_DATE);
  2712. $firstOccurrence = $it->getDtStart()->getTimestamp();
  2713. if ($it->isInfinite()) {
  2714. $lastOccurrence = $maxDate->getTimestamp();
  2715. } else {
  2716. $end = $it->getDtEnd();
  2717. while ($it->valid() && $end < $maxDate) {
  2718. $end = $it->getDtEnd();
  2719. $it->next();
  2720. }
  2721. $lastOccurrence = $end->getTimestamp();
  2722. }
  2723. }
  2724. }
  2725. if ($component->CLASS) {
  2726. $classification = CalDavBackend::CLASSIFICATION_PRIVATE;
  2727. switch ($component->CLASS->getValue()) {
  2728. case 'PUBLIC':
  2729. $classification = CalDavBackend::CLASSIFICATION_PUBLIC;
  2730. break;
  2731. case 'CONFIDENTIAL':
  2732. $classification = CalDavBackend::CLASSIFICATION_CONFIDENTIAL;
  2733. break;
  2734. }
  2735. }
  2736. return [
  2737. 'etag' => md5($calendarData),
  2738. 'size' => strlen($calendarData),
  2739. 'componentType' => $componentType,
  2740. 'firstOccurence' => is_null($firstOccurrence) ? null : max(0, $firstOccurrence),
  2741. 'lastOccurence' => is_null($lastOccurrence) ? null : max(0, $lastOccurrence),
  2742. 'uid' => $uid,
  2743. 'classification' => $classification
  2744. ];
  2745. }
  2746. /**
  2747. * @param $cardData
  2748. * @return bool|string
  2749. */
  2750. private function readBlob($cardData) {
  2751. if (is_resource($cardData)) {
  2752. return stream_get_contents($cardData);
  2753. }
  2754. return $cardData;
  2755. }
  2756. /**
  2757. * @param list<array{href: string, commonName: string, readOnly: bool}> $add
  2758. * @param list<string> $remove
  2759. */
  2760. public function updateShares(IShareable $shareable, array $add, array $remove): void {
  2761. $this->atomic(function () use ($shareable, $add, $remove) {
  2762. $calendarId = $shareable->getResourceId();
  2763. $calendarRow = $this->getCalendarById($calendarId);
  2764. if ($calendarRow === null) {
  2765. throw new \RuntimeException('Trying to update shares for non-existing calendar: ' . $calendarId);
  2766. }
  2767. $oldShares = $this->getShares($calendarId);
  2768. $this->calendarSharingBackend->updateShares($shareable, $add, $remove, $oldShares);
  2769. $this->dispatcher->dispatchTyped(new CalendarShareUpdatedEvent($calendarId, $calendarRow, $oldShares, $add, $remove));
  2770. }, $this->db);
  2771. }
  2772. /**
  2773. * @return list<array{href: string, commonName: string, status: int, readOnly: bool, '{http://owncloud.org/ns}principal': string, '{http://owncloud.org/ns}group-share': bool}>
  2774. */
  2775. public function getShares(int $resourceId): array {
  2776. return $this->calendarSharingBackend->getShares($resourceId);
  2777. }
  2778. public function preloadShares(array $resourceIds): void {
  2779. $this->calendarSharingBackend->preloadShares($resourceIds);
  2780. }
  2781. /**
  2782. * @param boolean $value
  2783. * @param \OCA\DAV\CalDAV\Calendar $calendar
  2784. * @return string|null
  2785. */
  2786. public function setPublishStatus($value, $calendar) {
  2787. return $this->atomic(function () use ($value, $calendar) {
  2788. $calendarId = $calendar->getResourceId();
  2789. $calendarData = $this->getCalendarById($calendarId);
  2790. $query = $this->db->getQueryBuilder();
  2791. if ($value) {
  2792. $publicUri = $this->random->generate(16, ISecureRandom::CHAR_HUMAN_READABLE);
  2793. $query->insert('dav_shares')
  2794. ->values([
  2795. 'principaluri' => $query->createNamedParameter($calendar->getPrincipalURI()),
  2796. 'type' => $query->createNamedParameter('calendar'),
  2797. 'access' => $query->createNamedParameter(self::ACCESS_PUBLIC),
  2798. 'resourceid' => $query->createNamedParameter($calendar->getResourceId()),
  2799. 'publicuri' => $query->createNamedParameter($publicUri)
  2800. ]);
  2801. $query->executeStatement();
  2802. $this->dispatcher->dispatchTyped(new CalendarPublishedEvent($calendarId, $calendarData, $publicUri));
  2803. return $publicUri;
  2804. }
  2805. $query->delete('dav_shares')
  2806. ->where($query->expr()->eq('resourceid', $query->createNamedParameter($calendar->getResourceId())))
  2807. ->andWhere($query->expr()->eq('access', $query->createNamedParameter(self::ACCESS_PUBLIC)));
  2808. $query->executeStatement();
  2809. $this->dispatcher->dispatchTyped(new CalendarUnpublishedEvent($calendarId, $calendarData));
  2810. return null;
  2811. }, $this->db);
  2812. }
  2813. /**
  2814. * @param \OCA\DAV\CalDAV\Calendar $calendar
  2815. * @return mixed
  2816. */
  2817. public function getPublishStatus($calendar) {
  2818. $query = $this->db->getQueryBuilder();
  2819. $result = $query->select('publicuri')
  2820. ->from('dav_shares')
  2821. ->where($query->expr()->eq('resourceid', $query->createNamedParameter($calendar->getResourceId())))
  2822. ->andWhere($query->expr()->eq('access', $query->createNamedParameter(self::ACCESS_PUBLIC)))
  2823. ->executeQuery();
  2824. $row = $result->fetch();
  2825. $result->closeCursor();
  2826. return $row ? reset($row) : false;
  2827. }
  2828. /**
  2829. * @param int $resourceId
  2830. * @param list<array{privilege: string, principal: string, protected: bool}> $acl
  2831. * @return list<array{privilege: string, principal: string, protected: bool}>
  2832. */
  2833. public function applyShareAcl(int $resourceId, array $acl): array {
  2834. $shares = $this->calendarSharingBackend->getShares($resourceId);
  2835. return $this->calendarSharingBackend->applyShareAcl($shares, $acl);
  2836. }
  2837. /**
  2838. * update properties table
  2839. *
  2840. * @param int $calendarId
  2841. * @param string $objectUri
  2842. * @param string $calendarData
  2843. * @param int $calendarType
  2844. */
  2845. public function updateProperties($calendarId, $objectUri, $calendarData, $calendarType = self::CALENDAR_TYPE_CALENDAR) {
  2846. $this->cachedObjects = [];
  2847. $this->atomic(function () use ($calendarId, $objectUri, $calendarData, $calendarType) {
  2848. $objectId = $this->getCalendarObjectId($calendarId, $objectUri, $calendarType);
  2849. try {
  2850. $vCalendar = $this->readCalendarData($calendarData);
  2851. } catch (\Exception $ex) {
  2852. return;
  2853. }
  2854. $this->purgeProperties($calendarId, $objectId);
  2855. $query = $this->db->getQueryBuilder();
  2856. $query->insert($this->dbObjectPropertiesTable)
  2857. ->values(
  2858. [
  2859. 'calendarid' => $query->createNamedParameter($calendarId),
  2860. 'calendartype' => $query->createNamedParameter($calendarType),
  2861. 'objectid' => $query->createNamedParameter($objectId),
  2862. 'name' => $query->createParameter('name'),
  2863. 'parameter' => $query->createParameter('parameter'),
  2864. 'value' => $query->createParameter('value'),
  2865. ]
  2866. );
  2867. $indexComponents = ['VEVENT', 'VJOURNAL', 'VTODO'];
  2868. foreach ($vCalendar->getComponents() as $component) {
  2869. if (!in_array($component->name, $indexComponents)) {
  2870. continue;
  2871. }
  2872. foreach ($component->children() as $property) {
  2873. if (in_array($property->name, self::INDEXED_PROPERTIES, true)) {
  2874. $value = $property->getValue();
  2875. // is this a shitty db?
  2876. if (!$this->db->supports4ByteText()) {
  2877. $value = preg_replace('/[\x{10000}-\x{10FFFF}]/u', "\xEF\xBF\xBD", $value);
  2878. }
  2879. $value = mb_strcut($value, 0, 254);
  2880. $query->setParameter('name', $property->name);
  2881. $query->setParameter('parameter', null);
  2882. $query->setParameter('value', mb_strcut($value, 0, 254));
  2883. $query->executeStatement();
  2884. }
  2885. if (array_key_exists($property->name, self::$indexParameters)) {
  2886. $parameters = $property->parameters();
  2887. $indexedParametersForProperty = self::$indexParameters[$property->name];
  2888. foreach ($parameters as $key => $value) {
  2889. if (in_array($key, $indexedParametersForProperty)) {
  2890. // is this a shitty db?
  2891. if ($this->db->supports4ByteText()) {
  2892. $value = preg_replace('/[\x{10000}-\x{10FFFF}]/u', "\xEF\xBF\xBD", $value);
  2893. }
  2894. $query->setParameter('name', $property->name);
  2895. $query->setParameter('parameter', mb_strcut($key, 0, 254));
  2896. $query->setParameter('value', mb_strcut($value, 0, 254));
  2897. $query->executeStatement();
  2898. }
  2899. }
  2900. }
  2901. }
  2902. }
  2903. }, $this->db);
  2904. }
  2905. /**
  2906. * deletes all birthday calendars
  2907. */
  2908. public function deleteAllBirthdayCalendars() {
  2909. $this->atomic(function () {
  2910. $query = $this->db->getQueryBuilder();
  2911. $result = $query->select(['id'])->from('calendars')
  2912. ->where($query->expr()->eq('uri', $query->createNamedParameter(BirthdayService::BIRTHDAY_CALENDAR_URI)))
  2913. ->executeQuery();
  2914. while (($row = $result->fetch()) !== false) {
  2915. $this->deleteCalendar(
  2916. $row['id'],
  2917. true // No data to keep in the trashbin, if the user re-enables then we regenerate
  2918. );
  2919. }
  2920. $result->closeCursor();
  2921. }, $this->db);
  2922. }
  2923. /**
  2924. * @param $subscriptionId
  2925. */
  2926. public function purgeAllCachedEventsForSubscription($subscriptionId) {
  2927. $this->atomic(function () use ($subscriptionId) {
  2928. $query = $this->db->getQueryBuilder();
  2929. $query->select('uri')
  2930. ->from('calendarobjects')
  2931. ->where($query->expr()->eq('calendarid', $query->createNamedParameter($subscriptionId)))
  2932. ->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)));
  2933. $stmt = $query->executeQuery();
  2934. $uris = [];
  2935. while (($row = $stmt->fetch()) !== false) {
  2936. $uris[] = $row['uri'];
  2937. }
  2938. $stmt->closeCursor();
  2939. $query = $this->db->getQueryBuilder();
  2940. $query->delete('calendarobjects')
  2941. ->where($query->expr()->eq('calendarid', $query->createNamedParameter($subscriptionId)))
  2942. ->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)))
  2943. ->executeStatement();
  2944. $query = $this->db->getQueryBuilder();
  2945. $query->delete('calendarchanges')
  2946. ->where($query->expr()->eq('calendarid', $query->createNamedParameter($subscriptionId)))
  2947. ->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)))
  2948. ->executeStatement();
  2949. $query = $this->db->getQueryBuilder();
  2950. $query->delete($this->dbObjectPropertiesTable)
  2951. ->where($query->expr()->eq('calendarid', $query->createNamedParameter($subscriptionId)))
  2952. ->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)))
  2953. ->executeStatement();
  2954. $this->addChanges($subscriptionId, $uris, 3, self::CALENDAR_TYPE_SUBSCRIPTION);
  2955. }, $this->db);
  2956. }
  2957. /**
  2958. * @param int $subscriptionId
  2959. * @param array<int> $calendarObjectIds
  2960. * @param array<string> $calendarObjectUris
  2961. */
  2962. public function purgeCachedEventsForSubscription(int $subscriptionId, array $calendarObjectIds, array $calendarObjectUris): void {
  2963. if(empty($calendarObjectUris)) {
  2964. return;
  2965. }
  2966. $this->atomic(function () use ($subscriptionId, $calendarObjectIds, $calendarObjectUris) {
  2967. foreach (array_chunk($calendarObjectIds, 1000) as $chunk) {
  2968. $query = $this->db->getQueryBuilder();
  2969. $query->delete($this->dbObjectPropertiesTable)
  2970. ->where($query->expr()->eq('calendarid', $query->createNamedParameter($subscriptionId)))
  2971. ->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)))
  2972. ->andWhere($query->expr()->in('id', $query->createNamedParameter($chunk, IQueryBuilder::PARAM_INT_ARRAY), IQueryBuilder::PARAM_INT_ARRAY))
  2973. ->executeStatement();
  2974. $query = $this->db->getQueryBuilder();
  2975. $query->delete('calendarobjects')
  2976. ->where($query->expr()->eq('calendarid', $query->createNamedParameter($subscriptionId)))
  2977. ->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)))
  2978. ->andWhere($query->expr()->in('id', $query->createNamedParameter($chunk, IQueryBuilder::PARAM_INT_ARRAY), IQueryBuilder::PARAM_INT_ARRAY))
  2979. ->executeStatement();
  2980. }
  2981. foreach (array_chunk($calendarObjectUris, 1000) as $chunk) {
  2982. $query = $this->db->getQueryBuilder();
  2983. $query->delete('calendarchanges')
  2984. ->where($query->expr()->eq('calendarid', $query->createNamedParameter($subscriptionId)))
  2985. ->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)))
  2986. ->andWhere($query->expr()->in('uri', $query->createNamedParameter($chunk, IQueryBuilder::PARAM_STR_ARRAY), IQueryBuilder::PARAM_STR_ARRAY))
  2987. ->executeStatement();
  2988. }
  2989. $this->addChanges($subscriptionId, $calendarObjectUris, 3, self::CALENDAR_TYPE_SUBSCRIPTION);
  2990. }, $this->db);
  2991. }
  2992. /**
  2993. * Move a calendar from one user to another
  2994. *
  2995. * @param string $uriName
  2996. * @param string $uriOrigin
  2997. * @param string $uriDestination
  2998. * @param string $newUriName (optional) the new uriName
  2999. */
  3000. public function moveCalendar($uriName, $uriOrigin, $uriDestination, $newUriName = null) {
  3001. $query = $this->db->getQueryBuilder();
  3002. $query->update('calendars')
  3003. ->set('principaluri', $query->createNamedParameter($uriDestination))
  3004. ->set('uri', $query->createNamedParameter($newUriName ?: $uriName))
  3005. ->where($query->expr()->eq('principaluri', $query->createNamedParameter($uriOrigin)))
  3006. ->andWhere($query->expr()->eq('uri', $query->createNamedParameter($uriName)))
  3007. ->executeStatement();
  3008. }
  3009. /**
  3010. * read VCalendar data into a VCalendar object
  3011. *
  3012. * @param string $objectData
  3013. * @return VCalendar
  3014. */
  3015. protected function readCalendarData($objectData) {
  3016. return Reader::read($objectData);
  3017. }
  3018. /**
  3019. * delete all properties from a given calendar object
  3020. *
  3021. * @param int $calendarId
  3022. * @param int $objectId
  3023. */
  3024. protected function purgeProperties($calendarId, $objectId) {
  3025. $this->cachedObjects = [];
  3026. $query = $this->db->getQueryBuilder();
  3027. $query->delete($this->dbObjectPropertiesTable)
  3028. ->where($query->expr()->eq('objectid', $query->createNamedParameter($objectId)))
  3029. ->andWhere($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)));
  3030. $query->executeStatement();
  3031. }
  3032. /**
  3033. * get ID from a given calendar object
  3034. *
  3035. * @param int $calendarId
  3036. * @param string $uri
  3037. * @param int $calendarType
  3038. * @return int
  3039. */
  3040. protected function getCalendarObjectId($calendarId, $uri, $calendarType):int {
  3041. $query = $this->db->getQueryBuilder();
  3042. $query->select('id')
  3043. ->from('calendarobjects')
  3044. ->where($query->expr()->eq('uri', $query->createNamedParameter($uri)))
  3045. ->andWhere($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)))
  3046. ->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter($calendarType)));
  3047. $result = $query->executeQuery();
  3048. $objectIds = $result->fetch();
  3049. $result->closeCursor();
  3050. if (!isset($objectIds['id'])) {
  3051. throw new \InvalidArgumentException('Calendarobject does not exists: ' . $uri);
  3052. }
  3053. return (int)$objectIds['id'];
  3054. }
  3055. /**
  3056. * @throws \InvalidArgumentException
  3057. */
  3058. public function pruneOutdatedSyncTokens(int $keep, int $retention): int {
  3059. if ($keep < 0) {
  3060. throw new \InvalidArgumentException();
  3061. }
  3062. $query = $this->db->getQueryBuilder();
  3063. $query->select($query->func()->max('id'))
  3064. ->from('calendarchanges');
  3065. $result = $query->executeQuery();
  3066. $maxId = (int)$result->fetchOne();
  3067. $result->closeCursor();
  3068. if (!$maxId || $maxId < $keep) {
  3069. return 0;
  3070. }
  3071. $query = $this->db->getQueryBuilder();
  3072. $query->delete('calendarchanges')
  3073. ->where(
  3074. $query->expr()->lte('id', $query->createNamedParameter($maxId - $keep, IQueryBuilder::PARAM_INT), IQueryBuilder::PARAM_INT),
  3075. $query->expr()->lte('created_at', $query->createNamedParameter($retention)),
  3076. );
  3077. return $query->executeStatement();
  3078. }
  3079. /**
  3080. * return legacy endpoint principal name to new principal name
  3081. *
  3082. * @param $principalUri
  3083. * @param $toV2
  3084. * @return string
  3085. */
  3086. private function convertPrincipal($principalUri, $toV2) {
  3087. if ($this->principalBackend->getPrincipalPrefix() === 'principals') {
  3088. [, $name] = Uri\split($principalUri);
  3089. if ($toV2 === true) {
  3090. return "principals/users/$name";
  3091. }
  3092. return "principals/$name";
  3093. }
  3094. return $principalUri;
  3095. }
  3096. /**
  3097. * adds information about an owner to the calendar data
  3098. *
  3099. */
  3100. private function addOwnerPrincipalToCalendar(array $calendarInfo): array {
  3101. $ownerPrincipalKey = '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal';
  3102. $displaynameKey = '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_NEXTCLOUD . '}owner-displayname';
  3103. if (isset($calendarInfo[$ownerPrincipalKey])) {
  3104. $uri = $calendarInfo[$ownerPrincipalKey];
  3105. } else {
  3106. $uri = $calendarInfo['principaluri'];
  3107. }
  3108. $principalInformation = $this->principalBackend->getPrincipalByPath($uri);
  3109. if (isset($principalInformation['{DAV:}displayname'])) {
  3110. $calendarInfo[$displaynameKey] = $principalInformation['{DAV:}displayname'];
  3111. }
  3112. return $calendarInfo;
  3113. }
  3114. private function addResourceTypeToCalendar(array $row, array $calendar): array {
  3115. if (isset($row['deleted_at'])) {
  3116. // Columns is set and not null -> this is a deleted calendar
  3117. // we send a custom resourcetype to hide the deleted calendar
  3118. // from ordinary DAV clients, but the Calendar app will know
  3119. // how to handle this special resource.
  3120. $calendar['{DAV:}resourcetype'] = new DAV\Xml\Property\ResourceType([
  3121. '{DAV:}collection',
  3122. sprintf('{%s}deleted-calendar', \OCA\DAV\DAV\Sharing\Plugin::NS_NEXTCLOUD),
  3123. ]);
  3124. }
  3125. return $calendar;
  3126. }
  3127. /**
  3128. * Amend the calendar info with database row data
  3129. *
  3130. * @param array $row
  3131. * @param array $calendar
  3132. *
  3133. * @return array
  3134. */
  3135. private function rowToCalendar($row, array $calendar): array {
  3136. foreach ($this->propertyMap as $xmlName => [$dbName, $type]) {
  3137. $value = $row[$dbName];
  3138. if ($value !== null) {
  3139. settype($value, $type);
  3140. }
  3141. $calendar[$xmlName] = $value;
  3142. }
  3143. return $calendar;
  3144. }
  3145. /**
  3146. * Amend the subscription info with database row data
  3147. *
  3148. * @param array $row
  3149. * @param array $subscription
  3150. *
  3151. * @return array
  3152. */
  3153. private function rowToSubscription($row, array $subscription): array {
  3154. foreach ($this->subscriptionPropertyMap as $xmlName => [$dbName, $type]) {
  3155. $value = $row[$dbName];
  3156. if ($value !== null) {
  3157. settype($value, $type);
  3158. }
  3159. $subscription[$xmlName] = $value;
  3160. }
  3161. return $subscription;
  3162. }
  3163. }