Passed
Push — master ( f0dd71...c56a27 )
by Christoph
11:49 queued 12s
created
apps/dav/lib/SystemTag/SystemTagsRelationsCollection.php 1 patch
Indentation   +49 added lines, -49 removed lines patch added patch discarded remove patch
@@ -37,59 +37,59 @@
 block discarded – undo
37 37
 
38 38
 class SystemTagsRelationsCollection extends SimpleCollection {
39 39
 
40
-	/**
41
-	 * SystemTagsRelationsCollection constructor.
42
-	 *
43
-	 * @param ISystemTagManager $tagManager
44
-	 * @param ISystemTagObjectMapper $tagMapper
45
-	 * @param IUserSession $userSession
46
-	 * @param IGroupManager $groupManager
47
-	 * @param EventDispatcherInterface $dispatcher
48
-	 */
49
-	public function __construct(
50
-		ISystemTagManager $tagManager,
51
-		ISystemTagObjectMapper $tagMapper,
52
-		IUserSession $userSession,
53
-		IGroupManager $groupManager,
54
-		EventDispatcherInterface $dispatcher
55
-	) {
56
-		$children = [
57
-			new SystemTagsObjectTypeCollection(
58
-				'files',
59
-				$tagManager,
60
-				$tagMapper,
61
-				$userSession,
62
-				$groupManager,
63
-				function ($name) {
64
-					$nodes = \OC::$server->getUserFolder()->getById((int)$name);
65
-					return !empty($nodes);
66
-				}
67
-			),
68
-		];
40
+    /**
41
+     * SystemTagsRelationsCollection constructor.
42
+     *
43
+     * @param ISystemTagManager $tagManager
44
+     * @param ISystemTagObjectMapper $tagMapper
45
+     * @param IUserSession $userSession
46
+     * @param IGroupManager $groupManager
47
+     * @param EventDispatcherInterface $dispatcher
48
+     */
49
+    public function __construct(
50
+        ISystemTagManager $tagManager,
51
+        ISystemTagObjectMapper $tagMapper,
52
+        IUserSession $userSession,
53
+        IGroupManager $groupManager,
54
+        EventDispatcherInterface $dispatcher
55
+    ) {
56
+        $children = [
57
+            new SystemTagsObjectTypeCollection(
58
+                'files',
59
+                $tagManager,
60
+                $tagMapper,
61
+                $userSession,
62
+                $groupManager,
63
+                function ($name) {
64
+                    $nodes = \OC::$server->getUserFolder()->getById((int)$name);
65
+                    return !empty($nodes);
66
+                }
67
+            ),
68
+        ];
69 69
 
70
-		$event = new SystemTagsEntityEvent(SystemTagsEntityEvent::EVENT_ENTITY);
71
-		$dispatcher->dispatch(SystemTagsEntityEvent::EVENT_ENTITY, $event);
70
+        $event = new SystemTagsEntityEvent(SystemTagsEntityEvent::EVENT_ENTITY);
71
+        $dispatcher->dispatch(SystemTagsEntityEvent::EVENT_ENTITY, $event);
72 72
 
73
-		foreach ($event->getEntityCollections() as $entity => $entityExistsFunction) {
74
-			$children[] = new SystemTagsObjectTypeCollection(
75
-				$entity,
76
-				$tagManager,
77
-				$tagMapper,
78
-				$userSession,
79
-				$groupManager,
80
-				$entityExistsFunction
81
-			);
82
-		}
73
+        foreach ($event->getEntityCollections() as $entity => $entityExistsFunction) {
74
+            $children[] = new SystemTagsObjectTypeCollection(
75
+                $entity,
76
+                $tagManager,
77
+                $tagMapper,
78
+                $userSession,
79
+                $groupManager,
80
+                $entityExistsFunction
81
+            );
82
+        }
83 83
 
84
-		parent::__construct('root', $children);
85
-	}
84
+        parent::__construct('root', $children);
85
+    }
86 86
 
87
-	function getName() {
88
-		return 'systemtags-relations';
89
-	}
87
+    function getName() {
88
+        return 'systemtags-relations';
89
+    }
90 90
 
91
-	function setName($name) {
92
-		throw new Forbidden('Permission denied to rename this collection');
93
-	}
91
+    function setName($name) {
92
+        throw new Forbidden('Permission denied to rename this collection');
93
+    }
94 94
 
95 95
 }
