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 88KB

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