CalDavBackend.php 128 KB

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