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