Passed
Push — master ( 4c6eb9...c449d5 )
by Morris
12:27 queued 10s
created
core/Command/App/ListApps.php 1 patch
Indentation   +106 added lines, -106 removed lines patch added patch discarded remove patch
@@ -35,110 +35,110 @@
 block discarded – undo
35 35
 
36 36
 class ListApps extends Base {
37 37
 
38
-	/** @var IAppManager */
39
-	protected $manager;
40
-
41
-	/**
42
-	 * @param IAppManager $manager
43
-	 */
44
-	public function __construct(IAppManager $manager) {
45
-		parent::__construct();
46
-		$this->manager = $manager;
47
-	}
48
-
49
-	protected function configure() {
50
-		parent::configure();
51
-
52
-		$this
53
-			->setName('app:list')
54
-			->setDescription('List all available apps')
55
-			->addOption(
56
-				'shipped',
57
-				null,
58
-				InputOption::VALUE_REQUIRED,
59
-				'true - limit to shipped apps only, false - limit to non-shipped apps only'
60
-			)
61
-		;
62
-	}
63
-
64
-	protected function execute(InputInterface $input, OutputInterface $output): int {
65
-		if ($input->getOption('shipped') === 'true' || $input->getOption('shipped') === 'false') {
66
-			$shippedFilter = $input->getOption('shipped') === 'true';
67
-		} else {
68
-			$shippedFilter = null;
69
-		}
70
-
71
-		$apps = \OC_App::getAllApps();
72
-		$enabledApps = $disabledApps = [];
73
-		$versions = \OC_App::getAppVersions();
74
-
75
-		//sort enabled apps above disabled apps
76
-		foreach ($apps as $app) {
77
-			if ($shippedFilter !== null && $this->manager->isShipped($app) !== $shippedFilter) {
78
-				continue;
79
-			}
80
-			if ($this->manager->isInstalled($app)) {
81
-				$enabledApps[] = $app;
82
-			} else {
83
-				$disabledApps[] = $app;
84
-			}
85
-		}
86
-
87
-		$apps = ['enabled' => [], 'disabled' => []];
88
-
89
-		sort($enabledApps);
90
-		foreach ($enabledApps as $app) {
91
-			$apps['enabled'][$app] = isset($versions[$app]) ? $versions[$app] : true;
92
-		}
93
-
94
-		sort($disabledApps);
95
-		foreach ($disabledApps as $app) {
96
-			$apps['disabled'][$app] = null;
97
-		}
98
-
99
-		$this->writeAppList($input, $output, $apps);
100
-		return 0;
101
-	}
102
-
103
-	/**
104
-	 * @param InputInterface $input
105
-	 * @param OutputInterface $output
106
-	 * @param array $items
107
-	 */
108
-	protected function writeAppList(InputInterface $input, OutputInterface $output, $items) {
109
-		switch ($input->getOption('output')) {
110
-			case self::OUTPUT_FORMAT_PLAIN:
111
-				$output->writeln('Enabled:');
112
-				parent::writeArrayInOutputFormat($input, $output, $items['enabled']);
113
-
114
-				$output->writeln('Disabled:');
115
-				parent::writeArrayInOutputFormat($input, $output, $items['disabled']);
116
-			break;
117
-
118
-			default:
119
-				parent::writeArrayInOutputFormat($input, $output, $items);
120
-			break;
121
-		}
122
-	}
123
-
124
-	/**
125
-	 * @param string $optionName
126
-	 * @param CompletionContext $context
127
-	 * @return array
128
-	 */
129
-	public function completeOptionValues($optionName, CompletionContext $context) {
130
-		if ($optionName === 'shipped') {
131
-			return ['true', 'false'];
132
-		}
133
-		return [];
134
-	}
135
-
136
-	/**
137
-	 * @param string $argumentName
138
-	 * @param CompletionContext $context
139
-	 * @return string[]
140
-	 */
141
-	public function completeArgumentValues($argumentName, CompletionContext $context) {
142
-		return [];
143
-	}
38
+    /** @var IAppManager */
39
+    protected $manager;
40
+
41
+    /**
42
+     * @param IAppManager $manager
43
+     */
44
+    public function __construct(IAppManager $manager) {
45
+        parent::__construct();
46
+        $this->manager = $manager;
47
+    }
48
+
49
+    protected function configure() {
50
+        parent::configure();
51
+
52
+        $this
53
+            ->setName('app:list')
54
+            ->setDescription('List all available apps')
55
+            ->addOption(
56
+                'shipped',
57
+                null,
58
+                InputOption::VALUE_REQUIRED,
59
+                'true - limit to shipped apps only, false - limit to non-shipped apps only'
60
+            )
61
+        ;
62
+    }
63
+
64
+    protected function execute(InputInterface $input, OutputInterface $output): int {
65
+        if ($input->getOption('shipped') === 'true' || $input->getOption('shipped') === 'false') {
66
+            $shippedFilter = $input->getOption('shipped') === 'true';
67
+        } else {
68
+            $shippedFilter = null;
69
+        }
70
+
71
+        $apps = \OC_App::getAllApps();
72
+        $enabledApps = $disabledApps = [];
73
+        $versions = \OC_App::getAppVersions();
74
+
75
+        //sort enabled apps above disabled apps
76
+        foreach ($apps as $app) {
77
+            if ($shippedFilter !== null && $this->manager->isShipped($app) !== $shippedFilter) {
78
+                continue;
79
+            }
80
+            if ($this->manager->isInstalled($app)) {
81
+                $enabledApps[] = $app;
82
+            } else {
83
+                $disabledApps[] = $app;
84
+            }
85
+        }
86
+
87
+        $apps = ['enabled' => [], 'disabled' => []];
88
+
89
+        sort($enabledApps);
90
+        foreach ($enabledApps as $app) {
91
+            $apps['enabled'][$app] = isset($versions[$app]) ? $versions[$app] : true;
92
+        }
93
+
94
+        sort($disabledApps);
95
+        foreach ($disabledApps as $app) {
96
+            $apps['disabled'][$app] = null;
97
+        }
98
+
99
+        $this->writeAppList($input, $output, $apps);
100
+        return 0;
101
+    }
102
+
103
+    /**
104
+     * @param InputInterface $input
105
+     * @param OutputInterface $output
106
+     * @param array $items
107
+     */
108
+    protected function writeAppList(InputInterface $input, OutputInterface $output, $items) {
109
+        switch ($input->getOption('output')) {
110
+            case self::OUTPUT_FORMAT_PLAIN:
111
+                $output->writeln('Enabled:');
112
+                parent::writeArrayInOutputFormat($input, $output, $items['enabled']);
113
+
114
+                $output->writeln('Disabled:');
115
+                parent::writeArrayInOutputFormat($input, $output, $items['disabled']);
116
+            break;
117
+
118
+            default:
119
+                parent::writeArrayInOutputFormat($input, $output, $items);
120
+            break;
121
+        }
122
+    }
123
+
124
+    /**
125
+     * @param string $optionName
126
+     * @param CompletionContext $context
127
+     * @return array
128
+     */
129
+    public function completeOptionValues($optionName, CompletionContext $context) {
130
+        if ($optionName === 'shipped') {
131
+            return ['true', 'false'];
132
+        }
133
+        return [];
134
+    }
135
+
136
+    /**
137
+     * @param string $argumentName
138
+     * @param CompletionContext $context
139
+     * @return string[]
140
+     */
141
+    public function completeArgumentValues($argumentName, CompletionContext $context) {
142
+        return [];
143
+    }
144 144
 }
Please login to merge, or discard this patch.
apps/user_ldap/lib/User_Proxy.php 1 patch
Indentation   +331 added lines, -331 removed lines patch added patch discarded remove patch
@@ -38,360 +38,360 @@
 block discarded – undo
38 38
 use OCP\Notification\IManager as INotificationManager;
39 39
 
40 40
 class User_Proxy extends Proxy implements \OCP\IUserBackend, \OCP\UserInterface, IUserLDAP {
41
-	private $backends = [];
42
-	/** @var User_LDAP */
43
-	private $refBackend = null;
41
+    private $backends = [];
42
+    /** @var User_LDAP */
43
+    private $refBackend = null;
44 44
 
45
-	/**
46
-	 * Constructor
47
-	 *
48
-	 * @param array $serverConfigPrefixes array containing the config Prefixes
49
-	 * @param ILDAPWrapper $ldap
50
-	 * @param IConfig $ocConfig
51
-	 * @param INotificationManager $notificationManager
52
-	 * @param IUserSession $userSession
53
-	 */
54
-	public function __construct(
55
-		array $serverConfigPrefixes,
56
-		ILDAPWrapper $ldap,
57
-		IConfig $ocConfig,
58
-		INotificationManager $notificationManager,
59
-		IUserSession $userSession,
60
-		UserPluginManager $userPluginManager
61
-	) {
62
-		parent::__construct($ldap);
63
-		foreach ($serverConfigPrefixes as $configPrefix) {
64
-			$this->backends[$configPrefix] =
65
-				new User_LDAP($this->getAccess($configPrefix), $ocConfig, $notificationManager, $userSession, $userPluginManager);
45
+    /**
46
+     * Constructor
47
+     *
48
+     * @param array $serverConfigPrefixes array containing the config Prefixes
49
+     * @param ILDAPWrapper $ldap
50
+     * @param IConfig $ocConfig
51
+     * @param INotificationManager $notificationManager
52
+     * @param IUserSession $userSession
53
+     */
54
+    public function __construct(
55
+        array $serverConfigPrefixes,
56
+        ILDAPWrapper $ldap,
57
+        IConfig $ocConfig,
58
+        INotificationManager $notificationManager,
59
+        IUserSession $userSession,
60
+        UserPluginManager $userPluginManager
61
+    ) {
62
+        parent::__construct($ldap);
63
+        foreach ($serverConfigPrefixes as $configPrefix) {
64
+            $this->backends[$configPrefix] =
65
+                new User_LDAP($this->getAccess($configPrefix), $ocConfig, $notificationManager, $userSession, $userPluginManager);
66 66
 
67
-			if (is_null($this->refBackend)) {
68
-				$this->refBackend = &$this->backends[$configPrefix];
69
-			}
70
-		}
71
-	}
67
+            if (is_null($this->refBackend)) {
68
+                $this->refBackend = &$this->backends[$configPrefix];
69
+            }
70
+        }
71
+    }
72 72
 
73
-	/**
74
-	 * Tries the backends one after the other until a positive result is returned from the specified method
75
-	 *
76
-	 * @param string $id the uid connected to the request
77
-	 * @param string $method the method of the user backend that shall be called
78
-	 * @param array $parameters an array of parameters to be passed
79
-	 * @return mixed the result of the method or false
80
-	 */
81
-	protected function walkBackends($id, $method, $parameters) {
82
-		$uid = $id;
83
-		$cacheKey = $this->getUserCacheKey($uid);
84
-		foreach ($this->backends as $configPrefix => $backend) {
85
-			$instance = $backend;
86
-			if (!method_exists($instance, $method)
87
-				&& method_exists($this->getAccess($configPrefix), $method)) {
88
-				$instance = $this->getAccess($configPrefix);
89
-			}
90
-			if ($result = call_user_func_array([$instance, $method], $parameters)) {
91
-				if (!$this->isSingleBackend()) {
92
-					$this->writeToCache($cacheKey, $configPrefix);
93
-				}
94
-				return $result;
95
-			}
96
-		}
97
-		return false;
98
-	}
73
+    /**
74
+     * Tries the backends one after the other until a positive result is returned from the specified method
75
+     *
76
+     * @param string $id the uid connected to the request
77
+     * @param string $method the method of the user backend that shall be called
78
+     * @param array $parameters an array of parameters to be passed
79
+     * @return mixed the result of the method or false
80
+     */
81
+    protected function walkBackends($id, $method, $parameters) {
82
+        $uid = $id;
83
+        $cacheKey = $this->getUserCacheKey($uid);
84
+        foreach ($this->backends as $configPrefix => $backend) {
85
+            $instance = $backend;
86
+            if (!method_exists($instance, $method)
87
+                && method_exists($this->getAccess($configPrefix), $method)) {
88
+                $instance = $this->getAccess($configPrefix);
89
+            }
90
+            if ($result = call_user_func_array([$instance, $method], $parameters)) {
91
+                if (!$this->isSingleBackend()) {
92
+                    $this->writeToCache($cacheKey, $configPrefix);
93
+                }
94
+                return $result;
95
+            }
96
+        }
97
+        return false;
98
+    }
99 99
 
100
-	/**
101
-	 * Asks the backend connected to the server that supposely takes care of the uid from the request.
102
-	 *
103
-	 * @param string $id the uid connected to the request
104
-	 * @param string $method the method of the user backend that shall be called
105
-	 * @param array $parameters an array of parameters to be passed
106
-	 * @param mixed $passOnWhen the result matches this variable
107
-	 * @return mixed the result of the method or false
108
-	 */
109
-	protected function callOnLastSeenOn($id, $method, $parameters, $passOnWhen) {
110
-		$uid = $id;
111
-		$cacheKey = $this->getUserCacheKey($uid);
112
-		$prefix = $this->getFromCache($cacheKey);
113
-		//in case the uid has been found in the past, try this stored connection first
114
-		if (!is_null($prefix)) {
115
-			if (isset($this->backends[$prefix])) {
116
-				$instance = $this->backends[$prefix];
117
-				if (!method_exists($instance, $method)
118
-					&& method_exists($this->getAccess($prefix), $method)) {
119
-					$instance = $this->getAccess($prefix);
120
-				}
121
-				$result = call_user_func_array([$instance, $method], $parameters);
122
-				if ($result === $passOnWhen) {
123
-					//not found here, reset cache to null if user vanished
124
-					//because sometimes methods return false with a reason
125
-					$userExists = call_user_func_array(
126
-						[$this->backends[$prefix], 'userExistsOnLDAP'],
127
-						[$uid]
128
-					);
129
-					if (!$userExists) {
130
-						$this->writeToCache($cacheKey, null);
131
-					}
132
-				}
133
-				return $result;
134
-			}
135
-		}
136
-		return false;
137
-	}
100
+    /**
101
+     * Asks the backend connected to the server that supposely takes care of the uid from the request.
102
+     *
103
+     * @param string $id the uid connected to the request
104
+     * @param string $method the method of the user backend that shall be called
105
+     * @param array $parameters an array of parameters to be passed
106
+     * @param mixed $passOnWhen the result matches this variable
107
+     * @return mixed the result of the method or false
108
+     */
109
+    protected function callOnLastSeenOn($id, $method, $parameters, $passOnWhen) {
110
+        $uid = $id;
111
+        $cacheKey = $this->getUserCacheKey($uid);
112
+        $prefix = $this->getFromCache($cacheKey);
113
+        //in case the uid has been found in the past, try this stored connection first
114
+        if (!is_null($prefix)) {
115
+            if (isset($this->backends[$prefix])) {
116
+                $instance = $this->backends[$prefix];
117
+                if (!method_exists($instance, $method)
118
+                    && method_exists($this->getAccess($prefix), $method)) {
119
+                    $instance = $this->getAccess($prefix);
120
+                }
121
+                $result = call_user_func_array([$instance, $method], $parameters);
122
+                if ($result === $passOnWhen) {
123
+                    //not found here, reset cache to null if user vanished
124
+                    //because sometimes methods return false with a reason
125
+                    $userExists = call_user_func_array(
126
+                        [$this->backends[$prefix], 'userExistsOnLDAP'],
127
+                        [$uid]
128
+                    );
129
+                    if (!$userExists) {
130
+                        $this->writeToCache($cacheKey, null);
131
+                    }
132
+                }
133
+                return $result;
134
+            }
135
+        }
136
+        return false;
137
+    }
138 138
 
139
-	protected function activeBackends(): int {
140
-		return count($this->backends);
141
-	}
139
+    protected function activeBackends(): int {
140
+        return count($this->backends);
141
+    }
142 142
 
143
-	/**
144
-	 * Check if backend implements actions
145
-	 *
146
-	 * @param int $actions bitwise-or'ed actions
147
-	 * @return boolean
148
-	 *
149
-	 * Returns the supported actions as int to be
150
-	 * compared with \OC\User\Backend::CREATE_USER etc.
151
-	 */
152
-	public function implementsActions($actions) {
153
-		//it's the same across all our user backends obviously
154
-		return $this->refBackend->implementsActions($actions);
155
-	}
143
+    /**
144
+     * Check if backend implements actions
145
+     *
146
+     * @param int $actions bitwise-or'ed actions
147
+     * @return boolean
148
+     *
149
+     * Returns the supported actions as int to be
150
+     * compared with \OC\User\Backend::CREATE_USER etc.
151
+     */
152
+    public function implementsActions($actions) {
153
+        //it's the same across all our user backends obviously
154
+        return $this->refBackend->implementsActions($actions);
155
+    }
156 156
 
157
-	/**
158
-	 * Backend name to be shown in user management
159
-	 *
160
-	 * @return string the name of the backend to be shown
161
-	 */
162
-	public function getBackendName() {
163
-		return $this->refBackend->getBackendName();
164
-	}
157
+    /**
158
+     * Backend name to be shown in user management
159
+     *
160
+     * @return string the name of the backend to be shown
161
+     */
162
+    public function getBackendName() {
163
+        return $this->refBackend->getBackendName();
164
+    }
165 165
 
166
-	/**
167
-	 * Get a list of all users
168
-	 *
169
-	 * @param string $search
170
-	 * @param null|int $limit
171
-	 * @param null|int $offset
172
-	 * @return string[] an array of all uids
173
-	 */
174
-	public function getUsers($search = '', $limit = 10, $offset = 0) {
175
-		//we do it just as the /OC_User implementation: do not play around with limit and offset but ask all backends
176
-		$users = [];
177
-		foreach ($this->backends as $backend) {
178
-			$backendUsers = $backend->getUsers($search, $limit, $offset);
179
-			if (is_array($backendUsers)) {
180
-				$users = array_merge($users, $backendUsers);
181
-			}
182
-		}
183
-		return $users;
184
-	}
166
+    /**
167
+     * Get a list of all users
168
+     *
169
+     * @param string $search
170
+     * @param null|int $limit
171
+     * @param null|int $offset
172
+     * @return string[] an array of all uids
173
+     */
174
+    public function getUsers($search = '', $limit = 10, $offset = 0) {
175
+        //we do it just as the /OC_User implementation: do not play around with limit and offset but ask all backends
176
+        $users = [];
177
+        foreach ($this->backends as $backend) {
178
+            $backendUsers = $backend->getUsers($search, $limit, $offset);
179
+            if (is_array($backendUsers)) {
180
+                $users = array_merge($users, $backendUsers);
181
+            }
182
+        }
183
+        return $users;
184
+    }
185 185
 
186
-	/**
187
-	 * check if a user exists
188
-	 *
189
-	 * @param string $uid the username
190
-	 * @return boolean
191
-	 */
192
-	public function userExists($uid) {
193
-		$existsOnLDAP = false;
194
-		$existsLocally = $this->handleRequest($uid, 'userExists', [$uid]);
195
-		if ($existsLocally) {
196
-			$existsOnLDAP = $this->userExistsOnLDAP($uid);
197
-		}
198
-		if ($existsLocally && !$existsOnLDAP) {
199
-			try {
200
-				$user = $this->getLDAPAccess($uid)->userManager->get($uid);
201
-				if ($user instanceof User) {
202
-					$user->markUser();
203
-				}
204
-			} catch (\Exception $e) {
205
-				// ignore
206
-			}
207
-		}
208
-		return $existsLocally;
209
-	}
186
+    /**
187
+     * check if a user exists
188
+     *
189
+     * @param string $uid the username
190
+     * @return boolean
191
+     */
192
+    public function userExists($uid) {
193
+        $existsOnLDAP = false;
194
+        $existsLocally = $this->handleRequest($uid, 'userExists', [$uid]);
195
+        if ($existsLocally) {
196
+            $existsOnLDAP = $this->userExistsOnLDAP($uid);
197
+        }
198
+        if ($existsLocally && !$existsOnLDAP) {
199
+            try {
200
+                $user = $this->getLDAPAccess($uid)->userManager->get($uid);
201
+                if ($user instanceof User) {
202
+                    $user->markUser();
203
+                }
204
+            } catch (\Exception $e) {
205
+                // ignore
206
+            }
207
+        }
208
+        return $existsLocally;
209
+    }
210 210
 
211
-	/**
212
-	 * check if a user exists on LDAP
213
-	 *
214
-	 * @param string|\OCA\User_LDAP\User\User $user either the Nextcloud user
215
-	 * name or an instance of that user
216
-	 * @return boolean
217
-	 */
218
-	public function userExistsOnLDAP($user) {
219
-		$id = ($user instanceof User) ? $user->getUsername() : $user;
220
-		return $this->handleRequest($id, 'userExistsOnLDAP', [$user]);
221
-	}
211
+    /**
212
+     * check if a user exists on LDAP
213
+     *
214
+     * @param string|\OCA\User_LDAP\User\User $user either the Nextcloud user
215
+     * name or an instance of that user
216
+     * @return boolean
217
+     */
218
+    public function userExistsOnLDAP($user) {
219
+        $id = ($user instanceof User) ? $user->getUsername() : $user;
220
+        return $this->handleRequest($id, 'userExistsOnLDAP', [$user]);
221
+    }
222 222
 
223
-	/**
224
-	 * Check if the password is correct
225
-	 *
226
-	 * @param string $uid The username
227
-	 * @param string $password The password
228
-	 * @return bool
229
-	 *
230
-	 * Check if the password is correct without logging in the user
231
-	 */
232
-	public function checkPassword($uid, $password) {
233
-		return $this->handleRequest($uid, 'checkPassword', [$uid, $password]);
234
-	}
223
+    /**
224
+     * Check if the password is correct
225
+     *
226
+     * @param string $uid The username
227
+     * @param string $password The password
228
+     * @return bool
229
+     *
230
+     * Check if the password is correct without logging in the user
231
+     */
232
+    public function checkPassword($uid, $password) {
233
+        return $this->handleRequest($uid, 'checkPassword', [$uid, $password]);
234
+    }
235 235
 
236
-	/**
237
-	 * returns the username for the given login name, if available
238
-	 *
239
-	 * @param string $loginName
240
-	 * @return string|false
241
-	 */
242
-	public function loginName2UserName($loginName) {
243
-		$id = 'LOGINNAME,' . $loginName;
244
-		return $this->handleRequest($id, 'loginName2UserName', [$loginName]);
245
-	}
236
+    /**
237
+     * returns the username for the given login name, if available
238
+     *
239
+     * @param string $loginName
240
+     * @return string|false
241
+     */
242
+    public function loginName2UserName($loginName) {
243
+        $id = 'LOGINNAME,' . $loginName;
244
+        return $this->handleRequest($id, 'loginName2UserName', [$loginName]);
245
+    }
246 246
 
247
-	/**
248
-	 * returns the username for the given LDAP DN, if available
249
-	 *
250
-	 * @param string $dn
251
-	 * @return string|false with the username
252
-	 */
253
-	public function dn2UserName($dn) {
254
-		$id = 'DN,' . $dn;
255
-		return $this->handleRequest($id, 'dn2UserName', [$dn]);
256
-	}
247
+    /**
248
+     * returns the username for the given LDAP DN, if available
249
+     *
250
+     * @param string $dn
251
+     * @return string|false with the username
252
+     */
253
+    public function dn2UserName($dn) {
254
+        $id = 'DN,' . $dn;
255
+        return $this->handleRequest($id, 'dn2UserName', [$dn]);
256
+    }
257 257
 
258
-	/**
259
-	 * get the user's home directory
260
-	 *
261
-	 * @param string $uid the username
262
-	 * @return boolean
263
-	 */
264
-	public function getHome($uid) {
265
-		return $this->handleRequest($uid, 'getHome', [$uid]);
266
-	}
258
+    /**
259
+     * get the user's home directory
260
+     *
261
+     * @param string $uid the username
262
+     * @return boolean
263
+     */
264
+    public function getHome($uid) {
265
+        return $this->handleRequest($uid, 'getHome', [$uid]);
266
+    }
267 267
 
268
-	/**
269
-	 * get display name of the user
270
-	 *
271
-	 * @param string $uid user ID of the user
272
-	 * @return string display name
273
-	 */
274
-	public function getDisplayName($uid) {
275
-		return $this->handleRequest($uid, 'getDisplayName', [$uid]);
276
-	}
268
+    /**
269
+     * get display name of the user
270
+     *
271
+     * @param string $uid user ID of the user
272
+     * @return string display name
273
+     */
274
+    public function getDisplayName($uid) {
275
+        return $this->handleRequest($uid, 'getDisplayName', [$uid]);
276
+    }
277 277
 
278
-	/**
279
-	 * set display name of the user
280
-	 *
281
-	 * @param string $uid user ID of the user
282
-	 * @param string $displayName new display name
283
-	 * @return string display name
284
-	 */
285
-	public function setDisplayName($uid, $displayName) {
286
-		return $this->handleRequest($uid, 'setDisplayName', [$uid, $displayName]);
287
-	}
278
+    /**
279
+     * set display name of the user
280
+     *
281
+     * @param string $uid user ID of the user
282
+     * @param string $displayName new display name
283
+     * @return string display name
284
+     */
285
+    public function setDisplayName($uid, $displayName) {
286
+        return $this->handleRequest($uid, 'setDisplayName', [$uid, $displayName]);
287
+    }
288 288
 
289
-	/**
290
-	 * checks whether the user is allowed to change his avatar in Nextcloud
291
-	 *
292
-	 * @param string $uid the Nextcloud user name
293
-	 * @return boolean either the user can or cannot
294
-	 */
295
-	public function canChangeAvatar($uid) {
296
-		return $this->handleRequest($uid, 'canChangeAvatar', [$uid], true);
297
-	}
289
+    /**
290
+     * checks whether the user is allowed to change his avatar in Nextcloud
291
+     *
292
+     * @param string $uid the Nextcloud user name
293
+     * @return boolean either the user can or cannot
294
+     */
295
+    public function canChangeAvatar($uid) {
296
+        return $this->handleRequest($uid, 'canChangeAvatar', [$uid], true);
297
+    }
298 298
 
299
-	/**
300
-	 * Get a list of all display names and user ids.
301
-	 *
302
-	 * @param string $search
303
-	 * @param string|null $limit
304
-	 * @param string|null $offset
305
-	 * @return array an array of all displayNames (value) and the corresponding uids (key)
306
-	 */
307
-	public function getDisplayNames($search = '', $limit = null, $offset = null) {
308
-		//we do it just as the /OC_User implementation: do not play around with limit and offset but ask all backends
309
-		$users = [];
310
-		foreach ($this->backends as $backend) {
311
-			$backendUsers = $backend->getDisplayNames($search, $limit, $offset);
312
-			if (is_array($backendUsers)) {
313
-				$users = $users + $backendUsers;
314
-			}
315
-		}
316
-		return $users;
317
-	}
299
+    /**
300
+     * Get a list of all display names and user ids.
301
+     *
302
+     * @param string $search
303
+     * @param string|null $limit
304
+     * @param string|null $offset
305
+     * @return array an array of all displayNames (value) and the corresponding uids (key)
306
+     */
307
+    public function getDisplayNames($search = '', $limit = null, $offset = null) {
308
+        //we do it just as the /OC_User implementation: do not play around with limit and offset but ask all backends
309
+        $users = [];
310
+        foreach ($this->backends as $backend) {
311
+            $backendUsers = $backend->getDisplayNames($search, $limit, $offset);
312
+            if (is_array($backendUsers)) {
313
+                $users = $users + $backendUsers;
314
+            }
315
+        }
316
+        return $users;
317
+    }
318 318
 
319
-	/**
320
-	 * delete a user
321
-	 *
322
-	 * @param string $uid The username of the user to delete
323
-	 * @return bool
324
-	 *
325
-	 * Deletes a user
326
-	 */
327
-	public function deleteUser($uid) {
328
-		return $this->handleRequest($uid, 'deleteUser', [$uid]);
329
-	}
319
+    /**
320
+     * delete a user
321
+     *
322
+     * @param string $uid The username of the user to delete
323
+     * @return bool
324
+     *
325
+     * Deletes a user
326
+     */
327
+    public function deleteUser($uid) {
328
+        return $this->handleRequest($uid, 'deleteUser', [$uid]);
329
+    }
330 330
 
331
-	/**
332
-	 * Set password
333
-	 *
334
-	 * @param string $uid The username
335
-	 * @param string $password The new password
336
-	 * @return bool
337
-	 *
338
-	 */
339
-	public function setPassword($uid, $password) {
340
-		return $this->handleRequest($uid, 'setPassword', [$uid, $password]);
341
-	}
331
+    /**
332
+     * Set password
333
+     *
334
+     * @param string $uid The username
335
+     * @param string $password The new password
336
+     * @return bool
337
+     *
338
+     */
339
+    public function setPassword($uid, $password) {
340
+        return $this->handleRequest($uid, 'setPassword', [$uid, $password]);
341
+    }
342 342
 
343
-	/**
344
-	 * @return bool
345
-	 */
346
-	public function hasUserListings() {
347
-		return $this->refBackend->hasUserListings();
348
-	}
343
+    /**
344
+     * @return bool
345
+     */
346
+    public function hasUserListings() {
347
+        return $this->refBackend->hasUserListings();
348
+    }
349 349
 
350
-	/**
351
-	 * Count the number of users
352
-	 *
353
-	 * @return int|bool
354
-	 */
355
-	public function countUsers() {
356
-		$users = false;
357
-		foreach ($this->backends as $backend) {
358
-			$backendUsers = $backend->countUsers();
359
-			if ($backendUsers !== false) {
360
-				$users += $backendUsers;
361
-			}
362
-		}
363
-		return $users;
364
-	}
350
+    /**
351
+     * Count the number of users
352
+     *
353
+     * @return int|bool
354
+     */
355
+    public function countUsers() {
356
+        $users = false;
357
+        foreach ($this->backends as $backend) {
358
+            $backendUsers = $backend->countUsers();
359
+            if ($backendUsers !== false) {
360
+                $users += $backendUsers;
361
+            }
362
+        }
363
+        return $users;
364
+    }
365 365
 
366
-	/**
367
-	 * Return access for LDAP interaction.
368
-	 *
369
-	 * @param string $uid
370
-	 * @return Access instance of Access for LDAP interaction
371
-	 */
372
-	public function getLDAPAccess($uid) {
373
-		return $this->handleRequest($uid, 'getLDAPAccess', [$uid]);
374
-	}
366
+    /**
367
+     * Return access for LDAP interaction.
368
+     *
369
+     * @param string $uid
370
+     * @return Access instance of Access for LDAP interaction
371
+     */
372
+    public function getLDAPAccess($uid) {
373
+        return $this->handleRequest($uid, 'getLDAPAccess', [$uid]);
374
+    }
375 375
 
376
-	/**
377
-	 * Return a new LDAP connection for the specified user.
378
-	 * The connection needs to be closed manually.
379
-	 *
380
-	 * @param string $uid
381
-	 * @return resource of the LDAP connection
382
-	 */
383
-	public function getNewLDAPConnection($uid) {
384
-		return $this->handleRequest($uid, 'getNewLDAPConnection', [$uid]);
385
-	}
376
+    /**
377
+     * Return a new LDAP connection for the specified user.
378
+     * The connection needs to be closed manually.
379
+     *
380
+     * @param string $uid
381
+     * @return resource of the LDAP connection
382
+     */
383
+    public function getNewLDAPConnection($uid) {
384
+        return $this->handleRequest($uid, 'getNewLDAPConnection', [$uid]);
385
+    }
386 386
 
387
-	/**
388
-	 * Creates a new user in LDAP
389
-	 *
390
-	 * @param $username
391
-	 * @param $password
392
-	 * @return bool
393
-	 */
394
-	public function createUser($username, $password) {
395
-		return $this->handleRequest($username, 'createUser', [$username, $password]);
396
-	}
387
+    /**
388
+     * Creates a new user in LDAP
389
+     *
390
+     * @param $username
391
+     * @param $password
392
+     * @return bool
393
+     */
394
+    public function createUser($username, $password) {
395
+        return $this->handleRequest($username, 'createUser', [$username, $password]);
396
+    }
397 397
 }
Please login to merge, or discard this patch.
apps/user_ldap/lib/Group_Proxy.php 1 patch
Indentation   +246 added lines, -246 removed lines patch added patch discarded remove patch
@@ -31,275 +31,275 @@
 block discarded – undo
31 31
 use OCP\Group\Backend\IGetDisplayNameBackend;
32 32
 
33 33
 class Group_Proxy extends Proxy implements \OCP\GroupInterface, IGroupLDAP, IGetDisplayNameBackend {
34
-	private $backends = [];
35
-	private $refBackend = null;
34
+    private $backends = [];
35
+    private $refBackend = null;
36 36
 
37
-	/**
38
-	 * Constructor
39
-	 *
40
-	 * @param string[] $serverConfigPrefixes array containing the config Prefixes
41
-	 */
42
-	public function __construct($serverConfigPrefixes, ILDAPWrapper $ldap, GroupPluginManager $groupPluginManager) {
43
-		parent::__construct($ldap);
44
-		foreach ($serverConfigPrefixes as $configPrefix) {
45
-			$this->backends[$configPrefix] =
46
-				new \OCA\User_LDAP\Group_LDAP($this->getAccess($configPrefix), $groupPluginManager);
47
-			if (is_null($this->refBackend)) {
48
-				$this->refBackend = &$this->backends[$configPrefix];
49
-			}
50
-		}
51
-	}
37
+    /**
38
+     * Constructor
39
+     *
40
+     * @param string[] $serverConfigPrefixes array containing the config Prefixes
41
+     */
42
+    public function __construct($serverConfigPrefixes, ILDAPWrapper $ldap, GroupPluginManager $groupPluginManager) {
43
+        parent::__construct($ldap);
44
+        foreach ($serverConfigPrefixes as $configPrefix) {
45
+            $this->backends[$configPrefix] =
46
+                new \OCA\User_LDAP\Group_LDAP($this->getAccess($configPrefix), $groupPluginManager);
47
+            if (is_null($this->refBackend)) {
48
+                $this->refBackend = &$this->backends[$configPrefix];
49
+            }
50
+        }
51
+    }
52 52
 
53
-	/**
54
-	 * Tries the backends one after the other until a positive result is returned from the specified method
55
-	 *
56
-	 * @param string $id the gid connected to the request
57
-	 * @param string $method the method of the group backend that shall be called
58
-	 * @param array $parameters an array of parameters to be passed
59
-	 * @return mixed the result of the method or false
60
-	 */
61
-	protected function walkBackends($id, $method, $parameters) {
62
-		$gid = $id;
63
-		$cacheKey = $this->getGroupCacheKey($gid);
64
-		foreach ($this->backends as $configPrefix => $backend) {
65
-			if ($result = call_user_func_array([$backend, $method], $parameters)) {
66
-				if (!$this->isSingleBackend()) {
67
-					$this->writeToCache($cacheKey, $configPrefix);
68
-				}
69
-				return $result;
70
-			}
71
-		}
72
-		return false;
73
-	}
53
+    /**
54
+     * Tries the backends one after the other until a positive result is returned from the specified method
55
+     *
56
+     * @param string $id the gid connected to the request
57
+     * @param string $method the method of the group backend that shall be called
58
+     * @param array $parameters an array of parameters to be passed
59
+     * @return mixed the result of the method or false
60
+     */
61
+    protected function walkBackends($id, $method, $parameters) {
62
+        $gid = $id;
63
+        $cacheKey = $this->getGroupCacheKey($gid);
64
+        foreach ($this->backends as $configPrefix => $backend) {
65
+            if ($result = call_user_func_array([$backend, $method], $parameters)) {
66
+                if (!$this->isSingleBackend()) {
67
+                    $this->writeToCache($cacheKey, $configPrefix);
68
+                }
69
+                return $result;
70
+            }
71
+        }
72
+        return false;
73
+    }
74 74
 
75
-	/**
76
-	 * Asks the backend connected to the server that supposely takes care of the gid from the request.
77
-	 *
78
-	 * @param string $id the gid connected to the request
79
-	 * @param string $method the method of the group backend that shall be called
80
-	 * @param array $parameters an array of parameters to be passed
81
-	 * @param mixed $passOnWhen the result matches this variable
82
-	 * @return mixed the result of the method or false
83
-	 */
84
-	protected function callOnLastSeenOn($id, $method, $parameters, $passOnWhen) {
85
-		$gid = $id;
86
-		$cacheKey = $this->getGroupCacheKey($gid);
87
-		$prefix = $this->getFromCache($cacheKey);
88
-		//in case the uid has been found in the past, try this stored connection first
89
-		if (!is_null($prefix)) {
90
-			if (isset($this->backends[$prefix])) {
91
-				$result = call_user_func_array([$this->backends[$prefix], $method], $parameters);
92
-				if ($result === $passOnWhen) {
93
-					//not found here, reset cache to null if group vanished
94
-					//because sometimes methods return false with a reason
95
-					$groupExists = call_user_func_array(
96
-						[$this->backends[$prefix], 'groupExists'],
97
-						[$gid]
98
-					);
99
-					if (!$groupExists) {
100
-						$this->writeToCache($cacheKey, null);
101
-					}
102
-				}
103
-				return $result;
104
-			}
105
-		}
106
-		return false;
107
-	}
75
+    /**
76
+     * Asks the backend connected to the server that supposely takes care of the gid from the request.
77
+     *
78
+     * @param string $id the gid connected to the request
79
+     * @param string $method the method of the group backend that shall be called
80
+     * @param array $parameters an array of parameters to be passed
81
+     * @param mixed $passOnWhen the result matches this variable
82
+     * @return mixed the result of the method or false
83
+     */
84
+    protected function callOnLastSeenOn($id, $method, $parameters, $passOnWhen) {
85
+        $gid = $id;
86
+        $cacheKey = $this->getGroupCacheKey($gid);
87
+        $prefix = $this->getFromCache($cacheKey);
88
+        //in case the uid has been found in the past, try this stored connection first
89
+        if (!is_null($prefix)) {
90
+            if (isset($this->backends[$prefix])) {
91
+                $result = call_user_func_array([$this->backends[$prefix], $method], $parameters);
92
+                if ($result === $passOnWhen) {
93
+                    //not found here, reset cache to null if group vanished
94
+                    //because sometimes methods return false with a reason
95
+                    $groupExists = call_user_func_array(
96
+                        [$this->backends[$prefix], 'groupExists'],
97
+                        [$gid]
98
+                    );
99
+                    if (!$groupExists) {
100
+                        $this->writeToCache($cacheKey, null);
101
+                    }
102
+                }
103
+                return $result;
104
+            }
105
+        }
106
+        return false;
107
+    }
108 108
 
109
-	protected function activeBackends(): int {
110
-		return count($this->backends);
111
-	}
109
+    protected function activeBackends(): int {
110
+        return count($this->backends);
111
+    }
112 112
 
113
-	/**
114
-	 * is user in group?
115
-	 *
116
-	 * @param string $uid uid of the user
117
-	 * @param string $gid gid of the group
118
-	 * @return bool
119
-	 *
120
-	 * Checks whether the user is member of a group or not.
121
-	 */
122
-	public function inGroup($uid, $gid) {
123
-		return $this->handleRequest($gid, 'inGroup', [$uid, $gid]);
124
-	}
113
+    /**
114
+     * is user in group?
115
+     *
116
+     * @param string $uid uid of the user
117
+     * @param string $gid gid of the group
118
+     * @return bool
119
+     *
120
+     * Checks whether the user is member of a group or not.
121
+     */
122
+    public function inGroup($uid, $gid) {
123
+        return $this->handleRequest($gid, 'inGroup', [$uid, $gid]);
124
+    }
125 125
 
126
-	/**
127
-	 * Get all groups a user belongs to
128
-	 *
129
-	 * @param string $uid Name of the user
130
-	 * @return string[] with group names
131
-	 *
132
-	 * This function fetches all groups a user belongs to. It does not check
133
-	 * if the user exists at all.
134
-	 */
135
-	public function getUserGroups($uid) {
136
-		$groups = [];
126
+    /**
127
+     * Get all groups a user belongs to
128
+     *
129
+     * @param string $uid Name of the user
130
+     * @return string[] with group names
131
+     *
132
+     * This function fetches all groups a user belongs to. It does not check
133
+     * if the user exists at all.
134
+     */
135
+    public function getUserGroups($uid) {
136
+        $groups = [];
137 137
 
138
-		foreach ($this->backends as $backend) {
139
-			$backendGroups = $backend->getUserGroups($uid);
140
-			if (is_array($backendGroups)) {
141
-				$groups = array_merge($groups, $backendGroups);
142
-			}
143
-		}
138
+        foreach ($this->backends as $backend) {
139
+            $backendGroups = $backend->getUserGroups($uid);
140
+            if (is_array($backendGroups)) {
141
+                $groups = array_merge($groups, $backendGroups);
142
+            }
143
+        }
144 144
 
145
-		return $groups;
146
-	}
145
+        return $groups;
146
+    }
147 147
 
148
-	/**
149
-	 * get a list of all users in a group
150
-	 *
151
-	 * @return string[] with user ids
152
-	 */
153
-	public function usersInGroup($gid, $search = '', $limit = -1, $offset = 0) {
154
-		$users = [];
148
+    /**
149
+     * get a list of all users in a group
150
+     *
151
+     * @return string[] with user ids
152
+     */
153
+    public function usersInGroup($gid, $search = '', $limit = -1, $offset = 0) {
154
+        $users = [];
155 155
 
156
-		foreach ($this->backends as $backend) {
157
-			$backendUsers = $backend->usersInGroup($gid, $search, $limit, $offset);
158
-			if (is_array($backendUsers)) {
159
-				$users = array_merge($users, $backendUsers);
160
-			}
161
-		}
156
+        foreach ($this->backends as $backend) {
157
+            $backendUsers = $backend->usersInGroup($gid, $search, $limit, $offset);
158
+            if (is_array($backendUsers)) {
159
+                $users = array_merge($users, $backendUsers);
160
+            }
161
+        }
162 162
 
163
-		return $users;
164
-	}
163
+        return $users;
164
+    }
165 165
 
166
-	/**
167
-	 * @param string $gid
168
-	 * @return bool
169
-	 */
170
-	public function createGroup($gid) {
171
-		return $this->handleRequest(
172
-			$gid, 'createGroup', [$gid]);
173
-	}
166
+    /**
167
+     * @param string $gid
168
+     * @return bool
169
+     */
170
+    public function createGroup($gid) {
171
+        return $this->handleRequest(
172
+            $gid, 'createGroup', [$gid]);
173
+    }
174 174
 
175
-	/**
176
-	 * delete a group
177
-	 *
178
-	 * @param string $gid gid of the group to delete
179
-	 * @return bool
180
-	 */
181
-	public function deleteGroup($gid) {
182
-		return $this->handleRequest(
183
-			$gid, 'deleteGroup', [$gid]);
184
-	}
175
+    /**
176
+     * delete a group
177
+     *
178
+     * @param string $gid gid of the group to delete
179
+     * @return bool
180
+     */
181
+    public function deleteGroup($gid) {
182
+        return $this->handleRequest(
183
+            $gid, 'deleteGroup', [$gid]);
184
+    }
185 185
 
186
-	/**
187
-	 * Add a user to a group
188
-	 *
189
-	 * @param string $uid Name of the user to add to group
190
-	 * @param string $gid Name of the group in which add the user
191
-	 * @return bool
192
-	 *
193
-	 * Adds a user to a group.
194
-	 */
195
-	public function addToGroup($uid, $gid) {
196
-		return $this->handleRequest(
197
-			$gid, 'addToGroup', [$uid, $gid]);
198
-	}
186
+    /**
187
+     * Add a user to a group
188
+     *
189
+     * @param string $uid Name of the user to add to group
190
+     * @param string $gid Name of the group in which add the user
191
+     * @return bool
192
+     *
193
+     * Adds a user to a group.
194
+     */
195
+    public function addToGroup($uid, $gid) {
196
+        return $this->handleRequest(
197
+            $gid, 'addToGroup', [$uid, $gid]);
198
+    }
199 199
 
200
-	/**
201
-	 * Removes a user from a group
202
-	 *
203
-	 * @param string $uid Name of the user to remove from group
204
-	 * @param string $gid Name of the group from which remove the user
205
-	 * @return bool
206
-	 *
207
-	 * removes the user from a group.
208
-	 */
209
-	public function removeFromGroup($uid, $gid) {
210
-		return $this->handleRequest(
211
-			$gid, 'removeFromGroup', [$uid, $gid]);
212
-	}
200
+    /**
201
+     * Removes a user from a group
202
+     *
203
+     * @param string $uid Name of the user to remove from group
204
+     * @param string $gid Name of the group from which remove the user
205
+     * @return bool
206
+     *
207
+     * removes the user from a group.
208
+     */
209
+    public function removeFromGroup($uid, $gid) {
210
+        return $this->handleRequest(
211
+            $gid, 'removeFromGroup', [$uid, $gid]);
212
+    }
213 213
 
214
-	/**
215
-	 * returns the number of users in a group, who match the search term
216
-	 *
217
-	 * @param string $gid the internal group name
218
-	 * @param string $search optional, a search string
219
-	 * @return int|bool
220
-	 */
221
-	public function countUsersInGroup($gid, $search = '') {
222
-		return $this->handleRequest(
223
-			$gid, 'countUsersInGroup', [$gid, $search]);
224
-	}
214
+    /**
215
+     * returns the number of users in a group, who match the search term
216
+     *
217
+     * @param string $gid the internal group name
218
+     * @param string $search optional, a search string
219
+     * @return int|bool
220
+     */
221
+    public function countUsersInGroup($gid, $search = '') {
222
+        return $this->handleRequest(
223
+            $gid, 'countUsersInGroup', [$gid, $search]);
224
+    }
225 225
 
226
-	/**
227
-	 * get an array with group details
228
-	 *
229
-	 * @param string $gid
230
-	 * @return array|false
231
-	 */
232
-	public function getGroupDetails($gid) {
233
-		return $this->handleRequest(
234
-			$gid, 'getGroupDetails', [$gid]);
235
-	}
226
+    /**
227
+     * get an array with group details
228
+     *
229
+     * @param string $gid
230
+     * @return array|false
231
+     */
232
+    public function getGroupDetails($gid) {
233
+        return $this->handleRequest(
234
+            $gid, 'getGroupDetails', [$gid]);
235
+    }
236 236
 
237
-	/**
238
-	 * get a list of all groups
239
-	 *
240
-	 * @return string[] with group names
241
-	 *
242
-	 * Returns a list with all groups
243
-	 */
244
-	public function getGroups($search = '', $limit = -1, $offset = 0) {
245
-		$groups = [];
237
+    /**
238
+     * get a list of all groups
239
+     *
240
+     * @return string[] with group names
241
+     *
242
+     * Returns a list with all groups
243
+     */
244
+    public function getGroups($search = '', $limit = -1, $offset = 0) {
245
+        $groups = [];
246 246
 
247
-		foreach ($this->backends as $backend) {
248
-			$backendGroups = $backend->getGroups($search, $limit, $offset);
249
-			if (is_array($backendGroups)) {
250
-				$groups = array_merge($groups, $backendGroups);
251
-			}
252
-		}
247
+        foreach ($this->backends as $backend) {
248
+            $backendGroups = $backend->getGroups($search, $limit, $offset);
249
+            if (is_array($backendGroups)) {
250
+                $groups = array_merge($groups, $backendGroups);
251
+            }
252
+        }
253 253
 
254
-		return $groups;
255
-	}
254
+        return $groups;
255
+    }
256 256
 
257
-	/**
258
-	 * check if a group exists
259
-	 *
260
-	 * @param string $gid
261
-	 * @return bool
262
-	 */
263
-	public function groupExists($gid) {
264
-		return $this->handleRequest($gid, 'groupExists', [$gid]);
265
-	}
257
+    /**
258
+     * check if a group exists
259
+     *
260
+     * @param string $gid
261
+     * @return bool
262
+     */
263
+    public function groupExists($gid) {
264
+        return $this->handleRequest($gid, 'groupExists', [$gid]);
265
+    }
266 266
 
267
-	/**
268
-	 * Check if backend implements actions
269
-	 *
270
-	 * @param int $actions bitwise-or'ed actions
271
-	 * @return boolean
272
-	 *
273
-	 * Returns the supported actions as int to be
274
-	 * compared with \OCP\GroupInterface::CREATE_GROUP etc.
275
-	 */
276
-	public function implementsActions($actions) {
277
-		//it's the same across all our user backends obviously
278
-		return $this->refBackend->implementsActions($actions);
279
-	}
267
+    /**
268
+     * Check if backend implements actions
269
+     *
270
+     * @param int $actions bitwise-or'ed actions
271
+     * @return boolean
272
+     *
273
+     * Returns the supported actions as int to be
274
+     * compared with \OCP\GroupInterface::CREATE_GROUP etc.
275
+     */
276
+    public function implementsActions($actions) {
277
+        //it's the same across all our user backends obviously
278
+        return $this->refBackend->implementsActions($actions);
279
+    }
280 280
 
281
-	/**
282
-	 * Return access for LDAP interaction.
283
-	 *
284
-	 * @param string $gid
285
-	 * @return Access instance of Access for LDAP interaction
286
-	 */
287
-	public function getLDAPAccess($gid) {
288
-		return $this->handleRequest($gid, 'getLDAPAccess', [$gid]);
289
-	}
281
+    /**
282
+     * Return access for LDAP interaction.
283
+     *
284
+     * @param string $gid
285
+     * @return Access instance of Access for LDAP interaction
286
+     */
287
+    public function getLDAPAccess($gid) {
288
+        return $this->handleRequest($gid, 'getLDAPAccess', [$gid]);
289
+    }
290 290
 
291
-	/**
292
-	 * Return a new LDAP connection for the specified group.
293
-	 * The connection needs to be closed manually.
294
-	 *
295
-	 * @param string $gid
296
-	 * @return resource of the LDAP connection
297
-	 */
298
-	public function getNewLDAPConnection($gid) {
299
-		return $this->handleRequest($gid, 'getNewLDAPConnection', [$gid]);
300
-	}
291
+    /**
292
+     * Return a new LDAP connection for the specified group.
293
+     * The connection needs to be closed manually.
294
+     *
295
+     * @param string $gid
296
+     * @return resource of the LDAP connection
297
+     */
298
+    public function getNewLDAPConnection($gid) {
299
+        return $this->handleRequest($gid, 'getNewLDAPConnection', [$gid]);
300
+    }
301 301
 
302
-	public function getDisplayName(string $gid): string {
303
-		return $this->handleRequest($gid, 'getDisplayName', [$gid]);
304
-	}
302
+    public function getDisplayName(string $gid): string {
303
+        return $this->handleRequest($gid, 'getDisplayName', [$gid]);
304
+    }
305 305
 }
Please login to merge, or discard this patch.
apps/files_external/lib/Migration/DummyUserSession.php 1 patch
Indentation   +34 added lines, -34 removed lines patch added patch discarded remove patch
@@ -29,45 +29,45 @@
 block discarded – undo
29 29
 
30 30
 class DummyUserSession implements IUserSession {
31 31
 
32
-	/**
33
-	 * @var IUser
34
-	 */
35
-	private $user;
32
+    /**
33
+     * @var IUser
34
+     */
35
+    private $user;
36 36
 
37
-	public function login($uid, $password) {
38
-	}
37
+    public function login($uid, $password) {
38
+    }
39 39
 
40
-	public function logout() {
41
-	}
40
+    public function logout() {
41
+    }
42 42
 
43
-	public function setUser($user) {
44
-		$this->user = $user;
45
-	}
43
+    public function setUser($user) {
44
+        $this->user = $user;
45
+    }
46 46
 
47
-	public function getUser() {
48
-		return $this->user;
49
-	}
47
+    public function getUser() {
48
+        return $this->user;
49
+    }
50 50
 
51
-	public function isLoggedIn() {
52
-		return !is_null($this->user);
53
-	}
51
+    public function isLoggedIn() {
52
+        return !is_null($this->user);
53
+    }
54 54
 
55
-	/**
56
-	 * get getImpersonatingUserID
57
-	 *
58
-	 * @return string|null
59
-	 * @since 17.0.0
60
-	 */
61
-	public function getImpersonatingUserID() : ?string {
62
-		return null;
63
-	}
55
+    /**
56
+     * get getImpersonatingUserID
57
+     *
58
+     * @return string|null
59
+     * @since 17.0.0
60
+     */
61
+    public function getImpersonatingUserID() : ?string {
62
+        return null;
63
+    }
64 64
 
65
-	/**
66
-	 * set setImpersonatingUserID
67
-	 *
68
-	 * @since 17.0.0
69
-	 */
70
-	public function setImpersonatingUserID(bool $useCurrentUser = true): void {
71
-		//no OP
72
-	}
65
+    /**
66
+     * set setImpersonatingUserID
67
+     *
68
+     * @since 17.0.0
69
+     */
70
+    public function setImpersonatingUserID(bool $useCurrentUser = true): void {
71
+        //no OP
72
+    }
73 73
 }
Please login to merge, or discard this patch.
apps/files_external/lib/Lib/Storage/SMB.php 1 patch
Indentation   +651 added lines, -651 removed lines patch added patch discarded remove patch
@@ -65,655 +65,655 @@
 block discarded – undo
65 65
 use OCP\ILogger;
66 66
 
67 67
 class SMB extends Common implements INotifyStorage {
68
-	/**
69
-	 * @var \Icewind\SMB\IServer
70
-	 */
71
-	protected $server;
72
-
73
-	/**
74
-	 * @var \Icewind\SMB\IShare
75
-	 */
76
-	protected $share;
77
-
78
-	/**
79
-	 * @var string
80
-	 */
81
-	protected $root;
82
-
83
-	/**
84
-	 * @var \Icewind\SMB\IFileInfo[]
85
-	 */
86
-	protected $statCache;
87
-
88
-	/** @var ILogger */
89
-	protected $logger;
90
-
91
-	/** @var bool */
92
-	protected $showHidden;
93
-
94
-	/** @var bool */
95
-	protected $checkAcl;
96
-
97
-	public function __construct($params) {
98
-		if (!isset($params['host'])) {
99
-			throw new \Exception('Invalid configuration, no host provided');
100
-		}
101
-
102
-		if (isset($params['auth'])) {
103
-			$auth = $params['auth'];
104
-		} elseif (isset($params['user']) && isset($params['password']) && isset($params['share'])) {
105
-			[$workgroup, $user] = $this->splitUser($params['user']);
106
-			$auth = new BasicAuth($user, $workgroup, $params['password']);
107
-		} else {
108
-			throw new \Exception('Invalid configuration, no credentials provided');
109
-		}
110
-
111
-		if (isset($params['logger'])) {
112
-			$this->logger = $params['logger'];
113
-		} else {
114
-			$this->logger = \OC::$server->getLogger();
115
-		}
116
-
117
-		$options = new Options();
118
-		if (isset($params['timeout'])) {
119
-			$timeout = (int)$params['timeout'];
120
-			if ($timeout > 0) {
121
-				$options->setTimeout($timeout);
122
-			}
123
-		}
124
-		$serverFactory = new ServerFactory($options);
125
-		$this->server = $serverFactory->createServer($params['host'], $auth);
126
-		$this->share = $this->server->getShare(trim($params['share'], '/'));
127
-
128
-		$this->root = $params['root'] ?? '/';
129
-		$this->root = '/' . ltrim($this->root, '/');
130
-		$this->root = rtrim($this->root, '/') . '/';
131
-
132
-		$this->showHidden = isset($params['show_hidden']) && $params['show_hidden'];
133
-		$this->checkAcl = isset($params['check_acl']) && $params['check_acl'];
134
-
135
-		$this->statCache = new CappedMemoryCache();
136
-		parent::__construct($params);
137
-	}
138
-
139
-	private function splitUser($user) {
140
-		if (strpos($user, '/')) {
141
-			return explode('/', $user, 2);
142
-		} elseif (strpos($user, '\\')) {
143
-			return explode('\\', $user);
144
-		} else {
145
-			return [null, $user];
146
-		}
147
-	}
148
-
149
-	/**
150
-	 * @return string
151
-	 */
152
-	public function getId() {
153
-		// FIXME: double slash to keep compatible with the old storage ids,
154
-		// failure to do so will lead to creation of a new storage id and
155
-		// loss of shares from the storage
156
-		return 'smb::' . $this->server->getAuth()->getUsername() . '@' . $this->server->getHost() . '//' . $this->share->getName() . '/' . $this->root;
157
-	}
158
-
159
-	/**
160
-	 * @param string $path
161
-	 * @return string
162
-	 */
163
-	protected function buildPath($path) {
164
-		return Filesystem::normalizePath($this->root . '/' . $path, true, false, true);
165
-	}
166
-
167
-	protected function relativePath($fullPath) {
168
-		if ($fullPath === $this->root) {
169
-			return '';
170
-		} elseif (substr($fullPath, 0, strlen($this->root)) === $this->root) {
171
-			return substr($fullPath, strlen($this->root));
172
-		} else {
173
-			return null;
174
-		}
175
-	}
176
-
177
-	/**
178
-	 * @param string $path
179
-	 * @return \Icewind\SMB\IFileInfo
180
-	 * @throws StorageAuthException
181
-	 */
182
-	protected function getFileInfo($path) {
183
-		try {
184
-			$path = $this->buildPath($path);
185
-			if (!isset($this->statCache[$path])) {
186
-				$this->statCache[$path] = $this->share->stat($path);
187
-			}
188
-			return $this->statCache[$path];
189
-		} catch (ConnectException $e) {
190
-			$this->throwUnavailable($e);
191
-		} catch (ForbiddenException $e) {
192
-			// with php-smbclient, this exceptions is thrown when the provided password is invalid.
193
-			// Possible is also ForbiddenException with a different error code, so we check it.
194
-			if ($e->getCode() === 1) {
195
-				$this->throwUnavailable($e);
196
-			}
197
-			throw $e;
198
-		}
199
-	}
200
-
201
-	/**
202
-	 * @param \Exception $e
203
-	 * @throws StorageAuthException
204
-	 */
205
-	protected function throwUnavailable(\Exception $e) {
206
-		$this->logger->logException($e, ['message' => 'Error while getting file info']);
207
-		throw new StorageAuthException($e->getMessage(), $e);
208
-	}
209
-
210
-	/**
211
-	 * get the acl from fileinfo that is relevant for the configured user
212
-	 *
213
-	 * @param IFileInfo $file
214
-	 * @return ACL|null
215
-	 */
216
-	private function getACL(IFileInfo $file): ?ACL {
217
-		$acls = $file->getAcls();
218
-		foreach ($acls as $user => $acl) {
219
-			[, $user] = explode('\\', $user); // strip domain
220
-			if ($user === $this->server->getAuth()->getUsername()) {
221
-				return $acl;
222
-			}
223
-		}
224
-
225
-		return null;
226
-	}
227
-
228
-	/**
229
-	 * @param string $path
230
-	 * @return \Icewind\SMB\IFileInfo[]
231
-	 * @throws StorageNotAvailableException
232
-	 */
233
-	protected function getFolderContents($path): iterable {
234
-		try {
235
-			$path = ltrim($this->buildPath($path), '/');
236
-			$files = $this->share->dir($path);
237
-			foreach ($files as $file) {
238
-				$this->statCache[$path . '/' . $file->getName()] = $file;
239
-			}
240
-
241
-			foreach ($files as $file) {
242
-				try {
243
-					// the isHidden check is done before checking the config boolean to ensure that the metadata is always fetch
244
-					// so we trigger the below exceptions where applicable
245
-					$hide = $file->isHidden() && !$this->showHidden;
246
-
247
-					if ($this->checkAcl && $acl = $this->getACL($file)) {
248
-						// if there is no explicit deny, we assume it's allowed
249
-						// this doesn't take inheritance fully into account but if read permissions is denied for a parent we wouldn't be in this folder
250
-						// additionally, it's better to have false negatives here then false positives
251
-						if ($acl->denies(ACL::MASK_READ) || $acl->denies(ACL::MASK_EXECUTE)) {
252
-							$this->logger->debug('Hiding non readable entry ' . $file->getName());
253
-							return false;
254
-						}
255
-					}
256
-
257
-					if ($hide) {
258
-						$this->logger->debug('hiding hidden file ' . $file->getName());
259
-					}
260
-					if (!$hide) {
261
-						yield $file;
262
-					}
263
-				} catch (ForbiddenException $e) {
264
-					$this->logger->logException($e, ['level' => ILogger::DEBUG, 'message' => 'Hiding forbidden entry ' . $file->getName()]);
265
-				} catch (NotFoundException $e) {
266
-					$this->logger->logException($e, ['level' => ILogger::DEBUG, 'message' => 'Hiding not found entry ' . $file->getName()]);
267
-				}
268
-			}
269
-		} catch (ConnectException $e) {
270
-			$this->logger->logException($e, ['message' => 'Error while getting folder content']);
271
-			throw new StorageNotAvailableException($e->getMessage(), $e->getCode(), $e);
272
-		}
273
-	}
274
-
275
-	/**
276
-	 * @param \Icewind\SMB\IFileInfo $info
277
-	 * @return array
278
-	 */
279
-	protected function formatInfo($info) {
280
-		$result = [
281
-			'size' => $info->getSize(),
282
-			'mtime' => $info->getMTime(),
283
-		];
284
-		if ($info->isDirectory()) {
285
-			$result['type'] = 'dir';
286
-		} else {
287
-			$result['type'] = 'file';
288
-		}
289
-		return $result;
290
-	}
291
-
292
-	/**
293
-	 * Rename the files. If the source or the target is the root, the rename won't happen.
294
-	 *
295
-	 * @param string $source the old name of the path
296
-	 * @param string $target the new name of the path
297
-	 * @return bool true if the rename is successful, false otherwise
298
-	 */
299
-	public function rename($source, $target, $retry = true) {
300
-		if ($this->isRootDir($source) || $this->isRootDir($target)) {
301
-			return false;
302
-		}
303
-
304
-		$absoluteSource = $this->buildPath($source);
305
-		$absoluteTarget = $this->buildPath($target);
306
-		try {
307
-			$result = $this->share->rename($absoluteSource, $absoluteTarget);
308
-		} catch (AlreadyExistsException $e) {
309
-			if ($retry) {
310
-				$this->remove($target);
311
-				$result = $this->share->rename($absoluteSource, $absoluteTarget, false);
312
-			} else {
313
-				$this->logger->logException($e, ['level' => ILogger::WARN]);
314
-				return false;
315
-			}
316
-		} catch (InvalidArgumentException $e) {
317
-			if ($retry) {
318
-				$this->remove($target);
319
-				$result = $this->share->rename($absoluteSource, $absoluteTarget, false);
320
-			} else {
321
-				$this->logger->logException($e, ['level' => ILogger::WARN]);
322
-				return false;
323
-			}
324
-		} catch (\Exception $e) {
325
-			$this->logger->logException($e, ['level' => ILogger::WARN]);
326
-			return false;
327
-		}
328
-		unset($this->statCache[$absoluteSource], $this->statCache[$absoluteTarget]);
329
-		return $result;
330
-	}
331
-
332
-	public function stat($path, $retry = true) {
333
-		try {
334
-			$result = $this->formatInfo($this->getFileInfo($path));
335
-		} catch (ForbiddenException $e) {
336
-			return false;
337
-		} catch (NotFoundException $e) {
338
-			return false;
339
-		} catch (TimedOutException $e) {
340
-			if ($retry) {
341
-				return $this->stat($path, false);
342
-			} else {
343
-				throw $e;
344
-			}
345
-		}
346
-		if ($this->remoteIsShare() && $this->isRootDir($path)) {
347
-			$result['mtime'] = $this->shareMTime();
348
-		}
349
-		return $result;
350
-	}
351
-
352
-	/**
353
-	 * get the best guess for the modification time of the share
354
-	 *
355
-	 * @return int
356
-	 */
357
-	private function shareMTime() {
358
-		$highestMTime = 0;
359
-		$files = $this->share->dir($this->root);
360
-		foreach ($files as $fileInfo) {
361
-			try {
362
-				if ($fileInfo->getMTime() > $highestMTime) {
363
-					$highestMTime = $fileInfo->getMTime();
364
-				}
365
-			} catch (NotFoundException $e) {
366
-				// Ignore this, can happen on unavailable DFS shares
367
-			} catch (ForbiddenException $e) {
368
-				// Ignore this too - it's a symlink
369
-			}
370
-		}
371
-		return $highestMTime;
372
-	}
373
-
374
-	/**
375
-	 * Check if the path is our root dir (not the smb one)
376
-	 *
377
-	 * @param string $path the path
378
-	 * @return bool
379
-	 */
380
-	private function isRootDir($path) {
381
-		return $path === '' || $path === '/' || $path === '.';
382
-	}
383
-
384
-	/**
385
-	 * Check if our root points to a smb share
386
-	 *
387
-	 * @return bool true if our root points to a share false otherwise
388
-	 */
389
-	private function remoteIsShare() {
390
-		return $this->share->getName() && (!$this->root || $this->root === '/');
391
-	}
392
-
393
-	/**
394
-	 * @param string $path
395
-	 * @return bool
396
-	 */
397
-	public function unlink($path) {
398
-		if ($this->isRootDir($path)) {
399
-			return false;
400
-		}
401
-
402
-		try {
403
-			if ($this->is_dir($path)) {
404
-				return $this->rmdir($path);
405
-			} else {
406
-				$path = $this->buildPath($path);
407
-				unset($this->statCache[$path]);
408
-				$this->share->del($path);
409
-				return true;
410
-			}
411
-		} catch (NotFoundException $e) {
412
-			return false;
413
-		} catch (ForbiddenException $e) {
414
-			return false;
415
-		} catch (ConnectException $e) {
416
-			$this->logger->logException($e, ['message' => 'Error while deleting file']);
417
-			throw new StorageNotAvailableException($e->getMessage(), $e->getCode(), $e);
418
-		}
419
-	}
420
-
421
-	/**
422
-	 * check if a file or folder has been updated since $time
423
-	 *
424
-	 * @param string $path
425
-	 * @param int $time
426
-	 * @return bool
427
-	 */
428
-	public function hasUpdated($path, $time) {
429
-		if (!$path and $this->root === '/') {
430
-			// mtime doesn't work for shares, but giving the nature of the backend,
431
-			// doing a full update is still just fast enough
432
-			return true;
433
-		} else {
434
-			$actualTime = $this->filemtime($path);
435
-			return $actualTime > $time;
436
-		}
437
-	}
438
-
439
-	/**
440
-	 * @param string $path
441
-	 * @param string $mode
442
-	 * @return resource|false
443
-	 */
444
-	public function fopen($path, $mode) {
445
-		$fullPath = $this->buildPath($path);
446
-		try {
447
-			switch ($mode) {
448
-				case 'r':
449
-				case 'rb':
450
-					if (!$this->file_exists($path)) {
451
-						return false;
452
-					}
453
-					return $this->share->read($fullPath);
454
-				case 'w':
455
-				case 'wb':
456
-					$source = $this->share->write($fullPath);
457
-					return CallBackWrapper::wrap($source, null, null, function () use ($fullPath) {
458
-						unset($this->statCache[$fullPath]);
459
-					});
460
-				case 'a':
461
-				case 'ab':
462
-				case 'r+':
463
-				case 'w+':
464
-				case 'wb+':
465
-				case 'a+':
466
-				case 'x':
467
-				case 'x+':
468
-				case 'c':
469
-				case 'c+':
470
-					//emulate these
471
-					if (strrpos($path, '.') !== false) {
472
-						$ext = substr($path, strrpos($path, '.'));
473
-					} else {
474
-						$ext = '';
475
-					}
476
-					if ($this->file_exists($path)) {
477
-						if (!$this->isUpdatable($path)) {
478
-							return false;
479
-						}
480
-						$tmpFile = $this->getCachedFile($path);
481
-					} else {
482
-						if (!$this->isCreatable(dirname($path))) {
483
-							return false;
484
-						}
485
-						$tmpFile = \OC::$server->getTempManager()->getTemporaryFile($ext);
486
-					}
487
-					$source = fopen($tmpFile, $mode);
488
-					$share = $this->share;
489
-					return CallbackWrapper::wrap($source, null, null, function () use ($tmpFile, $fullPath, $share) {
490
-						unset($this->statCache[$fullPath]);
491
-						$share->put($tmpFile, $fullPath);
492
-						unlink($tmpFile);
493
-					});
494
-			}
495
-			return false;
496
-		} catch (NotFoundException $e) {
497
-			return false;
498
-		} catch (ForbiddenException $e) {
499
-			return false;
500
-		} catch (ConnectException $e) {
501
-			$this->logger->logException($e, ['message' => 'Error while opening file']);
502
-			throw new StorageNotAvailableException($e->getMessage(), $e->getCode(), $e);
503
-		}
504
-	}
505
-
506
-	public function rmdir($path) {
507
-		if ($this->isRootDir($path)) {
508
-			return false;
509
-		}
510
-
511
-		try {
512
-			$this->statCache = [];
513
-			$content = $this->share->dir($this->buildPath($path));
514
-			foreach ($content as $file) {
515
-				if ($file->isDirectory()) {
516
-					$this->rmdir($path . '/' . $file->getName());
517
-				} else {
518
-					$this->share->del($file->getPath());
519
-				}
520
-			}
521
-			$this->share->rmdir($this->buildPath($path));
522
-			return true;
523
-		} catch (NotFoundException $e) {
524
-			return false;
525
-		} catch (ForbiddenException $e) {
526
-			return false;
527
-		} catch (ConnectException $e) {
528
-			$this->logger->logException($e, ['message' => 'Error while removing folder']);
529
-			throw new StorageNotAvailableException($e->getMessage(), $e->getCode(), $e);
530
-		}
531
-	}
532
-
533
-	public function touch($path, $mtime = null) {
534
-		try {
535
-			if (!$this->file_exists($path)) {
536
-				$fh = $this->share->write($this->buildPath($path));
537
-				fclose($fh);
538
-				return true;
539
-			}
540
-			return false;
541
-		} catch (ConnectException $e) {
542
-			$this->logger->logException($e, ['message' => 'Error while creating file']);
543
-			throw new StorageNotAvailableException($e->getMessage(), $e->getCode(), $e);
544
-		}
545
-	}
546
-
547
-	public function getMetaData($path) {
548
-		$fileInfo = $this->getFileInfo($path);
549
-		if (!$fileInfo) {
550
-			return null;
551
-		}
552
-
553
-		return $this->getMetaDataFromFileInfo($fileInfo);
554
-	}
555
-
556
-	private function getMetaDataFromFileInfo(IFileInfo $fileInfo) {
557
-		$permissions = Constants::PERMISSION_READ + Constants::PERMISSION_SHARE;
558
-
559
-		if (!$fileInfo->isReadOnly()) {
560
-			$permissions += Constants::PERMISSION_DELETE;
561
-			$permissions += Constants::PERMISSION_UPDATE;
562
-			if ($fileInfo->isDirectory()) {
563
-				$permissions += Constants::PERMISSION_CREATE;
564
-			}
565
-		}
566
-
567
-		$data = [];
568
-		if ($fileInfo->isDirectory()) {
569
-			$data['mimetype'] = 'httpd/unix-directory';
570
-		} else {
571
-			$data['mimetype'] = \OC::$server->getMimeTypeDetector()->detectPath($fileInfo->getPath());
572
-		}
573
-		$data['mtime'] = $fileInfo->getMTime();
574
-		if ($fileInfo->isDirectory()) {
575
-			$data['size'] = -1; //unknown
576
-		} else {
577
-			$data['size'] = $fileInfo->getSize();
578
-		}
579
-		$data['etag'] = $this->getETag($fileInfo->getPath());
580
-		$data['storage_mtime'] = $data['mtime'];
581
-		$data['permissions'] = $permissions;
582
-		$data['name'] = $fileInfo->getName();
583
-
584
-		return $data;
585
-	}
586
-
587
-	public function opendir($path) {
588
-		try {
589
-			$files = $this->getFolderContents($path);
590
-		} catch (NotFoundException $e) {
591
-			return false;
592
-		} catch (ForbiddenException $e) {
593
-			return false;
594
-		}
595
-		$names = array_map(function ($info) {
596
-			/** @var \Icewind\SMB\IFileInfo $info */
597
-			return $info->getName();
598
-		}, iterator_to_array($files));
599
-		return IteratorDirectory::wrap($names);
600
-	}
601
-
602
-	public function getDirectoryContent($directory): \Traversable {
603
-		$files = $this->getFolderContents($directory);
604
-		foreach ($files as $file) {
605
-			yield $this->getMetaDataFromFileInfo($file);
606
-		}
607
-	}
608
-
609
-	public function filetype($path) {
610
-		try {
611
-			return $this->getFileInfo($path)->isDirectory() ? 'dir' : 'file';
612
-		} catch (NotFoundException $e) {
613
-			return false;
614
-		} catch (ForbiddenException $e) {
615
-			return false;
616
-		}
617
-	}
618
-
619
-	public function mkdir($path) {
620
-		$path = $this->buildPath($path);
621
-		try {
622
-			$this->share->mkdir($path);
623
-			return true;
624
-		} catch (ConnectException $e) {
625
-			$this->logger->logException($e, ['message' => 'Error while creating folder']);
626
-			throw new StorageNotAvailableException($e->getMessage(), $e->getCode(), $e);
627
-		} catch (Exception $e) {
628
-			return false;
629
-		}
630
-	}
631
-
632
-	public function file_exists($path) {
633
-		try {
634
-			$this->getFileInfo($path);
635
-			return true;
636
-		} catch (NotFoundException $e) {
637
-			return false;
638
-		} catch (ForbiddenException $e) {
639
-			return false;
640
-		} catch (ConnectException $e) {
641
-			throw new StorageNotAvailableException($e->getMessage(), $e->getCode(), $e);
642
-		}
643
-	}
644
-
645
-	public function isReadable($path) {
646
-		try {
647
-			$info = $this->getFileInfo($path);
648
-			return $this->showHidden || !$info->isHidden();
649
-		} catch (NotFoundException $e) {
650
-			return false;
651
-		} catch (ForbiddenException $e) {
652
-			return false;
653
-		}
654
-	}
655
-
656
-	public function isUpdatable($path) {
657
-		try {
658
-			$info = $this->getFileInfo($path);
659
-			// following windows behaviour for read-only folders: they can be written into
660
-			// (https://support.microsoft.com/en-us/kb/326549 - "cause" section)
661
-			return ($this->showHidden || !$info->isHidden()) && (!$info->isReadOnly() || $this->is_dir($path));
662
-		} catch (NotFoundException $e) {
663
-			return false;
664
-		} catch (ForbiddenException $e) {
665
-			return false;
666
-		}
667
-	}
668
-
669
-	public function isDeletable($path) {
670
-		try {
671
-			$info = $this->getFileInfo($path);
672
-			return ($this->showHidden || !$info->isHidden()) && !$info->isReadOnly();
673
-		} catch (NotFoundException $e) {
674
-			return false;
675
-		} catch (ForbiddenException $e) {
676
-			return false;
677
-		}
678
-	}
679
-
680
-	/**
681
-	 * check if smbclient is installed
682
-	 */
683
-	public static function checkDependencies() {
684
-		return (
685
-			(bool)\OC_Helper::findBinaryPath('smbclient')
686
-			|| NativeServer::available(new System())
687
-		) ? true : ['smbclient'];
688
-	}
689
-
690
-	/**
691
-	 * Test a storage for availability
692
-	 *
693
-	 * @return bool
694
-	 */
695
-	public function test() {
696
-		try {
697
-			return parent::test();
698
-		} catch (Exception $e) {
699
-			$this->logger->logException($e);
700
-			return false;
701
-		}
702
-	}
703
-
704
-	public function listen($path, callable $callback) {
705
-		$this->notify($path)->listen(function (IChange $change) use ($callback) {
706
-			if ($change instanceof IRenameChange) {
707
-				return $callback($change->getType(), $change->getPath(), $change->getTargetPath());
708
-			} else {
709
-				return $callback($change->getType(), $change->getPath());
710
-			}
711
-		});
712
-	}
713
-
714
-	public function notify($path) {
715
-		$path = '/' . ltrim($path, '/');
716
-		$shareNotifyHandler = $this->share->notify($this->buildPath($path));
717
-		return new SMBNotifyHandler($shareNotifyHandler, $this->root);
718
-	}
68
+    /**
69
+     * @var \Icewind\SMB\IServer
70
+     */
71
+    protected $server;
72
+
73
+    /**
74
+     * @var \Icewind\SMB\IShare
75
+     */
76
+    protected $share;
77
+
78
+    /**
79
+     * @var string
80
+     */
81
+    protected $root;
82
+
83
+    /**
84
+     * @var \Icewind\SMB\IFileInfo[]
85
+     */
86
+    protected $statCache;
87
+
88
+    /** @var ILogger */
89
+    protected $logger;
90
+
91
+    /** @var bool */
92
+    protected $showHidden;
93
+
94
+    /** @var bool */
95
+    protected $checkAcl;
96
+
97
+    public function __construct($params) {
98
+        if (!isset($params['host'])) {
99
+            throw new \Exception('Invalid configuration, no host provided');
100
+        }
101
+
102
+        if (isset($params['auth'])) {
103
+            $auth = $params['auth'];
104
+        } elseif (isset($params['user']) && isset($params['password']) && isset($params['share'])) {
105
+            [$workgroup, $user] = $this->splitUser($params['user']);
106
+            $auth = new BasicAuth($user, $workgroup, $params['password']);
107
+        } else {
108
+            throw new \Exception('Invalid configuration, no credentials provided');
109
+        }
110
+
111
+        if (isset($params['logger'])) {
112
+            $this->logger = $params['logger'];
113
+        } else {
114
+            $this->logger = \OC::$server->getLogger();
115
+        }
116
+
117
+        $options = new Options();
118
+        if (isset($params['timeout'])) {
119
+            $timeout = (int)$params['timeout'];
120
+            if ($timeout > 0) {
121
+                $options->setTimeout($timeout);
122
+            }
123
+        }
124
+        $serverFactory = new ServerFactory($options);
125
+        $this->server = $serverFactory->createServer($params['host'], $auth);
126
+        $this->share = $this->server->getShare(trim($params['share'], '/'));
127
+
128
+        $this->root = $params['root'] ?? '/';
129
+        $this->root = '/' . ltrim($this->root, '/');
130
+        $this->root = rtrim($this->root, '/') . '/';
131
+
132
+        $this->showHidden = isset($params['show_hidden']) && $params['show_hidden'];
133
+        $this->checkAcl = isset($params['check_acl']) && $params['check_acl'];
134
+
135
+        $this->statCache = new CappedMemoryCache();
136
+        parent::__construct($params);
137
+    }
138
+
139
+    private function splitUser($user) {
140
+        if (strpos($user, '/')) {
141
+            return explode('/', $user, 2);
142
+        } elseif (strpos($user, '\\')) {
143
+            return explode('\\', $user);
144
+        } else {
145
+            return [null, $user];
146
+        }
147
+    }
148
+
149
+    /**
150
+     * @return string
151
+     */
152
+    public function getId() {
153
+        // FIXME: double slash to keep compatible with the old storage ids,
154
+        // failure to do so will lead to creation of a new storage id and
155
+        // loss of shares from the storage
156
+        return 'smb::' . $this->server->getAuth()->getUsername() . '@' . $this->server->getHost() . '//' . $this->share->getName() . '/' . $this->root;
157
+    }
158
+
159
+    /**
160
+     * @param string $path
161
+     * @return string
162
+     */
163
+    protected function buildPath($path) {
164
+        return Filesystem::normalizePath($this->root . '/' . $path, true, false, true);
165
+    }
166
+
167
+    protected function relativePath($fullPath) {
168
+        if ($fullPath === $this->root) {
169
+            return '';
170
+        } elseif (substr($fullPath, 0, strlen($this->root)) === $this->root) {
171
+            return substr($fullPath, strlen($this->root));
172
+        } else {
173
+            return null;
174
+        }
175
+    }
176
+
177
+    /**
178
+     * @param string $path
179
+     * @return \Icewind\SMB\IFileInfo
180
+     * @throws StorageAuthException
181
+     */
182
+    protected function getFileInfo($path) {
183
+        try {
184
+            $path = $this->buildPath($path);
185
+            if (!isset($this->statCache[$path])) {
186
+                $this->statCache[$path] = $this->share->stat($path);
187
+            }
188
+            return $this->statCache[$path];
189
+        } catch (ConnectException $e) {
190
+            $this->throwUnavailable($e);
191
+        } catch (ForbiddenException $e) {
192
+            // with php-smbclient, this exceptions is thrown when the provided password is invalid.
193
+            // Possible is also ForbiddenException with a different error code, so we check it.
194
+            if ($e->getCode() === 1) {
195
+                $this->throwUnavailable($e);
196
+            }
197
+            throw $e;
198
+        }
199
+    }
200
+
201
+    /**
202
+     * @param \Exception $e
203
+     * @throws StorageAuthException
204
+     */
205
+    protected function throwUnavailable(\Exception $e) {
206
+        $this->logger->logException($e, ['message' => 'Error while getting file info']);
207
+        throw new StorageAuthException($e->getMessage(), $e);
208
+    }
209
+
210
+    /**
211
+     * get the acl from fileinfo that is relevant for the configured user
212
+     *
213
+     * @param IFileInfo $file
214
+     * @return ACL|null
215
+     */
216
+    private function getACL(IFileInfo $file): ?ACL {
217
+        $acls = $file->getAcls();
218
+        foreach ($acls as $user => $acl) {
219
+            [, $user] = explode('\\', $user); // strip domain
220
+            if ($user === $this->server->getAuth()->getUsername()) {
221
+                return $acl;
222
+            }
223
+        }
224
+
225
+        return null;
226
+    }
227
+
228
+    /**
229
+     * @param string $path
230
+     * @return \Icewind\SMB\IFileInfo[]
231
+     * @throws StorageNotAvailableException
232
+     */
233
+    protected function getFolderContents($path): iterable {
234
+        try {
235
+            $path = ltrim($this->buildPath($path), '/');
236
+            $files = $this->share->dir($path);
237
+            foreach ($files as $file) {
238
+                $this->statCache[$path . '/' . $file->getName()] = $file;
239
+            }
240
+
241
+            foreach ($files as $file) {
242
+                try {
243
+                    // the isHidden check is done before checking the config boolean to ensure that the metadata is always fetch
244
+                    // so we trigger the below exceptions where applicable
245
+                    $hide = $file->isHidden() && !$this->showHidden;
246
+
247
+                    if ($this->checkAcl && $acl = $this->getACL($file)) {
248
+                        // if there is no explicit deny, we assume it's allowed
249
+                        // this doesn't take inheritance fully into account but if read permissions is denied for a parent we wouldn't be in this folder
250
+                        // additionally, it's better to have false negatives here then false positives
251
+                        if ($acl->denies(ACL::MASK_READ) || $acl->denies(ACL::MASK_EXECUTE)) {
252
+                            $this->logger->debug('Hiding non readable entry ' . $file->getName());
253
+                            return false;
254
+                        }
255
+                    }
256
+
257
+                    if ($hide) {
258
+                        $this->logger->debug('hiding hidden file ' . $file->getName());
259
+                    }
260
+                    if (!$hide) {
261
+                        yield $file;
262
+                    }
263
+                } catch (ForbiddenException $e) {
264
+                    $this->logger->logException($e, ['level' => ILogger::DEBUG, 'message' => 'Hiding forbidden entry ' . $file->getName()]);
265
+                } catch (NotFoundException $e) {
266
+                    $this->logger->logException($e, ['level' => ILogger::DEBUG, 'message' => 'Hiding not found entry ' . $file->getName()]);
267
+                }
268
+            }
269
+        } catch (ConnectException $e) {
270
+            $this->logger->logException($e, ['message' => 'Error while getting folder content']);
271
+            throw new StorageNotAvailableException($e->getMessage(), $e->getCode(), $e);
272
+        }
273
+    }
274
+
275
+    /**
276
+     * @param \Icewind\SMB\IFileInfo $info
277
+     * @return array
278
+     */
279
+    protected function formatInfo($info) {
280
+        $result = [
281
+            'size' => $info->getSize(),
282
+            'mtime' => $info->getMTime(),
283
+        ];
284
+        if ($info->isDirectory()) {
285
+            $result['type'] = 'dir';
286
+        } else {
287
+            $result['type'] = 'file';
288
+        }
289
+        return $result;
290
+    }
291
+
292
+    /**
293
+     * Rename the files. If the source or the target is the root, the rename won't happen.
294
+     *
295
+     * @param string $source the old name of the path
296
+     * @param string $target the new name of the path
297
+     * @return bool true if the rename is successful, false otherwise
298
+     */
299
+    public function rename($source, $target, $retry = true) {
300
+        if ($this->isRootDir($source) || $this->isRootDir($target)) {
301
+            return false;
302
+        }
303
+
304
+        $absoluteSource = $this->buildPath($source);
305
+        $absoluteTarget = $this->buildPath($target);
306
+        try {
307
+            $result = $this->share->rename($absoluteSource, $absoluteTarget);
308
+        } catch (AlreadyExistsException $e) {
309
+            if ($retry) {
310
+                $this->remove($target);
311
+                $result = $this->share->rename($absoluteSource, $absoluteTarget, false);
312
+            } else {
313
+                $this->logger->logException($e, ['level' => ILogger::WARN]);
314
+                return false;
315
+            }
316
+        } catch (InvalidArgumentException $e) {
317
+            if ($retry) {
318
+                $this->remove($target);
319
+                $result = $this->share->rename($absoluteSource, $absoluteTarget, false);
320
+            } else {
321
+                $this->logger->logException($e, ['level' => ILogger::WARN]);
322
+                return false;
323
+            }
324
+        } catch (\Exception $e) {
325
+            $this->logger->logException($e, ['level' => ILogger::WARN]);
326
+            return false;
327
+        }
328
+        unset($this->statCache[$absoluteSource], $this->statCache[$absoluteTarget]);
329
+        return $result;
330
+    }
331
+
332
+    public function stat($path, $retry = true) {
333
+        try {
334
+            $result = $this->formatInfo($this->getFileInfo($path));
335
+        } catch (ForbiddenException $e) {
336
+            return false;
337
+        } catch (NotFoundException $e) {
338
+            return false;
339
+        } catch (TimedOutException $e) {
340
+            if ($retry) {
341
+                return $this->stat($path, false);
342
+            } else {
343
+                throw $e;
344
+            }
345
+        }
346
+        if ($this->remoteIsShare() && $this->isRootDir($path)) {
347
+            $result['mtime'] = $this->shareMTime();
348
+        }
349
+        return $result;
350
+    }
351
+
352
+    /**
353
+     * get the best guess for the modification time of the share
354
+     *
355
+     * @return int
356
+     */
357
+    private function shareMTime() {
358
+        $highestMTime = 0;
359
+        $files = $this->share->dir($this->root);
360
+        foreach ($files as $fileInfo) {
361
+            try {
362
+                if ($fileInfo->getMTime() > $highestMTime) {
363
+                    $highestMTime = $fileInfo->getMTime();
364
+                }
365
+            } catch (NotFoundException $e) {
366
+                // Ignore this, can happen on unavailable DFS shares
367
+            } catch (ForbiddenException $e) {
368
+                // Ignore this too - it's a symlink
369
+            }
370
+        }
371
+        return $highestMTime;
372
+    }
373
+
374
+    /**
375
+     * Check if the path is our root dir (not the smb one)
376
+     *
377
+     * @param string $path the path
378
+     * @return bool
379
+     */
380
+    private function isRootDir($path) {
381
+        return $path === '' || $path === '/' || $path === '.';
382
+    }
383
+
384
+    /**
385
+     * Check if our root points to a smb share
386
+     *
387
+     * @return bool true if our root points to a share false otherwise
388
+     */
389
+    private function remoteIsShare() {
390
+        return $this->share->getName() && (!$this->root || $this->root === '/');
391
+    }
392
+
393
+    /**
394
+     * @param string $path
395
+     * @return bool
396
+     */
397
+    public function unlink($path) {
398
+        if ($this->isRootDir($path)) {
399
+            return false;
400
+        }
401
+
402
+        try {
403
+            if ($this->is_dir($path)) {
404
+                return $this->rmdir($path);
405
+            } else {
406
+                $path = $this->buildPath($path);
407
+                unset($this->statCache[$path]);
408
+                $this->share->del($path);
409
+                return true;
410
+            }
411
+        } catch (NotFoundException $e) {
412
+            return false;
413
+        } catch (ForbiddenException $e) {
414
+            return false;
415
+        } catch (ConnectException $e) {
416
+            $this->logger->logException($e, ['message' => 'Error while deleting file']);
417
+            throw new StorageNotAvailableException($e->getMessage(), $e->getCode(), $e);
418
+        }
419
+    }
420
+
421
+    /**
422
+     * check if a file or folder has been updated since $time
423
+     *
424
+     * @param string $path
425
+     * @param int $time
426
+     * @return bool
427
+     */
428
+    public function hasUpdated($path, $time) {
429
+        if (!$path and $this->root === '/') {
430
+            // mtime doesn't work for shares, but giving the nature of the backend,
431
+            // doing a full update is still just fast enough
432
+            return true;
433
+        } else {
434
+            $actualTime = $this->filemtime($path);
435
+            return $actualTime > $time;
436
+        }
437
+    }
438
+
439
+    /**
440
+     * @param string $path
441
+     * @param string $mode
442
+     * @return resource|false
443
+     */
444
+    public function fopen($path, $mode) {
445
+        $fullPath = $this->buildPath($path);
446
+        try {
447
+            switch ($mode) {
448
+                case 'r':
449
+                case 'rb':
450
+                    if (!$this->file_exists($path)) {
451
+                        return false;
452
+                    }
453
+                    return $this->share->read($fullPath);
454
+                case 'w':
455
+                case 'wb':
456
+                    $source = $this->share->write($fullPath);
457
+                    return CallBackWrapper::wrap($source, null, null, function () use ($fullPath) {
458
+                        unset($this->statCache[$fullPath]);
459
+                    });
460
+                case 'a':
461
+                case 'ab':
462
+                case 'r+':
463
+                case 'w+':
464
+                case 'wb+':
465
+                case 'a+':
466
+                case 'x':
467
+                case 'x+':
468
+                case 'c':
469
+                case 'c+':
470
+                    //emulate these
471
+                    if (strrpos($path, '.') !== false) {
472
+                        $ext = substr($path, strrpos($path, '.'));
473
+                    } else {
474
+                        $ext = '';
475
+                    }
476
+                    if ($this->file_exists($path)) {
477
+                        if (!$this->isUpdatable($path)) {
478
+                            return false;
479
+                        }
480
+                        $tmpFile = $this->getCachedFile($path);
481
+                    } else {
482
+                        if (!$this->isCreatable(dirname($path))) {
483
+                            return false;
484
+                        }
485
+                        $tmpFile = \OC::$server->getTempManager()->getTemporaryFile($ext);
486
+                    }
487
+                    $source = fopen($tmpFile, $mode);
488
+                    $share = $this->share;
489
+                    return CallbackWrapper::wrap($source, null, null, function () use ($tmpFile, $fullPath, $share) {
490
+                        unset($this->statCache[$fullPath]);
491
+                        $share->put($tmpFile, $fullPath);
492
+                        unlink($tmpFile);
493
+                    });
494
+            }
495
+            return false;
496
+        } catch (NotFoundException $e) {
497
+            return false;
498
+        } catch (ForbiddenException $e) {
499
+            return false;
500
+        } catch (ConnectException $e) {
501
+            $this->logger->logException($e, ['message' => 'Error while opening file']);
502
+            throw new StorageNotAvailableException($e->getMessage(), $e->getCode(), $e);
503
+        }
504
+    }
505
+
506
+    public function rmdir($path) {
507
+        if ($this->isRootDir($path)) {
508
+            return false;
509
+        }
510
+
511
+        try {
512
+            $this->statCache = [];
513
+            $content = $this->share->dir($this->buildPath($path));
514
+            foreach ($content as $file) {
515
+                if ($file->isDirectory()) {
516
+                    $this->rmdir($path . '/' . $file->getName());
517
+                } else {
518
+                    $this->share->del($file->getPath());
519
+                }
520
+            }
521
+            $this->share->rmdir($this->buildPath($path));
522
+            return true;
523
+        } catch (NotFoundException $e) {
524
+            return false;
525
+        } catch (ForbiddenException $e) {
526
+            return false;
527
+        } catch (ConnectException $e) {
528
+            $this->logger->logException($e, ['message' => 'Error while removing folder']);
529
+            throw new StorageNotAvailableException($e->getMessage(), $e->getCode(), $e);
530
+        }
531
+    }
532
+
533
+    public function touch($path, $mtime = null) {
534
+        try {
535
+            if (!$this->file_exists($path)) {
536
+                $fh = $this->share->write($this->buildPath($path));
537
+                fclose($fh);
538
+                return true;
539
+            }
540
+            return false;
541
+        } catch (ConnectException $e) {
542
+            $this->logger->logException($e, ['message' => 'Error while creating file']);
543
+            throw new StorageNotAvailableException($e->getMessage(), $e->getCode(), $e);
544
+        }
545
+    }
546
+
547
+    public function getMetaData($path) {
548
+        $fileInfo = $this->getFileInfo($path);
549
+        if (!$fileInfo) {
550
+            return null;
551
+        }
552
+
553
+        return $this->getMetaDataFromFileInfo($fileInfo);
554
+    }
555
+
556
+    private function getMetaDataFromFileInfo(IFileInfo $fileInfo) {
557
+        $permissions = Constants::PERMISSION_READ + Constants::PERMISSION_SHARE;
558
+
559
+        if (!$fileInfo->isReadOnly()) {
560
+            $permissions += Constants::PERMISSION_DELETE;
561
+            $permissions += Constants::PERMISSION_UPDATE;
562
+            if ($fileInfo->isDirectory()) {
563
+                $permissions += Constants::PERMISSION_CREATE;
564
+            }
565
+        }
566
+
567
+        $data = [];
568
+        if ($fileInfo->isDirectory()) {
569
+            $data['mimetype'] = 'httpd/unix-directory';
570
+        } else {
571
+            $data['mimetype'] = \OC::$server->getMimeTypeDetector()->detectPath($fileInfo->getPath());
572
+        }
573
+        $data['mtime'] = $fileInfo->getMTime();
574
+        if ($fileInfo->isDirectory()) {
575
+            $data['size'] = -1; //unknown
576
+        } else {
577
+            $data['size'] = $fileInfo->getSize();
578
+        }
579
+        $data['etag'] = $this->getETag($fileInfo->getPath());
580
+        $data['storage_mtime'] = $data['mtime'];
581
+        $data['permissions'] = $permissions;
582
+        $data['name'] = $fileInfo->getName();
583
+
584
+        return $data;
585
+    }
586
+
587
+    public function opendir($path) {
588
+        try {
589
+            $files = $this->getFolderContents($path);
590
+        } catch (NotFoundException $e) {
591
+            return false;
592
+        } catch (ForbiddenException $e) {
593
+            return false;
594
+        }
595
+        $names = array_map(function ($info) {
596
+            /** @var \Icewind\SMB\IFileInfo $info */
597
+            return $info->getName();
598
+        }, iterator_to_array($files));
599
+        return IteratorDirectory::wrap($names);
600
+    }
601
+
602
+    public function getDirectoryContent($directory): \Traversable {
603
+        $files = $this->getFolderContents($directory);
604
+        foreach ($files as $file) {
605
+            yield $this->getMetaDataFromFileInfo($file);
606
+        }
607
+    }
608
+
609
+    public function filetype($path) {
610
+        try {
611
+            return $this->getFileInfo($path)->isDirectory() ? 'dir' : 'file';
612
+        } catch (NotFoundException $e) {
613
+            return false;
614
+        } catch (ForbiddenException $e) {
615
+            return false;
616
+        }
617
+    }
618
+
619
+    public function mkdir($path) {
620
+        $path = $this->buildPath($path);
621
+        try {
622
+            $this->share->mkdir($path);
623
+            return true;
624
+        } catch (ConnectException $e) {
625
+            $this->logger->logException($e, ['message' => 'Error while creating folder']);
626
+            throw new StorageNotAvailableException($e->getMessage(), $e->getCode(), $e);
627
+        } catch (Exception $e) {
628
+            return false;
629
+        }
630
+    }
631
+
632
+    public function file_exists($path) {
633
+        try {
634
+            $this->getFileInfo($path);
635
+            return true;
636
+        } catch (NotFoundException $e) {
637
+            return false;
638
+        } catch (ForbiddenException $e) {
639
+            return false;
640
+        } catch (ConnectException $e) {
641
+            throw new StorageNotAvailableException($e->getMessage(), $e->getCode(), $e);
642
+        }
643
+    }
644
+
645
+    public function isReadable($path) {
646
+        try {
647
+            $info = $this->getFileInfo($path);
648
+            return $this->showHidden || !$info->isHidden();
649
+        } catch (NotFoundException $e) {
650
+            return false;
651
+        } catch (ForbiddenException $e) {
652
+            return false;
653
+        }
654
+    }
655
+
656
+    public function isUpdatable($path) {
657
+        try {
658
+            $info = $this->getFileInfo($path);
659
+            // following windows behaviour for read-only folders: they can be written into
660
+            // (https://support.microsoft.com/en-us/kb/326549 - "cause" section)
661
+            return ($this->showHidden || !$info->isHidden()) && (!$info->isReadOnly() || $this->is_dir($path));
662
+        } catch (NotFoundException $e) {
663
+            return false;
664
+        } catch (ForbiddenException $e) {
665
+            return false;
666
+        }
667
+    }
668
+
669
+    public function isDeletable($path) {
670
+        try {
671
+            $info = $this->getFileInfo($path);
672
+            return ($this->showHidden || !$info->isHidden()) && !$info->isReadOnly();
673
+        } catch (NotFoundException $e) {
674
+            return false;
675
+        } catch (ForbiddenException $e) {
676
+            return false;
677
+        }
678
+    }
679
+
680
+    /**
681
+     * check if smbclient is installed
682
+     */
683
+    public static function checkDependencies() {
684
+        return (
685
+            (bool)\OC_Helper::findBinaryPath('smbclient')
686
+            || NativeServer::available(new System())
687
+        ) ? true : ['smbclient'];
688
+    }
689
+
690
+    /**
691
+     * Test a storage for availability
692
+     *
693
+     * @return bool
694
+     */
695
+    public function test() {
696
+        try {
697
+            return parent::test();
698
+        } catch (Exception $e) {
699
+            $this->logger->logException($e);
700
+            return false;
701
+        }
702
+    }
703
+
704
+    public function listen($path, callable $callback) {
705
+        $this->notify($path)->listen(function (IChange $change) use ($callback) {
706
+            if ($change instanceof IRenameChange) {
707
+                return $callback($change->getType(), $change->getPath(), $change->getTargetPath());
708
+            } else {
709
+                return $callback($change->getType(), $change->getPath());
710
+            }
711
+        });
712
+    }
713
+
714
+    public function notify($path) {
715
+        $path = '/' . ltrim($path, '/');
716
+        $shareNotifyHandler = $this->share->notify($this->buildPath($path));
717
+        return new SMBNotifyHandler($shareNotifyHandler, $this->root);
718
+    }
719 719
 }
Please login to merge, or discard this patch.
apps/files_external/lib/Lib/Auth/Password/UserProvided.php 1 patch
Indentation   +39 added lines, -39 removed lines patch added patch discarded remove patch
@@ -38,51 +38,51 @@
 block discarded – undo
38 38
  * User provided Username and Password
39 39
  */
40 40
 class UserProvided extends AuthMechanism implements IUserProvided {
41
-	public const CREDENTIALS_IDENTIFIER_PREFIX = 'password::userprovided/';
41
+    public const CREDENTIALS_IDENTIFIER_PREFIX = 'password::userprovided/';
42 42
 
43
-	/** @var ICredentialsManager */
44
-	protected $credentialsManager;
43
+    /** @var ICredentialsManager */
44
+    protected $credentialsManager;
45 45
 
46
-	public function __construct(IL10N $l, ICredentialsManager $credentialsManager) {
47
-		$this->credentialsManager = $credentialsManager;
46
+    public function __construct(IL10N $l, ICredentialsManager $credentialsManager) {
47
+        $this->credentialsManager = $credentialsManager;
48 48
 
49
-		$this
50
-			->setIdentifier('password::userprovided')
51
-			->setVisibility(BackendService::VISIBILITY_ADMIN)
52
-			->setScheme(self::SCHEME_PASSWORD)
53
-			->setText($l->t('User entered, store in database'))
54
-			->addParameters([
55
-				(new DefinitionParameter('user', $l->t('Username')))
56
-					->setFlag(DefinitionParameter::FLAG_USER_PROVIDED),
57
-				(new DefinitionParameter('password', $l->t('Password')))
58
-					->setType(DefinitionParameter::VALUE_PASSWORD)
59
-					->setFlag(DefinitionParameter::FLAG_USER_PROVIDED),
60
-			]);
61
-	}
49
+        $this
50
+            ->setIdentifier('password::userprovided')
51
+            ->setVisibility(BackendService::VISIBILITY_ADMIN)
52
+            ->setScheme(self::SCHEME_PASSWORD)
53
+            ->setText($l->t('User entered, store in database'))
54
+            ->addParameters([
55
+                (new DefinitionParameter('user', $l->t('Username')))
56
+                    ->setFlag(DefinitionParameter::FLAG_USER_PROVIDED),
57
+                (new DefinitionParameter('password', $l->t('Password')))
58
+                    ->setType(DefinitionParameter::VALUE_PASSWORD)
59
+                    ->setFlag(DefinitionParameter::FLAG_USER_PROVIDED),
60
+            ]);
61
+    }
62 62
 
63
-	private function getCredentialsIdentifier($storageId) {
64
-		return self::CREDENTIALS_IDENTIFIER_PREFIX . $storageId;
65
-	}
63
+    private function getCredentialsIdentifier($storageId) {
64
+        return self::CREDENTIALS_IDENTIFIER_PREFIX . $storageId;
65
+    }
66 66
 
67
-	public function saveBackendOptions(IUser $user, $mountId, array $options) {
68
-		$this->credentialsManager->store($user->getUID(), $this->getCredentialsIdentifier($mountId), [
69
-			'user' => $options['user'], // explicitly copy the fields we want instead of just passing the entire $options array
70
-			'password' => $options['password'] // this way we prevent users from being able to modify any other field
71
-		]);
72
-	}
67
+    public function saveBackendOptions(IUser $user, $mountId, array $options) {
68
+        $this->credentialsManager->store($user->getUID(), $this->getCredentialsIdentifier($mountId), [
69
+            'user' => $options['user'], // explicitly copy the fields we want instead of just passing the entire $options array
70
+            'password' => $options['password'] // this way we prevent users from being able to modify any other field
71
+        ]);
72
+    }
73 73
 
74
-	public function manipulateStorageConfig(StorageConfig &$storage, IUser $user = null) {
75
-		if (!isset($user)) {
76
-			throw new InsufficientDataForMeaningfulAnswerException('No credentials saved');
77
-		}
78
-		$uid = $user->getUID();
79
-		$credentials = $this->credentialsManager->retrieve($uid, $this->getCredentialsIdentifier($storage->getId()));
74
+    public function manipulateStorageConfig(StorageConfig &$storage, IUser $user = null) {
75
+        if (!isset($user)) {
76
+            throw new InsufficientDataForMeaningfulAnswerException('No credentials saved');
77
+        }
78
+        $uid = $user->getUID();
79
+        $credentials = $this->credentialsManager->retrieve($uid, $this->getCredentialsIdentifier($storage->getId()));
80 80
 
81
-		if (!isset($credentials)) {
82
-			throw new InsufficientDataForMeaningfulAnswerException('No credentials saved');
83
-		}
81
+        if (!isset($credentials)) {
82
+            throw new InsufficientDataForMeaningfulAnswerException('No credentials saved');
83
+        }
84 84
 
85
-		$storage->setBackendOption('user', $credentials['user']);
86
-		$storage->setBackendOption('password', $credentials['password']);
87
-	}
85
+        $storage->setBackendOption('user', $credentials['user']);
86
+        $storage->setBackendOption('password', $credentials['password']);
87
+    }
88 88
 }
Please login to merge, or discard this patch.
apps/dav/lib/SystemTag/SystemTagsObjectMappingCollection.php 1 patch
Indentation   +166 added lines, -166 removed lines patch added patch discarded remove patch
@@ -42,170 +42,170 @@
 block discarded – undo
42 42
  */
43 43
 class SystemTagsObjectMappingCollection implements ICollection {
44 44
 
45
-	/**
46
-	 * @var string
47
-	 */
48
-	private $objectId;
49
-
50
-	/**
51
-	 * @var string
52
-	 */
53
-	private $objectType;
54
-
55
-	/**
56
-	 * @var ISystemTagManager
57
-	 */
58
-	private $tagManager;
59
-
60
-	/**
61
-	 * @var ISystemTagObjectMapper
62
-	 */
63
-	private $tagMapper;
64
-
65
-	/**
66
-	 * User
67
-	 *
68
-	 * @var IUser
69
-	 */
70
-	private $user;
71
-
72
-
73
-	/**
74
-	 * Constructor
75
-	 *
76
-	 * @param string $objectId object id
77
-	 * @param string $objectType object type
78
-	 * @param IUser $user user
79
-	 * @param ISystemTagManager $tagManager tag manager
80
-	 * @param ISystemTagObjectMapper $tagMapper tag mapper
81
-	 */
82
-	public function __construct(
83
-		$objectId,
84
-		$objectType,
85
-		IUser $user,
86
-		ISystemTagManager $tagManager,
87
-		ISystemTagObjectMapper $tagMapper
88
-	) {
89
-		$this->tagManager = $tagManager;
90
-		$this->tagMapper = $tagMapper;
91
-		$this->objectId = $objectId;
92
-		$this->objectType = $objectType;
93
-		$this->user = $user;
94
-	}
95
-
96
-	public function createFile($name, $data = null) {
97
-		$tagId = $name;
98
-		try {
99
-			$tags = $this->tagManager->getTagsByIds([$tagId]);
100
-			$tag = current($tags);
101
-			if (!$this->tagManager->canUserSeeTag($tag, $this->user)) {
102
-				throw new PreconditionFailed('Tag with id ' . $tagId . ' does not exist, cannot assign');
103
-			}
104
-			if (!$this->tagManager->canUserAssignTag($tag, $this->user)) {
105
-				throw new Forbidden('No permission to assign tag ' . $tagId);
106
-			}
107
-
108
-			$this->tagMapper->assignTags($this->objectId, $this->objectType, $tagId);
109
-		} catch (TagNotFoundException $e) {
110
-			throw new PreconditionFailed('Tag with id ' . $tagId . ' does not exist, cannot assign');
111
-		}
112
-	}
113
-
114
-	public function createDirectory($name) {
115
-		throw new Forbidden('Permission denied to create collections');
116
-	}
117
-
118
-	public function getChild($tagId) {
119
-		try {
120
-			if ($this->tagMapper->haveTag([$this->objectId], $this->objectType, $tagId, true)) {
121
-				$tag = $this->tagManager->getTagsByIds([$tagId]);
122
-				$tag = current($tag);
123
-				if ($this->tagManager->canUserSeeTag($tag, $this->user)) {
124
-					return $this->makeNode($tag);
125
-				}
126
-			}
127
-			throw new NotFound('Tag with id ' . $tagId . ' not present for object ' . $this->objectId);
128
-		} catch (\InvalidArgumentException $e) {
129
-			throw new BadRequest('Invalid tag id', 0, $e);
130
-		} catch (TagNotFoundException $e) {
131
-			throw new NotFound('Tag with id ' . $tagId . ' not found', 0, $e);
132
-		}
133
-	}
134
-
135
-	public function getChildren() {
136
-		$tagIds = current($this->tagMapper->getTagIdsForObjects([$this->objectId], $this->objectType));
137
-		if (empty($tagIds)) {
138
-			return [];
139
-		}
140
-		$tags = $this->tagManager->getTagsByIds($tagIds);
141
-
142
-		// filter out non-visible tags
143
-		$tags = array_filter($tags, function ($tag) {
144
-			return $this->tagManager->canUserSeeTag($tag, $this->user);
145
-		});
146
-
147
-		return array_values(array_map(function ($tag) {
148
-			return $this->makeNode($tag);
149
-		}, $tags));
150
-	}
151
-
152
-	public function childExists($tagId) {
153
-		try {
154
-			$result = $this->tagMapper->haveTag([$this->objectId], $this->objectType, $tagId, true);
155
-
156
-			if ($result) {
157
-				$tags = $this->tagManager->getTagsByIds([$tagId]);
158
-				$tag = current($tags);
159
-				if (!$this->tagManager->canUserSeeTag($tag, $this->user)) {
160
-					return false;
161
-				}
162
-			}
163
-
164
-			return $result;
165
-		} catch (\InvalidArgumentException $e) {
166
-			throw new BadRequest('Invalid tag id', 0, $e);
167
-		} catch (TagNotFoundException $e) {
168
-			return false;
169
-		}
170
-	}
171
-
172
-	public function delete() {
173
-		throw new Forbidden('Permission denied to delete this collection');
174
-	}
175
-
176
-	public function getName() {
177
-		return $this->objectId;
178
-	}
179
-
180
-	public function setName($name) {
181
-		throw new Forbidden('Permission denied to rename this collection');
182
-	}
183
-
184
-	/**
185
-	 * Returns the last modification time, as a unix timestamp
186
-	 *
187
-	 * @return int
188
-	 */
189
-	public function getLastModified() {
190
-		return null;
191
-	}
192
-
193
-	/**
194
-	 * Create a sabre node for the mapping of the
195
-	 * given system tag to the collection's object
196
-	 *
197
-	 * @param ISystemTag $tag
198
-	 *
199
-	 * @return SystemTagMappingNode
200
-	 */
201
-	private function makeNode(ISystemTag $tag) {
202
-		return new SystemTagMappingNode(
203
-			$tag,
204
-			$this->objectId,
205
-			$this->objectType,
206
-			$this->user,
207
-			$this->tagManager,
208
-			$this->tagMapper
209
-		);
210
-	}
45
+    /**
46
+     * @var string
47
+     */
48
+    private $objectId;
49
+
50
+    /**
51
+     * @var string
52
+     */
53
+    private $objectType;
54
+
55
+    /**
56
+     * @var ISystemTagManager
57
+     */
58
+    private $tagManager;
59
+
60
+    /**
61
+     * @var ISystemTagObjectMapper
62
+     */
63
+    private $tagMapper;
64
+
65
+    /**
66
+     * User
67
+     *
68
+     * @var IUser
69
+     */
70
+    private $user;
71
+
72
+
73
+    /**
74
+     * Constructor
75
+     *
76
+     * @param string $objectId object id
77
+     * @param string $objectType object type
78
+     * @param IUser $user user
79
+     * @param ISystemTagManager $tagManager tag manager
80
+     * @param ISystemTagObjectMapper $tagMapper tag mapper
81
+     */
82
+    public function __construct(
83
+        $objectId,
84
+        $objectType,
85
+        IUser $user,
86
+        ISystemTagManager $tagManager,
87
+        ISystemTagObjectMapper $tagMapper
88
+    ) {
89
+        $this->tagManager = $tagManager;
90
+        $this->tagMapper = $tagMapper;
91
+        $this->objectId = $objectId;
92
+        $this->objectType = $objectType;
93
+        $this->user = $user;
94
+    }
95
+
96
+    public function createFile($name, $data = null) {
97
+        $tagId = $name;
98
+        try {
99
+            $tags = $this->tagManager->getTagsByIds([$tagId]);
100
+            $tag = current($tags);
101
+            if (!$this->tagManager->canUserSeeTag($tag, $this->user)) {
102
+                throw new PreconditionFailed('Tag with id ' . $tagId . ' does not exist, cannot assign');
103
+            }
104
+            if (!$this->tagManager->canUserAssignTag($tag, $this->user)) {
105
+                throw new Forbidden('No permission to assign tag ' . $tagId);
106
+            }
107
+
108
+            $this->tagMapper->assignTags($this->objectId, $this->objectType, $tagId);
109
+        } catch (TagNotFoundException $e) {
110
+            throw new PreconditionFailed('Tag with id ' . $tagId . ' does not exist, cannot assign');
111
+        }
112
+    }
113
+
114
+    public function createDirectory($name) {
115
+        throw new Forbidden('Permission denied to create collections');
116
+    }
117
+
118
+    public function getChild($tagId) {
119
+        try {
120
+            if ($this->tagMapper->haveTag([$this->objectId], $this->objectType, $tagId, true)) {
121
+                $tag = $this->tagManager->getTagsByIds([$tagId]);
122
+                $tag = current($tag);
123
+                if ($this->tagManager->canUserSeeTag($tag, $this->user)) {
124
+                    return $this->makeNode($tag);
125
+                }
126
+            }
127
+            throw new NotFound('Tag with id ' . $tagId . ' not present for object ' . $this->objectId);
128
+        } catch (\InvalidArgumentException $e) {
129
+            throw new BadRequest('Invalid tag id', 0, $e);
130
+        } catch (TagNotFoundException $e) {
131
+            throw new NotFound('Tag with id ' . $tagId . ' not found', 0, $e);
132
+        }
133
+    }
134
+
135
+    public function getChildren() {
136
+        $tagIds = current($this->tagMapper->getTagIdsForObjects([$this->objectId], $this->objectType));
137
+        if (empty($tagIds)) {
138
+            return [];
139
+        }
140
+        $tags = $this->tagManager->getTagsByIds($tagIds);
141
+
142
+        // filter out non-visible tags
143
+        $tags = array_filter($tags, function ($tag) {
144
+            return $this->tagManager->canUserSeeTag($tag, $this->user);
145
+        });
146
+
147
+        return array_values(array_map(function ($tag) {
148
+            return $this->makeNode($tag);
149
+        }, $tags));
150
+    }
151
+
152
+    public function childExists($tagId) {
153
+        try {
154
+            $result = $this->tagMapper->haveTag([$this->objectId], $this->objectType, $tagId, true);
155
+
156
+            if ($result) {
157
+                $tags = $this->tagManager->getTagsByIds([$tagId]);
158
+                $tag = current($tags);
159
+                if (!$this->tagManager->canUserSeeTag($tag, $this->user)) {
160
+                    return false;
161
+                }
162
+            }
163
+
164
+            return $result;
165
+        } catch (\InvalidArgumentException $e) {
166
+            throw new BadRequest('Invalid tag id', 0, $e);
167
+        } catch (TagNotFoundException $e) {
168
+            return false;
169
+        }
170
+    }
171
+
172
+    public function delete() {
173
+        throw new Forbidden('Permission denied to delete this collection');
174
+    }
175
+
176
+    public function getName() {
177
+        return $this->objectId;
178
+    }
179
+
180
+    public function setName($name) {
181
+        throw new Forbidden('Permission denied to rename this collection');
182
+    }
183
+
184
+    /**
185
+     * Returns the last modification time, as a unix timestamp
186
+     *
187
+     * @return int
188
+     */
189
+    public function getLastModified() {
190
+        return null;
191
+    }
192
+
193
+    /**
194
+     * Create a sabre node for the mapping of the
195
+     * given system tag to the collection's object
196
+     *
197
+     * @param ISystemTag $tag
198
+     *
199
+     * @return SystemTagMappingNode
200
+     */
201
+    private function makeNode(ISystemTag $tag) {
202
+        return new SystemTagMappingNode(
203
+            $tag,
204
+            $this->objectId,
205
+            $this->objectType,
206
+            $this->user,
207
+            $this->tagManager,
208
+            $this->tagMapper
209
+        );
210
+    }
211 211
 }
Please login to merge, or discard this patch.
apps/dav/lib/CalDAV/CalDavBackend.php 1 patch
Indentation   +2652 added lines, -2652 removed lines patch added patch discarded remove patch
@@ -77,2656 +77,2656 @@
 block discarded – undo
77 77
  * @package OCA\DAV\CalDAV
78 78
  */
79 79
 class CalDavBackend extends AbstractBackend implements SyncSupport, SubscriptionSupport, SchedulingSupport {
80
-	public const CALENDAR_TYPE_CALENDAR = 0;
81
-	public const CALENDAR_TYPE_SUBSCRIPTION = 1;
82
-
83
-	public const PERSONAL_CALENDAR_URI = 'personal';
84
-	public const PERSONAL_CALENDAR_NAME = 'Personal';
85
-
86
-	public const RESOURCE_BOOKING_CALENDAR_URI = 'calendar';
87
-	public const RESOURCE_BOOKING_CALENDAR_NAME = 'Calendar';
88
-
89
-	/**
90
-	 * We need to specify a max date, because we need to stop *somewhere*
91
-	 *
92
-	 * On 32 bit system the maximum for a signed integer is 2147483647, so
93
-	 * MAX_DATE cannot be higher than date('Y-m-d', 2147483647) which results
94
-	 * in 2038-01-19 to avoid problems when the date is converted
95
-	 * to a unix timestamp.
96
-	 */
97
-	public const MAX_DATE = '2038-01-01';
98
-
99
-	public const ACCESS_PUBLIC = 4;
100
-	public const CLASSIFICATION_PUBLIC = 0;
101
-	public const CLASSIFICATION_PRIVATE = 1;
102
-	public const CLASSIFICATION_CONFIDENTIAL = 2;
103
-
104
-	/**
105
-	 * List of CalDAV properties, and how they map to database field names
106
-	 * Add your own properties by simply adding on to this array.
107
-	 *
108
-	 * Note that only string-based properties are supported here.
109
-	 *
110
-	 * @var array
111
-	 */
112
-	public $propertyMap = [
113
-		'{DAV:}displayname'                          => 'displayname',
114
-		'{urn:ietf:params:xml:ns:caldav}calendar-description' => 'description',
115
-		'{urn:ietf:params:xml:ns:caldav}calendar-timezone'    => 'timezone',
116
-		'{http://apple.com/ns/ical/}calendar-order'  => 'calendarorder',
117
-		'{http://apple.com/ns/ical/}calendar-color'  => 'calendarcolor',
118
-	];
119
-
120
-	/**
121
-	 * List of subscription properties, and how they map to database field names.
122
-	 *
123
-	 * @var array
124
-	 */
125
-	public $subscriptionPropertyMap = [
126
-		'{DAV:}displayname'                                           => 'displayname',
127
-		'{http://apple.com/ns/ical/}refreshrate'                      => 'refreshrate',
128
-		'{http://apple.com/ns/ical/}calendar-order'                   => 'calendarorder',
129
-		'{http://apple.com/ns/ical/}calendar-color'                   => 'calendarcolor',
130
-		'{http://calendarserver.org/ns/}subscribed-strip-todos'       => 'striptodos',
131
-		'{http://calendarserver.org/ns/}subscribed-strip-alarms'      => 'stripalarms',
132
-		'{http://calendarserver.org/ns/}subscribed-strip-attachments' => 'stripattachments',
133
-	];
134
-
135
-	/** @var array properties to index */
136
-	public static $indexProperties = ['CATEGORIES', 'COMMENT', 'DESCRIPTION',
137
-		'LOCATION', 'RESOURCES', 'STATUS', 'SUMMARY', 'ATTENDEE', 'CONTACT',
138
-		'ORGANIZER'];
139
-
140
-	/** @var array parameters to index */
141
-	public static $indexParameters = [
142
-		'ATTENDEE' => ['CN'],
143
-		'ORGANIZER' => ['CN'],
144
-	];
145
-
146
-	/**
147
-	 * @var string[] Map of uid => display name
148
-	 */
149
-	protected $userDisplayNames;
150
-
151
-	/** @var IDBConnection */
152
-	private $db;
153
-
154
-	/** @var Backend */
155
-	private $calendarSharingBackend;
156
-
157
-	/** @var Principal */
158
-	private $principalBackend;
159
-
160
-	/** @var IUserManager */
161
-	private $userManager;
162
-
163
-	/** @var ISecureRandom */
164
-	private $random;
165
-
166
-	/** @var ILogger */
167
-	private $logger;
168
-
169
-	/** @var EventDispatcherInterface */
170
-	private $dispatcher;
171
-
172
-	/** @var bool */
173
-	private $legacyEndpoint;
174
-
175
-	/** @var string */
176
-	private $dbObjectPropertiesTable = 'calendarobjects_props';
177
-
178
-	/**
179
-	 * CalDavBackend constructor.
180
-	 *
181
-	 * @param IDBConnection $db
182
-	 * @param Principal $principalBackend
183
-	 * @param IUserManager $userManager
184
-	 * @param IGroupManager $groupManager
185
-	 * @param ISecureRandom $random
186
-	 * @param ILogger $logger
187
-	 * @param EventDispatcherInterface $dispatcher
188
-	 * @param bool $legacyEndpoint
189
-	 */
190
-	public function __construct(IDBConnection $db,
191
-								Principal $principalBackend,
192
-								IUserManager $userManager,
193
-								IGroupManager $groupManager,
194
-								ISecureRandom $random,
195
-								ILogger $logger,
196
-								EventDispatcherInterface $dispatcher,
197
-								bool $legacyEndpoint = false) {
198
-		$this->db = $db;
199
-		$this->principalBackend = $principalBackend;
200
-		$this->userManager = $userManager;
201
-		$this->calendarSharingBackend = new Backend($this->db, $this->userManager, $groupManager, $principalBackend, 'calendar');
202
-		$this->random = $random;
203
-		$this->logger = $logger;
204
-		$this->dispatcher = $dispatcher;
205
-		$this->legacyEndpoint = $legacyEndpoint;
206
-	}
207
-
208
-	/**
209
-	 * Return the number of calendars for a principal
210
-	 *
211
-	 * By default this excludes the automatically generated birthday calendar
212
-	 *
213
-	 * @param $principalUri
214
-	 * @param bool $excludeBirthday
215
-	 * @return int
216
-	 */
217
-	public function getCalendarsForUserCount($principalUri, $excludeBirthday = true) {
218
-		$principalUri = $this->convertPrincipal($principalUri, true);
219
-		$query = $this->db->getQueryBuilder();
220
-		$query->select($query->func()->count('*'))
221
-			->from('calendars')
222
-			->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)));
223
-
224
-		if ($excludeBirthday) {
225
-			$query->andWhere($query->expr()->neq('uri', $query->createNamedParameter(BirthdayService::BIRTHDAY_CALENDAR_URI)));
226
-		}
227
-
228
-		return (int)$query->execute()->fetchColumn();
229
-	}
230
-
231
-	/**
232
-	 * Returns a list of calendars for a principal.
233
-	 *
234
-	 * Every project is an array with the following keys:
235
-	 *  * id, a unique id that will be used by other functions to modify the
236
-	 *    calendar. This can be the same as the uri or a database key.
237
-	 *  * uri, which the basename of the uri with which the calendar is
238
-	 *    accessed.
239
-	 *  * principaluri. The owner of the calendar. Almost always the same as
240
-	 *    principalUri passed to this method.
241
-	 *
242
-	 * Furthermore it can contain webdav properties in clark notation. A very
243
-	 * common one is '{DAV:}displayname'.
244
-	 *
245
-	 * Many clients also require:
246
-	 * {urn:ietf:params:xml:ns:caldav}supported-calendar-component-set
247
-	 * For this property, you can just return an instance of
248
-	 * Sabre\CalDAV\Property\SupportedCalendarComponentSet.
249
-	 *
250
-	 * If you return {http://sabredav.org/ns}read-only and set the value to 1,
251
-	 * ACL will automatically be put in read-only mode.
252
-	 *
253
-	 * @param string $principalUri
254
-	 * @return array
255
-	 */
256
-	public function getCalendarsForUser($principalUri) {
257
-		$principalUriOriginal = $principalUri;
258
-		$principalUri = $this->convertPrincipal($principalUri, true);
259
-		$fields = array_values($this->propertyMap);
260
-		$fields[] = 'id';
261
-		$fields[] = 'uri';
262
-		$fields[] = 'synctoken';
263
-		$fields[] = 'components';
264
-		$fields[] = 'principaluri';
265
-		$fields[] = 'transparent';
266
-
267
-		// Making fields a comma-delimited list
268
-		$query = $this->db->getQueryBuilder();
269
-		$query->select($fields)->from('calendars')
270
-				->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
271
-				->orderBy('calendarorder', 'ASC');
272
-		$stmt = $query->execute();
273
-
274
-		$calendars = [];
275
-		while ($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
276
-			$components = [];
277
-			if ($row['components']) {
278
-				$components = explode(',',$row['components']);
279
-			}
280
-
281
-			$calendar = [
282
-				'id' => $row['id'],
283
-				'uri' => $row['uri'],
284
-				'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
285
-				'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
286
-				'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
287
-				'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
288
-				'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
289
-				'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($principalUri, !$this->legacyEndpoint),
290
-			];
291
-
292
-			foreach ($this->propertyMap as $xmlName=>$dbName) {
293
-				$calendar[$xmlName] = $row[$dbName];
294
-			}
295
-
296
-			$this->addOwnerPrincipal($calendar);
297
-
298
-			if (!isset($calendars[$calendar['id']])) {
299
-				$calendars[$calendar['id']] = $calendar;
300
-			}
301
-		}
302
-
303
-		$stmt->closeCursor();
304
-
305
-		// query for shared calendars
306
-		$principals = $this->principalBackend->getGroupMembership($principalUriOriginal, true);
307
-		$principals = array_merge($principals, $this->principalBackend->getCircleMembership($principalUriOriginal));
308
-
309
-		$principals = array_map(function ($principal) {
310
-			return urldecode($principal);
311
-		}, $principals);
312
-		$principals[]= $principalUri;
313
-
314
-		$fields = array_values($this->propertyMap);
315
-		$fields[] = 'a.id';
316
-		$fields[] = 'a.uri';
317
-		$fields[] = 'a.synctoken';
318
-		$fields[] = 'a.components';
319
-		$fields[] = 'a.principaluri';
320
-		$fields[] = 'a.transparent';
321
-		$fields[] = 's.access';
322
-		$query = $this->db->getQueryBuilder();
323
-		$result = $query->select($fields)
324
-			->from('dav_shares', 's')
325
-			->join('s', 'calendars', 'a', $query->expr()->eq('s.resourceid', 'a.id'))
326
-			->where($query->expr()->in('s.principaluri', $query->createParameter('principaluri')))
327
-			->andWhere($query->expr()->eq('s.type', $query->createParameter('type')))
328
-			->setParameter('type', 'calendar')
329
-			->setParameter('principaluri', $principals, \Doctrine\DBAL\Connection::PARAM_STR_ARRAY)
330
-			->execute();
331
-
332
-		$readOnlyPropertyName = '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}read-only';
333
-		while ($row = $result->fetch()) {
334
-			if ($row['principaluri'] === $principalUri) {
335
-				continue;
336
-			}
337
-
338
-			$readOnly = (int) $row['access'] === Backend::ACCESS_READ;
339
-			if (isset($calendars[$row['id']])) {
340
-				if ($readOnly) {
341
-					// New share can not have more permissions then the old one.
342
-					continue;
343
-				}
344
-				if (isset($calendars[$row['id']][$readOnlyPropertyName]) &&
345
-					$calendars[$row['id']][$readOnlyPropertyName] === 0) {
346
-					// Old share is already read-write, no more permissions can be gained
347
-					continue;
348
-				}
349
-			}
350
-
351
-			list(, $name) = Uri\split($row['principaluri']);
352
-			$uri = $row['uri'] . '_shared_by_' . $name;
353
-			$row['displayname'] = $row['displayname'] . ' (' . $this->getUserDisplayName($name) . ')';
354
-			$components = [];
355
-			if ($row['components']) {
356
-				$components = explode(',',$row['components']);
357
-			}
358
-			$calendar = [
359
-				'id' => $row['id'],
360
-				'uri' => $uri,
361
-				'principaluri' => $this->convertPrincipal($principalUri, !$this->legacyEndpoint),
362
-				'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
363
-				'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
364
-				'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
365
-				'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp('transparent'),
366
-				'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
367
-				$readOnlyPropertyName => $readOnly,
368
-			];
369
-
370
-			foreach ($this->propertyMap as $xmlName=>$dbName) {
371
-				$calendar[$xmlName] = $row[$dbName];
372
-			}
373
-
374
-			$this->addOwnerPrincipal($calendar);
375
-
376
-			$calendars[$calendar['id']] = $calendar;
377
-		}
378
-		$result->closeCursor();
379
-
380
-		return array_values($calendars);
381
-	}
382
-
383
-	/**
384
-	 * @param $principalUri
385
-	 * @return array
386
-	 */
387
-	public function getUsersOwnCalendars($principalUri) {
388
-		$principalUri = $this->convertPrincipal($principalUri, true);
389
-		$fields = array_values($this->propertyMap);
390
-		$fields[] = 'id';
391
-		$fields[] = 'uri';
392
-		$fields[] = 'synctoken';
393
-		$fields[] = 'components';
394
-		$fields[] = 'principaluri';
395
-		$fields[] = 'transparent';
396
-		// Making fields a comma-delimited list
397
-		$query = $this->db->getQueryBuilder();
398
-		$query->select($fields)->from('calendars')
399
-			->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
400
-			->orderBy('calendarorder', 'ASC');
401
-		$stmt = $query->execute();
402
-		$calendars = [];
403
-		while ($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
404
-			$components = [];
405
-			if ($row['components']) {
406
-				$components = explode(',',$row['components']);
407
-			}
408
-			$calendar = [
409
-				'id' => $row['id'],
410
-				'uri' => $row['uri'],
411
-				'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
412
-				'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
413
-				'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
414
-				'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
415
-				'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
416
-			];
417
-			foreach ($this->propertyMap as $xmlName=>$dbName) {
418
-				$calendar[$xmlName] = $row[$dbName];
419
-			}
420
-
421
-			$this->addOwnerPrincipal($calendar);
422
-
423
-			if (!isset($calendars[$calendar['id']])) {
424
-				$calendars[$calendar['id']] = $calendar;
425
-			}
426
-		}
427
-		$stmt->closeCursor();
428
-		return array_values($calendars);
429
-	}
430
-
431
-
432
-	/**
433
-	 * @param $uid
434
-	 * @return string
435
-	 */
436
-	private function getUserDisplayName($uid) {
437
-		if (!isset($this->userDisplayNames[$uid])) {
438
-			$user = $this->userManager->get($uid);
439
-
440
-			if ($user instanceof IUser) {
441
-				$this->userDisplayNames[$uid] = $user->getDisplayName();
442
-			} else {
443
-				$this->userDisplayNames[$uid] = $uid;
444
-			}
445
-		}
446
-
447
-		return $this->userDisplayNames[$uid];
448
-	}
449
-
450
-	/**
451
-	 * @return array
452
-	 */
453
-	public function getPublicCalendars() {
454
-		$fields = array_values($this->propertyMap);
455
-		$fields[] = 'a.id';
456
-		$fields[] = 'a.uri';
457
-		$fields[] = 'a.synctoken';
458
-		$fields[] = 'a.components';
459
-		$fields[] = 'a.principaluri';
460
-		$fields[] = 'a.transparent';
461
-		$fields[] = 's.access';
462
-		$fields[] = 's.publicuri';
463
-		$calendars = [];
464
-		$query = $this->db->getQueryBuilder();
465
-		$result = $query->select($fields)
466
-			->from('dav_shares', 's')
467
-			->join('s', 'calendars', 'a', $query->expr()->eq('s.resourceid', 'a.id'))
468
-			->where($query->expr()->in('s.access', $query->createNamedParameter(self::ACCESS_PUBLIC)))
469
-			->andWhere($query->expr()->eq('s.type', $query->createNamedParameter('calendar')))
470
-			->execute();
471
-
472
-		while ($row = $result->fetch()) {
473
-			list(, $name) = Uri\split($row['principaluri']);
474
-			$row['displayname'] = $row['displayname'] . "($name)";
475
-			$components = [];
476
-			if ($row['components']) {
477
-				$components = explode(',',$row['components']);
478
-			}
479
-			$calendar = [
480
-				'id' => $row['id'],
481
-				'uri' => $row['publicuri'],
482
-				'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
483
-				'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
484
-				'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
485
-				'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
486
-				'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
487
-				'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($row['principaluri'], $this->legacyEndpoint),
488
-				'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}read-only' => (int)$row['access'] === Backend::ACCESS_READ,
489
-				'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}public' => (int)$row['access'] === self::ACCESS_PUBLIC,
490
-			];
491
-
492
-			foreach ($this->propertyMap as $xmlName=>$dbName) {
493
-				$calendar[$xmlName] = $row[$dbName];
494
-			}
495
-
496
-			$this->addOwnerPrincipal($calendar);
497
-
498
-			if (!isset($calendars[$calendar['id']])) {
499
-				$calendars[$calendar['id']] = $calendar;
500
-			}
501
-		}
502
-		$result->closeCursor();
503
-
504
-		return array_values($calendars);
505
-	}
506
-
507
-	/**
508
-	 * @param string $uri
509
-	 * @return array
510
-	 * @throws NotFound
511
-	 */
512
-	public function getPublicCalendar($uri) {
513
-		$fields = array_values($this->propertyMap);
514
-		$fields[] = 'a.id';
515
-		$fields[] = 'a.uri';
516
-		$fields[] = 'a.synctoken';
517
-		$fields[] = 'a.components';
518
-		$fields[] = 'a.principaluri';
519
-		$fields[] = 'a.transparent';
520
-		$fields[] = 's.access';
521
-		$fields[] = 's.publicuri';
522
-		$query = $this->db->getQueryBuilder();
523
-		$result = $query->select($fields)
524
-			->from('dav_shares', 's')
525
-			->join('s', 'calendars', 'a', $query->expr()->eq('s.resourceid', 'a.id'))
526
-			->where($query->expr()->in('s.access', $query->createNamedParameter(self::ACCESS_PUBLIC)))
527
-			->andWhere($query->expr()->eq('s.type', $query->createNamedParameter('calendar')))
528
-			->andWhere($query->expr()->eq('s.publicuri', $query->createNamedParameter($uri)))
529
-			->execute();
530
-
531
-		$row = $result->fetch(\PDO::FETCH_ASSOC);
532
-
533
-		$result->closeCursor();
534
-
535
-		if ($row === false) {
536
-			throw new NotFound('Node with name \'' . $uri . '\' could not be found');
537
-		}
538
-
539
-		list(, $name) = Uri\split($row['principaluri']);
540
-		$row['displayname'] = $row['displayname'] . ' ' . "($name)";
541
-		$components = [];
542
-		if ($row['components']) {
543
-			$components = explode(',',$row['components']);
544
-		}
545
-		$calendar = [
546
-			'id' => $row['id'],
547
-			'uri' => $row['publicuri'],
548
-			'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
549
-			'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
550
-			'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
551
-			'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
552
-			'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
553
-			'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
554
-			'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}read-only' => (int)$row['access'] === Backend::ACCESS_READ,
555
-			'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}public' => (int)$row['access'] === self::ACCESS_PUBLIC,
556
-		];
557
-
558
-		foreach ($this->propertyMap as $xmlName=>$dbName) {
559
-			$calendar[$xmlName] = $row[$dbName];
560
-		}
561
-
562
-		$this->addOwnerPrincipal($calendar);
563
-
564
-		return $calendar;
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
-	public 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
-		} elseif (isset($properties['components'])) {
743
-			// Allow to provide components internally without having
744
-			// to create a SupportedCalendarComponentSet object
745
-			$values['components'] = $properties['components'];
746
-		}
747
-
748
-		$transp = '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp';
749
-		if (isset($properties[$transp])) {
750
-			$values['transparent'] = (int) ($properties[$transp]->getValue() === 'transparent');
751
-		}
752
-
753
-		foreach ($this->propertyMap as $xmlName=>$dbName) {
754
-			if (isset($properties[$xmlName])) {
755
-				$values[$dbName] = $properties[$xmlName];
756
-			}
757
-		}
758
-
759
-		$query = $this->db->getQueryBuilder();
760
-		$query->insert('calendars');
761
-		foreach ($values as $column => $value) {
762
-			$query->setValue($column, $query->createNamedParameter($value));
763
-		}
764
-		$query->execute();
765
-		$calendarId = $query->getLastInsertId();
766
-
767
-		$this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::createCalendar', new GenericEvent(
768
-			'\OCA\DAV\CalDAV\CalDavBackend::createCalendar',
769
-			[
770
-				'calendarId' => $calendarId,
771
-				'calendarData' => $this->getCalendarById($calendarId),
772
-			]));
773
-
774
-		return $calendarId;
775
-	}
776
-
777
-	/**
778
-	 * Updates properties for a calendar.
779
-	 *
780
-	 * The list of mutations is stored in a Sabre\DAV\PropPatch object.
781
-	 * To do the actual updates, you must tell this object which properties
782
-	 * you're going to process with the handle() method.
783
-	 *
784
-	 * Calling the handle method is like telling the PropPatch object "I
785
-	 * promise I can handle updating this property".
786
-	 *
787
-	 * Read the PropPatch documentation for more info and examples.
788
-	 *
789
-	 * @param mixed $calendarId
790
-	 * @param PropPatch $propPatch
791
-	 * @return void
792
-	 */
793
-	public function updateCalendar($calendarId, PropPatch $propPatch) {
794
-		$supportedProperties = array_keys($this->propertyMap);
795
-		$supportedProperties[] = '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp';
796
-
797
-		/**
798
-		 * @suppress SqlInjectionChecker
799
-		 */
800
-		$propPatch->handle($supportedProperties, function ($mutations) use ($calendarId) {
801
-			$newValues = [];
802
-			foreach ($mutations as $propertyName => $propertyValue) {
803
-				switch ($propertyName) {
804
-					case '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp':
805
-						$fieldName = 'transparent';
806
-						$newValues[$fieldName] = (int) ($propertyValue->getValue() === 'transparent');
807
-						break;
808
-					default:
809
-						$fieldName = $this->propertyMap[$propertyName];
810
-						$newValues[$fieldName] = $propertyValue;
811
-						break;
812
-				}
813
-			}
814
-			$query = $this->db->getQueryBuilder();
815
-			$query->update('calendars');
816
-			foreach ($newValues as $fieldName => $value) {
817
-				$query->set($fieldName, $query->createNamedParameter($value));
818
-			}
819
-			$query->where($query->expr()->eq('id', $query->createNamedParameter($calendarId)));
820
-			$query->execute();
821
-
822
-			$this->addChange($calendarId, "", 2);
823
-
824
-			$this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::updateCalendar', new GenericEvent(
825
-				'\OCA\DAV\CalDAV\CalDavBackend::updateCalendar',
826
-				[
827
-					'calendarId' => $calendarId,
828
-					'calendarData' => $this->getCalendarById($calendarId),
829
-					'shares' => $this->getShares($calendarId),
830
-					'propertyMutations' => $mutations,
831
-				]));
832
-
833
-			return true;
834
-		});
835
-	}
836
-
837
-	/**
838
-	 * Delete a calendar and all it's objects
839
-	 *
840
-	 * @param mixed $calendarId
841
-	 * @return void
842
-	 */
843
-	public function deleteCalendar($calendarId) {
844
-		$this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::deleteCalendar', new GenericEvent(
845
-			'\OCA\DAV\CalDAV\CalDavBackend::deleteCalendar',
846
-			[
847
-				'calendarId' => $calendarId,
848
-				'calendarData' => $this->getCalendarById($calendarId),
849
-				'shares' => $this->getShares($calendarId),
850
-			]));
851
-
852
-		$stmt = $this->db->prepare('DELETE FROM `*PREFIX*calendarobjects` WHERE `calendarid` = ? AND `calendartype` = ?');
853
-		$stmt->execute([$calendarId, self::CALENDAR_TYPE_CALENDAR]);
854
-
855
-		$stmt = $this->db->prepare('DELETE FROM `*PREFIX*calendars` WHERE `id` = ?');
856
-		$stmt->execute([$calendarId]);
857
-
858
-		$stmt = $this->db->prepare('DELETE FROM `*PREFIX*calendarchanges` WHERE `calendarid` = ? AND `calendartype` = ?');
859
-		$stmt->execute([$calendarId, self::CALENDAR_TYPE_CALENDAR]);
860
-
861
-		$this->calendarSharingBackend->deleteAllShares($calendarId);
862
-
863
-		$query = $this->db->getQueryBuilder();
864
-		$query->delete($this->dbObjectPropertiesTable)
865
-			->where($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)))
866
-			->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_CALENDAR)))
867
-			->execute();
868
-	}
869
-
870
-	/**
871
-	 * Delete all of an user's shares
872
-	 *
873
-	 * @param string $principaluri
874
-	 * @return void
875
-	 */
876
-	public function deleteAllSharesByUser($principaluri) {
877
-		$this->calendarSharingBackend->deleteAllSharesByUser($principaluri);
878
-	}
879
-
880
-	/**
881
-	 * Returns all calendar objects within a calendar.
882
-	 *
883
-	 * Every item contains an array with the following keys:
884
-	 *   * calendardata - The iCalendar-compatible calendar data
885
-	 *   * uri - a unique key which will be used to construct the uri. This can
886
-	 *     be any arbitrary string, but making sure it ends with '.ics' is a
887
-	 *     good idea. This is only the basename, or filename, not the full
888
-	 *     path.
889
-	 *   * lastmodified - a timestamp of the last modification time
890
-	 *   * etag - An arbitrary string, surrounded by double-quotes. (e.g.:
891
-	 *   '"abcdef"')
892
-	 *   * size - The size of the calendar objects, in bytes.
893
-	 *   * component - optional, a string containing the type of object, such
894
-	 *     as 'vevent' or 'vtodo'. If specified, this will be used to populate
895
-	 *     the Content-Type header.
896
-	 *
897
-	 * Note that the etag is optional, but it's highly encouraged to return for
898
-	 * speed reasons.
899
-	 *
900
-	 * The calendardata is also optional. If it's not returned
901
-	 * 'getCalendarObject' will be called later, which *is* expected to return
902
-	 * calendardata.
903
-	 *
904
-	 * If neither etag or size are specified, the calendardata will be
905
-	 * used/fetched to determine these numbers. If both are specified the
906
-	 * amount of times this is needed is reduced by a great degree.
907
-	 *
908
-	 * @param mixed $calendarId
909
-	 * @param int $calendarType
910
-	 * @return array
911
-	 */
912
-	public function getCalendarObjects($calendarId, $calendarType=self::CALENDAR_TYPE_CALENDAR):array {
913
-		$query = $this->db->getQueryBuilder();
914
-		$query->select(['id', 'uri', 'lastmodified', 'etag', 'calendarid', 'size', 'componenttype', 'classification'])
915
-			->from('calendarobjects')
916
-			->where($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)))
917
-			->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter($calendarType)));
918
-		$stmt = $query->execute();
919
-
920
-		$result = [];
921
-		foreach ($stmt->fetchAll(\PDO::FETCH_ASSOC) as $row) {
922
-			$result[] = [
923
-				'id'           => $row['id'],
924
-				'uri'          => $row['uri'],
925
-				'lastmodified' => $row['lastmodified'],
926
-				'etag'         => '"' . $row['etag'] . '"',
927
-				'calendarid'   => $row['calendarid'],
928
-				'size'         => (int)$row['size'],
929
-				'component'    => strtolower($row['componenttype']),
930
-				'classification'=> (int)$row['classification']
931
-			];
932
-		}
933
-
934
-		return $result;
935
-	}
936
-
937
-	/**
938
-	 * Returns information from a single calendar object, based on it's object
939
-	 * uri.
940
-	 *
941
-	 * The object uri is only the basename, or filename and not a full path.
942
-	 *
943
-	 * The returned array must have the same keys as getCalendarObjects. The
944
-	 * 'calendardata' object is required here though, while it's not required
945
-	 * for getCalendarObjects.
946
-	 *
947
-	 * This method must return null if the object did not exist.
948
-	 *
949
-	 * @param mixed $calendarId
950
-	 * @param string $objectUri
951
-	 * @param int $calendarType
952
-	 * @return array|null
953
-	 */
954
-	public function getCalendarObject($calendarId, $objectUri, $calendarType=self::CALENDAR_TYPE_CALENDAR) {
955
-		$query = $this->db->getQueryBuilder();
956
-		$query->select(['id', 'uri', 'lastmodified', 'etag', 'calendarid', 'size', 'calendardata', 'componenttype', 'classification'])
957
-			->from('calendarobjects')
958
-			->where($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)))
959
-			->andWhere($query->expr()->eq('uri', $query->createNamedParameter($objectUri)))
960
-			->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter($calendarType)));
961
-		$stmt = $query->execute();
962
-		$row = $stmt->fetch(\PDO::FETCH_ASSOC);
963
-
964
-		if (!$row) {
965
-			return null;
966
-		}
967
-
968
-		return [
969
-			'id'            => $row['id'],
970
-			'uri'           => $row['uri'],
971
-			'lastmodified'  => $row['lastmodified'],
972
-			'etag'          => '"' . $row['etag'] . '"',
973
-			'calendarid'    => $row['calendarid'],
974
-			'size'          => (int)$row['size'],
975
-			'calendardata'  => $this->readBlob($row['calendardata']),
976
-			'component'     => strtolower($row['componenttype']),
977
-			'classification'=> (int)$row['classification']
978
-		];
979
-	}
980
-
981
-	/**
982
-	 * Returns a list of calendar objects.
983
-	 *
984
-	 * This method should work identical to getCalendarObject, but instead
985
-	 * return all the calendar objects in the list as an array.
986
-	 *
987
-	 * If the backend supports this, it may allow for some speed-ups.
988
-	 *
989
-	 * @param mixed $calendarId
990
-	 * @param string[] $uris
991
-	 * @param int $calendarType
992
-	 * @return array
993
-	 */
994
-	public function getMultipleCalendarObjects($calendarId, array $uris, $calendarType=self::CALENDAR_TYPE_CALENDAR):array {
995
-		if (empty($uris)) {
996
-			return [];
997
-		}
998
-
999
-		$chunks = array_chunk($uris, 100);
1000
-		$objects = [];
1001
-
1002
-		$query = $this->db->getQueryBuilder();
1003
-		$query->select(['id', 'uri', 'lastmodified', 'etag', 'calendarid', 'size', 'calendardata', 'componenttype', 'classification'])
1004
-			->from('calendarobjects')
1005
-			->where($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)))
1006
-			->andWhere($query->expr()->in('uri', $query->createParameter('uri')))
1007
-			->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter($calendarType)));
1008
-
1009
-		foreach ($chunks as $uris) {
1010
-			$query->setParameter('uri', $uris, IQueryBuilder::PARAM_STR_ARRAY);
1011
-			$result = $query->execute();
1012
-
1013
-			while ($row = $result->fetch()) {
1014
-				$objects[] = [
1015
-					'id'           => $row['id'],
1016
-					'uri'          => $row['uri'],
1017
-					'lastmodified' => $row['lastmodified'],
1018
-					'etag'         => '"' . $row['etag'] . '"',
1019
-					'calendarid'   => $row['calendarid'],
1020
-					'size'         => (int)$row['size'],
1021
-					'calendardata' => $this->readBlob($row['calendardata']),
1022
-					'component'    => strtolower($row['componenttype']),
1023
-					'classification' => (int)$row['classification']
1024
-				];
1025
-			}
1026
-			$result->closeCursor();
1027
-		}
1028
-
1029
-		return $objects;
1030
-	}
1031
-
1032
-	/**
1033
-	 * Creates a new calendar object.
1034
-	 *
1035
-	 * The object uri is only the basename, or filename and not a full path.
1036
-	 *
1037
-	 * It is possible return an etag from this function, which will be used in
1038
-	 * the response to this PUT request. Note that the ETag must be surrounded
1039
-	 * by double-quotes.
1040
-	 *
1041
-	 * However, you should only really return this ETag if you don't mangle the
1042
-	 * calendar-data. If the result of a subsequent GET to this object is not
1043
-	 * the exact same as this request body, you should omit the ETag.
1044
-	 *
1045
-	 * @param mixed $calendarId
1046
-	 * @param string $objectUri
1047
-	 * @param string $calendarData
1048
-	 * @param int $calendarType
1049
-	 * @return string
1050
-	 */
1051
-	public function createCalendarObject($calendarId, $objectUri, $calendarData, $calendarType=self::CALENDAR_TYPE_CALENDAR) {
1052
-		$extraData = $this->getDenormalizedData($calendarData);
1053
-
1054
-		$q = $this->db->getQueryBuilder();
1055
-		$q->select($q->func()->count('*'))
1056
-			->from('calendarobjects')
1057
-			->where($q->expr()->eq('calendarid', $q->createNamedParameter($calendarId)))
1058
-			->andWhere($q->expr()->eq('uid', $q->createNamedParameter($extraData['uid'])))
1059
-			->andWhere($q->expr()->eq('calendartype', $q->createNamedParameter($calendarType)));
1060
-
1061
-		$result = $q->execute();
1062
-		$count = (int) $result->fetchColumn();
1063
-		$result->closeCursor();
1064
-
1065
-		if ($count !== 0) {
1066
-			throw new \Sabre\DAV\Exception\BadRequest('Calendar object with uid already exists in this calendar collection.');
1067
-		}
1068
-
1069
-		$query = $this->db->getQueryBuilder();
1070
-		$query->insert('calendarobjects')
1071
-			->values([
1072
-				'calendarid' => $query->createNamedParameter($calendarId),
1073
-				'uri' => $query->createNamedParameter($objectUri),
1074
-				'calendardata' => $query->createNamedParameter($calendarData, IQueryBuilder::PARAM_LOB),
1075
-				'lastmodified' => $query->createNamedParameter(time()),
1076
-				'etag' => $query->createNamedParameter($extraData['etag']),
1077
-				'size' => $query->createNamedParameter($extraData['size']),
1078
-				'componenttype' => $query->createNamedParameter($extraData['componentType']),
1079
-				'firstoccurence' => $query->createNamedParameter($extraData['firstOccurence']),
1080
-				'lastoccurence' => $query->createNamedParameter($extraData['lastOccurence']),
1081
-				'classification' => $query->createNamedParameter($extraData['classification']),
1082
-				'uid' => $query->createNamedParameter($extraData['uid']),
1083
-				'calendartype' => $query->createNamedParameter($calendarType),
1084
-			])
1085
-			->execute();
1086
-
1087
-		$this->updateProperties($calendarId, $objectUri, $calendarData, $calendarType);
1088
-
1089
-		if ($calendarType === self::CALENDAR_TYPE_CALENDAR) {
1090
-			$this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::createCalendarObject', new GenericEvent(
1091
-				'\OCA\DAV\CalDAV\CalDavBackend::createCalendarObject',
1092
-				[
1093
-					'calendarId' => $calendarId,
1094
-					'calendarData' => $this->getCalendarById($calendarId),
1095
-					'shares' => $this->getShares($calendarId),
1096
-					'objectData' => $this->getCalendarObject($calendarId, $objectUri),
1097
-				]
1098
-			));
1099
-		} else {
1100
-			$this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::createCachedCalendarObject', new GenericEvent(
1101
-				'\OCA\DAV\CalDAV\CalDavBackend::createCachedCalendarObject',
1102
-				[
1103
-					'subscriptionId' => $calendarId,
1104
-					'calendarData' => $this->getCalendarById($calendarId),
1105
-					'shares' => $this->getShares($calendarId),
1106
-					'objectData' => $this->getCalendarObject($calendarId, $objectUri),
1107
-				]
1108
-			));
1109
-		}
1110
-		$this->addChange($calendarId, $objectUri, 1, $calendarType);
1111
-
1112
-		return '"' . $extraData['etag'] . '"';
1113
-	}
1114
-
1115
-	/**
1116
-	 * Updates an existing calendarobject, based on it's uri.
1117
-	 *
1118
-	 * The object uri is only the basename, or filename and not a full path.
1119
-	 *
1120
-	 * It is possible return an etag from this function, which will be used in
1121
-	 * the response to this PUT request. Note that the ETag must be surrounded
1122
-	 * by double-quotes.
1123
-	 *
1124
-	 * However, you should only really return this ETag if you don't mangle the
1125
-	 * calendar-data. If the result of a subsequent GET to this object is not
1126
-	 * the exact same as this request body, you should omit the ETag.
1127
-	 *
1128
-	 * @param mixed $calendarId
1129
-	 * @param string $objectUri
1130
-	 * @param string $calendarData
1131
-	 * @param int $calendarType
1132
-	 * @return string
1133
-	 */
1134
-	public function updateCalendarObject($calendarId, $objectUri, $calendarData, $calendarType=self::CALENDAR_TYPE_CALENDAR) {
1135
-		$extraData = $this->getDenormalizedData($calendarData);
1136
-		$query = $this->db->getQueryBuilder();
1137
-		$query->update('calendarobjects')
1138
-				->set('calendardata', $query->createNamedParameter($calendarData, IQueryBuilder::PARAM_LOB))
1139
-				->set('lastmodified', $query->createNamedParameter(time()))
1140
-				->set('etag', $query->createNamedParameter($extraData['etag']))
1141
-				->set('size', $query->createNamedParameter($extraData['size']))
1142
-				->set('componenttype', $query->createNamedParameter($extraData['componentType']))
1143
-				->set('firstoccurence', $query->createNamedParameter($extraData['firstOccurence']))
1144
-				->set('lastoccurence', $query->createNamedParameter($extraData['lastOccurence']))
1145
-				->set('classification', $query->createNamedParameter($extraData['classification']))
1146
-				->set('uid', $query->createNamedParameter($extraData['uid']))
1147
-			->where($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)))
1148
-			->andWhere($query->expr()->eq('uri', $query->createNamedParameter($objectUri)))
1149
-			->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter($calendarType)))
1150
-			->execute();
1151
-
1152
-		$this->updateProperties($calendarId, $objectUri, $calendarData, $calendarType);
1153
-
1154
-		$data = $this->getCalendarObject($calendarId, $objectUri);
1155
-		if (is_array($data)) {
1156
-			if ($calendarType === self::CALENDAR_TYPE_CALENDAR) {
1157
-				$this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::updateCalendarObject', new GenericEvent(
1158
-					'\OCA\DAV\CalDAV\CalDavBackend::updateCalendarObject',
1159
-					[
1160
-						'calendarId' => $calendarId,
1161
-						'calendarData' => $this->getCalendarById($calendarId),
1162
-						'shares' => $this->getShares($calendarId),
1163
-						'objectData' => $data,
1164
-					]
1165
-				));
1166
-			} else {
1167
-				$this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::updateCachedCalendarObject', new GenericEvent(
1168
-					'\OCA\DAV\CalDAV\CalDavBackend::updateCachedCalendarObject',
1169
-					[
1170
-						'subscriptionId' => $calendarId,
1171
-						'calendarData' => $this->getCalendarById($calendarId),
1172
-						'shares' => $this->getShares($calendarId),
1173
-						'objectData' => $data,
1174
-					]
1175
-				));
1176
-			}
1177
-		}
1178
-		$this->addChange($calendarId, $objectUri, 2, $calendarType);
1179
-
1180
-		return '"' . $extraData['etag'] . '"';
1181
-	}
1182
-
1183
-	/**
1184
-	 * @param int $calendarObjectId
1185
-	 * @param int $classification
1186
-	 */
1187
-	public function setClassification($calendarObjectId, $classification) {
1188
-		if (!in_array($classification, [
1189
-			self::CLASSIFICATION_PUBLIC, self::CLASSIFICATION_PRIVATE, self::CLASSIFICATION_CONFIDENTIAL
1190
-		])) {
1191
-			throw new \InvalidArgumentException();
1192
-		}
1193
-		$query = $this->db->getQueryBuilder();
1194
-		$query->update('calendarobjects')
1195
-			->set('classification', $query->createNamedParameter($classification))
1196
-			->where($query->expr()->eq('id', $query->createNamedParameter($calendarObjectId)))
1197
-			->execute();
1198
-	}
1199
-
1200
-	/**
1201
-	 * Deletes an existing calendar object.
1202
-	 *
1203
-	 * The object uri is only the basename, or filename and not a full path.
1204
-	 *
1205
-	 * @param mixed $calendarId
1206
-	 * @param string $objectUri
1207
-	 * @param int $calendarType
1208
-	 * @return void
1209
-	 */
1210
-	public function deleteCalendarObject($calendarId, $objectUri, $calendarType=self::CALENDAR_TYPE_CALENDAR) {
1211
-		$data = $this->getCalendarObject($calendarId, $objectUri, $calendarType);
1212
-		if (is_array($data)) {
1213
-			if ($calendarType === self::CALENDAR_TYPE_CALENDAR) {
1214
-				$this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::deleteCalendarObject', new GenericEvent(
1215
-					'\OCA\DAV\CalDAV\CalDavBackend::deleteCalendarObject',
1216
-					[
1217
-						'calendarId' => $calendarId,
1218
-						'calendarData' => $this->getCalendarById($calendarId),
1219
-						'shares' => $this->getShares($calendarId),
1220
-						'objectData' => $data,
1221
-					]
1222
-				));
1223
-			} else {
1224
-				$this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::deleteCachedCalendarObject', new GenericEvent(
1225
-					'\OCA\DAV\CalDAV\CalDavBackend::deleteCachedCalendarObject',
1226
-					[
1227
-						'subscriptionId' => $calendarId,
1228
-						'calendarData' => $this->getCalendarById($calendarId),
1229
-						'shares' => $this->getShares($calendarId),
1230
-						'objectData' => $data,
1231
-					]
1232
-				));
1233
-			}
1234
-		}
1235
-
1236
-		$stmt = $this->db->prepare('DELETE FROM `*PREFIX*calendarobjects` WHERE `calendarid` = ? AND `uri` = ? AND `calendartype` = ?');
1237
-		$stmt->execute([$calendarId, $objectUri, $calendarType]);
1238
-
1239
-		if (is_array($data)) {
1240
-			$this->purgeProperties($calendarId, $data['id'], $calendarType);
1241
-		}
1242
-
1243
-		$this->addChange($calendarId, $objectUri, 3, $calendarType);
1244
-	}
1245
-
1246
-	/**
1247
-	 * Performs a calendar-query on the contents of this calendar.
1248
-	 *
1249
-	 * The calendar-query is defined in RFC4791 : CalDAV. Using the
1250
-	 * calendar-query it is possible for a client to request a specific set of
1251
-	 * object, based on contents of iCalendar properties, date-ranges and
1252
-	 * iCalendar component types (VTODO, VEVENT).
1253
-	 *
1254
-	 * This method should just return a list of (relative) urls that match this
1255
-	 * query.
1256
-	 *
1257
-	 * The list of filters are specified as an array. The exact array is
1258
-	 * documented by Sabre\CalDAV\CalendarQueryParser.
1259
-	 *
1260
-	 * Note that it is extremely likely that getCalendarObject for every path
1261
-	 * returned from this method will be called almost immediately after. You
1262
-	 * may want to anticipate this to speed up these requests.
1263
-	 *
1264
-	 * This method provides a default implementation, which parses *all* the
1265
-	 * iCalendar objects in the specified calendar.
1266
-	 *
1267
-	 * This default may well be good enough for personal use, and calendars
1268
-	 * that aren't very large. But if you anticipate high usage, big calendars
1269
-	 * or high loads, you are strongly advised to optimize certain paths.
1270
-	 *
1271
-	 * The best way to do so is override this method and to optimize
1272
-	 * specifically for 'common filters'.
1273
-	 *
1274
-	 * Requests that are extremely common are:
1275
-	 *   * requests for just VEVENTS
1276
-	 *   * requests for just VTODO
1277
-	 *   * requests with a time-range-filter on either VEVENT or VTODO.
1278
-	 *
1279
-	 * ..and combinations of these requests. It may not be worth it to try to
1280
-	 * handle every possible situation and just rely on the (relatively
1281
-	 * easy to use) CalendarQueryValidator to handle the rest.
1282
-	 *
1283
-	 * Note that especially time-range-filters may be difficult to parse. A
1284
-	 * time-range filter specified on a VEVENT must for instance also handle
1285
-	 * recurrence rules correctly.
1286
-	 * A good example of how to interprete all these filters can also simply
1287
-	 * be found in Sabre\CalDAV\CalendarQueryFilter. This class is as correct
1288
-	 * as possible, so it gives you a good idea on what type of stuff you need
1289
-	 * to think of.
1290
-	 *
1291
-	 * @param mixed $calendarId
1292
-	 * @param array $filters
1293
-	 * @param int $calendarType
1294
-	 * @return array
1295
-	 */
1296
-	public function calendarQuery($calendarId, array $filters, $calendarType=self::CALENDAR_TYPE_CALENDAR):array {
1297
-		$componentType = null;
1298
-		$requirePostFilter = true;
1299
-		$timeRange = null;
1300
-
1301
-		// if no filters were specified, we don't need to filter after a query
1302
-		if (!$filters['prop-filters'] && !$filters['comp-filters']) {
1303
-			$requirePostFilter = false;
1304
-		}
1305
-
1306
-		// Figuring out if there's a component filter
1307
-		if (count($filters['comp-filters']) > 0 && !$filters['comp-filters'][0]['is-not-defined']) {
1308
-			$componentType = $filters['comp-filters'][0]['name'];
1309
-
1310
-			// Checking if we need post-filters
1311
-			if (!$filters['prop-filters'] && !$filters['comp-filters'][0]['comp-filters'] && !$filters['comp-filters'][0]['time-range'] && !$filters['comp-filters'][0]['prop-filters']) {
1312
-				$requirePostFilter = false;
1313
-			}
1314
-			// There was a time-range filter
1315
-			if ($componentType === 'VEVENT' && isset($filters['comp-filters'][0]['time-range'])) {
1316
-				$timeRange = $filters['comp-filters'][0]['time-range'];
1317
-
1318
-				// If start time OR the end time is not specified, we can do a
1319
-				// 100% accurate mysql query.
1320
-				if (!$filters['prop-filters'] && !$filters['comp-filters'][0]['comp-filters'] && !$filters['comp-filters'][0]['prop-filters'] && (!$timeRange['start'] || !$timeRange['end'])) {
1321
-					$requirePostFilter = false;
1322
-				}
1323
-			}
1324
-		}
1325
-		$columns = ['uri'];
1326
-		if ($requirePostFilter) {
1327
-			$columns = ['uri', 'calendardata'];
1328
-		}
1329
-		$query = $this->db->getQueryBuilder();
1330
-		$query->select($columns)
1331
-			->from('calendarobjects')
1332
-			->where($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)))
1333
-			->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter($calendarType)));
1334
-
1335
-		if ($componentType) {
1336
-			$query->andWhere($query->expr()->eq('componenttype', $query->createNamedParameter($componentType)));
1337
-		}
1338
-
1339
-		if ($timeRange && $timeRange['start']) {
1340
-			$query->andWhere($query->expr()->gt('lastoccurence', $query->createNamedParameter($timeRange['start']->getTimeStamp())));
1341
-		}
1342
-		if ($timeRange && $timeRange['end']) {
1343
-			$query->andWhere($query->expr()->lt('firstoccurence', $query->createNamedParameter($timeRange['end']->getTimeStamp())));
1344
-		}
1345
-
1346
-		$stmt = $query->execute();
1347
-
1348
-		$result = [];
1349
-		while ($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1350
-			if ($requirePostFilter) {
1351
-				// validateFilterForObject will parse the calendar data
1352
-				// catch parsing errors
1353
-				try {
1354
-					$matches = $this->validateFilterForObject($row, $filters);
1355
-				} catch (ParseException $ex) {
1356
-					$this->logger->logException($ex, [
1357
-						'app' => 'dav',
1358
-						'message' => 'Caught parsing exception for calendar data. This usually indicates invalid calendar data. calendar-id:'.$calendarId.' uri:'.$row['uri']
1359
-					]);
1360
-					continue;
1361
-				} catch (InvalidDataException $ex) {
1362
-					$this->logger->logException($ex, [
1363
-						'app' => 'dav',
1364
-						'message' => 'Caught invalid data exception for calendar data. This usually indicates invalid calendar data. calendar-id:'.$calendarId.' uri:'.$row['uri']
1365
-					]);
1366
-					continue;
1367
-				}
1368
-
1369
-				if (!$matches) {
1370
-					continue;
1371
-				}
1372
-			}
1373
-			$result[] = $row['uri'];
1374
-		}
1375
-
1376
-		return $result;
1377
-	}
1378
-
1379
-	/**
1380
-	 * custom Nextcloud search extension for CalDAV
1381
-	 *
1382
-	 * TODO - this should optionally cover cached calendar objects as well
1383
-	 *
1384
-	 * @param string $principalUri
1385
-	 * @param array $filters
1386
-	 * @param integer|null $limit
1387
-	 * @param integer|null $offset
1388
-	 * @return array
1389
-	 */
1390
-	public function calendarSearch($principalUri, array $filters, $limit=null, $offset=null) {
1391
-		$calendars = $this->getCalendarsForUser($principalUri);
1392
-		$ownCalendars = [];
1393
-		$sharedCalendars = [];
1394
-
1395
-		$uriMapper = [];
1396
-
1397
-		foreach ($calendars as $calendar) {
1398
-			if ($calendar['{http://owncloud.org/ns}owner-principal'] === $principalUri) {
1399
-				$ownCalendars[] = $calendar['id'];
1400
-			} else {
1401
-				$sharedCalendars[] = $calendar['id'];
1402
-			}
1403
-			$uriMapper[$calendar['id']] = $calendar['uri'];
1404
-		}
1405
-		if (count($ownCalendars) === 0 && count($sharedCalendars) === 0) {
1406
-			return [];
1407
-		}
1408
-
1409
-		$query = $this->db->getQueryBuilder();
1410
-		// Calendar id expressions
1411
-		$calendarExpressions = [];
1412
-		foreach ($ownCalendars as $id) {
1413
-			$calendarExpressions[] = $query->expr()->andX(
1414
-				$query->expr()->eq('c.calendarid',
1415
-					$query->createNamedParameter($id)),
1416
-				$query->expr()->eq('c.calendartype',
1417
-						$query->createNamedParameter(self::CALENDAR_TYPE_CALENDAR)));
1418
-		}
1419
-		foreach ($sharedCalendars as $id) {
1420
-			$calendarExpressions[] = $query->expr()->andX(
1421
-				$query->expr()->eq('c.calendarid',
1422
-					$query->createNamedParameter($id)),
1423
-				$query->expr()->eq('c.classification',
1424
-					$query->createNamedParameter(self::CLASSIFICATION_PUBLIC)),
1425
-				$query->expr()->eq('c.calendartype',
1426
-					$query->createNamedParameter(self::CALENDAR_TYPE_CALENDAR)));
1427
-		}
1428
-
1429
-		if (count($calendarExpressions) === 1) {
1430
-			$calExpr = $calendarExpressions[0];
1431
-		} else {
1432
-			$calExpr = call_user_func_array([$query->expr(), 'orX'], $calendarExpressions);
1433
-		}
1434
-
1435
-		// Component expressions
1436
-		$compExpressions = [];
1437
-		foreach ($filters['comps'] as $comp) {
1438
-			$compExpressions[] = $query->expr()
1439
-				->eq('c.componenttype', $query->createNamedParameter($comp));
1440
-		}
1441
-
1442
-		if (count($compExpressions) === 1) {
1443
-			$compExpr = $compExpressions[0];
1444
-		} else {
1445
-			$compExpr = call_user_func_array([$query->expr(), 'orX'], $compExpressions);
1446
-		}
1447
-
1448
-		if (!isset($filters['props'])) {
1449
-			$filters['props'] = [];
1450
-		}
1451
-		if (!isset($filters['params'])) {
1452
-			$filters['params'] = [];
1453
-		}
1454
-
1455
-		$propParamExpressions = [];
1456
-		foreach ($filters['props'] as $prop) {
1457
-			$propParamExpressions[] = $query->expr()->andX(
1458
-				$query->expr()->eq('i.name', $query->createNamedParameter($prop)),
1459
-				$query->expr()->isNull('i.parameter')
1460
-			);
1461
-		}
1462
-		foreach ($filters['params'] as $param) {
1463
-			$propParamExpressions[] = $query->expr()->andX(
1464
-				$query->expr()->eq('i.name', $query->createNamedParameter($param['property'])),
1465
-				$query->expr()->eq('i.parameter', $query->createNamedParameter($param['parameter']))
1466
-			);
1467
-		}
1468
-
1469
-		if (count($propParamExpressions) === 1) {
1470
-			$propParamExpr = $propParamExpressions[0];
1471
-		} else {
1472
-			$propParamExpr = call_user_func_array([$query->expr(), 'orX'], $propParamExpressions);
1473
-		}
1474
-
1475
-		$query->select(['c.calendarid', 'c.uri'])
1476
-			->from($this->dbObjectPropertiesTable, 'i')
1477
-			->join('i', 'calendarobjects', 'c', $query->expr()->eq('i.objectid', 'c.id'))
1478
-			->where($calExpr)
1479
-			->andWhere($compExpr)
1480
-			->andWhere($propParamExpr)
1481
-			->andWhere($query->expr()->iLike('i.value',
1482
-				$query->createNamedParameter('%'.$this->db->escapeLikeParameter($filters['search-term']).'%')));
1483
-
1484
-		if ($offset) {
1485
-			$query->setFirstResult($offset);
1486
-		}
1487
-		if ($limit) {
1488
-			$query->setMaxResults($limit);
1489
-		}
1490
-
1491
-		$stmt = $query->execute();
1492
-
1493
-		$result = [];
1494
-		while ($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1495
-			$path = $uriMapper[$row['calendarid']] . '/' . $row['uri'];
1496
-			if (!in_array($path, $result)) {
1497
-				$result[] = $path;
1498
-			}
1499
-		}
1500
-
1501
-		return $result;
1502
-	}
1503
-
1504
-	/**
1505
-	 * used for Nextcloud's calendar API
1506
-	 *
1507
-	 * @param array $calendarInfo
1508
-	 * @param string $pattern
1509
-	 * @param array $searchProperties
1510
-	 * @param array $options
1511
-	 * @param integer|null $limit
1512
-	 * @param integer|null $offset
1513
-	 *
1514
-	 * @return array
1515
-	 */
1516
-	public function search(array $calendarInfo, $pattern, array $searchProperties,
1517
-						   array $options, $limit, $offset) {
1518
-		$outerQuery = $this->db->getQueryBuilder();
1519
-		$innerQuery = $this->db->getQueryBuilder();
1520
-
1521
-		$innerQuery->selectDistinct('op.objectid')
1522
-			->from($this->dbObjectPropertiesTable, 'op')
1523
-			->andWhere($innerQuery->expr()->eq('op.calendarid',
1524
-				$outerQuery->createNamedParameter($calendarInfo['id'])))
1525
-			->andWhere($innerQuery->expr()->eq('op.calendartype',
1526
-				$outerQuery->createNamedParameter(self::CALENDAR_TYPE_CALENDAR)));
1527
-
1528
-		// only return public items for shared calendars for now
1529
-		if ($calendarInfo['principaluri'] !== $calendarInfo['{http://owncloud.org/ns}owner-principal']) {
1530
-			$innerQuery->andWhere($innerQuery->expr()->eq('c.classification',
1531
-				$outerQuery->createNamedParameter(self::CLASSIFICATION_PUBLIC)));
1532
-		}
1533
-
1534
-		$or = $innerQuery->expr()->orX();
1535
-		foreach ($searchProperties as $searchProperty) {
1536
-			$or->add($innerQuery->expr()->eq('op.name',
1537
-				$outerQuery->createNamedParameter($searchProperty)));
1538
-		}
1539
-		$innerQuery->andWhere($or);
1540
-
1541
-		if ($pattern !== '') {
1542
-			$innerQuery->andWhere($innerQuery->expr()->iLike('op.value',
1543
-				$outerQuery->createNamedParameter('%' .
1544
-					$this->db->escapeLikeParameter($pattern) . '%')));
1545
-		}
1546
-
1547
-		$outerQuery->select('c.id', 'c.calendardata', 'c.componenttype', 'c.uid', 'c.uri')
1548
-			->from('calendarobjects', 'c');
1549
-
1550
-		if (isset($options['timerange'])) {
1551
-			if (isset($options['timerange']['start']) && $options['timerange']['start'] instanceof DateTime) {
1552
-				$outerQuery->andWhere($outerQuery->expr()->gt('lastoccurence',
1553
-					$outerQuery->createNamedParameter($options['timerange']['start']->getTimeStamp())));
1554
-			}
1555
-			if (isset($options['timerange']['end']) && $options['timerange']['end'] instanceof DateTime) {
1556
-				$outerQuery->andWhere($outerQuery->expr()->lt('firstoccurence',
1557
-					$outerQuery->createNamedParameter($options['timerange']['end']->getTimeStamp())));
1558
-			}
1559
-		}
1560
-
1561
-		if (isset($options['types'])) {
1562
-			$or = $outerQuery->expr()->orX();
1563
-			foreach ($options['types'] as $type) {
1564
-				$or->add($outerQuery->expr()->eq('componenttype',
1565
-					$outerQuery->createNamedParameter($type)));
1566
-			}
1567
-			$outerQuery->andWhere($or);
1568
-		}
1569
-
1570
-		$outerQuery->andWhere($outerQuery->expr()->in('c.id',
1571
-			$outerQuery->createFunction($innerQuery->getSQL())));
1572
-
1573
-		if ($offset) {
1574
-			$outerQuery->setFirstResult($offset);
1575
-		}
1576
-		if ($limit) {
1577
-			$outerQuery->setMaxResults($limit);
1578
-		}
1579
-
1580
-		$result = $outerQuery->execute();
1581
-		$calendarObjects = $result->fetchAll();
1582
-
1583
-		return array_map(function ($o) {
1584
-			$calendarData = Reader::read($o['calendardata']);
1585
-			$comps = $calendarData->getComponents();
1586
-			$objects = [];
1587
-			$timezones = [];
1588
-			foreach ($comps as $comp) {
1589
-				if ($comp instanceof VTimeZone) {
1590
-					$timezones[] = $comp;
1591
-				} else {
1592
-					$objects[] = $comp;
1593
-				}
1594
-			}
1595
-
1596
-			return [
1597
-				'id' => $o['id'],
1598
-				'type' => $o['componenttype'],
1599
-				'uid' => $o['uid'],
1600
-				'uri' => $o['uri'],
1601
-				'objects' => array_map(function ($c) {
1602
-					return $this->transformSearchData($c);
1603
-				}, $objects),
1604
-				'timezones' => array_map(function ($c) {
1605
-					return $this->transformSearchData($c);
1606
-				}, $timezones),
1607
-			];
1608
-		}, $calendarObjects);
1609
-	}
1610
-
1611
-	/**
1612
-	 * @param Component $comp
1613
-	 * @return array
1614
-	 */
1615
-	private function transformSearchData(Component $comp) {
1616
-		$data = [];
1617
-		/** @var Component[] $subComponents */
1618
-		$subComponents = $comp->getComponents();
1619
-		/** @var Property[] $properties */
1620
-		$properties = array_filter($comp->children(), function ($c) {
1621
-			return $c instanceof Property;
1622
-		});
1623
-		$validationRules = $comp->getValidationRules();
1624
-
1625
-		foreach ($subComponents as $subComponent) {
1626
-			$name = $subComponent->name;
1627
-			if (!isset($data[$name])) {
1628
-				$data[$name] = [];
1629
-			}
1630
-			$data[$name][] = $this->transformSearchData($subComponent);
1631
-		}
1632
-
1633
-		foreach ($properties as $property) {
1634
-			$name = $property->name;
1635
-			if (!isset($validationRules[$name])) {
1636
-				$validationRules[$name] = '*';
1637
-			}
1638
-
1639
-			$rule = $validationRules[$property->name];
1640
-			if ($rule === '+' || $rule === '*') { // multiple
1641
-				if (!isset($data[$name])) {
1642
-					$data[$name] = [];
1643
-				}
1644
-
1645
-				$data[$name][] = $this->transformSearchProperty($property);
1646
-			} else { // once
1647
-				$data[$name] = $this->transformSearchProperty($property);
1648
-			}
1649
-		}
1650
-
1651
-		return $data;
1652
-	}
1653
-
1654
-	/**
1655
-	 * @param Property $prop
1656
-	 * @return array
1657
-	 */
1658
-	private function transformSearchProperty(Property $prop) {
1659
-		// No need to check Date, as it extends DateTime
1660
-		if ($prop instanceof Property\ICalendar\DateTime) {
1661
-			$value = $prop->getDateTime();
1662
-		} else {
1663
-			$value = $prop->getValue();
1664
-		}
1665
-
1666
-		return [
1667
-			$value,
1668
-			$prop->parameters()
1669
-		];
1670
-	}
1671
-
1672
-	/**
1673
-	 * @param string $principalUri
1674
-	 * @param string $pattern
1675
-	 * @param array $componentTypes
1676
-	 * @param array $searchProperties
1677
-	 * @param array $searchParameters
1678
-	 * @param array $options
1679
-	 * @return array
1680
-	 */
1681
-	public function searchPrincipalUri(string $principalUri,
1682
-									   string $pattern,
1683
-									   array $componentTypes,
1684
-									   array $searchProperties,
1685
-									   array $searchParameters,
1686
-									   array $options = []): array {
1687
-		$escapePattern = !\array_key_exists('escape_like_param', $options) || $options['escape_like_param'] !== false;
1688
-
1689
-		$calendarObjectIdQuery = $this->db->getQueryBuilder();
1690
-		$calendarOr = $calendarObjectIdQuery->expr()->orX();
1691
-		$searchOr = $calendarObjectIdQuery->expr()->orX();
1692
-
1693
-		// Fetch calendars and subscription
1694
-		$calendars = $this->getCalendarsForUser($principalUri);
1695
-		$subscriptions = $this->getSubscriptionsForUser($principalUri);
1696
-		foreach ($calendars as $calendar) {
1697
-			$calendarAnd = $calendarObjectIdQuery->expr()->andX();
1698
-			$calendarAnd->add($calendarObjectIdQuery->expr()->eq('cob.calendarid', $calendarObjectIdQuery->createNamedParameter((int)$calendar['id'])));
1699
-			$calendarAnd->add($calendarObjectIdQuery->expr()->eq('cob.calendartype', $calendarObjectIdQuery->createNamedParameter(self::CALENDAR_TYPE_CALENDAR)));
1700
-
1701
-			// If it's shared, limit search to public events
1702
-			if ($calendar['principaluri'] !== $calendar['{http://owncloud.org/ns}owner-principal']) {
1703
-				$calendarAnd->add($calendarObjectIdQuery->expr()->eq('co.classification', $calendarObjectIdQuery->createNamedParameter(self::CLASSIFICATION_PUBLIC)));
1704
-			}
1705
-
1706
-			$calendarOr->add($calendarAnd);
1707
-		}
1708
-		foreach ($subscriptions as $subscription) {
1709
-			$subscriptionAnd = $calendarObjectIdQuery->expr()->andX();
1710
-			$subscriptionAnd->add($calendarObjectIdQuery->expr()->eq('cob.calendarid', $calendarObjectIdQuery->createNamedParameter((int)$subscription['id'])));
1711
-			$subscriptionAnd->add($calendarObjectIdQuery->expr()->eq('cob.calendartype', $calendarObjectIdQuery->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)));
1712
-
1713
-			// If it's shared, limit search to public events
1714
-			if ($subscription['principaluri'] !== $subscription['{http://owncloud.org/ns}owner-principal']) {
1715
-				$subscriptionAnd->add($calendarObjectIdQuery->expr()->eq('co.classification', $calendarObjectIdQuery->createNamedParameter(self::CLASSIFICATION_PUBLIC)));
1716
-			}
1717
-
1718
-			$calendarOr->add($subscriptionAnd);
1719
-		}
1720
-
1721
-		foreach ($searchProperties as $property) {
1722
-			$propertyAnd = $calendarObjectIdQuery->expr()->andX();
1723
-			$propertyAnd->add($calendarObjectIdQuery->expr()->eq('cob.name', $calendarObjectIdQuery->createNamedParameter($property, IQueryBuilder::PARAM_STR)));
1724
-			$propertyAnd->add($calendarObjectIdQuery->expr()->isNull('cob.parameter'));
1725
-
1726
-			$searchOr->add($propertyAnd);
1727
-		}
1728
-		foreach ($searchParameters as $property => $parameter) {
1729
-			$parameterAnd = $calendarObjectIdQuery->expr()->andX();
1730
-			$parameterAnd->add($calendarObjectIdQuery->expr()->eq('cob.name', $calendarObjectIdQuery->createNamedParameter($property, IQueryBuilder::PARAM_STR)));
1731
-			$parameterAnd->add($calendarObjectIdQuery->expr()->eq('cob.parameter', $calendarObjectIdQuery->createNamedParameter($parameter, IQueryBuilder::PARAM_STR)));
1732
-
1733
-			$searchOr->add($parameterAnd);
1734
-		}
1735
-
1736
-		if ($calendarOr->count() === 0) {
1737
-			return [];
1738
-		}
1739
-		if ($searchOr->count() === 0) {
1740
-			return [];
1741
-		}
1742
-
1743
-		$calendarObjectIdQuery->selectDistinct('cob.objectid')
1744
-			->from($this->dbObjectPropertiesTable, 'cob')
1745
-			->leftJoin('cob', 'calendarobjects', 'co', $calendarObjectIdQuery->expr()->eq('co.id', 'cob.objectid'))
1746
-			->andWhere($calendarObjectIdQuery->expr()->in('co.componenttype', $calendarObjectIdQuery->createNamedParameter($componentTypes, IQueryBuilder::PARAM_STR_ARRAY)))
1747
-			->andWhere($calendarOr)
1748
-			->andWhere($searchOr);
1749
-
1750
-		if ('' !== $pattern) {
1751
-			if (!$escapePattern) {
1752
-				$calendarObjectIdQuery->andWhere($calendarObjectIdQuery->expr()->ilike('cob.value', $calendarObjectIdQuery->createNamedParameter($pattern)));
1753
-			} else {
1754
-				$calendarObjectIdQuery->andWhere($calendarObjectIdQuery->expr()->ilike('cob.value', $calendarObjectIdQuery->createNamedParameter('%' . $this->db->escapeLikeParameter($pattern) . '%')));
1755
-			}
1756
-		}
1757
-
1758
-		if (isset($options['limit'])) {
1759
-			$calendarObjectIdQuery->setMaxResults($options['limit']);
1760
-		}
1761
-		if (isset($options['offset'])) {
1762
-			$calendarObjectIdQuery->setFirstResult($options['offset']);
1763
-		}
1764
-
1765
-		$result = $calendarObjectIdQuery->execute();
1766
-		$matches = $result->fetchAll();
1767
-		$result->closeCursor();
1768
-		$matches = array_map(static function (array $match):int {
1769
-			return (int) $match['objectid'];
1770
-		}, $matches);
1771
-
1772
-		$query = $this->db->getQueryBuilder();
1773
-		$query->select('calendardata', 'uri', 'calendarid', 'calendartype')
1774
-			->from('calendarobjects')
1775
-			->where($query->expr()->in('id', $query->createNamedParameter($matches, IQueryBuilder::PARAM_INT_ARRAY)));
1776
-
1777
-		$result = $query->execute();
1778
-		$calendarObjects = $result->fetchAll();
1779
-		$result->closeCursor();
1780
-
1781
-		return array_map(function (array $array): array {
1782
-			$array['calendarid'] = (int)$array['calendarid'];
1783
-			$array['calendartype'] = (int)$array['calendartype'];
1784
-			$array['calendardata'] = $this->readBlob($array['calendardata']);
1785
-
1786
-			return $array;
1787
-		}, $calendarObjects);
1788
-	}
1789
-
1790
-	/**
1791
-	 * Searches through all of a users calendars and calendar objects to find
1792
-	 * an object with a specific UID.
1793
-	 *
1794
-	 * This method should return the path to this object, relative to the
1795
-	 * calendar home, so this path usually only contains two parts:
1796
-	 *
1797
-	 * calendarpath/objectpath.ics
1798
-	 *
1799
-	 * If the uid is not found, return null.
1800
-	 *
1801
-	 * This method should only consider * objects that the principal owns, so
1802
-	 * any calendars owned by other principals that also appear in this
1803
-	 * collection should be ignored.
1804
-	 *
1805
-	 * @param string $principalUri
1806
-	 * @param string $uid
1807
-	 * @return string|null
1808
-	 */
1809
-	public function getCalendarObjectByUID($principalUri, $uid) {
1810
-		$query = $this->db->getQueryBuilder();
1811
-		$query->selectAlias('c.uri', 'calendaruri')->selectAlias('co.uri', 'objecturi')
1812
-			->from('calendarobjects', 'co')
1813
-			->leftJoin('co', 'calendars', 'c', $query->expr()->eq('co.calendarid', 'c.id'))
1814
-			->where($query->expr()->eq('c.principaluri', $query->createNamedParameter($principalUri)))
1815
-			->andWhere($query->expr()->eq('co.uid', $query->createNamedParameter($uid)));
1816
-
1817
-		$stmt = $query->execute();
1818
-
1819
-		if ($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1820
-			return $row['calendaruri'] . '/' . $row['objecturi'];
1821
-		}
1822
-
1823
-		return null;
1824
-	}
1825
-
1826
-	/**
1827
-	 * The getChanges method returns all the changes that have happened, since
1828
-	 * the specified syncToken in the specified calendar.
1829
-	 *
1830
-	 * This function should return an array, such as the following:
1831
-	 *
1832
-	 * [
1833
-	 *   'syncToken' => 'The current synctoken',
1834
-	 *   'added'   => [
1835
-	 *      'new.txt',
1836
-	 *   ],
1837
-	 *   'modified'   => [
1838
-	 *      'modified.txt',
1839
-	 *   ],
1840
-	 *   'deleted' => [
1841
-	 *      'foo.php.bak',
1842
-	 *      'old.txt'
1843
-	 *   ]
1844
-	 * );
1845
-	 *
1846
-	 * The returned syncToken property should reflect the *current* syncToken
1847
-	 * of the calendar, as reported in the {http://sabredav.org/ns}sync-token
1848
-	 * property This is * needed here too, to ensure the operation is atomic.
1849
-	 *
1850
-	 * If the $syncToken argument is specified as null, this is an initial
1851
-	 * sync, and all members should be reported.
1852
-	 *
1853
-	 * The modified property is an array of nodenames that have changed since
1854
-	 * the last token.
1855
-	 *
1856
-	 * The deleted property is an array with nodenames, that have been deleted
1857
-	 * from collection.
1858
-	 *
1859
-	 * The $syncLevel argument is basically the 'depth' of the report. If it's
1860
-	 * 1, you only have to report changes that happened only directly in
1861
-	 * immediate descendants. If it's 2, it should also include changes from
1862
-	 * the nodes below the child collections. (grandchildren)
1863
-	 *
1864
-	 * The $limit argument allows a client to specify how many results should
1865
-	 * be returned at most. If the limit is not specified, it should be treated
1866
-	 * as infinite.
1867
-	 *
1868
-	 * If the limit (infinite or not) is higher than you're willing to return,
1869
-	 * you should throw a Sabre\DAV\Exception\TooMuchMatches() exception.
1870
-	 *
1871
-	 * If the syncToken is expired (due to data cleanup) or unknown, you must
1872
-	 * return null.
1873
-	 *
1874
-	 * The limit is 'suggestive'. You are free to ignore it.
1875
-	 *
1876
-	 * @param string $calendarId
1877
-	 * @param string $syncToken
1878
-	 * @param int $syncLevel
1879
-	 * @param int $limit
1880
-	 * @param int $calendarType
1881
-	 * @return array
1882
-	 */
1883
-	public function getChangesForCalendar($calendarId, $syncToken, $syncLevel, $limit = null, $calendarType=self::CALENDAR_TYPE_CALENDAR) {
1884
-		// Current synctoken
1885
-		$stmt = $this->db->prepare('SELECT `synctoken` FROM `*PREFIX*calendars` WHERE `id` = ?');
1886
-		$stmt->execute([ $calendarId ]);
1887
-		$currentToken = $stmt->fetchColumn(0);
1888
-
1889
-		if (is_null($currentToken)) {
1890
-			return null;
1891
-		}
1892
-
1893
-		$result = [
1894
-			'syncToken' => $currentToken,
1895
-			'added'     => [],
1896
-			'modified'  => [],
1897
-			'deleted'   => [],
1898
-		];
1899
-
1900
-		if ($syncToken) {
1901
-			$query = "SELECT `uri`, `operation` FROM `*PREFIX*calendarchanges` WHERE `synctoken` >= ? AND `synctoken` < ? AND `calendarid` = ? AND `calendartype` = ? ORDER BY `synctoken`";
1902
-			if ($limit>0) {
1903
-				$query.= " LIMIT " . (int)$limit;
1904
-			}
1905
-
1906
-			// Fetching all changes
1907
-			$stmt = $this->db->prepare($query);
1908
-			$stmt->execute([$syncToken, $currentToken, $calendarId, $calendarType]);
1909
-
1910
-			$changes = [];
1911
-
1912
-			// This loop ensures that any duplicates are overwritten, only the
1913
-			// last change on a node is relevant.
1914
-			while ($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1915
-				$changes[$row['uri']] = $row['operation'];
1916
-			}
1917
-
1918
-			foreach ($changes as $uri => $operation) {
1919
-				switch ($operation) {
1920
-					case 1:
1921
-						$result['added'][] = $uri;
1922
-						break;
1923
-					case 2:
1924
-						$result['modified'][] = $uri;
1925
-						break;
1926
-					case 3:
1927
-						$result['deleted'][] = $uri;
1928
-						break;
1929
-				}
1930
-			}
1931
-		} else {
1932
-			// No synctoken supplied, this is the initial sync.
1933
-			$query = "SELECT `uri` FROM `*PREFIX*calendarobjects` WHERE `calendarid` = ? AND `calendartype` = ?";
1934
-			$stmt = $this->db->prepare($query);
1935
-			$stmt->execute([$calendarId, $calendarType]);
1936
-
1937
-			$result['added'] = $stmt->fetchAll(\PDO::FETCH_COLUMN);
1938
-		}
1939
-		return $result;
1940
-	}
1941
-
1942
-	/**
1943
-	 * Returns a list of subscriptions for a principal.
1944
-	 *
1945
-	 * Every subscription is an array with the following keys:
1946
-	 *  * id, a unique id that will be used by other functions to modify the
1947
-	 *    subscription. This can be the same as the uri or a database key.
1948
-	 *  * uri. This is just the 'base uri' or 'filename' of the subscription.
1949
-	 *  * principaluri. The owner of the subscription. Almost always the same as
1950
-	 *    principalUri passed to this method.
1951
-	 *
1952
-	 * Furthermore, all the subscription info must be returned too:
1953
-	 *
1954
-	 * 1. {DAV:}displayname
1955
-	 * 2. {http://apple.com/ns/ical/}refreshrate
1956
-	 * 3. {http://calendarserver.org/ns/}subscribed-strip-todos (omit if todos
1957
-	 *    should not be stripped).
1958
-	 * 4. {http://calendarserver.org/ns/}subscribed-strip-alarms (omit if alarms
1959
-	 *    should not be stripped).
1960
-	 * 5. {http://calendarserver.org/ns/}subscribed-strip-attachments (omit if
1961
-	 *    attachments should not be stripped).
1962
-	 * 6. {http://calendarserver.org/ns/}source (Must be a
1963
-	 *     Sabre\DAV\Property\Href).
1964
-	 * 7. {http://apple.com/ns/ical/}calendar-color
1965
-	 * 8. {http://apple.com/ns/ical/}calendar-order
1966
-	 * 9. {urn:ietf:params:xml:ns:caldav}supported-calendar-component-set
1967
-	 *    (should just be an instance of
1968
-	 *    Sabre\CalDAV\Property\SupportedCalendarComponentSet, with a bunch of
1969
-	 *    default components).
1970
-	 *
1971
-	 * @param string $principalUri
1972
-	 * @return array
1973
-	 */
1974
-	public function getSubscriptionsForUser($principalUri) {
1975
-		$fields = array_values($this->subscriptionPropertyMap);
1976
-		$fields[] = 'id';
1977
-		$fields[] = 'uri';
1978
-		$fields[] = 'source';
1979
-		$fields[] = 'principaluri';
1980
-		$fields[] = 'lastmodified';
1981
-		$fields[] = 'synctoken';
1982
-
1983
-		$query = $this->db->getQueryBuilder();
1984
-		$query->select($fields)
1985
-			->from('calendarsubscriptions')
1986
-			->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
1987
-			->orderBy('calendarorder', 'asc');
1988
-		$stmt =$query->execute();
1989
-
1990
-		$subscriptions = [];
1991
-		while ($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1992
-			$subscription = [
1993
-				'id'           => $row['id'],
1994
-				'uri'          => $row['uri'],
1995
-				'principaluri' => $row['principaluri'],
1996
-				'source'       => $row['source'],
1997
-				'lastmodified' => $row['lastmodified'],
1998
-
1999
-				'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet(['VTODO', 'VEVENT']),
2000
-				'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
2001
-			];
2002
-
2003
-			foreach ($this->subscriptionPropertyMap as $xmlName=>$dbName) {
2004
-				if (!is_null($row[$dbName])) {
2005
-					$subscription[$xmlName] = $row[$dbName];
2006
-				}
2007
-			}
2008
-
2009
-			$subscriptions[] = $subscription;
2010
-		}
2011
-
2012
-		return $subscriptions;
2013
-	}
2014
-
2015
-	/**
2016
-	 * Creates a new subscription for a principal.
2017
-	 *
2018
-	 * If the creation was a success, an id must be returned that can be used to reference
2019
-	 * this subscription in other methods, such as updateSubscription.
2020
-	 *
2021
-	 * @param string $principalUri
2022
-	 * @param string $uri
2023
-	 * @param array $properties
2024
-	 * @return mixed
2025
-	 */
2026
-	public function createSubscription($principalUri, $uri, array $properties) {
2027
-		if (!isset($properties['{http://calendarserver.org/ns/}source'])) {
2028
-			throw new Forbidden('The {http://calendarserver.org/ns/}source property is required when creating subscriptions');
2029
-		}
2030
-
2031
-		$values = [
2032
-			'principaluri' => $principalUri,
2033
-			'uri'          => $uri,
2034
-			'source'       => $properties['{http://calendarserver.org/ns/}source']->getHref(),
2035
-			'lastmodified' => time(),
2036
-		];
2037
-
2038
-		$propertiesBoolean = ['striptodos', 'stripalarms', 'stripattachments'];
2039
-
2040
-		foreach ($this->subscriptionPropertyMap as $xmlName=>$dbName) {
2041
-			if (array_key_exists($xmlName, $properties)) {
2042
-				$values[$dbName] = $properties[$xmlName];
2043
-				if (in_array($dbName, $propertiesBoolean)) {
2044
-					$values[$dbName] = true;
2045
-				}
2046
-			}
2047
-		}
2048
-
2049
-		$valuesToInsert = [];
2050
-
2051
-		$query = $this->db->getQueryBuilder();
2052
-
2053
-		foreach (array_keys($values) as $name) {
2054
-			$valuesToInsert[$name] = $query->createNamedParameter($values[$name]);
2055
-		}
2056
-
2057
-		$query->insert('calendarsubscriptions')
2058
-			->values($valuesToInsert)
2059
-			->execute();
2060
-
2061
-		$subscriptionId = $this->db->lastInsertId('*PREFIX*calendarsubscriptions');
2062
-
2063
-		$this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::createSubscription', new GenericEvent(
2064
-			'\OCA\DAV\CalDAV\CalDavBackend::createSubscription',
2065
-			[
2066
-				'subscriptionId' => $subscriptionId,
2067
-				'subscriptionData' => $this->getSubscriptionById($subscriptionId),
2068
-			]));
2069
-
2070
-		return $subscriptionId;
2071
-	}
2072
-
2073
-	/**
2074
-	 * Updates a subscription
2075
-	 *
2076
-	 * The list of mutations is stored in a Sabre\DAV\PropPatch object.
2077
-	 * To do the actual updates, you must tell this object which properties
2078
-	 * you're going to process with the handle() method.
2079
-	 *
2080
-	 * Calling the handle method is like telling the PropPatch object "I
2081
-	 * promise I can handle updating this property".
2082
-	 *
2083
-	 * Read the PropPatch documentation for more info and examples.
2084
-	 *
2085
-	 * @param mixed $subscriptionId
2086
-	 * @param PropPatch $propPatch
2087
-	 * @return void
2088
-	 */
2089
-	public function updateSubscription($subscriptionId, PropPatch $propPatch) {
2090
-		$supportedProperties = array_keys($this->subscriptionPropertyMap);
2091
-		$supportedProperties[] = '{http://calendarserver.org/ns/}source';
2092
-
2093
-		/**
2094
-		 * @suppress SqlInjectionChecker
2095
-		 */
2096
-		$propPatch->handle($supportedProperties, function ($mutations) use ($subscriptionId) {
2097
-			$newValues = [];
2098
-
2099
-			foreach ($mutations as $propertyName=>$propertyValue) {
2100
-				if ($propertyName === '{http://calendarserver.org/ns/}source') {
2101
-					$newValues['source'] = $propertyValue->getHref();
2102
-				} else {
2103
-					$fieldName = $this->subscriptionPropertyMap[$propertyName];
2104
-					$newValues[$fieldName] = $propertyValue;
2105
-				}
2106
-			}
2107
-
2108
-			$query = $this->db->getQueryBuilder();
2109
-			$query->update('calendarsubscriptions')
2110
-				->set('lastmodified', $query->createNamedParameter(time()));
2111
-			foreach ($newValues as $fieldName=>$value) {
2112
-				$query->set($fieldName, $query->createNamedParameter($value));
2113
-			}
2114
-			$query->where($query->expr()->eq('id', $query->createNamedParameter($subscriptionId)))
2115
-				->execute();
2116
-
2117
-			$this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::updateSubscription', new GenericEvent(
2118
-				'\OCA\DAV\CalDAV\CalDavBackend::updateSubscription',
2119
-				[
2120
-					'subscriptionId' => $subscriptionId,
2121
-					'subscriptionData' => $this->getSubscriptionById($subscriptionId),
2122
-					'propertyMutations' => $mutations,
2123
-				]));
2124
-
2125
-			return true;
2126
-		});
2127
-	}
2128
-
2129
-	/**
2130
-	 * Deletes a subscription.
2131
-	 *
2132
-	 * @param mixed $subscriptionId
2133
-	 * @return void
2134
-	 */
2135
-	public function deleteSubscription($subscriptionId) {
2136
-		$this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::deleteSubscription', new GenericEvent(
2137
-			'\OCA\DAV\CalDAV\CalDavBackend::deleteSubscription',
2138
-			[
2139
-				'subscriptionId' => $subscriptionId,
2140
-				'subscriptionData' => $this->getSubscriptionById($subscriptionId),
2141
-			]));
2142
-
2143
-		$query = $this->db->getQueryBuilder();
2144
-		$query->delete('calendarsubscriptions')
2145
-			->where($query->expr()->eq('id', $query->createNamedParameter($subscriptionId)))
2146
-			->execute();
2147
-
2148
-		$query = $this->db->getQueryBuilder();
2149
-		$query->delete('calendarobjects')
2150
-			->where($query->expr()->eq('calendarid', $query->createNamedParameter($subscriptionId)))
2151
-			->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)))
2152
-			->execute();
2153
-
2154
-		$query->delete('calendarchanges')
2155
-			->where($query->expr()->eq('calendarid', $query->createNamedParameter($subscriptionId)))
2156
-			->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)))
2157
-			->execute();
2158
-
2159
-		$query->delete($this->dbObjectPropertiesTable)
2160
-			->where($query->expr()->eq('calendarid', $query->createNamedParameter($subscriptionId)))
2161
-			->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)))
2162
-			->execute();
2163
-	}
2164
-
2165
-	/**
2166
-	 * Returns a single scheduling object for the inbox collection.
2167
-	 *
2168
-	 * The returned array should contain the following elements:
2169
-	 *   * uri - A unique basename for the object. This will be used to
2170
-	 *           construct a full uri.
2171
-	 *   * calendardata - The iCalendar object
2172
-	 *   * lastmodified - The last modification date. Can be an int for a unix
2173
-	 *                    timestamp, or a PHP DateTime object.
2174
-	 *   * etag - A unique token that must change if the object changed.
2175
-	 *   * size - The size of the object, in bytes.
2176
-	 *
2177
-	 * @param string $principalUri
2178
-	 * @param string $objectUri
2179
-	 * @return array
2180
-	 */
2181
-	public function getSchedulingObject($principalUri, $objectUri) {
2182
-		$query = $this->db->getQueryBuilder();
2183
-		$stmt = $query->select(['uri', 'calendardata', 'lastmodified', 'etag', 'size'])
2184
-			->from('schedulingobjects')
2185
-			->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
2186
-			->andWhere($query->expr()->eq('uri', $query->createNamedParameter($objectUri)))
2187
-			->execute();
2188
-
2189
-		$row = $stmt->fetch(\PDO::FETCH_ASSOC);
2190
-
2191
-		if (!$row) {
2192
-			return null;
2193
-		}
2194
-
2195
-		return [
2196
-			'uri'          => $row['uri'],
2197
-			'calendardata' => $row['calendardata'],
2198
-			'lastmodified' => $row['lastmodified'],
2199
-			'etag'         => '"' . $row['etag'] . '"',
2200
-			'size'         => (int)$row['size'],
2201
-		];
2202
-	}
2203
-
2204
-	/**
2205
-	 * Returns all scheduling objects for the inbox collection.
2206
-	 *
2207
-	 * These objects should be returned as an array. Every item in the array
2208
-	 * should follow the same structure as returned from getSchedulingObject.
2209
-	 *
2210
-	 * The main difference is that 'calendardata' is optional.
2211
-	 *
2212
-	 * @param string $principalUri
2213
-	 * @return array
2214
-	 */
2215
-	public function getSchedulingObjects($principalUri) {
2216
-		$query = $this->db->getQueryBuilder();
2217
-		$stmt = $query->select(['uri', 'calendardata', 'lastmodified', 'etag', 'size'])
2218
-				->from('schedulingobjects')
2219
-				->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
2220
-				->execute();
2221
-
2222
-		$result = [];
2223
-		foreach ($stmt->fetchAll(\PDO::FETCH_ASSOC) as $row) {
2224
-			$result[] = [
2225
-				'calendardata' => $row['calendardata'],
2226
-				'uri'          => $row['uri'],
2227
-				'lastmodified' => $row['lastmodified'],
2228
-				'etag'         => '"' . $row['etag'] . '"',
2229
-				'size'         => (int)$row['size'],
2230
-			];
2231
-		}
2232
-
2233
-		return $result;
2234
-	}
2235
-
2236
-	/**
2237
-	 * Deletes a scheduling object from the inbox collection.
2238
-	 *
2239
-	 * @param string $principalUri
2240
-	 * @param string $objectUri
2241
-	 * @return void
2242
-	 */
2243
-	public function deleteSchedulingObject($principalUri, $objectUri) {
2244
-		$query = $this->db->getQueryBuilder();
2245
-		$query->delete('schedulingobjects')
2246
-				->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
2247
-				->andWhere($query->expr()->eq('uri', $query->createNamedParameter($objectUri)))
2248
-				->execute();
2249
-	}
2250
-
2251
-	/**
2252
-	 * Creates a new scheduling object. This should land in a users' inbox.
2253
-	 *
2254
-	 * @param string $principalUri
2255
-	 * @param string $objectUri
2256
-	 * @param string $objectData
2257
-	 * @return void
2258
-	 */
2259
-	public function createSchedulingObject($principalUri, $objectUri, $objectData) {
2260
-		$query = $this->db->getQueryBuilder();
2261
-		$query->insert('schedulingobjects')
2262
-			->values([
2263
-				'principaluri' => $query->createNamedParameter($principalUri),
2264
-				'calendardata' => $query->createNamedParameter($objectData, IQueryBuilder::PARAM_LOB),
2265
-				'uri' => $query->createNamedParameter($objectUri),
2266
-				'lastmodified' => $query->createNamedParameter(time()),
2267
-				'etag' => $query->createNamedParameter(md5($objectData)),
2268
-				'size' => $query->createNamedParameter(strlen($objectData))
2269
-			])
2270
-			->execute();
2271
-	}
2272
-
2273
-	/**
2274
-	 * Adds a change record to the calendarchanges table.
2275
-	 *
2276
-	 * @param mixed $calendarId
2277
-	 * @param string $objectUri
2278
-	 * @param int $operation 1 = add, 2 = modify, 3 = delete.
2279
-	 * @param int $calendarType
2280
-	 * @return void
2281
-	 */
2282
-	protected function addChange($calendarId, $objectUri, $operation, $calendarType=self::CALENDAR_TYPE_CALENDAR) {
2283
-		$table = $calendarType === self::CALENDAR_TYPE_CALENDAR ? 'calendars': 'calendarsubscriptions';
2284
-
2285
-		$query = $this->db->getQueryBuilder();
2286
-		$query->select('synctoken')
2287
-			->from($table)
2288
-			->where($query->expr()->eq('id', $query->createNamedParameter($calendarId)));
2289
-		$syncToken = (int)$query->execute()->fetchColumn();
2290
-
2291
-		$query = $this->db->getQueryBuilder();
2292
-		$query->insert('calendarchanges')
2293
-			->values([
2294
-				'uri' => $query->createNamedParameter($objectUri),
2295
-				'synctoken' => $query->createNamedParameter($syncToken),
2296
-				'calendarid' => $query->createNamedParameter($calendarId),
2297
-				'operation' => $query->createNamedParameter($operation),
2298
-				'calendartype' => $query->createNamedParameter($calendarType),
2299
-			])
2300
-			->execute();
2301
-
2302
-		$stmt = $this->db->prepare("UPDATE `*PREFIX*$table` SET `synctoken` = `synctoken` + 1 WHERE `id` = ?");
2303
-		$stmt->execute([
2304
-			$calendarId
2305
-		]);
2306
-	}
2307
-
2308
-	/**
2309
-	 * Parses some information from calendar objects, used for optimized
2310
-	 * calendar-queries.
2311
-	 *
2312
-	 * Returns an array with the following keys:
2313
-	 *   * etag - An md5 checksum of the object without the quotes.
2314
-	 *   * size - Size of the object in bytes
2315
-	 *   * componentType - VEVENT, VTODO or VJOURNAL
2316
-	 *   * firstOccurence
2317
-	 *   * lastOccurence
2318
-	 *   * uid - value of the UID property
2319
-	 *
2320
-	 * @param string $calendarData
2321
-	 * @return array
2322
-	 */
2323
-	public function getDenormalizedData($calendarData) {
2324
-		$vObject = Reader::read($calendarData);
2325
-		$componentType = null;
2326
-		$component = null;
2327
-		$firstOccurrence = null;
2328
-		$lastOccurrence = null;
2329
-		$uid = null;
2330
-		$classification = self::CLASSIFICATION_PUBLIC;
2331
-		foreach ($vObject->getComponents() as $component) {
2332
-			if ($component->name!=='VTIMEZONE') {
2333
-				$componentType = $component->name;
2334
-				$uid = (string)$component->UID;
2335
-				break;
2336
-			}
2337
-		}
2338
-		if (!$componentType) {
2339
-			throw new \Sabre\DAV\Exception\BadRequest('Calendar objects must have a VJOURNAL, VEVENT or VTODO component');
2340
-		}
2341
-		if ($componentType === 'VEVENT' && $component->DTSTART) {
2342
-			$firstOccurrence = $component->DTSTART->getDateTime()->getTimeStamp();
2343
-			// Finding the last occurrence is a bit harder
2344
-			if (!isset($component->RRULE)) {
2345
-				if (isset($component->DTEND)) {
2346
-					$lastOccurrence = $component->DTEND->getDateTime()->getTimeStamp();
2347
-				} elseif (isset($component->DURATION)) {
2348
-					$endDate = clone $component->DTSTART->getDateTime();
2349
-					$endDate->add(DateTimeParser::parse($component->DURATION->getValue()));
2350
-					$lastOccurrence = $endDate->getTimeStamp();
2351
-				} elseif (!$component->DTSTART->hasTime()) {
2352
-					$endDate = clone $component->DTSTART->getDateTime();
2353
-					$endDate->modify('+1 day');
2354
-					$lastOccurrence = $endDate->getTimeStamp();
2355
-				} else {
2356
-					$lastOccurrence = $firstOccurrence;
2357
-				}
2358
-			} else {
2359
-				$it = new EventIterator($vObject, (string)$component->UID);
2360
-				$maxDate = new DateTime(self::MAX_DATE);
2361
-				if ($it->isInfinite()) {
2362
-					$lastOccurrence = $maxDate->getTimestamp();
2363
-				} else {
2364
-					$end = $it->getDtEnd();
2365
-					while ($it->valid() && $end < $maxDate) {
2366
-						$end = $it->getDtEnd();
2367
-						$it->next();
2368
-					}
2369
-					$lastOccurrence = $end->getTimestamp();
2370
-				}
2371
-			}
2372
-		}
2373
-
2374
-		if ($component->CLASS) {
2375
-			$classification = CalDavBackend::CLASSIFICATION_PRIVATE;
2376
-			switch ($component->CLASS->getValue()) {
2377
-				case 'PUBLIC':
2378
-					$classification = CalDavBackend::CLASSIFICATION_PUBLIC;
2379
-					break;
2380
-				case 'CONFIDENTIAL':
2381
-					$classification = CalDavBackend::CLASSIFICATION_CONFIDENTIAL;
2382
-					break;
2383
-			}
2384
-		}
2385
-		return [
2386
-			'etag' => md5($calendarData),
2387
-			'size' => strlen($calendarData),
2388
-			'componentType' => $componentType,
2389
-			'firstOccurence' => is_null($firstOccurrence) ? null : max(0, $firstOccurrence),
2390
-			'lastOccurence'  => $lastOccurrence,
2391
-			'uid' => $uid,
2392
-			'classification' => $classification
2393
-		];
2394
-	}
2395
-
2396
-	/**
2397
-	 * @param $cardData
2398
-	 * @return bool|string
2399
-	 */
2400
-	private function readBlob($cardData) {
2401
-		if (is_resource($cardData)) {
2402
-			return stream_get_contents($cardData);
2403
-		}
2404
-
2405
-		return $cardData;
2406
-	}
2407
-
2408
-	/**
2409
-	 * @param IShareable $shareable
2410
-	 * @param array $add
2411
-	 * @param array $remove
2412
-	 */
2413
-	public function updateShares($shareable, $add, $remove) {
2414
-		$calendarId = $shareable->getResourceId();
2415
-		$this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::updateShares', new GenericEvent(
2416
-			'\OCA\DAV\CalDAV\CalDavBackend::updateShares',
2417
-			[
2418
-				'calendarId' => $calendarId,
2419
-				'calendarData' => $this->getCalendarById($calendarId),
2420
-				'shares' => $this->getShares($calendarId),
2421
-				'add' => $add,
2422
-				'remove' => $remove,
2423
-			]));
2424
-		$this->calendarSharingBackend->updateShares($shareable, $add, $remove);
2425
-	}
2426
-
2427
-	/**
2428
-	 * @param int $resourceId
2429
-	 * @param int $calendarType
2430
-	 * @return array
2431
-	 */
2432
-	public function getShares($resourceId, $calendarType=self::CALENDAR_TYPE_CALENDAR) {
2433
-		return $this->calendarSharingBackend->getShares($resourceId);
2434
-	}
2435
-
2436
-	/**
2437
-	 * @param boolean $value
2438
-	 * @param \OCA\DAV\CalDAV\Calendar $calendar
2439
-	 * @return string|null
2440
-	 */
2441
-	public function setPublishStatus($value, $calendar) {
2442
-		$calendarId = $calendar->getResourceId();
2443
-		$this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::publishCalendar', new GenericEvent(
2444
-			'\OCA\DAV\CalDAV\CalDavBackend::updateShares',
2445
-			[
2446
-				'calendarId' => $calendarId,
2447
-				'calendarData' => $this->getCalendarById($calendarId),
2448
-				'public' => $value,
2449
-			]));
2450
-
2451
-		$query = $this->db->getQueryBuilder();
2452
-		if ($value) {
2453
-			$publicUri = $this->random->generate(16, ISecureRandom::CHAR_HUMAN_READABLE);
2454
-			$query->insert('dav_shares')
2455
-				->values([
2456
-					'principaluri' => $query->createNamedParameter($calendar->getPrincipalURI()),
2457
-					'type' => $query->createNamedParameter('calendar'),
2458
-					'access' => $query->createNamedParameter(self::ACCESS_PUBLIC),
2459
-					'resourceid' => $query->createNamedParameter($calendar->getResourceId()),
2460
-					'publicuri' => $query->createNamedParameter($publicUri)
2461
-				]);
2462
-			$query->execute();
2463
-			return $publicUri;
2464
-		}
2465
-		$query->delete('dav_shares')
2466
-			->where($query->expr()->eq('resourceid', $query->createNamedParameter($calendar->getResourceId())))
2467
-			->andWhere($query->expr()->eq('access', $query->createNamedParameter(self::ACCESS_PUBLIC)));
2468
-		$query->execute();
2469
-		return null;
2470
-	}
2471
-
2472
-	/**
2473
-	 * @param \OCA\DAV\CalDAV\Calendar $calendar
2474
-	 * @return mixed
2475
-	 */
2476
-	public function getPublishStatus($calendar) {
2477
-		$query = $this->db->getQueryBuilder();
2478
-		$result = $query->select('publicuri')
2479
-			->from('dav_shares')
2480
-			->where($query->expr()->eq('resourceid', $query->createNamedParameter($calendar->getResourceId())))
2481
-			->andWhere($query->expr()->eq('access', $query->createNamedParameter(self::ACCESS_PUBLIC)))
2482
-			->execute();
2483
-
2484
-		$row = $result->fetch();
2485
-		$result->closeCursor();
2486
-		return $row ? reset($row) : false;
2487
-	}
2488
-
2489
-	/**
2490
-	 * @param int $resourceId
2491
-	 * @param array $acl
2492
-	 * @return array
2493
-	 */
2494
-	public function applyShareAcl($resourceId, $acl) {
2495
-		return $this->calendarSharingBackend->applyShareAcl($resourceId, $acl);
2496
-	}
2497
-
2498
-
2499
-
2500
-	/**
2501
-	 * update properties table
2502
-	 *
2503
-	 * @param int $calendarId
2504
-	 * @param string $objectUri
2505
-	 * @param string $calendarData
2506
-	 * @param int $calendarType
2507
-	 */
2508
-	public function updateProperties($calendarId, $objectUri, $calendarData, $calendarType=self::CALENDAR_TYPE_CALENDAR) {
2509
-		$objectId = $this->getCalendarObjectId($calendarId, $objectUri, $calendarType);
2510
-
2511
-		try {
2512
-			$vCalendar = $this->readCalendarData($calendarData);
2513
-		} catch (\Exception $ex) {
2514
-			return;
2515
-		}
2516
-
2517
-		$this->purgeProperties($calendarId, $objectId);
2518
-
2519
-		$query = $this->db->getQueryBuilder();
2520
-		$query->insert($this->dbObjectPropertiesTable)
2521
-			->values(
2522
-				[
2523
-					'calendarid' => $query->createNamedParameter($calendarId),
2524
-					'calendartype' => $query->createNamedParameter($calendarType),
2525
-					'objectid' => $query->createNamedParameter($objectId),
2526
-					'name' => $query->createParameter('name'),
2527
-					'parameter' => $query->createParameter('parameter'),
2528
-					'value' => $query->createParameter('value'),
2529
-				]
2530
-			);
2531
-
2532
-		$indexComponents = ['VEVENT', 'VJOURNAL', 'VTODO'];
2533
-		foreach ($vCalendar->getComponents() as $component) {
2534
-			if (!in_array($component->name, $indexComponents)) {
2535
-				continue;
2536
-			}
2537
-
2538
-			foreach ($component->children() as $property) {
2539
-				if (in_array($property->name, self::$indexProperties)) {
2540
-					$value = $property->getValue();
2541
-					// is this a shitty db?
2542
-					if (!$this->db->supports4ByteText()) {
2543
-						$value = preg_replace('/[\x{10000}-\x{10FFFF}]/u', "\xEF\xBF\xBD", $value);
2544
-					}
2545
-					$value = mb_substr($value, 0, 254);
2546
-
2547
-					$query->setParameter('name', $property->name);
2548
-					$query->setParameter('parameter', null);
2549
-					$query->setParameter('value', $value);
2550
-					$query->execute();
2551
-				}
2552
-
2553
-				if (array_key_exists($property->name, self::$indexParameters)) {
2554
-					$parameters = $property->parameters();
2555
-					$indexedParametersForProperty = self::$indexParameters[$property->name];
2556
-
2557
-					foreach ($parameters as $key => $value) {
2558
-						if (in_array($key, $indexedParametersForProperty)) {
2559
-							// is this a shitty db?
2560
-							if ($this->db->supports4ByteText()) {
2561
-								$value = preg_replace('/[\x{10000}-\x{10FFFF}]/u', "\xEF\xBF\xBD", $value);
2562
-							}
2563
-
2564
-							$query->setParameter('name', $property->name);
2565
-							$query->setParameter('parameter', mb_substr($key, 0, 254));
2566
-							$query->setParameter('value', mb_substr($value, 0, 254));
2567
-							$query->execute();
2568
-						}
2569
-					}
2570
-				}
2571
-			}
2572
-		}
2573
-	}
2574
-
2575
-	/**
2576
-	 * deletes all birthday calendars
2577
-	 */
2578
-	public function deleteAllBirthdayCalendars() {
2579
-		$query = $this->db->getQueryBuilder();
2580
-		$result = $query->select(['id'])->from('calendars')
2581
-			->where($query->expr()->eq('uri', $query->createNamedParameter(BirthdayService::BIRTHDAY_CALENDAR_URI)))
2582
-			->execute();
2583
-
2584
-		$ids = $result->fetchAll();
2585
-		foreach ($ids as $id) {
2586
-			$this->deleteCalendar($id['id']);
2587
-		}
2588
-	}
2589
-
2590
-	/**
2591
-	 * @param $subscriptionId
2592
-	 */
2593
-	public function purgeAllCachedEventsForSubscription($subscriptionId) {
2594
-		$query = $this->db->getQueryBuilder();
2595
-		$query->select('uri')
2596
-			->from('calendarobjects')
2597
-			->where($query->expr()->eq('calendarid', $query->createNamedParameter($subscriptionId)))
2598
-			->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)));
2599
-		$stmt = $query->execute();
2600
-
2601
-		$uris = [];
2602
-		foreach ($stmt->fetchAll(\PDO::FETCH_ASSOC) as $row) {
2603
-			$uris[] = $row['uri'];
2604
-		}
2605
-		$stmt->closeCursor();
2606
-
2607
-		$query = $this->db->getQueryBuilder();
2608
-		$query->delete('calendarobjects')
2609
-			->where($query->expr()->eq('calendarid', $query->createNamedParameter($subscriptionId)))
2610
-			->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)))
2611
-			->execute();
2612
-
2613
-		$query->delete('calendarchanges')
2614
-			->where($query->expr()->eq('calendarid', $query->createNamedParameter($subscriptionId)))
2615
-			->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)))
2616
-			->execute();
2617
-
2618
-		$query->delete($this->dbObjectPropertiesTable)
2619
-			->where($query->expr()->eq('calendarid', $query->createNamedParameter($subscriptionId)))
2620
-			->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)))
2621
-			->execute();
2622
-
2623
-		foreach ($uris as $uri) {
2624
-			$this->addChange($subscriptionId, $uri, 3, self::CALENDAR_TYPE_SUBSCRIPTION);
2625
-		}
2626
-	}
2627
-
2628
-	/**
2629
-	 * Move a calendar from one user to another
2630
-	 *
2631
-	 * @param string $uriName
2632
-	 * @param string $uriOrigin
2633
-	 * @param string $uriDestination
2634
-	 */
2635
-	public function moveCalendar($uriName, $uriOrigin, $uriDestination) {
2636
-		$query = $this->db->getQueryBuilder();
2637
-		$query->update('calendars')
2638
-			->set('principaluri', $query->createNamedParameter($uriDestination))
2639
-			->where($query->expr()->eq('principaluri', $query->createNamedParameter($uriOrigin)))
2640
-			->andWhere($query->expr()->eq('uri', $query->createNamedParameter($uriName)))
2641
-			->execute();
2642
-	}
2643
-
2644
-	/**
2645
-	 * read VCalendar data into a VCalendar object
2646
-	 *
2647
-	 * @param string $objectData
2648
-	 * @return VCalendar
2649
-	 */
2650
-	protected function readCalendarData($objectData) {
2651
-		return Reader::read($objectData);
2652
-	}
2653
-
2654
-	/**
2655
-	 * delete all properties from a given calendar object
2656
-	 *
2657
-	 * @param int $calendarId
2658
-	 * @param int $objectId
2659
-	 */
2660
-	protected function purgeProperties($calendarId, $objectId) {
2661
-		$query = $this->db->getQueryBuilder();
2662
-		$query->delete($this->dbObjectPropertiesTable)
2663
-			->where($query->expr()->eq('objectid', $query->createNamedParameter($objectId)))
2664
-			->andWhere($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)));
2665
-		$query->execute();
2666
-	}
2667
-
2668
-	/**
2669
-	 * get ID from a given calendar object
2670
-	 *
2671
-	 * @param int $calendarId
2672
-	 * @param string $uri
2673
-	 * @param int $calendarType
2674
-	 * @return int
2675
-	 */
2676
-	protected function getCalendarObjectId($calendarId, $uri, $calendarType):int {
2677
-		$query = $this->db->getQueryBuilder();
2678
-		$query->select('id')
2679
-			->from('calendarobjects')
2680
-			->where($query->expr()->eq('uri', $query->createNamedParameter($uri)))
2681
-			->andWhere($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)))
2682
-			->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter($calendarType)));
2683
-
2684
-		$result = $query->execute();
2685
-		$objectIds = $result->fetch();
2686
-		$result->closeCursor();
2687
-
2688
-		if (!isset($objectIds['id'])) {
2689
-			throw new \InvalidArgumentException('Calendarobject does not exists: ' . $uri);
2690
-		}
2691
-
2692
-		return (int)$objectIds['id'];
2693
-	}
2694
-
2695
-	/**
2696
-	 * return legacy endpoint principal name to new principal name
2697
-	 *
2698
-	 * @param $principalUri
2699
-	 * @param $toV2
2700
-	 * @return string
2701
-	 */
2702
-	private function convertPrincipal($principalUri, $toV2) {
2703
-		if ($this->principalBackend->getPrincipalPrefix() === 'principals') {
2704
-			list(, $name) = Uri\split($principalUri);
2705
-			if ($toV2 === true) {
2706
-				return "principals/users/$name";
2707
-			}
2708
-			return "principals/$name";
2709
-		}
2710
-		return $principalUri;
2711
-	}
2712
-
2713
-	/**
2714
-	 * adds information about an owner to the calendar data
2715
-	 *
2716
-	 * @param $calendarInfo
2717
-	 */
2718
-	private function addOwnerPrincipal(&$calendarInfo) {
2719
-		$ownerPrincipalKey = '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal';
2720
-		$displaynameKey = '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_NEXTCLOUD . '}owner-displayname';
2721
-		if (isset($calendarInfo[$ownerPrincipalKey])) {
2722
-			$uri = $calendarInfo[$ownerPrincipalKey];
2723
-		} else {
2724
-			$uri = $calendarInfo['principaluri'];
2725
-		}
2726
-
2727
-		$principalInformation = $this->principalBackend->getPrincipalByPath($uri);
2728
-		if (isset($principalInformation['{DAV:}displayname'])) {
2729
-			$calendarInfo[$displaynameKey] = $principalInformation['{DAV:}displayname'];
2730
-		}
2731
-	}
80
+    public const CALENDAR_TYPE_CALENDAR = 0;
81
+    public const CALENDAR_TYPE_SUBSCRIPTION = 1;
82
+
83
+    public const PERSONAL_CALENDAR_URI = 'personal';
84
+    public const PERSONAL_CALENDAR_NAME = 'Personal';
85
+
86
+    public const RESOURCE_BOOKING_CALENDAR_URI = 'calendar';
87
+    public const RESOURCE_BOOKING_CALENDAR_NAME = 'Calendar';
88
+
89
+    /**
90
+     * We need to specify a max date, because we need to stop *somewhere*
91
+     *
92
+     * On 32 bit system the maximum for a signed integer is 2147483647, so
93
+     * MAX_DATE cannot be higher than date('Y-m-d', 2147483647) which results
94
+     * in 2038-01-19 to avoid problems when the date is converted
95
+     * to a unix timestamp.
96
+     */
97
+    public const MAX_DATE = '2038-01-01';
98
+
99
+    public const ACCESS_PUBLIC = 4;
100
+    public const CLASSIFICATION_PUBLIC = 0;
101
+    public const CLASSIFICATION_PRIVATE = 1;
102
+    public const CLASSIFICATION_CONFIDENTIAL = 2;
103
+
104
+    /**
105
+     * List of CalDAV properties, and how they map to database field names
106
+     * Add your own properties by simply adding on to this array.
107
+     *
108
+     * Note that only string-based properties are supported here.
109
+     *
110
+     * @var array
111
+     */
112
+    public $propertyMap = [
113
+        '{DAV:}displayname'                          => 'displayname',
114
+        '{urn:ietf:params:xml:ns:caldav}calendar-description' => 'description',
115
+        '{urn:ietf:params:xml:ns:caldav}calendar-timezone'    => 'timezone',
116
+        '{http://apple.com/ns/ical/}calendar-order'  => 'calendarorder',
117
+        '{http://apple.com/ns/ical/}calendar-color'  => 'calendarcolor',
118
+    ];
119
+
120
+    /**
121
+     * List of subscription properties, and how they map to database field names.
122
+     *
123
+     * @var array
124
+     */
125
+    public $subscriptionPropertyMap = [
126
+        '{DAV:}displayname'                                           => 'displayname',
127
+        '{http://apple.com/ns/ical/}refreshrate'                      => 'refreshrate',
128
+        '{http://apple.com/ns/ical/}calendar-order'                   => 'calendarorder',
129
+        '{http://apple.com/ns/ical/}calendar-color'                   => 'calendarcolor',
130
+        '{http://calendarserver.org/ns/}subscribed-strip-todos'       => 'striptodos',
131
+        '{http://calendarserver.org/ns/}subscribed-strip-alarms'      => 'stripalarms',
132
+        '{http://calendarserver.org/ns/}subscribed-strip-attachments' => 'stripattachments',
133
+    ];
134
+
135
+    /** @var array properties to index */
136
+    public static $indexProperties = ['CATEGORIES', 'COMMENT', 'DESCRIPTION',
137
+        'LOCATION', 'RESOURCES', 'STATUS', 'SUMMARY', 'ATTENDEE', 'CONTACT',
138
+        'ORGANIZER'];
139
+
140
+    /** @var array parameters to index */
141
+    public static $indexParameters = [
142
+        'ATTENDEE' => ['CN'],
143
+        'ORGANIZER' => ['CN'],
144
+    ];
145
+
146
+    /**
147
+     * @var string[] Map of uid => display name
148
+     */
149
+    protected $userDisplayNames;
150
+
151
+    /** @var IDBConnection */
152
+    private $db;
153
+
154
+    /** @var Backend */
155
+    private $calendarSharingBackend;
156
+
157
+    /** @var Principal */
158
+    private $principalBackend;
159
+
160
+    /** @var IUserManager */
161
+    private $userManager;
162
+
163
+    /** @var ISecureRandom */
164
+    private $random;
165
+
166
+    /** @var ILogger */
167
+    private $logger;
168
+
169
+    /** @var EventDispatcherInterface */
170
+    private $dispatcher;
171
+
172
+    /** @var bool */
173
+    private $legacyEndpoint;
174
+
175
+    /** @var string */
176
+    private $dbObjectPropertiesTable = 'calendarobjects_props';
177
+
178
+    /**
179
+     * CalDavBackend constructor.
180
+     *
181
+     * @param IDBConnection $db
182
+     * @param Principal $principalBackend
183
+     * @param IUserManager $userManager
184
+     * @param IGroupManager $groupManager
185
+     * @param ISecureRandom $random
186
+     * @param ILogger $logger
187
+     * @param EventDispatcherInterface $dispatcher
188
+     * @param bool $legacyEndpoint
189
+     */
190
+    public function __construct(IDBConnection $db,
191
+                                Principal $principalBackend,
192
+                                IUserManager $userManager,
193
+                                IGroupManager $groupManager,
194
+                                ISecureRandom $random,
195
+                                ILogger $logger,
196
+                                EventDispatcherInterface $dispatcher,
197
+                                bool $legacyEndpoint = false) {
198
+        $this->db = $db;
199
+        $this->principalBackend = $principalBackend;
200
+        $this->userManager = $userManager;
201
+        $this->calendarSharingBackend = new Backend($this->db, $this->userManager, $groupManager, $principalBackend, 'calendar');
202
+        $this->random = $random;
203
+        $this->logger = $logger;
204
+        $this->dispatcher = $dispatcher;
205
+        $this->legacyEndpoint = $legacyEndpoint;
206
+    }
207
+
208
+    /**
209
+     * Return the number of calendars for a principal
210
+     *
211
+     * By default this excludes the automatically generated birthday calendar
212
+     *
213
+     * @param $principalUri
214
+     * @param bool $excludeBirthday
215
+     * @return int
216
+     */
217
+    public function getCalendarsForUserCount($principalUri, $excludeBirthday = true) {
218
+        $principalUri = $this->convertPrincipal($principalUri, true);
219
+        $query = $this->db->getQueryBuilder();
220
+        $query->select($query->func()->count('*'))
221
+            ->from('calendars')
222
+            ->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)));
223
+
224
+        if ($excludeBirthday) {
225
+            $query->andWhere($query->expr()->neq('uri', $query->createNamedParameter(BirthdayService::BIRTHDAY_CALENDAR_URI)));
226
+        }
227
+
228
+        return (int)$query->execute()->fetchColumn();
229
+    }
230
+
231
+    /**
232
+     * Returns a list of calendars for a principal.
233
+     *
234
+     * Every project is an array with the following keys:
235
+     *  * id, a unique id that will be used by other functions to modify the
236
+     *    calendar. This can be the same as the uri or a database key.
237
+     *  * uri, which the basename of the uri with which the calendar is
238
+     *    accessed.
239
+     *  * principaluri. The owner of the calendar. Almost always the same as
240
+     *    principalUri passed to this method.
241
+     *
242
+     * Furthermore it can contain webdav properties in clark notation. A very
243
+     * common one is '{DAV:}displayname'.
244
+     *
245
+     * Many clients also require:
246
+     * {urn:ietf:params:xml:ns:caldav}supported-calendar-component-set
247
+     * For this property, you can just return an instance of
248
+     * Sabre\CalDAV\Property\SupportedCalendarComponentSet.
249
+     *
250
+     * If you return {http://sabredav.org/ns}read-only and set the value to 1,
251
+     * ACL will automatically be put in read-only mode.
252
+     *
253
+     * @param string $principalUri
254
+     * @return array
255
+     */
256
+    public function getCalendarsForUser($principalUri) {
257
+        $principalUriOriginal = $principalUri;
258
+        $principalUri = $this->convertPrincipal($principalUri, true);
259
+        $fields = array_values($this->propertyMap);
260
+        $fields[] = 'id';
261
+        $fields[] = 'uri';
262
+        $fields[] = 'synctoken';
263
+        $fields[] = 'components';
264
+        $fields[] = 'principaluri';
265
+        $fields[] = 'transparent';
266
+
267
+        // Making fields a comma-delimited list
268
+        $query = $this->db->getQueryBuilder();
269
+        $query->select($fields)->from('calendars')
270
+                ->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
271
+                ->orderBy('calendarorder', 'ASC');
272
+        $stmt = $query->execute();
273
+
274
+        $calendars = [];
275
+        while ($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
276
+            $components = [];
277
+            if ($row['components']) {
278
+                $components = explode(',',$row['components']);
279
+            }
280
+
281
+            $calendar = [
282
+                'id' => $row['id'],
283
+                'uri' => $row['uri'],
284
+                'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
285
+                '{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
286
+                '{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
287
+                '{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
288
+                '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
289
+                '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($principalUri, !$this->legacyEndpoint),
290
+            ];
291
+
292
+            foreach ($this->propertyMap as $xmlName=>$dbName) {
293
+                $calendar[$xmlName] = $row[$dbName];
294
+            }
295
+
296
+            $this->addOwnerPrincipal($calendar);
297
+
298
+            if (!isset($calendars[$calendar['id']])) {
299
+                $calendars[$calendar['id']] = $calendar;
300
+            }
301
+        }
302
+
303
+        $stmt->closeCursor();
304
+
305
+        // query for shared calendars
306
+        $principals = $this->principalBackend->getGroupMembership($principalUriOriginal, true);
307
+        $principals = array_merge($principals, $this->principalBackend->getCircleMembership($principalUriOriginal));
308
+
309
+        $principals = array_map(function ($principal) {
310
+            return urldecode($principal);
311
+        }, $principals);
312
+        $principals[]= $principalUri;
313
+
314
+        $fields = array_values($this->propertyMap);
315
+        $fields[] = 'a.id';
316
+        $fields[] = 'a.uri';
317
+        $fields[] = 'a.synctoken';
318
+        $fields[] = 'a.components';
319
+        $fields[] = 'a.principaluri';
320
+        $fields[] = 'a.transparent';
321
+        $fields[] = 's.access';
322
+        $query = $this->db->getQueryBuilder();
323
+        $result = $query->select($fields)
324
+            ->from('dav_shares', 's')
325
+            ->join('s', 'calendars', 'a', $query->expr()->eq('s.resourceid', 'a.id'))
326
+            ->where($query->expr()->in('s.principaluri', $query->createParameter('principaluri')))
327
+            ->andWhere($query->expr()->eq('s.type', $query->createParameter('type')))
328
+            ->setParameter('type', 'calendar')
329
+            ->setParameter('principaluri', $principals, \Doctrine\DBAL\Connection::PARAM_STR_ARRAY)
330
+            ->execute();
331
+
332
+        $readOnlyPropertyName = '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}read-only';
333
+        while ($row = $result->fetch()) {
334
+            if ($row['principaluri'] === $principalUri) {
335
+                continue;
336
+            }
337
+
338
+            $readOnly = (int) $row['access'] === Backend::ACCESS_READ;
339
+            if (isset($calendars[$row['id']])) {
340
+                if ($readOnly) {
341
+                    // New share can not have more permissions then the old one.
342
+                    continue;
343
+                }
344
+                if (isset($calendars[$row['id']][$readOnlyPropertyName]) &&
345
+                    $calendars[$row['id']][$readOnlyPropertyName] === 0) {
346
+                    // Old share is already read-write, no more permissions can be gained
347
+                    continue;
348
+                }
349
+            }
350
+
351
+            list(, $name) = Uri\split($row['principaluri']);
352
+            $uri = $row['uri'] . '_shared_by_' . $name;
353
+            $row['displayname'] = $row['displayname'] . ' (' . $this->getUserDisplayName($name) . ')';
354
+            $components = [];
355
+            if ($row['components']) {
356
+                $components = explode(',',$row['components']);
357
+            }
358
+            $calendar = [
359
+                'id' => $row['id'],
360
+                'uri' => $uri,
361
+                'principaluri' => $this->convertPrincipal($principalUri, !$this->legacyEndpoint),
362
+                '{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
363
+                '{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
364
+                '{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
365
+                '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp('transparent'),
366
+                '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
367
+                $readOnlyPropertyName => $readOnly,
368
+            ];
369
+
370
+            foreach ($this->propertyMap as $xmlName=>$dbName) {
371
+                $calendar[$xmlName] = $row[$dbName];
372
+            }
373
+
374
+            $this->addOwnerPrincipal($calendar);
375
+
376
+            $calendars[$calendar['id']] = $calendar;
377
+        }
378
+        $result->closeCursor();
379
+
380
+        return array_values($calendars);
381
+    }
382
+
383
+    /**
384
+     * @param $principalUri
385
+     * @return array
386
+     */
387
+    public function getUsersOwnCalendars($principalUri) {
388
+        $principalUri = $this->convertPrincipal($principalUri, true);
389
+        $fields = array_values($this->propertyMap);
390
+        $fields[] = 'id';
391
+        $fields[] = 'uri';
392
+        $fields[] = 'synctoken';
393
+        $fields[] = 'components';
394
+        $fields[] = 'principaluri';
395
+        $fields[] = 'transparent';
396
+        // Making fields a comma-delimited list
397
+        $query = $this->db->getQueryBuilder();
398
+        $query->select($fields)->from('calendars')
399
+            ->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
400
+            ->orderBy('calendarorder', 'ASC');
401
+        $stmt = $query->execute();
402
+        $calendars = [];
403
+        while ($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
404
+            $components = [];
405
+            if ($row['components']) {
406
+                $components = explode(',',$row['components']);
407
+            }
408
+            $calendar = [
409
+                'id' => $row['id'],
410
+                'uri' => $row['uri'],
411
+                'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
412
+                '{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
413
+                '{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
414
+                '{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
415
+                '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
416
+            ];
417
+            foreach ($this->propertyMap as $xmlName=>$dbName) {
418
+                $calendar[$xmlName] = $row[$dbName];
419
+            }
420
+
421
+            $this->addOwnerPrincipal($calendar);
422
+
423
+            if (!isset($calendars[$calendar['id']])) {
424
+                $calendars[$calendar['id']] = $calendar;
425
+            }
426
+        }
427
+        $stmt->closeCursor();
428
+        return array_values($calendars);
429
+    }
430
+
431
+
432
+    /**
433
+     * @param $uid
434
+     * @return string
435
+     */
436
+    private function getUserDisplayName($uid) {
437
+        if (!isset($this->userDisplayNames[$uid])) {
438
+            $user = $this->userManager->get($uid);
439
+
440
+            if ($user instanceof IUser) {
441
+                $this->userDisplayNames[$uid] = $user->getDisplayName();
442
+            } else {
443
+                $this->userDisplayNames[$uid] = $uid;
444
+            }
445
+        }
446
+
447
+        return $this->userDisplayNames[$uid];
448
+    }
449
+
450
+    /**
451
+     * @return array
452
+     */
453
+    public function getPublicCalendars() {
454
+        $fields = array_values($this->propertyMap);
455
+        $fields[] = 'a.id';
456
+        $fields[] = 'a.uri';
457
+        $fields[] = 'a.synctoken';
458
+        $fields[] = 'a.components';
459
+        $fields[] = 'a.principaluri';
460
+        $fields[] = 'a.transparent';
461
+        $fields[] = 's.access';
462
+        $fields[] = 's.publicuri';
463
+        $calendars = [];
464
+        $query = $this->db->getQueryBuilder();
465
+        $result = $query->select($fields)
466
+            ->from('dav_shares', 's')
467
+            ->join('s', 'calendars', 'a', $query->expr()->eq('s.resourceid', 'a.id'))
468
+            ->where($query->expr()->in('s.access', $query->createNamedParameter(self::ACCESS_PUBLIC)))
469
+            ->andWhere($query->expr()->eq('s.type', $query->createNamedParameter('calendar')))
470
+            ->execute();
471
+
472
+        while ($row = $result->fetch()) {
473
+            list(, $name) = Uri\split($row['principaluri']);
474
+            $row['displayname'] = $row['displayname'] . "($name)";
475
+            $components = [];
476
+            if ($row['components']) {
477
+                $components = explode(',',$row['components']);
478
+            }
479
+            $calendar = [
480
+                'id' => $row['id'],
481
+                'uri' => $row['publicuri'],
482
+                'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
483
+                '{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
484
+                '{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
485
+                '{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
486
+                '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
487
+                '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($row['principaluri'], $this->legacyEndpoint),
488
+                '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}read-only' => (int)$row['access'] === Backend::ACCESS_READ,
489
+                '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}public' => (int)$row['access'] === self::ACCESS_PUBLIC,
490
+            ];
491
+
492
+            foreach ($this->propertyMap as $xmlName=>$dbName) {
493
+                $calendar[$xmlName] = $row[$dbName];
494
+            }
495
+
496
+            $this->addOwnerPrincipal($calendar);
497
+
498
+            if (!isset($calendars[$calendar['id']])) {
499
+                $calendars[$calendar['id']] = $calendar;
500
+            }
501
+        }
502
+        $result->closeCursor();
503
+
504
+        return array_values($calendars);
505
+    }
506
+
507
+    /**
508
+     * @param string $uri
509
+     * @return array
510
+     * @throws NotFound
511
+     */
512
+    public function getPublicCalendar($uri) {
513
+        $fields = array_values($this->propertyMap);
514
+        $fields[] = 'a.id';
515
+        $fields[] = 'a.uri';
516
+        $fields[] = 'a.synctoken';
517
+        $fields[] = 'a.components';
518
+        $fields[] = 'a.principaluri';
519
+        $fields[] = 'a.transparent';
520
+        $fields[] = 's.access';
521
+        $fields[] = 's.publicuri';
522
+        $query = $this->db->getQueryBuilder();
523
+        $result = $query->select($fields)
524
+            ->from('dav_shares', 's')
525
+            ->join('s', 'calendars', 'a', $query->expr()->eq('s.resourceid', 'a.id'))
526
+            ->where($query->expr()->in('s.access', $query->createNamedParameter(self::ACCESS_PUBLIC)))
527
+            ->andWhere($query->expr()->eq('s.type', $query->createNamedParameter('calendar')))
528
+            ->andWhere($query->expr()->eq('s.publicuri', $query->createNamedParameter($uri)))
529
+            ->execute();
530
+
531
+        $row = $result->fetch(\PDO::FETCH_ASSOC);
532
+
533
+        $result->closeCursor();
534
+
535
+        if ($row === false) {
536
+            throw new NotFound('Node with name \'' . $uri . '\' could not be found');
537
+        }
538
+
539
+        list(, $name) = Uri\split($row['principaluri']);
540
+        $row['displayname'] = $row['displayname'] . ' ' . "($name)";
541
+        $components = [];
542
+        if ($row['components']) {
543
+            $components = explode(',',$row['components']);
544
+        }
545
+        $calendar = [
546
+            'id' => $row['id'],
547
+            'uri' => $row['publicuri'],
548
+            'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
549
+            '{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
550
+            '{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
551
+            '{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
552
+            '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
553
+            '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
554
+            '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}read-only' => (int)$row['access'] === Backend::ACCESS_READ,
555
+            '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}public' => (int)$row['access'] === self::ACCESS_PUBLIC,
556
+        ];
557
+
558
+        foreach ($this->propertyMap as $xmlName=>$dbName) {
559
+            $calendar[$xmlName] = $row[$dbName];
560
+        }
561
+
562
+        $this->addOwnerPrincipal($calendar);
563
+
564
+        return $calendar;
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
+    public 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
+        } elseif (isset($properties['components'])) {
743
+            // Allow to provide components internally without having
744
+            // to create a SupportedCalendarComponentSet object
745
+            $values['components'] = $properties['components'];
746
+        }
747
+
748
+        $transp = '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp';
749
+        if (isset($properties[$transp])) {
750
+            $values['transparent'] = (int) ($properties[$transp]->getValue() === 'transparent');
751
+        }
752
+
753
+        foreach ($this->propertyMap as $xmlName=>$dbName) {
754
+            if (isset($properties[$xmlName])) {
755
+                $values[$dbName] = $properties[$xmlName];
756
+            }
757
+        }
758
+
759
+        $query = $this->db->getQueryBuilder();
760
+        $query->insert('calendars');
761
+        foreach ($values as $column => $value) {
762
+            $query->setValue($column, $query->createNamedParameter($value));
763
+        }
764
+        $query->execute();
765
+        $calendarId = $query->getLastInsertId();
766
+
767
+        $this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::createCalendar', new GenericEvent(
768
+            '\OCA\DAV\CalDAV\CalDavBackend::createCalendar',
769
+            [
770
+                'calendarId' => $calendarId,
771
+                'calendarData' => $this->getCalendarById($calendarId),
772
+            ]));
773
+
774
+        return $calendarId;
775
+    }
776
+
777
+    /**
778
+     * Updates properties for a calendar.
779
+     *
780
+     * The list of mutations is stored in a Sabre\DAV\PropPatch object.
781
+     * To do the actual updates, you must tell this object which properties
782
+     * you're going to process with the handle() method.
783
+     *
784
+     * Calling the handle method is like telling the PropPatch object "I
785
+     * promise I can handle updating this property".
786
+     *
787
+     * Read the PropPatch documentation for more info and examples.
788
+     *
789
+     * @param mixed $calendarId
790
+     * @param PropPatch $propPatch
791
+     * @return void
792
+     */
793
+    public function updateCalendar($calendarId, PropPatch $propPatch) {
794
+        $supportedProperties = array_keys($this->propertyMap);
795
+        $supportedProperties[] = '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp';
796
+
797
+        /**
798
+         * @suppress SqlInjectionChecker
799
+         */
800
+        $propPatch->handle($supportedProperties, function ($mutations) use ($calendarId) {
801
+            $newValues = [];
802
+            foreach ($mutations as $propertyName => $propertyValue) {
803
+                switch ($propertyName) {
804
+                    case '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp':
805
+                        $fieldName = 'transparent';
806
+                        $newValues[$fieldName] = (int) ($propertyValue->getValue() === 'transparent');
807
+                        break;
808
+                    default:
809
+                        $fieldName = $this->propertyMap[$propertyName];
810
+                        $newValues[$fieldName] = $propertyValue;
811
+                        break;
812
+                }
813
+            }
814
+            $query = $this->db->getQueryBuilder();
815
+            $query->update('calendars');
816
+            foreach ($newValues as $fieldName => $value) {
817
+                $query->set($fieldName, $query->createNamedParameter($value));
818
+            }
819
+            $query->where($query->expr()->eq('id', $query->createNamedParameter($calendarId)));
820
+            $query->execute();
821
+
822
+            $this->addChange($calendarId, "", 2);
823
+
824
+            $this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::updateCalendar', new GenericEvent(
825
+                '\OCA\DAV\CalDAV\CalDavBackend::updateCalendar',
826
+                [
827
+                    'calendarId' => $calendarId,
828
+                    'calendarData' => $this->getCalendarById($calendarId),
829
+                    'shares' => $this->getShares($calendarId),
830
+                    'propertyMutations' => $mutations,
831
+                ]));
832
+
833
+            return true;
834
+        });
835
+    }
836
+
837
+    /**
838
+     * Delete a calendar and all it's objects
839
+     *
840
+     * @param mixed $calendarId
841
+     * @return void
842
+     */
843
+    public function deleteCalendar($calendarId) {
844
+        $this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::deleteCalendar', new GenericEvent(
845
+            '\OCA\DAV\CalDAV\CalDavBackend::deleteCalendar',
846
+            [
847
+                'calendarId' => $calendarId,
848
+                'calendarData' => $this->getCalendarById($calendarId),
849
+                'shares' => $this->getShares($calendarId),
850
+            ]));
851
+
852
+        $stmt = $this->db->prepare('DELETE FROM `*PREFIX*calendarobjects` WHERE `calendarid` = ? AND `calendartype` = ?');
853
+        $stmt->execute([$calendarId, self::CALENDAR_TYPE_CALENDAR]);
854
+
855
+        $stmt = $this->db->prepare('DELETE FROM `*PREFIX*calendars` WHERE `id` = ?');
856
+        $stmt->execute([$calendarId]);
857
+
858
+        $stmt = $this->db->prepare('DELETE FROM `*PREFIX*calendarchanges` WHERE `calendarid` = ? AND `calendartype` = ?');
859
+        $stmt->execute([$calendarId, self::CALENDAR_TYPE_CALENDAR]);
860
+
861
+        $this->calendarSharingBackend->deleteAllShares($calendarId);
862
+
863
+        $query = $this->db->getQueryBuilder();
864
+        $query->delete($this->dbObjectPropertiesTable)
865
+            ->where($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)))
866
+            ->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_CALENDAR)))
867
+            ->execute();
868
+    }
869
+
870
+    /**
871
+     * Delete all of an user's shares
872
+     *
873
+     * @param string $principaluri
874
+     * @return void
875
+     */
876
+    public function deleteAllSharesByUser($principaluri) {
877
+        $this->calendarSharingBackend->deleteAllSharesByUser($principaluri);
878
+    }
879
+
880
+    /**
881
+     * Returns all calendar objects within a calendar.
882
+     *
883
+     * Every item contains an array with the following keys:
884
+     *   * calendardata - The iCalendar-compatible calendar data
885
+     *   * uri - a unique key which will be used to construct the uri. This can
886
+     *     be any arbitrary string, but making sure it ends with '.ics' is a
887
+     *     good idea. This is only the basename, or filename, not the full
888
+     *     path.
889
+     *   * lastmodified - a timestamp of the last modification time
890
+     *   * etag - An arbitrary string, surrounded by double-quotes. (e.g.:
891
+     *   '"abcdef"')
892
+     *   * size - The size of the calendar objects, in bytes.
893
+     *   * component - optional, a string containing the type of object, such
894
+     *     as 'vevent' or 'vtodo'. If specified, this will be used to populate
895
+     *     the Content-Type header.
896
+     *
897
+     * Note that the etag is optional, but it's highly encouraged to return for
898
+     * speed reasons.
899
+     *
900
+     * The calendardata is also optional. If it's not returned
901
+     * 'getCalendarObject' will be called later, which *is* expected to return
902
+     * calendardata.
903
+     *
904
+     * If neither etag or size are specified, the calendardata will be
905
+     * used/fetched to determine these numbers. If both are specified the
906
+     * amount of times this is needed is reduced by a great degree.
907
+     *
908
+     * @param mixed $calendarId
909
+     * @param int $calendarType
910
+     * @return array
911
+     */
912
+    public function getCalendarObjects($calendarId, $calendarType=self::CALENDAR_TYPE_CALENDAR):array {
913
+        $query = $this->db->getQueryBuilder();
914
+        $query->select(['id', 'uri', 'lastmodified', 'etag', 'calendarid', 'size', 'componenttype', 'classification'])
915
+            ->from('calendarobjects')
916
+            ->where($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)))
917
+            ->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter($calendarType)));
918
+        $stmt = $query->execute();
919
+
920
+        $result = [];
921
+        foreach ($stmt->fetchAll(\PDO::FETCH_ASSOC) as $row) {
922
+            $result[] = [
923
+                'id'           => $row['id'],
924
+                'uri'          => $row['uri'],
925
+                'lastmodified' => $row['lastmodified'],
926
+                'etag'         => '"' . $row['etag'] . '"',
927
+                'calendarid'   => $row['calendarid'],
928
+                'size'         => (int)$row['size'],
929
+                'component'    => strtolower($row['componenttype']),
930
+                'classification'=> (int)$row['classification']
931
+            ];
932
+        }
933
+
934
+        return $result;
935
+    }
936
+
937
+    /**
938
+     * Returns information from a single calendar object, based on it's object
939
+     * uri.
940
+     *
941
+     * The object uri is only the basename, or filename and not a full path.
942
+     *
943
+     * The returned array must have the same keys as getCalendarObjects. The
944
+     * 'calendardata' object is required here though, while it's not required
945
+     * for getCalendarObjects.
946
+     *
947
+     * This method must return null if the object did not exist.
948
+     *
949
+     * @param mixed $calendarId
950
+     * @param string $objectUri
951
+     * @param int $calendarType
952
+     * @return array|null
953
+     */
954
+    public function getCalendarObject($calendarId, $objectUri, $calendarType=self::CALENDAR_TYPE_CALENDAR) {
955
+        $query = $this->db->getQueryBuilder();
956
+        $query->select(['id', 'uri', 'lastmodified', 'etag', 'calendarid', 'size', 'calendardata', 'componenttype', 'classification'])
957
+            ->from('calendarobjects')
958
+            ->where($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)))
959
+            ->andWhere($query->expr()->eq('uri', $query->createNamedParameter($objectUri)))
960
+            ->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter($calendarType)));
961
+        $stmt = $query->execute();
962
+        $row = $stmt->fetch(\PDO::FETCH_ASSOC);
963
+
964
+        if (!$row) {
965
+            return null;
966
+        }
967
+
968
+        return [
969
+            'id'            => $row['id'],
970
+            'uri'           => $row['uri'],
971
+            'lastmodified'  => $row['lastmodified'],
972
+            'etag'          => '"' . $row['etag'] . '"',
973
+            'calendarid'    => $row['calendarid'],
974
+            'size'          => (int)$row['size'],
975
+            'calendardata'  => $this->readBlob($row['calendardata']),
976
+            'component'     => strtolower($row['componenttype']),
977
+            'classification'=> (int)$row['classification']
978
+        ];
979
+    }
980
+
981
+    /**
982
+     * Returns a list of calendar objects.
983
+     *
984
+     * This method should work identical to getCalendarObject, but instead
985
+     * return all the calendar objects in the list as an array.
986
+     *
987
+     * If the backend supports this, it may allow for some speed-ups.
988
+     *
989
+     * @param mixed $calendarId
990
+     * @param string[] $uris
991
+     * @param int $calendarType
992
+     * @return array
993
+     */
994
+    public function getMultipleCalendarObjects($calendarId, array $uris, $calendarType=self::CALENDAR_TYPE_CALENDAR):array {
995
+        if (empty($uris)) {
996
+            return [];
997
+        }
998
+
999
+        $chunks = array_chunk($uris, 100);
1000
+        $objects = [];
1001
+
1002
+        $query = $this->db->getQueryBuilder();
1003
+        $query->select(['id', 'uri', 'lastmodified', 'etag', 'calendarid', 'size', 'calendardata', 'componenttype', 'classification'])
1004
+            ->from('calendarobjects')
1005
+            ->where($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)))
1006
+            ->andWhere($query->expr()->in('uri', $query->createParameter('uri')))
1007
+            ->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter($calendarType)));
1008
+
1009
+        foreach ($chunks as $uris) {
1010
+            $query->setParameter('uri', $uris, IQueryBuilder::PARAM_STR_ARRAY);
1011
+            $result = $query->execute();
1012
+
1013
+            while ($row = $result->fetch()) {
1014
+                $objects[] = [
1015
+                    'id'           => $row['id'],
1016
+                    'uri'          => $row['uri'],
1017
+                    'lastmodified' => $row['lastmodified'],
1018
+                    'etag'         => '"' . $row['etag'] . '"',
1019
+                    'calendarid'   => $row['calendarid'],
1020
+                    'size'         => (int)$row['size'],
1021
+                    'calendardata' => $this->readBlob($row['calendardata']),
1022
+                    'component'    => strtolower($row['componenttype']),
1023
+                    'classification' => (int)$row['classification']
1024
+                ];
1025
+            }
1026
+            $result->closeCursor();
1027
+        }
1028
+
1029
+        return $objects;
1030
+    }
1031
+
1032
+    /**
1033
+     * Creates a new calendar object.
1034
+     *
1035
+     * The object uri is only the basename, or filename and not a full path.
1036
+     *
1037
+     * It is possible return an etag from this function, which will be used in
1038
+     * the response to this PUT request. Note that the ETag must be surrounded
1039
+     * by double-quotes.
1040
+     *
1041
+     * However, you should only really return this ETag if you don't mangle the
1042
+     * calendar-data. If the result of a subsequent GET to this object is not
1043
+     * the exact same as this request body, you should omit the ETag.
1044
+     *
1045
+     * @param mixed $calendarId
1046
+     * @param string $objectUri
1047
+     * @param string $calendarData
1048
+     * @param int $calendarType
1049
+     * @return string
1050
+     */
1051
+    public function createCalendarObject($calendarId, $objectUri, $calendarData, $calendarType=self::CALENDAR_TYPE_CALENDAR) {
1052
+        $extraData = $this->getDenormalizedData($calendarData);
1053
+
1054
+        $q = $this->db->getQueryBuilder();
1055
+        $q->select($q->func()->count('*'))
1056
+            ->from('calendarobjects')
1057
+            ->where($q->expr()->eq('calendarid', $q->createNamedParameter($calendarId)))
1058
+            ->andWhere($q->expr()->eq('uid', $q->createNamedParameter($extraData['uid'])))
1059
+            ->andWhere($q->expr()->eq('calendartype', $q->createNamedParameter($calendarType)));
1060
+
1061
+        $result = $q->execute();
1062
+        $count = (int) $result->fetchColumn();
1063
+        $result->closeCursor();
1064
+
1065
+        if ($count !== 0) {
1066
+            throw new \Sabre\DAV\Exception\BadRequest('Calendar object with uid already exists in this calendar collection.');
1067
+        }
1068
+
1069
+        $query = $this->db->getQueryBuilder();
1070
+        $query->insert('calendarobjects')
1071
+            ->values([
1072
+                'calendarid' => $query->createNamedParameter($calendarId),
1073
+                'uri' => $query->createNamedParameter($objectUri),
1074
+                'calendardata' => $query->createNamedParameter($calendarData, IQueryBuilder::PARAM_LOB),
1075
+                'lastmodified' => $query->createNamedParameter(time()),
1076
+                'etag' => $query->createNamedParameter($extraData['etag']),
1077
+                'size' => $query->createNamedParameter($extraData['size']),
1078
+                'componenttype' => $query->createNamedParameter($extraData['componentType']),
1079
+                'firstoccurence' => $query->createNamedParameter($extraData['firstOccurence']),
1080
+                'lastoccurence' => $query->createNamedParameter($extraData['lastOccurence']),
1081
+                'classification' => $query->createNamedParameter($extraData['classification']),
1082
+                'uid' => $query->createNamedParameter($extraData['uid']),
1083
+                'calendartype' => $query->createNamedParameter($calendarType),
1084
+            ])
1085
+            ->execute();
1086
+
1087
+        $this->updateProperties($calendarId, $objectUri, $calendarData, $calendarType);
1088
+
1089
+        if ($calendarType === self::CALENDAR_TYPE_CALENDAR) {
1090
+            $this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::createCalendarObject', new GenericEvent(
1091
+                '\OCA\DAV\CalDAV\CalDavBackend::createCalendarObject',
1092
+                [
1093
+                    'calendarId' => $calendarId,
1094
+                    'calendarData' => $this->getCalendarById($calendarId),
1095
+                    'shares' => $this->getShares($calendarId),
1096
+                    'objectData' => $this->getCalendarObject($calendarId, $objectUri),
1097
+                ]
1098
+            ));
1099
+        } else {
1100
+            $this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::createCachedCalendarObject', new GenericEvent(
1101
+                '\OCA\DAV\CalDAV\CalDavBackend::createCachedCalendarObject',
1102
+                [
1103
+                    'subscriptionId' => $calendarId,
1104
+                    'calendarData' => $this->getCalendarById($calendarId),
1105
+                    'shares' => $this->getShares($calendarId),
1106
+                    'objectData' => $this->getCalendarObject($calendarId, $objectUri),
1107
+                ]
1108
+            ));
1109
+        }
1110
+        $this->addChange($calendarId, $objectUri, 1, $calendarType);
1111
+
1112
+        return '"' . $extraData['etag'] . '"';
1113
+    }
1114
+
1115
+    /**
1116
+     * Updates an existing calendarobject, based on it's uri.
1117
+     *
1118
+     * The object uri is only the basename, or filename and not a full path.
1119
+     *
1120
+     * It is possible return an etag from this function, which will be used in
1121
+     * the response to this PUT request. Note that the ETag must be surrounded
1122
+     * by double-quotes.
1123
+     *
1124
+     * However, you should only really return this ETag if you don't mangle the
1125
+     * calendar-data. If the result of a subsequent GET to this object is not
1126
+     * the exact same as this request body, you should omit the ETag.
1127
+     *
1128
+     * @param mixed $calendarId
1129
+     * @param string $objectUri
1130
+     * @param string $calendarData
1131
+     * @param int $calendarType
1132
+     * @return string
1133
+     */
1134
+    public function updateCalendarObject($calendarId, $objectUri, $calendarData, $calendarType=self::CALENDAR_TYPE_CALENDAR) {
1135
+        $extraData = $this->getDenormalizedData($calendarData);
1136
+        $query = $this->db->getQueryBuilder();
1137
+        $query->update('calendarobjects')
1138
+                ->set('calendardata', $query->createNamedParameter($calendarData, IQueryBuilder::PARAM_LOB))
1139
+                ->set('lastmodified', $query->createNamedParameter(time()))
1140
+                ->set('etag', $query->createNamedParameter($extraData['etag']))
1141
+                ->set('size', $query->createNamedParameter($extraData['size']))
1142
+                ->set('componenttype', $query->createNamedParameter($extraData['componentType']))
1143
+                ->set('firstoccurence', $query->createNamedParameter($extraData['firstOccurence']))
1144
+                ->set('lastoccurence', $query->createNamedParameter($extraData['lastOccurence']))
1145
+                ->set('classification', $query->createNamedParameter($extraData['classification']))
1146
+                ->set('uid', $query->createNamedParameter($extraData['uid']))
1147
+            ->where($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)))
1148
+            ->andWhere($query->expr()->eq('uri', $query->createNamedParameter($objectUri)))
1149
+            ->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter($calendarType)))
1150
+            ->execute();
1151
+
1152
+        $this->updateProperties($calendarId, $objectUri, $calendarData, $calendarType);
1153
+
1154
+        $data = $this->getCalendarObject($calendarId, $objectUri);
1155
+        if (is_array($data)) {
1156
+            if ($calendarType === self::CALENDAR_TYPE_CALENDAR) {
1157
+                $this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::updateCalendarObject', new GenericEvent(
1158
+                    '\OCA\DAV\CalDAV\CalDavBackend::updateCalendarObject',
1159
+                    [
1160
+                        'calendarId' => $calendarId,
1161
+                        'calendarData' => $this->getCalendarById($calendarId),
1162
+                        'shares' => $this->getShares($calendarId),
1163
+                        'objectData' => $data,
1164
+                    ]
1165
+                ));
1166
+            } else {
1167
+                $this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::updateCachedCalendarObject', new GenericEvent(
1168
+                    '\OCA\DAV\CalDAV\CalDavBackend::updateCachedCalendarObject',
1169
+                    [
1170
+                        'subscriptionId' => $calendarId,
1171
+                        'calendarData' => $this->getCalendarById($calendarId),
1172
+                        'shares' => $this->getShares($calendarId),
1173
+                        'objectData' => $data,
1174
+                    ]
1175
+                ));
1176
+            }
1177
+        }
1178
+        $this->addChange($calendarId, $objectUri, 2, $calendarType);
1179
+
1180
+        return '"' . $extraData['etag'] . '"';
1181
+    }
1182
+
1183
+    /**
1184
+     * @param int $calendarObjectId
1185
+     * @param int $classification
1186
+     */
1187
+    public function setClassification($calendarObjectId, $classification) {
1188
+        if (!in_array($classification, [
1189
+            self::CLASSIFICATION_PUBLIC, self::CLASSIFICATION_PRIVATE, self::CLASSIFICATION_CONFIDENTIAL
1190
+        ])) {
1191
+            throw new \InvalidArgumentException();
1192
+        }
1193
+        $query = $this->db->getQueryBuilder();
1194
+        $query->update('calendarobjects')
1195
+            ->set('classification', $query->createNamedParameter($classification))
1196
+            ->where($query->expr()->eq('id', $query->createNamedParameter($calendarObjectId)))
1197
+            ->execute();
1198
+    }
1199
+
1200
+    /**
1201
+     * Deletes an existing calendar object.
1202
+     *
1203
+     * The object uri is only the basename, or filename and not a full path.
1204
+     *
1205
+     * @param mixed $calendarId
1206
+     * @param string $objectUri
1207
+     * @param int $calendarType
1208
+     * @return void
1209
+     */
1210
+    public function deleteCalendarObject($calendarId, $objectUri, $calendarType=self::CALENDAR_TYPE_CALENDAR) {
1211
+        $data = $this->getCalendarObject($calendarId, $objectUri, $calendarType);
1212
+        if (is_array($data)) {
1213
+            if ($calendarType === self::CALENDAR_TYPE_CALENDAR) {
1214
+                $this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::deleteCalendarObject', new GenericEvent(
1215
+                    '\OCA\DAV\CalDAV\CalDavBackend::deleteCalendarObject',
1216
+                    [
1217
+                        'calendarId' => $calendarId,
1218
+                        'calendarData' => $this->getCalendarById($calendarId),
1219
+                        'shares' => $this->getShares($calendarId),
1220
+                        'objectData' => $data,
1221
+                    ]
1222
+                ));
1223
+            } else {
1224
+                $this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::deleteCachedCalendarObject', new GenericEvent(
1225
+                    '\OCA\DAV\CalDAV\CalDavBackend::deleteCachedCalendarObject',
1226
+                    [
1227
+                        'subscriptionId' => $calendarId,
1228
+                        'calendarData' => $this->getCalendarById($calendarId),
1229
+                        'shares' => $this->getShares($calendarId),
1230
+                        'objectData' => $data,
1231
+                    ]
1232
+                ));
1233
+            }
1234
+        }
1235
+
1236
+        $stmt = $this->db->prepare('DELETE FROM `*PREFIX*calendarobjects` WHERE `calendarid` = ? AND `uri` = ? AND `calendartype` = ?');
1237
+        $stmt->execute([$calendarId, $objectUri, $calendarType]);
1238
+
1239
+        if (is_array($data)) {
1240
+            $this->purgeProperties($calendarId, $data['id'], $calendarType);
1241
+        }
1242
+
1243
+        $this->addChange($calendarId, $objectUri, 3, $calendarType);
1244
+    }
1245
+
1246
+    /**
1247
+     * Performs a calendar-query on the contents of this calendar.
1248
+     *
1249
+     * The calendar-query is defined in RFC4791 : CalDAV. Using the
1250
+     * calendar-query it is possible for a client to request a specific set of
1251
+     * object, based on contents of iCalendar properties, date-ranges and
1252
+     * iCalendar component types (VTODO, VEVENT).
1253
+     *
1254
+     * This method should just return a list of (relative) urls that match this
1255
+     * query.
1256
+     *
1257
+     * The list of filters are specified as an array. The exact array is
1258
+     * documented by Sabre\CalDAV\CalendarQueryParser.
1259
+     *
1260
+     * Note that it is extremely likely that getCalendarObject for every path
1261
+     * returned from this method will be called almost immediately after. You
1262
+     * may want to anticipate this to speed up these requests.
1263
+     *
1264
+     * This method provides a default implementation, which parses *all* the
1265
+     * iCalendar objects in the specified calendar.
1266
+     *
1267
+     * This default may well be good enough for personal use, and calendars
1268
+     * that aren't very large. But if you anticipate high usage, big calendars
1269
+     * or high loads, you are strongly advised to optimize certain paths.
1270
+     *
1271
+     * The best way to do so is override this method and to optimize
1272
+     * specifically for 'common filters'.
1273
+     *
1274
+     * Requests that are extremely common are:
1275
+     *   * requests for just VEVENTS
1276
+     *   * requests for just VTODO
1277
+     *   * requests with a time-range-filter on either VEVENT or VTODO.
1278
+     *
1279
+     * ..and combinations of these requests. It may not be worth it to try to
1280
+     * handle every possible situation and just rely on the (relatively
1281
+     * easy to use) CalendarQueryValidator to handle the rest.
1282
+     *
1283
+     * Note that especially time-range-filters may be difficult to parse. A
1284
+     * time-range filter specified on a VEVENT must for instance also handle
1285
+     * recurrence rules correctly.
1286
+     * A good example of how to interprete all these filters can also simply
1287
+     * be found in Sabre\CalDAV\CalendarQueryFilter. This class is as correct
1288
+     * as possible, so it gives you a good idea on what type of stuff you need
1289
+     * to think of.
1290
+     *
1291
+     * @param mixed $calendarId
1292
+     * @param array $filters
1293
+     * @param int $calendarType
1294
+     * @return array
1295
+     */
1296
+    public function calendarQuery($calendarId, array $filters, $calendarType=self::CALENDAR_TYPE_CALENDAR):array {
1297
+        $componentType = null;
1298
+        $requirePostFilter = true;
1299
+        $timeRange = null;
1300
+
1301
+        // if no filters were specified, we don't need to filter after a query
1302
+        if (!$filters['prop-filters'] && !$filters['comp-filters']) {
1303
+            $requirePostFilter = false;
1304
+        }
1305
+
1306
+        // Figuring out if there's a component filter
1307
+        if (count($filters['comp-filters']) > 0 && !$filters['comp-filters'][0]['is-not-defined']) {
1308
+            $componentType = $filters['comp-filters'][0]['name'];
1309
+
1310
+            // Checking if we need post-filters
1311
+            if (!$filters['prop-filters'] && !$filters['comp-filters'][0]['comp-filters'] && !$filters['comp-filters'][0]['time-range'] && !$filters['comp-filters'][0]['prop-filters']) {
1312
+                $requirePostFilter = false;
1313
+            }
1314
+            // There was a time-range filter
1315
+            if ($componentType === 'VEVENT' && isset($filters['comp-filters'][0]['time-range'])) {
1316
+                $timeRange = $filters['comp-filters'][0]['time-range'];
1317
+
1318
+                // If start time OR the end time is not specified, we can do a
1319
+                // 100% accurate mysql query.
1320
+                if (!$filters['prop-filters'] && !$filters['comp-filters'][0]['comp-filters'] && !$filters['comp-filters'][0]['prop-filters'] && (!$timeRange['start'] || !$timeRange['end'])) {
1321
+                    $requirePostFilter = false;
1322
+                }
1323
+            }
1324
+        }
1325
+        $columns = ['uri'];
1326
+        if ($requirePostFilter) {
1327
+            $columns = ['uri', 'calendardata'];
1328
+        }
1329
+        $query = $this->db->getQueryBuilder();
1330
+        $query->select($columns)
1331
+            ->from('calendarobjects')
1332
+            ->where($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)))
1333
+            ->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter($calendarType)));
1334
+
1335
+        if ($componentType) {
1336
+            $query->andWhere($query->expr()->eq('componenttype', $query->createNamedParameter($componentType)));
1337
+        }
1338
+
1339
+        if ($timeRange && $timeRange['start']) {
1340
+            $query->andWhere($query->expr()->gt('lastoccurence', $query->createNamedParameter($timeRange['start']->getTimeStamp())));
1341
+        }
1342
+        if ($timeRange && $timeRange['end']) {
1343
+            $query->andWhere($query->expr()->lt('firstoccurence', $query->createNamedParameter($timeRange['end']->getTimeStamp())));
1344
+        }
1345
+
1346
+        $stmt = $query->execute();
1347
+
1348
+        $result = [];
1349
+        while ($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1350
+            if ($requirePostFilter) {
1351
+                // validateFilterForObject will parse the calendar data
1352
+                // catch parsing errors
1353
+                try {
1354
+                    $matches = $this->validateFilterForObject($row, $filters);
1355
+                } catch (ParseException $ex) {
1356
+                    $this->logger->logException($ex, [
1357
+                        'app' => 'dav',
1358
+                        'message' => 'Caught parsing exception for calendar data. This usually indicates invalid calendar data. calendar-id:'.$calendarId.' uri:'.$row['uri']
1359
+                    ]);
1360
+                    continue;
1361
+                } catch (InvalidDataException $ex) {
1362
+                    $this->logger->logException($ex, [
1363
+                        'app' => 'dav',
1364
+                        'message' => 'Caught invalid data exception for calendar data. This usually indicates invalid calendar data. calendar-id:'.$calendarId.' uri:'.$row['uri']
1365
+                    ]);
1366
+                    continue;
1367
+                }
1368
+
1369
+                if (!$matches) {
1370
+                    continue;
1371
+                }
1372
+            }
1373
+            $result[] = $row['uri'];
1374
+        }
1375
+
1376
+        return $result;
1377
+    }
1378
+
1379
+    /**
1380
+     * custom Nextcloud search extension for CalDAV
1381
+     *
1382
+     * TODO - this should optionally cover cached calendar objects as well
1383
+     *
1384
+     * @param string $principalUri
1385
+     * @param array $filters
1386
+     * @param integer|null $limit
1387
+     * @param integer|null $offset
1388
+     * @return array
1389
+     */
1390
+    public function calendarSearch($principalUri, array $filters, $limit=null, $offset=null) {
1391
+        $calendars = $this->getCalendarsForUser($principalUri);
1392
+        $ownCalendars = [];
1393
+        $sharedCalendars = [];
1394
+
1395
+        $uriMapper = [];
1396
+
1397
+        foreach ($calendars as $calendar) {
1398
+            if ($calendar['{http://owncloud.org/ns}owner-principal'] === $principalUri) {
1399
+                $ownCalendars[] = $calendar['id'];
1400
+            } else {
1401
+                $sharedCalendars[] = $calendar['id'];
1402
+            }
1403
+            $uriMapper[$calendar['id']] = $calendar['uri'];
1404
+        }
1405
+        if (count($ownCalendars) === 0 && count($sharedCalendars) === 0) {
1406
+            return [];
1407
+        }
1408
+
1409
+        $query = $this->db->getQueryBuilder();
1410
+        // Calendar id expressions
1411
+        $calendarExpressions = [];
1412
+        foreach ($ownCalendars as $id) {
1413
+            $calendarExpressions[] = $query->expr()->andX(
1414
+                $query->expr()->eq('c.calendarid',
1415
+                    $query->createNamedParameter($id)),
1416
+                $query->expr()->eq('c.calendartype',
1417
+                        $query->createNamedParameter(self::CALENDAR_TYPE_CALENDAR)));
1418
+        }
1419
+        foreach ($sharedCalendars as $id) {
1420
+            $calendarExpressions[] = $query->expr()->andX(
1421
+                $query->expr()->eq('c.calendarid',
1422
+                    $query->createNamedParameter($id)),
1423
+                $query->expr()->eq('c.classification',
1424
+                    $query->createNamedParameter(self::CLASSIFICATION_PUBLIC)),
1425
+                $query->expr()->eq('c.calendartype',
1426
+                    $query->createNamedParameter(self::CALENDAR_TYPE_CALENDAR)));
1427
+        }
1428
+
1429
+        if (count($calendarExpressions) === 1) {
1430
+            $calExpr = $calendarExpressions[0];
1431
+        } else {
1432
+            $calExpr = call_user_func_array([$query->expr(), 'orX'], $calendarExpressions);
1433
+        }
1434
+
1435
+        // Component expressions
1436
+        $compExpressions = [];
1437
+        foreach ($filters['comps'] as $comp) {
1438
+            $compExpressions[] = $query->expr()
1439
+                ->eq('c.componenttype', $query->createNamedParameter($comp));
1440
+        }
1441
+
1442
+        if (count($compExpressions) === 1) {
1443
+            $compExpr = $compExpressions[0];
1444
+        } else {
1445
+            $compExpr = call_user_func_array([$query->expr(), 'orX'], $compExpressions);
1446
+        }
1447
+
1448
+        if (!isset($filters['props'])) {
1449
+            $filters['props'] = [];
1450
+        }
1451
+        if (!isset($filters['params'])) {
1452
+            $filters['params'] = [];
1453
+        }
1454
+
1455
+        $propParamExpressions = [];
1456
+        foreach ($filters['props'] as $prop) {
1457
+            $propParamExpressions[] = $query->expr()->andX(
1458
+                $query->expr()->eq('i.name', $query->createNamedParameter($prop)),
1459
+                $query->expr()->isNull('i.parameter')
1460
+            );
1461
+        }
1462
+        foreach ($filters['params'] as $param) {
1463
+            $propParamExpressions[] = $query->expr()->andX(
1464
+                $query->expr()->eq('i.name', $query->createNamedParameter($param['property'])),
1465
+                $query->expr()->eq('i.parameter', $query->createNamedParameter($param['parameter']))
1466
+            );
1467
+        }
1468
+
1469
+        if (count($propParamExpressions) === 1) {
1470
+            $propParamExpr = $propParamExpressions[0];
1471
+        } else {
1472
+            $propParamExpr = call_user_func_array([$query->expr(), 'orX'], $propParamExpressions);
1473
+        }
1474
+
1475
+        $query->select(['c.calendarid', 'c.uri'])
1476
+            ->from($this->dbObjectPropertiesTable, 'i')
1477
+            ->join('i', 'calendarobjects', 'c', $query->expr()->eq('i.objectid', 'c.id'))
1478
+            ->where($calExpr)
1479
+            ->andWhere($compExpr)
1480
+            ->andWhere($propParamExpr)
1481
+            ->andWhere($query->expr()->iLike('i.value',
1482
+                $query->createNamedParameter('%'.$this->db->escapeLikeParameter($filters['search-term']).'%')));
1483
+
1484
+        if ($offset) {
1485
+            $query->setFirstResult($offset);
1486
+        }
1487
+        if ($limit) {
1488
+            $query->setMaxResults($limit);
1489
+        }
1490
+
1491
+        $stmt = $query->execute();
1492
+
1493
+        $result = [];
1494
+        while ($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1495
+            $path = $uriMapper[$row['calendarid']] . '/' . $row['uri'];
1496
+            if (!in_array($path, $result)) {
1497
+                $result[] = $path;
1498
+            }
1499
+        }
1500
+
1501
+        return $result;
1502
+    }
1503
+
1504
+    /**
1505
+     * used for Nextcloud's calendar API
1506
+     *
1507
+     * @param array $calendarInfo
1508
+     * @param string $pattern
1509
+     * @param array $searchProperties
1510
+     * @param array $options
1511
+     * @param integer|null $limit
1512
+     * @param integer|null $offset
1513
+     *
1514
+     * @return array
1515
+     */
1516
+    public function search(array $calendarInfo, $pattern, array $searchProperties,
1517
+                            array $options, $limit, $offset) {
1518
+        $outerQuery = $this->db->getQueryBuilder();
1519
+        $innerQuery = $this->db->getQueryBuilder();
1520
+
1521
+        $innerQuery->selectDistinct('op.objectid')
1522
+            ->from($this->dbObjectPropertiesTable, 'op')
1523
+            ->andWhere($innerQuery->expr()->eq('op.calendarid',
1524
+                $outerQuery->createNamedParameter($calendarInfo['id'])))
1525
+            ->andWhere($innerQuery->expr()->eq('op.calendartype',
1526
+                $outerQuery->createNamedParameter(self::CALENDAR_TYPE_CALENDAR)));
1527
+
1528
+        // only return public items for shared calendars for now
1529
+        if ($calendarInfo['principaluri'] !== $calendarInfo['{http://owncloud.org/ns}owner-principal']) {
1530
+            $innerQuery->andWhere($innerQuery->expr()->eq('c.classification',
1531
+                $outerQuery->createNamedParameter(self::CLASSIFICATION_PUBLIC)));
1532
+        }
1533
+
1534
+        $or = $innerQuery->expr()->orX();
1535
+        foreach ($searchProperties as $searchProperty) {
1536
+            $or->add($innerQuery->expr()->eq('op.name',
1537
+                $outerQuery->createNamedParameter($searchProperty)));
1538
+        }
1539
+        $innerQuery->andWhere($or);
1540
+
1541
+        if ($pattern !== '') {
1542
+            $innerQuery->andWhere($innerQuery->expr()->iLike('op.value',
1543
+                $outerQuery->createNamedParameter('%' .
1544
+                    $this->db->escapeLikeParameter($pattern) . '%')));
1545
+        }
1546
+
1547
+        $outerQuery->select('c.id', 'c.calendardata', 'c.componenttype', 'c.uid', 'c.uri')
1548
+            ->from('calendarobjects', 'c');
1549
+
1550
+        if (isset($options['timerange'])) {
1551
+            if (isset($options['timerange']['start']) && $options['timerange']['start'] instanceof DateTime) {
1552
+                $outerQuery->andWhere($outerQuery->expr()->gt('lastoccurence',
1553
+                    $outerQuery->createNamedParameter($options['timerange']['start']->getTimeStamp())));
1554
+            }
1555
+            if (isset($options['timerange']['end']) && $options['timerange']['end'] instanceof DateTime) {
1556
+                $outerQuery->andWhere($outerQuery->expr()->lt('firstoccurence',
1557
+                    $outerQuery->createNamedParameter($options['timerange']['end']->getTimeStamp())));
1558
+            }
1559
+        }
1560
+
1561
+        if (isset($options['types'])) {
1562
+            $or = $outerQuery->expr()->orX();
1563
+            foreach ($options['types'] as $type) {
1564
+                $or->add($outerQuery->expr()->eq('componenttype',
1565
+                    $outerQuery->createNamedParameter($type)));
1566
+            }
1567
+            $outerQuery->andWhere($or);
1568
+        }
1569
+
1570
+        $outerQuery->andWhere($outerQuery->expr()->in('c.id',
1571
+            $outerQuery->createFunction($innerQuery->getSQL())));
1572
+
1573
+        if ($offset) {
1574
+            $outerQuery->setFirstResult($offset);
1575
+        }
1576
+        if ($limit) {
1577
+            $outerQuery->setMaxResults($limit);
1578
+        }
1579
+
1580
+        $result = $outerQuery->execute();
1581
+        $calendarObjects = $result->fetchAll();
1582
+
1583
+        return array_map(function ($o) {
1584
+            $calendarData = Reader::read($o['calendardata']);
1585
+            $comps = $calendarData->getComponents();
1586
+            $objects = [];
1587
+            $timezones = [];
1588
+            foreach ($comps as $comp) {
1589
+                if ($comp instanceof VTimeZone) {
1590
+                    $timezones[] = $comp;
1591
+                } else {
1592
+                    $objects[] = $comp;
1593
+                }
1594
+            }
1595
+
1596
+            return [
1597
+                'id' => $o['id'],
1598
+                'type' => $o['componenttype'],
1599
+                'uid' => $o['uid'],
1600
+                'uri' => $o['uri'],
1601
+                'objects' => array_map(function ($c) {
1602
+                    return $this->transformSearchData($c);
1603
+                }, $objects),
1604
+                'timezones' => array_map(function ($c) {
1605
+                    return $this->transformSearchData($c);
1606
+                }, $timezones),
1607
+            ];
1608
+        }, $calendarObjects);
1609
+    }
1610
+
1611
+    /**
1612
+     * @param Component $comp
1613
+     * @return array
1614
+     */
1615
+    private function transformSearchData(Component $comp) {
1616
+        $data = [];
1617
+        /** @var Component[] $subComponents */
1618
+        $subComponents = $comp->getComponents();
1619
+        /** @var Property[] $properties */
1620
+        $properties = array_filter($comp->children(), function ($c) {
1621
+            return $c instanceof Property;
1622
+        });
1623
+        $validationRules = $comp->getValidationRules();
1624
+
1625
+        foreach ($subComponents as $subComponent) {
1626
+            $name = $subComponent->name;
1627
+            if (!isset($data[$name])) {
1628
+                $data[$name] = [];
1629
+            }
1630
+            $data[$name][] = $this->transformSearchData($subComponent);
1631
+        }
1632
+
1633
+        foreach ($properties as $property) {
1634
+            $name = $property->name;
1635
+            if (!isset($validationRules[$name])) {
1636
+                $validationRules[$name] = '*';
1637
+            }
1638
+
1639
+            $rule = $validationRules[$property->name];
1640
+            if ($rule === '+' || $rule === '*') { // multiple
1641
+                if (!isset($data[$name])) {
1642
+                    $data[$name] = [];
1643
+                }
1644
+
1645
+                $data[$name][] = $this->transformSearchProperty($property);
1646
+            } else { // once
1647
+                $data[$name] = $this->transformSearchProperty($property);
1648
+            }
1649
+        }
1650
+
1651
+        return $data;
1652
+    }
1653
+
1654
+    /**
1655
+     * @param Property $prop
1656
+     * @return array
1657
+     */
1658
+    private function transformSearchProperty(Property $prop) {
1659
+        // No need to check Date, as it extends DateTime
1660
+        if ($prop instanceof Property\ICalendar\DateTime) {
1661
+            $value = $prop->getDateTime();
1662
+        } else {
1663
+            $value = $prop->getValue();
1664
+        }
1665
+
1666
+        return [
1667
+            $value,
1668
+            $prop->parameters()
1669
+        ];
1670
+    }
1671
+
1672
+    /**
1673
+     * @param string $principalUri
1674
+     * @param string $pattern
1675
+     * @param array $componentTypes
1676
+     * @param array $searchProperties
1677
+     * @param array $searchParameters
1678
+     * @param array $options
1679
+     * @return array
1680
+     */
1681
+    public function searchPrincipalUri(string $principalUri,
1682
+                                        string $pattern,
1683
+                                        array $componentTypes,
1684
+                                        array $searchProperties,
1685
+                                        array $searchParameters,
1686
+                                        array $options = []): array {
1687
+        $escapePattern = !\array_key_exists('escape_like_param', $options) || $options['escape_like_param'] !== false;
1688
+
1689
+        $calendarObjectIdQuery = $this->db->getQueryBuilder();
1690
+        $calendarOr = $calendarObjectIdQuery->expr()->orX();
1691
+        $searchOr = $calendarObjectIdQuery->expr()->orX();
1692
+
1693
+        // Fetch calendars and subscription
1694
+        $calendars = $this->getCalendarsForUser($principalUri);
1695
+        $subscriptions = $this->getSubscriptionsForUser($principalUri);
1696
+        foreach ($calendars as $calendar) {
1697
+            $calendarAnd = $calendarObjectIdQuery->expr()->andX();
1698
+            $calendarAnd->add($calendarObjectIdQuery->expr()->eq('cob.calendarid', $calendarObjectIdQuery->createNamedParameter((int)$calendar['id'])));
1699
+            $calendarAnd->add($calendarObjectIdQuery->expr()->eq('cob.calendartype', $calendarObjectIdQuery->createNamedParameter(self::CALENDAR_TYPE_CALENDAR)));
1700
+
1701
+            // If it's shared, limit search to public events
1702
+            if ($calendar['principaluri'] !== $calendar['{http://owncloud.org/ns}owner-principal']) {
1703
+                $calendarAnd->add($calendarObjectIdQuery->expr()->eq('co.classification', $calendarObjectIdQuery->createNamedParameter(self::CLASSIFICATION_PUBLIC)));
1704
+            }
1705
+
1706
+            $calendarOr->add($calendarAnd);
1707
+        }
1708
+        foreach ($subscriptions as $subscription) {
1709
+            $subscriptionAnd = $calendarObjectIdQuery->expr()->andX();
1710
+            $subscriptionAnd->add($calendarObjectIdQuery->expr()->eq('cob.calendarid', $calendarObjectIdQuery->createNamedParameter((int)$subscription['id'])));
1711
+            $subscriptionAnd->add($calendarObjectIdQuery->expr()->eq('cob.calendartype', $calendarObjectIdQuery->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)));
1712
+
1713
+            // If it's shared, limit search to public events
1714
+            if ($subscription['principaluri'] !== $subscription['{http://owncloud.org/ns}owner-principal']) {
1715
+                $subscriptionAnd->add($calendarObjectIdQuery->expr()->eq('co.classification', $calendarObjectIdQuery->createNamedParameter(self::CLASSIFICATION_PUBLIC)));
1716
+            }
1717
+
1718
+            $calendarOr->add($subscriptionAnd);
1719
+        }
1720
+
1721
+        foreach ($searchProperties as $property) {
1722
+            $propertyAnd = $calendarObjectIdQuery->expr()->andX();
1723
+            $propertyAnd->add($calendarObjectIdQuery->expr()->eq('cob.name', $calendarObjectIdQuery->createNamedParameter($property, IQueryBuilder::PARAM_STR)));
1724
+            $propertyAnd->add($calendarObjectIdQuery->expr()->isNull('cob.parameter'));
1725
+
1726
+            $searchOr->add($propertyAnd);
1727
+        }
1728
+        foreach ($searchParameters as $property => $parameter) {
1729
+            $parameterAnd = $calendarObjectIdQuery->expr()->andX();
1730
+            $parameterAnd->add($calendarObjectIdQuery->expr()->eq('cob.name', $calendarObjectIdQuery->createNamedParameter($property, IQueryBuilder::PARAM_STR)));
1731
+            $parameterAnd->add($calendarObjectIdQuery->expr()->eq('cob.parameter', $calendarObjectIdQuery->createNamedParameter($parameter, IQueryBuilder::PARAM_STR)));
1732
+
1733
+            $searchOr->add($parameterAnd);
1734
+        }
1735
+
1736
+        if ($calendarOr->count() === 0) {
1737
+            return [];
1738
+        }
1739
+        if ($searchOr->count() === 0) {
1740
+            return [];
1741
+        }
1742
+
1743
+        $calendarObjectIdQuery->selectDistinct('cob.objectid')
1744
+            ->from($this->dbObjectPropertiesTable, 'cob')
1745
+            ->leftJoin('cob', 'calendarobjects', 'co', $calendarObjectIdQuery->expr()->eq('co.id', 'cob.objectid'))
1746
+            ->andWhere($calendarObjectIdQuery->expr()->in('co.componenttype', $calendarObjectIdQuery->createNamedParameter($componentTypes, IQueryBuilder::PARAM_STR_ARRAY)))
1747
+            ->andWhere($calendarOr)
1748
+            ->andWhere($searchOr);
1749
+
1750
+        if ('' !== $pattern) {
1751
+            if (!$escapePattern) {
1752
+                $calendarObjectIdQuery->andWhere($calendarObjectIdQuery->expr()->ilike('cob.value', $calendarObjectIdQuery->createNamedParameter($pattern)));
1753
+            } else {
1754
+                $calendarObjectIdQuery->andWhere($calendarObjectIdQuery->expr()->ilike('cob.value', $calendarObjectIdQuery->createNamedParameter('%' . $this->db->escapeLikeParameter($pattern) . '%')));
1755
+            }
1756
+        }
1757
+
1758
+        if (isset($options['limit'])) {
1759
+            $calendarObjectIdQuery->setMaxResults($options['limit']);
1760
+        }
1761
+        if (isset($options['offset'])) {
1762
+            $calendarObjectIdQuery->setFirstResult($options['offset']);
1763
+        }
1764
+
1765
+        $result = $calendarObjectIdQuery->execute();
1766
+        $matches = $result->fetchAll();
1767
+        $result->closeCursor();
1768
+        $matches = array_map(static function (array $match):int {
1769
+            return (int) $match['objectid'];
1770
+        }, $matches);
1771
+
1772
+        $query = $this->db->getQueryBuilder();
1773
+        $query->select('calendardata', 'uri', 'calendarid', 'calendartype')
1774
+            ->from('calendarobjects')
1775
+            ->where($query->expr()->in('id', $query->createNamedParameter($matches, IQueryBuilder::PARAM_INT_ARRAY)));
1776
+
1777
+        $result = $query->execute();
1778
+        $calendarObjects = $result->fetchAll();
1779
+        $result->closeCursor();
1780
+
1781
+        return array_map(function (array $array): array {
1782
+            $array['calendarid'] = (int)$array['calendarid'];
1783
+            $array['calendartype'] = (int)$array['calendartype'];
1784
+            $array['calendardata'] = $this->readBlob($array['calendardata']);
1785
+
1786
+            return $array;
1787
+        }, $calendarObjects);
1788
+    }
1789
+
1790
+    /**
1791
+     * Searches through all of a users calendars and calendar objects to find
1792
+     * an object with a specific UID.
1793
+     *
1794
+     * This method should return the path to this object, relative to the
1795
+     * calendar home, so this path usually only contains two parts:
1796
+     *
1797
+     * calendarpath/objectpath.ics
1798
+     *
1799
+     * If the uid is not found, return null.
1800
+     *
1801
+     * This method should only consider * objects that the principal owns, so
1802
+     * any calendars owned by other principals that also appear in this
1803
+     * collection should be ignored.
1804
+     *
1805
+     * @param string $principalUri
1806
+     * @param string $uid
1807
+     * @return string|null
1808
+     */
1809
+    public function getCalendarObjectByUID($principalUri, $uid) {
1810
+        $query = $this->db->getQueryBuilder();
1811
+        $query->selectAlias('c.uri', 'calendaruri')->selectAlias('co.uri', 'objecturi')
1812
+            ->from('calendarobjects', 'co')
1813
+            ->leftJoin('co', 'calendars', 'c', $query->expr()->eq('co.calendarid', 'c.id'))
1814
+            ->where($query->expr()->eq('c.principaluri', $query->createNamedParameter($principalUri)))
1815
+            ->andWhere($query->expr()->eq('co.uid', $query->createNamedParameter($uid)));
1816
+
1817
+        $stmt = $query->execute();
1818
+
1819
+        if ($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1820
+            return $row['calendaruri'] . '/' . $row['objecturi'];
1821
+        }
1822
+
1823
+        return null;
1824
+    }
1825
+
1826
+    /**
1827
+     * The getChanges method returns all the changes that have happened, since
1828
+     * the specified syncToken in the specified calendar.
1829
+     *
1830
+     * This function should return an array, such as the following:
1831
+     *
1832
+     * [
1833
+     *   'syncToken' => 'The current synctoken',
1834
+     *   'added'   => [
1835
+     *      'new.txt',
1836
+     *   ],
1837
+     *   'modified'   => [
1838
+     *      'modified.txt',
1839
+     *   ],
1840
+     *   'deleted' => [
1841
+     *      'foo.php.bak',
1842
+     *      'old.txt'
1843
+     *   ]
1844
+     * );
1845
+     *
1846
+     * The returned syncToken property should reflect the *current* syncToken
1847
+     * of the calendar, as reported in the {http://sabredav.org/ns}sync-token
1848
+     * property This is * needed here too, to ensure the operation is atomic.
1849
+     *
1850
+     * If the $syncToken argument is specified as null, this is an initial
1851
+     * sync, and all members should be reported.
1852
+     *
1853
+     * The modified property is an array of nodenames that have changed since
1854
+     * the last token.
1855
+     *
1856
+     * The deleted property is an array with nodenames, that have been deleted
1857
+     * from collection.
1858
+     *
1859
+     * The $syncLevel argument is basically the 'depth' of the report. If it's
1860
+     * 1, you only have to report changes that happened only directly in
1861
+     * immediate descendants. If it's 2, it should also include changes from
1862
+     * the nodes below the child collections. (grandchildren)
1863
+     *
1864
+     * The $limit argument allows a client to specify how many results should
1865
+     * be returned at most. If the limit is not specified, it should be treated
1866
+     * as infinite.
1867
+     *
1868
+     * If the limit (infinite or not) is higher than you're willing to return,
1869
+     * you should throw a Sabre\DAV\Exception\TooMuchMatches() exception.
1870
+     *
1871
+     * If the syncToken is expired (due to data cleanup) or unknown, you must
1872
+     * return null.
1873
+     *
1874
+     * The limit is 'suggestive'. You are free to ignore it.
1875
+     *
1876
+     * @param string $calendarId
1877
+     * @param string $syncToken
1878
+     * @param int $syncLevel
1879
+     * @param int $limit
1880
+     * @param int $calendarType
1881
+     * @return array
1882
+     */
1883
+    public function getChangesForCalendar($calendarId, $syncToken, $syncLevel, $limit = null, $calendarType=self::CALENDAR_TYPE_CALENDAR) {
1884
+        // Current synctoken
1885
+        $stmt = $this->db->prepare('SELECT `synctoken` FROM `*PREFIX*calendars` WHERE `id` = ?');
1886
+        $stmt->execute([ $calendarId ]);
1887
+        $currentToken = $stmt->fetchColumn(0);
1888
+
1889
+        if (is_null($currentToken)) {
1890
+            return null;
1891
+        }
1892
+
1893
+        $result = [
1894
+            'syncToken' => $currentToken,
1895
+            'added'     => [],
1896
+            'modified'  => [],
1897
+            'deleted'   => [],
1898
+        ];
1899
+
1900
+        if ($syncToken) {
1901
+            $query = "SELECT `uri`, `operation` FROM `*PREFIX*calendarchanges` WHERE `synctoken` >= ? AND `synctoken` < ? AND `calendarid` = ? AND `calendartype` = ? ORDER BY `synctoken`";
1902
+            if ($limit>0) {
1903
+                $query.= " LIMIT " . (int)$limit;
1904
+            }
1905
+
1906
+            // Fetching all changes
1907
+            $stmt = $this->db->prepare($query);
1908
+            $stmt->execute([$syncToken, $currentToken, $calendarId, $calendarType]);
1909
+
1910
+            $changes = [];
1911
+
1912
+            // This loop ensures that any duplicates are overwritten, only the
1913
+            // last change on a node is relevant.
1914
+            while ($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1915
+                $changes[$row['uri']] = $row['operation'];
1916
+            }
1917
+
1918
+            foreach ($changes as $uri => $operation) {
1919
+                switch ($operation) {
1920
+                    case 1:
1921
+                        $result['added'][] = $uri;
1922
+                        break;
1923
+                    case 2:
1924
+                        $result['modified'][] = $uri;
1925
+                        break;
1926
+                    case 3:
1927
+                        $result['deleted'][] = $uri;
1928
+                        break;
1929
+                }
1930
+            }
1931
+        } else {
1932
+            // No synctoken supplied, this is the initial sync.
1933
+            $query = "SELECT `uri` FROM `*PREFIX*calendarobjects` WHERE `calendarid` = ? AND `calendartype` = ?";
1934
+            $stmt = $this->db->prepare($query);
1935
+            $stmt->execute([$calendarId, $calendarType]);
1936
+
1937
+            $result['added'] = $stmt->fetchAll(\PDO::FETCH_COLUMN);
1938
+        }
1939
+        return $result;
1940
+    }
1941
+
1942
+    /**
1943
+     * Returns a list of subscriptions for a principal.
1944
+     *
1945
+     * Every subscription is an array with the following keys:
1946
+     *  * id, a unique id that will be used by other functions to modify the
1947
+     *    subscription. This can be the same as the uri or a database key.
1948
+     *  * uri. This is just the 'base uri' or 'filename' of the subscription.
1949
+     *  * principaluri. The owner of the subscription. Almost always the same as
1950
+     *    principalUri passed to this method.
1951
+     *
1952
+     * Furthermore, all the subscription info must be returned too:
1953
+     *
1954
+     * 1. {DAV:}displayname
1955
+     * 2. {http://apple.com/ns/ical/}refreshrate
1956
+     * 3. {http://calendarserver.org/ns/}subscribed-strip-todos (omit if todos
1957
+     *    should not be stripped).
1958
+     * 4. {http://calendarserver.org/ns/}subscribed-strip-alarms (omit if alarms
1959
+     *    should not be stripped).
1960
+     * 5. {http://calendarserver.org/ns/}subscribed-strip-attachments (omit if
1961
+     *    attachments should not be stripped).
1962
+     * 6. {http://calendarserver.org/ns/}source (Must be a
1963
+     *     Sabre\DAV\Property\Href).
1964
+     * 7. {http://apple.com/ns/ical/}calendar-color
1965
+     * 8. {http://apple.com/ns/ical/}calendar-order
1966
+     * 9. {urn:ietf:params:xml:ns:caldav}supported-calendar-component-set
1967
+     *    (should just be an instance of
1968
+     *    Sabre\CalDAV\Property\SupportedCalendarComponentSet, with a bunch of
1969
+     *    default components).
1970
+     *
1971
+     * @param string $principalUri
1972
+     * @return array
1973
+     */
1974
+    public function getSubscriptionsForUser($principalUri) {
1975
+        $fields = array_values($this->subscriptionPropertyMap);
1976
+        $fields[] = 'id';
1977
+        $fields[] = 'uri';
1978
+        $fields[] = 'source';
1979
+        $fields[] = 'principaluri';
1980
+        $fields[] = 'lastmodified';
1981
+        $fields[] = 'synctoken';
1982
+
1983
+        $query = $this->db->getQueryBuilder();
1984
+        $query->select($fields)
1985
+            ->from('calendarsubscriptions')
1986
+            ->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
1987
+            ->orderBy('calendarorder', 'asc');
1988
+        $stmt =$query->execute();
1989
+
1990
+        $subscriptions = [];
1991
+        while ($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1992
+            $subscription = [
1993
+                'id'           => $row['id'],
1994
+                'uri'          => $row['uri'],
1995
+                'principaluri' => $row['principaluri'],
1996
+                'source'       => $row['source'],
1997
+                'lastmodified' => $row['lastmodified'],
1998
+
1999
+                '{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet(['VTODO', 'VEVENT']),
2000
+                '{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
2001
+            ];
2002
+
2003
+            foreach ($this->subscriptionPropertyMap as $xmlName=>$dbName) {
2004
+                if (!is_null($row[$dbName])) {
2005
+                    $subscription[$xmlName] = $row[$dbName];
2006
+                }
2007
+            }
2008
+
2009
+            $subscriptions[] = $subscription;
2010
+        }
2011
+
2012
+        return $subscriptions;
2013
+    }
2014
+
2015
+    /**
2016
+     * Creates a new subscription for a principal.
2017
+     *
2018
+     * If the creation was a success, an id must be returned that can be used to reference
2019
+     * this subscription in other methods, such as updateSubscription.
2020
+     *
2021
+     * @param string $principalUri
2022
+     * @param string $uri
2023
+     * @param array $properties
2024
+     * @return mixed
2025
+     */
2026
+    public function createSubscription($principalUri, $uri, array $properties) {
2027
+        if (!isset($properties['{http://calendarserver.org/ns/}source'])) {
2028
+            throw new Forbidden('The {http://calendarserver.org/ns/}source property is required when creating subscriptions');
2029
+        }
2030
+
2031
+        $values = [
2032
+            'principaluri' => $principalUri,
2033
+            'uri'          => $uri,
2034
+            'source'       => $properties['{http://calendarserver.org/ns/}source']->getHref(),
2035
+            'lastmodified' => time(),
2036
+        ];
2037
+
2038
+        $propertiesBoolean = ['striptodos', 'stripalarms', 'stripattachments'];
2039
+
2040
+        foreach ($this->subscriptionPropertyMap as $xmlName=>$dbName) {
2041
+            if (array_key_exists($xmlName, $properties)) {
2042
+                $values[$dbName] = $properties[$xmlName];
2043
+                if (in_array($dbName, $propertiesBoolean)) {
2044
+                    $values[$dbName] = true;
2045
+                }
2046
+            }
2047
+        }
2048
+
2049
+        $valuesToInsert = [];
2050
+
2051
+        $query = $this->db->getQueryBuilder();
2052
+
2053
+        foreach (array_keys($values) as $name) {
2054
+            $valuesToInsert[$name] = $query->createNamedParameter($values[$name]);
2055
+        }
2056
+
2057
+        $query->insert('calendarsubscriptions')
2058
+            ->values($valuesToInsert)
2059
+            ->execute();
2060
+
2061
+        $subscriptionId = $this->db->lastInsertId('*PREFIX*calendarsubscriptions');
2062
+
2063
+        $this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::createSubscription', new GenericEvent(
2064
+            '\OCA\DAV\CalDAV\CalDavBackend::createSubscription',
2065
+            [
2066
+                'subscriptionId' => $subscriptionId,
2067
+                'subscriptionData' => $this->getSubscriptionById($subscriptionId),
2068
+            ]));
2069
+
2070
+        return $subscriptionId;
2071
+    }
2072
+
2073
+    /**
2074
+     * Updates a subscription
2075
+     *
2076
+     * The list of mutations is stored in a Sabre\DAV\PropPatch object.
2077
+     * To do the actual updates, you must tell this object which properties
2078
+     * you're going to process with the handle() method.
2079
+     *
2080
+     * Calling the handle method is like telling the PropPatch object "I
2081
+     * promise I can handle updating this property".
2082
+     *
2083
+     * Read the PropPatch documentation for more info and examples.
2084
+     *
2085
+     * @param mixed $subscriptionId
2086
+     * @param PropPatch $propPatch
2087
+     * @return void
2088
+     */
2089
+    public function updateSubscription($subscriptionId, PropPatch $propPatch) {
2090
+        $supportedProperties = array_keys($this->subscriptionPropertyMap);
2091
+        $supportedProperties[] = '{http://calendarserver.org/ns/}source';
2092
+
2093
+        /**
2094
+         * @suppress SqlInjectionChecker
2095
+         */
2096
+        $propPatch->handle($supportedProperties, function ($mutations) use ($subscriptionId) {
2097
+            $newValues = [];
2098
+
2099
+            foreach ($mutations as $propertyName=>$propertyValue) {
2100
+                if ($propertyName === '{http://calendarserver.org/ns/}source') {
2101
+                    $newValues['source'] = $propertyValue->getHref();
2102
+                } else {
2103
+                    $fieldName = $this->subscriptionPropertyMap[$propertyName];
2104
+                    $newValues[$fieldName] = $propertyValue;
2105
+                }
2106
+            }
2107
+
2108
+            $query = $this->db->getQueryBuilder();
2109
+            $query->update('calendarsubscriptions')
2110
+                ->set('lastmodified', $query->createNamedParameter(time()));
2111
+            foreach ($newValues as $fieldName=>$value) {
2112
+                $query->set($fieldName, $query->createNamedParameter($value));
2113
+            }
2114
+            $query->where($query->expr()->eq('id', $query->createNamedParameter($subscriptionId)))
2115
+                ->execute();
2116
+
2117
+            $this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::updateSubscription', new GenericEvent(
2118
+                '\OCA\DAV\CalDAV\CalDavBackend::updateSubscription',
2119
+                [
2120
+                    'subscriptionId' => $subscriptionId,
2121
+                    'subscriptionData' => $this->getSubscriptionById($subscriptionId),
2122
+                    'propertyMutations' => $mutations,
2123
+                ]));
2124
+
2125
+            return true;
2126
+        });
2127
+    }
2128
+
2129
+    /**
2130
+     * Deletes a subscription.
2131
+     *
2132
+     * @param mixed $subscriptionId
2133
+     * @return void
2134
+     */
2135
+    public function deleteSubscription($subscriptionId) {
2136
+        $this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::deleteSubscription', new GenericEvent(
2137
+            '\OCA\DAV\CalDAV\CalDavBackend::deleteSubscription',
2138
+            [
2139
+                'subscriptionId' => $subscriptionId,
2140
+                'subscriptionData' => $this->getSubscriptionById($subscriptionId),
2141
+            ]));
2142
+
2143
+        $query = $this->db->getQueryBuilder();
2144
+        $query->delete('calendarsubscriptions')
2145
+            ->where($query->expr()->eq('id', $query->createNamedParameter($subscriptionId)))
2146
+            ->execute();
2147
+
2148
+        $query = $this->db->getQueryBuilder();
2149
+        $query->delete('calendarobjects')
2150
+            ->where($query->expr()->eq('calendarid', $query->createNamedParameter($subscriptionId)))
2151
+            ->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)))
2152
+            ->execute();
2153
+
2154
+        $query->delete('calendarchanges')
2155
+            ->where($query->expr()->eq('calendarid', $query->createNamedParameter($subscriptionId)))
2156
+            ->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)))
2157
+            ->execute();
2158
+
2159
+        $query->delete($this->dbObjectPropertiesTable)
2160
+            ->where($query->expr()->eq('calendarid', $query->createNamedParameter($subscriptionId)))
2161
+            ->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)))
2162
+            ->execute();
2163
+    }
2164
+
2165
+    /**
2166
+     * Returns a single scheduling object for the inbox collection.
2167
+     *
2168
+     * The returned array should contain the following elements:
2169
+     *   * uri - A unique basename for the object. This will be used to
2170
+     *           construct a full uri.
2171
+     *   * calendardata - The iCalendar object
2172
+     *   * lastmodified - The last modification date. Can be an int for a unix
2173
+     *                    timestamp, or a PHP DateTime object.
2174
+     *   * etag - A unique token that must change if the object changed.
2175
+     *   * size - The size of the object, in bytes.
2176
+     *
2177
+     * @param string $principalUri
2178
+     * @param string $objectUri
2179
+     * @return array
2180
+     */
2181
+    public function getSchedulingObject($principalUri, $objectUri) {
2182
+        $query = $this->db->getQueryBuilder();
2183
+        $stmt = $query->select(['uri', 'calendardata', 'lastmodified', 'etag', 'size'])
2184
+            ->from('schedulingobjects')
2185
+            ->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
2186
+            ->andWhere($query->expr()->eq('uri', $query->createNamedParameter($objectUri)))
2187
+            ->execute();
2188
+
2189
+        $row = $stmt->fetch(\PDO::FETCH_ASSOC);
2190
+
2191
+        if (!$row) {
2192
+            return null;
2193
+        }
2194
+
2195
+        return [
2196
+            'uri'          => $row['uri'],
2197
+            'calendardata' => $row['calendardata'],
2198
+            'lastmodified' => $row['lastmodified'],
2199
+            'etag'         => '"' . $row['etag'] . '"',
2200
+            'size'         => (int)$row['size'],
2201
+        ];
2202
+    }
2203
+
2204
+    /**
2205
+     * Returns all scheduling objects for the inbox collection.
2206
+     *
2207
+     * These objects should be returned as an array. Every item in the array
2208
+     * should follow the same structure as returned from getSchedulingObject.
2209
+     *
2210
+     * The main difference is that 'calendardata' is optional.
2211
+     *
2212
+     * @param string $principalUri
2213
+     * @return array
2214
+     */
2215
+    public function getSchedulingObjects($principalUri) {
2216
+        $query = $this->db->getQueryBuilder();
2217
+        $stmt = $query->select(['uri', 'calendardata', 'lastmodified', 'etag', 'size'])
2218
+                ->from('schedulingobjects')
2219
+                ->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
2220
+                ->execute();
2221
+
2222
+        $result = [];
2223
+        foreach ($stmt->fetchAll(\PDO::FETCH_ASSOC) as $row) {
2224
+            $result[] = [
2225
+                'calendardata' => $row['calendardata'],
2226
+                'uri'          => $row['uri'],
2227
+                'lastmodified' => $row['lastmodified'],
2228
+                'etag'         => '"' . $row['etag'] . '"',
2229
+                'size'         => (int)$row['size'],
2230
+            ];
2231
+        }
2232
+
2233
+        return $result;
2234
+    }
2235
+
2236
+    /**
2237
+     * Deletes a scheduling object from the inbox collection.
2238
+     *
2239
+     * @param string $principalUri
2240
+     * @param string $objectUri
2241
+     * @return void
2242
+     */
2243
+    public function deleteSchedulingObject($principalUri, $objectUri) {
2244
+        $query = $this->db->getQueryBuilder();
2245
+        $query->delete('schedulingobjects')
2246
+                ->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
2247
+                ->andWhere($query->expr()->eq('uri', $query->createNamedParameter($objectUri)))
2248
+                ->execute();
2249
+    }
2250
+
2251
+    /**
2252
+     * Creates a new scheduling object. This should land in a users' inbox.
2253
+     *
2254
+     * @param string $principalUri
2255
+     * @param string $objectUri
2256
+     * @param string $objectData
2257
+     * @return void
2258
+     */
2259
+    public function createSchedulingObject($principalUri, $objectUri, $objectData) {
2260
+        $query = $this->db->getQueryBuilder();
2261
+        $query->insert('schedulingobjects')
2262
+            ->values([
2263
+                'principaluri' => $query->createNamedParameter($principalUri),
2264
+                'calendardata' => $query->createNamedParameter($objectData, IQueryBuilder::PARAM_LOB),
2265
+                'uri' => $query->createNamedParameter($objectUri),
2266
+                'lastmodified' => $query->createNamedParameter(time()),
2267
+                'etag' => $query->createNamedParameter(md5($objectData)),
2268
+                'size' => $query->createNamedParameter(strlen($objectData))
2269
+            ])
2270
+            ->execute();
2271
+    }
2272
+
2273
+    /**
2274
+     * Adds a change record to the calendarchanges table.
2275
+     *
2276
+     * @param mixed $calendarId
2277
+     * @param string $objectUri
2278
+     * @param int $operation 1 = add, 2 = modify, 3 = delete.
2279
+     * @param int $calendarType
2280
+     * @return void
2281
+     */
2282
+    protected function addChange($calendarId, $objectUri, $operation, $calendarType=self::CALENDAR_TYPE_CALENDAR) {
2283
+        $table = $calendarType === self::CALENDAR_TYPE_CALENDAR ? 'calendars': 'calendarsubscriptions';
2284
+
2285
+        $query = $this->db->getQueryBuilder();
2286
+        $query->select('synctoken')
2287
+            ->from($table)
2288
+            ->where($query->expr()->eq('id', $query->createNamedParameter($calendarId)));
2289
+        $syncToken = (int)$query->execute()->fetchColumn();
2290
+
2291
+        $query = $this->db->getQueryBuilder();
2292
+        $query->insert('calendarchanges')
2293
+            ->values([
2294
+                'uri' => $query->createNamedParameter($objectUri),
2295
+                'synctoken' => $query->createNamedParameter($syncToken),
2296
+                'calendarid' => $query->createNamedParameter($calendarId),
2297
+                'operation' => $query->createNamedParameter($operation),
2298
+                'calendartype' => $query->createNamedParameter($calendarType),
2299
+            ])
2300
+            ->execute();
2301
+
2302
+        $stmt = $this->db->prepare("UPDATE `*PREFIX*$table` SET `synctoken` = `synctoken` + 1 WHERE `id` = ?");
2303
+        $stmt->execute([
2304
+            $calendarId
2305
+        ]);
2306
+    }
2307
+
2308
+    /**
2309
+     * Parses some information from calendar objects, used for optimized
2310
+     * calendar-queries.
2311
+     *
2312
+     * Returns an array with the following keys:
2313
+     *   * etag - An md5 checksum of the object without the quotes.
2314
+     *   * size - Size of the object in bytes
2315
+     *   * componentType - VEVENT, VTODO or VJOURNAL
2316
+     *   * firstOccurence
2317
+     *   * lastOccurence
2318
+     *   * uid - value of the UID property
2319
+     *
2320
+     * @param string $calendarData
2321
+     * @return array
2322
+     */
2323
+    public function getDenormalizedData($calendarData) {
2324
+        $vObject = Reader::read($calendarData);
2325
+        $componentType = null;
2326
+        $component = null;
2327
+        $firstOccurrence = null;
2328
+        $lastOccurrence = null;
2329
+        $uid = null;
2330
+        $classification = self::CLASSIFICATION_PUBLIC;
2331
+        foreach ($vObject->getComponents() as $component) {
2332
+            if ($component->name!=='VTIMEZONE') {
2333
+                $componentType = $component->name;
2334
+                $uid = (string)$component->UID;
2335
+                break;
2336
+            }
2337
+        }
2338
+        if (!$componentType) {
2339
+            throw new \Sabre\DAV\Exception\BadRequest('Calendar objects must have a VJOURNAL, VEVENT or VTODO component');
2340
+        }
2341
+        if ($componentType === 'VEVENT' && $component->DTSTART) {
2342
+            $firstOccurrence = $component->DTSTART->getDateTime()->getTimeStamp();
2343
+            // Finding the last occurrence is a bit harder
2344
+            if (!isset($component->RRULE)) {
2345
+                if (isset($component->DTEND)) {
2346
+                    $lastOccurrence = $component->DTEND->getDateTime()->getTimeStamp();
2347
+                } elseif (isset($component->DURATION)) {
2348
+                    $endDate = clone $component->DTSTART->getDateTime();
2349
+                    $endDate->add(DateTimeParser::parse($component->DURATION->getValue()));
2350
+                    $lastOccurrence = $endDate->getTimeStamp();
2351
+                } elseif (!$component->DTSTART->hasTime()) {
2352
+                    $endDate = clone $component->DTSTART->getDateTime();
2353
+                    $endDate->modify('+1 day');
2354
+                    $lastOccurrence = $endDate->getTimeStamp();
2355
+                } else {
2356
+                    $lastOccurrence = $firstOccurrence;
2357
+                }
2358
+            } else {
2359
+                $it = new EventIterator($vObject, (string)$component->UID);
2360
+                $maxDate = new DateTime(self::MAX_DATE);
2361
+                if ($it->isInfinite()) {
2362
+                    $lastOccurrence = $maxDate->getTimestamp();
2363
+                } else {
2364
+                    $end = $it->getDtEnd();
2365
+                    while ($it->valid() && $end < $maxDate) {
2366
+                        $end = $it->getDtEnd();
2367
+                        $it->next();
2368
+                    }
2369
+                    $lastOccurrence = $end->getTimestamp();
2370
+                }
2371
+            }
2372
+        }
2373
+
2374
+        if ($component->CLASS) {
2375
+            $classification = CalDavBackend::CLASSIFICATION_PRIVATE;
2376
+            switch ($component->CLASS->getValue()) {
2377
+                case 'PUBLIC':
2378
+                    $classification = CalDavBackend::CLASSIFICATION_PUBLIC;
2379
+                    break;
2380
+                case 'CONFIDENTIAL':
2381
+                    $classification = CalDavBackend::CLASSIFICATION_CONFIDENTIAL;
2382
+                    break;
2383
+            }
2384
+        }
2385
+        return [
2386
+            'etag' => md5($calendarData),
2387
+            'size' => strlen($calendarData),
2388
+            'componentType' => $componentType,
2389
+            'firstOccurence' => is_null($firstOccurrence) ? null : max(0, $firstOccurrence),
2390
+            'lastOccurence'  => $lastOccurrence,
2391
+            'uid' => $uid,
2392
+            'classification' => $classification
2393
+        ];
2394
+    }
2395
+
2396
+    /**
2397
+     * @param $cardData
2398
+     * @return bool|string
2399
+     */
2400
+    private function readBlob($cardData) {
2401
+        if (is_resource($cardData)) {
2402
+            return stream_get_contents($cardData);
2403
+        }
2404
+
2405
+        return $cardData;
2406
+    }
2407
+
2408
+    /**
2409
+     * @param IShareable $shareable
2410
+     * @param array $add
2411
+     * @param array $remove
2412
+     */
2413
+    public function updateShares($shareable, $add, $remove) {
2414
+        $calendarId = $shareable->getResourceId();
2415
+        $this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::updateShares', new GenericEvent(
2416
+            '\OCA\DAV\CalDAV\CalDavBackend::updateShares',
2417
+            [
2418
+                'calendarId' => $calendarId,
2419
+                'calendarData' => $this->getCalendarById($calendarId),
2420
+                'shares' => $this->getShares($calendarId),
2421
+                'add' => $add,
2422
+                'remove' => $remove,
2423
+            ]));
2424
+        $this->calendarSharingBackend->updateShares($shareable, $add, $remove);
2425
+    }
2426
+
2427
+    /**
2428
+     * @param int $resourceId
2429
+     * @param int $calendarType
2430
+     * @return array
2431
+     */
2432
+    public function getShares($resourceId, $calendarType=self::CALENDAR_TYPE_CALENDAR) {
2433
+        return $this->calendarSharingBackend->getShares($resourceId);
2434
+    }
2435
+
2436
+    /**
2437
+     * @param boolean $value
2438
+     * @param \OCA\DAV\CalDAV\Calendar $calendar
2439
+     * @return string|null
2440
+     */
2441
+    public function setPublishStatus($value, $calendar) {
2442
+        $calendarId = $calendar->getResourceId();
2443
+        $this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::publishCalendar', new GenericEvent(
2444
+            '\OCA\DAV\CalDAV\CalDavBackend::updateShares',
2445
+            [
2446
+                'calendarId' => $calendarId,
2447
+                'calendarData' => $this->getCalendarById($calendarId),
2448
+                'public' => $value,
2449
+            ]));
2450
+
2451
+        $query = $this->db->getQueryBuilder();
2452
+        if ($value) {
2453
+            $publicUri = $this->random->generate(16, ISecureRandom::CHAR_HUMAN_READABLE);
2454
+            $query->insert('dav_shares')
2455
+                ->values([
2456
+                    'principaluri' => $query->createNamedParameter($calendar->getPrincipalURI()),
2457
+                    'type' => $query->createNamedParameter('calendar'),
2458
+                    'access' => $query->createNamedParameter(self::ACCESS_PUBLIC),
2459
+                    'resourceid' => $query->createNamedParameter($calendar->getResourceId()),
2460
+                    'publicuri' => $query->createNamedParameter($publicUri)
2461
+                ]);
2462
+            $query->execute();
2463
+            return $publicUri;
2464
+        }
2465
+        $query->delete('dav_shares')
2466
+            ->where($query->expr()->eq('resourceid', $query->createNamedParameter($calendar->getResourceId())))
2467
+            ->andWhere($query->expr()->eq('access', $query->createNamedParameter(self::ACCESS_PUBLIC)));
2468
+        $query->execute();
2469
+        return null;
2470
+    }
2471
+
2472
+    /**
2473
+     * @param \OCA\DAV\CalDAV\Calendar $calendar
2474
+     * @return mixed
2475
+     */
2476
+    public function getPublishStatus($calendar) {
2477
+        $query = $this->db->getQueryBuilder();
2478
+        $result = $query->select('publicuri')
2479
+            ->from('dav_shares')
2480
+            ->where($query->expr()->eq('resourceid', $query->createNamedParameter($calendar->getResourceId())))
2481
+            ->andWhere($query->expr()->eq('access', $query->createNamedParameter(self::ACCESS_PUBLIC)))
2482
+            ->execute();
2483
+
2484
+        $row = $result->fetch();
2485
+        $result->closeCursor();
2486
+        return $row ? reset($row) : false;
2487
+    }
2488
+
2489
+    /**
2490
+     * @param int $resourceId
2491
+     * @param array $acl
2492
+     * @return array
2493
+     */
2494
+    public function applyShareAcl($resourceId, $acl) {
2495
+        return $this->calendarSharingBackend->applyShareAcl($resourceId, $acl);
2496
+    }
2497
+
2498
+
2499
+
2500
+    /**
2501
+     * update properties table
2502
+     *
2503
+     * @param int $calendarId
2504
+     * @param string $objectUri
2505
+     * @param string $calendarData
2506
+     * @param int $calendarType
2507
+     */
2508
+    public function updateProperties($calendarId, $objectUri, $calendarData, $calendarType=self::CALENDAR_TYPE_CALENDAR) {
2509
+        $objectId = $this->getCalendarObjectId($calendarId, $objectUri, $calendarType);
2510
+
2511
+        try {
2512
+            $vCalendar = $this->readCalendarData($calendarData);
2513
+        } catch (\Exception $ex) {
2514
+            return;
2515
+        }
2516
+
2517
+        $this->purgeProperties($calendarId, $objectId);
2518
+
2519
+        $query = $this->db->getQueryBuilder();
2520
+        $query->insert($this->dbObjectPropertiesTable)
2521
+            ->values(
2522
+                [
2523
+                    'calendarid' => $query->createNamedParameter($calendarId),
2524
+                    'calendartype' => $query->createNamedParameter($calendarType),
2525
+                    'objectid' => $query->createNamedParameter($objectId),
2526
+                    'name' => $query->createParameter('name'),
2527
+                    'parameter' => $query->createParameter('parameter'),
2528
+                    'value' => $query->createParameter('value'),
2529
+                ]
2530
+            );
2531
+
2532
+        $indexComponents = ['VEVENT', 'VJOURNAL', 'VTODO'];
2533
+        foreach ($vCalendar->getComponents() as $component) {
2534
+            if (!in_array($component->name, $indexComponents)) {
2535
+                continue;
2536
+            }
2537
+
2538
+            foreach ($component->children() as $property) {
2539
+                if (in_array($property->name, self::$indexProperties)) {
2540
+                    $value = $property->getValue();
2541
+                    // is this a shitty db?
2542
+                    if (!$this->db->supports4ByteText()) {
2543
+                        $value = preg_replace('/[\x{10000}-\x{10FFFF}]/u', "\xEF\xBF\xBD", $value);
2544
+                    }
2545
+                    $value = mb_substr($value, 0, 254);
2546
+
2547
+                    $query->setParameter('name', $property->name);
2548
+                    $query->setParameter('parameter', null);
2549
+                    $query->setParameter('value', $value);
2550
+                    $query->execute();
2551
+                }
2552
+
2553
+                if (array_key_exists($property->name, self::$indexParameters)) {
2554
+                    $parameters = $property->parameters();
2555
+                    $indexedParametersForProperty = self::$indexParameters[$property->name];
2556
+
2557
+                    foreach ($parameters as $key => $value) {
2558
+                        if (in_array($key, $indexedParametersForProperty)) {
2559
+                            // is this a shitty db?
2560
+                            if ($this->db->supports4ByteText()) {
2561
+                                $value = preg_replace('/[\x{10000}-\x{10FFFF}]/u', "\xEF\xBF\xBD", $value);
2562
+                            }
2563
+
2564
+                            $query->setParameter('name', $property->name);
2565
+                            $query->setParameter('parameter', mb_substr($key, 0, 254));
2566
+                            $query->setParameter('value', mb_substr($value, 0, 254));
2567
+                            $query->execute();
2568
+                        }
2569
+                    }
2570
+                }
2571
+            }
2572
+        }
2573
+    }
2574
+
2575
+    /**
2576
+     * deletes all birthday calendars
2577
+     */
2578
+    public function deleteAllBirthdayCalendars() {
2579
+        $query = $this->db->getQueryBuilder();
2580
+        $result = $query->select(['id'])->from('calendars')
2581
+            ->where($query->expr()->eq('uri', $query->createNamedParameter(BirthdayService::BIRTHDAY_CALENDAR_URI)))
2582
+            ->execute();
2583
+
2584
+        $ids = $result->fetchAll();
2585
+        foreach ($ids as $id) {
2586
+            $this->deleteCalendar($id['id']);
2587
+        }
2588
+    }
2589
+
2590
+    /**
2591
+     * @param $subscriptionId
2592
+     */
2593
+    public function purgeAllCachedEventsForSubscription($subscriptionId) {
2594
+        $query = $this->db->getQueryBuilder();
2595
+        $query->select('uri')
2596
+            ->from('calendarobjects')
2597
+            ->where($query->expr()->eq('calendarid', $query->createNamedParameter($subscriptionId)))
2598
+            ->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)));
2599
+        $stmt = $query->execute();
2600
+
2601
+        $uris = [];
2602
+        foreach ($stmt->fetchAll(\PDO::FETCH_ASSOC) as $row) {
2603
+            $uris[] = $row['uri'];
2604
+        }
2605
+        $stmt->closeCursor();
2606
+
2607
+        $query = $this->db->getQueryBuilder();
2608
+        $query->delete('calendarobjects')
2609
+            ->where($query->expr()->eq('calendarid', $query->createNamedParameter($subscriptionId)))
2610
+            ->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)))
2611
+            ->execute();
2612
+
2613
+        $query->delete('calendarchanges')
2614
+            ->where($query->expr()->eq('calendarid', $query->createNamedParameter($subscriptionId)))
2615
+            ->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)))
2616
+            ->execute();
2617
+
2618
+        $query->delete($this->dbObjectPropertiesTable)
2619
+            ->where($query->expr()->eq('calendarid', $query->createNamedParameter($subscriptionId)))
2620
+            ->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)))
2621
+            ->execute();
2622
+
2623
+        foreach ($uris as $uri) {
2624
+            $this->addChange($subscriptionId, $uri, 3, self::CALENDAR_TYPE_SUBSCRIPTION);
2625
+        }
2626
+    }
2627
+
2628
+    /**
2629
+     * Move a calendar from one user to another
2630
+     *
2631
+     * @param string $uriName
2632
+     * @param string $uriOrigin
2633
+     * @param string $uriDestination
2634
+     */
2635
+    public function moveCalendar($uriName, $uriOrigin, $uriDestination) {
2636
+        $query = $this->db->getQueryBuilder();
2637
+        $query->update('calendars')
2638
+            ->set('principaluri', $query->createNamedParameter($uriDestination))
2639
+            ->where($query->expr()->eq('principaluri', $query->createNamedParameter($uriOrigin)))
2640
+            ->andWhere($query->expr()->eq('uri', $query->createNamedParameter($uriName)))
2641
+            ->execute();
2642
+    }
2643
+
2644
+    /**
2645
+     * read VCalendar data into a VCalendar object
2646
+     *
2647
+     * @param string $objectData
2648
+     * @return VCalendar
2649
+     */
2650
+    protected function readCalendarData($objectData) {
2651
+        return Reader::read($objectData);
2652
+    }
2653
+
2654
+    /**
2655
+     * delete all properties from a given calendar object
2656
+     *
2657
+     * @param int $calendarId
2658
+     * @param int $objectId
2659
+     */
2660
+    protected function purgeProperties($calendarId, $objectId) {
2661
+        $query = $this->db->getQueryBuilder();
2662
+        $query->delete($this->dbObjectPropertiesTable)
2663
+            ->where($query->expr()->eq('objectid', $query->createNamedParameter($objectId)))
2664
+            ->andWhere($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)));
2665
+        $query->execute();
2666
+    }
2667
+
2668
+    /**
2669
+     * get ID from a given calendar object
2670
+     *
2671
+     * @param int $calendarId
2672
+     * @param string $uri
2673
+     * @param int $calendarType
2674
+     * @return int
2675
+     */
2676
+    protected function getCalendarObjectId($calendarId, $uri, $calendarType):int {
2677
+        $query = $this->db->getQueryBuilder();
2678
+        $query->select('id')
2679
+            ->from('calendarobjects')
2680
+            ->where($query->expr()->eq('uri', $query->createNamedParameter($uri)))
2681
+            ->andWhere($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)))
2682
+            ->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter($calendarType)));
2683
+
2684
+        $result = $query->execute();
2685
+        $objectIds = $result->fetch();
2686
+        $result->closeCursor();
2687
+
2688
+        if (!isset($objectIds['id'])) {
2689
+            throw new \InvalidArgumentException('Calendarobject does not exists: ' . $uri);
2690
+        }
2691
+
2692
+        return (int)$objectIds['id'];
2693
+    }
2694
+
2695
+    /**
2696
+     * return legacy endpoint principal name to new principal name
2697
+     *
2698
+     * @param $principalUri
2699
+     * @param $toV2
2700
+     * @return string
2701
+     */
2702
+    private function convertPrincipal($principalUri, $toV2) {
2703
+        if ($this->principalBackend->getPrincipalPrefix() === 'principals') {
2704
+            list(, $name) = Uri\split($principalUri);
2705
+            if ($toV2 === true) {
2706
+                return "principals/users/$name";
2707
+            }
2708
+            return "principals/$name";
2709
+        }
2710
+        return $principalUri;
2711
+    }
2712
+
2713
+    /**
2714
+     * adds information about an owner to the calendar data
2715
+     *
2716
+     * @param $calendarInfo
2717
+     */
2718
+    private function addOwnerPrincipal(&$calendarInfo) {
2719
+        $ownerPrincipalKey = '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal';
2720
+        $displaynameKey = '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_NEXTCLOUD . '}owner-displayname';
2721
+        if (isset($calendarInfo[$ownerPrincipalKey])) {
2722
+            $uri = $calendarInfo[$ownerPrincipalKey];
2723
+        } else {
2724
+            $uri = $calendarInfo['principaluri'];
2725
+        }
2726
+
2727
+        $principalInformation = $this->principalBackend->getPrincipalByPath($uri);
2728
+        if (isset($principalInformation['{DAV:}displayname'])) {
2729
+            $calendarInfo[$displaynameKey] = $principalInformation['{DAV:}displayname'];
2730
+        }
2731
+    }
2732 2732
 }
Please login to merge, or discard this patch.
apps/dav/lib/Connector/Sabre/ObjectTree.php 1 patch
Indentation   +199 added lines, -199 removed lines patch added patch discarded remove patch
@@ -41,203 +41,203 @@
 block discarded – undo
41 41
 
42 42
 class ObjectTree extends CachingTree {
43 43
 
44
-	/**
45
-	 * @var \OC\Files\View
46
-	 */
47
-	protected $fileView;
48
-
49
-	/**
50
-	 * @var  \OCP\Files\Mount\IMountManager
51
-	 */
52
-	protected $mountManager;
53
-
54
-	/**
55
-	 * Creates the object
56
-	 */
57
-	public function __construct() {
58
-	}
59
-
60
-	/**
61
-	 * @param \Sabre\DAV\INode $rootNode
62
-	 * @param \OC\Files\View $view
63
-	 * @param  \OCP\Files\Mount\IMountManager $mountManager
64
-	 */
65
-	public function init(\Sabre\DAV\INode $rootNode, \OC\Files\View $view, \OCP\Files\Mount\IMountManager $mountManager) {
66
-		$this->rootNode = $rootNode;
67
-		$this->fileView = $view;
68
-		$this->mountManager = $mountManager;
69
-	}
70
-
71
-	/**
72
-	 * If the given path is a chunked file name, converts it
73
-	 * to the real file name. Only applies if the OC-CHUNKED header
74
-	 * is present.
75
-	 *
76
-	 * @param string $path chunk file path to convert
77
-	 *
78
-	 * @return string path to real file
79
-	 */
80
-	private function resolveChunkFile($path) {
81
-		if (isset($_SERVER['HTTP_OC_CHUNKED'])) {
82
-			// resolve to real file name to find the proper node
83
-			list($dir, $name) = \Sabre\Uri\split($path);
84
-			if ($dir === '/' || $dir === '.') {
85
-				$dir = '';
86
-			}
87
-
88
-			$info = \OC_FileChunking::decodeName($name);
89
-			// only replace path if it was really the chunked file
90
-			if (isset($info['transferid'])) {
91
-				// getNodePath is called for multiple nodes within a chunk
92
-				// upload call
93
-				$path = $dir . '/' . $info['name'];
94
-				$path = ltrim($path, '/');
95
-			}
96
-		}
97
-		return $path;
98
-	}
99
-
100
-	/**
101
-	 * Returns the INode object for the requested path
102
-	 *
103
-	 * @param string $path
104
-	 * @return \Sabre\DAV\INode
105
-	 * @throws InvalidPath
106
-	 * @throws \Sabre\DAV\Exception\Locked
107
-	 * @throws \Sabre\DAV\Exception\NotFound
108
-	 * @throws \Sabre\DAV\Exception\ServiceUnavailable
109
-	 */
110
-	public function getNodeForPath($path) {
111
-		if (!$this->fileView) {
112
-			throw new \Sabre\DAV\Exception\ServiceUnavailable('filesystem not setup');
113
-		}
114
-
115
-		$path = trim($path, '/');
116
-
117
-		if (isset($this->cache[$path])) {
118
-			return $this->cache[$path];
119
-		}
120
-
121
-		if ($path) {
122
-			try {
123
-				$this->fileView->verifyPath($path, basename($path));
124
-			} catch (\OCP\Files\InvalidPathException $ex) {
125
-				throw new InvalidPath($ex->getMessage());
126
-			}
127
-		}
128
-
129
-		// Is it the root node?
130
-		if (!strlen($path)) {
131
-			return $this->rootNode;
132
-		}
133
-
134
-		if (pathinfo($path, PATHINFO_EXTENSION) === 'part') {
135
-			// read from storage
136
-			$absPath = $this->fileView->getAbsolutePath($path);
137
-			$mount = $this->fileView->getMount($path);
138
-			$storage = $mount->getStorage();
139
-			$internalPath = $mount->getInternalPath($absPath);
140
-			if ($storage && $storage->file_exists($internalPath)) {
141
-				/**
142
-				 * @var \OC\Files\Storage\Storage $storage
143
-				 */
144
-				// get data directly
145
-				$data = $storage->getMetaData($internalPath);
146
-				$info = new FileInfo($absPath, $storage, $internalPath, $data, $mount);
147
-			} else {
148
-				$info = null;
149
-			}
150
-		} else {
151
-			// resolve chunk file name to real name, if applicable
152
-			$path = $this->resolveChunkFile($path);
153
-
154
-			// read from cache
155
-			try {
156
-				$info = $this->fileView->getFileInfo($path);
157
-
158
-				if ($info instanceof \OCP\Files\FileInfo && $info->getStorage()->instanceOfStorage(FailedStorage::class)) {
159
-					throw new StorageNotAvailableException();
160
-				}
161
-			} catch (StorageNotAvailableException $e) {
162
-				throw new \Sabre\DAV\Exception\ServiceUnavailable('Storage is temporarily not available', 0, $e);
163
-			} catch (StorageInvalidException $e) {
164
-				throw new \Sabre\DAV\Exception\NotFound('Storage ' . $path . ' is invalid');
165
-			} catch (LockedException $e) {
166
-				throw new \Sabre\DAV\Exception\Locked();
167
-			} catch (ForbiddenException $e) {
168
-				throw new \Sabre\DAV\Exception\Forbidden();
169
-			}
170
-		}
171
-
172
-		if (!$info) {
173
-			throw new \Sabre\DAV\Exception\NotFound('File with name ' . $path . ' could not be located');
174
-		}
175
-
176
-		if ($info->getType() === 'dir') {
177
-			$node = new \OCA\DAV\Connector\Sabre\Directory($this->fileView, $info, $this);
178
-		} else {
179
-			$node = new \OCA\DAV\Connector\Sabre\File($this->fileView, $info);
180
-		}
181
-
182
-		$this->cache[$path] = $node;
183
-		return $node;
184
-	}
185
-
186
-	/**
187
-	 * Copies a file or directory.
188
-	 *
189
-	 * This method must work recursively and delete the destination
190
-	 * if it exists
191
-	 *
192
-	 * @param string $sourcePath
193
-	 * @param string $destinationPath
194
-	 * @throws FileLocked
195
-	 * @throws Forbidden
196
-	 * @throws InvalidPath
197
-	 * @throws \Exception
198
-	 * @throws \Sabre\DAV\Exception\Forbidden
199
-	 * @throws \Sabre\DAV\Exception\Locked
200
-	 * @throws \Sabre\DAV\Exception\NotFound
201
-	 * @throws \Sabre\DAV\Exception\ServiceUnavailable
202
-	 * @return void
203
-	 */
204
-	public function copy($sourcePath, $destinationPath) {
205
-		if (!$this->fileView) {
206
-			throw new \Sabre\DAV\Exception\ServiceUnavailable('filesystem not setup');
207
-		}
208
-
209
-
210
-		$info = $this->fileView->getFileInfo(dirname($destinationPath));
211
-		if ($this->fileView->file_exists($destinationPath)) {
212
-			$destinationPermission = $info && $info->isUpdateable();
213
-		} else {
214
-			$destinationPermission = $info && $info->isCreatable();
215
-		}
216
-		if (!$destinationPermission) {
217
-			throw new Forbidden('No permissions to copy object.');
218
-		}
219
-
220
-		// this will trigger existence check
221
-		$this->getNodeForPath($sourcePath);
222
-
223
-		list($destinationDir, $destinationName) = \Sabre\Uri\split($destinationPath);
224
-		try {
225
-			$this->fileView->verifyPath($destinationDir, $destinationName);
226
-		} catch (\OCP\Files\InvalidPathException $ex) {
227
-			throw new InvalidPath($ex->getMessage());
228
-		}
229
-
230
-		try {
231
-			$this->fileView->copy($sourcePath, $destinationPath);
232
-		} catch (StorageNotAvailableException $e) {
233
-			throw new \Sabre\DAV\Exception\ServiceUnavailable($e->getMessage());
234
-		} catch (ForbiddenException $ex) {
235
-			throw new Forbidden($ex->getMessage(), $ex->getRetry());
236
-		} catch (LockedException $e) {
237
-			throw new FileLocked($e->getMessage(), $e->getCode(), $e);
238
-		}
239
-
240
-		list($destinationDir,) = \Sabre\Uri\split($destinationPath);
241
-		$this->markDirty($destinationDir);
242
-	}
44
+    /**
45
+     * @var \OC\Files\View
46
+     */
47
+    protected $fileView;
48
+
49
+    /**
50
+     * @var  \OCP\Files\Mount\IMountManager
51
+     */
52
+    protected $mountManager;
53
+
54
+    /**
55
+     * Creates the object
56
+     */
57
+    public function __construct() {
58
+    }
59
+
60
+    /**
61
+     * @param \Sabre\DAV\INode $rootNode
62
+     * @param \OC\Files\View $view
63
+     * @param  \OCP\Files\Mount\IMountManager $mountManager
64
+     */
65
+    public function init(\Sabre\DAV\INode $rootNode, \OC\Files\View $view, \OCP\Files\Mount\IMountManager $mountManager) {
66
+        $this->rootNode = $rootNode;
67
+        $this->fileView = $view;
68
+        $this->mountManager = $mountManager;
69
+    }
70
+
71
+    /**
72
+     * If the given path is a chunked file name, converts it
73
+     * to the real file name. Only applies if the OC-CHUNKED header
74
+     * is present.
75
+     *
76
+     * @param string $path chunk file path to convert
77
+     *
78
+     * @return string path to real file
79
+     */
80
+    private function resolveChunkFile($path) {
81
+        if (isset($_SERVER['HTTP_OC_CHUNKED'])) {
82
+            // resolve to real file name to find the proper node
83
+            list($dir, $name) = \Sabre\Uri\split($path);
84
+            if ($dir === '/' || $dir === '.') {
85
+                $dir = '';
86
+            }
87
+
88
+            $info = \OC_FileChunking::decodeName($name);
89
+            // only replace path if it was really the chunked file
90
+            if (isset($info['transferid'])) {
91
+                // getNodePath is called for multiple nodes within a chunk
92
+                // upload call
93
+                $path = $dir . '/' . $info['name'];
94
+                $path = ltrim($path, '/');
95
+            }
96
+        }
97
+        return $path;
98
+    }
99
+
100
+    /**
101
+     * Returns the INode object for the requested path
102
+     *
103
+     * @param string $path
104
+     * @return \Sabre\DAV\INode
105
+     * @throws InvalidPath
106
+     * @throws \Sabre\DAV\Exception\Locked
107
+     * @throws \Sabre\DAV\Exception\NotFound
108
+     * @throws \Sabre\DAV\Exception\ServiceUnavailable
109
+     */
110
+    public function getNodeForPath($path) {
111
+        if (!$this->fileView) {
112
+            throw new \Sabre\DAV\Exception\ServiceUnavailable('filesystem not setup');
113
+        }
114
+
115
+        $path = trim($path, '/');
116
+
117
+        if (isset($this->cache[$path])) {
118
+            return $this->cache[$path];
119
+        }
120
+
121
+        if ($path) {
122
+            try {
123
+                $this->fileView->verifyPath($path, basename($path));
124
+            } catch (\OCP\Files\InvalidPathException $ex) {
125
+                throw new InvalidPath($ex->getMessage());
126
+            }
127
+        }
128
+
129
+        // Is it the root node?
130
+        if (!strlen($path)) {
131
+            return $this->rootNode;
132
+        }
133
+
134
+        if (pathinfo($path, PATHINFO_EXTENSION) === 'part') {
135
+            // read from storage
136
+            $absPath = $this->fileView->getAbsolutePath($path);
137
+            $mount = $this->fileView->getMount($path);
138
+            $storage = $mount->getStorage();
139
+            $internalPath = $mount->getInternalPath($absPath);
140
+            if ($storage && $storage->file_exists($internalPath)) {
141
+                /**
142
+                 * @var \OC\Files\Storage\Storage $storage
143
+                 */
144
+                // get data directly
145
+                $data = $storage->getMetaData($internalPath);
146
+                $info = new FileInfo($absPath, $storage, $internalPath, $data, $mount);
147
+            } else {
148
+                $info = null;
149
+            }
150
+        } else {
151
+            // resolve chunk file name to real name, if applicable
152
+            $path = $this->resolveChunkFile($path);
153
+
154
+            // read from cache
155
+            try {
156
+                $info = $this->fileView->getFileInfo($path);
157
+
158
+                if ($info instanceof \OCP\Files\FileInfo && $info->getStorage()->instanceOfStorage(FailedStorage::class)) {
159
+                    throw new StorageNotAvailableException();
160
+                }
161
+            } catch (StorageNotAvailableException $e) {
162
+                throw new \Sabre\DAV\Exception\ServiceUnavailable('Storage is temporarily not available', 0, $e);
163
+            } catch (StorageInvalidException $e) {
164
+                throw new \Sabre\DAV\Exception\NotFound('Storage ' . $path . ' is invalid');
165
+            } catch (LockedException $e) {
166
+                throw new \Sabre\DAV\Exception\Locked();
167
+            } catch (ForbiddenException $e) {
168
+                throw new \Sabre\DAV\Exception\Forbidden();
169
+            }
170
+        }
171
+
172
+        if (!$info) {
173
+            throw new \Sabre\DAV\Exception\NotFound('File with name ' . $path . ' could not be located');
174
+        }
175
+
176
+        if ($info->getType() === 'dir') {
177
+            $node = new \OCA\DAV\Connector\Sabre\Directory($this->fileView, $info, $this);
178
+        } else {
179
+            $node = new \OCA\DAV\Connector\Sabre\File($this->fileView, $info);
180
+        }
181
+
182
+        $this->cache[$path] = $node;
183
+        return $node;
184
+    }
185
+
186
+    /**
187
+     * Copies a file or directory.
188
+     *
189
+     * This method must work recursively and delete the destination
190
+     * if it exists
191
+     *
192
+     * @param string $sourcePath
193
+     * @param string $destinationPath
194
+     * @throws FileLocked
195
+     * @throws Forbidden
196
+     * @throws InvalidPath
197
+     * @throws \Exception
198
+     * @throws \Sabre\DAV\Exception\Forbidden
199
+     * @throws \Sabre\DAV\Exception\Locked
200
+     * @throws \Sabre\DAV\Exception\NotFound
201
+     * @throws \Sabre\DAV\Exception\ServiceUnavailable
202
+     * @return void
203
+     */
204
+    public function copy($sourcePath, $destinationPath) {
205
+        if (!$this->fileView) {
206
+            throw new \Sabre\DAV\Exception\ServiceUnavailable('filesystem not setup');
207
+        }
208
+
209
+
210
+        $info = $this->fileView->getFileInfo(dirname($destinationPath));
211
+        if ($this->fileView->file_exists($destinationPath)) {
212
+            $destinationPermission = $info && $info->isUpdateable();
213
+        } else {
214
+            $destinationPermission = $info && $info->isCreatable();
215
+        }
216
+        if (!$destinationPermission) {
217
+            throw new Forbidden('No permissions to copy object.');
218
+        }
219
+
220
+        // this will trigger existence check
221
+        $this->getNodeForPath($sourcePath);
222
+
223
+        list($destinationDir, $destinationName) = \Sabre\Uri\split($destinationPath);
224
+        try {
225
+            $this->fileView->verifyPath($destinationDir, $destinationName);
226
+        } catch (\OCP\Files\InvalidPathException $ex) {
227
+            throw new InvalidPath($ex->getMessage());
228
+        }
229
+
230
+        try {
231
+            $this->fileView->copy($sourcePath, $destinationPath);
232
+        } catch (StorageNotAvailableException $e) {
233
+            throw new \Sabre\DAV\Exception\ServiceUnavailable($e->getMessage());
234
+        } catch (ForbiddenException $ex) {
235
+            throw new Forbidden($ex->getMessage(), $ex->getRetry());
236
+        } catch (LockedException $e) {
237
+            throw new FileLocked($e->getMessage(), $e->getCode(), $e);
238
+        }
239
+
240
+        list($destinationDir,) = \Sabre\Uri\split($destinationPath);
241
+        $this->markDirty($destinationDir);
242
+    }
243 243
 }
Please login to merge, or discard this patch.