CalDavBackend.php 117 KB

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