CalDavBackend.php 88 KB

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