CalDavBackend.php 122 KB

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