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