CalDavBackend.php 88 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633
  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 nhirokinet <nhirokinet@nhiroki.net>
  10. * @author Robin Appelman <robin@icewind.nl>
  11. * @author Roeland Jago Douma <roeland@famdouma.nl>
  12. * @author Stefan Weil <sw@weilnetz.de>
  13. * @author Thomas Citharel <tcit@tcit.fr>
  14. * @author Thomas Müller <thomas.mueller@tmit.eu>
  15. * @author Vinicius Cubas Brand <vinicius@eita.org.br>
  16. * @author Daniel Tygel <dtygel@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\DAV\Sharing\IShareable;
  35. use OCP\DB\QueryBuilder\IQueryBuilder;
  36. use OCA\DAV\Connector\Sabre\Principal;
  37. use OCA\DAV\DAV\Sharing\Backend;
  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\VObject\Component;
  55. use Sabre\VObject\Component\VCalendar;
  56. use Sabre\VObject\Component\VTimeZone;
  57. use Sabre\VObject\DateTimeParser;
  58. use Sabre\VObject\InvalidDataException;
  59. use Sabre\VObject\ParseException;
  60. use Sabre\VObject\Property;
  61. use Sabre\VObject\Reader;
  62. use Sabre\VObject\Recur\EventIterator;
  63. use Sabre\Uri;
  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. }
  652. $transp = '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp';
  653. if (isset($properties[$transp])) {
  654. $values['transparent'] = (int) ($properties[$transp]->getValue() === 'transparent');
  655. }
  656. foreach($this->propertyMap as $xmlName=>$dbName) {
  657. if (isset($properties[$xmlName])) {
  658. $values[$dbName] = $properties[$xmlName];
  659. }
  660. }
  661. $query = $this->db->getQueryBuilder();
  662. $query->insert('calendars');
  663. foreach($values as $column => $value) {
  664. $query->setValue($column, $query->createNamedParameter($value));
  665. }
  666. $query->execute();
  667. $calendarId = $query->getLastInsertId();
  668. $this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::createCalendar', new GenericEvent(
  669. '\OCA\DAV\CalDAV\CalDavBackend::createCalendar',
  670. [
  671. 'calendarId' => $calendarId,
  672. 'calendarData' => $this->getCalendarById($calendarId),
  673. ]));
  674. return $calendarId;
  675. }
  676. /**
  677. * Updates properties for a calendar.
  678. *
  679. * The list of mutations is stored in a Sabre\DAV\PropPatch object.
  680. * To do the actual updates, you must tell this object which properties
  681. * you're going to process with the handle() method.
  682. *
  683. * Calling the handle method is like telling the PropPatch object "I
  684. * promise I can handle updating this property".
  685. *
  686. * Read the PropPatch documentation for more info and examples.
  687. *
  688. * @param mixed $calendarId
  689. * @param PropPatch $propPatch
  690. * @return void
  691. */
  692. function updateCalendar($calendarId, PropPatch $propPatch) {
  693. $supportedProperties = array_keys($this->propertyMap);
  694. $supportedProperties[] = '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp';
  695. /**
  696. * @suppress SqlInjectionChecker
  697. */
  698. $propPatch->handle($supportedProperties, function($mutations) use ($calendarId) {
  699. $newValues = [];
  700. foreach ($mutations as $propertyName => $propertyValue) {
  701. switch ($propertyName) {
  702. case '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' :
  703. $fieldName = 'transparent';
  704. $newValues[$fieldName] = (int) ($propertyValue->getValue() === 'transparent');
  705. break;
  706. default :
  707. $fieldName = $this->propertyMap[$propertyName];
  708. $newValues[$fieldName] = $propertyValue;
  709. break;
  710. }
  711. }
  712. $query = $this->db->getQueryBuilder();
  713. $query->update('calendars');
  714. foreach ($newValues as $fieldName => $value) {
  715. $query->set($fieldName, $query->createNamedParameter($value));
  716. }
  717. $query->where($query->expr()->eq('id', $query->createNamedParameter($calendarId)));
  718. $query->execute();
  719. $this->addChange($calendarId, "", 2);
  720. $this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::updateCalendar', new GenericEvent(
  721. '\OCA\DAV\CalDAV\CalDavBackend::updateCalendar',
  722. [
  723. 'calendarId' => $calendarId,
  724. 'calendarData' => $this->getCalendarById($calendarId),
  725. 'shares' => $this->getShares($calendarId),
  726. 'propertyMutations' => $mutations,
  727. ]));
  728. return true;
  729. });
  730. }
  731. /**
  732. * Delete a calendar and all it's objects
  733. *
  734. * @param mixed $calendarId
  735. * @return void
  736. */
  737. function deleteCalendar($calendarId) {
  738. $this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::deleteCalendar', new GenericEvent(
  739. '\OCA\DAV\CalDAV\CalDavBackend::deleteCalendar',
  740. [
  741. 'calendarId' => $calendarId,
  742. 'calendarData' => $this->getCalendarById($calendarId),
  743. 'shares' => $this->getShares($calendarId),
  744. ]));
  745. $stmt = $this->db->prepare('DELETE FROM `*PREFIX*calendarobjects` WHERE `calendarid` = ? AND `calendartype` = ?');
  746. $stmt->execute([$calendarId, self::CALENDAR_TYPE_CALENDAR]);
  747. $stmt = $this->db->prepare('DELETE FROM `*PREFIX*calendars` WHERE `id` = ?');
  748. $stmt->execute([$calendarId]);
  749. $stmt = $this->db->prepare('DELETE FROM `*PREFIX*calendarchanges` WHERE `calendarid` = ? AND `calendartype` = ?');
  750. $stmt->execute([$calendarId, self::CALENDAR_TYPE_CALENDAR]);
  751. $this->calendarSharingBackend->deleteAllShares($calendarId);
  752. $query = $this->db->getQueryBuilder();
  753. $query->delete($this->dbObjectPropertiesTable)
  754. ->where($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)))
  755. ->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_CALENDAR)))
  756. ->execute();
  757. }
  758. /**
  759. * Delete all of an user's shares
  760. *
  761. * @param string $principaluri
  762. * @return void
  763. */
  764. function deleteAllSharesByUser($principaluri) {
  765. $this->calendarSharingBackend->deleteAllSharesByUser($principaluri);
  766. }
  767. /**
  768. * Returns all calendar objects within a calendar.
  769. *
  770. * Every item contains an array with the following keys:
  771. * * calendardata - The iCalendar-compatible calendar data
  772. * * uri - a unique key which will be used to construct the uri. This can
  773. * be any arbitrary string, but making sure it ends with '.ics' is a
  774. * good idea. This is only the basename, or filename, not the full
  775. * path.
  776. * * lastmodified - a timestamp of the last modification time
  777. * * etag - An arbitrary string, surrounded by double-quotes. (e.g.:
  778. * '"abcdef"')
  779. * * size - The size of the calendar objects, in bytes.
  780. * * component - optional, a string containing the type of object, such
  781. * as 'vevent' or 'vtodo'. If specified, this will be used to populate
  782. * the Content-Type header.
  783. *
  784. * Note that the etag is optional, but it's highly encouraged to return for
  785. * speed reasons.
  786. *
  787. * The calendardata is also optional. If it's not returned
  788. * 'getCalendarObject' will be called later, which *is* expected to return
  789. * calendardata.
  790. *
  791. * If neither etag or size are specified, the calendardata will be
  792. * used/fetched to determine these numbers. If both are specified the
  793. * amount of times this is needed is reduced by a great degree.
  794. *
  795. * @param mixed $id
  796. * @param int $calendarType
  797. * @return array
  798. */
  799. public function getCalendarObjects($id, $calendarType=self::CALENDAR_TYPE_CALENDAR):array {
  800. $query = $this->db->getQueryBuilder();
  801. $query->select(['id', 'uri', 'lastmodified', 'etag', 'calendarid', 'size', 'componenttype', 'classification'])
  802. ->from('calendarobjects')
  803. ->where($query->expr()->eq('calendarid', $query->createNamedParameter($id)))
  804. ->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter($calendarType)));
  805. $stmt = $query->execute();
  806. $result = [];
  807. foreach($stmt->fetchAll(\PDO::FETCH_ASSOC) as $row) {
  808. $result[] = [
  809. 'id' => $row['id'],
  810. 'uri' => $row['uri'],
  811. 'lastmodified' => $row['lastmodified'],
  812. 'etag' => '"' . $row['etag'] . '"',
  813. 'calendarid' => $row['calendarid'],
  814. 'size' => (int)$row['size'],
  815. 'component' => strtolower($row['componenttype']),
  816. 'classification'=> (int)$row['classification']
  817. ];
  818. }
  819. return $result;
  820. }
  821. /**
  822. * Returns information from a single calendar object, based on it's object
  823. * uri.
  824. *
  825. * The object uri is only the basename, or filename and not a full path.
  826. *
  827. * The returned array must have the same keys as getCalendarObjects. The
  828. * 'calendardata' object is required here though, while it's not required
  829. * for getCalendarObjects.
  830. *
  831. * This method must return null if the object did not exist.
  832. *
  833. * @param mixed $id
  834. * @param string $objectUri
  835. * @param int $calendarType
  836. * @return array|null
  837. */
  838. public function getCalendarObject($id, $objectUri, $calendarType=self::CALENDAR_TYPE_CALENDAR) {
  839. $query = $this->db->getQueryBuilder();
  840. $query->select(['id', 'uri', 'lastmodified', 'etag', 'calendarid', 'size', 'calendardata', 'componenttype', 'classification'])
  841. ->from('calendarobjects')
  842. ->where($query->expr()->eq('calendarid', $query->createNamedParameter($id)))
  843. ->andWhere($query->expr()->eq('uri', $query->createNamedParameter($objectUri)))
  844. ->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter($calendarType)));
  845. $stmt = $query->execute();
  846. $row = $stmt->fetch(\PDO::FETCH_ASSOC);
  847. if(!$row) {
  848. return null;
  849. }
  850. return [
  851. 'id' => $row['id'],
  852. 'uri' => $row['uri'],
  853. 'lastmodified' => $row['lastmodified'],
  854. 'etag' => '"' . $row['etag'] . '"',
  855. 'calendarid' => $row['calendarid'],
  856. 'size' => (int)$row['size'],
  857. 'calendardata' => $this->readBlob($row['calendardata']),
  858. 'component' => strtolower($row['componenttype']),
  859. 'classification'=> (int)$row['classification']
  860. ];
  861. }
  862. /**
  863. * Returns a list of calendar objects.
  864. *
  865. * This method should work identical to getCalendarObject, but instead
  866. * return all the calendar objects in the list as an array.
  867. *
  868. * If the backend supports this, it may allow for some speed-ups.
  869. *
  870. * @param mixed $calendarId
  871. * @param string[] $uris
  872. * @param int $calendarType
  873. * @return array
  874. */
  875. public function getMultipleCalendarObjects($id, array $uris, $calendarType=self::CALENDAR_TYPE_CALENDAR):array {
  876. if (empty($uris)) {
  877. return [];
  878. }
  879. $chunks = array_chunk($uris, 100);
  880. $objects = [];
  881. $query = $this->db->getQueryBuilder();
  882. $query->select(['id', 'uri', 'lastmodified', 'etag', 'calendarid', 'size', 'calendardata', 'componenttype', 'classification'])
  883. ->from('calendarobjects')
  884. ->where($query->expr()->eq('calendarid', $query->createNamedParameter($id)))
  885. ->andWhere($query->expr()->in('uri', $query->createParameter('uri')))
  886. ->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter($calendarType)));
  887. foreach ($chunks as $uris) {
  888. $query->setParameter('uri', $uris, IQueryBuilder::PARAM_STR_ARRAY);
  889. $result = $query->execute();
  890. while ($row = $result->fetch()) {
  891. $objects[] = [
  892. 'id' => $row['id'],
  893. 'uri' => $row['uri'],
  894. 'lastmodified' => $row['lastmodified'],
  895. 'etag' => '"' . $row['etag'] . '"',
  896. 'calendarid' => $row['calendarid'],
  897. 'size' => (int)$row['size'],
  898. 'calendardata' => $this->readBlob($row['calendardata']),
  899. 'component' => strtolower($row['componenttype']),
  900. 'classification' => (int)$row['classification']
  901. ];
  902. }
  903. $result->closeCursor();
  904. }
  905. return $objects;
  906. }
  907. /**
  908. * Creates a new calendar object.
  909. *
  910. * The object uri is only the basename, or filename and not a full path.
  911. *
  912. * It is possible return an etag from this function, which will be used in
  913. * the response to this PUT request. Note that the ETag must be surrounded
  914. * by double-quotes.
  915. *
  916. * However, you should only really return this ETag if you don't mangle the
  917. * calendar-data. If the result of a subsequent GET to this object is not
  918. * the exact same as this request body, you should omit the ETag.
  919. *
  920. * @param mixed $calendarId
  921. * @param string $objectUri
  922. * @param string $calendarData
  923. * @param int $calendarType
  924. * @return string
  925. */
  926. function createCalendarObject($calendarId, $objectUri, $calendarData, $calendarType=self::CALENDAR_TYPE_CALENDAR) {
  927. $extraData = $this->getDenormalizedData($calendarData);
  928. $q = $this->db->getQueryBuilder();
  929. $q->select($q->func()->count('*'))
  930. ->from('calendarobjects')
  931. ->where($q->expr()->eq('calendarid', $q->createNamedParameter($calendarId)))
  932. ->andWhere($q->expr()->eq('uid', $q->createNamedParameter($extraData['uid'])))
  933. ->andWhere($q->expr()->eq('calendartype', $q->createNamedParameter($calendarType)));
  934. $result = $q->execute();
  935. $count = (int) $result->fetchColumn();
  936. $result->closeCursor();
  937. if ($count !== 0) {
  938. throw new \Sabre\DAV\Exception\BadRequest('Calendar object with uid already exists in this calendar collection.');
  939. }
  940. $query = $this->db->getQueryBuilder();
  941. $query->insert('calendarobjects')
  942. ->values([
  943. 'calendarid' => $query->createNamedParameter($calendarId),
  944. 'uri' => $query->createNamedParameter($objectUri),
  945. 'calendardata' => $query->createNamedParameter($calendarData, IQueryBuilder::PARAM_LOB),
  946. 'lastmodified' => $query->createNamedParameter(time()),
  947. 'etag' => $query->createNamedParameter($extraData['etag']),
  948. 'size' => $query->createNamedParameter($extraData['size']),
  949. 'componenttype' => $query->createNamedParameter($extraData['componentType']),
  950. 'firstoccurence' => $query->createNamedParameter($extraData['firstOccurence']),
  951. 'lastoccurence' => $query->createNamedParameter($extraData['lastOccurence']),
  952. 'classification' => $query->createNamedParameter($extraData['classification']),
  953. 'uid' => $query->createNamedParameter($extraData['uid']),
  954. 'calendartype' => $query->createNamedParameter($calendarType),
  955. ])
  956. ->execute();
  957. $this->updateProperties($calendarId, $objectUri, $calendarData, $calendarType);
  958. if ($calendarType === self::CALENDAR_TYPE_CALENDAR) {
  959. $this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::createCalendarObject', new GenericEvent(
  960. '\OCA\DAV\CalDAV\CalDavBackend::createCalendarObject',
  961. [
  962. 'calendarId' => $calendarId,
  963. 'calendarData' => $this->getCalendarById($calendarId),
  964. 'shares' => $this->getShares($calendarId),
  965. 'objectData' => $this->getCalendarObject($calendarId, $objectUri),
  966. ]
  967. ));
  968. } else {
  969. $this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::createCachedCalendarObject', new GenericEvent(
  970. '\OCA\DAV\CalDAV\CalDavBackend::createCachedCalendarObject',
  971. [
  972. 'subscriptionId' => $calendarId,
  973. 'calendarData' => $this->getCalendarById($calendarId),
  974. 'shares' => $this->getShares($calendarId),
  975. 'objectData' => $this->getCalendarObject($calendarId, $objectUri),
  976. ]
  977. ));
  978. }
  979. $this->addChange($calendarId, $objectUri, 1, $calendarType);
  980. return '"' . $extraData['etag'] . '"';
  981. }
  982. /**
  983. * Updates an existing calendarobject, based on it's uri.
  984. *
  985. * The object uri is only the basename, or filename and not a full path.
  986. *
  987. * It is possible return an etag from this function, which will be used in
  988. * the response to this PUT request. Note that the ETag must be surrounded
  989. * by double-quotes.
  990. *
  991. * However, you should only really return this ETag if you don't mangle the
  992. * calendar-data. If the result of a subsequent GET to this object is not
  993. * the exact same as this request body, you should omit the ETag.
  994. *
  995. * @param mixed $calendarId
  996. * @param string $objectUri
  997. * @param string $calendarData
  998. * @param int $calendarType
  999. * @return string
  1000. */
  1001. function updateCalendarObject($calendarId, $objectUri, $calendarData, $calendarType=self::CALENDAR_TYPE_CALENDAR) {
  1002. $extraData = $this->getDenormalizedData($calendarData);
  1003. $query = $this->db->getQueryBuilder();
  1004. $query->update('calendarobjects')
  1005. ->set('calendardata', $query->createNamedParameter($calendarData, IQueryBuilder::PARAM_LOB))
  1006. ->set('lastmodified', $query->createNamedParameter(time()))
  1007. ->set('etag', $query->createNamedParameter($extraData['etag']))
  1008. ->set('size', $query->createNamedParameter($extraData['size']))
  1009. ->set('componenttype', $query->createNamedParameter($extraData['componentType']))
  1010. ->set('firstoccurence', $query->createNamedParameter($extraData['firstOccurence']))
  1011. ->set('lastoccurence', $query->createNamedParameter($extraData['lastOccurence']))
  1012. ->set('classification', $query->createNamedParameter($extraData['classification']))
  1013. ->set('uid', $query->createNamedParameter($extraData['uid']))
  1014. ->where($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)))
  1015. ->andWhere($query->expr()->eq('uri', $query->createNamedParameter($objectUri)))
  1016. ->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter($calendarType)))
  1017. ->execute();
  1018. $this->updateProperties($calendarId, $objectUri, $calendarData, $calendarType);
  1019. $data = $this->getCalendarObject($calendarId, $objectUri);
  1020. if (is_array($data)) {
  1021. if ($calendarType === self::CALENDAR_TYPE_CALENDAR) {
  1022. $this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::updateCalendarObject', new GenericEvent(
  1023. '\OCA\DAV\CalDAV\CalDavBackend::updateCalendarObject',
  1024. [
  1025. 'calendarId' => $calendarId,
  1026. 'calendarData' => $this->getCalendarById($calendarId),
  1027. 'shares' => $this->getShares($calendarId),
  1028. 'objectData' => $data,
  1029. ]
  1030. ));
  1031. } else {
  1032. $this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::updateCachedCalendarObject', new GenericEvent(
  1033. '\OCA\DAV\CalDAV\CalDavBackend::updateCachedCalendarObject',
  1034. [
  1035. 'subscriptionId' => $calendarId,
  1036. 'calendarData' => $this->getCalendarById($calendarId),
  1037. 'shares' => $this->getShares($calendarId),
  1038. 'objectData' => $data,
  1039. ]
  1040. ));
  1041. }
  1042. }
  1043. $this->addChange($calendarId, $objectUri, 2, $calendarType);
  1044. return '"' . $extraData['etag'] . '"';
  1045. }
  1046. /**
  1047. * @param int $calendarObjectId
  1048. * @param int $classification
  1049. */
  1050. public function setClassification($calendarObjectId, $classification) {
  1051. if (!in_array($classification, [
  1052. self::CLASSIFICATION_PUBLIC, self::CLASSIFICATION_PRIVATE, self::CLASSIFICATION_CONFIDENTIAL
  1053. ])) {
  1054. throw new \InvalidArgumentException();
  1055. }
  1056. $query = $this->db->getQueryBuilder();
  1057. $query->update('calendarobjects')
  1058. ->set('classification', $query->createNamedParameter($classification))
  1059. ->where($query->expr()->eq('id', $query->createNamedParameter($calendarObjectId)))
  1060. ->execute();
  1061. }
  1062. /**
  1063. * Deletes an existing calendar object.
  1064. *
  1065. * The object uri is only the basename, or filename and not a full path.
  1066. *
  1067. * @param mixed $calendarId
  1068. * @param string $objectUri
  1069. * @param int $calendarType
  1070. * @return void
  1071. */
  1072. function deleteCalendarObject($calendarId, $objectUri, $calendarType=self::CALENDAR_TYPE_CALENDAR) {
  1073. $data = $this->getCalendarObject($calendarId, $objectUri, $calendarType);
  1074. if (is_array($data)) {
  1075. if ($calendarType === self::CALENDAR_TYPE_CALENDAR) {
  1076. $this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::deleteCalendarObject', new GenericEvent(
  1077. '\OCA\DAV\CalDAV\CalDavBackend::deleteCalendarObject',
  1078. [
  1079. 'calendarId' => $calendarId,
  1080. 'calendarData' => $this->getCalendarById($calendarId),
  1081. 'shares' => $this->getShares($calendarId),
  1082. 'objectData' => $data,
  1083. ]
  1084. ));
  1085. } else {
  1086. $this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::deleteCachedCalendarObject', new GenericEvent(
  1087. '\OCA\DAV\CalDAV\CalDavBackend::deleteCachedCalendarObject',
  1088. [
  1089. 'subscriptionId' => $calendarId,
  1090. 'calendarData' => $this->getCalendarById($calendarId),
  1091. 'shares' => $this->getShares($calendarId),
  1092. 'objectData' => $data,
  1093. ]
  1094. ));
  1095. }
  1096. }
  1097. $stmt = $this->db->prepare('DELETE FROM `*PREFIX*calendarobjects` WHERE `calendarid` = ? AND `uri` = ? AND `calendartype` = ?');
  1098. $stmt->execute([$calendarId, $objectUri, $calendarType]);
  1099. $this->purgeProperties($calendarId, $data['id'], $calendarType);
  1100. $this->addChange($calendarId, $objectUri, 3, $calendarType);
  1101. }
  1102. /**
  1103. * Performs a calendar-query on the contents of this calendar.
  1104. *
  1105. * The calendar-query is defined in RFC4791 : CalDAV. Using the
  1106. * calendar-query it is possible for a client to request a specific set of
  1107. * object, based on contents of iCalendar properties, date-ranges and
  1108. * iCalendar component types (VTODO, VEVENT).
  1109. *
  1110. * This method should just return a list of (relative) urls that match this
  1111. * query.
  1112. *
  1113. * The list of filters are specified as an array. The exact array is
  1114. * documented by Sabre\CalDAV\CalendarQueryParser.
  1115. *
  1116. * Note that it is extremely likely that getCalendarObject for every path
  1117. * returned from this method will be called almost immediately after. You
  1118. * may want to anticipate this to speed up these requests.
  1119. *
  1120. * This method provides a default implementation, which parses *all* the
  1121. * iCalendar objects in the specified calendar.
  1122. *
  1123. * This default may well be good enough for personal use, and calendars
  1124. * that aren't very large. But if you anticipate high usage, big calendars
  1125. * or high loads, you are strongly advised to optimize certain paths.
  1126. *
  1127. * The best way to do so is override this method and to optimize
  1128. * specifically for 'common filters'.
  1129. *
  1130. * Requests that are extremely common are:
  1131. * * requests for just VEVENTS
  1132. * * requests for just VTODO
  1133. * * requests with a time-range-filter on either VEVENT or VTODO.
  1134. *
  1135. * ..and combinations of these requests. It may not be worth it to try to
  1136. * handle every possible situation and just rely on the (relatively
  1137. * easy to use) CalendarQueryValidator to handle the rest.
  1138. *
  1139. * Note that especially time-range-filters may be difficult to parse. A
  1140. * time-range filter specified on a VEVENT must for instance also handle
  1141. * recurrence rules correctly.
  1142. * A good example of how to interprete all these filters can also simply
  1143. * be found in Sabre\CalDAV\CalendarQueryFilter. This class is as correct
  1144. * as possible, so it gives you a good idea on what type of stuff you need
  1145. * to think of.
  1146. *
  1147. * @param mixed $id
  1148. * @param array $filters
  1149. * @param int $calendarType
  1150. * @return array
  1151. */
  1152. public function calendarQuery($id, array $filters, $calendarType=self::CALENDAR_TYPE_CALENDAR):array {
  1153. $componentType = null;
  1154. $requirePostFilter = true;
  1155. $timeRange = null;
  1156. // if no filters were specified, we don't need to filter after a query
  1157. if (!$filters['prop-filters'] && !$filters['comp-filters']) {
  1158. $requirePostFilter = false;
  1159. }
  1160. // Figuring out if there's a component filter
  1161. if (count($filters['comp-filters']) > 0 && !$filters['comp-filters'][0]['is-not-defined']) {
  1162. $componentType = $filters['comp-filters'][0]['name'];
  1163. // Checking if we need post-filters
  1164. if (!$filters['prop-filters'] && !$filters['comp-filters'][0]['comp-filters'] && !$filters['comp-filters'][0]['time-range'] && !$filters['comp-filters'][0]['prop-filters']) {
  1165. $requirePostFilter = false;
  1166. }
  1167. // There was a time-range filter
  1168. if ($componentType === 'VEVENT' && isset($filters['comp-filters'][0]['time-range'])) {
  1169. $timeRange = $filters['comp-filters'][0]['time-range'];
  1170. // If start time OR the end time is not specified, we can do a
  1171. // 100% accurate mysql query.
  1172. if (!$filters['prop-filters'] && !$filters['comp-filters'][0]['comp-filters'] && !$filters['comp-filters'][0]['prop-filters'] && (!$timeRange['start'] || !$timeRange['end'])) {
  1173. $requirePostFilter = false;
  1174. }
  1175. }
  1176. }
  1177. $columns = ['uri'];
  1178. if ($requirePostFilter) {
  1179. $columns = ['uri', 'calendardata'];
  1180. }
  1181. $query = $this->db->getQueryBuilder();
  1182. $query->select($columns)
  1183. ->from('calendarobjects')
  1184. ->where($query->expr()->eq('calendarid', $query->createNamedParameter($id)))
  1185. ->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter($calendarType)));
  1186. if ($componentType) {
  1187. $query->andWhere($query->expr()->eq('componenttype', $query->createNamedParameter($componentType)));
  1188. }
  1189. if ($timeRange && $timeRange['start']) {
  1190. $query->andWhere($query->expr()->gt('lastoccurence', $query->createNamedParameter($timeRange['start']->getTimeStamp())));
  1191. }
  1192. if ($timeRange && $timeRange['end']) {
  1193. $query->andWhere($query->expr()->lt('firstoccurence', $query->createNamedParameter($timeRange['end']->getTimeStamp())));
  1194. }
  1195. $stmt = $query->execute();
  1196. $result = [];
  1197. while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
  1198. if ($requirePostFilter) {
  1199. // validateFilterForObject will parse the calendar data
  1200. // catch parsing errors
  1201. try {
  1202. $matches = $this->validateFilterForObject($row, $filters);
  1203. } catch(ParseException $ex) {
  1204. $this->logger->logException($ex, [
  1205. 'app' => 'dav',
  1206. 'message' => 'Caught parsing exception for calendar data. This usually indicates invalid calendar data. calendar-id:'.$id.' uri:'.$row['uri']
  1207. ]);
  1208. continue;
  1209. } catch (InvalidDataException $ex) {
  1210. $this->logger->logException($ex, [
  1211. 'app' => 'dav',
  1212. 'message' => 'Caught invalid data exception for calendar data. This usually indicates invalid calendar data. calendar-id:'.$id.' uri:'.$row['uri']
  1213. ]);
  1214. continue;
  1215. }
  1216. if (!$matches) {
  1217. continue;
  1218. }
  1219. }
  1220. $result[] = $row['uri'];
  1221. }
  1222. return $result;
  1223. }
  1224. /**
  1225. * custom Nextcloud search extension for CalDAV
  1226. *
  1227. * TODO - this should optionally cover cached calendar objects as well
  1228. *
  1229. * @param string $principalUri
  1230. * @param array $filters
  1231. * @param integer|null $limit
  1232. * @param integer|null $offset
  1233. * @return array
  1234. */
  1235. public function calendarSearch($principalUri, array $filters, $limit=null, $offset=null) {
  1236. $calendars = $this->getCalendarsForUser($principalUri);
  1237. $ownCalendars = [];
  1238. $sharedCalendars = [];
  1239. $uriMapper = [];
  1240. foreach($calendars as $calendar) {
  1241. if ($calendar['{http://owncloud.org/ns}owner-principal'] === $principalUri) {
  1242. $ownCalendars[] = $calendar['id'];
  1243. } else {
  1244. $sharedCalendars[] = $calendar['id'];
  1245. }
  1246. $uriMapper[$calendar['id']] = $calendar['uri'];
  1247. }
  1248. if (count($ownCalendars) === 0 && count($sharedCalendars) === 0) {
  1249. return [];
  1250. }
  1251. $query = $this->db->getQueryBuilder();
  1252. // Calendar id expressions
  1253. $calendarExpressions = [];
  1254. foreach($ownCalendars as $id) {
  1255. $calendarExpressions[] = $query->expr()->andX(
  1256. $query->expr()->eq('c.calendarid',
  1257. $query->createNamedParameter($id)),
  1258. $query->expr()->eq('c.calendartype',
  1259. $query->createNamedParameter(self::CALENDAR_TYPE_CALENDAR)));
  1260. }
  1261. foreach($sharedCalendars as $id) {
  1262. $calendarExpressions[] = $query->expr()->andX(
  1263. $query->expr()->eq('c.calendarid',
  1264. $query->createNamedParameter($id)),
  1265. $query->expr()->eq('c.classification',
  1266. $query->createNamedParameter(self::CLASSIFICATION_PUBLIC)),
  1267. $query->expr()->eq('c.calendartype',
  1268. $query->createNamedParameter(self::CALENDAR_TYPE_CALENDAR)));
  1269. }
  1270. if (count($calendarExpressions) === 1) {
  1271. $calExpr = $calendarExpressions[0];
  1272. } else {
  1273. $calExpr = call_user_func_array([$query->expr(), 'orX'], $calendarExpressions);
  1274. }
  1275. // Component expressions
  1276. $compExpressions = [];
  1277. foreach($filters['comps'] as $comp) {
  1278. $compExpressions[] = $query->expr()
  1279. ->eq('c.componenttype', $query->createNamedParameter($comp));
  1280. }
  1281. if (count($compExpressions) === 1) {
  1282. $compExpr = $compExpressions[0];
  1283. } else {
  1284. $compExpr = call_user_func_array([$query->expr(), 'orX'], $compExpressions);
  1285. }
  1286. if (!isset($filters['props'])) {
  1287. $filters['props'] = [];
  1288. }
  1289. if (!isset($filters['params'])) {
  1290. $filters['params'] = [];
  1291. }
  1292. $propParamExpressions = [];
  1293. foreach($filters['props'] as $prop) {
  1294. $propParamExpressions[] = $query->expr()->andX(
  1295. $query->expr()->eq('i.name', $query->createNamedParameter($prop)),
  1296. $query->expr()->isNull('i.parameter')
  1297. );
  1298. }
  1299. foreach($filters['params'] as $param) {
  1300. $propParamExpressions[] = $query->expr()->andX(
  1301. $query->expr()->eq('i.name', $query->createNamedParameter($param['property'])),
  1302. $query->expr()->eq('i.parameter', $query->createNamedParameter($param['parameter']))
  1303. );
  1304. }
  1305. if (count($propParamExpressions) === 1) {
  1306. $propParamExpr = $propParamExpressions[0];
  1307. } else {
  1308. $propParamExpr = call_user_func_array([$query->expr(), 'orX'], $propParamExpressions);
  1309. }
  1310. $query->select(['c.calendarid', 'c.uri'])
  1311. ->from($this->dbObjectPropertiesTable, 'i')
  1312. ->join('i', 'calendarobjects', 'c', $query->expr()->eq('i.objectid', 'c.id'))
  1313. ->where($calExpr)
  1314. ->andWhere($compExpr)
  1315. ->andWhere($propParamExpr)
  1316. ->andWhere($query->expr()->iLike('i.value',
  1317. $query->createNamedParameter('%'.$this->db->escapeLikeParameter($filters['search-term']).'%')));
  1318. if ($offset) {
  1319. $query->setFirstResult($offset);
  1320. }
  1321. if ($limit) {
  1322. $query->setMaxResults($limit);
  1323. }
  1324. $stmt = $query->execute();
  1325. $result = [];
  1326. while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
  1327. $path = $uriMapper[$row['calendarid']] . '/' . $row['uri'];
  1328. if (!in_array($path, $result)) {
  1329. $result[] = $path;
  1330. }
  1331. }
  1332. return $result;
  1333. }
  1334. /**
  1335. * used for Nextcloud's calendar API
  1336. *
  1337. * @param array $calendarInfo
  1338. * @param string $pattern
  1339. * @param array $searchProperties
  1340. * @param array $options
  1341. * @param integer|null $limit
  1342. * @param integer|null $offset
  1343. *
  1344. * @return array
  1345. */
  1346. public function search(array $calendarInfo, $pattern, array $searchProperties,
  1347. array $options, $limit, $offset) {
  1348. $outerQuery = $this->db->getQueryBuilder();
  1349. $innerQuery = $this->db->getQueryBuilder();
  1350. $innerQuery->selectDistinct('op.objectid')
  1351. ->from($this->dbObjectPropertiesTable, 'op')
  1352. ->andWhere($innerQuery->expr()->eq('op.calendarid',
  1353. $outerQuery->createNamedParameter($calendarInfo['id'])))
  1354. ->andWhere($innerQuery->expr()->eq('op.calendartype',
  1355. $outerQuery->createNamedParameter(self::CALENDAR_TYPE_CALENDAR)));
  1356. // only return public items for shared calendars for now
  1357. if ($calendarInfo['principaluri'] !== $calendarInfo['{http://owncloud.org/ns}owner-principal']) {
  1358. $innerQuery->andWhere($innerQuery->expr()->eq('c.classification',
  1359. $outerQuery->createNamedParameter(self::CLASSIFICATION_PUBLIC)));
  1360. }
  1361. $or = $innerQuery->expr()->orX();
  1362. foreach($searchProperties as $searchProperty) {
  1363. $or->add($innerQuery->expr()->eq('op.name',
  1364. $outerQuery->createNamedParameter($searchProperty)));
  1365. }
  1366. $innerQuery->andWhere($or);
  1367. if ($pattern !== '') {
  1368. $innerQuery->andWhere($innerQuery->expr()->iLike('op.value',
  1369. $outerQuery->createNamedParameter('%' .
  1370. $this->db->escapeLikeParameter($pattern) . '%')));
  1371. }
  1372. $outerQuery->select('c.id', 'c.calendardata', 'c.componenttype', 'c.uid', 'c.uri')
  1373. ->from('calendarobjects', 'c');
  1374. if (isset($options['timerange'])) {
  1375. if (isset($options['timerange']['start'])) {
  1376. $outerQuery->andWhere($outerQuery->expr()->gt('lastoccurence',
  1377. $outerQuery->createNamedParameter($options['timerange']['start']->getTimeStamp)));
  1378. }
  1379. if (isset($options['timerange']['end'])) {
  1380. $outerQuery->andWhere($outerQuery->expr()->lt('firstoccurence',
  1381. $outerQuery->createNamedParameter($options['timerange']['end']->getTimeStamp)));
  1382. }
  1383. }
  1384. if (isset($options['types'])) {
  1385. $or = $outerQuery->expr()->orX();
  1386. foreach($options['types'] as $type) {
  1387. $or->add($outerQuery->expr()->eq('componenttype',
  1388. $outerQuery->createNamedParameter($type)));
  1389. }
  1390. $outerQuery->andWhere($or);
  1391. }
  1392. $outerQuery->andWhere($outerQuery->expr()->in('c.id',
  1393. $outerQuery->createFunction($innerQuery->getSQL())));
  1394. if ($offset) {
  1395. $outerQuery->setFirstResult($offset);
  1396. }
  1397. if ($limit) {
  1398. $outerQuery->setMaxResults($limit);
  1399. }
  1400. $result = $outerQuery->execute();
  1401. $calendarObjects = $result->fetchAll();
  1402. return array_map(function($o) {
  1403. $calendarData = Reader::read($o['calendardata']);
  1404. $comps = $calendarData->getComponents();
  1405. $objects = [];
  1406. $timezones = [];
  1407. foreach($comps as $comp) {
  1408. if ($comp instanceof VTimeZone) {
  1409. $timezones[] = $comp;
  1410. } else {
  1411. $objects[] = $comp;
  1412. }
  1413. }
  1414. return [
  1415. 'id' => $o['id'],
  1416. 'type' => $o['componenttype'],
  1417. 'uid' => $o['uid'],
  1418. 'uri' => $o['uri'],
  1419. 'objects' => array_map(function($c) {
  1420. return $this->transformSearchData($c);
  1421. }, $objects),
  1422. 'timezones' => array_map(function($c) {
  1423. return $this->transformSearchData($c);
  1424. }, $timezones),
  1425. ];
  1426. }, $calendarObjects);
  1427. }
  1428. /**
  1429. * @param Component $comp
  1430. * @return array
  1431. */
  1432. private function transformSearchData(Component $comp) {
  1433. $data = [];
  1434. /** @var Component[] $subComponents */
  1435. $subComponents = $comp->getComponents();
  1436. /** @var Property[] $properties */
  1437. $properties = array_filter($comp->children(), function($c) {
  1438. return $c instanceof Property;
  1439. });
  1440. $validationRules = $comp->getValidationRules();
  1441. foreach($subComponents as $subComponent) {
  1442. $name = $subComponent->name;
  1443. if (!isset($data[$name])) {
  1444. $data[$name] = [];
  1445. }
  1446. $data[$name][] = $this->transformSearchData($subComponent);
  1447. }
  1448. foreach($properties as $property) {
  1449. $name = $property->name;
  1450. if (!isset($validationRules[$name])) {
  1451. $validationRules[$name] = '*';
  1452. }
  1453. $rule = $validationRules[$property->name];
  1454. if ($rule === '+' || $rule === '*') { // multiple
  1455. if (!isset($data[$name])) {
  1456. $data[$name] = [];
  1457. }
  1458. $data[$name][] = $this->transformSearchProperty($property);
  1459. } else { // once
  1460. $data[$name] = $this->transformSearchProperty($property);
  1461. }
  1462. }
  1463. return $data;
  1464. }
  1465. /**
  1466. * @param Property $prop
  1467. * @return array
  1468. */
  1469. private function transformSearchProperty(Property $prop) {
  1470. // No need to check Date, as it extends DateTime
  1471. if ($prop instanceof Property\ICalendar\DateTime) {
  1472. $value = $prop->getDateTime();
  1473. } else {
  1474. $value = $prop->getValue();
  1475. }
  1476. return [
  1477. $value,
  1478. $prop->parameters()
  1479. ];
  1480. }
  1481. /**
  1482. * Searches through all of a users calendars and calendar objects to find
  1483. * an object with a specific UID.
  1484. *
  1485. * This method should return the path to this object, relative to the
  1486. * calendar home, so this path usually only contains two parts:
  1487. *
  1488. * calendarpath/objectpath.ics
  1489. *
  1490. * If the uid is not found, return null.
  1491. *
  1492. * This method should only consider * objects that the principal owns, so
  1493. * any calendars owned by other principals that also appear in this
  1494. * collection should be ignored.
  1495. *
  1496. * @param string $principalUri
  1497. * @param string $uid
  1498. * @return string|null
  1499. */
  1500. function getCalendarObjectByUID($principalUri, $uid) {
  1501. $query = $this->db->getQueryBuilder();
  1502. $query->selectAlias('c.uri', 'calendaruri')->selectAlias('co.uri', 'objecturi')
  1503. ->from('calendarobjects', 'co')
  1504. ->leftJoin('co', 'calendars', 'c', $query->expr()->eq('co.calendarid', 'c.id'))
  1505. ->where($query->expr()->eq('c.principaluri', $query->createNamedParameter($principalUri)))
  1506. ->andWhere($query->expr()->eq('co.uid', $query->createNamedParameter($uid)))
  1507. ->andWhere($query->expr()->eq('co.uid', $query->createNamedParameter($uid)));
  1508. $stmt = $query->execute();
  1509. if ($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
  1510. return $row['calendaruri'] . '/' . $row['objecturi'];
  1511. }
  1512. return null;
  1513. }
  1514. /**
  1515. * The getChanges method returns all the changes that have happened, since
  1516. * the specified syncToken in the specified calendar.
  1517. *
  1518. * This function should return an array, such as the following:
  1519. *
  1520. * [
  1521. * 'syncToken' => 'The current synctoken',
  1522. * 'added' => [
  1523. * 'new.txt',
  1524. * ],
  1525. * 'modified' => [
  1526. * 'modified.txt',
  1527. * ],
  1528. * 'deleted' => [
  1529. * 'foo.php.bak',
  1530. * 'old.txt'
  1531. * ]
  1532. * );
  1533. *
  1534. * The returned syncToken property should reflect the *current* syncToken
  1535. * of the calendar, as reported in the {http://sabredav.org/ns}sync-token
  1536. * property This is * needed here too, to ensure the operation is atomic.
  1537. *
  1538. * If the $syncToken argument is specified as null, this is an initial
  1539. * sync, and all members should be reported.
  1540. *
  1541. * The modified property is an array of nodenames that have changed since
  1542. * the last token.
  1543. *
  1544. * The deleted property is an array with nodenames, that have been deleted
  1545. * from collection.
  1546. *
  1547. * The $syncLevel argument is basically the 'depth' of the report. If it's
  1548. * 1, you only have to report changes that happened only directly in
  1549. * immediate descendants. If it's 2, it should also include changes from
  1550. * the nodes below the child collections. (grandchildren)
  1551. *
  1552. * The $limit argument allows a client to specify how many results should
  1553. * be returned at most. If the limit is not specified, it should be treated
  1554. * as infinite.
  1555. *
  1556. * If the limit (infinite or not) is higher than you're willing to return,
  1557. * you should throw a Sabre\DAV\Exception\TooMuchMatches() exception.
  1558. *
  1559. * If the syncToken is expired (due to data cleanup) or unknown, you must
  1560. * return null.
  1561. *
  1562. * The limit is 'suggestive'. You are free to ignore it.
  1563. *
  1564. * @param string $calendarId
  1565. * @param string $syncToken
  1566. * @param int $syncLevel
  1567. * @param int $limit
  1568. * @param int $calendarType
  1569. * @return array
  1570. */
  1571. function getChangesForCalendar($calendarId, $syncToken, $syncLevel, $limit = null, $calendarType=self::CALENDAR_TYPE_CALENDAR) {
  1572. // Current synctoken
  1573. $stmt = $this->db->prepare('SELECT `synctoken` FROM `*PREFIX*calendars` WHERE `id` = ?');
  1574. $stmt->execute([ $calendarId ]);
  1575. $currentToken = $stmt->fetchColumn(0);
  1576. if (is_null($currentToken)) {
  1577. return null;
  1578. }
  1579. $result = [
  1580. 'syncToken' => $currentToken,
  1581. 'added' => [],
  1582. 'modified' => [],
  1583. 'deleted' => [],
  1584. ];
  1585. if ($syncToken) {
  1586. $query = "SELECT `uri`, `operation` FROM `*PREFIX*calendarchanges` WHERE `synctoken` >= ? AND `synctoken` < ? AND `calendarid` = ? AND `calendartype` = ? ORDER BY `synctoken`";
  1587. if ($limit>0) {
  1588. $query.= " LIMIT " . (int)$limit;
  1589. }
  1590. // Fetching all changes
  1591. $stmt = $this->db->prepare($query);
  1592. $stmt->execute([$syncToken, $currentToken, $calendarId, $calendarType]);
  1593. $changes = [];
  1594. // This loop ensures that any duplicates are overwritten, only the
  1595. // last change on a node is relevant.
  1596. while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
  1597. $changes[$row['uri']] = $row['operation'];
  1598. }
  1599. foreach($changes as $uri => $operation) {
  1600. switch($operation) {
  1601. case 1 :
  1602. $result['added'][] = $uri;
  1603. break;
  1604. case 2 :
  1605. $result['modified'][] = $uri;
  1606. break;
  1607. case 3 :
  1608. $result['deleted'][] = $uri;
  1609. break;
  1610. }
  1611. }
  1612. } else {
  1613. // No synctoken supplied, this is the initial sync.
  1614. $query = "SELECT `uri` FROM `*PREFIX*calendarobjects` WHERE `calendarid` = ? AND `calendartype` = ?";
  1615. $stmt = $this->db->prepare($query);
  1616. $stmt->execute([$calendarId, $calendarType]);
  1617. $result['added'] = $stmt->fetchAll(\PDO::FETCH_COLUMN);
  1618. }
  1619. return $result;
  1620. }
  1621. /**
  1622. * Returns a list of subscriptions for a principal.
  1623. *
  1624. * Every subscription is an array with the following keys:
  1625. * * id, a unique id that will be used by other functions to modify the
  1626. * subscription. This can be the same as the uri or a database key.
  1627. * * uri. This is just the 'base uri' or 'filename' of the subscription.
  1628. * * principaluri. The owner of the subscription. Almost always the same as
  1629. * principalUri passed to this method.
  1630. *
  1631. * Furthermore, all the subscription info must be returned too:
  1632. *
  1633. * 1. {DAV:}displayname
  1634. * 2. {http://apple.com/ns/ical/}refreshrate
  1635. * 3. {http://calendarserver.org/ns/}subscribed-strip-todos (omit if todos
  1636. * should not be stripped).
  1637. * 4. {http://calendarserver.org/ns/}subscribed-strip-alarms (omit if alarms
  1638. * should not be stripped).
  1639. * 5. {http://calendarserver.org/ns/}subscribed-strip-attachments (omit if
  1640. * attachments should not be stripped).
  1641. * 6. {http://calendarserver.org/ns/}source (Must be a
  1642. * Sabre\DAV\Property\Href).
  1643. * 7. {http://apple.com/ns/ical/}calendar-color
  1644. * 8. {http://apple.com/ns/ical/}calendar-order
  1645. * 9. {urn:ietf:params:xml:ns:caldav}supported-calendar-component-set
  1646. * (should just be an instance of
  1647. * Sabre\CalDAV\Property\SupportedCalendarComponentSet, with a bunch of
  1648. * default components).
  1649. *
  1650. * @param string $principalUri
  1651. * @return array
  1652. */
  1653. function getSubscriptionsForUser($principalUri) {
  1654. $fields = array_values($this->subscriptionPropertyMap);
  1655. $fields[] = 'id';
  1656. $fields[] = 'uri';
  1657. $fields[] = 'source';
  1658. $fields[] = 'principaluri';
  1659. $fields[] = 'lastmodified';
  1660. $fields[] = 'synctoken';
  1661. $query = $this->db->getQueryBuilder();
  1662. $query->select($fields)
  1663. ->from('calendarsubscriptions')
  1664. ->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
  1665. ->orderBy('calendarorder', 'asc');
  1666. $stmt =$query->execute();
  1667. $subscriptions = [];
  1668. while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
  1669. $subscription = [
  1670. 'id' => $row['id'],
  1671. 'uri' => $row['uri'],
  1672. 'principaluri' => $row['principaluri'],
  1673. 'source' => $row['source'],
  1674. 'lastmodified' => $row['lastmodified'],
  1675. '{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet(['VTODO', 'VEVENT']),
  1676. '{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
  1677. ];
  1678. foreach($this->subscriptionPropertyMap as $xmlName=>$dbName) {
  1679. if (!is_null($row[$dbName])) {
  1680. $subscription[$xmlName] = $row[$dbName];
  1681. }
  1682. }
  1683. $subscriptions[] = $subscription;
  1684. }
  1685. return $subscriptions;
  1686. }
  1687. /**
  1688. * Creates a new subscription for a principal.
  1689. *
  1690. * If the creation was a success, an id must be returned that can be used to reference
  1691. * this subscription in other methods, such as updateSubscription.
  1692. *
  1693. * @param string $principalUri
  1694. * @param string $uri
  1695. * @param array $properties
  1696. * @return mixed
  1697. */
  1698. function createSubscription($principalUri, $uri, array $properties) {
  1699. if (!isset($properties['{http://calendarserver.org/ns/}source'])) {
  1700. throw new Forbidden('The {http://calendarserver.org/ns/}source property is required when creating subscriptions');
  1701. }
  1702. $values = [
  1703. 'principaluri' => $principalUri,
  1704. 'uri' => $uri,
  1705. 'source' => $properties['{http://calendarserver.org/ns/}source']->getHref(),
  1706. 'lastmodified' => time(),
  1707. ];
  1708. $propertiesBoolean = ['striptodos', 'stripalarms', 'stripattachments'];
  1709. foreach($this->subscriptionPropertyMap as $xmlName=>$dbName) {
  1710. if (array_key_exists($xmlName, $properties)) {
  1711. $values[$dbName] = $properties[$xmlName];
  1712. if (in_array($dbName, $propertiesBoolean)) {
  1713. $values[$dbName] = true;
  1714. }
  1715. }
  1716. }
  1717. $valuesToInsert = array();
  1718. $query = $this->db->getQueryBuilder();
  1719. foreach (array_keys($values) as $name) {
  1720. $valuesToInsert[$name] = $query->createNamedParameter($values[$name]);
  1721. }
  1722. $query->insert('calendarsubscriptions')
  1723. ->values($valuesToInsert)
  1724. ->execute();
  1725. $subscriptionId = $this->db->lastInsertId('*PREFIX*calendarsubscriptions');
  1726. $this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::createSubscription', new GenericEvent(
  1727. '\OCA\DAV\CalDAV\CalDavBackend::createSubscription',
  1728. [
  1729. 'subscriptionId' => $subscriptionId,
  1730. 'subscriptionData' => $this->getSubscriptionById($subscriptionId),
  1731. ]));
  1732. return $subscriptionId;
  1733. }
  1734. /**
  1735. * Updates a subscription
  1736. *
  1737. * The list of mutations is stored in a Sabre\DAV\PropPatch object.
  1738. * To do the actual updates, you must tell this object which properties
  1739. * you're going to process with the handle() method.
  1740. *
  1741. * Calling the handle method is like telling the PropPatch object "I
  1742. * promise I can handle updating this property".
  1743. *
  1744. * Read the PropPatch documentation for more info and examples.
  1745. *
  1746. * @param mixed $subscriptionId
  1747. * @param PropPatch $propPatch
  1748. * @return void
  1749. */
  1750. function updateSubscription($subscriptionId, PropPatch $propPatch) {
  1751. $supportedProperties = array_keys($this->subscriptionPropertyMap);
  1752. $supportedProperties[] = '{http://calendarserver.org/ns/}source';
  1753. /**
  1754. * @suppress SqlInjectionChecker
  1755. */
  1756. $propPatch->handle($supportedProperties, function($mutations) use ($subscriptionId) {
  1757. $newValues = [];
  1758. foreach($mutations as $propertyName=>$propertyValue) {
  1759. if ($propertyName === '{http://calendarserver.org/ns/}source') {
  1760. $newValues['source'] = $propertyValue->getHref();
  1761. } else {
  1762. $fieldName = $this->subscriptionPropertyMap[$propertyName];
  1763. $newValues[$fieldName] = $propertyValue;
  1764. }
  1765. }
  1766. $query = $this->db->getQueryBuilder();
  1767. $query->update('calendarsubscriptions')
  1768. ->set('lastmodified', $query->createNamedParameter(time()));
  1769. foreach($newValues as $fieldName=>$value) {
  1770. $query->set($fieldName, $query->createNamedParameter($value));
  1771. }
  1772. $query->where($query->expr()->eq('id', $query->createNamedParameter($subscriptionId)))
  1773. ->execute();
  1774. $this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::updateSubscription', new GenericEvent(
  1775. '\OCA\DAV\CalDAV\CalDavBackend::updateSubscription',
  1776. [
  1777. 'subscriptionId' => $subscriptionId,
  1778. 'subscriptionData' => $this->getSubscriptionById($subscriptionId),
  1779. 'propertyMutations' => $mutations,
  1780. ]));
  1781. return true;
  1782. });
  1783. }
  1784. /**
  1785. * Deletes a subscription.
  1786. *
  1787. * @param mixed $subscriptionId
  1788. * @return void
  1789. */
  1790. function deleteSubscription($subscriptionId) {
  1791. $this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::deleteSubscription', new GenericEvent(
  1792. '\OCA\DAV\CalDAV\CalDavBackend::deleteSubscription',
  1793. [
  1794. 'subscriptionId' => $subscriptionId,
  1795. 'subscriptionData' => $this->getSubscriptionById($subscriptionId),
  1796. ]));
  1797. $query = $this->db->getQueryBuilder();
  1798. $query->delete('calendarsubscriptions')
  1799. ->where($query->expr()->eq('id', $query->createNamedParameter($subscriptionId)))
  1800. ->execute();
  1801. $query = $this->db->getQueryBuilder();
  1802. $query->delete('calendarobjects')
  1803. ->where($query->expr()->eq('calendarid', $query->createNamedParameter($subscriptionId)))
  1804. ->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)))
  1805. ->execute();
  1806. $query->delete('calendarchanges')
  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($this->dbObjectPropertiesTable)
  1811. ->where($query->expr()->eq('calendarid', $query->createNamedParameter($subscriptionId)))
  1812. ->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)))
  1813. ->execute();
  1814. }
  1815. /**
  1816. * Returns a single scheduling object for the inbox collection.
  1817. *
  1818. * The returned array should contain the following elements:
  1819. * * uri - A unique basename for the object. This will be used to
  1820. * construct a full uri.
  1821. * * calendardata - The iCalendar object
  1822. * * lastmodified - The last modification date. Can be an int for a unix
  1823. * timestamp, or a PHP DateTime object.
  1824. * * etag - A unique token that must change if the object changed.
  1825. * * size - The size of the object, in bytes.
  1826. *
  1827. * @param string $principalUri
  1828. * @param string $objectUri
  1829. * @return array
  1830. */
  1831. function getSchedulingObject($principalUri, $objectUri) {
  1832. $query = $this->db->getQueryBuilder();
  1833. $stmt = $query->select(['uri', 'calendardata', 'lastmodified', 'etag', 'size'])
  1834. ->from('schedulingobjects')
  1835. ->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
  1836. ->andWhere($query->expr()->eq('uri', $query->createNamedParameter($objectUri)))
  1837. ->execute();
  1838. $row = $stmt->fetch(\PDO::FETCH_ASSOC);
  1839. if(!$row) {
  1840. return null;
  1841. }
  1842. return [
  1843. 'uri' => $row['uri'],
  1844. 'calendardata' => $row['calendardata'],
  1845. 'lastmodified' => $row['lastmodified'],
  1846. 'etag' => '"' . $row['etag'] . '"',
  1847. 'size' => (int)$row['size'],
  1848. ];
  1849. }
  1850. /**
  1851. * Returns all scheduling objects for the inbox collection.
  1852. *
  1853. * These objects should be returned as an array. Every item in the array
  1854. * should follow the same structure as returned from getSchedulingObject.
  1855. *
  1856. * The main difference is that 'calendardata' is optional.
  1857. *
  1858. * @param string $principalUri
  1859. * @return array
  1860. */
  1861. function getSchedulingObjects($principalUri) {
  1862. $query = $this->db->getQueryBuilder();
  1863. $stmt = $query->select(['uri', 'calendardata', 'lastmodified', 'etag', 'size'])
  1864. ->from('schedulingobjects')
  1865. ->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
  1866. ->execute();
  1867. $result = [];
  1868. foreach($stmt->fetchAll(\PDO::FETCH_ASSOC) as $row) {
  1869. $result[] = [
  1870. 'calendardata' => $row['calendardata'],
  1871. 'uri' => $row['uri'],
  1872. 'lastmodified' => $row['lastmodified'],
  1873. 'etag' => '"' . $row['etag'] . '"',
  1874. 'size' => (int)$row['size'],
  1875. ];
  1876. }
  1877. return $result;
  1878. }
  1879. /**
  1880. * Deletes a scheduling object from the inbox collection.
  1881. *
  1882. * @param string $principalUri
  1883. * @param string $objectUri
  1884. * @return void
  1885. */
  1886. function deleteSchedulingObject($principalUri, $objectUri) {
  1887. $query = $this->db->getQueryBuilder();
  1888. $query->delete('schedulingobjects')
  1889. ->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
  1890. ->andWhere($query->expr()->eq('uri', $query->createNamedParameter($objectUri)))
  1891. ->execute();
  1892. }
  1893. /**
  1894. * Creates a new scheduling object. This should land in a users' inbox.
  1895. *
  1896. * @param string $principalUri
  1897. * @param string $objectUri
  1898. * @param string $objectData
  1899. * @return void
  1900. */
  1901. function createSchedulingObject($principalUri, $objectUri, $objectData) {
  1902. $query = $this->db->getQueryBuilder();
  1903. $query->insert('schedulingobjects')
  1904. ->values([
  1905. 'principaluri' => $query->createNamedParameter($principalUri),
  1906. 'calendardata' => $query->createNamedParameter($objectData, IQueryBuilder::PARAM_LOB),
  1907. 'uri' => $query->createNamedParameter($objectUri),
  1908. 'lastmodified' => $query->createNamedParameter(time()),
  1909. 'etag' => $query->createNamedParameter(md5($objectData)),
  1910. 'size' => $query->createNamedParameter(strlen($objectData))
  1911. ])
  1912. ->execute();
  1913. }
  1914. /**
  1915. * Adds a change record to the calendarchanges table.
  1916. *
  1917. * @param mixed $calendarId
  1918. * @param string $objectUri
  1919. * @param int $operation 1 = add, 2 = modify, 3 = delete.
  1920. * @param int $calendarType
  1921. * @return void
  1922. */
  1923. protected function addChange($calendarId, $objectUri, $operation, $calendarType=self::CALENDAR_TYPE_CALENDAR) {
  1924. $table = $calendarType === self::CALENDAR_TYPE_CALENDAR ? 'calendars': 'calendarsubscriptions';
  1925. $query = $this->db->getQueryBuilder();
  1926. $query->select('synctoken')
  1927. ->from($table)
  1928. ->where($query->expr()->eq('id', $query->createNamedParameter($calendarId)));
  1929. $syncToken = (int)$query->execute()->fetchColumn();
  1930. $query = $this->db->getQueryBuilder();
  1931. $query->insert('calendarchanges')
  1932. ->values([
  1933. 'uri' => $query->createNamedParameter($objectUri),
  1934. 'synctoken' => $query->createNamedParameter($syncToken),
  1935. 'calendarid' => $query->createNamedParameter($calendarId),
  1936. 'operation' => $query->createNamedParameter($operation),
  1937. 'calendartype' => $query->createNamedParameter($calendarType),
  1938. ])
  1939. ->execute();
  1940. $stmt = $this->db->prepare("UPDATE `*PREFIX*$table` SET `synctoken` = `synctoken` + 1 WHERE `id` = ?");
  1941. $stmt->execute([
  1942. $calendarId
  1943. ]);
  1944. }
  1945. /**
  1946. * Parses some information from calendar objects, used for optimized
  1947. * calendar-queries.
  1948. *
  1949. * Returns an array with the following keys:
  1950. * * etag - An md5 checksum of the object without the quotes.
  1951. * * size - Size of the object in bytes
  1952. * * componentType - VEVENT, VTODO or VJOURNAL
  1953. * * firstOccurence
  1954. * * lastOccurence
  1955. * * uid - value of the UID property
  1956. *
  1957. * @param string $calendarData
  1958. * @return array
  1959. */
  1960. public function getDenormalizedData($calendarData) {
  1961. $vObject = Reader::read($calendarData);
  1962. $componentType = null;
  1963. $component = null;
  1964. $firstOccurrence = null;
  1965. $lastOccurrence = null;
  1966. $uid = null;
  1967. $classification = self::CLASSIFICATION_PUBLIC;
  1968. foreach($vObject->getComponents() as $component) {
  1969. if ($component->name!=='VTIMEZONE') {
  1970. $componentType = $component->name;
  1971. $uid = (string)$component->UID;
  1972. break;
  1973. }
  1974. }
  1975. if (!$componentType) {
  1976. throw new \Sabre\DAV\Exception\BadRequest('Calendar objects must have a VJOURNAL, VEVENT or VTODO component');
  1977. }
  1978. if ($componentType === 'VEVENT' && $component->DTSTART) {
  1979. $firstOccurrence = $component->DTSTART->getDateTime()->getTimeStamp();
  1980. // Finding the last occurrence is a bit harder
  1981. if (!isset($component->RRULE)) {
  1982. if (isset($component->DTEND)) {
  1983. $lastOccurrence = $component->DTEND->getDateTime()->getTimeStamp();
  1984. } elseif (isset($component->DURATION)) {
  1985. $endDate = clone $component->DTSTART->getDateTime();
  1986. $endDate->add(DateTimeParser::parse($component->DURATION->getValue()));
  1987. $lastOccurrence = $endDate->getTimeStamp();
  1988. } elseif (!$component->DTSTART->hasTime()) {
  1989. $endDate = clone $component->DTSTART->getDateTime();
  1990. $endDate->modify('+1 day');
  1991. $lastOccurrence = $endDate->getTimeStamp();
  1992. } else {
  1993. $lastOccurrence = $firstOccurrence;
  1994. }
  1995. } else {
  1996. $it = new EventIterator($vObject, (string)$component->UID);
  1997. $maxDate = new \DateTime(self::MAX_DATE);
  1998. if ($it->isInfinite()) {
  1999. $lastOccurrence = $maxDate->getTimestamp();
  2000. } else {
  2001. $end = $it->getDtEnd();
  2002. while($it->valid() && $end < $maxDate) {
  2003. $end = $it->getDtEnd();
  2004. $it->next();
  2005. }
  2006. $lastOccurrence = $end->getTimestamp();
  2007. }
  2008. }
  2009. }
  2010. if ($component->CLASS) {
  2011. $classification = CalDavBackend::CLASSIFICATION_PRIVATE;
  2012. switch ($component->CLASS->getValue()) {
  2013. case 'PUBLIC':
  2014. $classification = CalDavBackend::CLASSIFICATION_PUBLIC;
  2015. break;
  2016. case 'CONFIDENTIAL':
  2017. $classification = CalDavBackend::CLASSIFICATION_CONFIDENTIAL;
  2018. break;
  2019. }
  2020. }
  2021. return [
  2022. 'etag' => md5($calendarData),
  2023. 'size' => strlen($calendarData),
  2024. 'componentType' => $componentType,
  2025. 'firstOccurence' => is_null($firstOccurrence) ? null : max(0, $firstOccurrence),
  2026. 'lastOccurence' => $lastOccurrence,
  2027. 'uid' => $uid,
  2028. 'classification' => $classification
  2029. ];
  2030. }
  2031. /**
  2032. * @param $cardData
  2033. * @return bool|string
  2034. */
  2035. private function readBlob($cardData) {
  2036. if (is_resource($cardData)) {
  2037. return stream_get_contents($cardData);
  2038. }
  2039. return $cardData;
  2040. }
  2041. /**
  2042. * @param IShareable $shareable
  2043. * @param array $add
  2044. * @param array $remove
  2045. */
  2046. public function updateShares($shareable, $add, $remove) {
  2047. $calendarId = $shareable->getResourceId();
  2048. $this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::updateShares', new GenericEvent(
  2049. '\OCA\DAV\CalDAV\CalDavBackend::updateShares',
  2050. [
  2051. 'calendarId' => $calendarId,
  2052. 'calendarData' => $this->getCalendarById($calendarId),
  2053. 'shares' => $this->getShares($calendarId),
  2054. 'add' => $add,
  2055. 'remove' => $remove,
  2056. ]));
  2057. $this->calendarSharingBackend->updateShares($shareable, $add, $remove);
  2058. }
  2059. /**
  2060. * @param int $resourceId
  2061. * @param int $calendarType
  2062. * @return array
  2063. */
  2064. public function getShares($resourceId, $calendarType=self::CALENDAR_TYPE_CALENDAR) {
  2065. return $this->calendarSharingBackend->getShares($resourceId);
  2066. }
  2067. /**
  2068. * @param boolean $value
  2069. * @param \OCA\DAV\CalDAV\Calendar $calendar
  2070. * @return string|null
  2071. */
  2072. public function setPublishStatus($value, $calendar) {
  2073. $calendarId = $calendar->getResourceId();
  2074. $this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::publishCalendar', new GenericEvent(
  2075. '\OCA\DAV\CalDAV\CalDavBackend::updateShares',
  2076. [
  2077. 'calendarId' => $calendarId,
  2078. 'calendarData' => $this->getCalendarById($calendarId),
  2079. 'public' => $value,
  2080. ]));
  2081. $query = $this->db->getQueryBuilder();
  2082. if ($value) {
  2083. $publicUri = $this->random->generate(16, ISecureRandom::CHAR_HUMAN_READABLE);
  2084. $query->insert('dav_shares')
  2085. ->values([
  2086. 'principaluri' => $query->createNamedParameter($calendar->getPrincipalURI()),
  2087. 'type' => $query->createNamedParameter('calendar'),
  2088. 'access' => $query->createNamedParameter(self::ACCESS_PUBLIC),
  2089. 'resourceid' => $query->createNamedParameter($calendar->getResourceId()),
  2090. 'publicuri' => $query->createNamedParameter($publicUri)
  2091. ]);
  2092. $query->execute();
  2093. return $publicUri;
  2094. }
  2095. $query->delete('dav_shares')
  2096. ->where($query->expr()->eq('resourceid', $query->createNamedParameter($calendar->getResourceId())))
  2097. ->andWhere($query->expr()->eq('access', $query->createNamedParameter(self::ACCESS_PUBLIC)));
  2098. $query->execute();
  2099. return null;
  2100. }
  2101. /**
  2102. * @param \OCA\DAV\CalDAV\Calendar $calendar
  2103. * @return mixed
  2104. */
  2105. public function getPublishStatus($calendar) {
  2106. $query = $this->db->getQueryBuilder();
  2107. $result = $query->select('publicuri')
  2108. ->from('dav_shares')
  2109. ->where($query->expr()->eq('resourceid', $query->createNamedParameter($calendar->getResourceId())))
  2110. ->andWhere($query->expr()->eq('access', $query->createNamedParameter(self::ACCESS_PUBLIC)))
  2111. ->execute();
  2112. $row = $result->fetch();
  2113. $result->closeCursor();
  2114. return $row ? reset($row) : false;
  2115. }
  2116. /**
  2117. * @param int $resourceId
  2118. * @param array $acl
  2119. * @return array
  2120. */
  2121. public function applyShareAcl($resourceId, $acl) {
  2122. return $this->calendarSharingBackend->applyShareAcl($resourceId, $acl);
  2123. }
  2124. /**
  2125. * update properties table
  2126. *
  2127. * @param int $calendarId
  2128. * @param string $objectUri
  2129. * @param string $calendarData
  2130. * @param int $calendarType
  2131. */
  2132. public function updateProperties($calendarId, $objectUri, $calendarData, $calendarType=self::CALENDAR_TYPE_CALENDAR) {
  2133. $objectId = $this->getCalendarObjectId($calendarId, $objectUri, $calendarType);
  2134. try {
  2135. $vCalendar = $this->readCalendarData($calendarData);
  2136. } catch (\Exception $ex) {
  2137. return;
  2138. }
  2139. $this->purgeProperties($calendarId, $objectId);
  2140. $query = $this->db->getQueryBuilder();
  2141. $query->insert($this->dbObjectPropertiesTable)
  2142. ->values(
  2143. [
  2144. 'calendarid' => $query->createNamedParameter($calendarId),
  2145. 'calendartype' => $query->createNamedParameter($calendarType),
  2146. 'objectid' => $query->createNamedParameter($objectId),
  2147. 'name' => $query->createParameter('name'),
  2148. 'parameter' => $query->createParameter('parameter'),
  2149. 'value' => $query->createParameter('value'),
  2150. ]
  2151. );
  2152. $indexComponents = ['VEVENT', 'VJOURNAL', 'VTODO'];
  2153. foreach ($vCalendar->getComponents() as $component) {
  2154. if (!in_array($component->name, $indexComponents)) {
  2155. continue;
  2156. }
  2157. foreach ($component->children() as $property) {
  2158. if (in_array($property->name, self::$indexProperties)) {
  2159. $value = $property->getValue();
  2160. // is this a shitty db?
  2161. if (!$this->db->supports4ByteText()) {
  2162. $value = preg_replace('/[\x{10000}-\x{10FFFF}]/u', "\xEF\xBF\xBD", $value);
  2163. }
  2164. $value = mb_substr($value, 0, 254);
  2165. $query->setParameter('name', $property->name);
  2166. $query->setParameter('parameter', null);
  2167. $query->setParameter('value', $value);
  2168. $query->execute();
  2169. }
  2170. if (array_key_exists($property->name, self::$indexParameters)) {
  2171. $parameters = $property->parameters();
  2172. $indexedParametersForProperty = self::$indexParameters[$property->name];
  2173. foreach ($parameters as $key => $value) {
  2174. if (in_array($key, $indexedParametersForProperty)) {
  2175. // is this a shitty db?
  2176. if ($this->db->supports4ByteText()) {
  2177. $value = preg_replace('/[\x{10000}-\x{10FFFF}]/u', "\xEF\xBF\xBD", $value);
  2178. }
  2179. $value = mb_substr($value, 0, 254);
  2180. $query->setParameter('name', $property->name);
  2181. $query->setParameter('parameter', substr($key, 0, 254));
  2182. $query->setParameter('value', substr($value, 0, 254));
  2183. $query->execute();
  2184. }
  2185. }
  2186. }
  2187. }
  2188. }
  2189. }
  2190. /**
  2191. * deletes all birthday calendars
  2192. */
  2193. public function deleteAllBirthdayCalendars() {
  2194. $query = $this->db->getQueryBuilder();
  2195. $result = $query->select(['id'])->from('calendars')
  2196. ->where($query->expr()->eq('uri', $query->createNamedParameter(BirthdayService::BIRTHDAY_CALENDAR_URI)))
  2197. ->execute();
  2198. $ids = $result->fetchAll();
  2199. foreach($ids as $id) {
  2200. $this->deleteCalendar($id['id']);
  2201. }
  2202. }
  2203. /**
  2204. * @param $subscriptionId
  2205. */
  2206. public function purgeAllCachedEventsForSubscription($subscriptionId) {
  2207. $query = $this->db->getQueryBuilder();
  2208. $query->select('uri')
  2209. ->from('calendarobjects')
  2210. ->where($query->expr()->eq('calendarid', $query->createNamedParameter($subscriptionId)))
  2211. ->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)));
  2212. $stmt = $query->execute();
  2213. $uris = [];
  2214. foreach($stmt->fetchAll(\PDO::FETCH_ASSOC) as $row) {
  2215. $uris[] = $row['uri'];
  2216. }
  2217. $stmt->closeCursor();
  2218. $query = $this->db->getQueryBuilder();
  2219. $query->delete('calendarobjects')
  2220. ->where($query->expr()->eq('calendarid', $query->createNamedParameter($subscriptionId)))
  2221. ->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)))
  2222. ->execute();
  2223. $query->delete('calendarchanges')
  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($this->dbObjectPropertiesTable)
  2228. ->where($query->expr()->eq('calendarid', $query->createNamedParameter($subscriptionId)))
  2229. ->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)))
  2230. ->execute();
  2231. foreach($uris as $uri) {
  2232. $this->addChange($subscriptionId, $uri, 3, self::CALENDAR_TYPE_SUBSCRIPTION);
  2233. }
  2234. }
  2235. /**
  2236. * Move a calendar from one user to another
  2237. *
  2238. * @param string $uriName
  2239. * @param string $uriOrigin
  2240. * @param string $uriDestination
  2241. */
  2242. public function moveCalendar($uriName, $uriOrigin, $uriDestination)
  2243. {
  2244. $query = $this->db->getQueryBuilder();
  2245. $query->update('calendars')
  2246. ->set('principaluri', $query->createNamedParameter($uriDestination))
  2247. ->where($query->expr()->eq('principaluri', $query->createNamedParameter($uriOrigin)))
  2248. ->andWhere($query->expr()->eq('uri', $query->createNamedParameter($uriName)))
  2249. ->execute();
  2250. }
  2251. /**
  2252. * read VCalendar data into a VCalendar object
  2253. *
  2254. * @param string $objectData
  2255. * @return VCalendar
  2256. */
  2257. protected function readCalendarData($objectData) {
  2258. return Reader::read($objectData);
  2259. }
  2260. /**
  2261. * delete all properties from a given calendar object
  2262. *
  2263. * @param int $calendarId
  2264. * @param int $objectId
  2265. */
  2266. protected function purgeProperties($calendarId, $objectId) {
  2267. $query = $this->db->getQueryBuilder();
  2268. $query->delete($this->dbObjectPropertiesTable)
  2269. ->where($query->expr()->eq('objectid', $query->createNamedParameter($objectId)))
  2270. ->andWhere($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)));
  2271. $query->execute();
  2272. }
  2273. /**
  2274. * get ID from a given calendar object
  2275. *
  2276. * @param int $calendarId
  2277. * @param string $uri
  2278. * @param int $calendarType
  2279. * @return int
  2280. */
  2281. protected function getCalendarObjectId($calendarId, $uri, $calendarType):int {
  2282. $query = $this->db->getQueryBuilder();
  2283. $query->select('id')
  2284. ->from('calendarobjects')
  2285. ->where($query->expr()->eq('uri', $query->createNamedParameter($uri)))
  2286. ->andWhere($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)))
  2287. ->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter($calendarType)));
  2288. $result = $query->execute();
  2289. $objectIds = $result->fetch();
  2290. $result->closeCursor();
  2291. if (!isset($objectIds['id'])) {
  2292. throw new \InvalidArgumentException('Calendarobject does not exists: ' . $uri);
  2293. }
  2294. return (int)$objectIds['id'];
  2295. }
  2296. /**
  2297. * return legacy endpoint principal name to new principal name
  2298. *
  2299. * @param $principalUri
  2300. * @param $toV2
  2301. * @return string
  2302. */
  2303. private function convertPrincipal($principalUri, $toV2) {
  2304. if ($this->principalBackend->getPrincipalPrefix() === 'principals') {
  2305. list(, $name) = Uri\split($principalUri);
  2306. if ($toV2 === true) {
  2307. return "principals/users/$name";
  2308. }
  2309. return "principals/$name";
  2310. }
  2311. return $principalUri;
  2312. }
  2313. /**
  2314. * adds information about an owner to the calendar data
  2315. *
  2316. * @param $calendarInfo
  2317. */
  2318. private function addOwnerPrincipal(&$calendarInfo) {
  2319. $ownerPrincipalKey = '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal';
  2320. $displaynameKey = '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_NEXTCLOUD . '}owner-displayname';
  2321. if (isset($calendarInfo[$ownerPrincipalKey])) {
  2322. $uri = $calendarInfo[$ownerPrincipalKey];
  2323. } else {
  2324. $uri = $calendarInfo['principaluri'];
  2325. }
  2326. $principalInformation = $this->principalBackend->getPrincipalByPath($uri);
  2327. if (isset($principalInformation['{DAV:}displayname'])) {
  2328. $calendarInfo[$displaynameKey] = $principalInformation['{DAV:}displayname'];
  2329. }
  2330. }
  2331. }