Completed
Push — master ( 5cf799...31899d )
by Daniel
17:07 queued 15s
created
lib/public/Calendar/ICalendarExport.php 1 patch
Indentation   +10 added lines, -10 removed lines patch added patch discarded remove patch
@@ -17,15 +17,15 @@
 block discarded – undo
17 17
  */
18 18
 interface ICalendarExport {
19 19
 	
20
-	/**
21
-	 * Export objects
22
-	 *
23
-	 * @since 32.0.0
24
-	 *
25
-	 * @param CalendarExportOptions|null $options
26
-	 *
27
-	 * @return Generator<\Sabre\VObject\Component\VCalendar>
28
-	 */
29
-	public function export(?CalendarExportOptions $options): Generator;
20
+    /**
21
+     * Export objects
22
+     *
23
+     * @since 32.0.0
24
+     *
25
+     * @param CalendarExportOptions|null $options
26
+     *
27
+     * @return Generator<\Sabre\VObject\Component\VCalendar>
28
+     */
29
+    public function export(?CalendarExportOptions $options): Generator;
30 30
 
31 31
 }
Please login to merge, or discard this patch.
lib/public/Calendar/CalendarExportOptions.php 1 patch
Indentation   +44 added lines, -44 removed lines patch added patch discarded remove patch
@@ -15,54 +15,54 @@
 block discarded – undo
15 15
  */
16 16
 final class CalendarExportOptions {
17 17
 
18
-	/** @var 'ical'|'jcal'|'xcal' */
19
-	private string $format = 'ical';
20
-	private ?string $rangeStart = null;
21
-	private ?int $rangeCount = null;
18
+    /** @var 'ical'|'jcal'|'xcal' */
19
+    private string $format = 'ical';
20
+    private ?string $rangeStart = null;
21
+    private ?int $rangeCount = null;
22 22
 
23
-	/**
24
-	 * Gets the export format
25
-	 *
26
-	 * @return 'ical'|'jcal'|'xcal' (defaults to ical)
27
-	 */
28
-	public function getFormat(): string {
29
-		return $this->format;
30
-	}
23
+    /**
24
+     * Gets the export format
25
+     *
26
+     * @return 'ical'|'jcal'|'xcal' (defaults to ical)
27
+     */
28
+    public function getFormat(): string {
29
+        return $this->format;
30
+    }
31 31
 
32
-	/**
33
-	 * Sets the export format
34
-	 *
35
-	 * @param 'ical'|'jcal'|'xcal' $format
36
-	 */
37
-	public function setFormat(string $format): void {
38
-		$this->format = $format;
39
-	}
32
+    /**
33
+     * Sets the export format
34
+     *
35
+     * @param 'ical'|'jcal'|'xcal' $format
36
+     */
37
+    public function setFormat(string $format): void {
38
+        $this->format = $format;
39
+    }
40 40
 
41
-	/**
42
-	 * Gets the start of the range to export
43
-	 */
44
-	public function getRangeStart(): ?string {
45
-		return $this->rangeStart;
46
-	}
41
+    /**
42
+     * Gets the start of the range to export
43
+     */
44
+    public function getRangeStart(): ?string {
45
+        return $this->rangeStart;
46
+    }
47 47
 
48
-	/**
49
-	 * Sets the start of the range to export
50
-	 */
51
-	public function setRangeStart(?string $rangeStart): void {
52
-		$this->rangeStart = $rangeStart;
53
-	}
48
+    /**
49
+     * Sets the start of the range to export
50
+     */
51
+    public function setRangeStart(?string $rangeStart): void {
52
+        $this->rangeStart = $rangeStart;
53
+    }
54 54
 
55
-	/**
56
-	 * Gets the number of objects to export
57
-	 */
58
-	public function getRangeCount(): ?int {
59
-		return $this->rangeCount;
60
-	}
55
+    /**
56
+     * Gets the number of objects to export
57
+     */
58
+    public function getRangeCount(): ?int {
59
+        return $this->rangeCount;
60
+    }
61 61
 
62
-	/**
63
-	 * Sets the number of objects to export
64
-	 */
65
-	public function setRangeCount(?int $rangeCount): void {
66
-		$this->rangeCount = $rangeCount;
67
-	}
62
+    /**
63
+     * Sets the number of objects to export
64
+     */
65
+    public function setRangeCount(?int $rangeCount): void {
66
+        $this->rangeCount = $rangeCount;
67
+    }
68 68
 }
Please login to merge, or discard this patch.
apps/dav/lib/Command/ExportCalendar.php 1 patch
Indentation   +59 added lines, -59 removed lines patch added patch discarded remove patch
@@ -26,70 +26,70 @@
 block discarded – undo
26 26
  * Used to export data from supported calendars to disk or stdout
27 27
  */
28 28
 #[AsCommand(
29
-	name: 'calendar:export',
30
-	description: 'Export calendar data from supported calendars to disk or stdout',
31
-	hidden: false
29
+    name: 'calendar:export',
30
+    description: 'Export calendar data from supported calendars to disk or stdout',
31
+    hidden: false
32 32
 )]
33 33
 class ExportCalendar extends Command {
34
-	public function __construct(
35
-		private IUserManager $userManager,
36
-		private IManager $calendarManager,
37
-		private ExportService $exportService,
38
-	) {
39
-		parent::__construct();
40
-	}
34
+    public function __construct(
35
+        private IUserManager $userManager,
36
+        private IManager $calendarManager,
37
+        private ExportService $exportService,
38
+    ) {
39
+        parent::__construct();
40
+    }
41 41
 
42
-	protected function configure(): void {
43
-		$this->setName('calendar:export')
44
-			->setDescription('Export calendar data from supported calendars to disk or stdout')
45
-			->addArgument('uid', InputArgument::REQUIRED, 'Id of system user')
46
-			->addArgument('uri', InputArgument::REQUIRED, 'Uri of calendar')
47
-			->addOption('format', null, InputOption::VALUE_REQUIRED, 'Format of output (ical, jcal, xcal) defaults to ical', 'ical')
48
-			->addOption('location', null, InputOption::VALUE_REQUIRED, 'Location of where to write the output. defaults to stdout');
49
-	}
42
+    protected function configure(): void {
43
+        $this->setName('calendar:export')
44
+            ->setDescription('Export calendar data from supported calendars to disk or stdout')
45
+            ->addArgument('uid', InputArgument::REQUIRED, 'Id of system user')
46
+            ->addArgument('uri', InputArgument::REQUIRED, 'Uri of calendar')
47
+            ->addOption('format', null, InputOption::VALUE_REQUIRED, 'Format of output (ical, jcal, xcal) defaults to ical', 'ical')
48
+            ->addOption('location', null, InputOption::VALUE_REQUIRED, 'Location of where to write the output. defaults to stdout');
49
+    }
50 50
 
51
-	protected function execute(InputInterface $input, OutputInterface $output): int {
52
-		$userId = $input->getArgument('uid');
53
-		$calendarId = $input->getArgument('uri');
54
-		$format = $input->getOption('format');
55
-		$location = $input->getOption('location');
51
+    protected function execute(InputInterface $input, OutputInterface $output): int {
52
+        $userId = $input->getArgument('uid');
53
+        $calendarId = $input->getArgument('uri');
54
+        $format = $input->getOption('format');
55
+        $location = $input->getOption('location');
56 56
 
57
-		if (!$this->userManager->userExists($userId)) {
58
-			throw new InvalidArgumentException("User <$userId> not found.");
59
-		}
60
-		// retrieve calendar and evaluate if export is supported
61
-		$calendars = $this->calendarManager->getCalendarsForPrincipal('principals/users/' . $userId, [$calendarId]);
62
-		if ($calendars === []) {
63
-			throw new InvalidArgumentException("Calendar <$calendarId> not found.");
64
-		}
65
-		$calendar = $calendars[0];
66
-		if (!$calendar instanceof ICalendarExport) {
67
-			throw new InvalidArgumentException("Calendar <$calendarId> does not support exporting");
68
-		}
69
-		// construct options object
70
-		$options = new CalendarExportOptions();
71
-		// evaluate if provided format is supported
72
-		if (!in_array($format, ExportService::FORMATS, true)) {
73
-			throw new InvalidArgumentException("Format <$format> is not valid.");
74
-		}
75
-		$options->setFormat($format);
76
-		// evaluate is a valid location was given and is usable otherwise output to stdout
77
-		if ($location !== null) {
78
-			$handle = fopen($location, 'wb');
79
-			if ($handle === false) {
80
-				throw new InvalidArgumentException("Location <$location> is not valid. Can not open location for write operation.");
81
-			}
57
+        if (!$this->userManager->userExists($userId)) {
58
+            throw new InvalidArgumentException("User <$userId> not found.");
59
+        }
60
+        // retrieve calendar and evaluate if export is supported
61
+        $calendars = $this->calendarManager->getCalendarsForPrincipal('principals/users/' . $userId, [$calendarId]);
62
+        if ($calendars === []) {
63
+            throw new InvalidArgumentException("Calendar <$calendarId> not found.");
64
+        }
65
+        $calendar = $calendars[0];
66
+        if (!$calendar instanceof ICalendarExport) {
67
+            throw new InvalidArgumentException("Calendar <$calendarId> does not support exporting");
68
+        }
69
+        // construct options object
70
+        $options = new CalendarExportOptions();
71
+        // evaluate if provided format is supported
72
+        if (!in_array($format, ExportService::FORMATS, true)) {
73
+            throw new InvalidArgumentException("Format <$format> is not valid.");
74
+        }
75
+        $options->setFormat($format);
76
+        // evaluate is a valid location was given and is usable otherwise output to stdout
77
+        if ($location !== null) {
78
+            $handle = fopen($location, 'wb');
79
+            if ($handle === false) {
80
+                throw new InvalidArgumentException("Location <$location> is not valid. Can not open location for write operation.");
81
+            }
82 82
 			
83
-			foreach ($this->exportService->export($calendar, $options) as $chunk) {
84
-				fwrite($handle, $chunk);
85
-			}
86
-			fclose($handle);
87
-		} else {
88
-			foreach ($this->exportService->export($calendar, $options) as $chunk) {
89
-				$output->writeln($chunk);
90
-			}
91
-		}
83
+            foreach ($this->exportService->export($calendar, $options) as $chunk) {
84
+                fwrite($handle, $chunk);
85
+            }
86
+            fclose($handle);
87
+        } else {
88
+            foreach ($this->exportService->export($calendar, $options) as $chunk) {
89
+                $output->writeln($chunk);
90
+            }
91
+        }
92 92
 
93
-		return self::SUCCESS;
94
-	}
93
+        return self::SUCCESS;
94
+    }
95 95
 }
Please login to merge, or discard this patch.
apps/dav/lib/Migration/Version1006Date20180628111625.php 1 patch
Indentation   +63 added lines, -63 removed lines patch added patch discarded remove patch
@@ -15,77 +15,77 @@
 block discarded – undo
15 15
 
16 16
 class Version1006Date20180628111625 extends SimpleMigrationStep {
17 17
 
18
-	/**
19
-	 * @param IOutput $output
20
-	 * @param \Closure $schemaClosure The `\Closure` returns a `ISchemaWrapper`
21
-	 * @param array $options
22
-	 * @return null|ISchemaWrapper
23
-	 */
24
-	public function changeSchema(IOutput $output, \Closure $schemaClosure, array $options) {
25
-		/** @var ISchemaWrapper $schema */
26
-		$schema = $schemaClosure();
18
+    /**
19
+     * @param IOutput $output
20
+     * @param \Closure $schemaClosure The `\Closure` returns a `ISchemaWrapper`
21
+     * @param array $options
22
+     * @return null|ISchemaWrapper
23
+     */
24
+    public function changeSchema(IOutput $output, \Closure $schemaClosure, array $options) {
25
+        /** @var ISchemaWrapper $schema */
26
+        $schema = $schemaClosure();
27 27
 
28
-		if ($schema->hasTable('calendarchanges')) {
29
-			$calendarChangesTable = $schema->getTable('calendarchanges');
30
-			$calendarChangesTable->addColumn('calendartype', Types::INTEGER, [
31
-				'notnull' => true,
32
-				'default' => 0,
33
-			]);
28
+        if ($schema->hasTable('calendarchanges')) {
29
+            $calendarChangesTable = $schema->getTable('calendarchanges');
30
+            $calendarChangesTable->addColumn('calendartype', Types::INTEGER, [
31
+                'notnull' => true,
32
+                'default' => 0,
33
+            ]);
34 34
 
35
-			if ($calendarChangesTable->hasIndex('calendarid_synctoken')) {
36
-				$calendarChangesTable->dropIndex('calendarid_synctoken');
37
-			}
38
-			$calendarChangesTable->addIndex(['calendarid', 'calendartype', 'synctoken'], 'calid_type_synctoken');
39
-		}
35
+            if ($calendarChangesTable->hasIndex('calendarid_synctoken')) {
36
+                $calendarChangesTable->dropIndex('calendarid_synctoken');
37
+            }
38
+            $calendarChangesTable->addIndex(['calendarid', 'calendartype', 'synctoken'], 'calid_type_synctoken');
39
+        }
40 40
 
41
-		if ($schema->hasTable('calendarobjects')) {
42
-			$calendarObjectsTable = $schema->getTable('calendarobjects');
43
-			$calendarObjectsTable->addColumn('calendartype', Types::INTEGER, [
44
-				'notnull' => true,
45
-				'default' => 0,
46
-			]);
41
+        if ($schema->hasTable('calendarobjects')) {
42
+            $calendarObjectsTable = $schema->getTable('calendarobjects');
43
+            $calendarObjectsTable->addColumn('calendartype', Types::INTEGER, [
44
+                'notnull' => true,
45
+                'default' => 0,
46
+            ]);
47 47
 
48
-			if ($calendarObjectsTable->hasIndex('calobjects_index')) {
49
-				$calendarObjectsTable->dropIndex('calobjects_index');
50
-			}
51
-			$calendarObjectsTable->addUniqueIndex(['calendarid', 'calendartype', 'uri'], 'calobjects_index');
52
-			$calendarObjectsTable->addUniqueIndex(['calendarid', 'calendartype', 'uid'], 'calobjects_by_uid_index');
53
-		}
48
+            if ($calendarObjectsTable->hasIndex('calobjects_index')) {
49
+                $calendarObjectsTable->dropIndex('calobjects_index');
50
+            }
51
+            $calendarObjectsTable->addUniqueIndex(['calendarid', 'calendartype', 'uri'], 'calobjects_index');
52
+            $calendarObjectsTable->addUniqueIndex(['calendarid', 'calendartype', 'uid'], 'calobjects_by_uid_index');
53
+        }
54 54
 
55
-		if ($schema->hasTable('calendarobjects_props')) {
56
-			$calendarObjectsPropsTable = $schema->getTable('calendarobjects_props');
57
-			$calendarObjectsPropsTable->addColumn('calendartype', Types::INTEGER, [
58
-				'notnull' => true,
59
-				'default' => 0,
60
-			]);
55
+        if ($schema->hasTable('calendarobjects_props')) {
56
+            $calendarObjectsPropsTable = $schema->getTable('calendarobjects_props');
57
+            $calendarObjectsPropsTable->addColumn('calendartype', Types::INTEGER, [
58
+                'notnull' => true,
59
+                'default' => 0,
60
+            ]);
61 61
 
62 62
 
63
-			if ($calendarObjectsPropsTable->hasIndex('calendarobject_index')) {
64
-				$calendarObjectsPropsTable->dropIndex('calendarobject_index');
65
-			}
66
-			if ($calendarObjectsPropsTable->hasIndex('calendarobject_name_index')) {
67
-				$calendarObjectsPropsTable->dropIndex('calendarobject_name_index');
68
-			}
69
-			if ($calendarObjectsPropsTable->hasIndex('calendarobject_value_index')) {
70
-				$calendarObjectsPropsTable->dropIndex('calendarobject_value_index');
71
-			}
63
+            if ($calendarObjectsPropsTable->hasIndex('calendarobject_index')) {
64
+                $calendarObjectsPropsTable->dropIndex('calendarobject_index');
65
+            }
66
+            if ($calendarObjectsPropsTable->hasIndex('calendarobject_name_index')) {
67
+                $calendarObjectsPropsTable->dropIndex('calendarobject_name_index');
68
+            }
69
+            if ($calendarObjectsPropsTable->hasIndex('calendarobject_value_index')) {
70
+                $calendarObjectsPropsTable->dropIndex('calendarobject_value_index');
71
+            }
72 72
 
73
-			$calendarObjectsPropsTable->addIndex(['objectid', 'calendartype'], 'calendarobject_index');
74
-			$calendarObjectsPropsTable->addIndex(['name', 'calendartype'], 'calendarobject_name_index');
75
-			$calendarObjectsPropsTable->addIndex(['value', 'calendartype'], 'calendarobject_value_index');
76
-			$calendarObjectsPropsTable->addIndex(['calendarid', 'calendartype'], 'calendarobject_calid_index');
77
-		}
73
+            $calendarObjectsPropsTable->addIndex(['objectid', 'calendartype'], 'calendarobject_index');
74
+            $calendarObjectsPropsTable->addIndex(['name', 'calendartype'], 'calendarobject_name_index');
75
+            $calendarObjectsPropsTable->addIndex(['value', 'calendartype'], 'calendarobject_value_index');
76
+            $calendarObjectsPropsTable->addIndex(['calendarid', 'calendartype'], 'calendarobject_calid_index');
77
+        }
78 78
 
79
-		if ($schema->hasTable('calendarsubscriptions')) {
80
-			$calendarSubscriptionsTable = $schema->getTable('calendarsubscriptions');
81
-			$calendarSubscriptionsTable->addColumn('synctoken', 'integer', [
82
-				'notnull' => true,
83
-				'default' => 1,
84
-				'length' => 10,
85
-				'unsigned' => true,
86
-			]);
87
-		}
79
+        if ($schema->hasTable('calendarsubscriptions')) {
80
+            $calendarSubscriptionsTable = $schema->getTable('calendarsubscriptions');
81
+            $calendarSubscriptionsTable->addColumn('synctoken', 'integer', [
82
+                'notnull' => true,
83
+                'default' => 1,
84
+                'length' => 10,
85
+                'unsigned' => true,
86
+            ]);
87
+        }
88 88
 
89
-		return $schema;
90
-	}
89
+        return $schema;
90
+    }
91 91
 }
Please login to merge, or discard this patch.
apps/dav/lib/Listener/AddMissingIndicesListener.php 1 patch
Indentation   +20 added lines, -20 removed lines patch added patch discarded remove patch
@@ -16,25 +16,25 @@
 block discarded – undo
16 16
  */
17 17
 class AddMissingIndicesListener implements IEventListener {
18 18
 
19
-	public function handle(Event $event): void {
20
-		if (!($event instanceof AddMissingIndicesEvent)) {
21
-			return;
22
-		}
23
-		$event->addMissingIndex(
24
-			'dav_shares',
25
-			'dav_shares_resourceid_type',
26
-			['resourceid', 'type']
27
-		);
28
-		$event->addMissingIndex(
29
-			'dav_shares',
30
-			'dav_shares_resourceid_access',
31
-			['resourceid', 'access']
32
-		);
33
-		$event->addMissingIndex(
34
-			'calendarobjects',
35
-			'calobjects_by_uid_index',
36
-			['calendarid', 'calendartype', 'uid']
37
-		);
38
-	}
19
+    public function handle(Event $event): void {
20
+        if (!($event instanceof AddMissingIndicesEvent)) {
21
+            return;
22
+        }
23
+        $event->addMissingIndex(
24
+            'dav_shares',
25
+            'dav_shares_resourceid_type',
26
+            ['resourceid', 'type']
27
+        );
28
+        $event->addMissingIndex(
29
+            'dav_shares',
30
+            'dav_shares_resourceid_access',
31
+            ['resourceid', 'access']
32
+        );
33
+        $event->addMissingIndex(
34
+            'calendarobjects',
35
+            'calobjects_by_uid_index',
36
+            ['calendarid', 'calendartype', 'uid']
37
+        );
38
+    }
39 39
 
40 40
 }
Please login to merge, or discard this patch.
apps/dav/lib/CalDAV/CalDavBackend.php 1 patch
Indentation   +3578 added lines, -3578 removed lines patch added patch discarded remove patch
@@ -92,3583 +92,3583 @@
 block discarded – undo
92 92
  * @package OCA\DAV\CalDAV
93 93
  */
94 94
 class CalDavBackend extends AbstractBackend implements SyncSupport, SubscriptionSupport, SchedulingSupport {
95
-	use TTransactional;
96
-
97
-	public const CALENDAR_TYPE_CALENDAR = 0;
98
-	public const CALENDAR_TYPE_SUBSCRIPTION = 1;
99
-
100
-	public const PERSONAL_CALENDAR_URI = 'personal';
101
-	public const PERSONAL_CALENDAR_NAME = 'Personal';
102
-
103
-	public const RESOURCE_BOOKING_CALENDAR_URI = 'calendar';
104
-	public const RESOURCE_BOOKING_CALENDAR_NAME = 'Calendar';
105
-
106
-	/**
107
-	 * We need to specify a max date, because we need to stop *somewhere*
108
-	 *
109
-	 * On 32 bit system the maximum for a signed integer is 2147483647, so
110
-	 * MAX_DATE cannot be higher than date('Y-m-d', 2147483647) which results
111
-	 * in 2038-01-19 to avoid problems when the date is converted
112
-	 * to a unix timestamp.
113
-	 */
114
-	public const MAX_DATE = '2038-01-01';
115
-
116
-	public const ACCESS_PUBLIC = 4;
117
-	public const CLASSIFICATION_PUBLIC = 0;
118
-	public const CLASSIFICATION_PRIVATE = 1;
119
-	public const CLASSIFICATION_CONFIDENTIAL = 2;
120
-
121
-	/**
122
-	 * List of CalDAV properties, and how they map to database field names and their type
123
-	 * Add your own properties by simply adding on to this array.
124
-	 *
125
-	 * @var array
126
-	 * @psalm-var array<string, string[]>
127
-	 */
128
-	public array $propertyMap = [
129
-		'{DAV:}displayname' => ['displayname', 'string'],
130
-		'{urn:ietf:params:xml:ns:caldav}calendar-description' => ['description', 'string'],
131
-		'{urn:ietf:params:xml:ns:caldav}calendar-timezone' => ['timezone', 'string'],
132
-		'{http://apple.com/ns/ical/}calendar-order' => ['calendarorder', 'int'],
133
-		'{http://apple.com/ns/ical/}calendar-color' => ['calendarcolor', 'string'],
134
-		'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_NEXTCLOUD . '}deleted-at' => ['deleted_at', 'int'],
135
-	];
136
-
137
-	/**
138
-	 * List of subscription properties, and how they map to database field names.
139
-	 *
140
-	 * @var array
141
-	 */
142
-	public array $subscriptionPropertyMap = [
143
-		'{DAV:}displayname' => ['displayname', 'string'],
144
-		'{http://apple.com/ns/ical/}refreshrate' => ['refreshrate', 'string'],
145
-		'{http://apple.com/ns/ical/}calendar-order' => ['calendarorder', 'int'],
146
-		'{http://apple.com/ns/ical/}calendar-color' => ['calendarcolor', 'string'],
147
-		'{http://calendarserver.org/ns/}subscribed-strip-todos' => ['striptodos', 'bool'],
148
-		'{http://calendarserver.org/ns/}subscribed-strip-alarms' => ['stripalarms', 'string'],
149
-		'{http://calendarserver.org/ns/}subscribed-strip-attachments' => ['stripattachments', 'string'],
150
-	];
151
-
152
-	/**
153
-	 * properties to index
154
-	 *
155
-	 * This list has to be kept in sync with ICalendarQuery::SEARCH_PROPERTY_*
156
-	 *
157
-	 * @see \OCP\Calendar\ICalendarQuery
158
-	 */
159
-	private const INDEXED_PROPERTIES = [
160
-		'CATEGORIES',
161
-		'COMMENT',
162
-		'DESCRIPTION',
163
-		'LOCATION',
164
-		'RESOURCES',
165
-		'STATUS',
166
-		'SUMMARY',
167
-		'ATTENDEE',
168
-		'CONTACT',
169
-		'ORGANIZER'
170
-	];
171
-
172
-	/** @var array parameters to index */
173
-	public static array $indexParameters = [
174
-		'ATTENDEE' => ['CN'],
175
-		'ORGANIZER' => ['CN'],
176
-	];
177
-
178
-	/**
179
-	 * @var string[] Map of uid => display name
180
-	 */
181
-	protected array $userDisplayNames;
182
-
183
-	private string $dbObjectsTable = 'calendarobjects';
184
-	private string $dbObjectPropertiesTable = 'calendarobjects_props';
185
-	private string $dbObjectInvitationsTable = 'calendar_invitations';
186
-	private array $cachedObjects = [];
187
-
188
-	public function __construct(
189
-		private IDBConnection $db,
190
-		private Principal $principalBackend,
191
-		private IUserManager $userManager,
192
-		private ISecureRandom $random,
193
-		private LoggerInterface $logger,
194
-		private IEventDispatcher $dispatcher,
195
-		private IConfig $config,
196
-		private Sharing\Backend $calendarSharingBackend,
197
-		private bool $legacyEndpoint = false,
198
-	) {
199
-	}
200
-
201
-	/**
202
-	 * Return the number of calendars for a principal
203
-	 *
204
-	 * By default this excludes the automatically generated birthday calendar
205
-	 *
206
-	 * @param $principalUri
207
-	 * @param bool $excludeBirthday
208
-	 * @return int
209
-	 */
210
-	public function getCalendarsForUserCount($principalUri, $excludeBirthday = true) {
211
-		$principalUri = $this->convertPrincipal($principalUri, true);
212
-		$query = $this->db->getQueryBuilder();
213
-		$query->select($query->func()->count('*'))
214
-			->from('calendars');
215
-
216
-		if ($principalUri === '') {
217
-			$query->where($query->expr()->emptyString('principaluri'));
218
-		} else {
219
-			$query->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)));
220
-		}
221
-
222
-		if ($excludeBirthday) {
223
-			$query->andWhere($query->expr()->neq('uri', $query->createNamedParameter(BirthdayService::BIRTHDAY_CALENDAR_URI)));
224
-		}
225
-
226
-		$result = $query->executeQuery();
227
-		$column = (int)$result->fetchOne();
228
-		$result->closeCursor();
229
-		return $column;
230
-	}
231
-
232
-	/**
233
-	 * Return the number of subscriptions for a principal
234
-	 */
235
-	public function getSubscriptionsForUserCount(string $principalUri): int {
236
-		$principalUri = $this->convertPrincipal($principalUri, true);
237
-		$query = $this->db->getQueryBuilder();
238
-		$query->select($query->func()->count('*'))
239
-			->from('calendarsubscriptions');
240
-
241
-		if ($principalUri === '') {
242
-			$query->where($query->expr()->emptyString('principaluri'));
243
-		} else {
244
-			$query->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)));
245
-		}
246
-
247
-		$result = $query->executeQuery();
248
-		$column = (int)$result->fetchOne();
249
-		$result->closeCursor();
250
-		return $column;
251
-	}
252
-
253
-	/**
254
-	 * @return array{id: int, deleted_at: int}[]
255
-	 */
256
-	public function getDeletedCalendars(int $deletedBefore): array {
257
-		$qb = $this->db->getQueryBuilder();
258
-		$qb->select(['id', 'deleted_at'])
259
-			->from('calendars')
260
-			->where($qb->expr()->isNotNull('deleted_at'))
261
-			->andWhere($qb->expr()->lt('deleted_at', $qb->createNamedParameter($deletedBefore)));
262
-		$result = $qb->executeQuery();
263
-		$calendars = [];
264
-		while (($row = $result->fetch()) !== false) {
265
-			$calendars[] = [
266
-				'id' => (int)$row['id'],
267
-				'deleted_at' => (int)$row['deleted_at'],
268
-			];
269
-		}
270
-		$result->closeCursor();
271
-		return $calendars;
272
-	}
273
-
274
-	/**
275
-	 * Returns a list of calendars for a principal.
276
-	 *
277
-	 * Every project is an array with the following keys:
278
-	 *  * id, a unique id that will be used by other functions to modify the
279
-	 *    calendar. This can be the same as the uri or a database key.
280
-	 *  * uri, which the basename of the uri with which the calendar is
281
-	 *    accessed.
282
-	 *  * principaluri. The owner of the calendar. Almost always the same as
283
-	 *    principalUri passed to this method.
284
-	 *
285
-	 * Furthermore it can contain webdav properties in clark notation. A very
286
-	 * common one is '{DAV:}displayname'.
287
-	 *
288
-	 * Many clients also require:
289
-	 * {urn:ietf:params:xml:ns:caldav}supported-calendar-component-set
290
-	 * For this property, you can just return an instance of
291
-	 * Sabre\CalDAV\Property\SupportedCalendarComponentSet.
292
-	 *
293
-	 * If you return {http://sabredav.org/ns}read-only and set the value to 1,
294
-	 * ACL will automatically be put in read-only mode.
295
-	 *
296
-	 * @param string $principalUri
297
-	 * @return array
298
-	 */
299
-	public function getCalendarsForUser($principalUri) {
300
-		return $this->atomic(function () use ($principalUri) {
301
-			$principalUriOriginal = $principalUri;
302
-			$principalUri = $this->convertPrincipal($principalUri, true);
303
-			$fields = array_column($this->propertyMap, 0);
304
-			$fields[] = 'id';
305
-			$fields[] = 'uri';
306
-			$fields[] = 'synctoken';
307
-			$fields[] = 'components';
308
-			$fields[] = 'principaluri';
309
-			$fields[] = 'transparent';
310
-
311
-			// Making fields a comma-delimited list
312
-			$query = $this->db->getQueryBuilder();
313
-			$query->select($fields)
314
-				->from('calendars')
315
-				->orderBy('calendarorder', 'ASC');
316
-
317
-			if ($principalUri === '') {
318
-				$query->where($query->expr()->emptyString('principaluri'));
319
-			} else {
320
-				$query->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)));
321
-			}
322
-
323
-			$result = $query->executeQuery();
324
-
325
-			$calendars = [];
326
-			while ($row = $result->fetch()) {
327
-				$row['principaluri'] = (string)$row['principaluri'];
328
-				$components = [];
329
-				if ($row['components']) {
330
-					$components = explode(',', $row['components']);
331
-				}
332
-
333
-				$calendar = [
334
-					'id' => $row['id'],
335
-					'uri' => $row['uri'],
336
-					'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
337
-					'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken'] ?: '0'),
338
-					'{http://sabredav.org/ns}sync-token' => $row['synctoken'] ?: '0',
339
-					'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
340
-					'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
341
-					'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($principalUri, !$this->legacyEndpoint),
342
-				];
343
-
344
-				$calendar = $this->rowToCalendar($row, $calendar);
345
-				$calendar = $this->addOwnerPrincipalToCalendar($calendar);
346
-				$calendar = $this->addResourceTypeToCalendar($row, $calendar);
347
-
348
-				if (!isset($calendars[$calendar['id']])) {
349
-					$calendars[$calendar['id']] = $calendar;
350
-				}
351
-			}
352
-			$result->closeCursor();
353
-
354
-			// query for shared calendars
355
-			$principals = $this->principalBackend->getGroupMembership($principalUriOriginal, true);
356
-			$principals = array_merge($principals, $this->principalBackend->getCircleMembership($principalUriOriginal));
357
-			$principals[] = $principalUri;
358
-
359
-			$fields = array_column($this->propertyMap, 0);
360
-			$fields = array_map(function (string $field) {
361
-				return 'a.' . $field;
362
-			}, $fields);
363
-			$fields[] = 'a.id';
364
-			$fields[] = 'a.uri';
365
-			$fields[] = 'a.synctoken';
366
-			$fields[] = 'a.components';
367
-			$fields[] = 'a.principaluri';
368
-			$fields[] = 'a.transparent';
369
-			$fields[] = 's.access';
370
-
371
-			$select = $this->db->getQueryBuilder();
372
-			$subSelect = $this->db->getQueryBuilder();
373
-
374
-			$subSelect->select('resourceid')
375
-				->from('dav_shares', 'd')
376
-				->where($subSelect->expr()->eq('d.access', $select->createNamedParameter(Backend::ACCESS_UNSHARED, IQueryBuilder::PARAM_INT), IQueryBuilder::PARAM_INT))
377
-				->andWhere($subSelect->expr()->in('d.principaluri', $select->createNamedParameter($principals, IQueryBuilder::PARAM_STR_ARRAY), IQueryBuilder::PARAM_STR_ARRAY));
378
-
379
-			$select->select($fields)
380
-				->from('dav_shares', 's')
381
-				->join('s', 'calendars', 'a', $select->expr()->eq('s.resourceid', 'a.id', IQueryBuilder::PARAM_INT))
382
-				->where($select->expr()->in('s.principaluri', $select->createNamedParameter($principals, IQueryBuilder::PARAM_STR_ARRAY), IQueryBuilder::PARAM_STR_ARRAY))
383
-				->andWhere($select->expr()->eq('s.type', $select->createNamedParameter('calendar', IQueryBuilder::PARAM_STR), IQueryBuilder::PARAM_STR))
384
-				->andWhere($select->expr()->notIn('a.id', $select->createFunction($subSelect->getSQL()), IQueryBuilder::PARAM_INT_ARRAY));
385
-
386
-			$results = $select->executeQuery();
387
-
388
-			$readOnlyPropertyName = '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}read-only';
389
-			while ($row = $results->fetch()) {
390
-				$row['principaluri'] = (string)$row['principaluri'];
391
-				if ($row['principaluri'] === $principalUri) {
392
-					continue;
393
-				}
394
-
395
-				$readOnly = (int)$row['access'] === Backend::ACCESS_READ;
396
-				if (isset($calendars[$row['id']])) {
397
-					if ($readOnly) {
398
-						// New share can not have more permissions than the old one.
399
-						continue;
400
-					}
401
-					if (isset($calendars[$row['id']][$readOnlyPropertyName]) &&
402
-						$calendars[$row['id']][$readOnlyPropertyName] === 0) {
403
-						// Old share is already read-write, no more permissions can be gained
404
-						continue;
405
-					}
406
-				}
407
-
408
-				[, $name] = Uri\split($row['principaluri']);
409
-				$uri = $row['uri'] . '_shared_by_' . $name;
410
-				$row['displayname'] = $row['displayname'] . ' (' . ($this->userManager->getDisplayName($name) ?? ($name ?? '')) . ')';
411
-				$components = [];
412
-				if ($row['components']) {
413
-					$components = explode(',', $row['components']);
414
-				}
415
-				$calendar = [
416
-					'id' => $row['id'],
417
-					'uri' => $uri,
418
-					'principaluri' => $this->convertPrincipal($principalUri, !$this->legacyEndpoint),
419
-					'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken'] ?: '0'),
420
-					'{http://sabredav.org/ns}sync-token' => $row['synctoken'] ?: '0',
421
-					'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
422
-					'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp('transparent'),
423
-					'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
424
-					$readOnlyPropertyName => $readOnly,
425
-				];
426
-
427
-				$calendar = $this->rowToCalendar($row, $calendar);
428
-				$calendar = $this->addOwnerPrincipalToCalendar($calendar);
429
-				$calendar = $this->addResourceTypeToCalendar($row, $calendar);
430
-
431
-				$calendars[$calendar['id']] = $calendar;
432
-			}
433
-			$result->closeCursor();
434
-
435
-			return array_values($calendars);
436
-		}, $this->db);
437
-	}
438
-
439
-	/**
440
-	 * @param $principalUri
441
-	 * @return array
442
-	 */
443
-	public function getUsersOwnCalendars($principalUri) {
444
-		$principalUri = $this->convertPrincipal($principalUri, true);
445
-		$fields = array_column($this->propertyMap, 0);
446
-		$fields[] = 'id';
447
-		$fields[] = 'uri';
448
-		$fields[] = 'synctoken';
449
-		$fields[] = 'components';
450
-		$fields[] = 'principaluri';
451
-		$fields[] = 'transparent';
452
-		// Making fields a comma-delimited list
453
-		$query = $this->db->getQueryBuilder();
454
-		$query->select($fields)->from('calendars')
455
-			->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
456
-			->orderBy('calendarorder', 'ASC');
457
-		$stmt = $query->executeQuery();
458
-		$calendars = [];
459
-		while ($row = $stmt->fetch()) {
460
-			$row['principaluri'] = (string)$row['principaluri'];
461
-			$components = [];
462
-			if ($row['components']) {
463
-				$components = explode(',', $row['components']);
464
-			}
465
-			$calendar = [
466
-				'id' => $row['id'],
467
-				'uri' => $row['uri'],
468
-				'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
469
-				'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken'] ?: '0'),
470
-				'{http://sabredav.org/ns}sync-token' => $row['synctoken'] ?: '0',
471
-				'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
472
-				'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
473
-			];
474
-
475
-			$calendar = $this->rowToCalendar($row, $calendar);
476
-			$calendar = $this->addOwnerPrincipalToCalendar($calendar);
477
-			$calendar = $this->addResourceTypeToCalendar($row, $calendar);
478
-
479
-			if (!isset($calendars[$calendar['id']])) {
480
-				$calendars[$calendar['id']] = $calendar;
481
-			}
482
-		}
483
-		$stmt->closeCursor();
484
-		return array_values($calendars);
485
-	}
486
-
487
-	/**
488
-	 * @return array
489
-	 */
490
-	public function getPublicCalendars() {
491
-		$fields = array_column($this->propertyMap, 0);
492
-		$fields[] = 'a.id';
493
-		$fields[] = 'a.uri';
494
-		$fields[] = 'a.synctoken';
495
-		$fields[] = 'a.components';
496
-		$fields[] = 'a.principaluri';
497
-		$fields[] = 'a.transparent';
498
-		$fields[] = 's.access';
499
-		$fields[] = 's.publicuri';
500
-		$calendars = [];
501
-		$query = $this->db->getQueryBuilder();
502
-		$result = $query->select($fields)
503
-			->from('dav_shares', 's')
504
-			->join('s', 'calendars', 'a', $query->expr()->eq('s.resourceid', 'a.id'))
505
-			->where($query->expr()->in('s.access', $query->createNamedParameter(self::ACCESS_PUBLIC)))
506
-			->andWhere($query->expr()->eq('s.type', $query->createNamedParameter('calendar')))
507
-			->executeQuery();
508
-
509
-		while ($row = $result->fetch()) {
510
-			$row['principaluri'] = (string)$row['principaluri'];
511
-			[, $name] = Uri\split($row['principaluri']);
512
-			$row['displayname'] = $row['displayname'] . "($name)";
513
-			$components = [];
514
-			if ($row['components']) {
515
-				$components = explode(',', $row['components']);
516
-			}
517
-			$calendar = [
518
-				'id' => $row['id'],
519
-				'uri' => $row['publicuri'],
520
-				'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
521
-				'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken'] ?: '0'),
522
-				'{http://sabredav.org/ns}sync-token' => $row['synctoken'] ?: '0',
523
-				'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
524
-				'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
525
-				'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($row['principaluri'], $this->legacyEndpoint),
526
-				'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}read-only' => (int)$row['access'] === Backend::ACCESS_READ,
527
-				'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}public' => (int)$row['access'] === self::ACCESS_PUBLIC,
528
-			];
529
-
530
-			$calendar = $this->rowToCalendar($row, $calendar);
531
-			$calendar = $this->addOwnerPrincipalToCalendar($calendar);
532
-			$calendar = $this->addResourceTypeToCalendar($row, $calendar);
533
-
534
-			if (!isset($calendars[$calendar['id']])) {
535
-				$calendars[$calendar['id']] = $calendar;
536
-			}
537
-		}
538
-		$result->closeCursor();
539
-
540
-		return array_values($calendars);
541
-	}
542
-
543
-	/**
544
-	 * @param string $uri
545
-	 * @return array
546
-	 * @throws NotFound
547
-	 */
548
-	public function getPublicCalendar($uri) {
549
-		$fields = array_column($this->propertyMap, 0);
550
-		$fields[] = 'a.id';
551
-		$fields[] = 'a.uri';
552
-		$fields[] = 'a.synctoken';
553
-		$fields[] = 'a.components';
554
-		$fields[] = 'a.principaluri';
555
-		$fields[] = 'a.transparent';
556
-		$fields[] = 's.access';
557
-		$fields[] = 's.publicuri';
558
-		$query = $this->db->getQueryBuilder();
559
-		$result = $query->select($fields)
560
-			->from('dav_shares', 's')
561
-			->join('s', 'calendars', 'a', $query->expr()->eq('s.resourceid', 'a.id'))
562
-			->where($query->expr()->in('s.access', $query->createNamedParameter(self::ACCESS_PUBLIC)))
563
-			->andWhere($query->expr()->eq('s.type', $query->createNamedParameter('calendar')))
564
-			->andWhere($query->expr()->eq('s.publicuri', $query->createNamedParameter($uri)))
565
-			->executeQuery();
566
-
567
-		$row = $result->fetch();
568
-
569
-		$result->closeCursor();
570
-
571
-		if ($row === false) {
572
-			throw new NotFound('Node with name \'' . $uri . '\' could not be found');
573
-		}
574
-
575
-		$row['principaluri'] = (string)$row['principaluri'];
576
-		[, $name] = Uri\split($row['principaluri']);
577
-		$row['displayname'] = $row['displayname'] . ' ' . "($name)";
578
-		$components = [];
579
-		if ($row['components']) {
580
-			$components = explode(',', $row['components']);
581
-		}
582
-		$calendar = [
583
-			'id' => $row['id'],
584
-			'uri' => $row['publicuri'],
585
-			'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
586
-			'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken'] ?: '0'),
587
-			'{http://sabredav.org/ns}sync-token' => $row['synctoken'] ?: '0',
588
-			'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
589
-			'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
590
-			'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
591
-			'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}read-only' => (int)$row['access'] === Backend::ACCESS_READ,
592
-			'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}public' => (int)$row['access'] === self::ACCESS_PUBLIC,
593
-		];
594
-
595
-		$calendar = $this->rowToCalendar($row, $calendar);
596
-		$calendar = $this->addOwnerPrincipalToCalendar($calendar);
597
-		$calendar = $this->addResourceTypeToCalendar($row, $calendar);
598
-
599
-		return $calendar;
600
-	}
601
-
602
-	/**
603
-	 * @param string $principal
604
-	 * @param string $uri
605
-	 * @return array|null
606
-	 */
607
-	public function getCalendarByUri($principal, $uri) {
608
-		$fields = array_column($this->propertyMap, 0);
609
-		$fields[] = 'id';
610
-		$fields[] = 'uri';
611
-		$fields[] = 'synctoken';
612
-		$fields[] = 'components';
613
-		$fields[] = 'principaluri';
614
-		$fields[] = 'transparent';
615
-
616
-		// Making fields a comma-delimited list
617
-		$query = $this->db->getQueryBuilder();
618
-		$query->select($fields)->from('calendars')
619
-			->where($query->expr()->eq('uri', $query->createNamedParameter($uri)))
620
-			->andWhere($query->expr()->eq('principaluri', $query->createNamedParameter($principal)))
621
-			->setMaxResults(1);
622
-		$stmt = $query->executeQuery();
623
-
624
-		$row = $stmt->fetch();
625
-		$stmt->closeCursor();
626
-		if ($row === false) {
627
-			return null;
628
-		}
629
-
630
-		$row['principaluri'] = (string)$row['principaluri'];
631
-		$components = [];
632
-		if ($row['components']) {
633
-			$components = explode(',', $row['components']);
634
-		}
635
-
636
-		$calendar = [
637
-			'id' => $row['id'],
638
-			'uri' => $row['uri'],
639
-			'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
640
-			'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken'] ?: '0'),
641
-			'{http://sabredav.org/ns}sync-token' => $row['synctoken'] ?: '0',
642
-			'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
643
-			'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
644
-		];
645
-
646
-		$calendar = $this->rowToCalendar($row, $calendar);
647
-		$calendar = $this->addOwnerPrincipalToCalendar($calendar);
648
-		$calendar = $this->addResourceTypeToCalendar($row, $calendar);
649
-
650
-		return $calendar;
651
-	}
652
-
653
-	/**
654
-	 * @return array{id: int, uri: string, '{http://calendarserver.org/ns/}getctag': string, '{http://sabredav.org/ns}sync-token': int, '{urn:ietf:params:xml:ns:caldav}supported-calendar-component-set': SupportedCalendarComponentSet, '{urn:ietf:params:xml:ns:caldav}schedule-calendar-transp': ScheduleCalendarTransp, '{urn:ietf:params:xml:ns:caldav}calendar-timezone': ?string }|null
655
-	 */
656
-	public function getCalendarById(int $calendarId): ?array {
657
-		$fields = array_column($this->propertyMap, 0);
658
-		$fields[] = 'id';
659
-		$fields[] = 'uri';
660
-		$fields[] = 'synctoken';
661
-		$fields[] = 'components';
662
-		$fields[] = 'principaluri';
663
-		$fields[] = 'transparent';
664
-
665
-		// Making fields a comma-delimited list
666
-		$query = $this->db->getQueryBuilder();
667
-		$query->select($fields)->from('calendars')
668
-			->where($query->expr()->eq('id', $query->createNamedParameter($calendarId)))
669
-			->setMaxResults(1);
670
-		$stmt = $query->executeQuery();
671
-
672
-		$row = $stmt->fetch();
673
-		$stmt->closeCursor();
674
-		if ($row === false) {
675
-			return null;
676
-		}
677
-
678
-		$row['principaluri'] = (string)$row['principaluri'];
679
-		$components = [];
680
-		if ($row['components']) {
681
-			$components = explode(',', $row['components']);
682
-		}
683
-
684
-		$calendar = [
685
-			'id' => $row['id'],
686
-			'uri' => $row['uri'],
687
-			'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
688
-			'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken'] ?: '0'),
689
-			'{http://sabredav.org/ns}sync-token' => $row['synctoken'] ?? 0,
690
-			'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
691
-			'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
692
-		];
693
-
694
-		$calendar = $this->rowToCalendar($row, $calendar);
695
-		$calendar = $this->addOwnerPrincipalToCalendar($calendar);
696
-		$calendar = $this->addResourceTypeToCalendar($row, $calendar);
697
-
698
-		return $calendar;
699
-	}
700
-
701
-	/**
702
-	 * @param $subscriptionId
703
-	 */
704
-	public function getSubscriptionById($subscriptionId) {
705
-		$fields = array_column($this->subscriptionPropertyMap, 0);
706
-		$fields[] = 'id';
707
-		$fields[] = 'uri';
708
-		$fields[] = 'source';
709
-		$fields[] = 'synctoken';
710
-		$fields[] = 'principaluri';
711
-		$fields[] = 'lastmodified';
712
-
713
-		$query = $this->db->getQueryBuilder();
714
-		$query->select($fields)
715
-			->from('calendarsubscriptions')
716
-			->where($query->expr()->eq('id', $query->createNamedParameter($subscriptionId)))
717
-			->orderBy('calendarorder', 'asc');
718
-		$stmt = $query->executeQuery();
719
-
720
-		$row = $stmt->fetch();
721
-		$stmt->closeCursor();
722
-		if ($row === false) {
723
-			return null;
724
-		}
725
-
726
-		$row['principaluri'] = (string)$row['principaluri'];
727
-		$subscription = [
728
-			'id' => $row['id'],
729
-			'uri' => $row['uri'],
730
-			'principaluri' => $row['principaluri'],
731
-			'source' => $row['source'],
732
-			'lastmodified' => $row['lastmodified'],
733
-			'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet(['VTODO', 'VEVENT']),
734
-			'{http://sabredav.org/ns}sync-token' => $row['synctoken'] ?: '0',
735
-		];
736
-
737
-		return $this->rowToSubscription($row, $subscription);
738
-	}
739
-
740
-	public function getSubscriptionByUri(string $principal, string $uri): ?array {
741
-		$fields = array_column($this->subscriptionPropertyMap, 0);
742
-		$fields[] = 'id';
743
-		$fields[] = 'uri';
744
-		$fields[] = 'source';
745
-		$fields[] = 'synctoken';
746
-		$fields[] = 'principaluri';
747
-		$fields[] = 'lastmodified';
748
-
749
-		$query = $this->db->getQueryBuilder();
750
-		$query->select($fields)
751
-			->from('calendarsubscriptions')
752
-			->where($query->expr()->eq('uri', $query->createNamedParameter($uri)))
753
-			->andWhere($query->expr()->eq('principaluri', $query->createNamedParameter($principal)))
754
-			->setMaxResults(1);
755
-		$stmt = $query->executeQuery();
756
-
757
-		$row = $stmt->fetch();
758
-		$stmt->closeCursor();
759
-		if ($row === false) {
760
-			return null;
761
-		}
762
-
763
-		$row['principaluri'] = (string)$row['principaluri'];
764
-		$subscription = [
765
-			'id' => $row['id'],
766
-			'uri' => $row['uri'],
767
-			'principaluri' => $row['principaluri'],
768
-			'source' => $row['source'],
769
-			'lastmodified' => $row['lastmodified'],
770
-			'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet(['VTODO', 'VEVENT']),
771
-			'{http://sabredav.org/ns}sync-token' => $row['synctoken'] ?: '0',
772
-		];
773
-
774
-		return $this->rowToSubscription($row, $subscription);
775
-	}
776
-
777
-	/**
778
-	 * Creates a new calendar for a principal.
779
-	 *
780
-	 * If the creation was a success, an id must be returned that can be used to reference
781
-	 * this calendar in other methods, such as updateCalendar.
782
-	 *
783
-	 * @param string $principalUri
784
-	 * @param string $calendarUri
785
-	 * @param array $properties
786
-	 * @return int
787
-	 *
788
-	 * @throws CalendarException
789
-	 */
790
-	public function createCalendar($principalUri, $calendarUri, array $properties) {
791
-		if (strlen($calendarUri) > 255) {
792
-			throw new CalendarException('URI too long. Calendar not created');
793
-		}
794
-
795
-		$values = [
796
-			'principaluri' => $this->convertPrincipal($principalUri, true),
797
-			'uri' => $calendarUri,
798
-			'synctoken' => 1,
799
-			'transparent' => 0,
800
-			'components' => 'VEVENT,VTODO,VJOURNAL',
801
-			'displayname' => $calendarUri
802
-		];
803
-
804
-		// Default value
805
-		$sccs = '{urn:ietf:params:xml:ns:caldav}supported-calendar-component-set';
806
-		if (isset($properties[$sccs])) {
807
-			if (!($properties[$sccs] instanceof SupportedCalendarComponentSet)) {
808
-				throw new DAV\Exception('The ' . $sccs . ' property must be of type: \Sabre\CalDAV\Property\SupportedCalendarComponentSet');
809
-			}
810
-			$values['components'] = implode(',', $properties[$sccs]->getValue());
811
-		} elseif (isset($properties['components'])) {
812
-			// Allow to provide components internally without having
813
-			// to create a SupportedCalendarComponentSet object
814
-			$values['components'] = $properties['components'];
815
-		}
816
-
817
-		$transp = '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp';
818
-		if (isset($properties[$transp])) {
819
-			$values['transparent'] = (int)($properties[$transp]->getValue() === 'transparent');
820
-		}
821
-
822
-		foreach ($this->propertyMap as $xmlName => [$dbName, $type]) {
823
-			if (isset($properties[$xmlName])) {
824
-				$values[$dbName] = $properties[$xmlName];
825
-			}
826
-		}
827
-
828
-		[$calendarId, $calendarData] = $this->atomic(function () use ($values) {
829
-			$query = $this->db->getQueryBuilder();
830
-			$query->insert('calendars');
831
-			foreach ($values as $column => $value) {
832
-				$query->setValue($column, $query->createNamedParameter($value));
833
-			}
834
-			$query->executeStatement();
835
-			$calendarId = $query->getLastInsertId();
836
-
837
-			$calendarData = $this->getCalendarById($calendarId);
838
-			return [$calendarId, $calendarData];
839
-		}, $this->db);
840
-
841
-		$this->dispatcher->dispatchTyped(new CalendarCreatedEvent((int)$calendarId, $calendarData));
842
-
843
-		return $calendarId;
844
-	}
845
-
846
-	/**
847
-	 * Updates properties for a calendar.
848
-	 *
849
-	 * The list of mutations is stored in a Sabre\DAV\PropPatch object.
850
-	 * To do the actual updates, you must tell this object which properties
851
-	 * you're going to process with the handle() method.
852
-	 *
853
-	 * Calling the handle method is like telling the PropPatch object "I
854
-	 * promise I can handle updating this property".
855
-	 *
856
-	 * Read the PropPatch documentation for more info and examples.
857
-	 *
858
-	 * @param mixed $calendarId
859
-	 * @param PropPatch $propPatch
860
-	 * @return void
861
-	 */
862
-	public function updateCalendar($calendarId, PropPatch $propPatch) {
863
-		$supportedProperties = array_keys($this->propertyMap);
864
-		$supportedProperties[] = '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp';
865
-
866
-		$propPatch->handle($supportedProperties, function ($mutations) use ($calendarId) {
867
-			$newValues = [];
868
-			foreach ($mutations as $propertyName => $propertyValue) {
869
-				switch ($propertyName) {
870
-					case '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp':
871
-						$fieldName = 'transparent';
872
-						$newValues[$fieldName] = (int)($propertyValue->getValue() === 'transparent');
873
-						break;
874
-					default:
875
-						$fieldName = $this->propertyMap[$propertyName][0];
876
-						$newValues[$fieldName] = $propertyValue;
877
-						break;
878
-				}
879
-			}
880
-			[$calendarData, $shares] = $this->atomic(function () use ($calendarId, $newValues) {
881
-				$query = $this->db->getQueryBuilder();
882
-				$query->update('calendars');
883
-				foreach ($newValues as $fieldName => $value) {
884
-					$query->set($fieldName, $query->createNamedParameter($value));
885
-				}
886
-				$query->where($query->expr()->eq('id', $query->createNamedParameter($calendarId)));
887
-				$query->executeStatement();
888
-
889
-				$this->addChanges($calendarId, [''], 2);
890
-
891
-				$calendarData = $this->getCalendarById($calendarId);
892
-				$shares = $this->getShares($calendarId);
893
-				return [$calendarData, $shares];
894
-			}, $this->db);
895
-
896
-			$this->dispatcher->dispatchTyped(new CalendarUpdatedEvent($calendarId, $calendarData, $shares, $mutations));
897
-
898
-			return true;
899
-		});
900
-	}
901
-
902
-	/**
903
-	 * Delete a calendar and all it's objects
904
-	 *
905
-	 * @param mixed $calendarId
906
-	 * @return void
907
-	 */
908
-	public function deleteCalendar($calendarId, bool $forceDeletePermanently = false) {
909
-		$this->atomic(function () use ($calendarId, $forceDeletePermanently): void {
910
-			// The calendar is deleted right away if this is either enforced by the caller
911
-			// or the special contacts birthday calendar or when the preference of an empty
912
-			// retention (0 seconds) is set, which signals a disabled trashbin.
913
-			$calendarData = $this->getCalendarById($calendarId);
914
-			$isBirthdayCalendar = isset($calendarData['uri']) && $calendarData['uri'] === BirthdayService::BIRTHDAY_CALENDAR_URI;
915
-			$trashbinDisabled = $this->config->getAppValue(Application::APP_ID, RetentionService::RETENTION_CONFIG_KEY) === '0';
916
-			if ($forceDeletePermanently || $isBirthdayCalendar || $trashbinDisabled) {
917
-				$calendarData = $this->getCalendarById($calendarId);
918
-				$shares = $this->getShares($calendarId);
919
-
920
-				$this->purgeCalendarInvitations($calendarId);
921
-
922
-				$qbDeleteCalendarObjectProps = $this->db->getQueryBuilder();
923
-				$qbDeleteCalendarObjectProps->delete($this->dbObjectPropertiesTable)
924
-					->where($qbDeleteCalendarObjectProps->expr()->eq('calendarid', $qbDeleteCalendarObjectProps->createNamedParameter($calendarId)))
925
-					->andWhere($qbDeleteCalendarObjectProps->expr()->eq('calendartype', $qbDeleteCalendarObjectProps->createNamedParameter(self::CALENDAR_TYPE_CALENDAR)))
926
-					->executeStatement();
927
-
928
-				$qbDeleteCalendarObjects = $this->db->getQueryBuilder();
929
-				$qbDeleteCalendarObjects->delete('calendarobjects')
930
-					->where($qbDeleteCalendarObjects->expr()->eq('calendarid', $qbDeleteCalendarObjects->createNamedParameter($calendarId)))
931
-					->andWhere($qbDeleteCalendarObjects->expr()->eq('calendartype', $qbDeleteCalendarObjects->createNamedParameter(self::CALENDAR_TYPE_CALENDAR)))
932
-					->executeStatement();
933
-
934
-				$qbDeleteCalendarChanges = $this->db->getQueryBuilder();
935
-				$qbDeleteCalendarChanges->delete('calendarchanges')
936
-					->where($qbDeleteCalendarChanges->expr()->eq('calendarid', $qbDeleteCalendarChanges->createNamedParameter($calendarId)))
937
-					->andWhere($qbDeleteCalendarChanges->expr()->eq('calendartype', $qbDeleteCalendarChanges->createNamedParameter(self::CALENDAR_TYPE_CALENDAR)))
938
-					->executeStatement();
939
-
940
-				$this->calendarSharingBackend->deleteAllShares($calendarId);
941
-
942
-				$qbDeleteCalendar = $this->db->getQueryBuilder();
943
-				$qbDeleteCalendar->delete('calendars')
944
-					->where($qbDeleteCalendar->expr()->eq('id', $qbDeleteCalendar->createNamedParameter($calendarId)))
945
-					->executeStatement();
946
-
947
-				// Only dispatch if we actually deleted anything
948
-				if ($calendarData) {
949
-					$this->dispatcher->dispatchTyped(new CalendarDeletedEvent($calendarId, $calendarData, $shares));
950
-				}
951
-			} else {
952
-				$qbMarkCalendarDeleted = $this->db->getQueryBuilder();
953
-				$qbMarkCalendarDeleted->update('calendars')
954
-					->set('deleted_at', $qbMarkCalendarDeleted->createNamedParameter(time()))
955
-					->where($qbMarkCalendarDeleted->expr()->eq('id', $qbMarkCalendarDeleted->createNamedParameter($calendarId)))
956
-					->executeStatement();
957
-
958
-				$calendarData = $this->getCalendarById($calendarId);
959
-				$shares = $this->getShares($calendarId);
960
-				if ($calendarData) {
961
-					$this->dispatcher->dispatchTyped(new CalendarMovedToTrashEvent(
962
-						$calendarId,
963
-						$calendarData,
964
-						$shares
965
-					));
966
-				}
967
-			}
968
-		}, $this->db);
969
-	}
970
-
971
-	public function restoreCalendar(int $id): void {
972
-		$this->atomic(function () use ($id): void {
973
-			$qb = $this->db->getQueryBuilder();
974
-			$update = $qb->update('calendars')
975
-				->set('deleted_at', $qb->createNamedParameter(null))
976
-				->where($qb->expr()->eq('id', $qb->createNamedParameter($id, IQueryBuilder::PARAM_INT), IQueryBuilder::PARAM_INT));
977
-			$update->executeStatement();
978
-
979
-			$calendarData = $this->getCalendarById($id);
980
-			$shares = $this->getShares($id);
981
-			if ($calendarData === null) {
982
-				throw new RuntimeException('Calendar data that was just written can\'t be read back. Check your database configuration.');
983
-			}
984
-			$this->dispatcher->dispatchTyped(new CalendarRestoredEvent(
985
-				$id,
986
-				$calendarData,
987
-				$shares
988
-			));
989
-		}, $this->db);
990
-	}
991
-
992
-	/**
993
-	 * Returns all calendar entries as a stream of data
994
-	 *
995
-	 * @since 32.0.0
996
-	 *
997
-	 * @return Generator<array>
998
-	 */
999
-	public function exportCalendar(int $calendarId, int $calendarType = self::CALENDAR_TYPE_CALENDAR, ?CalendarExportOptions $options = null): Generator {
1000
-		// extract options
1001
-		$rangeStart = $options?->getRangeStart();
1002
-		$rangeCount = $options?->getRangeCount();
1003
-		// construct query
1004
-		$qb = $this->db->getQueryBuilder();
1005
-		$qb->select('*')
1006
-			->from('calendarobjects')
1007
-			->where($qb->expr()->eq('calendarid', $qb->createNamedParameter($calendarId)))
1008
-			->andWhere($qb->expr()->eq('calendartype', $qb->createNamedParameter($calendarType)))
1009
-			->andWhere($qb->expr()->isNull('deleted_at'));
1010
-		if ($rangeStart !== null) {
1011
-			$qb->andWhere($qb->expr()->gt('uid', $qb->createNamedParameter($rangeStart)));
1012
-		}
1013
-		if ($rangeCount !== null) {
1014
-			$qb->setMaxResults($rangeCount);
1015
-		}
1016
-		if ($rangeStart !== null || $rangeCount !== null) {
1017
-			$qb->orderBy('uid', 'ASC');
1018
-		}
1019
-		$rs = $qb->executeQuery();
1020
-		// iterate through results
1021
-		try {
1022
-			while (($row = $rs->fetch()) !== false) {
1023
-				yield $row;
1024
-			}
1025
-		} finally {
1026
-			$rs->closeCursor();
1027
-		}
1028
-	}
95
+    use TTransactional;
96
+
97
+    public const CALENDAR_TYPE_CALENDAR = 0;
98
+    public const CALENDAR_TYPE_SUBSCRIPTION = 1;
99
+
100
+    public const PERSONAL_CALENDAR_URI = 'personal';
101
+    public const PERSONAL_CALENDAR_NAME = 'Personal';
102
+
103
+    public const RESOURCE_BOOKING_CALENDAR_URI = 'calendar';
104
+    public const RESOURCE_BOOKING_CALENDAR_NAME = 'Calendar';
105
+
106
+    /**
107
+     * We need to specify a max date, because we need to stop *somewhere*
108
+     *
109
+     * On 32 bit system the maximum for a signed integer is 2147483647, so
110
+     * MAX_DATE cannot be higher than date('Y-m-d', 2147483647) which results
111
+     * in 2038-01-19 to avoid problems when the date is converted
112
+     * to a unix timestamp.
113
+     */
114
+    public const MAX_DATE = '2038-01-01';
115
+
116
+    public const ACCESS_PUBLIC = 4;
117
+    public const CLASSIFICATION_PUBLIC = 0;
118
+    public const CLASSIFICATION_PRIVATE = 1;
119
+    public const CLASSIFICATION_CONFIDENTIAL = 2;
120
+
121
+    /**
122
+     * List of CalDAV properties, and how they map to database field names and their type
123
+     * Add your own properties by simply adding on to this array.
124
+     *
125
+     * @var array
126
+     * @psalm-var array<string, string[]>
127
+     */
128
+    public array $propertyMap = [
129
+        '{DAV:}displayname' => ['displayname', 'string'],
130
+        '{urn:ietf:params:xml:ns:caldav}calendar-description' => ['description', 'string'],
131
+        '{urn:ietf:params:xml:ns:caldav}calendar-timezone' => ['timezone', 'string'],
132
+        '{http://apple.com/ns/ical/}calendar-order' => ['calendarorder', 'int'],
133
+        '{http://apple.com/ns/ical/}calendar-color' => ['calendarcolor', 'string'],
134
+        '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_NEXTCLOUD . '}deleted-at' => ['deleted_at', 'int'],
135
+    ];
136
+
137
+    /**
138
+     * List of subscription properties, and how they map to database field names.
139
+     *
140
+     * @var array
141
+     */
142
+    public array $subscriptionPropertyMap = [
143
+        '{DAV:}displayname' => ['displayname', 'string'],
144
+        '{http://apple.com/ns/ical/}refreshrate' => ['refreshrate', 'string'],
145
+        '{http://apple.com/ns/ical/}calendar-order' => ['calendarorder', 'int'],
146
+        '{http://apple.com/ns/ical/}calendar-color' => ['calendarcolor', 'string'],
147
+        '{http://calendarserver.org/ns/}subscribed-strip-todos' => ['striptodos', 'bool'],
148
+        '{http://calendarserver.org/ns/}subscribed-strip-alarms' => ['stripalarms', 'string'],
149
+        '{http://calendarserver.org/ns/}subscribed-strip-attachments' => ['stripattachments', 'string'],
150
+    ];
151
+
152
+    /**
153
+     * properties to index
154
+     *
155
+     * This list has to be kept in sync with ICalendarQuery::SEARCH_PROPERTY_*
156
+     *
157
+     * @see \OCP\Calendar\ICalendarQuery
158
+     */
159
+    private const INDEXED_PROPERTIES = [
160
+        'CATEGORIES',
161
+        'COMMENT',
162
+        'DESCRIPTION',
163
+        'LOCATION',
164
+        'RESOURCES',
165
+        'STATUS',
166
+        'SUMMARY',
167
+        'ATTENDEE',
168
+        'CONTACT',
169
+        'ORGANIZER'
170
+    ];
171
+
172
+    /** @var array parameters to index */
173
+    public static array $indexParameters = [
174
+        'ATTENDEE' => ['CN'],
175
+        'ORGANIZER' => ['CN'],
176
+    ];
177
+
178
+    /**
179
+     * @var string[] Map of uid => display name
180
+     */
181
+    protected array $userDisplayNames;
182
+
183
+    private string $dbObjectsTable = 'calendarobjects';
184
+    private string $dbObjectPropertiesTable = 'calendarobjects_props';
185
+    private string $dbObjectInvitationsTable = 'calendar_invitations';
186
+    private array $cachedObjects = [];
187
+
188
+    public function __construct(
189
+        private IDBConnection $db,
190
+        private Principal $principalBackend,
191
+        private IUserManager $userManager,
192
+        private ISecureRandom $random,
193
+        private LoggerInterface $logger,
194
+        private IEventDispatcher $dispatcher,
195
+        private IConfig $config,
196
+        private Sharing\Backend $calendarSharingBackend,
197
+        private bool $legacyEndpoint = false,
198
+    ) {
199
+    }
200
+
201
+    /**
202
+     * Return the number of calendars for a principal
203
+     *
204
+     * By default this excludes the automatically generated birthday calendar
205
+     *
206
+     * @param $principalUri
207
+     * @param bool $excludeBirthday
208
+     * @return int
209
+     */
210
+    public function getCalendarsForUserCount($principalUri, $excludeBirthday = true) {
211
+        $principalUri = $this->convertPrincipal($principalUri, true);
212
+        $query = $this->db->getQueryBuilder();
213
+        $query->select($query->func()->count('*'))
214
+            ->from('calendars');
215
+
216
+        if ($principalUri === '') {
217
+            $query->where($query->expr()->emptyString('principaluri'));
218
+        } else {
219
+            $query->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)));
220
+        }
221
+
222
+        if ($excludeBirthday) {
223
+            $query->andWhere($query->expr()->neq('uri', $query->createNamedParameter(BirthdayService::BIRTHDAY_CALENDAR_URI)));
224
+        }
225
+
226
+        $result = $query->executeQuery();
227
+        $column = (int)$result->fetchOne();
228
+        $result->closeCursor();
229
+        return $column;
230
+    }
231
+
232
+    /**
233
+     * Return the number of subscriptions for a principal
234
+     */
235
+    public function getSubscriptionsForUserCount(string $principalUri): int {
236
+        $principalUri = $this->convertPrincipal($principalUri, true);
237
+        $query = $this->db->getQueryBuilder();
238
+        $query->select($query->func()->count('*'))
239
+            ->from('calendarsubscriptions');
240
+
241
+        if ($principalUri === '') {
242
+            $query->where($query->expr()->emptyString('principaluri'));
243
+        } else {
244
+            $query->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)));
245
+        }
246
+
247
+        $result = $query->executeQuery();
248
+        $column = (int)$result->fetchOne();
249
+        $result->closeCursor();
250
+        return $column;
251
+    }
252
+
253
+    /**
254
+     * @return array{id: int, deleted_at: int}[]
255
+     */
256
+    public function getDeletedCalendars(int $deletedBefore): array {
257
+        $qb = $this->db->getQueryBuilder();
258
+        $qb->select(['id', 'deleted_at'])
259
+            ->from('calendars')
260
+            ->where($qb->expr()->isNotNull('deleted_at'))
261
+            ->andWhere($qb->expr()->lt('deleted_at', $qb->createNamedParameter($deletedBefore)));
262
+        $result = $qb->executeQuery();
263
+        $calendars = [];
264
+        while (($row = $result->fetch()) !== false) {
265
+            $calendars[] = [
266
+                'id' => (int)$row['id'],
267
+                'deleted_at' => (int)$row['deleted_at'],
268
+            ];
269
+        }
270
+        $result->closeCursor();
271
+        return $calendars;
272
+    }
273
+
274
+    /**
275
+     * Returns a list of calendars for a principal.
276
+     *
277
+     * Every project is an array with the following keys:
278
+     *  * id, a unique id that will be used by other functions to modify the
279
+     *    calendar. This can be the same as the uri or a database key.
280
+     *  * uri, which the basename of the uri with which the calendar is
281
+     *    accessed.
282
+     *  * principaluri. The owner of the calendar. Almost always the same as
283
+     *    principalUri passed to this method.
284
+     *
285
+     * Furthermore it can contain webdav properties in clark notation. A very
286
+     * common one is '{DAV:}displayname'.
287
+     *
288
+     * Many clients also require:
289
+     * {urn:ietf:params:xml:ns:caldav}supported-calendar-component-set
290
+     * For this property, you can just return an instance of
291
+     * Sabre\CalDAV\Property\SupportedCalendarComponentSet.
292
+     *
293
+     * If you return {http://sabredav.org/ns}read-only and set the value to 1,
294
+     * ACL will automatically be put in read-only mode.
295
+     *
296
+     * @param string $principalUri
297
+     * @return array
298
+     */
299
+    public function getCalendarsForUser($principalUri) {
300
+        return $this->atomic(function () use ($principalUri) {
301
+            $principalUriOriginal = $principalUri;
302
+            $principalUri = $this->convertPrincipal($principalUri, true);
303
+            $fields = array_column($this->propertyMap, 0);
304
+            $fields[] = 'id';
305
+            $fields[] = 'uri';
306
+            $fields[] = 'synctoken';
307
+            $fields[] = 'components';
308
+            $fields[] = 'principaluri';
309
+            $fields[] = 'transparent';
310
+
311
+            // Making fields a comma-delimited list
312
+            $query = $this->db->getQueryBuilder();
313
+            $query->select($fields)
314
+                ->from('calendars')
315
+                ->orderBy('calendarorder', 'ASC');
316
+
317
+            if ($principalUri === '') {
318
+                $query->where($query->expr()->emptyString('principaluri'));
319
+            } else {
320
+                $query->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)));
321
+            }
322
+
323
+            $result = $query->executeQuery();
324
+
325
+            $calendars = [];
326
+            while ($row = $result->fetch()) {
327
+                $row['principaluri'] = (string)$row['principaluri'];
328
+                $components = [];
329
+                if ($row['components']) {
330
+                    $components = explode(',', $row['components']);
331
+                }
332
+
333
+                $calendar = [
334
+                    'id' => $row['id'],
335
+                    'uri' => $row['uri'],
336
+                    'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
337
+                    '{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken'] ?: '0'),
338
+                    '{http://sabredav.org/ns}sync-token' => $row['synctoken'] ?: '0',
339
+                    '{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
340
+                    '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
341
+                    '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($principalUri, !$this->legacyEndpoint),
342
+                ];
343
+
344
+                $calendar = $this->rowToCalendar($row, $calendar);
345
+                $calendar = $this->addOwnerPrincipalToCalendar($calendar);
346
+                $calendar = $this->addResourceTypeToCalendar($row, $calendar);
347
+
348
+                if (!isset($calendars[$calendar['id']])) {
349
+                    $calendars[$calendar['id']] = $calendar;
350
+                }
351
+            }
352
+            $result->closeCursor();
353
+
354
+            // query for shared calendars
355
+            $principals = $this->principalBackend->getGroupMembership($principalUriOriginal, true);
356
+            $principals = array_merge($principals, $this->principalBackend->getCircleMembership($principalUriOriginal));
357
+            $principals[] = $principalUri;
358
+
359
+            $fields = array_column($this->propertyMap, 0);
360
+            $fields = array_map(function (string $field) {
361
+                return 'a.' . $field;
362
+            }, $fields);
363
+            $fields[] = 'a.id';
364
+            $fields[] = 'a.uri';
365
+            $fields[] = 'a.synctoken';
366
+            $fields[] = 'a.components';
367
+            $fields[] = 'a.principaluri';
368
+            $fields[] = 'a.transparent';
369
+            $fields[] = 's.access';
370
+
371
+            $select = $this->db->getQueryBuilder();
372
+            $subSelect = $this->db->getQueryBuilder();
373
+
374
+            $subSelect->select('resourceid')
375
+                ->from('dav_shares', 'd')
376
+                ->where($subSelect->expr()->eq('d.access', $select->createNamedParameter(Backend::ACCESS_UNSHARED, IQueryBuilder::PARAM_INT), IQueryBuilder::PARAM_INT))
377
+                ->andWhere($subSelect->expr()->in('d.principaluri', $select->createNamedParameter($principals, IQueryBuilder::PARAM_STR_ARRAY), IQueryBuilder::PARAM_STR_ARRAY));
378
+
379
+            $select->select($fields)
380
+                ->from('dav_shares', 's')
381
+                ->join('s', 'calendars', 'a', $select->expr()->eq('s.resourceid', 'a.id', IQueryBuilder::PARAM_INT))
382
+                ->where($select->expr()->in('s.principaluri', $select->createNamedParameter($principals, IQueryBuilder::PARAM_STR_ARRAY), IQueryBuilder::PARAM_STR_ARRAY))
383
+                ->andWhere($select->expr()->eq('s.type', $select->createNamedParameter('calendar', IQueryBuilder::PARAM_STR), IQueryBuilder::PARAM_STR))
384
+                ->andWhere($select->expr()->notIn('a.id', $select->createFunction($subSelect->getSQL()), IQueryBuilder::PARAM_INT_ARRAY));
385
+
386
+            $results = $select->executeQuery();
387
+
388
+            $readOnlyPropertyName = '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}read-only';
389
+            while ($row = $results->fetch()) {
390
+                $row['principaluri'] = (string)$row['principaluri'];
391
+                if ($row['principaluri'] === $principalUri) {
392
+                    continue;
393
+                }
394
+
395
+                $readOnly = (int)$row['access'] === Backend::ACCESS_READ;
396
+                if (isset($calendars[$row['id']])) {
397
+                    if ($readOnly) {
398
+                        // New share can not have more permissions than the old one.
399
+                        continue;
400
+                    }
401
+                    if (isset($calendars[$row['id']][$readOnlyPropertyName]) &&
402
+                        $calendars[$row['id']][$readOnlyPropertyName] === 0) {
403
+                        // Old share is already read-write, no more permissions can be gained
404
+                        continue;
405
+                    }
406
+                }
407
+
408
+                [, $name] = Uri\split($row['principaluri']);
409
+                $uri = $row['uri'] . '_shared_by_' . $name;
410
+                $row['displayname'] = $row['displayname'] . ' (' . ($this->userManager->getDisplayName($name) ?? ($name ?? '')) . ')';
411
+                $components = [];
412
+                if ($row['components']) {
413
+                    $components = explode(',', $row['components']);
414
+                }
415
+                $calendar = [
416
+                    'id' => $row['id'],
417
+                    'uri' => $uri,
418
+                    'principaluri' => $this->convertPrincipal($principalUri, !$this->legacyEndpoint),
419
+                    '{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken'] ?: '0'),
420
+                    '{http://sabredav.org/ns}sync-token' => $row['synctoken'] ?: '0',
421
+                    '{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
422
+                    '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp('transparent'),
423
+                    '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
424
+                    $readOnlyPropertyName => $readOnly,
425
+                ];
426
+
427
+                $calendar = $this->rowToCalendar($row, $calendar);
428
+                $calendar = $this->addOwnerPrincipalToCalendar($calendar);
429
+                $calendar = $this->addResourceTypeToCalendar($row, $calendar);
430
+
431
+                $calendars[$calendar['id']] = $calendar;
432
+            }
433
+            $result->closeCursor();
434
+
435
+            return array_values($calendars);
436
+        }, $this->db);
437
+    }
438
+
439
+    /**
440
+     * @param $principalUri
441
+     * @return array
442
+     */
443
+    public function getUsersOwnCalendars($principalUri) {
444
+        $principalUri = $this->convertPrincipal($principalUri, true);
445
+        $fields = array_column($this->propertyMap, 0);
446
+        $fields[] = 'id';
447
+        $fields[] = 'uri';
448
+        $fields[] = 'synctoken';
449
+        $fields[] = 'components';
450
+        $fields[] = 'principaluri';
451
+        $fields[] = 'transparent';
452
+        // Making fields a comma-delimited list
453
+        $query = $this->db->getQueryBuilder();
454
+        $query->select($fields)->from('calendars')
455
+            ->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
456
+            ->orderBy('calendarorder', 'ASC');
457
+        $stmt = $query->executeQuery();
458
+        $calendars = [];
459
+        while ($row = $stmt->fetch()) {
460
+            $row['principaluri'] = (string)$row['principaluri'];
461
+            $components = [];
462
+            if ($row['components']) {
463
+                $components = explode(',', $row['components']);
464
+            }
465
+            $calendar = [
466
+                'id' => $row['id'],
467
+                'uri' => $row['uri'],
468
+                'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
469
+                '{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken'] ?: '0'),
470
+                '{http://sabredav.org/ns}sync-token' => $row['synctoken'] ?: '0',
471
+                '{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
472
+                '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
473
+            ];
474
+
475
+            $calendar = $this->rowToCalendar($row, $calendar);
476
+            $calendar = $this->addOwnerPrincipalToCalendar($calendar);
477
+            $calendar = $this->addResourceTypeToCalendar($row, $calendar);
478
+
479
+            if (!isset($calendars[$calendar['id']])) {
480
+                $calendars[$calendar['id']] = $calendar;
481
+            }
482
+        }
483
+        $stmt->closeCursor();
484
+        return array_values($calendars);
485
+    }
486
+
487
+    /**
488
+     * @return array
489
+     */
490
+    public function getPublicCalendars() {
491
+        $fields = array_column($this->propertyMap, 0);
492
+        $fields[] = 'a.id';
493
+        $fields[] = 'a.uri';
494
+        $fields[] = 'a.synctoken';
495
+        $fields[] = 'a.components';
496
+        $fields[] = 'a.principaluri';
497
+        $fields[] = 'a.transparent';
498
+        $fields[] = 's.access';
499
+        $fields[] = 's.publicuri';
500
+        $calendars = [];
501
+        $query = $this->db->getQueryBuilder();
502
+        $result = $query->select($fields)
503
+            ->from('dav_shares', 's')
504
+            ->join('s', 'calendars', 'a', $query->expr()->eq('s.resourceid', 'a.id'))
505
+            ->where($query->expr()->in('s.access', $query->createNamedParameter(self::ACCESS_PUBLIC)))
506
+            ->andWhere($query->expr()->eq('s.type', $query->createNamedParameter('calendar')))
507
+            ->executeQuery();
508
+
509
+        while ($row = $result->fetch()) {
510
+            $row['principaluri'] = (string)$row['principaluri'];
511
+            [, $name] = Uri\split($row['principaluri']);
512
+            $row['displayname'] = $row['displayname'] . "($name)";
513
+            $components = [];
514
+            if ($row['components']) {
515
+                $components = explode(',', $row['components']);
516
+            }
517
+            $calendar = [
518
+                'id' => $row['id'],
519
+                'uri' => $row['publicuri'],
520
+                'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
521
+                '{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken'] ?: '0'),
522
+                '{http://sabredav.org/ns}sync-token' => $row['synctoken'] ?: '0',
523
+                '{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
524
+                '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
525
+                '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($row['principaluri'], $this->legacyEndpoint),
526
+                '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}read-only' => (int)$row['access'] === Backend::ACCESS_READ,
527
+                '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}public' => (int)$row['access'] === self::ACCESS_PUBLIC,
528
+            ];
529
+
530
+            $calendar = $this->rowToCalendar($row, $calendar);
531
+            $calendar = $this->addOwnerPrincipalToCalendar($calendar);
532
+            $calendar = $this->addResourceTypeToCalendar($row, $calendar);
533
+
534
+            if (!isset($calendars[$calendar['id']])) {
535
+                $calendars[$calendar['id']] = $calendar;
536
+            }
537
+        }
538
+        $result->closeCursor();
539
+
540
+        return array_values($calendars);
541
+    }
542
+
543
+    /**
544
+     * @param string $uri
545
+     * @return array
546
+     * @throws NotFound
547
+     */
548
+    public function getPublicCalendar($uri) {
549
+        $fields = array_column($this->propertyMap, 0);
550
+        $fields[] = 'a.id';
551
+        $fields[] = 'a.uri';
552
+        $fields[] = 'a.synctoken';
553
+        $fields[] = 'a.components';
554
+        $fields[] = 'a.principaluri';
555
+        $fields[] = 'a.transparent';
556
+        $fields[] = 's.access';
557
+        $fields[] = 's.publicuri';
558
+        $query = $this->db->getQueryBuilder();
559
+        $result = $query->select($fields)
560
+            ->from('dav_shares', 's')
561
+            ->join('s', 'calendars', 'a', $query->expr()->eq('s.resourceid', 'a.id'))
562
+            ->where($query->expr()->in('s.access', $query->createNamedParameter(self::ACCESS_PUBLIC)))
563
+            ->andWhere($query->expr()->eq('s.type', $query->createNamedParameter('calendar')))
564
+            ->andWhere($query->expr()->eq('s.publicuri', $query->createNamedParameter($uri)))
565
+            ->executeQuery();
566
+
567
+        $row = $result->fetch();
568
+
569
+        $result->closeCursor();
570
+
571
+        if ($row === false) {
572
+            throw new NotFound('Node with name \'' . $uri . '\' could not be found');
573
+        }
574
+
575
+        $row['principaluri'] = (string)$row['principaluri'];
576
+        [, $name] = Uri\split($row['principaluri']);
577
+        $row['displayname'] = $row['displayname'] . ' ' . "($name)";
578
+        $components = [];
579
+        if ($row['components']) {
580
+            $components = explode(',', $row['components']);
581
+        }
582
+        $calendar = [
583
+            'id' => $row['id'],
584
+            'uri' => $row['publicuri'],
585
+            'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
586
+            '{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken'] ?: '0'),
587
+            '{http://sabredav.org/ns}sync-token' => $row['synctoken'] ?: '0',
588
+            '{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
589
+            '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
590
+            '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
591
+            '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}read-only' => (int)$row['access'] === Backend::ACCESS_READ,
592
+            '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}public' => (int)$row['access'] === self::ACCESS_PUBLIC,
593
+        ];
594
+
595
+        $calendar = $this->rowToCalendar($row, $calendar);
596
+        $calendar = $this->addOwnerPrincipalToCalendar($calendar);
597
+        $calendar = $this->addResourceTypeToCalendar($row, $calendar);
598
+
599
+        return $calendar;
600
+    }
601
+
602
+    /**
603
+     * @param string $principal
604
+     * @param string $uri
605
+     * @return array|null
606
+     */
607
+    public function getCalendarByUri($principal, $uri) {
608
+        $fields = array_column($this->propertyMap, 0);
609
+        $fields[] = 'id';
610
+        $fields[] = 'uri';
611
+        $fields[] = 'synctoken';
612
+        $fields[] = 'components';
613
+        $fields[] = 'principaluri';
614
+        $fields[] = 'transparent';
615
+
616
+        // Making fields a comma-delimited list
617
+        $query = $this->db->getQueryBuilder();
618
+        $query->select($fields)->from('calendars')
619
+            ->where($query->expr()->eq('uri', $query->createNamedParameter($uri)))
620
+            ->andWhere($query->expr()->eq('principaluri', $query->createNamedParameter($principal)))
621
+            ->setMaxResults(1);
622
+        $stmt = $query->executeQuery();
623
+
624
+        $row = $stmt->fetch();
625
+        $stmt->closeCursor();
626
+        if ($row === false) {
627
+            return null;
628
+        }
629
+
630
+        $row['principaluri'] = (string)$row['principaluri'];
631
+        $components = [];
632
+        if ($row['components']) {
633
+            $components = explode(',', $row['components']);
634
+        }
635
+
636
+        $calendar = [
637
+            'id' => $row['id'],
638
+            'uri' => $row['uri'],
639
+            'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
640
+            '{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken'] ?: '0'),
641
+            '{http://sabredav.org/ns}sync-token' => $row['synctoken'] ?: '0',
642
+            '{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
643
+            '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
644
+        ];
645
+
646
+        $calendar = $this->rowToCalendar($row, $calendar);
647
+        $calendar = $this->addOwnerPrincipalToCalendar($calendar);
648
+        $calendar = $this->addResourceTypeToCalendar($row, $calendar);
649
+
650
+        return $calendar;
651
+    }
652
+
653
+    /**
654
+     * @return array{id: int, uri: string, '{http://calendarserver.org/ns/}getctag': string, '{http://sabredav.org/ns}sync-token': int, '{urn:ietf:params:xml:ns:caldav}supported-calendar-component-set': SupportedCalendarComponentSet, '{urn:ietf:params:xml:ns:caldav}schedule-calendar-transp': ScheduleCalendarTransp, '{urn:ietf:params:xml:ns:caldav}calendar-timezone': ?string }|null
655
+     */
656
+    public function getCalendarById(int $calendarId): ?array {
657
+        $fields = array_column($this->propertyMap, 0);
658
+        $fields[] = 'id';
659
+        $fields[] = 'uri';
660
+        $fields[] = 'synctoken';
661
+        $fields[] = 'components';
662
+        $fields[] = 'principaluri';
663
+        $fields[] = 'transparent';
664
+
665
+        // Making fields a comma-delimited list
666
+        $query = $this->db->getQueryBuilder();
667
+        $query->select($fields)->from('calendars')
668
+            ->where($query->expr()->eq('id', $query->createNamedParameter($calendarId)))
669
+            ->setMaxResults(1);
670
+        $stmt = $query->executeQuery();
671
+
672
+        $row = $stmt->fetch();
673
+        $stmt->closeCursor();
674
+        if ($row === false) {
675
+            return null;
676
+        }
677
+
678
+        $row['principaluri'] = (string)$row['principaluri'];
679
+        $components = [];
680
+        if ($row['components']) {
681
+            $components = explode(',', $row['components']);
682
+        }
683
+
684
+        $calendar = [
685
+            'id' => $row['id'],
686
+            'uri' => $row['uri'],
687
+            'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
688
+            '{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken'] ?: '0'),
689
+            '{http://sabredav.org/ns}sync-token' => $row['synctoken'] ?? 0,
690
+            '{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
691
+            '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
692
+        ];
693
+
694
+        $calendar = $this->rowToCalendar($row, $calendar);
695
+        $calendar = $this->addOwnerPrincipalToCalendar($calendar);
696
+        $calendar = $this->addResourceTypeToCalendar($row, $calendar);
697
+
698
+        return $calendar;
699
+    }
700
+
701
+    /**
702
+     * @param $subscriptionId
703
+     */
704
+    public function getSubscriptionById($subscriptionId) {
705
+        $fields = array_column($this->subscriptionPropertyMap, 0);
706
+        $fields[] = 'id';
707
+        $fields[] = 'uri';
708
+        $fields[] = 'source';
709
+        $fields[] = 'synctoken';
710
+        $fields[] = 'principaluri';
711
+        $fields[] = 'lastmodified';
712
+
713
+        $query = $this->db->getQueryBuilder();
714
+        $query->select($fields)
715
+            ->from('calendarsubscriptions')
716
+            ->where($query->expr()->eq('id', $query->createNamedParameter($subscriptionId)))
717
+            ->orderBy('calendarorder', 'asc');
718
+        $stmt = $query->executeQuery();
719
+
720
+        $row = $stmt->fetch();
721
+        $stmt->closeCursor();
722
+        if ($row === false) {
723
+            return null;
724
+        }
725
+
726
+        $row['principaluri'] = (string)$row['principaluri'];
727
+        $subscription = [
728
+            'id' => $row['id'],
729
+            'uri' => $row['uri'],
730
+            'principaluri' => $row['principaluri'],
731
+            'source' => $row['source'],
732
+            'lastmodified' => $row['lastmodified'],
733
+            '{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet(['VTODO', 'VEVENT']),
734
+            '{http://sabredav.org/ns}sync-token' => $row['synctoken'] ?: '0',
735
+        ];
736
+
737
+        return $this->rowToSubscription($row, $subscription);
738
+    }
739
+
740
+    public function getSubscriptionByUri(string $principal, string $uri): ?array {
741
+        $fields = array_column($this->subscriptionPropertyMap, 0);
742
+        $fields[] = 'id';
743
+        $fields[] = 'uri';
744
+        $fields[] = 'source';
745
+        $fields[] = 'synctoken';
746
+        $fields[] = 'principaluri';
747
+        $fields[] = 'lastmodified';
748
+
749
+        $query = $this->db->getQueryBuilder();
750
+        $query->select($fields)
751
+            ->from('calendarsubscriptions')
752
+            ->where($query->expr()->eq('uri', $query->createNamedParameter($uri)))
753
+            ->andWhere($query->expr()->eq('principaluri', $query->createNamedParameter($principal)))
754
+            ->setMaxResults(1);
755
+        $stmt = $query->executeQuery();
756
+
757
+        $row = $stmt->fetch();
758
+        $stmt->closeCursor();
759
+        if ($row === false) {
760
+            return null;
761
+        }
762
+
763
+        $row['principaluri'] = (string)$row['principaluri'];
764
+        $subscription = [
765
+            'id' => $row['id'],
766
+            'uri' => $row['uri'],
767
+            'principaluri' => $row['principaluri'],
768
+            'source' => $row['source'],
769
+            'lastmodified' => $row['lastmodified'],
770
+            '{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet(['VTODO', 'VEVENT']),
771
+            '{http://sabredav.org/ns}sync-token' => $row['synctoken'] ?: '0',
772
+        ];
773
+
774
+        return $this->rowToSubscription($row, $subscription);
775
+    }
776
+
777
+    /**
778
+     * Creates a new calendar for a principal.
779
+     *
780
+     * If the creation was a success, an id must be returned that can be used to reference
781
+     * this calendar in other methods, such as updateCalendar.
782
+     *
783
+     * @param string $principalUri
784
+     * @param string $calendarUri
785
+     * @param array $properties
786
+     * @return int
787
+     *
788
+     * @throws CalendarException
789
+     */
790
+    public function createCalendar($principalUri, $calendarUri, array $properties) {
791
+        if (strlen($calendarUri) > 255) {
792
+            throw new CalendarException('URI too long. Calendar not created');
793
+        }
794
+
795
+        $values = [
796
+            'principaluri' => $this->convertPrincipal($principalUri, true),
797
+            'uri' => $calendarUri,
798
+            'synctoken' => 1,
799
+            'transparent' => 0,
800
+            'components' => 'VEVENT,VTODO,VJOURNAL',
801
+            'displayname' => $calendarUri
802
+        ];
803
+
804
+        // Default value
805
+        $sccs = '{urn:ietf:params:xml:ns:caldav}supported-calendar-component-set';
806
+        if (isset($properties[$sccs])) {
807
+            if (!($properties[$sccs] instanceof SupportedCalendarComponentSet)) {
808
+                throw new DAV\Exception('The ' . $sccs . ' property must be of type: \Sabre\CalDAV\Property\SupportedCalendarComponentSet');
809
+            }
810
+            $values['components'] = implode(',', $properties[$sccs]->getValue());
811
+        } elseif (isset($properties['components'])) {
812
+            // Allow to provide components internally without having
813
+            // to create a SupportedCalendarComponentSet object
814
+            $values['components'] = $properties['components'];
815
+        }
816
+
817
+        $transp = '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp';
818
+        if (isset($properties[$transp])) {
819
+            $values['transparent'] = (int)($properties[$transp]->getValue() === 'transparent');
820
+        }
821
+
822
+        foreach ($this->propertyMap as $xmlName => [$dbName, $type]) {
823
+            if (isset($properties[$xmlName])) {
824
+                $values[$dbName] = $properties[$xmlName];
825
+            }
826
+        }
827
+
828
+        [$calendarId, $calendarData] = $this->atomic(function () use ($values) {
829
+            $query = $this->db->getQueryBuilder();
830
+            $query->insert('calendars');
831
+            foreach ($values as $column => $value) {
832
+                $query->setValue($column, $query->createNamedParameter($value));
833
+            }
834
+            $query->executeStatement();
835
+            $calendarId = $query->getLastInsertId();
836
+
837
+            $calendarData = $this->getCalendarById($calendarId);
838
+            return [$calendarId, $calendarData];
839
+        }, $this->db);
840
+
841
+        $this->dispatcher->dispatchTyped(new CalendarCreatedEvent((int)$calendarId, $calendarData));
842
+
843
+        return $calendarId;
844
+    }
845
+
846
+    /**
847
+     * Updates properties for a calendar.
848
+     *
849
+     * The list of mutations is stored in a Sabre\DAV\PropPatch object.
850
+     * To do the actual updates, you must tell this object which properties
851
+     * you're going to process with the handle() method.
852
+     *
853
+     * Calling the handle method is like telling the PropPatch object "I
854
+     * promise I can handle updating this property".
855
+     *
856
+     * Read the PropPatch documentation for more info and examples.
857
+     *
858
+     * @param mixed $calendarId
859
+     * @param PropPatch $propPatch
860
+     * @return void
861
+     */
862
+    public function updateCalendar($calendarId, PropPatch $propPatch) {
863
+        $supportedProperties = array_keys($this->propertyMap);
864
+        $supportedProperties[] = '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp';
865
+
866
+        $propPatch->handle($supportedProperties, function ($mutations) use ($calendarId) {
867
+            $newValues = [];
868
+            foreach ($mutations as $propertyName => $propertyValue) {
869
+                switch ($propertyName) {
870
+                    case '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp':
871
+                        $fieldName = 'transparent';
872
+                        $newValues[$fieldName] = (int)($propertyValue->getValue() === 'transparent');
873
+                        break;
874
+                    default:
875
+                        $fieldName = $this->propertyMap[$propertyName][0];
876
+                        $newValues[$fieldName] = $propertyValue;
877
+                        break;
878
+                }
879
+            }
880
+            [$calendarData, $shares] = $this->atomic(function () use ($calendarId, $newValues) {
881
+                $query = $this->db->getQueryBuilder();
882
+                $query->update('calendars');
883
+                foreach ($newValues as $fieldName => $value) {
884
+                    $query->set($fieldName, $query->createNamedParameter($value));
885
+                }
886
+                $query->where($query->expr()->eq('id', $query->createNamedParameter($calendarId)));
887
+                $query->executeStatement();
888
+
889
+                $this->addChanges($calendarId, [''], 2);
890
+
891
+                $calendarData = $this->getCalendarById($calendarId);
892
+                $shares = $this->getShares($calendarId);
893
+                return [$calendarData, $shares];
894
+            }, $this->db);
895
+
896
+            $this->dispatcher->dispatchTyped(new CalendarUpdatedEvent($calendarId, $calendarData, $shares, $mutations));
897
+
898
+            return true;
899
+        });
900
+    }
901
+
902
+    /**
903
+     * Delete a calendar and all it's objects
904
+     *
905
+     * @param mixed $calendarId
906
+     * @return void
907
+     */
908
+    public function deleteCalendar($calendarId, bool $forceDeletePermanently = false) {
909
+        $this->atomic(function () use ($calendarId, $forceDeletePermanently): void {
910
+            // The calendar is deleted right away if this is either enforced by the caller
911
+            // or the special contacts birthday calendar or when the preference of an empty
912
+            // retention (0 seconds) is set, which signals a disabled trashbin.
913
+            $calendarData = $this->getCalendarById($calendarId);
914
+            $isBirthdayCalendar = isset($calendarData['uri']) && $calendarData['uri'] === BirthdayService::BIRTHDAY_CALENDAR_URI;
915
+            $trashbinDisabled = $this->config->getAppValue(Application::APP_ID, RetentionService::RETENTION_CONFIG_KEY) === '0';
916
+            if ($forceDeletePermanently || $isBirthdayCalendar || $trashbinDisabled) {
917
+                $calendarData = $this->getCalendarById($calendarId);
918
+                $shares = $this->getShares($calendarId);
919
+
920
+                $this->purgeCalendarInvitations($calendarId);
921
+
922
+                $qbDeleteCalendarObjectProps = $this->db->getQueryBuilder();
923
+                $qbDeleteCalendarObjectProps->delete($this->dbObjectPropertiesTable)
924
+                    ->where($qbDeleteCalendarObjectProps->expr()->eq('calendarid', $qbDeleteCalendarObjectProps->createNamedParameter($calendarId)))
925
+                    ->andWhere($qbDeleteCalendarObjectProps->expr()->eq('calendartype', $qbDeleteCalendarObjectProps->createNamedParameter(self::CALENDAR_TYPE_CALENDAR)))
926
+                    ->executeStatement();
927
+
928
+                $qbDeleteCalendarObjects = $this->db->getQueryBuilder();
929
+                $qbDeleteCalendarObjects->delete('calendarobjects')
930
+                    ->where($qbDeleteCalendarObjects->expr()->eq('calendarid', $qbDeleteCalendarObjects->createNamedParameter($calendarId)))
931
+                    ->andWhere($qbDeleteCalendarObjects->expr()->eq('calendartype', $qbDeleteCalendarObjects->createNamedParameter(self::CALENDAR_TYPE_CALENDAR)))
932
+                    ->executeStatement();
933
+
934
+                $qbDeleteCalendarChanges = $this->db->getQueryBuilder();
935
+                $qbDeleteCalendarChanges->delete('calendarchanges')
936
+                    ->where($qbDeleteCalendarChanges->expr()->eq('calendarid', $qbDeleteCalendarChanges->createNamedParameter($calendarId)))
937
+                    ->andWhere($qbDeleteCalendarChanges->expr()->eq('calendartype', $qbDeleteCalendarChanges->createNamedParameter(self::CALENDAR_TYPE_CALENDAR)))
938
+                    ->executeStatement();
939
+
940
+                $this->calendarSharingBackend->deleteAllShares($calendarId);
941
+
942
+                $qbDeleteCalendar = $this->db->getQueryBuilder();
943
+                $qbDeleteCalendar->delete('calendars')
944
+                    ->where($qbDeleteCalendar->expr()->eq('id', $qbDeleteCalendar->createNamedParameter($calendarId)))
945
+                    ->executeStatement();
946
+
947
+                // Only dispatch if we actually deleted anything
948
+                if ($calendarData) {
949
+                    $this->dispatcher->dispatchTyped(new CalendarDeletedEvent($calendarId, $calendarData, $shares));
950
+                }
951
+            } else {
952
+                $qbMarkCalendarDeleted = $this->db->getQueryBuilder();
953
+                $qbMarkCalendarDeleted->update('calendars')
954
+                    ->set('deleted_at', $qbMarkCalendarDeleted->createNamedParameter(time()))
955
+                    ->where($qbMarkCalendarDeleted->expr()->eq('id', $qbMarkCalendarDeleted->createNamedParameter($calendarId)))
956
+                    ->executeStatement();
957
+
958
+                $calendarData = $this->getCalendarById($calendarId);
959
+                $shares = $this->getShares($calendarId);
960
+                if ($calendarData) {
961
+                    $this->dispatcher->dispatchTyped(new CalendarMovedToTrashEvent(
962
+                        $calendarId,
963
+                        $calendarData,
964
+                        $shares
965
+                    ));
966
+                }
967
+            }
968
+        }, $this->db);
969
+    }
970
+
971
+    public function restoreCalendar(int $id): void {
972
+        $this->atomic(function () use ($id): void {
973
+            $qb = $this->db->getQueryBuilder();
974
+            $update = $qb->update('calendars')
975
+                ->set('deleted_at', $qb->createNamedParameter(null))
976
+                ->where($qb->expr()->eq('id', $qb->createNamedParameter($id, IQueryBuilder::PARAM_INT), IQueryBuilder::PARAM_INT));
977
+            $update->executeStatement();
978
+
979
+            $calendarData = $this->getCalendarById($id);
980
+            $shares = $this->getShares($id);
981
+            if ($calendarData === null) {
982
+                throw new RuntimeException('Calendar data that was just written can\'t be read back. Check your database configuration.');
983
+            }
984
+            $this->dispatcher->dispatchTyped(new CalendarRestoredEvent(
985
+                $id,
986
+                $calendarData,
987
+                $shares
988
+            ));
989
+        }, $this->db);
990
+    }
991
+
992
+    /**
993
+     * Returns all calendar entries as a stream of data
994
+     *
995
+     * @since 32.0.0
996
+     *
997
+     * @return Generator<array>
998
+     */
999
+    public function exportCalendar(int $calendarId, int $calendarType = self::CALENDAR_TYPE_CALENDAR, ?CalendarExportOptions $options = null): Generator {
1000
+        // extract options
1001
+        $rangeStart = $options?->getRangeStart();
1002
+        $rangeCount = $options?->getRangeCount();
1003
+        // construct query
1004
+        $qb = $this->db->getQueryBuilder();
1005
+        $qb->select('*')
1006
+            ->from('calendarobjects')
1007
+            ->where($qb->expr()->eq('calendarid', $qb->createNamedParameter($calendarId)))
1008
+            ->andWhere($qb->expr()->eq('calendartype', $qb->createNamedParameter($calendarType)))
1009
+            ->andWhere($qb->expr()->isNull('deleted_at'));
1010
+        if ($rangeStart !== null) {
1011
+            $qb->andWhere($qb->expr()->gt('uid', $qb->createNamedParameter($rangeStart)));
1012
+        }
1013
+        if ($rangeCount !== null) {
1014
+            $qb->setMaxResults($rangeCount);
1015
+        }
1016
+        if ($rangeStart !== null || $rangeCount !== null) {
1017
+            $qb->orderBy('uid', 'ASC');
1018
+        }
1019
+        $rs = $qb->executeQuery();
1020
+        // iterate through results
1021
+        try {
1022
+            while (($row = $rs->fetch()) !== false) {
1023
+                yield $row;
1024
+            }
1025
+        } finally {
1026
+            $rs->closeCursor();
1027
+        }
1028
+    }
1029 1029
 	
1030
-	/**
1031
-	 * Returns all calendar objects with limited metadata for a calendar
1032
-	 *
1033
-	 * Every item contains an array with the following keys:
1034
-	 *   * id - the table row id
1035
-	 *   * etag - An arbitrary string
1036
-	 *   * uri - a unique key which will be used to construct the uri. This can
1037
-	 *     be any arbitrary string.
1038
-	 *   * calendardata - The iCalendar-compatible calendar data
1039
-	 *
1040
-	 * @param mixed $calendarId
1041
-	 * @param int $calendarType
1042
-	 * @return array
1043
-	 */
1044
-	public function getLimitedCalendarObjects(int $calendarId, int $calendarType = self::CALENDAR_TYPE_CALENDAR):array {
1045
-		$query = $this->db->getQueryBuilder();
1046
-		$query->select(['id','uid', 'etag', 'uri', 'calendardata'])
1047
-			->from('calendarobjects')
1048
-			->where($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)))
1049
-			->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter($calendarType)))
1050
-			->andWhere($query->expr()->isNull('deleted_at'));
1051
-		$stmt = $query->executeQuery();
1052
-
1053
-		$result = [];
1054
-		while (($row = $stmt->fetch()) !== false) {
1055
-			$result[$row['uid']] = [
1056
-				'id' => $row['id'],
1057
-				'etag' => $row['etag'],
1058
-				'uri' => $row['uri'],
1059
-				'calendardata' => $row['calendardata'],
1060
-			];
1061
-		}
1062
-		$stmt->closeCursor();
1063
-
1064
-		return $result;
1065
-	}
1066
-
1067
-	/**
1068
-	 * Delete all of an user's shares
1069
-	 *
1070
-	 * @param string $principaluri
1071
-	 * @return void
1072
-	 */
1073
-	public function deleteAllSharesByUser($principaluri) {
1074
-		$this->calendarSharingBackend->deleteAllSharesByUser($principaluri);
1075
-	}
1076
-
1077
-	/**
1078
-	 * Returns all calendar objects within a calendar.
1079
-	 *
1080
-	 * Every item contains an array with the following keys:
1081
-	 *   * calendardata - The iCalendar-compatible calendar data
1082
-	 *   * uri - a unique key which will be used to construct the uri. This can
1083
-	 *     be any arbitrary string, but making sure it ends with '.ics' is a
1084
-	 *     good idea. This is only the basename, or filename, not the full
1085
-	 *     path.
1086
-	 *   * lastmodified - a timestamp of the last modification time
1087
-	 *   * etag - An arbitrary string, surrounded by double-quotes. (e.g.:
1088
-	 *   '"abcdef"')
1089
-	 *   * size - The size of the calendar objects, in bytes.
1090
-	 *   * component - optional, a string containing the type of object, such
1091
-	 *     as 'vevent' or 'vtodo'. If specified, this will be used to populate
1092
-	 *     the Content-Type header.
1093
-	 *
1094
-	 * Note that the etag is optional, but it's highly encouraged to return for
1095
-	 * speed reasons.
1096
-	 *
1097
-	 * The calendardata is also optional. If it's not returned
1098
-	 * 'getCalendarObject' will be called later, which *is* expected to return
1099
-	 * calendardata.
1100
-	 *
1101
-	 * If neither etag or size are specified, the calendardata will be
1102
-	 * used/fetched to determine these numbers. If both are specified the
1103
-	 * amount of times this is needed is reduced by a great degree.
1104
-	 *
1105
-	 * @param mixed $calendarId
1106
-	 * @param int $calendarType
1107
-	 * @return array
1108
-	 */
1109
-	public function getCalendarObjects($calendarId, $calendarType = self::CALENDAR_TYPE_CALENDAR):array {
1110
-		$query = $this->db->getQueryBuilder();
1111
-		$query->select(['id', 'uri', 'lastmodified', 'etag', 'calendarid', 'size', 'componenttype', 'classification'])
1112
-			->from('calendarobjects')
1113
-			->where($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)))
1114
-			->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter($calendarType)))
1115
-			->andWhere($query->expr()->isNull('deleted_at'));
1116
-		$stmt = $query->executeQuery();
1117
-
1118
-		$result = [];
1119
-		while (($row = $stmt->fetch()) !== false) {
1120
-			$result[] = [
1121
-				'id' => $row['id'],
1122
-				'uri' => $row['uri'],
1123
-				'lastmodified' => $row['lastmodified'],
1124
-				'etag' => '"' . $row['etag'] . '"',
1125
-				'calendarid' => $row['calendarid'],
1126
-				'size' => (int)$row['size'],
1127
-				'component' => strtolower($row['componenttype']),
1128
-				'classification' => (int)$row['classification']
1129
-			];
1130
-		}
1131
-		$stmt->closeCursor();
1132
-
1133
-		return $result;
1134
-	}
1135
-
1136
-	public function getDeletedCalendarObjects(int $deletedBefore): array {
1137
-		$query = $this->db->getQueryBuilder();
1138
-		$query->select(['co.id', 'co.uri', 'co.lastmodified', 'co.etag', 'co.calendarid', 'co.calendartype', 'co.size', 'co.componenttype', 'co.classification', 'co.deleted_at'])
1139
-			->from('calendarobjects', 'co')
1140
-			->join('co', 'calendars', 'c', $query->expr()->eq('c.id', 'co.calendarid', IQueryBuilder::PARAM_INT))
1141
-			->where($query->expr()->isNotNull('co.deleted_at'))
1142
-			->andWhere($query->expr()->lt('co.deleted_at', $query->createNamedParameter($deletedBefore)));
1143
-		$stmt = $query->executeQuery();
1144
-
1145
-		$result = [];
1146
-		while (($row = $stmt->fetch()) !== false) {
1147
-			$result[] = [
1148
-				'id' => $row['id'],
1149
-				'uri' => $row['uri'],
1150
-				'lastmodified' => $row['lastmodified'],
1151
-				'etag' => '"' . $row['etag'] . '"',
1152
-				'calendarid' => (int)$row['calendarid'],
1153
-				'calendartype' => (int)$row['calendartype'],
1154
-				'size' => (int)$row['size'],
1155
-				'component' => strtolower($row['componenttype']),
1156
-				'classification' => (int)$row['classification'],
1157
-				'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_NEXTCLOUD . '}deleted-at' => $row['deleted_at'] === null ? $row['deleted_at'] : (int)$row['deleted_at'],
1158
-			];
1159
-		}
1160
-		$stmt->closeCursor();
1161
-
1162
-		return $result;
1163
-	}
1164
-
1165
-	/**
1166
-	 * Return all deleted calendar objects by the given principal that are not
1167
-	 * in deleted calendars.
1168
-	 *
1169
-	 * @param string $principalUri
1170
-	 * @return array
1171
-	 * @throws Exception
1172
-	 */
1173
-	public function getDeletedCalendarObjectsByPrincipal(string $principalUri): array {
1174
-		$query = $this->db->getQueryBuilder();
1175
-		$query->select(['co.id', 'co.uri', 'co.lastmodified', 'co.etag', 'co.calendarid', 'co.size', 'co.componenttype', 'co.classification', 'co.deleted_at'])
1176
-			->selectAlias('c.uri', 'calendaruri')
1177
-			->from('calendarobjects', 'co')
1178
-			->join('co', 'calendars', 'c', $query->expr()->eq('c.id', 'co.calendarid', IQueryBuilder::PARAM_INT))
1179
-			->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
1180
-			->andWhere($query->expr()->isNotNull('co.deleted_at'))
1181
-			->andWhere($query->expr()->isNull('c.deleted_at'));
1182
-		$stmt = $query->executeQuery();
1183
-
1184
-		$result = [];
1185
-		while ($row = $stmt->fetch()) {
1186
-			$result[] = [
1187
-				'id' => $row['id'],
1188
-				'uri' => $row['uri'],
1189
-				'lastmodified' => $row['lastmodified'],
1190
-				'etag' => '"' . $row['etag'] . '"',
1191
-				'calendarid' => $row['calendarid'],
1192
-				'calendaruri' => $row['calendaruri'],
1193
-				'size' => (int)$row['size'],
1194
-				'component' => strtolower($row['componenttype']),
1195
-				'classification' => (int)$row['classification'],
1196
-				'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_NEXTCLOUD . '}deleted-at' => $row['deleted_at'] === null ? $row['deleted_at'] : (int)$row['deleted_at'],
1197
-			];
1198
-		}
1199
-		$stmt->closeCursor();
1200
-
1201
-		return $result;
1202
-	}
1203
-
1204
-	/**
1205
-	 * Returns information from a single calendar object, based on it's object
1206
-	 * uri.
1207
-	 *
1208
-	 * The object uri is only the basename, or filename and not a full path.
1209
-	 *
1210
-	 * The returned array must have the same keys as getCalendarObjects. The
1211
-	 * 'calendardata' object is required here though, while it's not required
1212
-	 * for getCalendarObjects.
1213
-	 *
1214
-	 * This method must return null if the object did not exist.
1215
-	 *
1216
-	 * @param mixed $calendarId
1217
-	 * @param string $objectUri
1218
-	 * @param int $calendarType
1219
-	 * @return array|null
1220
-	 */
1221
-	public function getCalendarObject($calendarId, $objectUri, int $calendarType = self::CALENDAR_TYPE_CALENDAR) {
1222
-		$key = $calendarId . '::' . $objectUri . '::' . $calendarType;
1223
-		if (isset($this->cachedObjects[$key])) {
1224
-			return $this->cachedObjects[$key];
1225
-		}
1226
-		$query = $this->db->getQueryBuilder();
1227
-		$query->select(['id', 'uri', 'uid', 'lastmodified', 'etag', 'calendarid', 'size', 'calendardata', 'componenttype', 'classification', 'deleted_at'])
1228
-			->from('calendarobjects')
1229
-			->where($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)))
1230
-			->andWhere($query->expr()->eq('uri', $query->createNamedParameter($objectUri)))
1231
-			->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter($calendarType)));
1232
-		$stmt = $query->executeQuery();
1233
-		$row = $stmt->fetch();
1234
-		$stmt->closeCursor();
1235
-
1236
-		if (!$row) {
1237
-			return null;
1238
-		}
1239
-
1240
-		$object = $this->rowToCalendarObject($row);
1241
-		$this->cachedObjects[$key] = $object;
1242
-		return $object;
1243
-	}
1244
-
1245
-	private function rowToCalendarObject(array $row): array {
1246
-		return [
1247
-			'id' => $row['id'],
1248
-			'uri' => $row['uri'],
1249
-			'uid' => $row['uid'],
1250
-			'lastmodified' => $row['lastmodified'],
1251
-			'etag' => '"' . $row['etag'] . '"',
1252
-			'calendarid' => $row['calendarid'],
1253
-			'size' => (int)$row['size'],
1254
-			'calendardata' => $this->readBlob($row['calendardata']),
1255
-			'component' => strtolower($row['componenttype']),
1256
-			'classification' => (int)$row['classification'],
1257
-			'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_NEXTCLOUD . '}deleted-at' => $row['deleted_at'] === null ? $row['deleted_at'] : (int)$row['deleted_at'],
1258
-		];
1259
-	}
1260
-
1261
-	/**
1262
-	 * Returns a list of calendar objects.
1263
-	 *
1264
-	 * This method should work identical to getCalendarObject, but instead
1265
-	 * return all the calendar objects in the list as an array.
1266
-	 *
1267
-	 * If the backend supports this, it may allow for some speed-ups.
1268
-	 *
1269
-	 * @param mixed $calendarId
1270
-	 * @param string[] $uris
1271
-	 * @param int $calendarType
1272
-	 * @return array
1273
-	 */
1274
-	public function getMultipleCalendarObjects($calendarId, array $uris, $calendarType = self::CALENDAR_TYPE_CALENDAR):array {
1275
-		if (empty($uris)) {
1276
-			return [];
1277
-		}
1278
-
1279
-		$chunks = array_chunk($uris, 100);
1280
-		$objects = [];
1281
-
1282
-		$query = $this->db->getQueryBuilder();
1283
-		$query->select(['id', 'uri', 'lastmodified', 'etag', 'calendarid', 'size', 'calendardata', 'componenttype', 'classification'])
1284
-			->from('calendarobjects')
1285
-			->where($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)))
1286
-			->andWhere($query->expr()->in('uri', $query->createParameter('uri')))
1287
-			->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter($calendarType)))
1288
-			->andWhere($query->expr()->isNull('deleted_at'));
1289
-
1290
-		foreach ($chunks as $uris) {
1291
-			$query->setParameter('uri', $uris, IQueryBuilder::PARAM_STR_ARRAY);
1292
-			$result = $query->executeQuery();
1293
-
1294
-			while ($row = $result->fetch()) {
1295
-				$objects[] = [
1296
-					'id' => $row['id'],
1297
-					'uri' => $row['uri'],
1298
-					'lastmodified' => $row['lastmodified'],
1299
-					'etag' => '"' . $row['etag'] . '"',
1300
-					'calendarid' => $row['calendarid'],
1301
-					'size' => (int)$row['size'],
1302
-					'calendardata' => $this->readBlob($row['calendardata']),
1303
-					'component' => strtolower($row['componenttype']),
1304
-					'classification' => (int)$row['classification']
1305
-				];
1306
-			}
1307
-			$result->closeCursor();
1308
-		}
1309
-
1310
-		return $objects;
1311
-	}
1312
-
1313
-	/**
1314
-	 * Creates a new calendar object.
1315
-	 *
1316
-	 * The object uri is only the basename, or filename and not a full path.
1317
-	 *
1318
-	 * It is possible return an etag from this function, which will be used in
1319
-	 * the response to this PUT request. Note that the ETag must be surrounded
1320
-	 * by double-quotes.
1321
-	 *
1322
-	 * However, you should only really return this ETag if you don't mangle the
1323
-	 * calendar-data. If the result of a subsequent GET to this object is not
1324
-	 * the exact same as this request body, you should omit the ETag.
1325
-	 *
1326
-	 * @param mixed $calendarId
1327
-	 * @param string $objectUri
1328
-	 * @param string $calendarData
1329
-	 * @param int $calendarType
1330
-	 * @return string
1331
-	 */
1332
-	public function createCalendarObject($calendarId, $objectUri, $calendarData, $calendarType = self::CALENDAR_TYPE_CALENDAR) {
1333
-		$this->cachedObjects = [];
1334
-		$extraData = $this->getDenormalizedData($calendarData);
1335
-
1336
-		return $this->atomic(function () use ($calendarId, $objectUri, $calendarData, $extraData, $calendarType) {
1337
-			// Try to detect duplicates
1338
-			$qb = $this->db->getQueryBuilder();
1339
-			$qb->select($qb->func()->count('*'))
1340
-				->from('calendarobjects')
1341
-				->where($qb->expr()->eq('calendarid', $qb->createNamedParameter($calendarId)))
1342
-				->andWhere($qb->expr()->eq('uid', $qb->createNamedParameter($extraData['uid'])))
1343
-				->andWhere($qb->expr()->eq('calendartype', $qb->createNamedParameter($calendarType)))
1344
-				->andWhere($qb->expr()->isNull('deleted_at'));
1345
-			$result = $qb->executeQuery();
1346
-			$count = (int)$result->fetchOne();
1347
-			$result->closeCursor();
1348
-
1349
-			if ($count !== 0) {
1350
-				throw new BadRequest('Calendar object with uid already exists in this calendar collection.');
1351
-			}
1352
-			// For a more specific error message we also try to explicitly look up the UID but as a deleted entry
1353
-			$qbDel = $this->db->getQueryBuilder();
1354
-			$qbDel->select('*')
1355
-				->from('calendarobjects')
1356
-				->where($qbDel->expr()->eq('calendarid', $qbDel->createNamedParameter($calendarId)))
1357
-				->andWhere($qbDel->expr()->eq('uid', $qbDel->createNamedParameter($extraData['uid'])))
1358
-				->andWhere($qbDel->expr()->eq('calendartype', $qbDel->createNamedParameter($calendarType)))
1359
-				->andWhere($qbDel->expr()->isNotNull('deleted_at'));
1360
-			$result = $qbDel->executeQuery();
1361
-			$found = $result->fetch();
1362
-			$result->closeCursor();
1363
-			if ($found !== false) {
1364
-				// the object existed previously but has been deleted
1365
-				// remove the trashbin entry and continue as if it was a new object
1366
-				$this->deleteCalendarObject($calendarId, $found['uri']);
1367
-			}
1368
-
1369
-			$query = $this->db->getQueryBuilder();
1370
-			$query->insert('calendarobjects')
1371
-				->values([
1372
-					'calendarid' => $query->createNamedParameter($calendarId),
1373
-					'uri' => $query->createNamedParameter($objectUri),
1374
-					'calendardata' => $query->createNamedParameter($calendarData, IQueryBuilder::PARAM_LOB),
1375
-					'lastmodified' => $query->createNamedParameter(time()),
1376
-					'etag' => $query->createNamedParameter($extraData['etag']),
1377
-					'size' => $query->createNamedParameter($extraData['size']),
1378
-					'componenttype' => $query->createNamedParameter($extraData['componentType']),
1379
-					'firstoccurence' => $query->createNamedParameter($extraData['firstOccurence']),
1380
-					'lastoccurence' => $query->createNamedParameter($extraData['lastOccurence']),
1381
-					'classification' => $query->createNamedParameter($extraData['classification']),
1382
-					'uid' => $query->createNamedParameter($extraData['uid']),
1383
-					'calendartype' => $query->createNamedParameter($calendarType),
1384
-				])
1385
-				->executeStatement();
1386
-
1387
-			$this->updateProperties($calendarId, $objectUri, $calendarData, $calendarType);
1388
-			$this->addChanges($calendarId, [$objectUri], 1, $calendarType);
1389
-
1390
-			$objectRow = $this->getCalendarObject($calendarId, $objectUri, $calendarType);
1391
-			assert($objectRow !== null);
1392
-
1393
-			if ($calendarType === self::CALENDAR_TYPE_CALENDAR) {
1394
-				$calendarRow = $this->getCalendarById($calendarId);
1395
-				$shares = $this->getShares($calendarId);
1396
-
1397
-				$this->dispatcher->dispatchTyped(new CalendarObjectCreatedEvent($calendarId, $calendarRow, $shares, $objectRow));
1398
-			} else {
1399
-				$subscriptionRow = $this->getSubscriptionById($calendarId);
1400
-
1401
-				$this->dispatcher->dispatchTyped(new CachedCalendarObjectCreatedEvent($calendarId, $subscriptionRow, [], $objectRow));
1402
-			}
1403
-
1404
-			return '"' . $extraData['etag'] . '"';
1405
-		}, $this->db);
1406
-	}
1407
-
1408
-	/**
1409
-	 * Updates an existing calendarobject, based on it's uri.
1410
-	 *
1411
-	 * The object uri is only the basename, or filename and not a full path.
1412
-	 *
1413
-	 * It is possible return an etag from this function, which will be used in
1414
-	 * the response to this PUT request. Note that the ETag must be surrounded
1415
-	 * by double-quotes.
1416
-	 *
1417
-	 * However, you should only really return this ETag if you don't mangle the
1418
-	 * calendar-data. If the result of a subsequent GET to this object is not
1419
-	 * the exact same as this request body, you should omit the ETag.
1420
-	 *
1421
-	 * @param mixed $calendarId
1422
-	 * @param string $objectUri
1423
-	 * @param string $calendarData
1424
-	 * @param int $calendarType
1425
-	 * @return string
1426
-	 */
1427
-	public function updateCalendarObject($calendarId, $objectUri, $calendarData, $calendarType = self::CALENDAR_TYPE_CALENDAR) {
1428
-		$this->cachedObjects = [];
1429
-		$extraData = $this->getDenormalizedData($calendarData);
1430
-
1431
-		return $this->atomic(function () use ($calendarId, $objectUri, $calendarData, $extraData, $calendarType) {
1432
-			$query = $this->db->getQueryBuilder();
1433
-			$query->update('calendarobjects')
1434
-				->set('calendardata', $query->createNamedParameter($calendarData, IQueryBuilder::PARAM_LOB))
1435
-				->set('lastmodified', $query->createNamedParameter(time()))
1436
-				->set('etag', $query->createNamedParameter($extraData['etag']))
1437
-				->set('size', $query->createNamedParameter($extraData['size']))
1438
-				->set('componenttype', $query->createNamedParameter($extraData['componentType']))
1439
-				->set('firstoccurence', $query->createNamedParameter($extraData['firstOccurence']))
1440
-				->set('lastoccurence', $query->createNamedParameter($extraData['lastOccurence']))
1441
-				->set('classification', $query->createNamedParameter($extraData['classification']))
1442
-				->set('uid', $query->createNamedParameter($extraData['uid']))
1443
-				->where($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)))
1444
-				->andWhere($query->expr()->eq('uri', $query->createNamedParameter($objectUri)))
1445
-				->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter($calendarType)))
1446
-				->executeStatement();
1447
-
1448
-			$this->updateProperties($calendarId, $objectUri, $calendarData, $calendarType);
1449
-			$this->addChanges($calendarId, [$objectUri], 2, $calendarType);
1450
-
1451
-			$objectRow = $this->getCalendarObject($calendarId, $objectUri, $calendarType);
1452
-			if (is_array($objectRow)) {
1453
-				if ($calendarType === self::CALENDAR_TYPE_CALENDAR) {
1454
-					$calendarRow = $this->getCalendarById($calendarId);
1455
-					$shares = $this->getShares($calendarId);
1456
-
1457
-					$this->dispatcher->dispatchTyped(new CalendarObjectUpdatedEvent($calendarId, $calendarRow, $shares, $objectRow));
1458
-				} else {
1459
-					$subscriptionRow = $this->getSubscriptionById($calendarId);
1460
-
1461
-					$this->dispatcher->dispatchTyped(new CachedCalendarObjectUpdatedEvent($calendarId, $subscriptionRow, [], $objectRow));
1462
-				}
1463
-			}
1464
-
1465
-			return '"' . $extraData['etag'] . '"';
1466
-		}, $this->db);
1467
-	}
1468
-
1469
-	/**
1470
-	 * Moves a calendar object from calendar to calendar.
1471
-	 *
1472
-	 * @param string $sourcePrincipalUri
1473
-	 * @param int $sourceObjectId
1474
-	 * @param string $targetPrincipalUri
1475
-	 * @param int $targetCalendarId
1476
-	 * @param string $tragetObjectUri
1477
-	 * @param int $calendarType
1478
-	 * @return bool
1479
-	 * @throws Exception
1480
-	 */
1481
-	public function moveCalendarObject(string $sourcePrincipalUri, int $sourceObjectId, string $targetPrincipalUri, int $targetCalendarId, string $tragetObjectUri, int $calendarType = self::CALENDAR_TYPE_CALENDAR): bool {
1482
-		$this->cachedObjects = [];
1483
-		return $this->atomic(function () use ($sourcePrincipalUri, $sourceObjectId, $targetPrincipalUri, $targetCalendarId, $tragetObjectUri, $calendarType) {
1484
-			$object = $this->getCalendarObjectById($sourcePrincipalUri, $sourceObjectId);
1485
-			if (empty($object)) {
1486
-				return false;
1487
-			}
1488
-
1489
-			$sourceCalendarId = $object['calendarid'];
1490
-			$sourceObjectUri = $object['uri'];
1491
-
1492
-			$query = $this->db->getQueryBuilder();
1493
-			$query->update('calendarobjects')
1494
-				->set('calendarid', $query->createNamedParameter($targetCalendarId, IQueryBuilder::PARAM_INT))
1495
-				->set('uri', $query->createNamedParameter($tragetObjectUri, IQueryBuilder::PARAM_STR))
1496
-				->where($query->expr()->eq('id', $query->createNamedParameter($sourceObjectId, IQueryBuilder::PARAM_INT), IQueryBuilder::PARAM_INT))
1497
-				->executeStatement();
1498
-
1499
-			$this->purgeProperties($sourceCalendarId, $sourceObjectId);
1500
-			$this->updateProperties($targetCalendarId, $tragetObjectUri, $object['calendardata'], $calendarType);
1501
-
1502
-			$this->addChanges($sourceCalendarId, [$sourceObjectUri], 3, $calendarType);
1503
-			$this->addChanges($targetCalendarId, [$tragetObjectUri], 1, $calendarType);
1504
-
1505
-			$object = $this->getCalendarObjectById($targetPrincipalUri, $sourceObjectId);
1506
-			// Calendar Object wasn't found - possibly because it was deleted in the meantime by a different client
1507
-			if (empty($object)) {
1508
-				return false;
1509
-			}
1510
-
1511
-			$targetCalendarRow = $this->getCalendarById($targetCalendarId);
1512
-			// the calendar this event is being moved to does not exist any longer
1513
-			if (empty($targetCalendarRow)) {
1514
-				return false;
1515
-			}
1516
-
1517
-			if ($calendarType === self::CALENDAR_TYPE_CALENDAR) {
1518
-				$sourceShares = $this->getShares($sourceCalendarId);
1519
-				$targetShares = $this->getShares($targetCalendarId);
1520
-				$sourceCalendarRow = $this->getCalendarById($sourceCalendarId);
1521
-				$this->dispatcher->dispatchTyped(new CalendarObjectMovedEvent($sourceCalendarId, $sourceCalendarRow, $targetCalendarId, $targetCalendarRow, $sourceShares, $targetShares, $object));
1522
-			}
1523
-			return true;
1524
-		}, $this->db);
1525
-	}
1526
-
1527
-
1528
-	/**
1529
-	 * @param int $calendarObjectId
1530
-	 * @param int $classification
1531
-	 */
1532
-	public function setClassification($calendarObjectId, $classification) {
1533
-		$this->cachedObjects = [];
1534
-		if (!in_array($classification, [
1535
-			self::CLASSIFICATION_PUBLIC, self::CLASSIFICATION_PRIVATE, self::CLASSIFICATION_CONFIDENTIAL
1536
-		])) {
1537
-			throw new \InvalidArgumentException();
1538
-		}
1539
-		$query = $this->db->getQueryBuilder();
1540
-		$query->update('calendarobjects')
1541
-			->set('classification', $query->createNamedParameter($classification))
1542
-			->where($query->expr()->eq('id', $query->createNamedParameter($calendarObjectId)))
1543
-			->executeStatement();
1544
-	}
1545
-
1546
-	/**
1547
-	 * Deletes an existing calendar object.
1548
-	 *
1549
-	 * The object uri is only the basename, or filename and not a full path.
1550
-	 *
1551
-	 * @param mixed $calendarId
1552
-	 * @param string $objectUri
1553
-	 * @param int $calendarType
1554
-	 * @param bool $forceDeletePermanently
1555
-	 * @return void
1556
-	 */
1557
-	public function deleteCalendarObject($calendarId, $objectUri, $calendarType = self::CALENDAR_TYPE_CALENDAR, bool $forceDeletePermanently = false) {
1558
-		$this->cachedObjects = [];
1559
-		$this->atomic(function () use ($calendarId, $objectUri, $calendarType, $forceDeletePermanently): void {
1560
-			$data = $this->getCalendarObject($calendarId, $objectUri, $calendarType);
1561
-
1562
-			if ($data === null) {
1563
-				// Nothing to delete
1564
-				return;
1565
-			}
1566
-
1567
-			if ($forceDeletePermanently || $this->config->getAppValue(Application::APP_ID, RetentionService::RETENTION_CONFIG_KEY) === '0') {
1568
-				$stmt = $this->db->prepare('DELETE FROM `*PREFIX*calendarobjects` WHERE `calendarid` = ? AND `uri` = ? AND `calendartype` = ?');
1569
-				$stmt->execute([$calendarId, $objectUri, $calendarType]);
1570
-
1571
-				$this->purgeProperties($calendarId, $data['id']);
1572
-
1573
-				$this->purgeObjectInvitations($data['uid']);
1574
-
1575
-				if ($calendarType === self::CALENDAR_TYPE_CALENDAR) {
1576
-					$calendarRow = $this->getCalendarById($calendarId);
1577
-					$shares = $this->getShares($calendarId);
1578
-
1579
-					$this->dispatcher->dispatchTyped(new CalendarObjectDeletedEvent($calendarId, $calendarRow, $shares, $data));
1580
-				} else {
1581
-					$subscriptionRow = $this->getSubscriptionById($calendarId);
1582
-
1583
-					$this->dispatcher->dispatchTyped(new CachedCalendarObjectDeletedEvent($calendarId, $subscriptionRow, [], $data));
1584
-				}
1585
-			} else {
1586
-				$pathInfo = pathinfo($data['uri']);
1587
-				if (!empty($pathInfo['extension'])) {
1588
-					// Append a suffix to "free" the old URI for recreation
1589
-					$newUri = sprintf(
1590
-						'%s-deleted.%s',
1591
-						$pathInfo['filename'],
1592
-						$pathInfo['extension']
1593
-					);
1594
-				} else {
1595
-					$newUri = sprintf(
1596
-						'%s-deleted',
1597
-						$pathInfo['filename']
1598
-					);
1599
-				}
1600
-
1601
-				// Try to detect conflicts before the DB does
1602
-				// As unlikely as it seems, this can happen when the user imports, then deletes, imports and deletes again
1603
-				$newObject = $this->getCalendarObject($calendarId, $newUri, $calendarType);
1604
-				if ($newObject !== null) {
1605
-					throw new Forbidden("A calendar object with URI $newUri already exists in calendar $calendarId, therefore this object can't be moved into the trashbin");
1606
-				}
1607
-
1608
-				$qb = $this->db->getQueryBuilder();
1609
-				$markObjectDeletedQuery = $qb->update('calendarobjects')
1610
-					->set('deleted_at', $qb->createNamedParameter(time(), IQueryBuilder::PARAM_INT))
1611
-					->set('uri', $qb->createNamedParameter($newUri))
1612
-					->where(
1613
-						$qb->expr()->eq('calendarid', $qb->createNamedParameter($calendarId)),
1614
-						$qb->expr()->eq('calendartype', $qb->createNamedParameter($calendarType, IQueryBuilder::PARAM_INT), IQueryBuilder::PARAM_INT),
1615
-						$qb->expr()->eq('uri', $qb->createNamedParameter($objectUri))
1616
-					);
1617
-				$markObjectDeletedQuery->executeStatement();
1618
-
1619
-				$calendarData = $this->getCalendarById($calendarId);
1620
-				if ($calendarData !== null) {
1621
-					$this->dispatcher->dispatchTyped(
1622
-						new CalendarObjectMovedToTrashEvent(
1623
-							$calendarId,
1624
-							$calendarData,
1625
-							$this->getShares($calendarId),
1626
-							$data
1627
-						)
1628
-					);
1629
-				}
1630
-			}
1631
-
1632
-			$this->addChanges($calendarId, [$objectUri], 3, $calendarType);
1633
-		}, $this->db);
1634
-	}
1635
-
1636
-	/**
1637
-	 * @param mixed $objectData
1638
-	 *
1639
-	 * @throws Forbidden
1640
-	 */
1641
-	public function restoreCalendarObject(array $objectData): void {
1642
-		$this->cachedObjects = [];
1643
-		$this->atomic(function () use ($objectData): void {
1644
-			$id = (int)$objectData['id'];
1645
-			$restoreUri = str_replace('-deleted.ics', '.ics', $objectData['uri']);
1646
-			$targetObject = $this->getCalendarObject(
1647
-				$objectData['calendarid'],
1648
-				$restoreUri
1649
-			);
1650
-			if ($targetObject !== null) {
1651
-				throw new Forbidden("Can not restore calendar $id because a calendar object with the URI $restoreUri already exists");
1652
-			}
1653
-
1654
-			$qb = $this->db->getQueryBuilder();
1655
-			$update = $qb->update('calendarobjects')
1656
-				->set('uri', $qb->createNamedParameter($restoreUri))
1657
-				->set('deleted_at', $qb->createNamedParameter(null))
1658
-				->where($qb->expr()->eq('id', $qb->createNamedParameter($id, IQueryBuilder::PARAM_INT), IQueryBuilder::PARAM_INT));
1659
-			$update->executeStatement();
1660
-
1661
-			// Make sure this change is tracked in the changes table
1662
-			$qb2 = $this->db->getQueryBuilder();
1663
-			$selectObject = $qb2->select('calendardata', 'uri', 'calendarid', 'calendartype')
1664
-				->selectAlias('componenttype', 'component')
1665
-				->from('calendarobjects')
1666
-				->where($qb2->expr()->eq('id', $qb2->createNamedParameter($id, IQueryBuilder::PARAM_INT), IQueryBuilder::PARAM_INT));
1667
-			$result = $selectObject->executeQuery();
1668
-			$row = $result->fetch();
1669
-			$result->closeCursor();
1670
-			if ($row === false) {
1671
-				// Welp, this should possibly not have happened, but let's ignore
1672
-				return;
1673
-			}
1674
-			$this->addChanges($row['calendarid'], [$row['uri']], 1, (int)$row['calendartype']);
1675
-
1676
-			$calendarRow = $this->getCalendarById((int)$row['calendarid']);
1677
-			if ($calendarRow === null) {
1678
-				throw new RuntimeException('Calendar object data that was just written can\'t be read back. Check your database configuration.');
1679
-			}
1680
-			$this->dispatcher->dispatchTyped(
1681
-				new CalendarObjectRestoredEvent(
1682
-					(int)$objectData['calendarid'],
1683
-					$calendarRow,
1684
-					$this->getShares((int)$row['calendarid']),
1685
-					$row
1686
-				)
1687
-			);
1688
-		}, $this->db);
1689
-	}
1690
-
1691
-	/**
1692
-	 * Performs a calendar-query on the contents of this calendar.
1693
-	 *
1694
-	 * The calendar-query is defined in RFC4791 : CalDAV. Using the
1695
-	 * calendar-query it is possible for a client to request a specific set of
1696
-	 * object, based on contents of iCalendar properties, date-ranges and
1697
-	 * iCalendar component types (VTODO, VEVENT).
1698
-	 *
1699
-	 * This method should just return a list of (relative) urls that match this
1700
-	 * query.
1701
-	 *
1702
-	 * The list of filters are specified as an array. The exact array is
1703
-	 * documented by Sabre\CalDAV\CalendarQueryParser.
1704
-	 *
1705
-	 * Note that it is extremely likely that getCalendarObject for every path
1706
-	 * returned from this method will be called almost immediately after. You
1707
-	 * may want to anticipate this to speed up these requests.
1708
-	 *
1709
-	 * This method provides a default implementation, which parses *all* the
1710
-	 * iCalendar objects in the specified calendar.
1711
-	 *
1712
-	 * This default may well be good enough for personal use, and calendars
1713
-	 * that aren't very large. But if you anticipate high usage, big calendars
1714
-	 * or high loads, you are strongly advised to optimize certain paths.
1715
-	 *
1716
-	 * The best way to do so is override this method and to optimize
1717
-	 * specifically for 'common filters'.
1718
-	 *
1719
-	 * Requests that are extremely common are:
1720
-	 *   * requests for just VEVENTS
1721
-	 *   * requests for just VTODO
1722
-	 *   * requests with a time-range-filter on either VEVENT or VTODO.
1723
-	 *
1724
-	 * ..and combinations of these requests. It may not be worth it to try to
1725
-	 * handle every possible situation and just rely on the (relatively
1726
-	 * easy to use) CalendarQueryValidator to handle the rest.
1727
-	 *
1728
-	 * Note that especially time-range-filters may be difficult to parse. A
1729
-	 * time-range filter specified on a VEVENT must for instance also handle
1730
-	 * recurrence rules correctly.
1731
-	 * A good example of how to interpret all these filters can also simply
1732
-	 * be found in Sabre\CalDAV\CalendarQueryFilter. This class is as correct
1733
-	 * as possible, so it gives you a good idea on what type of stuff you need
1734
-	 * to think of.
1735
-	 *
1736
-	 * @param mixed $calendarId
1737
-	 * @param array $filters
1738
-	 * @param int $calendarType
1739
-	 * @return array
1740
-	 */
1741
-	public function calendarQuery($calendarId, array $filters, $calendarType = self::CALENDAR_TYPE_CALENDAR):array {
1742
-		$componentType = null;
1743
-		$requirePostFilter = true;
1744
-		$timeRange = null;
1745
-
1746
-		// if no filters were specified, we don't need to filter after a query
1747
-		if (!$filters['prop-filters'] && !$filters['comp-filters']) {
1748
-			$requirePostFilter = false;
1749
-		}
1750
-
1751
-		// Figuring out if there's a component filter
1752
-		if (count($filters['comp-filters']) > 0 && !$filters['comp-filters'][0]['is-not-defined']) {
1753
-			$componentType = $filters['comp-filters'][0]['name'];
1754
-
1755
-			// Checking if we need post-filters
1756
-			if (!$filters['prop-filters'] && !$filters['comp-filters'][0]['comp-filters'] && !$filters['comp-filters'][0]['time-range'] && !$filters['comp-filters'][0]['prop-filters']) {
1757
-				$requirePostFilter = false;
1758
-			}
1759
-			// There was a time-range filter
1760
-			if ($componentType === 'VEVENT' && isset($filters['comp-filters'][0]['time-range']) && is_array($filters['comp-filters'][0]['time-range'])) {
1761
-				$timeRange = $filters['comp-filters'][0]['time-range'];
1762
-
1763
-				// If start time OR the end time is not specified, we can do a
1764
-				// 100% accurate mysql query.
1765
-				if (!$filters['prop-filters'] && !$filters['comp-filters'][0]['comp-filters'] && !$filters['comp-filters'][0]['prop-filters'] && (!$timeRange['start'] || !$timeRange['end'])) {
1766
-					$requirePostFilter = false;
1767
-				}
1768
-			}
1769
-		}
1770
-		$query = $this->db->getQueryBuilder();
1771
-		$query->select(['id', 'uri', 'uid', 'lastmodified', 'etag', 'calendarid', 'size', 'calendardata', 'componenttype', 'classification', 'deleted_at'])
1772
-			->from('calendarobjects')
1773
-			->where($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)))
1774
-			->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter($calendarType)))
1775
-			->andWhere($query->expr()->isNull('deleted_at'));
1776
-
1777
-		if ($componentType) {
1778
-			$query->andWhere($query->expr()->eq('componenttype', $query->createNamedParameter($componentType)));
1779
-		}
1780
-
1781
-		if ($timeRange && $timeRange['start']) {
1782
-			$query->andWhere($query->expr()->gt('lastoccurence', $query->createNamedParameter($timeRange['start']->getTimeStamp())));
1783
-		}
1784
-		if ($timeRange && $timeRange['end']) {
1785
-			$query->andWhere($query->expr()->lt('firstoccurence', $query->createNamedParameter($timeRange['end']->getTimeStamp())));
1786
-		}
1787
-
1788
-		$stmt = $query->executeQuery();
1789
-
1790
-		$result = [];
1791
-		while ($row = $stmt->fetch()) {
1792
-			// if we leave it as a blob we can't read it both from the post filter and the rowToCalendarObject
1793
-			if (isset($row['calendardata'])) {
1794
-				$row['calendardata'] = $this->readBlob($row['calendardata']);
1795
-			}
1796
-
1797
-			if ($requirePostFilter) {
1798
-				// validateFilterForObject will parse the calendar data
1799
-				// catch parsing errors
1800
-				try {
1801
-					$matches = $this->validateFilterForObject($row, $filters);
1802
-				} catch (ParseException $ex) {
1803
-					$this->logger->error('Caught parsing exception for calendar data. This usually indicates invalid calendar data. calendar-id:' . $calendarId . ' uri:' . $row['uri'], [
1804
-						'app' => 'dav',
1805
-						'exception' => $ex,
1806
-					]);
1807
-					continue;
1808
-				} catch (InvalidDataException $ex) {
1809
-					$this->logger->error('Caught invalid data exception for calendar data. This usually indicates invalid calendar data. calendar-id:' . $calendarId . ' uri:' . $row['uri'], [
1810
-						'app' => 'dav',
1811
-						'exception' => $ex,
1812
-					]);
1813
-					continue;
1814
-				} catch (MaxInstancesExceededException $ex) {
1815
-					$this->logger->warning('Caught max instances exceeded exception for calendar data. This usually indicates too much recurring (more than 3500) event in calendar data. Object uri: ' . $row['uri'], [
1816
-						'app' => 'dav',
1817
-						'exception' => $ex,
1818
-					]);
1819
-					continue;
1820
-				}
1821
-
1822
-				if (!$matches) {
1823
-					continue;
1824
-				}
1825
-			}
1826
-			$result[] = $row['uri'];
1827
-			$key = $calendarId . '::' . $row['uri'] . '::' . $calendarType;
1828
-			$this->cachedObjects[$key] = $this->rowToCalendarObject($row);
1829
-		}
1830
-
1831
-		return $result;
1832
-	}
1833
-
1834
-	/**
1835
-	 * custom Nextcloud search extension for CalDAV
1836
-	 *
1837
-	 * TODO - this should optionally cover cached calendar objects as well
1838
-	 *
1839
-	 * @param string $principalUri
1840
-	 * @param array $filters
1841
-	 * @param integer|null $limit
1842
-	 * @param integer|null $offset
1843
-	 * @return array
1844
-	 */
1845
-	public function calendarSearch($principalUri, array $filters, $limit = null, $offset = null) {
1846
-		return $this->atomic(function () use ($principalUri, $filters, $limit, $offset) {
1847
-			$calendars = $this->getCalendarsForUser($principalUri);
1848
-			$ownCalendars = [];
1849
-			$sharedCalendars = [];
1850
-
1851
-			$uriMapper = [];
1852
-
1853
-			foreach ($calendars as $calendar) {
1854
-				if ($calendar['{http://owncloud.org/ns}owner-principal'] === $principalUri) {
1855
-					$ownCalendars[] = $calendar['id'];
1856
-				} else {
1857
-					$sharedCalendars[] = $calendar['id'];
1858
-				}
1859
-				$uriMapper[$calendar['id']] = $calendar['uri'];
1860
-			}
1861
-			if (count($ownCalendars) === 0 && count($sharedCalendars) === 0) {
1862
-				return [];
1863
-			}
1864
-
1865
-			$query = $this->db->getQueryBuilder();
1866
-			// Calendar id expressions
1867
-			$calendarExpressions = [];
1868
-			foreach ($ownCalendars as $id) {
1869
-				$calendarExpressions[] = $query->expr()->andX(
1870
-					$query->expr()->eq('c.calendarid',
1871
-						$query->createNamedParameter($id)),
1872
-					$query->expr()->eq('c.calendartype',
1873
-						$query->createNamedParameter(self::CALENDAR_TYPE_CALENDAR)));
1874
-			}
1875
-			foreach ($sharedCalendars as $id) {
1876
-				$calendarExpressions[] = $query->expr()->andX(
1877
-					$query->expr()->eq('c.calendarid',
1878
-						$query->createNamedParameter($id)),
1879
-					$query->expr()->eq('c.classification',
1880
-						$query->createNamedParameter(self::CLASSIFICATION_PUBLIC)),
1881
-					$query->expr()->eq('c.calendartype',
1882
-						$query->createNamedParameter(self::CALENDAR_TYPE_CALENDAR)));
1883
-			}
1884
-
1885
-			if (count($calendarExpressions) === 1) {
1886
-				$calExpr = $calendarExpressions[0];
1887
-			} else {
1888
-				$calExpr = call_user_func_array([$query->expr(), 'orX'], $calendarExpressions);
1889
-			}
1890
-
1891
-			// Component expressions
1892
-			$compExpressions = [];
1893
-			foreach ($filters['comps'] as $comp) {
1894
-				$compExpressions[] = $query->expr()
1895
-					->eq('c.componenttype', $query->createNamedParameter($comp));
1896
-			}
1897
-
1898
-			if (count($compExpressions) === 1) {
1899
-				$compExpr = $compExpressions[0];
1900
-			} else {
1901
-				$compExpr = call_user_func_array([$query->expr(), 'orX'], $compExpressions);
1902
-			}
1903
-
1904
-			if (!isset($filters['props'])) {
1905
-				$filters['props'] = [];
1906
-			}
1907
-			if (!isset($filters['params'])) {
1908
-				$filters['params'] = [];
1909
-			}
1910
-
1911
-			$propParamExpressions = [];
1912
-			foreach ($filters['props'] as $prop) {
1913
-				$propParamExpressions[] = $query->expr()->andX(
1914
-					$query->expr()->eq('i.name', $query->createNamedParameter($prop)),
1915
-					$query->expr()->isNull('i.parameter')
1916
-				);
1917
-			}
1918
-			foreach ($filters['params'] as $param) {
1919
-				$propParamExpressions[] = $query->expr()->andX(
1920
-					$query->expr()->eq('i.name', $query->createNamedParameter($param['property'])),
1921
-					$query->expr()->eq('i.parameter', $query->createNamedParameter($param['parameter']))
1922
-				);
1923
-			}
1924
-
1925
-			if (count($propParamExpressions) === 1) {
1926
-				$propParamExpr = $propParamExpressions[0];
1927
-			} else {
1928
-				$propParamExpr = call_user_func_array([$query->expr(), 'orX'], $propParamExpressions);
1929
-			}
1930
-
1931
-			$query->select(['c.calendarid', 'c.uri'])
1932
-				->from($this->dbObjectPropertiesTable, 'i')
1933
-				->join('i', 'calendarobjects', 'c', $query->expr()->eq('i.objectid', 'c.id'))
1934
-				->where($calExpr)
1935
-				->andWhere($compExpr)
1936
-				->andWhere($propParamExpr)
1937
-				->andWhere($query->expr()->iLike('i.value',
1938
-					$query->createNamedParameter('%' . $this->db->escapeLikeParameter($filters['search-term']) . '%')))
1939
-				->andWhere($query->expr()->isNull('deleted_at'));
1940
-
1941
-			if ($offset) {
1942
-				$query->setFirstResult($offset);
1943
-			}
1944
-			if ($limit) {
1945
-				$query->setMaxResults($limit);
1946
-			}
1947
-
1948
-			$stmt = $query->executeQuery();
1949
-
1950
-			$result = [];
1951
-			while ($row = $stmt->fetch()) {
1952
-				$path = $uriMapper[$row['calendarid']] . '/' . $row['uri'];
1953
-				if (!in_array($path, $result)) {
1954
-					$result[] = $path;
1955
-				}
1956
-			}
1957
-
1958
-			return $result;
1959
-		}, $this->db);
1960
-	}
1961
-
1962
-	/**
1963
-	 * used for Nextcloud's calendar API
1964
-	 *
1965
-	 * @param array $calendarInfo
1966
-	 * @param string $pattern
1967
-	 * @param array $searchProperties
1968
-	 * @param array $options
1969
-	 * @param integer|null $limit
1970
-	 * @param integer|null $offset
1971
-	 *
1972
-	 * @return array
1973
-	 */
1974
-	public function search(
1975
-		array $calendarInfo,
1976
-		$pattern,
1977
-		array $searchProperties,
1978
-		array $options,
1979
-		$limit,
1980
-		$offset,
1981
-	) {
1982
-		$outerQuery = $this->db->getQueryBuilder();
1983
-		$innerQuery = $this->db->getQueryBuilder();
1984
-
1985
-		if (isset($calendarInfo['source'])) {
1986
-			$calendarType = self::CALENDAR_TYPE_SUBSCRIPTION;
1987
-		} else {
1988
-			$calendarType = self::CALENDAR_TYPE_CALENDAR;
1989
-		}
1990
-
1991
-		$innerQuery->selectDistinct('op.objectid')
1992
-			->from($this->dbObjectPropertiesTable, 'op')
1993
-			->andWhere($innerQuery->expr()->eq('op.calendarid',
1994
-				$outerQuery->createNamedParameter($calendarInfo['id'])))
1995
-			->andWhere($innerQuery->expr()->eq('op.calendartype',
1996
-				$outerQuery->createNamedParameter($calendarType)));
1997
-
1998
-		$outerQuery->select('c.id', 'c.calendardata', 'c.componenttype', 'c.uid', 'c.uri')
1999
-			->from('calendarobjects', 'c')
2000
-			->where($outerQuery->expr()->isNull('deleted_at'));
2001
-
2002
-		// only return public items for shared calendars for now
2003
-		if (isset($calendarInfo['{http://owncloud.org/ns}owner-principal']) === false || $calendarInfo['principaluri'] !== $calendarInfo['{http://owncloud.org/ns}owner-principal']) {
2004
-			$outerQuery->andWhere($outerQuery->expr()->eq('c.classification',
2005
-				$outerQuery->createNamedParameter(self::CLASSIFICATION_PUBLIC)));
2006
-		}
2007
-
2008
-		if (!empty($searchProperties)) {
2009
-			$or = [];
2010
-			foreach ($searchProperties as $searchProperty) {
2011
-				$or[] = $innerQuery->expr()->eq('op.name',
2012
-					$outerQuery->createNamedParameter($searchProperty));
2013
-			}
2014
-			$innerQuery->andWhere($innerQuery->expr()->orX(...$or));
2015
-		}
2016
-
2017
-		if ($pattern !== '') {
2018
-			$innerQuery->andWhere($innerQuery->expr()->iLike('op.value',
2019
-				$outerQuery->createNamedParameter('%' .
2020
-					$this->db->escapeLikeParameter($pattern) . '%')));
2021
-		}
2022
-
2023
-		$start = null;
2024
-		$end = null;
2025
-
2026
-		$hasLimit = is_int($limit);
2027
-		$hasTimeRange = false;
2028
-
2029
-		if (isset($options['timerange']['start']) && $options['timerange']['start'] instanceof DateTimeInterface) {
2030
-			/** @var DateTimeInterface $start */
2031
-			$start = $options['timerange']['start'];
2032
-			$outerQuery->andWhere(
2033
-				$outerQuery->expr()->gt(
2034
-					'lastoccurence',
2035
-					$outerQuery->createNamedParameter($start->getTimestamp())
2036
-				)
2037
-			);
2038
-			$hasTimeRange = true;
2039
-		}
2040
-
2041
-		if (isset($options['timerange']['end']) && $options['timerange']['end'] instanceof DateTimeInterface) {
2042
-			/** @var DateTimeInterface $end */
2043
-			$end = $options['timerange']['end'];
2044
-			$outerQuery->andWhere(
2045
-				$outerQuery->expr()->lt(
2046
-					'firstoccurence',
2047
-					$outerQuery->createNamedParameter($end->getTimestamp())
2048
-				)
2049
-			);
2050
-			$hasTimeRange = true;
2051
-		}
2052
-
2053
-		if (isset($options['uid'])) {
2054
-			$outerQuery->andWhere($outerQuery->expr()->eq('uid', $outerQuery->createNamedParameter($options['uid'])));
2055
-		}
2056
-
2057
-		if (!empty($options['types'])) {
2058
-			$or = [];
2059
-			foreach ($options['types'] as $type) {
2060
-				$or[] = $outerQuery->expr()->eq('componenttype',
2061
-					$outerQuery->createNamedParameter($type));
2062
-			}
2063
-			$outerQuery->andWhere($outerQuery->expr()->orX(...$or));
2064
-		}
2065
-
2066
-		$outerQuery->andWhere($outerQuery->expr()->in('c.id', $outerQuery->createFunction($innerQuery->getSQL())));
2067
-
2068
-		// Without explicit order by its undefined in which order the SQL server returns the events.
2069
-		// For the pagination with hasLimit and hasTimeRange, a stable ordering is helpful.
2070
-		$outerQuery->addOrderBy('id');
2071
-
2072
-		$offset = (int)$offset;
2073
-		$outerQuery->setFirstResult($offset);
2074
-
2075
-		$calendarObjects = [];
2076
-
2077
-		if ($hasLimit && $hasTimeRange) {
2078
-			/**
2079
-			 * Event recurrences are evaluated at runtime because the database only knows the first and last occurrence.
2080
-			 *
2081
-			 * Given, a user created 8 events with a yearly reoccurrence and two for events tomorrow.
2082
-			 * The upcoming event widget asks the CalDAV backend for 7 events within the next 14 days.
2083
-			 *
2084
-			 * If limit 7 is applied to the SQL query, we find the 7 events with a yearly reoccurrence
2085
-			 * and discard the events after evaluating the reoccurrence rules because they are not due within
2086
-			 * the next 14 days and end up with an empty result even if there are two events to show.
2087
-			 *
2088
-			 * The workaround for search requests with a limit and time range is asking for more row than requested
2089
-			 * and retrying if we have not reached the limit.
2090
-			 *
2091
-			 * 25 rows and 3 retries is entirely arbitrary.
2092
-			 */
2093
-			$maxResults = (int)max($limit, 25);
2094
-			$outerQuery->setMaxResults($maxResults);
2095
-
2096
-			for ($attempt = $objectsCount = 0; $attempt < 3 && $objectsCount < $limit; $attempt++) {
2097
-				$objectsCount = array_push($calendarObjects, ...$this->searchCalendarObjects($outerQuery, $start, $end));
2098
-				$outerQuery->setFirstResult($offset += $maxResults);
2099
-			}
2100
-
2101
-			$calendarObjects = array_slice($calendarObjects, 0, $limit, false);
2102
-		} else {
2103
-			$outerQuery->setMaxResults($limit);
2104
-			$calendarObjects = $this->searchCalendarObjects($outerQuery, $start, $end);
2105
-		}
2106
-
2107
-		$calendarObjects = array_map(function ($o) use ($options) {
2108
-			$calendarData = Reader::read($o['calendardata']);
2109
-
2110
-			// Expand recurrences if an explicit time range is requested
2111
-			if ($calendarData instanceof VCalendar
2112
-				&& isset($options['timerange']['start'], $options['timerange']['end'])) {
2113
-				$calendarData = $calendarData->expand(
2114
-					$options['timerange']['start'],
2115
-					$options['timerange']['end'],
2116
-				);
2117
-			}
2118
-
2119
-			$comps = $calendarData->getComponents();
2120
-			$objects = [];
2121
-			$timezones = [];
2122
-			foreach ($comps as $comp) {
2123
-				if ($comp instanceof VTimeZone) {
2124
-					$timezones[] = $comp;
2125
-				} else {
2126
-					$objects[] = $comp;
2127
-				}
2128
-			}
2129
-
2130
-			return [
2131
-				'id' => $o['id'],
2132
-				'type' => $o['componenttype'],
2133
-				'uid' => $o['uid'],
2134
-				'uri' => $o['uri'],
2135
-				'objects' => array_map(function ($c) {
2136
-					return $this->transformSearchData($c);
2137
-				}, $objects),
2138
-				'timezones' => array_map(function ($c) {
2139
-					return $this->transformSearchData($c);
2140
-				}, $timezones),
2141
-			];
2142
-		}, $calendarObjects);
2143
-
2144
-		usort($calendarObjects, function (array $a, array $b) {
2145
-			/** @var DateTimeImmutable $startA */
2146
-			$startA = $a['objects'][0]['DTSTART'][0] ?? new DateTimeImmutable(self::MAX_DATE);
2147
-			/** @var DateTimeImmutable $startB */
2148
-			$startB = $b['objects'][0]['DTSTART'][0] ?? new DateTimeImmutable(self::MAX_DATE);
2149
-
2150
-			return $startA->getTimestamp() <=> $startB->getTimestamp();
2151
-		});
2152
-
2153
-		return $calendarObjects;
2154
-	}
2155
-
2156
-	private function searchCalendarObjects(IQueryBuilder $query, ?DateTimeInterface $start, ?DateTimeInterface $end): array {
2157
-		$calendarObjects = [];
2158
-		$filterByTimeRange = ($start instanceof DateTimeInterface) || ($end instanceof DateTimeInterface);
2159
-
2160
-		$result = $query->executeQuery();
2161
-
2162
-		while (($row = $result->fetch()) !== false) {
2163
-			if ($filterByTimeRange === false) {
2164
-				// No filter required
2165
-				$calendarObjects[] = $row;
2166
-				continue;
2167
-			}
2168
-
2169
-			try {
2170
-				$isValid = $this->validateFilterForObject($row, [
2171
-					'name' => 'VCALENDAR',
2172
-					'comp-filters' => [
2173
-						[
2174
-							'name' => 'VEVENT',
2175
-							'comp-filters' => [],
2176
-							'prop-filters' => [],
2177
-							'is-not-defined' => false,
2178
-							'time-range' => [
2179
-								'start' => $start,
2180
-								'end' => $end,
2181
-							],
2182
-						],
2183
-					],
2184
-					'prop-filters' => [],
2185
-					'is-not-defined' => false,
2186
-					'time-range' => null,
2187
-				]);
2188
-			} catch (MaxInstancesExceededException $ex) {
2189
-				$this->logger->warning('Caught max instances exceeded exception for calendar data. This usually indicates too much recurring (more than 3500) event in calendar data. Object uri: ' . $row['uri'], [
2190
-					'app' => 'dav',
2191
-					'exception' => $ex,
2192
-				]);
2193
-				continue;
2194
-			}
2195
-
2196
-			if (is_resource($row['calendardata'])) {
2197
-				// Put the stream back to the beginning so it can be read another time
2198
-				rewind($row['calendardata']);
2199
-			}
2200
-
2201
-			if ($isValid) {
2202
-				$calendarObjects[] = $row;
2203
-			}
2204
-		}
2205
-
2206
-		$result->closeCursor();
2207
-
2208
-		return $calendarObjects;
2209
-	}
2210
-
2211
-	/**
2212
-	 * @param Component $comp
2213
-	 * @return array
2214
-	 */
2215
-	private function transformSearchData(Component $comp) {
2216
-		$data = [];
2217
-		/** @var Component[] $subComponents */
2218
-		$subComponents = $comp->getComponents();
2219
-		/** @var Property[] $properties */
2220
-		$properties = array_filter($comp->children(), function ($c) {
2221
-			return $c instanceof Property;
2222
-		});
2223
-		$validationRules = $comp->getValidationRules();
2224
-
2225
-		foreach ($subComponents as $subComponent) {
2226
-			$name = $subComponent->name;
2227
-			if (!isset($data[$name])) {
2228
-				$data[$name] = [];
2229
-			}
2230
-			$data[$name][] = $this->transformSearchData($subComponent);
2231
-		}
2232
-
2233
-		foreach ($properties as $property) {
2234
-			$name = $property->name;
2235
-			if (!isset($validationRules[$name])) {
2236
-				$validationRules[$name] = '*';
2237
-			}
2238
-
2239
-			$rule = $validationRules[$property->name];
2240
-			if ($rule === '+' || $rule === '*') { // multiple
2241
-				if (!isset($data[$name])) {
2242
-					$data[$name] = [];
2243
-				}
2244
-
2245
-				$data[$name][] = $this->transformSearchProperty($property);
2246
-			} else { // once
2247
-				$data[$name] = $this->transformSearchProperty($property);
2248
-			}
2249
-		}
2250
-
2251
-		return $data;
2252
-	}
2253
-
2254
-	/**
2255
-	 * @param Property $prop
2256
-	 * @return array
2257
-	 */
2258
-	private function transformSearchProperty(Property $prop) {
2259
-		// No need to check Date, as it extends DateTime
2260
-		if ($prop instanceof Property\ICalendar\DateTime) {
2261
-			$value = $prop->getDateTime();
2262
-		} else {
2263
-			$value = $prop->getValue();
2264
-		}
2265
-
2266
-		return [
2267
-			$value,
2268
-			$prop->parameters()
2269
-		];
2270
-	}
2271
-
2272
-	/**
2273
-	 * @param string $principalUri
2274
-	 * @param string $pattern
2275
-	 * @param array $componentTypes
2276
-	 * @param array $searchProperties
2277
-	 * @param array $searchParameters
2278
-	 * @param array $options
2279
-	 * @return array
2280
-	 */
2281
-	public function searchPrincipalUri(string $principalUri,
2282
-		string $pattern,
2283
-		array $componentTypes,
2284
-		array $searchProperties,
2285
-		array $searchParameters,
2286
-		array $options = [],
2287
-	): array {
2288
-		return $this->atomic(function () use ($principalUri, $pattern, $componentTypes, $searchProperties, $searchParameters, $options) {
2289
-			$escapePattern = !\array_key_exists('escape_like_param', $options) || $options['escape_like_param'] !== false;
2290
-
2291
-			$calendarObjectIdQuery = $this->db->getQueryBuilder();
2292
-			$calendarOr = [];
2293
-			$searchOr = [];
2294
-
2295
-			// Fetch calendars and subscription
2296
-			$calendars = $this->getCalendarsForUser($principalUri);
2297
-			$subscriptions = $this->getSubscriptionsForUser($principalUri);
2298
-			foreach ($calendars as $calendar) {
2299
-				$calendarAnd = $calendarObjectIdQuery->expr()->andX(
2300
-					$calendarObjectIdQuery->expr()->eq('cob.calendarid', $calendarObjectIdQuery->createNamedParameter((int)$calendar['id'])),
2301
-					$calendarObjectIdQuery->expr()->eq('cob.calendartype', $calendarObjectIdQuery->createNamedParameter(self::CALENDAR_TYPE_CALENDAR)),
2302
-				);
2303
-
2304
-				// If it's shared, limit search to public events
2305
-				if (isset($calendar['{http://owncloud.org/ns}owner-principal'])
2306
-					&& $calendar['principaluri'] !== $calendar['{http://owncloud.org/ns}owner-principal']) {
2307
-					$calendarAnd->add($calendarObjectIdQuery->expr()->eq('co.classification', $calendarObjectIdQuery->createNamedParameter(self::CLASSIFICATION_PUBLIC)));
2308
-				}
2309
-
2310
-				$calendarOr[] = $calendarAnd;
2311
-			}
2312
-			foreach ($subscriptions as $subscription) {
2313
-				$subscriptionAnd = $calendarObjectIdQuery->expr()->andX(
2314
-					$calendarObjectIdQuery->expr()->eq('cob.calendarid', $calendarObjectIdQuery->createNamedParameter((int)$subscription['id'])),
2315
-					$calendarObjectIdQuery->expr()->eq('cob.calendartype', $calendarObjectIdQuery->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)),
2316
-				);
2317
-
2318
-				// If it's shared, limit search to public events
2319
-				if (isset($subscription['{http://owncloud.org/ns}owner-principal'])
2320
-					&& $subscription['principaluri'] !== $subscription['{http://owncloud.org/ns}owner-principal']) {
2321
-					$subscriptionAnd->add($calendarObjectIdQuery->expr()->eq('co.classification', $calendarObjectIdQuery->createNamedParameter(self::CLASSIFICATION_PUBLIC)));
2322
-				}
2323
-
2324
-				$calendarOr[] = $subscriptionAnd;
2325
-			}
2326
-
2327
-			foreach ($searchProperties as $property) {
2328
-				$propertyAnd = $calendarObjectIdQuery->expr()->andX(
2329
-					$calendarObjectIdQuery->expr()->eq('cob.name', $calendarObjectIdQuery->createNamedParameter($property, IQueryBuilder::PARAM_STR)),
2330
-					$calendarObjectIdQuery->expr()->isNull('cob.parameter'),
2331
-				);
2332
-
2333
-				$searchOr[] = $propertyAnd;
2334
-			}
2335
-			foreach ($searchParameters as $property => $parameter) {
2336
-				$parameterAnd = $calendarObjectIdQuery->expr()->andX(
2337
-					$calendarObjectIdQuery->expr()->eq('cob.name', $calendarObjectIdQuery->createNamedParameter($property, IQueryBuilder::PARAM_STR)),
2338
-					$calendarObjectIdQuery->expr()->eq('cob.parameter', $calendarObjectIdQuery->createNamedParameter($parameter, IQueryBuilder::PARAM_STR_ARRAY)),
2339
-				);
2340
-
2341
-				$searchOr[] = $parameterAnd;
2342
-			}
2343
-
2344
-			if (empty($calendarOr)) {
2345
-				return [];
2346
-			}
2347
-			if (empty($searchOr)) {
2348
-				return [];
2349
-			}
2350
-
2351
-			$calendarObjectIdQuery->selectDistinct('cob.objectid')
2352
-				->from($this->dbObjectPropertiesTable, 'cob')
2353
-				->leftJoin('cob', 'calendarobjects', 'co', $calendarObjectIdQuery->expr()->eq('co.id', 'cob.objectid'))
2354
-				->andWhere($calendarObjectIdQuery->expr()->in('co.componenttype', $calendarObjectIdQuery->createNamedParameter($componentTypes, IQueryBuilder::PARAM_STR_ARRAY)))
2355
-				->andWhere($calendarObjectIdQuery->expr()->orX(...$calendarOr))
2356
-				->andWhere($calendarObjectIdQuery->expr()->orX(...$searchOr))
2357
-				->andWhere($calendarObjectIdQuery->expr()->isNull('deleted_at'));
2358
-
2359
-			if ($pattern !== '') {
2360
-				if (!$escapePattern) {
2361
-					$calendarObjectIdQuery->andWhere($calendarObjectIdQuery->expr()->ilike('cob.value', $calendarObjectIdQuery->createNamedParameter($pattern)));
2362
-				} else {
2363
-					$calendarObjectIdQuery->andWhere($calendarObjectIdQuery->expr()->ilike('cob.value', $calendarObjectIdQuery->createNamedParameter('%' . $this->db->escapeLikeParameter($pattern) . '%')));
2364
-				}
2365
-			}
2366
-
2367
-			if (isset($options['limit'])) {
2368
-				$calendarObjectIdQuery->setMaxResults($options['limit']);
2369
-			}
2370
-			if (isset($options['offset'])) {
2371
-				$calendarObjectIdQuery->setFirstResult($options['offset']);
2372
-			}
2373
-			if (isset($options['timerange'])) {
2374
-				if (isset($options['timerange']['start']) && $options['timerange']['start'] instanceof DateTimeInterface) {
2375
-					$calendarObjectIdQuery->andWhere($calendarObjectIdQuery->expr()->gt(
2376
-						'lastoccurence',
2377
-						$calendarObjectIdQuery->createNamedParameter($options['timerange']['start']->getTimeStamp()),
2378
-					));
2379
-				}
2380
-				if (isset($options['timerange']['end']) && $options['timerange']['end'] instanceof DateTimeInterface) {
2381
-					$calendarObjectIdQuery->andWhere($calendarObjectIdQuery->expr()->lt(
2382
-						'firstoccurence',
2383
-						$calendarObjectIdQuery->createNamedParameter($options['timerange']['end']->getTimeStamp()),
2384
-					));
2385
-				}
2386
-			}
2387
-
2388
-			$result = $calendarObjectIdQuery->executeQuery();
2389
-			$matches = [];
2390
-			while (($row = $result->fetch()) !== false) {
2391
-				$matches[] = (int)$row['objectid'];
2392
-			}
2393
-			$result->closeCursor();
2394
-
2395
-			$query = $this->db->getQueryBuilder();
2396
-			$query->select('calendardata', 'uri', 'calendarid', 'calendartype')
2397
-				->from('calendarobjects')
2398
-				->where($query->expr()->in('id', $query->createNamedParameter($matches, IQueryBuilder::PARAM_INT_ARRAY)));
2399
-
2400
-			$result = $query->executeQuery();
2401
-			$calendarObjects = [];
2402
-			while (($array = $result->fetch()) !== false) {
2403
-				$array['calendarid'] = (int)$array['calendarid'];
2404
-				$array['calendartype'] = (int)$array['calendartype'];
2405
-				$array['calendardata'] = $this->readBlob($array['calendardata']);
2406
-
2407
-				$calendarObjects[] = $array;
2408
-			}
2409
-			$result->closeCursor();
2410
-			return $calendarObjects;
2411
-		}, $this->db);
2412
-	}
2413
-
2414
-	/**
2415
-	 * Searches through all of a users calendars and calendar objects to find
2416
-	 * an object with a specific UID.
2417
-	 *
2418
-	 * This method should return the path to this object, relative to the
2419
-	 * calendar home, so this path usually only contains two parts:
2420
-	 *
2421
-	 * calendarpath/objectpath.ics
2422
-	 *
2423
-	 * If the uid is not found, return null.
2424
-	 *
2425
-	 * This method should only consider * objects that the principal owns, so
2426
-	 * any calendars owned by other principals that also appear in this
2427
-	 * collection should be ignored.
2428
-	 *
2429
-	 * @param string $principalUri
2430
-	 * @param string $uid
2431
-	 * @return string|null
2432
-	 */
2433
-	public function getCalendarObjectByUID($principalUri, $uid) {
2434
-		$query = $this->db->getQueryBuilder();
2435
-		$query->selectAlias('c.uri', 'calendaruri')->selectAlias('co.uri', 'objecturi')
2436
-			->from('calendarobjects', 'co')
2437
-			->leftJoin('co', 'calendars', 'c', $query->expr()->eq('co.calendarid', 'c.id'))
2438
-			->where($query->expr()->eq('c.principaluri', $query->createNamedParameter($principalUri)))
2439
-			->andWhere($query->expr()->eq('co.uid', $query->createNamedParameter($uid)))
2440
-			->andWhere($query->expr()->isNull('co.deleted_at'));
2441
-		$stmt = $query->executeQuery();
2442
-		$row = $stmt->fetch();
2443
-		$stmt->closeCursor();
2444
-		if ($row) {
2445
-			return $row['calendaruri'] . '/' . $row['objecturi'];
2446
-		}
2447
-
2448
-		return null;
2449
-	}
2450
-
2451
-	public function getCalendarObjectById(string $principalUri, int $id): ?array {
2452
-		$query = $this->db->getQueryBuilder();
2453
-		$query->select(['co.id', 'co.uri', 'co.lastmodified', 'co.etag', 'co.calendarid', 'co.size', 'co.calendardata', 'co.componenttype', 'co.classification', 'co.deleted_at'])
2454
-			->selectAlias('c.uri', 'calendaruri')
2455
-			->from('calendarobjects', 'co')
2456
-			->join('co', 'calendars', 'c', $query->expr()->eq('c.id', 'co.calendarid', IQueryBuilder::PARAM_INT))
2457
-			->where($query->expr()->eq('c.principaluri', $query->createNamedParameter($principalUri)))
2458
-			->andWhere($query->expr()->eq('co.id', $query->createNamedParameter($id, IQueryBuilder::PARAM_INT), IQueryBuilder::PARAM_INT));
2459
-		$stmt = $query->executeQuery();
2460
-		$row = $stmt->fetch();
2461
-		$stmt->closeCursor();
2462
-
2463
-		if (!$row) {
2464
-			return null;
2465
-		}
2466
-
2467
-		return [
2468
-			'id' => $row['id'],
2469
-			'uri' => $row['uri'],
2470
-			'lastmodified' => $row['lastmodified'],
2471
-			'etag' => '"' . $row['etag'] . '"',
2472
-			'calendarid' => $row['calendarid'],
2473
-			'calendaruri' => $row['calendaruri'],
2474
-			'size' => (int)$row['size'],
2475
-			'calendardata' => $this->readBlob($row['calendardata']),
2476
-			'component' => strtolower($row['componenttype']),
2477
-			'classification' => (int)$row['classification'],
2478
-			'deleted_at' => isset($row['deleted_at']) ? ((int)$row['deleted_at']) : null,
2479
-		];
2480
-	}
2481
-
2482
-	/**
2483
-	 * The getChanges method returns all the changes that have happened, since
2484
-	 * the specified syncToken in the specified calendar.
2485
-	 *
2486
-	 * This function should return an array, such as the following:
2487
-	 *
2488
-	 * [
2489
-	 *   'syncToken' => 'The current synctoken',
2490
-	 *   'added'   => [
2491
-	 *      'new.txt',
2492
-	 *   ],
2493
-	 *   'modified'   => [
2494
-	 *      'modified.txt',
2495
-	 *   ],
2496
-	 *   'deleted' => [
2497
-	 *      'foo.php.bak',
2498
-	 *      'old.txt'
2499
-	 *   ]
2500
-	 * );
2501
-	 *
2502
-	 * The returned syncToken property should reflect the *current* syncToken
2503
-	 * of the calendar, as reported in the {http://sabredav.org/ns}sync-token
2504
-	 * property This is * needed here too, to ensure the operation is atomic.
2505
-	 *
2506
-	 * If the $syncToken argument is specified as null, this is an initial
2507
-	 * sync, and all members should be reported.
2508
-	 *
2509
-	 * The modified property is an array of nodenames that have changed since
2510
-	 * the last token.
2511
-	 *
2512
-	 * The deleted property is an array with nodenames, that have been deleted
2513
-	 * from collection.
2514
-	 *
2515
-	 * The $syncLevel argument is basically the 'depth' of the report. If it's
2516
-	 * 1, you only have to report changes that happened only directly in
2517
-	 * immediate descendants. If it's 2, it should also include changes from
2518
-	 * the nodes below the child collections. (grandchildren)
2519
-	 *
2520
-	 * The $limit argument allows a client to specify how many results should
2521
-	 * be returned at most. If the limit is not specified, it should be treated
2522
-	 * as infinite.
2523
-	 *
2524
-	 * If the limit (infinite or not) is higher than you're willing to return,
2525
-	 * you should throw a Sabre\DAV\Exception\TooMuchMatches() exception.
2526
-	 *
2527
-	 * If the syncToken is expired (due to data cleanup) or unknown, you must
2528
-	 * return null.
2529
-	 *
2530
-	 * The limit is 'suggestive'. You are free to ignore it.
2531
-	 *
2532
-	 * @param string $calendarId
2533
-	 * @param string $syncToken
2534
-	 * @param int $syncLevel
2535
-	 * @param int|null $limit
2536
-	 * @param int $calendarType
2537
-	 * @return ?array
2538
-	 */
2539
-	public function getChangesForCalendar($calendarId, $syncToken, $syncLevel, $limit = null, $calendarType = self::CALENDAR_TYPE_CALENDAR) {
2540
-		$table = $calendarType === self::CALENDAR_TYPE_CALENDAR ? 'calendars': 'calendarsubscriptions';
2541
-
2542
-		return $this->atomic(function () use ($calendarId, $syncToken, $syncLevel, $limit, $calendarType, $table) {
2543
-			// Current synctoken
2544
-			$qb = $this->db->getQueryBuilder();
2545
-			$qb->select('synctoken')
2546
-				->from($table)
2547
-				->where(
2548
-					$qb->expr()->eq('id', $qb->createNamedParameter($calendarId))
2549
-				);
2550
-			$stmt = $qb->executeQuery();
2551
-			$currentToken = $stmt->fetchOne();
2552
-			$initialSync = !is_numeric($syncToken);
2553
-
2554
-			if ($currentToken === false) {
2555
-				return null;
2556
-			}
2557
-
2558
-			// evaluate if this is a initial sync and construct appropriate command
2559
-			if ($initialSync) {
2560
-				$qb = $this->db->getQueryBuilder();
2561
-				$qb->select('uri')
2562
-					->from('calendarobjects')
2563
-					->where($qb->expr()->eq('calendarid', $qb->createNamedParameter($calendarId)))
2564
-					->andWhere($qb->expr()->eq('calendartype', $qb->createNamedParameter($calendarType)))
2565
-					->andWhere($qb->expr()->isNull('deleted_at'));
2566
-			} else {
2567
-				$qb = $this->db->getQueryBuilder();
2568
-				$qb->select('uri', $qb->func()->max('operation'))
2569
-					->from('calendarchanges')
2570
-					->where($qb->expr()->eq('calendarid', $qb->createNamedParameter($calendarId)))
2571
-					->andWhere($qb->expr()->eq('calendartype', $qb->createNamedParameter($calendarType)))
2572
-					->andWhere($qb->expr()->gte('synctoken', $qb->createNamedParameter($syncToken)))
2573
-					->andWhere($qb->expr()->lt('synctoken', $qb->createNamedParameter($currentToken)))
2574
-					->groupBy('uri');
2575
-			}
2576
-			// evaluate if limit exists
2577
-			if (is_numeric($limit)) {
2578
-				$qb->setMaxResults($limit);
2579
-			}
2580
-			// execute command
2581
-			$stmt = $qb->executeQuery();
2582
-			// build results
2583
-			$result = ['syncToken' => $currentToken, 'added' => [], 'modified' => [], 'deleted' => []];
2584
-			// retrieve results
2585
-			if ($initialSync) {
2586
-				$result['added'] = $stmt->fetchAll(\PDO::FETCH_COLUMN);
2587
-			} else {
2588
-				// \PDO::FETCH_NUM is needed due to the inconsistent field names
2589
-				// produced by doctrine for MAX() with different databases
2590
-				while ($entry = $stmt->fetch(\PDO::FETCH_NUM)) {
2591
-					// assign uri (column 0) to appropriate mutation based on operation (column 1)
2592
-					// forced (int) is needed as doctrine with OCI returns the operation field as string not integer
2593
-					match ((int)$entry[1]) {
2594
-						1 => $result['added'][] = $entry[0],
2595
-						2 => $result['modified'][] = $entry[0],
2596
-						3 => $result['deleted'][] = $entry[0],
2597
-						default => $this->logger->debug('Unknown calendar change operation detected')
2598
-					};
2599
-				}
2600
-			}
2601
-			$stmt->closeCursor();
2602
-
2603
-			return $result;
2604
-		}, $this->db);
2605
-	}
2606
-
2607
-	/**
2608
-	 * Returns a list of subscriptions for a principal.
2609
-	 *
2610
-	 * Every subscription is an array with the following keys:
2611
-	 *  * id, a unique id that will be used by other functions to modify the
2612
-	 *    subscription. This can be the same as the uri or a database key.
2613
-	 *  * uri. This is just the 'base uri' or 'filename' of the subscription.
2614
-	 *  * principaluri. The owner of the subscription. Almost always the same as
2615
-	 *    principalUri passed to this method.
2616
-	 *
2617
-	 * Furthermore, all the subscription info must be returned too:
2618
-	 *
2619
-	 * 1. {DAV:}displayname
2620
-	 * 2. {http://apple.com/ns/ical/}refreshrate
2621
-	 * 3. {http://calendarserver.org/ns/}subscribed-strip-todos (omit if todos
2622
-	 *    should not be stripped).
2623
-	 * 4. {http://calendarserver.org/ns/}subscribed-strip-alarms (omit if alarms
2624
-	 *    should not be stripped).
2625
-	 * 5. {http://calendarserver.org/ns/}subscribed-strip-attachments (omit if
2626
-	 *    attachments should not be stripped).
2627
-	 * 6. {http://calendarserver.org/ns/}source (Must be a
2628
-	 *     Sabre\DAV\Property\Href).
2629
-	 * 7. {http://apple.com/ns/ical/}calendar-color
2630
-	 * 8. {http://apple.com/ns/ical/}calendar-order
2631
-	 * 9. {urn:ietf:params:xml:ns:caldav}supported-calendar-component-set
2632
-	 *    (should just be an instance of
2633
-	 *    Sabre\CalDAV\Property\SupportedCalendarComponentSet, with a bunch of
2634
-	 *    default components).
2635
-	 *
2636
-	 * @param string $principalUri
2637
-	 * @return array
2638
-	 */
2639
-	public function getSubscriptionsForUser($principalUri) {
2640
-		$fields = array_column($this->subscriptionPropertyMap, 0);
2641
-		$fields[] = 'id';
2642
-		$fields[] = 'uri';
2643
-		$fields[] = 'source';
2644
-		$fields[] = 'principaluri';
2645
-		$fields[] = 'lastmodified';
2646
-		$fields[] = 'synctoken';
2647
-
2648
-		$query = $this->db->getQueryBuilder();
2649
-		$query->select($fields)
2650
-			->from('calendarsubscriptions')
2651
-			->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
2652
-			->orderBy('calendarorder', 'asc');
2653
-		$stmt = $query->executeQuery();
2654
-
2655
-		$subscriptions = [];
2656
-		while ($row = $stmt->fetch()) {
2657
-			$subscription = [
2658
-				'id' => $row['id'],
2659
-				'uri' => $row['uri'],
2660
-				'principaluri' => $row['principaluri'],
2661
-				'source' => $row['source'],
2662
-				'lastmodified' => $row['lastmodified'],
2663
-
2664
-				'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet(['VTODO', 'VEVENT']),
2665
-				'{http://sabredav.org/ns}sync-token' => $row['synctoken'] ?: '0',
2666
-			];
2667
-
2668
-			$subscriptions[] = $this->rowToSubscription($row, $subscription);
2669
-		}
2670
-
2671
-		return $subscriptions;
2672
-	}
2673
-
2674
-	/**
2675
-	 * Creates a new subscription for a principal.
2676
-	 *
2677
-	 * If the creation was a success, an id must be returned that can be used to reference
2678
-	 * this subscription in other methods, such as updateSubscription.
2679
-	 *
2680
-	 * @param string $principalUri
2681
-	 * @param string $uri
2682
-	 * @param array $properties
2683
-	 * @return mixed
2684
-	 */
2685
-	public function createSubscription($principalUri, $uri, array $properties) {
2686
-		if (!isset($properties['{http://calendarserver.org/ns/}source'])) {
2687
-			throw new Forbidden('The {http://calendarserver.org/ns/}source property is required when creating subscriptions');
2688
-		}
2689
-
2690
-		$values = [
2691
-			'principaluri' => $principalUri,
2692
-			'uri' => $uri,
2693
-			'source' => $properties['{http://calendarserver.org/ns/}source']->getHref(),
2694
-			'lastmodified' => time(),
2695
-		];
2696
-
2697
-		$propertiesBoolean = ['striptodos', 'stripalarms', 'stripattachments'];
2698
-
2699
-		foreach ($this->subscriptionPropertyMap as $xmlName => [$dbName, $type]) {
2700
-			if (array_key_exists($xmlName, $properties)) {
2701
-				$values[$dbName] = $properties[$xmlName];
2702
-				if (in_array($dbName, $propertiesBoolean)) {
2703
-					$values[$dbName] = true;
2704
-				}
2705
-			}
2706
-		}
2707
-
2708
-		[$subscriptionId, $subscriptionRow] = $this->atomic(function () use ($values) {
2709
-			$valuesToInsert = [];
2710
-			$query = $this->db->getQueryBuilder();
2711
-			foreach (array_keys($values) as $name) {
2712
-				$valuesToInsert[$name] = $query->createNamedParameter($values[$name]);
2713
-			}
2714
-			$query->insert('calendarsubscriptions')
2715
-				->values($valuesToInsert)
2716
-				->executeStatement();
2717
-
2718
-			$subscriptionId = $query->getLastInsertId();
2719
-
2720
-			$subscriptionRow = $this->getSubscriptionById($subscriptionId);
2721
-			return [$subscriptionId, $subscriptionRow];
2722
-		}, $this->db);
2723
-
2724
-		$this->dispatcher->dispatchTyped(new SubscriptionCreatedEvent($subscriptionId, $subscriptionRow));
2725
-
2726
-		return $subscriptionId;
2727
-	}
2728
-
2729
-	/**
2730
-	 * Updates a subscription
2731
-	 *
2732
-	 * The list of mutations is stored in a Sabre\DAV\PropPatch object.
2733
-	 * To do the actual updates, you must tell this object which properties
2734
-	 * you're going to process with the handle() method.
2735
-	 *
2736
-	 * Calling the handle method is like telling the PropPatch object "I
2737
-	 * promise I can handle updating this property".
2738
-	 *
2739
-	 * Read the PropPatch documentation for more info and examples.
2740
-	 *
2741
-	 * @param mixed $subscriptionId
2742
-	 * @param PropPatch $propPatch
2743
-	 * @return void
2744
-	 */
2745
-	public function updateSubscription($subscriptionId, PropPatch $propPatch) {
2746
-		$supportedProperties = array_keys($this->subscriptionPropertyMap);
2747
-		$supportedProperties[] = '{http://calendarserver.org/ns/}source';
2748
-
2749
-		$propPatch->handle($supportedProperties, function ($mutations) use ($subscriptionId) {
2750
-			$newValues = [];
2751
-
2752
-			foreach ($mutations as $propertyName => $propertyValue) {
2753
-				if ($propertyName === '{http://calendarserver.org/ns/}source') {
2754
-					$newValues['source'] = $propertyValue->getHref();
2755
-				} else {
2756
-					$fieldName = $this->subscriptionPropertyMap[$propertyName][0];
2757
-					$newValues[$fieldName] = $propertyValue;
2758
-				}
2759
-			}
2760
-
2761
-			$subscriptionRow = $this->atomic(function () use ($subscriptionId, $newValues) {
2762
-				$query = $this->db->getQueryBuilder();
2763
-				$query->update('calendarsubscriptions')
2764
-					->set('lastmodified', $query->createNamedParameter(time()));
2765
-				foreach ($newValues as $fieldName => $value) {
2766
-					$query->set($fieldName, $query->createNamedParameter($value));
2767
-				}
2768
-				$query->where($query->expr()->eq('id', $query->createNamedParameter($subscriptionId)))
2769
-					->executeStatement();
2770
-
2771
-				return $this->getSubscriptionById($subscriptionId);
2772
-			}, $this->db);
2773
-
2774
-			$this->dispatcher->dispatchTyped(new SubscriptionUpdatedEvent((int)$subscriptionId, $subscriptionRow, [], $mutations));
2775
-
2776
-			return true;
2777
-		});
2778
-	}
2779
-
2780
-	/**
2781
-	 * Deletes a subscription.
2782
-	 *
2783
-	 * @param mixed $subscriptionId
2784
-	 * @return void
2785
-	 */
2786
-	public function deleteSubscription($subscriptionId) {
2787
-		$this->atomic(function () use ($subscriptionId): void {
2788
-			$subscriptionRow = $this->getSubscriptionById($subscriptionId);
2789
-
2790
-			$query = $this->db->getQueryBuilder();
2791
-			$query->delete('calendarsubscriptions')
2792
-				->where($query->expr()->eq('id', $query->createNamedParameter($subscriptionId)))
2793
-				->executeStatement();
2794
-
2795
-			$query = $this->db->getQueryBuilder();
2796
-			$query->delete('calendarobjects')
2797
-				->where($query->expr()->eq('calendarid', $query->createNamedParameter($subscriptionId)))
2798
-				->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)))
2799
-				->executeStatement();
2800
-
2801
-			$query->delete('calendarchanges')
2802
-				->where($query->expr()->eq('calendarid', $query->createNamedParameter($subscriptionId)))
2803
-				->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)))
2804
-				->executeStatement();
2805
-
2806
-			$query->delete($this->dbObjectPropertiesTable)
2807
-				->where($query->expr()->eq('calendarid', $query->createNamedParameter($subscriptionId)))
2808
-				->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)))
2809
-				->executeStatement();
2810
-
2811
-			if ($subscriptionRow) {
2812
-				$this->dispatcher->dispatchTyped(new SubscriptionDeletedEvent((int)$subscriptionId, $subscriptionRow, []));
2813
-			}
2814
-		}, $this->db);
2815
-	}
2816
-
2817
-	/**
2818
-	 * Returns a single scheduling object for the inbox collection.
2819
-	 *
2820
-	 * The returned array should contain the following elements:
2821
-	 *   * uri - A unique basename for the object. This will be used to
2822
-	 *           construct a full uri.
2823
-	 *   * calendardata - The iCalendar object
2824
-	 *   * lastmodified - The last modification date. Can be an int for a unix
2825
-	 *                    timestamp, or a PHP DateTime object.
2826
-	 *   * etag - A unique token that must change if the object changed.
2827
-	 *   * size - The size of the object, in bytes.
2828
-	 *
2829
-	 * @param string $principalUri
2830
-	 * @param string $objectUri
2831
-	 * @return array
2832
-	 */
2833
-	public function getSchedulingObject($principalUri, $objectUri) {
2834
-		$query = $this->db->getQueryBuilder();
2835
-		$stmt = $query->select(['uri', 'calendardata', 'lastmodified', 'etag', 'size'])
2836
-			->from('schedulingobjects')
2837
-			->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
2838
-			->andWhere($query->expr()->eq('uri', $query->createNamedParameter($objectUri)))
2839
-			->executeQuery();
2840
-
2841
-		$row = $stmt->fetch();
2842
-
2843
-		if (!$row) {
2844
-			return null;
2845
-		}
2846
-
2847
-		return [
2848
-			'uri' => $row['uri'],
2849
-			'calendardata' => $row['calendardata'],
2850
-			'lastmodified' => $row['lastmodified'],
2851
-			'etag' => '"' . $row['etag'] . '"',
2852
-			'size' => (int)$row['size'],
2853
-		];
2854
-	}
2855
-
2856
-	/**
2857
-	 * Returns all scheduling objects for the inbox collection.
2858
-	 *
2859
-	 * These objects should be returned as an array. Every item in the array
2860
-	 * should follow the same structure as returned from getSchedulingObject.
2861
-	 *
2862
-	 * The main difference is that 'calendardata' is optional.
2863
-	 *
2864
-	 * @param string $principalUri
2865
-	 * @return array
2866
-	 */
2867
-	public function getSchedulingObjects($principalUri) {
2868
-		$query = $this->db->getQueryBuilder();
2869
-		$stmt = $query->select(['uri', 'calendardata', 'lastmodified', 'etag', 'size'])
2870
-			->from('schedulingobjects')
2871
-			->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
2872
-			->executeQuery();
2873
-
2874
-		$results = [];
2875
-		while (($row = $stmt->fetch()) !== false) {
2876
-			$results[] = [
2877
-				'calendardata' => $row['calendardata'],
2878
-				'uri' => $row['uri'],
2879
-				'lastmodified' => $row['lastmodified'],
2880
-				'etag' => '"' . $row['etag'] . '"',
2881
-				'size' => (int)$row['size'],
2882
-			];
2883
-		}
2884
-		$stmt->closeCursor();
2885
-
2886
-		return $results;
2887
-	}
2888
-
2889
-	/**
2890
-	 * Deletes a scheduling object from the inbox collection.
2891
-	 *
2892
-	 * @param string $principalUri
2893
-	 * @param string $objectUri
2894
-	 * @return void
2895
-	 */
2896
-	public function deleteSchedulingObject($principalUri, $objectUri) {
2897
-		$this->cachedObjects = [];
2898
-		$query = $this->db->getQueryBuilder();
2899
-		$query->delete('schedulingobjects')
2900
-			->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
2901
-			->andWhere($query->expr()->eq('uri', $query->createNamedParameter($objectUri)))
2902
-			->executeStatement();
2903
-	}
2904
-
2905
-	/**
2906
-	 * Deletes all scheduling objects last modified before $modifiedBefore from the inbox collection.
2907
-	 *
2908
-	 * @param int $modifiedBefore
2909
-	 * @param int $limit
2910
-	 * @return void
2911
-	 */
2912
-	public function deleteOutdatedSchedulingObjects(int $modifiedBefore, int $limit): void {
2913
-		$query = $this->db->getQueryBuilder();
2914
-		$query->select('id')
2915
-			->from('schedulingobjects')
2916
-			->where($query->expr()->lt('lastmodified', $query->createNamedParameter($modifiedBefore)))
2917
-			->setMaxResults($limit);
2918
-		$result = $query->executeQuery();
2919
-		$count = $result->rowCount();
2920
-		if ($count === 0) {
2921
-			return;
2922
-		}
2923
-		$ids = array_map(static function (array $id) {
2924
-			return (int)$id[0];
2925
-		}, $result->fetchAll(\PDO::FETCH_NUM));
2926
-		$result->closeCursor();
2927
-
2928
-		$numDeleted = 0;
2929
-		$deleteQuery = $this->db->getQueryBuilder();
2930
-		$deleteQuery->delete('schedulingobjects')
2931
-			->where($deleteQuery->expr()->in('id', $deleteQuery->createParameter('ids'), IQueryBuilder::PARAM_INT_ARRAY));
2932
-		foreach (array_chunk($ids, 1000) as $chunk) {
2933
-			$deleteQuery->setParameter('ids', $chunk, IQueryBuilder::PARAM_INT_ARRAY);
2934
-			$numDeleted += $deleteQuery->executeStatement();
2935
-		}
2936
-
2937
-		if ($numDeleted === $limit) {
2938
-			$this->logger->info("Deleted $limit scheduling objects, continuing with next batch");
2939
-			$this->deleteOutdatedSchedulingObjects($modifiedBefore, $limit);
2940
-		}
2941
-	}
2942
-
2943
-	/**
2944
-	 * Creates a new scheduling object. This should land in a users' inbox.
2945
-	 *
2946
-	 * @param string $principalUri
2947
-	 * @param string $objectUri
2948
-	 * @param string $objectData
2949
-	 * @return void
2950
-	 */
2951
-	public function createSchedulingObject($principalUri, $objectUri, $objectData) {
2952
-		$this->cachedObjects = [];
2953
-		$query = $this->db->getQueryBuilder();
2954
-		$query->insert('schedulingobjects')
2955
-			->values([
2956
-				'principaluri' => $query->createNamedParameter($principalUri),
2957
-				'calendardata' => $query->createNamedParameter($objectData, IQueryBuilder::PARAM_LOB),
2958
-				'uri' => $query->createNamedParameter($objectUri),
2959
-				'lastmodified' => $query->createNamedParameter(time()),
2960
-				'etag' => $query->createNamedParameter(md5($objectData)),
2961
-				'size' => $query->createNamedParameter(strlen($objectData))
2962
-			])
2963
-			->executeStatement();
2964
-	}
2965
-
2966
-	/**
2967
-	 * Adds a change record to the calendarchanges table.
2968
-	 *
2969
-	 * @param mixed $calendarId
2970
-	 * @param string[] $objectUris
2971
-	 * @param int $operation 1 = add, 2 = modify, 3 = delete.
2972
-	 * @param int $calendarType
2973
-	 * @return void
2974
-	 */
2975
-	protected function addChanges(int $calendarId, array $objectUris, int $operation, int $calendarType = self::CALENDAR_TYPE_CALENDAR): void {
2976
-		$this->cachedObjects = [];
2977
-		$table = $calendarType === self::CALENDAR_TYPE_CALENDAR ? 'calendars': 'calendarsubscriptions';
2978
-
2979
-		$this->atomic(function () use ($calendarId, $objectUris, $operation, $calendarType, $table): void {
2980
-			$query = $this->db->getQueryBuilder();
2981
-			$query->select('synctoken')
2982
-				->from($table)
2983
-				->where($query->expr()->eq('id', $query->createNamedParameter($calendarId)));
2984
-			$result = $query->executeQuery();
2985
-			$syncToken = (int)$result->fetchOne();
2986
-			$result->closeCursor();
2987
-
2988
-			$query = $this->db->getQueryBuilder();
2989
-			$query->insert('calendarchanges')
2990
-				->values([
2991
-					'uri' => $query->createParameter('uri'),
2992
-					'synctoken' => $query->createNamedParameter($syncToken),
2993
-					'calendarid' => $query->createNamedParameter($calendarId),
2994
-					'operation' => $query->createNamedParameter($operation),
2995
-					'calendartype' => $query->createNamedParameter($calendarType),
2996
-					'created_at' => time(),
2997
-				]);
2998
-			foreach ($objectUris as $uri) {
2999
-				$query->setParameter('uri', $uri);
3000
-				$query->executeStatement();
3001
-			}
3002
-
3003
-			$query = $this->db->getQueryBuilder();
3004
-			$query->update($table)
3005
-				->set('synctoken', $query->createNamedParameter($syncToken + 1, IQueryBuilder::PARAM_INT))
3006
-				->where($query->expr()->eq('id', $query->createNamedParameter($calendarId)))
3007
-				->executeStatement();
3008
-		}, $this->db);
3009
-	}
3010
-
3011
-	public function restoreChanges(int $calendarId, int $calendarType = self::CALENDAR_TYPE_CALENDAR): void {
3012
-		$this->cachedObjects = [];
3013
-
3014
-		$this->atomic(function () use ($calendarId, $calendarType): void {
3015
-			$qbAdded = $this->db->getQueryBuilder();
3016
-			$qbAdded->select('uri')
3017
-				->from('calendarobjects')
3018
-				->where(
3019
-					$qbAdded->expr()->andX(
3020
-						$qbAdded->expr()->eq('calendarid', $qbAdded->createNamedParameter($calendarId)),
3021
-						$qbAdded->expr()->eq('calendartype', $qbAdded->createNamedParameter($calendarType)),
3022
-						$qbAdded->expr()->isNull('deleted_at'),
3023
-					)
3024
-				);
3025
-			$resultAdded = $qbAdded->executeQuery();
3026
-			$addedUris = $resultAdded->fetchAll(\PDO::FETCH_COLUMN);
3027
-			$resultAdded->closeCursor();
3028
-			// Track everything as changed
3029
-			// Tracking the creation is not necessary because \OCA\DAV\CalDAV\CalDavBackend::getChangesForCalendar
3030
-			// only returns the last change per object.
3031
-			$this->addChanges($calendarId, $addedUris, 2, $calendarType);
3032
-
3033
-			$qbDeleted = $this->db->getQueryBuilder();
3034
-			$qbDeleted->select('uri')
3035
-				->from('calendarobjects')
3036
-				->where(
3037
-					$qbDeleted->expr()->andX(
3038
-						$qbDeleted->expr()->eq('calendarid', $qbDeleted->createNamedParameter($calendarId)),
3039
-						$qbDeleted->expr()->eq('calendartype', $qbDeleted->createNamedParameter($calendarType)),
3040
-						$qbDeleted->expr()->isNotNull('deleted_at'),
3041
-					)
3042
-				);
3043
-			$resultDeleted = $qbDeleted->executeQuery();
3044
-			$deletedUris = array_map(function (string $uri) {
3045
-				return str_replace('-deleted.ics', '.ics', $uri);
3046
-			}, $resultDeleted->fetchAll(\PDO::FETCH_COLUMN));
3047
-			$resultDeleted->closeCursor();
3048
-			$this->addChanges($calendarId, $deletedUris, 3, $calendarType);
3049
-		}, $this->db);
3050
-	}
3051
-
3052
-	/**
3053
-	 * Parses some information from calendar objects, used for optimized
3054
-	 * calendar-queries.
3055
-	 *
3056
-	 * Returns an array with the following keys:
3057
-	 *   * etag - An md5 checksum of the object without the quotes.
3058
-	 *   * size - Size of the object in bytes
3059
-	 *   * componentType - VEVENT, VTODO or VJOURNAL
3060
-	 *   * firstOccurence
3061
-	 *   * lastOccurence
3062
-	 *   * uid - value of the UID property
3063
-	 *
3064
-	 * @param string $calendarData
3065
-	 * @return array
3066
-	 */
3067
-	public function getDenormalizedData(string $calendarData): array {
3068
-		$vObject = Reader::read($calendarData);
3069
-		$vEvents = [];
3070
-		$componentType = null;
3071
-		$component = null;
3072
-		$firstOccurrence = null;
3073
-		$lastOccurrence = null;
3074
-		$uid = null;
3075
-		$classification = self::CLASSIFICATION_PUBLIC;
3076
-		$hasDTSTART = false;
3077
-		foreach ($vObject->getComponents() as $component) {
3078
-			if ($component->name !== 'VTIMEZONE') {
3079
-				// Finding all VEVENTs, and track them
3080
-				if ($component->name === 'VEVENT') {
3081
-					$vEvents[] = $component;
3082
-					if ($component->DTSTART) {
3083
-						$hasDTSTART = true;
3084
-					}
3085
-				}
3086
-				// Track first component type and uid
3087
-				if ($uid === null) {
3088
-					$componentType = $component->name;
3089
-					$uid = (string)$component->UID;
3090
-				}
3091
-			}
3092
-		}
3093
-		if (!$componentType) {
3094
-			throw new BadRequest('Calendar objects must have a VJOURNAL, VEVENT or VTODO component');
3095
-		}
3096
-
3097
-		if ($hasDTSTART) {
3098
-			$component = $vEvents[0];
3099
-
3100
-			// Finding the last occurrence is a bit harder
3101
-			if (!isset($component->RRULE) && count($vEvents) === 1) {
3102
-				$firstOccurrence = $component->DTSTART->getDateTime()->getTimeStamp();
3103
-				if (isset($component->DTEND)) {
3104
-					$lastOccurrence = $component->DTEND->getDateTime()->getTimeStamp();
3105
-				} elseif (isset($component->DURATION)) {
3106
-					$endDate = clone $component->DTSTART->getDateTime();
3107
-					$endDate->add(DateTimeParser::parse($component->DURATION->getValue()));
3108
-					$lastOccurrence = $endDate->getTimeStamp();
3109
-				} elseif (!$component->DTSTART->hasTime()) {
3110
-					$endDate = clone $component->DTSTART->getDateTime();
3111
-					$endDate->modify('+1 day');
3112
-					$lastOccurrence = $endDate->getTimeStamp();
3113
-				} else {
3114
-					$lastOccurrence = $firstOccurrence;
3115
-				}
3116
-			} else {
3117
-				try {
3118
-					$it = new EventIterator($vEvents);
3119
-				} catch (NoInstancesException $e) {
3120
-					$this->logger->debug('Caught no instance exception for calendar data. This usually indicates invalid calendar data.', [
3121
-						'app' => 'dav',
3122
-						'exception' => $e,
3123
-					]);
3124
-					throw new Forbidden($e->getMessage());
3125
-				}
3126
-				$maxDate = new DateTime(self::MAX_DATE);
3127
-				$firstOccurrence = $it->getDtStart()->getTimestamp();
3128
-				if ($it->isInfinite()) {
3129
-					$lastOccurrence = $maxDate->getTimestamp();
3130
-				} else {
3131
-					$end = $it->getDtEnd();
3132
-					while ($it->valid() && $end < $maxDate) {
3133
-						$end = $it->getDtEnd();
3134
-						$it->next();
3135
-					}
3136
-					$lastOccurrence = $end->getTimestamp();
3137
-				}
3138
-			}
3139
-		}
3140
-
3141
-		if ($component->CLASS) {
3142
-			$classification = CalDavBackend::CLASSIFICATION_PRIVATE;
3143
-			switch ($component->CLASS->getValue()) {
3144
-				case 'PUBLIC':
3145
-					$classification = CalDavBackend::CLASSIFICATION_PUBLIC;
3146
-					break;
3147
-				case 'CONFIDENTIAL':
3148
-					$classification = CalDavBackend::CLASSIFICATION_CONFIDENTIAL;
3149
-					break;
3150
-			}
3151
-		}
3152
-		return [
3153
-			'etag' => md5($calendarData),
3154
-			'size' => strlen($calendarData),
3155
-			'componentType' => $componentType,
3156
-			'firstOccurence' => is_null($firstOccurrence) ? null : max(0, $firstOccurrence),
3157
-			'lastOccurence' => is_null($lastOccurrence) ? null : max(0, $lastOccurrence),
3158
-			'uid' => $uid,
3159
-			'classification' => $classification
3160
-		];
3161
-	}
3162
-
3163
-	/**
3164
-	 * @param $cardData
3165
-	 * @return bool|string
3166
-	 */
3167
-	private function readBlob($cardData) {
3168
-		if (is_resource($cardData)) {
3169
-			return stream_get_contents($cardData);
3170
-		}
3171
-
3172
-		return $cardData;
3173
-	}
3174
-
3175
-	/**
3176
-	 * @param list<array{href: string, commonName: string, readOnly: bool}> $add
3177
-	 * @param list<string> $remove
3178
-	 */
3179
-	public function updateShares(IShareable $shareable, array $add, array $remove): void {
3180
-		$this->atomic(function () use ($shareable, $add, $remove): void {
3181
-			$calendarId = $shareable->getResourceId();
3182
-			$calendarRow = $this->getCalendarById($calendarId);
3183
-			if ($calendarRow === null) {
3184
-				throw new \RuntimeException('Trying to update shares for non-existing calendar: ' . $calendarId);
3185
-			}
3186
-			$oldShares = $this->getShares($calendarId);
3187
-
3188
-			$this->calendarSharingBackend->updateShares($shareable, $add, $remove, $oldShares);
3189
-
3190
-			$this->dispatcher->dispatchTyped(new CalendarShareUpdatedEvent($calendarId, $calendarRow, $oldShares, $add, $remove));
3191
-		}, $this->db);
3192
-	}
3193
-
3194
-	/**
3195
-	 * @return list<array{href: string, commonName: string, status: int, readOnly: bool, '{http://owncloud.org/ns}principal': string, '{http://owncloud.org/ns}group-share': bool}>
3196
-	 */
3197
-	public function getShares(int $resourceId): array {
3198
-		return $this->calendarSharingBackend->getShares($resourceId);
3199
-	}
3200
-
3201
-	public function preloadShares(array $resourceIds): void {
3202
-		$this->calendarSharingBackend->preloadShares($resourceIds);
3203
-	}
3204
-
3205
-	/**
3206
-	 * @param boolean $value
3207
-	 * @param Calendar $calendar
3208
-	 * @return string|null
3209
-	 */
3210
-	public function setPublishStatus($value, $calendar) {
3211
-		return $this->atomic(function () use ($value, $calendar) {
3212
-			$calendarId = $calendar->getResourceId();
3213
-			$calendarData = $this->getCalendarById($calendarId);
3214
-
3215
-			$query = $this->db->getQueryBuilder();
3216
-			if ($value) {
3217
-				$publicUri = $this->random->generate(16, ISecureRandom::CHAR_HUMAN_READABLE);
3218
-				$query->insert('dav_shares')
3219
-					->values([
3220
-						'principaluri' => $query->createNamedParameter($calendar->getPrincipalURI()),
3221
-						'type' => $query->createNamedParameter('calendar'),
3222
-						'access' => $query->createNamedParameter(self::ACCESS_PUBLIC),
3223
-						'resourceid' => $query->createNamedParameter($calendar->getResourceId()),
3224
-						'publicuri' => $query->createNamedParameter($publicUri)
3225
-					]);
3226
-				$query->executeStatement();
3227
-
3228
-				$this->dispatcher->dispatchTyped(new CalendarPublishedEvent($calendarId, $calendarData, $publicUri));
3229
-				return $publicUri;
3230
-			}
3231
-			$query->delete('dav_shares')
3232
-				->where($query->expr()->eq('resourceid', $query->createNamedParameter($calendar->getResourceId())))
3233
-				->andWhere($query->expr()->eq('access', $query->createNamedParameter(self::ACCESS_PUBLIC)));
3234
-			$query->executeStatement();
3235
-
3236
-			$this->dispatcher->dispatchTyped(new CalendarUnpublishedEvent($calendarId, $calendarData));
3237
-			return null;
3238
-		}, $this->db);
3239
-	}
3240
-
3241
-	/**
3242
-	 * @param Calendar $calendar
3243
-	 * @return mixed
3244
-	 */
3245
-	public function getPublishStatus($calendar) {
3246
-		$query = $this->db->getQueryBuilder();
3247
-		$result = $query->select('publicuri')
3248
-			->from('dav_shares')
3249
-			->where($query->expr()->eq('resourceid', $query->createNamedParameter($calendar->getResourceId())))
3250
-			->andWhere($query->expr()->eq('access', $query->createNamedParameter(self::ACCESS_PUBLIC)))
3251
-			->executeQuery();
3252
-
3253
-		$row = $result->fetch();
3254
-		$result->closeCursor();
3255
-		return $row ? reset($row) : false;
3256
-	}
3257
-
3258
-	/**
3259
-	 * @param int $resourceId
3260
-	 * @param list<array{privilege: string, principal: string, protected: bool}> $acl
3261
-	 * @return list<array{privilege: string, principal: string, protected: bool}>
3262
-	 */
3263
-	public function applyShareAcl(int $resourceId, array $acl): array {
3264
-		$shares = $this->calendarSharingBackend->getShares($resourceId);
3265
-		return $this->calendarSharingBackend->applyShareAcl($shares, $acl);
3266
-	}
3267
-
3268
-	/**
3269
-	 * update properties table
3270
-	 *
3271
-	 * @param int $calendarId
3272
-	 * @param string $objectUri
3273
-	 * @param string $calendarData
3274
-	 * @param int $calendarType
3275
-	 */
3276
-	public function updateProperties($calendarId, $objectUri, $calendarData, $calendarType = self::CALENDAR_TYPE_CALENDAR) {
3277
-		$this->cachedObjects = [];
3278
-		$this->atomic(function () use ($calendarId, $objectUri, $calendarData, $calendarType): void {
3279
-			$objectId = $this->getCalendarObjectId($calendarId, $objectUri, $calendarType);
3280
-
3281
-			try {
3282
-				$vCalendar = $this->readCalendarData($calendarData);
3283
-			} catch (\Exception $ex) {
3284
-				return;
3285
-			}
3286
-
3287
-			$this->purgeProperties($calendarId, $objectId);
3288
-
3289
-			$query = $this->db->getQueryBuilder();
3290
-			$query->insert($this->dbObjectPropertiesTable)
3291
-				->values(
3292
-					[
3293
-						'calendarid' => $query->createNamedParameter($calendarId),
3294
-						'calendartype' => $query->createNamedParameter($calendarType),
3295
-						'objectid' => $query->createNamedParameter($objectId),
3296
-						'name' => $query->createParameter('name'),
3297
-						'parameter' => $query->createParameter('parameter'),
3298
-						'value' => $query->createParameter('value'),
3299
-					]
3300
-				);
3301
-
3302
-			$indexComponents = ['VEVENT', 'VJOURNAL', 'VTODO'];
3303
-			foreach ($vCalendar->getComponents() as $component) {
3304
-				if (!in_array($component->name, $indexComponents)) {
3305
-					continue;
3306
-				}
3307
-
3308
-				foreach ($component->children() as $property) {
3309
-					if (in_array($property->name, self::INDEXED_PROPERTIES, true)) {
3310
-						$value = $property->getValue();
3311
-						// is this a shitty db?
3312
-						if (!$this->db->supports4ByteText()) {
3313
-							$value = preg_replace('/[\x{10000}-\x{10FFFF}]/u', "\xEF\xBF\xBD", $value);
3314
-						}
3315
-						$value = mb_strcut($value, 0, 254);
3316
-
3317
-						$query->setParameter('name', $property->name);
3318
-						$query->setParameter('parameter', null);
3319
-						$query->setParameter('value', mb_strcut($value, 0, 254));
3320
-						$query->executeStatement();
3321
-					}
3322
-
3323
-					if (array_key_exists($property->name, self::$indexParameters)) {
3324
-						$parameters = $property->parameters();
3325
-						$indexedParametersForProperty = self::$indexParameters[$property->name];
3326
-
3327
-						foreach ($parameters as $key => $value) {
3328
-							if (in_array($key, $indexedParametersForProperty)) {
3329
-								// is this a shitty db?
3330
-								if ($this->db->supports4ByteText()) {
3331
-									$value = preg_replace('/[\x{10000}-\x{10FFFF}]/u', "\xEF\xBF\xBD", $value);
3332
-								}
3333
-
3334
-								$query->setParameter('name', $property->name);
3335
-								$query->setParameter('parameter', mb_strcut($key, 0, 254));
3336
-								$query->setParameter('value', mb_strcut($value, 0, 254));
3337
-								$query->executeStatement();
3338
-							}
3339
-						}
3340
-					}
3341
-				}
3342
-			}
3343
-		}, $this->db);
3344
-	}
3345
-
3346
-	/**
3347
-	 * deletes all birthday calendars
3348
-	 */
3349
-	public function deleteAllBirthdayCalendars() {
3350
-		$this->atomic(function (): void {
3351
-			$query = $this->db->getQueryBuilder();
3352
-			$result = $query->select(['id'])->from('calendars')
3353
-				->where($query->expr()->eq('uri', $query->createNamedParameter(BirthdayService::BIRTHDAY_CALENDAR_URI)))
3354
-				->executeQuery();
3355
-
3356
-			while (($row = $result->fetch()) !== false) {
3357
-				$this->deleteCalendar(
3358
-					$row['id'],
3359
-					true // No data to keep in the trashbin, if the user re-enables then we regenerate
3360
-				);
3361
-			}
3362
-			$result->closeCursor();
3363
-		}, $this->db);
3364
-	}
3365
-
3366
-	/**
3367
-	 * @param $subscriptionId
3368
-	 */
3369
-	public function purgeAllCachedEventsForSubscription($subscriptionId) {
3370
-		$this->atomic(function () use ($subscriptionId): void {
3371
-			$query = $this->db->getQueryBuilder();
3372
-			$query->select('uri')
3373
-				->from('calendarobjects')
3374
-				->where($query->expr()->eq('calendarid', $query->createNamedParameter($subscriptionId)))
3375
-				->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)));
3376
-			$stmt = $query->executeQuery();
3377
-
3378
-			$uris = [];
3379
-			while (($row = $stmt->fetch()) !== false) {
3380
-				$uris[] = $row['uri'];
3381
-			}
3382
-			$stmt->closeCursor();
3383
-
3384
-			$query = $this->db->getQueryBuilder();
3385
-			$query->delete('calendarobjects')
3386
-				->where($query->expr()->eq('calendarid', $query->createNamedParameter($subscriptionId)))
3387
-				->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)))
3388
-				->executeStatement();
3389
-
3390
-			$query = $this->db->getQueryBuilder();
3391
-			$query->delete('calendarchanges')
3392
-				->where($query->expr()->eq('calendarid', $query->createNamedParameter($subscriptionId)))
3393
-				->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)))
3394
-				->executeStatement();
3395
-
3396
-			$query = $this->db->getQueryBuilder();
3397
-			$query->delete($this->dbObjectPropertiesTable)
3398
-				->where($query->expr()->eq('calendarid', $query->createNamedParameter($subscriptionId)))
3399
-				->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)))
3400
-				->executeStatement();
3401
-
3402
-			$this->addChanges($subscriptionId, $uris, 3, self::CALENDAR_TYPE_SUBSCRIPTION);
3403
-		}, $this->db);
3404
-	}
3405
-
3406
-	/**
3407
-	 * @param int $subscriptionId
3408
-	 * @param array<int> $calendarObjectIds
3409
-	 * @param array<string> $calendarObjectUris
3410
-	 */
3411
-	public function purgeCachedEventsForSubscription(int $subscriptionId, array $calendarObjectIds, array $calendarObjectUris): void {
3412
-		if (empty($calendarObjectUris)) {
3413
-			return;
3414
-		}
3415
-
3416
-		$this->atomic(function () use ($subscriptionId, $calendarObjectIds, $calendarObjectUris): void {
3417
-			foreach (array_chunk($calendarObjectIds, 1000) as $chunk) {
3418
-				$query = $this->db->getQueryBuilder();
3419
-				$query->delete($this->dbObjectPropertiesTable)
3420
-					->where($query->expr()->eq('calendarid', $query->createNamedParameter($subscriptionId)))
3421
-					->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)))
3422
-					->andWhere($query->expr()->in('id', $query->createNamedParameter($chunk, IQueryBuilder::PARAM_INT_ARRAY), IQueryBuilder::PARAM_INT_ARRAY))
3423
-					->executeStatement();
3424
-
3425
-				$query = $this->db->getQueryBuilder();
3426
-				$query->delete('calendarobjects')
3427
-					->where($query->expr()->eq('calendarid', $query->createNamedParameter($subscriptionId)))
3428
-					->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)))
3429
-					->andWhere($query->expr()->in('id', $query->createNamedParameter($chunk, IQueryBuilder::PARAM_INT_ARRAY), IQueryBuilder::PARAM_INT_ARRAY))
3430
-					->executeStatement();
3431
-			}
3432
-
3433
-			foreach (array_chunk($calendarObjectUris, 1000) as $chunk) {
3434
-				$query = $this->db->getQueryBuilder();
3435
-				$query->delete('calendarchanges')
3436
-					->where($query->expr()->eq('calendarid', $query->createNamedParameter($subscriptionId)))
3437
-					->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)))
3438
-					->andWhere($query->expr()->in('uri', $query->createNamedParameter($chunk, IQueryBuilder::PARAM_STR_ARRAY), IQueryBuilder::PARAM_STR_ARRAY))
3439
-					->executeStatement();
3440
-			}
3441
-			$this->addChanges($subscriptionId, $calendarObjectUris, 3, self::CALENDAR_TYPE_SUBSCRIPTION);
3442
-		}, $this->db);
3443
-	}
3444
-
3445
-	/**
3446
-	 * Move a calendar from one user to another
3447
-	 *
3448
-	 * @param string $uriName
3449
-	 * @param string $uriOrigin
3450
-	 * @param string $uriDestination
3451
-	 * @param string $newUriName (optional) the new uriName
3452
-	 */
3453
-	public function moveCalendar($uriName, $uriOrigin, $uriDestination, $newUriName = null) {
3454
-		$query = $this->db->getQueryBuilder();
3455
-		$query->update('calendars')
3456
-			->set('principaluri', $query->createNamedParameter($uriDestination))
3457
-			->set('uri', $query->createNamedParameter($newUriName ?: $uriName))
3458
-			->where($query->expr()->eq('principaluri', $query->createNamedParameter($uriOrigin)))
3459
-			->andWhere($query->expr()->eq('uri', $query->createNamedParameter($uriName)))
3460
-			->executeStatement();
3461
-	}
3462
-
3463
-	/**
3464
-	 * read VCalendar data into a VCalendar object
3465
-	 *
3466
-	 * @param string $objectData
3467
-	 * @return VCalendar
3468
-	 */
3469
-	protected function readCalendarData($objectData) {
3470
-		return Reader::read($objectData);
3471
-	}
3472
-
3473
-	/**
3474
-	 * delete all properties from a given calendar object
3475
-	 *
3476
-	 * @param int $calendarId
3477
-	 * @param int $objectId
3478
-	 */
3479
-	protected function purgeProperties($calendarId, $objectId) {
3480
-		$this->cachedObjects = [];
3481
-		$query = $this->db->getQueryBuilder();
3482
-		$query->delete($this->dbObjectPropertiesTable)
3483
-			->where($query->expr()->eq('objectid', $query->createNamedParameter($objectId)))
3484
-			->andWhere($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)));
3485
-		$query->executeStatement();
3486
-	}
3487
-
3488
-	/**
3489
-	 * get ID from a given calendar object
3490
-	 *
3491
-	 * @param int $calendarId
3492
-	 * @param string $uri
3493
-	 * @param int $calendarType
3494
-	 * @return int
3495
-	 */
3496
-	protected function getCalendarObjectId($calendarId, $uri, $calendarType):int {
3497
-		$query = $this->db->getQueryBuilder();
3498
-		$query->select('id')
3499
-			->from('calendarobjects')
3500
-			->where($query->expr()->eq('uri', $query->createNamedParameter($uri)))
3501
-			->andWhere($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)))
3502
-			->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter($calendarType)));
3503
-
3504
-		$result = $query->executeQuery();
3505
-		$objectIds = $result->fetch();
3506
-		$result->closeCursor();
3507
-
3508
-		if (!isset($objectIds['id'])) {
3509
-			throw new \InvalidArgumentException('Calendarobject does not exists: ' . $uri);
3510
-		}
3511
-
3512
-		return (int)$objectIds['id'];
3513
-	}
3514
-
3515
-	/**
3516
-	 * @throws \InvalidArgumentException
3517
-	 */
3518
-	public function pruneOutdatedSyncTokens(int $keep, int $retention): int {
3519
-		if ($keep < 0) {
3520
-			throw new \InvalidArgumentException();
3521
-		}
3522
-
3523
-		$query = $this->db->getQueryBuilder();
3524
-		$query->select($query->func()->max('id'))
3525
-			->from('calendarchanges');
3526
-
3527
-		$result = $query->executeQuery();
3528
-		$maxId = (int)$result->fetchOne();
3529
-		$result->closeCursor();
3530
-		if (!$maxId || $maxId < $keep) {
3531
-			return 0;
3532
-		}
3533
-
3534
-		$query = $this->db->getQueryBuilder();
3535
-		$query->delete('calendarchanges')
3536
-			->where(
3537
-				$query->expr()->lte('id', $query->createNamedParameter($maxId - $keep, IQueryBuilder::PARAM_INT), IQueryBuilder::PARAM_INT),
3538
-				$query->expr()->lte('created_at', $query->createNamedParameter($retention)),
3539
-			);
3540
-		return $query->executeStatement();
3541
-	}
3542
-
3543
-	/**
3544
-	 * return legacy endpoint principal name to new principal name
3545
-	 *
3546
-	 * @param $principalUri
3547
-	 * @param $toV2
3548
-	 * @return string
3549
-	 */
3550
-	private function convertPrincipal($principalUri, $toV2) {
3551
-		if ($this->principalBackend->getPrincipalPrefix() === 'principals') {
3552
-			[, $name] = Uri\split($principalUri);
3553
-			if ($toV2 === true) {
3554
-				return "principals/users/$name";
3555
-			}
3556
-			return "principals/$name";
3557
-		}
3558
-		return $principalUri;
3559
-	}
3560
-
3561
-	/**
3562
-	 * adds information about an owner to the calendar data
3563
-	 *
3564
-	 */
3565
-	private function addOwnerPrincipalToCalendar(array $calendarInfo): array {
3566
-		$ownerPrincipalKey = '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal';
3567
-		$displaynameKey = '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_NEXTCLOUD . '}owner-displayname';
3568
-		if (isset($calendarInfo[$ownerPrincipalKey])) {
3569
-			$uri = $calendarInfo[$ownerPrincipalKey];
3570
-		} else {
3571
-			$uri = $calendarInfo['principaluri'];
3572
-		}
3573
-
3574
-		$principalInformation = $this->principalBackend->getPrincipalByPath($uri);
3575
-		if (isset($principalInformation['{DAV:}displayname'])) {
3576
-			$calendarInfo[$displaynameKey] = $principalInformation['{DAV:}displayname'];
3577
-		}
3578
-		return $calendarInfo;
3579
-	}
3580
-
3581
-	private function addResourceTypeToCalendar(array $row, array $calendar): array {
3582
-		if (isset($row['deleted_at'])) {
3583
-			// Columns is set and not null -> this is a deleted calendar
3584
-			// we send a custom resourcetype to hide the deleted calendar
3585
-			// from ordinary DAV clients, but the Calendar app will know
3586
-			// how to handle this special resource.
3587
-			$calendar['{DAV:}resourcetype'] = new DAV\Xml\Property\ResourceType([
3588
-				'{DAV:}collection',
3589
-				sprintf('{%s}deleted-calendar', \OCA\DAV\DAV\Sharing\Plugin::NS_NEXTCLOUD),
3590
-			]);
3591
-		}
3592
-		return $calendar;
3593
-	}
3594
-
3595
-	/**
3596
-	 * Amend the calendar info with database row data
3597
-	 *
3598
-	 * @param array $row
3599
-	 * @param array $calendar
3600
-	 *
3601
-	 * @return array
3602
-	 */
3603
-	private function rowToCalendar($row, array $calendar): array {
3604
-		foreach ($this->propertyMap as $xmlName => [$dbName, $type]) {
3605
-			$value = $row[$dbName];
3606
-			if ($value !== null) {
3607
-				settype($value, $type);
3608
-			}
3609
-			$calendar[$xmlName] = $value;
3610
-		}
3611
-		return $calendar;
3612
-	}
3613
-
3614
-	/**
3615
-	 * Amend the subscription info with database row data
3616
-	 *
3617
-	 * @param array $row
3618
-	 * @param array $subscription
3619
-	 *
3620
-	 * @return array
3621
-	 */
3622
-	private function rowToSubscription($row, array $subscription): array {
3623
-		foreach ($this->subscriptionPropertyMap as $xmlName => [$dbName, $type]) {
3624
-			$value = $row[$dbName];
3625
-			if ($value !== null) {
3626
-				settype($value, $type);
3627
-			}
3628
-			$subscription[$xmlName] = $value;
3629
-		}
3630
-		return $subscription;
3631
-	}
3632
-
3633
-	/**
3634
-	 * delete all invitations from a given calendar
3635
-	 *
3636
-	 * @since 31.0.0
3637
-	 *
3638
-	 * @param int $calendarId
3639
-	 *
3640
-	 * @return void
3641
-	 */
3642
-	protected function purgeCalendarInvitations(int $calendarId): void {
3643
-		// select all calendar object uid's
3644
-		$cmd = $this->db->getQueryBuilder();
3645
-		$cmd->select('uid')
3646
-			->from($this->dbObjectsTable)
3647
-			->where($cmd->expr()->eq('calendarid', $cmd->createNamedParameter($calendarId)));
3648
-		$allIds = $cmd->executeQuery()->fetchAll(\PDO::FETCH_COLUMN);
3649
-		// delete all links that match object uid's
3650
-		$cmd = $this->db->getQueryBuilder();
3651
-		$cmd->delete($this->dbObjectInvitationsTable)
3652
-			->where($cmd->expr()->in('uid', $cmd->createParameter('uids'), IQueryBuilder::PARAM_STR_ARRAY));
3653
-		foreach (array_chunk($allIds, 1000) as $chunkIds) {
3654
-			$cmd->setParameter('uids', $chunkIds, IQueryBuilder::PARAM_STR_ARRAY);
3655
-			$cmd->executeStatement();
3656
-		}
3657
-	}
3658
-
3659
-	/**
3660
-	 * Delete all invitations from a given calendar event
3661
-	 *
3662
-	 * @since 31.0.0
3663
-	 *
3664
-	 * @param string $eventId UID of the event
3665
-	 *
3666
-	 * @return void
3667
-	 */
3668
-	protected function purgeObjectInvitations(string $eventId): void {
3669
-		$cmd = $this->db->getQueryBuilder();
3670
-		$cmd->delete($this->dbObjectInvitationsTable)
3671
-			->where($cmd->expr()->eq('uid', $cmd->createNamedParameter($eventId, IQueryBuilder::PARAM_STR), IQueryBuilder::PARAM_STR));
3672
-		$cmd->executeStatement();
3673
-	}
1030
+    /**
1031
+     * Returns all calendar objects with limited metadata for a calendar
1032
+     *
1033
+     * Every item contains an array with the following keys:
1034
+     *   * id - the table row id
1035
+     *   * etag - An arbitrary string
1036
+     *   * uri - a unique key which will be used to construct the uri. This can
1037
+     *     be any arbitrary string.
1038
+     *   * calendardata - The iCalendar-compatible calendar data
1039
+     *
1040
+     * @param mixed $calendarId
1041
+     * @param int $calendarType
1042
+     * @return array
1043
+     */
1044
+    public function getLimitedCalendarObjects(int $calendarId, int $calendarType = self::CALENDAR_TYPE_CALENDAR):array {
1045
+        $query = $this->db->getQueryBuilder();
1046
+        $query->select(['id','uid', 'etag', 'uri', 'calendardata'])
1047
+            ->from('calendarobjects')
1048
+            ->where($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)))
1049
+            ->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter($calendarType)))
1050
+            ->andWhere($query->expr()->isNull('deleted_at'));
1051
+        $stmt = $query->executeQuery();
1052
+
1053
+        $result = [];
1054
+        while (($row = $stmt->fetch()) !== false) {
1055
+            $result[$row['uid']] = [
1056
+                'id' => $row['id'],
1057
+                'etag' => $row['etag'],
1058
+                'uri' => $row['uri'],
1059
+                'calendardata' => $row['calendardata'],
1060
+            ];
1061
+        }
1062
+        $stmt->closeCursor();
1063
+
1064
+        return $result;
1065
+    }
1066
+
1067
+    /**
1068
+     * Delete all of an user's shares
1069
+     *
1070
+     * @param string $principaluri
1071
+     * @return void
1072
+     */
1073
+    public function deleteAllSharesByUser($principaluri) {
1074
+        $this->calendarSharingBackend->deleteAllSharesByUser($principaluri);
1075
+    }
1076
+
1077
+    /**
1078
+     * Returns all calendar objects within a calendar.
1079
+     *
1080
+     * Every item contains an array with the following keys:
1081
+     *   * calendardata - The iCalendar-compatible calendar data
1082
+     *   * uri - a unique key which will be used to construct the uri. This can
1083
+     *     be any arbitrary string, but making sure it ends with '.ics' is a
1084
+     *     good idea. This is only the basename, or filename, not the full
1085
+     *     path.
1086
+     *   * lastmodified - a timestamp of the last modification time
1087
+     *   * etag - An arbitrary string, surrounded by double-quotes. (e.g.:
1088
+     *   '"abcdef"')
1089
+     *   * size - The size of the calendar objects, in bytes.
1090
+     *   * component - optional, a string containing the type of object, such
1091
+     *     as 'vevent' or 'vtodo'. If specified, this will be used to populate
1092
+     *     the Content-Type header.
1093
+     *
1094
+     * Note that the etag is optional, but it's highly encouraged to return for
1095
+     * speed reasons.
1096
+     *
1097
+     * The calendardata is also optional. If it's not returned
1098
+     * 'getCalendarObject' will be called later, which *is* expected to return
1099
+     * calendardata.
1100
+     *
1101
+     * If neither etag or size are specified, the calendardata will be
1102
+     * used/fetched to determine these numbers. If both are specified the
1103
+     * amount of times this is needed is reduced by a great degree.
1104
+     *
1105
+     * @param mixed $calendarId
1106
+     * @param int $calendarType
1107
+     * @return array
1108
+     */
1109
+    public function getCalendarObjects($calendarId, $calendarType = self::CALENDAR_TYPE_CALENDAR):array {
1110
+        $query = $this->db->getQueryBuilder();
1111
+        $query->select(['id', 'uri', 'lastmodified', 'etag', 'calendarid', 'size', 'componenttype', 'classification'])
1112
+            ->from('calendarobjects')
1113
+            ->where($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)))
1114
+            ->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter($calendarType)))
1115
+            ->andWhere($query->expr()->isNull('deleted_at'));
1116
+        $stmt = $query->executeQuery();
1117
+
1118
+        $result = [];
1119
+        while (($row = $stmt->fetch()) !== false) {
1120
+            $result[] = [
1121
+                'id' => $row['id'],
1122
+                'uri' => $row['uri'],
1123
+                'lastmodified' => $row['lastmodified'],
1124
+                'etag' => '"' . $row['etag'] . '"',
1125
+                'calendarid' => $row['calendarid'],
1126
+                'size' => (int)$row['size'],
1127
+                'component' => strtolower($row['componenttype']),
1128
+                'classification' => (int)$row['classification']
1129
+            ];
1130
+        }
1131
+        $stmt->closeCursor();
1132
+
1133
+        return $result;
1134
+    }
1135
+
1136
+    public function getDeletedCalendarObjects(int $deletedBefore): array {
1137
+        $query = $this->db->getQueryBuilder();
1138
+        $query->select(['co.id', 'co.uri', 'co.lastmodified', 'co.etag', 'co.calendarid', 'co.calendartype', 'co.size', 'co.componenttype', 'co.classification', 'co.deleted_at'])
1139
+            ->from('calendarobjects', 'co')
1140
+            ->join('co', 'calendars', 'c', $query->expr()->eq('c.id', 'co.calendarid', IQueryBuilder::PARAM_INT))
1141
+            ->where($query->expr()->isNotNull('co.deleted_at'))
1142
+            ->andWhere($query->expr()->lt('co.deleted_at', $query->createNamedParameter($deletedBefore)));
1143
+        $stmt = $query->executeQuery();
1144
+
1145
+        $result = [];
1146
+        while (($row = $stmt->fetch()) !== false) {
1147
+            $result[] = [
1148
+                'id' => $row['id'],
1149
+                'uri' => $row['uri'],
1150
+                'lastmodified' => $row['lastmodified'],
1151
+                'etag' => '"' . $row['etag'] . '"',
1152
+                'calendarid' => (int)$row['calendarid'],
1153
+                'calendartype' => (int)$row['calendartype'],
1154
+                'size' => (int)$row['size'],
1155
+                'component' => strtolower($row['componenttype']),
1156
+                'classification' => (int)$row['classification'],
1157
+                '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_NEXTCLOUD . '}deleted-at' => $row['deleted_at'] === null ? $row['deleted_at'] : (int)$row['deleted_at'],
1158
+            ];
1159
+        }
1160
+        $stmt->closeCursor();
1161
+
1162
+        return $result;
1163
+    }
1164
+
1165
+    /**
1166
+     * Return all deleted calendar objects by the given principal that are not
1167
+     * in deleted calendars.
1168
+     *
1169
+     * @param string $principalUri
1170
+     * @return array
1171
+     * @throws Exception
1172
+     */
1173
+    public function getDeletedCalendarObjectsByPrincipal(string $principalUri): array {
1174
+        $query = $this->db->getQueryBuilder();
1175
+        $query->select(['co.id', 'co.uri', 'co.lastmodified', 'co.etag', 'co.calendarid', 'co.size', 'co.componenttype', 'co.classification', 'co.deleted_at'])
1176
+            ->selectAlias('c.uri', 'calendaruri')
1177
+            ->from('calendarobjects', 'co')
1178
+            ->join('co', 'calendars', 'c', $query->expr()->eq('c.id', 'co.calendarid', IQueryBuilder::PARAM_INT))
1179
+            ->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
1180
+            ->andWhere($query->expr()->isNotNull('co.deleted_at'))
1181
+            ->andWhere($query->expr()->isNull('c.deleted_at'));
1182
+        $stmt = $query->executeQuery();
1183
+
1184
+        $result = [];
1185
+        while ($row = $stmt->fetch()) {
1186
+            $result[] = [
1187
+                'id' => $row['id'],
1188
+                'uri' => $row['uri'],
1189
+                'lastmodified' => $row['lastmodified'],
1190
+                'etag' => '"' . $row['etag'] . '"',
1191
+                'calendarid' => $row['calendarid'],
1192
+                'calendaruri' => $row['calendaruri'],
1193
+                'size' => (int)$row['size'],
1194
+                'component' => strtolower($row['componenttype']),
1195
+                'classification' => (int)$row['classification'],
1196
+                '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_NEXTCLOUD . '}deleted-at' => $row['deleted_at'] === null ? $row['deleted_at'] : (int)$row['deleted_at'],
1197
+            ];
1198
+        }
1199
+        $stmt->closeCursor();
1200
+
1201
+        return $result;
1202
+    }
1203
+
1204
+    /**
1205
+     * Returns information from a single calendar object, based on it's object
1206
+     * uri.
1207
+     *
1208
+     * The object uri is only the basename, or filename and not a full path.
1209
+     *
1210
+     * The returned array must have the same keys as getCalendarObjects. The
1211
+     * 'calendardata' object is required here though, while it's not required
1212
+     * for getCalendarObjects.
1213
+     *
1214
+     * This method must return null if the object did not exist.
1215
+     *
1216
+     * @param mixed $calendarId
1217
+     * @param string $objectUri
1218
+     * @param int $calendarType
1219
+     * @return array|null
1220
+     */
1221
+    public function getCalendarObject($calendarId, $objectUri, int $calendarType = self::CALENDAR_TYPE_CALENDAR) {
1222
+        $key = $calendarId . '::' . $objectUri . '::' . $calendarType;
1223
+        if (isset($this->cachedObjects[$key])) {
1224
+            return $this->cachedObjects[$key];
1225
+        }
1226
+        $query = $this->db->getQueryBuilder();
1227
+        $query->select(['id', 'uri', 'uid', 'lastmodified', 'etag', 'calendarid', 'size', 'calendardata', 'componenttype', 'classification', 'deleted_at'])
1228
+            ->from('calendarobjects')
1229
+            ->where($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)))
1230
+            ->andWhere($query->expr()->eq('uri', $query->createNamedParameter($objectUri)))
1231
+            ->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter($calendarType)));
1232
+        $stmt = $query->executeQuery();
1233
+        $row = $stmt->fetch();
1234
+        $stmt->closeCursor();
1235
+
1236
+        if (!$row) {
1237
+            return null;
1238
+        }
1239
+
1240
+        $object = $this->rowToCalendarObject($row);
1241
+        $this->cachedObjects[$key] = $object;
1242
+        return $object;
1243
+    }
1244
+
1245
+    private function rowToCalendarObject(array $row): array {
1246
+        return [
1247
+            'id' => $row['id'],
1248
+            'uri' => $row['uri'],
1249
+            'uid' => $row['uid'],
1250
+            'lastmodified' => $row['lastmodified'],
1251
+            'etag' => '"' . $row['etag'] . '"',
1252
+            'calendarid' => $row['calendarid'],
1253
+            'size' => (int)$row['size'],
1254
+            'calendardata' => $this->readBlob($row['calendardata']),
1255
+            'component' => strtolower($row['componenttype']),
1256
+            'classification' => (int)$row['classification'],
1257
+            '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_NEXTCLOUD . '}deleted-at' => $row['deleted_at'] === null ? $row['deleted_at'] : (int)$row['deleted_at'],
1258
+        ];
1259
+    }
1260
+
1261
+    /**
1262
+     * Returns a list of calendar objects.
1263
+     *
1264
+     * This method should work identical to getCalendarObject, but instead
1265
+     * return all the calendar objects in the list as an array.
1266
+     *
1267
+     * If the backend supports this, it may allow for some speed-ups.
1268
+     *
1269
+     * @param mixed $calendarId
1270
+     * @param string[] $uris
1271
+     * @param int $calendarType
1272
+     * @return array
1273
+     */
1274
+    public function getMultipleCalendarObjects($calendarId, array $uris, $calendarType = self::CALENDAR_TYPE_CALENDAR):array {
1275
+        if (empty($uris)) {
1276
+            return [];
1277
+        }
1278
+
1279
+        $chunks = array_chunk($uris, 100);
1280
+        $objects = [];
1281
+
1282
+        $query = $this->db->getQueryBuilder();
1283
+        $query->select(['id', 'uri', 'lastmodified', 'etag', 'calendarid', 'size', 'calendardata', 'componenttype', 'classification'])
1284
+            ->from('calendarobjects')
1285
+            ->where($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)))
1286
+            ->andWhere($query->expr()->in('uri', $query->createParameter('uri')))
1287
+            ->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter($calendarType)))
1288
+            ->andWhere($query->expr()->isNull('deleted_at'));
1289
+
1290
+        foreach ($chunks as $uris) {
1291
+            $query->setParameter('uri', $uris, IQueryBuilder::PARAM_STR_ARRAY);
1292
+            $result = $query->executeQuery();
1293
+
1294
+            while ($row = $result->fetch()) {
1295
+                $objects[] = [
1296
+                    'id' => $row['id'],
1297
+                    'uri' => $row['uri'],
1298
+                    'lastmodified' => $row['lastmodified'],
1299
+                    'etag' => '"' . $row['etag'] . '"',
1300
+                    'calendarid' => $row['calendarid'],
1301
+                    'size' => (int)$row['size'],
1302
+                    'calendardata' => $this->readBlob($row['calendardata']),
1303
+                    'component' => strtolower($row['componenttype']),
1304
+                    'classification' => (int)$row['classification']
1305
+                ];
1306
+            }
1307
+            $result->closeCursor();
1308
+        }
1309
+
1310
+        return $objects;
1311
+    }
1312
+
1313
+    /**
1314
+     * Creates a new calendar object.
1315
+     *
1316
+     * The object uri is only the basename, or filename and not a full path.
1317
+     *
1318
+     * It is possible return an etag from this function, which will be used in
1319
+     * the response to this PUT request. Note that the ETag must be surrounded
1320
+     * by double-quotes.
1321
+     *
1322
+     * However, you should only really return this ETag if you don't mangle the
1323
+     * calendar-data. If the result of a subsequent GET to this object is not
1324
+     * the exact same as this request body, you should omit the ETag.
1325
+     *
1326
+     * @param mixed $calendarId
1327
+     * @param string $objectUri
1328
+     * @param string $calendarData
1329
+     * @param int $calendarType
1330
+     * @return string
1331
+     */
1332
+    public function createCalendarObject($calendarId, $objectUri, $calendarData, $calendarType = self::CALENDAR_TYPE_CALENDAR) {
1333
+        $this->cachedObjects = [];
1334
+        $extraData = $this->getDenormalizedData($calendarData);
1335
+
1336
+        return $this->atomic(function () use ($calendarId, $objectUri, $calendarData, $extraData, $calendarType) {
1337
+            // Try to detect duplicates
1338
+            $qb = $this->db->getQueryBuilder();
1339
+            $qb->select($qb->func()->count('*'))
1340
+                ->from('calendarobjects')
1341
+                ->where($qb->expr()->eq('calendarid', $qb->createNamedParameter($calendarId)))
1342
+                ->andWhere($qb->expr()->eq('uid', $qb->createNamedParameter($extraData['uid'])))
1343
+                ->andWhere($qb->expr()->eq('calendartype', $qb->createNamedParameter($calendarType)))
1344
+                ->andWhere($qb->expr()->isNull('deleted_at'));
1345
+            $result = $qb->executeQuery();
1346
+            $count = (int)$result->fetchOne();
1347
+            $result->closeCursor();
1348
+
1349
+            if ($count !== 0) {
1350
+                throw new BadRequest('Calendar object with uid already exists in this calendar collection.');
1351
+            }
1352
+            // For a more specific error message we also try to explicitly look up the UID but as a deleted entry
1353
+            $qbDel = $this->db->getQueryBuilder();
1354
+            $qbDel->select('*')
1355
+                ->from('calendarobjects')
1356
+                ->where($qbDel->expr()->eq('calendarid', $qbDel->createNamedParameter($calendarId)))
1357
+                ->andWhere($qbDel->expr()->eq('uid', $qbDel->createNamedParameter($extraData['uid'])))
1358
+                ->andWhere($qbDel->expr()->eq('calendartype', $qbDel->createNamedParameter($calendarType)))
1359
+                ->andWhere($qbDel->expr()->isNotNull('deleted_at'));
1360
+            $result = $qbDel->executeQuery();
1361
+            $found = $result->fetch();
1362
+            $result->closeCursor();
1363
+            if ($found !== false) {
1364
+                // the object existed previously but has been deleted
1365
+                // remove the trashbin entry and continue as if it was a new object
1366
+                $this->deleteCalendarObject($calendarId, $found['uri']);
1367
+            }
1368
+
1369
+            $query = $this->db->getQueryBuilder();
1370
+            $query->insert('calendarobjects')
1371
+                ->values([
1372
+                    'calendarid' => $query->createNamedParameter($calendarId),
1373
+                    'uri' => $query->createNamedParameter($objectUri),
1374
+                    'calendardata' => $query->createNamedParameter($calendarData, IQueryBuilder::PARAM_LOB),
1375
+                    'lastmodified' => $query->createNamedParameter(time()),
1376
+                    'etag' => $query->createNamedParameter($extraData['etag']),
1377
+                    'size' => $query->createNamedParameter($extraData['size']),
1378
+                    'componenttype' => $query->createNamedParameter($extraData['componentType']),
1379
+                    'firstoccurence' => $query->createNamedParameter($extraData['firstOccurence']),
1380
+                    'lastoccurence' => $query->createNamedParameter($extraData['lastOccurence']),
1381
+                    'classification' => $query->createNamedParameter($extraData['classification']),
1382
+                    'uid' => $query->createNamedParameter($extraData['uid']),
1383
+                    'calendartype' => $query->createNamedParameter($calendarType),
1384
+                ])
1385
+                ->executeStatement();
1386
+
1387
+            $this->updateProperties($calendarId, $objectUri, $calendarData, $calendarType);
1388
+            $this->addChanges($calendarId, [$objectUri], 1, $calendarType);
1389
+
1390
+            $objectRow = $this->getCalendarObject($calendarId, $objectUri, $calendarType);
1391
+            assert($objectRow !== null);
1392
+
1393
+            if ($calendarType === self::CALENDAR_TYPE_CALENDAR) {
1394
+                $calendarRow = $this->getCalendarById($calendarId);
1395
+                $shares = $this->getShares($calendarId);
1396
+
1397
+                $this->dispatcher->dispatchTyped(new CalendarObjectCreatedEvent($calendarId, $calendarRow, $shares, $objectRow));
1398
+            } else {
1399
+                $subscriptionRow = $this->getSubscriptionById($calendarId);
1400
+
1401
+                $this->dispatcher->dispatchTyped(new CachedCalendarObjectCreatedEvent($calendarId, $subscriptionRow, [], $objectRow));
1402
+            }
1403
+
1404
+            return '"' . $extraData['etag'] . '"';
1405
+        }, $this->db);
1406
+    }
1407
+
1408
+    /**
1409
+     * Updates an existing calendarobject, based on it's uri.
1410
+     *
1411
+     * The object uri is only the basename, or filename and not a full path.
1412
+     *
1413
+     * It is possible return an etag from this function, which will be used in
1414
+     * the response to this PUT request. Note that the ETag must be surrounded
1415
+     * by double-quotes.
1416
+     *
1417
+     * However, you should only really return this ETag if you don't mangle the
1418
+     * calendar-data. If the result of a subsequent GET to this object is not
1419
+     * the exact same as this request body, you should omit the ETag.
1420
+     *
1421
+     * @param mixed $calendarId
1422
+     * @param string $objectUri
1423
+     * @param string $calendarData
1424
+     * @param int $calendarType
1425
+     * @return string
1426
+     */
1427
+    public function updateCalendarObject($calendarId, $objectUri, $calendarData, $calendarType = self::CALENDAR_TYPE_CALENDAR) {
1428
+        $this->cachedObjects = [];
1429
+        $extraData = $this->getDenormalizedData($calendarData);
1430
+
1431
+        return $this->atomic(function () use ($calendarId, $objectUri, $calendarData, $extraData, $calendarType) {
1432
+            $query = $this->db->getQueryBuilder();
1433
+            $query->update('calendarobjects')
1434
+                ->set('calendardata', $query->createNamedParameter($calendarData, IQueryBuilder::PARAM_LOB))
1435
+                ->set('lastmodified', $query->createNamedParameter(time()))
1436
+                ->set('etag', $query->createNamedParameter($extraData['etag']))
1437
+                ->set('size', $query->createNamedParameter($extraData['size']))
1438
+                ->set('componenttype', $query->createNamedParameter($extraData['componentType']))
1439
+                ->set('firstoccurence', $query->createNamedParameter($extraData['firstOccurence']))
1440
+                ->set('lastoccurence', $query->createNamedParameter($extraData['lastOccurence']))
1441
+                ->set('classification', $query->createNamedParameter($extraData['classification']))
1442
+                ->set('uid', $query->createNamedParameter($extraData['uid']))
1443
+                ->where($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)))
1444
+                ->andWhere($query->expr()->eq('uri', $query->createNamedParameter($objectUri)))
1445
+                ->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter($calendarType)))
1446
+                ->executeStatement();
1447
+
1448
+            $this->updateProperties($calendarId, $objectUri, $calendarData, $calendarType);
1449
+            $this->addChanges($calendarId, [$objectUri], 2, $calendarType);
1450
+
1451
+            $objectRow = $this->getCalendarObject($calendarId, $objectUri, $calendarType);
1452
+            if (is_array($objectRow)) {
1453
+                if ($calendarType === self::CALENDAR_TYPE_CALENDAR) {
1454
+                    $calendarRow = $this->getCalendarById($calendarId);
1455
+                    $shares = $this->getShares($calendarId);
1456
+
1457
+                    $this->dispatcher->dispatchTyped(new CalendarObjectUpdatedEvent($calendarId, $calendarRow, $shares, $objectRow));
1458
+                } else {
1459
+                    $subscriptionRow = $this->getSubscriptionById($calendarId);
1460
+
1461
+                    $this->dispatcher->dispatchTyped(new CachedCalendarObjectUpdatedEvent($calendarId, $subscriptionRow, [], $objectRow));
1462
+                }
1463
+            }
1464
+
1465
+            return '"' . $extraData['etag'] . '"';
1466
+        }, $this->db);
1467
+    }
1468
+
1469
+    /**
1470
+     * Moves a calendar object from calendar to calendar.
1471
+     *
1472
+     * @param string $sourcePrincipalUri
1473
+     * @param int $sourceObjectId
1474
+     * @param string $targetPrincipalUri
1475
+     * @param int $targetCalendarId
1476
+     * @param string $tragetObjectUri
1477
+     * @param int $calendarType
1478
+     * @return bool
1479
+     * @throws Exception
1480
+     */
1481
+    public function moveCalendarObject(string $sourcePrincipalUri, int $sourceObjectId, string $targetPrincipalUri, int $targetCalendarId, string $tragetObjectUri, int $calendarType = self::CALENDAR_TYPE_CALENDAR): bool {
1482
+        $this->cachedObjects = [];
1483
+        return $this->atomic(function () use ($sourcePrincipalUri, $sourceObjectId, $targetPrincipalUri, $targetCalendarId, $tragetObjectUri, $calendarType) {
1484
+            $object = $this->getCalendarObjectById($sourcePrincipalUri, $sourceObjectId);
1485
+            if (empty($object)) {
1486
+                return false;
1487
+            }
1488
+
1489
+            $sourceCalendarId = $object['calendarid'];
1490
+            $sourceObjectUri = $object['uri'];
1491
+
1492
+            $query = $this->db->getQueryBuilder();
1493
+            $query->update('calendarobjects')
1494
+                ->set('calendarid', $query->createNamedParameter($targetCalendarId, IQueryBuilder::PARAM_INT))
1495
+                ->set('uri', $query->createNamedParameter($tragetObjectUri, IQueryBuilder::PARAM_STR))
1496
+                ->where($query->expr()->eq('id', $query->createNamedParameter($sourceObjectId, IQueryBuilder::PARAM_INT), IQueryBuilder::PARAM_INT))
1497
+                ->executeStatement();
1498
+
1499
+            $this->purgeProperties($sourceCalendarId, $sourceObjectId);
1500
+            $this->updateProperties($targetCalendarId, $tragetObjectUri, $object['calendardata'], $calendarType);
1501
+
1502
+            $this->addChanges($sourceCalendarId, [$sourceObjectUri], 3, $calendarType);
1503
+            $this->addChanges($targetCalendarId, [$tragetObjectUri], 1, $calendarType);
1504
+
1505
+            $object = $this->getCalendarObjectById($targetPrincipalUri, $sourceObjectId);
1506
+            // Calendar Object wasn't found - possibly because it was deleted in the meantime by a different client
1507
+            if (empty($object)) {
1508
+                return false;
1509
+            }
1510
+
1511
+            $targetCalendarRow = $this->getCalendarById($targetCalendarId);
1512
+            // the calendar this event is being moved to does not exist any longer
1513
+            if (empty($targetCalendarRow)) {
1514
+                return false;
1515
+            }
1516
+
1517
+            if ($calendarType === self::CALENDAR_TYPE_CALENDAR) {
1518
+                $sourceShares = $this->getShares($sourceCalendarId);
1519
+                $targetShares = $this->getShares($targetCalendarId);
1520
+                $sourceCalendarRow = $this->getCalendarById($sourceCalendarId);
1521
+                $this->dispatcher->dispatchTyped(new CalendarObjectMovedEvent($sourceCalendarId, $sourceCalendarRow, $targetCalendarId, $targetCalendarRow, $sourceShares, $targetShares, $object));
1522
+            }
1523
+            return true;
1524
+        }, $this->db);
1525
+    }
1526
+
1527
+
1528
+    /**
1529
+     * @param int $calendarObjectId
1530
+     * @param int $classification
1531
+     */
1532
+    public function setClassification($calendarObjectId, $classification) {
1533
+        $this->cachedObjects = [];
1534
+        if (!in_array($classification, [
1535
+            self::CLASSIFICATION_PUBLIC, self::CLASSIFICATION_PRIVATE, self::CLASSIFICATION_CONFIDENTIAL
1536
+        ])) {
1537
+            throw new \InvalidArgumentException();
1538
+        }
1539
+        $query = $this->db->getQueryBuilder();
1540
+        $query->update('calendarobjects')
1541
+            ->set('classification', $query->createNamedParameter($classification))
1542
+            ->where($query->expr()->eq('id', $query->createNamedParameter($calendarObjectId)))
1543
+            ->executeStatement();
1544
+    }
1545
+
1546
+    /**
1547
+     * Deletes an existing calendar object.
1548
+     *
1549
+     * The object uri is only the basename, or filename and not a full path.
1550
+     *
1551
+     * @param mixed $calendarId
1552
+     * @param string $objectUri
1553
+     * @param int $calendarType
1554
+     * @param bool $forceDeletePermanently
1555
+     * @return void
1556
+     */
1557
+    public function deleteCalendarObject($calendarId, $objectUri, $calendarType = self::CALENDAR_TYPE_CALENDAR, bool $forceDeletePermanently = false) {
1558
+        $this->cachedObjects = [];
1559
+        $this->atomic(function () use ($calendarId, $objectUri, $calendarType, $forceDeletePermanently): void {
1560
+            $data = $this->getCalendarObject($calendarId, $objectUri, $calendarType);
1561
+
1562
+            if ($data === null) {
1563
+                // Nothing to delete
1564
+                return;
1565
+            }
1566
+
1567
+            if ($forceDeletePermanently || $this->config->getAppValue(Application::APP_ID, RetentionService::RETENTION_CONFIG_KEY) === '0') {
1568
+                $stmt = $this->db->prepare('DELETE FROM `*PREFIX*calendarobjects` WHERE `calendarid` = ? AND `uri` = ? AND `calendartype` = ?');
1569
+                $stmt->execute([$calendarId, $objectUri, $calendarType]);
1570
+
1571
+                $this->purgeProperties($calendarId, $data['id']);
1572
+
1573
+                $this->purgeObjectInvitations($data['uid']);
1574
+
1575
+                if ($calendarType === self::CALENDAR_TYPE_CALENDAR) {
1576
+                    $calendarRow = $this->getCalendarById($calendarId);
1577
+                    $shares = $this->getShares($calendarId);
1578
+
1579
+                    $this->dispatcher->dispatchTyped(new CalendarObjectDeletedEvent($calendarId, $calendarRow, $shares, $data));
1580
+                } else {
1581
+                    $subscriptionRow = $this->getSubscriptionById($calendarId);
1582
+
1583
+                    $this->dispatcher->dispatchTyped(new CachedCalendarObjectDeletedEvent($calendarId, $subscriptionRow, [], $data));
1584
+                }
1585
+            } else {
1586
+                $pathInfo = pathinfo($data['uri']);
1587
+                if (!empty($pathInfo['extension'])) {
1588
+                    // Append a suffix to "free" the old URI for recreation
1589
+                    $newUri = sprintf(
1590
+                        '%s-deleted.%s',
1591
+                        $pathInfo['filename'],
1592
+                        $pathInfo['extension']
1593
+                    );
1594
+                } else {
1595
+                    $newUri = sprintf(
1596
+                        '%s-deleted',
1597
+                        $pathInfo['filename']
1598
+                    );
1599
+                }
1600
+
1601
+                // Try to detect conflicts before the DB does
1602
+                // As unlikely as it seems, this can happen when the user imports, then deletes, imports and deletes again
1603
+                $newObject = $this->getCalendarObject($calendarId, $newUri, $calendarType);
1604
+                if ($newObject !== null) {
1605
+                    throw new Forbidden("A calendar object with URI $newUri already exists in calendar $calendarId, therefore this object can't be moved into the trashbin");
1606
+                }
1607
+
1608
+                $qb = $this->db->getQueryBuilder();
1609
+                $markObjectDeletedQuery = $qb->update('calendarobjects')
1610
+                    ->set('deleted_at', $qb->createNamedParameter(time(), IQueryBuilder::PARAM_INT))
1611
+                    ->set('uri', $qb->createNamedParameter($newUri))
1612
+                    ->where(
1613
+                        $qb->expr()->eq('calendarid', $qb->createNamedParameter($calendarId)),
1614
+                        $qb->expr()->eq('calendartype', $qb->createNamedParameter($calendarType, IQueryBuilder::PARAM_INT), IQueryBuilder::PARAM_INT),
1615
+                        $qb->expr()->eq('uri', $qb->createNamedParameter($objectUri))
1616
+                    );
1617
+                $markObjectDeletedQuery->executeStatement();
1618
+
1619
+                $calendarData = $this->getCalendarById($calendarId);
1620
+                if ($calendarData !== null) {
1621
+                    $this->dispatcher->dispatchTyped(
1622
+                        new CalendarObjectMovedToTrashEvent(
1623
+                            $calendarId,
1624
+                            $calendarData,
1625
+                            $this->getShares($calendarId),
1626
+                            $data
1627
+                        )
1628
+                    );
1629
+                }
1630
+            }
1631
+
1632
+            $this->addChanges($calendarId, [$objectUri], 3, $calendarType);
1633
+        }, $this->db);
1634
+    }
1635
+
1636
+    /**
1637
+     * @param mixed $objectData
1638
+     *
1639
+     * @throws Forbidden
1640
+     */
1641
+    public function restoreCalendarObject(array $objectData): void {
1642
+        $this->cachedObjects = [];
1643
+        $this->atomic(function () use ($objectData): void {
1644
+            $id = (int)$objectData['id'];
1645
+            $restoreUri = str_replace('-deleted.ics', '.ics', $objectData['uri']);
1646
+            $targetObject = $this->getCalendarObject(
1647
+                $objectData['calendarid'],
1648
+                $restoreUri
1649
+            );
1650
+            if ($targetObject !== null) {
1651
+                throw new Forbidden("Can not restore calendar $id because a calendar object with the URI $restoreUri already exists");
1652
+            }
1653
+
1654
+            $qb = $this->db->getQueryBuilder();
1655
+            $update = $qb->update('calendarobjects')
1656
+                ->set('uri', $qb->createNamedParameter($restoreUri))
1657
+                ->set('deleted_at', $qb->createNamedParameter(null))
1658
+                ->where($qb->expr()->eq('id', $qb->createNamedParameter($id, IQueryBuilder::PARAM_INT), IQueryBuilder::PARAM_INT));
1659
+            $update->executeStatement();
1660
+
1661
+            // Make sure this change is tracked in the changes table
1662
+            $qb2 = $this->db->getQueryBuilder();
1663
+            $selectObject = $qb2->select('calendardata', 'uri', 'calendarid', 'calendartype')
1664
+                ->selectAlias('componenttype', 'component')
1665
+                ->from('calendarobjects')
1666
+                ->where($qb2->expr()->eq('id', $qb2->createNamedParameter($id, IQueryBuilder::PARAM_INT), IQueryBuilder::PARAM_INT));
1667
+            $result = $selectObject->executeQuery();
1668
+            $row = $result->fetch();
1669
+            $result->closeCursor();
1670
+            if ($row === false) {
1671
+                // Welp, this should possibly not have happened, but let's ignore
1672
+                return;
1673
+            }
1674
+            $this->addChanges($row['calendarid'], [$row['uri']], 1, (int)$row['calendartype']);
1675
+
1676
+            $calendarRow = $this->getCalendarById((int)$row['calendarid']);
1677
+            if ($calendarRow === null) {
1678
+                throw new RuntimeException('Calendar object data that was just written can\'t be read back. Check your database configuration.');
1679
+            }
1680
+            $this->dispatcher->dispatchTyped(
1681
+                new CalendarObjectRestoredEvent(
1682
+                    (int)$objectData['calendarid'],
1683
+                    $calendarRow,
1684
+                    $this->getShares((int)$row['calendarid']),
1685
+                    $row
1686
+                )
1687
+            );
1688
+        }, $this->db);
1689
+    }
1690
+
1691
+    /**
1692
+     * Performs a calendar-query on the contents of this calendar.
1693
+     *
1694
+     * The calendar-query is defined in RFC4791 : CalDAV. Using the
1695
+     * calendar-query it is possible for a client to request a specific set of
1696
+     * object, based on contents of iCalendar properties, date-ranges and
1697
+     * iCalendar component types (VTODO, VEVENT).
1698
+     *
1699
+     * This method should just return a list of (relative) urls that match this
1700
+     * query.
1701
+     *
1702
+     * The list of filters are specified as an array. The exact array is
1703
+     * documented by Sabre\CalDAV\CalendarQueryParser.
1704
+     *
1705
+     * Note that it is extremely likely that getCalendarObject for every path
1706
+     * returned from this method will be called almost immediately after. You
1707
+     * may want to anticipate this to speed up these requests.
1708
+     *
1709
+     * This method provides a default implementation, which parses *all* the
1710
+     * iCalendar objects in the specified calendar.
1711
+     *
1712
+     * This default may well be good enough for personal use, and calendars
1713
+     * that aren't very large. But if you anticipate high usage, big calendars
1714
+     * or high loads, you are strongly advised to optimize certain paths.
1715
+     *
1716
+     * The best way to do so is override this method and to optimize
1717
+     * specifically for 'common filters'.
1718
+     *
1719
+     * Requests that are extremely common are:
1720
+     *   * requests for just VEVENTS
1721
+     *   * requests for just VTODO
1722
+     *   * requests with a time-range-filter on either VEVENT or VTODO.
1723
+     *
1724
+     * ..and combinations of these requests. It may not be worth it to try to
1725
+     * handle every possible situation and just rely on the (relatively
1726
+     * easy to use) CalendarQueryValidator to handle the rest.
1727
+     *
1728
+     * Note that especially time-range-filters may be difficult to parse. A
1729
+     * time-range filter specified on a VEVENT must for instance also handle
1730
+     * recurrence rules correctly.
1731
+     * A good example of how to interpret all these filters can also simply
1732
+     * be found in Sabre\CalDAV\CalendarQueryFilter. This class is as correct
1733
+     * as possible, so it gives you a good idea on what type of stuff you need
1734
+     * to think of.
1735
+     *
1736
+     * @param mixed $calendarId
1737
+     * @param array $filters
1738
+     * @param int $calendarType
1739
+     * @return array
1740
+     */
1741
+    public function calendarQuery($calendarId, array $filters, $calendarType = self::CALENDAR_TYPE_CALENDAR):array {
1742
+        $componentType = null;
1743
+        $requirePostFilter = true;
1744
+        $timeRange = null;
1745
+
1746
+        // if no filters were specified, we don't need to filter after a query
1747
+        if (!$filters['prop-filters'] && !$filters['comp-filters']) {
1748
+            $requirePostFilter = false;
1749
+        }
1750
+
1751
+        // Figuring out if there's a component filter
1752
+        if (count($filters['comp-filters']) > 0 && !$filters['comp-filters'][0]['is-not-defined']) {
1753
+            $componentType = $filters['comp-filters'][0]['name'];
1754
+
1755
+            // Checking if we need post-filters
1756
+            if (!$filters['prop-filters'] && !$filters['comp-filters'][0]['comp-filters'] && !$filters['comp-filters'][0]['time-range'] && !$filters['comp-filters'][0]['prop-filters']) {
1757
+                $requirePostFilter = false;
1758
+            }
1759
+            // There was a time-range filter
1760
+            if ($componentType === 'VEVENT' && isset($filters['comp-filters'][0]['time-range']) && is_array($filters['comp-filters'][0]['time-range'])) {
1761
+                $timeRange = $filters['comp-filters'][0]['time-range'];
1762
+
1763
+                // If start time OR the end time is not specified, we can do a
1764
+                // 100% accurate mysql query.
1765
+                if (!$filters['prop-filters'] && !$filters['comp-filters'][0]['comp-filters'] && !$filters['comp-filters'][0]['prop-filters'] && (!$timeRange['start'] || !$timeRange['end'])) {
1766
+                    $requirePostFilter = false;
1767
+                }
1768
+            }
1769
+        }
1770
+        $query = $this->db->getQueryBuilder();
1771
+        $query->select(['id', 'uri', 'uid', 'lastmodified', 'etag', 'calendarid', 'size', 'calendardata', 'componenttype', 'classification', 'deleted_at'])
1772
+            ->from('calendarobjects')
1773
+            ->where($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)))
1774
+            ->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter($calendarType)))
1775
+            ->andWhere($query->expr()->isNull('deleted_at'));
1776
+
1777
+        if ($componentType) {
1778
+            $query->andWhere($query->expr()->eq('componenttype', $query->createNamedParameter($componentType)));
1779
+        }
1780
+
1781
+        if ($timeRange && $timeRange['start']) {
1782
+            $query->andWhere($query->expr()->gt('lastoccurence', $query->createNamedParameter($timeRange['start']->getTimeStamp())));
1783
+        }
1784
+        if ($timeRange && $timeRange['end']) {
1785
+            $query->andWhere($query->expr()->lt('firstoccurence', $query->createNamedParameter($timeRange['end']->getTimeStamp())));
1786
+        }
1787
+
1788
+        $stmt = $query->executeQuery();
1789
+
1790
+        $result = [];
1791
+        while ($row = $stmt->fetch()) {
1792
+            // if we leave it as a blob we can't read it both from the post filter and the rowToCalendarObject
1793
+            if (isset($row['calendardata'])) {
1794
+                $row['calendardata'] = $this->readBlob($row['calendardata']);
1795
+            }
1796
+
1797
+            if ($requirePostFilter) {
1798
+                // validateFilterForObject will parse the calendar data
1799
+                // catch parsing errors
1800
+                try {
1801
+                    $matches = $this->validateFilterForObject($row, $filters);
1802
+                } catch (ParseException $ex) {
1803
+                    $this->logger->error('Caught parsing exception for calendar data. This usually indicates invalid calendar data. calendar-id:' . $calendarId . ' uri:' . $row['uri'], [
1804
+                        'app' => 'dav',
1805
+                        'exception' => $ex,
1806
+                    ]);
1807
+                    continue;
1808
+                } catch (InvalidDataException $ex) {
1809
+                    $this->logger->error('Caught invalid data exception for calendar data. This usually indicates invalid calendar data. calendar-id:' . $calendarId . ' uri:' . $row['uri'], [
1810
+                        'app' => 'dav',
1811
+                        'exception' => $ex,
1812
+                    ]);
1813
+                    continue;
1814
+                } catch (MaxInstancesExceededException $ex) {
1815
+                    $this->logger->warning('Caught max instances exceeded exception for calendar data. This usually indicates too much recurring (more than 3500) event in calendar data. Object uri: ' . $row['uri'], [
1816
+                        'app' => 'dav',
1817
+                        'exception' => $ex,
1818
+                    ]);
1819
+                    continue;
1820
+                }
1821
+
1822
+                if (!$matches) {
1823
+                    continue;
1824
+                }
1825
+            }
1826
+            $result[] = $row['uri'];
1827
+            $key = $calendarId . '::' . $row['uri'] . '::' . $calendarType;
1828
+            $this->cachedObjects[$key] = $this->rowToCalendarObject($row);
1829
+        }
1830
+
1831
+        return $result;
1832
+    }
1833
+
1834
+    /**
1835
+     * custom Nextcloud search extension for CalDAV
1836
+     *
1837
+     * TODO - this should optionally cover cached calendar objects as well
1838
+     *
1839
+     * @param string $principalUri
1840
+     * @param array $filters
1841
+     * @param integer|null $limit
1842
+     * @param integer|null $offset
1843
+     * @return array
1844
+     */
1845
+    public function calendarSearch($principalUri, array $filters, $limit = null, $offset = null) {
1846
+        return $this->atomic(function () use ($principalUri, $filters, $limit, $offset) {
1847
+            $calendars = $this->getCalendarsForUser($principalUri);
1848
+            $ownCalendars = [];
1849
+            $sharedCalendars = [];
1850
+
1851
+            $uriMapper = [];
1852
+
1853
+            foreach ($calendars as $calendar) {
1854
+                if ($calendar['{http://owncloud.org/ns}owner-principal'] === $principalUri) {
1855
+                    $ownCalendars[] = $calendar['id'];
1856
+                } else {
1857
+                    $sharedCalendars[] = $calendar['id'];
1858
+                }
1859
+                $uriMapper[$calendar['id']] = $calendar['uri'];
1860
+            }
1861
+            if (count($ownCalendars) === 0 && count($sharedCalendars) === 0) {
1862
+                return [];
1863
+            }
1864
+
1865
+            $query = $this->db->getQueryBuilder();
1866
+            // Calendar id expressions
1867
+            $calendarExpressions = [];
1868
+            foreach ($ownCalendars as $id) {
1869
+                $calendarExpressions[] = $query->expr()->andX(
1870
+                    $query->expr()->eq('c.calendarid',
1871
+                        $query->createNamedParameter($id)),
1872
+                    $query->expr()->eq('c.calendartype',
1873
+                        $query->createNamedParameter(self::CALENDAR_TYPE_CALENDAR)));
1874
+            }
1875
+            foreach ($sharedCalendars as $id) {
1876
+                $calendarExpressions[] = $query->expr()->andX(
1877
+                    $query->expr()->eq('c.calendarid',
1878
+                        $query->createNamedParameter($id)),
1879
+                    $query->expr()->eq('c.classification',
1880
+                        $query->createNamedParameter(self::CLASSIFICATION_PUBLIC)),
1881
+                    $query->expr()->eq('c.calendartype',
1882
+                        $query->createNamedParameter(self::CALENDAR_TYPE_CALENDAR)));
1883
+            }
1884
+
1885
+            if (count($calendarExpressions) === 1) {
1886
+                $calExpr = $calendarExpressions[0];
1887
+            } else {
1888
+                $calExpr = call_user_func_array([$query->expr(), 'orX'], $calendarExpressions);
1889
+            }
1890
+
1891
+            // Component expressions
1892
+            $compExpressions = [];
1893
+            foreach ($filters['comps'] as $comp) {
1894
+                $compExpressions[] = $query->expr()
1895
+                    ->eq('c.componenttype', $query->createNamedParameter($comp));
1896
+            }
1897
+
1898
+            if (count($compExpressions) === 1) {
1899
+                $compExpr = $compExpressions[0];
1900
+            } else {
1901
+                $compExpr = call_user_func_array([$query->expr(), 'orX'], $compExpressions);
1902
+            }
1903
+
1904
+            if (!isset($filters['props'])) {
1905
+                $filters['props'] = [];
1906
+            }
1907
+            if (!isset($filters['params'])) {
1908
+                $filters['params'] = [];
1909
+            }
1910
+
1911
+            $propParamExpressions = [];
1912
+            foreach ($filters['props'] as $prop) {
1913
+                $propParamExpressions[] = $query->expr()->andX(
1914
+                    $query->expr()->eq('i.name', $query->createNamedParameter($prop)),
1915
+                    $query->expr()->isNull('i.parameter')
1916
+                );
1917
+            }
1918
+            foreach ($filters['params'] as $param) {
1919
+                $propParamExpressions[] = $query->expr()->andX(
1920
+                    $query->expr()->eq('i.name', $query->createNamedParameter($param['property'])),
1921
+                    $query->expr()->eq('i.parameter', $query->createNamedParameter($param['parameter']))
1922
+                );
1923
+            }
1924
+
1925
+            if (count($propParamExpressions) === 1) {
1926
+                $propParamExpr = $propParamExpressions[0];
1927
+            } else {
1928
+                $propParamExpr = call_user_func_array([$query->expr(), 'orX'], $propParamExpressions);
1929
+            }
1930
+
1931
+            $query->select(['c.calendarid', 'c.uri'])
1932
+                ->from($this->dbObjectPropertiesTable, 'i')
1933
+                ->join('i', 'calendarobjects', 'c', $query->expr()->eq('i.objectid', 'c.id'))
1934
+                ->where($calExpr)
1935
+                ->andWhere($compExpr)
1936
+                ->andWhere($propParamExpr)
1937
+                ->andWhere($query->expr()->iLike('i.value',
1938
+                    $query->createNamedParameter('%' . $this->db->escapeLikeParameter($filters['search-term']) . '%')))
1939
+                ->andWhere($query->expr()->isNull('deleted_at'));
1940
+
1941
+            if ($offset) {
1942
+                $query->setFirstResult($offset);
1943
+            }
1944
+            if ($limit) {
1945
+                $query->setMaxResults($limit);
1946
+            }
1947
+
1948
+            $stmt = $query->executeQuery();
1949
+
1950
+            $result = [];
1951
+            while ($row = $stmt->fetch()) {
1952
+                $path = $uriMapper[$row['calendarid']] . '/' . $row['uri'];
1953
+                if (!in_array($path, $result)) {
1954
+                    $result[] = $path;
1955
+                }
1956
+            }
1957
+
1958
+            return $result;
1959
+        }, $this->db);
1960
+    }
1961
+
1962
+    /**
1963
+     * used for Nextcloud's calendar API
1964
+     *
1965
+     * @param array $calendarInfo
1966
+     * @param string $pattern
1967
+     * @param array $searchProperties
1968
+     * @param array $options
1969
+     * @param integer|null $limit
1970
+     * @param integer|null $offset
1971
+     *
1972
+     * @return array
1973
+     */
1974
+    public function search(
1975
+        array $calendarInfo,
1976
+        $pattern,
1977
+        array $searchProperties,
1978
+        array $options,
1979
+        $limit,
1980
+        $offset,
1981
+    ) {
1982
+        $outerQuery = $this->db->getQueryBuilder();
1983
+        $innerQuery = $this->db->getQueryBuilder();
1984
+
1985
+        if (isset($calendarInfo['source'])) {
1986
+            $calendarType = self::CALENDAR_TYPE_SUBSCRIPTION;
1987
+        } else {
1988
+            $calendarType = self::CALENDAR_TYPE_CALENDAR;
1989
+        }
1990
+
1991
+        $innerQuery->selectDistinct('op.objectid')
1992
+            ->from($this->dbObjectPropertiesTable, 'op')
1993
+            ->andWhere($innerQuery->expr()->eq('op.calendarid',
1994
+                $outerQuery->createNamedParameter($calendarInfo['id'])))
1995
+            ->andWhere($innerQuery->expr()->eq('op.calendartype',
1996
+                $outerQuery->createNamedParameter($calendarType)));
1997
+
1998
+        $outerQuery->select('c.id', 'c.calendardata', 'c.componenttype', 'c.uid', 'c.uri')
1999
+            ->from('calendarobjects', 'c')
2000
+            ->where($outerQuery->expr()->isNull('deleted_at'));
2001
+
2002
+        // only return public items for shared calendars for now
2003
+        if (isset($calendarInfo['{http://owncloud.org/ns}owner-principal']) === false || $calendarInfo['principaluri'] !== $calendarInfo['{http://owncloud.org/ns}owner-principal']) {
2004
+            $outerQuery->andWhere($outerQuery->expr()->eq('c.classification',
2005
+                $outerQuery->createNamedParameter(self::CLASSIFICATION_PUBLIC)));
2006
+        }
2007
+
2008
+        if (!empty($searchProperties)) {
2009
+            $or = [];
2010
+            foreach ($searchProperties as $searchProperty) {
2011
+                $or[] = $innerQuery->expr()->eq('op.name',
2012
+                    $outerQuery->createNamedParameter($searchProperty));
2013
+            }
2014
+            $innerQuery->andWhere($innerQuery->expr()->orX(...$or));
2015
+        }
2016
+
2017
+        if ($pattern !== '') {
2018
+            $innerQuery->andWhere($innerQuery->expr()->iLike('op.value',
2019
+                $outerQuery->createNamedParameter('%' .
2020
+                    $this->db->escapeLikeParameter($pattern) . '%')));
2021
+        }
2022
+
2023
+        $start = null;
2024
+        $end = null;
2025
+
2026
+        $hasLimit = is_int($limit);
2027
+        $hasTimeRange = false;
2028
+
2029
+        if (isset($options['timerange']['start']) && $options['timerange']['start'] instanceof DateTimeInterface) {
2030
+            /** @var DateTimeInterface $start */
2031
+            $start = $options['timerange']['start'];
2032
+            $outerQuery->andWhere(
2033
+                $outerQuery->expr()->gt(
2034
+                    'lastoccurence',
2035
+                    $outerQuery->createNamedParameter($start->getTimestamp())
2036
+                )
2037
+            );
2038
+            $hasTimeRange = true;
2039
+        }
2040
+
2041
+        if (isset($options['timerange']['end']) && $options['timerange']['end'] instanceof DateTimeInterface) {
2042
+            /** @var DateTimeInterface $end */
2043
+            $end = $options['timerange']['end'];
2044
+            $outerQuery->andWhere(
2045
+                $outerQuery->expr()->lt(
2046
+                    'firstoccurence',
2047
+                    $outerQuery->createNamedParameter($end->getTimestamp())
2048
+                )
2049
+            );
2050
+            $hasTimeRange = true;
2051
+        }
2052
+
2053
+        if (isset($options['uid'])) {
2054
+            $outerQuery->andWhere($outerQuery->expr()->eq('uid', $outerQuery->createNamedParameter($options['uid'])));
2055
+        }
2056
+
2057
+        if (!empty($options['types'])) {
2058
+            $or = [];
2059
+            foreach ($options['types'] as $type) {
2060
+                $or[] = $outerQuery->expr()->eq('componenttype',
2061
+                    $outerQuery->createNamedParameter($type));
2062
+            }
2063
+            $outerQuery->andWhere($outerQuery->expr()->orX(...$or));
2064
+        }
2065
+
2066
+        $outerQuery->andWhere($outerQuery->expr()->in('c.id', $outerQuery->createFunction($innerQuery->getSQL())));
2067
+
2068
+        // Without explicit order by its undefined in which order the SQL server returns the events.
2069
+        // For the pagination with hasLimit and hasTimeRange, a stable ordering is helpful.
2070
+        $outerQuery->addOrderBy('id');
2071
+
2072
+        $offset = (int)$offset;
2073
+        $outerQuery->setFirstResult($offset);
2074
+
2075
+        $calendarObjects = [];
2076
+
2077
+        if ($hasLimit && $hasTimeRange) {
2078
+            /**
2079
+             * Event recurrences are evaluated at runtime because the database only knows the first and last occurrence.
2080
+             *
2081
+             * Given, a user created 8 events with a yearly reoccurrence and two for events tomorrow.
2082
+             * The upcoming event widget asks the CalDAV backend for 7 events within the next 14 days.
2083
+             *
2084
+             * If limit 7 is applied to the SQL query, we find the 7 events with a yearly reoccurrence
2085
+             * and discard the events after evaluating the reoccurrence rules because they are not due within
2086
+             * the next 14 days and end up with an empty result even if there are two events to show.
2087
+             *
2088
+             * The workaround for search requests with a limit and time range is asking for more row than requested
2089
+             * and retrying if we have not reached the limit.
2090
+             *
2091
+             * 25 rows and 3 retries is entirely arbitrary.
2092
+             */
2093
+            $maxResults = (int)max($limit, 25);
2094
+            $outerQuery->setMaxResults($maxResults);
2095
+
2096
+            for ($attempt = $objectsCount = 0; $attempt < 3 && $objectsCount < $limit; $attempt++) {
2097
+                $objectsCount = array_push($calendarObjects, ...$this->searchCalendarObjects($outerQuery, $start, $end));
2098
+                $outerQuery->setFirstResult($offset += $maxResults);
2099
+            }
2100
+
2101
+            $calendarObjects = array_slice($calendarObjects, 0, $limit, false);
2102
+        } else {
2103
+            $outerQuery->setMaxResults($limit);
2104
+            $calendarObjects = $this->searchCalendarObjects($outerQuery, $start, $end);
2105
+        }
2106
+
2107
+        $calendarObjects = array_map(function ($o) use ($options) {
2108
+            $calendarData = Reader::read($o['calendardata']);
2109
+
2110
+            // Expand recurrences if an explicit time range is requested
2111
+            if ($calendarData instanceof VCalendar
2112
+                && isset($options['timerange']['start'], $options['timerange']['end'])) {
2113
+                $calendarData = $calendarData->expand(
2114
+                    $options['timerange']['start'],
2115
+                    $options['timerange']['end'],
2116
+                );
2117
+            }
2118
+
2119
+            $comps = $calendarData->getComponents();
2120
+            $objects = [];
2121
+            $timezones = [];
2122
+            foreach ($comps as $comp) {
2123
+                if ($comp instanceof VTimeZone) {
2124
+                    $timezones[] = $comp;
2125
+                } else {
2126
+                    $objects[] = $comp;
2127
+                }
2128
+            }
2129
+
2130
+            return [
2131
+                'id' => $o['id'],
2132
+                'type' => $o['componenttype'],
2133
+                'uid' => $o['uid'],
2134
+                'uri' => $o['uri'],
2135
+                'objects' => array_map(function ($c) {
2136
+                    return $this->transformSearchData($c);
2137
+                }, $objects),
2138
+                'timezones' => array_map(function ($c) {
2139
+                    return $this->transformSearchData($c);
2140
+                }, $timezones),
2141
+            ];
2142
+        }, $calendarObjects);
2143
+
2144
+        usort($calendarObjects, function (array $a, array $b) {
2145
+            /** @var DateTimeImmutable $startA */
2146
+            $startA = $a['objects'][0]['DTSTART'][0] ?? new DateTimeImmutable(self::MAX_DATE);
2147
+            /** @var DateTimeImmutable $startB */
2148
+            $startB = $b['objects'][0]['DTSTART'][0] ?? new DateTimeImmutable(self::MAX_DATE);
2149
+
2150
+            return $startA->getTimestamp() <=> $startB->getTimestamp();
2151
+        });
2152
+
2153
+        return $calendarObjects;
2154
+    }
2155
+
2156
+    private function searchCalendarObjects(IQueryBuilder $query, ?DateTimeInterface $start, ?DateTimeInterface $end): array {
2157
+        $calendarObjects = [];
2158
+        $filterByTimeRange = ($start instanceof DateTimeInterface) || ($end instanceof DateTimeInterface);
2159
+
2160
+        $result = $query->executeQuery();
2161
+
2162
+        while (($row = $result->fetch()) !== false) {
2163
+            if ($filterByTimeRange === false) {
2164
+                // No filter required
2165
+                $calendarObjects[] = $row;
2166
+                continue;
2167
+            }
2168
+
2169
+            try {
2170
+                $isValid = $this->validateFilterForObject($row, [
2171
+                    'name' => 'VCALENDAR',
2172
+                    'comp-filters' => [
2173
+                        [
2174
+                            'name' => 'VEVENT',
2175
+                            'comp-filters' => [],
2176
+                            'prop-filters' => [],
2177
+                            'is-not-defined' => false,
2178
+                            'time-range' => [
2179
+                                'start' => $start,
2180
+                                'end' => $end,
2181
+                            ],
2182
+                        ],
2183
+                    ],
2184
+                    'prop-filters' => [],
2185
+                    'is-not-defined' => false,
2186
+                    'time-range' => null,
2187
+                ]);
2188
+            } catch (MaxInstancesExceededException $ex) {
2189
+                $this->logger->warning('Caught max instances exceeded exception for calendar data. This usually indicates too much recurring (more than 3500) event in calendar data. Object uri: ' . $row['uri'], [
2190
+                    'app' => 'dav',
2191
+                    'exception' => $ex,
2192
+                ]);
2193
+                continue;
2194
+            }
2195
+
2196
+            if (is_resource($row['calendardata'])) {
2197
+                // Put the stream back to the beginning so it can be read another time
2198
+                rewind($row['calendardata']);
2199
+            }
2200
+
2201
+            if ($isValid) {
2202
+                $calendarObjects[] = $row;
2203
+            }
2204
+        }
2205
+
2206
+        $result->closeCursor();
2207
+
2208
+        return $calendarObjects;
2209
+    }
2210
+
2211
+    /**
2212
+     * @param Component $comp
2213
+     * @return array
2214
+     */
2215
+    private function transformSearchData(Component $comp) {
2216
+        $data = [];
2217
+        /** @var Component[] $subComponents */
2218
+        $subComponents = $comp->getComponents();
2219
+        /** @var Property[] $properties */
2220
+        $properties = array_filter($comp->children(), function ($c) {
2221
+            return $c instanceof Property;
2222
+        });
2223
+        $validationRules = $comp->getValidationRules();
2224
+
2225
+        foreach ($subComponents as $subComponent) {
2226
+            $name = $subComponent->name;
2227
+            if (!isset($data[$name])) {
2228
+                $data[$name] = [];
2229
+            }
2230
+            $data[$name][] = $this->transformSearchData($subComponent);
2231
+        }
2232
+
2233
+        foreach ($properties as $property) {
2234
+            $name = $property->name;
2235
+            if (!isset($validationRules[$name])) {
2236
+                $validationRules[$name] = '*';
2237
+            }
2238
+
2239
+            $rule = $validationRules[$property->name];
2240
+            if ($rule === '+' || $rule === '*') { // multiple
2241
+                if (!isset($data[$name])) {
2242
+                    $data[$name] = [];
2243
+                }
2244
+
2245
+                $data[$name][] = $this->transformSearchProperty($property);
2246
+            } else { // once
2247
+                $data[$name] = $this->transformSearchProperty($property);
2248
+            }
2249
+        }
2250
+
2251
+        return $data;
2252
+    }
2253
+
2254
+    /**
2255
+     * @param Property $prop
2256
+     * @return array
2257
+     */
2258
+    private function transformSearchProperty(Property $prop) {
2259
+        // No need to check Date, as it extends DateTime
2260
+        if ($prop instanceof Property\ICalendar\DateTime) {
2261
+            $value = $prop->getDateTime();
2262
+        } else {
2263
+            $value = $prop->getValue();
2264
+        }
2265
+
2266
+        return [
2267
+            $value,
2268
+            $prop->parameters()
2269
+        ];
2270
+    }
2271
+
2272
+    /**
2273
+     * @param string $principalUri
2274
+     * @param string $pattern
2275
+     * @param array $componentTypes
2276
+     * @param array $searchProperties
2277
+     * @param array $searchParameters
2278
+     * @param array $options
2279
+     * @return array
2280
+     */
2281
+    public function searchPrincipalUri(string $principalUri,
2282
+        string $pattern,
2283
+        array $componentTypes,
2284
+        array $searchProperties,
2285
+        array $searchParameters,
2286
+        array $options = [],
2287
+    ): array {
2288
+        return $this->atomic(function () use ($principalUri, $pattern, $componentTypes, $searchProperties, $searchParameters, $options) {
2289
+            $escapePattern = !\array_key_exists('escape_like_param', $options) || $options['escape_like_param'] !== false;
2290
+
2291
+            $calendarObjectIdQuery = $this->db->getQueryBuilder();
2292
+            $calendarOr = [];
2293
+            $searchOr = [];
2294
+
2295
+            // Fetch calendars and subscription
2296
+            $calendars = $this->getCalendarsForUser($principalUri);
2297
+            $subscriptions = $this->getSubscriptionsForUser($principalUri);
2298
+            foreach ($calendars as $calendar) {
2299
+                $calendarAnd = $calendarObjectIdQuery->expr()->andX(
2300
+                    $calendarObjectIdQuery->expr()->eq('cob.calendarid', $calendarObjectIdQuery->createNamedParameter((int)$calendar['id'])),
2301
+                    $calendarObjectIdQuery->expr()->eq('cob.calendartype', $calendarObjectIdQuery->createNamedParameter(self::CALENDAR_TYPE_CALENDAR)),
2302
+                );
2303
+
2304
+                // If it's shared, limit search to public events
2305
+                if (isset($calendar['{http://owncloud.org/ns}owner-principal'])
2306
+                    && $calendar['principaluri'] !== $calendar['{http://owncloud.org/ns}owner-principal']) {
2307
+                    $calendarAnd->add($calendarObjectIdQuery->expr()->eq('co.classification', $calendarObjectIdQuery->createNamedParameter(self::CLASSIFICATION_PUBLIC)));
2308
+                }
2309
+
2310
+                $calendarOr[] = $calendarAnd;
2311
+            }
2312
+            foreach ($subscriptions as $subscription) {
2313
+                $subscriptionAnd = $calendarObjectIdQuery->expr()->andX(
2314
+                    $calendarObjectIdQuery->expr()->eq('cob.calendarid', $calendarObjectIdQuery->createNamedParameter((int)$subscription['id'])),
2315
+                    $calendarObjectIdQuery->expr()->eq('cob.calendartype', $calendarObjectIdQuery->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)),
2316
+                );
2317
+
2318
+                // If it's shared, limit search to public events
2319
+                if (isset($subscription['{http://owncloud.org/ns}owner-principal'])
2320
+                    && $subscription['principaluri'] !== $subscription['{http://owncloud.org/ns}owner-principal']) {
2321
+                    $subscriptionAnd->add($calendarObjectIdQuery->expr()->eq('co.classification', $calendarObjectIdQuery->createNamedParameter(self::CLASSIFICATION_PUBLIC)));
2322
+                }
2323
+
2324
+                $calendarOr[] = $subscriptionAnd;
2325
+            }
2326
+
2327
+            foreach ($searchProperties as $property) {
2328
+                $propertyAnd = $calendarObjectIdQuery->expr()->andX(
2329
+                    $calendarObjectIdQuery->expr()->eq('cob.name', $calendarObjectIdQuery->createNamedParameter($property, IQueryBuilder::PARAM_STR)),
2330
+                    $calendarObjectIdQuery->expr()->isNull('cob.parameter'),
2331
+                );
2332
+
2333
+                $searchOr[] = $propertyAnd;
2334
+            }
2335
+            foreach ($searchParameters as $property => $parameter) {
2336
+                $parameterAnd = $calendarObjectIdQuery->expr()->andX(
2337
+                    $calendarObjectIdQuery->expr()->eq('cob.name', $calendarObjectIdQuery->createNamedParameter($property, IQueryBuilder::PARAM_STR)),
2338
+                    $calendarObjectIdQuery->expr()->eq('cob.parameter', $calendarObjectIdQuery->createNamedParameter($parameter, IQueryBuilder::PARAM_STR_ARRAY)),
2339
+                );
2340
+
2341
+                $searchOr[] = $parameterAnd;
2342
+            }
2343
+
2344
+            if (empty($calendarOr)) {
2345
+                return [];
2346
+            }
2347
+            if (empty($searchOr)) {
2348
+                return [];
2349
+            }
2350
+
2351
+            $calendarObjectIdQuery->selectDistinct('cob.objectid')
2352
+                ->from($this->dbObjectPropertiesTable, 'cob')
2353
+                ->leftJoin('cob', 'calendarobjects', 'co', $calendarObjectIdQuery->expr()->eq('co.id', 'cob.objectid'))
2354
+                ->andWhere($calendarObjectIdQuery->expr()->in('co.componenttype', $calendarObjectIdQuery->createNamedParameter($componentTypes, IQueryBuilder::PARAM_STR_ARRAY)))
2355
+                ->andWhere($calendarObjectIdQuery->expr()->orX(...$calendarOr))
2356
+                ->andWhere($calendarObjectIdQuery->expr()->orX(...$searchOr))
2357
+                ->andWhere($calendarObjectIdQuery->expr()->isNull('deleted_at'));
2358
+
2359
+            if ($pattern !== '') {
2360
+                if (!$escapePattern) {
2361
+                    $calendarObjectIdQuery->andWhere($calendarObjectIdQuery->expr()->ilike('cob.value', $calendarObjectIdQuery->createNamedParameter($pattern)));
2362
+                } else {
2363
+                    $calendarObjectIdQuery->andWhere($calendarObjectIdQuery->expr()->ilike('cob.value', $calendarObjectIdQuery->createNamedParameter('%' . $this->db->escapeLikeParameter($pattern) . '%')));
2364
+                }
2365
+            }
2366
+
2367
+            if (isset($options['limit'])) {
2368
+                $calendarObjectIdQuery->setMaxResults($options['limit']);
2369
+            }
2370
+            if (isset($options['offset'])) {
2371
+                $calendarObjectIdQuery->setFirstResult($options['offset']);
2372
+            }
2373
+            if (isset($options['timerange'])) {
2374
+                if (isset($options['timerange']['start']) && $options['timerange']['start'] instanceof DateTimeInterface) {
2375
+                    $calendarObjectIdQuery->andWhere($calendarObjectIdQuery->expr()->gt(
2376
+                        'lastoccurence',
2377
+                        $calendarObjectIdQuery->createNamedParameter($options['timerange']['start']->getTimeStamp()),
2378
+                    ));
2379
+                }
2380
+                if (isset($options['timerange']['end']) && $options['timerange']['end'] instanceof DateTimeInterface) {
2381
+                    $calendarObjectIdQuery->andWhere($calendarObjectIdQuery->expr()->lt(
2382
+                        'firstoccurence',
2383
+                        $calendarObjectIdQuery->createNamedParameter($options['timerange']['end']->getTimeStamp()),
2384
+                    ));
2385
+                }
2386
+            }
2387
+
2388
+            $result = $calendarObjectIdQuery->executeQuery();
2389
+            $matches = [];
2390
+            while (($row = $result->fetch()) !== false) {
2391
+                $matches[] = (int)$row['objectid'];
2392
+            }
2393
+            $result->closeCursor();
2394
+
2395
+            $query = $this->db->getQueryBuilder();
2396
+            $query->select('calendardata', 'uri', 'calendarid', 'calendartype')
2397
+                ->from('calendarobjects')
2398
+                ->where($query->expr()->in('id', $query->createNamedParameter($matches, IQueryBuilder::PARAM_INT_ARRAY)));
2399
+
2400
+            $result = $query->executeQuery();
2401
+            $calendarObjects = [];
2402
+            while (($array = $result->fetch()) !== false) {
2403
+                $array['calendarid'] = (int)$array['calendarid'];
2404
+                $array['calendartype'] = (int)$array['calendartype'];
2405
+                $array['calendardata'] = $this->readBlob($array['calendardata']);
2406
+
2407
+                $calendarObjects[] = $array;
2408
+            }
2409
+            $result->closeCursor();
2410
+            return $calendarObjects;
2411
+        }, $this->db);
2412
+    }
2413
+
2414
+    /**
2415
+     * Searches through all of a users calendars and calendar objects to find
2416
+     * an object with a specific UID.
2417
+     *
2418
+     * This method should return the path to this object, relative to the
2419
+     * calendar home, so this path usually only contains two parts:
2420
+     *
2421
+     * calendarpath/objectpath.ics
2422
+     *
2423
+     * If the uid is not found, return null.
2424
+     *
2425
+     * This method should only consider * objects that the principal owns, so
2426
+     * any calendars owned by other principals that also appear in this
2427
+     * collection should be ignored.
2428
+     *
2429
+     * @param string $principalUri
2430
+     * @param string $uid
2431
+     * @return string|null
2432
+     */
2433
+    public function getCalendarObjectByUID($principalUri, $uid) {
2434
+        $query = $this->db->getQueryBuilder();
2435
+        $query->selectAlias('c.uri', 'calendaruri')->selectAlias('co.uri', 'objecturi')
2436
+            ->from('calendarobjects', 'co')
2437
+            ->leftJoin('co', 'calendars', 'c', $query->expr()->eq('co.calendarid', 'c.id'))
2438
+            ->where($query->expr()->eq('c.principaluri', $query->createNamedParameter($principalUri)))
2439
+            ->andWhere($query->expr()->eq('co.uid', $query->createNamedParameter($uid)))
2440
+            ->andWhere($query->expr()->isNull('co.deleted_at'));
2441
+        $stmt = $query->executeQuery();
2442
+        $row = $stmt->fetch();
2443
+        $stmt->closeCursor();
2444
+        if ($row) {
2445
+            return $row['calendaruri'] . '/' . $row['objecturi'];
2446
+        }
2447
+
2448
+        return null;
2449
+    }
2450
+
2451
+    public function getCalendarObjectById(string $principalUri, int $id): ?array {
2452
+        $query = $this->db->getQueryBuilder();
2453
+        $query->select(['co.id', 'co.uri', 'co.lastmodified', 'co.etag', 'co.calendarid', 'co.size', 'co.calendardata', 'co.componenttype', 'co.classification', 'co.deleted_at'])
2454
+            ->selectAlias('c.uri', 'calendaruri')
2455
+            ->from('calendarobjects', 'co')
2456
+            ->join('co', 'calendars', 'c', $query->expr()->eq('c.id', 'co.calendarid', IQueryBuilder::PARAM_INT))
2457
+            ->where($query->expr()->eq('c.principaluri', $query->createNamedParameter($principalUri)))
2458
+            ->andWhere($query->expr()->eq('co.id', $query->createNamedParameter($id, IQueryBuilder::PARAM_INT), IQueryBuilder::PARAM_INT));
2459
+        $stmt = $query->executeQuery();
2460
+        $row = $stmt->fetch();
2461
+        $stmt->closeCursor();
2462
+
2463
+        if (!$row) {
2464
+            return null;
2465
+        }
2466
+
2467
+        return [
2468
+            'id' => $row['id'],
2469
+            'uri' => $row['uri'],
2470
+            'lastmodified' => $row['lastmodified'],
2471
+            'etag' => '"' . $row['etag'] . '"',
2472
+            'calendarid' => $row['calendarid'],
2473
+            'calendaruri' => $row['calendaruri'],
2474
+            'size' => (int)$row['size'],
2475
+            'calendardata' => $this->readBlob($row['calendardata']),
2476
+            'component' => strtolower($row['componenttype']),
2477
+            'classification' => (int)$row['classification'],
2478
+            'deleted_at' => isset($row['deleted_at']) ? ((int)$row['deleted_at']) : null,
2479
+        ];
2480
+    }
2481
+
2482
+    /**
2483
+     * The getChanges method returns all the changes that have happened, since
2484
+     * the specified syncToken in the specified calendar.
2485
+     *
2486
+     * This function should return an array, such as the following:
2487
+     *
2488
+     * [
2489
+     *   'syncToken' => 'The current synctoken',
2490
+     *   'added'   => [
2491
+     *      'new.txt',
2492
+     *   ],
2493
+     *   'modified'   => [
2494
+     *      'modified.txt',
2495
+     *   ],
2496
+     *   'deleted' => [
2497
+     *      'foo.php.bak',
2498
+     *      'old.txt'
2499
+     *   ]
2500
+     * );
2501
+     *
2502
+     * The returned syncToken property should reflect the *current* syncToken
2503
+     * of the calendar, as reported in the {http://sabredav.org/ns}sync-token
2504
+     * property This is * needed here too, to ensure the operation is atomic.
2505
+     *
2506
+     * If the $syncToken argument is specified as null, this is an initial
2507
+     * sync, and all members should be reported.
2508
+     *
2509
+     * The modified property is an array of nodenames that have changed since
2510
+     * the last token.
2511
+     *
2512
+     * The deleted property is an array with nodenames, that have been deleted
2513
+     * from collection.
2514
+     *
2515
+     * The $syncLevel argument is basically the 'depth' of the report. If it's
2516
+     * 1, you only have to report changes that happened only directly in
2517
+     * immediate descendants. If it's 2, it should also include changes from
2518
+     * the nodes below the child collections. (grandchildren)
2519
+     *
2520
+     * The $limit argument allows a client to specify how many results should
2521
+     * be returned at most. If the limit is not specified, it should be treated
2522
+     * as infinite.
2523
+     *
2524
+     * If the limit (infinite or not) is higher than you're willing to return,
2525
+     * you should throw a Sabre\DAV\Exception\TooMuchMatches() exception.
2526
+     *
2527
+     * If the syncToken is expired (due to data cleanup) or unknown, you must
2528
+     * return null.
2529
+     *
2530
+     * The limit is 'suggestive'. You are free to ignore it.
2531
+     *
2532
+     * @param string $calendarId
2533
+     * @param string $syncToken
2534
+     * @param int $syncLevel
2535
+     * @param int|null $limit
2536
+     * @param int $calendarType
2537
+     * @return ?array
2538
+     */
2539
+    public function getChangesForCalendar($calendarId, $syncToken, $syncLevel, $limit = null, $calendarType = self::CALENDAR_TYPE_CALENDAR) {
2540
+        $table = $calendarType === self::CALENDAR_TYPE_CALENDAR ? 'calendars': 'calendarsubscriptions';
2541
+
2542
+        return $this->atomic(function () use ($calendarId, $syncToken, $syncLevel, $limit, $calendarType, $table) {
2543
+            // Current synctoken
2544
+            $qb = $this->db->getQueryBuilder();
2545
+            $qb->select('synctoken')
2546
+                ->from($table)
2547
+                ->where(
2548
+                    $qb->expr()->eq('id', $qb->createNamedParameter($calendarId))
2549
+                );
2550
+            $stmt = $qb->executeQuery();
2551
+            $currentToken = $stmt->fetchOne();
2552
+            $initialSync = !is_numeric($syncToken);
2553
+
2554
+            if ($currentToken === false) {
2555
+                return null;
2556
+            }
2557
+
2558
+            // evaluate if this is a initial sync and construct appropriate command
2559
+            if ($initialSync) {
2560
+                $qb = $this->db->getQueryBuilder();
2561
+                $qb->select('uri')
2562
+                    ->from('calendarobjects')
2563
+                    ->where($qb->expr()->eq('calendarid', $qb->createNamedParameter($calendarId)))
2564
+                    ->andWhere($qb->expr()->eq('calendartype', $qb->createNamedParameter($calendarType)))
2565
+                    ->andWhere($qb->expr()->isNull('deleted_at'));
2566
+            } else {
2567
+                $qb = $this->db->getQueryBuilder();
2568
+                $qb->select('uri', $qb->func()->max('operation'))
2569
+                    ->from('calendarchanges')
2570
+                    ->where($qb->expr()->eq('calendarid', $qb->createNamedParameter($calendarId)))
2571
+                    ->andWhere($qb->expr()->eq('calendartype', $qb->createNamedParameter($calendarType)))
2572
+                    ->andWhere($qb->expr()->gte('synctoken', $qb->createNamedParameter($syncToken)))
2573
+                    ->andWhere($qb->expr()->lt('synctoken', $qb->createNamedParameter($currentToken)))
2574
+                    ->groupBy('uri');
2575
+            }
2576
+            // evaluate if limit exists
2577
+            if (is_numeric($limit)) {
2578
+                $qb->setMaxResults($limit);
2579
+            }
2580
+            // execute command
2581
+            $stmt = $qb->executeQuery();
2582
+            // build results
2583
+            $result = ['syncToken' => $currentToken, 'added' => [], 'modified' => [], 'deleted' => []];
2584
+            // retrieve results
2585
+            if ($initialSync) {
2586
+                $result['added'] = $stmt->fetchAll(\PDO::FETCH_COLUMN);
2587
+            } else {
2588
+                // \PDO::FETCH_NUM is needed due to the inconsistent field names
2589
+                // produced by doctrine for MAX() with different databases
2590
+                while ($entry = $stmt->fetch(\PDO::FETCH_NUM)) {
2591
+                    // assign uri (column 0) to appropriate mutation based on operation (column 1)
2592
+                    // forced (int) is needed as doctrine with OCI returns the operation field as string not integer
2593
+                    match ((int)$entry[1]) {
2594
+                        1 => $result['added'][] = $entry[0],
2595
+                        2 => $result['modified'][] = $entry[0],
2596
+                        3 => $result['deleted'][] = $entry[0],
2597
+                        default => $this->logger->debug('Unknown calendar change operation detected')
2598
+                    };
2599
+                }
2600
+            }
2601
+            $stmt->closeCursor();
2602
+
2603
+            return $result;
2604
+        }, $this->db);
2605
+    }
2606
+
2607
+    /**
2608
+     * Returns a list of subscriptions for a principal.
2609
+     *
2610
+     * Every subscription is an array with the following keys:
2611
+     *  * id, a unique id that will be used by other functions to modify the
2612
+     *    subscription. This can be the same as the uri or a database key.
2613
+     *  * uri. This is just the 'base uri' or 'filename' of the subscription.
2614
+     *  * principaluri. The owner of the subscription. Almost always the same as
2615
+     *    principalUri passed to this method.
2616
+     *
2617
+     * Furthermore, all the subscription info must be returned too:
2618
+     *
2619
+     * 1. {DAV:}displayname
2620
+     * 2. {http://apple.com/ns/ical/}refreshrate
2621
+     * 3. {http://calendarserver.org/ns/}subscribed-strip-todos (omit if todos
2622
+     *    should not be stripped).
2623
+     * 4. {http://calendarserver.org/ns/}subscribed-strip-alarms (omit if alarms
2624
+     *    should not be stripped).
2625
+     * 5. {http://calendarserver.org/ns/}subscribed-strip-attachments (omit if
2626
+     *    attachments should not be stripped).
2627
+     * 6. {http://calendarserver.org/ns/}source (Must be a
2628
+     *     Sabre\DAV\Property\Href).
2629
+     * 7. {http://apple.com/ns/ical/}calendar-color
2630
+     * 8. {http://apple.com/ns/ical/}calendar-order
2631
+     * 9. {urn:ietf:params:xml:ns:caldav}supported-calendar-component-set
2632
+     *    (should just be an instance of
2633
+     *    Sabre\CalDAV\Property\SupportedCalendarComponentSet, with a bunch of
2634
+     *    default components).
2635
+     *
2636
+     * @param string $principalUri
2637
+     * @return array
2638
+     */
2639
+    public function getSubscriptionsForUser($principalUri) {
2640
+        $fields = array_column($this->subscriptionPropertyMap, 0);
2641
+        $fields[] = 'id';
2642
+        $fields[] = 'uri';
2643
+        $fields[] = 'source';
2644
+        $fields[] = 'principaluri';
2645
+        $fields[] = 'lastmodified';
2646
+        $fields[] = 'synctoken';
2647
+
2648
+        $query = $this->db->getQueryBuilder();
2649
+        $query->select($fields)
2650
+            ->from('calendarsubscriptions')
2651
+            ->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
2652
+            ->orderBy('calendarorder', 'asc');
2653
+        $stmt = $query->executeQuery();
2654
+
2655
+        $subscriptions = [];
2656
+        while ($row = $stmt->fetch()) {
2657
+            $subscription = [
2658
+                'id' => $row['id'],
2659
+                'uri' => $row['uri'],
2660
+                'principaluri' => $row['principaluri'],
2661
+                'source' => $row['source'],
2662
+                'lastmodified' => $row['lastmodified'],
2663
+
2664
+                '{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet(['VTODO', 'VEVENT']),
2665
+                '{http://sabredav.org/ns}sync-token' => $row['synctoken'] ?: '0',
2666
+            ];
2667
+
2668
+            $subscriptions[] = $this->rowToSubscription($row, $subscription);
2669
+        }
2670
+
2671
+        return $subscriptions;
2672
+    }
2673
+
2674
+    /**
2675
+     * Creates a new subscription for a principal.
2676
+     *
2677
+     * If the creation was a success, an id must be returned that can be used to reference
2678
+     * this subscription in other methods, such as updateSubscription.
2679
+     *
2680
+     * @param string $principalUri
2681
+     * @param string $uri
2682
+     * @param array $properties
2683
+     * @return mixed
2684
+     */
2685
+    public function createSubscription($principalUri, $uri, array $properties) {
2686
+        if (!isset($properties['{http://calendarserver.org/ns/}source'])) {
2687
+            throw new Forbidden('The {http://calendarserver.org/ns/}source property is required when creating subscriptions');
2688
+        }
2689
+
2690
+        $values = [
2691
+            'principaluri' => $principalUri,
2692
+            'uri' => $uri,
2693
+            'source' => $properties['{http://calendarserver.org/ns/}source']->getHref(),
2694
+            'lastmodified' => time(),
2695
+        ];
2696
+
2697
+        $propertiesBoolean = ['striptodos', 'stripalarms', 'stripattachments'];
2698
+
2699
+        foreach ($this->subscriptionPropertyMap as $xmlName => [$dbName, $type]) {
2700
+            if (array_key_exists($xmlName, $properties)) {
2701
+                $values[$dbName] = $properties[$xmlName];
2702
+                if (in_array($dbName, $propertiesBoolean)) {
2703
+                    $values[$dbName] = true;
2704
+                }
2705
+            }
2706
+        }
2707
+
2708
+        [$subscriptionId, $subscriptionRow] = $this->atomic(function () use ($values) {
2709
+            $valuesToInsert = [];
2710
+            $query = $this->db->getQueryBuilder();
2711
+            foreach (array_keys($values) as $name) {
2712
+                $valuesToInsert[$name] = $query->createNamedParameter($values[$name]);
2713
+            }
2714
+            $query->insert('calendarsubscriptions')
2715
+                ->values($valuesToInsert)
2716
+                ->executeStatement();
2717
+
2718
+            $subscriptionId = $query->getLastInsertId();
2719
+
2720
+            $subscriptionRow = $this->getSubscriptionById($subscriptionId);
2721
+            return [$subscriptionId, $subscriptionRow];
2722
+        }, $this->db);
2723
+
2724
+        $this->dispatcher->dispatchTyped(new SubscriptionCreatedEvent($subscriptionId, $subscriptionRow));
2725
+
2726
+        return $subscriptionId;
2727
+    }
2728
+
2729
+    /**
2730
+     * Updates a subscription
2731
+     *
2732
+     * The list of mutations is stored in a Sabre\DAV\PropPatch object.
2733
+     * To do the actual updates, you must tell this object which properties
2734
+     * you're going to process with the handle() method.
2735
+     *
2736
+     * Calling the handle method is like telling the PropPatch object "I
2737
+     * promise I can handle updating this property".
2738
+     *
2739
+     * Read the PropPatch documentation for more info and examples.
2740
+     *
2741
+     * @param mixed $subscriptionId
2742
+     * @param PropPatch $propPatch
2743
+     * @return void
2744
+     */
2745
+    public function updateSubscription($subscriptionId, PropPatch $propPatch) {
2746
+        $supportedProperties = array_keys($this->subscriptionPropertyMap);
2747
+        $supportedProperties[] = '{http://calendarserver.org/ns/}source';
2748
+
2749
+        $propPatch->handle($supportedProperties, function ($mutations) use ($subscriptionId) {
2750
+            $newValues = [];
2751
+
2752
+            foreach ($mutations as $propertyName => $propertyValue) {
2753
+                if ($propertyName === '{http://calendarserver.org/ns/}source') {
2754
+                    $newValues['source'] = $propertyValue->getHref();
2755
+                } else {
2756
+                    $fieldName = $this->subscriptionPropertyMap[$propertyName][0];
2757
+                    $newValues[$fieldName] = $propertyValue;
2758
+                }
2759
+            }
2760
+
2761
+            $subscriptionRow = $this->atomic(function () use ($subscriptionId, $newValues) {
2762
+                $query = $this->db->getQueryBuilder();
2763
+                $query->update('calendarsubscriptions')
2764
+                    ->set('lastmodified', $query->createNamedParameter(time()));
2765
+                foreach ($newValues as $fieldName => $value) {
2766
+                    $query->set($fieldName, $query->createNamedParameter($value));
2767
+                }
2768
+                $query->where($query->expr()->eq('id', $query->createNamedParameter($subscriptionId)))
2769
+                    ->executeStatement();
2770
+
2771
+                return $this->getSubscriptionById($subscriptionId);
2772
+            }, $this->db);
2773
+
2774
+            $this->dispatcher->dispatchTyped(new SubscriptionUpdatedEvent((int)$subscriptionId, $subscriptionRow, [], $mutations));
2775
+
2776
+            return true;
2777
+        });
2778
+    }
2779
+
2780
+    /**
2781
+     * Deletes a subscription.
2782
+     *
2783
+     * @param mixed $subscriptionId
2784
+     * @return void
2785
+     */
2786
+    public function deleteSubscription($subscriptionId) {
2787
+        $this->atomic(function () use ($subscriptionId): void {
2788
+            $subscriptionRow = $this->getSubscriptionById($subscriptionId);
2789
+
2790
+            $query = $this->db->getQueryBuilder();
2791
+            $query->delete('calendarsubscriptions')
2792
+                ->where($query->expr()->eq('id', $query->createNamedParameter($subscriptionId)))
2793
+                ->executeStatement();
2794
+
2795
+            $query = $this->db->getQueryBuilder();
2796
+            $query->delete('calendarobjects')
2797
+                ->where($query->expr()->eq('calendarid', $query->createNamedParameter($subscriptionId)))
2798
+                ->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)))
2799
+                ->executeStatement();
2800
+
2801
+            $query->delete('calendarchanges')
2802
+                ->where($query->expr()->eq('calendarid', $query->createNamedParameter($subscriptionId)))
2803
+                ->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)))
2804
+                ->executeStatement();
2805
+
2806
+            $query->delete($this->dbObjectPropertiesTable)
2807
+                ->where($query->expr()->eq('calendarid', $query->createNamedParameter($subscriptionId)))
2808
+                ->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)))
2809
+                ->executeStatement();
2810
+
2811
+            if ($subscriptionRow) {
2812
+                $this->dispatcher->dispatchTyped(new SubscriptionDeletedEvent((int)$subscriptionId, $subscriptionRow, []));
2813
+            }
2814
+        }, $this->db);
2815
+    }
2816
+
2817
+    /**
2818
+     * Returns a single scheduling object for the inbox collection.
2819
+     *
2820
+     * The returned array should contain the following elements:
2821
+     *   * uri - A unique basename for the object. This will be used to
2822
+     *           construct a full uri.
2823
+     *   * calendardata - The iCalendar object
2824
+     *   * lastmodified - The last modification date. Can be an int for a unix
2825
+     *                    timestamp, or a PHP DateTime object.
2826
+     *   * etag - A unique token that must change if the object changed.
2827
+     *   * size - The size of the object, in bytes.
2828
+     *
2829
+     * @param string $principalUri
2830
+     * @param string $objectUri
2831
+     * @return array
2832
+     */
2833
+    public function getSchedulingObject($principalUri, $objectUri) {
2834
+        $query = $this->db->getQueryBuilder();
2835
+        $stmt = $query->select(['uri', 'calendardata', 'lastmodified', 'etag', 'size'])
2836
+            ->from('schedulingobjects')
2837
+            ->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
2838
+            ->andWhere($query->expr()->eq('uri', $query->createNamedParameter($objectUri)))
2839
+            ->executeQuery();
2840
+
2841
+        $row = $stmt->fetch();
2842
+
2843
+        if (!$row) {
2844
+            return null;
2845
+        }
2846
+
2847
+        return [
2848
+            'uri' => $row['uri'],
2849
+            'calendardata' => $row['calendardata'],
2850
+            'lastmodified' => $row['lastmodified'],
2851
+            'etag' => '"' . $row['etag'] . '"',
2852
+            'size' => (int)$row['size'],
2853
+        ];
2854
+    }
2855
+
2856
+    /**
2857
+     * Returns all scheduling objects for the inbox collection.
2858
+     *
2859
+     * These objects should be returned as an array. Every item in the array
2860
+     * should follow the same structure as returned from getSchedulingObject.
2861
+     *
2862
+     * The main difference is that 'calendardata' is optional.
2863
+     *
2864
+     * @param string $principalUri
2865
+     * @return array
2866
+     */
2867
+    public function getSchedulingObjects($principalUri) {
2868
+        $query = $this->db->getQueryBuilder();
2869
+        $stmt = $query->select(['uri', 'calendardata', 'lastmodified', 'etag', 'size'])
2870
+            ->from('schedulingobjects')
2871
+            ->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
2872
+            ->executeQuery();
2873
+
2874
+        $results = [];
2875
+        while (($row = $stmt->fetch()) !== false) {
2876
+            $results[] = [
2877
+                'calendardata' => $row['calendardata'],
2878
+                'uri' => $row['uri'],
2879
+                'lastmodified' => $row['lastmodified'],
2880
+                'etag' => '"' . $row['etag'] . '"',
2881
+                'size' => (int)$row['size'],
2882
+            ];
2883
+        }
2884
+        $stmt->closeCursor();
2885
+
2886
+        return $results;
2887
+    }
2888
+
2889
+    /**
2890
+     * Deletes a scheduling object from the inbox collection.
2891
+     *
2892
+     * @param string $principalUri
2893
+     * @param string $objectUri
2894
+     * @return void
2895
+     */
2896
+    public function deleteSchedulingObject($principalUri, $objectUri) {
2897
+        $this->cachedObjects = [];
2898
+        $query = $this->db->getQueryBuilder();
2899
+        $query->delete('schedulingobjects')
2900
+            ->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
2901
+            ->andWhere($query->expr()->eq('uri', $query->createNamedParameter($objectUri)))
2902
+            ->executeStatement();
2903
+    }
2904
+
2905
+    /**
2906
+     * Deletes all scheduling objects last modified before $modifiedBefore from the inbox collection.
2907
+     *
2908
+     * @param int $modifiedBefore
2909
+     * @param int $limit
2910
+     * @return void
2911
+     */
2912
+    public function deleteOutdatedSchedulingObjects(int $modifiedBefore, int $limit): void {
2913
+        $query = $this->db->getQueryBuilder();
2914
+        $query->select('id')
2915
+            ->from('schedulingobjects')
2916
+            ->where($query->expr()->lt('lastmodified', $query->createNamedParameter($modifiedBefore)))
2917
+            ->setMaxResults($limit);
2918
+        $result = $query->executeQuery();
2919
+        $count = $result->rowCount();
2920
+        if ($count === 0) {
2921
+            return;
2922
+        }
2923
+        $ids = array_map(static function (array $id) {
2924
+            return (int)$id[0];
2925
+        }, $result->fetchAll(\PDO::FETCH_NUM));
2926
+        $result->closeCursor();
2927
+
2928
+        $numDeleted = 0;
2929
+        $deleteQuery = $this->db->getQueryBuilder();
2930
+        $deleteQuery->delete('schedulingobjects')
2931
+            ->where($deleteQuery->expr()->in('id', $deleteQuery->createParameter('ids'), IQueryBuilder::PARAM_INT_ARRAY));
2932
+        foreach (array_chunk($ids, 1000) as $chunk) {
2933
+            $deleteQuery->setParameter('ids', $chunk, IQueryBuilder::PARAM_INT_ARRAY);
2934
+            $numDeleted += $deleteQuery->executeStatement();
2935
+        }
2936
+
2937
+        if ($numDeleted === $limit) {
2938
+            $this->logger->info("Deleted $limit scheduling objects, continuing with next batch");
2939
+            $this->deleteOutdatedSchedulingObjects($modifiedBefore, $limit);
2940
+        }
2941
+    }
2942
+
2943
+    /**
2944
+     * Creates a new scheduling object. This should land in a users' inbox.
2945
+     *
2946
+     * @param string $principalUri
2947
+     * @param string $objectUri
2948
+     * @param string $objectData
2949
+     * @return void
2950
+     */
2951
+    public function createSchedulingObject($principalUri, $objectUri, $objectData) {
2952
+        $this->cachedObjects = [];
2953
+        $query = $this->db->getQueryBuilder();
2954
+        $query->insert('schedulingobjects')
2955
+            ->values([
2956
+                'principaluri' => $query->createNamedParameter($principalUri),
2957
+                'calendardata' => $query->createNamedParameter($objectData, IQueryBuilder::PARAM_LOB),
2958
+                'uri' => $query->createNamedParameter($objectUri),
2959
+                'lastmodified' => $query->createNamedParameter(time()),
2960
+                'etag' => $query->createNamedParameter(md5($objectData)),
2961
+                'size' => $query->createNamedParameter(strlen($objectData))
2962
+            ])
2963
+            ->executeStatement();
2964
+    }
2965
+
2966
+    /**
2967
+     * Adds a change record to the calendarchanges table.
2968
+     *
2969
+     * @param mixed $calendarId
2970
+     * @param string[] $objectUris
2971
+     * @param int $operation 1 = add, 2 = modify, 3 = delete.
2972
+     * @param int $calendarType
2973
+     * @return void
2974
+     */
2975
+    protected function addChanges(int $calendarId, array $objectUris, int $operation, int $calendarType = self::CALENDAR_TYPE_CALENDAR): void {
2976
+        $this->cachedObjects = [];
2977
+        $table = $calendarType === self::CALENDAR_TYPE_CALENDAR ? 'calendars': 'calendarsubscriptions';
2978
+
2979
+        $this->atomic(function () use ($calendarId, $objectUris, $operation, $calendarType, $table): void {
2980
+            $query = $this->db->getQueryBuilder();
2981
+            $query->select('synctoken')
2982
+                ->from($table)
2983
+                ->where($query->expr()->eq('id', $query->createNamedParameter($calendarId)));
2984
+            $result = $query->executeQuery();
2985
+            $syncToken = (int)$result->fetchOne();
2986
+            $result->closeCursor();
2987
+
2988
+            $query = $this->db->getQueryBuilder();
2989
+            $query->insert('calendarchanges')
2990
+                ->values([
2991
+                    'uri' => $query->createParameter('uri'),
2992
+                    'synctoken' => $query->createNamedParameter($syncToken),
2993
+                    'calendarid' => $query->createNamedParameter($calendarId),
2994
+                    'operation' => $query->createNamedParameter($operation),
2995
+                    'calendartype' => $query->createNamedParameter($calendarType),
2996
+                    'created_at' => time(),
2997
+                ]);
2998
+            foreach ($objectUris as $uri) {
2999
+                $query->setParameter('uri', $uri);
3000
+                $query->executeStatement();
3001
+            }
3002
+
3003
+            $query = $this->db->getQueryBuilder();
3004
+            $query->update($table)
3005
+                ->set('synctoken', $query->createNamedParameter($syncToken + 1, IQueryBuilder::PARAM_INT))
3006
+                ->where($query->expr()->eq('id', $query->createNamedParameter($calendarId)))
3007
+                ->executeStatement();
3008
+        }, $this->db);
3009
+    }
3010
+
3011
+    public function restoreChanges(int $calendarId, int $calendarType = self::CALENDAR_TYPE_CALENDAR): void {
3012
+        $this->cachedObjects = [];
3013
+
3014
+        $this->atomic(function () use ($calendarId, $calendarType): void {
3015
+            $qbAdded = $this->db->getQueryBuilder();
3016
+            $qbAdded->select('uri')
3017
+                ->from('calendarobjects')
3018
+                ->where(
3019
+                    $qbAdded->expr()->andX(
3020
+                        $qbAdded->expr()->eq('calendarid', $qbAdded->createNamedParameter($calendarId)),
3021
+                        $qbAdded->expr()->eq('calendartype', $qbAdded->createNamedParameter($calendarType)),
3022
+                        $qbAdded->expr()->isNull('deleted_at'),
3023
+                    )
3024
+                );
3025
+            $resultAdded = $qbAdded->executeQuery();
3026
+            $addedUris = $resultAdded->fetchAll(\PDO::FETCH_COLUMN);
3027
+            $resultAdded->closeCursor();
3028
+            // Track everything as changed
3029
+            // Tracking the creation is not necessary because \OCA\DAV\CalDAV\CalDavBackend::getChangesForCalendar
3030
+            // only returns the last change per object.
3031
+            $this->addChanges($calendarId, $addedUris, 2, $calendarType);
3032
+
3033
+            $qbDeleted = $this->db->getQueryBuilder();
3034
+            $qbDeleted->select('uri')
3035
+                ->from('calendarobjects')
3036
+                ->where(
3037
+                    $qbDeleted->expr()->andX(
3038
+                        $qbDeleted->expr()->eq('calendarid', $qbDeleted->createNamedParameter($calendarId)),
3039
+                        $qbDeleted->expr()->eq('calendartype', $qbDeleted->createNamedParameter($calendarType)),
3040
+                        $qbDeleted->expr()->isNotNull('deleted_at'),
3041
+                    )
3042
+                );
3043
+            $resultDeleted = $qbDeleted->executeQuery();
3044
+            $deletedUris = array_map(function (string $uri) {
3045
+                return str_replace('-deleted.ics', '.ics', $uri);
3046
+            }, $resultDeleted->fetchAll(\PDO::FETCH_COLUMN));
3047
+            $resultDeleted->closeCursor();
3048
+            $this->addChanges($calendarId, $deletedUris, 3, $calendarType);
3049
+        }, $this->db);
3050
+    }
3051
+
3052
+    /**
3053
+     * Parses some information from calendar objects, used for optimized
3054
+     * calendar-queries.
3055
+     *
3056
+     * Returns an array with the following keys:
3057
+     *   * etag - An md5 checksum of the object without the quotes.
3058
+     *   * size - Size of the object in bytes
3059
+     *   * componentType - VEVENT, VTODO or VJOURNAL
3060
+     *   * firstOccurence
3061
+     *   * lastOccurence
3062
+     *   * uid - value of the UID property
3063
+     *
3064
+     * @param string $calendarData
3065
+     * @return array
3066
+     */
3067
+    public function getDenormalizedData(string $calendarData): array {
3068
+        $vObject = Reader::read($calendarData);
3069
+        $vEvents = [];
3070
+        $componentType = null;
3071
+        $component = null;
3072
+        $firstOccurrence = null;
3073
+        $lastOccurrence = null;
3074
+        $uid = null;
3075
+        $classification = self::CLASSIFICATION_PUBLIC;
3076
+        $hasDTSTART = false;
3077
+        foreach ($vObject->getComponents() as $component) {
3078
+            if ($component->name !== 'VTIMEZONE') {
3079
+                // Finding all VEVENTs, and track them
3080
+                if ($component->name === 'VEVENT') {
3081
+                    $vEvents[] = $component;
3082
+                    if ($component->DTSTART) {
3083
+                        $hasDTSTART = true;
3084
+                    }
3085
+                }
3086
+                // Track first component type and uid
3087
+                if ($uid === null) {
3088
+                    $componentType = $component->name;
3089
+                    $uid = (string)$component->UID;
3090
+                }
3091
+            }
3092
+        }
3093
+        if (!$componentType) {
3094
+            throw new BadRequest('Calendar objects must have a VJOURNAL, VEVENT or VTODO component');
3095
+        }
3096
+
3097
+        if ($hasDTSTART) {
3098
+            $component = $vEvents[0];
3099
+
3100
+            // Finding the last occurrence is a bit harder
3101
+            if (!isset($component->RRULE) && count($vEvents) === 1) {
3102
+                $firstOccurrence = $component->DTSTART->getDateTime()->getTimeStamp();
3103
+                if (isset($component->DTEND)) {
3104
+                    $lastOccurrence = $component->DTEND->getDateTime()->getTimeStamp();
3105
+                } elseif (isset($component->DURATION)) {
3106
+                    $endDate = clone $component->DTSTART->getDateTime();
3107
+                    $endDate->add(DateTimeParser::parse($component->DURATION->getValue()));
3108
+                    $lastOccurrence = $endDate->getTimeStamp();
3109
+                } elseif (!$component->DTSTART->hasTime()) {
3110
+                    $endDate = clone $component->DTSTART->getDateTime();
3111
+                    $endDate->modify('+1 day');
3112
+                    $lastOccurrence = $endDate->getTimeStamp();
3113
+                } else {
3114
+                    $lastOccurrence = $firstOccurrence;
3115
+                }
3116
+            } else {
3117
+                try {
3118
+                    $it = new EventIterator($vEvents);
3119
+                } catch (NoInstancesException $e) {
3120
+                    $this->logger->debug('Caught no instance exception for calendar data. This usually indicates invalid calendar data.', [
3121
+                        'app' => 'dav',
3122
+                        'exception' => $e,
3123
+                    ]);
3124
+                    throw new Forbidden($e->getMessage());
3125
+                }
3126
+                $maxDate = new DateTime(self::MAX_DATE);
3127
+                $firstOccurrence = $it->getDtStart()->getTimestamp();
3128
+                if ($it->isInfinite()) {
3129
+                    $lastOccurrence = $maxDate->getTimestamp();
3130
+                } else {
3131
+                    $end = $it->getDtEnd();
3132
+                    while ($it->valid() && $end < $maxDate) {
3133
+                        $end = $it->getDtEnd();
3134
+                        $it->next();
3135
+                    }
3136
+                    $lastOccurrence = $end->getTimestamp();
3137
+                }
3138
+            }
3139
+        }
3140
+
3141
+        if ($component->CLASS) {
3142
+            $classification = CalDavBackend::CLASSIFICATION_PRIVATE;
3143
+            switch ($component->CLASS->getValue()) {
3144
+                case 'PUBLIC':
3145
+                    $classification = CalDavBackend::CLASSIFICATION_PUBLIC;
3146
+                    break;
3147
+                case 'CONFIDENTIAL':
3148
+                    $classification = CalDavBackend::CLASSIFICATION_CONFIDENTIAL;
3149
+                    break;
3150
+            }
3151
+        }
3152
+        return [
3153
+            'etag' => md5($calendarData),
3154
+            'size' => strlen($calendarData),
3155
+            'componentType' => $componentType,
3156
+            'firstOccurence' => is_null($firstOccurrence) ? null : max(0, $firstOccurrence),
3157
+            'lastOccurence' => is_null($lastOccurrence) ? null : max(0, $lastOccurrence),
3158
+            'uid' => $uid,
3159
+            'classification' => $classification
3160
+        ];
3161
+    }
3162
+
3163
+    /**
3164
+     * @param $cardData
3165
+     * @return bool|string
3166
+     */
3167
+    private function readBlob($cardData) {
3168
+        if (is_resource($cardData)) {
3169
+            return stream_get_contents($cardData);
3170
+        }
3171
+
3172
+        return $cardData;
3173
+    }
3174
+
3175
+    /**
3176
+     * @param list<array{href: string, commonName: string, readOnly: bool}> $add
3177
+     * @param list<string> $remove
3178
+     */
3179
+    public function updateShares(IShareable $shareable, array $add, array $remove): void {
3180
+        $this->atomic(function () use ($shareable, $add, $remove): void {
3181
+            $calendarId = $shareable->getResourceId();
3182
+            $calendarRow = $this->getCalendarById($calendarId);
3183
+            if ($calendarRow === null) {
3184
+                throw new \RuntimeException('Trying to update shares for non-existing calendar: ' . $calendarId);
3185
+            }
3186
+            $oldShares = $this->getShares($calendarId);
3187
+
3188
+            $this->calendarSharingBackend->updateShares($shareable, $add, $remove, $oldShares);
3189
+
3190
+            $this->dispatcher->dispatchTyped(new CalendarShareUpdatedEvent($calendarId, $calendarRow, $oldShares, $add, $remove));
3191
+        }, $this->db);
3192
+    }
3193
+
3194
+    /**
3195
+     * @return list<array{href: string, commonName: string, status: int, readOnly: bool, '{http://owncloud.org/ns}principal': string, '{http://owncloud.org/ns}group-share': bool}>
3196
+     */
3197
+    public function getShares(int $resourceId): array {
3198
+        return $this->calendarSharingBackend->getShares($resourceId);
3199
+    }
3200
+
3201
+    public function preloadShares(array $resourceIds): void {
3202
+        $this->calendarSharingBackend->preloadShares($resourceIds);
3203
+    }
3204
+
3205
+    /**
3206
+     * @param boolean $value
3207
+     * @param Calendar $calendar
3208
+     * @return string|null
3209
+     */
3210
+    public function setPublishStatus($value, $calendar) {
3211
+        return $this->atomic(function () use ($value, $calendar) {
3212
+            $calendarId = $calendar->getResourceId();
3213
+            $calendarData = $this->getCalendarById($calendarId);
3214
+
3215
+            $query = $this->db->getQueryBuilder();
3216
+            if ($value) {
3217
+                $publicUri = $this->random->generate(16, ISecureRandom::CHAR_HUMAN_READABLE);
3218
+                $query->insert('dav_shares')
3219
+                    ->values([
3220
+                        'principaluri' => $query->createNamedParameter($calendar->getPrincipalURI()),
3221
+                        'type' => $query->createNamedParameter('calendar'),
3222
+                        'access' => $query->createNamedParameter(self::ACCESS_PUBLIC),
3223
+                        'resourceid' => $query->createNamedParameter($calendar->getResourceId()),
3224
+                        'publicuri' => $query->createNamedParameter($publicUri)
3225
+                    ]);
3226
+                $query->executeStatement();
3227
+
3228
+                $this->dispatcher->dispatchTyped(new CalendarPublishedEvent($calendarId, $calendarData, $publicUri));
3229
+                return $publicUri;
3230
+            }
3231
+            $query->delete('dav_shares')
3232
+                ->where($query->expr()->eq('resourceid', $query->createNamedParameter($calendar->getResourceId())))
3233
+                ->andWhere($query->expr()->eq('access', $query->createNamedParameter(self::ACCESS_PUBLIC)));
3234
+            $query->executeStatement();
3235
+
3236
+            $this->dispatcher->dispatchTyped(new CalendarUnpublishedEvent($calendarId, $calendarData));
3237
+            return null;
3238
+        }, $this->db);
3239
+    }
3240
+
3241
+    /**
3242
+     * @param Calendar $calendar
3243
+     * @return mixed
3244
+     */
3245
+    public function getPublishStatus($calendar) {
3246
+        $query = $this->db->getQueryBuilder();
3247
+        $result = $query->select('publicuri')
3248
+            ->from('dav_shares')
3249
+            ->where($query->expr()->eq('resourceid', $query->createNamedParameter($calendar->getResourceId())))
3250
+            ->andWhere($query->expr()->eq('access', $query->createNamedParameter(self::ACCESS_PUBLIC)))
3251
+            ->executeQuery();
3252
+
3253
+        $row = $result->fetch();
3254
+        $result->closeCursor();
3255
+        return $row ? reset($row) : false;
3256
+    }
3257
+
3258
+    /**
3259
+     * @param int $resourceId
3260
+     * @param list<array{privilege: string, principal: string, protected: bool}> $acl
3261
+     * @return list<array{privilege: string, principal: string, protected: bool}>
3262
+     */
3263
+    public function applyShareAcl(int $resourceId, array $acl): array {
3264
+        $shares = $this->calendarSharingBackend->getShares($resourceId);
3265
+        return $this->calendarSharingBackend->applyShareAcl($shares, $acl);
3266
+    }
3267
+
3268
+    /**
3269
+     * update properties table
3270
+     *
3271
+     * @param int $calendarId
3272
+     * @param string $objectUri
3273
+     * @param string $calendarData
3274
+     * @param int $calendarType
3275
+     */
3276
+    public function updateProperties($calendarId, $objectUri, $calendarData, $calendarType = self::CALENDAR_TYPE_CALENDAR) {
3277
+        $this->cachedObjects = [];
3278
+        $this->atomic(function () use ($calendarId, $objectUri, $calendarData, $calendarType): void {
3279
+            $objectId = $this->getCalendarObjectId($calendarId, $objectUri, $calendarType);
3280
+
3281
+            try {
3282
+                $vCalendar = $this->readCalendarData($calendarData);
3283
+            } catch (\Exception $ex) {
3284
+                return;
3285
+            }
3286
+
3287
+            $this->purgeProperties($calendarId, $objectId);
3288
+
3289
+            $query = $this->db->getQueryBuilder();
3290
+            $query->insert($this->dbObjectPropertiesTable)
3291
+                ->values(
3292
+                    [
3293
+                        'calendarid' => $query->createNamedParameter($calendarId),
3294
+                        'calendartype' => $query->createNamedParameter($calendarType),
3295
+                        'objectid' => $query->createNamedParameter($objectId),
3296
+                        'name' => $query->createParameter('name'),
3297
+                        'parameter' => $query->createParameter('parameter'),
3298
+                        'value' => $query->createParameter('value'),
3299
+                    ]
3300
+                );
3301
+
3302
+            $indexComponents = ['VEVENT', 'VJOURNAL', 'VTODO'];
3303
+            foreach ($vCalendar->getComponents() as $component) {
3304
+                if (!in_array($component->name, $indexComponents)) {
3305
+                    continue;
3306
+                }
3307
+
3308
+                foreach ($component->children() as $property) {
3309
+                    if (in_array($property->name, self::INDEXED_PROPERTIES, true)) {
3310
+                        $value = $property->getValue();
3311
+                        // is this a shitty db?
3312
+                        if (!$this->db->supports4ByteText()) {
3313
+                            $value = preg_replace('/[\x{10000}-\x{10FFFF}]/u', "\xEF\xBF\xBD", $value);
3314
+                        }
3315
+                        $value = mb_strcut($value, 0, 254);
3316
+
3317
+                        $query->setParameter('name', $property->name);
3318
+                        $query->setParameter('parameter', null);
3319
+                        $query->setParameter('value', mb_strcut($value, 0, 254));
3320
+                        $query->executeStatement();
3321
+                    }
3322
+
3323
+                    if (array_key_exists($property->name, self::$indexParameters)) {
3324
+                        $parameters = $property->parameters();
3325
+                        $indexedParametersForProperty = self::$indexParameters[$property->name];
3326
+
3327
+                        foreach ($parameters as $key => $value) {
3328
+                            if (in_array($key, $indexedParametersForProperty)) {
3329
+                                // is this a shitty db?
3330
+                                if ($this->db->supports4ByteText()) {
3331
+                                    $value = preg_replace('/[\x{10000}-\x{10FFFF}]/u', "\xEF\xBF\xBD", $value);
3332
+                                }
3333
+
3334
+                                $query->setParameter('name', $property->name);
3335
+                                $query->setParameter('parameter', mb_strcut($key, 0, 254));
3336
+                                $query->setParameter('value', mb_strcut($value, 0, 254));
3337
+                                $query->executeStatement();
3338
+                            }
3339
+                        }
3340
+                    }
3341
+                }
3342
+            }
3343
+        }, $this->db);
3344
+    }
3345
+
3346
+    /**
3347
+     * deletes all birthday calendars
3348
+     */
3349
+    public function deleteAllBirthdayCalendars() {
3350
+        $this->atomic(function (): void {
3351
+            $query = $this->db->getQueryBuilder();
3352
+            $result = $query->select(['id'])->from('calendars')
3353
+                ->where($query->expr()->eq('uri', $query->createNamedParameter(BirthdayService::BIRTHDAY_CALENDAR_URI)))
3354
+                ->executeQuery();
3355
+
3356
+            while (($row = $result->fetch()) !== false) {
3357
+                $this->deleteCalendar(
3358
+                    $row['id'],
3359
+                    true // No data to keep in the trashbin, if the user re-enables then we regenerate
3360
+                );
3361
+            }
3362
+            $result->closeCursor();
3363
+        }, $this->db);
3364
+    }
3365
+
3366
+    /**
3367
+     * @param $subscriptionId
3368
+     */
3369
+    public function purgeAllCachedEventsForSubscription($subscriptionId) {
3370
+        $this->atomic(function () use ($subscriptionId): void {
3371
+            $query = $this->db->getQueryBuilder();
3372
+            $query->select('uri')
3373
+                ->from('calendarobjects')
3374
+                ->where($query->expr()->eq('calendarid', $query->createNamedParameter($subscriptionId)))
3375
+                ->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)));
3376
+            $stmt = $query->executeQuery();
3377
+
3378
+            $uris = [];
3379
+            while (($row = $stmt->fetch()) !== false) {
3380
+                $uris[] = $row['uri'];
3381
+            }
3382
+            $stmt->closeCursor();
3383
+
3384
+            $query = $this->db->getQueryBuilder();
3385
+            $query->delete('calendarobjects')
3386
+                ->where($query->expr()->eq('calendarid', $query->createNamedParameter($subscriptionId)))
3387
+                ->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)))
3388
+                ->executeStatement();
3389
+
3390
+            $query = $this->db->getQueryBuilder();
3391
+            $query->delete('calendarchanges')
3392
+                ->where($query->expr()->eq('calendarid', $query->createNamedParameter($subscriptionId)))
3393
+                ->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)))
3394
+                ->executeStatement();
3395
+
3396
+            $query = $this->db->getQueryBuilder();
3397
+            $query->delete($this->dbObjectPropertiesTable)
3398
+                ->where($query->expr()->eq('calendarid', $query->createNamedParameter($subscriptionId)))
3399
+                ->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)))
3400
+                ->executeStatement();
3401
+
3402
+            $this->addChanges($subscriptionId, $uris, 3, self::CALENDAR_TYPE_SUBSCRIPTION);
3403
+        }, $this->db);
3404
+    }
3405
+
3406
+    /**
3407
+     * @param int $subscriptionId
3408
+     * @param array<int> $calendarObjectIds
3409
+     * @param array<string> $calendarObjectUris
3410
+     */
3411
+    public function purgeCachedEventsForSubscription(int $subscriptionId, array $calendarObjectIds, array $calendarObjectUris): void {
3412
+        if (empty($calendarObjectUris)) {
3413
+            return;
3414
+        }
3415
+
3416
+        $this->atomic(function () use ($subscriptionId, $calendarObjectIds, $calendarObjectUris): void {
3417
+            foreach (array_chunk($calendarObjectIds, 1000) as $chunk) {
3418
+                $query = $this->db->getQueryBuilder();
3419
+                $query->delete($this->dbObjectPropertiesTable)
3420
+                    ->where($query->expr()->eq('calendarid', $query->createNamedParameter($subscriptionId)))
3421
+                    ->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)))
3422
+                    ->andWhere($query->expr()->in('id', $query->createNamedParameter($chunk, IQueryBuilder::PARAM_INT_ARRAY), IQueryBuilder::PARAM_INT_ARRAY))
3423
+                    ->executeStatement();
3424
+
3425
+                $query = $this->db->getQueryBuilder();
3426
+                $query->delete('calendarobjects')
3427
+                    ->where($query->expr()->eq('calendarid', $query->createNamedParameter($subscriptionId)))
3428
+                    ->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)))
3429
+                    ->andWhere($query->expr()->in('id', $query->createNamedParameter($chunk, IQueryBuilder::PARAM_INT_ARRAY), IQueryBuilder::PARAM_INT_ARRAY))
3430
+                    ->executeStatement();
3431
+            }
3432
+
3433
+            foreach (array_chunk($calendarObjectUris, 1000) as $chunk) {
3434
+                $query = $this->db->getQueryBuilder();
3435
+                $query->delete('calendarchanges')
3436
+                    ->where($query->expr()->eq('calendarid', $query->createNamedParameter($subscriptionId)))
3437
+                    ->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)))
3438
+                    ->andWhere($query->expr()->in('uri', $query->createNamedParameter($chunk, IQueryBuilder::PARAM_STR_ARRAY), IQueryBuilder::PARAM_STR_ARRAY))
3439
+                    ->executeStatement();
3440
+            }
3441
+            $this->addChanges($subscriptionId, $calendarObjectUris, 3, self::CALENDAR_TYPE_SUBSCRIPTION);
3442
+        }, $this->db);
3443
+    }
3444
+
3445
+    /**
3446
+     * Move a calendar from one user to another
3447
+     *
3448
+     * @param string $uriName
3449
+     * @param string $uriOrigin
3450
+     * @param string $uriDestination
3451
+     * @param string $newUriName (optional) the new uriName
3452
+     */
3453
+    public function moveCalendar($uriName, $uriOrigin, $uriDestination, $newUriName = null) {
3454
+        $query = $this->db->getQueryBuilder();
3455
+        $query->update('calendars')
3456
+            ->set('principaluri', $query->createNamedParameter($uriDestination))
3457
+            ->set('uri', $query->createNamedParameter($newUriName ?: $uriName))
3458
+            ->where($query->expr()->eq('principaluri', $query->createNamedParameter($uriOrigin)))
3459
+            ->andWhere($query->expr()->eq('uri', $query->createNamedParameter($uriName)))
3460
+            ->executeStatement();
3461
+    }
3462
+
3463
+    /**
3464
+     * read VCalendar data into a VCalendar object
3465
+     *
3466
+     * @param string $objectData
3467
+     * @return VCalendar
3468
+     */
3469
+    protected function readCalendarData($objectData) {
3470
+        return Reader::read($objectData);
3471
+    }
3472
+
3473
+    /**
3474
+     * delete all properties from a given calendar object
3475
+     *
3476
+     * @param int $calendarId
3477
+     * @param int $objectId
3478
+     */
3479
+    protected function purgeProperties($calendarId, $objectId) {
3480
+        $this->cachedObjects = [];
3481
+        $query = $this->db->getQueryBuilder();
3482
+        $query->delete($this->dbObjectPropertiesTable)
3483
+            ->where($query->expr()->eq('objectid', $query->createNamedParameter($objectId)))
3484
+            ->andWhere($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)));
3485
+        $query->executeStatement();
3486
+    }
3487
+
3488
+    /**
3489
+     * get ID from a given calendar object
3490
+     *
3491
+     * @param int $calendarId
3492
+     * @param string $uri
3493
+     * @param int $calendarType
3494
+     * @return int
3495
+     */
3496
+    protected function getCalendarObjectId($calendarId, $uri, $calendarType):int {
3497
+        $query = $this->db->getQueryBuilder();
3498
+        $query->select('id')
3499
+            ->from('calendarobjects')
3500
+            ->where($query->expr()->eq('uri', $query->createNamedParameter($uri)))
3501
+            ->andWhere($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)))
3502
+            ->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter($calendarType)));
3503
+
3504
+        $result = $query->executeQuery();
3505
+        $objectIds = $result->fetch();
3506
+        $result->closeCursor();
3507
+
3508
+        if (!isset($objectIds['id'])) {
3509
+            throw new \InvalidArgumentException('Calendarobject does not exists: ' . $uri);
3510
+        }
3511
+
3512
+        return (int)$objectIds['id'];
3513
+    }
3514
+
3515
+    /**
3516
+     * @throws \InvalidArgumentException
3517
+     */
3518
+    public function pruneOutdatedSyncTokens(int $keep, int $retention): int {
3519
+        if ($keep < 0) {
3520
+            throw new \InvalidArgumentException();
3521
+        }
3522
+
3523
+        $query = $this->db->getQueryBuilder();
3524
+        $query->select($query->func()->max('id'))
3525
+            ->from('calendarchanges');
3526
+
3527
+        $result = $query->executeQuery();
3528
+        $maxId = (int)$result->fetchOne();
3529
+        $result->closeCursor();
3530
+        if (!$maxId || $maxId < $keep) {
3531
+            return 0;
3532
+        }
3533
+
3534
+        $query = $this->db->getQueryBuilder();
3535
+        $query->delete('calendarchanges')
3536
+            ->where(
3537
+                $query->expr()->lte('id', $query->createNamedParameter($maxId - $keep, IQueryBuilder::PARAM_INT), IQueryBuilder::PARAM_INT),
3538
+                $query->expr()->lte('created_at', $query->createNamedParameter($retention)),
3539
+            );
3540
+        return $query->executeStatement();
3541
+    }
3542
+
3543
+    /**
3544
+     * return legacy endpoint principal name to new principal name
3545
+     *
3546
+     * @param $principalUri
3547
+     * @param $toV2
3548
+     * @return string
3549
+     */
3550
+    private function convertPrincipal($principalUri, $toV2) {
3551
+        if ($this->principalBackend->getPrincipalPrefix() === 'principals') {
3552
+            [, $name] = Uri\split($principalUri);
3553
+            if ($toV2 === true) {
3554
+                return "principals/users/$name";
3555
+            }
3556
+            return "principals/$name";
3557
+        }
3558
+        return $principalUri;
3559
+    }
3560
+
3561
+    /**
3562
+     * adds information about an owner to the calendar data
3563
+     *
3564
+     */
3565
+    private function addOwnerPrincipalToCalendar(array $calendarInfo): array {
3566
+        $ownerPrincipalKey = '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal';
3567
+        $displaynameKey = '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_NEXTCLOUD . '}owner-displayname';
3568
+        if (isset($calendarInfo[$ownerPrincipalKey])) {
3569
+            $uri = $calendarInfo[$ownerPrincipalKey];
3570
+        } else {
3571
+            $uri = $calendarInfo['principaluri'];
3572
+        }
3573
+
3574
+        $principalInformation = $this->principalBackend->getPrincipalByPath($uri);
3575
+        if (isset($principalInformation['{DAV:}displayname'])) {
3576
+            $calendarInfo[$displaynameKey] = $principalInformation['{DAV:}displayname'];
3577
+        }
3578
+        return $calendarInfo;
3579
+    }
3580
+
3581
+    private function addResourceTypeToCalendar(array $row, array $calendar): array {
3582
+        if (isset($row['deleted_at'])) {
3583
+            // Columns is set and not null -> this is a deleted calendar
3584
+            // we send a custom resourcetype to hide the deleted calendar
3585
+            // from ordinary DAV clients, but the Calendar app will know
3586
+            // how to handle this special resource.
3587
+            $calendar['{DAV:}resourcetype'] = new DAV\Xml\Property\ResourceType([
3588
+                '{DAV:}collection',
3589
+                sprintf('{%s}deleted-calendar', \OCA\DAV\DAV\Sharing\Plugin::NS_NEXTCLOUD),
3590
+            ]);
3591
+        }
3592
+        return $calendar;
3593
+    }
3594
+
3595
+    /**
3596
+     * Amend the calendar info with database row data
3597
+     *
3598
+     * @param array $row
3599
+     * @param array $calendar
3600
+     *
3601
+     * @return array
3602
+     */
3603
+    private function rowToCalendar($row, array $calendar): array {
3604
+        foreach ($this->propertyMap as $xmlName => [$dbName, $type]) {
3605
+            $value = $row[$dbName];
3606
+            if ($value !== null) {
3607
+                settype($value, $type);
3608
+            }
3609
+            $calendar[$xmlName] = $value;
3610
+        }
3611
+        return $calendar;
3612
+    }
3613
+
3614
+    /**
3615
+     * Amend the subscription info with database row data
3616
+     *
3617
+     * @param array $row
3618
+     * @param array $subscription
3619
+     *
3620
+     * @return array
3621
+     */
3622
+    private function rowToSubscription($row, array $subscription): array {
3623
+        foreach ($this->subscriptionPropertyMap as $xmlName => [$dbName, $type]) {
3624
+            $value = $row[$dbName];
3625
+            if ($value !== null) {
3626
+                settype($value, $type);
3627
+            }
3628
+            $subscription[$xmlName] = $value;
3629
+        }
3630
+        return $subscription;
3631
+    }
3632
+
3633
+    /**
3634
+     * delete all invitations from a given calendar
3635
+     *
3636
+     * @since 31.0.0
3637
+     *
3638
+     * @param int $calendarId
3639
+     *
3640
+     * @return void
3641
+     */
3642
+    protected function purgeCalendarInvitations(int $calendarId): void {
3643
+        // select all calendar object uid's
3644
+        $cmd = $this->db->getQueryBuilder();
3645
+        $cmd->select('uid')
3646
+            ->from($this->dbObjectsTable)
3647
+            ->where($cmd->expr()->eq('calendarid', $cmd->createNamedParameter($calendarId)));
3648
+        $allIds = $cmd->executeQuery()->fetchAll(\PDO::FETCH_COLUMN);
3649
+        // delete all links that match object uid's
3650
+        $cmd = $this->db->getQueryBuilder();
3651
+        $cmd->delete($this->dbObjectInvitationsTable)
3652
+            ->where($cmd->expr()->in('uid', $cmd->createParameter('uids'), IQueryBuilder::PARAM_STR_ARRAY));
3653
+        foreach (array_chunk($allIds, 1000) as $chunkIds) {
3654
+            $cmd->setParameter('uids', $chunkIds, IQueryBuilder::PARAM_STR_ARRAY);
3655
+            $cmd->executeStatement();
3656
+        }
3657
+    }
3658
+
3659
+    /**
3660
+     * Delete all invitations from a given calendar event
3661
+     *
3662
+     * @since 31.0.0
3663
+     *
3664
+     * @param string $eventId UID of the event
3665
+     *
3666
+     * @return void
3667
+     */
3668
+    protected function purgeObjectInvitations(string $eventId): void {
3669
+        $cmd = $this->db->getQueryBuilder();
3670
+        $cmd->delete($this->dbObjectInvitationsTable)
3671
+            ->where($cmd->expr()->eq('uid', $cmd->createNamedParameter($eventId, IQueryBuilder::PARAM_STR), IQueryBuilder::PARAM_STR));
3672
+        $cmd->executeStatement();
3673
+    }
3674 3674
 }
Please login to merge, or discard this patch.
apps/dav/lib/CalDAV/Export/ExportService.php 1 patch
Indentation   +78 added lines, -78 removed lines patch added patch discarded remove patch
@@ -19,89 +19,89 @@
 block discarded – undo
19 19
  */
20 20
 class ExportService {
21 21
 	
22
-	public const FORMATS = ['ical', 'jcal', 'xcal'];
23
-	private string $systemVersion;
22
+    public const FORMATS = ['ical', 'jcal', 'xcal'];
23
+    private string $systemVersion;
24 24
 
25
-	public function __construct(ServerVersion $serverVersion) {
26
-		$this->systemVersion = $serverVersion->getVersionString();
27
-	}
25
+    public function __construct(ServerVersion $serverVersion) {
26
+        $this->systemVersion = $serverVersion->getVersionString();
27
+    }
28 28
 
29
-	/**
30
-	 * Generates serialized content stream for a calendar and objects based in selected format
31
-	 *
32
-	 * @return Generator<string>
33
-	 */
34
-	public function export(ICalendarExport $calendar, CalendarExportOptions $options): Generator {
35
-		// output start of serialized content based on selected format
36
-		yield $this->exportStart($options->getFormat());
37
-		// iterate through each returned vCalendar entry
38
-		// extract each component except timezones, convert to appropriate format and output
39
-		// extract any timezones and save them but do not output
40
-		$timezones = [];
41
-		foreach ($calendar->export($options) as $entry) {
42
-			$consecutive = false;
43
-			foreach ($entry->getComponents() as $vComponent) {
44
-				if ($vComponent->name === 'VTIMEZONE') {
45
-					if (isset($vComponent->TZID) && !isset($timezones[$vComponent->TZID->getValue()])) {
46
-						$timezones[$vComponent->TZID->getValue()] = clone $vComponent;
47
-					}
48
-				} else {
49
-					yield $this->exportObject($vComponent, $options->getFormat(), $consecutive);
50
-					$consecutive = true;
51
-				}
52
-			}
53
-		}
54
-		// iterate through each saved vTimezone entry, convert to appropriate format and output
55
-		foreach ($timezones as $vComponent) {
56
-			yield $this->exportObject($vComponent, $options->getFormat(), $consecutive);
57
-			$consecutive = true;
58
-		}
59
-		// output end of serialized content based on selected format
60
-		yield $this->exportFinish($options->getFormat());
61
-	}
29
+    /**
30
+     * Generates serialized content stream for a calendar and objects based in selected format
31
+     *
32
+     * @return Generator<string>
33
+     */
34
+    public function export(ICalendarExport $calendar, CalendarExportOptions $options): Generator {
35
+        // output start of serialized content based on selected format
36
+        yield $this->exportStart($options->getFormat());
37
+        // iterate through each returned vCalendar entry
38
+        // extract each component except timezones, convert to appropriate format and output
39
+        // extract any timezones and save them but do not output
40
+        $timezones = [];
41
+        foreach ($calendar->export($options) as $entry) {
42
+            $consecutive = false;
43
+            foreach ($entry->getComponents() as $vComponent) {
44
+                if ($vComponent->name === 'VTIMEZONE') {
45
+                    if (isset($vComponent->TZID) && !isset($timezones[$vComponent->TZID->getValue()])) {
46
+                        $timezones[$vComponent->TZID->getValue()] = clone $vComponent;
47
+                    }
48
+                } else {
49
+                    yield $this->exportObject($vComponent, $options->getFormat(), $consecutive);
50
+                    $consecutive = true;
51
+                }
52
+            }
53
+        }
54
+        // iterate through each saved vTimezone entry, convert to appropriate format and output
55
+        foreach ($timezones as $vComponent) {
56
+            yield $this->exportObject($vComponent, $options->getFormat(), $consecutive);
57
+            $consecutive = true;
58
+        }
59
+        // output end of serialized content based on selected format
60
+        yield $this->exportFinish($options->getFormat());
61
+    }
62 62
 
63
-	/**
64
-	 * Generates serialized content start based on selected format
65
-	 */
66
-	private function exportStart(string $format): string {
67
-		return match ($format) {
68
-			'jcal' => '["vcalendar",[["version",{},"text","2.0"],["prodid",{},"text","-\/\/IDN nextcloud.com\/\/Calendar Export v' . $this->systemVersion . '\/\/EN"]],[',
69
-			'xcal' => '<?xml version="1.0" encoding="UTF-8"?><icalendar xmlns="urn:ietf:params:xml:ns:icalendar-2.0"><vcalendar><properties><version><text>2.0</text></version><prodid><text>-//IDN nextcloud.com//Calendar Export v' . $this->systemVersion . '//EN</text></prodid></properties><components>',
70
-			default => "BEGIN:VCALENDAR\nVERSION:2.0\nPRODID:-//IDN nextcloud.com//Calendar Export v" . $this->systemVersion . "//EN\n"
71
-		};
72
-	}
63
+    /**
64
+     * Generates serialized content start based on selected format
65
+     */
66
+    private function exportStart(string $format): string {
67
+        return match ($format) {
68
+            'jcal' => '["vcalendar",[["version",{},"text","2.0"],["prodid",{},"text","-\/\/IDN nextcloud.com\/\/Calendar Export v' . $this->systemVersion . '\/\/EN"]],[',
69
+            'xcal' => '<?xml version="1.0" encoding="UTF-8"?><icalendar xmlns="urn:ietf:params:xml:ns:icalendar-2.0"><vcalendar><properties><version><text>2.0</text></version><prodid><text>-//IDN nextcloud.com//Calendar Export v' . $this->systemVersion . '//EN</text></prodid></properties><components>',
70
+            default => "BEGIN:VCALENDAR\nVERSION:2.0\nPRODID:-//IDN nextcloud.com//Calendar Export v" . $this->systemVersion . "//EN\n"
71
+        };
72
+    }
73 73
 
74
-	/**
75
-	 * Generates serialized content end based on selected format
76
-	 */
77
-	private function exportFinish(string $format): string {
78
-		return match ($format) {
79
-			'jcal' => ']]',
80
-			'xcal' => '</components></vcalendar></icalendar>',
81
-			default => "END:VCALENDAR\n"
82
-		};
83
-	}
74
+    /**
75
+     * Generates serialized content end based on selected format
76
+     */
77
+    private function exportFinish(string $format): string {
78
+        return match ($format) {
79
+            'jcal' => ']]',
80
+            'xcal' => '</components></vcalendar></icalendar>',
81
+            default => "END:VCALENDAR\n"
82
+        };
83
+    }
84 84
 
85
-	/**
86
-	 * Generates serialized content for a component based on selected format
87
-	 */
88
-	private function exportObject(Component $vobject, string $format, bool $consecutive): string {
89
-		return match ($format) {
90
-			'jcal' => $consecutive ? ',' . Writer::writeJson($vobject) : Writer::writeJson($vobject),
91
-			'xcal' => $this->exportObjectXml($vobject),
92
-			default => Writer::write($vobject)
93
-		};
94
-	}
85
+    /**
86
+     * Generates serialized content for a component based on selected format
87
+     */
88
+    private function exportObject(Component $vobject, string $format, bool $consecutive): string {
89
+        return match ($format) {
90
+            'jcal' => $consecutive ? ',' . Writer::writeJson($vobject) : Writer::writeJson($vobject),
91
+            'xcal' => $this->exportObjectXml($vobject),
92
+            default => Writer::write($vobject)
93
+        };
94
+    }
95 95
 	
96
-	/**
97
-	 * Generates serialized content for a component in xml format
98
-	 */
99
-	private function exportObjectXml(Component $vobject): string {
100
-		$writer = new \Sabre\Xml\Writer();
101
-		$writer->openMemory();
102
-		$writer->setIndent(false);
103
-		$vobject->xmlSerialize($writer);
104
-		return $writer->outputMemory();
105
-	}
96
+    /**
97
+     * Generates serialized content for a component in xml format
98
+     */
99
+    private function exportObjectXml(Component $vobject): string {
100
+        $writer = new \Sabre\Xml\Writer();
101
+        $writer->openMemory();
102
+        $writer->setIndent(false);
103
+        $vobject->xmlSerialize($writer);
104
+        return $writer->outputMemory();
105
+    }
106 106
 
107 107
 }
Please login to merge, or discard this patch.
apps/dav/lib/CalDAV/CalendarImpl.php 1 patch
Indentation   +254 added lines, -254 removed lines patch added patch discarded remove patch
@@ -30,259 +30,259 @@
 block discarded – undo
30 30
 use function Sabre\Uri\split as uriSplit;
31 31
 
32 32
 class CalendarImpl implements ICreateFromString, IHandleImipMessage, ICalendarIsWritable, ICalendarIsShared, ICalendarExport {
33
-	public function __construct(
34
-		private Calendar $calendar,
35
-		/** @var array<string, mixed> */
36
-		private array $calendarInfo,
37
-		private CalDavBackend $backend,
38
-	) {
39
-	}
40
-
41
-	/**
42
-	 * @return string defining the technical unique key
43
-	 * @since 13.0.0
44
-	 */
45
-	public function getKey(): string {
46
-		return (string)$this->calendarInfo['id'];
47
-	}
48
-
49
-	/**
50
-	 * {@inheritDoc}
51
-	 */
52
-	public function getUri(): string {
53
-		return $this->calendarInfo['uri'];
54
-	}
55
-
56
-	/**
57
-	 * In comparison to getKey() this function returns a human readable (maybe translated) name
58
-	 * @since 13.0.0
59
-	 */
60
-	public function getDisplayName(): ?string {
61
-		return $this->calendarInfo['{DAV:}displayname'];
62
-	}
63
-
64
-	/**
65
-	 * Calendar color
66
-	 * @since 13.0.0
67
-	 */
68
-	public function getDisplayColor(): ?string {
69
-		return $this->calendarInfo['{http://apple.com/ns/ical/}calendar-color'];
70
-	}
71
-
72
-	public function getSchedulingTransparency(): ?ScheduleCalendarTransp {
73
-		return $this->calendarInfo['{' . \OCA\DAV\CalDAV\Schedule\Plugin::NS_CALDAV . '}schedule-calendar-transp'];
74
-	}
75
-
76
-	public function getSchedulingTimezone(): ?VTimeZone {
77
-		$tzProp = '{' . \OCA\DAV\CalDAV\Schedule\Plugin::NS_CALDAV . '}calendar-timezone';
78
-		if (!isset($this->calendarInfo[$tzProp])) {
79
-			return null;
80
-		}
81
-		// This property contains a VCALENDAR with a single VTIMEZONE
82
-		/** @var string $timezoneProp */
83
-		$timezoneProp = $this->calendarInfo[$tzProp];
84
-		/** @var VCalendar $vobj */
85
-		$vobj = Reader::read($timezoneProp);
86
-		$components = $vobj->getComponents();
87
-		if (empty($components)) {
88
-			return null;
89
-		}
90
-		/** @var VTimeZone $vtimezone */
91
-		$vtimezone = $components[0];
92
-		return $vtimezone;
93
-	}
94
-
95
-	/**
96
-	 * @param string $pattern which should match within the $searchProperties
97
-	 * @param array $searchProperties defines the properties within the query pattern should match
98
-	 * @param array $options - optional parameters:
99
-	 *                       ['timerange' => ['start' => new DateTime(...), 'end' => new DateTime(...)]]
100
-	 * @param int|null $limit - limit number of search results
101
-	 * @param int|null $offset - offset for paging of search results
102
-	 * @return array an array of events/journals/todos which are arrays of key-value-pairs
103
-	 * @since 13.0.0
104
-	 */
105
-	public function search(string $pattern, array $searchProperties = [], array $options = [], $limit = null, $offset = null): array {
106
-		return $this->backend->search($this->calendarInfo, $pattern,
107
-			$searchProperties, $options, $limit, $offset);
108
-	}
109
-
110
-	/**
111
-	 * @return int build up using \OCP\Constants
112
-	 * @since 13.0.0
113
-	 */
114
-	public function getPermissions(): int {
115
-		$permissions = $this->calendar->getACL();
116
-		$result = 0;
117
-		foreach ($permissions as $permission) {
118
-			if ($this->calendarInfo['principaluri'] !== $permission['principal']) {
119
-				continue;
120
-			}
121
-
122
-			switch ($permission['privilege']) {
123
-				case '{DAV:}read':
124
-					$result |= Constants::PERMISSION_READ;
125
-					break;
126
-				case '{DAV:}write':
127
-					$result |= Constants::PERMISSION_CREATE;
128
-					$result |= Constants::PERMISSION_UPDATE;
129
-					break;
130
-				case '{DAV:}all':
131
-					$result |= Constants::PERMISSION_ALL;
132
-					break;
133
-			}
134
-		}
135
-
136
-		return $result;
137
-	}
138
-
139
-	/**
140
-	 * @since 31.0.0
141
-	 */
142
-	public function isWritable(): bool {
143
-		return $this->calendar->canWrite();
144
-	}
145
-
146
-	/**
147
-	 * @since 26.0.0
148
-	 */
149
-	public function isDeleted(): bool {
150
-		return $this->calendar->isDeleted();
151
-	}
152
-
153
-	/**
154
-	 * @since 31.0.0
155
-	 */
156
-	public function isShared(): bool {
157
-		return $this->calendar->isShared();
158
-	}
159
-
160
-	/**
161
-	 * Create a new calendar event for this calendar
162
-	 * by way of an ICS string
163
-	 *
164
-	 * @param string $name the file name - needs to contain the .ics ending
165
-	 * @param string $calendarData a string containing a valid VEVENT ics
166
-	 *
167
-	 * @throws CalendarException
168
-	 */
169
-	public function createFromString(string $name, string $calendarData): void {
170
-		$server = new InvitationResponseServer(false);
171
-
172
-		/** @var CustomPrincipalPlugin $plugin */
173
-		$plugin = $server->getServer()->getPlugin('auth');
174
-		// we're working around the previous implementation
175
-		// that only allowed the public system principal to be used
176
-		// so set the custom principal here
177
-		$plugin->setCurrentPrincipal($this->calendar->getPrincipalURI());
178
-
179
-		if (empty($this->calendarInfo['uri'])) {
180
-			throw new CalendarException('Could not write to calendar as URI parameter is missing');
181
-		}
182
-
183
-		// Build full calendar path
184
-		[, $user] = uriSplit($this->calendar->getPrincipalURI());
185
-		$fullCalendarFilename = sprintf('calendars/%s/%s/%s', $user, $this->calendarInfo['uri'], $name);
186
-
187
-		// Force calendar change URI
188
-		/** @var Schedule\Plugin $schedulingPlugin */
189
-		$schedulingPlugin = $server->getServer()->getPlugin('caldav-schedule');
190
-		$schedulingPlugin->setPathOfCalendarObjectChange($fullCalendarFilename);
191
-
192
-		$stream = fopen('php://memory', 'rb+');
193
-		fwrite($stream, $calendarData);
194
-		rewind($stream);
195
-		try {
196
-			$server->getServer()->createFile($fullCalendarFilename, $stream);
197
-		} catch (Conflict $e) {
198
-			throw new CalendarException('Could not create new calendar event: ' . $e->getMessage(), 0, $e);
199
-		} finally {
200
-			fclose($stream);
201
-		}
202
-	}
203
-
204
-	/**
205
-	 * @throws CalendarException
206
-	 */
207
-	public function handleIMipMessage(string $name, string $calendarData): void {
208
-		$server = $this->getInvitationResponseServer();
209
-
210
-		/** @var CustomPrincipalPlugin $plugin */
211
-		$plugin = $server->getServer()->getPlugin('auth');
212
-		// we're working around the previous implementation
213
-		// that only allowed the public system principal to be used
214
-		// so set the custom principal here
215
-		$plugin->setCurrentPrincipal($this->calendar->getPrincipalURI());
216
-
217
-		if (empty($this->calendarInfo['uri'])) {
218
-			throw new CalendarException('Could not write to calendar as URI parameter is missing');
219
-		}
220
-		// Force calendar change URI
221
-		/** @var Schedule\Plugin $schedulingPlugin */
222
-		$schedulingPlugin = $server->getServer()->getPlugin('caldav-schedule');
223
-		// Let sabre handle the rest
224
-		$iTipMessage = new Message();
225
-		/** @var VCalendar $vObject */
226
-		$vObject = Reader::read($calendarData);
227
-		/** @var VEvent $vEvent */
228
-		$vEvent = $vObject->{'VEVENT'};
229
-
230
-		if ($vObject->{'METHOD'} === null) {
231
-			throw new CalendarException('No Method provided for scheduling data. Could not process message');
232
-		}
233
-
234
-		if (!isset($vEvent->{'ORGANIZER'}) || !isset($vEvent->{'ATTENDEE'})) {
235
-			throw new CalendarException('Could not process scheduling data, neccessary data missing from ICAL');
236
-		}
237
-		$organizer = $vEvent->{'ORGANIZER'}->getValue();
238
-		$attendee = $vEvent->{'ATTENDEE'}->getValue();
239
-
240
-		$iTipMessage->method = $vObject->{'METHOD'}->getValue();
241
-		if ($iTipMessage->method === 'REQUEST') {
242
-			$iTipMessage->sender = $organizer;
243
-			$iTipMessage->recipient = $attendee;
244
-		} elseif ($iTipMessage->method === 'REPLY') {
245
-			if ($server->isExternalAttendee($vEvent->{'ATTENDEE'}->getValue())) {
246
-				$iTipMessage->recipient = $organizer;
247
-			} else {
248
-				$iTipMessage->recipient = $attendee;
249
-			}
250
-			$iTipMessage->sender = $attendee;
251
-		} elseif ($iTipMessage->method === 'CANCEL') {
252
-			$iTipMessage->recipient = $attendee;
253
-			$iTipMessage->sender = $organizer;
254
-		}
255
-		$iTipMessage->uid = isset($vEvent->{'UID'}) ? $vEvent->{'UID'}->getValue() : '';
256
-		$iTipMessage->component = 'VEVENT';
257
-		$iTipMessage->sequence = isset($vEvent->{'SEQUENCE'}) ? (int)$vEvent->{'SEQUENCE'}->getValue() : 0;
258
-		$iTipMessage->message = $vObject;
259
-		$server->server->emit('schedule', [$iTipMessage]);
260
-	}
261
-
262
-	public function getInvitationResponseServer(): InvitationResponseServer {
263
-		return new InvitationResponseServer(false);
264
-	}
265
-
266
-	/**
267
-	 * Export objects
268
-	 *
269
-	 * @since 32.0.0
270
-	 *
271
-	 * @return Generator<mixed, \Sabre\VObject\Component\VCalendar, mixed, mixed>
272
-	 */
273
-	public function export(?CalendarExportOptions $options = null): Generator {
274
-		foreach (
275
-			$this->backend->exportCalendar(
276
-				$this->calendarInfo['id'],
277
-				$this->backend::CALENDAR_TYPE_CALENDAR,
278
-				$options
279
-			) as $event
280
-		) {
281
-			$vObject = Reader::read($event['calendardata']);
282
-			if ($vObject instanceof VCalendar) {
283
-				yield $vObject;
284
-			}
285
-		}
286
-	}
33
+    public function __construct(
34
+        private Calendar $calendar,
35
+        /** @var array<string, mixed> */
36
+        private array $calendarInfo,
37
+        private CalDavBackend $backend,
38
+    ) {
39
+    }
40
+
41
+    /**
42
+     * @return string defining the technical unique key
43
+     * @since 13.0.0
44
+     */
45
+    public function getKey(): string {
46
+        return (string)$this->calendarInfo['id'];
47
+    }
48
+
49
+    /**
50
+     * {@inheritDoc}
51
+     */
52
+    public function getUri(): string {
53
+        return $this->calendarInfo['uri'];
54
+    }
55
+
56
+    /**
57
+     * In comparison to getKey() this function returns a human readable (maybe translated) name
58
+     * @since 13.0.0
59
+     */
60
+    public function getDisplayName(): ?string {
61
+        return $this->calendarInfo['{DAV:}displayname'];
62
+    }
63
+
64
+    /**
65
+     * Calendar color
66
+     * @since 13.0.0
67
+     */
68
+    public function getDisplayColor(): ?string {
69
+        return $this->calendarInfo['{http://apple.com/ns/ical/}calendar-color'];
70
+    }
71
+
72
+    public function getSchedulingTransparency(): ?ScheduleCalendarTransp {
73
+        return $this->calendarInfo['{' . \OCA\DAV\CalDAV\Schedule\Plugin::NS_CALDAV . '}schedule-calendar-transp'];
74
+    }
75
+
76
+    public function getSchedulingTimezone(): ?VTimeZone {
77
+        $tzProp = '{' . \OCA\DAV\CalDAV\Schedule\Plugin::NS_CALDAV . '}calendar-timezone';
78
+        if (!isset($this->calendarInfo[$tzProp])) {
79
+            return null;
80
+        }
81
+        // This property contains a VCALENDAR with a single VTIMEZONE
82
+        /** @var string $timezoneProp */
83
+        $timezoneProp = $this->calendarInfo[$tzProp];
84
+        /** @var VCalendar $vobj */
85
+        $vobj = Reader::read($timezoneProp);
86
+        $components = $vobj->getComponents();
87
+        if (empty($components)) {
88
+            return null;
89
+        }
90
+        /** @var VTimeZone $vtimezone */
91
+        $vtimezone = $components[0];
92
+        return $vtimezone;
93
+    }
94
+
95
+    /**
96
+     * @param string $pattern which should match within the $searchProperties
97
+     * @param array $searchProperties defines the properties within the query pattern should match
98
+     * @param array $options - optional parameters:
99
+     *                       ['timerange' => ['start' => new DateTime(...), 'end' => new DateTime(...)]]
100
+     * @param int|null $limit - limit number of search results
101
+     * @param int|null $offset - offset for paging of search results
102
+     * @return array an array of events/journals/todos which are arrays of key-value-pairs
103
+     * @since 13.0.0
104
+     */
105
+    public function search(string $pattern, array $searchProperties = [], array $options = [], $limit = null, $offset = null): array {
106
+        return $this->backend->search($this->calendarInfo, $pattern,
107
+            $searchProperties, $options, $limit, $offset);
108
+    }
109
+
110
+    /**
111
+     * @return int build up using \OCP\Constants
112
+     * @since 13.0.0
113
+     */
114
+    public function getPermissions(): int {
115
+        $permissions = $this->calendar->getACL();
116
+        $result = 0;
117
+        foreach ($permissions as $permission) {
118
+            if ($this->calendarInfo['principaluri'] !== $permission['principal']) {
119
+                continue;
120
+            }
121
+
122
+            switch ($permission['privilege']) {
123
+                case '{DAV:}read':
124
+                    $result |= Constants::PERMISSION_READ;
125
+                    break;
126
+                case '{DAV:}write':
127
+                    $result |= Constants::PERMISSION_CREATE;
128
+                    $result |= Constants::PERMISSION_UPDATE;
129
+                    break;
130
+                case '{DAV:}all':
131
+                    $result |= Constants::PERMISSION_ALL;
132
+                    break;
133
+            }
134
+        }
135
+
136
+        return $result;
137
+    }
138
+
139
+    /**
140
+     * @since 31.0.0
141
+     */
142
+    public function isWritable(): bool {
143
+        return $this->calendar->canWrite();
144
+    }
145
+
146
+    /**
147
+     * @since 26.0.0
148
+     */
149
+    public function isDeleted(): bool {
150
+        return $this->calendar->isDeleted();
151
+    }
152
+
153
+    /**
154
+     * @since 31.0.0
155
+     */
156
+    public function isShared(): bool {
157
+        return $this->calendar->isShared();
158
+    }
159
+
160
+    /**
161
+     * Create a new calendar event for this calendar
162
+     * by way of an ICS string
163
+     *
164
+     * @param string $name the file name - needs to contain the .ics ending
165
+     * @param string $calendarData a string containing a valid VEVENT ics
166
+     *
167
+     * @throws CalendarException
168
+     */
169
+    public function createFromString(string $name, string $calendarData): void {
170
+        $server = new InvitationResponseServer(false);
171
+
172
+        /** @var CustomPrincipalPlugin $plugin */
173
+        $plugin = $server->getServer()->getPlugin('auth');
174
+        // we're working around the previous implementation
175
+        // that only allowed the public system principal to be used
176
+        // so set the custom principal here
177
+        $plugin->setCurrentPrincipal($this->calendar->getPrincipalURI());
178
+
179
+        if (empty($this->calendarInfo['uri'])) {
180
+            throw new CalendarException('Could not write to calendar as URI parameter is missing');
181
+        }
182
+
183
+        // Build full calendar path
184
+        [, $user] = uriSplit($this->calendar->getPrincipalURI());
185
+        $fullCalendarFilename = sprintf('calendars/%s/%s/%s', $user, $this->calendarInfo['uri'], $name);
186
+
187
+        // Force calendar change URI
188
+        /** @var Schedule\Plugin $schedulingPlugin */
189
+        $schedulingPlugin = $server->getServer()->getPlugin('caldav-schedule');
190
+        $schedulingPlugin->setPathOfCalendarObjectChange($fullCalendarFilename);
191
+
192
+        $stream = fopen('php://memory', 'rb+');
193
+        fwrite($stream, $calendarData);
194
+        rewind($stream);
195
+        try {
196
+            $server->getServer()->createFile($fullCalendarFilename, $stream);
197
+        } catch (Conflict $e) {
198
+            throw new CalendarException('Could not create new calendar event: ' . $e->getMessage(), 0, $e);
199
+        } finally {
200
+            fclose($stream);
201
+        }
202
+    }
203
+
204
+    /**
205
+     * @throws CalendarException
206
+     */
207
+    public function handleIMipMessage(string $name, string $calendarData): void {
208
+        $server = $this->getInvitationResponseServer();
209
+
210
+        /** @var CustomPrincipalPlugin $plugin */
211
+        $plugin = $server->getServer()->getPlugin('auth');
212
+        // we're working around the previous implementation
213
+        // that only allowed the public system principal to be used
214
+        // so set the custom principal here
215
+        $plugin->setCurrentPrincipal($this->calendar->getPrincipalURI());
216
+
217
+        if (empty($this->calendarInfo['uri'])) {
218
+            throw new CalendarException('Could not write to calendar as URI parameter is missing');
219
+        }
220
+        // Force calendar change URI
221
+        /** @var Schedule\Plugin $schedulingPlugin */
222
+        $schedulingPlugin = $server->getServer()->getPlugin('caldav-schedule');
223
+        // Let sabre handle the rest
224
+        $iTipMessage = new Message();
225
+        /** @var VCalendar $vObject */
226
+        $vObject = Reader::read($calendarData);
227
+        /** @var VEvent $vEvent */
228
+        $vEvent = $vObject->{'VEVENT'};
229
+
230
+        if ($vObject->{'METHOD'} === null) {
231
+            throw new CalendarException('No Method provided for scheduling data. Could not process message');
232
+        }
233
+
234
+        if (!isset($vEvent->{'ORGANIZER'}) || !isset($vEvent->{'ATTENDEE'})) {
235
+            throw new CalendarException('Could not process scheduling data, neccessary data missing from ICAL');
236
+        }
237
+        $organizer = $vEvent->{'ORGANIZER'}->getValue();
238
+        $attendee = $vEvent->{'ATTENDEE'}->getValue();
239
+
240
+        $iTipMessage->method = $vObject->{'METHOD'}->getValue();
241
+        if ($iTipMessage->method === 'REQUEST') {
242
+            $iTipMessage->sender = $organizer;
243
+            $iTipMessage->recipient = $attendee;
244
+        } elseif ($iTipMessage->method === 'REPLY') {
245
+            if ($server->isExternalAttendee($vEvent->{'ATTENDEE'}->getValue())) {
246
+                $iTipMessage->recipient = $organizer;
247
+            } else {
248
+                $iTipMessage->recipient = $attendee;
249
+            }
250
+            $iTipMessage->sender = $attendee;
251
+        } elseif ($iTipMessage->method === 'CANCEL') {
252
+            $iTipMessage->recipient = $attendee;
253
+            $iTipMessage->sender = $organizer;
254
+        }
255
+        $iTipMessage->uid = isset($vEvent->{'UID'}) ? $vEvent->{'UID'}->getValue() : '';
256
+        $iTipMessage->component = 'VEVENT';
257
+        $iTipMessage->sequence = isset($vEvent->{'SEQUENCE'}) ? (int)$vEvent->{'SEQUENCE'}->getValue() : 0;
258
+        $iTipMessage->message = $vObject;
259
+        $server->server->emit('schedule', [$iTipMessage]);
260
+    }
261
+
262
+    public function getInvitationResponseServer(): InvitationResponseServer {
263
+        return new InvitationResponseServer(false);
264
+    }
265
+
266
+    /**
267
+     * Export objects
268
+     *
269
+     * @since 32.0.0
270
+     *
271
+     * @return Generator<mixed, \Sabre\VObject\Component\VCalendar, mixed, mixed>
272
+     */
273
+    public function export(?CalendarExportOptions $options = null): Generator {
274
+        foreach (
275
+            $this->backend->exportCalendar(
276
+                $this->calendarInfo['id'],
277
+                $this->backend::CALENDAR_TYPE_CALENDAR,
278
+                $options
279
+            ) as $event
280
+        ) {
281
+            $vObject = Reader::read($event['calendardata']);
282
+            if ($vObject instanceof VCalendar) {
283
+                yield $vObject;
284
+            }
285
+        }
286
+    }
287 287
 
288 288
 }
Please login to merge, or discard this patch.
apps/dav/tests/unit/CalDAV/CalendarImplTest.php 1 patch
Indentation   +252 added lines, -252 removed lines patch added patch discarded remove patch
@@ -22,108 +22,108 @@  discard block
 block discarded – undo
22 22
 
23 23
 class CalendarImplTest extends \Test\TestCase {
24 24
 
25
-	private Calendar|MockObject $calendar;
26
-	private array $calendarInfo;
27
-	private CalDavBackend|MockObject $backend;
28
-	private CalendarImpl|MockObject $calendarImpl;
29
-	private array $mockExportCollection;
30
-
31
-	protected function setUp(): void {
32
-		parent::setUp();
33
-
34
-		$this->calendar = $this->createMock(Calendar::class);
35
-		$this->calendarInfo = [
36
-			'id' => 1,
37
-			'{DAV:}displayname' => 'user readable name 123',
38
-			'{http://apple.com/ns/ical/}calendar-color' => '#AABBCC',
39
-			'uri' => '/this/is/a/uri',
40
-			'principaluri' => 'principal/users/foobar'
41
-		];
42
-		$this->backend = $this->createMock(CalDavBackend::class);
43
-
44
-		$this->calendarImpl = new CalendarImpl(
45
-			$this->calendar,
46
-			$this->calendarInfo,
47
-			$this->backend
48
-		);
49
-	}
50
-
51
-
52
-	public function testGetKey(): void {
53
-		$this->assertEquals($this->calendarImpl->getKey(), 1);
54
-	}
55
-
56
-	public function testGetDisplayname(): void {
57
-		$this->assertEquals($this->calendarImpl->getDisplayName(), 'user readable name 123');
58
-	}
59
-
60
-	public function testGetDisplayColor(): void {
61
-		$this->assertEquals($this->calendarImpl->getDisplayColor(), '#AABBCC');
62
-	}
63
-
64
-	public function testSearch(): void {
65
-		$this->backend->expects($this->once())
66
-			->method('search')
67
-			->with($this->calendarInfo, 'abc', ['def'], ['ghi'], 42, 1337)
68
-			->willReturn(['SEARCHRESULTS']);
69
-
70
-		$result = $this->calendarImpl->search('abc', ['def'], ['ghi'], 42, 1337);
71
-		$this->assertEquals($result, ['SEARCHRESULTS']);
72
-	}
73
-
74
-	public function testGetPermissionRead(): void {
75
-		$this->calendar->expects($this->once())
76
-			->method('getACL')
77
-			->with()
78
-			->willReturn([
79
-				['privilege' => '{DAV:}read', 'principal' => 'principal/users/foobar'],
80
-				['privilege' => '{DAV:}read', 'principal' => 'principal/users/other'],
81
-				['privilege' => '{DAV:}write', 'principal' => 'principal/users/other'],
82
-				['privilege' => '{DAV:}all', 'principal' => 'principal/users/other'],
83
-			]);
84
-
85
-		$this->assertEquals(1, $this->calendarImpl->getPermissions());
86
-	}
87
-
88
-	public function testGetPermissionWrite(): void {
89
-		$this->calendar->expects($this->once())
90
-			->method('getACL')
91
-			->with()
92
-			->willReturn([
93
-				['privilege' => '{DAV:}write', 'principal' => 'principal/users/foobar'],
94
-				['privilege' => '{DAV:}read', 'principal' => 'principal/users/other'],
95
-				['privilege' => '{DAV:}all', 'principal' => 'principal/users/other'],
96
-			]);
97
-
98
-		$this->assertEquals(6, $this->calendarImpl->getPermissions());
99
-	}
100
-
101
-	public function testGetPermissionReadWrite(): void {
102
-		$this->calendar->expects($this->once())
103
-			->method('getACL')
104
-			->with()
105
-			->willReturn([
106
-				['privilege' => '{DAV:}write', 'principal' => 'principal/users/foobar'],
107
-				['privilege' => '{DAV:}read', 'principal' => 'principal/users/foobar'],
108
-				['privilege' => '{DAV:}all', 'principal' => 'principal/users/other'],
109
-			]);
110
-
111
-		$this->assertEquals(7, $this->calendarImpl->getPermissions());
112
-	}
113
-
114
-	public function testGetPermissionAll(): void {
115
-		$this->calendar->expects($this->once())
116
-			->method('getACL')
117
-			->with()
118
-			->willReturn([
119
-				['privilege' => '{DAV:}all', 'principal' => 'principal/users/foobar'],
120
-			]);
121
-
122
-		$this->assertEquals(31, $this->calendarImpl->getPermissions());
123
-	}
124
-
125
-	public function testHandleImipMessage(): void {
126
-		$message = <<<EOF
25
+    private Calendar|MockObject $calendar;
26
+    private array $calendarInfo;
27
+    private CalDavBackend|MockObject $backend;
28
+    private CalendarImpl|MockObject $calendarImpl;
29
+    private array $mockExportCollection;
30
+
31
+    protected function setUp(): void {
32
+        parent::setUp();
33
+
34
+        $this->calendar = $this->createMock(Calendar::class);
35
+        $this->calendarInfo = [
36
+            'id' => 1,
37
+            '{DAV:}displayname' => 'user readable name 123',
38
+            '{http://apple.com/ns/ical/}calendar-color' => '#AABBCC',
39
+            'uri' => '/this/is/a/uri',
40
+            'principaluri' => 'principal/users/foobar'
41
+        ];
42
+        $this->backend = $this->createMock(CalDavBackend::class);
43
+
44
+        $this->calendarImpl = new CalendarImpl(
45
+            $this->calendar,
46
+            $this->calendarInfo,
47
+            $this->backend
48
+        );
49
+    }
50
+
51
+
52
+    public function testGetKey(): void {
53
+        $this->assertEquals($this->calendarImpl->getKey(), 1);
54
+    }
55
+
56
+    public function testGetDisplayname(): void {
57
+        $this->assertEquals($this->calendarImpl->getDisplayName(), 'user readable name 123');
58
+    }
59
+
60
+    public function testGetDisplayColor(): void {
61
+        $this->assertEquals($this->calendarImpl->getDisplayColor(), '#AABBCC');
62
+    }
63
+
64
+    public function testSearch(): void {
65
+        $this->backend->expects($this->once())
66
+            ->method('search')
67
+            ->with($this->calendarInfo, 'abc', ['def'], ['ghi'], 42, 1337)
68
+            ->willReturn(['SEARCHRESULTS']);
69
+
70
+        $result = $this->calendarImpl->search('abc', ['def'], ['ghi'], 42, 1337);
71
+        $this->assertEquals($result, ['SEARCHRESULTS']);
72
+    }
73
+
74
+    public function testGetPermissionRead(): void {
75
+        $this->calendar->expects($this->once())
76
+            ->method('getACL')
77
+            ->with()
78
+            ->willReturn([
79
+                ['privilege' => '{DAV:}read', 'principal' => 'principal/users/foobar'],
80
+                ['privilege' => '{DAV:}read', 'principal' => 'principal/users/other'],
81
+                ['privilege' => '{DAV:}write', 'principal' => 'principal/users/other'],
82
+                ['privilege' => '{DAV:}all', 'principal' => 'principal/users/other'],
83
+            ]);
84
+
85
+        $this->assertEquals(1, $this->calendarImpl->getPermissions());
86
+    }
87
+
88
+    public function testGetPermissionWrite(): void {
89
+        $this->calendar->expects($this->once())
90
+            ->method('getACL')
91
+            ->with()
92
+            ->willReturn([
93
+                ['privilege' => '{DAV:}write', 'principal' => 'principal/users/foobar'],
94
+                ['privilege' => '{DAV:}read', 'principal' => 'principal/users/other'],
95
+                ['privilege' => '{DAV:}all', 'principal' => 'principal/users/other'],
96
+            ]);
97
+
98
+        $this->assertEquals(6, $this->calendarImpl->getPermissions());
99
+    }
100
+
101
+    public function testGetPermissionReadWrite(): void {
102
+        $this->calendar->expects($this->once())
103
+            ->method('getACL')
104
+            ->with()
105
+            ->willReturn([
106
+                ['privilege' => '{DAV:}write', 'principal' => 'principal/users/foobar'],
107
+                ['privilege' => '{DAV:}read', 'principal' => 'principal/users/foobar'],
108
+                ['privilege' => '{DAV:}all', 'principal' => 'principal/users/other'],
109
+            ]);
110
+
111
+        $this->assertEquals(7, $this->calendarImpl->getPermissions());
112
+    }
113
+
114
+    public function testGetPermissionAll(): void {
115
+        $this->calendar->expects($this->once())
116
+            ->method('getACL')
117
+            ->with()
118
+            ->willReturn([
119
+                ['privilege' => '{DAV:}all', 'principal' => 'principal/users/foobar'],
120
+            ]);
121
+
122
+        $this->assertEquals(31, $this->calendarImpl->getPermissions());
123
+    }
124
+
125
+    public function testHandleImipMessage(): void {
126
+        $message = <<<EOF
127 127
 BEGIN:VCALENDAR
128 128
 PRODID:-//Nextcloud/Nextcloud CalDAV Server//EN
129 129
 METHOD:REPLY
@@ -138,92 +138,92 @@  discard block
 block discarded – undo
138 138
 END:VCALENDAR
139 139
 EOF;
140 140
 
141
-		/** @var CustomPrincipalPlugin|MockObject $authPlugin */
142
-		$authPlugin = $this->createMock(CustomPrincipalPlugin::class);
143
-		$authPlugin->expects(self::once())
144
-			->method('setCurrentPrincipal')
145
-			->with($this->calendar->getPrincipalURI());
146
-
147
-		/** @var \Sabre\DAVACL\Plugin|MockObject $aclPlugin */
148
-		$aclPlugin = $this->createMock(\Sabre\DAVACL\Plugin::class);
149
-
150
-		/** @var Plugin|MockObject $schedulingPlugin */
151
-		$schedulingPlugin = $this->createMock(Plugin::class);
152
-		$iTipMessage = $this->getITipMessage($message);
153
-		$iTipMessage->recipient = 'mailto:[email protected]';
154
-
155
-		$server = $this->createMock(Server::class);
156
-		$server->expects($this->any())
157
-			->method('getPlugin')
158
-			->willReturnMap([
159
-				['auth', $authPlugin],
160
-				['acl', $aclPlugin],
161
-				['caldav-schedule', $schedulingPlugin]
162
-			]);
163
-		$server->expects(self::once())
164
-			->method('emit');
165
-
166
-		$invitationResponseServer = $this->createPartialMock(InvitationResponseServer::class, ['getServer', 'isExternalAttendee']);
167
-		$invitationResponseServer->server = $server;
168
-		$invitationResponseServer->expects($this->any())
169
-			->method('getServer')
170
-			->willReturn($server);
171
-		$invitationResponseServer->expects(self::once())
172
-			->method('isExternalAttendee')
173
-			->willReturn(false);
174
-
175
-		$calendarImpl = $this->getMockBuilder(CalendarImpl::class)
176
-			->setConstructorArgs([$this->calendar, $this->calendarInfo, $this->backend])
177
-			->onlyMethods(['getInvitationResponseServer'])
178
-			->getMock();
179
-		$calendarImpl->expects($this->once())
180
-			->method('getInvitationResponseServer')
181
-			->willReturn($invitationResponseServer);
182
-
183
-		$calendarImpl->handleIMipMessage('filename.ics', $message);
184
-	}
185
-
186
-	public function testHandleImipMessageNoCalendarUri(): void {
187
-		/** @var CustomPrincipalPlugin|MockObject $authPlugin */
188
-		$authPlugin = $this->createMock(CustomPrincipalPlugin::class);
189
-		$authPlugin->expects(self::once())
190
-			->method('setCurrentPrincipal')
191
-			->with($this->calendar->getPrincipalURI());
192
-		unset($this->calendarInfo['uri']);
193
-
194
-		/** @var Plugin|MockObject $schedulingPlugin */
195
-		$schedulingPlugin = $this->createMock(Plugin::class);
196
-
197
-		/** @var \Sabre\DAVACL\Plugin|MockObject $schedulingPlugin */
198
-		$aclPlugin = $this->createMock(\Sabre\DAVACL\Plugin::class);
199
-
200
-		$server =
201
-			$this->createMock(Server::class);
202
-		$server->expects($this->any())
203
-			->method('getPlugin')
204
-			->willReturnMap([
205
-				['auth', $authPlugin],
206
-				['acl', $aclPlugin],
207
-				['caldav-schedule', $schedulingPlugin]
208
-			]);
209
-		$server->expects(self::never())
210
-			->method('emit');
211
-
212
-		$invitationResponseServer = $this->createPartialMock(InvitationResponseServer::class, ['getServer']);
213
-		$invitationResponseServer->server = $server;
214
-		$invitationResponseServer->expects($this->any())
215
-			->method('getServer')
216
-			->willReturn($server);
217
-
218
-		$calendarImpl = $this->getMockBuilder(CalendarImpl::class)
219
-			->setConstructorArgs([$this->calendar, $this->calendarInfo, $this->backend])
220
-			->onlyMethods(['getInvitationResponseServer'])
221
-			->getMock();
222
-		$calendarImpl->expects($this->once())
223
-			->method('getInvitationResponseServer')
224
-			->willReturn($invitationResponseServer);
225
-
226
-		$message = <<<EOF
141
+        /** @var CustomPrincipalPlugin|MockObject $authPlugin */
142
+        $authPlugin = $this->createMock(CustomPrincipalPlugin::class);
143
+        $authPlugin->expects(self::once())
144
+            ->method('setCurrentPrincipal')
145
+            ->with($this->calendar->getPrincipalURI());
146
+
147
+        /** @var \Sabre\DAVACL\Plugin|MockObject $aclPlugin */
148
+        $aclPlugin = $this->createMock(\Sabre\DAVACL\Plugin::class);
149
+
150
+        /** @var Plugin|MockObject $schedulingPlugin */
151
+        $schedulingPlugin = $this->createMock(Plugin::class);
152
+        $iTipMessage = $this->getITipMessage($message);
153
+        $iTipMessage->recipient = 'mailto:[email protected]';
154
+
155
+        $server = $this->createMock(Server::class);
156
+        $server->expects($this->any())
157
+            ->method('getPlugin')
158
+            ->willReturnMap([
159
+                ['auth', $authPlugin],
160
+                ['acl', $aclPlugin],
161
+                ['caldav-schedule', $schedulingPlugin]
162
+            ]);
163
+        $server->expects(self::once())
164
+            ->method('emit');
165
+
166
+        $invitationResponseServer = $this->createPartialMock(InvitationResponseServer::class, ['getServer', 'isExternalAttendee']);
167
+        $invitationResponseServer->server = $server;
168
+        $invitationResponseServer->expects($this->any())
169
+            ->method('getServer')
170
+            ->willReturn($server);
171
+        $invitationResponseServer->expects(self::once())
172
+            ->method('isExternalAttendee')
173
+            ->willReturn(false);
174
+
175
+        $calendarImpl = $this->getMockBuilder(CalendarImpl::class)
176
+            ->setConstructorArgs([$this->calendar, $this->calendarInfo, $this->backend])
177
+            ->onlyMethods(['getInvitationResponseServer'])
178
+            ->getMock();
179
+        $calendarImpl->expects($this->once())
180
+            ->method('getInvitationResponseServer')
181
+            ->willReturn($invitationResponseServer);
182
+
183
+        $calendarImpl->handleIMipMessage('filename.ics', $message);
184
+    }
185
+
186
+    public function testHandleImipMessageNoCalendarUri(): void {
187
+        /** @var CustomPrincipalPlugin|MockObject $authPlugin */
188
+        $authPlugin = $this->createMock(CustomPrincipalPlugin::class);
189
+        $authPlugin->expects(self::once())
190
+            ->method('setCurrentPrincipal')
191
+            ->with($this->calendar->getPrincipalURI());
192
+        unset($this->calendarInfo['uri']);
193
+
194
+        /** @var Plugin|MockObject $schedulingPlugin */
195
+        $schedulingPlugin = $this->createMock(Plugin::class);
196
+
197
+        /** @var \Sabre\DAVACL\Plugin|MockObject $schedulingPlugin */
198
+        $aclPlugin = $this->createMock(\Sabre\DAVACL\Plugin::class);
199
+
200
+        $server =
201
+            $this->createMock(Server::class);
202
+        $server->expects($this->any())
203
+            ->method('getPlugin')
204
+            ->willReturnMap([
205
+                ['auth', $authPlugin],
206
+                ['acl', $aclPlugin],
207
+                ['caldav-schedule', $schedulingPlugin]
208
+            ]);
209
+        $server->expects(self::never())
210
+            ->method('emit');
211
+
212
+        $invitationResponseServer = $this->createPartialMock(InvitationResponseServer::class, ['getServer']);
213
+        $invitationResponseServer->server = $server;
214
+        $invitationResponseServer->expects($this->any())
215
+            ->method('getServer')
216
+            ->willReturn($server);
217
+
218
+        $calendarImpl = $this->getMockBuilder(CalendarImpl::class)
219
+            ->setConstructorArgs([$this->calendar, $this->calendarInfo, $this->backend])
220
+            ->onlyMethods(['getInvitationResponseServer'])
221
+            ->getMock();
222
+        $calendarImpl->expects($this->once())
223
+            ->method('getInvitationResponseServer')
224
+            ->willReturn($invitationResponseServer);
225
+
226
+        $message = <<<EOF
227 227
 BEGIN:VCALENDAR
228 228
 PRODID:-//Nextcloud/Nextcloud CalDAV Server//EN
229 229
 METHOD:REPLY
@@ -238,70 +238,70 @@  discard block
 block discarded – undo
238 238
 END:VCALENDAR
239 239
 EOF;
240 240
 
241
-		$this->expectException(CalendarException::class);
242
-		$calendarImpl->handleIMipMessage('filename.ics', $message);
243
-	}
244
-
245
-	private function getITipMessage($calendarData): Message {
246
-		$iTipMessage = new Message();
247
-		/** @var VCalendar $vObject */
248
-		$vObject = Reader::read($calendarData);
249
-		/** @var VEvent $vEvent */
250
-		$vEvent = $vObject->{'VEVENT'};
251
-		$orgaizer = $vEvent->{'ORGANIZER'}->getValue();
252
-		$attendee = $vEvent->{'ATTENDEE'}->getValue();
253
-
254
-		$iTipMessage->method = $vObject->{'METHOD'}->getValue();
255
-		$iTipMessage->recipient = $orgaizer;
256
-		$iTipMessage->sender = $attendee;
257
-		$iTipMessage->uid = isset($vEvent->{'UID'}) ? $vEvent->{'UID'}->getValue() : '';
258
-		$iTipMessage->component = 'VEVENT';
259
-		$iTipMessage->sequence = isset($vEvent->{'SEQUENCE'}) ? (int)$vEvent->{'SEQUENCE'}->getValue() : 0;
260
-		$iTipMessage->message = $vObject;
261
-		return $iTipMessage;
262
-	}
263
-
264
-	protected function mockExportGenerator(): Generator {
265
-		foreach ($this->mockExportCollection as $entry) {
266
-			yield $entry;
267
-		}
268
-	}
269
-
270
-	public function testExport(): void {
271
-		// Arrange
272
-		// construct calendar with a 1 hour event and same start/end time zones
273
-		$vCalendar = new VCalendar();
274
-		/** @var VEvent $vEvent */
275
-		$vEvent = $vCalendar->add('VEVENT', []);
276
-		$vEvent->UID->setValue('96a0e6b1-d886-4a55-a60d-152b31401dcc');
277
-		$vEvent->add('DTSTART', '20240701T080000', ['TZID' => 'America/Toronto']);
278
-		$vEvent->add('DTEND', '20240701T090000', ['TZID' => 'America/Toronto']);
279
-		$vEvent->add('SUMMARY', 'Test Recurrence Event');
280
-		$vEvent->add('ORGANIZER', 'mailto:[email protected]', ['CN' => 'Organizer']);
281
-		$vEvent->add('ATTENDEE', 'mailto:[email protected]', [
282
-			'CN' => 'Attendee One',
283
-			'CUTYPE' => 'INDIVIDUAL',
284
-			'PARTSTAT' => 'NEEDS-ACTION',
285
-			'ROLE' => 'REQ-PARTICIPANT',
286
-			'RSVP' => 'TRUE'
287
-		]);
288
-		// construct data store return
289
-		$this->mockExportCollection[] = [
290
-			'id' => 1,
291
-			'calendardata' => $vCalendar->serialize()
292
-		];
293
-		$this->backend->expects($this->once())
294
-			->method('exportCalendar')
295
-			->with(1, $this->backend::CALENDAR_TYPE_CALENDAR, null)
296
-			->willReturn($this->mockExportGenerator());
297
-
298
-		// Act
299
-		foreach ($this->calendarImpl->export(null) as $entry) {
300
-			$exported[] = $entry;
301
-		}
241
+        $this->expectException(CalendarException::class);
242
+        $calendarImpl->handleIMipMessage('filename.ics', $message);
243
+    }
244
+
245
+    private function getITipMessage($calendarData): Message {
246
+        $iTipMessage = new Message();
247
+        /** @var VCalendar $vObject */
248
+        $vObject = Reader::read($calendarData);
249
+        /** @var VEvent $vEvent */
250
+        $vEvent = $vObject->{'VEVENT'};
251
+        $orgaizer = $vEvent->{'ORGANIZER'}->getValue();
252
+        $attendee = $vEvent->{'ATTENDEE'}->getValue();
253
+
254
+        $iTipMessage->method = $vObject->{'METHOD'}->getValue();
255
+        $iTipMessage->recipient = $orgaizer;
256
+        $iTipMessage->sender = $attendee;
257
+        $iTipMessage->uid = isset($vEvent->{'UID'}) ? $vEvent->{'UID'}->getValue() : '';
258
+        $iTipMessage->component = 'VEVENT';
259
+        $iTipMessage->sequence = isset($vEvent->{'SEQUENCE'}) ? (int)$vEvent->{'SEQUENCE'}->getValue() : 0;
260
+        $iTipMessage->message = $vObject;
261
+        return $iTipMessage;
262
+    }
263
+
264
+    protected function mockExportGenerator(): Generator {
265
+        foreach ($this->mockExportCollection as $entry) {
266
+            yield $entry;
267
+        }
268
+    }
269
+
270
+    public function testExport(): void {
271
+        // Arrange
272
+        // construct calendar with a 1 hour event and same start/end time zones
273
+        $vCalendar = new VCalendar();
274
+        /** @var VEvent $vEvent */
275
+        $vEvent = $vCalendar->add('VEVENT', []);
276
+        $vEvent->UID->setValue('96a0e6b1-d886-4a55-a60d-152b31401dcc');
277
+        $vEvent->add('DTSTART', '20240701T080000', ['TZID' => 'America/Toronto']);
278
+        $vEvent->add('DTEND', '20240701T090000', ['TZID' => 'America/Toronto']);
279
+        $vEvent->add('SUMMARY', 'Test Recurrence Event');
280
+        $vEvent->add('ORGANIZER', 'mailto:[email protected]', ['CN' => 'Organizer']);
281
+        $vEvent->add('ATTENDEE', 'mailto:[email protected]', [
282
+            'CN' => 'Attendee One',
283
+            'CUTYPE' => 'INDIVIDUAL',
284
+            'PARTSTAT' => 'NEEDS-ACTION',
285
+            'ROLE' => 'REQ-PARTICIPANT',
286
+            'RSVP' => 'TRUE'
287
+        ]);
288
+        // construct data store return
289
+        $this->mockExportCollection[] = [
290
+            'id' => 1,
291
+            'calendardata' => $vCalendar->serialize()
292
+        ];
293
+        $this->backend->expects($this->once())
294
+            ->method('exportCalendar')
295
+            ->with(1, $this->backend::CALENDAR_TYPE_CALENDAR, null)
296
+            ->willReturn($this->mockExportGenerator());
297
+
298
+        // Act
299
+        foreach ($this->calendarImpl->export(null) as $entry) {
300
+            $exported[] = $entry;
301
+        }
302 302
 		
303
-		// Assert
304
-		$this->assertCount(1, $exported, 'Invalid exported items count');
305
-	}
303
+        // Assert
304
+        $this->assertCount(1, $exported, 'Invalid exported items count');
305
+    }
306 306
 
307 307
 }
Please login to merge, or discard this patch.