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

CalDavBackend.php 87KB

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