Please login to merge, or discard this patch.
apps/dav/lib/Controller/BirthdayCalendarController.php 1 patch
Indentation   +65 added lines, -65 removed lines patch added patch discarded remove patch
@@ -38,80 +38,80 @@
 block discarded – undo
38 38
 
39 39
 class BirthdayCalendarController extends Controller {
40 40
 
41
-	/**
42
-	 * @var IDBConnection
43
-	 */
44
-	protected $db;
41
+    /**
42
+     * @var IDBConnection
43
+     */
44
+    protected $db;
45 45
 
46
-	/**
47
-	 * @var IConfig
48
-	 */
49
-	protected $config;
46
+    /**
47
+     * @var IConfig
48
+     */
49
+    protected $config;
50 50
 
51
-	/**
52
-	 * @var IUserManager
53
-	 */
54
-	protected $userManager;
51
+    /**
52
+     * @var IUserManager
53
+     */
54
+    protected $userManager;
55 55
 
56
-	/**
57
-	 * @var CalDavBackend
58
-	 */
59
-	protected $caldavBackend;
56
+    /**
57
+     * @var CalDavBackend
58
+     */
59
+    protected $caldavBackend;
60 60
 
61
-	/**
62
-	 * @var IJobList
63
-	 */
64
-	protected $jobList;
61
+    /**
62
+     * @var IJobList
63
+     */
64
+    protected $jobList;
65 65
 
66
-	/**
67
-	 * BirthdayCalendar constructor.
68
-	 *
69
-	 * @param string $appName
70
-	 * @param IRequest $request
71
-	 * @param IDBConnection $db
72
-	 * @param IConfig $config
73
-	 * @param IJobList $jobList
74
-	 * @param IUserManager $userManager
75
-	 * @param CalDavBackend $calDavBackend
76
-	 */
77
-	public function __construct($appName, IRequest $request,
78
-								IDBConnection $db, IConfig $config,
79
-								IJobList $jobList,
80
-								IUserManager $userManager,
81
-								CalDavBackend $calDavBackend) {
82
-		parent::__construct($appName, $request);
83
-		$this->db = $db;
84
-		$this->config = $config;
85
-		$this->userManager = $userManager;
86
-		$this->jobList = $jobList;
87
-		$this->caldavBackend = $calDavBackend;
88
-	}
66
+    /**
67
+     * BirthdayCalendar constructor.
68
+     *
69
+     * @param string $appName
70
+     * @param IRequest $request
71
+     * @param IDBConnection $db
72
+     * @param IConfig $config
73
+     * @param IJobList $jobList
74
+     * @param IUserManager $userManager
75
+     * @param CalDavBackend $calDavBackend
76
+     */
77
+    public function __construct($appName, IRequest $request,
78
+                                IDBConnection $db, IConfig $config,
79
+                                IJobList $jobList,
80
+                                IUserManager $userManager,
81
+                                CalDavBackend $calDavBackend) {
82
+        parent::__construct($appName, $request);
83
+        $this->db = $db;
84
+        $this->config = $config;
85
+        $this->userManager = $userManager;
86
+        $this->jobList = $jobList;
87
+        $this->caldavBackend = $calDavBackend;
88
+    }
89 89
 
90
-	/**
91
-	 * @return Response
92
-	 */
93
-	public function enable() {
94
-		$this->config->setAppValue($this->appName, 'generateBirthdayCalendar', 'yes');
90
+    /**
91
+     * @return Response
92
+     */
93
+    public function enable() {
94
+        $this->config->setAppValue($this->appName, 'generateBirthdayCalendar', 'yes');
95 95
 
96
-		// add background job for each user
97
-		$this->userManager->callForSeenUsers(function (IUser $user) {
98
-			$this->jobList->add(GenerateBirthdayCalendarBackgroundJob::class, [
99
-				'userId' => $user->getUID(),
100
-			]);
101
-		});
96
+        // add background job for each user
97
+        $this->userManager->callForSeenUsers(function (IUser $user) {
98
+            $this->jobList->add(GenerateBirthdayCalendarBackgroundJob::class, [
99
+                'userId' => $user->getUID(),
100
+            ]);
101
+        });
102 102
 
103
-		return new JSONResponse([]);
104
-	}
103
+        return new JSONResponse([]);
104
+    }
105 105
 
106
-	/**
107
-	 * @return Response
108
-	 */
109
-	public function disable() {
110
-		$this->config->setAppValue($this->appName, 'generateBirthdayCalendar', 'no');
106
+    /**
107
+     * @return Response
108
+     */
109
+    public function disable() {
110
+        $this->config->setAppValue($this->appName, 'generateBirthdayCalendar', 'no');
111 111
 
112
-		$this->jobList->remove(GenerateBirthdayCalendarBackgroundJob::class);
113
-		$this->caldavBackend->deleteAllBirthdayCalendars();
112
+        $this->jobList->remove(GenerateBirthdayCalendarBackgroundJob::class);
113
+        $this->caldavBackend->deleteAllBirthdayCalendars();
114 114
 
115
-		return new JSONResponse([]);
116
-	}
115
+        return new JSONResponse([]);
116
+    }
117 117
 }
