You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

CalDavBackend.php 98KB

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