CalDavBackend.php 124 KB

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