Please login to merge, or discard this patch.
apps/dav/lib/Comments/CommentNode.php 1 patch
Indentation   +241 added lines, -241 removed lines patch added patch discarded remove patch
@@ -35,270 +35,270 @@
 block discarded – undo
35 35
 use Sabre\DAV\PropPatch;
36 36
 
37 37
 class CommentNode implements \Sabre\DAV\INode, \Sabre\DAV\IProperties {
38
-	const NS_OWNCLOUD = 'http://owncloud.org/ns';
38
+    const NS_OWNCLOUD = 'http://owncloud.org/ns';
39 39
 
40
-	const PROPERTY_NAME_UNREAD = '{http://owncloud.org/ns}isUnread';
41
-	const PROPERTY_NAME_MESSAGE = '{http://owncloud.org/ns}message';
42
-	const PROPERTY_NAME_ACTOR_DISPLAYNAME = '{http://owncloud.org/ns}actorDisplayName';
43
-	const PROPERTY_NAME_MENTIONS = '{http://owncloud.org/ns}mentions';
44
-	const PROPERTY_NAME_MENTION = '{http://owncloud.org/ns}mention';
45
-	const PROPERTY_NAME_MENTION_TYPE = '{http://owncloud.org/ns}mentionType';
46
-	const PROPERTY_NAME_MENTION_ID = '{http://owncloud.org/ns}mentionId';
47
-	const PROPERTY_NAME_MENTION_DISPLAYNAME = '{http://owncloud.org/ns}mentionDisplayName';
40
+    const PROPERTY_NAME_UNREAD = '{http://owncloud.org/ns}isUnread';
41
+    const PROPERTY_NAME_MESSAGE = '{http://owncloud.org/ns}message';
42
+    const PROPERTY_NAME_ACTOR_DISPLAYNAME = '{http://owncloud.org/ns}actorDisplayName';
43
+    const PROPERTY_NAME_MENTIONS = '{http://owncloud.org/ns}mentions';
44
+    const PROPERTY_NAME_MENTION = '{http://owncloud.org/ns}mention';
45
+    const PROPERTY_NAME_MENTION_TYPE = '{http://owncloud.org/ns}mentionType';
46
+    const PROPERTY_NAME_MENTION_ID = '{http://owncloud.org/ns}mentionId';
47
+    const PROPERTY_NAME_MENTION_DISPLAYNAME = '{http://owncloud.org/ns}mentionDisplayName';
48 48
 
49
-	/** @var  IComment */
50
-	public $comment;
49
+    /** @var  IComment */
50
+    public $comment;
51 51
 
52
-	/** @var ICommentsManager */
53
-	protected $commentsManager;
52
+    /** @var ICommentsManager */
53
+    protected $commentsManager;
54 54
 
55
-	/** @var  ILogger */
56
-	protected $logger;
55
+    /** @var  ILogger */
56
+    protected $logger;
57 57
 
58
-	/** @var array list of properties with key being their name and value their setter */
59
-	protected $properties = [];
58
+    /** @var array list of properties with key being their name and value their setter */
59
+    protected $properties = [];
60 60
 
61
-	/** @var IUserManager */
62
-	protected $userManager;
61
+    /** @var IUserManager */
62
+    protected $userManager;
63 63
 
64
-	/** @var IUserSession */
65
-	protected $userSession;
64
+    /** @var IUserSession */
65
+    protected $userSession;
66 66
 
67
-	/**
68
-	 * CommentNode constructor.
69
-	 *
70
-	 * @param ICommentsManager $commentsManager
71
-	 * @param IComment $comment
72
-	 * @param IUserManager $userManager
73
-	 * @param IUserSession $userSession
74
-	 * @param ILogger $logger
75
-	 */
76
-	public function __construct(
77
-		ICommentsManager $commentsManager,
78
-		IComment $comment,
79
-		IUserManager $userManager,
80
-		IUserSession $userSession,
81
-		ILogger $logger
82
-	) {
83
-		$this->commentsManager = $commentsManager;
84
-		$this->comment = $comment;
85
-		$this->logger = $logger;
67
+    /**
68
+     * CommentNode constructor.
69
+     *
70
+     * @param ICommentsManager $commentsManager
71
+     * @param IComment $comment
72
+     * @param IUserManager $userManager
73
+     * @param IUserSession $userSession
74
+     * @param ILogger $logger
75
+     */
76
+    public function __construct(
77
+        ICommentsManager $commentsManager,
78
+        IComment $comment,
79
+        IUserManager $userManager,
80
+        IUserSession $userSession,
81
+        ILogger $logger
82
+    ) {
83
+        $this->commentsManager = $commentsManager;
84
+        $this->comment = $comment;
85
+        $this->logger = $logger;
86 86
 
87
-		$methods = get_class_methods($this->comment);
88
-		$methods = array_filter($methods, function ($name) {
89
-			return strpos($name, 'get') === 0;
90
-		});
91
-		foreach($methods as $getter) {
92
-			if($getter === 'getMentions') {
93
-				continue;	// special treatment
94
-			}
95
-			$name = '{'.self::NS_OWNCLOUD.'}' . lcfirst(substr($getter, 3));
96
-			$this->properties[$name] = $getter;
97
-		}
98
-		$this->userManager = $userManager;
99
-		$this->userSession = $userSession;
100
-	}
87
+        $methods = get_class_methods($this->comment);
88
+        $methods = array_filter($methods, function ($name) {
89
+            return strpos($name, 'get') === 0;
90
+        });
91
+        foreach($methods as $getter) {
92
+            if($getter === 'getMentions') {
93
+                continue;	// special treatment
94
+            }
95
+            $name = '{'.self::NS_OWNCLOUD.'}' . lcfirst(substr($getter, 3));
96
+            $this->properties[$name] = $getter;
97
+        }
98
+        $this->userManager = $userManager;
99
+        $this->userSession = $userSession;
100
+    }
101 101
 
102
-	/**
103
-	 * returns a list of all possible property names
104
-	 *
105
-	 * @return array
106
-	 */
107
-	static public function getPropertyNames() {
108
-		return [
109
-			'{http://owncloud.org/ns}id',
110
-			'{http://owncloud.org/ns}parentId',
111
-			'{http://owncloud.org/ns}topmostParentId',
112
-			'{http://owncloud.org/ns}childrenCount',
113
-			'{http://owncloud.org/ns}verb',
114
-			'{http://owncloud.org/ns}actorType',
115
-			'{http://owncloud.org/ns}actorId',
116
-			'{http://owncloud.org/ns}creationDateTime',
117
-			'{http://owncloud.org/ns}latestChildDateTime',
118
-			'{http://owncloud.org/ns}objectType',
119
-			'{http://owncloud.org/ns}objectId',
120
-			// re-used property names are defined as constants
121
-			self::PROPERTY_NAME_MESSAGE,
122
-			self::PROPERTY_NAME_ACTOR_DISPLAYNAME,
123
-			self::PROPERTY_NAME_UNREAD,
124
-			self::PROPERTY_NAME_MENTIONS,
125
-			self::PROPERTY_NAME_MENTION,
126
-			self::PROPERTY_NAME_MENTION_TYPE,
127
-			self::PROPERTY_NAME_MENTION_ID,
128
-			self::PROPERTY_NAME_MENTION_DISPLAYNAME,
129
-		];
130
-	}
102
+    /**
103
+     * returns a list of all possible property names
104
+     *
105
+     * @return array
106
+     */
107
+    static public function getPropertyNames() {
108
+        return [
109
+            '{http://owncloud.org/ns}id',
110
+            '{http://owncloud.org/ns}parentId',
111
+            '{http://owncloud.org/ns}topmostParentId',
112
+            '{http://owncloud.org/ns}childrenCount',
113
+            '{http://owncloud.org/ns}verb',
114
+            '{http://owncloud.org/ns}actorType',
115
+            '{http://owncloud.org/ns}actorId',
116
+            '{http://owncloud.org/ns}creationDateTime',
117
+            '{http://owncloud.org/ns}latestChildDateTime',
118
+            '{http://owncloud.org/ns}objectType',
119
+            '{http://owncloud.org/ns}objectId',
120
+            // re-used property names are defined as constants
121
+            self::PROPERTY_NAME_MESSAGE,
122
+            self::PROPERTY_NAME_ACTOR_DISPLAYNAME,
123
+            self::PROPERTY_NAME_UNREAD,
124
+            self::PROPERTY_NAME_MENTIONS,
125
+            self::PROPERTY_NAME_MENTION,
126
+            self::PROPERTY_NAME_MENTION_TYPE,
127
+            self::PROPERTY_NAME_MENTION_ID,
128
+            self::PROPERTY_NAME_MENTION_DISPLAYNAME,
129
+        ];
130
+    }
131 131
 
132
-	protected function checkWriteAccessOnComment() {
133
-		$user = $this->userSession->getUser();
134
-		if(    $this->comment->getActorType() !== 'users'
135
-			|| is_null($user)
136
-			|| $this->comment->getActorId() !== $user->getUID()
137
-		) {
138
-			throw new Forbidden('Only authors are allowed to edit their comment.');
139
-		}
140
-	}
132
+    protected function checkWriteAccessOnComment() {
133
+        $user = $this->userSession->getUser();
134
+        if(    $this->comment->getActorType() !== 'users'
135
+            || is_null($user)
136
+            || $this->comment->getActorId() !== $user->getUID()
137
+        ) {
138
+            throw new Forbidden('Only authors are allowed to edit their comment.');
139
+        }
140
+    }
141 141
 
142
-	/**
143
-	 * Deleted the current node
144
-	 *
145
-	 * @return void
146
-	 */
147
-	function delete() {
148
-		$this->checkWriteAccessOnComment();
149
-		$this->commentsManager->delete($this->comment->getId());
150
-	}
142
+    /**
143
+     * Deleted the current node
144
+     *
145
+     * @return void
146
+     */
147
+    function delete() {
148
+        $this->checkWriteAccessOnComment();
149
+        $this->commentsManager->delete($this->comment->getId());
150
+    }
151 151
 
152
-	/**
153
-	 * Returns the name of the node.
154
-	 *
155
-	 * This is used to generate the url.
156
-	 *
157
-	 * @return string
158
-	 */
159
-	function getName() {
160
-		return $this->comment->getId();
161
-	}
152
+    /**
153
+     * Returns the name of the node.
154
+     *
155
+     * This is used to generate the url.
156
+     *
157
+     * @return string
158
+     */
159
+    function getName() {
160
+        return $this->comment->getId();
161
+    }
162 162
 
163
-	/**
164
-	 * Renames the node
165
-	 *
166
-	 * @param string $name The new name
167
-	 * @throws MethodNotAllowed
168
-	 */
169
-	function setName($name) {
170
-		throw new MethodNotAllowed();
171
-	}
163
+    /**
164
+     * Renames the node
165
+     *
166
+     * @param string $name The new name
167
+     * @throws MethodNotAllowed
168
+     */
169
+    function setName($name) {
170
+        throw new MethodNotAllowed();
171
+    }
172 172
 
173
-	/**
174
-	 * Returns the last modification time, as a unix timestamp
175
-	 *
176
-	 * @return int
177
-	 */
178
-	function getLastModified() {
179
-		return null;
180
-	}
173
+    /**
174
+     * Returns the last modification time, as a unix timestamp
175
+     *
176
+     * @return int
177
+     */
178
+    function getLastModified() {
179
+        return null;
180
+    }
181 181
 
182
-	/**
183
-	 * update the comment's message
184
-	 *
185
-	 * @param $propertyValue
186
-	 * @return bool
187
-	 * @throws BadRequest
188
-	 * @throws \Exception
189
-	 */
190
-	public function updateComment($propertyValue) {
191
-		$this->checkWriteAccessOnComment();
192
-		try {
193
-			$this->comment->setMessage($propertyValue);
194
-			$this->commentsManager->save($this->comment);
195
-			return true;
196
-		} catch (\Exception $e) {
197
-			$this->logger->logException($e, ['app' => 'dav/comments']);
198
-			if($e instanceof MessageTooLongException) {
199
-				$msg = 'Message exceeds allowed character limit of ';
200
-				throw new BadRequest($msg . IComment::MAX_MESSAGE_LENGTH, 0, $e);
201
-			}
202
-			throw $e;
203
-		}
204
-	}
182
+    /**
183
+     * update the comment's message
184
+     *
185
+     * @param $propertyValue
186
+     * @return bool
187
+     * @throws BadRequest
188
+     * @throws \Exception
189
+     */
190
+    public function updateComment($propertyValue) {
191
+        $this->checkWriteAccessOnComment();
192
+        try {
193
+            $this->comment->setMessage($propertyValue);
194
+            $this->commentsManager->save($this->comment);
195
+            return true;
196
+        } catch (\Exception $e) {
197
+            $this->logger->logException($e, ['app' => 'dav/comments']);
198
+            if($e instanceof MessageTooLongException) {
199
+                $msg = 'Message exceeds allowed character limit of ';
200
+                throw new BadRequest($msg . IComment::MAX_MESSAGE_LENGTH, 0, $e);
201
+            }
202
+            throw $e;
203
+        }
204
+    }
205 205
 
206
-	/**
207
-	 * Updates properties on this node.
208
-	 *
209
-	 * This method received a PropPatch object, which contains all the
210
-	 * information about the update.
211
-	 *
212
-	 * To update specific properties, call the 'handle' method on this object.
213
-	 * Read the PropPatch documentation for more information.
214
-	 *
215
-	 * @param PropPatch $propPatch
216
-	 * @return void
217
-	 */
218
-	function propPatch(PropPatch $propPatch) {
219
-		// other properties than 'message' are read only
220
-		$propPatch->handle(self::PROPERTY_NAME_MESSAGE, [$this, 'updateComment']);
221
-	}
206
+    /**
207
+     * Updates properties on this node.
208
+     *
209
+     * This method received a PropPatch object, which contains all the
210
+     * information about the update.
211
+     *
212
+     * To update specific properties, call the 'handle' method on this object.
213
+     * Read the PropPatch documentation for more information.
214
+     *
215
+     * @param PropPatch $propPatch
216
+     * @return void
217
+     */
218
+    function propPatch(PropPatch $propPatch) {
219
+        // other properties than 'message' are read only
220
+        $propPatch->handle(self::PROPERTY_NAME_MESSAGE, [$this, 'updateComment']);
221
+    }
222 222
 
223
-	/**
224
-	 * Returns a list of properties for this nodes.
225
-	 *
226
-	 * The properties list is a list of propertynames the client requested,
227
-	 * encoded in clark-notation {xmlnamespace}tagname
228
-	 *
229
-	 * If the array is empty, it means 'all properties' were requested.
230
-	 *
231
-	 * Note that it's fine to liberally give properties back, instead of
232
-	 * conforming to the list of requested properties.
233
-	 * The Server class will filter out the extra.
234
-	 *
235
-	 * @param array $properties
236
-	 * @return array
237
-	 */
238
-	function getProperties($properties) {
239
-		$properties = array_keys($this->properties);
223
+    /**
224
+     * Returns a list of properties for this nodes.
225
+     *
226
+     * The properties list is a list of propertynames the client requested,
227
+     * encoded in clark-notation {xmlnamespace}tagname
228
+     *
229
+     * If the array is empty, it means 'all properties' were requested.
230
+     *
231
+     * Note that it's fine to liberally give properties back, instead of
232
+     * conforming to the list of requested properties.
233
+     * The Server class will filter out the extra.
234
+     *
235
+     * @param array $properties
236
+     * @return array
237
+     */
238
+    function getProperties($properties) {
239
+        $properties = array_keys($this->properties);
240 240
 
241
-		$result = [];
242
-		foreach($properties as $property) {
243
-			$getter = $this->properties[$property];
244
-			if(method_exists($this->comment, $getter)) {
245
-				$result[$property] = $this->comment->$getter();
246
-			}
247
-		}
241
+        $result = [];
242
+        foreach($properties as $property) {
243
+            $getter = $this->properties[$property];
244
+            if(method_exists($this->comment, $getter)) {
245
+                $result[$property] = $this->comment->$getter();
246
+            }
247
+        }
248 248
 
249
-		if($this->comment->getActorType() === 'users') {
250
-			$user = $this->userManager->get($this->comment->getActorId());
251
-			$displayName = is_null($user) ? null : $user->getDisplayName();
252
-			$result[self::PROPERTY_NAME_ACTOR_DISPLAYNAME] = $displayName;
253
-		}
249
+        if($this->comment->getActorType() === 'users') {
250
+            $user = $this->userManager->get($this->comment->getActorId());
251
+            $displayName = is_null($user) ? null : $user->getDisplayName();
252
+            $result[self::PROPERTY_NAME_ACTOR_DISPLAYNAME] = $displayName;
253
+        }
254 254
 
255
-		$result[self::PROPERTY_NAME_MENTIONS] = $this->composeMentionsPropertyValue();
255
+        $result[self::PROPERTY_NAME_MENTIONS] = $this->composeMentionsPropertyValue();
256 256
 
257
-		$unread = null;
258
-		$user =  $this->userSession->getUser();
259
-		if(!is_null($user)) {
260
-			$readUntil = $this->commentsManager->getReadMark(
261
-				$this->comment->getObjectType(),
262
-				$this->comment->getObjectId(),
263
-				$user
264
-			);
265
-			if(is_null($readUntil)) {
266
-				$unread = 'true';
267
-			} else {
268
-				$unread = $this->comment->getCreationDateTime() > $readUntil;
269
-				// re-format for output
270
-				$unread = $unread ? 'true' : 'false';
271
-			}
272
-		}
273
-		$result[self::PROPERTY_NAME_UNREAD] = $unread;
257
+        $unread = null;
258
+        $user =  $this->userSession->getUser();
259
+        if(!is_null($user)) {
260
+            $readUntil = $this->commentsManager->getReadMark(
261
+                $this->comment->getObjectType(),
262
+                $this->comment->getObjectId(),
263
+                $user
264
+            );
265
+            if(is_null($readUntil)) {
266
+                $unread = 'true';
267
+            } else {
268
+                $unread = $this->comment->getCreationDateTime() > $readUntil;
269
+                // re-format for output
270
+                $unread = $unread ? 'true' : 'false';
271
+            }
272
+        }
273
+        $result[self::PROPERTY_NAME_UNREAD] = $unread;
274 274
 
275
-		return $result;
276
-	}
275
+        return $result;
276
+    }
277 277
 
278
-	/**
279
-	 * transforms a mentions array as returned from IComment->getMentions to an
280
-	 * array with DAV-compatible structure that can be assigned to the
281
-	 * PROPERTY_NAME_MENTION property.
282
-	 *
283
-	 * @return array
284
-	 */
285
-	protected function composeMentionsPropertyValue() {
286
-		return array_map(function ($mention) {
287
-			try {
288
-				$displayName = $this->commentsManager->resolveDisplayName($mention['type'], $mention['id']);
289
-			} catch (\OutOfBoundsException $e) {
290
-				$this->logger->logException($e);
291
-				// No displayname, upon client's discretion what to display.
292
-				$displayName = '';
293
-			}
278
+    /**
279
+     * transforms a mentions array as returned from IComment->getMentions to an
280
+     * array with DAV-compatible structure that can be assigned to the
281
+     * PROPERTY_NAME_MENTION property.
282
+     *
283
+     * @return array
284
+     */
285
+    protected function composeMentionsPropertyValue() {
286
+        return array_map(function ($mention) {
287
+            try {
288
+                $displayName = $this->commentsManager->resolveDisplayName($mention['type'], $mention['id']);
289
+            } catch (\OutOfBoundsException $e) {
290
+                $this->logger->logException($e);
291
+                // No displayname, upon client's discretion what to display.
292
+                $displayName = '';
293
+            }
294 294
 
295
-			return [
296
-				self::PROPERTY_NAME_MENTION => [
297
-					self::PROPERTY_NAME_MENTION_TYPE        => $mention['type'],
298
-					self::PROPERTY_NAME_MENTION_ID          => $mention['id'],
299
-					self::PROPERTY_NAME_MENTION_DISPLAYNAME => $displayName,
300
-				]
301
-			];
302
-		}, $this->comment->getMentions());
303
-	}
295
+            return [
296
+                self::PROPERTY_NAME_MENTION => [
297
+                    self::PROPERTY_NAME_MENTION_TYPE        => $mention['type'],
298
+                    self::PROPERTY_NAME_MENTION_ID          => $mention['id'],
299
+                    self::PROPERTY_NAME_MENTION_DISPLAYNAME => $displayName,
300
+                ]
301
+            ];
302
+        }, $this->comment->getMentions());
303
+    }
304 304
 }
Please login to merge, or discard this patch.
apps/dav/lib/Comments/CommentsPlugin.php 1 patch
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.
apps/dav/lib/CalDAV/CalDavBackend.php 1 patch
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.
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 1 patch
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.
apps/dav/lib/CalDAV/WebcalCaching/RefreshWebcalService.php 1 patch
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.
apps/dav/lib/CalDAV/Calendar.php 1 patch
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.