Passed
Push — master ( f0dd71...c56a27 )
by Christoph
11:49 queued 12s
created
apps/dav/lib/Comments/CommentsPlugin.php 2 patches
Indentation   +207 added lines, -207 removed lines patch added patch discarded remove patch
@@ -44,213 +44,213 @@
 block discarded – undo
44 44
  * Sabre plugin to handle comments:
45 45
  */
46 46
 class CommentsPlugin extends ServerPlugin {
47
-	// namespace
48
-	const NS_OWNCLOUD = 'http://owncloud.org/ns';
49
-
50
-	const REPORT_NAME            = '{http://owncloud.org/ns}filter-comments';
51
-	const REPORT_PARAM_LIMIT     = '{http://owncloud.org/ns}limit';
52
-	const REPORT_PARAM_OFFSET    = '{http://owncloud.org/ns}offset';
53
-	const REPORT_PARAM_TIMESTAMP = '{http://owncloud.org/ns}datetime';
54
-
55
-	/** @var ICommentsManager  */
56
-	protected $commentsManager;
57
-
58
-	/** @var \Sabre\DAV\Server $server */
59
-	private $server;
60
-
61
-	/** @var  \OCP\IUserSession */
62
-	protected $userSession;
63
-
64
-	/**
65
-	 * Comments plugin
66
-	 *
67
-	 * @param ICommentsManager $commentsManager
68
-	 * @param IUserSession $userSession
69
-	 */
70
-	public function __construct(ICommentsManager $commentsManager, IUserSession $userSession) {
71
-		$this->commentsManager = $commentsManager;
72
-		$this->userSession = $userSession;
73
-	}
74
-
75
-	/**
76
-	 * This initializes the plugin.
77
-	 *
78
-	 * This function is called by Sabre\DAV\Server, after
79
-	 * addPlugin is called.
80
-	 *
81
-	 * This method should set up the required event subscriptions.
82
-	 *
83
-	 * @param Server $server
84
-	 * @return void
85
-	 */
86
-	function initialize(Server $server) {
87
-		$this->server = $server;
88
-		if(strpos($this->server->getRequestUri(), 'comments/') !== 0) {
89
-			return;
90
-		}
91
-
92
-		$this->server->xml->namespaceMap[self::NS_OWNCLOUD] = 'oc';
93
-
94
-		$this->server->xml->classMap['DateTime'] = function (Writer $writer, \DateTime $value) {
95
-			$writer->write(\Sabre\HTTP\toDate($value));
96
-		};
97
-
98
-		$this->server->on('report', [$this, 'onReport']);
99
-		$this->server->on('method:POST', [$this, 'httpPost']);
100
-	}
101
-
102
-	/**
103
-	 * POST operation on Comments collections
104
-	 *
105
-	 * @param RequestInterface $request request object
106
-	 * @param ResponseInterface $response response object
107
-	 * @return null|false
108
-	 */
109
-	public function httpPost(RequestInterface $request, ResponseInterface $response) {
110
-		$path = $request->getPath();
111
-		$node = $this->server->tree->getNodeForPath($path);
112
-		if (!$node instanceof EntityCollection) {
113
-			return null;
114
-		}
115
-
116
-		$data = $request->getBodyAsString();
117
-		$comment = $this->createComment(
118
-			$node->getName(),
119
-			$node->getId(),
120
-			$data,
121
-			$request->getHeader('Content-Type')
122
-		);
123
-
124
-		// update read marker for the current user/poster to avoid
125
-		// having their own comments marked as unread
126
-		$node->setReadMarker(null);
127
-
128
-		$url = rtrim($request->getUrl(), '/') . '/' . urlencode($comment->getId());
129
-
130
-		$response->setHeader('Content-Location', $url);
131
-
132
-		// created
133
-		$response->setStatus(201);
134
-		return false;
135
-	}
136
-
137
-	/**
138
-	 * Returns a list of reports this plugin supports.
139
-	 *
140
-	 * This will be used in the {DAV:}supported-report-set property.
141
-	 *
142
-	 * @param string $uri
143
-	 * @return array
144
-	 */
145
-	public function getSupportedReportSet($uri) {
146
-		return [self::REPORT_NAME];
147
-	}
148
-
149
-	/**
150
-	 * REPORT operations to look for comments
151
-	 *
152
-	 * @param string $reportName
153
-	 * @param array $report
154
-	 * @param string $uri
155
-	 * @return bool
156
-	 * @throws NotFound
157
-	 * @throws ReportNotSupported
158
-	 */
159
-	public function onReport($reportName, $report, $uri) {
160
-		$node = $this->server->tree->getNodeForPath($uri);
161
-		if(!$node instanceof EntityCollection || $reportName !== self::REPORT_NAME) {
162
-			throw new ReportNotSupported();
163
-		}
164
-		$args = ['limit' => 0, 'offset' => 0, 'datetime' => null];
165
-		$acceptableParameters = [
166
-			$this::REPORT_PARAM_LIMIT,
167
-			$this::REPORT_PARAM_OFFSET,
168
-			$this::REPORT_PARAM_TIMESTAMP
169
-		];
170
-		$ns = '{' . $this::NS_OWNCLOUD . '}';
171
-		foreach($report as $parameter) {
172
-			if(!in_array($parameter['name'], $acceptableParameters) || empty($parameter['value'])) {
173
-				continue;
174
-			}
175
-			$args[str_replace($ns, '', $parameter['name'])] = $parameter['value'];
176
-		}
177
-
178
-		if(!is_null($args['datetime'])) {
179
-			$args['datetime'] = new \DateTime($args['datetime']);
180
-		}
181
-
182
-		$results = $node->findChildren($args['limit'], $args['offset'], $args['datetime']);
183
-
184
-		$responses = [];
185
-		foreach($results as $node) {
186
-			$nodePath = $this->server->getRequestUri() . '/' . $node->comment->getId();
187
-			$resultSet = $this->server->getPropertiesForPath($nodePath, CommentNode::getPropertyNames());
188
-			if(isset($resultSet[0]) && isset($resultSet[0][200])) {
189
-				$responses[] = new Response(
190
-					$this->server->getBaseUri() . $nodePath,
191
-					[200 => $resultSet[0][200]],
192
-					200
193
-				);
194
-			}
195
-
196
-		}
197
-
198
-		$xml = $this->server->xml->write(
199
-			'{DAV:}multistatus',
200
-			new MultiStatus($responses)
201
-		);
202
-
203
-		$this->server->httpResponse->setStatus(207);
204
-		$this->server->httpResponse->setHeader('Content-Type', 'application/xml; charset=utf-8');
205
-		$this->server->httpResponse->setBody($xml);
206
-
207
-		return false;
208
-	}
209
-
210
-	/**
211
-	 * Creates a new comment
212
-	 *
213
-	 * @param string $objectType e.g. "files"
214
-	 * @param string $objectId e.g. the file id
215
-	 * @param string $data JSON encoded string containing the properties of the tag to create
216
-	 * @param string $contentType content type of the data
217
-	 * @return IComment newly created comment
218
-	 *
219
-	 * @throws BadRequest if a field was missing
220
-	 * @throws UnsupportedMediaType if the content type is not supported
221
-	 */
222
-	private function createComment($objectType, $objectId, $data, $contentType = 'application/json') {
223
-		if (explode(';', $contentType)[0] === 'application/json') {
224
-			$data = json_decode($data, true);
225
-		} else {
226
-			throw new UnsupportedMediaType();
227
-		}
228
-
229
-		$actorType = $data['actorType'];
230
-		$actorId = null;
231
-		if($actorType === 'users') {
232
-			$user = $this->userSession->getUser();
233
-			if(!is_null($user)) {
234
-				$actorId = $user->getUID();
235
-			}
236
-		}
237
-		if(is_null($actorId)) {
238
-			throw new BadRequest('Invalid actor "' .  $actorType .'"');
239
-		}
240
-
241
-		try {
242
-			$comment = $this->commentsManager->create($actorType, $actorId, $objectType, $objectId);
243
-			$comment->setMessage($data['message']);
244
-			$comment->setVerb($data['verb']);
245
-			$this->commentsManager->save($comment);
246
-			return $comment;
247
-		} catch (\InvalidArgumentException $e) {
248
-			throw new BadRequest('Invalid input values', 0, $e);
249
-		} catch (\OCP\Comments\MessageTooLongException $e) {
250
-			$msg = 'Message exceeds allowed character limit of ';
251
-			throw new BadRequest($msg . \OCP\Comments\IComment::MAX_MESSAGE_LENGTH, 0,	$e);
252
-		}
253
-	}
47
+    // namespace
48
+    const NS_OWNCLOUD = 'http://owncloud.org/ns';
49
+
50
+    const REPORT_NAME            = '{http://owncloud.org/ns}filter-comments';
51
+    const REPORT_PARAM_LIMIT     = '{http://owncloud.org/ns}limit';
52
+    const REPORT_PARAM_OFFSET    = '{http://owncloud.org/ns}offset';
53
+    const REPORT_PARAM_TIMESTAMP = '{http://owncloud.org/ns}datetime';
54
+
55
+    /** @var ICommentsManager  */
56
+    protected $commentsManager;
57
+
58
+    /** @var \Sabre\DAV\Server $server */
59
+    private $server;
60
+
61
+    /** @var  \OCP\IUserSession */
62
+    protected $userSession;
63
+
64
+    /**
65
+     * Comments plugin
66
+     *
67
+     * @param ICommentsManager $commentsManager
68
+     * @param IUserSession $userSession
69
+     */
70
+    public function __construct(ICommentsManager $commentsManager, IUserSession $userSession) {
71
+        $this->commentsManager = $commentsManager;
72
+        $this->userSession = $userSession;
73
+    }
74
+
75
+    /**
76
+     * This initializes the plugin.
77
+     *
78
+     * This function is called by Sabre\DAV\Server, after
79
+     * addPlugin is called.
80
+     *
81
+     * This method should set up the required event subscriptions.
82
+     *
83
+     * @param Server $server
84
+     * @return void
85
+     */
86
+    function initialize(Server $server) {
87
+        $this->server = $server;
88
+        if(strpos($this->server->getRequestUri(), 'comments/') !== 0) {
89
+            return;
90
+        }
91
+
92
+        $this->server->xml->namespaceMap[self::NS_OWNCLOUD] = 'oc';
93
+
94
+        $this->server->xml->classMap['DateTime'] = function (Writer $writer, \DateTime $value) {
95
+            $writer->write(\Sabre\HTTP\toDate($value));
96
+        };
97
+
98
+        $this->server->on('report', [$this, 'onReport']);
99
+        $this->server->on('method:POST', [$this, 'httpPost']);
100
+    }
101
+
102
+    /**
103
+     * POST operation on Comments collections
104
+     *
105
+     * @param RequestInterface $request request object
106
+     * @param ResponseInterface $response response object
107
+     * @return null|false
108
+     */
109
+    public function httpPost(RequestInterface $request, ResponseInterface $response) {
110
+        $path = $request->getPath();
111
+        $node = $this->server->tree->getNodeForPath($path);
112
+        if (!$node instanceof EntityCollection) {
113
+            return null;
114
+        }
115
+
116
+        $data = $request->getBodyAsString();
117
+        $comment = $this->createComment(
118
+            $node->getName(),
119
+            $node->getId(),
120
+            $data,
121
+            $request->getHeader('Content-Type')
122
+        );
123
+
124
+        // update read marker for the current user/poster to avoid
125
+        // having their own comments marked as unread
126
+        $node->setReadMarker(null);
127
+
128
+        $url = rtrim($request->getUrl(), '/') . '/' . urlencode($comment->getId());
129
+
130
+        $response->setHeader('Content-Location', $url);
131
+
132
+        // created
133
+        $response->setStatus(201);
134
+        return false;
135
+    }
136
+
137
+    /**
138
+     * Returns a list of reports this plugin supports.
139
+     *
140
+     * This will be used in the {DAV:}supported-report-set property.
141
+     *
142
+     * @param string $uri
143
+     * @return array
144
+     */
145
+    public function getSupportedReportSet($uri) {
146
+        return [self::REPORT_NAME];
147
+    }
148
+
149
+    /**
150
+     * REPORT operations to look for comments
151
+     *
152
+     * @param string $reportName
153
+     * @param array $report
154
+     * @param string $uri
155
+     * @return bool
156
+     * @throws NotFound
157
+     * @throws ReportNotSupported
158
+     */
159
+    public function onReport($reportName, $report, $uri) {
160
+        $node = $this->server->tree->getNodeForPath($uri);
161
+        if(!$node instanceof EntityCollection || $reportName !== self::REPORT_NAME) {
162
+            throw new ReportNotSupported();
163
+        }
164
+        $args = ['limit' => 0, 'offset' => 0, 'datetime' => null];
165
+        $acceptableParameters = [
166
+            $this::REPORT_PARAM_LIMIT,
167
+            $this::REPORT_PARAM_OFFSET,
168
+            $this::REPORT_PARAM_TIMESTAMP
169
+        ];
170
+        $ns = '{' . $this::NS_OWNCLOUD . '}';
171
+        foreach($report as $parameter) {
172
+            if(!in_array($parameter['name'], $acceptableParameters) || empty($parameter['value'])) {
173
+                continue;
174
+            }
175
+            $args[str_replace($ns, '', $parameter['name'])] = $parameter['value'];
176
+        }
177
+
178
+        if(!is_null($args['datetime'])) {
179
+            $args['datetime'] = new \DateTime($args['datetime']);
180
+        }
181
+
182
+        $results = $node->findChildren($args['limit'], $args['offset'], $args['datetime']);
183
+
184
+        $responses = [];
185
+        foreach($results as $node) {
186
+            $nodePath = $this->server->getRequestUri() . '/' . $node->comment->getId();
187
+            $resultSet = $this->server->getPropertiesForPath($nodePath, CommentNode::getPropertyNames());
188
+            if(isset($resultSet[0]) && isset($resultSet[0][200])) {
189
+                $responses[] = new Response(
190
+                    $this->server->getBaseUri() . $nodePath,
191
+                    [200 => $resultSet[0][200]],
192
+                    200
193
+                );
194
+            }
195
+
196
+        }
197
+
198
+        $xml = $this->server->xml->write(
199
+            '{DAV:}multistatus',
200
+            new MultiStatus($responses)
201
+        );
202
+
203
+        $this->server->httpResponse->setStatus(207);
204
+        $this->server->httpResponse->setHeader('Content-Type', 'application/xml; charset=utf-8');
205
+        $this->server->httpResponse->setBody($xml);
206
+
207
+        return false;
208
+    }
209
+
210
+    /**
211
+     * Creates a new comment
212
+     *
213
+     * @param string $objectType e.g. "files"
214
+     * @param string $objectId e.g. the file id
215
+     * @param string $data JSON encoded string containing the properties of the tag to create
216
+     * @param string $contentType content type of the data
217
+     * @return IComment newly created comment
218
+     *
219
+     * @throws BadRequest if a field was missing
220
+     * @throws UnsupportedMediaType if the content type is not supported
221
+     */
222
+    private function createComment($objectType, $objectId, $data, $contentType = 'application/json') {
223
+        if (explode(';', $contentType)[0] === 'application/json') {
224
+            $data = json_decode($data, true);
225
+        } else {
226
+            throw new UnsupportedMediaType();
227
+        }
228
+
229
+        $actorType = $data['actorType'];
230
+        $actorId = null;
231
+        if($actorType === 'users') {
232
+            $user = $this->userSession->getUser();
233
+            if(!is_null($user)) {
234
+                $actorId = $user->getUID();
235
+            }
236
+        }
237
+        if(is_null($actorId)) {
238
+            throw new BadRequest('Invalid actor "' .  $actorType .'"');
239
+        }
240
+
241
+        try {
242
+            $comment = $this->commentsManager->create($actorType, $actorId, $objectType, $objectId);
243
+            $comment->setMessage($data['message']);
244
+            $comment->setVerb($data['verb']);
245
+            $this->commentsManager->save($comment);
246
+            return $comment;
247
+        } catch (\InvalidArgumentException $e) {
248
+            throw new BadRequest('Invalid input values', 0, $e);
249
+        } catch (\OCP\Comments\MessageTooLongException $e) {
250
+            $msg = 'Message exceeds allowed character limit of ';
251
+            throw new BadRequest($msg . \OCP\Comments\IComment::MAX_MESSAGE_LENGTH, 0,	$e);
252
+        }
253
+    }
254 254
 
255 255
 
256 256
 
Please login to merge, or discard this patch.
Spacing   +17 added lines, -17 removed lines patch added patch discarded remove patch
@@ -85,13 +85,13 @@  discard block
 block discarded – undo
85 85
 	 */
86 86
 	function initialize(Server $server) {
87 87
 		$this->server = $server;
88
-		if(strpos($this->server->getRequestUri(), 'comments/') !== 0) {
88
+		if (strpos($this->server->getRequestUri(), 'comments/') !== 0) {
89 89
 			return;
90 90
 		}
91 91
 
92 92
 		$this->server->xml->namespaceMap[self::NS_OWNCLOUD] = 'oc';
93 93
 
94
-		$this->server->xml->classMap['DateTime'] = function (Writer $writer, \DateTime $value) {
94
+		$this->server->xml->classMap['DateTime'] = function(Writer $writer, \DateTime $value) {
95 95
 			$writer->write(\Sabre\HTTP\toDate($value));
96 96
 		};
97 97
 
@@ -125,7 +125,7 @@  discard block
 block discarded – undo
125 125
 		// having their own comments marked as unread
126 126
 		$node->setReadMarker(null);
127 127
 
128
-		$url = rtrim($request->getUrl(), '/') . '/' . urlencode($comment->getId());
128
+		$url = rtrim($request->getUrl(), '/').'/'.urlencode($comment->getId());
129 129
 
130 130
 		$response->setHeader('Content-Location', $url);
131 131
 
@@ -158,7 +158,7 @@  discard block
 block discarded – undo
158 158
 	 */
159 159
 	public function onReport($reportName, $report, $uri) {
160 160
 		$node = $this->server->tree->getNodeForPath($uri);
161
-		if(!$node instanceof EntityCollection || $reportName !== self::REPORT_NAME) {
161
+		if (!$node instanceof EntityCollection || $reportName !== self::REPORT_NAME) {
162 162
 			throw new ReportNotSupported();
163 163
 		}
164 164
 		$args = ['limit' => 0, 'offset' => 0, 'datetime' => null];
@@ -167,27 +167,27 @@  discard block
 block discarded – undo
167 167
 			$this::REPORT_PARAM_OFFSET,
168 168
 			$this::REPORT_PARAM_TIMESTAMP
169 169
 		];
170
-		$ns = '{' . $this::NS_OWNCLOUD . '}';
171
-		foreach($report as $parameter) {
172
-			if(!in_array($parameter['name'], $acceptableParameters) || empty($parameter['value'])) {
170
+		$ns = '{'.$this::NS_OWNCLOUD.'}';
171
+		foreach ($report as $parameter) {
172
+			if (!in_array($parameter['name'], $acceptableParameters) || empty($parameter['value'])) {
173 173
 				continue;
174 174
 			}
175 175
 			$args[str_replace($ns, '', $parameter['name'])] = $parameter['value'];
176 176
 		}
177 177
 
178
-		if(!is_null($args['datetime'])) {
178
+		if (!is_null($args['datetime'])) {
179 179
 			$args['datetime'] = new \DateTime($args['datetime']);
180 180
 		}
181 181
 
182 182
 		$results = $node->findChildren($args['limit'], $args['offset'], $args['datetime']);
183 183
 
184 184
 		$responses = [];
185
-		foreach($results as $node) {
186
-			$nodePath = $this->server->getRequestUri() . '/' . $node->comment->getId();
185
+		foreach ($results as $node) {
186
+			$nodePath = $this->server->getRequestUri().'/'.$node->comment->getId();
187 187
 			$resultSet = $this->server->getPropertiesForPath($nodePath, CommentNode::getPropertyNames());
188
-			if(isset($resultSet[0]) && isset($resultSet[0][200])) {
188
+			if (isset($resultSet[0]) && isset($resultSet[0][200])) {
189 189
 				$responses[] = new Response(
190
-					$this->server->getBaseUri() . $nodePath,
190
+					$this->server->getBaseUri().$nodePath,
191 191
 					[200 => $resultSet[0][200]],
192 192
 					200
193 193
 				);
@@ -228,14 +228,14 @@  discard block
 block discarded – undo
228 228
 
229 229
 		$actorType = $data['actorType'];
230 230
 		$actorId = null;
231
-		if($actorType === 'users') {
231
+		if ($actorType === 'users') {
232 232
 			$user = $this->userSession->getUser();
233
-			if(!is_null($user)) {
233
+			if (!is_null($user)) {
234 234
 				$actorId = $user->getUID();
235 235
 			}
236 236
 		}
237
-		if(is_null($actorId)) {
238
-			throw new BadRequest('Invalid actor "' .  $actorType .'"');
237
+		if (is_null($actorId)) {
238
+			throw new BadRequest('Invalid actor "'.$actorType.'"');
239 239
 		}
240 240
 
241 241
 		try {
@@ -248,7 +248,7 @@  discard block
 block discarded – undo
248 248
 			throw new BadRequest('Invalid input values', 0, $e);
249 249
 		} catch (\OCP\Comments\MessageTooLongException $e) {
250 250
 			$msg = 'Message exceeds allowed character limit of ';
251
-			throw new BadRequest($msg . \OCP\Comments\IComment::MAX_MESSAGE_LENGTH, 0,	$e);
251
+			throw new BadRequest($msg.\OCP\Comments\IComment::MAX_MESSAGE_LENGTH, 0, $e);
252 252
 		}
253 253
 	}
254 254
 
Please login to merge, or discard this patch.
apps/dav/lib/CalDAV/CalDavBackend.php 2 patches
Indentation   +2560 added lines, -2560 removed lines patch added patch discarded remove patch
@@ -78,2564 +78,2564 @@
 block discarded – undo
78 78
  */
79 79
 class CalDavBackend extends AbstractBackend implements SyncSupport, SubscriptionSupport, SchedulingSupport {
80 80
 
81
-	const CALENDAR_TYPE_CALENDAR = 0;
82
-	const CALENDAR_TYPE_SUBSCRIPTION = 1;
83
-
84
-	const PERSONAL_CALENDAR_URI = 'personal';
85
-	const PERSONAL_CALENDAR_NAME = 'Personal';
86
-
87
-	const RESOURCE_BOOKING_CALENDAR_URI = 'calendar';
88
-	const RESOURCE_BOOKING_CALENDAR_NAME = 'Calendar';
89
-
90
-	/**
91
-	 * We need to specify a max date, because we need to stop *somewhere*
92
-	 *
93
-	 * On 32 bit system the maximum for a signed integer is 2147483647, so
94
-	 * MAX_DATE cannot be higher than date('Y-m-d', 2147483647) which results
95
-	 * in 2038-01-19 to avoid problems when the date is converted
96
-	 * to a unix timestamp.
97
-	 */
98
-	const MAX_DATE = '2038-01-01';
99
-
100
-	const ACCESS_PUBLIC = 4;
101
-	const CLASSIFICATION_PUBLIC = 0;
102
-	const CLASSIFICATION_PRIVATE = 1;
103
-	const CLASSIFICATION_CONFIDENTIAL = 2;
104
-
105
-	/**
106
-	 * List of CalDAV properties, and how they map to database field names
107
-	 * Add your own properties by simply adding on to this array.
108
-	 *
109
-	 * Note that only string-based properties are supported here.
110
-	 *
111
-	 * @var array
112
-	 */
113
-	public $propertyMap = [
114
-		'{DAV:}displayname'                          => 'displayname',
115
-		'{urn:ietf:params:xml:ns:caldav}calendar-description' => 'description',
116
-		'{urn:ietf:params:xml:ns:caldav}calendar-timezone'    => 'timezone',
117
-		'{http://apple.com/ns/ical/}calendar-order'  => 'calendarorder',
118
-		'{http://apple.com/ns/ical/}calendar-color'  => 'calendarcolor',
119
-	];
120
-
121
-	/**
122
-	 * List of subscription properties, and how they map to database field names.
123
-	 *
124
-	 * @var array
125
-	 */
126
-	public $subscriptionPropertyMap = [
127
-		'{DAV:}displayname'                                           => 'displayname',
128
-		'{http://apple.com/ns/ical/}refreshrate'                      => 'refreshrate',
129
-		'{http://apple.com/ns/ical/}calendar-order'                   => 'calendarorder',
130
-		'{http://apple.com/ns/ical/}calendar-color'                   => 'calendarcolor',
131
-		'{http://calendarserver.org/ns/}subscribed-strip-todos'       => 'striptodos',
132
-		'{http://calendarserver.org/ns/}subscribed-strip-alarms'      => 'stripalarms',
133
-		'{http://calendarserver.org/ns/}subscribed-strip-attachments' => 'stripattachments',
134
-	];
135
-
136
-	/** @var array properties to index */
137
-	public static $indexProperties = ['CATEGORIES', 'COMMENT', 'DESCRIPTION',
138
-		'LOCATION', 'RESOURCES', 'STATUS', 'SUMMARY', 'ATTENDEE', 'CONTACT',
139
-		'ORGANIZER'];
140
-
141
-	/** @var array parameters to index */
142
-	public static $indexParameters = [
143
-		'ATTENDEE' => ['CN'],
144
-		'ORGANIZER' => ['CN'],
145
-	];
146
-
147
-	/**
148
-	 * @var string[] Map of uid => display name
149
-	 */
150
-	protected $userDisplayNames;
151
-
152
-	/** @var IDBConnection */
153
-	private $db;
154
-
155
-	/** @var Backend */
156
-	private $calendarSharingBackend;
157
-
158
-	/** @var Principal */
159
-	private $principalBackend;
160
-
161
-	/** @var IUserManager */
162
-	private $userManager;
163
-
164
-	/** @var ISecureRandom */
165
-	private $random;
166
-
167
-	/** @var ILogger */
168
-	private $logger;
169
-
170
-	/** @var EventDispatcherInterface */
171
-	private $dispatcher;
172
-
173
-	/** @var bool */
174
-	private $legacyEndpoint;
175
-
176
-	/** @var string */
177
-	private $dbObjectPropertiesTable = 'calendarobjects_props';
178
-
179
-	/**
180
-	 * CalDavBackend constructor.
181
-	 *
182
-	 * @param IDBConnection $db
183
-	 * @param Principal $principalBackend
184
-	 * @param IUserManager $userManager
185
-	 * @param IGroupManager $groupManager
186
-	 * @param ISecureRandom $random
187
-	 * @param ILogger $logger
188
-	 * @param EventDispatcherInterface $dispatcher
189
-	 * @param bool $legacyEndpoint
190
-	 */
191
-	public function __construct(IDBConnection $db,
192
-								Principal $principalBackend,
193
-								IUserManager $userManager,
194
-								IGroupManager $groupManager,
195
-								ISecureRandom $random,
196
-								ILogger $logger,
197
-								EventDispatcherInterface $dispatcher,
198
-								bool $legacyEndpoint = false) {
199
-		$this->db = $db;
200
-		$this->principalBackend = $principalBackend;
201
-		$this->userManager = $userManager;
202
-		$this->calendarSharingBackend = new Backend($this->db, $this->userManager, $groupManager, $principalBackend, 'calendar');
203
-		$this->random = $random;
204
-		$this->logger = $logger;
205
-		$this->dispatcher = $dispatcher;
206
-		$this->legacyEndpoint = $legacyEndpoint;
207
-	}
208
-
209
-	/**
210
-	 * Return the number of calendars for a principal
211
-	 *
212
-	 * By default this excludes the automatically generated birthday calendar
213
-	 *
214
-	 * @param $principalUri
215
-	 * @param bool $excludeBirthday
216
-	 * @return int
217
-	 */
218
-	public function getCalendarsForUserCount($principalUri, $excludeBirthday = true) {
219
-		$principalUri = $this->convertPrincipal($principalUri, true);
220
-		$query = $this->db->getQueryBuilder();
221
-		$query->select($query->func()->count('*'))
222
-			->from('calendars')
223
-			->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)));
224
-
225
-		if ($excludeBirthday) {
226
-			$query->andWhere($query->expr()->neq('uri', $query->createNamedParameter(BirthdayService::BIRTHDAY_CALENDAR_URI)));
227
-		}
228
-
229
-		return (int)$query->execute()->fetchColumn();
230
-	}
231
-
232
-	/**
233
-	 * Returns a list of calendars for a principal.
234
-	 *
235
-	 * Every project is an array with the following keys:
236
-	 *  * id, a unique id that will be used by other functions to modify the
237
-	 *    calendar. This can be the same as the uri or a database key.
238
-	 *  * uri, which the basename of the uri with which the calendar is
239
-	 *    accessed.
240
-	 *  * principaluri. The owner of the calendar. Almost always the same as
241
-	 *    principalUri passed to this method.
242
-	 *
243
-	 * Furthermore it can contain webdav properties in clark notation. A very
244
-	 * common one is '{DAV:}displayname'.
245
-	 *
246
-	 * Many clients also require:
247
-	 * {urn:ietf:params:xml:ns:caldav}supported-calendar-component-set
248
-	 * For this property, you can just return an instance of
249
-	 * Sabre\CalDAV\Property\SupportedCalendarComponentSet.
250
-	 *
251
-	 * If you return {http://sabredav.org/ns}read-only and set the value to 1,
252
-	 * ACL will automatically be put in read-only mode.
253
-	 *
254
-	 * @param string $principalUri
255
-	 * @return array
256
-	 */
257
-	function getCalendarsForUser($principalUri) {
258
-		$principalUriOriginal = $principalUri;
259
-		$principalUri = $this->convertPrincipal($principalUri, true);
260
-		$fields = array_values($this->propertyMap);
261
-		$fields[] = 'id';
262
-		$fields[] = 'uri';
263
-		$fields[] = 'synctoken';
264
-		$fields[] = 'components';
265
-		$fields[] = 'principaluri';
266
-		$fields[] = 'transparent';
267
-
268
-		// Making fields a comma-delimited list
269
-		$query = $this->db->getQueryBuilder();
270
-		$query->select($fields)->from('calendars')
271
-				->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
272
-				->orderBy('calendarorder', 'ASC');
273
-		$stmt = $query->execute();
274
-
275
-		$calendars = [];
276
-		while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
277
-
278
-			$components = [];
279
-			if ($row['components']) {
280
-				$components = explode(',',$row['components']);
281
-			}
282
-
283
-			$calendar = [
284
-				'id' => $row['id'],
285
-				'uri' => $row['uri'],
286
-				'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
287
-				'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
288
-				'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
289
-				'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
290
-				'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
291
-				'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($principalUri, !$this->legacyEndpoint),
292
-			];
293
-
294
-			foreach($this->propertyMap as $xmlName=>$dbName) {
295
-				$calendar[$xmlName] = $row[$dbName];
296
-			}
297
-
298
-			$this->addOwnerPrincipal($calendar);
299
-
300
-			if (!isset($calendars[$calendar['id']])) {
301
-				$calendars[$calendar['id']] = $calendar;
302
-			}
303
-		}
304
-
305
-		$stmt->closeCursor();
306
-
307
-		// query for shared calendars
308
-		$principals = $this->principalBackend->getGroupMembership($principalUriOriginal, true);
309
-		$principals = array_merge($principals, $this->principalBackend->getCircleMembership($principalUriOriginal));
310
-
311
-		$principals = array_map(function ($principal) {
312
-			return urldecode($principal);
313
-		}, $principals);
314
-		$principals[]= $principalUri;
315
-
316
-		$fields = array_values($this->propertyMap);
317
-		$fields[] = 'a.id';
318
-		$fields[] = 'a.uri';
319
-		$fields[] = 'a.synctoken';
320
-		$fields[] = 'a.components';
321
-		$fields[] = 'a.principaluri';
322
-		$fields[] = 'a.transparent';
323
-		$fields[] = 's.access';
324
-		$query = $this->db->getQueryBuilder();
325
-		$result = $query->select($fields)
326
-			->from('dav_shares', 's')
327
-			->join('s', 'calendars', 'a', $query->expr()->eq('s.resourceid', 'a.id'))
328
-			->where($query->expr()->in('s.principaluri', $query->createParameter('principaluri')))
329
-			->andWhere($query->expr()->eq('s.type', $query->createParameter('type')))
330
-			->setParameter('type', 'calendar')
331
-			->setParameter('principaluri', $principals, \Doctrine\DBAL\Connection::PARAM_STR_ARRAY)
332
-			->execute();
333
-
334
-		$readOnlyPropertyName = '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}read-only';
335
-		while($row = $result->fetch()) {
336
-			if ($row['principaluri'] === $principalUri) {
337
-				continue;
338
-			}
339
-
340
-			$readOnly = (int) $row['access'] === Backend::ACCESS_READ;
341
-			if (isset($calendars[$row['id']])) {
342
-				if ($readOnly) {
343
-					// New share can not have more permissions then the old one.
344
-					continue;
345
-				}
346
-				if (isset($calendars[$row['id']][$readOnlyPropertyName]) &&
347
-					$calendars[$row['id']][$readOnlyPropertyName] === 0) {
348
-					// Old share is already read-write, no more permissions can be gained
349
-					continue;
350
-				}
351
-			}
352
-
353
-			list(, $name) = Uri\split($row['principaluri']);
354
-			$uri = $row['uri'] . '_shared_by_' . $name;
355
-			$row['displayname'] = $row['displayname'] . ' (' . $this->getUserDisplayName($name) . ')';
356
-			$components = [];
357
-			if ($row['components']) {
358
-				$components = explode(',',$row['components']);
359
-			}
360
-			$calendar = [
361
-				'id' => $row['id'],
362
-				'uri' => $uri,
363
-				'principaluri' => $this->convertPrincipal($principalUri, !$this->legacyEndpoint),
364
-				'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
365
-				'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
366
-				'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
367
-				'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp('transparent'),
368
-				'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
369
-				$readOnlyPropertyName => $readOnly,
370
-			];
371
-
372
-			foreach($this->propertyMap as $xmlName=>$dbName) {
373
-				$calendar[$xmlName] = $row[$dbName];
374
-			}
375
-
376
-			$this->addOwnerPrincipal($calendar);
377
-
378
-			$calendars[$calendar['id']] = $calendar;
379
-		}
380
-		$result->closeCursor();
381
-
382
-		return array_values($calendars);
383
-	}
384
-
385
-	/**
386
-	 * @param $principalUri
387
-	 * @return array
388
-	 */
389
-	public function getUsersOwnCalendars($principalUri) {
390
-		$principalUri = $this->convertPrincipal($principalUri, true);
391
-		$fields = array_values($this->propertyMap);
392
-		$fields[] = 'id';
393
-		$fields[] = 'uri';
394
-		$fields[] = 'synctoken';
395
-		$fields[] = 'components';
396
-		$fields[] = 'principaluri';
397
-		$fields[] = 'transparent';
398
-		// Making fields a comma-delimited list
399
-		$query = $this->db->getQueryBuilder();
400
-		$query->select($fields)->from('calendars')
401
-			->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
402
-			->orderBy('calendarorder', 'ASC');
403
-		$stmt = $query->execute();
404
-		$calendars = [];
405
-		while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
406
-			$components = [];
407
-			if ($row['components']) {
408
-				$components = explode(',',$row['components']);
409
-			}
410
-			$calendar = [
411
-				'id' => $row['id'],
412
-				'uri' => $row['uri'],
413
-				'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
414
-				'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
415
-				'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
416
-				'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
417
-				'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
418
-			];
419
-			foreach($this->propertyMap as $xmlName=>$dbName) {
420
-				$calendar[$xmlName] = $row[$dbName];
421
-			}
422
-
423
-			$this->addOwnerPrincipal($calendar);
424
-
425
-			if (!isset($calendars[$calendar['id']])) {
426
-				$calendars[$calendar['id']] = $calendar;
427
-			}
428
-		}
429
-		$stmt->closeCursor();
430
-		return array_values($calendars);
431
-	}
432
-
433
-
434
-	/**
435
-	 * @param $uid
436
-	 * @return string
437
-	 */
438
-	private function getUserDisplayName($uid) {
439
-		if (!isset($this->userDisplayNames[$uid])) {
440
-			$user = $this->userManager->get($uid);
441
-
442
-			if ($user instanceof IUser) {
443
-				$this->userDisplayNames[$uid] = $user->getDisplayName();
444
-			} else {
445
-				$this->userDisplayNames[$uid] = $uid;
446
-			}
447
-		}
448
-
449
-		return $this->userDisplayNames[$uid];
450
-	}
451
-
452
-	/**
453
-	 * @return array
454
-	 */
455
-	public function getPublicCalendars() {
456
-		$fields = array_values($this->propertyMap);
457
-		$fields[] = 'a.id';
458
-		$fields[] = 'a.uri';
459
-		$fields[] = 'a.synctoken';
460
-		$fields[] = 'a.components';
461
-		$fields[] = 'a.principaluri';
462
-		$fields[] = 'a.transparent';
463
-		$fields[] = 's.access';
464
-		$fields[] = 's.publicuri';
465
-		$calendars = [];
466
-		$query = $this->db->getQueryBuilder();
467
-		$result = $query->select($fields)
468
-			->from('dav_shares', 's')
469
-			->join('s', 'calendars', 'a', $query->expr()->eq('s.resourceid', 'a.id'))
470
-			->where($query->expr()->in('s.access', $query->createNamedParameter(self::ACCESS_PUBLIC)))
471
-			->andWhere($query->expr()->eq('s.type', $query->createNamedParameter('calendar')))
472
-			->execute();
473
-
474
-		while($row = $result->fetch()) {
475
-			list(, $name) = Uri\split($row['principaluri']);
476
-			$row['displayname'] = $row['displayname'] . "($name)";
477
-			$components = [];
478
-			if ($row['components']) {
479
-				$components = explode(',',$row['components']);
480
-			}
481
-			$calendar = [
482
-				'id' => $row['id'],
483
-				'uri' => $row['publicuri'],
484
-				'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
485
-				'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
486
-				'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
487
-				'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
488
-				'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
489
-				'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($row['principaluri'], $this->legacyEndpoint),
490
-				'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}read-only' => (int)$row['access'] === Backend::ACCESS_READ,
491
-				'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}public' => (int)$row['access'] === self::ACCESS_PUBLIC,
492
-			];
493
-
494
-			foreach($this->propertyMap as $xmlName=>$dbName) {
495
-				$calendar[$xmlName] = $row[$dbName];
496
-			}
497
-
498
-			$this->addOwnerPrincipal($calendar);
499
-
500
-			if (!isset($calendars[$calendar['id']])) {
501
-				$calendars[$calendar['id']] = $calendar;
502
-			}
503
-		}
504
-		$result->closeCursor();
505
-
506
-		return array_values($calendars);
507
-	}
508
-
509
-	/**
510
-	 * @param string $uri
511
-	 * @return array
512
-	 * @throws NotFound
513
-	 */
514
-	public function getPublicCalendar($uri) {
515
-		$fields = array_values($this->propertyMap);
516
-		$fields[] = 'a.id';
517
-		$fields[] = 'a.uri';
518
-		$fields[] = 'a.synctoken';
519
-		$fields[] = 'a.components';
520
-		$fields[] = 'a.principaluri';
521
-		$fields[] = 'a.transparent';
522
-		$fields[] = 's.access';
523
-		$fields[] = 's.publicuri';
524
-		$query = $this->db->getQueryBuilder();
525
-		$result = $query->select($fields)
526
-			->from('dav_shares', 's')
527
-			->join('s', 'calendars', 'a', $query->expr()->eq('s.resourceid', 'a.id'))
528
-			->where($query->expr()->in('s.access', $query->createNamedParameter(self::ACCESS_PUBLIC)))
529
-			->andWhere($query->expr()->eq('s.type', $query->createNamedParameter('calendar')))
530
-			->andWhere($query->expr()->eq('s.publicuri', $query->createNamedParameter($uri)))
531
-			->execute();
532
-
533
-		$row = $result->fetch(\PDO::FETCH_ASSOC);
534
-
535
-		$result->closeCursor();
536
-
537
-		if ($row === false) {
538
-			throw new NotFound('Node with name \'' . $uri . '\' could not be found');
539
-		}
540
-
541
-		list(, $name) = Uri\split($row['principaluri']);
542
-		$row['displayname'] = $row['displayname'] . ' ' . "($name)";
543
-		$components = [];
544
-		if ($row['components']) {
545
-			$components = explode(',',$row['components']);
546
-		}
547
-		$calendar = [
548
-			'id' => $row['id'],
549
-			'uri' => $row['publicuri'],
550
-			'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
551
-			'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
552
-			'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
553
-			'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
554
-			'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
555
-			'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
556
-			'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}read-only' => (int)$row['access'] === Backend::ACCESS_READ,
557
-			'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}public' => (int)$row['access'] === self::ACCESS_PUBLIC,
558
-		];
559
-
560
-		foreach($this->propertyMap as $xmlName=>$dbName) {
561
-			$calendar[$xmlName] = $row[$dbName];
562
-		}
563
-
564
-		$this->addOwnerPrincipal($calendar);
565
-
566
-		return $calendar;
567
-
568
-	}
569
-
570
-	/**
571
-	 * @param string $principal
572
-	 * @param string $uri
573
-	 * @return array|null
574
-	 */
575
-	public function getCalendarByUri($principal, $uri) {
576
-		$fields = array_values($this->propertyMap);
577
-		$fields[] = 'id';
578
-		$fields[] = 'uri';
579
-		$fields[] = 'synctoken';
580
-		$fields[] = 'components';
581
-		$fields[] = 'principaluri';
582
-		$fields[] = 'transparent';
583
-
584
-		// Making fields a comma-delimited list
585
-		$query = $this->db->getQueryBuilder();
586
-		$query->select($fields)->from('calendars')
587
-			->where($query->expr()->eq('uri', $query->createNamedParameter($uri)))
588
-			->andWhere($query->expr()->eq('principaluri', $query->createNamedParameter($principal)))
589
-			->setMaxResults(1);
590
-		$stmt = $query->execute();
591
-
592
-		$row = $stmt->fetch(\PDO::FETCH_ASSOC);
593
-		$stmt->closeCursor();
594
-		if ($row === false) {
595
-			return null;
596
-		}
597
-
598
-		$components = [];
599
-		if ($row['components']) {
600
-			$components = explode(',',$row['components']);
601
-		}
602
-
603
-		$calendar = [
604
-			'id' => $row['id'],
605
-			'uri' => $row['uri'],
606
-			'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
607
-			'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
608
-			'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
609
-			'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
610
-			'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
611
-		];
612
-
613
-		foreach($this->propertyMap as $xmlName=>$dbName) {
614
-			$calendar[$xmlName] = $row[$dbName];
615
-		}
616
-
617
-		$this->addOwnerPrincipal($calendar);
618
-
619
-		return $calendar;
620
-	}
621
-
622
-	/**
623
-	 * @param $calendarId
624
-	 * @return array|null
625
-	 */
626
-	public function getCalendarById($calendarId) {
627
-		$fields = array_values($this->propertyMap);
628
-		$fields[] = 'id';
629
-		$fields[] = 'uri';
630
-		$fields[] = 'synctoken';
631
-		$fields[] = 'components';
632
-		$fields[] = 'principaluri';
633
-		$fields[] = 'transparent';
634
-
635
-		// Making fields a comma-delimited list
636
-		$query = $this->db->getQueryBuilder();
637
-		$query->select($fields)->from('calendars')
638
-			->where($query->expr()->eq('id', $query->createNamedParameter($calendarId)))
639
-			->setMaxResults(1);
640
-		$stmt = $query->execute();
641
-
642
-		$row = $stmt->fetch(\PDO::FETCH_ASSOC);
643
-		$stmt->closeCursor();
644
-		if ($row === false) {
645
-			return null;
646
-		}
647
-
648
-		$components = [];
649
-		if ($row['components']) {
650
-			$components = explode(',',$row['components']);
651
-		}
652
-
653
-		$calendar = [
654
-			'id' => $row['id'],
655
-			'uri' => $row['uri'],
656
-			'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
657
-			'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
658
-			'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
659
-			'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
660
-			'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
661
-		];
662
-
663
-		foreach($this->propertyMap as $xmlName=>$dbName) {
664
-			$calendar[$xmlName] = $row[$dbName];
665
-		}
666
-
667
-		$this->addOwnerPrincipal($calendar);
668
-
669
-		return $calendar;
670
-	}
671
-
672
-	/**
673
-	 * @param $subscriptionId
674
-	 */
675
-	public function getSubscriptionById($subscriptionId) {
676
-		$fields = array_values($this->subscriptionPropertyMap);
677
-		$fields[] = 'id';
678
-		$fields[] = 'uri';
679
-		$fields[] = 'source';
680
-		$fields[] = 'synctoken';
681
-		$fields[] = 'principaluri';
682
-		$fields[] = 'lastmodified';
683
-
684
-		$query = $this->db->getQueryBuilder();
685
-		$query->select($fields)
686
-			->from('calendarsubscriptions')
687
-			->where($query->expr()->eq('id', $query->createNamedParameter($subscriptionId)))
688
-			->orderBy('calendarorder', 'asc');
689
-		$stmt =$query->execute();
690
-
691
-		$row = $stmt->fetch(\PDO::FETCH_ASSOC);
692
-		$stmt->closeCursor();
693
-		if ($row === false) {
694
-			return null;
695
-		}
696
-
697
-		$subscription = [
698
-			'id'           => $row['id'],
699
-			'uri'          => $row['uri'],
700
-			'principaluri' => $row['principaluri'],
701
-			'source'       => $row['source'],
702
-			'lastmodified' => $row['lastmodified'],
703
-			'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet(['VTODO', 'VEVENT']),
704
-			'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
705
-		];
706
-
707
-		foreach($this->subscriptionPropertyMap as $xmlName=>$dbName) {
708
-			if (!is_null($row[$dbName])) {
709
-				$subscription[$xmlName] = $row[$dbName];
710
-			}
711
-		}
712
-
713
-		return $subscription;
714
-	}
715
-
716
-	/**
717
-	 * Creates a new calendar for a principal.
718
-	 *
719
-	 * If the creation was a success, an id must be returned that can be used to reference
720
-	 * this calendar in other methods, such as updateCalendar.
721
-	 *
722
-	 * @param string $principalUri
723
-	 * @param string $calendarUri
724
-	 * @param array $properties
725
-	 * @return int
726
-	 * @suppress SqlInjectionChecker
727
-	 */
728
-	function createCalendar($principalUri, $calendarUri, array $properties) {
729
-		$values = [
730
-			'principaluri' => $this->convertPrincipal($principalUri, true),
731
-			'uri'          => $calendarUri,
732
-			'synctoken'    => 1,
733
-			'transparent'  => 0,
734
-			'components'   => 'VEVENT,VTODO',
735
-			'displayname'  => $calendarUri
736
-		];
737
-
738
-		// Default value
739
-		$sccs = '{urn:ietf:params:xml:ns:caldav}supported-calendar-component-set';
740
-		if (isset($properties[$sccs])) {
741
-			if (!($properties[$sccs] instanceof SupportedCalendarComponentSet)) {
742
-				throw new DAV\Exception('The ' . $sccs . ' property must be of type: \Sabre\CalDAV\Property\SupportedCalendarComponentSet');
743
-			}
744
-			$values['components'] = implode(',',$properties[$sccs]->getValue());
745
-		} else if (isset($properties['components'])) {
746
-			// Allow to provide components internally without having
747
-			// to create a SupportedCalendarComponentSet object
748
-			$values['components'] = $properties['components'];
749
-		}
750
-
751
-		$transp = '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp';
752
-		if (isset($properties[$transp])) {
753
-			$values['transparent'] = (int) ($properties[$transp]->getValue() === 'transparent');
754
-		}
755
-
756
-		foreach($this->propertyMap as $xmlName=>$dbName) {
757
-			if (isset($properties[$xmlName])) {
758
-				$values[$dbName] = $properties[$xmlName];
759
-			}
760
-		}
761
-
762
-		$query = $this->db->getQueryBuilder();
763
-		$query->insert('calendars');
764
-		foreach($values as $column => $value) {
765
-			$query->setValue($column, $query->createNamedParameter($value));
766
-		}
767
-		$query->execute();
768
-		$calendarId = $query->getLastInsertId();
769
-
770
-		$this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::createCalendar', new GenericEvent(
771
-			'\OCA\DAV\CalDAV\CalDavBackend::createCalendar',
772
-			[
773
-				'calendarId' => $calendarId,
774
-				'calendarData' => $this->getCalendarById($calendarId),
775
-			]));
776
-
777
-		return $calendarId;
778
-	}
779
-
780
-	/**
781
-	 * Updates properties for a calendar.
782
-	 *
783
-	 * The list of mutations is stored in a Sabre\DAV\PropPatch object.
784
-	 * To do the actual updates, you must tell this object which properties
785
-	 * you're going to process with the handle() method.
786
-	 *
787
-	 * Calling the handle method is like telling the PropPatch object "I
788
-	 * promise I can handle updating this property".
789
-	 *
790
-	 * Read the PropPatch documentation for more info and examples.
791
-	 *
792
-	 * @param mixed $calendarId
793
-	 * @param PropPatch $propPatch
794
-	 * @return void
795
-	 */
796
-	function updateCalendar($calendarId, PropPatch $propPatch) {
797
-		$supportedProperties = array_keys($this->propertyMap);
798
-		$supportedProperties[] = '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp';
799
-
800
-		/**
801
-		 * @suppress SqlInjectionChecker
802
-		 */
803
-		$propPatch->handle($supportedProperties, function ($mutations) use ($calendarId) {
804
-			$newValues = [];
805
-			foreach ($mutations as $propertyName => $propertyValue) {
806
-
807
-				switch ($propertyName) {
808
-					case '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' :
809
-						$fieldName = 'transparent';
810
-						$newValues[$fieldName] = (int) ($propertyValue->getValue() === 'transparent');
811
-						break;
812
-					default :
813
-						$fieldName = $this->propertyMap[$propertyName];
814
-						$newValues[$fieldName] = $propertyValue;
815
-						break;
816
-				}
817
-
818
-			}
819
-			$query = $this->db->getQueryBuilder();
820
-			$query->update('calendars');
821
-			foreach ($newValues as $fieldName => $value) {
822
-				$query->set($fieldName, $query->createNamedParameter($value));
823
-			}
824
-			$query->where($query->expr()->eq('id', $query->createNamedParameter($calendarId)));
825
-			$query->execute();
826
-
827
-			$this->addChange($calendarId, "", 2);
828
-
829
-			$this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::updateCalendar', new GenericEvent(
830
-				'\OCA\DAV\CalDAV\CalDavBackend::updateCalendar',
831
-				[
832
-					'calendarId' => $calendarId,
833
-					'calendarData' => $this->getCalendarById($calendarId),
834
-					'shares' => $this->getShares($calendarId),
835
-					'propertyMutations' => $mutations,
836
-				]));
837
-
838
-			return true;
839
-		});
840
-	}
841
-
842
-	/**
843
-	 * Delete a calendar and all it's objects
844
-	 *
845
-	 * @param mixed $calendarId
846
-	 * @return void
847
-	 */
848
-	function deleteCalendar($calendarId) {
849
-		$this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::deleteCalendar', new GenericEvent(
850
-			'\OCA\DAV\CalDAV\CalDavBackend::deleteCalendar',
851
-			[
852
-				'calendarId' => $calendarId,
853
-				'calendarData' => $this->getCalendarById($calendarId),
854
-				'shares' => $this->getShares($calendarId),
855
-			]));
856
-
857
-		$stmt = $this->db->prepare('DELETE FROM `*PREFIX*calendarobjects` WHERE `calendarid` = ? AND `calendartype` = ?');
858
-		$stmt->execute([$calendarId, self::CALENDAR_TYPE_CALENDAR]);
859
-
860
-		$stmt = $this->db->prepare('DELETE FROM `*PREFIX*calendars` WHERE `id` = ?');
861
-		$stmt->execute([$calendarId]);
862
-
863
-		$stmt = $this->db->prepare('DELETE FROM `*PREFIX*calendarchanges` WHERE `calendarid` = ? AND `calendartype` = ?');
864
-		$stmt->execute([$calendarId, self::CALENDAR_TYPE_CALENDAR]);
865
-
866
-		$this->calendarSharingBackend->deleteAllShares($calendarId);
867
-
868
-		$query = $this->db->getQueryBuilder();
869
-		$query->delete($this->dbObjectPropertiesTable)
870
-			->where($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)))
871
-			->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_CALENDAR)))
872
-			->execute();
873
-	}
874
-
875
-	/**
876
-	 * Delete all of an user's shares
877
-	 *
878
-	 * @param string $principaluri
879
-	 * @return void
880
-	 */
881
-	function deleteAllSharesByUser($principaluri) {
882
-		$this->calendarSharingBackend->deleteAllSharesByUser($principaluri);
883
-	}
884
-
885
-	/**
886
-	 * Returns all calendar objects within a calendar.
887
-	 *
888
-	 * Every item contains an array with the following keys:
889
-	 *   * calendardata - The iCalendar-compatible calendar data
890
-	 *   * uri - a unique key which will be used to construct the uri. This can
891
-	 *     be any arbitrary string, but making sure it ends with '.ics' is a
892
-	 *     good idea. This is only the basename, or filename, not the full
893
-	 *     path.
894
-	 *   * lastmodified - a timestamp of the last modification time
895
-	 *   * etag - An arbitrary string, surrounded by double-quotes. (e.g.:
896
-	 *   '"abcdef"')
897
-	 *   * size - The size of the calendar objects, in bytes.
898
-	 *   * component - optional, a string containing the type of object, such
899
-	 *     as 'vevent' or 'vtodo'. If specified, this will be used to populate
900
-	 *     the Content-Type header.
901
-	 *
902
-	 * Note that the etag is optional, but it's highly encouraged to return for
903
-	 * speed reasons.
904
-	 *
905
-	 * The calendardata is also optional. If it's not returned
906
-	 * 'getCalendarObject' will be called later, which *is* expected to return
907
-	 * calendardata.
908
-	 *
909
-	 * If neither etag or size are specified, the calendardata will be
910
-	 * used/fetched to determine these numbers. If both are specified the
911
-	 * amount of times this is needed is reduced by a great degree.
912
-	 *
913
-	 * @param mixed $id
914
-	 * @param int $calendarType
915
-	 * @return array
916
-	 */
917
-	public function getCalendarObjects($id, $calendarType=self::CALENDAR_TYPE_CALENDAR):array {
918
-		$query = $this->db->getQueryBuilder();
919
-		$query->select(['id', 'uri', 'lastmodified', 'etag', 'calendarid', 'size', 'componenttype', 'classification'])
920
-			->from('calendarobjects')
921
-			->where($query->expr()->eq('calendarid', $query->createNamedParameter($id)))
922
-			->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter($calendarType)));
923
-		$stmt = $query->execute();
924
-
925
-		$result = [];
926
-		foreach($stmt->fetchAll(\PDO::FETCH_ASSOC) as $row) {
927
-			$result[] = [
928
-				'id'           => $row['id'],
929
-				'uri'          => $row['uri'],
930
-				'lastmodified' => $row['lastmodified'],
931
-				'etag'         => '"' . $row['etag'] . '"',
932
-				'calendarid'   => $row['calendarid'],
933
-				'size'         => (int)$row['size'],
934
-				'component'    => strtolower($row['componenttype']),
935
-				'classification'=> (int)$row['classification']
936
-			];
937
-		}
938
-
939
-		return $result;
940
-	}
941
-
942
-	/**
943
-	 * Returns information from a single calendar object, based on it's object
944
-	 * uri.
945
-	 *
946
-	 * The object uri is only the basename, or filename and not a full path.
947
-	 *
948
-	 * The returned array must have the same keys as getCalendarObjects. The
949
-	 * 'calendardata' object is required here though, while it's not required
950
-	 * for getCalendarObjects.
951
-	 *
952
-	 * This method must return null if the object did not exist.
953
-	 *
954
-	 * @param mixed $id
955
-	 * @param string $objectUri
956
-	 * @param int $calendarType
957
-	 * @return array|null
958
-	 */
959
-	public function getCalendarObject($id, $objectUri, $calendarType=self::CALENDAR_TYPE_CALENDAR) {
960
-		$query = $this->db->getQueryBuilder();
961
-		$query->select(['id', 'uri', 'lastmodified', 'etag', 'calendarid', 'size', 'calendardata', 'componenttype', 'classification'])
962
-			->from('calendarobjects')
963
-			->where($query->expr()->eq('calendarid', $query->createNamedParameter($id)))
964
-			->andWhere($query->expr()->eq('uri', $query->createNamedParameter($objectUri)))
965
-			->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter($calendarType)));
966
-		$stmt = $query->execute();
967
-		$row = $stmt->fetch(\PDO::FETCH_ASSOC);
968
-
969
-		if(!$row) {
970
-			return null;
971
-		}
972
-
973
-		return [
974
-			'id'            => $row['id'],
975
-			'uri'           => $row['uri'],
976
-			'lastmodified'  => $row['lastmodified'],
977
-			'etag'          => '"' . $row['etag'] . '"',
978
-			'calendarid'    => $row['calendarid'],
979
-			'size'          => (int)$row['size'],
980
-			'calendardata'  => $this->readBlob($row['calendardata']),
981
-			'component'     => strtolower($row['componenttype']),
982
-			'classification'=> (int)$row['classification']
983
-		];
984
-	}
985
-
986
-	/**
987
-	 * Returns a list of calendar objects.
988
-	 *
989
-	 * This method should work identical to getCalendarObject, but instead
990
-	 * return all the calendar objects in the list as an array.
991
-	 *
992
-	 * If the backend supports this, it may allow for some speed-ups.
993
-	 *
994
-	 * @param mixed $calendarId
995
-	 * @param string[] $uris
996
-	 * @param int $calendarType
997
-	 * @return array
998
-	 */
999
-	public function getMultipleCalendarObjects($id, array $uris, $calendarType=self::CALENDAR_TYPE_CALENDAR):array {
1000
-		if (empty($uris)) {
1001
-			return [];
1002
-		}
1003
-
1004
-		$chunks = array_chunk($uris, 100);
1005
-		$objects = [];
1006
-
1007
-		$query = $this->db->getQueryBuilder();
1008
-		$query->select(['id', 'uri', 'lastmodified', 'etag', 'calendarid', 'size', 'calendardata', 'componenttype', 'classification'])
1009
-			->from('calendarobjects')
1010
-			->where($query->expr()->eq('calendarid', $query->createNamedParameter($id)))
1011
-			->andWhere($query->expr()->in('uri', $query->createParameter('uri')))
1012
-			->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter($calendarType)));
1013
-
1014
-		foreach ($chunks as $uris) {
1015
-			$query->setParameter('uri', $uris, IQueryBuilder::PARAM_STR_ARRAY);
1016
-			$result = $query->execute();
1017
-
1018
-			while ($row = $result->fetch()) {
1019
-				$objects[] = [
1020
-					'id'           => $row['id'],
1021
-					'uri'          => $row['uri'],
1022
-					'lastmodified' => $row['lastmodified'],
1023
-					'etag'         => '"' . $row['etag'] . '"',
1024
-					'calendarid'   => $row['calendarid'],
1025
-					'size'         => (int)$row['size'],
1026
-					'calendardata' => $this->readBlob($row['calendardata']),
1027
-					'component'    => strtolower($row['componenttype']),
1028
-					'classification' => (int)$row['classification']
1029
-				];
1030
-			}
1031
-			$result->closeCursor();
1032
-		}
1033
-
1034
-		return $objects;
1035
-	}
1036
-
1037
-	/**
1038
-	 * Creates a new calendar object.
1039
-	 *
1040
-	 * The object uri is only the basename, or filename and not a full path.
1041
-	 *
1042
-	 * It is possible return an etag from this function, which will be used in
1043
-	 * the response to this PUT request. Note that the ETag must be surrounded
1044
-	 * by double-quotes.
1045
-	 *
1046
-	 * However, you should only really return this ETag if you don't mangle the
1047
-	 * calendar-data. If the result of a subsequent GET to this object is not
1048
-	 * the exact same as this request body, you should omit the ETag.
1049
-	 *
1050
-	 * @param mixed $calendarId
1051
-	 * @param string $objectUri
1052
-	 * @param string $calendarData
1053
-	 * @param int $calendarType
1054
-	 * @return string
1055
-	 */
1056
-	function createCalendarObject($calendarId, $objectUri, $calendarData, $calendarType=self::CALENDAR_TYPE_CALENDAR) {
1057
-		$extraData = $this->getDenormalizedData($calendarData);
1058
-
1059
-		$q = $this->db->getQueryBuilder();
1060
-		$q->select($q->func()->count('*'))
1061
-			->from('calendarobjects')
1062
-			->where($q->expr()->eq('calendarid', $q->createNamedParameter($calendarId)))
1063
-			->andWhere($q->expr()->eq('uid', $q->createNamedParameter($extraData['uid'])))
1064
-			->andWhere($q->expr()->eq('calendartype', $q->createNamedParameter($calendarType)));
1065
-
1066
-		$result = $q->execute();
1067
-		$count = (int) $result->fetchColumn();
1068
-		$result->closeCursor();
1069
-
1070
-		if ($count !== 0) {
1071
-			throw new \Sabre\DAV\Exception\BadRequest('Calendar object with uid already exists in this calendar collection.');
1072
-		}
1073
-
1074
-		$query = $this->db->getQueryBuilder();
1075
-		$query->insert('calendarobjects')
1076
-			->values([
1077
-				'calendarid' => $query->createNamedParameter($calendarId),
1078
-				'uri' => $query->createNamedParameter($objectUri),
1079
-				'calendardata' => $query->createNamedParameter($calendarData, IQueryBuilder::PARAM_LOB),
1080
-				'lastmodified' => $query->createNamedParameter(time()),
1081
-				'etag' => $query->createNamedParameter($extraData['etag']),
1082
-				'size' => $query->createNamedParameter($extraData['size']),
1083
-				'componenttype' => $query->createNamedParameter($extraData['componentType']),
1084
-				'firstoccurence' => $query->createNamedParameter($extraData['firstOccurence']),
1085
-				'lastoccurence' => $query->createNamedParameter($extraData['lastOccurence']),
1086
-				'classification' => $query->createNamedParameter($extraData['classification']),
1087
-				'uid' => $query->createNamedParameter($extraData['uid']),
1088
-				'calendartype' => $query->createNamedParameter($calendarType),
1089
-			])
1090
-			->execute();
1091
-
1092
-		$this->updateProperties($calendarId, $objectUri, $calendarData, $calendarType);
1093
-
1094
-		if ($calendarType === self::CALENDAR_TYPE_CALENDAR) {
1095
-			$this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::createCalendarObject', new GenericEvent(
1096
-				'\OCA\DAV\CalDAV\CalDavBackend::createCalendarObject',
1097
-				[
1098
-					'calendarId' => $calendarId,
1099
-					'calendarData' => $this->getCalendarById($calendarId),
1100
-					'shares' => $this->getShares($calendarId),
1101
-					'objectData' => $this->getCalendarObject($calendarId, $objectUri),
1102
-				]
1103
-			));
1104
-		} else {
1105
-			$this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::createCachedCalendarObject', new GenericEvent(
1106
-				'\OCA\DAV\CalDAV\CalDavBackend::createCachedCalendarObject',
1107
-				[
1108
-					'subscriptionId' => $calendarId,
1109
-					'calendarData' => $this->getCalendarById($calendarId),
1110
-					'shares' => $this->getShares($calendarId),
1111
-					'objectData' => $this->getCalendarObject($calendarId, $objectUri),
1112
-				]
1113
-			));
1114
-		}
1115
-		$this->addChange($calendarId, $objectUri, 1, $calendarType);
1116
-
1117
-		return '"' . $extraData['etag'] . '"';
1118
-	}
1119
-
1120
-	/**
1121
-	 * Updates an existing calendarobject, based on it's uri.
1122
-	 *
1123
-	 * The object uri is only the basename, or filename and not a full path.
1124
-	 *
1125
-	 * It is possible return an etag from this function, which will be used in
1126
-	 * the response to this PUT request. Note that the ETag must be surrounded
1127
-	 * by double-quotes.
1128
-	 *
1129
-	 * However, you should only really return this ETag if you don't mangle the
1130
-	 * calendar-data. If the result of a subsequent GET to this object is not
1131
-	 * the exact same as this request body, you should omit the ETag.
1132
-	 *
1133
-	 * @param mixed $calendarId
1134
-	 * @param string $objectUri
1135
-	 * @param string $calendarData
1136
-	 * @param int $calendarType
1137
-	 * @return string
1138
-	 */
1139
-	function updateCalendarObject($calendarId, $objectUri, $calendarData, $calendarType=self::CALENDAR_TYPE_CALENDAR) {
1140
-		$extraData = $this->getDenormalizedData($calendarData);
1141
-		$query = $this->db->getQueryBuilder();
1142
-		$query->update('calendarobjects')
1143
-				->set('calendardata', $query->createNamedParameter($calendarData, IQueryBuilder::PARAM_LOB))
1144
-				->set('lastmodified', $query->createNamedParameter(time()))
1145
-				->set('etag', $query->createNamedParameter($extraData['etag']))
1146
-				->set('size', $query->createNamedParameter($extraData['size']))
1147
-				->set('componenttype', $query->createNamedParameter($extraData['componentType']))
1148
-				->set('firstoccurence', $query->createNamedParameter($extraData['firstOccurence']))
1149
-				->set('lastoccurence', $query->createNamedParameter($extraData['lastOccurence']))
1150
-				->set('classification', $query->createNamedParameter($extraData['classification']))
1151
-				->set('uid', $query->createNamedParameter($extraData['uid']))
1152
-			->where($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)))
1153
-			->andWhere($query->expr()->eq('uri', $query->createNamedParameter($objectUri)))
1154
-			->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter($calendarType)))
1155
-			->execute();
1156
-
1157
-		$this->updateProperties($calendarId, $objectUri, $calendarData, $calendarType);
1158
-
1159
-		$data = $this->getCalendarObject($calendarId, $objectUri);
1160
-		if (is_array($data)) {
1161
-			if ($calendarType === self::CALENDAR_TYPE_CALENDAR) {
1162
-				$this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::updateCalendarObject', new GenericEvent(
1163
-					'\OCA\DAV\CalDAV\CalDavBackend::updateCalendarObject',
1164
-					[
1165
-						'calendarId' => $calendarId,
1166
-						'calendarData' => $this->getCalendarById($calendarId),
1167
-						'shares' => $this->getShares($calendarId),
1168
-						'objectData' => $data,
1169
-					]
1170
-				));
1171
-			} else {
1172
-				$this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::updateCachedCalendarObject', new GenericEvent(
1173
-					'\OCA\DAV\CalDAV\CalDavBackend::updateCachedCalendarObject',
1174
-					[
1175
-						'subscriptionId' => $calendarId,
1176
-						'calendarData' => $this->getCalendarById($calendarId),
1177
-						'shares' => $this->getShares($calendarId),
1178
-						'objectData' => $data,
1179
-					]
1180
-				));
1181
-			}
1182
-		}
1183
-		$this->addChange($calendarId, $objectUri, 2, $calendarType);
1184
-
1185
-		return '"' . $extraData['etag'] . '"';
1186
-	}
1187
-
1188
-	/**
1189
-	 * @param int $calendarObjectId
1190
-	 * @param int $classification
1191
-	 */
1192
-	public function setClassification($calendarObjectId, $classification) {
1193
-		if (!in_array($classification, [
1194
-			self::CLASSIFICATION_PUBLIC, self::CLASSIFICATION_PRIVATE, self::CLASSIFICATION_CONFIDENTIAL
1195
-		])) {
1196
-			throw new \InvalidArgumentException();
1197
-		}
1198
-		$query = $this->db->getQueryBuilder();
1199
-		$query->update('calendarobjects')
1200
-			->set('classification', $query->createNamedParameter($classification))
1201
-			->where($query->expr()->eq('id', $query->createNamedParameter($calendarObjectId)))
1202
-			->execute();
1203
-	}
1204
-
1205
-	/**
1206
-	 * Deletes an existing calendar object.
1207
-	 *
1208
-	 * The object uri is only the basename, or filename and not a full path.
1209
-	 *
1210
-	 * @param mixed $calendarId
1211
-	 * @param string $objectUri
1212
-	 * @param int $calendarType
1213
-	 * @return void
1214
-	 */
1215
-	function deleteCalendarObject($calendarId, $objectUri, $calendarType=self::CALENDAR_TYPE_CALENDAR) {
1216
-		$data = $this->getCalendarObject($calendarId, $objectUri, $calendarType);
1217
-		if (is_array($data)) {
1218
-			if ($calendarType === self::CALENDAR_TYPE_CALENDAR) {
1219
-				$this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::deleteCalendarObject', new GenericEvent(
1220
-					'\OCA\DAV\CalDAV\CalDavBackend::deleteCalendarObject',
1221
-					[
1222
-						'calendarId' => $calendarId,
1223
-						'calendarData' => $this->getCalendarById($calendarId),
1224
-						'shares' => $this->getShares($calendarId),
1225
-						'objectData' => $data,
1226
-					]
1227
-				));
1228
-			} else {
1229
-				$this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::deleteCachedCalendarObject', new GenericEvent(
1230
-					'\OCA\DAV\CalDAV\CalDavBackend::deleteCachedCalendarObject',
1231
-					[
1232
-						'subscriptionId' => $calendarId,
1233
-						'calendarData' => $this->getCalendarById($calendarId),
1234
-						'shares' => $this->getShares($calendarId),
1235
-						'objectData' => $data,
1236
-					]
1237
-				));
1238
-			}
1239
-		}
1240
-
1241
-		$stmt = $this->db->prepare('DELETE FROM `*PREFIX*calendarobjects` WHERE `calendarid` = ? AND `uri` = ? AND `calendartype` = ?');
1242
-		$stmt->execute([$calendarId, $objectUri, $calendarType]);
1243
-
1244
-		if (is_array($data)) {
1245
-			$this->purgeProperties($calendarId, $data['id'], $calendarType);
1246
-		}
1247
-
1248
-		$this->addChange($calendarId, $objectUri, 3, $calendarType);
1249
-	}
1250
-
1251
-	/**
1252
-	 * Performs a calendar-query on the contents of this calendar.
1253
-	 *
1254
-	 * The calendar-query is defined in RFC4791 : CalDAV. Using the
1255
-	 * calendar-query it is possible for a client to request a specific set of
1256
-	 * object, based on contents of iCalendar properties, date-ranges and
1257
-	 * iCalendar component types (VTODO, VEVENT).
1258
-	 *
1259
-	 * This method should just return a list of (relative) urls that match this
1260
-	 * query.
1261
-	 *
1262
-	 * The list of filters are specified as an array. The exact array is
1263
-	 * documented by Sabre\CalDAV\CalendarQueryParser.
1264
-	 *
1265
-	 * Note that it is extremely likely that getCalendarObject for every path
1266
-	 * returned from this method will be called almost immediately after. You
1267
-	 * may want to anticipate this to speed up these requests.
1268
-	 *
1269
-	 * This method provides a default implementation, which parses *all* the
1270
-	 * iCalendar objects in the specified calendar.
1271
-	 *
1272
-	 * This default may well be good enough for personal use, and calendars
1273
-	 * that aren't very large. But if you anticipate high usage, big calendars
1274
-	 * or high loads, you are strongly advised to optimize certain paths.
1275
-	 *
1276
-	 * The best way to do so is override this method and to optimize
1277
-	 * specifically for 'common filters'.
1278
-	 *
1279
-	 * Requests that are extremely common are:
1280
-	 *   * requests for just VEVENTS
1281
-	 *   * requests for just VTODO
1282
-	 *   * requests with a time-range-filter on either VEVENT or VTODO.
1283
-	 *
1284
-	 * ..and combinations of these requests. It may not be worth it to try to
1285
-	 * handle every possible situation and just rely on the (relatively
1286
-	 * easy to use) CalendarQueryValidator to handle the rest.
1287
-	 *
1288
-	 * Note that especially time-range-filters may be difficult to parse. A
1289
-	 * time-range filter specified on a VEVENT must for instance also handle
1290
-	 * recurrence rules correctly.
1291
-	 * A good example of how to interprete all these filters can also simply
1292
-	 * be found in Sabre\CalDAV\CalendarQueryFilter. This class is as correct
1293
-	 * as possible, so it gives you a good idea on what type of stuff you need
1294
-	 * to think of.
1295
-	 *
1296
-	 * @param mixed $id
1297
-	 * @param array $filters
1298
-	 * @param int $calendarType
1299
-	 * @return array
1300
-	 */
1301
-	public function calendarQuery($id, array $filters, $calendarType=self::CALENDAR_TYPE_CALENDAR):array {
1302
-		$componentType = null;
1303
-		$requirePostFilter = true;
1304
-		$timeRange = null;
1305
-
1306
-		// if no filters were specified, we don't need to filter after a query
1307
-		if (!$filters['prop-filters'] && !$filters['comp-filters']) {
1308
-			$requirePostFilter = false;
1309
-		}
1310
-
1311
-		// Figuring out if there's a component filter
1312
-		if (count($filters['comp-filters']) > 0 && !$filters['comp-filters'][0]['is-not-defined']) {
1313
-			$componentType = $filters['comp-filters'][0]['name'];
1314
-
1315
-			// Checking if we need post-filters
1316
-			if (!$filters['prop-filters'] && !$filters['comp-filters'][0]['comp-filters'] && !$filters['comp-filters'][0]['time-range'] && !$filters['comp-filters'][0]['prop-filters']) {
1317
-				$requirePostFilter = false;
1318
-			}
1319
-			// There was a time-range filter
1320
-			if ($componentType === 'VEVENT' && isset($filters['comp-filters'][0]['time-range'])) {
1321
-				$timeRange = $filters['comp-filters'][0]['time-range'];
1322
-
1323
-				// If start time OR the end time is not specified, we can do a
1324
-				// 100% accurate mysql query.
1325
-				if (!$filters['prop-filters'] && !$filters['comp-filters'][0]['comp-filters'] && !$filters['comp-filters'][0]['prop-filters'] && (!$timeRange['start'] || !$timeRange['end'])) {
1326
-					$requirePostFilter = false;
1327
-				}
1328
-			}
1329
-
1330
-		}
1331
-		$columns = ['uri'];
1332
-		if ($requirePostFilter) {
1333
-			$columns = ['uri', 'calendardata'];
1334
-		}
1335
-		$query = $this->db->getQueryBuilder();
1336
-		$query->select($columns)
1337
-			->from('calendarobjects')
1338
-			->where($query->expr()->eq('calendarid', $query->createNamedParameter($id)))
1339
-			->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter($calendarType)));
1340
-
1341
-		if ($componentType) {
1342
-			$query->andWhere($query->expr()->eq('componenttype', $query->createNamedParameter($componentType)));
1343
-		}
1344
-
1345
-		if ($timeRange && $timeRange['start']) {
1346
-			$query->andWhere($query->expr()->gt('lastoccurence', $query->createNamedParameter($timeRange['start']->getTimeStamp())));
1347
-		}
1348
-		if ($timeRange && $timeRange['end']) {
1349
-			$query->andWhere($query->expr()->lt('firstoccurence', $query->createNamedParameter($timeRange['end']->getTimeStamp())));
1350
-		}
1351
-
1352
-		$stmt = $query->execute();
1353
-
1354
-		$result = [];
1355
-		while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1356
-			if ($requirePostFilter) {
1357
-				// validateFilterForObject will parse the calendar data
1358
-				// catch parsing errors
1359
-				try {
1360
-					$matches = $this->validateFilterForObject($row, $filters);
1361
-				} catch(ParseException $ex) {
1362
-					$this->logger->logException($ex, [
1363
-						'app' => 'dav',
1364
-						'message' => 'Caught parsing exception for calendar data. This usually indicates invalid calendar data. calendar-id:'.$id.' uri:'.$row['uri']
1365
-					]);
1366
-					continue;
1367
-				} catch (InvalidDataException $ex) {
1368
-					$this->logger->logException($ex, [
1369
-						'app' => 'dav',
1370
-						'message' => 'Caught invalid data exception for calendar data. This usually indicates invalid calendar data. calendar-id:'.$id.' uri:'.$row['uri']
1371
-					]);
1372
-					continue;
1373
-				}
1374
-
1375
-				if (!$matches) {
1376
-					continue;
1377
-				}
1378
-			}
1379
-			$result[] = $row['uri'];
1380
-		}
1381
-
1382
-		return $result;
1383
-	}
1384
-
1385
-	/**
1386
-	 * custom Nextcloud search extension for CalDAV
1387
-	 *
1388
-	 * TODO - this should optionally cover cached calendar objects as well
1389
-	 *
1390
-	 * @param string $principalUri
1391
-	 * @param array $filters
1392
-	 * @param integer|null $limit
1393
-	 * @param integer|null $offset
1394
-	 * @return array
1395
-	 */
1396
-	public function calendarSearch($principalUri, array $filters, $limit=null, $offset=null) {
1397
-		$calendars = $this->getCalendarsForUser($principalUri);
1398
-		$ownCalendars = [];
1399
-		$sharedCalendars = [];
1400
-
1401
-		$uriMapper = [];
1402
-
1403
-		foreach($calendars as $calendar) {
1404
-			if ($calendar['{http://owncloud.org/ns}owner-principal'] === $principalUri) {
1405
-				$ownCalendars[] = $calendar['id'];
1406
-			} else {
1407
-				$sharedCalendars[] = $calendar['id'];
1408
-			}
1409
-			$uriMapper[$calendar['id']] = $calendar['uri'];
1410
-		}
1411
-		if (count($ownCalendars) === 0 && count($sharedCalendars) === 0) {
1412
-			return [];
1413
-		}
1414
-
1415
-		$query = $this->db->getQueryBuilder();
1416
-		// Calendar id expressions
1417
-		$calendarExpressions = [];
1418
-		foreach($ownCalendars as $id) {
1419
-			$calendarExpressions[] = $query->expr()->andX(
1420
-				$query->expr()->eq('c.calendarid',
1421
-					$query->createNamedParameter($id)),
1422
-				$query->expr()->eq('c.calendartype',
1423
-						$query->createNamedParameter(self::CALENDAR_TYPE_CALENDAR)));
1424
-		}
1425
-		foreach($sharedCalendars as $id) {
1426
-			$calendarExpressions[] = $query->expr()->andX(
1427
-				$query->expr()->eq('c.calendarid',
1428
-					$query->createNamedParameter($id)),
1429
-				$query->expr()->eq('c.classification',
1430
-					$query->createNamedParameter(self::CLASSIFICATION_PUBLIC)),
1431
-				$query->expr()->eq('c.calendartype',
1432
-					$query->createNamedParameter(self::CALENDAR_TYPE_CALENDAR)));
1433
-		}
1434
-
1435
-		if (count($calendarExpressions) === 1) {
1436
-			$calExpr = $calendarExpressions[0];
1437
-		} else {
1438
-			$calExpr = call_user_func_array([$query->expr(), 'orX'], $calendarExpressions);
1439
-		}
1440
-
1441
-		// Component expressions
1442
-		$compExpressions = [];
1443
-		foreach($filters['comps'] as $comp) {
1444
-			$compExpressions[] = $query->expr()
1445
-				->eq('c.componenttype', $query->createNamedParameter($comp));
1446
-		}
1447
-
1448
-		if (count($compExpressions) === 1) {
1449
-			$compExpr = $compExpressions[0];
1450
-		} else {
1451
-			$compExpr = call_user_func_array([$query->expr(), 'orX'], $compExpressions);
1452
-		}
1453
-
1454
-		if (!isset($filters['props'])) {
1455
-			$filters['props'] = [];
1456
-		}
1457
-		if (!isset($filters['params'])) {
1458
-			$filters['params'] = [];
1459
-		}
1460
-
1461
-		$propParamExpressions = [];
1462
-		foreach($filters['props'] as $prop) {
1463
-			$propParamExpressions[] = $query->expr()->andX(
1464
-				$query->expr()->eq('i.name', $query->createNamedParameter($prop)),
1465
-				$query->expr()->isNull('i.parameter')
1466
-			);
1467
-		}
1468
-		foreach($filters['params'] as $param) {
1469
-			$propParamExpressions[] = $query->expr()->andX(
1470
-				$query->expr()->eq('i.name', $query->createNamedParameter($param['property'])),
1471
-				$query->expr()->eq('i.parameter', $query->createNamedParameter($param['parameter']))
1472
-			);
1473
-		}
1474
-
1475
-		if (count($propParamExpressions) === 1) {
1476
-			$propParamExpr = $propParamExpressions[0];
1477
-		} else {
1478
-			$propParamExpr = call_user_func_array([$query->expr(), 'orX'], $propParamExpressions);
1479
-		}
1480
-
1481
-		$query->select(['c.calendarid', 'c.uri'])
1482
-			->from($this->dbObjectPropertiesTable, 'i')
1483
-			->join('i', 'calendarobjects', 'c', $query->expr()->eq('i.objectid', 'c.id'))
1484
-			->where($calExpr)
1485
-			->andWhere($compExpr)
1486
-			->andWhere($propParamExpr)
1487
-			->andWhere($query->expr()->iLike('i.value',
1488
-				$query->createNamedParameter('%'.$this->db->escapeLikeParameter($filters['search-term']).'%')));
1489
-
1490
-		if ($offset) {
1491
-			$query->setFirstResult($offset);
1492
-		}
1493
-		if ($limit) {
1494
-			$query->setMaxResults($limit);
1495
-		}
1496
-
1497
-		$stmt = $query->execute();
1498
-
1499
-		$result = [];
1500
-		while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1501
-			$path = $uriMapper[$row['calendarid']] . '/' . $row['uri'];
1502
-			if (!in_array($path, $result)) {
1503
-				$result[] = $path;
1504
-			}
1505
-		}
1506
-
1507
-		return $result;
1508
-	}
1509
-
1510
-	/**
1511
-	 * used for Nextcloud's calendar API
1512
-	 *
1513
-	 * @param array $calendarInfo
1514
-	 * @param string $pattern
1515
-	 * @param array $searchProperties
1516
-	 * @param array $options
1517
-	 * @param integer|null $limit
1518
-	 * @param integer|null $offset
1519
-	 *
1520
-	 * @return array
1521
-	 */
1522
-	public function search(array $calendarInfo, $pattern, array $searchProperties,
1523
-						   array $options, $limit, $offset) {
1524
-		$outerQuery = $this->db->getQueryBuilder();
1525
-		$innerQuery = $this->db->getQueryBuilder();
1526
-
1527
-		$innerQuery->selectDistinct('op.objectid')
1528
-			->from($this->dbObjectPropertiesTable, 'op')
1529
-			->andWhere($innerQuery->expr()->eq('op.calendarid',
1530
-				$outerQuery->createNamedParameter($calendarInfo['id'])))
1531
-			->andWhere($innerQuery->expr()->eq('op.calendartype',
1532
-				$outerQuery->createNamedParameter(self::CALENDAR_TYPE_CALENDAR)));
1533
-
1534
-		// only return public items for shared calendars for now
1535
-		if ($calendarInfo['principaluri'] !== $calendarInfo['{http://owncloud.org/ns}owner-principal']) {
1536
-			$innerQuery->andWhere($innerQuery->expr()->eq('c.classification',
1537
-				$outerQuery->createNamedParameter(self::CLASSIFICATION_PUBLIC)));
1538
-		}
1539
-
1540
-		$or = $innerQuery->expr()->orX();
1541
-		foreach($searchProperties as $searchProperty) {
1542
-			$or->add($innerQuery->expr()->eq('op.name',
1543
-				$outerQuery->createNamedParameter($searchProperty)));
1544
-		}
1545
-		$innerQuery->andWhere($or);
1546
-
1547
-		if ($pattern !== '') {
1548
-			$innerQuery->andWhere($innerQuery->expr()->iLike('op.value',
1549
-				$outerQuery->createNamedParameter('%' .
1550
-					$this->db->escapeLikeParameter($pattern) . '%')));
1551
-		}
1552
-
1553
-		$outerQuery->select('c.id', 'c.calendardata', 'c.componenttype', 'c.uid', 'c.uri')
1554
-			->from('calendarobjects', 'c');
1555
-
1556
-		if (isset($options['timerange'])) {
1557
-			if (isset($options['timerange']['start']) && $options['timerange']['start'] instanceof DateTime) {
1558
-				$outerQuery->andWhere($outerQuery->expr()->gt('lastoccurence',
1559
-					$outerQuery->createNamedParameter($options['timerange']['start']->getTimeStamp())));
1560
-
1561
-			}
1562
-			if (isset($options['timerange']['end']) && $options['timerange']['end'] instanceof DateTime) {
1563
-				$outerQuery->andWhere($outerQuery->expr()->lt('firstoccurence',
1564
-					$outerQuery->createNamedParameter($options['timerange']['end']->getTimeStamp())));
1565
-			}
1566
-		}
1567
-
1568
-		if (isset($options['types'])) {
1569
-			$or = $outerQuery->expr()->orX();
1570
-			foreach($options['types'] as $type) {
1571
-				$or->add($outerQuery->expr()->eq('componenttype',
1572
-					$outerQuery->createNamedParameter($type)));
1573
-			}
1574
-			$outerQuery->andWhere($or);
1575
-		}
1576
-
1577
-		$outerQuery->andWhere($outerQuery->expr()->in('c.id',
1578
-			$outerQuery->createFunction($innerQuery->getSQL())));
1579
-
1580
-		if ($offset) {
1581
-			$outerQuery->setFirstResult($offset);
1582
-		}
1583
-		if ($limit) {
1584
-			$outerQuery->setMaxResults($limit);
1585
-		}
1586
-
1587
-		$result = $outerQuery->execute();
1588
-		$calendarObjects = $result->fetchAll();
1589
-
1590
-		return array_map(function ($o) {
1591
-			$calendarData = Reader::read($o['calendardata']);
1592
-			$comps = $calendarData->getComponents();
1593
-			$objects = [];
1594
-			$timezones = [];
1595
-			foreach($comps as $comp) {
1596
-				if ($comp instanceof VTimeZone) {
1597
-					$timezones[] = $comp;
1598
-				} else {
1599
-					$objects[] = $comp;
1600
-				}
1601
-			}
1602
-
1603
-			return [
1604
-				'id' => $o['id'],
1605
-				'type' => $o['componenttype'],
1606
-				'uid' => $o['uid'],
1607
-				'uri' => $o['uri'],
1608
-				'objects' => array_map(function ($c) {
1609
-					return $this->transformSearchData($c);
1610
-				}, $objects),
1611
-				'timezones' => array_map(function ($c) {
1612
-					return $this->transformSearchData($c);
1613
-				}, $timezones),
1614
-			];
1615
-		}, $calendarObjects);
1616
-	}
1617
-
1618
-	/**
1619
-	 * @param Component $comp
1620
-	 * @return array
1621
-	 */
1622
-	private function transformSearchData(Component $comp) {
1623
-		$data = [];
1624
-		/** @var Component[] $subComponents */
1625
-		$subComponents = $comp->getComponents();
1626
-		/** @var Property[] $properties */
1627
-		$properties = array_filter($comp->children(), function ($c) {
1628
-			return $c instanceof Property;
1629
-		});
1630
-		$validationRules = $comp->getValidationRules();
1631
-
1632
-		foreach($subComponents as $subComponent) {
1633
-			$name = $subComponent->name;
1634
-			if (!isset($data[$name])) {
1635
-				$data[$name] = [];
1636
-			}
1637
-			$data[$name][] = $this->transformSearchData($subComponent);
1638
-		}
1639
-
1640
-		foreach($properties as $property) {
1641
-			$name = $property->name;
1642
-			if (!isset($validationRules[$name])) {
1643
-				$validationRules[$name] = '*';
1644
-			}
1645
-
1646
-			$rule = $validationRules[$property->name];
1647
-			if ($rule === '+' || $rule === '*') { // multiple
1648
-				if (!isset($data[$name])) {
1649
-					$data[$name] = [];
1650
-				}
1651
-
1652
-				$data[$name][] = $this->transformSearchProperty($property);
1653
-			} else { // once
1654
-				$data[$name] = $this->transformSearchProperty($property);
1655
-			}
1656
-		}
1657
-
1658
-		return $data;
1659
-	}
1660
-
1661
-	/**
1662
-	 * @param Property $prop
1663
-	 * @return array
1664
-	 */
1665
-	private function transformSearchProperty(Property $prop) {
1666
-		// No need to check Date, as it extends DateTime
1667
-		if ($prop instanceof Property\ICalendar\DateTime) {
1668
-			$value = $prop->getDateTime();
1669
-		} else {
1670
-			$value = $prop->getValue();
1671
-		}
1672
-
1673
-		return [
1674
-			$value,
1675
-			$prop->parameters()
1676
-		];
1677
-	}
1678
-
1679
-	/**
1680
-	 * Searches through all of a users calendars and calendar objects to find
1681
-	 * an object with a specific UID.
1682
-	 *
1683
-	 * This method should return the path to this object, relative to the
1684
-	 * calendar home, so this path usually only contains two parts:
1685
-	 *
1686
-	 * calendarpath/objectpath.ics
1687
-	 *
1688
-	 * If the uid is not found, return null.
1689
-	 *
1690
-	 * This method should only consider * objects that the principal owns, so
1691
-	 * any calendars owned by other principals that also appear in this
1692
-	 * collection should be ignored.
1693
-	 *
1694
-	 * @param string $principalUri
1695
-	 * @param string $uid
1696
-	 * @return string|null
1697
-	 */
1698
-	function getCalendarObjectByUID($principalUri, $uid) {
1699
-
1700
-		$query = $this->db->getQueryBuilder();
1701
-		$query->selectAlias('c.uri', 'calendaruri')->selectAlias('co.uri', 'objecturi')
1702
-			->from('calendarobjects', 'co')
1703
-			->leftJoin('co', 'calendars', 'c', $query->expr()->eq('co.calendarid', 'c.id'))
1704
-			->where($query->expr()->eq('c.principaluri', $query->createNamedParameter($principalUri)))
1705
-			->andWhere($query->expr()->eq('co.uid', $query->createNamedParameter($uid)))
1706
-			->andWhere($query->expr()->eq('co.uid', $query->createNamedParameter($uid)));
1707
-
1708
-		$stmt = $query->execute();
1709
-
1710
-		if ($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1711
-			return $row['calendaruri'] . '/' . $row['objecturi'];
1712
-		}
1713
-
1714
-		return null;
1715
-	}
1716
-
1717
-	/**
1718
-	 * The getChanges method returns all the changes that have happened, since
1719
-	 * the specified syncToken in the specified calendar.
1720
-	 *
1721
-	 * This function should return an array, such as the following:
1722
-	 *
1723
-	 * [
1724
-	 *   'syncToken' => 'The current synctoken',
1725
-	 *   'added'   => [
1726
-	 *      'new.txt',
1727
-	 *   ],
1728
-	 *   'modified'   => [
1729
-	 *      'modified.txt',
1730
-	 *   ],
1731
-	 *   'deleted' => [
1732
-	 *      'foo.php.bak',
1733
-	 *      'old.txt'
1734
-	 *   ]
1735
-	 * );
1736
-	 *
1737
-	 * The returned syncToken property should reflect the *current* syncToken
1738
-	 * of the calendar, as reported in the {http://sabredav.org/ns}sync-token
1739
-	 * property This is * needed here too, to ensure the operation is atomic.
1740
-	 *
1741
-	 * If the $syncToken argument is specified as null, this is an initial
1742
-	 * sync, and all members should be reported.
1743
-	 *
1744
-	 * The modified property is an array of nodenames that have changed since
1745
-	 * the last token.
1746
-	 *
1747
-	 * The deleted property is an array with nodenames, that have been deleted
1748
-	 * from collection.
1749
-	 *
1750
-	 * The $syncLevel argument is basically the 'depth' of the report. If it's
1751
-	 * 1, you only have to report changes that happened only directly in
1752
-	 * immediate descendants. If it's 2, it should also include changes from
1753
-	 * the nodes below the child collections. (grandchildren)
1754
-	 *
1755
-	 * The $limit argument allows a client to specify how many results should
1756
-	 * be returned at most. If the limit is not specified, it should be treated
1757
-	 * as infinite.
1758
-	 *
1759
-	 * If the limit (infinite or not) is higher than you're willing to return,
1760
-	 * you should throw a Sabre\DAV\Exception\TooMuchMatches() exception.
1761
-	 *
1762
-	 * If the syncToken is expired (due to data cleanup) or unknown, you must
1763
-	 * return null.
1764
-	 *
1765
-	 * The limit is 'suggestive'. You are free to ignore it.
1766
-	 *
1767
-	 * @param string $calendarId
1768
-	 * @param string $syncToken
1769
-	 * @param int $syncLevel
1770
-	 * @param int $limit
1771
-	 * @param int $calendarType
1772
-	 * @return array
1773
-	 */
1774
-	function getChangesForCalendar($calendarId, $syncToken, $syncLevel, $limit = null, $calendarType=self::CALENDAR_TYPE_CALENDAR) {
1775
-		// Current synctoken
1776
-		$stmt = $this->db->prepare('SELECT `synctoken` FROM `*PREFIX*calendars` WHERE `id` = ?');
1777
-		$stmt->execute([ $calendarId ]);
1778
-		$currentToken = $stmt->fetchColumn(0);
1779
-
1780
-		if (is_null($currentToken)) {
1781
-			return null;
1782
-		}
1783
-
1784
-		$result = [
1785
-			'syncToken' => $currentToken,
1786
-			'added'     => [],
1787
-			'modified'  => [],
1788
-			'deleted'   => [],
1789
-		];
1790
-
1791
-		if ($syncToken) {
1792
-
1793
-			$query = "SELECT `uri`, `operation` FROM `*PREFIX*calendarchanges` WHERE `synctoken` >= ? AND `synctoken` < ? AND `calendarid` = ? AND `calendartype` = ? ORDER BY `synctoken`";
1794
-			if ($limit>0) {
1795
-				$query.= " LIMIT " . (int)$limit;
1796
-			}
1797
-
1798
-			// Fetching all changes
1799
-			$stmt = $this->db->prepare($query);
1800
-			$stmt->execute([$syncToken, $currentToken, $calendarId, $calendarType]);
1801
-
1802
-			$changes = [];
1803
-
1804
-			// This loop ensures that any duplicates are overwritten, only the
1805
-			// last change on a node is relevant.
1806
-			while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1807
-
1808
-				$changes[$row['uri']] = $row['operation'];
1809
-
1810
-			}
1811
-
1812
-			foreach($changes as $uri => $operation) {
1813
-
1814
-				switch($operation) {
1815
-					case 1 :
1816
-						$result['added'][] = $uri;
1817
-						break;
1818
-					case 2 :
1819
-						$result['modified'][] = $uri;
1820
-						break;
1821
-					case 3 :
1822
-						$result['deleted'][] = $uri;
1823
-						break;
1824
-				}
1825
-
1826
-			}
1827
-		} else {
1828
-			// No synctoken supplied, this is the initial sync.
1829
-			$query = "SELECT `uri` FROM `*PREFIX*calendarobjects` WHERE `calendarid` = ? AND `calendartype` = ?";
1830
-			$stmt = $this->db->prepare($query);
1831
-			$stmt->execute([$calendarId, $calendarType]);
1832
-
1833
-			$result['added'] = $stmt->fetchAll(\PDO::FETCH_COLUMN);
1834
-		}
1835
-		return $result;
1836
-
1837
-	}
1838
-
1839
-	/**
1840
-	 * Returns a list of subscriptions for a principal.
1841
-	 *
1842
-	 * Every subscription is an array with the following keys:
1843
-	 *  * id, a unique id that will be used by other functions to modify the
1844
-	 *    subscription. This can be the same as the uri or a database key.
1845
-	 *  * uri. This is just the 'base uri' or 'filename' of the subscription.
1846
-	 *  * principaluri. The owner of the subscription. Almost always the same as
1847
-	 *    principalUri passed to this method.
1848
-	 *
1849
-	 * Furthermore, all the subscription info must be returned too:
1850
-	 *
1851
-	 * 1. {DAV:}displayname
1852
-	 * 2. {http://apple.com/ns/ical/}refreshrate
1853
-	 * 3. {http://calendarserver.org/ns/}subscribed-strip-todos (omit if todos
1854
-	 *    should not be stripped).
1855
-	 * 4. {http://calendarserver.org/ns/}subscribed-strip-alarms (omit if alarms
1856
-	 *    should not be stripped).
1857
-	 * 5. {http://calendarserver.org/ns/}subscribed-strip-attachments (omit if
1858
-	 *    attachments should not be stripped).
1859
-	 * 6. {http://calendarserver.org/ns/}source (Must be a
1860
-	 *     Sabre\DAV\Property\Href).
1861
-	 * 7. {http://apple.com/ns/ical/}calendar-color
1862
-	 * 8. {http://apple.com/ns/ical/}calendar-order
1863
-	 * 9. {urn:ietf:params:xml:ns:caldav}supported-calendar-component-set
1864
-	 *    (should just be an instance of
1865
-	 *    Sabre\CalDAV\Property\SupportedCalendarComponentSet, with a bunch of
1866
-	 *    default components).
1867
-	 *
1868
-	 * @param string $principalUri
1869
-	 * @return array
1870
-	 */
1871
-	function getSubscriptionsForUser($principalUri) {
1872
-		$fields = array_values($this->subscriptionPropertyMap);
1873
-		$fields[] = 'id';
1874
-		$fields[] = 'uri';
1875
-		$fields[] = 'source';
1876
-		$fields[] = 'principaluri';
1877
-		$fields[] = 'lastmodified';
1878
-		$fields[] = 'synctoken';
1879
-
1880
-		$query = $this->db->getQueryBuilder();
1881
-		$query->select($fields)
1882
-			->from('calendarsubscriptions')
1883
-			->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
1884
-			->orderBy('calendarorder', 'asc');
1885
-		$stmt =$query->execute();
1886
-
1887
-		$subscriptions = [];
1888
-		while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1889
-
1890
-			$subscription = [
1891
-				'id'           => $row['id'],
1892
-				'uri'          => $row['uri'],
1893
-				'principaluri' => $row['principaluri'],
1894
-				'source'       => $row['source'],
1895
-				'lastmodified' => $row['lastmodified'],
1896
-
1897
-				'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet(['VTODO', 'VEVENT']),
1898
-				'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
1899
-			];
1900
-
1901
-			foreach($this->subscriptionPropertyMap as $xmlName=>$dbName) {
1902
-				if (!is_null($row[$dbName])) {
1903
-					$subscription[$xmlName] = $row[$dbName];
1904
-				}
1905
-			}
1906
-
1907
-			$subscriptions[] = $subscription;
1908
-
1909
-		}
1910
-
1911
-		return $subscriptions;
1912
-	}
1913
-
1914
-	/**
1915
-	 * Creates a new subscription for a principal.
1916
-	 *
1917
-	 * If the creation was a success, an id must be returned that can be used to reference
1918
-	 * this subscription in other methods, such as updateSubscription.
1919
-	 *
1920
-	 * @param string $principalUri
1921
-	 * @param string $uri
1922
-	 * @param array $properties
1923
-	 * @return mixed
1924
-	 */
1925
-	function createSubscription($principalUri, $uri, array $properties) {
1926
-
1927
-		if (!isset($properties['{http://calendarserver.org/ns/}source'])) {
1928
-			throw new Forbidden('The {http://calendarserver.org/ns/}source property is required when creating subscriptions');
1929
-		}
1930
-
1931
-		$values = [
1932
-			'principaluri' => $principalUri,
1933
-			'uri'          => $uri,
1934
-			'source'       => $properties['{http://calendarserver.org/ns/}source']->getHref(),
1935
-			'lastmodified' => time(),
1936
-		];
1937
-
1938
-		$propertiesBoolean = ['striptodos', 'stripalarms', 'stripattachments'];
1939
-
1940
-		foreach($this->subscriptionPropertyMap as $xmlName=>$dbName) {
1941
-			if (array_key_exists($xmlName, $properties)) {
1942
-					$values[$dbName] = $properties[$xmlName];
1943
-					if (in_array($dbName, $propertiesBoolean)) {
1944
-						$values[$dbName] = true;
1945
-				}
1946
-			}
1947
-		}
1948
-
1949
-		$valuesToInsert = [];
1950
-
1951
-		$query = $this->db->getQueryBuilder();
1952
-
1953
-		foreach (array_keys($values) as $name) {
1954
-			$valuesToInsert[$name] = $query->createNamedParameter($values[$name]);
1955
-		}
1956
-
1957
-		$query->insert('calendarsubscriptions')
1958
-			->values($valuesToInsert)
1959
-			->execute();
1960
-
1961
-		$subscriptionId = $this->db->lastInsertId('*PREFIX*calendarsubscriptions');
1962
-
1963
-		$this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::createSubscription', new GenericEvent(
1964
-			'\OCA\DAV\CalDAV\CalDavBackend::createSubscription',
1965
-			[
1966
-				'subscriptionId' => $subscriptionId,
1967
-				'subscriptionData' => $this->getSubscriptionById($subscriptionId),
1968
-			]));
1969
-
1970
-		return $subscriptionId;
1971
-	}
1972
-
1973
-	/**
1974
-	 * Updates a subscription
1975
-	 *
1976
-	 * The list of mutations is stored in a Sabre\DAV\PropPatch object.
1977
-	 * To do the actual updates, you must tell this object which properties
1978
-	 * you're going to process with the handle() method.
1979
-	 *
1980
-	 * Calling the handle method is like telling the PropPatch object "I
1981
-	 * promise I can handle updating this property".
1982
-	 *
1983
-	 * Read the PropPatch documentation for more info and examples.
1984
-	 *
1985
-	 * @param mixed $subscriptionId
1986
-	 * @param PropPatch $propPatch
1987
-	 * @return void
1988
-	 */
1989
-	function updateSubscription($subscriptionId, PropPatch $propPatch) {
1990
-		$supportedProperties = array_keys($this->subscriptionPropertyMap);
1991
-		$supportedProperties[] = '{http://calendarserver.org/ns/}source';
1992
-
1993
-		/**
1994
-		 * @suppress SqlInjectionChecker
1995
-		 */
1996
-		$propPatch->handle($supportedProperties, function ($mutations) use ($subscriptionId) {
1997
-
1998
-			$newValues = [];
1999
-
2000
-			foreach($mutations as $propertyName=>$propertyValue) {
2001
-				if ($propertyName === '{http://calendarserver.org/ns/}source') {
2002
-					$newValues['source'] = $propertyValue->getHref();
2003
-				} else {
2004
-					$fieldName = $this->subscriptionPropertyMap[$propertyName];
2005
-					$newValues[$fieldName] = $propertyValue;
2006
-				}
2007
-			}
2008
-
2009
-			$query = $this->db->getQueryBuilder();
2010
-			$query->update('calendarsubscriptions')
2011
-				->set('lastmodified', $query->createNamedParameter(time()));
2012
-			foreach($newValues as $fieldName=>$value) {
2013
-				$query->set($fieldName, $query->createNamedParameter($value));
2014
-			}
2015
-			$query->where($query->expr()->eq('id', $query->createNamedParameter($subscriptionId)))
2016
-				->execute();
2017
-
2018
-			$this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::updateSubscription', new GenericEvent(
2019
-				'\OCA\DAV\CalDAV\CalDavBackend::updateSubscription',
2020
-				[
2021
-					'subscriptionId' => $subscriptionId,
2022
-					'subscriptionData' => $this->getSubscriptionById($subscriptionId),
2023
-					'propertyMutations' => $mutations,
2024
-				]));
2025
-
2026
-			return true;
2027
-
2028
-		});
2029
-	}
2030
-
2031
-	/**
2032
-	 * Deletes a subscription.
2033
-	 *
2034
-	 * @param mixed $subscriptionId
2035
-	 * @return void
2036
-	 */
2037
-	function deleteSubscription($subscriptionId) {
2038
-		$this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::deleteSubscription', new GenericEvent(
2039
-			'\OCA\DAV\CalDAV\CalDavBackend::deleteSubscription',
2040
-			[
2041
-				'subscriptionId' => $subscriptionId,
2042
-				'subscriptionData' => $this->getSubscriptionById($subscriptionId),
2043
-			]));
2044
-
2045
-		$query = $this->db->getQueryBuilder();
2046
-		$query->delete('calendarsubscriptions')
2047
-			->where($query->expr()->eq('id', $query->createNamedParameter($subscriptionId)))
2048
-			->execute();
2049
-
2050
-		$query = $this->db->getQueryBuilder();
2051
-		$query->delete('calendarobjects')
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('calendarchanges')
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
-		$query->delete($this->dbObjectPropertiesTable)
2062
-			->where($query->expr()->eq('calendarid', $query->createNamedParameter($subscriptionId)))
2063
-			->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)))
2064
-			->execute();
2065
-	}
2066
-
2067
-	/**
2068
-	 * Returns a single scheduling object for the inbox collection.
2069
-	 *
2070
-	 * The returned array should contain the following elements:
2071
-	 *   * uri - A unique basename for the object. This will be used to
2072
-	 *           construct a full uri.
2073
-	 *   * calendardata - The iCalendar object
2074
-	 *   * lastmodified - The last modification date. Can be an int for a unix
2075
-	 *                    timestamp, or a PHP DateTime object.
2076
-	 *   * etag - A unique token that must change if the object changed.
2077
-	 *   * size - The size of the object, in bytes.
2078
-	 *
2079
-	 * @param string $principalUri
2080
-	 * @param string $objectUri
2081
-	 * @return array
2082
-	 */
2083
-	function getSchedulingObject($principalUri, $objectUri) {
2084
-		$query = $this->db->getQueryBuilder();
2085
-		$stmt = $query->select(['uri', 'calendardata', 'lastmodified', 'etag', 'size'])
2086
-			->from('schedulingobjects')
2087
-			->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
2088
-			->andWhere($query->expr()->eq('uri', $query->createNamedParameter($objectUri)))
2089
-			->execute();
2090
-
2091
-		$row = $stmt->fetch(\PDO::FETCH_ASSOC);
2092
-
2093
-		if(!$row) {
2094
-			return null;
2095
-		}
2096
-
2097
-		return [
2098
-			'uri'          => $row['uri'],
2099
-			'calendardata' => $row['calendardata'],
2100
-			'lastmodified' => $row['lastmodified'],
2101
-			'etag'         => '"' . $row['etag'] . '"',
2102
-			'size'         => (int)$row['size'],
2103
-		];
2104
-	}
2105
-
2106
-	/**
2107
-	 * Returns all scheduling objects for the inbox collection.
2108
-	 *
2109
-	 * These objects should be returned as an array. Every item in the array
2110
-	 * should follow the same structure as returned from getSchedulingObject.
2111
-	 *
2112
-	 * The main difference is that 'calendardata' is optional.
2113
-	 *
2114
-	 * @param string $principalUri
2115
-	 * @return array
2116
-	 */
2117
-	function getSchedulingObjects($principalUri) {
2118
-		$query = $this->db->getQueryBuilder();
2119
-		$stmt = $query->select(['uri', 'calendardata', 'lastmodified', 'etag', 'size'])
2120
-				->from('schedulingobjects')
2121
-				->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
2122
-				->execute();
2123
-
2124
-		$result = [];
2125
-		foreach($stmt->fetchAll(\PDO::FETCH_ASSOC) as $row) {
2126
-			$result[] = [
2127
-				'calendardata' => $row['calendardata'],
2128
-				'uri'          => $row['uri'],
2129
-				'lastmodified' => $row['lastmodified'],
2130
-				'etag'         => '"' . $row['etag'] . '"',
2131
-				'size'         => (int)$row['size'],
2132
-			];
2133
-		}
2134
-
2135
-		return $result;
2136
-	}
2137
-
2138
-	/**
2139
-	 * Deletes a scheduling object from the inbox collection.
2140
-	 *
2141
-	 * @param string $principalUri
2142
-	 * @param string $objectUri
2143
-	 * @return void
2144
-	 */
2145
-	function deleteSchedulingObject($principalUri, $objectUri) {
2146
-		$query = $this->db->getQueryBuilder();
2147
-		$query->delete('schedulingobjects')
2148
-				->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
2149
-				->andWhere($query->expr()->eq('uri', $query->createNamedParameter($objectUri)))
2150
-				->execute();
2151
-	}
2152
-
2153
-	/**
2154
-	 * Creates a new scheduling object. This should land in a users' inbox.
2155
-	 *
2156
-	 * @param string $principalUri
2157
-	 * @param string $objectUri
2158
-	 * @param string $objectData
2159
-	 * @return void
2160
-	 */
2161
-	function createSchedulingObject($principalUri, $objectUri, $objectData) {
2162
-		$query = $this->db->getQueryBuilder();
2163
-		$query->insert('schedulingobjects')
2164
-			->values([
2165
-				'principaluri' => $query->createNamedParameter($principalUri),
2166
-				'calendardata' => $query->createNamedParameter($objectData, IQueryBuilder::PARAM_LOB),
2167
-				'uri' => $query->createNamedParameter($objectUri),
2168
-				'lastmodified' => $query->createNamedParameter(time()),
2169
-				'etag' => $query->createNamedParameter(md5($objectData)),
2170
-				'size' => $query->createNamedParameter(strlen($objectData))
2171
-			])
2172
-			->execute();
2173
-	}
2174
-
2175
-	/**
2176
-	 * Adds a change record to the calendarchanges table.
2177
-	 *
2178
-	 * @param mixed $calendarId
2179
-	 * @param string $objectUri
2180
-	 * @param int $operation 1 = add, 2 = modify, 3 = delete.
2181
-	 * @param int $calendarType
2182
-	 * @return void
2183
-	 */
2184
-	protected function addChange($calendarId, $objectUri, $operation, $calendarType=self::CALENDAR_TYPE_CALENDAR) {
2185
-		$table = $calendarType === self::CALENDAR_TYPE_CALENDAR ? 'calendars': 'calendarsubscriptions';
2186
-
2187
-		$query = $this->db->getQueryBuilder();
2188
-		$query->select('synctoken')
2189
-			->from($table)
2190
-			->where($query->expr()->eq('id', $query->createNamedParameter($calendarId)));
2191
-		$syncToken = (int)$query->execute()->fetchColumn();
2192
-
2193
-		$query = $this->db->getQueryBuilder();
2194
-		$query->insert('calendarchanges')
2195
-			->values([
2196
-				'uri' => $query->createNamedParameter($objectUri),
2197
-				'synctoken' => $query->createNamedParameter($syncToken),
2198
-				'calendarid' => $query->createNamedParameter($calendarId),
2199
-				'operation' => $query->createNamedParameter($operation),
2200
-				'calendartype' => $query->createNamedParameter($calendarType),
2201
-			])
2202
-			->execute();
2203
-
2204
-		$stmt = $this->db->prepare("UPDATE `*PREFIX*$table` SET `synctoken` = `synctoken` + 1 WHERE `id` = ?");
2205
-		$stmt->execute([
2206
-			$calendarId
2207
-		]);
2208
-
2209
-	}
2210
-
2211
-	/**
2212
-	 * Parses some information from calendar objects, used for optimized
2213
-	 * calendar-queries.
2214
-	 *
2215
-	 * Returns an array with the following keys:
2216
-	 *   * etag - An md5 checksum of the object without the quotes.
2217
-	 *   * size - Size of the object in bytes
2218
-	 *   * componentType - VEVENT, VTODO or VJOURNAL
2219
-	 *   * firstOccurence
2220
-	 *   * lastOccurence
2221
-	 *   * uid - value of the UID property
2222
-	 *
2223
-	 * @param string $calendarData
2224
-	 * @return array
2225
-	 */
2226
-	public function getDenormalizedData($calendarData) {
2227
-
2228
-		$vObject = Reader::read($calendarData);
2229
-		$componentType = null;
2230
-		$component = null;
2231
-		$firstOccurrence = null;
2232
-		$lastOccurrence = null;
2233
-		$uid = null;
2234
-		$classification = self::CLASSIFICATION_PUBLIC;
2235
-		foreach($vObject->getComponents() as $component) {
2236
-			if ($component->name!=='VTIMEZONE') {
2237
-				$componentType = $component->name;
2238
-				$uid = (string)$component->UID;
2239
-				break;
2240
-			}
2241
-		}
2242
-		if (!$componentType) {
2243
-			throw new \Sabre\DAV\Exception\BadRequest('Calendar objects must have a VJOURNAL, VEVENT or VTODO component');
2244
-		}
2245
-		if ($componentType === 'VEVENT' && $component->DTSTART) {
2246
-			$firstOccurrence = $component->DTSTART->getDateTime()->getTimeStamp();
2247
-			// Finding the last occurrence is a bit harder
2248
-			if (!isset($component->RRULE)) {
2249
-				if (isset($component->DTEND)) {
2250
-					$lastOccurrence = $component->DTEND->getDateTime()->getTimeStamp();
2251
-				} elseif (isset($component->DURATION)) {
2252
-					$endDate = clone $component->DTSTART->getDateTime();
2253
-					$endDate->add(DateTimeParser::parse($component->DURATION->getValue()));
2254
-					$lastOccurrence = $endDate->getTimeStamp();
2255
-				} elseif (!$component->DTSTART->hasTime()) {
2256
-					$endDate = clone $component->DTSTART->getDateTime();
2257
-					$endDate->modify('+1 day');
2258
-					$lastOccurrence = $endDate->getTimeStamp();
2259
-				} else {
2260
-					$lastOccurrence = $firstOccurrence;
2261
-				}
2262
-			} else {
2263
-				$it = new EventIterator($vObject, (string)$component->UID);
2264
-				$maxDate = new DateTime(self::MAX_DATE);
2265
-				if ($it->isInfinite()) {
2266
-					$lastOccurrence = $maxDate->getTimestamp();
2267
-				} else {
2268
-					$end = $it->getDtEnd();
2269
-					while($it->valid() && $end < $maxDate) {
2270
-						$end = $it->getDtEnd();
2271
-						$it->next();
2272
-
2273
-					}
2274
-					$lastOccurrence = $end->getTimestamp();
2275
-				}
2276
-
2277
-			}
2278
-		}
2279
-
2280
-		if ($component->CLASS) {
2281
-			$classification = CalDavBackend::CLASSIFICATION_PRIVATE;
2282
-			switch ($component->CLASS->getValue()) {
2283
-				case 'PUBLIC':
2284
-					$classification = CalDavBackend::CLASSIFICATION_PUBLIC;
2285
-					break;
2286
-				case 'CONFIDENTIAL':
2287
-					$classification = CalDavBackend::CLASSIFICATION_CONFIDENTIAL;
2288
-					break;
2289
-			}
2290
-		}
2291
-		return [
2292
-			'etag' => md5($calendarData),
2293
-			'size' => strlen($calendarData),
2294
-			'componentType' => $componentType,
2295
-			'firstOccurence' => is_null($firstOccurrence) ? null : max(0, $firstOccurrence),
2296
-			'lastOccurence'  => $lastOccurrence,
2297
-			'uid' => $uid,
2298
-			'classification' => $classification
2299
-		];
2300
-
2301
-	}
2302
-
2303
-	/**
2304
-	 * @param $cardData
2305
-	 * @return bool|string
2306
-	 */
2307
-	private function readBlob($cardData) {
2308
-		if (is_resource($cardData)) {
2309
-			return stream_get_contents($cardData);
2310
-		}
2311
-
2312
-		return $cardData;
2313
-	}
2314
-
2315
-	/**
2316
-	 * @param IShareable $shareable
2317
-	 * @param array $add
2318
-	 * @param array $remove
2319
-	 */
2320
-	public function updateShares($shareable, $add, $remove) {
2321
-		$calendarId = $shareable->getResourceId();
2322
-		$this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::updateShares', new GenericEvent(
2323
-			'\OCA\DAV\CalDAV\CalDavBackend::updateShares',
2324
-			[
2325
-				'calendarId' => $calendarId,
2326
-				'calendarData' => $this->getCalendarById($calendarId),
2327
-				'shares' => $this->getShares($calendarId),
2328
-				'add' => $add,
2329
-				'remove' => $remove,
2330
-			]));
2331
-		$this->calendarSharingBackend->updateShares($shareable, $add, $remove);
2332
-	}
2333
-
2334
-	/**
2335
-	 * @param int $resourceId
2336
-	 * @param int $calendarType
2337
-	 * @return array
2338
-	 */
2339
-	public function getShares($resourceId, $calendarType=self::CALENDAR_TYPE_CALENDAR) {
2340
-		return $this->calendarSharingBackend->getShares($resourceId);
2341
-	}
2342
-
2343
-	/**
2344
-	 * @param boolean $value
2345
-	 * @param \OCA\DAV\CalDAV\Calendar $calendar
2346
-	 * @return string|null
2347
-	 */
2348
-	public function setPublishStatus($value, $calendar) {
2349
-
2350
-		$calendarId = $calendar->getResourceId();
2351
-		$this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::publishCalendar', new GenericEvent(
2352
-			'\OCA\DAV\CalDAV\CalDavBackend::updateShares',
2353
-			[
2354
-				'calendarId' => $calendarId,
2355
-				'calendarData' => $this->getCalendarById($calendarId),
2356
-				'public' => $value,
2357
-			]));
2358
-
2359
-		$query = $this->db->getQueryBuilder();
2360
-		if ($value) {
2361
-			$publicUri = $this->random->generate(16, ISecureRandom::CHAR_HUMAN_READABLE);
2362
-			$query->insert('dav_shares')
2363
-				->values([
2364
-					'principaluri' => $query->createNamedParameter($calendar->getPrincipalURI()),
2365
-					'type' => $query->createNamedParameter('calendar'),
2366
-					'access' => $query->createNamedParameter(self::ACCESS_PUBLIC),
2367
-					'resourceid' => $query->createNamedParameter($calendar->getResourceId()),
2368
-					'publicuri' => $query->createNamedParameter($publicUri)
2369
-				]);
2370
-			$query->execute();
2371
-			return $publicUri;
2372
-		}
2373
-		$query->delete('dav_shares')
2374
-			->where($query->expr()->eq('resourceid', $query->createNamedParameter($calendar->getResourceId())))
2375
-			->andWhere($query->expr()->eq('access', $query->createNamedParameter(self::ACCESS_PUBLIC)));
2376
-		$query->execute();
2377
-		return null;
2378
-	}
2379
-
2380
-	/**
2381
-	 * @param \OCA\DAV\CalDAV\Calendar $calendar
2382
-	 * @return mixed
2383
-	 */
2384
-	public function getPublishStatus($calendar) {
2385
-		$query = $this->db->getQueryBuilder();
2386
-		$result = $query->select('publicuri')
2387
-			->from('dav_shares')
2388
-			->where($query->expr()->eq('resourceid', $query->createNamedParameter($calendar->getResourceId())))
2389
-			->andWhere($query->expr()->eq('access', $query->createNamedParameter(self::ACCESS_PUBLIC)))
2390
-			->execute();
2391
-
2392
-		$row = $result->fetch();
2393
-		$result->closeCursor();
2394
-		return $row ? reset($row) : false;
2395
-	}
2396
-
2397
-	/**
2398
-	 * @param int $resourceId
2399
-	 * @param array $acl
2400
-	 * @return array
2401
-	 */
2402
-	public function applyShareAcl($resourceId, $acl) {
2403
-		return $this->calendarSharingBackend->applyShareAcl($resourceId, $acl);
2404
-	}
2405
-
2406
-
2407
-
2408
-	/**
2409
-	 * update properties table
2410
-	 *
2411
-	 * @param int $calendarId
2412
-	 * @param string $objectUri
2413
-	 * @param string $calendarData
2414
-	 * @param int $calendarType
2415
-	 */
2416
-	public function updateProperties($calendarId, $objectUri, $calendarData, $calendarType=self::CALENDAR_TYPE_CALENDAR) {
2417
-		$objectId = $this->getCalendarObjectId($calendarId, $objectUri, $calendarType);
2418
-
2419
-		try {
2420
-			$vCalendar = $this->readCalendarData($calendarData);
2421
-		} catch (\Exception $ex) {
2422
-			return;
2423
-		}
2424
-
2425
-		$this->purgeProperties($calendarId, $objectId);
2426
-
2427
-		$query = $this->db->getQueryBuilder();
2428
-		$query->insert($this->dbObjectPropertiesTable)
2429
-			->values(
2430
-				[
2431
-					'calendarid' => $query->createNamedParameter($calendarId),
2432
-					'calendartype' => $query->createNamedParameter($calendarType),
2433
-					'objectid' => $query->createNamedParameter($objectId),
2434
-					'name' => $query->createParameter('name'),
2435
-					'parameter' => $query->createParameter('parameter'),
2436
-					'value' => $query->createParameter('value'),
2437
-				]
2438
-			);
2439
-
2440
-		$indexComponents = ['VEVENT', 'VJOURNAL', 'VTODO'];
2441
-		foreach ($vCalendar->getComponents() as $component) {
2442
-			if (!in_array($component->name, $indexComponents)) {
2443
-				continue;
2444
-			}
2445
-
2446
-			foreach ($component->children() as $property) {
2447
-				if (in_array($property->name, self::$indexProperties)) {
2448
-					$value = $property->getValue();
2449
-					// is this a shitty db?
2450
-					if (!$this->db->supports4ByteText()) {
2451
-						$value = preg_replace('/[\x{10000}-\x{10FFFF}]/u', "\xEF\xBF\xBD", $value);
2452
-					}
2453
-					$value = mb_substr($value, 0, 254);
2454
-
2455
-					$query->setParameter('name', $property->name);
2456
-					$query->setParameter('parameter', null);
2457
-					$query->setParameter('value', $value);
2458
-					$query->execute();
2459
-				}
2460
-
2461
-				if (array_key_exists($property->name, self::$indexParameters)) {
2462
-					$parameters = $property->parameters();
2463
-					$indexedParametersForProperty = self::$indexParameters[$property->name];
2464
-
2465
-					foreach ($parameters as $key => $value) {
2466
-						if (in_array($key, $indexedParametersForProperty)) {
2467
-							// is this a shitty db?
2468
-							if ($this->db->supports4ByteText()) {
2469
-								$value = preg_replace('/[\x{10000}-\x{10FFFF}]/u', "\xEF\xBF\xBD", $value);
2470
-							}
2471
-
2472
-							$query->setParameter('name', $property->name);
2473
-							$query->setParameter('parameter', mb_substr($key, 0, 254));
2474
-							$query->setParameter('value', mb_substr($value, 0, 254));
2475
-							$query->execute();
2476
-						}
2477
-					}
2478
-				}
2479
-			}
2480
-		}
2481
-	}
2482
-
2483
-	/**
2484
-	 * deletes all birthday calendars
2485
-	 */
2486
-	public function deleteAllBirthdayCalendars() {
2487
-		$query = $this->db->getQueryBuilder();
2488
-		$result = $query->select(['id'])->from('calendars')
2489
-			->where($query->expr()->eq('uri', $query->createNamedParameter(BirthdayService::BIRTHDAY_CALENDAR_URI)))
2490
-			->execute();
2491
-
2492
-		$ids = $result->fetchAll();
2493
-		foreach($ids as $id) {
2494
-			$this->deleteCalendar($id['id']);
2495
-		}
2496
-	}
2497
-
2498
-	/**
2499
-	 * @param $subscriptionId
2500
-	 */
2501
-	public function purgeAllCachedEventsForSubscription($subscriptionId) {
2502
-		$query = $this->db->getQueryBuilder();
2503
-		$query->select('uri')
2504
-			->from('calendarobjects')
2505
-			->where($query->expr()->eq('calendarid', $query->createNamedParameter($subscriptionId)))
2506
-			->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)));
2507
-		$stmt = $query->execute();
2508
-
2509
-		$uris = [];
2510
-		foreach($stmt->fetchAll(\PDO::FETCH_ASSOC) as $row) {
2511
-			$uris[] = $row['uri'];
2512
-		}
2513
-		$stmt->closeCursor();
2514
-
2515
-		$query = $this->db->getQueryBuilder();
2516
-		$query->delete('calendarobjects')
2517
-			->where($query->expr()->eq('calendarid', $query->createNamedParameter($subscriptionId)))
2518
-			->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)))
2519
-			->execute();
2520
-
2521
-		$query->delete('calendarchanges')
2522
-			->where($query->expr()->eq('calendarid', $query->createNamedParameter($subscriptionId)))
2523
-			->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)))
2524
-			->execute();
2525
-
2526
-		$query->delete($this->dbObjectPropertiesTable)
2527
-			->where($query->expr()->eq('calendarid', $query->createNamedParameter($subscriptionId)))
2528
-			->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)))
2529
-			->execute();
2530
-
2531
-		foreach($uris as $uri) {
2532
-			$this->addChange($subscriptionId, $uri, 3, self::CALENDAR_TYPE_SUBSCRIPTION);
2533
-		}
2534
-	}
2535
-
2536
-	/**
2537
-	 * Move a calendar from one user to another
2538
-	 *
2539
-	 * @param string $uriName
2540
-	 * @param string $uriOrigin
2541
-	 * @param string $uriDestination
2542
-	 */
2543
-	public function moveCalendar($uriName, $uriOrigin, $uriDestination)
2544
-	{
2545
-		$query = $this->db->getQueryBuilder();
2546
-		$query->update('calendars')
2547
-			->set('principaluri', $query->createNamedParameter($uriDestination))
2548
-			->where($query->expr()->eq('principaluri', $query->createNamedParameter($uriOrigin)))
2549
-			->andWhere($query->expr()->eq('uri', $query->createNamedParameter($uriName)))
2550
-			->execute();
2551
-	}
2552
-
2553
-	/**
2554
-	 * read VCalendar data into a VCalendar object
2555
-	 *
2556
-	 * @param string $objectData
2557
-	 * @return VCalendar
2558
-	 */
2559
-	protected function readCalendarData($objectData) {
2560
-		return Reader::read($objectData);
2561
-	}
2562
-
2563
-	/**
2564
-	 * delete all properties from a given calendar object
2565
-	 *
2566
-	 * @param int $calendarId
2567
-	 * @param int $objectId
2568
-	 */
2569
-	protected function purgeProperties($calendarId, $objectId) {
2570
-		$query = $this->db->getQueryBuilder();
2571
-		$query->delete($this->dbObjectPropertiesTable)
2572
-			->where($query->expr()->eq('objectid', $query->createNamedParameter($objectId)))
2573
-			->andWhere($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)));
2574
-		$query->execute();
2575
-	}
2576
-
2577
-	/**
2578
-	 * get ID from a given calendar object
2579
-	 *
2580
-	 * @param int $calendarId
2581
-	 * @param string $uri
2582
-	 * @param int $calendarType
2583
-	 * @return int
2584
-	 */
2585
-	protected function getCalendarObjectId($calendarId, $uri, $calendarType):int {
2586
-		$query = $this->db->getQueryBuilder();
2587
-		$query->select('id')
2588
-			->from('calendarobjects')
2589
-			->where($query->expr()->eq('uri', $query->createNamedParameter($uri)))
2590
-			->andWhere($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)))
2591
-			->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter($calendarType)));
2592
-
2593
-		$result = $query->execute();
2594
-		$objectIds = $result->fetch();
2595
-		$result->closeCursor();
2596
-
2597
-		if (!isset($objectIds['id'])) {
2598
-			throw new \InvalidArgumentException('Calendarobject does not exists: ' . $uri);
2599
-		}
2600
-
2601
-		return (int)$objectIds['id'];
2602
-	}
2603
-
2604
-	/**
2605
-	 * return legacy endpoint principal name to new principal name
2606
-	 *
2607
-	 * @param $principalUri
2608
-	 * @param $toV2
2609
-	 * @return string
2610
-	 */
2611
-	private function convertPrincipal($principalUri, $toV2) {
2612
-		if ($this->principalBackend->getPrincipalPrefix() === 'principals') {
2613
-			list(, $name) = Uri\split($principalUri);
2614
-			if ($toV2 === true) {
2615
-				return "principals/users/$name";
2616
-			}
2617
-			return "principals/$name";
2618
-		}
2619
-		return $principalUri;
2620
-	}
2621
-
2622
-	/**
2623
-	 * adds information about an owner to the calendar data
2624
-	 *
2625
-	 * @param $calendarInfo
2626
-	 */
2627
-	private function addOwnerPrincipal(&$calendarInfo) {
2628
-		$ownerPrincipalKey = '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal';
2629
-		$displaynameKey = '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_NEXTCLOUD . '}owner-displayname';
2630
-		if (isset($calendarInfo[$ownerPrincipalKey])) {
2631
-			$uri = $calendarInfo[$ownerPrincipalKey];
2632
-		} else {
2633
-			$uri = $calendarInfo['principaluri'];
2634
-		}
2635
-
2636
-		$principalInformation = $this->principalBackend->getPrincipalByPath($uri);
2637
-		if (isset($principalInformation['{DAV:}displayname'])) {
2638
-			$calendarInfo[$displaynameKey] = $principalInformation['{DAV:}displayname'];
2639
-		}
2640
-	}
81
+    const CALENDAR_TYPE_CALENDAR = 0;
82
+    const CALENDAR_TYPE_SUBSCRIPTION = 1;
83
+
84
+    const PERSONAL_CALENDAR_URI = 'personal';
85
+    const PERSONAL_CALENDAR_NAME = 'Personal';
86
+
87
+    const RESOURCE_BOOKING_CALENDAR_URI = 'calendar';
88
+    const RESOURCE_BOOKING_CALENDAR_NAME = 'Calendar';
89
+
90
+    /**
91
+     * We need to specify a max date, because we need to stop *somewhere*
92
+     *
93
+     * On 32 bit system the maximum for a signed integer is 2147483647, so
94
+     * MAX_DATE cannot be higher than date('Y-m-d', 2147483647) which results
95
+     * in 2038-01-19 to avoid problems when the date is converted
96
+     * to a unix timestamp.
97
+     */
98
+    const MAX_DATE = '2038-01-01';
99
+
100
+    const ACCESS_PUBLIC = 4;
101
+    const CLASSIFICATION_PUBLIC = 0;
102
+    const CLASSIFICATION_PRIVATE = 1;
103
+    const CLASSIFICATION_CONFIDENTIAL = 2;
104
+
105
+    /**
106
+     * List of CalDAV properties, and how they map to database field names
107
+     * Add your own properties by simply adding on to this array.
108
+     *
109
+     * Note that only string-based properties are supported here.
110
+     *
111
+     * @var array
112
+     */
113
+    public $propertyMap = [
114
+        '{DAV:}displayname'                          => 'displayname',
115
+        '{urn:ietf:params:xml:ns:caldav}calendar-description' => 'description',
116
+        '{urn:ietf:params:xml:ns:caldav}calendar-timezone'    => 'timezone',
117
+        '{http://apple.com/ns/ical/}calendar-order'  => 'calendarorder',
118
+        '{http://apple.com/ns/ical/}calendar-color'  => 'calendarcolor',
119
+    ];
120
+
121
+    /**
122
+     * List of subscription properties, and how they map to database field names.
123
+     *
124
+     * @var array
125
+     */
126
+    public $subscriptionPropertyMap = [
127
+        '{DAV:}displayname'                                           => 'displayname',
128
+        '{http://apple.com/ns/ical/}refreshrate'                      => 'refreshrate',
129
+        '{http://apple.com/ns/ical/}calendar-order'                   => 'calendarorder',
130
+        '{http://apple.com/ns/ical/}calendar-color'                   => 'calendarcolor',
131
+        '{http://calendarserver.org/ns/}subscribed-strip-todos'       => 'striptodos',
132
+        '{http://calendarserver.org/ns/}subscribed-strip-alarms'      => 'stripalarms',
133
+        '{http://calendarserver.org/ns/}subscribed-strip-attachments' => 'stripattachments',
134
+    ];
135
+
136
+    /** @var array properties to index */
137
+    public static $indexProperties = ['CATEGORIES', 'COMMENT', 'DESCRIPTION',
138
+        'LOCATION', 'RESOURCES', 'STATUS', 'SUMMARY', 'ATTENDEE', 'CONTACT',
139
+        'ORGANIZER'];
140
+
141
+    /** @var array parameters to index */
142
+    public static $indexParameters = [
143
+        'ATTENDEE' => ['CN'],
144
+        'ORGANIZER' => ['CN'],
145
+    ];
146
+
147
+    /**
148
+     * @var string[] Map of uid => display name
149
+     */
150
+    protected $userDisplayNames;
151
+
152
+    /** @var IDBConnection */
153
+    private $db;
154
+
155
+    /** @var Backend */
156
+    private $calendarSharingBackend;
157
+
158
+    /** @var Principal */
159
+    private $principalBackend;
160
+
161
+    /** @var IUserManager */
162
+    private $userManager;
163
+
164
+    /** @var ISecureRandom */
165
+    private $random;
166
+
167
+    /** @var ILogger */
168
+    private $logger;
169
+
170
+    /** @var EventDispatcherInterface */
171
+    private $dispatcher;
172
+
173
+    /** @var bool */
174
+    private $legacyEndpoint;
175
+
176
+    /** @var string */
177
+    private $dbObjectPropertiesTable = 'calendarobjects_props';
178
+
179
+    /**
180
+     * CalDavBackend constructor.
181
+     *
182
+     * @param IDBConnection $db
183
+     * @param Principal $principalBackend
184
+     * @param IUserManager $userManager
185
+     * @param IGroupManager $groupManager
186
+     * @param ISecureRandom $random
187
+     * @param ILogger $logger
188
+     * @param EventDispatcherInterface $dispatcher
189
+     * @param bool $legacyEndpoint
190
+     */
191
+    public function __construct(IDBConnection $db,
192
+                                Principal $principalBackend,
193
+                                IUserManager $userManager,
194
+                                IGroupManager $groupManager,
195
+                                ISecureRandom $random,
196
+                                ILogger $logger,
197
+                                EventDispatcherInterface $dispatcher,
198
+                                bool $legacyEndpoint = false) {
199
+        $this->db = $db;
200
+        $this->principalBackend = $principalBackend;
201
+        $this->userManager = $userManager;
202
+        $this->calendarSharingBackend = new Backend($this->db, $this->userManager, $groupManager, $principalBackend, 'calendar');
203
+        $this->random = $random;
204
+        $this->logger = $logger;
205
+        $this->dispatcher = $dispatcher;
206
+        $this->legacyEndpoint = $legacyEndpoint;
207
+    }
208
+
209
+    /**
210
+     * Return the number of calendars for a principal
211
+     *
212
+     * By default this excludes the automatically generated birthday calendar
213
+     *
214
+     * @param $principalUri
215
+     * @param bool $excludeBirthday
216
+     * @return int
217
+     */
218
+    public function getCalendarsForUserCount($principalUri, $excludeBirthday = true) {
219
+        $principalUri = $this->convertPrincipal($principalUri, true);
220
+        $query = $this->db->getQueryBuilder();
221
+        $query->select($query->func()->count('*'))
222
+            ->from('calendars')
223
+            ->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)));
224
+
225
+        if ($excludeBirthday) {
226
+            $query->andWhere($query->expr()->neq('uri', $query->createNamedParameter(BirthdayService::BIRTHDAY_CALENDAR_URI)));
227
+        }
228
+
229
+        return (int)$query->execute()->fetchColumn();
230
+    }
231
+
232
+    /**
233
+     * Returns a list of calendars for a principal.
234
+     *
235
+     * Every project is an array with the following keys:
236
+     *  * id, a unique id that will be used by other functions to modify the
237
+     *    calendar. This can be the same as the uri or a database key.
238
+     *  * uri, which the basename of the uri with which the calendar is
239
+     *    accessed.
240
+     *  * principaluri. The owner of the calendar. Almost always the same as
241
+     *    principalUri passed to this method.
242
+     *
243
+     * Furthermore it can contain webdav properties in clark notation. A very
244
+     * common one is '{DAV:}displayname'.
245
+     *
246
+     * Many clients also require:
247
+     * {urn:ietf:params:xml:ns:caldav}supported-calendar-component-set
248
+     * For this property, you can just return an instance of
249
+     * Sabre\CalDAV\Property\SupportedCalendarComponentSet.
250
+     *
251
+     * If you return {http://sabredav.org/ns}read-only and set the value to 1,
252
+     * ACL will automatically be put in read-only mode.
253
+     *
254
+     * @param string $principalUri
255
+     * @return array
256
+     */
257
+    function getCalendarsForUser($principalUri) {
258
+        $principalUriOriginal = $principalUri;
259
+        $principalUri = $this->convertPrincipal($principalUri, true);
260
+        $fields = array_values($this->propertyMap);
261
+        $fields[] = 'id';
262
+        $fields[] = 'uri';
263
+        $fields[] = 'synctoken';
264
+        $fields[] = 'components';
265
+        $fields[] = 'principaluri';
266
+        $fields[] = 'transparent';
267
+
268
+        // Making fields a comma-delimited list
269
+        $query = $this->db->getQueryBuilder();
270
+        $query->select($fields)->from('calendars')
271
+                ->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
272
+                ->orderBy('calendarorder', 'ASC');
273
+        $stmt = $query->execute();
274
+
275
+        $calendars = [];
276
+        while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
277
+
278
+            $components = [];
279
+            if ($row['components']) {
280
+                $components = explode(',',$row['components']);
281
+            }
282
+
283
+            $calendar = [
284
+                'id' => $row['id'],
285
+                'uri' => $row['uri'],
286
+                'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
287
+                '{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
288
+                '{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
289
+                '{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
290
+                '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
291
+                '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($principalUri, !$this->legacyEndpoint),
292
+            ];
293
+
294
+            foreach($this->propertyMap as $xmlName=>$dbName) {
295
+                $calendar[$xmlName] = $row[$dbName];
296
+            }
297
+
298
+            $this->addOwnerPrincipal($calendar);
299
+
300
+            if (!isset($calendars[$calendar['id']])) {
301
+                $calendars[$calendar['id']] = $calendar;
302
+            }
303
+        }
304
+
305
+        $stmt->closeCursor();
306
+
307
+        // query for shared calendars
308
+        $principals = $this->principalBackend->getGroupMembership($principalUriOriginal, true);
309
+        $principals = array_merge($principals, $this->principalBackend->getCircleMembership($principalUriOriginal));
310
+
311
+        $principals = array_map(function ($principal) {
312
+            return urldecode($principal);
313
+        }, $principals);
314
+        $principals[]= $principalUri;
315
+
316
+        $fields = array_values($this->propertyMap);
317
+        $fields[] = 'a.id';
318
+        $fields[] = 'a.uri';
319
+        $fields[] = 'a.synctoken';
320
+        $fields[] = 'a.components';
321
+        $fields[] = 'a.principaluri';
322
+        $fields[] = 'a.transparent';
323
+        $fields[] = 's.access';
324
+        $query = $this->db->getQueryBuilder();
325
+        $result = $query->select($fields)
326
+            ->from('dav_shares', 's')
327
+            ->join('s', 'calendars', 'a', $query->expr()->eq('s.resourceid', 'a.id'))
328
+            ->where($query->expr()->in('s.principaluri', $query->createParameter('principaluri')))
329
+            ->andWhere($query->expr()->eq('s.type', $query->createParameter('type')))
330
+            ->setParameter('type', 'calendar')
331
+            ->setParameter('principaluri', $principals, \Doctrine\DBAL\Connection::PARAM_STR_ARRAY)
332
+            ->execute();
333
+
334
+        $readOnlyPropertyName = '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}read-only';
335
+        while($row = $result->fetch()) {
336
+            if ($row['principaluri'] === $principalUri) {
337
+                continue;
338
+            }
339
+
340
+            $readOnly = (int) $row['access'] === Backend::ACCESS_READ;
341
+            if (isset($calendars[$row['id']])) {
342
+                if ($readOnly) {
343
+                    // New share can not have more permissions then the old one.
344
+                    continue;
345
+                }
346
+                if (isset($calendars[$row['id']][$readOnlyPropertyName]) &&
347
+                    $calendars[$row['id']][$readOnlyPropertyName] === 0) {
348
+                    // Old share is already read-write, no more permissions can be gained
349
+                    continue;
350
+                }
351
+            }
352
+
353
+            list(, $name) = Uri\split($row['principaluri']);
354
+            $uri = $row['uri'] . '_shared_by_' . $name;
355
+            $row['displayname'] = $row['displayname'] . ' (' . $this->getUserDisplayName($name) . ')';
356
+            $components = [];
357
+            if ($row['components']) {
358
+                $components = explode(',',$row['components']);
359
+            }
360
+            $calendar = [
361
+                'id' => $row['id'],
362
+                'uri' => $uri,
363
+                'principaluri' => $this->convertPrincipal($principalUri, !$this->legacyEndpoint),
364
+                '{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
365
+                '{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
366
+                '{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
367
+                '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp('transparent'),
368
+                '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
369
+                $readOnlyPropertyName => $readOnly,
370
+            ];
371
+
372
+            foreach($this->propertyMap as $xmlName=>$dbName) {
373
+                $calendar[$xmlName] = $row[$dbName];
374
+            }
375
+
376
+            $this->addOwnerPrincipal($calendar);
377
+
378
+            $calendars[$calendar['id']] = $calendar;
379
+        }
380
+        $result->closeCursor();
381
+
382
+        return array_values($calendars);
383
+    }
384
+
385
+    /**
386
+     * @param $principalUri
387
+     * @return array
388
+     */
389
+    public function getUsersOwnCalendars($principalUri) {
390
+        $principalUri = $this->convertPrincipal($principalUri, true);
391
+        $fields = array_values($this->propertyMap);
392
+        $fields[] = 'id';
393
+        $fields[] = 'uri';
394
+        $fields[] = 'synctoken';
395
+        $fields[] = 'components';
396
+        $fields[] = 'principaluri';
397
+        $fields[] = 'transparent';
398
+        // Making fields a comma-delimited list
399
+        $query = $this->db->getQueryBuilder();
400
+        $query->select($fields)->from('calendars')
401
+            ->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
402
+            ->orderBy('calendarorder', 'ASC');
403
+        $stmt = $query->execute();
404
+        $calendars = [];
405
+        while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
406
+            $components = [];
407
+            if ($row['components']) {
408
+                $components = explode(',',$row['components']);
409
+            }
410
+            $calendar = [
411
+                'id' => $row['id'],
412
+                'uri' => $row['uri'],
413
+                'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
414
+                '{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
415
+                '{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
416
+                '{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
417
+                '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
418
+            ];
419
+            foreach($this->propertyMap as $xmlName=>$dbName) {
420
+                $calendar[$xmlName] = $row[$dbName];
421
+            }
422
+
423
+            $this->addOwnerPrincipal($calendar);
424
+
425
+            if (!isset($calendars[$calendar['id']])) {
426
+                $calendars[$calendar['id']] = $calendar;
427
+            }
428
+        }
429
+        $stmt->closeCursor();
430
+        return array_values($calendars);
431
+    }
432
+
433
+
434
+    /**
435
+     * @param $uid
436
+     * @return string
437
+     */
438
+    private function getUserDisplayName($uid) {
439
+        if (!isset($this->userDisplayNames[$uid])) {
440
+            $user = $this->userManager->get($uid);
441
+
442
+            if ($user instanceof IUser) {
443
+                $this->userDisplayNames[$uid] = $user->getDisplayName();
444
+            } else {
445
+                $this->userDisplayNames[$uid] = $uid;
446
+            }
447
+        }
448
+
449
+        return $this->userDisplayNames[$uid];
450
+    }
451
+
452
+    /**
453
+     * @return array
454
+     */
455
+    public function getPublicCalendars() {
456
+        $fields = array_values($this->propertyMap);
457
+        $fields[] = 'a.id';
458
+        $fields[] = 'a.uri';
459
+        $fields[] = 'a.synctoken';
460
+        $fields[] = 'a.components';
461
+        $fields[] = 'a.principaluri';
462
+        $fields[] = 'a.transparent';
463
+        $fields[] = 's.access';
464
+        $fields[] = 's.publicuri';
465
+        $calendars = [];
466
+        $query = $this->db->getQueryBuilder();
467
+        $result = $query->select($fields)
468
+            ->from('dav_shares', 's')
469
+            ->join('s', 'calendars', 'a', $query->expr()->eq('s.resourceid', 'a.id'))
470
+            ->where($query->expr()->in('s.access', $query->createNamedParameter(self::ACCESS_PUBLIC)))
471
+            ->andWhere($query->expr()->eq('s.type', $query->createNamedParameter('calendar')))
472
+            ->execute();
473
+
474
+        while($row = $result->fetch()) {
475
+            list(, $name) = Uri\split($row['principaluri']);
476
+            $row['displayname'] = $row['displayname'] . "($name)";
477
+            $components = [];
478
+            if ($row['components']) {
479
+                $components = explode(',',$row['components']);
480
+            }
481
+            $calendar = [
482
+                'id' => $row['id'],
483
+                'uri' => $row['publicuri'],
484
+                'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
485
+                '{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
486
+                '{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
487
+                '{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
488
+                '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
489
+                '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($row['principaluri'], $this->legacyEndpoint),
490
+                '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}read-only' => (int)$row['access'] === Backend::ACCESS_READ,
491
+                '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}public' => (int)$row['access'] === self::ACCESS_PUBLIC,
492
+            ];
493
+
494
+            foreach($this->propertyMap as $xmlName=>$dbName) {
495
+                $calendar[$xmlName] = $row[$dbName];
496
+            }
497
+
498
+            $this->addOwnerPrincipal($calendar);
499
+
500
+            if (!isset($calendars[$calendar['id']])) {
501
+                $calendars[$calendar['id']] = $calendar;
502
+            }
503
+        }
504
+        $result->closeCursor();
505
+
506
+        return array_values($calendars);
507
+    }
508
+
509
+    /**
510
+     * @param string $uri
511
+     * @return array
512
+     * @throws NotFound
513
+     */
514
+    public function getPublicCalendar($uri) {
515
+        $fields = array_values($this->propertyMap);
516
+        $fields[] = 'a.id';
517
+        $fields[] = 'a.uri';
518
+        $fields[] = 'a.synctoken';
519
+        $fields[] = 'a.components';
520
+        $fields[] = 'a.principaluri';
521
+        $fields[] = 'a.transparent';
522
+        $fields[] = 's.access';
523
+        $fields[] = 's.publicuri';
524
+        $query = $this->db->getQueryBuilder();
525
+        $result = $query->select($fields)
526
+            ->from('dav_shares', 's')
527
+            ->join('s', 'calendars', 'a', $query->expr()->eq('s.resourceid', 'a.id'))
528
+            ->where($query->expr()->in('s.access', $query->createNamedParameter(self::ACCESS_PUBLIC)))
529
+            ->andWhere($query->expr()->eq('s.type', $query->createNamedParameter('calendar')))
530
+            ->andWhere($query->expr()->eq('s.publicuri', $query->createNamedParameter($uri)))
531
+            ->execute();
532
+
533
+        $row = $result->fetch(\PDO::FETCH_ASSOC);
534
+
535
+        $result->closeCursor();
536
+
537
+        if ($row === false) {
538
+            throw new NotFound('Node with name \'' . $uri . '\' could not be found');
539
+        }
540
+
541
+        list(, $name) = Uri\split($row['principaluri']);
542
+        $row['displayname'] = $row['displayname'] . ' ' . "($name)";
543
+        $components = [];
544
+        if ($row['components']) {
545
+            $components = explode(',',$row['components']);
546
+        }
547
+        $calendar = [
548
+            'id' => $row['id'],
549
+            'uri' => $row['publicuri'],
550
+            'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
551
+            '{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
552
+            '{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
553
+            '{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
554
+            '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
555
+            '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
556
+            '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}read-only' => (int)$row['access'] === Backend::ACCESS_READ,
557
+            '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}public' => (int)$row['access'] === self::ACCESS_PUBLIC,
558
+        ];
559
+
560
+        foreach($this->propertyMap as $xmlName=>$dbName) {
561
+            $calendar[$xmlName] = $row[$dbName];
562
+        }
563
+
564
+        $this->addOwnerPrincipal($calendar);
565
+
566
+        return $calendar;
567
+
568
+    }
569
+
570
+    /**
571
+     * @param string $principal
572
+     * @param string $uri
573
+     * @return array|null
574
+     */
575
+    public function getCalendarByUri($principal, $uri) {
576
+        $fields = array_values($this->propertyMap);
577
+        $fields[] = 'id';
578
+        $fields[] = 'uri';
579
+        $fields[] = 'synctoken';
580
+        $fields[] = 'components';
581
+        $fields[] = 'principaluri';
582
+        $fields[] = 'transparent';
583
+
584
+        // Making fields a comma-delimited list
585
+        $query = $this->db->getQueryBuilder();
586
+        $query->select($fields)->from('calendars')
587
+            ->where($query->expr()->eq('uri', $query->createNamedParameter($uri)))
588
+            ->andWhere($query->expr()->eq('principaluri', $query->createNamedParameter($principal)))
589
+            ->setMaxResults(1);
590
+        $stmt = $query->execute();
591
+
592
+        $row = $stmt->fetch(\PDO::FETCH_ASSOC);
593
+        $stmt->closeCursor();
594
+        if ($row === false) {
595
+            return null;
596
+        }
597
+
598
+        $components = [];
599
+        if ($row['components']) {
600
+            $components = explode(',',$row['components']);
601
+        }
602
+
603
+        $calendar = [
604
+            'id' => $row['id'],
605
+            'uri' => $row['uri'],
606
+            'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
607
+            '{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
608
+            '{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
609
+            '{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
610
+            '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
611
+        ];
612
+
613
+        foreach($this->propertyMap as $xmlName=>$dbName) {
614
+            $calendar[$xmlName] = $row[$dbName];
615
+        }
616
+
617
+        $this->addOwnerPrincipal($calendar);
618
+
619
+        return $calendar;
620
+    }
621
+
622
+    /**
623
+     * @param $calendarId
624
+     * @return array|null
625
+     */
626
+    public function getCalendarById($calendarId) {
627
+        $fields = array_values($this->propertyMap);
628
+        $fields[] = 'id';
629
+        $fields[] = 'uri';
630
+        $fields[] = 'synctoken';
631
+        $fields[] = 'components';
632
+        $fields[] = 'principaluri';
633
+        $fields[] = 'transparent';
634
+
635
+        // Making fields a comma-delimited list
636
+        $query = $this->db->getQueryBuilder();
637
+        $query->select($fields)->from('calendars')
638
+            ->where($query->expr()->eq('id', $query->createNamedParameter($calendarId)))
639
+            ->setMaxResults(1);
640
+        $stmt = $query->execute();
641
+
642
+        $row = $stmt->fetch(\PDO::FETCH_ASSOC);
643
+        $stmt->closeCursor();
644
+        if ($row === false) {
645
+            return null;
646
+        }
647
+
648
+        $components = [];
649
+        if ($row['components']) {
650
+            $components = explode(',',$row['components']);
651
+        }
652
+
653
+        $calendar = [
654
+            'id' => $row['id'],
655
+            'uri' => $row['uri'],
656
+            'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
657
+            '{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
658
+            '{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
659
+            '{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
660
+            '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
661
+        ];
662
+
663
+        foreach($this->propertyMap as $xmlName=>$dbName) {
664
+            $calendar[$xmlName] = $row[$dbName];
665
+        }
666
+
667
+        $this->addOwnerPrincipal($calendar);
668
+
669
+        return $calendar;
670
+    }
671
+
672
+    /**
673
+     * @param $subscriptionId
674
+     */
675
+    public function getSubscriptionById($subscriptionId) {
676
+        $fields = array_values($this->subscriptionPropertyMap);
677
+        $fields[] = 'id';
678
+        $fields[] = 'uri';
679
+        $fields[] = 'source';
680
+        $fields[] = 'synctoken';
681
+        $fields[] = 'principaluri';
682
+        $fields[] = 'lastmodified';
683
+
684
+        $query = $this->db->getQueryBuilder();
685
+        $query->select($fields)
686
+            ->from('calendarsubscriptions')
687
+            ->where($query->expr()->eq('id', $query->createNamedParameter($subscriptionId)))
688
+            ->orderBy('calendarorder', 'asc');
689
+        $stmt =$query->execute();
690
+
691
+        $row = $stmt->fetch(\PDO::FETCH_ASSOC);
692
+        $stmt->closeCursor();
693
+        if ($row === false) {
694
+            return null;
695
+        }
696
+
697
+        $subscription = [
698
+            'id'           => $row['id'],
699
+            'uri'          => $row['uri'],
700
+            'principaluri' => $row['principaluri'],
701
+            'source'       => $row['source'],
702
+            'lastmodified' => $row['lastmodified'],
703
+            '{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet(['VTODO', 'VEVENT']),
704
+            '{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
705
+        ];
706
+
707
+        foreach($this->subscriptionPropertyMap as $xmlName=>$dbName) {
708
+            if (!is_null($row[$dbName])) {
709
+                $subscription[$xmlName] = $row[$dbName];
710
+            }
711
+        }
712
+
713
+        return $subscription;
714
+    }
715
+
716
+    /**
717
+     * Creates a new calendar for a principal.
718
+     *
719
+     * If the creation was a success, an id must be returned that can be used to reference
720
+     * this calendar in other methods, such as updateCalendar.
721
+     *
722
+     * @param string $principalUri
723
+     * @param string $calendarUri
724
+     * @param array $properties
725
+     * @return int
726
+     * @suppress SqlInjectionChecker
727
+     */
728
+    function createCalendar($principalUri, $calendarUri, array $properties) {
729
+        $values = [
730
+            'principaluri' => $this->convertPrincipal($principalUri, true),
731
+            'uri'          => $calendarUri,
732
+            'synctoken'    => 1,
733
+            'transparent'  => 0,
734
+            'components'   => 'VEVENT,VTODO',
735
+            'displayname'  => $calendarUri
736
+        ];
737
+
738
+        // Default value
739
+        $sccs = '{urn:ietf:params:xml:ns:caldav}supported-calendar-component-set';
740
+        if (isset($properties[$sccs])) {
741
+            if (!($properties[$sccs] instanceof SupportedCalendarComponentSet)) {
742
+                throw new DAV\Exception('The ' . $sccs . ' property must be of type: \Sabre\CalDAV\Property\SupportedCalendarComponentSet');
743
+            }
744
+            $values['components'] = implode(',',$properties[$sccs]->getValue());
745
+        } else if (isset($properties['components'])) {
746
+            // Allow to provide components internally without having
747
+            // to create a SupportedCalendarComponentSet object
748
+            $values['components'] = $properties['components'];
749
+        }
750
+
751
+        $transp = '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp';
752
+        if (isset($properties[$transp])) {
753
+            $values['transparent'] = (int) ($properties[$transp]->getValue() === 'transparent');
754
+        }
755
+
756
+        foreach($this->propertyMap as $xmlName=>$dbName) {
757
+            if (isset($properties[$xmlName])) {
758
+                $values[$dbName] = $properties[$xmlName];
759
+            }
760
+        }
761
+
762
+        $query = $this->db->getQueryBuilder();
763
+        $query->insert('calendars');
764
+        foreach($values as $column => $value) {
765
+            $query->setValue($column, $query->createNamedParameter($value));
766
+        }
767
+        $query->execute();
768
+        $calendarId = $query->getLastInsertId();
769
+
770
+        $this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::createCalendar', new GenericEvent(
771
+            '\OCA\DAV\CalDAV\CalDavBackend::createCalendar',
772
+            [
773
+                'calendarId' => $calendarId,
774
+                'calendarData' => $this->getCalendarById($calendarId),
775
+            ]));
776
+
777
+        return $calendarId;
778
+    }
779
+
780
+    /**
781
+     * Updates properties for a calendar.
782
+     *
783
+     * The list of mutations is stored in a Sabre\DAV\PropPatch object.
784
+     * To do the actual updates, you must tell this object which properties
785
+     * you're going to process with the handle() method.
786
+     *
787
+     * Calling the handle method is like telling the PropPatch object "I
788
+     * promise I can handle updating this property".
789
+     *
790
+     * Read the PropPatch documentation for more info and examples.
791
+     *
792
+     * @param mixed $calendarId
793
+     * @param PropPatch $propPatch
794
+     * @return void
795
+     */
796
+    function updateCalendar($calendarId, PropPatch $propPatch) {
797
+        $supportedProperties = array_keys($this->propertyMap);
798
+        $supportedProperties[] = '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp';
799
+
800
+        /**
801
+         * @suppress SqlInjectionChecker
802
+         */
803
+        $propPatch->handle($supportedProperties, function ($mutations) use ($calendarId) {
804
+            $newValues = [];
805
+            foreach ($mutations as $propertyName => $propertyValue) {
806
+
807
+                switch ($propertyName) {
808
+                    case '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' :
809
+                        $fieldName = 'transparent';
810
+                        $newValues[$fieldName] = (int) ($propertyValue->getValue() === 'transparent');
811
+                        break;
812
+                    default :
813
+                        $fieldName = $this->propertyMap[$propertyName];
814
+                        $newValues[$fieldName] = $propertyValue;
815
+                        break;
816
+                }
817
+
818
+            }
819
+            $query = $this->db->getQueryBuilder();
820
+            $query->update('calendars');
821
+            foreach ($newValues as $fieldName => $value) {
822
+                $query->set($fieldName, $query->createNamedParameter($value));
823
+            }
824
+            $query->where($query->expr()->eq('id', $query->createNamedParameter($calendarId)));
825
+            $query->execute();
826
+
827
+            $this->addChange($calendarId, "", 2);
828
+
829
+            $this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::updateCalendar', new GenericEvent(
830
+                '\OCA\DAV\CalDAV\CalDavBackend::updateCalendar',
831
+                [
832
+                    'calendarId' => $calendarId,
833
+                    'calendarData' => $this->getCalendarById($calendarId),
834
+                    'shares' => $this->getShares($calendarId),
835
+                    'propertyMutations' => $mutations,
836
+                ]));
837
+
838
+            return true;
839
+        });
840
+    }
841
+
842
+    /**
843
+     * Delete a calendar and all it's objects
844
+     *
845
+     * @param mixed $calendarId
846
+     * @return void
847
+     */
848
+    function deleteCalendar($calendarId) {
849
+        $this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::deleteCalendar', new GenericEvent(
850
+            '\OCA\DAV\CalDAV\CalDavBackend::deleteCalendar',
851
+            [
852
+                'calendarId' => $calendarId,
853
+                'calendarData' => $this->getCalendarById($calendarId),
854
+                'shares' => $this->getShares($calendarId),
855
+            ]));
856
+
857
+        $stmt = $this->db->prepare('DELETE FROM `*PREFIX*calendarobjects` WHERE `calendarid` = ? AND `calendartype` = ?');
858
+        $stmt->execute([$calendarId, self::CALENDAR_TYPE_CALENDAR]);
859
+
860
+        $stmt = $this->db->prepare('DELETE FROM `*PREFIX*calendars` WHERE `id` = ?');
861
+        $stmt->execute([$calendarId]);
862
+
863
+        $stmt = $this->db->prepare('DELETE FROM `*PREFIX*calendarchanges` WHERE `calendarid` = ? AND `calendartype` = ?');
864
+        $stmt->execute([$calendarId, self::CALENDAR_TYPE_CALENDAR]);
865
+
866
+        $this->calendarSharingBackend->deleteAllShares($calendarId);
867
+
868
+        $query = $this->db->getQueryBuilder();
869
+        $query->delete($this->dbObjectPropertiesTable)
870
+            ->where($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)))
871
+            ->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_CALENDAR)))
872
+            ->execute();
873
+    }
874
+
875
+    /**
876
+     * Delete all of an user's shares
877
+     *
878
+     * @param string $principaluri
879
+     * @return void
880
+     */
881
+    function deleteAllSharesByUser($principaluri) {
882
+        $this->calendarSharingBackend->deleteAllSharesByUser($principaluri);
883
+    }
884
+
885
+    /**
886
+     * Returns all calendar objects within a calendar.
887
+     *
888
+     * Every item contains an array with the following keys:
889
+     *   * calendardata - The iCalendar-compatible calendar data
890
+     *   * uri - a unique key which will be used to construct the uri. This can
891
+     *     be any arbitrary string, but making sure it ends with '.ics' is a
892
+     *     good idea. This is only the basename, or filename, not the full
893
+     *     path.
894
+     *   * lastmodified - a timestamp of the last modification time
895
+     *   * etag - An arbitrary string, surrounded by double-quotes. (e.g.:
896
+     *   '"abcdef"')
897
+     *   * size - The size of the calendar objects, in bytes.
898
+     *   * component - optional, a string containing the type of object, such
899
+     *     as 'vevent' or 'vtodo'. If specified, this will be used to populate
900
+     *     the Content-Type header.
901
+     *
902
+     * Note that the etag is optional, but it's highly encouraged to return for
903
+     * speed reasons.
904
+     *
905
+     * The calendardata is also optional. If it's not returned
906
+     * 'getCalendarObject' will be called later, which *is* expected to return
907
+     * calendardata.
908
+     *
909
+     * If neither etag or size are specified, the calendardata will be
910
+     * used/fetched to determine these numbers. If both are specified the
911
+     * amount of times this is needed is reduced by a great degree.
912
+     *
913
+     * @param mixed $id
914
+     * @param int $calendarType
915
+     * @return array
916
+     */
917
+    public function getCalendarObjects($id, $calendarType=self::CALENDAR_TYPE_CALENDAR):array {
918
+        $query = $this->db->getQueryBuilder();
919
+        $query->select(['id', 'uri', 'lastmodified', 'etag', 'calendarid', 'size', 'componenttype', 'classification'])
920
+            ->from('calendarobjects')
921
+            ->where($query->expr()->eq('calendarid', $query->createNamedParameter($id)))
922
+            ->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter($calendarType)));
923
+        $stmt = $query->execute();
924
+
925
+        $result = [];
926
+        foreach($stmt->fetchAll(\PDO::FETCH_ASSOC) as $row) {
927
+            $result[] = [
928
+                'id'           => $row['id'],
929
+                'uri'          => $row['uri'],
930
+                'lastmodified' => $row['lastmodified'],
931
+                'etag'         => '"' . $row['etag'] . '"',
932
+                'calendarid'   => $row['calendarid'],
933
+                'size'         => (int)$row['size'],
934
+                'component'    => strtolower($row['componenttype']),
935
+                'classification'=> (int)$row['classification']
936
+            ];
937
+        }
938
+
939
+        return $result;
940
+    }
941
+
942
+    /**
943
+     * Returns information from a single calendar object, based on it's object
944
+     * uri.
945
+     *
946
+     * The object uri is only the basename, or filename and not a full path.
947
+     *
948
+     * The returned array must have the same keys as getCalendarObjects. The
949
+     * 'calendardata' object is required here though, while it's not required
950
+     * for getCalendarObjects.
951
+     *
952
+     * This method must return null if the object did not exist.
953
+     *
954
+     * @param mixed $id
955
+     * @param string $objectUri
956
+     * @param int $calendarType
957
+     * @return array|null
958
+     */
959
+    public function getCalendarObject($id, $objectUri, $calendarType=self::CALENDAR_TYPE_CALENDAR) {
960
+        $query = $this->db->getQueryBuilder();
961
+        $query->select(['id', 'uri', 'lastmodified', 'etag', 'calendarid', 'size', 'calendardata', 'componenttype', 'classification'])
962
+            ->from('calendarobjects')
963
+            ->where($query->expr()->eq('calendarid', $query->createNamedParameter($id)))
964
+            ->andWhere($query->expr()->eq('uri', $query->createNamedParameter($objectUri)))
965
+            ->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter($calendarType)));
966
+        $stmt = $query->execute();
967
+        $row = $stmt->fetch(\PDO::FETCH_ASSOC);
968
+
969
+        if(!$row) {
970
+            return null;
971
+        }
972
+
973
+        return [
974
+            'id'            => $row['id'],
975
+            'uri'           => $row['uri'],
976
+            'lastmodified'  => $row['lastmodified'],
977
+            'etag'          => '"' . $row['etag'] . '"',
978
+            'calendarid'    => $row['calendarid'],
979
+            'size'          => (int)$row['size'],
980
+            'calendardata'  => $this->readBlob($row['calendardata']),
981
+            'component'     => strtolower($row['componenttype']),
982
+            'classification'=> (int)$row['classification']
983
+        ];
984
+    }
985
+
986
+    /**
987
+     * Returns a list of calendar objects.
988
+     *
989
+     * This method should work identical to getCalendarObject, but instead
990
+     * return all the calendar objects in the list as an array.
991
+     *
992
+     * If the backend supports this, it may allow for some speed-ups.
993
+     *
994
+     * @param mixed $calendarId
995
+     * @param string[] $uris
996
+     * @param int $calendarType
997
+     * @return array
998
+     */
999
+    public function getMultipleCalendarObjects($id, array $uris, $calendarType=self::CALENDAR_TYPE_CALENDAR):array {
1000
+        if (empty($uris)) {
1001
+            return [];
1002
+        }
1003
+
1004
+        $chunks = array_chunk($uris, 100);
1005
+        $objects = [];
1006
+
1007
+        $query = $this->db->getQueryBuilder();
1008
+        $query->select(['id', 'uri', 'lastmodified', 'etag', 'calendarid', 'size', 'calendardata', 'componenttype', 'classification'])
1009
+            ->from('calendarobjects')
1010
+            ->where($query->expr()->eq('calendarid', $query->createNamedParameter($id)))
1011
+            ->andWhere($query->expr()->in('uri', $query->createParameter('uri')))
1012
+            ->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter($calendarType)));
1013
+
1014
+        foreach ($chunks as $uris) {
1015
+            $query->setParameter('uri', $uris, IQueryBuilder::PARAM_STR_ARRAY);
1016
+            $result = $query->execute();
1017
+
1018
+            while ($row = $result->fetch()) {
1019
+                $objects[] = [
1020
+                    'id'           => $row['id'],
1021
+                    'uri'          => $row['uri'],
1022
+                    'lastmodified' => $row['lastmodified'],
1023
+                    'etag'         => '"' . $row['etag'] . '"',
1024
+                    'calendarid'   => $row['calendarid'],
1025
+                    'size'         => (int)$row['size'],
1026
+                    'calendardata' => $this->readBlob($row['calendardata']),
1027
+                    'component'    => strtolower($row['componenttype']),
1028
+                    'classification' => (int)$row['classification']
1029
+                ];
1030
+            }
1031
+            $result->closeCursor();
1032
+        }
1033
+
1034
+        return $objects;
1035
+    }
1036
+
1037
+    /**
1038
+     * Creates a new calendar object.
1039
+     *
1040
+     * The object uri is only the basename, or filename and not a full path.
1041
+     *
1042
+     * It is possible return an etag from this function, which will be used in
1043
+     * the response to this PUT request. Note that the ETag must be surrounded
1044
+     * by double-quotes.
1045
+     *
1046
+     * However, you should only really return this ETag if you don't mangle the
1047
+     * calendar-data. If the result of a subsequent GET to this object is not
1048
+     * the exact same as this request body, you should omit the ETag.
1049
+     *
1050
+     * @param mixed $calendarId
1051
+     * @param string $objectUri
1052
+     * @param string $calendarData
1053
+     * @param int $calendarType
1054
+     * @return string
1055
+     */
1056
+    function createCalendarObject($calendarId, $objectUri, $calendarData, $calendarType=self::CALENDAR_TYPE_CALENDAR) {
1057
+        $extraData = $this->getDenormalizedData($calendarData);
1058
+
1059
+        $q = $this->db->getQueryBuilder();
1060
+        $q->select($q->func()->count('*'))
1061
+            ->from('calendarobjects')
1062
+            ->where($q->expr()->eq('calendarid', $q->createNamedParameter($calendarId)))
1063
+            ->andWhere($q->expr()->eq('uid', $q->createNamedParameter($extraData['uid'])))
1064
+            ->andWhere($q->expr()->eq('calendartype', $q->createNamedParameter($calendarType)));
1065
+
1066
+        $result = $q->execute();
1067
+        $count = (int) $result->fetchColumn();
1068
+        $result->closeCursor();
1069
+
1070
+        if ($count !== 0) {
1071
+            throw new \Sabre\DAV\Exception\BadRequest('Calendar object with uid already exists in this calendar collection.');
1072
+        }
1073
+
1074
+        $query = $this->db->getQueryBuilder();
1075
+        $query->insert('calendarobjects')
1076
+            ->values([
1077
+                'calendarid' => $query->createNamedParameter($calendarId),
1078
+                'uri' => $query->createNamedParameter($objectUri),
1079
+                'calendardata' => $query->createNamedParameter($calendarData, IQueryBuilder::PARAM_LOB),
1080
+                'lastmodified' => $query->createNamedParameter(time()),
1081
+                'etag' => $query->createNamedParameter($extraData['etag']),
1082
+                'size' => $query->createNamedParameter($extraData['size']),
1083
+                'componenttype' => $query->createNamedParameter($extraData['componentType']),
1084
+                'firstoccurence' => $query->createNamedParameter($extraData['firstOccurence']),
1085
+                'lastoccurence' => $query->createNamedParameter($extraData['lastOccurence']),
1086
+                'classification' => $query->createNamedParameter($extraData['classification']),
1087
+                'uid' => $query->createNamedParameter($extraData['uid']),
1088
+                'calendartype' => $query->createNamedParameter($calendarType),
1089
+            ])
1090
+            ->execute();
1091
+
1092
+        $this->updateProperties($calendarId, $objectUri, $calendarData, $calendarType);
1093
+
1094
+        if ($calendarType === self::CALENDAR_TYPE_CALENDAR) {
1095
+            $this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::createCalendarObject', new GenericEvent(
1096
+                '\OCA\DAV\CalDAV\CalDavBackend::createCalendarObject',
1097
+                [
1098
+                    'calendarId' => $calendarId,
1099
+                    'calendarData' => $this->getCalendarById($calendarId),
1100
+                    'shares' => $this->getShares($calendarId),
1101
+                    'objectData' => $this->getCalendarObject($calendarId, $objectUri),
1102
+                ]
1103
+            ));
1104
+        } else {
1105
+            $this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::createCachedCalendarObject', new GenericEvent(
1106
+                '\OCA\DAV\CalDAV\CalDavBackend::createCachedCalendarObject',
1107
+                [
1108
+                    'subscriptionId' => $calendarId,
1109
+                    'calendarData' => $this->getCalendarById($calendarId),
1110
+                    'shares' => $this->getShares($calendarId),
1111
+                    'objectData' => $this->getCalendarObject($calendarId, $objectUri),
1112
+                ]
1113
+            ));
1114
+        }
1115
+        $this->addChange($calendarId, $objectUri, 1, $calendarType);
1116
+
1117
+        return '"' . $extraData['etag'] . '"';
1118
+    }
1119
+
1120
+    /**
1121
+     * Updates an existing calendarobject, based on it's uri.
1122
+     *
1123
+     * The object uri is only the basename, or filename and not a full path.
1124
+     *
1125
+     * It is possible return an etag from this function, which will be used in
1126
+     * the response to this PUT request. Note that the ETag must be surrounded
1127
+     * by double-quotes.
1128
+     *
1129
+     * However, you should only really return this ETag if you don't mangle the
1130
+     * calendar-data. If the result of a subsequent GET to this object is not
1131
+     * the exact same as this request body, you should omit the ETag.
1132
+     *
1133
+     * @param mixed $calendarId
1134
+     * @param string $objectUri
1135
+     * @param string $calendarData
1136
+     * @param int $calendarType
1137
+     * @return string
1138
+     */
1139
+    function updateCalendarObject($calendarId, $objectUri, $calendarData, $calendarType=self::CALENDAR_TYPE_CALENDAR) {
1140
+        $extraData = $this->getDenormalizedData($calendarData);
1141
+        $query = $this->db->getQueryBuilder();
1142
+        $query->update('calendarobjects')
1143
+                ->set('calendardata', $query->createNamedParameter($calendarData, IQueryBuilder::PARAM_LOB))
1144
+                ->set('lastmodified', $query->createNamedParameter(time()))
1145
+                ->set('etag', $query->createNamedParameter($extraData['etag']))
1146
+                ->set('size', $query->createNamedParameter($extraData['size']))
1147
+                ->set('componenttype', $query->createNamedParameter($extraData['componentType']))
1148
+                ->set('firstoccurence', $query->createNamedParameter($extraData['firstOccurence']))
1149
+                ->set('lastoccurence', $query->createNamedParameter($extraData['lastOccurence']))
1150
+                ->set('classification', $query->createNamedParameter($extraData['classification']))
1151
+                ->set('uid', $query->createNamedParameter($extraData['uid']))
1152
+            ->where($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)))
1153
+            ->andWhere($query->expr()->eq('uri', $query->createNamedParameter($objectUri)))
1154
+            ->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter($calendarType)))
1155
+            ->execute();
1156
+
1157
+        $this->updateProperties($calendarId, $objectUri, $calendarData, $calendarType);
1158
+
1159
+        $data = $this->getCalendarObject($calendarId, $objectUri);
1160
+        if (is_array($data)) {
1161
+            if ($calendarType === self::CALENDAR_TYPE_CALENDAR) {
1162
+                $this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::updateCalendarObject', new GenericEvent(
1163
+                    '\OCA\DAV\CalDAV\CalDavBackend::updateCalendarObject',
1164
+                    [
1165
+                        'calendarId' => $calendarId,
1166
+                        'calendarData' => $this->getCalendarById($calendarId),
1167
+                        'shares' => $this->getShares($calendarId),
1168
+                        'objectData' => $data,
1169
+                    ]
1170
+                ));
1171
+            } else {
1172
+                $this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::updateCachedCalendarObject', new GenericEvent(
1173
+                    '\OCA\DAV\CalDAV\CalDavBackend::updateCachedCalendarObject',
1174
+                    [
1175
+                        'subscriptionId' => $calendarId,
1176
+                        'calendarData' => $this->getCalendarById($calendarId),
1177
+                        'shares' => $this->getShares($calendarId),
1178
+                        'objectData' => $data,
1179
+                    ]
1180
+                ));
1181
+            }
1182
+        }
1183
+        $this->addChange($calendarId, $objectUri, 2, $calendarType);
1184
+
1185
+        return '"' . $extraData['etag'] . '"';
1186
+    }
1187
+
1188
+    /**
1189
+     * @param int $calendarObjectId
1190
+     * @param int $classification
1191
+     */
1192
+    public function setClassification($calendarObjectId, $classification) {
1193
+        if (!in_array($classification, [
1194
+            self::CLASSIFICATION_PUBLIC, self::CLASSIFICATION_PRIVATE, self::CLASSIFICATION_CONFIDENTIAL
1195
+        ])) {
1196
+            throw new \InvalidArgumentException();
1197
+        }
1198
+        $query = $this->db->getQueryBuilder();
1199
+        $query->update('calendarobjects')
1200
+            ->set('classification', $query->createNamedParameter($classification))
1201
+            ->where($query->expr()->eq('id', $query->createNamedParameter($calendarObjectId)))
1202
+            ->execute();
1203
+    }
1204
+
1205
+    /**
1206
+     * Deletes an existing calendar object.
1207
+     *
1208
+     * The object uri is only the basename, or filename and not a full path.
1209
+     *
1210
+     * @param mixed $calendarId
1211
+     * @param string $objectUri
1212
+     * @param int $calendarType
1213
+     * @return void
1214
+     */
1215
+    function deleteCalendarObject($calendarId, $objectUri, $calendarType=self::CALENDAR_TYPE_CALENDAR) {
1216
+        $data = $this->getCalendarObject($calendarId, $objectUri, $calendarType);
1217
+        if (is_array($data)) {
1218
+            if ($calendarType === self::CALENDAR_TYPE_CALENDAR) {
1219
+                $this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::deleteCalendarObject', new GenericEvent(
1220
+                    '\OCA\DAV\CalDAV\CalDavBackend::deleteCalendarObject',
1221
+                    [
1222
+                        'calendarId' => $calendarId,
1223
+                        'calendarData' => $this->getCalendarById($calendarId),
1224
+                        'shares' => $this->getShares($calendarId),
1225
+                        'objectData' => $data,
1226
+                    ]
1227
+                ));
1228
+            } else {
1229
+                $this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::deleteCachedCalendarObject', new GenericEvent(
1230
+                    '\OCA\DAV\CalDAV\CalDavBackend::deleteCachedCalendarObject',
1231
+                    [
1232
+                        'subscriptionId' => $calendarId,
1233
+                        'calendarData' => $this->getCalendarById($calendarId),
1234
+                        'shares' => $this->getShares($calendarId),
1235
+                        'objectData' => $data,
1236
+                    ]
1237
+                ));
1238
+            }
1239
+        }
1240
+
1241
+        $stmt = $this->db->prepare('DELETE FROM `*PREFIX*calendarobjects` WHERE `calendarid` = ? AND `uri` = ? AND `calendartype` = ?');
1242
+        $stmt->execute([$calendarId, $objectUri, $calendarType]);
1243
+
1244
+        if (is_array($data)) {
1245
+            $this->purgeProperties($calendarId, $data['id'], $calendarType);
1246
+        }
1247
+
1248
+        $this->addChange($calendarId, $objectUri, 3, $calendarType);
1249
+    }
1250
+
1251
+    /**
1252
+     * Performs a calendar-query on the contents of this calendar.
1253
+     *
1254
+     * The calendar-query is defined in RFC4791 : CalDAV. Using the
1255
+     * calendar-query it is possible for a client to request a specific set of
1256
+     * object, based on contents of iCalendar properties, date-ranges and
1257
+     * iCalendar component types (VTODO, VEVENT).
1258
+     *
1259
+     * This method should just return a list of (relative) urls that match this
1260
+     * query.
1261
+     *
1262
+     * The list of filters are specified as an array. The exact array is
1263
+     * documented by Sabre\CalDAV\CalendarQueryParser.
1264
+     *
1265
+     * Note that it is extremely likely that getCalendarObject for every path
1266
+     * returned from this method will be called almost immediately after. You
1267
+     * may want to anticipate this to speed up these requests.
1268
+     *
1269
+     * This method provides a default implementation, which parses *all* the
1270
+     * iCalendar objects in the specified calendar.
1271
+     *
1272
+     * This default may well be good enough for personal use, and calendars
1273
+     * that aren't very large. But if you anticipate high usage, big calendars
1274
+     * or high loads, you are strongly advised to optimize certain paths.
1275
+     *
1276
+     * The best way to do so is override this method and to optimize
1277
+     * specifically for 'common filters'.
1278
+     *
1279
+     * Requests that are extremely common are:
1280
+     *   * requests for just VEVENTS
1281
+     *   * requests for just VTODO
1282
+     *   * requests with a time-range-filter on either VEVENT or VTODO.
1283
+     *
1284
+     * ..and combinations of these requests. It may not be worth it to try to
1285
+     * handle every possible situation and just rely on the (relatively
1286
+     * easy to use) CalendarQueryValidator to handle the rest.
1287
+     *
1288
+     * Note that especially time-range-filters may be difficult to parse. A
1289
+     * time-range filter specified on a VEVENT must for instance also handle
1290
+     * recurrence rules correctly.
1291
+     * A good example of how to interprete all these filters can also simply
1292
+     * be found in Sabre\CalDAV\CalendarQueryFilter. This class is as correct
1293
+     * as possible, so it gives you a good idea on what type of stuff you need
1294
+     * to think of.
1295
+     *
1296
+     * @param mixed $id
1297
+     * @param array $filters
1298
+     * @param int $calendarType
1299
+     * @return array
1300
+     */
1301
+    public function calendarQuery($id, array $filters, $calendarType=self::CALENDAR_TYPE_CALENDAR):array {
1302
+        $componentType = null;
1303
+        $requirePostFilter = true;
1304
+        $timeRange = null;
1305
+
1306
+        // if no filters were specified, we don't need to filter after a query
1307
+        if (!$filters['prop-filters'] && !$filters['comp-filters']) {
1308
+            $requirePostFilter = false;
1309
+        }
1310
+
1311
+        // Figuring out if there's a component filter
1312
+        if (count($filters['comp-filters']) > 0 && !$filters['comp-filters'][0]['is-not-defined']) {
1313
+            $componentType = $filters['comp-filters'][0]['name'];
1314
+
1315
+            // Checking if we need post-filters
1316
+            if (!$filters['prop-filters'] && !$filters['comp-filters'][0]['comp-filters'] && !$filters['comp-filters'][0]['time-range'] && !$filters['comp-filters'][0]['prop-filters']) {
1317
+                $requirePostFilter = false;
1318
+            }
1319
+            // There was a time-range filter
1320
+            if ($componentType === 'VEVENT' && isset($filters['comp-filters'][0]['time-range'])) {
1321
+                $timeRange = $filters['comp-filters'][0]['time-range'];
1322
+
1323
+                // If start time OR the end time is not specified, we can do a
1324
+                // 100% accurate mysql query.
1325
+                if (!$filters['prop-filters'] && !$filters['comp-filters'][0]['comp-filters'] && !$filters['comp-filters'][0]['prop-filters'] && (!$timeRange['start'] || !$timeRange['end'])) {
1326
+                    $requirePostFilter = false;
1327
+                }
1328
+            }
1329
+
1330
+        }
1331
+        $columns = ['uri'];
1332
+        if ($requirePostFilter) {
1333
+            $columns = ['uri', 'calendardata'];
1334
+        }
1335
+        $query = $this->db->getQueryBuilder();
1336
+        $query->select($columns)
1337
+            ->from('calendarobjects')
1338
+            ->where($query->expr()->eq('calendarid', $query->createNamedParameter($id)))
1339
+            ->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter($calendarType)));
1340
+
1341
+        if ($componentType) {
1342
+            $query->andWhere($query->expr()->eq('componenttype', $query->createNamedParameter($componentType)));
1343
+        }
1344
+
1345
+        if ($timeRange && $timeRange['start']) {
1346
+            $query->andWhere($query->expr()->gt('lastoccurence', $query->createNamedParameter($timeRange['start']->getTimeStamp())));
1347
+        }
1348
+        if ($timeRange && $timeRange['end']) {
1349
+            $query->andWhere($query->expr()->lt('firstoccurence', $query->createNamedParameter($timeRange['end']->getTimeStamp())));
1350
+        }
1351
+
1352
+        $stmt = $query->execute();
1353
+
1354
+        $result = [];
1355
+        while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1356
+            if ($requirePostFilter) {
1357
+                // validateFilterForObject will parse the calendar data
1358
+                // catch parsing errors
1359
+                try {
1360
+                    $matches = $this->validateFilterForObject($row, $filters);
1361
+                } catch(ParseException $ex) {
1362
+                    $this->logger->logException($ex, [
1363
+                        'app' => 'dav',
1364
+                        'message' => 'Caught parsing exception for calendar data. This usually indicates invalid calendar data. calendar-id:'.$id.' uri:'.$row['uri']
1365
+                    ]);
1366
+                    continue;
1367
+                } catch (InvalidDataException $ex) {
1368
+                    $this->logger->logException($ex, [
1369
+                        'app' => 'dav',
1370
+                        'message' => 'Caught invalid data exception for calendar data. This usually indicates invalid calendar data. calendar-id:'.$id.' uri:'.$row['uri']
1371
+                    ]);
1372
+                    continue;
1373
+                }
1374
+
1375
+                if (!$matches) {
1376
+                    continue;
1377
+                }
1378
+            }
1379
+            $result[] = $row['uri'];
1380
+        }
1381
+
1382
+        return $result;
1383
+    }
1384
+
1385
+    /**
1386
+     * custom Nextcloud search extension for CalDAV
1387
+     *
1388
+     * TODO - this should optionally cover cached calendar objects as well
1389
+     *
1390
+     * @param string $principalUri
1391
+     * @param array $filters
1392
+     * @param integer|null $limit
1393
+     * @param integer|null $offset
1394
+     * @return array
1395
+     */
1396
+    public function calendarSearch($principalUri, array $filters, $limit=null, $offset=null) {
1397
+        $calendars = $this->getCalendarsForUser($principalUri);
1398
+        $ownCalendars = [];
1399
+        $sharedCalendars = [];
1400
+
1401
+        $uriMapper = [];
1402
+
1403
+        foreach($calendars as $calendar) {
1404
+            if ($calendar['{http://owncloud.org/ns}owner-principal'] === $principalUri) {
1405
+                $ownCalendars[] = $calendar['id'];
1406
+            } else {
1407
+                $sharedCalendars[] = $calendar['id'];
1408
+            }
1409
+            $uriMapper[$calendar['id']] = $calendar['uri'];
1410
+        }
1411
+        if (count($ownCalendars) === 0 && count($sharedCalendars) === 0) {
1412
+            return [];
1413
+        }
1414
+
1415
+        $query = $this->db->getQueryBuilder();
1416
+        // Calendar id expressions
1417
+        $calendarExpressions = [];
1418
+        foreach($ownCalendars as $id) {
1419
+            $calendarExpressions[] = $query->expr()->andX(
1420
+                $query->expr()->eq('c.calendarid',
1421
+                    $query->createNamedParameter($id)),
1422
+                $query->expr()->eq('c.calendartype',
1423
+                        $query->createNamedParameter(self::CALENDAR_TYPE_CALENDAR)));
1424
+        }
1425
+        foreach($sharedCalendars as $id) {
1426
+            $calendarExpressions[] = $query->expr()->andX(
1427
+                $query->expr()->eq('c.calendarid',
1428
+                    $query->createNamedParameter($id)),
1429
+                $query->expr()->eq('c.classification',
1430
+                    $query->createNamedParameter(self::CLASSIFICATION_PUBLIC)),
1431
+                $query->expr()->eq('c.calendartype',
1432
+                    $query->createNamedParameter(self::CALENDAR_TYPE_CALENDAR)));
1433
+        }
1434
+
1435
+        if (count($calendarExpressions) === 1) {
1436
+            $calExpr = $calendarExpressions[0];
1437
+        } else {
1438
+            $calExpr = call_user_func_array([$query->expr(), 'orX'], $calendarExpressions);
1439
+        }
1440
+
1441
+        // Component expressions
1442
+        $compExpressions = [];
1443
+        foreach($filters['comps'] as $comp) {
1444
+            $compExpressions[] = $query->expr()
1445
+                ->eq('c.componenttype', $query->createNamedParameter($comp));
1446
+        }
1447
+
1448
+        if (count($compExpressions) === 1) {
1449
+            $compExpr = $compExpressions[0];
1450
+        } else {
1451
+            $compExpr = call_user_func_array([$query->expr(), 'orX'], $compExpressions);
1452
+        }
1453
+
1454
+        if (!isset($filters['props'])) {
1455
+            $filters['props'] = [];
1456
+        }
1457
+        if (!isset($filters['params'])) {
1458
+            $filters['params'] = [];
1459
+        }
1460
+
1461
+        $propParamExpressions = [];
1462
+        foreach($filters['props'] as $prop) {
1463
+            $propParamExpressions[] = $query->expr()->andX(
1464
+                $query->expr()->eq('i.name', $query->createNamedParameter($prop)),
1465
+                $query->expr()->isNull('i.parameter')
1466
+            );
1467
+        }
1468
+        foreach($filters['params'] as $param) {
1469
+            $propParamExpressions[] = $query->expr()->andX(
1470
+                $query->expr()->eq('i.name', $query->createNamedParameter($param['property'])),
1471
+                $query->expr()->eq('i.parameter', $query->createNamedParameter($param['parameter']))
1472
+            );
1473
+        }
1474
+
1475
+        if (count($propParamExpressions) === 1) {
1476
+            $propParamExpr = $propParamExpressions[0];
1477
+        } else {
1478
+            $propParamExpr = call_user_func_array([$query->expr(), 'orX'], $propParamExpressions);
1479
+        }
1480
+
1481
+        $query->select(['c.calendarid', 'c.uri'])
1482
+            ->from($this->dbObjectPropertiesTable, 'i')
1483
+            ->join('i', 'calendarobjects', 'c', $query->expr()->eq('i.objectid', 'c.id'))
1484
+            ->where($calExpr)
1485
+            ->andWhere($compExpr)
1486
+            ->andWhere($propParamExpr)
1487
+            ->andWhere($query->expr()->iLike('i.value',
1488
+                $query->createNamedParameter('%'.$this->db->escapeLikeParameter($filters['search-term']).'%')));
1489
+
1490
+        if ($offset) {
1491
+            $query->setFirstResult($offset);
1492
+        }
1493
+        if ($limit) {
1494
+            $query->setMaxResults($limit);
1495
+        }
1496
+
1497
+        $stmt = $query->execute();
1498
+
1499
+        $result = [];
1500
+        while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1501
+            $path = $uriMapper[$row['calendarid']] . '/' . $row['uri'];
1502
+            if (!in_array($path, $result)) {
1503
+                $result[] = $path;
1504
+            }
1505
+        }
1506
+
1507
+        return $result;
1508
+    }
1509
+
1510
+    /**
1511
+     * used for Nextcloud's calendar API
1512
+     *
1513
+     * @param array $calendarInfo
1514
+     * @param string $pattern
1515
+     * @param array $searchProperties
1516
+     * @param array $options
1517
+     * @param integer|null $limit
1518
+     * @param integer|null $offset
1519
+     *
1520
+     * @return array
1521
+     */
1522
+    public function search(array $calendarInfo, $pattern, array $searchProperties,
1523
+                            array $options, $limit, $offset) {
1524
+        $outerQuery = $this->db->getQueryBuilder();
1525
+        $innerQuery = $this->db->getQueryBuilder();
1526
+
1527
+        $innerQuery->selectDistinct('op.objectid')
1528
+            ->from($this->dbObjectPropertiesTable, 'op')
1529
+            ->andWhere($innerQuery->expr()->eq('op.calendarid',
1530
+                $outerQuery->createNamedParameter($calendarInfo['id'])))
1531
+            ->andWhere($innerQuery->expr()->eq('op.calendartype',
1532
+                $outerQuery->createNamedParameter(self::CALENDAR_TYPE_CALENDAR)));
1533
+
1534
+        // only return public items for shared calendars for now
1535
+        if ($calendarInfo['principaluri'] !== $calendarInfo['{http://owncloud.org/ns}owner-principal']) {
1536
+            $innerQuery->andWhere($innerQuery->expr()->eq('c.classification',
1537
+                $outerQuery->createNamedParameter(self::CLASSIFICATION_PUBLIC)));
1538
+        }
1539
+
1540
+        $or = $innerQuery->expr()->orX();
1541
+        foreach($searchProperties as $searchProperty) {
1542
+            $or->add($innerQuery->expr()->eq('op.name',
1543
+                $outerQuery->createNamedParameter($searchProperty)));
1544
+        }
1545
+        $innerQuery->andWhere($or);
1546
+
1547
+        if ($pattern !== '') {
1548
+            $innerQuery->andWhere($innerQuery->expr()->iLike('op.value',
1549
+                $outerQuery->createNamedParameter('%' .
1550
+                    $this->db->escapeLikeParameter($pattern) . '%')));
1551
+        }
1552
+
1553
+        $outerQuery->select('c.id', 'c.calendardata', 'c.componenttype', 'c.uid', 'c.uri')
1554
+            ->from('calendarobjects', 'c');
1555
+
1556
+        if (isset($options['timerange'])) {
1557
+            if (isset($options['timerange']['start']) && $options['timerange']['start'] instanceof DateTime) {
1558
+                $outerQuery->andWhere($outerQuery->expr()->gt('lastoccurence',
1559
+                    $outerQuery->createNamedParameter($options['timerange']['start']->getTimeStamp())));
1560
+
1561
+            }
1562
+            if (isset($options['timerange']['end']) && $options['timerange']['end'] instanceof DateTime) {
1563
+                $outerQuery->andWhere($outerQuery->expr()->lt('firstoccurence',
1564
+                    $outerQuery->createNamedParameter($options['timerange']['end']->getTimeStamp())));
1565
+            }
1566
+        }
1567
+
1568
+        if (isset($options['types'])) {
1569
+            $or = $outerQuery->expr()->orX();
1570
+            foreach($options['types'] as $type) {
1571
+                $or->add($outerQuery->expr()->eq('componenttype',
1572
+                    $outerQuery->createNamedParameter($type)));
1573
+            }
1574
+            $outerQuery->andWhere($or);
1575
+        }
1576
+
1577
+        $outerQuery->andWhere($outerQuery->expr()->in('c.id',
1578
+            $outerQuery->createFunction($innerQuery->getSQL())));
1579
+
1580
+        if ($offset) {
1581
+            $outerQuery->setFirstResult($offset);
1582
+        }
1583
+        if ($limit) {
1584
+            $outerQuery->setMaxResults($limit);
1585
+        }
1586
+
1587
+        $result = $outerQuery->execute();
1588
+        $calendarObjects = $result->fetchAll();
1589
+
1590
+        return array_map(function ($o) {
1591
+            $calendarData = Reader::read($o['calendardata']);
1592
+            $comps = $calendarData->getComponents();
1593
+            $objects = [];
1594
+            $timezones = [];
1595
+            foreach($comps as $comp) {
1596
+                if ($comp instanceof VTimeZone) {
1597
+                    $timezones[] = $comp;
1598
+                } else {
1599
+                    $objects[] = $comp;
1600
+                }
1601
+            }
1602
+
1603
+            return [
1604
+                'id' => $o['id'],
1605
+                'type' => $o['componenttype'],
1606
+                'uid' => $o['uid'],
1607
+                'uri' => $o['uri'],
1608
+                'objects' => array_map(function ($c) {
1609
+                    return $this->transformSearchData($c);
1610
+                }, $objects),
1611
+                'timezones' => array_map(function ($c) {
1612
+                    return $this->transformSearchData($c);
1613
+                }, $timezones),
1614
+            ];
1615
+        }, $calendarObjects);
1616
+    }
1617
+
1618
+    /**
1619
+     * @param Component $comp
1620
+     * @return array
1621
+     */
1622
+    private function transformSearchData(Component $comp) {
1623
+        $data = [];
1624
+        /** @var Component[] $subComponents */
1625
+        $subComponents = $comp->getComponents();
1626
+        /** @var Property[] $properties */
1627
+        $properties = array_filter($comp->children(), function ($c) {
1628
+            return $c instanceof Property;
1629
+        });
1630
+        $validationRules = $comp->getValidationRules();
1631
+
1632
+        foreach($subComponents as $subComponent) {
1633
+            $name = $subComponent->name;
1634
+            if (!isset($data[$name])) {
1635
+                $data[$name] = [];
1636
+            }
1637
+            $data[$name][] = $this->transformSearchData($subComponent);
1638
+        }
1639
+
1640
+        foreach($properties as $property) {
1641
+            $name = $property->name;
1642
+            if (!isset($validationRules[$name])) {
1643
+                $validationRules[$name] = '*';
1644
+            }
1645
+
1646
+            $rule = $validationRules[$property->name];
1647
+            if ($rule === '+' || $rule === '*') { // multiple
1648
+                if (!isset($data[$name])) {
1649
+                    $data[$name] = [];
1650
+                }
1651
+
1652
+                $data[$name][] = $this->transformSearchProperty($property);
1653
+            } else { // once
1654
+                $data[$name] = $this->transformSearchProperty($property);
1655
+            }
1656
+        }
1657
+
1658
+        return $data;
1659
+    }
1660
+
1661
+    /**
1662
+     * @param Property $prop
1663
+     * @return array
1664
+     */
1665
+    private function transformSearchProperty(Property $prop) {
1666
+        // No need to check Date, as it extends DateTime
1667
+        if ($prop instanceof Property\ICalendar\DateTime) {
1668
+            $value = $prop->getDateTime();
1669
+        } else {
1670
+            $value = $prop->getValue();
1671
+        }
1672
+
1673
+        return [
1674
+            $value,
1675
+            $prop->parameters()
1676
+        ];
1677
+    }
1678
+
1679
+    /**
1680
+     * Searches through all of a users calendars and calendar objects to find
1681
+     * an object with a specific UID.
1682
+     *
1683
+     * This method should return the path to this object, relative to the
1684
+     * calendar home, so this path usually only contains two parts:
1685
+     *
1686
+     * calendarpath/objectpath.ics
1687
+     *
1688
+     * If the uid is not found, return null.
1689
+     *
1690
+     * This method should only consider * objects that the principal owns, so
1691
+     * any calendars owned by other principals that also appear in this
1692
+     * collection should be ignored.
1693
+     *
1694
+     * @param string $principalUri
1695
+     * @param string $uid
1696
+     * @return string|null
1697
+     */
1698
+    function getCalendarObjectByUID($principalUri, $uid) {
1699
+
1700
+        $query = $this->db->getQueryBuilder();
1701
+        $query->selectAlias('c.uri', 'calendaruri')->selectAlias('co.uri', 'objecturi')
1702
+            ->from('calendarobjects', 'co')
1703
+            ->leftJoin('co', 'calendars', 'c', $query->expr()->eq('co.calendarid', 'c.id'))
1704
+            ->where($query->expr()->eq('c.principaluri', $query->createNamedParameter($principalUri)))
1705
+            ->andWhere($query->expr()->eq('co.uid', $query->createNamedParameter($uid)))
1706
+            ->andWhere($query->expr()->eq('co.uid', $query->createNamedParameter($uid)));
1707
+
1708
+        $stmt = $query->execute();
1709
+
1710
+        if ($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1711
+            return $row['calendaruri'] . '/' . $row['objecturi'];
1712
+        }
1713
+
1714
+        return null;
1715
+    }
1716
+
1717
+    /**
1718
+     * The getChanges method returns all the changes that have happened, since
1719
+     * the specified syncToken in the specified calendar.
1720
+     *
1721
+     * This function should return an array, such as the following:
1722
+     *
1723
+     * [
1724
+     *   'syncToken' => 'The current synctoken',
1725
+     *   'added'   => [
1726
+     *      'new.txt',
1727
+     *   ],
1728
+     *   'modified'   => [
1729
+     *      'modified.txt',
1730
+     *   ],
1731
+     *   'deleted' => [
1732
+     *      'foo.php.bak',
1733
+     *      'old.txt'
1734
+     *   ]
1735
+     * );
1736
+     *
1737
+     * The returned syncToken property should reflect the *current* syncToken
1738
+     * of the calendar, as reported in the {http://sabredav.org/ns}sync-token
1739
+     * property This is * needed here too, to ensure the operation is atomic.
1740
+     *
1741
+     * If the $syncToken argument is specified as null, this is an initial
1742
+     * sync, and all members should be reported.
1743
+     *
1744
+     * The modified property is an array of nodenames that have changed since
1745
+     * the last token.
1746
+     *
1747
+     * The deleted property is an array with nodenames, that have been deleted
1748
+     * from collection.
1749
+     *
1750
+     * The $syncLevel argument is basically the 'depth' of the report. If it's
1751
+     * 1, you only have to report changes that happened only directly in
1752
+     * immediate descendants. If it's 2, it should also include changes from
1753
+     * the nodes below the child collections. (grandchildren)
1754
+     *
1755
+     * The $limit argument allows a client to specify how many results should
1756
+     * be returned at most. If the limit is not specified, it should be treated
1757
+     * as infinite.
1758
+     *
1759
+     * If the limit (infinite or not) is higher than you're willing to return,
1760
+     * you should throw a Sabre\DAV\Exception\TooMuchMatches() exception.
1761
+     *
1762
+     * If the syncToken is expired (due to data cleanup) or unknown, you must
1763
+     * return null.
1764
+     *
1765
+     * The limit is 'suggestive'. You are free to ignore it.
1766
+     *
1767
+     * @param string $calendarId
1768
+     * @param string $syncToken
1769
+     * @param int $syncLevel
1770
+     * @param int $limit
1771
+     * @param int $calendarType
1772
+     * @return array
1773
+     */
1774
+    function getChangesForCalendar($calendarId, $syncToken, $syncLevel, $limit = null, $calendarType=self::CALENDAR_TYPE_CALENDAR) {
1775
+        // Current synctoken
1776
+        $stmt = $this->db->prepare('SELECT `synctoken` FROM `*PREFIX*calendars` WHERE `id` = ?');
1777
+        $stmt->execute([ $calendarId ]);
1778
+        $currentToken = $stmt->fetchColumn(0);
1779
+
1780
+        if (is_null($currentToken)) {
1781
+            return null;
1782
+        }
1783
+
1784
+        $result = [
1785
+            'syncToken' => $currentToken,
1786
+            'added'     => [],
1787
+            'modified'  => [],
1788
+            'deleted'   => [],
1789
+        ];
1790
+
1791
+        if ($syncToken) {
1792
+
1793
+            $query = "SELECT `uri`, `operation` FROM `*PREFIX*calendarchanges` WHERE `synctoken` >= ? AND `synctoken` < ? AND `calendarid` = ? AND `calendartype` = ? ORDER BY `synctoken`";
1794
+            if ($limit>0) {
1795
+                $query.= " LIMIT " . (int)$limit;
1796
+            }
1797
+
1798
+            // Fetching all changes
1799
+            $stmt = $this->db->prepare($query);
1800
+            $stmt->execute([$syncToken, $currentToken, $calendarId, $calendarType]);
1801
+
1802
+            $changes = [];
1803
+
1804
+            // This loop ensures that any duplicates are overwritten, only the
1805
+            // last change on a node is relevant.
1806
+            while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1807
+
1808
+                $changes[$row['uri']] = $row['operation'];
1809
+
1810
+            }
1811
+
1812
+            foreach($changes as $uri => $operation) {
1813
+
1814
+                switch($operation) {
1815
+                    case 1 :
1816
+                        $result['added'][] = $uri;
1817
+                        break;
1818
+                    case 2 :
1819
+                        $result['modified'][] = $uri;
1820
+                        break;
1821
+                    case 3 :
1822
+                        $result['deleted'][] = $uri;
1823
+                        break;
1824
+                }
1825
+
1826
+            }
1827
+        } else {
1828
+            // No synctoken supplied, this is the initial sync.
1829
+            $query = "SELECT `uri` FROM `*PREFIX*calendarobjects` WHERE `calendarid` = ? AND `calendartype` = ?";
1830
+            $stmt = $this->db->prepare($query);
1831
+            $stmt->execute([$calendarId, $calendarType]);
1832
+
1833
+            $result['added'] = $stmt->fetchAll(\PDO::FETCH_COLUMN);
1834
+        }
1835
+        return $result;
1836
+
1837
+    }
1838
+
1839
+    /**
1840
+     * Returns a list of subscriptions for a principal.
1841
+     *
1842
+     * Every subscription is an array with the following keys:
1843
+     *  * id, a unique id that will be used by other functions to modify the
1844
+     *    subscription. This can be the same as the uri or a database key.
1845
+     *  * uri. This is just the 'base uri' or 'filename' of the subscription.
1846
+     *  * principaluri. The owner of the subscription. Almost always the same as
1847
+     *    principalUri passed to this method.
1848
+     *
1849
+     * Furthermore, all the subscription info must be returned too:
1850
+     *
1851
+     * 1. {DAV:}displayname
1852
+     * 2. {http://apple.com/ns/ical/}refreshrate
1853
+     * 3. {http://calendarserver.org/ns/}subscribed-strip-todos (omit if todos
1854
+     *    should not be stripped).
1855
+     * 4. {http://calendarserver.org/ns/}subscribed-strip-alarms (omit if alarms
1856
+     *    should not be stripped).
1857
+     * 5. {http://calendarserver.org/ns/}subscribed-strip-attachments (omit if
1858
+     *    attachments should not be stripped).
1859
+     * 6. {http://calendarserver.org/ns/}source (Must be a
1860
+     *     Sabre\DAV\Property\Href).
1861
+     * 7. {http://apple.com/ns/ical/}calendar-color
1862
+     * 8. {http://apple.com/ns/ical/}calendar-order
1863
+     * 9. {urn:ietf:params:xml:ns:caldav}supported-calendar-component-set
1864
+     *    (should just be an instance of
1865
+     *    Sabre\CalDAV\Property\SupportedCalendarComponentSet, with a bunch of
1866
+     *    default components).
1867
+     *
1868
+     * @param string $principalUri
1869
+     * @return array
1870
+     */
1871
+    function getSubscriptionsForUser($principalUri) {
1872
+        $fields = array_values($this->subscriptionPropertyMap);
1873
+        $fields[] = 'id';
1874
+        $fields[] = 'uri';
1875
+        $fields[] = 'source';
1876
+        $fields[] = 'principaluri';
1877
+        $fields[] = 'lastmodified';
1878
+        $fields[] = 'synctoken';
1879
+
1880
+        $query = $this->db->getQueryBuilder();
1881
+        $query->select($fields)
1882
+            ->from('calendarsubscriptions')
1883
+            ->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
1884
+            ->orderBy('calendarorder', 'asc');
1885
+        $stmt =$query->execute();
1886
+
1887
+        $subscriptions = [];
1888
+        while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1889
+
1890
+            $subscription = [
1891
+                'id'           => $row['id'],
1892
+                'uri'          => $row['uri'],
1893
+                'principaluri' => $row['principaluri'],
1894
+                'source'       => $row['source'],
1895
+                'lastmodified' => $row['lastmodified'],
1896
+
1897
+                '{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet(['VTODO', 'VEVENT']),
1898
+                '{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
1899
+            ];
1900
+
1901
+            foreach($this->subscriptionPropertyMap as $xmlName=>$dbName) {
1902
+                if (!is_null($row[$dbName])) {
1903
+                    $subscription[$xmlName] = $row[$dbName];
1904
+                }
1905
+            }
1906
+
1907
+            $subscriptions[] = $subscription;
1908
+
1909
+        }
1910
+
1911
+        return $subscriptions;
1912
+    }
1913
+
1914
+    /**
1915
+     * Creates a new subscription for a principal.
1916
+     *
1917
+     * If the creation was a success, an id must be returned that can be used to reference
1918
+     * this subscription in other methods, such as updateSubscription.
1919
+     *
1920
+     * @param string $principalUri
1921
+     * @param string $uri
1922
+     * @param array $properties
1923
+     * @return mixed
1924
+     */
1925
+    function createSubscription($principalUri, $uri, array $properties) {
1926
+
1927
+        if (!isset($properties['{http://calendarserver.org/ns/}source'])) {
1928
+            throw new Forbidden('The {http://calendarserver.org/ns/}source property is required when creating subscriptions');
1929
+        }
1930
+
1931
+        $values = [
1932
+            'principaluri' => $principalUri,
1933
+            'uri'          => $uri,
1934
+            'source'       => $properties['{http://calendarserver.org/ns/}source']->getHref(),
1935
+            'lastmodified' => time(),
1936
+        ];
1937
+
1938
+        $propertiesBoolean = ['striptodos', 'stripalarms', 'stripattachments'];
1939
+
1940
+        foreach($this->subscriptionPropertyMap as $xmlName=>$dbName) {
1941
+            if (array_key_exists($xmlName, $properties)) {
1942
+                    $values[$dbName] = $properties[$xmlName];
1943
+                    if (in_array($dbName, $propertiesBoolean)) {
1944
+                        $values[$dbName] = true;
1945
+                }
1946
+            }
1947
+        }
1948
+
1949
+        $valuesToInsert = [];
1950
+
1951
+        $query = $this->db->getQueryBuilder();
1952
+
1953
+        foreach (array_keys($values) as $name) {
1954
+            $valuesToInsert[$name] = $query->createNamedParameter($values[$name]);
1955
+        }
1956
+
1957
+        $query->insert('calendarsubscriptions')
1958
+            ->values($valuesToInsert)
1959
+            ->execute();
1960
+
1961
+        $subscriptionId = $this->db->lastInsertId('*PREFIX*calendarsubscriptions');
1962
+
1963
+        $this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::createSubscription', new GenericEvent(
1964
+            '\OCA\DAV\CalDAV\CalDavBackend::createSubscription',
1965
+            [
1966
+                'subscriptionId' => $subscriptionId,
1967
+                'subscriptionData' => $this->getSubscriptionById($subscriptionId),
1968
+            ]));
1969
+
1970
+        return $subscriptionId;
1971
+    }
1972
+
1973
+    /**
1974
+     * Updates a subscription
1975
+     *
1976
+     * The list of mutations is stored in a Sabre\DAV\PropPatch object.
1977
+     * To do the actual updates, you must tell this object which properties
1978
+     * you're going to process with the handle() method.
1979
+     *
1980
+     * Calling the handle method is like telling the PropPatch object "I
1981
+     * promise I can handle updating this property".
1982
+     *
1983
+     * Read the PropPatch documentation for more info and examples.
1984
+     *
1985
+     * @param mixed $subscriptionId
1986
+     * @param PropPatch $propPatch
1987
+     * @return void
1988
+     */
1989
+    function updateSubscription($subscriptionId, PropPatch $propPatch) {
1990
+        $supportedProperties = array_keys($this->subscriptionPropertyMap);
1991
+        $supportedProperties[] = '{http://calendarserver.org/ns/}source';
1992
+
1993
+        /**
1994
+         * @suppress SqlInjectionChecker
1995
+         */
1996
+        $propPatch->handle($supportedProperties, function ($mutations) use ($subscriptionId) {
1997
+
1998
+            $newValues = [];
1999
+
2000
+            foreach($mutations as $propertyName=>$propertyValue) {
2001
+                if ($propertyName === '{http://calendarserver.org/ns/}source') {
2002
+                    $newValues['source'] = $propertyValue->getHref();
2003
+                } else {
2004
+                    $fieldName = $this->subscriptionPropertyMap[$propertyName];
2005
+                    $newValues[$fieldName] = $propertyValue;
2006
+                }
2007
+            }
2008
+
2009
+            $query = $this->db->getQueryBuilder();
2010
+            $query->update('calendarsubscriptions')
2011
+                ->set('lastmodified', $query->createNamedParameter(time()));
2012
+            foreach($newValues as $fieldName=>$value) {
2013
+                $query->set($fieldName, $query->createNamedParameter($value));
2014
+            }
2015
+            $query->where($query->expr()->eq('id', $query->createNamedParameter($subscriptionId)))
2016
+                ->execute();
2017
+
2018
+            $this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::updateSubscription', new GenericEvent(
2019
+                '\OCA\DAV\CalDAV\CalDavBackend::updateSubscription',
2020
+                [
2021
+                    'subscriptionId' => $subscriptionId,
2022
+                    'subscriptionData' => $this->getSubscriptionById($subscriptionId),
2023
+                    'propertyMutations' => $mutations,
2024
+                ]));
2025
+
2026
+            return true;
2027
+
2028
+        });
2029
+    }
2030
+
2031
+    /**
2032
+     * Deletes a subscription.
2033
+     *
2034
+     * @param mixed $subscriptionId
2035
+     * @return void
2036
+     */
2037
+    function deleteSubscription($subscriptionId) {
2038
+        $this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::deleteSubscription', new GenericEvent(
2039
+            '\OCA\DAV\CalDAV\CalDavBackend::deleteSubscription',
2040
+            [
2041
+                'subscriptionId' => $subscriptionId,
2042
+                'subscriptionData' => $this->getSubscriptionById($subscriptionId),
2043
+            ]));
2044
+
2045
+        $query = $this->db->getQueryBuilder();
2046
+        $query->delete('calendarsubscriptions')
2047
+            ->where($query->expr()->eq('id', $query->createNamedParameter($subscriptionId)))
2048
+            ->execute();
2049
+
2050
+        $query = $this->db->getQueryBuilder();
2051
+        $query->delete('calendarobjects')
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('calendarchanges')
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
+        $query->delete($this->dbObjectPropertiesTable)
2062
+            ->where($query->expr()->eq('calendarid', $query->createNamedParameter($subscriptionId)))
2063
+            ->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)))
2064
+            ->execute();
2065
+    }
2066
+
2067
+    /**
2068
+     * Returns a single scheduling object for the inbox collection.
2069
+     *
2070
+     * The returned array should contain the following elements:
2071
+     *   * uri - A unique basename for the object. This will be used to
2072
+     *           construct a full uri.
2073
+     *   * calendardata - The iCalendar object
2074
+     *   * lastmodified - The last modification date. Can be an int for a unix
2075
+     *                    timestamp, or a PHP DateTime object.
2076
+     *   * etag - A unique token that must change if the object changed.
2077
+     *   * size - The size of the object, in bytes.
2078
+     *
2079
+     * @param string $principalUri
2080
+     * @param string $objectUri
2081
+     * @return array
2082
+     */
2083
+    function getSchedulingObject($principalUri, $objectUri) {
2084
+        $query = $this->db->getQueryBuilder();
2085
+        $stmt = $query->select(['uri', 'calendardata', 'lastmodified', 'etag', 'size'])
2086
+            ->from('schedulingobjects')
2087
+            ->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
2088
+            ->andWhere($query->expr()->eq('uri', $query->createNamedParameter($objectUri)))
2089
+            ->execute();
2090
+
2091
+        $row = $stmt->fetch(\PDO::FETCH_ASSOC);
2092
+
2093
+        if(!$row) {
2094
+            return null;
2095
+        }
2096
+
2097
+        return [
2098
+            'uri'          => $row['uri'],
2099
+            'calendardata' => $row['calendardata'],
2100
+            'lastmodified' => $row['lastmodified'],
2101
+            'etag'         => '"' . $row['etag'] . '"',
2102
+            'size'         => (int)$row['size'],
2103
+        ];
2104
+    }
2105
+
2106
+    /**
2107
+     * Returns all scheduling objects for the inbox collection.
2108
+     *
2109
+     * These objects should be returned as an array. Every item in the array
2110
+     * should follow the same structure as returned from getSchedulingObject.
2111
+     *
2112
+     * The main difference is that 'calendardata' is optional.
2113
+     *
2114
+     * @param string $principalUri
2115
+     * @return array
2116
+     */
2117
+    function getSchedulingObjects($principalUri) {
2118
+        $query = $this->db->getQueryBuilder();
2119
+        $stmt = $query->select(['uri', 'calendardata', 'lastmodified', 'etag', 'size'])
2120
+                ->from('schedulingobjects')
2121
+                ->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
2122
+                ->execute();
2123
+
2124
+        $result = [];
2125
+        foreach($stmt->fetchAll(\PDO::FETCH_ASSOC) as $row) {
2126
+            $result[] = [
2127
+                'calendardata' => $row['calendardata'],
2128
+                'uri'          => $row['uri'],
2129
+                'lastmodified' => $row['lastmodified'],
2130
+                'etag'         => '"' . $row['etag'] . '"',
2131
+                'size'         => (int)$row['size'],
2132
+            ];
2133
+        }
2134
+
2135
+        return $result;
2136
+    }
2137
+
2138
+    /**
2139
+     * Deletes a scheduling object from the inbox collection.
2140
+     *
2141
+     * @param string $principalUri
2142
+     * @param string $objectUri
2143
+     * @return void
2144
+     */
2145
+    function deleteSchedulingObject($principalUri, $objectUri) {
2146
+        $query = $this->db->getQueryBuilder();
2147
+        $query->delete('schedulingobjects')
2148
+                ->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
2149
+                ->andWhere($query->expr()->eq('uri', $query->createNamedParameter($objectUri)))
2150
+                ->execute();
2151
+    }
2152
+
2153
+    /**
2154
+     * Creates a new scheduling object. This should land in a users' inbox.
2155
+     *
2156
+     * @param string $principalUri
2157
+     * @param string $objectUri
2158
+     * @param string $objectData
2159
+     * @return void
2160
+     */
2161
+    function createSchedulingObject($principalUri, $objectUri, $objectData) {
2162
+        $query = $this->db->getQueryBuilder();
2163
+        $query->insert('schedulingobjects')
2164
+            ->values([
2165
+                'principaluri' => $query->createNamedParameter($principalUri),
2166
+                'calendardata' => $query->createNamedParameter($objectData, IQueryBuilder::PARAM_LOB),
2167
+                'uri' => $query->createNamedParameter($objectUri),
2168
+                'lastmodified' => $query->createNamedParameter(time()),
2169
+                'etag' => $query->createNamedParameter(md5($objectData)),
2170
+                'size' => $query->createNamedParameter(strlen($objectData))
2171
+            ])
2172
+            ->execute();
2173
+    }
2174
+
2175
+    /**
2176
+     * Adds a change record to the calendarchanges table.
2177
+     *
2178
+     * @param mixed $calendarId
2179
+     * @param string $objectUri
2180
+     * @param int $operation 1 = add, 2 = modify, 3 = delete.
2181
+     * @param int $calendarType
2182
+     * @return void
2183
+     */
2184
+    protected function addChange($calendarId, $objectUri, $operation, $calendarType=self::CALENDAR_TYPE_CALENDAR) {
2185
+        $table = $calendarType === self::CALENDAR_TYPE_CALENDAR ? 'calendars': 'calendarsubscriptions';
2186
+
2187
+        $query = $this->db->getQueryBuilder();
2188
+        $query->select('synctoken')
2189
+            ->from($table)
2190
+            ->where($query->expr()->eq('id', $query->createNamedParameter($calendarId)));
2191
+        $syncToken = (int)$query->execute()->fetchColumn();
2192
+
2193
+        $query = $this->db->getQueryBuilder();
2194
+        $query->insert('calendarchanges')
2195
+            ->values([
2196
+                'uri' => $query->createNamedParameter($objectUri),
2197
+                'synctoken' => $query->createNamedParameter($syncToken),
2198
+                'calendarid' => $query->createNamedParameter($calendarId),
2199
+                'operation' => $query->createNamedParameter($operation),
2200
+                'calendartype' => $query->createNamedParameter($calendarType),
2201
+            ])
2202
+            ->execute();
2203
+
2204
+        $stmt = $this->db->prepare("UPDATE `*PREFIX*$table` SET `synctoken` = `synctoken` + 1 WHERE `id` = ?");
2205
+        $stmt->execute([
2206
+            $calendarId
2207
+        ]);
2208
+
2209
+    }
2210
+
2211
+    /**
2212
+     * Parses some information from calendar objects, used for optimized
2213
+     * calendar-queries.
2214
+     *
2215
+     * Returns an array with the following keys:
2216
+     *   * etag - An md5 checksum of the object without the quotes.
2217
+     *   * size - Size of the object in bytes
2218
+     *   * componentType - VEVENT, VTODO or VJOURNAL
2219
+     *   * firstOccurence
2220
+     *   * lastOccurence
2221
+     *   * uid - value of the UID property
2222
+     *
2223
+     * @param string $calendarData
2224
+     * @return array
2225
+     */
2226
+    public function getDenormalizedData($calendarData) {
2227
+
2228
+        $vObject = Reader::read($calendarData);
2229
+        $componentType = null;
2230
+        $component = null;
2231
+        $firstOccurrence = null;
2232
+        $lastOccurrence = null;
2233
+        $uid = null;
2234
+        $classification = self::CLASSIFICATION_PUBLIC;
2235
+        foreach($vObject->getComponents() as $component) {
2236
+            if ($component->name!=='VTIMEZONE') {
2237
+                $componentType = $component->name;
2238
+                $uid = (string)$component->UID;
2239
+                break;
2240
+            }
2241
+        }
2242
+        if (!$componentType) {
2243
+            throw new \Sabre\DAV\Exception\BadRequest('Calendar objects must have a VJOURNAL, VEVENT or VTODO component');
2244
+        }
2245
+        if ($componentType === 'VEVENT' && $component->DTSTART) {
2246
+            $firstOccurrence = $component->DTSTART->getDateTime()->getTimeStamp();
2247
+            // Finding the last occurrence is a bit harder
2248
+            if (!isset($component->RRULE)) {
2249
+                if (isset($component->DTEND)) {
2250
+                    $lastOccurrence = $component->DTEND->getDateTime()->getTimeStamp();
2251
+                } elseif (isset($component->DURATION)) {
2252
+                    $endDate = clone $component->DTSTART->getDateTime();
2253
+                    $endDate->add(DateTimeParser::parse($component->DURATION->getValue()));
2254
+                    $lastOccurrence = $endDate->getTimeStamp();
2255
+                } elseif (!$component->DTSTART->hasTime()) {
2256
+                    $endDate = clone $component->DTSTART->getDateTime();
2257
+                    $endDate->modify('+1 day');
2258
+                    $lastOccurrence = $endDate->getTimeStamp();
2259
+                } else {
2260
+                    $lastOccurrence = $firstOccurrence;
2261
+                }
2262
+            } else {
2263
+                $it = new EventIterator($vObject, (string)$component->UID);
2264
+                $maxDate = new DateTime(self::MAX_DATE);
2265
+                if ($it->isInfinite()) {
2266
+                    $lastOccurrence = $maxDate->getTimestamp();
2267
+                } else {
2268
+                    $end = $it->getDtEnd();
2269
+                    while($it->valid() && $end < $maxDate) {
2270
+                        $end = $it->getDtEnd();
2271
+                        $it->next();
2272
+
2273
+                    }
2274
+                    $lastOccurrence = $end->getTimestamp();
2275
+                }
2276
+
2277
+            }
2278
+        }
2279
+
2280
+        if ($component->CLASS) {
2281
+            $classification = CalDavBackend::CLASSIFICATION_PRIVATE;
2282
+            switch ($component->CLASS->getValue()) {
2283
+                case 'PUBLIC':
2284
+                    $classification = CalDavBackend::CLASSIFICATION_PUBLIC;
2285
+                    break;
2286
+                case 'CONFIDENTIAL':
2287
+                    $classification = CalDavBackend::CLASSIFICATION_CONFIDENTIAL;
2288
+                    break;
2289
+            }
2290
+        }
2291
+        return [
2292
+            'etag' => md5($calendarData),
2293
+            'size' => strlen($calendarData),
2294
+            'componentType' => $componentType,
2295
+            'firstOccurence' => is_null($firstOccurrence) ? null : max(0, $firstOccurrence),
2296
+            'lastOccurence'  => $lastOccurrence,
2297
+            'uid' => $uid,
2298
+            'classification' => $classification
2299
+        ];
2300
+
2301
+    }
2302
+
2303
+    /**
2304
+     * @param $cardData
2305
+     * @return bool|string
2306
+     */
2307
+    private function readBlob($cardData) {
2308
+        if (is_resource($cardData)) {
2309
+            return stream_get_contents($cardData);
2310
+        }
2311
+
2312
+        return $cardData;
2313
+    }
2314
+
2315
+    /**
2316
+     * @param IShareable $shareable
2317
+     * @param array $add
2318
+     * @param array $remove
2319
+     */
2320
+    public function updateShares($shareable, $add, $remove) {
2321
+        $calendarId = $shareable->getResourceId();
2322
+        $this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::updateShares', new GenericEvent(
2323
+            '\OCA\DAV\CalDAV\CalDavBackend::updateShares',
2324
+            [
2325
+                'calendarId' => $calendarId,
2326
+                'calendarData' => $this->getCalendarById($calendarId),
2327
+                'shares' => $this->getShares($calendarId),
2328
+                'add' => $add,
2329
+                'remove' => $remove,
2330
+            ]));
2331
+        $this->calendarSharingBackend->updateShares($shareable, $add, $remove);
2332
+    }
2333
+
2334
+    /**
2335
+     * @param int $resourceId
2336
+     * @param int $calendarType
2337
+     * @return array
2338
+     */
2339
+    public function getShares($resourceId, $calendarType=self::CALENDAR_TYPE_CALENDAR) {
2340
+        return $this->calendarSharingBackend->getShares($resourceId);
2341
+    }
2342
+
2343
+    /**
2344
+     * @param boolean $value
2345
+     * @param \OCA\DAV\CalDAV\Calendar $calendar
2346
+     * @return string|null
2347
+     */
2348
+    public function setPublishStatus($value, $calendar) {
2349
+
2350
+        $calendarId = $calendar->getResourceId();
2351
+        $this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::publishCalendar', new GenericEvent(
2352
+            '\OCA\DAV\CalDAV\CalDavBackend::updateShares',
2353
+            [
2354
+                'calendarId' => $calendarId,
2355
+                'calendarData' => $this->getCalendarById($calendarId),
2356
+                'public' => $value,
2357
+            ]));
2358
+
2359
+        $query = $this->db->getQueryBuilder();
2360
+        if ($value) {
2361
+            $publicUri = $this->random->generate(16, ISecureRandom::CHAR_HUMAN_READABLE);
2362
+            $query->insert('dav_shares')
2363
+                ->values([
2364
+                    'principaluri' => $query->createNamedParameter($calendar->getPrincipalURI()),
2365
+                    'type' => $query->createNamedParameter('calendar'),
2366
+                    'access' => $query->createNamedParameter(self::ACCESS_PUBLIC),
2367
+                    'resourceid' => $query->createNamedParameter($calendar->getResourceId()),
2368
+                    'publicuri' => $query->createNamedParameter($publicUri)
2369
+                ]);
2370
+            $query->execute();
2371
+            return $publicUri;
2372
+        }
2373
+        $query->delete('dav_shares')
2374
+            ->where($query->expr()->eq('resourceid', $query->createNamedParameter($calendar->getResourceId())))
2375
+            ->andWhere($query->expr()->eq('access', $query->createNamedParameter(self::ACCESS_PUBLIC)));
2376
+        $query->execute();
2377
+        return null;
2378
+    }
2379
+
2380
+    /**
2381
+     * @param \OCA\DAV\CalDAV\Calendar $calendar
2382
+     * @return mixed
2383
+     */
2384
+    public function getPublishStatus($calendar) {
2385
+        $query = $this->db->getQueryBuilder();
2386
+        $result = $query->select('publicuri')
2387
+            ->from('dav_shares')
2388
+            ->where($query->expr()->eq('resourceid', $query->createNamedParameter($calendar->getResourceId())))
2389
+            ->andWhere($query->expr()->eq('access', $query->createNamedParameter(self::ACCESS_PUBLIC)))
2390
+            ->execute();
2391
+
2392
+        $row = $result->fetch();
2393
+        $result->closeCursor();
2394
+        return $row ? reset($row) : false;
2395
+    }
2396
+
2397
+    /**
2398
+     * @param int $resourceId
2399
+     * @param array $acl
2400
+     * @return array
2401
+     */
2402
+    public function applyShareAcl($resourceId, $acl) {
2403
+        return $this->calendarSharingBackend->applyShareAcl($resourceId, $acl);
2404
+    }
2405
+
2406
+
2407
+
2408
+    /**
2409
+     * update properties table
2410
+     *
2411
+     * @param int $calendarId
2412
+     * @param string $objectUri
2413
+     * @param string $calendarData
2414
+     * @param int $calendarType
2415
+     */
2416
+    public function updateProperties($calendarId, $objectUri, $calendarData, $calendarType=self::CALENDAR_TYPE_CALENDAR) {
2417
+        $objectId = $this->getCalendarObjectId($calendarId, $objectUri, $calendarType);
2418
+
2419
+        try {
2420
+            $vCalendar = $this->readCalendarData($calendarData);
2421
+        } catch (\Exception $ex) {
2422
+            return;
2423
+        }
2424
+
2425
+        $this->purgeProperties($calendarId, $objectId);
2426
+
2427
+        $query = $this->db->getQueryBuilder();
2428
+        $query->insert($this->dbObjectPropertiesTable)
2429
+            ->values(
2430
+                [
2431
+                    'calendarid' => $query->createNamedParameter($calendarId),
2432
+                    'calendartype' => $query->createNamedParameter($calendarType),
2433
+                    'objectid' => $query->createNamedParameter($objectId),
2434
+                    'name' => $query->createParameter('name'),
2435
+                    'parameter' => $query->createParameter('parameter'),
2436
+                    'value' => $query->createParameter('value'),
2437
+                ]
2438
+            );
2439
+
2440
+        $indexComponents = ['VEVENT', 'VJOURNAL', 'VTODO'];
2441
+        foreach ($vCalendar->getComponents() as $component) {
2442
+            if (!in_array($component->name, $indexComponents)) {
2443
+                continue;
2444
+            }
2445
+
2446
+            foreach ($component->children() as $property) {
2447
+                if (in_array($property->name, self::$indexProperties)) {
2448
+                    $value = $property->getValue();
2449
+                    // is this a shitty db?
2450
+                    if (!$this->db->supports4ByteText()) {
2451
+                        $value = preg_replace('/[\x{10000}-\x{10FFFF}]/u', "\xEF\xBF\xBD", $value);
2452
+                    }
2453
+                    $value = mb_substr($value, 0, 254);
2454
+
2455
+                    $query->setParameter('name', $property->name);
2456
+                    $query->setParameter('parameter', null);
2457
+                    $query->setParameter('value', $value);
2458
+                    $query->execute();
2459
+                }
2460
+
2461
+                if (array_key_exists($property->name, self::$indexParameters)) {
2462
+                    $parameters = $property->parameters();
2463
+                    $indexedParametersForProperty = self::$indexParameters[$property->name];
2464
+
2465
+                    foreach ($parameters as $key => $value) {
2466
+                        if (in_array($key, $indexedParametersForProperty)) {
2467
+                            // is this a shitty db?
2468
+                            if ($this->db->supports4ByteText()) {
2469
+                                $value = preg_replace('/[\x{10000}-\x{10FFFF}]/u', "\xEF\xBF\xBD", $value);
2470
+                            }
2471
+
2472
+                            $query->setParameter('name', $property->name);
2473
+                            $query->setParameter('parameter', mb_substr($key, 0, 254));
2474
+                            $query->setParameter('value', mb_substr($value, 0, 254));
2475
+                            $query->execute();
2476
+                        }
2477
+                    }
2478
+                }
2479
+            }
2480
+        }
2481
+    }
2482
+
2483
+    /**
2484
+     * deletes all birthday calendars
2485
+     */
2486
+    public function deleteAllBirthdayCalendars() {
2487
+        $query = $this->db->getQueryBuilder();
2488
+        $result = $query->select(['id'])->from('calendars')
2489
+            ->where($query->expr()->eq('uri', $query->createNamedParameter(BirthdayService::BIRTHDAY_CALENDAR_URI)))
2490
+            ->execute();
2491
+
2492
+        $ids = $result->fetchAll();
2493
+        foreach($ids as $id) {
2494
+            $this->deleteCalendar($id['id']);
2495
+        }
2496
+    }
2497
+
2498
+    /**
2499
+     * @param $subscriptionId
2500
+     */
2501
+    public function purgeAllCachedEventsForSubscription($subscriptionId) {
2502
+        $query = $this->db->getQueryBuilder();
2503
+        $query->select('uri')
2504
+            ->from('calendarobjects')
2505
+            ->where($query->expr()->eq('calendarid', $query->createNamedParameter($subscriptionId)))
2506
+            ->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)));
2507
+        $stmt = $query->execute();
2508
+
2509
+        $uris = [];
2510
+        foreach($stmt->fetchAll(\PDO::FETCH_ASSOC) as $row) {
2511
+            $uris[] = $row['uri'];
2512
+        }
2513
+        $stmt->closeCursor();
2514
+
2515
+        $query = $this->db->getQueryBuilder();
2516
+        $query->delete('calendarobjects')
2517
+            ->where($query->expr()->eq('calendarid', $query->createNamedParameter($subscriptionId)))
2518
+            ->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)))
2519
+            ->execute();
2520
+
2521
+        $query->delete('calendarchanges')
2522
+            ->where($query->expr()->eq('calendarid', $query->createNamedParameter($subscriptionId)))
2523
+            ->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)))
2524
+            ->execute();
2525
+
2526
+        $query->delete($this->dbObjectPropertiesTable)
2527
+            ->where($query->expr()->eq('calendarid', $query->createNamedParameter($subscriptionId)))
2528
+            ->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)))
2529
+            ->execute();
2530
+
2531
+        foreach($uris as $uri) {
2532
+            $this->addChange($subscriptionId, $uri, 3, self::CALENDAR_TYPE_SUBSCRIPTION);
2533
+        }
2534
+    }
2535
+
2536
+    /**
2537
+     * Move a calendar from one user to another
2538
+     *
2539
+     * @param string $uriName
2540
+     * @param string $uriOrigin
2541
+     * @param string $uriDestination
2542
+     */
2543
+    public function moveCalendar($uriName, $uriOrigin, $uriDestination)
2544
+    {
2545
+        $query = $this->db->getQueryBuilder();
2546
+        $query->update('calendars')
2547
+            ->set('principaluri', $query->createNamedParameter($uriDestination))
2548
+            ->where($query->expr()->eq('principaluri', $query->createNamedParameter($uriOrigin)))
2549
+            ->andWhere($query->expr()->eq('uri', $query->createNamedParameter($uriName)))
2550
+            ->execute();
2551
+    }
2552
+
2553
+    /**
2554
+     * read VCalendar data into a VCalendar object
2555
+     *
2556
+     * @param string $objectData
2557
+     * @return VCalendar
2558
+     */
2559
+    protected function readCalendarData($objectData) {
2560
+        return Reader::read($objectData);
2561
+    }
2562
+
2563
+    /**
2564
+     * delete all properties from a given calendar object
2565
+     *
2566
+     * @param int $calendarId
2567
+     * @param int $objectId
2568
+     */
2569
+    protected function purgeProperties($calendarId, $objectId) {
2570
+        $query = $this->db->getQueryBuilder();
2571
+        $query->delete($this->dbObjectPropertiesTable)
2572
+            ->where($query->expr()->eq('objectid', $query->createNamedParameter($objectId)))
2573
+            ->andWhere($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)));
2574
+        $query->execute();
2575
+    }
2576
+
2577
+    /**
2578
+     * get ID from a given calendar object
2579
+     *
2580
+     * @param int $calendarId
2581
+     * @param string $uri
2582
+     * @param int $calendarType
2583
+     * @return int
2584
+     */
2585
+    protected function getCalendarObjectId($calendarId, $uri, $calendarType):int {
2586
+        $query = $this->db->getQueryBuilder();
2587
+        $query->select('id')
2588
+            ->from('calendarobjects')
2589
+            ->where($query->expr()->eq('uri', $query->createNamedParameter($uri)))
2590
+            ->andWhere($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)))
2591
+            ->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter($calendarType)));
2592
+
2593
+        $result = $query->execute();
2594
+        $objectIds = $result->fetch();
2595
+        $result->closeCursor();
2596
+
2597
+        if (!isset($objectIds['id'])) {
2598
+            throw new \InvalidArgumentException('Calendarobject does not exists: ' . $uri);
2599
+        }
2600
+
2601
+        return (int)$objectIds['id'];
2602
+    }
2603
+
2604
+    /**
2605
+     * return legacy endpoint principal name to new principal name
2606
+     *
2607
+     * @param $principalUri
2608
+     * @param $toV2
2609
+     * @return string
2610
+     */
2611
+    private function convertPrincipal($principalUri, $toV2) {
2612
+        if ($this->principalBackend->getPrincipalPrefix() === 'principals') {
2613
+            list(, $name) = Uri\split($principalUri);
2614
+            if ($toV2 === true) {
2615
+                return "principals/users/$name";
2616
+            }
2617
+            return "principals/$name";
2618
+        }
2619
+        return $principalUri;
2620
+    }
2621
+
2622
+    /**
2623
+     * adds information about an owner to the calendar data
2624
+     *
2625
+     * @param $calendarInfo
2626
+     */
2627
+    private function addOwnerPrincipal(&$calendarInfo) {
2628
+        $ownerPrincipalKey = '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal';
2629
+        $displaynameKey = '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_NEXTCLOUD . '}owner-displayname';
2630
+        if (isset($calendarInfo[$ownerPrincipalKey])) {
2631
+            $uri = $calendarInfo[$ownerPrincipalKey];
2632
+        } else {
2633
+            $uri = $calendarInfo['principaluri'];
2634
+        }
2635
+
2636
+        $principalInformation = $this->principalBackend->getPrincipalByPath($uri);
2637
+        if (isset($principalInformation['{DAV:}displayname'])) {
2638
+            $calendarInfo[$displaynameKey] = $principalInformation['{DAV:}displayname'];
2639
+        }
2640
+    }
2641 2641
 }
Please login to merge, or discard this patch.
Spacing   +157 added lines, -157 removed lines patch added patch discarded remove patch
@@ -226,7 +226,7 @@  discard block
 block discarded – undo
226 226
 			$query->andWhere($query->expr()->neq('uri', $query->createNamedParameter(BirthdayService::BIRTHDAY_CALENDAR_URI)));
227 227
 		}
228 228
 
229
-		return (int)$query->execute()->fetchColumn();
229
+		return (int) $query->execute()->fetchColumn();
230 230
 	}
231 231
 
232 232
 	/**
@@ -273,25 +273,25 @@  discard block
 block discarded – undo
273 273
 		$stmt = $query->execute();
274 274
 
275 275
 		$calendars = [];
276
-		while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
276
+		while ($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
277 277
 
278 278
 			$components = [];
279 279
 			if ($row['components']) {
280
-				$components = explode(',',$row['components']);
280
+				$components = explode(',', $row['components']);
281 281
 			}
282 282
 
283 283
 			$calendar = [
284 284
 				'id' => $row['id'],
285 285
 				'uri' => $row['uri'],
286 286
 				'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
287
-				'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
288
-				'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
289
-				'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
290
-				'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
291
-				'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($principalUri, !$this->legacyEndpoint),
287
+				'{'.Plugin::NS_CALENDARSERVER.'}getctag' => 'http://sabre.io/ns/sync/'.($row['synctoken'] ? $row['synctoken'] : '0'),
288
+				'{http://sabredav.org/ns}sync-token' => $row['synctoken'] ? $row['synctoken'] : '0',
289
+				'{'.Plugin::NS_CALDAV.'}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
290
+				'{'.Plugin::NS_CALDAV.'}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent'] ? 'transparent' : 'opaque'),
291
+				'{'.\OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD.'}owner-principal' => $this->convertPrincipal($principalUri, !$this->legacyEndpoint),
292 292
 			];
293 293
 
294
-			foreach($this->propertyMap as $xmlName=>$dbName) {
294
+			foreach ($this->propertyMap as $xmlName=>$dbName) {
295 295
 				$calendar[$xmlName] = $row[$dbName];
296 296
 			}
297 297
 
@@ -308,10 +308,10 @@  discard block
 block discarded – undo
308 308
 		$principals = $this->principalBackend->getGroupMembership($principalUriOriginal, true);
309 309
 		$principals = array_merge($principals, $this->principalBackend->getCircleMembership($principalUriOriginal));
310 310
 
311
-		$principals = array_map(function ($principal) {
311
+		$principals = array_map(function($principal) {
312 312
 			return urldecode($principal);
313 313
 		}, $principals);
314
-		$principals[]= $principalUri;
314
+		$principals[] = $principalUri;
315 315
 
316 316
 		$fields = array_values($this->propertyMap);
317 317
 		$fields[] = 'a.id';
@@ -331,8 +331,8 @@  discard block
 block discarded – undo
331 331
 			->setParameter('principaluri', $principals, \Doctrine\DBAL\Connection::PARAM_STR_ARRAY)
332 332
 			->execute();
333 333
 
334
-		$readOnlyPropertyName = '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}read-only';
335
-		while($row = $result->fetch()) {
334
+		$readOnlyPropertyName = '{'.\OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD.'}read-only';
335
+		while ($row = $result->fetch()) {
336 336
 			if ($row['principaluri'] === $principalUri) {
337 337
 				continue;
338 338
 			}
@@ -351,25 +351,25 @@  discard block
 block discarded – undo
351 351
 			}
352 352
 
353 353
 			list(, $name) = Uri\split($row['principaluri']);
354
-			$uri = $row['uri'] . '_shared_by_' . $name;
355
-			$row['displayname'] = $row['displayname'] . ' (' . $this->getUserDisplayName($name) . ')';
354
+			$uri = $row['uri'].'_shared_by_'.$name;
355
+			$row['displayname'] = $row['displayname'].' ('.$this->getUserDisplayName($name).')';
356 356
 			$components = [];
357 357
 			if ($row['components']) {
358
-				$components = explode(',',$row['components']);
358
+				$components = explode(',', $row['components']);
359 359
 			}
360 360
 			$calendar = [
361 361
 				'id' => $row['id'],
362 362
 				'uri' => $uri,
363 363
 				'principaluri' => $this->convertPrincipal($principalUri, !$this->legacyEndpoint),
364
-				'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
365
-				'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
366
-				'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
367
-				'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp('transparent'),
368
-				'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
364
+				'{'.Plugin::NS_CALENDARSERVER.'}getctag' => 'http://sabre.io/ns/sync/'.($row['synctoken'] ? $row['synctoken'] : '0'),
365
+				'{http://sabredav.org/ns}sync-token' => $row['synctoken'] ? $row['synctoken'] : '0',
366
+				'{'.Plugin::NS_CALDAV.'}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
367
+				'{'.Plugin::NS_CALDAV.'}schedule-calendar-transp' => new ScheduleCalendarTransp('transparent'),
368
+				'{'.\OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD.'}owner-principal' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
369 369
 				$readOnlyPropertyName => $readOnly,
370 370
 			];
371 371
 
372
-			foreach($this->propertyMap as $xmlName=>$dbName) {
372
+			foreach ($this->propertyMap as $xmlName=>$dbName) {
373 373
 				$calendar[$xmlName] = $row[$dbName];
374 374
 			}
375 375
 
@@ -402,21 +402,21 @@  discard block
 block discarded – undo
402 402
 			->orderBy('calendarorder', 'ASC');
403 403
 		$stmt = $query->execute();
404 404
 		$calendars = [];
405
-		while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
405
+		while ($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
406 406
 			$components = [];
407 407
 			if ($row['components']) {
408
-				$components = explode(',',$row['components']);
408
+				$components = explode(',', $row['components']);
409 409
 			}
410 410
 			$calendar = [
411 411
 				'id' => $row['id'],
412 412
 				'uri' => $row['uri'],
413 413
 				'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
414
-				'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
415
-				'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
416
-				'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
417
-				'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
414
+				'{'.Plugin::NS_CALENDARSERVER.'}getctag' => 'http://sabre.io/ns/sync/'.($row['synctoken'] ? $row['synctoken'] : '0'),
415
+				'{http://sabredav.org/ns}sync-token' => $row['synctoken'] ? $row['synctoken'] : '0',
416
+				'{'.Plugin::NS_CALDAV.'}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
417
+				'{'.Plugin::NS_CALDAV.'}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent'] ? 'transparent' : 'opaque'),
418 418
 			];
419
-			foreach($this->propertyMap as $xmlName=>$dbName) {
419
+			foreach ($this->propertyMap as $xmlName=>$dbName) {
420 420
 				$calendar[$xmlName] = $row[$dbName];
421 421
 			}
422 422
 
@@ -471,27 +471,27 @@  discard block
 block discarded – undo
471 471
 			->andWhere($query->expr()->eq('s.type', $query->createNamedParameter('calendar')))
472 472
 			->execute();
473 473
 
474
-		while($row = $result->fetch()) {
474
+		while ($row = $result->fetch()) {
475 475
 			list(, $name) = Uri\split($row['principaluri']);
476
-			$row['displayname'] = $row['displayname'] . "($name)";
476
+			$row['displayname'] = $row['displayname']."($name)";
477 477
 			$components = [];
478 478
 			if ($row['components']) {
479
-				$components = explode(',',$row['components']);
479
+				$components = explode(',', $row['components']);
480 480
 			}
481 481
 			$calendar = [
482 482
 				'id' => $row['id'],
483 483
 				'uri' => $row['publicuri'],
484 484
 				'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
485
-				'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
486
-				'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
487
-				'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
488
-				'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
489
-				'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($row['principaluri'], $this->legacyEndpoint),
490
-				'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}read-only' => (int)$row['access'] === Backend::ACCESS_READ,
491
-				'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}public' => (int)$row['access'] === self::ACCESS_PUBLIC,
485
+				'{'.Plugin::NS_CALENDARSERVER.'}getctag' => 'http://sabre.io/ns/sync/'.($row['synctoken'] ? $row['synctoken'] : '0'),
486
+				'{http://sabredav.org/ns}sync-token' => $row['synctoken'] ? $row['synctoken'] : '0',
487
+				'{'.Plugin::NS_CALDAV.'}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
488
+				'{'.Plugin::NS_CALDAV.'}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent'] ? 'transparent' : 'opaque'),
489
+				'{'.\OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD.'}owner-principal' => $this->convertPrincipal($row['principaluri'], $this->legacyEndpoint),
490
+				'{'.\OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD.'}read-only' => (int) $row['access'] === Backend::ACCESS_READ,
491
+				'{'.\OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD.'}public' => (int) $row['access'] === self::ACCESS_PUBLIC,
492 492
 			];
493 493
 
494
-			foreach($this->propertyMap as $xmlName=>$dbName) {
494
+			foreach ($this->propertyMap as $xmlName=>$dbName) {
495 495
 				$calendar[$xmlName] = $row[$dbName];
496 496
 			}
497 497
 
@@ -535,29 +535,29 @@  discard block
 block discarded – undo
535 535
 		$result->closeCursor();
536 536
 
537 537
 		if ($row === false) {
538
-			throw new NotFound('Node with name \'' . $uri . '\' could not be found');
538
+			throw new NotFound('Node with name \''.$uri.'\' could not be found');
539 539
 		}
540 540
 
541 541
 		list(, $name) = Uri\split($row['principaluri']);
542
-		$row['displayname'] = $row['displayname'] . ' ' . "($name)";
542
+		$row['displayname'] = $row['displayname'].' '."($name)";
543 543
 		$components = [];
544 544
 		if ($row['components']) {
545
-			$components = explode(',',$row['components']);
545
+			$components = explode(',', $row['components']);
546 546
 		}
547 547
 		$calendar = [
548 548
 			'id' => $row['id'],
549 549
 			'uri' => $row['publicuri'],
550 550
 			'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
551
-			'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
552
-			'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
553
-			'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
554
-			'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
555
-			'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
556
-			'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}read-only' => (int)$row['access'] === Backend::ACCESS_READ,
557
-			'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}public' => (int)$row['access'] === self::ACCESS_PUBLIC,
551
+			'{'.Plugin::NS_CALENDARSERVER.'}getctag' => 'http://sabre.io/ns/sync/'.($row['synctoken'] ? $row['synctoken'] : '0'),
552
+			'{http://sabredav.org/ns}sync-token' => $row['synctoken'] ? $row['synctoken'] : '0',
553
+			'{'.Plugin::NS_CALDAV.'}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
554
+			'{'.Plugin::NS_CALDAV.'}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent'] ? 'transparent' : 'opaque'),
555
+			'{'.\OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD.'}owner-principal' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
556
+			'{'.\OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD.'}read-only' => (int) $row['access'] === Backend::ACCESS_READ,
557
+			'{'.\OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD.'}public' => (int) $row['access'] === self::ACCESS_PUBLIC,
558 558
 		];
559 559
 
560
-		foreach($this->propertyMap as $xmlName=>$dbName) {
560
+		foreach ($this->propertyMap as $xmlName=>$dbName) {
561 561
 			$calendar[$xmlName] = $row[$dbName];
562 562
 		}
563 563
 
@@ -597,20 +597,20 @@  discard block
 block discarded – undo
597 597
 
598 598
 		$components = [];
599 599
 		if ($row['components']) {
600
-			$components = explode(',',$row['components']);
600
+			$components = explode(',', $row['components']);
601 601
 		}
602 602
 
603 603
 		$calendar = [
604 604
 			'id' => $row['id'],
605 605
 			'uri' => $row['uri'],
606 606
 			'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
607
-			'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
608
-			'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
609
-			'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
610
-			'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
607
+			'{'.Plugin::NS_CALENDARSERVER.'}getctag' => 'http://sabre.io/ns/sync/'.($row['synctoken'] ? $row['synctoken'] : '0'),
608
+			'{http://sabredav.org/ns}sync-token' => $row['synctoken'] ? $row['synctoken'] : '0',
609
+			'{'.Plugin::NS_CALDAV.'}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
610
+			'{'.Plugin::NS_CALDAV.'}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent'] ? 'transparent' : 'opaque'),
611 611
 		];
612 612
 
613
-		foreach($this->propertyMap as $xmlName=>$dbName) {
613
+		foreach ($this->propertyMap as $xmlName=>$dbName) {
614 614
 			$calendar[$xmlName] = $row[$dbName];
615 615
 		}
616 616
 
@@ -647,20 +647,20 @@  discard block
 block discarded – undo
647 647
 
648 648
 		$components = [];
649 649
 		if ($row['components']) {
650
-			$components = explode(',',$row['components']);
650
+			$components = explode(',', $row['components']);
651 651
 		}
652 652
 
653 653
 		$calendar = [
654 654
 			'id' => $row['id'],
655 655
 			'uri' => $row['uri'],
656 656
 			'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
657
-			'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
658
-			'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
659
-			'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
660
-			'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
657
+			'{'.Plugin::NS_CALENDARSERVER.'}getctag' => 'http://sabre.io/ns/sync/'.($row['synctoken'] ? $row['synctoken'] : '0'),
658
+			'{http://sabredav.org/ns}sync-token' => $row['synctoken'] ? $row['synctoken'] : '0',
659
+			'{'.Plugin::NS_CALDAV.'}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
660
+			'{'.Plugin::NS_CALDAV.'}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent'] ? 'transparent' : 'opaque'),
661 661
 		];
662 662
 
663
-		foreach($this->propertyMap as $xmlName=>$dbName) {
663
+		foreach ($this->propertyMap as $xmlName=>$dbName) {
664 664
 			$calendar[$xmlName] = $row[$dbName];
665 665
 		}
666 666
 
@@ -686,7 +686,7 @@  discard block
 block discarded – undo
686 686
 			->from('calendarsubscriptions')
687 687
 			->where($query->expr()->eq('id', $query->createNamedParameter($subscriptionId)))
688 688
 			->orderBy('calendarorder', 'asc');
689
-		$stmt =$query->execute();
689
+		$stmt = $query->execute();
690 690
 
691 691
 		$row = $stmt->fetch(\PDO::FETCH_ASSOC);
692 692
 		$stmt->closeCursor();
@@ -700,11 +700,11 @@  discard block
 block discarded – undo
700 700
 			'principaluri' => $row['principaluri'],
701 701
 			'source'       => $row['source'],
702 702
 			'lastmodified' => $row['lastmodified'],
703
-			'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet(['VTODO', 'VEVENT']),
704
-			'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
703
+			'{'.Plugin::NS_CALDAV.'}supported-calendar-component-set' => new SupportedCalendarComponentSet(['VTODO', 'VEVENT']),
704
+			'{http://sabredav.org/ns}sync-token' => $row['synctoken'] ? $row['synctoken'] : '0',
705 705
 		];
706 706
 
707
-		foreach($this->subscriptionPropertyMap as $xmlName=>$dbName) {
707
+		foreach ($this->subscriptionPropertyMap as $xmlName=>$dbName) {
708 708
 			if (!is_null($row[$dbName])) {
709 709
 				$subscription[$xmlName] = $row[$dbName];
710 710
 			}
@@ -739,21 +739,21 @@  discard block
 block discarded – undo
739 739
 		$sccs = '{urn:ietf:params:xml:ns:caldav}supported-calendar-component-set';
740 740
 		if (isset($properties[$sccs])) {
741 741
 			if (!($properties[$sccs] instanceof SupportedCalendarComponentSet)) {
742
-				throw new DAV\Exception('The ' . $sccs . ' property must be of type: \Sabre\CalDAV\Property\SupportedCalendarComponentSet');
742
+				throw new DAV\Exception('The '.$sccs.' property must be of type: \Sabre\CalDAV\Property\SupportedCalendarComponentSet');
743 743
 			}
744
-			$values['components'] = implode(',',$properties[$sccs]->getValue());
744
+			$values['components'] = implode(',', $properties[$sccs]->getValue());
745 745
 		} else if (isset($properties['components'])) {
746 746
 			// Allow to provide components internally without having
747 747
 			// to create a SupportedCalendarComponentSet object
748 748
 			$values['components'] = $properties['components'];
749 749
 		}
750 750
 
751
-		$transp = '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp';
751
+		$transp = '{'.Plugin::NS_CALDAV.'}schedule-calendar-transp';
752 752
 		if (isset($properties[$transp])) {
753 753
 			$values['transparent'] = (int) ($properties[$transp]->getValue() === 'transparent');
754 754
 		}
755 755
 
756
-		foreach($this->propertyMap as $xmlName=>$dbName) {
756
+		foreach ($this->propertyMap as $xmlName=>$dbName) {
757 757
 			if (isset($properties[$xmlName])) {
758 758
 				$values[$dbName] = $properties[$xmlName];
759 759
 			}
@@ -761,7 +761,7 @@  discard block
 block discarded – undo
761 761
 
762 762
 		$query = $this->db->getQueryBuilder();
763 763
 		$query->insert('calendars');
764
-		foreach($values as $column => $value) {
764
+		foreach ($values as $column => $value) {
765 765
 			$query->setValue($column, $query->createNamedParameter($value));
766 766
 		}
767 767
 		$query->execute();
@@ -795,17 +795,17 @@  discard block
 block discarded – undo
795 795
 	 */
796 796
 	function updateCalendar($calendarId, PropPatch $propPatch) {
797 797
 		$supportedProperties = array_keys($this->propertyMap);
798
-		$supportedProperties[] = '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp';
798
+		$supportedProperties[] = '{'.Plugin::NS_CALDAV.'}schedule-calendar-transp';
799 799
 
800 800
 		/**
801 801
 		 * @suppress SqlInjectionChecker
802 802
 		 */
803
-		$propPatch->handle($supportedProperties, function ($mutations) use ($calendarId) {
803
+		$propPatch->handle($supportedProperties, function($mutations) use ($calendarId) {
804 804
 			$newValues = [];
805 805
 			foreach ($mutations as $propertyName => $propertyValue) {
806 806
 
807 807
 				switch ($propertyName) {
808
-					case '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' :
808
+					case '{'.Plugin::NS_CALDAV.'}schedule-calendar-transp' :
809 809
 						$fieldName = 'transparent';
810 810
 						$newValues[$fieldName] = (int) ($propertyValue->getValue() === 'transparent');
811 811
 						break;
@@ -914,7 +914,7 @@  discard block
 block discarded – undo
914 914
 	 * @param int $calendarType
915 915
 	 * @return array
916 916
 	 */
917
-	public function getCalendarObjects($id, $calendarType=self::CALENDAR_TYPE_CALENDAR):array {
917
+	public function getCalendarObjects($id, $calendarType = self::CALENDAR_TYPE_CALENDAR):array {
918 918
 		$query = $this->db->getQueryBuilder();
919 919
 		$query->select(['id', 'uri', 'lastmodified', 'etag', 'calendarid', 'size', 'componenttype', 'classification'])
920 920
 			->from('calendarobjects')
@@ -923,16 +923,16 @@  discard block
 block discarded – undo
923 923
 		$stmt = $query->execute();
924 924
 
925 925
 		$result = [];
926
-		foreach($stmt->fetchAll(\PDO::FETCH_ASSOC) as $row) {
926
+		foreach ($stmt->fetchAll(\PDO::FETCH_ASSOC) as $row) {
927 927
 			$result[] = [
928 928
 				'id'           => $row['id'],
929 929
 				'uri'          => $row['uri'],
930 930
 				'lastmodified' => $row['lastmodified'],
931
-				'etag'         => '"' . $row['etag'] . '"',
931
+				'etag'         => '"'.$row['etag'].'"',
932 932
 				'calendarid'   => $row['calendarid'],
933
-				'size'         => (int)$row['size'],
933
+				'size'         => (int) $row['size'],
934 934
 				'component'    => strtolower($row['componenttype']),
935
-				'classification'=> (int)$row['classification']
935
+				'classification'=> (int) $row['classification']
936 936
 			];
937 937
 		}
938 938
 
@@ -956,7 +956,7 @@  discard block
 block discarded – undo
956 956
 	 * @param int $calendarType
957 957
 	 * @return array|null
958 958
 	 */
959
-	public function getCalendarObject($id, $objectUri, $calendarType=self::CALENDAR_TYPE_CALENDAR) {
959
+	public function getCalendarObject($id, $objectUri, $calendarType = self::CALENDAR_TYPE_CALENDAR) {
960 960
 		$query = $this->db->getQueryBuilder();
961 961
 		$query->select(['id', 'uri', 'lastmodified', 'etag', 'calendarid', 'size', 'calendardata', 'componenttype', 'classification'])
962 962
 			->from('calendarobjects')
@@ -966,7 +966,7 @@  discard block
 block discarded – undo
966 966
 		$stmt = $query->execute();
967 967
 		$row = $stmt->fetch(\PDO::FETCH_ASSOC);
968 968
 
969
-		if(!$row) {
969
+		if (!$row) {
970 970
 			return null;
971 971
 		}
972 972
 
@@ -974,12 +974,12 @@  discard block
 block discarded – undo
974 974
 			'id'            => $row['id'],
975 975
 			'uri'           => $row['uri'],
976 976
 			'lastmodified'  => $row['lastmodified'],
977
-			'etag'          => '"' . $row['etag'] . '"',
977
+			'etag'          => '"'.$row['etag'].'"',
978 978
 			'calendarid'    => $row['calendarid'],
979
-			'size'          => (int)$row['size'],
979
+			'size'          => (int) $row['size'],
980 980
 			'calendardata'  => $this->readBlob($row['calendardata']),
981 981
 			'component'     => strtolower($row['componenttype']),
982
-			'classification'=> (int)$row['classification']
982
+			'classification'=> (int) $row['classification']
983 983
 		];
984 984
 	}
985 985
 
@@ -996,7 +996,7 @@  discard block
 block discarded – undo
996 996
 	 * @param int $calendarType
997 997
 	 * @return array
998 998
 	 */
999
-	public function getMultipleCalendarObjects($id, array $uris, $calendarType=self::CALENDAR_TYPE_CALENDAR):array {
999
+	public function getMultipleCalendarObjects($id, array $uris, $calendarType = self::CALENDAR_TYPE_CALENDAR):array {
1000 1000
 		if (empty($uris)) {
1001 1001
 			return [];
1002 1002
 		}
@@ -1020,12 +1020,12 @@  discard block
 block discarded – undo
1020 1020
 					'id'           => $row['id'],
1021 1021
 					'uri'          => $row['uri'],
1022 1022
 					'lastmodified' => $row['lastmodified'],
1023
-					'etag'         => '"' . $row['etag'] . '"',
1023
+					'etag'         => '"'.$row['etag'].'"',
1024 1024
 					'calendarid'   => $row['calendarid'],
1025
-					'size'         => (int)$row['size'],
1025
+					'size'         => (int) $row['size'],
1026 1026
 					'calendardata' => $this->readBlob($row['calendardata']),
1027 1027
 					'component'    => strtolower($row['componenttype']),
1028
-					'classification' => (int)$row['classification']
1028
+					'classification' => (int) $row['classification']
1029 1029
 				];
1030 1030
 			}
1031 1031
 			$result->closeCursor();
@@ -1053,7 +1053,7 @@  discard block
 block discarded – undo
1053 1053
 	 * @param int $calendarType
1054 1054
 	 * @return string
1055 1055
 	 */
1056
-	function createCalendarObject($calendarId, $objectUri, $calendarData, $calendarType=self::CALENDAR_TYPE_CALENDAR) {
1056
+	function createCalendarObject($calendarId, $objectUri, $calendarData, $calendarType = self::CALENDAR_TYPE_CALENDAR) {
1057 1057
 		$extraData = $this->getDenormalizedData($calendarData);
1058 1058
 
1059 1059
 		$q = $this->db->getQueryBuilder();
@@ -1114,7 +1114,7 @@  discard block
 block discarded – undo
1114 1114
 		}
1115 1115
 		$this->addChange($calendarId, $objectUri, 1, $calendarType);
1116 1116
 
1117
-		return '"' . $extraData['etag'] . '"';
1117
+		return '"'.$extraData['etag'].'"';
1118 1118
 	}
1119 1119
 
1120 1120
 	/**
@@ -1136,7 +1136,7 @@  discard block
 block discarded – undo
1136 1136
 	 * @param int $calendarType
1137 1137
 	 * @return string
1138 1138
 	 */
1139
-	function updateCalendarObject($calendarId, $objectUri, $calendarData, $calendarType=self::CALENDAR_TYPE_CALENDAR) {
1139
+	function updateCalendarObject($calendarId, $objectUri, $calendarData, $calendarType = self::CALENDAR_TYPE_CALENDAR) {
1140 1140
 		$extraData = $this->getDenormalizedData($calendarData);
1141 1141
 		$query = $this->db->getQueryBuilder();
1142 1142
 		$query->update('calendarobjects')
@@ -1182,7 +1182,7 @@  discard block
 block discarded – undo
1182 1182
 		}
1183 1183
 		$this->addChange($calendarId, $objectUri, 2, $calendarType);
1184 1184
 
1185
-		return '"' . $extraData['etag'] . '"';
1185
+		return '"'.$extraData['etag'].'"';
1186 1186
 	}
1187 1187
 
1188 1188
 	/**
@@ -1212,7 +1212,7 @@  discard block
 block discarded – undo
1212 1212
 	 * @param int $calendarType
1213 1213
 	 * @return void
1214 1214
 	 */
1215
-	function deleteCalendarObject($calendarId, $objectUri, $calendarType=self::CALENDAR_TYPE_CALENDAR) {
1215
+	function deleteCalendarObject($calendarId, $objectUri, $calendarType = self::CALENDAR_TYPE_CALENDAR) {
1216 1216
 		$data = $this->getCalendarObject($calendarId, $objectUri, $calendarType);
1217 1217
 		if (is_array($data)) {
1218 1218
 			if ($calendarType === self::CALENDAR_TYPE_CALENDAR) {
@@ -1298,7 +1298,7 @@  discard block
 block discarded – undo
1298 1298
 	 * @param int $calendarType
1299 1299
 	 * @return array
1300 1300
 	 */
1301
-	public function calendarQuery($id, array $filters, $calendarType=self::CALENDAR_TYPE_CALENDAR):array {
1301
+	public function calendarQuery($id, array $filters, $calendarType = self::CALENDAR_TYPE_CALENDAR):array {
1302 1302
 		$componentType = null;
1303 1303
 		$requirePostFilter = true;
1304 1304
 		$timeRange = null;
@@ -1352,13 +1352,13 @@  discard block
 block discarded – undo
1352 1352
 		$stmt = $query->execute();
1353 1353
 
1354 1354
 		$result = [];
1355
-		while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1355
+		while ($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1356 1356
 			if ($requirePostFilter) {
1357 1357
 				// validateFilterForObject will parse the calendar data
1358 1358
 				// catch parsing errors
1359 1359
 				try {
1360 1360
 					$matches = $this->validateFilterForObject($row, $filters);
1361
-				} catch(ParseException $ex) {
1361
+				} catch (ParseException $ex) {
1362 1362
 					$this->logger->logException($ex, [
1363 1363
 						'app' => 'dav',
1364 1364
 						'message' => 'Caught parsing exception for calendar data. This usually indicates invalid calendar data. calendar-id:'.$id.' uri:'.$row['uri']
@@ -1393,14 +1393,14 @@  discard block
 block discarded – undo
1393 1393
 	 * @param integer|null $offset
1394 1394
 	 * @return array
1395 1395
 	 */
1396
-	public function calendarSearch($principalUri, array $filters, $limit=null, $offset=null) {
1396
+	public function calendarSearch($principalUri, array $filters, $limit = null, $offset = null) {
1397 1397
 		$calendars = $this->getCalendarsForUser($principalUri);
1398 1398
 		$ownCalendars = [];
1399 1399
 		$sharedCalendars = [];
1400 1400
 
1401 1401
 		$uriMapper = [];
1402 1402
 
1403
-		foreach($calendars as $calendar) {
1403
+		foreach ($calendars as $calendar) {
1404 1404
 			if ($calendar['{http://owncloud.org/ns}owner-principal'] === $principalUri) {
1405 1405
 				$ownCalendars[] = $calendar['id'];
1406 1406
 			} else {
@@ -1415,14 +1415,14 @@  discard block
 block discarded – undo
1415 1415
 		$query = $this->db->getQueryBuilder();
1416 1416
 		// Calendar id expressions
1417 1417
 		$calendarExpressions = [];
1418
-		foreach($ownCalendars as $id) {
1418
+		foreach ($ownCalendars as $id) {
1419 1419
 			$calendarExpressions[] = $query->expr()->andX(
1420 1420
 				$query->expr()->eq('c.calendarid',
1421 1421
 					$query->createNamedParameter($id)),
1422 1422
 				$query->expr()->eq('c.calendartype',
1423 1423
 						$query->createNamedParameter(self::CALENDAR_TYPE_CALENDAR)));
1424 1424
 		}
1425
-		foreach($sharedCalendars as $id) {
1425
+		foreach ($sharedCalendars as $id) {
1426 1426
 			$calendarExpressions[] = $query->expr()->andX(
1427 1427
 				$query->expr()->eq('c.calendarid',
1428 1428
 					$query->createNamedParameter($id)),
@@ -1440,7 +1440,7 @@  discard block
 block discarded – undo
1440 1440
 
1441 1441
 		// Component expressions
1442 1442
 		$compExpressions = [];
1443
-		foreach($filters['comps'] as $comp) {
1443
+		foreach ($filters['comps'] as $comp) {
1444 1444
 			$compExpressions[] = $query->expr()
1445 1445
 				->eq('c.componenttype', $query->createNamedParameter($comp));
1446 1446
 		}
@@ -1459,13 +1459,13 @@  discard block
 block discarded – undo
1459 1459
 		}
1460 1460
 
1461 1461
 		$propParamExpressions = [];
1462
-		foreach($filters['props'] as $prop) {
1462
+		foreach ($filters['props'] as $prop) {
1463 1463
 			$propParamExpressions[] = $query->expr()->andX(
1464 1464
 				$query->expr()->eq('i.name', $query->createNamedParameter($prop)),
1465 1465
 				$query->expr()->isNull('i.parameter')
1466 1466
 			);
1467 1467
 		}
1468
-		foreach($filters['params'] as $param) {
1468
+		foreach ($filters['params'] as $param) {
1469 1469
 			$propParamExpressions[] = $query->expr()->andX(
1470 1470
 				$query->expr()->eq('i.name', $query->createNamedParameter($param['property'])),
1471 1471
 				$query->expr()->eq('i.parameter', $query->createNamedParameter($param['parameter']))
@@ -1497,8 +1497,8 @@  discard block
 block discarded – undo
1497 1497
 		$stmt = $query->execute();
1498 1498
 
1499 1499
 		$result = [];
1500
-		while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1501
-			$path = $uriMapper[$row['calendarid']] . '/' . $row['uri'];
1500
+		while ($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1501
+			$path = $uriMapper[$row['calendarid']].'/'.$row['uri'];
1502 1502
 			if (!in_array($path, $result)) {
1503 1503
 				$result[] = $path;
1504 1504
 			}
@@ -1538,7 +1538,7 @@  discard block
 block discarded – undo
1538 1538
 		}
1539 1539
 
1540 1540
 		$or = $innerQuery->expr()->orX();
1541
-		foreach($searchProperties as $searchProperty) {
1541
+		foreach ($searchProperties as $searchProperty) {
1542 1542
 			$or->add($innerQuery->expr()->eq('op.name',
1543 1543
 				$outerQuery->createNamedParameter($searchProperty)));
1544 1544
 		}
@@ -1546,8 +1546,8 @@  discard block
 block discarded – undo
1546 1546
 
1547 1547
 		if ($pattern !== '') {
1548 1548
 			$innerQuery->andWhere($innerQuery->expr()->iLike('op.value',
1549
-				$outerQuery->createNamedParameter('%' .
1550
-					$this->db->escapeLikeParameter($pattern) . '%')));
1549
+				$outerQuery->createNamedParameter('%'.
1550
+					$this->db->escapeLikeParameter($pattern).'%')));
1551 1551
 		}
1552 1552
 
1553 1553
 		$outerQuery->select('c.id', 'c.calendardata', 'c.componenttype', 'c.uid', 'c.uri')
@@ -1567,7 +1567,7 @@  discard block
 block discarded – undo
1567 1567
 
1568 1568
 		if (isset($options['types'])) {
1569 1569
 			$or = $outerQuery->expr()->orX();
1570
-			foreach($options['types'] as $type) {
1570
+			foreach ($options['types'] as $type) {
1571 1571
 				$or->add($outerQuery->expr()->eq('componenttype',
1572 1572
 					$outerQuery->createNamedParameter($type)));
1573 1573
 			}
@@ -1587,12 +1587,12 @@  discard block
 block discarded – undo
1587 1587
 		$result = $outerQuery->execute();
1588 1588
 		$calendarObjects = $result->fetchAll();
1589 1589
 
1590
-		return array_map(function ($o) {
1590
+		return array_map(function($o) {
1591 1591
 			$calendarData = Reader::read($o['calendardata']);
1592 1592
 			$comps = $calendarData->getComponents();
1593 1593
 			$objects = [];
1594 1594
 			$timezones = [];
1595
-			foreach($comps as $comp) {
1595
+			foreach ($comps as $comp) {
1596 1596
 				if ($comp instanceof VTimeZone) {
1597 1597
 					$timezones[] = $comp;
1598 1598
 				} else {
@@ -1605,10 +1605,10 @@  discard block
 block discarded – undo
1605 1605
 				'type' => $o['componenttype'],
1606 1606
 				'uid' => $o['uid'],
1607 1607
 				'uri' => $o['uri'],
1608
-				'objects' => array_map(function ($c) {
1608
+				'objects' => array_map(function($c) {
1609 1609
 					return $this->transformSearchData($c);
1610 1610
 				}, $objects),
1611
-				'timezones' => array_map(function ($c) {
1611
+				'timezones' => array_map(function($c) {
1612 1612
 					return $this->transformSearchData($c);
1613 1613
 				}, $timezones),
1614 1614
 			];
@@ -1624,12 +1624,12 @@  discard block
 block discarded – undo
1624 1624
 		/** @var Component[] $subComponents */
1625 1625
 		$subComponents = $comp->getComponents();
1626 1626
 		/** @var Property[] $properties */
1627
-		$properties = array_filter($comp->children(), function ($c) {
1627
+		$properties = array_filter($comp->children(), function($c) {
1628 1628
 			return $c instanceof Property;
1629 1629
 		});
1630 1630
 		$validationRules = $comp->getValidationRules();
1631 1631
 
1632
-		foreach($subComponents as $subComponent) {
1632
+		foreach ($subComponents as $subComponent) {
1633 1633
 			$name = $subComponent->name;
1634 1634
 			if (!isset($data[$name])) {
1635 1635
 				$data[$name] = [];
@@ -1637,7 +1637,7 @@  discard block
 block discarded – undo
1637 1637
 			$data[$name][] = $this->transformSearchData($subComponent);
1638 1638
 		}
1639 1639
 
1640
-		foreach($properties as $property) {
1640
+		foreach ($properties as $property) {
1641 1641
 			$name = $property->name;
1642 1642
 			if (!isset($validationRules[$name])) {
1643 1643
 				$validationRules[$name] = '*';
@@ -1708,7 +1708,7 @@  discard block
 block discarded – undo
1708 1708
 		$stmt = $query->execute();
1709 1709
 
1710 1710
 		if ($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1711
-			return $row['calendaruri'] . '/' . $row['objecturi'];
1711
+			return $row['calendaruri'].'/'.$row['objecturi'];
1712 1712
 		}
1713 1713
 
1714 1714
 		return null;
@@ -1771,10 +1771,10 @@  discard block
 block discarded – undo
1771 1771
 	 * @param int $calendarType
1772 1772
 	 * @return array
1773 1773
 	 */
1774
-	function getChangesForCalendar($calendarId, $syncToken, $syncLevel, $limit = null, $calendarType=self::CALENDAR_TYPE_CALENDAR) {
1774
+	function getChangesForCalendar($calendarId, $syncToken, $syncLevel, $limit = null, $calendarType = self::CALENDAR_TYPE_CALENDAR) {
1775 1775
 		// Current synctoken
1776 1776
 		$stmt = $this->db->prepare('SELECT `synctoken` FROM `*PREFIX*calendars` WHERE `id` = ?');
1777
-		$stmt->execute([ $calendarId ]);
1777
+		$stmt->execute([$calendarId]);
1778 1778
 		$currentToken = $stmt->fetchColumn(0);
1779 1779
 
1780 1780
 		if (is_null($currentToken)) {
@@ -1791,8 +1791,8 @@  discard block
 block discarded – undo
1791 1791
 		if ($syncToken) {
1792 1792
 
1793 1793
 			$query = "SELECT `uri`, `operation` FROM `*PREFIX*calendarchanges` WHERE `synctoken` >= ? AND `synctoken` < ? AND `calendarid` = ? AND `calendartype` = ? ORDER BY `synctoken`";
1794
-			if ($limit>0) {
1795
-				$query.= " LIMIT " . (int)$limit;
1794
+			if ($limit > 0) {
1795
+				$query .= " LIMIT ".(int) $limit;
1796 1796
 			}
1797 1797
 
1798 1798
 			// Fetching all changes
@@ -1803,15 +1803,15 @@  discard block
 block discarded – undo
1803 1803
 
1804 1804
 			// This loop ensures that any duplicates are overwritten, only the
1805 1805
 			// last change on a node is relevant.
1806
-			while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1806
+			while ($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1807 1807
 
1808 1808
 				$changes[$row['uri']] = $row['operation'];
1809 1809
 
1810 1810
 			}
1811 1811
 
1812
-			foreach($changes as $uri => $operation) {
1812
+			foreach ($changes as $uri => $operation) {
1813 1813
 
1814
-				switch($operation) {
1814
+				switch ($operation) {
1815 1815
 					case 1 :
1816 1816
 						$result['added'][] = $uri;
1817 1817
 						break;
@@ -1882,10 +1882,10 @@  discard block
 block discarded – undo
1882 1882
 			->from('calendarsubscriptions')
1883 1883
 			->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
1884 1884
 			->orderBy('calendarorder', 'asc');
1885
-		$stmt =$query->execute();
1885
+		$stmt = $query->execute();
1886 1886
 
1887 1887
 		$subscriptions = [];
1888
-		while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1888
+		while ($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1889 1889
 
1890 1890
 			$subscription = [
1891 1891
 				'id'           => $row['id'],
@@ -1894,11 +1894,11 @@  discard block
 block discarded – undo
1894 1894
 				'source'       => $row['source'],
1895 1895
 				'lastmodified' => $row['lastmodified'],
1896 1896
 
1897
-				'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet(['VTODO', 'VEVENT']),
1898
-				'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
1897
+				'{'.Plugin::NS_CALDAV.'}supported-calendar-component-set' => new SupportedCalendarComponentSet(['VTODO', 'VEVENT']),
1898
+				'{http://sabredav.org/ns}sync-token' => $row['synctoken'] ? $row['synctoken'] : '0',
1899 1899
 			];
1900 1900
 
1901
-			foreach($this->subscriptionPropertyMap as $xmlName=>$dbName) {
1901
+			foreach ($this->subscriptionPropertyMap as $xmlName=>$dbName) {
1902 1902
 				if (!is_null($row[$dbName])) {
1903 1903
 					$subscription[$xmlName] = $row[$dbName];
1904 1904
 				}
@@ -1937,7 +1937,7 @@  discard block
 block discarded – undo
1937 1937
 
1938 1938
 		$propertiesBoolean = ['striptodos', 'stripalarms', 'stripattachments'];
1939 1939
 
1940
-		foreach($this->subscriptionPropertyMap as $xmlName=>$dbName) {
1940
+		foreach ($this->subscriptionPropertyMap as $xmlName=>$dbName) {
1941 1941
 			if (array_key_exists($xmlName, $properties)) {
1942 1942
 					$values[$dbName] = $properties[$xmlName];
1943 1943
 					if (in_array($dbName, $propertiesBoolean)) {
@@ -1993,11 +1993,11 @@  discard block
 block discarded – undo
1993 1993
 		/**
1994 1994
 		 * @suppress SqlInjectionChecker
1995 1995
 		 */
1996
-		$propPatch->handle($supportedProperties, function ($mutations) use ($subscriptionId) {
1996
+		$propPatch->handle($supportedProperties, function($mutations) use ($subscriptionId) {
1997 1997
 
1998 1998
 			$newValues = [];
1999 1999
 
2000
-			foreach($mutations as $propertyName=>$propertyValue) {
2000
+			foreach ($mutations as $propertyName=>$propertyValue) {
2001 2001
 				if ($propertyName === '{http://calendarserver.org/ns/}source') {
2002 2002
 					$newValues['source'] = $propertyValue->getHref();
2003 2003
 				} else {
@@ -2009,7 +2009,7 @@  discard block
 block discarded – undo
2009 2009
 			$query = $this->db->getQueryBuilder();
2010 2010
 			$query->update('calendarsubscriptions')
2011 2011
 				->set('lastmodified', $query->createNamedParameter(time()));
2012
-			foreach($newValues as $fieldName=>$value) {
2012
+			foreach ($newValues as $fieldName=>$value) {
2013 2013
 				$query->set($fieldName, $query->createNamedParameter($value));
2014 2014
 			}
2015 2015
 			$query->where($query->expr()->eq('id', $query->createNamedParameter($subscriptionId)))
@@ -2090,7 +2090,7 @@  discard block
 block discarded – undo
2090 2090
 
2091 2091
 		$row = $stmt->fetch(\PDO::FETCH_ASSOC);
2092 2092
 
2093
-		if(!$row) {
2093
+		if (!$row) {
2094 2094
 			return null;
2095 2095
 		}
2096 2096
 
@@ -2098,8 +2098,8 @@  discard block
 block discarded – undo
2098 2098
 			'uri'          => $row['uri'],
2099 2099
 			'calendardata' => $row['calendardata'],
2100 2100
 			'lastmodified' => $row['lastmodified'],
2101
-			'etag'         => '"' . $row['etag'] . '"',
2102
-			'size'         => (int)$row['size'],
2101
+			'etag'         => '"'.$row['etag'].'"',
2102
+			'size'         => (int) $row['size'],
2103 2103
 		];
2104 2104
 	}
2105 2105
 
@@ -2122,13 +2122,13 @@  discard block
 block discarded – undo
2122 2122
 				->execute();
2123 2123
 
2124 2124
 		$result = [];
2125
-		foreach($stmt->fetchAll(\PDO::FETCH_ASSOC) as $row) {
2125
+		foreach ($stmt->fetchAll(\PDO::FETCH_ASSOC) as $row) {
2126 2126
 			$result[] = [
2127 2127
 				'calendardata' => $row['calendardata'],
2128 2128
 				'uri'          => $row['uri'],
2129 2129
 				'lastmodified' => $row['lastmodified'],
2130
-				'etag'         => '"' . $row['etag'] . '"',
2131
-				'size'         => (int)$row['size'],
2130
+				'etag'         => '"'.$row['etag'].'"',
2131
+				'size'         => (int) $row['size'],
2132 2132
 			];
2133 2133
 		}
2134 2134
 
@@ -2181,14 +2181,14 @@  discard block
 block discarded – undo
2181 2181
 	 * @param int $calendarType
2182 2182
 	 * @return void
2183 2183
 	 */
2184
-	protected function addChange($calendarId, $objectUri, $operation, $calendarType=self::CALENDAR_TYPE_CALENDAR) {
2185
-		$table = $calendarType === self::CALENDAR_TYPE_CALENDAR ? 'calendars': 'calendarsubscriptions';
2184
+	protected function addChange($calendarId, $objectUri, $operation, $calendarType = self::CALENDAR_TYPE_CALENDAR) {
2185
+		$table = $calendarType === self::CALENDAR_TYPE_CALENDAR ? 'calendars' : 'calendarsubscriptions';
2186 2186
 
2187 2187
 		$query = $this->db->getQueryBuilder();
2188 2188
 		$query->select('synctoken')
2189 2189
 			->from($table)
2190 2190
 			->where($query->expr()->eq('id', $query->createNamedParameter($calendarId)));
2191
-		$syncToken = (int)$query->execute()->fetchColumn();
2191
+		$syncToken = (int) $query->execute()->fetchColumn();
2192 2192
 
2193 2193
 		$query = $this->db->getQueryBuilder();
2194 2194
 		$query->insert('calendarchanges')
@@ -2232,10 +2232,10 @@  discard block
 block discarded – undo
2232 2232
 		$lastOccurrence = null;
2233 2233
 		$uid = null;
2234 2234
 		$classification = self::CLASSIFICATION_PUBLIC;
2235
-		foreach($vObject->getComponents() as $component) {
2236
-			if ($component->name!=='VTIMEZONE') {
2235
+		foreach ($vObject->getComponents() as $component) {
2236
+			if ($component->name !== 'VTIMEZONE') {
2237 2237
 				$componentType = $component->name;
2238
-				$uid = (string)$component->UID;
2238
+				$uid = (string) $component->UID;
2239 2239
 				break;
2240 2240
 			}
2241 2241
 		}
@@ -2260,13 +2260,13 @@  discard block
 block discarded – undo
2260 2260
 					$lastOccurrence = $firstOccurrence;
2261 2261
 				}
2262 2262
 			} else {
2263
-				$it = new EventIterator($vObject, (string)$component->UID);
2263
+				$it = new EventIterator($vObject, (string) $component->UID);
2264 2264
 				$maxDate = new DateTime(self::MAX_DATE);
2265 2265
 				if ($it->isInfinite()) {
2266 2266
 					$lastOccurrence = $maxDate->getTimestamp();
2267 2267
 				} else {
2268 2268
 					$end = $it->getDtEnd();
2269
-					while($it->valid() && $end < $maxDate) {
2269
+					while ($it->valid() && $end < $maxDate) {
2270 2270
 						$end = $it->getDtEnd();
2271 2271
 						$it->next();
2272 2272
 
@@ -2336,7 +2336,7 @@  discard block
 block discarded – undo
2336 2336
 	 * @param int $calendarType
2337 2337
 	 * @return array
2338 2338
 	 */
2339
-	public function getShares($resourceId, $calendarType=self::CALENDAR_TYPE_CALENDAR) {
2339
+	public function getShares($resourceId, $calendarType = self::CALENDAR_TYPE_CALENDAR) {
2340 2340
 		return $this->calendarSharingBackend->getShares($resourceId);
2341 2341
 	}
2342 2342
 
@@ -2413,7 +2413,7 @@  discard block
 block discarded – undo
2413 2413
 	 * @param string $calendarData
2414 2414
 	 * @param int $calendarType
2415 2415
 	 */
2416
-	public function updateProperties($calendarId, $objectUri, $calendarData, $calendarType=self::CALENDAR_TYPE_CALENDAR) {
2416
+	public function updateProperties($calendarId, $objectUri, $calendarData, $calendarType = self::CALENDAR_TYPE_CALENDAR) {
2417 2417
 		$objectId = $this->getCalendarObjectId($calendarId, $objectUri, $calendarType);
2418 2418
 
2419 2419
 		try {
@@ -2490,7 +2490,7 @@  discard block
 block discarded – undo
2490 2490
 			->execute();
2491 2491
 
2492 2492
 		$ids = $result->fetchAll();
2493
-		foreach($ids as $id) {
2493
+		foreach ($ids as $id) {
2494 2494
 			$this->deleteCalendar($id['id']);
2495 2495
 		}
2496 2496
 	}
@@ -2507,7 +2507,7 @@  discard block
 block discarded – undo
2507 2507
 		$stmt = $query->execute();
2508 2508
 
2509 2509
 		$uris = [];
2510
-		foreach($stmt->fetchAll(\PDO::FETCH_ASSOC) as $row) {
2510
+		foreach ($stmt->fetchAll(\PDO::FETCH_ASSOC) as $row) {
2511 2511
 			$uris[] = $row['uri'];
2512 2512
 		}
2513 2513
 		$stmt->closeCursor();
@@ -2528,7 +2528,7 @@  discard block
 block discarded – undo
2528 2528
 			->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)))
2529 2529
 			->execute();
2530 2530
 
2531
-		foreach($uris as $uri) {
2531
+		foreach ($uris as $uri) {
2532 2532
 			$this->addChange($subscriptionId, $uri, 3, self::CALENDAR_TYPE_SUBSCRIPTION);
2533 2533
 		}
2534 2534
 	}
@@ -2595,10 +2595,10 @@  discard block
 block discarded – undo
2595 2595
 		$result->closeCursor();
2596 2596
 
2597 2597
 		if (!isset($objectIds['id'])) {
2598
-			throw new \InvalidArgumentException('Calendarobject does not exists: ' . $uri);
2598
+			throw new \InvalidArgumentException('Calendarobject does not exists: '.$uri);
2599 2599
 		}
2600 2600
 
2601
-		return (int)$objectIds['id'];
2601
+		return (int) $objectIds['id'];
2602 2602
 	}
2603 2603
 
2604 2604
 	/**
@@ -2625,8 +2625,8 @@  discard block
 block discarded – undo
2625 2625
 	 * @param $calendarInfo
2626 2626
 	 */
2627 2627
 	private function addOwnerPrincipal(&$calendarInfo) {
2628
-		$ownerPrincipalKey = '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal';
2629
-		$displaynameKey = '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_NEXTCLOUD . '}owner-displayname';
2628
+		$ownerPrincipalKey = '{'.\OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD.'}owner-principal';
2629
+		$displaynameKey = '{'.\OCA\DAV\DAV\Sharing\Plugin::NS_NEXTCLOUD.'}owner-displayname';
2630 2630
 		if (isset($calendarInfo[$ownerPrincipalKey])) {
2631 2631
 			$uri = $calendarInfo[$ownerPrincipalKey];
2632 2632
 		} else {
Please login to merge, or discard this patch.
apps/dav/lib/CalDAV/BirthdayCalendar/EnablePlugin.php 1 patch
Indentation   +98 added lines, -98 removed lines patch added patch discarded remove patch
@@ -39,102 +39,102 @@
 block discarded – undo
39 39
  * @package OCA\DAV\CalDAV\BirthdayCalendar
40 40
  */
41 41
 class EnablePlugin extends ServerPlugin {
42
-	const NS_Nextcloud = 'http://nextcloud.com/ns';
43
-
44
-	/**
45
-	 * @var IConfig
46
-	 */
47
-	protected $config;
48
-
49
-	/**
50
-	 * @var BirthdayService
51
-	 */
52
-	protected $birthdayService;
53
-
54
-	/**
55
-	 * @var Server
56
-	 */
57
-	protected $server;
58
-
59
-	/**
60
-	 * PublishPlugin constructor.
61
-	 *
62
-	 * @param IConfig $config
63
-	 * @param BirthdayService $birthdayService
64
-	 */
65
-	public function __construct(IConfig $config, BirthdayService $birthdayService) {
66
-		$this->config = $config;
67
-		$this->birthdayService = $birthdayService;
68
-	}
69
-
70
-	/**
71
-	 * This method should return a list of server-features.
72
-	 *
73
-	 * This is for example 'versioning' and is added to the DAV: header
74
-	 * in an OPTIONS response.
75
-	 *
76
-	 * @return string[]
77
-	 */
78
-	public function getFeatures() {
79
-		return ['nc-enable-birthday-calendar'];
80
-	}
81
-
82
-	/**
83
-	 * Returns a plugin name.
84
-	 *
85
-	 * Using this name other plugins will be able to access other plugins
86
-	 * using Sabre\DAV\Server::getPlugin
87
-	 *
88
-	 * @return string
89
-	 */
90
-	public function getPluginName() {
91
-		return 'nc-enable-birthday-calendar';
92
-	}
93
-
94
-	/**
95
-	 * This initializes the plugin.
96
-	 *
97
-	 * This function is called by Sabre\DAV\Server, after
98
-	 * addPlugin is called.
99
-	 *
100
-	 * This method should set up the required event subscriptions.
101
-	 *
102
-	 * @param Server $server
103
-	 */
104
-	public function initialize(Server $server) {
105
-		$this->server = $server;
106
-
107
-		$this->server->on('method:POST', [$this, 'httpPost']);
108
-	}
109
-
110
-	/**
111
-	 * We intercept this to handle POST requests on calendar homes.
112
-	 *
113
-	 * @param RequestInterface $request
114
-	 * @param ResponseInterface $response
115
-	 *
116
-	 * @return bool|void
117
-	 */
118
-	public function httpPost(RequestInterface $request, ResponseInterface $response) {
119
-		$node = $this->server->tree->getNodeForPath($this->server->getRequestUri());
120
-		if (!($node instanceof CalendarHome)) {
121
-			return;
122
-		}
123
-
124
-		$requestBody = $request->getBodyAsString();
125
-		$this->server->xml->parse($requestBody, $request->getUrl(), $documentType);
126
-		if ($documentType !== '{'.self::NS_Nextcloud.'}enable-birthday-calendar') {
127
-			return;
128
-		}
129
-
130
-		$principalUri = $node->getOwner();
131
-		$userId = substr($principalUri, 17);
132
-
133
-		$this->config->setUserValue($userId, 'dav', 'generateBirthdayCalendar', 'yes');
134
-		$this->birthdayService->syncUser($userId);
135
-
136
-		$this->server->httpResponse->setStatus(204);
137
-
138
-		return false;
139
-	}
42
+    const NS_Nextcloud = 'http://nextcloud.com/ns';
43
+
44
+    /**
45
+     * @var IConfig
46
+     */
47
+    protected $config;
48
+
49
+    /**
50
+     * @var BirthdayService
51
+     */
52
+    protected $birthdayService;
53
+
54
+    /**
55
+     * @var Server
56
+     */
57
+    protected $server;
58
+
59
+    /**
60
+     * PublishPlugin constructor.
61
+     *
62
+     * @param IConfig $config
63
+     * @param BirthdayService $birthdayService
64
+     */
65
+    public function __construct(IConfig $config, BirthdayService $birthdayService) {
66
+        $this->config = $config;
67
+        $this->birthdayService = $birthdayService;
68
+    }
69
+
70
+    /**
71
+     * This method should return a list of server-features.
72
+     *
73
+     * This is for example 'versioning' and is added to the DAV: header
74
+     * in an OPTIONS response.
75
+     *
76
+     * @return string[]
77
+     */
78
+    public function getFeatures() {
79
+        return ['nc-enable-birthday-calendar'];
80
+    }
81
+
82
+    /**
83
+     * Returns a plugin name.
84
+     *
85
+     * Using this name other plugins will be able to access other plugins
86
+     * using Sabre\DAV\Server::getPlugin
87
+     *
88
+     * @return string
89
+     */
90
+    public function getPluginName() {
91
+        return 'nc-enable-birthday-calendar';
92
+    }
93
+
94
+    /**
95
+     * This initializes the plugin.
96
+     *
97
+     * This function is called by Sabre\DAV\Server, after
98
+     * addPlugin is called.
99
+     *
100
+     * This method should set up the required event subscriptions.
101
+     *
102
+     * @param Server $server
103
+     */
104
+    public function initialize(Server $server) {
105
+        $this->server = $server;
106
+
107
+        $this->server->on('method:POST', [$this, 'httpPost']);
108
+    }
109
+
110
+    /**
111
+     * We intercept this to handle POST requests on calendar homes.
112
+     *
113
+     * @param RequestInterface $request
114
+     * @param ResponseInterface $response
115
+     *
116
+     * @return bool|void
117
+     */
118
+    public function httpPost(RequestInterface $request, ResponseInterface $response) {
119
+        $node = $this->server->tree->getNodeForPath($this->server->getRequestUri());
120
+        if (!($node instanceof CalendarHome)) {
121
+            return;
122
+        }
123
+
124
+        $requestBody = $request->getBodyAsString();
125
+        $this->server->xml->parse($requestBody, $request->getUrl(), $documentType);
126
+        if ($documentType !== '{'.self::NS_Nextcloud.'}enable-birthday-calendar') {
127
+            return;
128
+        }
129
+
130
+        $principalUri = $node->getOwner();
131
+        $userId = substr($principalUri, 17);
132
+
133
+        $this->config->setUserValue($userId, 'dav', 'generateBirthdayCalendar', 'yes');
134
+        $this->birthdayService->syncUser($userId);
135
+
136
+        $this->server->httpResponse->setStatus(204);
137
+
138
+        return false;
139
+    }
140 140
 }
Please login to merge, or discard this patch.
apps/dav/lib/CalDAV/Schedule/Plugin.php 2 patches
Indentation   +471 added lines, -471 removed lines patch added patch discarded remove patch
@@ -50,151 +50,151 @@  discard block
 block discarded – undo
50 50
 
51 51
 class Plugin extends \Sabre\CalDAV\Schedule\Plugin {
52 52
 
53
-	/** @var ITip\Message[] */
54
-	private $schedulingResponses = [];
55
-
56
-	/** @var string|null */
57
-	private $pathOfCalendarObjectChange = null;
58
-
59
-	/**
60
-	 * Initializes the plugin
61
-	 *
62
-	 * @param Server $server
63
-	 * @return void
64
-	 */
65
-	function initialize(Server $server) {
66
-		parent::initialize($server);
67
-		$server->on('propFind', [$this, 'propFindDefaultCalendarUrl'], 90);
68
-		$server->on('afterWriteContent', [$this, 'dispatchSchedulingResponses']);
69
-		$server->on('afterCreateFile', [$this, 'dispatchSchedulingResponses']);
70
-	}
71
-
72
-	/**
73
-	 * This method handler is invoked during fetching of properties.
74
-	 *
75
-	 * We use this event to add calendar-auto-schedule-specific properties.
76
-	 *
77
-	 * @param PropFind $propFind
78
-	 * @param INode $node
79
-	 * @return void
80
-	 */
81
-	function propFind(PropFind $propFind, INode $node) {
82
-		if ($node instanceof IPrincipal) {
83
-			// overwrite Sabre/Dav's implementation
84
-			$propFind->handle('{' . self::NS_CALDAV . '}calendar-user-type', function () use ($node) {
85
-				if ($node instanceof IProperties) {
86
-					$calendarUserType = '{' . self::NS_CALDAV . '}calendar-user-type';
87
-					$props = $node->getProperties([$calendarUserType]);
88
-
89
-					if (isset($props[$calendarUserType])) {
90
-						return $props[$calendarUserType];
91
-					}
92
-				}
93
-
94
-				return 'INDIVIDUAL';
95
-			});
96
-		}
97
-
98
-		parent::propFind($propFind, $node);
99
-	}
100
-
101
-	/**
102
-	 * Returns a list of addresses that are associated with a principal.
103
-	 *
104
-	 * @param string $principal
105
-	 * @return array
106
-	 */
107
-	protected function getAddressesForPrincipal($principal) {
108
-		$result = parent::getAddressesForPrincipal($principal);
109
-
110
-		if ($result === null) {
111
-			$result = [];
112
-		}
113
-
114
-		return $result;
115
-	}
116
-
117
-	/**
118
-	 * @param RequestInterface $request
119
-	 * @param ResponseInterface $response
120
-	 * @param VCalendar $vCal
121
-	 * @param mixed $calendarPath
122
-	 * @param mixed $modified
123
-	 * @param mixed $isNew
124
-	 */
125
-	public function calendarObjectChange(RequestInterface $request, ResponseInterface $response, VCalendar $vCal, $calendarPath, &$modified, $isNew) {
126
-		// Save the first path we get as a calendar-object-change request
127
-		if (!$this->pathOfCalendarObjectChange) {
128
-			$this->pathOfCalendarObjectChange = $request->getPath();
129
-		}
130
-
131
-		parent::calendarObjectChange($request, $response, $vCal, $calendarPath, $modified, $isNew);
132
-	}
133
-
134
-	/**
135
-	 * @inheritDoc
136
-	 */
137
-	public function scheduleLocalDelivery(ITip\Message $iTipMessage):void {
138
-		parent::scheduleLocalDelivery($iTipMessage);
139
-
140
-		// We only care when the message was successfully delivered locally
141
-		if ($iTipMessage->scheduleStatus !== '1.2;Message delivered locally') {
142
-			return;
143
-		}
144
-
145
-		// We only care about request. reply and cancel are properly handled
146
-		// by parent::scheduleLocalDelivery already
147
-		if (strcasecmp($iTipMessage->method, 'REQUEST') !== 0) {
148
-			return;
149
-		}
150
-
151
-		// If parent::scheduleLocalDelivery set scheduleStatus to 1.2,
152
-		// it means that it was successfully delivered locally.
153
-		// Meaning that the ACL plugin is loaded and that a principial
154
-		// exists for the given recipient id, no need to double check
155
-		/** @var \Sabre\DAVACL\Plugin $aclPlugin */
156
-		$aclPlugin = $this->server->getPlugin('acl');
157
-		$principalUri = $aclPlugin->getPrincipalByUri($iTipMessage->recipient);
158
-		$calendarUserType = $this->getCalendarUserTypeForPrincipal($principalUri);
159
-		if (strcasecmp($calendarUserType, 'ROOM') !== 0 && strcasecmp($calendarUserType, 'RESOURCE') !== 0) {
160
-			return;
161
-		}
162
-
163
-		$attendee = $this->getCurrentAttendee($iTipMessage);
164
-		if (!$attendee) {
165
-			return;
166
-		}
167
-
168
-		// We only respond when a response was actually requested
169
-		$rsvp = $this->getAttendeeRSVP($attendee);
170
-		if (!$rsvp) {
171
-			return;
172
-		}
173
-
174
-		if (!isset($iTipMessage->message)) {
175
-			return;
176
-		}
177
-
178
-		$vcalendar = $iTipMessage->message;
179
-		if (!isset($vcalendar->VEVENT)) {
180
-			return;
181
-		}
182
-
183
-		/** @var Component $vevent */
184
-		$vevent = $vcalendar->VEVENT;
185
-
186
-		// We don't support autoresponses for recurrencing events for now
187
-		if (isset($vevent->RRULE) || isset($vevent->RDATE)) {
188
-			return;
189
-		}
190
-
191
-		$dtstart = $vevent->DTSTART;
192
-		$dtend =  $this->getDTEndFromVEvent($vevent);
193
-		$uid = $vevent->UID->getValue();
194
-		$sequence = isset($vevent->SEQUENCE) ? $vevent->SEQUENCE->getValue() : 0;
195
-		$recurrenceId = isset($vevent->{'RECURRENCE-ID'}) ? $vevent->{'RECURRENCE-ID'}->serialize() : '';
196
-
197
-		$message = <<<EOF
53
+    /** @var ITip\Message[] */
54
+    private $schedulingResponses = [];
55
+
56
+    /** @var string|null */
57
+    private $pathOfCalendarObjectChange = null;
58
+
59
+    /**
60
+     * Initializes the plugin
61
+     *
62
+     * @param Server $server
63
+     * @return void
64
+     */
65
+    function initialize(Server $server) {
66
+        parent::initialize($server);
67
+        $server->on('propFind', [$this, 'propFindDefaultCalendarUrl'], 90);
68
+        $server->on('afterWriteContent', [$this, 'dispatchSchedulingResponses']);
69
+        $server->on('afterCreateFile', [$this, 'dispatchSchedulingResponses']);
70
+    }
71
+
72
+    /**
73
+     * This method handler is invoked during fetching of properties.
74
+     *
75
+     * We use this event to add calendar-auto-schedule-specific properties.
76
+     *
77
+     * @param PropFind $propFind
78
+     * @param INode $node
79
+     * @return void
80
+     */
81
+    function propFind(PropFind $propFind, INode $node) {
82
+        if ($node instanceof IPrincipal) {
83
+            // overwrite Sabre/Dav's implementation
84
+            $propFind->handle('{' . self::NS_CALDAV . '}calendar-user-type', function () use ($node) {
85
+                if ($node instanceof IProperties) {
86
+                    $calendarUserType = '{' . self::NS_CALDAV . '}calendar-user-type';
87
+                    $props = $node->getProperties([$calendarUserType]);
88
+
89
+                    if (isset($props[$calendarUserType])) {
90
+                        return $props[$calendarUserType];
91
+                    }
92
+                }
93
+
94
+                return 'INDIVIDUAL';
95
+            });
96
+        }
97
+
98
+        parent::propFind($propFind, $node);
99
+    }
100
+
101
+    /**
102
+     * Returns a list of addresses that are associated with a principal.
103
+     *
104
+     * @param string $principal
105
+     * @return array
106
+     */
107
+    protected function getAddressesForPrincipal($principal) {
108
+        $result = parent::getAddressesForPrincipal($principal);
109
+
110
+        if ($result === null) {
111
+            $result = [];
112
+        }
113
+
114
+        return $result;
115
+    }
116
+
117
+    /**
118
+     * @param RequestInterface $request
119
+     * @param ResponseInterface $response
120
+     * @param VCalendar $vCal
121
+     * @param mixed $calendarPath
122
+     * @param mixed $modified
123
+     * @param mixed $isNew
124
+     */
125
+    public function calendarObjectChange(RequestInterface $request, ResponseInterface $response, VCalendar $vCal, $calendarPath, &$modified, $isNew) {
126
+        // Save the first path we get as a calendar-object-change request
127
+        if (!$this->pathOfCalendarObjectChange) {
128
+            $this->pathOfCalendarObjectChange = $request->getPath();
129
+        }
130
+
131
+        parent::calendarObjectChange($request, $response, $vCal, $calendarPath, $modified, $isNew);
132
+    }
133
+
134
+    /**
135
+     * @inheritDoc
136
+     */
137
+    public function scheduleLocalDelivery(ITip\Message $iTipMessage):void {
138
+        parent::scheduleLocalDelivery($iTipMessage);
139
+
140
+        // We only care when the message was successfully delivered locally
141
+        if ($iTipMessage->scheduleStatus !== '1.2;Message delivered locally') {
142
+            return;
143
+        }
144
+
145
+        // We only care about request. reply and cancel are properly handled
146
+        // by parent::scheduleLocalDelivery already
147
+        if (strcasecmp($iTipMessage->method, 'REQUEST') !== 0) {
148
+            return;
149
+        }
150
+
151
+        // If parent::scheduleLocalDelivery set scheduleStatus to 1.2,
152
+        // it means that it was successfully delivered locally.
153
+        // Meaning that the ACL plugin is loaded and that a principial
154
+        // exists for the given recipient id, no need to double check
155
+        /** @var \Sabre\DAVACL\Plugin $aclPlugin */
156
+        $aclPlugin = $this->server->getPlugin('acl');
157
+        $principalUri = $aclPlugin->getPrincipalByUri($iTipMessage->recipient);
158
+        $calendarUserType = $this->getCalendarUserTypeForPrincipal($principalUri);
159
+        if (strcasecmp($calendarUserType, 'ROOM') !== 0 && strcasecmp($calendarUserType, 'RESOURCE') !== 0) {
160
+            return;
161
+        }
162
+
163
+        $attendee = $this->getCurrentAttendee($iTipMessage);
164
+        if (!$attendee) {
165
+            return;
166
+        }
167
+
168
+        // We only respond when a response was actually requested
169
+        $rsvp = $this->getAttendeeRSVP($attendee);
170
+        if (!$rsvp) {
171
+            return;
172
+        }
173
+
174
+        if (!isset($iTipMessage->message)) {
175
+            return;
176
+        }
177
+
178
+        $vcalendar = $iTipMessage->message;
179
+        if (!isset($vcalendar->VEVENT)) {
180
+            return;
181
+        }
182
+
183
+        /** @var Component $vevent */
184
+        $vevent = $vcalendar->VEVENT;
185
+
186
+        // We don't support autoresponses for recurrencing events for now
187
+        if (isset($vevent->RRULE) || isset($vevent->RDATE)) {
188
+            return;
189
+        }
190
+
191
+        $dtstart = $vevent->DTSTART;
192
+        $dtend =  $this->getDTEndFromVEvent($vevent);
193
+        $uid = $vevent->UID->getValue();
194
+        $sequence = isset($vevent->SEQUENCE) ? $vevent->SEQUENCE->getValue() : 0;
195
+        $recurrenceId = isset($vevent->{'RECURRENCE-ID'}) ? $vevent->{'RECURRENCE-ID'}->serialize() : '';
196
+
197
+        $message = <<<EOF
198 198
 BEGIN:VCALENDAR
199 199
 PRODID:-//Nextcloud/Nextcloud CalDAV Server//EN
200 200
 METHOD:REPLY
@@ -209,330 +209,330 @@  discard block
 block discarded – undo
209 209
 END:VCALENDAR
210 210
 EOF;
211 211
 
212
-		if ($this->isAvailableAtTime($attendee->getValue(), $dtstart->getDateTime(), $dtend->getDateTime(), $uid)) {
213
-			$partStat = 'ACCEPTED';
214
-		} else {
215
-			$partStat = 'DECLINED';
216
-		}
217
-
218
-		$vObject = Reader::read(vsprintf($message, [
219
-			$partStat,
220
-			$iTipMessage->recipient,
221
-			$iTipMessage->sender,
222
-			$uid,
223
-			$sequence,
224
-			$recurrenceId
225
-		]));
226
-
227
-		$responseITipMessage = new ITip\Message();
228
-		$responseITipMessage->uid = $uid;
229
-		$responseITipMessage->component = 'VEVENT';
230
-		$responseITipMessage->method = 'REPLY';
231
-		$responseITipMessage->sequence = $sequence;
232
-		$responseITipMessage->sender = $iTipMessage->recipient;
233
-		$responseITipMessage->recipient = $iTipMessage->sender;
234
-		$responseITipMessage->message = $vObject;
235
-
236
-		// We can't dispatch them now already, because the organizers calendar-object
237
-		// was not yet created. Hence Sabre/DAV won't find a calendar-object, when we
238
-		// send our reply.
239
-		$this->schedulingResponses[] = $responseITipMessage;
240
-	}
241
-
242
-	/**
243
-	 * @param string $uri
244
-	 */
245
-	public function dispatchSchedulingResponses(string $uri):void {
246
-		if ($uri !== $this->pathOfCalendarObjectChange) {
247
-			return;
248
-		}
249
-
250
-		foreach ($this->schedulingResponses as $schedulingResponse) {
251
-			$this->scheduleLocalDelivery($schedulingResponse);
252
-		}
253
-	}
254
-
255
-	/**
256
-	 * Always use the personal calendar as target for scheduled events
257
-	 *
258
-	 * @param PropFind $propFind
259
-	 * @param INode $node
260
-	 * @return void
261
-	 */
262
-	function propFindDefaultCalendarUrl(PropFind $propFind, INode $node) {
263
-		if ($node instanceof IPrincipal) {
264
-			$propFind->handle('{' . self::NS_CALDAV . '}schedule-default-calendar-URL', function () use ($node) {
265
-				/** @var \OCA\DAV\CalDAV\Plugin $caldavPlugin */
266
-				$caldavPlugin = $this->server->getPlugin('caldav');
267
-				$principalUrl = $node->getPrincipalUrl();
268
-
269
-				$calendarHomePath = $caldavPlugin->getCalendarHomeForPrincipal($principalUrl);
270
-				if (!$calendarHomePath) {
271
-					return null;
272
-				}
273
-
274
-				if (strpos($principalUrl, 'principals/users') === 0) {
275
-					$uri = CalDavBackend::PERSONAL_CALENDAR_URI;
276
-					$displayname = CalDavBackend::PERSONAL_CALENDAR_NAME;
277
-				} elseif (strpos($principalUrl, 'principals/calendar-resources') === 0 ||
278
-						  strpos($principalUrl, 'principals/calendar-rooms') === 0) {
279
-					$uri = CalDavBackend::RESOURCE_BOOKING_CALENDAR_URI;
280
-					$displayname = CalDavBackend::RESOURCE_BOOKING_CALENDAR_NAME;
281
-				} else {
282
-					// How did we end up here?
283
-					// TODO - throw exception or just ignore?
284
-					return null;
285
-				}
286
-
287
-				/** @var CalendarHome $calendarHome */
288
-				$calendarHome = $this->server->tree->getNodeForPath($calendarHomePath);
289
-				if (!$calendarHome->childExists($uri)) {
290
-					$calendarHome->getCalDAVBackend()->createCalendar($principalUrl, $uri, [
291
-						'{DAV:}displayname' => $displayname,
292
-					]);
293
-				}
294
-
295
-				$result = $this->server->getPropertiesForPath($calendarHomePath . '/' . $uri, [], 1);
296
-				if (empty($result)) {
297
-					return null;
298
-				}
299
-
300
-				return new LocalHref($result[0]['href']);
301
-			});
302
-		}
303
-	}
304
-
305
-	/**
306
-	 * Returns a list of addresses that are associated with a principal.
307
-	 *
308
-	 * @param string $principal
309
-	 * @return string?
310
-	 */
311
-	protected function getCalendarUserTypeForPrincipal($principal):?string {
312
-		$calendarUserType = '{' . self::NS_CALDAV . '}calendar-user-type';
313
-		$properties = $this->server->getProperties(
314
-			$principal,
315
-			[$calendarUserType]
316
-		);
317
-
318
-		// If we can't find this information, we'll stop processing
319
-		if (!isset($properties[$calendarUserType])) {
320
-			return null;
321
-		}
322
-
323
-		return $properties[$calendarUserType];
324
-	}
325
-
326
-	/**
327
-	 * @param ITip\Message $iTipMessage
328
-	 * @return null|Property
329
-	 */
330
-	private function getCurrentAttendee(ITip\Message $iTipMessage):?Property {
331
-		/** @var VEvent $vevent */
332
-		$vevent = $iTipMessage->message->VEVENT;
333
-		$attendees = $vevent->select('ATTENDEE');
334
-		foreach ($attendees as $attendee) {
335
-			/** @var Property $attendee */
336
-			if (strcasecmp($attendee->getValue(), $iTipMessage->recipient) === 0) {
337
-				return $attendee;
338
-			}
339
-		}
340
-		return null;
341
-	}
342
-
343
-	/**
344
-	 * @param Property|null $attendee
345
-	 * @return bool
346
-	 */
347
-	private function getAttendeeRSVP(Property $attendee = null):bool {
348
-		if ($attendee !== null) {
349
-			$rsvp = $attendee->offsetGet('RSVP');
350
-			if (($rsvp instanceof Parameter) && (strcasecmp($rsvp->getValue(), 'TRUE') === 0)) {
351
-				return true;
352
-			}
353
-		}
354
-		// RFC 5545 3.2.17: default RSVP is false
355
-		return false;
356
-	}
357
-
358
-	/**
359
-	 * @param VEvent $vevent
360
-	 * @return Property\ICalendar\DateTime
361
-	 */
362
-	private function getDTEndFromVEvent(VEvent $vevent):Property\ICalendar\DateTime {
363
-		if (isset($vevent->DTEND)) {
364
-			return $vevent->DTEND;
365
-		}
366
-
367
-		if (isset($vevent->DURATION)) {
368
-			$isFloating = $vevent->DTSTART->isFloating();
369
-			/** @var Property\ICalendar\DateTime $end */
370
-			$end = clone $vevent->DTSTART;
371
-			$endDateTime = $end->getDateTime();
372
-			$endDateTime = $endDateTime->add(DateTimeParser::parse($vevent->DURATION->getValue()));
373
-			$end->setDateTime($endDateTime, $isFloating);
374
-			return $end;
375
-		}
376
-
377
-		if (!$vevent->DTSTART->hasTime()) {
378
-			$isFloating = $vevent->DTSTART->isFloating();
379
-			/** @var Property\ICalendar\DateTime $end */
380
-			$end = clone $vevent->DTSTART;
381
-			$endDateTime = $end->getDateTime();
382
-			$endDateTime = $endDateTime->modify('+1 day');
383
-			$end->setDateTime($endDateTime, $isFloating);
384
-			return $end;
385
-		}
386
-
387
-		return clone $vevent->DTSTART;
388
-	}
389
-
390
-	/**
391
-	 * @param string $email
392
-	 * @param \DateTimeInterface $start
393
-	 * @param \DateTimeInterface $end
394
-	 * @param string $ignoreUID
395
-	 * @return bool
396
-	 */
397
-	private function isAvailableAtTime(string $email, \DateTimeInterface $start, \DateTimeInterface $end, string $ignoreUID):bool {
398
-		// This method is heavily inspired by Sabre\CalDAV\Schedule\Plugin::scheduleLocalDelivery
399
-		// and Sabre\CalDAV\Schedule\Plugin::getFreeBusyForEmail
400
-
401
-		$aclPlugin = $this->server->getPlugin('acl');
402
-		$this->server->removeListener('propFind', [$aclPlugin, 'propFind']);
403
-
404
-		$result = $aclPlugin->principalSearch(
405
-			['{http://sabredav.org/ns}email-address' => $this->stripOffMailTo($email)],
406
-			[
407
-				'{DAV:}principal-URL',
408
-				'{' . self::NS_CALDAV . '}calendar-home-set',
409
-				'{' . self::NS_CALDAV . '}schedule-inbox-URL',
410
-				'{http://sabredav.org/ns}email-address',
411
-
412
-			]
413
-		);
414
-		$this->server->on('propFind', [$aclPlugin, 'propFind'], 20);
415
-
416
-
417
-		// Grabbing the calendar list
418
-		$objects = [];
419
-		$calendarTimeZone = new DateTimeZone('UTC');
420
-
421
-		$homePath = $result[0][200]['{' . self::NS_CALDAV . '}calendar-home-set']->getHref();
422
-		foreach ($this->server->tree->getNodeForPath($homePath)->getChildren() as $node) {
423
-			if (!$node instanceof ICalendar) {
424
-				continue;
425
-			}
426
-
427
-			// Getting the list of object uris within the time-range
428
-			$urls = $node->calendarQuery([
429
-				'name' => 'VCALENDAR',
430
-				'comp-filters' => [
431
-					[
432
-						'name' => 'VEVENT',
433
-						'is-not-defined' => false,
434
-						'time-range' => [
435
-							'start' => $start,
436
-							'end' => $end,
437
-						],
438
-						'comp-filters'   => [],
439
-						'prop-filters'   => [],
440
-					],
441
-					[
442
-						'name' => 'VEVENT',
443
-						'is-not-defined' => false,
444
-						'time-range' => null,
445
-						'comp-filters'   => [],
446
-						'prop-filters'   => [
447
-							[
448
-								'name'           => 'UID',
449
-								'is-not-defined' => false,
450
-								'time-range'     => null,
451
-								'text-match'     => [
452
-									'value' => $ignoreUID,
453
-									'negate-condition' => true,
454
-									'collation' => 'i;octet',
455
-								],
456
-								'param-filters' => [],
457
-							],
458
-						]
459
-					],
460
-				],
461
-				'prop-filters' => [],
462
-				'is-not-defined' => false,
463
-				'time-range' => null,
464
-			]);
465
-
466
-			foreach ($urls as $url) {
467
-				$objects[] = $node->getChild($url)->get();
468
-			}
469
-		}
470
-
471
-		$inboxProps = $this->server->getProperties(
472
-			$result[0][200]['{' . self::NS_CALDAV . '}schedule-inbox-URL']->getHref(),
473
-			['{' . self::NS_CALDAV . '}calendar-availability']
474
-		);
475
-
476
-		$vcalendar = new VCalendar();
477
-		$vcalendar->METHOD = 'REPLY';
478
-
479
-		$generator = new FreeBusyGenerator();
480
-		$generator->setObjects($objects);
481
-		$generator->setTimeRange($start, $end);
482
-		$generator->setBaseObject($vcalendar);
483
-		$generator->setTimeZone($calendarTimeZone);
484
-
485
-		if (isset($inboxProps['{' . self::NS_CALDAV . '}calendar-availability'])) {
486
-			$generator->setVAvailability(
487
-				Reader::read(
488
-					$inboxProps['{' . self::NS_CALDAV . '}calendar-availability']
489
-				)
490
-			);
491
-		}
492
-
493
-		$result = $generator->getResult();
494
-		if (!isset($result->VFREEBUSY)) {
495
-			return false;
496
-		}
497
-
498
-		/** @var Component $freeBusyComponent */
499
-		$freeBusyComponent = $result->VFREEBUSY;
500
-		$freeBusyProperties = $freeBusyComponent->select('FREEBUSY');
501
-		// If there is no Free-busy property at all, the time-range is empty and available
502
-		if (count($freeBusyProperties) === 0) {
503
-			return true;
504
-		}
505
-
506
-		// If more than one Free-Busy property was returned, it means that an event
507
-		// starts or ends inside this time-range, so it's not availabe and we return false
508
-		if (count($freeBusyProperties) > 1) {
509
-			return false;
510
-		}
511
-
512
-		/** @var Property $freeBusyProperty */
513
-		$freeBusyProperty = $freeBusyProperties[0];
514
-		if (!$freeBusyProperty->offsetExists('FBTYPE')) {
515
-			// If there is no FBTYPE, it means it's busy
516
-			return false;
517
-		}
518
-
519
-		$fbTypeParameter = $freeBusyProperty->offsetGet('FBTYPE');
520
-		if (!($fbTypeParameter instanceof Parameter)) {
521
-			return false;
522
-		}
523
-
524
-		return (strcasecmp($fbTypeParameter->getValue(), 'FREE') === 0);
525
-	}
526
-
527
-	/**
528
-	 * @param string $email
529
-	 * @return string
530
-	 */
531
-	private function stripOffMailTo(string $email): string {
532
-		if (stripos($email, 'mailto:')  === 0) {
533
-			return substr($email, 7);
534
-		}
535
-
536
-		return $email;
537
-	}
212
+        if ($this->isAvailableAtTime($attendee->getValue(), $dtstart->getDateTime(), $dtend->getDateTime(), $uid)) {
213
+            $partStat = 'ACCEPTED';
214
+        } else {
215
+            $partStat = 'DECLINED';
216
+        }
217
+
218
+        $vObject = Reader::read(vsprintf($message, [
219
+            $partStat,
220
+            $iTipMessage->recipient,
221
+            $iTipMessage->sender,
222
+            $uid,
223
+            $sequence,
224
+            $recurrenceId
225
+        ]));
226
+
227
+        $responseITipMessage = new ITip\Message();
228
+        $responseITipMessage->uid = $uid;
229
+        $responseITipMessage->component = 'VEVENT';
230
+        $responseITipMessage->method = 'REPLY';
231
+        $responseITipMessage->sequence = $sequence;
232
+        $responseITipMessage->sender = $iTipMessage->recipient;
233
+        $responseITipMessage->recipient = $iTipMessage->sender;
234
+        $responseITipMessage->message = $vObject;
235
+
236
+        // We can't dispatch them now already, because the organizers calendar-object
237
+        // was not yet created. Hence Sabre/DAV won't find a calendar-object, when we
238
+        // send our reply.
239
+        $this->schedulingResponses[] = $responseITipMessage;
240
+    }
241
+
242
+    /**
243
+     * @param string $uri
244
+     */
245
+    public function dispatchSchedulingResponses(string $uri):void {
246
+        if ($uri !== $this->pathOfCalendarObjectChange) {
247
+            return;
248
+        }
249
+
250
+        foreach ($this->schedulingResponses as $schedulingResponse) {
251
+            $this->scheduleLocalDelivery($schedulingResponse);
252
+        }
253
+    }
254
+
255
+    /**
256
+     * Always use the personal calendar as target for scheduled events
257
+     *
258
+     * @param PropFind $propFind
259
+     * @param INode $node
260
+     * @return void
261
+     */
262
+    function propFindDefaultCalendarUrl(PropFind $propFind, INode $node) {
263
+        if ($node instanceof IPrincipal) {
264
+            $propFind->handle('{' . self::NS_CALDAV . '}schedule-default-calendar-URL', function () use ($node) {
265
+                /** @var \OCA\DAV\CalDAV\Plugin $caldavPlugin */
266
+                $caldavPlugin = $this->server->getPlugin('caldav');
267
+                $principalUrl = $node->getPrincipalUrl();
268
+
269
+                $calendarHomePath = $caldavPlugin->getCalendarHomeForPrincipal($principalUrl);
270
+                if (!$calendarHomePath) {
271
+                    return null;
272
+                }
273
+
274
+                if (strpos($principalUrl, 'principals/users') === 0) {
275
+                    $uri = CalDavBackend::PERSONAL_CALENDAR_URI;
276
+                    $displayname = CalDavBackend::PERSONAL_CALENDAR_NAME;
277
+                } elseif (strpos($principalUrl, 'principals/calendar-resources') === 0 ||
278
+                          strpos($principalUrl, 'principals/calendar-rooms') === 0) {
279
+                    $uri = CalDavBackend::RESOURCE_BOOKING_CALENDAR_URI;
280
+                    $displayname = CalDavBackend::RESOURCE_BOOKING_CALENDAR_NAME;
281
+                } else {
282
+                    // How did we end up here?
283
+                    // TODO - throw exception or just ignore?
284
+                    return null;
285
+                }
286
+
287
+                /** @var CalendarHome $calendarHome */
288
+                $calendarHome = $this->server->tree->getNodeForPath($calendarHomePath);
289
+                if (!$calendarHome->childExists($uri)) {
290
+                    $calendarHome->getCalDAVBackend()->createCalendar($principalUrl, $uri, [
291
+                        '{DAV:}displayname' => $displayname,
292
+                    ]);
293
+                }
294
+
295
+                $result = $this->server->getPropertiesForPath($calendarHomePath . '/' . $uri, [], 1);
296
+                if (empty($result)) {
297
+                    return null;
298
+                }
299
+
300
+                return new LocalHref($result[0]['href']);
301
+            });
302
+        }
303
+    }
304
+
305
+    /**
306
+     * Returns a list of addresses that are associated with a principal.
307
+     *
308
+     * @param string $principal
309
+     * @return string?
310
+     */
311
+    protected function getCalendarUserTypeForPrincipal($principal):?string {
312
+        $calendarUserType = '{' . self::NS_CALDAV . '}calendar-user-type';
313
+        $properties = $this->server->getProperties(
314
+            $principal,
315
+            [$calendarUserType]
316
+        );
317
+
318
+        // If we can't find this information, we'll stop processing
319
+        if (!isset($properties[$calendarUserType])) {
320
+            return null;
321
+        }
322
+
323
+        return $properties[$calendarUserType];
324
+    }
325
+
326
+    /**
327
+     * @param ITip\Message $iTipMessage
328
+     * @return null|Property
329
+     */
330
+    private function getCurrentAttendee(ITip\Message $iTipMessage):?Property {
331
+        /** @var VEvent $vevent */
332
+        $vevent = $iTipMessage->message->VEVENT;
333
+        $attendees = $vevent->select('ATTENDEE');
334
+        foreach ($attendees as $attendee) {
335
+            /** @var Property $attendee */
336
+            if (strcasecmp($attendee->getValue(), $iTipMessage->recipient) === 0) {
337
+                return $attendee;
338
+            }
339
+        }
340
+        return null;
341
+    }
342
+
343
+    /**
344
+     * @param Property|null $attendee
345
+     * @return bool
346
+     */
347
+    private function getAttendeeRSVP(Property $attendee = null):bool {
348
+        if ($attendee !== null) {
349
+            $rsvp = $attendee->offsetGet('RSVP');
350
+            if (($rsvp instanceof Parameter) && (strcasecmp($rsvp->getValue(), 'TRUE') === 0)) {
351
+                return true;
352
+            }
353
+        }
354
+        // RFC 5545 3.2.17: default RSVP is false
355
+        return false;
356
+    }
357
+
358
+    /**
359
+     * @param VEvent $vevent
360
+     * @return Property\ICalendar\DateTime
361
+     */
362
+    private function getDTEndFromVEvent(VEvent $vevent):Property\ICalendar\DateTime {
363
+        if (isset($vevent->DTEND)) {
364
+            return $vevent->DTEND;
365
+        }
366
+
367
+        if (isset($vevent->DURATION)) {
368
+            $isFloating = $vevent->DTSTART->isFloating();
369
+            /** @var Property\ICalendar\DateTime $end */
370
+            $end = clone $vevent->DTSTART;
371
+            $endDateTime = $end->getDateTime();
372
+            $endDateTime = $endDateTime->add(DateTimeParser::parse($vevent->DURATION->getValue()));
373
+            $end->setDateTime($endDateTime, $isFloating);
374
+            return $end;
375
+        }
376
+
377
+        if (!$vevent->DTSTART->hasTime()) {
378
+            $isFloating = $vevent->DTSTART->isFloating();
379
+            /** @var Property\ICalendar\DateTime $end */
380
+            $end = clone $vevent->DTSTART;
381
+            $endDateTime = $end->getDateTime();
382
+            $endDateTime = $endDateTime->modify('+1 day');
383
+            $end->setDateTime($endDateTime, $isFloating);
384
+            return $end;
385
+        }
386
+
387
+        return clone $vevent->DTSTART;
388
+    }
389
+
390
+    /**
391
+     * @param string $email
392
+     * @param \DateTimeInterface $start
393
+     * @param \DateTimeInterface $end
394
+     * @param string $ignoreUID
395
+     * @return bool
396
+     */
397
+    private function isAvailableAtTime(string $email, \DateTimeInterface $start, \DateTimeInterface $end, string $ignoreUID):bool {
398
+        // This method is heavily inspired by Sabre\CalDAV\Schedule\Plugin::scheduleLocalDelivery
399
+        // and Sabre\CalDAV\Schedule\Plugin::getFreeBusyForEmail
400
+
401
+        $aclPlugin = $this->server->getPlugin('acl');
402
+        $this->server->removeListener('propFind', [$aclPlugin, 'propFind']);
403
+
404
+        $result = $aclPlugin->principalSearch(
405
+            ['{http://sabredav.org/ns}email-address' => $this->stripOffMailTo($email)],
406
+            [
407
+                '{DAV:}principal-URL',
408
+                '{' . self::NS_CALDAV . '}calendar-home-set',
409
+                '{' . self::NS_CALDAV . '}schedule-inbox-URL',
410
+                '{http://sabredav.org/ns}email-address',
411
+
412
+            ]
413
+        );
414
+        $this->server->on('propFind', [$aclPlugin, 'propFind'], 20);
415
+
416
+
417
+        // Grabbing the calendar list
418
+        $objects = [];
419
+        $calendarTimeZone = new DateTimeZone('UTC');
420
+
421
+        $homePath = $result[0][200]['{' . self::NS_CALDAV . '}calendar-home-set']->getHref();
422
+        foreach ($this->server->tree->getNodeForPath($homePath)->getChildren() as $node) {
423
+            if (!$node instanceof ICalendar) {
424
+                continue;
425
+            }
426
+
427
+            // Getting the list of object uris within the time-range
428
+            $urls = $node->calendarQuery([
429
+                'name' => 'VCALENDAR',
430
+                'comp-filters' => [
431
+                    [
432
+                        'name' => 'VEVENT',
433
+                        'is-not-defined' => false,
434
+                        'time-range' => [
435
+                            'start' => $start,
436
+                            'end' => $end,
437
+                        ],
438
+                        'comp-filters'   => [],
439
+                        'prop-filters'   => [],
440
+                    ],
441
+                    [
442
+                        'name' => 'VEVENT',
443
+                        'is-not-defined' => false,
444
+                        'time-range' => null,
445
+                        'comp-filters'   => [],
446
+                        'prop-filters'   => [
447
+                            [
448
+                                'name'           => 'UID',
449
+                                'is-not-defined' => false,
450
+                                'time-range'     => null,
451
+                                'text-match'     => [
452
+                                    'value' => $ignoreUID,
453
+                                    'negate-condition' => true,
454
+                                    'collation' => 'i;octet',
455
+                                ],
456
+                                'param-filters' => [],
457
+                            ],
458
+                        ]
459
+                    ],
460
+                ],
461
+                'prop-filters' => [],
462
+                'is-not-defined' => false,
463
+                'time-range' => null,
464
+            ]);
465
+
466
+            foreach ($urls as $url) {
467
+                $objects[] = $node->getChild($url)->get();
468
+            }
469
+        }
470
+
471
+        $inboxProps = $this->server->getProperties(
472
+            $result[0][200]['{' . self::NS_CALDAV . '}schedule-inbox-URL']->getHref(),
473
+            ['{' . self::NS_CALDAV . '}calendar-availability']
474
+        );
475
+
476
+        $vcalendar = new VCalendar();
477
+        $vcalendar->METHOD = 'REPLY';
478
+
479
+        $generator = new FreeBusyGenerator();
480
+        $generator->setObjects($objects);
481
+        $generator->setTimeRange($start, $end);
482
+        $generator->setBaseObject($vcalendar);
483
+        $generator->setTimeZone($calendarTimeZone);
484
+
485
+        if (isset($inboxProps['{' . self::NS_CALDAV . '}calendar-availability'])) {
486
+            $generator->setVAvailability(
487
+                Reader::read(
488
+                    $inboxProps['{' . self::NS_CALDAV . '}calendar-availability']
489
+                )
490
+            );
491
+        }
492
+
493
+        $result = $generator->getResult();
494
+        if (!isset($result->VFREEBUSY)) {
495
+            return false;
496
+        }
497
+
498
+        /** @var Component $freeBusyComponent */
499
+        $freeBusyComponent = $result->VFREEBUSY;
500
+        $freeBusyProperties = $freeBusyComponent->select('FREEBUSY');
501
+        // If there is no Free-busy property at all, the time-range is empty and available
502
+        if (count($freeBusyProperties) === 0) {
503
+            return true;
504
+        }
505
+
506
+        // If more than one Free-Busy property was returned, it means that an event
507
+        // starts or ends inside this time-range, so it's not availabe and we return false
508
+        if (count($freeBusyProperties) > 1) {
509
+            return false;
510
+        }
511
+
512
+        /** @var Property $freeBusyProperty */
513
+        $freeBusyProperty = $freeBusyProperties[0];
514
+        if (!$freeBusyProperty->offsetExists('FBTYPE')) {
515
+            // If there is no FBTYPE, it means it's busy
516
+            return false;
517
+        }
518
+
519
+        $fbTypeParameter = $freeBusyProperty->offsetGet('FBTYPE');
520
+        if (!($fbTypeParameter instanceof Parameter)) {
521
+            return false;
522
+        }
523
+
524
+        return (strcasecmp($fbTypeParameter->getValue(), 'FREE') === 0);
525
+    }
526
+
527
+    /**
528
+     * @param string $email
529
+     * @return string
530
+     */
531
+    private function stripOffMailTo(string $email): string {
532
+        if (stripos($email, 'mailto:')  === 0) {
533
+            return substr($email, 7);
534
+        }
535
+
536
+        return $email;
537
+    }
538 538
 }
Please login to merge, or discard this patch.
Spacing   +16 added lines, -16 removed lines patch added patch discarded remove patch
@@ -81,9 +81,9 @@  discard block
 block discarded – undo
81 81
 	function propFind(PropFind $propFind, INode $node) {
82 82
 		if ($node instanceof IPrincipal) {
83 83
 			// overwrite Sabre/Dav's implementation
84
-			$propFind->handle('{' . self::NS_CALDAV . '}calendar-user-type', function () use ($node) {
84
+			$propFind->handle('{'.self::NS_CALDAV.'}calendar-user-type', function() use ($node) {
85 85
 				if ($node instanceof IProperties) {
86
-					$calendarUserType = '{' . self::NS_CALDAV . '}calendar-user-type';
86
+					$calendarUserType = '{'.self::NS_CALDAV.'}calendar-user-type';
87 87
 					$props = $node->getProperties([$calendarUserType]);
88 88
 
89 89
 					if (isset($props[$calendarUserType])) {
@@ -189,7 +189,7 @@  discard block
 block discarded – undo
189 189
 		}
190 190
 
191 191
 		$dtstart = $vevent->DTSTART;
192
-		$dtend =  $this->getDTEndFromVEvent($vevent);
192
+		$dtend = $this->getDTEndFromVEvent($vevent);
193 193
 		$uid = $vevent->UID->getValue();
194 194
 		$sequence = isset($vevent->SEQUENCE) ? $vevent->SEQUENCE->getValue() : 0;
195 195
 		$recurrenceId = isset($vevent->{'RECURRENCE-ID'}) ? $vevent->{'RECURRENCE-ID'}->serialize() : '';
@@ -261,7 +261,7 @@  discard block
 block discarded – undo
261 261
 	 */
262 262
 	function propFindDefaultCalendarUrl(PropFind $propFind, INode $node) {
263 263
 		if ($node instanceof IPrincipal) {
264
-			$propFind->handle('{' . self::NS_CALDAV . '}schedule-default-calendar-URL', function () use ($node) {
264
+			$propFind->handle('{'.self::NS_CALDAV.'}schedule-default-calendar-URL', function() use ($node) {
265 265
 				/** @var \OCA\DAV\CalDAV\Plugin $caldavPlugin */
266 266
 				$caldavPlugin = $this->server->getPlugin('caldav');
267 267
 				$principalUrl = $node->getPrincipalUrl();
@@ -292,7 +292,7 @@  discard block
 block discarded – undo
292 292
 					]);
293 293
 				}
294 294
 
295
-				$result = $this->server->getPropertiesForPath($calendarHomePath . '/' . $uri, [], 1);
295
+				$result = $this->server->getPropertiesForPath($calendarHomePath.'/'.$uri, [], 1);
296 296
 				if (empty($result)) {
297 297
 					return null;
298 298
 				}
@@ -308,8 +308,8 @@  discard block
 block discarded – undo
308 308
 	 * @param string $principal
309 309
 	 * @return string?
310 310
 	 */
311
-	protected function getCalendarUserTypeForPrincipal($principal):?string {
312
-		$calendarUserType = '{' . self::NS_CALDAV . '}calendar-user-type';
311
+	protected function getCalendarUserTypeForPrincipal($principal): ?string {
312
+		$calendarUserType = '{'.self::NS_CALDAV.'}calendar-user-type';
313 313
 		$properties = $this->server->getProperties(
314 314
 			$principal,
315 315
 			[$calendarUserType]
@@ -327,7 +327,7 @@  discard block
 block discarded – undo
327 327
 	 * @param ITip\Message $iTipMessage
328 328
 	 * @return null|Property
329 329
 	 */
330
-	private function getCurrentAttendee(ITip\Message $iTipMessage):?Property {
330
+	private function getCurrentAttendee(ITip\Message $iTipMessage): ?Property {
331 331
 		/** @var VEvent $vevent */
332 332
 		$vevent = $iTipMessage->message->VEVENT;
333 333
 		$attendees = $vevent->select('ATTENDEE');
@@ -405,8 +405,8 @@  discard block
 block discarded – undo
405 405
 			['{http://sabredav.org/ns}email-address' => $this->stripOffMailTo($email)],
406 406
 			[
407 407
 				'{DAV:}principal-URL',
408
-				'{' . self::NS_CALDAV . '}calendar-home-set',
409
-				'{' . self::NS_CALDAV . '}schedule-inbox-URL',
408
+				'{'.self::NS_CALDAV.'}calendar-home-set',
409
+				'{'.self::NS_CALDAV.'}schedule-inbox-URL',
410 410
 				'{http://sabredav.org/ns}email-address',
411 411
 
412 412
 			]
@@ -418,7 +418,7 @@  discard block
 block discarded – undo
418 418
 		$objects = [];
419 419
 		$calendarTimeZone = new DateTimeZone('UTC');
420 420
 
421
-		$homePath = $result[0][200]['{' . self::NS_CALDAV . '}calendar-home-set']->getHref();
421
+		$homePath = $result[0][200]['{'.self::NS_CALDAV.'}calendar-home-set']->getHref();
422 422
 		foreach ($this->server->tree->getNodeForPath($homePath)->getChildren() as $node) {
423 423
 			if (!$node instanceof ICalendar) {
424 424
 				continue;
@@ -469,8 +469,8 @@  discard block
 block discarded – undo
469 469
 		}
470 470
 
471 471
 		$inboxProps = $this->server->getProperties(
472
-			$result[0][200]['{' . self::NS_CALDAV . '}schedule-inbox-URL']->getHref(),
473
-			['{' . self::NS_CALDAV . '}calendar-availability']
472
+			$result[0][200]['{'.self::NS_CALDAV.'}schedule-inbox-URL']->getHref(),
473
+			['{'.self::NS_CALDAV.'}calendar-availability']
474 474
 		);
475 475
 
476 476
 		$vcalendar = new VCalendar();
@@ -482,10 +482,10 @@  discard block
 block discarded – undo
482 482
 		$generator->setBaseObject($vcalendar);
483 483
 		$generator->setTimeZone($calendarTimeZone);
484 484
 
485
-		if (isset($inboxProps['{' . self::NS_CALDAV . '}calendar-availability'])) {
485
+		if (isset($inboxProps['{'.self::NS_CALDAV.'}calendar-availability'])) {
486 486
 			$generator->setVAvailability(
487 487
 				Reader::read(
488
-					$inboxProps['{' . self::NS_CALDAV . '}calendar-availability']
488
+					$inboxProps['{'.self::NS_CALDAV.'}calendar-availability']
489 489
 				)
490 490
 			);
491 491
 		}
@@ -529,7 +529,7 @@  discard block
 block discarded – undo
529 529
 	 * @return string
530 530
 	 */
531 531
 	private function stripOffMailTo(string $email): string {
532
-		if (stripos($email, 'mailto:')  === 0) {
532
+		if (stripos($email, 'mailto:') === 0) {
533 533
 			return substr($email, 7);
534 534
 		}
535 535
 
Please login to merge, or discard this patch.
apps/dav/lib/CalDAV/WebcalCaching/RefreshWebcalService.php 2 patches
Indentation   +369 added lines, -369 removed lines patch added patch discarded remove patch
@@ -50,373 +50,373 @@
 block discarded – undo
50 50
 
51 51
 class RefreshWebcalService {
52 52
 
53
-	/** @var CalDavBackend */
54
-	private $calDavBackend;
55
-
56
-	/** @var IClientService */
57
-	private $clientService;
58
-
59
-	/** @var IConfig */
60
-	private $config;
61
-
62
-	/** @var ILogger */
63
-	private $logger;
64
-
65
-	public const REFRESH_RATE = '{http://apple.com/ns/ical/}refreshrate';
66
-	public const STRIP_ALARMS = '{http://calendarserver.org/ns/}subscribed-strip-alarms';
67
-	public const STRIP_ATTACHMENTS = '{http://calendarserver.org/ns/}subscribed-strip-attachments';
68
-	public const STRIP_TODOS = '{http://calendarserver.org/ns/}subscribed-strip-todos';
69
-
70
-	/**
71
-	 * RefreshWebcalJob constructor.
72
-	 *
73
-	 * @param CalDavBackend $calDavBackend
74
-	 * @param IClientService $clientService
75
-	 * @param IConfig $config
76
-	 * @param ILogger $logger
77
-	 */
78
-	public function __construct(CalDavBackend $calDavBackend, IClientService $clientService, IConfig $config, ILogger $logger) {
79
-		$this->calDavBackend = $calDavBackend;
80
-		$this->clientService = $clientService;
81
-		$this->config = $config;
82
-		$this->logger = $logger;
83
-	}
84
-
85
-	/**
86
-	 * @param string $principalUri
87
-	 * @param string $uri
88
-	 */
89
-	public function refreshSubscription(string $principalUri, string $uri) {
90
-		$subscription = $this->getSubscription($principalUri, $uri);
91
-		$mutations = [];
92
-		if (!$subscription) {
93
-			return;
94
-		}
95
-
96
-		$webcalData = $this->queryWebcalFeed($subscription, $mutations);
97
-		if (!$webcalData) {
98
-			return;
99
-		}
100
-
101
-		$stripTodos = ($subscription[self::STRIP_TODOS] ?? 1) === 1;
102
-		$stripAlarms = ($subscription[self::STRIP_ALARMS] ?? 1) === 1;
103
-		$stripAttachments = ($subscription[self::STRIP_ATTACHMENTS] ?? 1) === 1;
104
-
105
-		try {
106
-			$splitter = new ICalendar($webcalData, Reader::OPTION_FORGIVING);
107
-
108
-			// we wait with deleting all outdated events till we parsed the new ones
109
-			// in case the new calendar is broken and `new ICalendar` throws a ParseException
110
-			// the user will still see the old data
111
-			$this->calDavBackend->purgeAllCachedEventsForSubscription($subscription['id']);
112
-
113
-			while ($vObject = $splitter->getNext()) {
114
-				/** @var Component $vObject */
115
-				$compName = null;
116
-
117
-				foreach ($vObject->getComponents() as $component) {
118
-					if ($component->name === 'VTIMEZONE') {
119
-						continue;
120
-					}
121
-
122
-					$compName = $component->name;
123
-
124
-					if ($stripAlarms) {
125
-						unset($component->{'VALARM'});
126
-					}
127
-					if ($stripAttachments) {
128
-						unset($component->{'ATTACH'});
129
-					}
130
-				}
131
-
132
-				if ($stripTodos && $compName === 'VTODO') {
133
-					continue;
134
-				}
135
-
136
-				$uri = $this->getRandomCalendarObjectUri();
137
-				$calendarData = $vObject->serialize();
138
-				try {
139
-					$this->calDavBackend->createCalendarObject($subscription['id'], $uri, $calendarData, CalDavBackend::CALENDAR_TYPE_SUBSCRIPTION);
140
-				} catch(BadRequest $ex) {
141
-					$this->logger->logException($ex);
142
-				}
143
-			}
144
-
145
-			$newRefreshRate = $this->checkWebcalDataForRefreshRate($subscription, $webcalData);
146
-			if ($newRefreshRate) {
147
-				$mutations[self::REFRESH_RATE] = $newRefreshRate;
148
-			}
149
-
150
-			$this->updateSubscription($subscription, $mutations);
151
-		} catch(ParseException $ex) {
152
-			$subscriptionId = $subscription['id'];
153
-
154
-			$this->logger->logException($ex);
155
-			$this->logger->warning("Subscription $subscriptionId could not be refreshed due to a parsing error");
156
-		}
157
-	}
158
-
159
-	/**
160
-	 * loads subscription from backend
161
-	 *
162
-	 * @param string $principalUri
163
-	 * @param string $uri
164
-	 * @return array|null
165
-	 */
166
-	public function getSubscription(string $principalUri, string $uri) {
167
-		$subscriptions = array_values(array_filter(
168
-			$this->calDavBackend->getSubscriptionsForUser($principalUri),
169
-			function ($sub) use ($uri) {
170
-				return $sub['uri'] === $uri;
171
-			}
172
-		));
173
-
174
-		if (count($subscriptions) === 0) {
175
-			return null;
176
-		}
177
-
178
-		return $subscriptions[0];
179
-	}
180
-
181
-	/**
182
-	 * gets webcal feed from remote server
183
-	 *
184
-	 * @param array $subscription
185
-	 * @param array &$mutations
186
-	 * @return null|string
187
-	 */
188
-	private function queryWebcalFeed(array $subscription, array &$mutations) {
189
-		$client = $this->clientService->newClient();
190
-
191
-		$didBreak301Chain = false;
192
-		$latestLocation = null;
193
-
194
-		$handlerStack = HandlerStack::create();
195
-		$handlerStack->push(Middleware::mapRequest(function (RequestInterface $request) {
196
-			return $request
197
-				->withHeader('Accept', 'text/calendar, application/calendar+json, application/calendar+xml')
198
-				->withHeader('User-Agent', 'Nextcloud Webcal Crawler');
199
-		}));
200
-		$handlerStack->push(Middleware::mapResponse(function (ResponseInterface $response) use (&$didBreak301Chain, &$latestLocation) {
201
-			if (!$didBreak301Chain) {
202
-				if ($response->getStatusCode() !== 301) {
203
-					$didBreak301Chain = true;
204
-				} else {
205
-					$latestLocation = $response->getHeader('Location');
206
-				}
207
-			}
208
-			return $response;
209
-		}));
210
-
211
-		$allowLocalAccess = $this->config->getAppValue('dav', 'webcalAllowLocalAccess', 'no');
212
-		$subscriptionId = $subscription['id'];
213
-		$url = $this->cleanURL($subscription['source']);
214
-		if ($url === null) {
215
-			return null;
216
-		}
217
-
218
-		if ($allowLocalAccess !== 'yes') {
219
-			$host = strtolower(parse_url($url, PHP_URL_HOST));
220
-			// remove brackets from IPv6 addresses
221
-			if (strpos($host, '[') === 0 && substr($host, -1) === ']') {
222
-				$host = substr($host, 1, -1);
223
-			}
224
-
225
-			// Disallow localhost and local network
226
-			if ($host === 'localhost' || substr($host, -6) === '.local' || substr($host, -10) === '.localhost') {
227
-				$this->logger->warning("Subscription $subscriptionId was not refreshed because it violates local access rules");
228
-				return null;
229
-			}
230
-
231
-			// Disallow hostname only
232
-			if (substr_count($host, '.') === 0) {
233
-				$this->logger->warning("Subscription $subscriptionId was not refreshed because it violates local access rules");
234
-				return null;
235
-			}
236
-
237
-			if ((bool)filter_var($host, FILTER_VALIDATE_IP) && !filter_var($host, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE)) {
238
-				$this->logger->warning("Subscription $subscriptionId was not refreshed because it violates local access rules");
239
-				return null;
240
-			}
241
-
242
-			// Also check for IPv6 IPv4 nesting, because that's not covered by filter_var
243
-			if ((bool)filter_var($host, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6) && substr_count($host, '.') > 0) {
244
-				$delimiter = strrpos($host, ':'); // Get last colon
245
-				$ipv4Address = substr($host, $delimiter + 1);
246
-
247
-				if (!filter_var($ipv4Address, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE)) {
248
-					$this->logger->warning("Subscription $subscriptionId was not refreshed because it violates local access rules");
249
-					return null;
250
-				}
251
-			}
252
-		}
253
-
254
-		try {
255
-			$params = [
256
-				'allow_redirects' => [
257
-					'redirects' => 10
258
-				],
259
-				'handler' => $handlerStack,
260
-			];
261
-
262
-			$user = parse_url($subscription['source'], PHP_URL_USER);
263
-			$pass = parse_url($subscription['source'], PHP_URL_PASS);
264
-			if ($user !== null && $pass !== null) {
265
-				$params['auth'] = [$user, $pass];
266
-			}
267
-
268
-			$response = $client->get($url, $params);
269
-			$body = $response->getBody();
270
-
271
-			if ($latestLocation) {
272
-				$mutations['{http://calendarserver.org/ns/}source'] = new Href($latestLocation);
273
-			}
274
-
275
-			$contentType = $response->getHeader('Content-Type');
276
-			$contentType = explode(';', $contentType, 2)[0];
277
-			switch($contentType) {
278
-				case 'application/calendar+json':
279
-					try {
280
-						$jCalendar = Reader::readJson($body, Reader::OPTION_FORGIVING);
281
-					} catch(Exception $ex) {
282
-						// In case of a parsing error return null
283
-						$this->logger->debug("Subscription $subscriptionId could not be parsed");
284
-						return null;
285
-					}
286
-					return $jCalendar->serialize();
287
-
288
-				case 'application/calendar+xml':
289
-					try {
290
-						$xCalendar = Reader::readXML($body);
291
-					} catch(Exception $ex) {
292
-						// In case of a parsing error return null
293
-						$this->logger->debug("Subscription $subscriptionId could not be parsed");
294
-						return null;
295
-					}
296
-					return $xCalendar->serialize();
297
-
298
-				case 'text/calendar':
299
-				default:
300
-					try {
301
-						$vCalendar = Reader::read($body);
302
-					} catch(Exception $ex) {
303
-						// In case of a parsing error return null
304
-						$this->logger->debug("Subscription $subscriptionId could not be parsed");
305
-						return null;
306
-					}
307
-					return $vCalendar->serialize();
308
-			}
309
-		} catch(Exception $ex) {
310
-			$this->logger->logException($ex);
311
-			$this->logger->warning("Subscription $subscriptionId could not be refreshed due to a network error");
312
-
313
-			return null;
314
-		}
315
-	}
316
-
317
-	/**
318
-	 * check if:
319
-	 *  - current subscription stores a refreshrate
320
-	 *  - the webcal feed suggests a refreshrate
321
-	 *  - return suggested refreshrate if user didn't set a custom one
322
-	 *
323
-	 * @param array $subscription
324
-	 * @param string $webcalData
325
-	 * @return string|null
326
-	 */
327
-	private function checkWebcalDataForRefreshRate($subscription, $webcalData) {
328
-		// if there is no refreshrate stored in the database, check the webcal feed
329
-		// whether it suggests any refresh rate and store that in the database
330
-		if (isset($subscription[self::REFRESH_RATE]) && $subscription[self::REFRESH_RATE] !== null) {
331
-			return null;
332
-		}
333
-
334
-		/** @var Component\VCalendar $vCalendar */
335
-		$vCalendar = Reader::read($webcalData);
336
-
337
-		$newRefreshRate = null;
338
-		if (isset($vCalendar->{'X-PUBLISHED-TTL'})) {
339
-			$newRefreshRate = $vCalendar->{'X-PUBLISHED-TTL'}->getValue();
340
-		}
341
-		if (isset($vCalendar->{'REFRESH-INTERVAL'})) {
342
-			$newRefreshRate = $vCalendar->{'REFRESH-INTERVAL'}->getValue();
343
-		}
344
-
345
-		if (!$newRefreshRate) {
346
-			return null;
347
-		}
348
-
349
-		// check if new refresh rate is even valid
350
-		try {
351
-			DateTimeParser::parseDuration($newRefreshRate);
352
-		} catch(InvalidDataException $ex) {
353
-			return null;
354
-		}
355
-
356
-		return $newRefreshRate;
357
-	}
358
-
359
-	/**
360
-	 * update subscription stored in database
361
-	 * used to set:
362
-	 *  - refreshrate
363
-	 *  - source
364
-	 *
365
-	 * @param array $subscription
366
-	 * @param array $mutations
367
-	 */
368
-	private function updateSubscription(array $subscription, array $mutations) {
369
-		if (empty($mutations)) {
370
-			return;
371
-		}
372
-
373
-		$propPatch = new PropPatch($mutations);
374
-		$this->calDavBackend->updateSubscription($subscription['id'], $propPatch);
375
-		$propPatch->commit();
376
-	}
377
-
378
-	/**
379
-	 * This method will strip authentication information and replace the
380
-	 * 'webcal' or 'webcals' protocol scheme
381
-	 *
382
-	 * @param string $url
383
-	 * @return string|null
384
-	 */
385
-	private function cleanURL(string $url) {
386
-		$parsed = parse_url($url);
387
-		if ($parsed === false) {
388
-			return null;
389
-		}
390
-
391
-		if (isset($parsed['scheme']) && $parsed['scheme'] === 'http') {
392
-			$scheme = 'http';
393
-		} else {
394
-			$scheme = 'https';
395
-		}
396
-
397
-		$host = $parsed['host'] ?? '';
398
-		$port = isset($parsed['port']) ? ':' . $parsed['port'] : '';
399
-		$path = $parsed['path'] ?? '';
400
-		$query = isset($parsed['query']) ? '?' . $parsed['query'] : '';
401
-		$fragment = isset($parsed['fragment']) ? '#' . $parsed['fragment'] : '';
402
-
403
-		$cleanURL = "$scheme://$host$port$path$query$fragment";
404
-		// parse_url is giving some weird results if no url and no :// is given,
405
-		// so let's test the url again
406
-		$parsedClean = parse_url($cleanURL);
407
-		if ($parsedClean === false || !isset($parsedClean['host'])) {
408
-			return null;
409
-		}
410
-
411
-		return $cleanURL;
412
-	}
413
-
414
-	/**
415
-	 * Returns a random uri for a calendar-object
416
-	 *
417
-	 * @return string
418
-	 */
419
-	public function getRandomCalendarObjectUri():string {
420
-		return UUIDUtil::getUUID() . '.ics';
421
-	}
53
+    /** @var CalDavBackend */
54
+    private $calDavBackend;
55
+
56
+    /** @var IClientService */
57
+    private $clientService;
58
+
59
+    /** @var IConfig */
60
+    private $config;
61
+
62
+    /** @var ILogger */
63
+    private $logger;
64
+
65
+    public const REFRESH_RATE = '{http://apple.com/ns/ical/}refreshrate';
66
+    public const STRIP_ALARMS = '{http://calendarserver.org/ns/}subscribed-strip-alarms';
67
+    public const STRIP_ATTACHMENTS = '{http://calendarserver.org/ns/}subscribed-strip-attachments';
68
+    public const STRIP_TODOS = '{http://calendarserver.org/ns/}subscribed-strip-todos';
69
+
70
+    /**
71
+     * RefreshWebcalJob constructor.
72
+     *
73
+     * @param CalDavBackend $calDavBackend
74
+     * @param IClientService $clientService
75
+     * @param IConfig $config
76
+     * @param ILogger $logger
77
+     */
78
+    public function __construct(CalDavBackend $calDavBackend, IClientService $clientService, IConfig $config, ILogger $logger) {
79
+        $this->calDavBackend = $calDavBackend;
80
+        $this->clientService = $clientService;
81
+        $this->config = $config;
82
+        $this->logger = $logger;
83
+    }
84
+
85
+    /**
86
+     * @param string $principalUri
87
+     * @param string $uri
88
+     */
89
+    public function refreshSubscription(string $principalUri, string $uri) {
90
+        $subscription = $this->getSubscription($principalUri, $uri);
91
+        $mutations = [];
92
+        if (!$subscription) {
93
+            return;
94
+        }
95
+
96
+        $webcalData = $this->queryWebcalFeed($subscription, $mutations);
97
+        if (!$webcalData) {
98
+            return;
99
+        }
100
+
101
+        $stripTodos = ($subscription[self::STRIP_TODOS] ?? 1) === 1;
102
+        $stripAlarms = ($subscription[self::STRIP_ALARMS] ?? 1) === 1;
103
+        $stripAttachments = ($subscription[self::STRIP_ATTACHMENTS] ?? 1) === 1;
104
+
105
+        try {
106
+            $splitter = new ICalendar($webcalData, Reader::OPTION_FORGIVING);
107
+
108
+            // we wait with deleting all outdated events till we parsed the new ones
109
+            // in case the new calendar is broken and `new ICalendar` throws a ParseException
110
+            // the user will still see the old data
111
+            $this->calDavBackend->purgeAllCachedEventsForSubscription($subscription['id']);
112
+
113
+            while ($vObject = $splitter->getNext()) {
114
+                /** @var Component $vObject */
115
+                $compName = null;
116
+
117
+                foreach ($vObject->getComponents() as $component) {
118
+                    if ($component->name === 'VTIMEZONE') {
119
+                        continue;
120
+                    }
121
+
122
+                    $compName = $component->name;
123
+
124
+                    if ($stripAlarms) {
125
+                        unset($component->{'VALARM'});
126
+                    }
127
+                    if ($stripAttachments) {
128
+                        unset($component->{'ATTACH'});
129
+                    }
130
+                }
131
+
132
+                if ($stripTodos && $compName === 'VTODO') {
133
+                    continue;
134
+                }
135
+
136
+                $uri = $this->getRandomCalendarObjectUri();
137
+                $calendarData = $vObject->serialize();
138
+                try {
139
+                    $this->calDavBackend->createCalendarObject($subscription['id'], $uri, $calendarData, CalDavBackend::CALENDAR_TYPE_SUBSCRIPTION);
140
+                } catch(BadRequest $ex) {
141
+                    $this->logger->logException($ex);
142
+                }
143
+            }
144
+
145
+            $newRefreshRate = $this->checkWebcalDataForRefreshRate($subscription, $webcalData);
146
+            if ($newRefreshRate) {
147
+                $mutations[self::REFRESH_RATE] = $newRefreshRate;
148
+            }
149
+
150
+            $this->updateSubscription($subscription, $mutations);
151
+        } catch(ParseException $ex) {
152
+            $subscriptionId = $subscription['id'];
153
+
154
+            $this->logger->logException($ex);
155
+            $this->logger->warning("Subscription $subscriptionId could not be refreshed due to a parsing error");
156
+        }
157
+    }
158
+
159
+    /**
160
+     * loads subscription from backend
161
+     *
162
+     * @param string $principalUri
163
+     * @param string $uri
164
+     * @return array|null
165
+     */
166
+    public function getSubscription(string $principalUri, string $uri) {
167
+        $subscriptions = array_values(array_filter(
168
+            $this->calDavBackend->getSubscriptionsForUser($principalUri),
169
+            function ($sub) use ($uri) {
170
+                return $sub['uri'] === $uri;
171
+            }
172
+        ));
173
+
174
+        if (count($subscriptions) === 0) {
175
+            return null;
176
+        }
177
+
178
+        return $subscriptions[0];
179
+    }
180
+
181
+    /**
182
+     * gets webcal feed from remote server
183
+     *
184
+     * @param array $subscription
185
+     * @param array &$mutations
186
+     * @return null|string
187
+     */
188
+    private function queryWebcalFeed(array $subscription, array &$mutations) {
189
+        $client = $this->clientService->newClient();
190
+
191
+        $didBreak301Chain = false;
192
+        $latestLocation = null;
193
+
194
+        $handlerStack = HandlerStack::create();
195
+        $handlerStack->push(Middleware::mapRequest(function (RequestInterface $request) {
196
+            return $request
197
+                ->withHeader('Accept', 'text/calendar, application/calendar+json, application/calendar+xml')
198
+                ->withHeader('User-Agent', 'Nextcloud Webcal Crawler');
199
+        }));
200
+        $handlerStack->push(Middleware::mapResponse(function (ResponseInterface $response) use (&$didBreak301Chain, &$latestLocation) {
201
+            if (!$didBreak301Chain) {
202
+                if ($response->getStatusCode() !== 301) {
203
+                    $didBreak301Chain = true;
204
+                } else {
205
+                    $latestLocation = $response->getHeader('Location');
206
+                }
207
+            }
208
+            return $response;
209
+        }));
210
+
211
+        $allowLocalAccess = $this->config->getAppValue('dav', 'webcalAllowLocalAccess', 'no');
212
+        $subscriptionId = $subscription['id'];
213
+        $url = $this->cleanURL($subscription['source']);
214
+        if ($url === null) {
215
+            return null;
216
+        }
217
+
218
+        if ($allowLocalAccess !== 'yes') {
219
+            $host = strtolower(parse_url($url, PHP_URL_HOST));
220
+            // remove brackets from IPv6 addresses
221
+            if (strpos($host, '[') === 0 && substr($host, -1) === ']') {
222
+                $host = substr($host, 1, -1);
223
+            }
224
+
225
+            // Disallow localhost and local network
226
+            if ($host === 'localhost' || substr($host, -6) === '.local' || substr($host, -10) === '.localhost') {
227
+                $this->logger->warning("Subscription $subscriptionId was not refreshed because it violates local access rules");
228
+                return null;
229
+            }
230
+
231
+            // Disallow hostname only
232
+            if (substr_count($host, '.') === 0) {
233
+                $this->logger->warning("Subscription $subscriptionId was not refreshed because it violates local access rules");
234
+                return null;
235
+            }
236
+
237
+            if ((bool)filter_var($host, FILTER_VALIDATE_IP) && !filter_var($host, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE)) {
238
+                $this->logger->warning("Subscription $subscriptionId was not refreshed because it violates local access rules");
239
+                return null;
240
+            }
241
+
242
+            // Also check for IPv6 IPv4 nesting, because that's not covered by filter_var
243
+            if ((bool)filter_var($host, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6) && substr_count($host, '.') > 0) {
244
+                $delimiter = strrpos($host, ':'); // Get last colon
245
+                $ipv4Address = substr($host, $delimiter + 1);
246
+
247
+                if (!filter_var($ipv4Address, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE)) {
248
+                    $this->logger->warning("Subscription $subscriptionId was not refreshed because it violates local access rules");
249
+                    return null;
250
+                }
251
+            }
252
+        }
253
+
254
+        try {
255
+            $params = [
256
+                'allow_redirects' => [
257
+                    'redirects' => 10
258
+                ],
259
+                'handler' => $handlerStack,
260
+            ];
261
+
262
+            $user = parse_url($subscription['source'], PHP_URL_USER);
263
+            $pass = parse_url($subscription['source'], PHP_URL_PASS);
264
+            if ($user !== null && $pass !== null) {
265
+                $params['auth'] = [$user, $pass];
266
+            }
267
+
268
+            $response = $client->get($url, $params);
269
+            $body = $response->getBody();
270
+
271
+            if ($latestLocation) {
272
+                $mutations['{http://calendarserver.org/ns/}source'] = new Href($latestLocation);
273
+            }
274
+
275
+            $contentType = $response->getHeader('Content-Type');
276
+            $contentType = explode(';', $contentType, 2)[0];
277
+            switch($contentType) {
278
+                case 'application/calendar+json':
279
+                    try {
280
+                        $jCalendar = Reader::readJson($body, Reader::OPTION_FORGIVING);
281
+                    } catch(Exception $ex) {
282
+                        // In case of a parsing error return null
283
+                        $this->logger->debug("Subscription $subscriptionId could not be parsed");
284
+                        return null;
285
+                    }
286
+                    return $jCalendar->serialize();
287
+
288
+                case 'application/calendar+xml':
289
+                    try {
290
+                        $xCalendar = Reader::readXML($body);
291
+                    } catch(Exception $ex) {
292
+                        // In case of a parsing error return null
293
+                        $this->logger->debug("Subscription $subscriptionId could not be parsed");
294
+                        return null;
295
+                    }
296
+                    return $xCalendar->serialize();
297
+
298
+                case 'text/calendar':
299
+                default:
300
+                    try {
301
+                        $vCalendar = Reader::read($body);
302
+                    } catch(Exception $ex) {
303
+                        // In case of a parsing error return null
304
+                        $this->logger->debug("Subscription $subscriptionId could not be parsed");
305
+                        return null;
306
+                    }
307
+                    return $vCalendar->serialize();
308
+            }
309
+        } catch(Exception $ex) {
310
+            $this->logger->logException($ex);
311
+            $this->logger->warning("Subscription $subscriptionId could not be refreshed due to a network error");
312
+
313
+            return null;
314
+        }
315
+    }
316
+
317
+    /**
318
+     * check if:
319
+     *  - current subscription stores a refreshrate
320
+     *  - the webcal feed suggests a refreshrate
321
+     *  - return suggested refreshrate if user didn't set a custom one
322
+     *
323
+     * @param array $subscription
324
+     * @param string $webcalData
325
+     * @return string|null
326
+     */
327
+    private function checkWebcalDataForRefreshRate($subscription, $webcalData) {
328
+        // if there is no refreshrate stored in the database, check the webcal feed
329
+        // whether it suggests any refresh rate and store that in the database
330
+        if (isset($subscription[self::REFRESH_RATE]) && $subscription[self::REFRESH_RATE] !== null) {
331
+            return null;
332
+        }
333
+
334
+        /** @var Component\VCalendar $vCalendar */
335
+        $vCalendar = Reader::read($webcalData);
336
+
337
+        $newRefreshRate = null;
338
+        if (isset($vCalendar->{'X-PUBLISHED-TTL'})) {
339
+            $newRefreshRate = $vCalendar->{'X-PUBLISHED-TTL'}->getValue();
340
+        }
341
+        if (isset($vCalendar->{'REFRESH-INTERVAL'})) {
342
+            $newRefreshRate = $vCalendar->{'REFRESH-INTERVAL'}->getValue();
343
+        }
344
+
345
+        if (!$newRefreshRate) {
346
+            return null;
347
+        }
348
+
349
+        // check if new refresh rate is even valid
350
+        try {
351
+            DateTimeParser::parseDuration($newRefreshRate);
352
+        } catch(InvalidDataException $ex) {
353
+            return null;
354
+        }
355
+
356
+        return $newRefreshRate;
357
+    }
358
+
359
+    /**
360
+     * update subscription stored in database
361
+     * used to set:
362
+     *  - refreshrate
363
+     *  - source
364
+     *
365
+     * @param array $subscription
366
+     * @param array $mutations
367
+     */
368
+    private function updateSubscription(array $subscription, array $mutations) {
369
+        if (empty($mutations)) {
370
+            return;
371
+        }
372
+
373
+        $propPatch = new PropPatch($mutations);
374
+        $this->calDavBackend->updateSubscription($subscription['id'], $propPatch);
375
+        $propPatch->commit();
376
+    }
377
+
378
+    /**
379
+     * This method will strip authentication information and replace the
380
+     * 'webcal' or 'webcals' protocol scheme
381
+     *
382
+     * @param string $url
383
+     * @return string|null
384
+     */
385
+    private function cleanURL(string $url) {
386
+        $parsed = parse_url($url);
387
+        if ($parsed === false) {
388
+            return null;
389
+        }
390
+
391
+        if (isset($parsed['scheme']) && $parsed['scheme'] === 'http') {
392
+            $scheme = 'http';
393
+        } else {
394
+            $scheme = 'https';
395
+        }
396
+
397
+        $host = $parsed['host'] ?? '';
398
+        $port = isset($parsed['port']) ? ':' . $parsed['port'] : '';
399
+        $path = $parsed['path'] ?? '';
400
+        $query = isset($parsed['query']) ? '?' . $parsed['query'] : '';
401
+        $fragment = isset($parsed['fragment']) ? '#' . $parsed['fragment'] : '';
402
+
403
+        $cleanURL = "$scheme://$host$port$path$query$fragment";
404
+        // parse_url is giving some weird results if no url and no :// is given,
405
+        // so let's test the url again
406
+        $parsedClean = parse_url($cleanURL);
407
+        if ($parsedClean === false || !isset($parsedClean['host'])) {
408
+            return null;
409
+        }
410
+
411
+        return $cleanURL;
412
+    }
413
+
414
+    /**
415
+     * Returns a random uri for a calendar-object
416
+     *
417
+     * @return string
418
+     */
419
+    public function getRandomCalendarObjectUri():string {
420
+        return UUIDUtil::getUUID() . '.ics';
421
+    }
422 422
 }
Please login to merge, or discard this patch.
Spacing   +17 added lines, -17 removed lines patch added patch discarded remove patch
@@ -137,7 +137,7 @@  discard block
 block discarded – undo
137 137
 				$calendarData = $vObject->serialize();
138 138
 				try {
139 139
 					$this->calDavBackend->createCalendarObject($subscription['id'], $uri, $calendarData, CalDavBackend::CALENDAR_TYPE_SUBSCRIPTION);
140
-				} catch(BadRequest $ex) {
140
+				} catch (BadRequest $ex) {
141 141
 					$this->logger->logException($ex);
142 142
 				}
143 143
 			}
@@ -148,7 +148,7 @@  discard block
 block discarded – undo
148 148
 			}
149 149
 
150 150
 			$this->updateSubscription($subscription, $mutations);
151
-		} catch(ParseException $ex) {
151
+		} catch (ParseException $ex) {
152 152
 			$subscriptionId = $subscription['id'];
153 153
 
154 154
 			$this->logger->logException($ex);
@@ -166,7 +166,7 @@  discard block
 block discarded – undo
166 166
 	public function getSubscription(string $principalUri, string $uri) {
167 167
 		$subscriptions = array_values(array_filter(
168 168
 			$this->calDavBackend->getSubscriptionsForUser($principalUri),
169
-			function ($sub) use ($uri) {
169
+			function($sub) use ($uri) {
170 170
 				return $sub['uri'] === $uri;
171 171
 			}
172 172
 		));
@@ -192,12 +192,12 @@  discard block
 block discarded – undo
192 192
 		$latestLocation = null;
193 193
 
194 194
 		$handlerStack = HandlerStack::create();
195
-		$handlerStack->push(Middleware::mapRequest(function (RequestInterface $request) {
195
+		$handlerStack->push(Middleware::mapRequest(function(RequestInterface $request) {
196 196
 			return $request
197 197
 				->withHeader('Accept', 'text/calendar, application/calendar+json, application/calendar+xml')
198 198
 				->withHeader('User-Agent', 'Nextcloud Webcal Crawler');
199 199
 		}));
200
-		$handlerStack->push(Middleware::mapResponse(function (ResponseInterface $response) use (&$didBreak301Chain, &$latestLocation) {
200
+		$handlerStack->push(Middleware::mapResponse(function(ResponseInterface $response) use (&$didBreak301Chain, &$latestLocation) {
201 201
 			if (!$didBreak301Chain) {
202 202
 				if ($response->getStatusCode() !== 301) {
203 203
 					$didBreak301Chain = true;
@@ -234,13 +234,13 @@  discard block
 block discarded – undo
234 234
 				return null;
235 235
 			}
236 236
 
237
-			if ((bool)filter_var($host, FILTER_VALIDATE_IP) && !filter_var($host, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE)) {
237
+			if ((bool) filter_var($host, FILTER_VALIDATE_IP) && !filter_var($host, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE)) {
238 238
 				$this->logger->warning("Subscription $subscriptionId was not refreshed because it violates local access rules");
239 239
 				return null;
240 240
 			}
241 241
 
242 242
 			// Also check for IPv6 IPv4 nesting, because that's not covered by filter_var
243
-			if ((bool)filter_var($host, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6) && substr_count($host, '.') > 0) {
243
+			if ((bool) filter_var($host, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6) && substr_count($host, '.') > 0) {
244 244
 				$delimiter = strrpos($host, ':'); // Get last colon
245 245
 				$ipv4Address = substr($host, $delimiter + 1);
246 246
 
@@ -274,11 +274,11 @@  discard block
 block discarded – undo
274 274
 
275 275
 			$contentType = $response->getHeader('Content-Type');
276 276
 			$contentType = explode(';', $contentType, 2)[0];
277
-			switch($contentType) {
277
+			switch ($contentType) {
278 278
 				case 'application/calendar+json':
279 279
 					try {
280 280
 						$jCalendar = Reader::readJson($body, Reader::OPTION_FORGIVING);
281
-					} catch(Exception $ex) {
281
+					} catch (Exception $ex) {
282 282
 						// In case of a parsing error return null
283 283
 						$this->logger->debug("Subscription $subscriptionId could not be parsed");
284 284
 						return null;
@@ -288,7 +288,7 @@  discard block
 block discarded – undo
288 288
 				case 'application/calendar+xml':
289 289
 					try {
290 290
 						$xCalendar = Reader::readXML($body);
291
-					} catch(Exception $ex) {
291
+					} catch (Exception $ex) {
292 292
 						// In case of a parsing error return null
293 293
 						$this->logger->debug("Subscription $subscriptionId could not be parsed");
294 294
 						return null;
@@ -299,14 +299,14 @@  discard block
 block discarded – undo
299 299
 				default:
300 300
 					try {
301 301
 						$vCalendar = Reader::read($body);
302
-					} catch(Exception $ex) {
302
+					} catch (Exception $ex) {
303 303
 						// In case of a parsing error return null
304 304
 						$this->logger->debug("Subscription $subscriptionId could not be parsed");
305 305
 						return null;
306 306
 					}
307 307
 					return $vCalendar->serialize();
308 308
 			}
309
-		} catch(Exception $ex) {
309
+		} catch (Exception $ex) {
310 310
 			$this->logger->logException($ex);
311 311
 			$this->logger->warning("Subscription $subscriptionId could not be refreshed due to a network error");
312 312
 
@@ -349,7 +349,7 @@  discard block
 block discarded – undo
349 349
 		// check if new refresh rate is even valid
350 350
 		try {
351 351
 			DateTimeParser::parseDuration($newRefreshRate);
352
-		} catch(InvalidDataException $ex) {
352
+		} catch (InvalidDataException $ex) {
353 353
 			return null;
354 354
 		}
355 355
 
@@ -395,10 +395,10 @@  discard block
 block discarded – undo
395 395
 		}
396 396
 
397 397
 		$host = $parsed['host'] ?? '';
398
-		$port = isset($parsed['port']) ? ':' . $parsed['port'] : '';
398
+		$port = isset($parsed['port']) ? ':'.$parsed['port'] : '';
399 399
 		$path = $parsed['path'] ?? '';
400
-		$query = isset($parsed['query']) ? '?' . $parsed['query'] : '';
401
-		$fragment = isset($parsed['fragment']) ? '#' . $parsed['fragment'] : '';
400
+		$query = isset($parsed['query']) ? '?'.$parsed['query'] : '';
401
+		$fragment = isset($parsed['fragment']) ? '#'.$parsed['fragment'] : '';
402 402
 
403 403
 		$cleanURL = "$scheme://$host$port$path$query$fragment";
404 404
 		// parse_url is giving some weird results if no url and no :// is given,
@@ -417,6 +417,6 @@  discard block
 block discarded – undo
417 417
 	 * @return string
418 418
 	 */
419 419
 	public function getRandomCalendarObjectUri():string {
420
-		return UUIDUtil::getUUID() . '.ics';
420
+		return UUIDUtil::getUUID().'.ics';
421 421
 	}
422 422
 }
Please login to merge, or discard this patch.
apps/dav/lib/CalDAV/Calendar.php 2 patches
Indentation   +360 added lines, -360 removed lines patch added patch discarded remove patch
@@ -45,364 +45,364 @@
 block discarded – undo
45 45
  */
46 46
 class Calendar extends \Sabre\CalDAV\Calendar implements IShareable {
47 47
 
48
-	/** @var IConfig */
49
-	private $config;
50
-
51
-	/** @var IL10N */
52
-	protected $l10n;
53
-
54
-	/**
55
-	 * Calendar constructor.
56
-	 *
57
-	 * @param BackendInterface $caldavBackend
58
-	 * @param $calendarInfo
59
-	 * @param IL10N $l10n
60
-	 * @param IConfig $config
61
-	 */
62
-	public function __construct(BackendInterface $caldavBackend, $calendarInfo, IL10N $l10n, IConfig $config) {
63
-		parent::__construct($caldavBackend, $calendarInfo);
64
-
65
-		if ($this->getName() === BirthdayService::BIRTHDAY_CALENDAR_URI) {
66
-			$this->calendarInfo['{DAV:}displayname'] = $l10n->t('Contact birthdays');
67
-		}
68
-		if ($this->getName() === CalDavBackend::PERSONAL_CALENDAR_URI &&
69
-			$this->calendarInfo['{DAV:}displayname'] === CalDavBackend::PERSONAL_CALENDAR_NAME) {
70
-			$this->calendarInfo['{DAV:}displayname'] = $l10n->t('Personal');
71
-		}
72
-
73
-		$this->config = $config;
74
-		$this->l10n = $l10n;
75
-	}
76
-
77
-	/**
78
-	 * Updates the list of shares.
79
-	 *
80
-	 * The first array is a list of people that are to be added to the
81
-	 * resource.
82
-	 *
83
-	 * Every element in the add array has the following properties:
84
-	 *   * href - A url. Usually a mailto: address
85
-	 *   * commonName - Usually a first and last name, or false
86
-	 *   * summary - A description of the share, can also be false
87
-	 *   * readOnly - A boolean value
88
-	 *
89
-	 * Every element in the remove array is just the address string.
90
-	 *
91
-	 * @param array $add
92
-	 * @param array $remove
93
-	 * @return void
94
-	 * @throws Forbidden
95
-	 */
96
-	public function updateShares(array $add, array $remove) {
97
-		if ($this->isShared()) {
98
-			throw new Forbidden();
99
-		}
100
-		$this->caldavBackend->updateShares($this, $add, $remove);
101
-	}
102
-
103
-	/**
104
-	 * Returns the list of people whom this resource is shared with.
105
-	 *
106
-	 * Every element in this array should have the following properties:
107
-	 *   * href - Often a mailto: address
108
-	 *   * commonName - Optional, for example a first + last name
109
-	 *   * status - See the Sabre\CalDAV\SharingPlugin::STATUS_ constants.
110
-	 *   * readOnly - boolean
111
-	 *   * summary - Optional, a description for the share
112
-	 *
113
-	 * @return array
114
-	 */
115
-	public function getShares() {
116
-		if ($this->isShared()) {
117
-			return [];
118
-		}
119
-		return $this->caldavBackend->getShares($this->getResourceId());
120
-	}
121
-
122
-	/**
123
-	 * @return int
124
-	 */
125
-	public function getResourceId() {
126
-		return $this->calendarInfo['id'];
127
-	}
128
-
129
-	/**
130
-	 * @return string
131
-	 */
132
-	public function getPrincipalURI() {
133
-		return $this->calendarInfo['principaluri'];
134
-	}
135
-
136
-	/**
137
-	 * @return array
138
-	 */
139
-	public function getACL() {
140
-		$acl =  [
141
-			[
142
-				'privilege' => '{DAV:}read',
143
-				'principal' => $this->getOwner(),
144
-				'protected' => true,
145
-			],
146
-			[
147
-				'privilege' => '{DAV:}read',
148
-				'principal' => $this->getOwner() . '/calendar-proxy-write',
149
-				'protected' => true,
150
-			],
151
-			[
152
-				'privilege' => '{DAV:}read',
153
-				'principal' => $this->getOwner() . '/calendar-proxy-read',
154
-				'protected' => true,
155
-			],
156
-		];
157
-
158
-		if ($this->getName() !== BirthdayService::BIRTHDAY_CALENDAR_URI) {
159
-			$acl[] = [
160
-				'privilege' => '{DAV:}write',
161
-				'principal' => $this->getOwner(),
162
-				'protected' => true,
163
-			];
164
-			$acl[] = [
165
-				'privilege' => '{DAV:}write',
166
-				'principal' => $this->getOwner() . '/calendar-proxy-write',
167
-				'protected' => true,
168
-			];
169
-		} else {
170
-			$acl[] = [
171
-				'privilege' => '{DAV:}write-properties',
172
-				'principal' => $this->getOwner(),
173
-				'protected' => true,
174
-			];
175
-			$acl[] = [
176
-				'privilege' => '{DAV:}write-properties',
177
-				'principal' => $this->getOwner() . '/calendar-proxy-write',
178
-				'protected' => true,
179
-			];
180
-		}
181
-
182
-		$acl[] = [
183
-			'privilege' => '{DAV:}write-properties',
184
-			'principal' => $this->getOwner() . '/calendar-proxy-read',
185
-			'protected' => true,
186
-		];
187
-
188
-		if (!$this->isShared()) {
189
-			return $acl;
190
-		}
191
-
192
-		if ($this->getOwner() !== parent::getOwner()) {
193
-			$acl[] =  [
194
-				'privilege' => '{DAV:}read',
195
-				'principal' => parent::getOwner(),
196
-				'protected' => true,
197
-			];
198
-			if ($this->canWrite()) {
199
-				$acl[] = [
200
-					'privilege' => '{DAV:}write',
201
-					'principal' => parent::getOwner(),
202
-					'protected' => true,
203
-				];
204
-			} else {
205
-				$acl[] = [
206
-					'privilege' => '{DAV:}write-properties',
207
-					'principal' => parent::getOwner(),
208
-					'protected' => true,
209
-				];
210
-			}
211
-		}
212
-		if ($this->isPublic()) {
213
-			$acl[] = [
214
-				'privilege' => '{DAV:}read',
215
-				'principal' => 'principals/system/public',
216
-				'protected' => true,
217
-			];
218
-		}
219
-
220
-		$acl = $this->caldavBackend->applyShareAcl($this->getResourceId(), $acl);
221
-		$allowedPrincipals = [
222
-			$this->getOwner(),
223
-			$this->getOwner(). '/calendar-proxy-read',
224
-			$this->getOwner(). '/calendar-proxy-write',
225
-			parent::getOwner(),
226
-			'principals/system/public'
227
-		];
228
-		return array_filter($acl, function ($rule) use ($allowedPrincipals) {
229
-			return \in_array($rule['principal'], $allowedPrincipals, true);
230
-		});
231
-	}
232
-
233
-	public function getChildACL() {
234
-		return $this->getACL();
235
-	}
236
-
237
-	public function getOwner() {
238
-		if (isset($this->calendarInfo['{http://owncloud.org/ns}owner-principal'])) {
239
-			return $this->calendarInfo['{http://owncloud.org/ns}owner-principal'];
240
-		}
241
-		return parent::getOwner();
242
-	}
243
-
244
-	public function delete() {
245
-		if (isset($this->calendarInfo['{http://owncloud.org/ns}owner-principal']) &&
246
-			$this->calendarInfo['{http://owncloud.org/ns}owner-principal'] !== $this->calendarInfo['principaluri']) {
247
-			$principal = 'principal:' . parent::getOwner();
248
-			$shares = $this->caldavBackend->getShares($this->getResourceId());
249
-			$shares = array_filter($shares, function ($share) use ($principal) {
250
-				return $share['href'] === $principal;
251
-			});
252
-			if (empty($shares)) {
253
-				throw new Forbidden();
254
-			}
255
-
256
-			$this->caldavBackend->updateShares($this, [], [
257
-				$principal
258
-			]);
259
-			return;
260
-		}
261
-
262
-		// Remember when a user deleted their birthday calendar
263
-		// in order to not regenerate it on the next contacts change
264
-		if ($this->getName() === BirthdayService::BIRTHDAY_CALENDAR_URI) {
265
-			$principalURI = $this->getPrincipalURI();
266
-			$userId = substr($principalURI, 17);
267
-
268
-			$this->config->setUserValue($userId, 'dav', 'generateBirthdayCalendar', 'no');
269
-		}
270
-
271
-		parent::delete();
272
-	}
273
-
274
-	public function propPatch(PropPatch $propPatch) {
275
-		// parent::propPatch will only update calendars table
276
-		// if calendar is shared, changes have to be made to the properties table
277
-		if (!$this->isShared()) {
278
-			parent::propPatch($propPatch);
279
-		}
280
-	}
281
-
282
-	public function getChild($name) {
283
-
284
-		$obj = $this->caldavBackend->getCalendarObject($this->calendarInfo['id'], $name);
285
-
286
-		if (!$obj) {
287
-			throw new NotFound('Calendar object not found');
288
-		}
289
-
290
-		if ($obj['classification'] === CalDavBackend::CLASSIFICATION_PRIVATE && $this->isShared()) {
291
-			throw new NotFound('Calendar object not found');
292
-		}
293
-
294
-		$obj['acl'] = $this->getChildACL();
295
-
296
-		return new CalendarObject($this->caldavBackend, $this->l10n, $this->calendarInfo, $obj);
297
-
298
-	}
299
-
300
-	public function getChildren() {
301
-
302
-		$objs = $this->caldavBackend->getCalendarObjects($this->calendarInfo['id']);
303
-		$children = [];
304
-		foreach ($objs as $obj) {
305
-			if ($obj['classification'] === CalDavBackend::CLASSIFICATION_PRIVATE && $this->isShared()) {
306
-				continue;
307
-			}
308
-			$obj['acl'] = $this->getChildACL();
309
-			$children[] = new CalendarObject($this->caldavBackend, $this->l10n, $this->calendarInfo, $obj);
310
-		}
311
-		return $children;
312
-
313
-	}
314
-
315
-	public function getMultipleChildren(array $paths) {
316
-
317
-		$objs = $this->caldavBackend->getMultipleCalendarObjects($this->calendarInfo['id'], $paths);
318
-		$children = [];
319
-		foreach ($objs as $obj) {
320
-			if ($obj['classification'] === CalDavBackend::CLASSIFICATION_PRIVATE && $this->isShared()) {
321
-				continue;
322
-			}
323
-			$obj['acl'] = $this->getChildACL();
324
-			$children[] = new CalendarObject($this->caldavBackend, $this->l10n, $this->calendarInfo, $obj);
325
-		}
326
-		return $children;
327
-
328
-	}
329
-
330
-	public function childExists($name) {
331
-		$obj = $this->caldavBackend->getCalendarObject($this->calendarInfo['id'], $name);
332
-		if (!$obj) {
333
-			return false;
334
-		}
335
-		if ($obj['classification'] === CalDavBackend::CLASSIFICATION_PRIVATE && $this->isShared()) {
336
-			return false;
337
-		}
338
-
339
-		return true;
340
-	}
341
-
342
-	public function calendarQuery(array $filters) {
343
-
344
-		$uris = $this->caldavBackend->calendarQuery($this->calendarInfo['id'], $filters);
345
-		if ($this->isShared()) {
346
-			return array_filter($uris, function ($uri) {
347
-				return $this->childExists($uri);
348
-			});
349
-		}
350
-
351
-		return $uris;
352
-	}
353
-
354
-	/**
355
-	 * @param boolean $value
356
-	 * @return string|null
357
-	 */
358
-	public function setPublishStatus($value) {
359
-		$publicUri = $this->caldavBackend->setPublishStatus($value, $this);
360
-		$this->calendarInfo['publicuri'] = $publicUri;
361
-		return $publicUri;
362
-	}
363
-
364
-	/**
365
-	 * @return mixed $value
366
-	 */
367
-	public function getPublishStatus() {
368
-		return $this->caldavBackend->getPublishStatus($this);
369
-	}
370
-
371
-	public function canWrite() {
372
-		if ($this->getName() === BirthdayService::BIRTHDAY_CALENDAR_URI) {
373
-			return false;
374
-		}
375
-
376
-		if (isset($this->calendarInfo['{http://owncloud.org/ns}read-only'])) {
377
-			return !$this->calendarInfo['{http://owncloud.org/ns}read-only'];
378
-		}
379
-		return true;
380
-	}
381
-
382
-	private function isPublic() {
383
-		return isset($this->calendarInfo['{http://owncloud.org/ns}public']);
384
-	}
385
-
386
-	protected function isShared() {
387
-		if (!isset($this->calendarInfo['{http://owncloud.org/ns}owner-principal'])) {
388
-			return false;
389
-		}
390
-
391
-		return $this->calendarInfo['{http://owncloud.org/ns}owner-principal'] !== $this->calendarInfo['principaluri'];
392
-	}
393
-
394
-	public function isSubscription() {
395
-		return isset($this->calendarInfo['{http://calendarserver.org/ns/}source']);
396
-	}
397
-
398
-	/**
399
-	 * @inheritDoc
400
-	 */
401
-	public function getChanges($syncToken, $syncLevel, $limit = null) {
402
-		if (!$syncToken && $limit) {
403
-			throw new UnsupportedLimitOnInitialSyncException();
404
-		}
405
-
406
-		return parent::getChanges($syncToken, $syncLevel, $limit);
407
-	}
48
+    /** @var IConfig */
49
+    private $config;
50
+
51
+    /** @var IL10N */
52
+    protected $l10n;
53
+
54
+    /**
55
+     * Calendar constructor.
56
+     *
57
+     * @param BackendInterface $caldavBackend
58
+     * @param $calendarInfo
59
+     * @param IL10N $l10n
60
+     * @param IConfig $config
61
+     */
62
+    public function __construct(BackendInterface $caldavBackend, $calendarInfo, IL10N $l10n, IConfig $config) {
63
+        parent::__construct($caldavBackend, $calendarInfo);
64
+
65
+        if ($this->getName() === BirthdayService::BIRTHDAY_CALENDAR_URI) {
66
+            $this->calendarInfo['{DAV:}displayname'] = $l10n->t('Contact birthdays');
67
+        }
68
+        if ($this->getName() === CalDavBackend::PERSONAL_CALENDAR_URI &&
69
+            $this->calendarInfo['{DAV:}displayname'] === CalDavBackend::PERSONAL_CALENDAR_NAME) {
70
+            $this->calendarInfo['{DAV:}displayname'] = $l10n->t('Personal');
71
+        }
72
+
73
+        $this->config = $config;
74
+        $this->l10n = $l10n;
75
+    }
76
+
77
+    /**
78
+     * Updates the list of shares.
79
+     *
80
+     * The first array is a list of people that are to be added to the
81
+     * resource.
82
+     *
83
+     * Every element in the add array has the following properties:
84
+     *   * href - A url. Usually a mailto: address
85
+     *   * commonName - Usually a first and last name, or false
86
+     *   * summary - A description of the share, can also be false
87
+     *   * readOnly - A boolean value
88
+     *
89
+     * Every element in the remove array is just the address string.
90
+     *
91
+     * @param array $add
92
+     * @param array $remove
93
+     * @return void
94
+     * @throws Forbidden
95
+     */
96
+    public function updateShares(array $add, array $remove) {
97
+        if ($this->isShared()) {
98
+            throw new Forbidden();
99
+        }
100
+        $this->caldavBackend->updateShares($this, $add, $remove);
101
+    }
102
+
103
+    /**
104
+     * Returns the list of people whom this resource is shared with.
105
+     *
106
+     * Every element in this array should have the following properties:
107
+     *   * href - Often a mailto: address
108
+     *   * commonName - Optional, for example a first + last name
109
+     *   * status - See the Sabre\CalDAV\SharingPlugin::STATUS_ constants.
110
+     *   * readOnly - boolean
111
+     *   * summary - Optional, a description for the share
112
+     *
113
+     * @return array
114
+     */
115
+    public function getShares() {
116
+        if ($this->isShared()) {
117
+            return [];
118
+        }
119
+        return $this->caldavBackend->getShares($this->getResourceId());
120
+    }
121
+
122
+    /**
123
+     * @return int
124
+     */
125
+    public function getResourceId() {
126
+        return $this->calendarInfo['id'];
127
+    }
128
+
129
+    /**
130
+     * @return string
131
+     */
132
+    public function getPrincipalURI() {
133
+        return $this->calendarInfo['principaluri'];
134
+    }
135
+
136
+    /**
137
+     * @return array
138
+     */
139
+    public function getACL() {
140
+        $acl =  [
141
+            [
142
+                'privilege' => '{DAV:}read',
143
+                'principal' => $this->getOwner(),
144
+                'protected' => true,
145
+            ],
146
+            [
147
+                'privilege' => '{DAV:}read',
148
+                'principal' => $this->getOwner() . '/calendar-proxy-write',
149
+                'protected' => true,
150
+            ],
151
+            [
152
+                'privilege' => '{DAV:}read',
153
+                'principal' => $this->getOwner() . '/calendar-proxy-read',
154
+                'protected' => true,
155
+            ],
156
+        ];
157
+
158
+        if ($this->getName() !== BirthdayService::BIRTHDAY_CALENDAR_URI) {
159
+            $acl[] = [
160
+                'privilege' => '{DAV:}write',
161
+                'principal' => $this->getOwner(),
162
+                'protected' => true,
163
+            ];
164
+            $acl[] = [
165
+                'privilege' => '{DAV:}write',
166
+                'principal' => $this->getOwner() . '/calendar-proxy-write',
167
+                'protected' => true,
168
+            ];
169
+        } else {
170
+            $acl[] = [
171
+                'privilege' => '{DAV:}write-properties',
172
+                'principal' => $this->getOwner(),
173
+                'protected' => true,
174
+            ];
175
+            $acl[] = [
176
+                'privilege' => '{DAV:}write-properties',
177
+                'principal' => $this->getOwner() . '/calendar-proxy-write',
178
+                'protected' => true,
179
+            ];
180
+        }
181
+
182
+        $acl[] = [
183
+            'privilege' => '{DAV:}write-properties',
184
+            'principal' => $this->getOwner() . '/calendar-proxy-read',
185
+            'protected' => true,
186
+        ];
187
+
188
+        if (!$this->isShared()) {
189
+            return $acl;
190
+        }
191
+
192
+        if ($this->getOwner() !== parent::getOwner()) {
193
+            $acl[] =  [
194
+                'privilege' => '{DAV:}read',
195
+                'principal' => parent::getOwner(),
196
+                'protected' => true,
197
+            ];
198
+            if ($this->canWrite()) {
199
+                $acl[] = [
200
+                    'privilege' => '{DAV:}write',
201
+                    'principal' => parent::getOwner(),
202
+                    'protected' => true,
203
+                ];
204
+            } else {
205
+                $acl[] = [
206
+                    'privilege' => '{DAV:}write-properties',
207
+                    'principal' => parent::getOwner(),
208
+                    'protected' => true,
209
+                ];
210
+            }
211
+        }
212
+        if ($this->isPublic()) {
213
+            $acl[] = [
214
+                'privilege' => '{DAV:}read',
215
+                'principal' => 'principals/system/public',
216
+                'protected' => true,
217
+            ];
218
+        }
219
+
220
+        $acl = $this->caldavBackend->applyShareAcl($this->getResourceId(), $acl);
221
+        $allowedPrincipals = [
222
+            $this->getOwner(),
223
+            $this->getOwner(). '/calendar-proxy-read',
224
+            $this->getOwner(). '/calendar-proxy-write',
225
+            parent::getOwner(),
226
+            'principals/system/public'
227
+        ];
228
+        return array_filter($acl, function ($rule) use ($allowedPrincipals) {
229
+            return \in_array($rule['principal'], $allowedPrincipals, true);
230
+        });
231
+    }
232
+
233
+    public function getChildACL() {
234
+        return $this->getACL();
235
+    }
236
+
237
+    public function getOwner() {
238
+        if (isset($this->calendarInfo['{http://owncloud.org/ns}owner-principal'])) {
239
+            return $this->calendarInfo['{http://owncloud.org/ns}owner-principal'];
240
+        }
241
+        return parent::getOwner();
242
+    }
243
+
244
+    public function delete() {
245
+        if (isset($this->calendarInfo['{http://owncloud.org/ns}owner-principal']) &&
246
+            $this->calendarInfo['{http://owncloud.org/ns}owner-principal'] !== $this->calendarInfo['principaluri']) {
247
+            $principal = 'principal:' . parent::getOwner();
248
+            $shares = $this->caldavBackend->getShares($this->getResourceId());
249
+            $shares = array_filter($shares, function ($share) use ($principal) {
250
+                return $share['href'] === $principal;
251
+            });
252
+            if (empty($shares)) {
253
+                throw new Forbidden();
254
+            }
255
+
256
+            $this->caldavBackend->updateShares($this, [], [
257
+                $principal
258
+            ]);
259
+            return;
260
+        }
261
+
262
+        // Remember when a user deleted their birthday calendar
263
+        // in order to not regenerate it on the next contacts change
264
+        if ($this->getName() === BirthdayService::BIRTHDAY_CALENDAR_URI) {
265
+            $principalURI = $this->getPrincipalURI();
266
+            $userId = substr($principalURI, 17);
267
+
268
+            $this->config->setUserValue($userId, 'dav', 'generateBirthdayCalendar', 'no');
269
+        }
270
+
271
+        parent::delete();
272
+    }
273
+
274
+    public function propPatch(PropPatch $propPatch) {
275
+        // parent::propPatch will only update calendars table
276
+        // if calendar is shared, changes have to be made to the properties table
277
+        if (!$this->isShared()) {
278
+            parent::propPatch($propPatch);
279
+        }
280
+    }
281
+
282
+    public function getChild($name) {
283
+
284
+        $obj = $this->caldavBackend->getCalendarObject($this->calendarInfo['id'], $name);
285
+
286
+        if (!$obj) {
287
+            throw new NotFound('Calendar object not found');
288
+        }
289
+
290
+        if ($obj['classification'] === CalDavBackend::CLASSIFICATION_PRIVATE && $this->isShared()) {
291
+            throw new NotFound('Calendar object not found');
292
+        }
293
+
294
+        $obj['acl'] = $this->getChildACL();
295
+
296
+        return new CalendarObject($this->caldavBackend, $this->l10n, $this->calendarInfo, $obj);
297
+
298
+    }
299
+
300
+    public function getChildren() {
301
+
302
+        $objs = $this->caldavBackend->getCalendarObjects($this->calendarInfo['id']);
303
+        $children = [];
304
+        foreach ($objs as $obj) {
305
+            if ($obj['classification'] === CalDavBackend::CLASSIFICATION_PRIVATE && $this->isShared()) {
306
+                continue;
307
+            }
308
+            $obj['acl'] = $this->getChildACL();
309
+            $children[] = new CalendarObject($this->caldavBackend, $this->l10n, $this->calendarInfo, $obj);
310
+        }
311
+        return $children;
312
+
313
+    }
314
+
315
+    public function getMultipleChildren(array $paths) {
316
+
317
+        $objs = $this->caldavBackend->getMultipleCalendarObjects($this->calendarInfo['id'], $paths);
318
+        $children = [];
319
+        foreach ($objs as $obj) {
320
+            if ($obj['classification'] === CalDavBackend::CLASSIFICATION_PRIVATE && $this->isShared()) {
321
+                continue;
322
+            }
323
+            $obj['acl'] = $this->getChildACL();
324
+            $children[] = new CalendarObject($this->caldavBackend, $this->l10n, $this->calendarInfo, $obj);
325
+        }
326
+        return $children;
327
+
328
+    }
329
+
330
+    public function childExists($name) {
331
+        $obj = $this->caldavBackend->getCalendarObject($this->calendarInfo['id'], $name);
332
+        if (!$obj) {
333
+            return false;
334
+        }
335
+        if ($obj['classification'] === CalDavBackend::CLASSIFICATION_PRIVATE && $this->isShared()) {
336
+            return false;
337
+        }
338
+
339
+        return true;
340
+    }
341
+
342
+    public function calendarQuery(array $filters) {
343
+
344
+        $uris = $this->caldavBackend->calendarQuery($this->calendarInfo['id'], $filters);
345
+        if ($this->isShared()) {
346
+            return array_filter($uris, function ($uri) {
347
+                return $this->childExists($uri);
348
+            });
349
+        }
350
+
351
+        return $uris;
352
+    }
353
+
354
+    /**
355
+     * @param boolean $value
356
+     * @return string|null
357
+     */
358
+    public function setPublishStatus($value) {
359
+        $publicUri = $this->caldavBackend->setPublishStatus($value, $this);
360
+        $this->calendarInfo['publicuri'] = $publicUri;
361
+        return $publicUri;
362
+    }
363
+
364
+    /**
365
+     * @return mixed $value
366
+     */
367
+    public function getPublishStatus() {
368
+        return $this->caldavBackend->getPublishStatus($this);
369
+    }
370
+
371
+    public function canWrite() {
372
+        if ($this->getName() === BirthdayService::BIRTHDAY_CALENDAR_URI) {
373
+            return false;
374
+        }
375
+
376
+        if (isset($this->calendarInfo['{http://owncloud.org/ns}read-only'])) {
377
+            return !$this->calendarInfo['{http://owncloud.org/ns}read-only'];
378
+        }
379
+        return true;
380
+    }
381
+
382
+    private function isPublic() {
383
+        return isset($this->calendarInfo['{http://owncloud.org/ns}public']);
384
+    }
385
+
386
+    protected function isShared() {
387
+        if (!isset($this->calendarInfo['{http://owncloud.org/ns}owner-principal'])) {
388
+            return false;
389
+        }
390
+
391
+        return $this->calendarInfo['{http://owncloud.org/ns}owner-principal'] !== $this->calendarInfo['principaluri'];
392
+    }
393
+
394
+    public function isSubscription() {
395
+        return isset($this->calendarInfo['{http://calendarserver.org/ns/}source']);
396
+    }
397
+
398
+    /**
399
+     * @inheritDoc
400
+     */
401
+    public function getChanges($syncToken, $syncLevel, $limit = null) {
402
+        if (!$syncToken && $limit) {
403
+            throw new UnsupportedLimitOnInitialSyncException();
404
+        }
405
+
406
+        return parent::getChanges($syncToken, $syncLevel, $limit);
407
+    }
408 408
 }
Please login to merge, or discard this patch.
Spacing   +13 added lines, -13 removed lines patch added patch discarded remove patch
@@ -137,7 +137,7 @@  discard block
 block discarded – undo
137 137
 	 * @return array
138 138
 	 */
139 139
 	public function getACL() {
140
-		$acl =  [
140
+		$acl = [
141 141
 			[
142 142
 				'privilege' => '{DAV:}read',
143 143
 				'principal' => $this->getOwner(),
@@ -145,12 +145,12 @@  discard block
 block discarded – undo
145 145
 			],
146 146
 			[
147 147
 				'privilege' => '{DAV:}read',
148
-				'principal' => $this->getOwner() . '/calendar-proxy-write',
148
+				'principal' => $this->getOwner().'/calendar-proxy-write',
149 149
 				'protected' => true,
150 150
 			],
151 151
 			[
152 152
 				'privilege' => '{DAV:}read',
153
-				'principal' => $this->getOwner() . '/calendar-proxy-read',
153
+				'principal' => $this->getOwner().'/calendar-proxy-read',
154 154
 				'protected' => true,
155 155
 			],
156 156
 		];
@@ -163,7 +163,7 @@  discard block
 block discarded – undo
163 163
 			];
164 164
 			$acl[] = [
165 165
 				'privilege' => '{DAV:}write',
166
-				'principal' => $this->getOwner() . '/calendar-proxy-write',
166
+				'principal' => $this->getOwner().'/calendar-proxy-write',
167 167
 				'protected' => true,
168 168
 			];
169 169
 		} else {
@@ -174,14 +174,14 @@  discard block
 block discarded – undo
174 174
 			];
175 175
 			$acl[] = [
176 176
 				'privilege' => '{DAV:}write-properties',
177
-				'principal' => $this->getOwner() . '/calendar-proxy-write',
177
+				'principal' => $this->getOwner().'/calendar-proxy-write',
178 178
 				'protected' => true,
179 179
 			];
180 180
 		}
181 181
 
182 182
 		$acl[] = [
183 183
 			'privilege' => '{DAV:}write-properties',
184
-			'principal' => $this->getOwner() . '/calendar-proxy-read',
184
+			'principal' => $this->getOwner().'/calendar-proxy-read',
185 185
 			'protected' => true,
186 186
 		];
187 187
 
@@ -190,7 +190,7 @@  discard block
 block discarded – undo
190 190
 		}
191 191
 
192 192
 		if ($this->getOwner() !== parent::getOwner()) {
193
-			$acl[] =  [
193
+			$acl[] = [
194 194
 				'privilege' => '{DAV:}read',
195 195
 				'principal' => parent::getOwner(),
196 196
 				'protected' => true,
@@ -220,12 +220,12 @@  discard block
 block discarded – undo
220 220
 		$acl = $this->caldavBackend->applyShareAcl($this->getResourceId(), $acl);
221 221
 		$allowedPrincipals = [
222 222
 			$this->getOwner(),
223
-			$this->getOwner(). '/calendar-proxy-read',
224
-			$this->getOwner(). '/calendar-proxy-write',
223
+			$this->getOwner().'/calendar-proxy-read',
224
+			$this->getOwner().'/calendar-proxy-write',
225 225
 			parent::getOwner(),
226 226
 			'principals/system/public'
227 227
 		];
228
-		return array_filter($acl, function ($rule) use ($allowedPrincipals) {
228
+		return array_filter($acl, function($rule) use ($allowedPrincipals) {
229 229
 			return \in_array($rule['principal'], $allowedPrincipals, true);
230 230
 		});
231 231
 	}
@@ -244,9 +244,9 @@  discard block
 block discarded – undo
244 244
 	public function delete() {
245 245
 		if (isset($this->calendarInfo['{http://owncloud.org/ns}owner-principal']) &&
246 246
 			$this->calendarInfo['{http://owncloud.org/ns}owner-principal'] !== $this->calendarInfo['principaluri']) {
247
-			$principal = 'principal:' . parent::getOwner();
247
+			$principal = 'principal:'.parent::getOwner();
248 248
 			$shares = $this->caldavBackend->getShares($this->getResourceId());
249
-			$shares = array_filter($shares, function ($share) use ($principal) {
249
+			$shares = array_filter($shares, function($share) use ($principal) {
250 250
 				return $share['href'] === $principal;
251 251
 			});
252 252
 			if (empty($shares)) {
@@ -343,7 +343,7 @@  discard block
 block discarded – undo
343 343
 
344 344
 		$uris = $this->caldavBackend->calendarQuery($this->calendarInfo['id'], $filters);
345 345
 		if ($this->isShared()) {
346
-			return array_filter($uris, function ($uri) {
346
+			return array_filter($uris, function($uri) {
347 347
 				return $this->childExists($uri);
348 348
 			});
349 349
 		}
Please login to merge, or discard this patch.
apps/dav/lib/CalDAV/ResourceBooking/AbstractPrincipalBackend.php 2 patches
Indentation   +435 added lines, -435 removed lines patch added patch discarded remove patch
@@ -35,439 +35,439 @@
 block discarded – undo
35 35
 
36 36
 abstract class AbstractPrincipalBackend implements BackendInterface {
37 37
 
38
-	/** @var IDBConnection */
39
-	private $db;
40
-
41
-	/** @var IUserSession */
42
-	private $userSession;
43
-
44
-	/** @var IGroupManager */
45
-	private $groupManager;
46
-
47
-	/** @var ILogger */
48
-	private $logger;
49
-
50
-	/** @var ProxyMapper */
51
-	private $proxyMapper;
52
-
53
-	/** @var string */
54
-	private $principalPrefix;
55
-
56
-	/** @var string */
57
-	private $dbTableName;
58
-
59
-	/** @var string */
60
-	private $dbMetaDataTableName;
61
-
62
-	/** @var string */
63
-	private $dbForeignKeyName;
64
-
65
-	/** @var string */
66
-	private $cuType;
67
-
68
-	/**
69
-	 * @param IDBConnection $dbConnection
70
-	 * @param IUserSession $userSession
71
-	 * @param IGroupManager $groupManager
72
-	 * @param ILogger $logger
73
-	 * @param string $principalPrefix
74
-	 * @param string $dbPrefix
75
-	 * @param string $cuType
76
-	 */
77
-	public function __construct(IDBConnection $dbConnection,
78
-								IUserSession $userSession,
79
-								IGroupManager $groupManager,
80
-								ILogger $logger,
81
-								ProxyMapper $proxyMapper,
82
-								string $principalPrefix,
83
-								string $dbPrefix,
84
-								string $cuType) {
85
-		$this->db = $dbConnection;
86
-		$this->userSession = $userSession;
87
-		$this->groupManager = $groupManager;
88
-		$this->logger = $logger;
89
-		$this->proxyMapper = $proxyMapper;
90
-		$this->principalPrefix = $principalPrefix;
91
-		$this->dbTableName = 'calendar_' . $dbPrefix . 's';
92
-		$this->dbMetaDataTableName = $this->dbTableName . '_md';
93
-		$this->dbForeignKeyName = $dbPrefix . '_id';
94
-		$this->cuType = $cuType;
95
-	}
96
-
97
-	use PrincipalProxyTrait;
98
-
99
-	/**
100
-	 * Returns a list of principals based on a prefix.
101
-	 *
102
-	 * This prefix will often contain something like 'principals'. You are only
103
-	 * expected to return principals that are in this base path.
104
-	 *
105
-	 * You are expected to return at least a 'uri' for every user, you can
106
-	 * return any additional properties if you wish so. Common properties are:
107
-	 *   {DAV:}displayname
108
-	 *
109
-	 * @param string $prefixPath
110
-	 * @return string[]
111
-	 */
112
-	public function getPrincipalsByPrefix($prefixPath) {
113
-		$principals = [];
114
-
115
-		if ($prefixPath === $this->principalPrefix) {
116
-			$query = $this->db->getQueryBuilder();
117
-			$query->select(['id', 'backend_id', 'resource_id', 'email', 'displayname'])
118
-				->from($this->dbTableName);
119
-			$stmt = $query->execute();
120
-
121
-			$metaDataQuery = $this->db->getQueryBuilder();
122
-			$metaDataQuery->select([$this->dbForeignKeyName, 'key', 'value'])
123
-				->from($this->dbMetaDataTableName);
124
-			$metaDataStmt = $metaDataQuery->execute();
125
-			$metaDataRows = $metaDataStmt->fetchAll(\PDO::FETCH_ASSOC);
126
-
127
-			$metaDataById = [];
128
-			foreach($metaDataRows as $metaDataRow) {
129
-				if (!isset($metaDataById[$metaDataRow[$this->dbForeignKeyName]])) {
130
-					$metaDataById[$metaDataRow[$this->dbForeignKeyName]] = [];
131
-				}
132
-
133
-				$metaDataById[$metaDataRow[$this->dbForeignKeyName]][$metaDataRow['key']] =
134
-					$metaDataRow['value'];
135
-			}
136
-
137
-			while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
138
-				$id = $row['id'];
139
-
140
-				if (isset($metaDataById[$id])) {
141
-					$principals[] = $this->rowToPrincipal($row, $metaDataById[$id]);
142
-				} else {
143
-					$principals[] = $this->rowToPrincipal($row);
144
-				}
145
-
146
-			}
147
-
148
-			$stmt->closeCursor();
149
-		}
150
-
151
-		return $principals;
152
-	}
153
-
154
-	/**
155
-	 * Returns a specific principal, specified by it's path.
156
-	 * The returned structure should be the exact same as from
157
-	 * getPrincipalsByPrefix.
158
-	 *
159
-	 * @param string $path
160
-	 * @return array
161
-	 */
162
-	public function getPrincipalByPath($path) {
163
-		if (strpos($path, $this->principalPrefix) !== 0) {
164
-			return null;
165
-		}
166
-		list(, $name) = \Sabre\Uri\split($path);
167
-
168
-		list($backendId, $resourceId) = explode('-',  $name, 2);
169
-
170
-		$query = $this->db->getQueryBuilder();
171
-		$query->select(['id', 'backend_id', 'resource_id', 'email', 'displayname'])
172
-			->from($this->dbTableName)
173
-			->where($query->expr()->eq('backend_id', $query->createNamedParameter($backendId)))
174
-			->andWhere($query->expr()->eq('resource_id', $query->createNamedParameter($resourceId)));
175
-		$stmt = $query->execute();
176
-		$row = $stmt->fetch(\PDO::FETCH_ASSOC);
177
-
178
-		if(!$row) {
179
-			return null;
180
-		}
181
-
182
-		$metaDataQuery = $this->db->getQueryBuilder();
183
-		$metaDataQuery->select(['key', 'value'])
184
-			->from($this->dbMetaDataTableName)
185
-			->where($metaDataQuery->expr()->eq($this->dbForeignKeyName, $metaDataQuery->createNamedParameter($row['id'])));
186
-		$metaDataStmt = $metaDataQuery->execute();
187
-		$metaDataRows = $metaDataStmt->fetchAll(\PDO::FETCH_ASSOC);
188
-		$metadata = [];
189
-
190
-		foreach($metaDataRows as $metaDataRow) {
191
-			$metadata[$metaDataRow['key']] = $metaDataRow['value'];
192
-		}
193
-
194
-		return $this->rowToPrincipal($row, $metadata);
195
-	}
196
-
197
-	/**
198
-	 * @param int $id
199
-	 * @return array|null
200
-	 */
201
-	public function getPrincipalById($id):?array {
202
-		$query = $this->db->getQueryBuilder();
203
-		$query->select(['id', 'backend_id', 'resource_id', 'email', 'displayname'])
204
-			->from($this->dbTableName)
205
-			->where($query->expr()->eq('id', $query->createNamedParameter($id)));
206
-		$stmt = $query->execute();
207
-		$row = $stmt->fetch(\PDO::FETCH_ASSOC);
208
-
209
-		if(!$row) {
210
-			return null;
211
-		}
212
-
213
-		$metaDataQuery = $this->db->getQueryBuilder();
214
-		$metaDataQuery->select(['key', 'value'])
215
-			->from($this->dbMetaDataTableName)
216
-			->where($metaDataQuery->expr()->eq($this->dbForeignKeyName, $metaDataQuery->createNamedParameter($row['id'])));
217
-		$metaDataStmt = $metaDataQuery->execute();
218
-		$metaDataRows = $metaDataStmt->fetchAll(\PDO::FETCH_ASSOC);
219
-		$metadata = [];
220
-
221
-		foreach($metaDataRows as $metaDataRow) {
222
-			$metadata[$metaDataRow['key']] = $metaDataRow['value'];
223
-		}
224
-
225
-		return $this->rowToPrincipal($row, $metadata);
226
-	}
227
-
228
-	/**
229
-	 * @param string $path
230
-	 * @param PropPatch $propPatch
231
-	 * @return int
232
-	 */
233
-	function updatePrincipal($path, PropPatch $propPatch) {
234
-		return 0;
235
-	}
236
-
237
-	/**
238
-	 * @param string $prefixPath
239
-	 * @param array $searchProperties
240
-	 * @param string $test
241
-	 * @return array
242
-	 */
243
-	function searchPrincipals($prefixPath, array $searchProperties, $test = 'allof') {
244
-		$results = [];
245
-		if (\count($searchProperties) === 0) {
246
-			return [];
247
-		}
248
-		if ($prefixPath !== $this->principalPrefix) {
249
-			return [];
250
-		}
251
-
252
-		$user = $this->userSession->getUser();
253
-		if (!$user) {
254
-			return [];
255
-		}
256
-		$usersGroups = $this->groupManager->getUserGroupIds($user);
257
-
258
-		foreach ($searchProperties as $prop => $value) {
259
-			switch ($prop) {
260
-				case '{http://sabredav.org/ns}email-address':
261
-					$query = $this->db->getQueryBuilder();
262
-					$query->select(['id', 'backend_id', 'resource_id', 'email', 'displayname', 'group_restrictions'])
263
-						->from($this->dbTableName)
264
-						->where($query->expr()->iLike('email', $query->createNamedParameter('%' . $this->db->escapeLikeParameter($value) . '%')));
265
-
266
-					$stmt = $query->execute();
267
-					$principals = [];
268
-					while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
269
-						if (!$this->isAllowedToAccessResource($row, $usersGroups)) {
270
-							continue;
271
-						}
272
-						$principals[] = $this->rowToPrincipal($row)['uri'];
273
-					}
274
-					$results[] = $principals;
275
-
276
-					$stmt->closeCursor();
277
-					break;
278
-
279
-				case '{DAV:}displayname':
280
-					$query = $this->db->getQueryBuilder();
281
-					$query->select(['id', 'backend_id', 'resource_id', 'email', 'displayname', 'group_restrictions'])
282
-						->from($this->dbTableName)
283
-						->where($query->expr()->iLike('displayname', $query->createNamedParameter('%' . $this->db->escapeLikeParameter($value) . '%')));
284
-
285
-					$stmt = $query->execute();
286
-					$principals = [];
287
-					while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
288
-						if (!$this->isAllowedToAccessResource($row, $usersGroups)) {
289
-							continue;
290
-						}
291
-						$principals[] = $this->rowToPrincipal($row)['uri'];
292
-					}
293
-					$results[] = $principals;
294
-
295
-					$stmt->closeCursor();
296
-					break;
297
-
298
-				case '{urn:ietf:params:xml:ns:caldav}calendar-user-address-set':
299
-					// If you add support for more search properties that qualify as a user-address,
300
-					// please also add them to the array below
301
-					$results[] = $this->searchPrincipals($this->principalPrefix, [
302
-						'{http://sabredav.org/ns}email-address' => $value,
303
-					], 'anyof');
304
-					break;
305
-
306
-				default:
307
-					$rowsByMetadata = $this->searchPrincipalsByMetadataKey($prop, $value);
308
-					$filteredRows = array_filter($rowsByMetadata, function ($row) use ($usersGroups) {
309
-						return $this->isAllowedToAccessResource($row, $usersGroups);
310
-					});
311
-
312
-					$results[] = array_map(function ($row) {
313
-						return $row['uri'];
314
-					}, $filteredRows);
315
-
316
-					break;
317
-			}
318
-		}
319
-
320
-		// results is an array of arrays, so this is not the first search result
321
-		// but the results of the first searchProperty
322
-		if (count($results) === 1) {
323
-			return $results[0];
324
-		}
325
-
326
-		switch ($test) {
327
-			case 'anyof':
328
-				return array_values(array_unique(array_merge(...$results)));
329
-
330
-			case 'allof':
331
-			default:
332
-				return array_values(array_intersect(...$results));
333
-		}
334
-	}
335
-
336
-	/**
337
-	 * Searches principals based on their metadata keys.
338
-	 * This allows to search for all principals with a specific key.
339
-	 * e.g.:
340
-	 * '{http://nextcloud.com/ns}room-building-address' => 'ABC Street 123, ...'
341
-	 *
342
-	 * @param $key
343
-	 * @param $value
344
-	 * @return array
345
-	 */
346
-	private function searchPrincipalsByMetadataKey($key, $value):array {
347
-		$query = $this->db->getQueryBuilder();
348
-		$query->select([$this->dbForeignKeyName])
349
-			->from($this->dbMetaDataTableName)
350
-			->where($query->expr()->eq('key', $query->createNamedParameter($key)))
351
-			->andWhere($query->expr()->iLike('value', $query->createNamedParameter('%' . $this->db->escapeLikeParameter($value) . '%')));
352
-		$stmt = $query->execute();
353
-
354
-		$rows = [];
355
-		while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
356
-			$id = $row[$this->dbForeignKeyName];
357
-
358
-			$principalRow = $this->getPrincipalById($id);
359
-			if (!$principalRow) {
360
-				continue;
361
-			}
362
-
363
-			$rows[] = $principalRow;
364
-		}
365
-
366
-		return $rows;
367
-	}
368
-
369
-	/**
370
-	 * @param string $uri
371
-	 * @param string $principalPrefix
372
-	 * @return null|string
373
-	 */
374
-	function findByUri($uri, $principalPrefix) {
375
-		$user = $this->userSession->getUser();
376
-		if (!$user) {
377
-			return null;
378
-		}
379
-		$usersGroups = $this->groupManager->getUserGroupIds($user);
380
-
381
-		if (strpos($uri, 'mailto:') === 0) {
382
-			$email = substr($uri, 7);
383
-			$query = $this->db->getQueryBuilder();
384
-			$query->select(['id', 'backend_id', 'resource_id', 'email', 'displayname', 'group_restrictions'])
385
-				->from($this->dbTableName)
386
-				->where($query->expr()->eq('email', $query->createNamedParameter($email)));
387
-
388
-			$stmt = $query->execute();
389
-			$row = $stmt->fetch(\PDO::FETCH_ASSOC);
390
-
391
-			if(!$row) {
392
-				return null;
393
-			}
394
-			if (!$this->isAllowedToAccessResource($row, $usersGroups)) {
395
-				return null;
396
-			}
397
-
398
-			return $this->rowToPrincipal($row)['uri'];
399
-		}
400
-
401
-		if (strpos($uri, 'principal:') === 0) {
402
-			$path = substr($uri, 10);
403
-			if (strpos($path, $this->principalPrefix) !== 0) {
404
-				return null;
405
-			}
406
-
407
-			list(, $name) = \Sabre\Uri\split($path);
408
-			list($backendId, $resourceId) = explode('-',  $name, 2);
409
-
410
-			$query = $this->db->getQueryBuilder();
411
-			$query->select(['id', 'backend_id', 'resource_id', 'email', 'displayname', 'group_restrictions'])
412
-				->from($this->dbTableName)
413
-				->where($query->expr()->eq('backend_id', $query->createNamedParameter($backendId)))
414
-				->andWhere($query->expr()->eq('resource_id', $query->createNamedParameter($resourceId)));
415
-			$stmt = $query->execute();
416
-			$row = $stmt->fetch(\PDO::FETCH_ASSOC);
417
-
418
-			if(!$row) {
419
-				return null;
420
-			}
421
-			if (!$this->isAllowedToAccessResource($row, $usersGroups)) {
422
-				return null;
423
-			}
424
-
425
-			return $this->rowToPrincipal($row)['uri'];
426
-		}
427
-
428
-		return null;
429
-	}
430
-
431
-	/**
432
-	 * convert database row to principal
433
-	 *
434
-	 * @param String[] $row
435
-	 * @param String[] $metadata
436
-	 * @return Array
437
-	 */
438
-	private function rowToPrincipal(array $row, array $metadata=[]):array {
439
-		return array_merge([
440
-			'uri' => $this->principalPrefix . '/' . $row['backend_id'] . '-' . $row['resource_id'],
441
-			'{DAV:}displayname' => $row['displayname'],
442
-			'{http://sabredav.org/ns}email-address' => $row['email'],
443
-			'{urn:ietf:params:xml:ns:caldav}calendar-user-type' => $this->cuType,
444
-		], $metadata);
445
-	}
446
-
447
-	/**
448
-	 * @param $row
449
-	 * @param $userGroups
450
-	 * @return bool
451
-	 */
452
-	private function isAllowedToAccessResource(array $row, array $userGroups):bool {
453
-		if (!isset($row['group_restrictions']) ||
454
-			$row['group_restrictions'] === null ||
455
-			$row['group_restrictions'] === '') {
456
-			return true;
457
-		}
458
-
459
-		// group restrictions contains something, but not parsable, deny access and log warning
460
-		$json = json_decode($row['group_restrictions']);
461
-		if (!\is_array($json)) {
462
-			$this->logger->info('group_restrictions field could not be parsed for ' . $this->dbTableName . '::' . $row['id'] . ', denying access to resource');
463
-			return false;
464
-		}
465
-
466
-		// empty array => no group restrictions
467
-		if (empty($json)) {
468
-			return true;
469
-		}
470
-
471
-		return !empty(array_intersect($json, $userGroups));
472
-	}
38
+    /** @var IDBConnection */
39
+    private $db;
40
+
41
+    /** @var IUserSession */
42
+    private $userSession;
43
+
44
+    /** @var IGroupManager */
45
+    private $groupManager;
46
+
47
+    /** @var ILogger */
48
+    private $logger;
49
+
50
+    /** @var ProxyMapper */
51
+    private $proxyMapper;
52
+
53
+    /** @var string */
54
+    private $principalPrefix;
55
+
56
+    /** @var string */
57
+    private $dbTableName;
58
+
59
+    /** @var string */
60
+    private $dbMetaDataTableName;
61
+
62
+    /** @var string */
63
+    private $dbForeignKeyName;
64
+
65
+    /** @var string */
66
+    private $cuType;
67
+
68
+    /**
69
+     * @param IDBConnection $dbConnection
70
+     * @param IUserSession $userSession
71
+     * @param IGroupManager $groupManager
72
+     * @param ILogger $logger
73
+     * @param string $principalPrefix
74
+     * @param string $dbPrefix
75
+     * @param string $cuType
76
+     */
77
+    public function __construct(IDBConnection $dbConnection,
78
+                                IUserSession $userSession,
79
+                                IGroupManager $groupManager,
80
+                                ILogger $logger,
81
+                                ProxyMapper $proxyMapper,
82
+                                string $principalPrefix,
83
+                                string $dbPrefix,
84
+                                string $cuType) {
85
+        $this->db = $dbConnection;
86
+        $this->userSession = $userSession;
87
+        $this->groupManager = $groupManager;
88
+        $this->logger = $logger;
89
+        $this->proxyMapper = $proxyMapper;
90
+        $this->principalPrefix = $principalPrefix;
91
+        $this->dbTableName = 'calendar_' . $dbPrefix . 's';
92
+        $this->dbMetaDataTableName = $this->dbTableName . '_md';
93
+        $this->dbForeignKeyName = $dbPrefix . '_id';
94
+        $this->cuType = $cuType;
95
+    }
96
+
97
+    use PrincipalProxyTrait;
98
+
99
+    /**
100
+     * Returns a list of principals based on a prefix.
101
+     *
102
+     * This prefix will often contain something like 'principals'. You are only
103
+     * expected to return principals that are in this base path.
104
+     *
105
+     * You are expected to return at least a 'uri' for every user, you can
106
+     * return any additional properties if you wish so. Common properties are:
107
+     *   {DAV:}displayname
108
+     *
109
+     * @param string $prefixPath
110
+     * @return string[]
111
+     */
112
+    public function getPrincipalsByPrefix($prefixPath) {
113
+        $principals = [];
114
+
115
+        if ($prefixPath === $this->principalPrefix) {
116
+            $query = $this->db->getQueryBuilder();
117
+            $query->select(['id', 'backend_id', 'resource_id', 'email', 'displayname'])
118
+                ->from($this->dbTableName);
119
+            $stmt = $query->execute();
120
+
121
+            $metaDataQuery = $this->db->getQueryBuilder();
122
+            $metaDataQuery->select([$this->dbForeignKeyName, 'key', 'value'])
123
+                ->from($this->dbMetaDataTableName);
124
+            $metaDataStmt = $metaDataQuery->execute();
125
+            $metaDataRows = $metaDataStmt->fetchAll(\PDO::FETCH_ASSOC);
126
+
127
+            $metaDataById = [];
128
+            foreach($metaDataRows as $metaDataRow) {
129
+                if (!isset($metaDataById[$metaDataRow[$this->dbForeignKeyName]])) {
130
+                    $metaDataById[$metaDataRow[$this->dbForeignKeyName]] = [];
131
+                }
132
+
133
+                $metaDataById[$metaDataRow[$this->dbForeignKeyName]][$metaDataRow['key']] =
134
+                    $metaDataRow['value'];
135
+            }
136
+
137
+            while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
138
+                $id = $row['id'];
139
+
140
+                if (isset($metaDataById[$id])) {
141
+                    $principals[] = $this->rowToPrincipal($row, $metaDataById[$id]);
142
+                } else {
143
+                    $principals[] = $this->rowToPrincipal($row);
144
+                }
145
+
146
+            }
147
+
148
+            $stmt->closeCursor();
149
+        }
150
+
151
+        return $principals;
152
+    }
153
+
154
+    /**
155
+     * Returns a specific principal, specified by it's path.
156
+     * The returned structure should be the exact same as from
157
+     * getPrincipalsByPrefix.
158
+     *
159
+     * @param string $path
160
+     * @return array
161
+     */
162
+    public function getPrincipalByPath($path) {
163
+        if (strpos($path, $this->principalPrefix) !== 0) {
164
+            return null;
165
+        }
166
+        list(, $name) = \Sabre\Uri\split($path);
167
+
168
+        list($backendId, $resourceId) = explode('-',  $name, 2);
169
+
170
+        $query = $this->db->getQueryBuilder();
171
+        $query->select(['id', 'backend_id', 'resource_id', 'email', 'displayname'])
172
+            ->from($this->dbTableName)
173
+            ->where($query->expr()->eq('backend_id', $query->createNamedParameter($backendId)))
174
+            ->andWhere($query->expr()->eq('resource_id', $query->createNamedParameter($resourceId)));
175
+        $stmt = $query->execute();
176
+        $row = $stmt->fetch(\PDO::FETCH_ASSOC);
177
+
178
+        if(!$row) {
179
+            return null;
180
+        }
181
+
182
+        $metaDataQuery = $this->db->getQueryBuilder();
183
+        $metaDataQuery->select(['key', 'value'])
184
+            ->from($this->dbMetaDataTableName)
185
+            ->where($metaDataQuery->expr()->eq($this->dbForeignKeyName, $metaDataQuery->createNamedParameter($row['id'])));
186
+        $metaDataStmt = $metaDataQuery->execute();
187
+        $metaDataRows = $metaDataStmt->fetchAll(\PDO::FETCH_ASSOC);
188
+        $metadata = [];
189
+
190
+        foreach($metaDataRows as $metaDataRow) {
191
+            $metadata[$metaDataRow['key']] = $metaDataRow['value'];
192
+        }
193
+
194
+        return $this->rowToPrincipal($row, $metadata);
195
+    }
196
+
197
+    /**
198
+     * @param int $id
199
+     * @return array|null
200
+     */
201
+    public function getPrincipalById($id):?array {
202
+        $query = $this->db->getQueryBuilder();
203
+        $query->select(['id', 'backend_id', 'resource_id', 'email', 'displayname'])
204
+            ->from($this->dbTableName)
205
+            ->where($query->expr()->eq('id', $query->createNamedParameter($id)));
206
+        $stmt = $query->execute();
207
+        $row = $stmt->fetch(\PDO::FETCH_ASSOC);
208
+
209
+        if(!$row) {
210
+            return null;
211
+        }
212
+
213
+        $metaDataQuery = $this->db->getQueryBuilder();
214
+        $metaDataQuery->select(['key', 'value'])
215
+            ->from($this->dbMetaDataTableName)
216
+            ->where($metaDataQuery->expr()->eq($this->dbForeignKeyName, $metaDataQuery->createNamedParameter($row['id'])));
217
+        $metaDataStmt = $metaDataQuery->execute();
218
+        $metaDataRows = $metaDataStmt->fetchAll(\PDO::FETCH_ASSOC);
219
+        $metadata = [];
220
+
221
+        foreach($metaDataRows as $metaDataRow) {
222
+            $metadata[$metaDataRow['key']] = $metaDataRow['value'];
223
+        }
224
+
225
+        return $this->rowToPrincipal($row, $metadata);
226
+    }
227
+
228
+    /**
229
+     * @param string $path
230
+     * @param PropPatch $propPatch
231
+     * @return int
232
+     */
233
+    function updatePrincipal($path, PropPatch $propPatch) {
234
+        return 0;
235
+    }
236
+
237
+    /**
238
+     * @param string $prefixPath
239
+     * @param array $searchProperties
240
+     * @param string $test
241
+     * @return array
242
+     */
243
+    function searchPrincipals($prefixPath, array $searchProperties, $test = 'allof') {
244
+        $results = [];
245
+        if (\count($searchProperties) === 0) {
246
+            return [];
247
+        }
248
+        if ($prefixPath !== $this->principalPrefix) {
249
+            return [];
250
+        }
251
+
252
+        $user = $this->userSession->getUser();
253
+        if (!$user) {
254
+            return [];
255
+        }
256
+        $usersGroups = $this->groupManager->getUserGroupIds($user);
257
+
258
+        foreach ($searchProperties as $prop => $value) {
259
+            switch ($prop) {
260
+                case '{http://sabredav.org/ns}email-address':
261
+                    $query = $this->db->getQueryBuilder();
262
+                    $query->select(['id', 'backend_id', 'resource_id', 'email', 'displayname', 'group_restrictions'])
263
+                        ->from($this->dbTableName)
264
+                        ->where($query->expr()->iLike('email', $query->createNamedParameter('%' . $this->db->escapeLikeParameter($value) . '%')));
265
+
266
+                    $stmt = $query->execute();
267
+                    $principals = [];
268
+                    while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
269
+                        if (!$this->isAllowedToAccessResource($row, $usersGroups)) {
270
+                            continue;
271
+                        }
272
+                        $principals[] = $this->rowToPrincipal($row)['uri'];
273
+                    }
274
+                    $results[] = $principals;
275
+
276
+                    $stmt->closeCursor();
277
+                    break;
278
+
279
+                case '{DAV:}displayname':
280
+                    $query = $this->db->getQueryBuilder();
281
+                    $query->select(['id', 'backend_id', 'resource_id', 'email', 'displayname', 'group_restrictions'])
282
+                        ->from($this->dbTableName)
283
+                        ->where($query->expr()->iLike('displayname', $query->createNamedParameter('%' . $this->db->escapeLikeParameter($value) . '%')));
284
+
285
+                    $stmt = $query->execute();
286
+                    $principals = [];
287
+                    while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
288
+                        if (!$this->isAllowedToAccessResource($row, $usersGroups)) {
289
+                            continue;
290
+                        }
291
+                        $principals[] = $this->rowToPrincipal($row)['uri'];
292
+                    }
293
+                    $results[] = $principals;
294
+
295
+                    $stmt->closeCursor();
296
+                    break;
297
+
298
+                case '{urn:ietf:params:xml:ns:caldav}calendar-user-address-set':
299
+                    // If you add support for more search properties that qualify as a user-address,
300
+                    // please also add them to the array below
301
+                    $results[] = $this->searchPrincipals($this->principalPrefix, [
302
+                        '{http://sabredav.org/ns}email-address' => $value,
303
+                    ], 'anyof');
304
+                    break;
305
+
306
+                default:
307
+                    $rowsByMetadata = $this->searchPrincipalsByMetadataKey($prop, $value);
308
+                    $filteredRows = array_filter($rowsByMetadata, function ($row) use ($usersGroups) {
309
+                        return $this->isAllowedToAccessResource($row, $usersGroups);
310
+                    });
311
+
312
+                    $results[] = array_map(function ($row) {
313
+                        return $row['uri'];
314
+                    }, $filteredRows);
315
+
316
+                    break;
317
+            }
318
+        }
319
+
320
+        // results is an array of arrays, so this is not the first search result
321
+        // but the results of the first searchProperty
322
+        if (count($results) === 1) {
323
+            return $results[0];
324
+        }
325
+
326
+        switch ($test) {
327
+            case 'anyof':
328
+                return array_values(array_unique(array_merge(...$results)));
329
+
330
+            case 'allof':
331
+            default:
332
+                return array_values(array_intersect(...$results));
333
+        }
334
+    }
335
+
336
+    /**
337
+     * Searches principals based on their metadata keys.
338
+     * This allows to search for all principals with a specific key.
339
+     * e.g.:
340
+     * '{http://nextcloud.com/ns}room-building-address' => 'ABC Street 123, ...'
341
+     *
342
+     * @param $key
343
+     * @param $value
344
+     * @return array
345
+     */
346
+    private function searchPrincipalsByMetadataKey($key, $value):array {
347
+        $query = $this->db->getQueryBuilder();
348
+        $query->select([$this->dbForeignKeyName])
349
+            ->from($this->dbMetaDataTableName)
350
+            ->where($query->expr()->eq('key', $query->createNamedParameter($key)))
351
+            ->andWhere($query->expr()->iLike('value', $query->createNamedParameter('%' . $this->db->escapeLikeParameter($value) . '%')));
352
+        $stmt = $query->execute();
353
+
354
+        $rows = [];
355
+        while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
356
+            $id = $row[$this->dbForeignKeyName];
357
+
358
+            $principalRow = $this->getPrincipalById($id);
359
+            if (!$principalRow) {
360
+                continue;
361
+            }
362
+
363
+            $rows[] = $principalRow;
364
+        }
365
+
366
+        return $rows;
367
+    }
368
+
369
+    /**
370
+     * @param string $uri
371
+     * @param string $principalPrefix
372
+     * @return null|string
373
+     */
374
+    function findByUri($uri, $principalPrefix) {
375
+        $user = $this->userSession->getUser();
376
+        if (!$user) {
377
+            return null;
378
+        }
379
+        $usersGroups = $this->groupManager->getUserGroupIds($user);
380
+
381
+        if (strpos($uri, 'mailto:') === 0) {
382
+            $email = substr($uri, 7);
383
+            $query = $this->db->getQueryBuilder();
384
+            $query->select(['id', 'backend_id', 'resource_id', 'email', 'displayname', 'group_restrictions'])
385
+                ->from($this->dbTableName)
386
+                ->where($query->expr()->eq('email', $query->createNamedParameter($email)));
387
+
388
+            $stmt = $query->execute();
389
+            $row = $stmt->fetch(\PDO::FETCH_ASSOC);
390
+
391
+            if(!$row) {
392
+                return null;
393
+            }
394
+            if (!$this->isAllowedToAccessResource($row, $usersGroups)) {
395
+                return null;
396
+            }
397
+
398
+            return $this->rowToPrincipal($row)['uri'];
399
+        }
400
+
401
+        if (strpos($uri, 'principal:') === 0) {
402
+            $path = substr($uri, 10);
403
+            if (strpos($path, $this->principalPrefix) !== 0) {
404
+                return null;
405
+            }
406
+
407
+            list(, $name) = \Sabre\Uri\split($path);
408
+            list($backendId, $resourceId) = explode('-',  $name, 2);
409
+
410
+            $query = $this->db->getQueryBuilder();
411
+            $query->select(['id', 'backend_id', 'resource_id', 'email', 'displayname', 'group_restrictions'])
412
+                ->from($this->dbTableName)
413
+                ->where($query->expr()->eq('backend_id', $query->createNamedParameter($backendId)))
414
+                ->andWhere($query->expr()->eq('resource_id', $query->createNamedParameter($resourceId)));
415
+            $stmt = $query->execute();
416
+            $row = $stmt->fetch(\PDO::FETCH_ASSOC);
417
+
418
+            if(!$row) {
419
+                return null;
420
+            }
421
+            if (!$this->isAllowedToAccessResource($row, $usersGroups)) {
422
+                return null;
423
+            }
424
+
425
+            return $this->rowToPrincipal($row)['uri'];
426
+        }
427
+
428
+        return null;
429
+    }
430
+
431
+    /**
432
+     * convert database row to principal
433
+     *
434
+     * @param String[] $row
435
+     * @param String[] $metadata
436
+     * @return Array
437
+     */
438
+    private function rowToPrincipal(array $row, array $metadata=[]):array {
439
+        return array_merge([
440
+            'uri' => $this->principalPrefix . '/' . $row['backend_id'] . '-' . $row['resource_id'],
441
+            '{DAV:}displayname' => $row['displayname'],
442
+            '{http://sabredav.org/ns}email-address' => $row['email'],
443
+            '{urn:ietf:params:xml:ns:caldav}calendar-user-type' => $this->cuType,
444
+        ], $metadata);
445
+    }
446
+
447
+    /**
448
+     * @param $row
449
+     * @param $userGroups
450
+     * @return bool
451
+     */
452
+    private function isAllowedToAccessResource(array $row, array $userGroups):bool {
453
+        if (!isset($row['group_restrictions']) ||
454
+            $row['group_restrictions'] === null ||
455
+            $row['group_restrictions'] === '') {
456
+            return true;
457
+        }
458
+
459
+        // group restrictions contains something, but not parsable, deny access and log warning
460
+        $json = json_decode($row['group_restrictions']);
461
+        if (!\is_array($json)) {
462
+            $this->logger->info('group_restrictions field could not be parsed for ' . $this->dbTableName . '::' . $row['id'] . ', denying access to resource');
463
+            return false;
464
+        }
465
+
466
+        // empty array => no group restrictions
467
+        if (empty($json)) {
468
+            return true;
469
+        }
470
+
471
+        return !empty(array_intersect($json, $userGroups));
472
+    }
473 473
 }
Please login to merge, or discard this patch.
Spacing   +25 added lines, -25 removed lines patch added patch discarded remove patch
@@ -88,9 +88,9 @@  discard block
 block discarded – undo
88 88
 		$this->logger = $logger;
89 89
 		$this->proxyMapper = $proxyMapper;
90 90
 		$this->principalPrefix = $principalPrefix;
91
-		$this->dbTableName = 'calendar_' . $dbPrefix . 's';
92
-		$this->dbMetaDataTableName = $this->dbTableName . '_md';
93
-		$this->dbForeignKeyName = $dbPrefix . '_id';
91
+		$this->dbTableName = 'calendar_'.$dbPrefix.'s';
92
+		$this->dbMetaDataTableName = $this->dbTableName.'_md';
93
+		$this->dbForeignKeyName = $dbPrefix.'_id';
94 94
 		$this->cuType = $cuType;
95 95
 	}
96 96
 
@@ -125,7 +125,7 @@  discard block
 block discarded – undo
125 125
 			$metaDataRows = $metaDataStmt->fetchAll(\PDO::FETCH_ASSOC);
126 126
 
127 127
 			$metaDataById = [];
128
-			foreach($metaDataRows as $metaDataRow) {
128
+			foreach ($metaDataRows as $metaDataRow) {
129 129
 				if (!isset($metaDataById[$metaDataRow[$this->dbForeignKeyName]])) {
130 130
 					$metaDataById[$metaDataRow[$this->dbForeignKeyName]] = [];
131 131
 				}
@@ -134,7 +134,7 @@  discard block
 block discarded – undo
134 134
 					$metaDataRow['value'];
135 135
 			}
136 136
 
137
-			while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
137
+			while ($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
138 138
 				$id = $row['id'];
139 139
 
140 140
 				if (isset($metaDataById[$id])) {
@@ -165,7 +165,7 @@  discard block
 block discarded – undo
165 165
 		}
166 166
 		list(, $name) = \Sabre\Uri\split($path);
167 167
 
168
-		list($backendId, $resourceId) = explode('-',  $name, 2);
168
+		list($backendId, $resourceId) = explode('-', $name, 2);
169 169
 
170 170
 		$query = $this->db->getQueryBuilder();
171 171
 		$query->select(['id', 'backend_id', 'resource_id', 'email', 'displayname'])
@@ -175,7 +175,7 @@  discard block
 block discarded – undo
175 175
 		$stmt = $query->execute();
176 176
 		$row = $stmt->fetch(\PDO::FETCH_ASSOC);
177 177
 
178
-		if(!$row) {
178
+		if (!$row) {
179 179
 			return null;
180 180
 		}
181 181
 
@@ -187,7 +187,7 @@  discard block
 block discarded – undo
187 187
 		$metaDataRows = $metaDataStmt->fetchAll(\PDO::FETCH_ASSOC);
188 188
 		$metadata = [];
189 189
 
190
-		foreach($metaDataRows as $metaDataRow) {
190
+		foreach ($metaDataRows as $metaDataRow) {
191 191
 			$metadata[$metaDataRow['key']] = $metaDataRow['value'];
192 192
 		}
193 193
 
@@ -198,7 +198,7 @@  discard block
 block discarded – undo
198 198
 	 * @param int $id
199 199
 	 * @return array|null
200 200
 	 */
201
-	public function getPrincipalById($id):?array {
201
+	public function getPrincipalById($id): ?array {
202 202
 		$query = $this->db->getQueryBuilder();
203 203
 		$query->select(['id', 'backend_id', 'resource_id', 'email', 'displayname'])
204 204
 			->from($this->dbTableName)
@@ -206,7 +206,7 @@  discard block
 block discarded – undo
206 206
 		$stmt = $query->execute();
207 207
 		$row = $stmt->fetch(\PDO::FETCH_ASSOC);
208 208
 
209
-		if(!$row) {
209
+		if (!$row) {
210 210
 			return null;
211 211
 		}
212 212
 
@@ -218,7 +218,7 @@  discard block
 block discarded – undo
218 218
 		$metaDataRows = $metaDataStmt->fetchAll(\PDO::FETCH_ASSOC);
219 219
 		$metadata = [];
220 220
 
221
-		foreach($metaDataRows as $metaDataRow) {
221
+		foreach ($metaDataRows as $metaDataRow) {
222 222
 			$metadata[$metaDataRow['key']] = $metaDataRow['value'];
223 223
 		}
224 224
 
@@ -261,11 +261,11 @@  discard block
 block discarded – undo
261 261
 					$query = $this->db->getQueryBuilder();
262 262
 					$query->select(['id', 'backend_id', 'resource_id', 'email', 'displayname', 'group_restrictions'])
263 263
 						->from($this->dbTableName)
264
-						->where($query->expr()->iLike('email', $query->createNamedParameter('%' . $this->db->escapeLikeParameter($value) . '%')));
264
+						->where($query->expr()->iLike('email', $query->createNamedParameter('%'.$this->db->escapeLikeParameter($value).'%')));
265 265
 
266 266
 					$stmt = $query->execute();
267 267
 					$principals = [];
268
-					while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
268
+					while ($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
269 269
 						if (!$this->isAllowedToAccessResource($row, $usersGroups)) {
270 270
 							continue;
271 271
 						}
@@ -280,11 +280,11 @@  discard block
 block discarded – undo
280 280
 					$query = $this->db->getQueryBuilder();
281 281
 					$query->select(['id', 'backend_id', 'resource_id', 'email', 'displayname', 'group_restrictions'])
282 282
 						->from($this->dbTableName)
283
-						->where($query->expr()->iLike('displayname', $query->createNamedParameter('%' . $this->db->escapeLikeParameter($value) . '%')));
283
+						->where($query->expr()->iLike('displayname', $query->createNamedParameter('%'.$this->db->escapeLikeParameter($value).'%')));
284 284
 
285 285
 					$stmt = $query->execute();
286 286
 					$principals = [];
287
-					while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
287
+					while ($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
288 288
 						if (!$this->isAllowedToAccessResource($row, $usersGroups)) {
289 289
 							continue;
290 290
 						}
@@ -305,11 +305,11 @@  discard block
 block discarded – undo
305 305
 
306 306
 				default:
307 307
 					$rowsByMetadata = $this->searchPrincipalsByMetadataKey($prop, $value);
308
-					$filteredRows = array_filter($rowsByMetadata, function ($row) use ($usersGroups) {
308
+					$filteredRows = array_filter($rowsByMetadata, function($row) use ($usersGroups) {
309 309
 						return $this->isAllowedToAccessResource($row, $usersGroups);
310 310
 					});
311 311
 
312
-					$results[] = array_map(function ($row) {
312
+					$results[] = array_map(function($row) {
313 313
 						return $row['uri'];
314 314
 					}, $filteredRows);
315 315
 
@@ -348,11 +348,11 @@  discard block
 block discarded – undo
348 348
 		$query->select([$this->dbForeignKeyName])
349 349
 			->from($this->dbMetaDataTableName)
350 350
 			->where($query->expr()->eq('key', $query->createNamedParameter($key)))
351
-			->andWhere($query->expr()->iLike('value', $query->createNamedParameter('%' . $this->db->escapeLikeParameter($value) . '%')));
351
+			->andWhere($query->expr()->iLike('value', $query->createNamedParameter('%'.$this->db->escapeLikeParameter($value).'%')));
352 352
 		$stmt = $query->execute();
353 353
 
354 354
 		$rows = [];
355
-		while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
355
+		while ($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
356 356
 			$id = $row[$this->dbForeignKeyName];
357 357
 
358 358
 			$principalRow = $this->getPrincipalById($id);
@@ -388,7 +388,7 @@  discard block
 block discarded – undo
388 388
 			$stmt = $query->execute();
389 389
 			$row = $stmt->fetch(\PDO::FETCH_ASSOC);
390 390
 
391
-			if(!$row) {
391
+			if (!$row) {
392 392
 				return null;
393 393
 			}
394 394
 			if (!$this->isAllowedToAccessResource($row, $usersGroups)) {
@@ -405,7 +405,7 @@  discard block
 block discarded – undo
405 405
 			}
406 406
 
407 407
 			list(, $name) = \Sabre\Uri\split($path);
408
-			list($backendId, $resourceId) = explode('-',  $name, 2);
408
+			list($backendId, $resourceId) = explode('-', $name, 2);
409 409
 
410 410
 			$query = $this->db->getQueryBuilder();
411 411
 			$query->select(['id', 'backend_id', 'resource_id', 'email', 'displayname', 'group_restrictions'])
@@ -415,7 +415,7 @@  discard block
 block discarded – undo
415 415
 			$stmt = $query->execute();
416 416
 			$row = $stmt->fetch(\PDO::FETCH_ASSOC);
417 417
 
418
-			if(!$row) {
418
+			if (!$row) {
419 419
 				return null;
420 420
 			}
421 421
 			if (!$this->isAllowedToAccessResource($row, $usersGroups)) {
@@ -435,9 +435,9 @@  discard block
 block discarded – undo
435 435
 	 * @param String[] $metadata
436 436
 	 * @return Array
437 437
 	 */
438
-	private function rowToPrincipal(array $row, array $metadata=[]):array {
438
+	private function rowToPrincipal(array $row, array $metadata = []):array {
439 439
 		return array_merge([
440
-			'uri' => $this->principalPrefix . '/' . $row['backend_id'] . '-' . $row['resource_id'],
440
+			'uri' => $this->principalPrefix.'/'.$row['backend_id'].'-'.$row['resource_id'],
441 441
 			'{DAV:}displayname' => $row['displayname'],
442 442
 			'{http://sabredav.org/ns}email-address' => $row['email'],
443 443
 			'{urn:ietf:params:xml:ns:caldav}calendar-user-type' => $this->cuType,
@@ -459,7 +459,7 @@  discard block
 block discarded – undo
459 459
 		// group restrictions contains something, but not parsable, deny access and log warning
460 460
 		$json = json_decode($row['group_restrictions']);
461 461
 		if (!\is_array($json)) {
462
-			$this->logger->info('group_restrictions field could not be parsed for ' . $this->dbTableName . '::' . $row['id'] . ', denying access to resource');
462
+			$this->logger->info('group_restrictions field could not be parsed for '.$this->dbTableName.'::'.$row['id'].', denying access to resource');
463 463
 			return false;
464 464
 		}
465 465
 
Please login to merge, or discard this patch.
apps/dav/lib/CalDAV/Reminder/ReminderService.php 2 patches
Indentation   +734 added lines, -734 removed lines patch added patch discarded remove patch
@@ -45,738 +45,738 @@
 block discarded – undo
45 45
 
46 46
 class ReminderService {
47 47
 
48
-	/** @var Backend */
49
-	private $backend;
50
-
51
-	/** @var NotificationProviderManager */
52
-	private $notificationProviderManager;
53
-
54
-	/** @var IUserManager */
55
-	private $userManager;
56
-
57
-	/** @var IGroupManager */
58
-	private $groupManager;
59
-
60
-	/** @var CalDavBackend */
61
-	private $caldavBackend;
62
-
63
-	/** @var ITimeFactory */
64
-	private $timeFactory;
65
-
66
-	public const REMINDER_TYPE_EMAIL = 'EMAIL';
67
-	public const REMINDER_TYPE_DISPLAY = 'DISPLAY';
68
-	public const REMINDER_TYPE_AUDIO = 'AUDIO';
69
-
70
-	/**
71
-	 * @var String[]
72
-	 *
73
-	 * Official RFC5545 reminder types
74
-	 */
75
-	public const REMINDER_TYPES = [
76
-		self::REMINDER_TYPE_EMAIL,
77
-		self::REMINDER_TYPE_DISPLAY,
78
-		self::REMINDER_TYPE_AUDIO
79
-	];
80
-
81
-	/**
82
-	 * ReminderService constructor.
83
-	 *
84
-	 * @param Backend $backend
85
-	 * @param NotificationProviderManager $notificationProviderManager
86
-	 * @param IUserManager $userManager
87
-	 * @param IGroupManager $groupManager
88
-	 * @param CalDavBackend $caldavBackend
89
-	 * @param ITimeFactory $timeFactory
90
-	 */
91
-	public function __construct(Backend $backend,
92
-								NotificationProviderManager $notificationProviderManager,
93
-								IUserManager $userManager,
94
-								IGroupManager $groupManager,
95
-								CalDavBackend $caldavBackend,
96
-								ITimeFactory $timeFactory) {
97
-		$this->backend = $backend;
98
-		$this->notificationProviderManager = $notificationProviderManager;
99
-		$this->userManager = $userManager;
100
-		$this->groupManager = $groupManager;
101
-		$this->caldavBackend = $caldavBackend;
102
-		$this->timeFactory = $timeFactory;
103
-	}
104
-
105
-	/**
106
-	 * Process reminders to activate
107
-	 *
108
-	 * @throws NotificationProvider\ProviderNotAvailableException
109
-	 * @throws NotificationTypeDoesNotExistException
110
-	 */
111
-	public function processReminders():void {
112
-		$reminders = $this->backend->getRemindersToProcess();
113
-
114
-		foreach($reminders as $reminder) {
115
-			$calendarData = is_resource($reminder['calendardata'])
116
-				? stream_get_contents($reminder['calendardata'])
117
-				: $reminder['calendardata'];
118
-
119
-			$vcalendar = $this->parseCalendarData($calendarData);
120
-			if (!$vcalendar) {
121
-				$this->backend->removeReminder($reminder['id']);
122
-				continue;
123
-			}
124
-
125
-			$vevent = $this->getVEventByRecurrenceId($vcalendar, $reminder['recurrence_id'], $reminder['is_recurrence_exception']);
126
-			if (!$vevent) {
127
-				$this->backend->removeReminder($reminder['id']);
128
-				continue;
129
-			}
130
-
131
-			if ($this->wasEventCancelled($vevent)) {
132
-				$this->deleteOrProcessNext($reminder, $vevent);
133
-				continue;
134
-			}
135
-
136
-			if (!$this->notificationProviderManager->hasProvider($reminder['type'])) {
137
-				$this->deleteOrProcessNext($reminder, $vevent);
138
-				continue;
139
-			}
140
-
141
-			$users = $this->getAllUsersWithWriteAccessToCalendar($reminder['calendar_id']);
142
-			$user = $this->getUserFromPrincipalURI($reminder['principaluri']);
143
-			if ($user) {
144
-				$users[] = $user;
145
-			}
146
-
147
-			$notificationProvider = $this->notificationProviderManager->getProvider($reminder['type']);
148
-			$notificationProvider->send($vevent, $reminder['displayname'], $users);
149
-
150
-			$this->deleteOrProcessNext($reminder, $vevent);
151
-		}
152
-	}
153
-
154
-	/**
155
-	 * @param string $action
156
-	 * @param array $objectData
157
-	 * @throws VObject\InvalidDataException
158
-	 */
159
-	public function onTouchCalendarObject(string $action,
160
-										  array $objectData):void {
161
-		// We only support VEvents for now
162
-		if (strcasecmp($objectData['component'], 'vevent') !== 0) {
163
-			return;
164
-		}
165
-
166
-		switch($action) {
167
-			case '\OCA\DAV\CalDAV\CalDavBackend::createCalendarObject':
168
-				$this->onCalendarObjectCreate($objectData);
169
-				break;
170
-
171
-			case '\OCA\DAV\CalDAV\CalDavBackend::updateCalendarObject':
172
-				$this->onCalendarObjectEdit($objectData);
173
-				break;
174
-
175
-			case '\OCA\DAV\CalDAV\CalDavBackend::deleteCalendarObject':
176
-				$this->onCalendarObjectDelete($objectData);
177
-				break;
178
-
179
-			default:
180
-				break;
181
-		}
182
-	}
183
-
184
-	/**
185
-	 * @param array $objectData
186
-	 */
187
-	private function onCalendarObjectCreate(array $objectData):void {
188
-		$calendarData = is_resource($objectData['calendardata'])
189
-			? stream_get_contents($objectData['calendardata'])
190
-			: $objectData['calendardata'];
191
-
192
-		/** @var VObject\Component\VCalendar $vcalendar */
193
-		$vcalendar = $this->parseCalendarData($calendarData);
194
-		if (!$vcalendar) {
195
-			return;
196
-		}
197
-
198
-		$vevents = $this->getAllVEventsFromVCalendar($vcalendar);
199
-		if (count($vevents) === 0) {
200
-			return;
201
-		}
202
-
203
-		$uid = (string) $vevents[0]->UID;
204
-		$recurrenceExceptions = $this->getRecurrenceExceptionFromListOfVEvents($vevents);
205
-		$masterItem = $this->getMasterItemFromListOfVEvents($vevents);
206
-		$now = $this->timeFactory->getDateTime();
207
-		$isRecurring = $masterItem ? $this->isRecurring($masterItem) : false;
208
-
209
-		foreach($recurrenceExceptions as $recurrenceException) {
210
-			$eventHash = $this->getEventHash($recurrenceException);
211
-
212
-			if (!isset($recurrenceException->VALARM)) {
213
-				continue;
214
-			}
215
-
216
-			foreach($recurrenceException->VALARM as $valarm) {
217
-				/** @var VAlarm $valarm */
218
-				$alarmHash = $this->getAlarmHash($valarm);
219
-				$triggerTime = $valarm->getEffectiveTriggerTime();
220
-				$diff = $now->diff($triggerTime);
221
-				if ($diff->invert === 1) {
222
-					continue;
223
-				}
224
-
225
-				$alarms = $this->getRemindersForVAlarm($valarm, $objectData,
226
-					$eventHash, $alarmHash, true, true);
227
-				$this->writeRemindersToDatabase($alarms);
228
-			}
229
-		}
230
-
231
-		if ($masterItem) {
232
-			$processedAlarms = [];
233
-			$masterAlarms = [];
234
-			$masterHash = $this->getEventHash($masterItem);
235
-
236
-			if (!isset($masterItem->VALARM)) {
237
-				return;
238
-			}
239
-
240
-			foreach($masterItem->VALARM as $valarm) {
241
-				$masterAlarms[] = $this->getAlarmHash($valarm);
242
-			}
243
-
244
-			try {
245
-				$iterator = new EventIterator($vevents, $uid);
246
-			} catch (NoInstancesException $e) {
247
-				// This event is recurring, but it doesn't have a single
248
-				// instance. We are skipping this event from the output
249
-				// entirely.
250
-				return;
251
-			}
252
-
253
-			while($iterator->valid() && count($processedAlarms) < count($masterAlarms)) {
254
-				$event = $iterator->getEventObject();
255
-
256
-				// Recurrence-exceptions are handled separately, so just ignore them here
257
-				if (\in_array($event, $recurrenceExceptions, true)) {
258
-					$iterator->next();
259
-					continue;
260
-				}
261
-
262
-				foreach($event->VALARM as $valarm) {
263
-					/** @var VAlarm $valarm */
264
-					$alarmHash = $this->getAlarmHash($valarm);
265
-					if (\in_array($alarmHash, $processedAlarms, true)) {
266
-						continue;
267
-					}
268
-
269
-					if (!\in_array((string) $valarm->ACTION, self::REMINDER_TYPES, true)) {
270
-						// Action allows x-name, we don't insert reminders
271
-						// into the database if they are not standard
272
-						$processedAlarms[] = $alarmHash;
273
-						continue;
274
-					}
275
-
276
-					$triggerTime = $valarm->getEffectiveTriggerTime();
277
-
278
-					// If effective trigger time is in the past
279
-					// just skip and generate for next event
280
-					$diff = $now->diff($triggerTime);
281
-					if ($diff->invert === 1) {
282
-						// If an absolute alarm is in the past,
283
-						// just add it to processedAlarms, so
284
-						// we don't extend till eternity
285
-						if (!$this->isAlarmRelative($valarm)) {
286
-							$processedAlarms[] = $alarmHash;
287
-						}
288
-
289
-						continue;
290
-					}
291
-
292
-					$alarms = $this->getRemindersForVAlarm($valarm, $objectData, $masterHash, $alarmHash, $isRecurring, false);
293
-					$this->writeRemindersToDatabase($alarms);
294
-					$processedAlarms[] = $alarmHash;
295
-				}
296
-
297
-				$iterator->next();
298
-			}
299
-		}
300
-	}
301
-
302
-	/**
303
-	 * @param array $objectData
304
-	 */
305
-	private function onCalendarObjectEdit(array $objectData):void {
306
-		// TODO - this can be vastly improved
307
-		//  - get cached reminders
308
-		//  - ...
309
-
310
-		$this->onCalendarObjectDelete($objectData);
311
-		$this->onCalendarObjectCreate($objectData);
312
-	}
313
-
314
-	/**
315
-	 * @param array $objectData
316
-	 */
317
-	private function onCalendarObjectDelete(array $objectData):void {
318
-		$this->backend->cleanRemindersForEvent((int) $objectData['id']);
319
-	}
320
-
321
-	/**
322
-	 * @param VAlarm $valarm
323
-	 * @param array $objectData
324
-	 * @param string|null $eventHash
325
-	 * @param string|null $alarmHash
326
-	 * @param bool $isRecurring
327
-	 * @param bool $isRecurrenceException
328
-	 * @return array
329
-	 */
330
-	private function getRemindersForVAlarm(VAlarm $valarm,
331
-										   array $objectData,
332
-										   string $eventHash=null,
333
-										   string $alarmHash=null,
334
-										   bool $isRecurring=false,
335
-										   bool $isRecurrenceException=false):array {
336
-		if ($eventHash === null) {
337
-			$eventHash = $this->getEventHash($valarm->parent);
338
-		}
339
-		if ($alarmHash === null) {
340
-			$alarmHash = $this->getAlarmHash($valarm);
341
-		}
342
-
343
-		$recurrenceId = $this->getEffectiveRecurrenceIdOfVEvent($valarm->parent);
344
-		$isRelative = $this->isAlarmRelative($valarm);
345
-		/** @var DateTimeImmutable $notificationDate */
346
-		$notificationDate = $valarm->getEffectiveTriggerTime();
347
-		$clonedNotificationDate = new \DateTime('now', $notificationDate->getTimezone());
348
-		$clonedNotificationDate->setTimestamp($notificationDate->getTimestamp());
349
-
350
-		$alarms = [];
351
-
352
-		$alarms[] = [
353
-			'calendar_id' => $objectData['calendarid'],
354
-			'object_id' => $objectData['id'],
355
-			'uid' => (string) $valarm->parent->UID,
356
-			'is_recurring' => $isRecurring,
357
-			'recurrence_id' => $recurrenceId,
358
-			'is_recurrence_exception' => $isRecurrenceException,
359
-			'event_hash' => $eventHash,
360
-			'alarm_hash' => $alarmHash,
361
-			'type' => (string) $valarm->ACTION,
362
-			'is_relative' => $isRelative,
363
-			'notification_date' => $notificationDate->getTimestamp(),
364
-			'is_repeat_based' => false,
365
-		];
366
-
367
-		$repeat = isset($valarm->REPEAT) ? (int) $valarm->REPEAT->getValue() : 0;
368
-		for($i = 0; $i < $repeat; $i++) {
369
-			if ($valarm->DURATION === null) {
370
-				continue;
371
-			}
372
-
373
-			$clonedNotificationDate->add($valarm->DURATION->getDateInterval());
374
-			$alarms[] = [
375
-				'calendar_id' => $objectData['calendarid'],
376
-				'object_id' => $objectData['id'],
377
-				'uid' => (string) $valarm->parent->UID,
378
-				'is_recurring' => $isRecurring,
379
-				'recurrence_id' => $recurrenceId,
380
-				'is_recurrence_exception' => $isRecurrenceException,
381
-				'event_hash' => $eventHash,
382
-				'alarm_hash' => $alarmHash,
383
-				'type' => (string) $valarm->ACTION,
384
-				'is_relative' => $isRelative,
385
-				'notification_date' => $clonedNotificationDate->getTimestamp(),
386
-				'is_repeat_based' => true,
387
-			];
388
-		}
389
-
390
-		return $alarms;
391
-	}
392
-
393
-	/**
394
-	 * @param array $reminders
395
-	 */
396
-	private function writeRemindersToDatabase(array $reminders): void {
397
-		foreach($reminders as $reminder) {
398
-			$this->backend->insertReminder(
399
-				(int) $reminder['calendar_id'],
400
-				(int) $reminder['object_id'],
401
-				$reminder['uid'],
402
-				$reminder['is_recurring'],
403
-				(int) $reminder['recurrence_id'],
404
-				$reminder['is_recurrence_exception'],
405
-				$reminder['event_hash'],
406
-				$reminder['alarm_hash'],
407
-				$reminder['type'],
408
-				$reminder['is_relative'],
409
-				(int) $reminder['notification_date'],
410
-				$reminder['is_repeat_based']
411
-			);
412
-		}
413
-	}
414
-
415
-	/**
416
-	 * @param array $reminder
417
-	 * @param VEvent $vevent
418
-	 */
419
-	private function deleteOrProcessNext(array $reminder,
420
-										 VObject\Component\VEvent $vevent):void {
421
-		if ($reminder['is_repeat_based'] ||
422
-			!$reminder['is_recurring'] ||
423
-			!$reminder['is_relative'] ||
424
-			$reminder['is_recurrence_exception']) {
425
-
426
-			$this->backend->removeReminder($reminder['id']);
427
-			return;
428
-		}
429
-
430
-		$vevents = $this->getAllVEventsFromVCalendar($vevent->parent);
431
-		$recurrenceExceptions = $this->getRecurrenceExceptionFromListOfVEvents($vevents);
432
-		$now = $this->timeFactory->getDateTime();
433
-
434
-		try {
435
-			$iterator = new EventIterator($vevents, $reminder['uid']);
436
-		} catch (NoInstancesException $e) {
437
-			// This event is recurring, but it doesn't have a single
438
-			// instance. We are skipping this event from the output
439
-			// entirely.
440
-			return;
441
-		}
442
-
443
-		while($iterator->valid()) {
444
-			$event = $iterator->getEventObject();
445
-
446
-			// Recurrence-exceptions are handled separately, so just ignore them here
447
-			if (\in_array($event, $recurrenceExceptions, true)) {
448
-				$iterator->next();
449
-				continue;
450
-			}
451
-
452
-			$recurrenceId = $this->getEffectiveRecurrenceIdOfVEvent($event);
453
-			if ($reminder['recurrence_id'] >= $recurrenceId) {
454
-				$iterator->next();
455
-				continue;
456
-			}
457
-
458
-			foreach($event->VALARM as $valarm) {
459
-				/** @var VAlarm $valarm */
460
-				$alarmHash = $this->getAlarmHash($valarm);
461
-				if ($alarmHash !== $reminder['alarm_hash']) {
462
-					continue;
463
-				}
464
-
465
-				$triggerTime = $valarm->getEffectiveTriggerTime();
466
-
467
-				// If effective trigger time is in the past
468
-				// just skip and generate for next event
469
-				$diff = $now->diff($triggerTime);
470
-				if ($diff->invert === 1) {
471
-					continue;
472
-				}
473
-
474
-				$this->backend->removeReminder($reminder['id']);
475
-				$alarms = $this->getRemindersForVAlarm($valarm, [
476
-					'calendarid' => $reminder['calendar_id'],
477
-					'id' => $reminder['object_id'],
478
-				], $reminder['event_hash'], $alarmHash, true, false);
479
-				$this->writeRemindersToDatabase($alarms);
480
-
481
-				// Abort generating reminders after creating one successfully
482
-				return;
483
-			}
484
-
485
-			$iterator->next();
486
-		}
487
-
488
-		$this->backend->removeReminder($reminder['id']);
489
-	}
490
-
491
-	/**
492
-	 * @param int $calendarId
493
-	 * @return IUser[]
494
-	 */
495
-	private function getAllUsersWithWriteAccessToCalendar(int $calendarId):array {
496
-		$shares = $this->caldavBackend->getShares($calendarId);
497
-
498
-		$users = [];
499
-		$userIds = [];
500
-		$groups = [];
501
-		foreach ($shares as $share) {
502
-			// Only consider writable shares
503
-			if ($share['readOnly']) {
504
-				continue;
505
-			}
506
-
507
-			$principal = explode('/', $share['{http://owncloud.org/ns}principal']);
508
-			if ($principal[1] === 'users') {
509
-				$user = $this->userManager->get($principal[2]);
510
-				if ($user) {
511
-					$users[] = $user;
512
-					$userIds[] = $principal[2];
513
-				}
514
-			} else if ($principal[1] === 'groups') {
515
-				$groups[] = $principal[2];
516
-			}
517
-		}
518
-
519
-		foreach ($groups as $gid) {
520
-			$group = $this->groupManager->get($gid);
521
-			if ($group instanceof IGroup) {
522
-				foreach ($group->getUsers() as $user) {
523
-					if (!\in_array($user->getUID(), $userIds, true)) {
524
-						$users[] = $user;
525
-						$userIds[] = $user->getUID();
526
-					}
527
-				}
528
-			}
529
-		}
530
-
531
-		return $users;
532
-	}
533
-
534
-	/**
535
-	 * Gets a hash of the event.
536
-	 * If the hash changes, we have to update all relative alarms.
537
-	 *
538
-	 * @param VEvent $vevent
539
-	 * @return string
540
-	 */
541
-	private function getEventHash(VEvent $vevent):string {
542
-		$properties = [
543
-			(string) $vevent->DTSTART->serialize(),
544
-		];
545
-
546
-		if ($vevent->DTEND) {
547
-			$properties[] = (string) $vevent->DTEND->serialize();
548
-		}
549
-		if ($vevent->DURATION) {
550
-			$properties[] = (string) $vevent->DURATION->serialize();
551
-		}
552
-		if ($vevent->{'RECURRENCE-ID'}) {
553
-			$properties[] = (string) $vevent->{'RECURRENCE-ID'}->serialize();
554
-		}
555
-		if ($vevent->RRULE) {
556
-			$properties[] = (string) $vevent->RRULE->serialize();
557
-		}
558
-		if ($vevent->EXDATE) {
559
-			$properties[] = (string) $vevent->EXDATE->serialize();
560
-		}
561
-		if ($vevent->RDATE) {
562
-			$properties[] = (string) $vevent->RDATE->serialize();
563
-		}
564
-
565
-		return md5(implode('::', $properties));
566
-	}
567
-
568
-	/**
569
-	 * Gets a hash of the alarm.
570
-	 * If the hash changes, we have to update oc_dav_reminders.
571
-	 *
572
-	 * @param VAlarm $valarm
573
-	 * @return string
574
-	 */
575
-	private function getAlarmHash(VAlarm $valarm):string {
576
-		$properties = [
577
-			(string) $valarm->ACTION->serialize(),
578
-			(string) $valarm->TRIGGER->serialize(),
579
-		];
580
-
581
-		if ($valarm->DURATION) {
582
-			$properties[] = (string) $valarm->DURATION->serialize();
583
-		}
584
-		if ($valarm->REPEAT) {
585
-			$properties[] = (string) $valarm->REPEAT->serialize();
586
-		}
587
-
588
-		return md5(implode('::', $properties));
589
-	}
590
-
591
-	/**
592
-	 * @param VObject\Component\VCalendar $vcalendar
593
-	 * @param int $recurrenceId
594
-	 * @param bool $isRecurrenceException
595
-	 * @return VEvent|null
596
-	 */
597
-	private function getVEventByRecurrenceId(VObject\Component\VCalendar $vcalendar,
598
-											 int $recurrenceId,
599
-											 bool $isRecurrenceException):?VEvent {
600
-		$vevents = $this->getAllVEventsFromVCalendar($vcalendar);
601
-		if (count($vevents) === 0) {
602
-			return null;
603
-		}
604
-
605
-		$uid = (string) $vevents[0]->UID;
606
-		$recurrenceExceptions = $this->getRecurrenceExceptionFromListOfVEvents($vevents);
607
-		$masterItem = $this->getMasterItemFromListOfVEvents($vevents);
608
-
609
-		// Handle recurrence-exceptions first, because recurrence-expansion is expensive
610
-		if ($isRecurrenceException) {
611
-			foreach($recurrenceExceptions as $recurrenceException) {
612
-				if ($this->getEffectiveRecurrenceIdOfVEvent($recurrenceException) === $recurrenceId) {
613
-					return $recurrenceException;
614
-				}
615
-			}
616
-
617
-			return null;
618
-		}
619
-
620
-		if ($masterItem) {
621
-			try {
622
-				$iterator = new EventIterator($vevents, $uid);
623
-			} catch (NoInstancesException $e) {
624
-				// This event is recurring, but it doesn't have a single
625
-				// instance. We are skipping this event from the output
626
-				// entirely.
627
-				return null;
628
-			}
629
-
630
-			while ($iterator->valid()) {
631
-				$event = $iterator->getEventObject();
632
-
633
-				// Recurrence-exceptions are handled separately, so just ignore them here
634
-				if (\in_array($event, $recurrenceExceptions, true)) {
635
-					$iterator->next();
636
-					continue;
637
-				}
638
-
639
-				if ($this->getEffectiveRecurrenceIdOfVEvent($event) === $recurrenceId) {
640
-					return $event;
641
-				}
642
-
643
-				$iterator->next();
644
-			}
645
-		}
646
-
647
-		return null;
648
-	}
649
-
650
-	/**
651
-	 * @param VEvent $vevent
652
-	 * @return string
653
-	 */
654
-	private function getStatusOfEvent(VEvent $vevent):string {
655
-		if ($vevent->STATUS) {
656
-			return (string) $vevent->STATUS;
657
-		}
658
-
659
-		// Doesn't say so in the standard,
660
-		// but we consider events without a status
661
-		// to be confirmed
662
-		return 'CONFIRMED';
663
-	}
664
-
665
-	/**
666
-	 * @param VObject\Component\VEvent $vevent
667
-	 * @return bool
668
-	 */
669
-	private function wasEventCancelled(VObject\Component\VEvent $vevent):bool {
670
-		return $this->getStatusOfEvent($vevent) === 'CANCELLED';
671
-	}
672
-
673
-	/**
674
-	 * @param string $calendarData
675
-	 * @return VObject\Component\VCalendar|null
676
-	 */
677
-	private function parseCalendarData(string $calendarData):?VObject\Component\VCalendar {
678
-		try {
679
-			return VObject\Reader::read($calendarData,
680
-				VObject\Reader::OPTION_FORGIVING);
681
-		} catch(ParseException $ex) {
682
-			return null;
683
-		}
684
-	}
685
-
686
-	/**
687
-	 * @param string $principalUri
688
-	 * @return IUser|null
689
-	 */
690
-	private function getUserFromPrincipalURI(string $principalUri):?IUser {
691
-		if (!$principalUri) {
692
-			return null;
693
-		}
694
-
695
-		if (stripos($principalUri, 'principals/users/') !== 0) {
696
-			return null;
697
-		}
698
-
699
-		$userId = substr($principalUri, 17);
700
-		return $this->userManager->get($userId);
701
-	}
702
-
703
-	/**
704
-	 * @param VObject\Component\VCalendar $vcalendar
705
-	 * @return VObject\Component\VEvent[]
706
-	 */
707
-	private function getAllVEventsFromVCalendar(VObject\Component\VCalendar $vcalendar):array {
708
-		$vevents = [];
709
-
710
-		foreach($vcalendar->children() as $child) {
711
-			if (!($child instanceof VObject\Component)) {
712
-				continue;
713
-			}
714
-
715
-			if ($child->name !== 'VEVENT') {
716
-				continue;
717
-			}
718
-
719
-			$vevents[] = $child;
720
-		}
721
-
722
-		return $vevents;
723
-	}
724
-
725
-	/**
726
-	 * @param array $vevents
727
-	 * @return VObject\Component\VEvent[]
728
-	 */
729
-	private function getRecurrenceExceptionFromListOfVEvents(array $vevents):array {
730
-		return array_values(array_filter($vevents, function (VEvent $vevent) {
731
-			return $vevent->{'RECURRENCE-ID'} !== null;
732
-		}));
733
-	}
734
-
735
-	/**
736
-	 * @param array $vevents
737
-	 * @return VEvent|null
738
-	 */
739
-	private function getMasterItemFromListOfVEvents(array $vevents):?VEvent {
740
-		$elements = array_values(array_filter($vevents, function (VEvent $vevent) {
741
-			return $vevent->{'RECURRENCE-ID'} === null;
742
-		}));
743
-
744
-		if (count($elements) === 0) {
745
-			return null;
746
-		}
747
-		if (count($elements) > 1) {
748
-			throw new \TypeError('Multiple master objects');
749
-		}
750
-
751
-		return $elements[0];
752
-	}
753
-
754
-	/**
755
-	 * @param VAlarm $valarm
756
-	 * @return bool
757
-	 */
758
-	private function isAlarmRelative(VAlarm $valarm):bool {
759
-		$trigger = $valarm->TRIGGER;
760
-		return $trigger instanceof VObject\Property\ICalendar\Duration;
761
-	}
762
-
763
-	/**
764
-	 * @param VEvent $vevent
765
-	 * @return int
766
-	 */
767
-	private function getEffectiveRecurrenceIdOfVEvent(VEvent $vevent):int {
768
-		if (isset($vevent->{'RECURRENCE-ID'})) {
769
-			return $vevent->{'RECURRENCE-ID'}->getDateTime()->getTimestamp();
770
-		}
771
-
772
-		return $vevent->DTSTART->getDateTime()->getTimestamp();
773
-	}
774
-
775
-	/**
776
-	 * @param VEvent $vevent
777
-	 * @return bool
778
-	 */
779
-	private function isRecurring(VEvent $vevent):bool {
780
-		return isset($vevent->RRULE) || isset($vevent->RDATE);
781
-	}
48
+    /** @var Backend */
49
+    private $backend;
50
+
51
+    /** @var NotificationProviderManager */
52
+    private $notificationProviderManager;
53
+
54
+    /** @var IUserManager */
55
+    private $userManager;
56
+
57
+    /** @var IGroupManager */
58
+    private $groupManager;
59
+
60
+    /** @var CalDavBackend */
61
+    private $caldavBackend;
62
+
63
+    /** @var ITimeFactory */
64
+    private $timeFactory;
65
+
66
+    public const REMINDER_TYPE_EMAIL = 'EMAIL';
67
+    public const REMINDER_TYPE_DISPLAY = 'DISPLAY';
68
+    public const REMINDER_TYPE_AUDIO = 'AUDIO';
69
+
70
+    /**
71
+     * @var String[]
72
+     *
73
+     * Official RFC5545 reminder types
74
+     */
75
+    public const REMINDER_TYPES = [
76
+        self::REMINDER_TYPE_EMAIL,
77
+        self::REMINDER_TYPE_DISPLAY,
78
+        self::REMINDER_TYPE_AUDIO
79
+    ];
80
+
81
+    /**
82
+     * ReminderService constructor.
83
+     *
84
+     * @param Backend $backend
85
+     * @param NotificationProviderManager $notificationProviderManager
86
+     * @param IUserManager $userManager
87
+     * @param IGroupManager $groupManager
88
+     * @param CalDavBackend $caldavBackend
89
+     * @param ITimeFactory $timeFactory
90
+     */
91
+    public function __construct(Backend $backend,
92
+                                NotificationProviderManager $notificationProviderManager,
93
+                                IUserManager $userManager,
94
+                                IGroupManager $groupManager,
95
+                                CalDavBackend $caldavBackend,
96
+                                ITimeFactory $timeFactory) {
97
+        $this->backend = $backend;
98
+        $this->notificationProviderManager = $notificationProviderManager;
99
+        $this->userManager = $userManager;
100
+        $this->groupManager = $groupManager;
101
+        $this->caldavBackend = $caldavBackend;
102
+        $this->timeFactory = $timeFactory;
103
+    }
104
+
105
+    /**
106
+     * Process reminders to activate
107
+     *
108
+     * @throws NotificationProvider\ProviderNotAvailableException
109
+     * @throws NotificationTypeDoesNotExistException
110
+     */
111
+    public function processReminders():void {
112
+        $reminders = $this->backend->getRemindersToProcess();
113
+
114
+        foreach($reminders as $reminder) {
115
+            $calendarData = is_resource($reminder['calendardata'])
116
+                ? stream_get_contents($reminder['calendardata'])
117
+                : $reminder['calendardata'];
118
+
119
+            $vcalendar = $this->parseCalendarData($calendarData);
120
+            if (!$vcalendar) {
121
+                $this->backend->removeReminder($reminder['id']);
122
+                continue;
123
+            }
124
+
125
+            $vevent = $this->getVEventByRecurrenceId($vcalendar, $reminder['recurrence_id'], $reminder['is_recurrence_exception']);
126
+            if (!$vevent) {
127
+                $this->backend->removeReminder($reminder['id']);
128
+                continue;
129
+            }
130
+
131
+            if ($this->wasEventCancelled($vevent)) {
132
+                $this->deleteOrProcessNext($reminder, $vevent);
133
+                continue;
134
+            }
135
+
136
+            if (!$this->notificationProviderManager->hasProvider($reminder['type'])) {
137
+                $this->deleteOrProcessNext($reminder, $vevent);
138
+                continue;
139
+            }
140
+
141
+            $users = $this->getAllUsersWithWriteAccessToCalendar($reminder['calendar_id']);
142
+            $user = $this->getUserFromPrincipalURI($reminder['principaluri']);
143
+            if ($user) {
144
+                $users[] = $user;
145
+            }
146
+
147
+            $notificationProvider = $this->notificationProviderManager->getProvider($reminder['type']);
148
+            $notificationProvider->send($vevent, $reminder['displayname'], $users);
149
+
150
+            $this->deleteOrProcessNext($reminder, $vevent);
151
+        }
152
+    }
153
+
154
+    /**
155
+     * @param string $action
156
+     * @param array $objectData
157
+     * @throws VObject\InvalidDataException
158
+     */
159
+    public function onTouchCalendarObject(string $action,
160
+                                            array $objectData):void {
161
+        // We only support VEvents for now
162
+        if (strcasecmp($objectData['component'], 'vevent') !== 0) {
163
+            return;
164
+        }
165
+
166
+        switch($action) {
167
+            case '\OCA\DAV\CalDAV\CalDavBackend::createCalendarObject':
168
+                $this->onCalendarObjectCreate($objectData);
169
+                break;
170
+
171
+            case '\OCA\DAV\CalDAV\CalDavBackend::updateCalendarObject':
172
+                $this->onCalendarObjectEdit($objectData);
173
+                break;
174
+
175
+            case '\OCA\DAV\CalDAV\CalDavBackend::deleteCalendarObject':
176
+                $this->onCalendarObjectDelete($objectData);
177
+                break;
178
+
179
+            default:
180
+                break;
181
+        }
182
+    }
183
+
184
+    /**
185
+     * @param array $objectData
186
+     */
187
+    private function onCalendarObjectCreate(array $objectData):void {
188
+        $calendarData = is_resource($objectData['calendardata'])
189
+            ? stream_get_contents($objectData['calendardata'])
190
+            : $objectData['calendardata'];
191
+
192
+        /** @var VObject\Component\VCalendar $vcalendar */
193
+        $vcalendar = $this->parseCalendarData($calendarData);
194
+        if (!$vcalendar) {
195
+            return;
196
+        }
197
+
198
+        $vevents = $this->getAllVEventsFromVCalendar($vcalendar);
199
+        if (count($vevents) === 0) {
200
+            return;
201
+        }
202
+
203
+        $uid = (string) $vevents[0]->UID;
204
+        $recurrenceExceptions = $this->getRecurrenceExceptionFromListOfVEvents($vevents);
205
+        $masterItem = $this->getMasterItemFromListOfVEvents($vevents);
206
+        $now = $this->timeFactory->getDateTime();
207
+        $isRecurring = $masterItem ? $this->isRecurring($masterItem) : false;
208
+
209
+        foreach($recurrenceExceptions as $recurrenceException) {
210
+            $eventHash = $this->getEventHash($recurrenceException);
211
+
212
+            if (!isset($recurrenceException->VALARM)) {
213
+                continue;
214
+            }
215
+
216
+            foreach($recurrenceException->VALARM as $valarm) {
217
+                /** @var VAlarm $valarm */
218
+                $alarmHash = $this->getAlarmHash($valarm);
219
+                $triggerTime = $valarm->getEffectiveTriggerTime();
220
+                $diff = $now->diff($triggerTime);
221
+                if ($diff->invert === 1) {
222
+                    continue;
223
+                }
224
+
225
+                $alarms = $this->getRemindersForVAlarm($valarm, $objectData,
226
+                    $eventHash, $alarmHash, true, true);
227
+                $this->writeRemindersToDatabase($alarms);
228
+            }
229
+        }
230
+
231
+        if ($masterItem) {
232
+            $processedAlarms = [];
233
+            $masterAlarms = [];
234
+            $masterHash = $this->getEventHash($masterItem);
235
+
236
+            if (!isset($masterItem->VALARM)) {
237
+                return;
238
+            }
239
+
240
+            foreach($masterItem->VALARM as $valarm) {
241
+                $masterAlarms[] = $this->getAlarmHash($valarm);
242
+            }
243
+
244
+            try {
245
+                $iterator = new EventIterator($vevents, $uid);
246
+            } catch (NoInstancesException $e) {
247
+                // This event is recurring, but it doesn't have a single
248
+                // instance. We are skipping this event from the output
249
+                // entirely.
250
+                return;
251
+            }
252
+
253
+            while($iterator->valid() && count($processedAlarms) < count($masterAlarms)) {
254
+                $event = $iterator->getEventObject();
255
+
256
+                // Recurrence-exceptions are handled separately, so just ignore them here
257
+                if (\in_array($event, $recurrenceExceptions, true)) {
258
+                    $iterator->next();
259
+                    continue;
260
+                }
261
+
262
+                foreach($event->VALARM as $valarm) {
263
+                    /** @var VAlarm $valarm */
264
+                    $alarmHash = $this->getAlarmHash($valarm);
265
+                    if (\in_array($alarmHash, $processedAlarms, true)) {
266
+                        continue;
267
+                    }
268
+
269
+                    if (!\in_array((string) $valarm->ACTION, self::REMINDER_TYPES, true)) {
270
+                        // Action allows x-name, we don't insert reminders
271
+                        // into the database if they are not standard
272
+                        $processedAlarms[] = $alarmHash;
273
+                        continue;
274
+                    }
275
+
276
+                    $triggerTime = $valarm->getEffectiveTriggerTime();
277
+
278
+                    // If effective trigger time is in the past
279
+                    // just skip and generate for next event
280
+                    $diff = $now->diff($triggerTime);
281
+                    if ($diff->invert === 1) {
282
+                        // If an absolute alarm is in the past,
283
+                        // just add it to processedAlarms, so
284
+                        // we don't extend till eternity
285
+                        if (!$this->isAlarmRelative($valarm)) {
286
+                            $processedAlarms[] = $alarmHash;
287
+                        }
288
+
289
+                        continue;
290
+                    }
291
+
292
+                    $alarms = $this->getRemindersForVAlarm($valarm, $objectData, $masterHash, $alarmHash, $isRecurring, false);
293
+                    $this->writeRemindersToDatabase($alarms);
294
+                    $processedAlarms[] = $alarmHash;
295
+                }
296
+
297
+                $iterator->next();
298
+            }
299
+        }
300
+    }
301
+
302
+    /**
303
+     * @param array $objectData
304
+     */
305
+    private function onCalendarObjectEdit(array $objectData):void {
306
+        // TODO - this can be vastly improved
307
+        //  - get cached reminders
308
+        //  - ...
309
+
310
+        $this->onCalendarObjectDelete($objectData);
311
+        $this->onCalendarObjectCreate($objectData);
312
+    }
313
+
314
+    /**
315
+     * @param array $objectData
316
+     */
317
+    private function onCalendarObjectDelete(array $objectData):void {
318
+        $this->backend->cleanRemindersForEvent((int) $objectData['id']);
319
+    }
320
+
321
+    /**
322
+     * @param VAlarm $valarm
323
+     * @param array $objectData
324
+     * @param string|null $eventHash
325
+     * @param string|null $alarmHash
326
+     * @param bool $isRecurring
327
+     * @param bool $isRecurrenceException
328
+     * @return array
329
+     */
330
+    private function getRemindersForVAlarm(VAlarm $valarm,
331
+                                            array $objectData,
332
+                                            string $eventHash=null,
333
+                                            string $alarmHash=null,
334
+                                            bool $isRecurring=false,
335
+                                            bool $isRecurrenceException=false):array {
336
+        if ($eventHash === null) {
337
+            $eventHash = $this->getEventHash($valarm->parent);
338
+        }
339
+        if ($alarmHash === null) {
340
+            $alarmHash = $this->getAlarmHash($valarm);
341
+        }
342
+
343
+        $recurrenceId = $this->getEffectiveRecurrenceIdOfVEvent($valarm->parent);
344
+        $isRelative = $this->isAlarmRelative($valarm);
345
+        /** @var DateTimeImmutable $notificationDate */
346
+        $notificationDate = $valarm->getEffectiveTriggerTime();
347
+        $clonedNotificationDate = new \DateTime('now', $notificationDate->getTimezone());
348
+        $clonedNotificationDate->setTimestamp($notificationDate->getTimestamp());
349
+
350
+        $alarms = [];
351
+
352
+        $alarms[] = [
353
+            'calendar_id' => $objectData['calendarid'],
354
+            'object_id' => $objectData['id'],
355
+            'uid' => (string) $valarm->parent->UID,
356
+            'is_recurring' => $isRecurring,
357
+            'recurrence_id' => $recurrenceId,
358
+            'is_recurrence_exception' => $isRecurrenceException,
359
+            'event_hash' => $eventHash,
360
+            'alarm_hash' => $alarmHash,
361
+            'type' => (string) $valarm->ACTION,
362
+            'is_relative' => $isRelative,
363
+            'notification_date' => $notificationDate->getTimestamp(),
364
+            'is_repeat_based' => false,
365
+        ];
366
+
367
+        $repeat = isset($valarm->REPEAT) ? (int) $valarm->REPEAT->getValue() : 0;
368
+        for($i = 0; $i < $repeat; $i++) {
369
+            if ($valarm->DURATION === null) {
370
+                continue;
371
+            }
372
+
373
+            $clonedNotificationDate->add($valarm->DURATION->getDateInterval());
374
+            $alarms[] = [
375
+                'calendar_id' => $objectData['calendarid'],
376
+                'object_id' => $objectData['id'],
377
+                'uid' => (string) $valarm->parent->UID,
378
+                'is_recurring' => $isRecurring,
379
+                'recurrence_id' => $recurrenceId,
380
+                'is_recurrence_exception' => $isRecurrenceException,
381
+                'event_hash' => $eventHash,
382
+                'alarm_hash' => $alarmHash,
383
+                'type' => (string) $valarm->ACTION,
384
+                'is_relative' => $isRelative,
385
+                'notification_date' => $clonedNotificationDate->getTimestamp(),
386
+                'is_repeat_based' => true,
387
+            ];
388
+        }
389
+
390
+        return $alarms;
391
+    }
392
+
393
+    /**
394
+     * @param array $reminders
395
+     */
396
+    private function writeRemindersToDatabase(array $reminders): void {
397
+        foreach($reminders as $reminder) {
398
+            $this->backend->insertReminder(
399
+                (int) $reminder['calendar_id'],
400
+                (int) $reminder['object_id'],
401
+                $reminder['uid'],
402
+                $reminder['is_recurring'],
403
+                (int) $reminder['recurrence_id'],
404
+                $reminder['is_recurrence_exception'],
405
+                $reminder['event_hash'],
406
+                $reminder['alarm_hash'],
407
+                $reminder['type'],
408
+                $reminder['is_relative'],
409
+                (int) $reminder['notification_date'],
410
+                $reminder['is_repeat_based']
411
+            );
412
+        }
413
+    }
414
+
415
+    /**
416
+     * @param array $reminder
417
+     * @param VEvent $vevent
418
+     */
419
+    private function deleteOrProcessNext(array $reminder,
420
+                                            VObject\Component\VEvent $vevent):void {
421
+        if ($reminder['is_repeat_based'] ||
422
+            !$reminder['is_recurring'] ||
423
+            !$reminder['is_relative'] ||
424
+            $reminder['is_recurrence_exception']) {
425
+
426
+            $this->backend->removeReminder($reminder['id']);
427
+            return;
428
+        }
429
+
430
+        $vevents = $this->getAllVEventsFromVCalendar($vevent->parent);
431
+        $recurrenceExceptions = $this->getRecurrenceExceptionFromListOfVEvents($vevents);
432
+        $now = $this->timeFactory->getDateTime();
433
+
434
+        try {
435
+            $iterator = new EventIterator($vevents, $reminder['uid']);
436
+        } catch (NoInstancesException $e) {
437
+            // This event is recurring, but it doesn't have a single
438
+            // instance. We are skipping this event from the output
439
+            // entirely.
440
+            return;
441
+        }
442
+
443
+        while($iterator->valid()) {
444
+            $event = $iterator->getEventObject();
445
+
446
+            // Recurrence-exceptions are handled separately, so just ignore them here
447
+            if (\in_array($event, $recurrenceExceptions, true)) {
448
+                $iterator->next();
449
+                continue;
450
+            }
451
+
452
+            $recurrenceId = $this->getEffectiveRecurrenceIdOfVEvent($event);
453
+            if ($reminder['recurrence_id'] >= $recurrenceId) {
454
+                $iterator->next();
455
+                continue;
456
+            }
457
+
458
+            foreach($event->VALARM as $valarm) {
459
+                /** @var VAlarm $valarm */
460
+                $alarmHash = $this->getAlarmHash($valarm);
461
+                if ($alarmHash !== $reminder['alarm_hash']) {
462
+                    continue;
463
+                }
464
+
465
+                $triggerTime = $valarm->getEffectiveTriggerTime();
466
+
467
+                // If effective trigger time is in the past
468
+                // just skip and generate for next event
469
+                $diff = $now->diff($triggerTime);
470
+                if ($diff->invert === 1) {
471
+                    continue;
472
+                }
473
+
474
+                $this->backend->removeReminder($reminder['id']);
475
+                $alarms = $this->getRemindersForVAlarm($valarm, [
476
+                    'calendarid' => $reminder['calendar_id'],
477
+                    'id' => $reminder['object_id'],
478
+                ], $reminder['event_hash'], $alarmHash, true, false);
479
+                $this->writeRemindersToDatabase($alarms);
480
+
481
+                // Abort generating reminders after creating one successfully
482
+                return;
483
+            }
484
+
485
+            $iterator->next();
486
+        }
487
+
488
+        $this->backend->removeReminder($reminder['id']);
489
+    }
490
+
491
+    /**
492
+     * @param int $calendarId
493
+     * @return IUser[]
494
+     */
495
+    private function getAllUsersWithWriteAccessToCalendar(int $calendarId):array {
496
+        $shares = $this->caldavBackend->getShares($calendarId);
497
+
498
+        $users = [];
499
+        $userIds = [];
500
+        $groups = [];
501
+        foreach ($shares as $share) {
502
+            // Only consider writable shares
503
+            if ($share['readOnly']) {
504
+                continue;
505
+            }
506
+
507
+            $principal = explode('/', $share['{http://owncloud.org/ns}principal']);
508
+            if ($principal[1] === 'users') {
509
+                $user = $this->userManager->get($principal[2]);
510
+                if ($user) {
511
+                    $users[] = $user;
512
+                    $userIds[] = $principal[2];
513
+                }
514
+            } else if ($principal[1] === 'groups') {
515
+                $groups[] = $principal[2];
516
+            }
517
+        }
518
+
519
+        foreach ($groups as $gid) {
520
+            $group = $this->groupManager->get($gid);
521
+            if ($group instanceof IGroup) {
522
+                foreach ($group->getUsers() as $user) {
523
+                    if (!\in_array($user->getUID(), $userIds, true)) {
524
+                        $users[] = $user;
525
+                        $userIds[] = $user->getUID();
526
+                    }
527
+                }
528
+            }
529
+        }
530
+
531
+        return $users;
532
+    }
533
+
534
+    /**
535
+     * Gets a hash of the event.
536
+     * If the hash changes, we have to update all relative alarms.
537
+     *
538
+     * @param VEvent $vevent
539
+     * @return string
540
+     */
541
+    private function getEventHash(VEvent $vevent):string {
542
+        $properties = [
543
+            (string) $vevent->DTSTART->serialize(),
544
+        ];
545
+
546
+        if ($vevent->DTEND) {
547
+            $properties[] = (string) $vevent->DTEND->serialize();
548
+        }
549
+        if ($vevent->DURATION) {
550
+            $properties[] = (string) $vevent->DURATION->serialize();
551
+        }
552
+        if ($vevent->{'RECURRENCE-ID'}) {
553
+            $properties[] = (string) $vevent->{'RECURRENCE-ID'}->serialize();
554
+        }
555
+        if ($vevent->RRULE) {
556
+            $properties[] = (string) $vevent->RRULE->serialize();
557
+        }
558
+        if ($vevent->EXDATE) {
559
+            $properties[] = (string) $vevent->EXDATE->serialize();
560
+        }
561
+        if ($vevent->RDATE) {
562
+            $properties[] = (string) $vevent->RDATE->serialize();
563
+        }
564
+
565
+        return md5(implode('::', $properties));
566
+    }
567
+
568
+    /**
569
+     * Gets a hash of the alarm.
570
+     * If the hash changes, we have to update oc_dav_reminders.
571
+     *
572
+     * @param VAlarm $valarm
573
+     * @return string
574
+     */
575
+    private function getAlarmHash(VAlarm $valarm):string {
576
+        $properties = [
577
+            (string) $valarm->ACTION->serialize(),
578
+            (string) $valarm->TRIGGER->serialize(),
579
+        ];
580
+
581
+        if ($valarm->DURATION) {
582
+            $properties[] = (string) $valarm->DURATION->serialize();
583
+        }
584
+        if ($valarm->REPEAT) {
585
+            $properties[] = (string) $valarm->REPEAT->serialize();
586
+        }
587
+
588
+        return md5(implode('::', $properties));
589
+    }
590
+
591
+    /**
592
+     * @param VObject\Component\VCalendar $vcalendar
593
+     * @param int $recurrenceId
594
+     * @param bool $isRecurrenceException
595
+     * @return VEvent|null
596
+     */
597
+    private function getVEventByRecurrenceId(VObject\Component\VCalendar $vcalendar,
598
+                                                int $recurrenceId,
599
+                                                bool $isRecurrenceException):?VEvent {
600
+        $vevents = $this->getAllVEventsFromVCalendar($vcalendar);
601
+        if (count($vevents) === 0) {
602
+            return null;
603
+        }
604
+
605
+        $uid = (string) $vevents[0]->UID;
606
+        $recurrenceExceptions = $this->getRecurrenceExceptionFromListOfVEvents($vevents);
607
+        $masterItem = $this->getMasterItemFromListOfVEvents($vevents);
608
+
609
+        // Handle recurrence-exceptions first, because recurrence-expansion is expensive
610
+        if ($isRecurrenceException) {
611
+            foreach($recurrenceExceptions as $recurrenceException) {
612
+                if ($this->getEffectiveRecurrenceIdOfVEvent($recurrenceException) === $recurrenceId) {
613
+                    return $recurrenceException;
614
+                }
615
+            }
616
+
617
+            return null;
618
+        }
619
+
620
+        if ($masterItem) {
621
+            try {
622
+                $iterator = new EventIterator($vevents, $uid);
623
+            } catch (NoInstancesException $e) {
624
+                // This event is recurring, but it doesn't have a single
625
+                // instance. We are skipping this event from the output
626
+                // entirely.
627
+                return null;
628
+            }
629
+
630
+            while ($iterator->valid()) {
631
+                $event = $iterator->getEventObject();
632
+
633
+                // Recurrence-exceptions are handled separately, so just ignore them here
634
+                if (\in_array($event, $recurrenceExceptions, true)) {
635
+                    $iterator->next();
636
+                    continue;
637
+                }
638
+
639
+                if ($this->getEffectiveRecurrenceIdOfVEvent($event) === $recurrenceId) {
640
+                    return $event;
641
+                }
642
+
643
+                $iterator->next();
644
+            }
645
+        }
646
+
647
+        return null;
648
+    }
649
+
650
+    /**
651
+     * @param VEvent $vevent
652
+     * @return string
653
+     */
654
+    private function getStatusOfEvent(VEvent $vevent):string {
655
+        if ($vevent->STATUS) {
656
+            return (string) $vevent->STATUS;
657
+        }
658
+
659
+        // Doesn't say so in the standard,
660
+        // but we consider events without a status
661
+        // to be confirmed
662
+        return 'CONFIRMED';
663
+    }
664
+
665
+    /**
666
+     * @param VObject\Component\VEvent $vevent
667
+     * @return bool
668
+     */
669
+    private function wasEventCancelled(VObject\Component\VEvent $vevent):bool {
670
+        return $this->getStatusOfEvent($vevent) === 'CANCELLED';
671
+    }
672
+
673
+    /**
674
+     * @param string $calendarData
675
+     * @return VObject\Component\VCalendar|null
676
+     */
677
+    private function parseCalendarData(string $calendarData):?VObject\Component\VCalendar {
678
+        try {
679
+            return VObject\Reader::read($calendarData,
680
+                VObject\Reader::OPTION_FORGIVING);
681
+        } catch(ParseException $ex) {
682
+            return null;
683
+        }
684
+    }
685
+
686
+    /**
687
+     * @param string $principalUri
688
+     * @return IUser|null
689
+     */
690
+    private function getUserFromPrincipalURI(string $principalUri):?IUser {
691
+        if (!$principalUri) {
692
+            return null;
693
+        }
694
+
695
+        if (stripos($principalUri, 'principals/users/') !== 0) {
696
+            return null;
697
+        }
698
+
699
+        $userId = substr($principalUri, 17);
700
+        return $this->userManager->get($userId);
701
+    }
702
+
703
+    /**
704
+     * @param VObject\Component\VCalendar $vcalendar
705
+     * @return VObject\Component\VEvent[]
706
+     */
707
+    private function getAllVEventsFromVCalendar(VObject\Component\VCalendar $vcalendar):array {
708
+        $vevents = [];
709
+
710
+        foreach($vcalendar->children() as $child) {
711
+            if (!($child instanceof VObject\Component)) {
712
+                continue;
713
+            }
714
+
715
+            if ($child->name !== 'VEVENT') {
716
+                continue;
717
+            }
718
+
719
+            $vevents[] = $child;
720
+        }
721
+
722
+        return $vevents;
723
+    }
724
+
725
+    /**
726
+     * @param array $vevents
727
+     * @return VObject\Component\VEvent[]
728
+     */
729
+    private function getRecurrenceExceptionFromListOfVEvents(array $vevents):array {
730
+        return array_values(array_filter($vevents, function (VEvent $vevent) {
731
+            return $vevent->{'RECURRENCE-ID'} !== null;
732
+        }));
733
+    }
734
+
735
+    /**
736
+     * @param array $vevents
737
+     * @return VEvent|null
738
+     */
739
+    private function getMasterItemFromListOfVEvents(array $vevents):?VEvent {
740
+        $elements = array_values(array_filter($vevents, function (VEvent $vevent) {
741
+            return $vevent->{'RECURRENCE-ID'} === null;
742
+        }));
743
+
744
+        if (count($elements) === 0) {
745
+            return null;
746
+        }
747
+        if (count($elements) > 1) {
748
+            throw new \TypeError('Multiple master objects');
749
+        }
750
+
751
+        return $elements[0];
752
+    }
753
+
754
+    /**
755
+     * @param VAlarm $valarm
756
+     * @return bool
757
+     */
758
+    private function isAlarmRelative(VAlarm $valarm):bool {
759
+        $trigger = $valarm->TRIGGER;
760
+        return $trigger instanceof VObject\Property\ICalendar\Duration;
761
+    }
762
+
763
+    /**
764
+     * @param VEvent $vevent
765
+     * @return int
766
+     */
767
+    private function getEffectiveRecurrenceIdOfVEvent(VEvent $vevent):int {
768
+        if (isset($vevent->{'RECURRENCE-ID'})) {
769
+            return $vevent->{'RECURRENCE-ID'}->getDateTime()->getTimestamp();
770
+        }
771
+
772
+        return $vevent->DTSTART->getDateTime()->getTimestamp();
773
+    }
774
+
775
+    /**
776
+     * @param VEvent $vevent
777
+     * @return bool
778
+     */
779
+    private function isRecurring(VEvent $vevent):bool {
780
+        return isset($vevent->RRULE) || isset($vevent->RDATE);
781
+    }
782 782
 }
Please login to merge, or discard this patch.
Spacing   +24 added lines, -24 removed lines patch added patch discarded remove patch
@@ -111,7 +111,7 @@  discard block
 block discarded – undo
111 111
 	public function processReminders():void {
112 112
 		$reminders = $this->backend->getRemindersToProcess();
113 113
 
114
-		foreach($reminders as $reminder) {
114
+		foreach ($reminders as $reminder) {
115 115
 			$calendarData = is_resource($reminder['calendardata'])
116 116
 				? stream_get_contents($reminder['calendardata'])
117 117
 				: $reminder['calendardata'];
@@ -163,7 +163,7 @@  discard block
 block discarded – undo
163 163
 			return;
164 164
 		}
165 165
 
166
-		switch($action) {
166
+		switch ($action) {
167 167
 			case '\OCA\DAV\CalDAV\CalDavBackend::createCalendarObject':
168 168
 				$this->onCalendarObjectCreate($objectData);
169 169
 				break;
@@ -206,14 +206,14 @@  discard block
 block discarded – undo
206 206
 		$now = $this->timeFactory->getDateTime();
207 207
 		$isRecurring = $masterItem ? $this->isRecurring($masterItem) : false;
208 208
 
209
-		foreach($recurrenceExceptions as $recurrenceException) {
209
+		foreach ($recurrenceExceptions as $recurrenceException) {
210 210
 			$eventHash = $this->getEventHash($recurrenceException);
211 211
 
212 212
 			if (!isset($recurrenceException->VALARM)) {
213 213
 				continue;
214 214
 			}
215 215
 
216
-			foreach($recurrenceException->VALARM as $valarm) {
216
+			foreach ($recurrenceException->VALARM as $valarm) {
217 217
 				/** @var VAlarm $valarm */
218 218
 				$alarmHash = $this->getAlarmHash($valarm);
219 219
 				$triggerTime = $valarm->getEffectiveTriggerTime();
@@ -237,7 +237,7 @@  discard block
 block discarded – undo
237 237
 				return;
238 238
 			}
239 239
 
240
-			foreach($masterItem->VALARM as $valarm) {
240
+			foreach ($masterItem->VALARM as $valarm) {
241 241
 				$masterAlarms[] = $this->getAlarmHash($valarm);
242 242
 			}
243 243
 
@@ -250,7 +250,7 @@  discard block
 block discarded – undo
250 250
 				return;
251 251
 			}
252 252
 
253
-			while($iterator->valid() && count($processedAlarms) < count($masterAlarms)) {
253
+			while ($iterator->valid() && count($processedAlarms) < count($masterAlarms)) {
254 254
 				$event = $iterator->getEventObject();
255 255
 
256 256
 				// Recurrence-exceptions are handled separately, so just ignore them here
@@ -259,7 +259,7 @@  discard block
 block discarded – undo
259 259
 					continue;
260 260
 				}
261 261
 
262
-				foreach($event->VALARM as $valarm) {
262
+				foreach ($event->VALARM as $valarm) {
263 263
 					/** @var VAlarm $valarm */
264 264
 					$alarmHash = $this->getAlarmHash($valarm);
265 265
 					if (\in_array($alarmHash, $processedAlarms, true)) {
@@ -329,10 +329,10 @@  discard block
 block discarded – undo
329 329
 	 */
330 330
 	private function getRemindersForVAlarm(VAlarm $valarm,
331 331
 										   array $objectData,
332
-										   string $eventHash=null,
333
-										   string $alarmHash=null,
334
-										   bool $isRecurring=false,
335
-										   bool $isRecurrenceException=false):array {
332
+										   string $eventHash = null,
333
+										   string $alarmHash = null,
334
+										   bool $isRecurring = false,
335
+										   bool $isRecurrenceException = false):array {
336 336
 		if ($eventHash === null) {
337 337
 			$eventHash = $this->getEventHash($valarm->parent);
338 338
 		}
@@ -365,7 +365,7 @@  discard block
 block discarded – undo
365 365
 		];
366 366
 
367 367
 		$repeat = isset($valarm->REPEAT) ? (int) $valarm->REPEAT->getValue() : 0;
368
-		for($i = 0; $i < $repeat; $i++) {
368
+		for ($i = 0; $i < $repeat; $i++) {
369 369
 			if ($valarm->DURATION === null) {
370 370
 				continue;
371 371
 			}
@@ -394,7 +394,7 @@  discard block
 block discarded – undo
394 394
 	 * @param array $reminders
395 395
 	 */
396 396
 	private function writeRemindersToDatabase(array $reminders): void {
397
-		foreach($reminders as $reminder) {
397
+		foreach ($reminders as $reminder) {
398 398
 			$this->backend->insertReminder(
399 399
 				(int) $reminder['calendar_id'],
400 400
 				(int) $reminder['object_id'],
@@ -440,7 +440,7 @@  discard block
 block discarded – undo
440 440
 			return;
441 441
 		}
442 442
 
443
-		while($iterator->valid()) {
443
+		while ($iterator->valid()) {
444 444
 			$event = $iterator->getEventObject();
445 445
 
446 446
 			// Recurrence-exceptions are handled separately, so just ignore them here
@@ -455,7 +455,7 @@  discard block
 block discarded – undo
455 455
 				continue;
456 456
 			}
457 457
 
458
-			foreach($event->VALARM as $valarm) {
458
+			foreach ($event->VALARM as $valarm) {
459 459
 				/** @var VAlarm $valarm */
460 460
 				$alarmHash = $this->getAlarmHash($valarm);
461 461
 				if ($alarmHash !== $reminder['alarm_hash']) {
@@ -596,7 +596,7 @@  discard block
 block discarded – undo
596 596
 	 */
597 597
 	private function getVEventByRecurrenceId(VObject\Component\VCalendar $vcalendar,
598 598
 											 int $recurrenceId,
599
-											 bool $isRecurrenceException):?VEvent {
599
+											 bool $isRecurrenceException): ?VEvent {
600 600
 		$vevents = $this->getAllVEventsFromVCalendar($vcalendar);
601 601
 		if (count($vevents) === 0) {
602 602
 			return null;
@@ -608,7 +608,7 @@  discard block
 block discarded – undo
608 608
 
609 609
 		// Handle recurrence-exceptions first, because recurrence-expansion is expensive
610 610
 		if ($isRecurrenceException) {
611
-			foreach($recurrenceExceptions as $recurrenceException) {
611
+			foreach ($recurrenceExceptions as $recurrenceException) {
612 612
 				if ($this->getEffectiveRecurrenceIdOfVEvent($recurrenceException) === $recurrenceId) {
613 613
 					return $recurrenceException;
614 614
 				}
@@ -674,11 +674,11 @@  discard block
 block discarded – undo
674 674
 	 * @param string $calendarData
675 675
 	 * @return VObject\Component\VCalendar|null
676 676
 	 */
677
-	private function parseCalendarData(string $calendarData):?VObject\Component\VCalendar {
677
+	private function parseCalendarData(string $calendarData): ?VObject\Component\VCalendar {
678 678
 		try {
679 679
 			return VObject\Reader::read($calendarData,
680 680
 				VObject\Reader::OPTION_FORGIVING);
681
-		} catch(ParseException $ex) {
681
+		} catch (ParseException $ex) {
682 682
 			return null;
683 683
 		}
684 684
 	}
@@ -687,7 +687,7 @@  discard block
 block discarded – undo
687 687
 	 * @param string $principalUri
688 688
 	 * @return IUser|null
689 689
 	 */
690
-	private function getUserFromPrincipalURI(string $principalUri):?IUser {
690
+	private function getUserFromPrincipalURI(string $principalUri): ?IUser {
691 691
 		if (!$principalUri) {
692 692
 			return null;
693 693
 		}
@@ -707,7 +707,7 @@  discard block
 block discarded – undo
707 707
 	private function getAllVEventsFromVCalendar(VObject\Component\VCalendar $vcalendar):array {
708 708
 		$vevents = [];
709 709
 
710
-		foreach($vcalendar->children() as $child) {
710
+		foreach ($vcalendar->children() as $child) {
711 711
 			if (!($child instanceof VObject\Component)) {
712 712
 				continue;
713 713
 			}
@@ -727,7 +727,7 @@  discard block
 block discarded – undo
727 727
 	 * @return VObject\Component\VEvent[]
728 728
 	 */
729 729
 	private function getRecurrenceExceptionFromListOfVEvents(array $vevents):array {
730
-		return array_values(array_filter($vevents, function (VEvent $vevent) {
730
+		return array_values(array_filter($vevents, function(VEvent $vevent) {
731 731
 			return $vevent->{'RECURRENCE-ID'} !== null;
732 732
 		}));
733 733
 	}
@@ -736,8 +736,8 @@  discard block
 block discarded – undo
736 736
 	 * @param array $vevents
737 737
 	 * @return VEvent|null
738 738
 	 */
739
-	private function getMasterItemFromListOfVEvents(array $vevents):?VEvent {
740
-		$elements = array_values(array_filter($vevents, function (VEvent $vevent) {
739
+	private function getMasterItemFromListOfVEvents(array $vevents): ?VEvent {
740
+		$elements = array_values(array_filter($vevents, function(VEvent $vevent) {
741 741
 			return $vevent->{'RECURRENCE-ID'} === null;
742 742
 		}));
743 743
 
Please login to merge, or discard this patch.
apps/dav/lib/CalDAV/Publishing/PublishPlugin.php 2 patches
Indentation   +190 added lines, -190 removed lines patch added patch discarded remove patch
@@ -40,197 +40,197 @@
 block discarded – undo
40 40
 use Sabre\HTTP\ResponseInterface;
41 41
 
42 42
 class PublishPlugin extends ServerPlugin {
43
-	const NS_CALENDARSERVER = 'http://calendarserver.org/ns/';
44
-
45
-	/**
46
-	 * Reference to SabreDAV server object.
47
-	 *
48
-	 * @var \Sabre\DAV\Server
49
-	 */
50
-	protected $server;
51
-
52
-	/**
53
-	 * Config instance to get instance secret.
54
-	 *
55
-	 * @var IConfig
56
-	 */
57
-	protected $config;
58
-
59
-	/**
60
-	 * URL Generator for absolute URLs.
61
-	 *
62
-	 * @var IURLGenerator
63
-	 */
64
-	protected $urlGenerator;
65
-
66
-	/**
67
-	 * PublishPlugin constructor.
68
-	 *
69
-	 * @param IConfig $config
70
-	 * @param IURLGenerator $urlGenerator
71
-	 */
72
-	public function __construct(IConfig $config, IURLGenerator $urlGenerator) {
73
-		$this->config = $config;
74
-		$this->urlGenerator = $urlGenerator;
75
-	}
76
-
77
-	/**
78
-	 * This method should return a list of server-features.
79
-	 *
80
-	 * This is for example 'versioning' and is added to the DAV: header
81
-	 * in an OPTIONS response.
82
-	 *
83
-	 * @return string[]
84
-	 */
85
-	public function getFeatures() {
86
-		// May have to be changed to be detected
87
-		return ['oc-calendar-publishing', 'calendarserver-sharing'];
88
-	}
89
-
90
-	/**
91
-	 * Returns a plugin name.
92
-	 *
93
-	 * Using this name other plugins will be able to access other plugins
94
-	 * using Sabre\DAV\Server::getPlugin
95
-	 *
96
-	 * @return string
97
-	 */
98
-	public function getPluginName() {
99
-		return 'oc-calendar-publishing';
100
-	}
101
-
102
-	/**
103
-	 * This initializes the plugin.
104
-	 *
105
-	 * This function is called by Sabre\DAV\Server, after
106
-	 * addPlugin is called.
107
-	 *
108
-	 * This method should set up the required event subscriptions.
109
-	 *
110
-	 * @param Server $server
111
-	 */
112
-	public function initialize(Server $server) {
113
-		$this->server = $server;
114
-
115
-		$this->server->on('method:POST', [$this, 'httpPost']);
116
-		$this->server->on('propFind',    [$this, 'propFind']);
117
-	}
118
-
119
-	public function propFind(PropFind $propFind, INode $node) {
120
-		if ($node instanceof Calendar) {
121
-			$propFind->handle('{'.self::NS_CALENDARSERVER.'}publish-url', function () use ($node) {
122
-				if ($node->getPublishStatus()) {
123
-					// We return the publish-url only if the calendar is published.
124
-					$token = $node->getPublishStatus();
125
-					$publishUrl = $this->urlGenerator->getAbsoluteURL($this->server->getBaseUri().'public-calendars/').$token;
126
-
127
-					return new Publisher($publishUrl, true);
128
-				}
129
-			});
130
-
131
-			$propFind->handle('{'.self::NS_CALENDARSERVER.'}allowed-sharing-modes', function () use ($node) {
132
-				$canShare = (!$node->isSubscription() && $node->canWrite());
133
-				$canPublish = (!$node->isSubscription() && $node->canWrite());
134
-
135
-				return new AllowedSharingModes($canShare, $canPublish);
136
-			});
137
-		}
138
-	}
139
-
140
-	/**
141
-	 * We intercept this to handle POST requests on calendars.
142
-	 *
143
-	 * @param RequestInterface $request
144
-	 * @param ResponseInterface $response
145
-	 *
146
-	 * @return void|bool
147
-	 */
148
-	public function httpPost(RequestInterface $request, ResponseInterface $response) {
149
-		$path = $request->getPath();
150
-
151
-		// Only handling xml
152
-		$contentType = $request->getHeader('Content-Type');
153
-		if (strpos($contentType, 'application/xml') === false && strpos($contentType, 'text/xml') === false) {
154
-			return;
155
-		}
156
-
157
-		// Making sure the node exists
158
-		try {
159
-			$node = $this->server->tree->getNodeForPath($path);
160
-		} catch (NotFound $e) {
161
-			return;
162
-		}
163
-
164
-		$requestBody = $request->getBodyAsString();
165
-
166
-		// If this request handler could not deal with this POST request, it
167
-		// will return 'null' and other plugins get a chance to handle the
168
-		// request.
169
-		//
170
-		// However, we already requested the full body. This is a problem,
171
-		// because a body can only be read once. This is why we preemptively
172
-		// re-populated the request body with the existing data.
173
-		$request->setBody($requestBody);
174
-
175
-		$this->server->xml->parse($requestBody, $request->getUrl(), $documentType);
176
-
177
-		switch ($documentType) {
178
-
179
-			case '{'.self::NS_CALENDARSERVER.'}publish-calendar' :
180
-
181
-			// We can only deal with IShareableCalendar objects
182
-			if (!$node instanceof Calendar) {
183
-				return;
184
-			}
185
-			$this->server->transactionType = 'post-publish-calendar';
186
-
187
-			// Getting ACL info
188
-			$acl = $this->server->getPlugin('acl');
189
-
190
-			// If there's no ACL support, we allow everything
191
-			if ($acl) {
192
-				$acl->checkPrivileges($path, '{DAV:}write');
193
-			}
194
-
195
-			$node->setPublishStatus(true);
196
-
197
-			// iCloud sends back the 202, so we will too.
198
-			$response->setStatus(202);
199
-
200
-			// Adding this because sending a response body may cause issues,
201
-			// and I wanted some type of indicator the response was handled.
202
-			$response->setHeader('X-Sabre-Status', 'everything-went-well');
203
-
204
-			// Breaking the event chain
205
-			return false;
206
-
207
-			case '{'.self::NS_CALENDARSERVER.'}unpublish-calendar' :
208
-
209
-			// We can only deal with IShareableCalendar objects
210
-			if (!$node instanceof Calendar) {
211
-				return;
212
-			}
213
-			$this->server->transactionType = 'post-unpublish-calendar';
214
-
215
-			// Getting ACL info
216
-			$acl = $this->server->getPlugin('acl');
217
-
218
-			// If there's no ACL support, we allow everything
219
-			if ($acl) {
220
-				$acl->checkPrivileges($path, '{DAV:}write');
221
-			}
222
-
223
-			$node->setPublishStatus(false);
224
-
225
-			$response->setStatus(200);
43
+    const NS_CALENDARSERVER = 'http://calendarserver.org/ns/';
44
+
45
+    /**
46
+     * Reference to SabreDAV server object.
47
+     *
48
+     * @var \Sabre\DAV\Server
49
+     */
50
+    protected $server;
51
+
52
+    /**
53
+     * Config instance to get instance secret.
54
+     *
55
+     * @var IConfig
56
+     */
57
+    protected $config;
58
+
59
+    /**
60
+     * URL Generator for absolute URLs.
61
+     *
62
+     * @var IURLGenerator
63
+     */
64
+    protected $urlGenerator;
65
+
66
+    /**
67
+     * PublishPlugin constructor.
68
+     *
69
+     * @param IConfig $config
70
+     * @param IURLGenerator $urlGenerator
71
+     */
72
+    public function __construct(IConfig $config, IURLGenerator $urlGenerator) {
73
+        $this->config = $config;
74
+        $this->urlGenerator = $urlGenerator;
75
+    }
76
+
77
+    /**
78
+     * This method should return a list of server-features.
79
+     *
80
+     * This is for example 'versioning' and is added to the DAV: header
81
+     * in an OPTIONS response.
82
+     *
83
+     * @return string[]
84
+     */
85
+    public function getFeatures() {
86
+        // May have to be changed to be detected
87
+        return ['oc-calendar-publishing', 'calendarserver-sharing'];
88
+    }
89
+
90
+    /**
91
+     * Returns a plugin name.
92
+     *
93
+     * Using this name other plugins will be able to access other plugins
94
+     * using Sabre\DAV\Server::getPlugin
95
+     *
96
+     * @return string
97
+     */
98
+    public function getPluginName() {
99
+        return 'oc-calendar-publishing';
100
+    }
101
+
102
+    /**
103
+     * This initializes the plugin.
104
+     *
105
+     * This function is called by Sabre\DAV\Server, after
106
+     * addPlugin is called.
107
+     *
108
+     * This method should set up the required event subscriptions.
109
+     *
110
+     * @param Server $server
111
+     */
112
+    public function initialize(Server $server) {
113
+        $this->server = $server;
114
+
115
+        $this->server->on('method:POST', [$this, 'httpPost']);
116
+        $this->server->on('propFind',    [$this, 'propFind']);
117
+    }
118
+
119
+    public function propFind(PropFind $propFind, INode $node) {
120
+        if ($node instanceof Calendar) {
121
+            $propFind->handle('{'.self::NS_CALENDARSERVER.'}publish-url', function () use ($node) {
122
+                if ($node->getPublishStatus()) {
123
+                    // We return the publish-url only if the calendar is published.
124
+                    $token = $node->getPublishStatus();
125
+                    $publishUrl = $this->urlGenerator->getAbsoluteURL($this->server->getBaseUri().'public-calendars/').$token;
126
+
127
+                    return new Publisher($publishUrl, true);
128
+                }
129
+            });
130
+
131
+            $propFind->handle('{'.self::NS_CALENDARSERVER.'}allowed-sharing-modes', function () use ($node) {
132
+                $canShare = (!$node->isSubscription() && $node->canWrite());
133
+                $canPublish = (!$node->isSubscription() && $node->canWrite());
134
+
135
+                return new AllowedSharingModes($canShare, $canPublish);
136
+            });
137
+        }
138
+    }
139
+
140
+    /**
141
+     * We intercept this to handle POST requests on calendars.
142
+     *
143
+     * @param RequestInterface $request
144
+     * @param ResponseInterface $response
145
+     *
146
+     * @return void|bool
147
+     */
148
+    public function httpPost(RequestInterface $request, ResponseInterface $response) {
149
+        $path = $request->getPath();
150
+
151
+        // Only handling xml
152
+        $contentType = $request->getHeader('Content-Type');
153
+        if (strpos($contentType, 'application/xml') === false && strpos($contentType, 'text/xml') === false) {
154
+            return;
155
+        }
156
+
157
+        // Making sure the node exists
158
+        try {
159
+            $node = $this->server->tree->getNodeForPath($path);
160
+        } catch (NotFound $e) {
161
+            return;
162
+        }
163
+
164
+        $requestBody = $request->getBodyAsString();
165
+
166
+        // If this request handler could not deal with this POST request, it
167
+        // will return 'null' and other plugins get a chance to handle the
168
+        // request.
169
+        //
170
+        // However, we already requested the full body. This is a problem,
171
+        // because a body can only be read once. This is why we preemptively
172
+        // re-populated the request body with the existing data.
173
+        $request->setBody($requestBody);
174
+
175
+        $this->server->xml->parse($requestBody, $request->getUrl(), $documentType);
176
+
177
+        switch ($documentType) {
178
+
179
+            case '{'.self::NS_CALENDARSERVER.'}publish-calendar' :
180
+
181
+            // We can only deal with IShareableCalendar objects
182
+            if (!$node instanceof Calendar) {
183
+                return;
184
+            }
185
+            $this->server->transactionType = 'post-publish-calendar';
186
+
187
+            // Getting ACL info
188
+            $acl = $this->server->getPlugin('acl');
189
+
190
+            // If there's no ACL support, we allow everything
191
+            if ($acl) {
192
+                $acl->checkPrivileges($path, '{DAV:}write');
193
+            }
194
+
195
+            $node->setPublishStatus(true);
196
+
197
+            // iCloud sends back the 202, so we will too.
198
+            $response->setStatus(202);
199
+
200
+            // Adding this because sending a response body may cause issues,
201
+            // and I wanted some type of indicator the response was handled.
202
+            $response->setHeader('X-Sabre-Status', 'everything-went-well');
203
+
204
+            // Breaking the event chain
205
+            return false;
206
+
207
+            case '{'.self::NS_CALENDARSERVER.'}unpublish-calendar' :
208
+
209
+            // We can only deal with IShareableCalendar objects
210
+            if (!$node instanceof Calendar) {
211
+                return;
212
+            }
213
+            $this->server->transactionType = 'post-unpublish-calendar';
214
+
215
+            // Getting ACL info
216
+            $acl = $this->server->getPlugin('acl');
217
+
218
+            // If there's no ACL support, we allow everything
219
+            if ($acl) {
220
+                $acl->checkPrivileges($path, '{DAV:}write');
221
+            }
222
+
223
+            $node->setPublishStatus(false);
224
+
225
+            $response->setStatus(200);
226 226
 
227
-			// Adding this because sending a response body may cause issues,
228
-			// and I wanted some type of indicator the response was handled.
229
-			$response->setHeader('X-Sabre-Status', 'everything-went-well');
227
+            // Adding this because sending a response body may cause issues,
228
+            // and I wanted some type of indicator the response was handled.
229
+            $response->setHeader('X-Sabre-Status', 'everything-went-well');
230 230
 
231
-			// Breaking the event chain
232
-			return false;
231
+            // Breaking the event chain
232
+            return false;
233 233
 
234
-		}
235
-	}
234
+        }
235
+    }
236 236
 }
Please login to merge, or discard this patch.
Spacing   +3 added lines, -3 removed lines patch added patch discarded remove patch
@@ -113,12 +113,12 @@  discard block
 block discarded – undo
113 113
 		$this->server = $server;
114 114
 
115 115
 		$this->server->on('method:POST', [$this, 'httpPost']);
116
-		$this->server->on('propFind',    [$this, 'propFind']);
116
+		$this->server->on('propFind', [$this, 'propFind']);
117 117
 	}
118 118
 
119 119
 	public function propFind(PropFind $propFind, INode $node) {
120 120
 		if ($node instanceof Calendar) {
121
-			$propFind->handle('{'.self::NS_CALENDARSERVER.'}publish-url', function () use ($node) {
121
+			$propFind->handle('{'.self::NS_CALENDARSERVER.'}publish-url', function() use ($node) {
122 122
 				if ($node->getPublishStatus()) {
123 123
 					// We return the publish-url only if the calendar is published.
124 124
 					$token = $node->getPublishStatus();
@@ -128,7 +128,7 @@  discard block
 block discarded – undo
128 128
 				}
129 129
 			});
130 130
 
131
-			$propFind->handle('{'.self::NS_CALENDARSERVER.'}allowed-sharing-modes', function () use ($node) {
131
+			$propFind->handle('{'.self::NS_CALENDARSERVER.'}allowed-sharing-modes', function() use ($node) {
132 132
 				$canShare = (!$node->isSubscription() && $node->canWrite());
133 133
 				$canPublish = (!$node->isSubscription() && $node->canWrite());
134 134
 
Please login to merge, or discard this patch.