CalDavBackend.php 126 KB

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