CalDavBackend.php 126 KB

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