CalDavBackend.php 116 KB

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