Du kannst nicht mehr als 25 Themen auswählen Themen müssen mit entweder einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.

CalDavBackend.php 113KB

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