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

CalDavBackend.php 98KB

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