CalDavBackend.php 122 KB

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