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