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