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